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"
32 #undef SCRAMBLE_DELAYED_REFS
35 * control flags for do_chunk_alloc's force field
36 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
37 * if we really need one.
39 * CHUNK_ALLOC_LIMITED means to only try and allocate one
40 * if we have very few chunks already allocated. This is
41 * used as part of the clustering code to help make sure
42 * we have a good pool of storage to cluster in, without
43 * filling the FS with empty chunks
45 * CHUNK_ALLOC_FORCE means it must try to allocate one
49 CHUNK_ALLOC_NO_FORCE = 0,
50 CHUNK_ALLOC_LIMITED = 1,
51 CHUNK_ALLOC_FORCE = 2,
55 * Declare a helper function to detect underflow of various space info members
57 #define DECLARE_SPACE_INFO_UPDATE(name) \
58 static inline void update_##name(struct btrfs_fs_info *fs_info, \
59 struct btrfs_space_info *sinfo, \
62 lockdep_assert_held(&sinfo->lock); \
63 trace_update_##name(fs_info, sinfo, sinfo->name, bytes); \
64 if (bytes < 0 && sinfo->name < -bytes) { \
69 sinfo->name += bytes; \
72 DECLARE_SPACE_INFO_UPDATE(bytes_may_use);
73 DECLARE_SPACE_INFO_UPDATE(bytes_pinned);
75 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
76 struct btrfs_delayed_ref_node *node, u64 parent,
77 u64 root_objectid, u64 owner_objectid,
78 u64 owner_offset, int refs_to_drop,
79 struct btrfs_delayed_extent_op *extra_op);
80 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
81 struct extent_buffer *leaf,
82 struct btrfs_extent_item *ei);
83 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
84 u64 parent, u64 root_objectid,
85 u64 flags, u64 owner, u64 offset,
86 struct btrfs_key *ins, int ref_mod);
87 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
88 struct btrfs_delayed_ref_node *node,
89 struct btrfs_delayed_extent_op *extent_op);
90 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
92 static int find_next_key(struct btrfs_path *path, int level,
93 struct btrfs_key *key);
94 static void dump_space_info(struct btrfs_fs_info *fs_info,
95 struct btrfs_space_info *info, u64 bytes,
96 int dump_block_groups);
97 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
99 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
100 struct btrfs_space_info *space_info,
102 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
103 struct btrfs_space_info *space_info,
107 block_group_cache_done(struct btrfs_block_group_cache *cache)
110 return cache->cached == BTRFS_CACHE_FINISHED ||
111 cache->cached == BTRFS_CACHE_ERROR;
114 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
116 return (cache->flags & bits) == bits;
119 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
121 atomic_inc(&cache->count);
124 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
126 if (atomic_dec_and_test(&cache->count)) {
127 WARN_ON(cache->pinned > 0);
128 WARN_ON(cache->reserved > 0);
131 * If not empty, someone is still holding mutex of
132 * full_stripe_lock, which can only be released by caller.
133 * And it will definitely cause use-after-free when caller
134 * tries to release full stripe lock.
136 * No better way to resolve, but only to warn.
138 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
139 kfree(cache->free_space_ctl);
145 * this adds the block group to the fs_info rb tree for the block group
148 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
149 struct btrfs_block_group_cache *block_group)
152 struct rb_node *parent = NULL;
153 struct btrfs_block_group_cache *cache;
155 spin_lock(&info->block_group_cache_lock);
156 p = &info->block_group_cache_tree.rb_node;
160 cache = rb_entry(parent, struct btrfs_block_group_cache,
162 if (block_group->key.objectid < cache->key.objectid) {
164 } else if (block_group->key.objectid > cache->key.objectid) {
167 spin_unlock(&info->block_group_cache_lock);
172 rb_link_node(&block_group->cache_node, parent, p);
173 rb_insert_color(&block_group->cache_node,
174 &info->block_group_cache_tree);
176 if (info->first_logical_byte > block_group->key.objectid)
177 info->first_logical_byte = block_group->key.objectid;
179 spin_unlock(&info->block_group_cache_lock);
185 * This will return the block group at or after bytenr if contains is 0, else
186 * it will return the block group that contains the bytenr
188 static struct btrfs_block_group_cache *
189 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
192 struct btrfs_block_group_cache *cache, *ret = NULL;
196 spin_lock(&info->block_group_cache_lock);
197 n = info->block_group_cache_tree.rb_node;
200 cache = rb_entry(n, struct btrfs_block_group_cache,
202 end = cache->key.objectid + cache->key.offset - 1;
203 start = cache->key.objectid;
205 if (bytenr < start) {
206 if (!contains && (!ret || start < ret->key.objectid))
209 } else if (bytenr > start) {
210 if (contains && bytenr <= end) {
221 btrfs_get_block_group(ret);
222 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
223 info->first_logical_byte = ret->key.objectid;
225 spin_unlock(&info->block_group_cache_lock);
230 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
231 u64 start, u64 num_bytes)
233 u64 end = start + num_bytes - 1;
234 set_extent_bits(&fs_info->freed_extents[0],
235 start, end, EXTENT_UPTODATE);
236 set_extent_bits(&fs_info->freed_extents[1],
237 start, end, EXTENT_UPTODATE);
241 static void free_excluded_extents(struct btrfs_block_group_cache *cache)
243 struct btrfs_fs_info *fs_info = cache->fs_info;
246 start = cache->key.objectid;
247 end = start + cache->key.offset - 1;
249 clear_extent_bits(&fs_info->freed_extents[0],
250 start, end, EXTENT_UPTODATE);
251 clear_extent_bits(&fs_info->freed_extents[1],
252 start, end, EXTENT_UPTODATE);
255 static int exclude_super_stripes(struct btrfs_block_group_cache *cache)
257 struct btrfs_fs_info *fs_info = cache->fs_info;
263 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
264 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
265 cache->bytes_super += stripe_len;
266 ret = add_excluded_extent(fs_info, cache->key.objectid,
272 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
273 bytenr = btrfs_sb_offset(i);
274 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
275 bytenr, &logical, &nr, &stripe_len);
282 if (logical[nr] > cache->key.objectid +
286 if (logical[nr] + stripe_len <= cache->key.objectid)
290 if (start < cache->key.objectid) {
291 start = cache->key.objectid;
292 len = (logical[nr] + stripe_len) - start;
294 len = min_t(u64, stripe_len,
295 cache->key.objectid +
296 cache->key.offset - start);
299 cache->bytes_super += len;
300 ret = add_excluded_extent(fs_info, start, len);
312 static struct btrfs_caching_control *
313 get_caching_control(struct btrfs_block_group_cache *cache)
315 struct btrfs_caching_control *ctl;
317 spin_lock(&cache->lock);
318 if (!cache->caching_ctl) {
319 spin_unlock(&cache->lock);
323 ctl = cache->caching_ctl;
324 refcount_inc(&ctl->count);
325 spin_unlock(&cache->lock);
329 static void put_caching_control(struct btrfs_caching_control *ctl)
331 if (refcount_dec_and_test(&ctl->count))
335 #ifdef CONFIG_BTRFS_DEBUG
336 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
338 struct btrfs_fs_info *fs_info = block_group->fs_info;
339 u64 start = block_group->key.objectid;
340 u64 len = block_group->key.offset;
341 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
342 fs_info->nodesize : fs_info->sectorsize;
343 u64 step = chunk << 1;
345 while (len > chunk) {
346 btrfs_remove_free_space(block_group, start, chunk);
357 * this is only called by cache_block_group, since we could have freed extents
358 * we need to check the pinned_extents for any extents that can't be used yet
359 * since their free space will be released as soon as the transaction commits.
361 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
364 struct btrfs_fs_info *info = block_group->fs_info;
365 u64 extent_start, extent_end, size, total_added = 0;
368 while (start < end) {
369 ret = find_first_extent_bit(info->pinned_extents, start,
370 &extent_start, &extent_end,
371 EXTENT_DIRTY | EXTENT_UPTODATE,
376 if (extent_start <= start) {
377 start = extent_end + 1;
378 } else if (extent_start > start && extent_start < end) {
379 size = extent_start - start;
381 ret = btrfs_add_free_space(block_group, start,
383 BUG_ON(ret); /* -ENOMEM or logic error */
384 start = extent_end + 1;
393 ret = btrfs_add_free_space(block_group, start, size);
394 BUG_ON(ret); /* -ENOMEM or logic error */
400 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
402 struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
403 struct btrfs_fs_info *fs_info = block_group->fs_info;
404 struct btrfs_root *extent_root = fs_info->extent_root;
405 struct btrfs_path *path;
406 struct extent_buffer *leaf;
407 struct btrfs_key key;
414 path = btrfs_alloc_path();
418 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
420 #ifdef CONFIG_BTRFS_DEBUG
422 * If we're fragmenting we don't want to make anybody think we can
423 * allocate from this block group until we've had a chance to fragment
426 if (btrfs_should_fragment_free_space(block_group))
430 * We don't want to deadlock with somebody trying to allocate a new
431 * extent for the extent root while also trying to search the extent
432 * root to add free space. So we skip locking and search the commit
433 * root, since its read-only
435 path->skip_locking = 1;
436 path->search_commit_root = 1;
437 path->reada = READA_FORWARD;
441 key.type = BTRFS_EXTENT_ITEM_KEY;
444 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
448 leaf = path->nodes[0];
449 nritems = btrfs_header_nritems(leaf);
452 if (btrfs_fs_closing(fs_info) > 1) {
457 if (path->slots[0] < nritems) {
458 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
460 ret = find_next_key(path, 0, &key);
464 if (need_resched() ||
465 rwsem_is_contended(&fs_info->commit_root_sem)) {
467 caching_ctl->progress = last;
468 btrfs_release_path(path);
469 up_read(&fs_info->commit_root_sem);
470 mutex_unlock(&caching_ctl->mutex);
472 mutex_lock(&caching_ctl->mutex);
473 down_read(&fs_info->commit_root_sem);
477 ret = btrfs_next_leaf(extent_root, path);
482 leaf = path->nodes[0];
483 nritems = btrfs_header_nritems(leaf);
487 if (key.objectid < last) {
490 key.type = BTRFS_EXTENT_ITEM_KEY;
493 caching_ctl->progress = last;
494 btrfs_release_path(path);
498 if (key.objectid < block_group->key.objectid) {
503 if (key.objectid >= block_group->key.objectid +
504 block_group->key.offset)
507 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
508 key.type == BTRFS_METADATA_ITEM_KEY) {
509 total_found += add_new_free_space(block_group, last,
511 if (key.type == BTRFS_METADATA_ITEM_KEY)
512 last = key.objectid +
515 last = key.objectid + key.offset;
517 if (total_found > CACHING_CTL_WAKE_UP) {
520 wake_up(&caching_ctl->wait);
527 total_found += add_new_free_space(block_group, last,
528 block_group->key.objectid +
529 block_group->key.offset);
530 caching_ctl->progress = (u64)-1;
533 btrfs_free_path(path);
537 static noinline void caching_thread(struct btrfs_work *work)
539 struct btrfs_block_group_cache *block_group;
540 struct btrfs_fs_info *fs_info;
541 struct btrfs_caching_control *caching_ctl;
544 caching_ctl = container_of(work, struct btrfs_caching_control, work);
545 block_group = caching_ctl->block_group;
546 fs_info = block_group->fs_info;
548 mutex_lock(&caching_ctl->mutex);
549 down_read(&fs_info->commit_root_sem);
551 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
552 ret = load_free_space_tree(caching_ctl);
554 ret = load_extent_tree_free(caching_ctl);
556 spin_lock(&block_group->lock);
557 block_group->caching_ctl = NULL;
558 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
559 spin_unlock(&block_group->lock);
561 #ifdef CONFIG_BTRFS_DEBUG
562 if (btrfs_should_fragment_free_space(block_group)) {
565 spin_lock(&block_group->space_info->lock);
566 spin_lock(&block_group->lock);
567 bytes_used = block_group->key.offset -
568 btrfs_block_group_used(&block_group->item);
569 block_group->space_info->bytes_used += bytes_used >> 1;
570 spin_unlock(&block_group->lock);
571 spin_unlock(&block_group->space_info->lock);
572 fragment_free_space(block_group);
576 caching_ctl->progress = (u64)-1;
578 up_read(&fs_info->commit_root_sem);
579 free_excluded_extents(block_group);
580 mutex_unlock(&caching_ctl->mutex);
582 wake_up(&caching_ctl->wait);
584 put_caching_control(caching_ctl);
585 btrfs_put_block_group(block_group);
588 static int cache_block_group(struct btrfs_block_group_cache *cache,
592 struct btrfs_fs_info *fs_info = cache->fs_info;
593 struct btrfs_caching_control *caching_ctl;
596 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
600 INIT_LIST_HEAD(&caching_ctl->list);
601 mutex_init(&caching_ctl->mutex);
602 init_waitqueue_head(&caching_ctl->wait);
603 caching_ctl->block_group = cache;
604 caching_ctl->progress = cache->key.objectid;
605 refcount_set(&caching_ctl->count, 1);
606 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
607 caching_thread, NULL, NULL);
609 spin_lock(&cache->lock);
611 * This should be a rare occasion, but this could happen I think in the
612 * case where one thread starts to load the space cache info, and then
613 * some other thread starts a transaction commit which tries to do an
614 * allocation while the other thread is still loading the space cache
615 * info. The previous loop should have kept us from choosing this block
616 * group, but if we've moved to the state where we will wait on caching
617 * block groups we need to first check if we're doing a fast load here,
618 * so we can wait for it to finish, otherwise we could end up allocating
619 * from a block group who's cache gets evicted for one reason or
622 while (cache->cached == BTRFS_CACHE_FAST) {
623 struct btrfs_caching_control *ctl;
625 ctl = cache->caching_ctl;
626 refcount_inc(&ctl->count);
627 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
628 spin_unlock(&cache->lock);
632 finish_wait(&ctl->wait, &wait);
633 put_caching_control(ctl);
634 spin_lock(&cache->lock);
637 if (cache->cached != BTRFS_CACHE_NO) {
638 spin_unlock(&cache->lock);
642 WARN_ON(cache->caching_ctl);
643 cache->caching_ctl = caching_ctl;
644 cache->cached = BTRFS_CACHE_FAST;
645 spin_unlock(&cache->lock);
647 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
648 mutex_lock(&caching_ctl->mutex);
649 ret = load_free_space_cache(cache);
651 spin_lock(&cache->lock);
653 cache->caching_ctl = NULL;
654 cache->cached = BTRFS_CACHE_FINISHED;
655 cache->last_byte_to_unpin = (u64)-1;
656 caching_ctl->progress = (u64)-1;
658 if (load_cache_only) {
659 cache->caching_ctl = NULL;
660 cache->cached = BTRFS_CACHE_NO;
662 cache->cached = BTRFS_CACHE_STARTED;
663 cache->has_caching_ctl = 1;
666 spin_unlock(&cache->lock);
667 #ifdef CONFIG_BTRFS_DEBUG
669 btrfs_should_fragment_free_space(cache)) {
672 spin_lock(&cache->space_info->lock);
673 spin_lock(&cache->lock);
674 bytes_used = cache->key.offset -
675 btrfs_block_group_used(&cache->item);
676 cache->space_info->bytes_used += bytes_used >> 1;
677 spin_unlock(&cache->lock);
678 spin_unlock(&cache->space_info->lock);
679 fragment_free_space(cache);
682 mutex_unlock(&caching_ctl->mutex);
684 wake_up(&caching_ctl->wait);
686 put_caching_control(caching_ctl);
687 free_excluded_extents(cache);
692 * We're either using the free space tree or no caching at all.
693 * Set cached to the appropriate value and wakeup any waiters.
695 spin_lock(&cache->lock);
696 if (load_cache_only) {
697 cache->caching_ctl = NULL;
698 cache->cached = BTRFS_CACHE_NO;
700 cache->cached = BTRFS_CACHE_STARTED;
701 cache->has_caching_ctl = 1;
703 spin_unlock(&cache->lock);
704 wake_up(&caching_ctl->wait);
707 if (load_cache_only) {
708 put_caching_control(caching_ctl);
712 down_write(&fs_info->commit_root_sem);
713 refcount_inc(&caching_ctl->count);
714 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
715 up_write(&fs_info->commit_root_sem);
717 btrfs_get_block_group(cache);
719 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
725 * return the block group that starts at or after bytenr
727 static struct btrfs_block_group_cache *
728 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
730 return block_group_cache_tree_search(info, bytenr, 0);
734 * return the block group that contains the given bytenr
736 struct btrfs_block_group_cache *btrfs_lookup_block_group(
737 struct btrfs_fs_info *info,
740 return block_group_cache_tree_search(info, bytenr, 1);
743 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
746 struct list_head *head = &info->space_info;
747 struct btrfs_space_info *found;
749 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
752 list_for_each_entry_rcu(found, head, list) {
753 if (found->flags & flags) {
762 static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
764 if (ref->type == BTRFS_REF_METADATA) {
765 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
766 return BTRFS_BLOCK_GROUP_SYSTEM;
768 return BTRFS_BLOCK_GROUP_METADATA;
770 return BTRFS_BLOCK_GROUP_DATA;
773 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
774 struct btrfs_ref *ref)
776 struct btrfs_space_info *space_info;
777 u64 flags = generic_ref_to_space_flags(ref);
779 space_info = __find_space_info(fs_info, flags);
781 percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
782 BTRFS_TOTAL_BYTES_PINNED_BATCH);
785 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
786 struct btrfs_ref *ref)
788 struct btrfs_space_info *space_info;
789 u64 flags = generic_ref_to_space_flags(ref);
791 space_info = __find_space_info(fs_info, flags);
793 percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
794 BTRFS_TOTAL_BYTES_PINNED_BATCH);
798 * after adding space to the filesystem, we need to clear the full flags
799 * on all the space infos.
801 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
803 struct list_head *head = &info->space_info;
804 struct btrfs_space_info *found;
807 list_for_each_entry_rcu(found, head, list)
812 /* simple helper to search for an existing data extent at a given offset */
813 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
816 struct btrfs_key key;
817 struct btrfs_path *path;
819 path = btrfs_alloc_path();
823 key.objectid = start;
825 key.type = BTRFS_EXTENT_ITEM_KEY;
826 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
827 btrfs_free_path(path);
832 * helper function to lookup reference count and flags of a tree block.
834 * the head node for delayed ref is used to store the sum of all the
835 * reference count modifications queued up in the rbtree. the head
836 * node may also store the extent flags to set. This way you can check
837 * to see what the reference count and extent flags would be if all of
838 * the delayed refs are not processed.
840 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
841 struct btrfs_fs_info *fs_info, u64 bytenr,
842 u64 offset, int metadata, u64 *refs, u64 *flags)
844 struct btrfs_delayed_ref_head *head;
845 struct btrfs_delayed_ref_root *delayed_refs;
846 struct btrfs_path *path;
847 struct btrfs_extent_item *ei;
848 struct extent_buffer *leaf;
849 struct btrfs_key key;
856 * If we don't have skinny metadata, don't bother doing anything
859 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
860 offset = fs_info->nodesize;
864 path = btrfs_alloc_path();
869 path->skip_locking = 1;
870 path->search_commit_root = 1;
874 key.objectid = bytenr;
877 key.type = BTRFS_METADATA_ITEM_KEY;
879 key.type = BTRFS_EXTENT_ITEM_KEY;
881 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
885 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
886 if (path->slots[0]) {
888 btrfs_item_key_to_cpu(path->nodes[0], &key,
890 if (key.objectid == bytenr &&
891 key.type == BTRFS_EXTENT_ITEM_KEY &&
892 key.offset == fs_info->nodesize)
898 leaf = path->nodes[0];
899 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
900 if (item_size >= sizeof(*ei)) {
901 ei = btrfs_item_ptr(leaf, path->slots[0],
902 struct btrfs_extent_item);
903 num_refs = btrfs_extent_refs(leaf, ei);
904 extent_flags = btrfs_extent_flags(leaf, ei);
907 btrfs_print_v0_err(fs_info);
909 btrfs_abort_transaction(trans, ret);
911 btrfs_handle_fs_error(fs_info, ret, NULL);
916 BUG_ON(num_refs == 0);
926 delayed_refs = &trans->transaction->delayed_refs;
927 spin_lock(&delayed_refs->lock);
928 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
930 if (!mutex_trylock(&head->mutex)) {
931 refcount_inc(&head->refs);
932 spin_unlock(&delayed_refs->lock);
934 btrfs_release_path(path);
937 * Mutex was contended, block until it's released and try
940 mutex_lock(&head->mutex);
941 mutex_unlock(&head->mutex);
942 btrfs_put_delayed_ref_head(head);
945 spin_lock(&head->lock);
946 if (head->extent_op && head->extent_op->update_flags)
947 extent_flags |= head->extent_op->flags_to_set;
949 BUG_ON(num_refs == 0);
951 num_refs += head->ref_mod;
952 spin_unlock(&head->lock);
953 mutex_unlock(&head->mutex);
955 spin_unlock(&delayed_refs->lock);
957 WARN_ON(num_refs == 0);
961 *flags = extent_flags;
963 btrfs_free_path(path);
968 * Back reference rules. Back refs have three main goals:
970 * 1) differentiate between all holders of references to an extent so that
971 * when a reference is dropped we can make sure it was a valid reference
972 * before freeing the extent.
974 * 2) Provide enough information to quickly find the holders of an extent
975 * if we notice a given block is corrupted or bad.
977 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
978 * maintenance. This is actually the same as #2, but with a slightly
979 * different use case.
981 * There are two kinds of back refs. The implicit back refs is optimized
982 * for pointers in non-shared tree blocks. For a given pointer in a block,
983 * back refs of this kind provide information about the block's owner tree
984 * and the pointer's key. These information allow us to find the block by
985 * b-tree searching. The full back refs is for pointers in tree blocks not
986 * referenced by their owner trees. The location of tree block is recorded
987 * in the back refs. Actually the full back refs is generic, and can be
988 * used in all cases the implicit back refs is used. The major shortcoming
989 * of the full back refs is its overhead. Every time a tree block gets
990 * COWed, we have to update back refs entry for all pointers in it.
992 * For a newly allocated tree block, we use implicit back refs for
993 * pointers in it. This means most tree related operations only involve
994 * implicit back refs. For a tree block created in old transaction, the
995 * only way to drop a reference to it is COW it. So we can detect the
996 * event that tree block loses its owner tree's reference and do the
997 * back refs conversion.
999 * When a tree block is COWed through a tree, there are four cases:
1001 * The reference count of the block is one and the tree is the block's
1002 * owner tree. Nothing to do in this case.
1004 * The reference count of the block is one and the tree is not the
1005 * block's owner tree. In this case, full back refs is used for pointers
1006 * in the block. Remove these full back refs, add implicit back refs for
1007 * every pointers in the new block.
1009 * The reference count of the block is greater than one and the tree is
1010 * the block's owner tree. In this case, implicit back refs is used for
1011 * pointers in the block. Add full back refs for every pointers in the
1012 * block, increase lower level extents' reference counts. The original
1013 * implicit back refs are entailed to the new block.
1015 * The reference count of the block is greater than one and the tree is
1016 * not the block's owner tree. Add implicit back refs for every pointer in
1017 * the new block, increase lower level extents' reference count.
1019 * Back Reference Key composing:
1021 * The key objectid corresponds to the first byte in the extent,
1022 * The key type is used to differentiate between types of back refs.
1023 * There are different meanings of the key offset for different types
1026 * File extents can be referenced by:
1028 * - multiple snapshots, subvolumes, or different generations in one subvol
1029 * - different files inside a single subvolume
1030 * - different offsets inside a file (bookend extents in file.c)
1032 * The extent ref structure for the implicit back refs has fields for:
1034 * - Objectid of the subvolume root
1035 * - objectid of the file holding the reference
1036 * - original offset in the file
1037 * - how many bookend extents
1039 * The key offset for the implicit back refs is hash of the first
1042 * The extent ref structure for the full back refs has field for:
1044 * - number of pointers in the tree leaf
1046 * The key offset for the implicit back refs is the first byte of
1049 * When a file extent is allocated, The implicit back refs is used.
1050 * the fields are filled in:
1052 * (root_key.objectid, inode objectid, offset in file, 1)
1054 * When a file extent is removed file truncation, we find the
1055 * corresponding implicit back refs and check the following fields:
1057 * (btrfs_header_owner(leaf), inode objectid, offset in file)
1059 * Btree extents can be referenced by:
1061 * - Different subvolumes
1063 * Both the implicit back refs and the full back refs for tree blocks
1064 * only consist of key. The key offset for the implicit back refs is
1065 * objectid of block's owner tree. The key offset for the full back refs
1066 * is the first byte of parent block.
1068 * When implicit back refs is used, information about the lowest key and
1069 * level of the tree block are required. These information are stored in
1070 * tree block info structure.
1074 * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
1075 * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
1076 * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
1078 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
1079 struct btrfs_extent_inline_ref *iref,
1080 enum btrfs_inline_ref_type is_data)
1082 int type = btrfs_extent_inline_ref_type(eb, iref);
1083 u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
1085 if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1086 type == BTRFS_SHARED_BLOCK_REF_KEY ||
1087 type == BTRFS_SHARED_DATA_REF_KEY ||
1088 type == BTRFS_EXTENT_DATA_REF_KEY) {
1089 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1090 if (type == BTRFS_TREE_BLOCK_REF_KEY)
1092 if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1093 ASSERT(eb->fs_info);
1095 * Every shared one has parent tree
1096 * block, which must be aligned to
1100 IS_ALIGNED(offset, eb->fs_info->nodesize))
1103 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1104 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1106 if (type == BTRFS_SHARED_DATA_REF_KEY) {
1107 ASSERT(eb->fs_info);
1109 * Every shared one has parent tree
1110 * block, which must be aligned to
1114 IS_ALIGNED(offset, eb->fs_info->nodesize))
1118 ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1123 btrfs_print_leaf((struct extent_buffer *)eb);
1124 btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1128 return BTRFS_REF_TYPE_INVALID;
1131 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1133 u32 high_crc = ~(u32)0;
1134 u32 low_crc = ~(u32)0;
1137 lenum = cpu_to_le64(root_objectid);
1138 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1139 lenum = cpu_to_le64(owner);
1140 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1141 lenum = cpu_to_le64(offset);
1142 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1144 return ((u64)high_crc << 31) ^ (u64)low_crc;
1147 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1148 struct btrfs_extent_data_ref *ref)
1150 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1151 btrfs_extent_data_ref_objectid(leaf, ref),
1152 btrfs_extent_data_ref_offset(leaf, ref));
1155 static int match_extent_data_ref(struct extent_buffer *leaf,
1156 struct btrfs_extent_data_ref *ref,
1157 u64 root_objectid, u64 owner, u64 offset)
1159 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1160 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1161 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1166 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1167 struct btrfs_path *path,
1168 u64 bytenr, u64 parent,
1170 u64 owner, u64 offset)
1172 struct btrfs_root *root = trans->fs_info->extent_root;
1173 struct btrfs_key key;
1174 struct btrfs_extent_data_ref *ref;
1175 struct extent_buffer *leaf;
1181 key.objectid = bytenr;
1183 key.type = BTRFS_SHARED_DATA_REF_KEY;
1184 key.offset = parent;
1186 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1187 key.offset = hash_extent_data_ref(root_objectid,
1192 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1204 leaf = path->nodes[0];
1205 nritems = btrfs_header_nritems(leaf);
1207 if (path->slots[0] >= nritems) {
1208 ret = btrfs_next_leaf(root, path);
1214 leaf = path->nodes[0];
1215 nritems = btrfs_header_nritems(leaf);
1219 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1220 if (key.objectid != bytenr ||
1221 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1224 ref = btrfs_item_ptr(leaf, path->slots[0],
1225 struct btrfs_extent_data_ref);
1227 if (match_extent_data_ref(leaf, ref, root_objectid,
1230 btrfs_release_path(path);
1242 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1243 struct btrfs_path *path,
1244 u64 bytenr, u64 parent,
1245 u64 root_objectid, u64 owner,
1246 u64 offset, int refs_to_add)
1248 struct btrfs_root *root = trans->fs_info->extent_root;
1249 struct btrfs_key key;
1250 struct extent_buffer *leaf;
1255 key.objectid = bytenr;
1257 key.type = BTRFS_SHARED_DATA_REF_KEY;
1258 key.offset = parent;
1259 size = sizeof(struct btrfs_shared_data_ref);
1261 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1262 key.offset = hash_extent_data_ref(root_objectid,
1264 size = sizeof(struct btrfs_extent_data_ref);
1267 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1268 if (ret && ret != -EEXIST)
1271 leaf = path->nodes[0];
1273 struct btrfs_shared_data_ref *ref;
1274 ref = btrfs_item_ptr(leaf, path->slots[0],
1275 struct btrfs_shared_data_ref);
1277 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1279 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1280 num_refs += refs_to_add;
1281 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1284 struct btrfs_extent_data_ref *ref;
1285 while (ret == -EEXIST) {
1286 ref = btrfs_item_ptr(leaf, path->slots[0],
1287 struct btrfs_extent_data_ref);
1288 if (match_extent_data_ref(leaf, ref, root_objectid,
1291 btrfs_release_path(path);
1293 ret = btrfs_insert_empty_item(trans, root, path, &key,
1295 if (ret && ret != -EEXIST)
1298 leaf = path->nodes[0];
1300 ref = btrfs_item_ptr(leaf, path->slots[0],
1301 struct btrfs_extent_data_ref);
1303 btrfs_set_extent_data_ref_root(leaf, ref,
1305 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1306 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1307 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1309 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1310 num_refs += refs_to_add;
1311 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1314 btrfs_mark_buffer_dirty(leaf);
1317 btrfs_release_path(path);
1321 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1322 struct btrfs_path *path,
1323 int refs_to_drop, int *last_ref)
1325 struct btrfs_key key;
1326 struct btrfs_extent_data_ref *ref1 = NULL;
1327 struct btrfs_shared_data_ref *ref2 = NULL;
1328 struct extent_buffer *leaf;
1332 leaf = path->nodes[0];
1333 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1335 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1336 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1337 struct btrfs_extent_data_ref);
1338 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1339 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1340 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1341 struct btrfs_shared_data_ref);
1342 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1343 } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1344 btrfs_print_v0_err(trans->fs_info);
1345 btrfs_abort_transaction(trans, -EINVAL);
1351 BUG_ON(num_refs < refs_to_drop);
1352 num_refs -= refs_to_drop;
1354 if (num_refs == 0) {
1355 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1358 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1359 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1360 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1361 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1362 btrfs_mark_buffer_dirty(leaf);
1367 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1368 struct btrfs_extent_inline_ref *iref)
1370 struct btrfs_key key;
1371 struct extent_buffer *leaf;
1372 struct btrfs_extent_data_ref *ref1;
1373 struct btrfs_shared_data_ref *ref2;
1377 leaf = path->nodes[0];
1378 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1380 BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1383 * If type is invalid, we should have bailed out earlier than
1386 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1387 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1388 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1389 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1390 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1392 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1393 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1395 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1396 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1397 struct btrfs_extent_data_ref);
1398 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1399 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1400 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1401 struct btrfs_shared_data_ref);
1402 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1409 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1410 struct btrfs_path *path,
1411 u64 bytenr, u64 parent,
1414 struct btrfs_root *root = trans->fs_info->extent_root;
1415 struct btrfs_key key;
1418 key.objectid = bytenr;
1420 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1421 key.offset = parent;
1423 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1424 key.offset = root_objectid;
1427 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1433 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1434 struct btrfs_path *path,
1435 u64 bytenr, u64 parent,
1438 struct btrfs_key key;
1441 key.objectid = bytenr;
1443 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1444 key.offset = parent;
1446 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1447 key.offset = root_objectid;
1450 ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1452 btrfs_release_path(path);
1456 static inline int extent_ref_type(u64 parent, u64 owner)
1459 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1461 type = BTRFS_SHARED_BLOCK_REF_KEY;
1463 type = BTRFS_TREE_BLOCK_REF_KEY;
1466 type = BTRFS_SHARED_DATA_REF_KEY;
1468 type = BTRFS_EXTENT_DATA_REF_KEY;
1473 static int find_next_key(struct btrfs_path *path, int level,
1474 struct btrfs_key *key)
1477 for (; level < BTRFS_MAX_LEVEL; level++) {
1478 if (!path->nodes[level])
1480 if (path->slots[level] + 1 >=
1481 btrfs_header_nritems(path->nodes[level]))
1484 btrfs_item_key_to_cpu(path->nodes[level], key,
1485 path->slots[level] + 1);
1487 btrfs_node_key_to_cpu(path->nodes[level], key,
1488 path->slots[level] + 1);
1495 * look for inline back ref. if back ref is found, *ref_ret is set
1496 * to the address of inline back ref, and 0 is returned.
1498 * if back ref isn't found, *ref_ret is set to the address where it
1499 * should be inserted, and -ENOENT is returned.
1501 * if insert is true and there are too many inline back refs, the path
1502 * points to the extent item, and -EAGAIN is returned.
1504 * NOTE: inline back refs are ordered in the same way that back ref
1505 * items in the tree are ordered.
1507 static noinline_for_stack
1508 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1509 struct btrfs_path *path,
1510 struct btrfs_extent_inline_ref **ref_ret,
1511 u64 bytenr, u64 num_bytes,
1512 u64 parent, u64 root_objectid,
1513 u64 owner, u64 offset, int insert)
1515 struct btrfs_fs_info *fs_info = trans->fs_info;
1516 struct btrfs_root *root = fs_info->extent_root;
1517 struct btrfs_key key;
1518 struct extent_buffer *leaf;
1519 struct btrfs_extent_item *ei;
1520 struct btrfs_extent_inline_ref *iref;
1530 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1533 key.objectid = bytenr;
1534 key.type = BTRFS_EXTENT_ITEM_KEY;
1535 key.offset = num_bytes;
1537 want = extent_ref_type(parent, owner);
1539 extra_size = btrfs_extent_inline_ref_size(want);
1540 path->keep_locks = 1;
1545 * Owner is our level, so we can just add one to get the level for the
1546 * block we are interested in.
1548 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1549 key.type = BTRFS_METADATA_ITEM_KEY;
1554 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1561 * We may be a newly converted file system which still has the old fat
1562 * extent entries for metadata, so try and see if we have one of those.
1564 if (ret > 0 && skinny_metadata) {
1565 skinny_metadata = false;
1566 if (path->slots[0]) {
1568 btrfs_item_key_to_cpu(path->nodes[0], &key,
1570 if (key.objectid == bytenr &&
1571 key.type == BTRFS_EXTENT_ITEM_KEY &&
1572 key.offset == num_bytes)
1576 key.objectid = bytenr;
1577 key.type = BTRFS_EXTENT_ITEM_KEY;
1578 key.offset = num_bytes;
1579 btrfs_release_path(path);
1584 if (ret && !insert) {
1587 } else if (WARN_ON(ret)) {
1592 leaf = path->nodes[0];
1593 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1594 if (unlikely(item_size < sizeof(*ei))) {
1596 btrfs_print_v0_err(fs_info);
1597 btrfs_abort_transaction(trans, err);
1601 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1602 flags = btrfs_extent_flags(leaf, ei);
1604 ptr = (unsigned long)(ei + 1);
1605 end = (unsigned long)ei + item_size;
1607 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1608 ptr += sizeof(struct btrfs_tree_block_info);
1612 if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1613 needed = BTRFS_REF_TYPE_DATA;
1615 needed = BTRFS_REF_TYPE_BLOCK;
1623 iref = (struct btrfs_extent_inline_ref *)ptr;
1624 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1625 if (type == BTRFS_REF_TYPE_INVALID) {
1633 ptr += btrfs_extent_inline_ref_size(type);
1637 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1638 struct btrfs_extent_data_ref *dref;
1639 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1640 if (match_extent_data_ref(leaf, dref, root_objectid,
1645 if (hash_extent_data_ref_item(leaf, dref) <
1646 hash_extent_data_ref(root_objectid, owner, offset))
1650 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1652 if (parent == ref_offset) {
1656 if (ref_offset < parent)
1659 if (root_objectid == ref_offset) {
1663 if (ref_offset < root_objectid)
1667 ptr += btrfs_extent_inline_ref_size(type);
1669 if (err == -ENOENT && insert) {
1670 if (item_size + extra_size >=
1671 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1676 * To add new inline back ref, we have to make sure
1677 * there is no corresponding back ref item.
1678 * For simplicity, we just do not add new inline back
1679 * ref if there is any kind of item for this block
1681 if (find_next_key(path, 0, &key) == 0 &&
1682 key.objectid == bytenr &&
1683 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1688 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1691 path->keep_locks = 0;
1692 btrfs_unlock_up_safe(path, 1);
1698 * helper to add new inline back ref
1700 static noinline_for_stack
1701 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1702 struct btrfs_path *path,
1703 struct btrfs_extent_inline_ref *iref,
1704 u64 parent, u64 root_objectid,
1705 u64 owner, u64 offset, int refs_to_add,
1706 struct btrfs_delayed_extent_op *extent_op)
1708 struct extent_buffer *leaf;
1709 struct btrfs_extent_item *ei;
1712 unsigned long item_offset;
1717 leaf = path->nodes[0];
1718 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1719 item_offset = (unsigned long)iref - (unsigned long)ei;
1721 type = extent_ref_type(parent, owner);
1722 size = btrfs_extent_inline_ref_size(type);
1724 btrfs_extend_item(path, size);
1726 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1727 refs = btrfs_extent_refs(leaf, ei);
1728 refs += refs_to_add;
1729 btrfs_set_extent_refs(leaf, ei, refs);
1731 __run_delayed_extent_op(extent_op, leaf, ei);
1733 ptr = (unsigned long)ei + item_offset;
1734 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1735 if (ptr < end - size)
1736 memmove_extent_buffer(leaf, ptr + size, ptr,
1739 iref = (struct btrfs_extent_inline_ref *)ptr;
1740 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1741 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1742 struct btrfs_extent_data_ref *dref;
1743 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1744 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1745 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1746 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1747 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1748 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1749 struct btrfs_shared_data_ref *sref;
1750 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1751 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1752 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1753 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1754 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1756 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1758 btrfs_mark_buffer_dirty(leaf);
1761 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1762 struct btrfs_path *path,
1763 struct btrfs_extent_inline_ref **ref_ret,
1764 u64 bytenr, u64 num_bytes, u64 parent,
1765 u64 root_objectid, u64 owner, u64 offset)
1769 ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1770 num_bytes, parent, root_objectid,
1775 btrfs_release_path(path);
1778 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1779 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1782 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1783 root_objectid, owner, offset);
1789 * helper to update/remove inline back ref
1791 static noinline_for_stack
1792 void update_inline_extent_backref(struct btrfs_path *path,
1793 struct btrfs_extent_inline_ref *iref,
1795 struct btrfs_delayed_extent_op *extent_op,
1798 struct extent_buffer *leaf = path->nodes[0];
1799 struct btrfs_extent_item *ei;
1800 struct btrfs_extent_data_ref *dref = NULL;
1801 struct btrfs_shared_data_ref *sref = NULL;
1809 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1810 refs = btrfs_extent_refs(leaf, ei);
1811 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1812 refs += refs_to_mod;
1813 btrfs_set_extent_refs(leaf, ei, refs);
1815 __run_delayed_extent_op(extent_op, leaf, ei);
1818 * If type is invalid, we should have bailed out after
1819 * lookup_inline_extent_backref().
1821 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1822 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1824 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1825 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1826 refs = btrfs_extent_data_ref_count(leaf, dref);
1827 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1828 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1829 refs = btrfs_shared_data_ref_count(leaf, sref);
1832 BUG_ON(refs_to_mod != -1);
1835 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1836 refs += refs_to_mod;
1839 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1840 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1842 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1845 size = btrfs_extent_inline_ref_size(type);
1846 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1847 ptr = (unsigned long)iref;
1848 end = (unsigned long)ei + item_size;
1849 if (ptr + size < end)
1850 memmove_extent_buffer(leaf, ptr, ptr + size,
1853 btrfs_truncate_item(path, item_size, 1);
1855 btrfs_mark_buffer_dirty(leaf);
1858 static noinline_for_stack
1859 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1860 struct btrfs_path *path,
1861 u64 bytenr, u64 num_bytes, u64 parent,
1862 u64 root_objectid, u64 owner,
1863 u64 offset, int refs_to_add,
1864 struct btrfs_delayed_extent_op *extent_op)
1866 struct btrfs_extent_inline_ref *iref;
1869 ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1870 num_bytes, parent, root_objectid,
1873 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1874 update_inline_extent_backref(path, iref, refs_to_add,
1876 } else if (ret == -ENOENT) {
1877 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1878 root_objectid, owner, offset,
1879 refs_to_add, extent_op);
1885 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1886 struct btrfs_path *path,
1887 u64 bytenr, u64 parent, u64 root_objectid,
1888 u64 owner, u64 offset, int refs_to_add)
1891 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1892 BUG_ON(refs_to_add != 1);
1893 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1896 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1897 root_objectid, owner, offset,
1903 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1904 struct btrfs_path *path,
1905 struct btrfs_extent_inline_ref *iref,
1906 int refs_to_drop, int is_data, int *last_ref)
1910 BUG_ON(!is_data && refs_to_drop != 1);
1912 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1914 } else if (is_data) {
1915 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1919 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1924 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1925 u64 *discarded_bytes)
1928 u64 bytes_left, end;
1929 u64 aligned_start = ALIGN(start, 1 << 9);
1931 if (WARN_ON(start != aligned_start)) {
1932 len -= aligned_start - start;
1933 len = round_down(len, 1 << 9);
1934 start = aligned_start;
1937 *discarded_bytes = 0;
1945 /* Skip any superblocks on this device. */
1946 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1947 u64 sb_start = btrfs_sb_offset(j);
1948 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1949 u64 size = sb_start - start;
1951 if (!in_range(sb_start, start, bytes_left) &&
1952 !in_range(sb_end, start, bytes_left) &&
1953 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1957 * Superblock spans beginning of range. Adjust start and
1960 if (sb_start <= start) {
1961 start += sb_end - start;
1966 bytes_left = end - start;
1971 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1974 *discarded_bytes += size;
1975 else if (ret != -EOPNOTSUPP)
1984 bytes_left = end - start;
1988 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1991 *discarded_bytes += bytes_left;
1996 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1997 u64 num_bytes, u64 *actual_bytes)
2000 u64 discarded_bytes = 0;
2001 struct btrfs_bio *bbio = NULL;
2005 * Avoid races with device replace and make sure our bbio has devices
2006 * associated to its stripes that don't go away while we are discarding.
2008 btrfs_bio_counter_inc_blocked(fs_info);
2009 /* Tell the block device(s) that the sectors can be discarded */
2010 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2012 /* Error condition is -ENOMEM */
2014 struct btrfs_bio_stripe *stripe = bbio->stripes;
2018 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2020 struct request_queue *req_q;
2022 if (!stripe->dev->bdev) {
2023 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
2026 req_q = bdev_get_queue(stripe->dev->bdev);
2027 if (!blk_queue_discard(req_q))
2030 ret = btrfs_issue_discard(stripe->dev->bdev,
2035 discarded_bytes += bytes;
2036 else if (ret != -EOPNOTSUPP)
2037 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2040 * Just in case we get back EOPNOTSUPP for some reason,
2041 * just ignore the return value so we don't screw up
2042 * people calling discard_extent.
2046 btrfs_put_bbio(bbio);
2048 btrfs_bio_counter_dec(fs_info);
2051 *actual_bytes = discarded_bytes;
2054 if (ret == -EOPNOTSUPP)
2059 /* Can return -ENOMEM */
2060 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2061 struct btrfs_ref *generic_ref)
2063 struct btrfs_fs_info *fs_info = trans->fs_info;
2064 int old_ref_mod, new_ref_mod;
2067 ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
2068 generic_ref->action);
2069 BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
2070 generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
2072 if (generic_ref->type == BTRFS_REF_METADATA)
2073 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
2074 NULL, &old_ref_mod, &new_ref_mod);
2076 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
2077 &old_ref_mod, &new_ref_mod);
2079 btrfs_ref_tree_mod(fs_info, generic_ref);
2081 if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
2082 sub_pinned_bytes(fs_info, generic_ref);
2088 * __btrfs_inc_extent_ref - insert backreference for a given extent
2090 * @trans: Handle of transaction
2092 * @node: The delayed ref node used to get the bytenr/length for
2093 * extent whose references are incremented.
2095 * @parent: If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2096 * BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2097 * bytenr of the parent block. Since new extents are always
2098 * created with indirect references, this will only be the case
2099 * when relocating a shared extent. In that case, root_objectid
2100 * will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2103 * @root_objectid: The id of the root where this modification has originated,
2104 * this can be either one of the well-known metadata trees or
2105 * the subvolume id which references this extent.
2107 * @owner: For data extents it is the inode number of the owning file.
2108 * For metadata extents this parameter holds the level in the
2109 * tree of the extent.
2111 * @offset: For metadata extents the offset is ignored and is currently
2112 * always passed as 0. For data extents it is the fileoffset
2113 * this extent belongs to.
2115 * @refs_to_add Number of references to add
2117 * @extent_op Pointer to a structure, holding information necessary when
2118 * updating a tree block's flags
2121 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2122 struct btrfs_delayed_ref_node *node,
2123 u64 parent, u64 root_objectid,
2124 u64 owner, u64 offset, int refs_to_add,
2125 struct btrfs_delayed_extent_op *extent_op)
2127 struct btrfs_path *path;
2128 struct extent_buffer *leaf;
2129 struct btrfs_extent_item *item;
2130 struct btrfs_key key;
2131 u64 bytenr = node->bytenr;
2132 u64 num_bytes = node->num_bytes;
2136 path = btrfs_alloc_path();
2140 path->reada = READA_FORWARD;
2141 path->leave_spinning = 1;
2142 /* this will setup the path even if it fails to insert the back ref */
2143 ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2144 parent, root_objectid, owner,
2145 offset, refs_to_add, extent_op);
2146 if ((ret < 0 && ret != -EAGAIN) || !ret)
2150 * Ok we had -EAGAIN which means we didn't have space to insert and
2151 * inline extent ref, so just update the reference count and add a
2154 leaf = path->nodes[0];
2155 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2156 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2157 refs = btrfs_extent_refs(leaf, item);
2158 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2160 __run_delayed_extent_op(extent_op, leaf, item);
2162 btrfs_mark_buffer_dirty(leaf);
2163 btrfs_release_path(path);
2165 path->reada = READA_FORWARD;
2166 path->leave_spinning = 1;
2167 /* now insert the actual backref */
2168 ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2169 owner, offset, refs_to_add);
2171 btrfs_abort_transaction(trans, ret);
2173 btrfs_free_path(path);
2177 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2178 struct btrfs_delayed_ref_node *node,
2179 struct btrfs_delayed_extent_op *extent_op,
2180 int insert_reserved)
2183 struct btrfs_delayed_data_ref *ref;
2184 struct btrfs_key ins;
2189 ins.objectid = node->bytenr;
2190 ins.offset = node->num_bytes;
2191 ins.type = BTRFS_EXTENT_ITEM_KEY;
2193 ref = btrfs_delayed_node_to_data_ref(node);
2194 trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2196 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2197 parent = ref->parent;
2198 ref_root = ref->root;
2200 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2202 flags |= extent_op->flags_to_set;
2203 ret = alloc_reserved_file_extent(trans, parent, ref_root,
2204 flags, ref->objectid,
2207 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2208 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2209 ref->objectid, ref->offset,
2210 node->ref_mod, extent_op);
2211 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2212 ret = __btrfs_free_extent(trans, node, parent,
2213 ref_root, ref->objectid,
2214 ref->offset, node->ref_mod,
2222 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2223 struct extent_buffer *leaf,
2224 struct btrfs_extent_item *ei)
2226 u64 flags = btrfs_extent_flags(leaf, ei);
2227 if (extent_op->update_flags) {
2228 flags |= extent_op->flags_to_set;
2229 btrfs_set_extent_flags(leaf, ei, flags);
2232 if (extent_op->update_key) {
2233 struct btrfs_tree_block_info *bi;
2234 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2235 bi = (struct btrfs_tree_block_info *)(ei + 1);
2236 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2240 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2241 struct btrfs_delayed_ref_head *head,
2242 struct btrfs_delayed_extent_op *extent_op)
2244 struct btrfs_fs_info *fs_info = trans->fs_info;
2245 struct btrfs_key key;
2246 struct btrfs_path *path;
2247 struct btrfs_extent_item *ei;
2248 struct extent_buffer *leaf;
2252 int metadata = !extent_op->is_data;
2257 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2260 path = btrfs_alloc_path();
2264 key.objectid = head->bytenr;
2267 key.type = BTRFS_METADATA_ITEM_KEY;
2268 key.offset = extent_op->level;
2270 key.type = BTRFS_EXTENT_ITEM_KEY;
2271 key.offset = head->num_bytes;
2275 path->reada = READA_FORWARD;
2276 path->leave_spinning = 1;
2277 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2284 if (path->slots[0] > 0) {
2286 btrfs_item_key_to_cpu(path->nodes[0], &key,
2288 if (key.objectid == head->bytenr &&
2289 key.type == BTRFS_EXTENT_ITEM_KEY &&
2290 key.offset == head->num_bytes)
2294 btrfs_release_path(path);
2297 key.objectid = head->bytenr;
2298 key.offset = head->num_bytes;
2299 key.type = BTRFS_EXTENT_ITEM_KEY;
2308 leaf = path->nodes[0];
2309 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2311 if (unlikely(item_size < sizeof(*ei))) {
2313 btrfs_print_v0_err(fs_info);
2314 btrfs_abort_transaction(trans, err);
2318 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2319 __run_delayed_extent_op(extent_op, leaf, ei);
2321 btrfs_mark_buffer_dirty(leaf);
2323 btrfs_free_path(path);
2327 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2328 struct btrfs_delayed_ref_node *node,
2329 struct btrfs_delayed_extent_op *extent_op,
2330 int insert_reserved)
2333 struct btrfs_delayed_tree_ref *ref;
2337 ref = btrfs_delayed_node_to_tree_ref(node);
2338 trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2340 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2341 parent = ref->parent;
2342 ref_root = ref->root;
2344 if (node->ref_mod != 1) {
2345 btrfs_err(trans->fs_info,
2346 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2347 node->bytenr, node->ref_mod, node->action, ref_root,
2351 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2352 BUG_ON(!extent_op || !extent_op->update_flags);
2353 ret = alloc_reserved_tree_block(trans, node, extent_op);
2354 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2355 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2356 ref->level, 0, 1, extent_op);
2357 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2358 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2359 ref->level, 0, 1, extent_op);
2366 /* helper function to actually process a single delayed ref entry */
2367 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2368 struct btrfs_delayed_ref_node *node,
2369 struct btrfs_delayed_extent_op *extent_op,
2370 int insert_reserved)
2374 if (trans->aborted) {
2375 if (insert_reserved)
2376 btrfs_pin_extent(trans->fs_info, node->bytenr,
2377 node->num_bytes, 1);
2381 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2382 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2383 ret = run_delayed_tree_ref(trans, node, extent_op,
2385 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2386 node->type == BTRFS_SHARED_DATA_REF_KEY)
2387 ret = run_delayed_data_ref(trans, node, extent_op,
2391 if (ret && insert_reserved)
2392 btrfs_pin_extent(trans->fs_info, node->bytenr,
2393 node->num_bytes, 1);
2397 static inline struct btrfs_delayed_ref_node *
2398 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2400 struct btrfs_delayed_ref_node *ref;
2402 if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
2406 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2407 * This is to prevent a ref count from going down to zero, which deletes
2408 * the extent item from the extent tree, when there still are references
2409 * to add, which would fail because they would not find the extent item.
2411 if (!list_empty(&head->ref_add_list))
2412 return list_first_entry(&head->ref_add_list,
2413 struct btrfs_delayed_ref_node, add_list);
2415 ref = rb_entry(rb_first_cached(&head->ref_tree),
2416 struct btrfs_delayed_ref_node, ref_node);
2417 ASSERT(list_empty(&ref->add_list));
2421 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2422 struct btrfs_delayed_ref_head *head)
2424 spin_lock(&delayed_refs->lock);
2425 head->processing = 0;
2426 delayed_refs->num_heads_ready++;
2427 spin_unlock(&delayed_refs->lock);
2428 btrfs_delayed_ref_unlock(head);
2431 static struct btrfs_delayed_extent_op *cleanup_extent_op(
2432 struct btrfs_delayed_ref_head *head)
2434 struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2439 if (head->must_insert_reserved) {
2440 head->extent_op = NULL;
2441 btrfs_free_delayed_extent_op(extent_op);
2447 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
2448 struct btrfs_delayed_ref_head *head)
2450 struct btrfs_delayed_extent_op *extent_op;
2453 extent_op = cleanup_extent_op(head);
2456 head->extent_op = NULL;
2457 spin_unlock(&head->lock);
2458 ret = run_delayed_extent_op(trans, head, extent_op);
2459 btrfs_free_delayed_extent_op(extent_op);
2460 return ret ? ret : 1;
2463 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
2464 struct btrfs_delayed_ref_root *delayed_refs,
2465 struct btrfs_delayed_ref_head *head)
2467 int nr_items = 1; /* Dropping this ref head update. */
2469 if (head->total_ref_mod < 0) {
2470 struct btrfs_space_info *space_info;
2474 flags = BTRFS_BLOCK_GROUP_DATA;
2475 else if (head->is_system)
2476 flags = BTRFS_BLOCK_GROUP_SYSTEM;
2478 flags = BTRFS_BLOCK_GROUP_METADATA;
2479 space_info = __find_space_info(fs_info, flags);
2481 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2483 BTRFS_TOTAL_BYTES_PINNED_BATCH);
2486 * We had csum deletions accounted for in our delayed refs rsv,
2487 * we need to drop the csum leaves for this update from our
2490 if (head->is_data) {
2491 spin_lock(&delayed_refs->lock);
2492 delayed_refs->pending_csums -= head->num_bytes;
2493 spin_unlock(&delayed_refs->lock);
2494 nr_items += btrfs_csum_bytes_to_leaves(fs_info,
2499 btrfs_delayed_refs_rsv_release(fs_info, nr_items);
2502 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2503 struct btrfs_delayed_ref_head *head)
2506 struct btrfs_fs_info *fs_info = trans->fs_info;
2507 struct btrfs_delayed_ref_root *delayed_refs;
2510 delayed_refs = &trans->transaction->delayed_refs;
2512 ret = run_and_cleanup_extent_op(trans, head);
2514 unselect_delayed_ref_head(delayed_refs, head);
2515 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2522 * Need to drop our head ref lock and re-acquire the delayed ref lock
2523 * and then re-check to make sure nobody got added.
2525 spin_unlock(&head->lock);
2526 spin_lock(&delayed_refs->lock);
2527 spin_lock(&head->lock);
2528 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
2529 spin_unlock(&head->lock);
2530 spin_unlock(&delayed_refs->lock);
2533 btrfs_delete_ref_head(delayed_refs, head);
2534 spin_unlock(&head->lock);
2535 spin_unlock(&delayed_refs->lock);
2537 if (head->must_insert_reserved) {
2538 btrfs_pin_extent(fs_info, head->bytenr,
2539 head->num_bytes, 1);
2540 if (head->is_data) {
2541 ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2546 btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
2548 trace_run_delayed_ref_head(fs_info, head, 0);
2549 btrfs_delayed_ref_unlock(head);
2550 btrfs_put_delayed_ref_head(head);
2554 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
2555 struct btrfs_trans_handle *trans)
2557 struct btrfs_delayed_ref_root *delayed_refs =
2558 &trans->transaction->delayed_refs;
2559 struct btrfs_delayed_ref_head *head = NULL;
2562 spin_lock(&delayed_refs->lock);
2563 head = btrfs_select_ref_head(delayed_refs);
2565 spin_unlock(&delayed_refs->lock);
2570 * Grab the lock that says we are going to process all the refs for
2573 ret = btrfs_delayed_ref_lock(delayed_refs, head);
2574 spin_unlock(&delayed_refs->lock);
2577 * We may have dropped the spin lock to get the head mutex lock, and
2578 * that might have given someone else time to free the head. If that's
2579 * true, it has been removed from our list and we can move on.
2582 head = ERR_PTR(-EAGAIN);
2587 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
2588 struct btrfs_delayed_ref_head *locked_ref,
2589 unsigned long *run_refs)
2591 struct btrfs_fs_info *fs_info = trans->fs_info;
2592 struct btrfs_delayed_ref_root *delayed_refs;
2593 struct btrfs_delayed_extent_op *extent_op;
2594 struct btrfs_delayed_ref_node *ref;
2595 int must_insert_reserved = 0;
2598 delayed_refs = &trans->transaction->delayed_refs;
2600 lockdep_assert_held(&locked_ref->mutex);
2601 lockdep_assert_held(&locked_ref->lock);
2603 while ((ref = select_delayed_ref(locked_ref))) {
2605 btrfs_check_delayed_seq(fs_info, ref->seq)) {
2606 spin_unlock(&locked_ref->lock);
2607 unselect_delayed_ref_head(delayed_refs, locked_ref);
2613 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2614 RB_CLEAR_NODE(&ref->ref_node);
2615 if (!list_empty(&ref->add_list))
2616 list_del(&ref->add_list);
2618 * When we play the delayed ref, also correct the ref_mod on
2621 switch (ref->action) {
2622 case BTRFS_ADD_DELAYED_REF:
2623 case BTRFS_ADD_DELAYED_EXTENT:
2624 locked_ref->ref_mod -= ref->ref_mod;
2626 case BTRFS_DROP_DELAYED_REF:
2627 locked_ref->ref_mod += ref->ref_mod;
2632 atomic_dec(&delayed_refs->num_entries);
2635 * Record the must_insert_reserved flag before we drop the
2638 must_insert_reserved = locked_ref->must_insert_reserved;
2639 locked_ref->must_insert_reserved = 0;
2641 extent_op = locked_ref->extent_op;
2642 locked_ref->extent_op = NULL;
2643 spin_unlock(&locked_ref->lock);
2645 ret = run_one_delayed_ref(trans, ref, extent_op,
2646 must_insert_reserved);
2648 btrfs_free_delayed_extent_op(extent_op);
2650 unselect_delayed_ref_head(delayed_refs, locked_ref);
2651 btrfs_put_delayed_ref(ref);
2652 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2657 btrfs_put_delayed_ref(ref);
2660 spin_lock(&locked_ref->lock);
2661 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2668 * Returns 0 on success or if called with an already aborted transaction.
2669 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2671 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2674 struct btrfs_fs_info *fs_info = trans->fs_info;
2675 struct btrfs_delayed_ref_root *delayed_refs;
2676 struct btrfs_delayed_ref_head *locked_ref = NULL;
2677 ktime_t start = ktime_get();
2679 unsigned long count = 0;
2680 unsigned long actual_count = 0;
2682 delayed_refs = &trans->transaction->delayed_refs;
2685 locked_ref = btrfs_obtain_ref_head(trans);
2686 if (IS_ERR_OR_NULL(locked_ref)) {
2687 if (PTR_ERR(locked_ref) == -EAGAIN) {
2696 * We need to try and merge add/drops of the same ref since we
2697 * can run into issues with relocate dropping the implicit ref
2698 * and then it being added back again before the drop can
2699 * finish. If we merged anything we need to re-loop so we can
2701 * Or we can get node references of the same type that weren't
2702 * merged when created due to bumps in the tree mod seq, and
2703 * we need to merge them to prevent adding an inline extent
2704 * backref before dropping it (triggering a BUG_ON at
2705 * insert_inline_extent_backref()).
2707 spin_lock(&locked_ref->lock);
2708 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2710 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2712 if (ret < 0 && ret != -EAGAIN) {
2714 * Error, btrfs_run_delayed_refs_for_head already
2715 * unlocked everything so just bail out
2720 * Success, perform the usual cleanup of a processed
2723 ret = cleanup_ref_head(trans, locked_ref);
2725 /* We dropped our lock, we need to loop. */
2734 * Either success case or btrfs_run_delayed_refs_for_head
2735 * returned -EAGAIN, meaning we need to select another head
2740 } while ((nr != -1 && count < nr) || locked_ref);
2743 * We don't want to include ref heads since we can have empty ref heads
2744 * and those will drastically skew our runtime down since we just do
2745 * accounting, no actual extent tree updates.
2747 if (actual_count > 0) {
2748 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2752 * We weigh the current average higher than our current runtime
2753 * to avoid large swings in the average.
2755 spin_lock(&delayed_refs->lock);
2756 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2757 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2758 spin_unlock(&delayed_refs->lock);
2763 #ifdef SCRAMBLE_DELAYED_REFS
2765 * Normally delayed refs get processed in ascending bytenr order. This
2766 * correlates in most cases to the order added. To expose dependencies on this
2767 * order, we start to process the tree in the middle instead of the beginning
2769 static u64 find_middle(struct rb_root *root)
2771 struct rb_node *n = root->rb_node;
2772 struct btrfs_delayed_ref_node *entry;
2775 u64 first = 0, last = 0;
2779 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2780 first = entry->bytenr;
2784 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2785 last = entry->bytenr;
2790 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2791 WARN_ON(!entry->in_tree);
2793 middle = entry->bytenr;
2806 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2810 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2811 sizeof(struct btrfs_extent_inline_ref));
2812 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2813 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2816 * We don't ever fill up leaves all the way so multiply by 2 just to be
2817 * closer to what we're really going to want to use.
2819 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2823 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2824 * would require to store the csums for that many bytes.
2826 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2829 u64 num_csums_per_leaf;
2832 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2833 num_csums_per_leaf = div64_u64(csum_size,
2834 (u64)btrfs_super_csum_size(fs_info->super_copy));
2835 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2836 num_csums += num_csums_per_leaf - 1;
2837 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2841 bool btrfs_check_space_for_delayed_refs(struct btrfs_fs_info *fs_info)
2843 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
2844 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2848 spin_lock(&global_rsv->lock);
2849 reserved = global_rsv->reserved;
2850 spin_unlock(&global_rsv->lock);
2853 * Since the global reserve is just kind of magic we don't really want
2854 * to rely on it to save our bacon, so if our size is more than the
2855 * delayed_refs_rsv and the global rsv then it's time to think about
2858 spin_lock(&delayed_refs_rsv->lock);
2859 reserved += delayed_refs_rsv->reserved;
2860 if (delayed_refs_rsv->size >= reserved)
2862 spin_unlock(&delayed_refs_rsv->lock);
2866 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans)
2869 atomic_read(&trans->transaction->delayed_refs.num_entries);
2874 avg_runtime = trans->fs_info->avg_delayed_ref_runtime;
2875 val = num_entries * avg_runtime;
2876 if (val >= NSEC_PER_SEC)
2878 if (val >= NSEC_PER_SEC / 2)
2881 return btrfs_check_space_for_delayed_refs(trans->fs_info);
2885 * this starts processing the delayed reference count updates and
2886 * extent insertions we have queued up so far. count can be
2887 * 0, which means to process everything in the tree at the start
2888 * of the run (but not newly added entries), or it can be some target
2889 * number you'd like to process.
2891 * Returns 0 on success or if called with an aborted transaction
2892 * Returns <0 on error and aborts the transaction
2894 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2895 unsigned long count)
2897 struct btrfs_fs_info *fs_info = trans->fs_info;
2898 struct rb_node *node;
2899 struct btrfs_delayed_ref_root *delayed_refs;
2900 struct btrfs_delayed_ref_head *head;
2902 int run_all = count == (unsigned long)-1;
2904 /* We'll clean this up in btrfs_cleanup_transaction */
2908 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2911 delayed_refs = &trans->transaction->delayed_refs;
2913 count = atomic_read(&delayed_refs->num_entries) * 2;
2916 #ifdef SCRAMBLE_DELAYED_REFS
2917 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2919 ret = __btrfs_run_delayed_refs(trans, count);
2921 btrfs_abort_transaction(trans, ret);
2926 btrfs_create_pending_block_groups(trans);
2928 spin_lock(&delayed_refs->lock);
2929 node = rb_first_cached(&delayed_refs->href_root);
2931 spin_unlock(&delayed_refs->lock);
2934 head = rb_entry(node, struct btrfs_delayed_ref_head,
2936 refcount_inc(&head->refs);
2937 spin_unlock(&delayed_refs->lock);
2939 /* Mutex was contended, block until it's released and retry. */
2940 mutex_lock(&head->mutex);
2941 mutex_unlock(&head->mutex);
2943 btrfs_put_delayed_ref_head(head);
2951 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2952 u64 bytenr, u64 num_bytes, u64 flags,
2953 int level, int is_data)
2955 struct btrfs_delayed_extent_op *extent_op;
2958 extent_op = btrfs_alloc_delayed_extent_op();
2962 extent_op->flags_to_set = flags;
2963 extent_op->update_flags = true;
2964 extent_op->update_key = false;
2965 extent_op->is_data = is_data ? true : false;
2966 extent_op->level = level;
2968 ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2970 btrfs_free_delayed_extent_op(extent_op);
2974 static noinline int check_delayed_ref(struct btrfs_root *root,
2975 struct btrfs_path *path,
2976 u64 objectid, u64 offset, u64 bytenr)
2978 struct btrfs_delayed_ref_head *head;
2979 struct btrfs_delayed_ref_node *ref;
2980 struct btrfs_delayed_data_ref *data_ref;
2981 struct btrfs_delayed_ref_root *delayed_refs;
2982 struct btrfs_transaction *cur_trans;
2983 struct rb_node *node;
2986 spin_lock(&root->fs_info->trans_lock);
2987 cur_trans = root->fs_info->running_transaction;
2989 refcount_inc(&cur_trans->use_count);
2990 spin_unlock(&root->fs_info->trans_lock);
2994 delayed_refs = &cur_trans->delayed_refs;
2995 spin_lock(&delayed_refs->lock);
2996 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2998 spin_unlock(&delayed_refs->lock);
2999 btrfs_put_transaction(cur_trans);
3003 if (!mutex_trylock(&head->mutex)) {
3004 refcount_inc(&head->refs);
3005 spin_unlock(&delayed_refs->lock);
3007 btrfs_release_path(path);
3010 * Mutex was contended, block until it's released and let
3013 mutex_lock(&head->mutex);
3014 mutex_unlock(&head->mutex);
3015 btrfs_put_delayed_ref_head(head);
3016 btrfs_put_transaction(cur_trans);
3019 spin_unlock(&delayed_refs->lock);
3021 spin_lock(&head->lock);
3023 * XXX: We should replace this with a proper search function in the
3026 for (node = rb_first_cached(&head->ref_tree); node;
3027 node = rb_next(node)) {
3028 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
3029 /* If it's a shared ref we know a cross reference exists */
3030 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3035 data_ref = btrfs_delayed_node_to_data_ref(ref);
3038 * If our ref doesn't match the one we're currently looking at
3039 * then we have a cross reference.
3041 if (data_ref->root != root->root_key.objectid ||
3042 data_ref->objectid != objectid ||
3043 data_ref->offset != offset) {
3048 spin_unlock(&head->lock);
3049 mutex_unlock(&head->mutex);
3050 btrfs_put_transaction(cur_trans);
3054 static noinline int check_committed_ref(struct btrfs_root *root,
3055 struct btrfs_path *path,
3056 u64 objectid, u64 offset, u64 bytenr)
3058 struct btrfs_fs_info *fs_info = root->fs_info;
3059 struct btrfs_root *extent_root = fs_info->extent_root;
3060 struct extent_buffer *leaf;
3061 struct btrfs_extent_data_ref *ref;
3062 struct btrfs_extent_inline_ref *iref;
3063 struct btrfs_extent_item *ei;
3064 struct btrfs_key key;
3069 key.objectid = bytenr;
3070 key.offset = (u64)-1;
3071 key.type = BTRFS_EXTENT_ITEM_KEY;
3073 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3076 BUG_ON(ret == 0); /* Corruption */
3079 if (path->slots[0] == 0)
3083 leaf = path->nodes[0];
3084 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3086 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3090 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3091 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3093 if (item_size != sizeof(*ei) +
3094 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3097 if (btrfs_extent_generation(leaf, ei) <=
3098 btrfs_root_last_snapshot(&root->root_item))
3101 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3103 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
3104 if (type != BTRFS_EXTENT_DATA_REF_KEY)
3107 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3108 if (btrfs_extent_refs(leaf, ei) !=
3109 btrfs_extent_data_ref_count(leaf, ref) ||
3110 btrfs_extent_data_ref_root(leaf, ref) !=
3111 root->root_key.objectid ||
3112 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3113 btrfs_extent_data_ref_offset(leaf, ref) != offset)
3121 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3124 struct btrfs_path *path;
3127 path = btrfs_alloc_path();
3132 ret = check_committed_ref(root, path, objectid,
3134 if (ret && ret != -ENOENT)
3137 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
3138 } while (ret == -EAGAIN);
3141 btrfs_free_path(path);
3142 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3147 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3148 struct btrfs_root *root,
3149 struct extent_buffer *buf,
3150 int full_backref, int inc)
3152 struct btrfs_fs_info *fs_info = root->fs_info;
3158 struct btrfs_key key;
3159 struct btrfs_file_extent_item *fi;
3160 struct btrfs_ref generic_ref = { 0 };
3161 bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
3167 if (btrfs_is_testing(fs_info))
3170 ref_root = btrfs_header_owner(buf);
3171 nritems = btrfs_header_nritems(buf);
3172 level = btrfs_header_level(buf);
3174 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3178 parent = buf->start;
3182 action = BTRFS_ADD_DELAYED_REF;
3184 action = BTRFS_DROP_DELAYED_REF;
3186 for (i = 0; i < nritems; i++) {
3188 btrfs_item_key_to_cpu(buf, &key, i);
3189 if (key.type != BTRFS_EXTENT_DATA_KEY)
3191 fi = btrfs_item_ptr(buf, i,
3192 struct btrfs_file_extent_item);
3193 if (btrfs_file_extent_type(buf, fi) ==
3194 BTRFS_FILE_EXTENT_INLINE)
3196 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3200 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3201 key.offset -= btrfs_file_extent_offset(buf, fi);
3202 btrfs_init_generic_ref(&generic_ref, action, bytenr,
3204 generic_ref.real_root = root->root_key.objectid;
3205 btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
3207 generic_ref.skip_qgroup = for_reloc;
3209 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3211 ret = btrfs_free_extent(trans, &generic_ref);
3215 bytenr = btrfs_node_blockptr(buf, i);
3216 num_bytes = fs_info->nodesize;
3217 btrfs_init_generic_ref(&generic_ref, action, bytenr,
3219 generic_ref.real_root = root->root_key.objectid;
3220 btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
3221 generic_ref.skip_qgroup = for_reloc;
3223 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3225 ret = btrfs_free_extent(trans, &generic_ref);
3235 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3236 struct extent_buffer *buf, int full_backref)
3238 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3241 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3242 struct extent_buffer *buf, int full_backref)
3244 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3247 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3248 struct btrfs_path *path,
3249 struct btrfs_block_group_cache *cache)
3251 struct btrfs_fs_info *fs_info = trans->fs_info;
3253 struct btrfs_root *extent_root = fs_info->extent_root;
3255 struct extent_buffer *leaf;
3257 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3264 leaf = path->nodes[0];
3265 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3266 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3267 btrfs_mark_buffer_dirty(leaf);
3269 btrfs_release_path(path);
3274 static struct btrfs_block_group_cache *next_block_group(
3275 struct btrfs_block_group_cache *cache)
3277 struct btrfs_fs_info *fs_info = cache->fs_info;
3278 struct rb_node *node;
3280 spin_lock(&fs_info->block_group_cache_lock);
3282 /* If our block group was removed, we need a full search. */
3283 if (RB_EMPTY_NODE(&cache->cache_node)) {
3284 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3286 spin_unlock(&fs_info->block_group_cache_lock);
3287 btrfs_put_block_group(cache);
3288 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3290 node = rb_next(&cache->cache_node);
3291 btrfs_put_block_group(cache);
3293 cache = rb_entry(node, struct btrfs_block_group_cache,
3295 btrfs_get_block_group(cache);
3298 spin_unlock(&fs_info->block_group_cache_lock);
3302 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3303 struct btrfs_trans_handle *trans,
3304 struct btrfs_path *path)
3306 struct btrfs_fs_info *fs_info = block_group->fs_info;
3307 struct btrfs_root *root = fs_info->tree_root;
3308 struct inode *inode = NULL;
3309 struct extent_changeset *data_reserved = NULL;
3311 int dcs = BTRFS_DC_ERROR;
3317 * If this block group is smaller than 100 megs don't bother caching the
3320 if (block_group->key.offset < (100 * SZ_1M)) {
3321 spin_lock(&block_group->lock);
3322 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3323 spin_unlock(&block_group->lock);
3330 inode = lookup_free_space_inode(block_group, path);
3331 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3332 ret = PTR_ERR(inode);
3333 btrfs_release_path(path);
3337 if (IS_ERR(inode)) {
3341 if (block_group->ro)
3344 ret = create_free_space_inode(trans, block_group, path);
3351 * We want to set the generation to 0, that way if anything goes wrong
3352 * from here on out we know not to trust this cache when we load up next
3355 BTRFS_I(inode)->generation = 0;
3356 ret = btrfs_update_inode(trans, root, inode);
3359 * So theoretically we could recover from this, simply set the
3360 * super cache generation to 0 so we know to invalidate the
3361 * cache, but then we'd have to keep track of the block groups
3362 * that fail this way so we know we _have_ to reset this cache
3363 * before the next commit or risk reading stale cache. So to
3364 * limit our exposure to horrible edge cases lets just abort the
3365 * transaction, this only happens in really bad situations
3368 btrfs_abort_transaction(trans, ret);
3373 /* We've already setup this transaction, go ahead and exit */
3374 if (block_group->cache_generation == trans->transid &&
3375 i_size_read(inode)) {
3376 dcs = BTRFS_DC_SETUP;
3380 if (i_size_read(inode) > 0) {
3381 ret = btrfs_check_trunc_cache_free_space(fs_info,
3382 &fs_info->global_block_rsv);
3386 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3391 spin_lock(&block_group->lock);
3392 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3393 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3395 * don't bother trying to write stuff out _if_
3396 * a) we're not cached,
3397 * b) we're with nospace_cache mount option,
3398 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3400 dcs = BTRFS_DC_WRITTEN;
3401 spin_unlock(&block_group->lock);
3404 spin_unlock(&block_group->lock);
3407 * We hit an ENOSPC when setting up the cache in this transaction, just
3408 * skip doing the setup, we've already cleared the cache so we're safe.
3410 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3416 * Try to preallocate enough space based on how big the block group is.
3417 * Keep in mind this has to include any pinned space which could end up
3418 * taking up quite a bit since it's not folded into the other space
3421 num_pages = div_u64(block_group->key.offset, SZ_256M);
3426 num_pages *= PAGE_SIZE;
3428 ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
3432 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3433 num_pages, num_pages,
3436 * Our cache requires contiguous chunks so that we don't modify a bunch
3437 * of metadata or split extents when writing the cache out, which means
3438 * we can enospc if we are heavily fragmented in addition to just normal
3439 * out of space conditions. So if we hit this just skip setting up any
3440 * other block groups for this transaction, maybe we'll unpin enough
3441 * space the next time around.
3444 dcs = BTRFS_DC_SETUP;
3445 else if (ret == -ENOSPC)
3446 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3451 btrfs_release_path(path);
3453 spin_lock(&block_group->lock);
3454 if (!ret && dcs == BTRFS_DC_SETUP)
3455 block_group->cache_generation = trans->transid;
3456 block_group->disk_cache_state = dcs;
3457 spin_unlock(&block_group->lock);
3459 extent_changeset_free(data_reserved);
3463 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3465 struct btrfs_fs_info *fs_info = trans->fs_info;
3466 struct btrfs_block_group_cache *cache, *tmp;
3467 struct btrfs_transaction *cur_trans = trans->transaction;
3468 struct btrfs_path *path;
3470 if (list_empty(&cur_trans->dirty_bgs) ||
3471 !btrfs_test_opt(fs_info, SPACE_CACHE))
3474 path = btrfs_alloc_path();
3478 /* Could add new block groups, use _safe just in case */
3479 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3481 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3482 cache_save_setup(cache, trans, path);
3485 btrfs_free_path(path);
3490 * transaction commit does final block group cache writeback during a
3491 * critical section where nothing is allowed to change the FS. This is
3492 * required in order for the cache to actually match the block group,
3493 * but can introduce a lot of latency into the commit.
3495 * So, btrfs_start_dirty_block_groups is here to kick off block group
3496 * cache IO. There's a chance we'll have to redo some of it if the
3497 * block group changes again during the commit, but it greatly reduces
3498 * the commit latency by getting rid of the easy block groups while
3499 * we're still allowing others to join the commit.
3501 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3503 struct btrfs_fs_info *fs_info = trans->fs_info;
3504 struct btrfs_block_group_cache *cache;
3505 struct btrfs_transaction *cur_trans = trans->transaction;
3508 struct btrfs_path *path = NULL;
3510 struct list_head *io = &cur_trans->io_bgs;
3511 int num_started = 0;
3514 spin_lock(&cur_trans->dirty_bgs_lock);
3515 if (list_empty(&cur_trans->dirty_bgs)) {
3516 spin_unlock(&cur_trans->dirty_bgs_lock);
3519 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3520 spin_unlock(&cur_trans->dirty_bgs_lock);
3524 * make sure all the block groups on our dirty list actually
3527 btrfs_create_pending_block_groups(trans);
3530 path = btrfs_alloc_path();
3536 * cache_write_mutex is here only to save us from balance or automatic
3537 * removal of empty block groups deleting this block group while we are
3538 * writing out the cache
3540 mutex_lock(&trans->transaction->cache_write_mutex);
3541 while (!list_empty(&dirty)) {
3542 bool drop_reserve = true;
3544 cache = list_first_entry(&dirty,
3545 struct btrfs_block_group_cache,
3548 * this can happen if something re-dirties a block
3549 * group that is already under IO. Just wait for it to
3550 * finish and then do it all again
3552 if (!list_empty(&cache->io_list)) {
3553 list_del_init(&cache->io_list);
3554 btrfs_wait_cache_io(trans, cache, path);
3555 btrfs_put_block_group(cache);
3560 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3561 * if it should update the cache_state. Don't delete
3562 * until after we wait.
3564 * Since we're not running in the commit critical section
3565 * we need the dirty_bgs_lock to protect from update_block_group
3567 spin_lock(&cur_trans->dirty_bgs_lock);
3568 list_del_init(&cache->dirty_list);
3569 spin_unlock(&cur_trans->dirty_bgs_lock);
3573 cache_save_setup(cache, trans, path);
3575 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3576 cache->io_ctl.inode = NULL;
3577 ret = btrfs_write_out_cache(trans, cache, path);
3578 if (ret == 0 && cache->io_ctl.inode) {
3583 * The cache_write_mutex is protecting the
3584 * io_list, also refer to the definition of
3585 * btrfs_transaction::io_bgs for more details
3587 list_add_tail(&cache->io_list, io);
3590 * if we failed to write the cache, the
3591 * generation will be bad and life goes on
3597 ret = write_one_cache_group(trans, path, cache);
3599 * Our block group might still be attached to the list
3600 * of new block groups in the transaction handle of some
3601 * other task (struct btrfs_trans_handle->new_bgs). This
3602 * means its block group item isn't yet in the extent
3603 * tree. If this happens ignore the error, as we will
3604 * try again later in the critical section of the
3605 * transaction commit.
3607 if (ret == -ENOENT) {
3609 spin_lock(&cur_trans->dirty_bgs_lock);
3610 if (list_empty(&cache->dirty_list)) {
3611 list_add_tail(&cache->dirty_list,
3612 &cur_trans->dirty_bgs);
3613 btrfs_get_block_group(cache);
3614 drop_reserve = false;
3616 spin_unlock(&cur_trans->dirty_bgs_lock);
3618 btrfs_abort_transaction(trans, ret);
3622 /* if it's not on the io list, we need to put the block group */
3624 btrfs_put_block_group(cache);
3626 btrfs_delayed_refs_rsv_release(fs_info, 1);
3632 * Avoid blocking other tasks for too long. It might even save
3633 * us from writing caches for block groups that are going to be
3636 mutex_unlock(&trans->transaction->cache_write_mutex);
3637 mutex_lock(&trans->transaction->cache_write_mutex);
3639 mutex_unlock(&trans->transaction->cache_write_mutex);
3642 * go through delayed refs for all the stuff we've just kicked off
3643 * and then loop back (just once)
3645 ret = btrfs_run_delayed_refs(trans, 0);
3646 if (!ret && loops == 0) {
3648 spin_lock(&cur_trans->dirty_bgs_lock);
3649 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3651 * dirty_bgs_lock protects us from concurrent block group
3652 * deletes too (not just cache_write_mutex).
3654 if (!list_empty(&dirty)) {
3655 spin_unlock(&cur_trans->dirty_bgs_lock);
3658 spin_unlock(&cur_trans->dirty_bgs_lock);
3659 } else if (ret < 0) {
3660 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3663 btrfs_free_path(path);
3667 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3669 struct btrfs_fs_info *fs_info = trans->fs_info;
3670 struct btrfs_block_group_cache *cache;
3671 struct btrfs_transaction *cur_trans = trans->transaction;
3674 struct btrfs_path *path;
3675 struct list_head *io = &cur_trans->io_bgs;
3676 int num_started = 0;
3678 path = btrfs_alloc_path();
3683 * Even though we are in the critical section of the transaction commit,
3684 * we can still have concurrent tasks adding elements to this
3685 * transaction's list of dirty block groups. These tasks correspond to
3686 * endio free space workers started when writeback finishes for a
3687 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3688 * allocate new block groups as a result of COWing nodes of the root
3689 * tree when updating the free space inode. The writeback for the space
3690 * caches is triggered by an earlier call to
3691 * btrfs_start_dirty_block_groups() and iterations of the following
3693 * Also we want to do the cache_save_setup first and then run the
3694 * delayed refs to make sure we have the best chance at doing this all
3697 spin_lock(&cur_trans->dirty_bgs_lock);
3698 while (!list_empty(&cur_trans->dirty_bgs)) {
3699 cache = list_first_entry(&cur_trans->dirty_bgs,
3700 struct btrfs_block_group_cache,
3704 * this can happen if cache_save_setup re-dirties a block
3705 * group that is already under IO. Just wait for it to
3706 * finish and then do it all again
3708 if (!list_empty(&cache->io_list)) {
3709 spin_unlock(&cur_trans->dirty_bgs_lock);
3710 list_del_init(&cache->io_list);
3711 btrfs_wait_cache_io(trans, cache, path);
3712 btrfs_put_block_group(cache);
3713 spin_lock(&cur_trans->dirty_bgs_lock);
3717 * don't remove from the dirty list until after we've waited
3720 list_del_init(&cache->dirty_list);
3721 spin_unlock(&cur_trans->dirty_bgs_lock);
3724 cache_save_setup(cache, trans, path);
3727 ret = btrfs_run_delayed_refs(trans,
3728 (unsigned long) -1);
3730 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3731 cache->io_ctl.inode = NULL;
3732 ret = btrfs_write_out_cache(trans, cache, path);
3733 if (ret == 0 && cache->io_ctl.inode) {
3736 list_add_tail(&cache->io_list, io);
3739 * if we failed to write the cache, the
3740 * generation will be bad and life goes on
3746 ret = write_one_cache_group(trans, path, cache);
3748 * One of the free space endio workers might have
3749 * created a new block group while updating a free space
3750 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3751 * and hasn't released its transaction handle yet, in
3752 * which case the new block group is still attached to
3753 * its transaction handle and its creation has not
3754 * finished yet (no block group item in the extent tree
3755 * yet, etc). If this is the case, wait for all free
3756 * space endio workers to finish and retry. This is a
3757 * a very rare case so no need for a more efficient and
3760 if (ret == -ENOENT) {
3761 wait_event(cur_trans->writer_wait,
3762 atomic_read(&cur_trans->num_writers) == 1);
3763 ret = write_one_cache_group(trans, path, cache);
3766 btrfs_abort_transaction(trans, ret);
3769 /* if its not on the io list, we need to put the block group */
3771 btrfs_put_block_group(cache);
3772 btrfs_delayed_refs_rsv_release(fs_info, 1);
3773 spin_lock(&cur_trans->dirty_bgs_lock);
3775 spin_unlock(&cur_trans->dirty_bgs_lock);
3778 * Refer to the definition of io_bgs member for details why it's safe
3779 * to use it without any locking
3781 while (!list_empty(io)) {
3782 cache = list_first_entry(io, struct btrfs_block_group_cache,
3784 list_del_init(&cache->io_list);
3785 btrfs_wait_cache_io(trans, cache, path);
3786 btrfs_put_block_group(cache);
3789 btrfs_free_path(path);
3793 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3795 struct btrfs_block_group_cache *block_group;
3798 block_group = btrfs_lookup_block_group(fs_info, bytenr);
3799 if (!block_group || block_group->ro)
3802 btrfs_put_block_group(block_group);
3806 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3808 struct btrfs_block_group_cache *bg;
3811 bg = btrfs_lookup_block_group(fs_info, bytenr);
3815 spin_lock(&bg->lock);
3819 atomic_inc(&bg->nocow_writers);
3820 spin_unlock(&bg->lock);
3822 /* no put on block group, done by btrfs_dec_nocow_writers */
3824 btrfs_put_block_group(bg);
3830 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3832 struct btrfs_block_group_cache *bg;
3834 bg = btrfs_lookup_block_group(fs_info, bytenr);
3836 if (atomic_dec_and_test(&bg->nocow_writers))
3837 wake_up_var(&bg->nocow_writers);
3839 * Once for our lookup and once for the lookup done by a previous call
3840 * to btrfs_inc_nocow_writers()
3842 btrfs_put_block_group(bg);
3843 btrfs_put_block_group(bg);
3846 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3848 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3851 static const char *alloc_name(u64 flags)
3854 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3856 case BTRFS_BLOCK_GROUP_METADATA:
3858 case BTRFS_BLOCK_GROUP_DATA:
3860 case BTRFS_BLOCK_GROUP_SYSTEM:
3864 return "invalid-combination";
3868 static int create_space_info(struct btrfs_fs_info *info, u64 flags)
3871 struct btrfs_space_info *space_info;
3875 space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
3879 ret = percpu_counter_init(&space_info->total_bytes_pinned, 0,
3886 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3887 INIT_LIST_HEAD(&space_info->block_groups[i]);
3888 init_rwsem(&space_info->groups_sem);
3889 spin_lock_init(&space_info->lock);
3890 space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3891 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3892 init_waitqueue_head(&space_info->wait);
3893 INIT_LIST_HEAD(&space_info->ro_bgs);
3894 INIT_LIST_HEAD(&space_info->tickets);
3895 INIT_LIST_HEAD(&space_info->priority_tickets);
3897 ret = kobject_init_and_add(&space_info->kobj, &space_info_ktype,
3898 info->space_info_kobj, "%s",
3899 alloc_name(space_info->flags));
3901 kobject_put(&space_info->kobj);
3905 list_add_rcu(&space_info->list, &info->space_info);
3906 if (flags & BTRFS_BLOCK_GROUP_DATA)
3907 info->data_sinfo = space_info;
3912 static void update_space_info(struct btrfs_fs_info *info, u64 flags,
3913 u64 total_bytes, u64 bytes_used,
3915 struct btrfs_space_info **space_info)
3917 struct btrfs_space_info *found;
3920 factor = btrfs_bg_type_to_factor(flags);
3922 found = __find_space_info(info, flags);
3924 spin_lock(&found->lock);
3925 found->total_bytes += total_bytes;
3926 found->disk_total += total_bytes * factor;
3927 found->bytes_used += bytes_used;
3928 found->disk_used += bytes_used * factor;
3929 found->bytes_readonly += bytes_readonly;
3930 if (total_bytes > 0)
3932 space_info_add_new_bytes(info, found, total_bytes -
3933 bytes_used - bytes_readonly);
3934 spin_unlock(&found->lock);
3935 *space_info = found;
3938 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3940 u64 extra_flags = chunk_to_extended(flags) &
3941 BTRFS_EXTENDED_PROFILE_MASK;
3943 write_seqlock(&fs_info->profiles_lock);
3944 if (flags & BTRFS_BLOCK_GROUP_DATA)
3945 fs_info->avail_data_alloc_bits |= extra_flags;
3946 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3947 fs_info->avail_metadata_alloc_bits |= extra_flags;
3948 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3949 fs_info->avail_system_alloc_bits |= extra_flags;
3950 write_sequnlock(&fs_info->profiles_lock);
3954 * returns target flags in extended format or 0 if restripe for this
3955 * chunk_type is not in progress
3957 * should be called with balance_lock held
3959 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3961 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3967 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3968 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3969 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3970 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3971 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3972 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3973 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3974 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3975 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3982 * @flags: available profiles in extended format (see ctree.h)
3984 * Returns reduced profile in chunk format. If profile changing is in
3985 * progress (either running or paused) picks the target profile (if it's
3986 * already available), otherwise falls back to plain reducing.
3988 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
3990 u64 num_devices = fs_info->fs_devices->rw_devices;
3996 * see if restripe for this chunk_type is in progress, if so
3997 * try to reduce to the target profile
3999 spin_lock(&fs_info->balance_lock);
4000 target = get_restripe_target(fs_info, flags);
4002 /* pick target profile only if it's already available */
4003 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
4004 spin_unlock(&fs_info->balance_lock);
4005 return extended_to_chunk(target);
4008 spin_unlock(&fs_info->balance_lock);
4010 /* First, mask out the RAID levels which aren't possible */
4011 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4012 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
4013 allowed |= btrfs_raid_array[raid_type].bg_flag;
4017 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
4018 allowed = BTRFS_BLOCK_GROUP_RAID6;
4019 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
4020 allowed = BTRFS_BLOCK_GROUP_RAID5;
4021 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
4022 allowed = BTRFS_BLOCK_GROUP_RAID10;
4023 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
4024 allowed = BTRFS_BLOCK_GROUP_RAID1;
4025 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
4026 allowed = BTRFS_BLOCK_GROUP_RAID0;
4028 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4030 return extended_to_chunk(flags | allowed);
4033 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
4040 seq = read_seqbegin(&fs_info->profiles_lock);
4042 if (flags & BTRFS_BLOCK_GROUP_DATA)
4043 flags |= fs_info->avail_data_alloc_bits;
4044 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4045 flags |= fs_info->avail_system_alloc_bits;
4046 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
4047 flags |= fs_info->avail_metadata_alloc_bits;
4048 } while (read_seqretry(&fs_info->profiles_lock, seq));
4050 return btrfs_reduce_alloc_profile(fs_info, flags);
4053 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
4055 struct btrfs_fs_info *fs_info = root->fs_info;
4060 flags = BTRFS_BLOCK_GROUP_DATA;
4061 else if (root == fs_info->chunk_root)
4062 flags = BTRFS_BLOCK_GROUP_SYSTEM;
4064 flags = BTRFS_BLOCK_GROUP_METADATA;
4066 ret = get_alloc_profile(fs_info, flags);
4070 u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
4072 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
4075 u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
4077 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4080 u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
4082 return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4085 static u64 btrfs_space_info_used(struct btrfs_space_info *s_info,
4086 bool may_use_included)
4089 return s_info->bytes_used + s_info->bytes_reserved +
4090 s_info->bytes_pinned + s_info->bytes_readonly +
4091 (may_use_included ? s_info->bytes_may_use : 0);
4094 int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
4096 struct btrfs_root *root = inode->root;
4097 struct btrfs_fs_info *fs_info = root->fs_info;
4098 struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
4101 int need_commit = 2;
4102 int have_pinned_space;
4104 /* make sure bytes are sectorsize aligned */
4105 bytes = ALIGN(bytes, fs_info->sectorsize);
4107 if (btrfs_is_free_space_inode(inode)) {
4109 ASSERT(current->journal_info);
4113 /* make sure we have enough space to handle the data first */
4114 spin_lock(&data_sinfo->lock);
4115 used = btrfs_space_info_used(data_sinfo, true);
4117 if (used + bytes > data_sinfo->total_bytes) {
4118 struct btrfs_trans_handle *trans;
4121 * if we don't have enough free bytes in this space then we need
4122 * to alloc a new chunk.
4124 if (!data_sinfo->full) {
4127 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4128 spin_unlock(&data_sinfo->lock);
4130 alloc_target = btrfs_data_alloc_profile(fs_info);
4132 * It is ugly that we don't call nolock join
4133 * transaction for the free space inode case here.
4134 * But it is safe because we only do the data space
4135 * reservation for the free space cache in the
4136 * transaction context, the common join transaction
4137 * just increase the counter of the current transaction
4138 * handler, doesn't try to acquire the trans_lock of
4141 trans = btrfs_join_transaction(root);
4143 return PTR_ERR(trans);
4145 ret = do_chunk_alloc(trans, alloc_target,
4146 CHUNK_ALLOC_NO_FORCE);
4147 btrfs_end_transaction(trans);
4152 have_pinned_space = 1;
4161 * If we don't have enough pinned space to deal with this
4162 * allocation, and no removed chunk in current transaction,
4163 * don't bother committing the transaction.
4165 have_pinned_space = __percpu_counter_compare(
4166 &data_sinfo->total_bytes_pinned,
4167 used + bytes - data_sinfo->total_bytes,
4168 BTRFS_TOTAL_BYTES_PINNED_BATCH);
4169 spin_unlock(&data_sinfo->lock);
4171 /* commit the current transaction and try again */
4176 if (need_commit > 0) {
4177 btrfs_start_delalloc_roots(fs_info, -1);
4178 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0,
4182 trans = btrfs_join_transaction(root);
4184 return PTR_ERR(trans);
4185 if (have_pinned_space >= 0 ||
4186 test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4187 &trans->transaction->flags) ||
4189 ret = btrfs_commit_transaction(trans);
4193 * The cleaner kthread might still be doing iput
4194 * operations. Wait for it to finish so that
4195 * more space is released. We don't need to
4196 * explicitly run the delayed iputs here because
4197 * the commit_transaction would have woken up
4200 ret = btrfs_wait_on_delayed_iputs(fs_info);
4205 btrfs_end_transaction(trans);
4209 trace_btrfs_space_reservation(fs_info,
4210 "space_info:enospc",
4211 data_sinfo->flags, bytes, 1);
4214 update_bytes_may_use(fs_info, data_sinfo, bytes);
4215 trace_btrfs_space_reservation(fs_info, "space_info",
4216 data_sinfo->flags, bytes, 1);
4217 spin_unlock(&data_sinfo->lock);
4222 int btrfs_check_data_free_space(struct inode *inode,
4223 struct extent_changeset **reserved, u64 start, u64 len)
4225 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4228 /* align the range */
4229 len = round_up(start + len, fs_info->sectorsize) -
4230 round_down(start, fs_info->sectorsize);
4231 start = round_down(start, fs_info->sectorsize);
4233 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
4237 /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4238 ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
4240 btrfs_free_reserved_data_space_noquota(inode, start, len);
4247 * Called if we need to clear a data reservation for this inode
4248 * Normally in a error case.
4250 * This one will *NOT* use accurate qgroup reserved space API, just for case
4251 * which we can't sleep and is sure it won't affect qgroup reserved space.
4252 * Like clear_bit_hook().
4254 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4257 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4258 struct btrfs_space_info *data_sinfo;
4260 /* Make sure the range is aligned to sectorsize */
4261 len = round_up(start + len, fs_info->sectorsize) -
4262 round_down(start, fs_info->sectorsize);
4263 start = round_down(start, fs_info->sectorsize);
4265 data_sinfo = fs_info->data_sinfo;
4266 spin_lock(&data_sinfo->lock);
4267 update_bytes_may_use(fs_info, data_sinfo, -len);
4268 trace_btrfs_space_reservation(fs_info, "space_info",
4269 data_sinfo->flags, len, 0);
4270 spin_unlock(&data_sinfo->lock);
4274 * Called if we need to clear a data reservation for this inode
4275 * Normally in a error case.
4277 * This one will handle the per-inode data rsv map for accurate reserved
4280 void btrfs_free_reserved_data_space(struct inode *inode,
4281 struct extent_changeset *reserved, u64 start, u64 len)
4283 struct btrfs_root *root = BTRFS_I(inode)->root;
4285 /* Make sure the range is aligned to sectorsize */
4286 len = round_up(start + len, root->fs_info->sectorsize) -
4287 round_down(start, root->fs_info->sectorsize);
4288 start = round_down(start, root->fs_info->sectorsize);
4290 btrfs_free_reserved_data_space_noquota(inode, start, len);
4291 btrfs_qgroup_free_data(inode, reserved, start, len);
4294 static void force_metadata_allocation(struct btrfs_fs_info *info)
4296 struct list_head *head = &info->space_info;
4297 struct btrfs_space_info *found;
4300 list_for_each_entry_rcu(found, head, list) {
4301 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4302 found->force_alloc = CHUNK_ALLOC_FORCE;
4307 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4309 return (global->size << 1);
4312 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4313 struct btrfs_space_info *sinfo, int force)
4315 u64 bytes_used = btrfs_space_info_used(sinfo, false);
4318 if (force == CHUNK_ALLOC_FORCE)
4322 * in limited mode, we want to have some free space up to
4323 * about 1% of the FS size.
4325 if (force == CHUNK_ALLOC_LIMITED) {
4326 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4327 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4329 if (sinfo->total_bytes - bytes_used < thresh)
4333 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
4338 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4342 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
4344 num_dev = fs_info->fs_devices->rw_devices;
4350 * If @is_allocation is true, reserve space in the system space info necessary
4351 * for allocating a chunk, otherwise if it's false, reserve space necessary for
4354 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4356 struct btrfs_fs_info *fs_info = trans->fs_info;
4357 struct btrfs_space_info *info;
4364 * Needed because we can end up allocating a system chunk and for an
4365 * atomic and race free space reservation in the chunk block reserve.
4367 lockdep_assert_held(&fs_info->chunk_mutex);
4369 info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4370 spin_lock(&info->lock);
4371 left = info->total_bytes - btrfs_space_info_used(info, true);
4372 spin_unlock(&info->lock);
4374 num_devs = get_profile_num_devs(fs_info, type);
4376 /* num_devs device items to update and 1 chunk item to add or remove */
4377 thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4378 btrfs_calc_trans_metadata_size(fs_info, 1);
4380 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4381 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4382 left, thresh, type);
4383 dump_space_info(fs_info, info, 0, 0);
4386 if (left < thresh) {
4387 u64 flags = btrfs_system_alloc_profile(fs_info);
4390 * Ignore failure to create system chunk. We might end up not
4391 * needing it, as we might not need to COW all nodes/leafs from
4392 * the paths we visit in the chunk tree (they were already COWed
4393 * or created in the current transaction for example).
4395 ret = btrfs_alloc_chunk(trans, flags);
4399 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4400 &fs_info->chunk_block_rsv,
4401 thresh, BTRFS_RESERVE_NO_FLUSH);
4403 trans->chunk_bytes_reserved += thresh;
4408 * If force is CHUNK_ALLOC_FORCE:
4409 * - return 1 if it successfully allocates a chunk,
4410 * - return errors including -ENOSPC otherwise.
4411 * If force is NOT CHUNK_ALLOC_FORCE:
4412 * - return 0 if it doesn't need to allocate a new chunk,
4413 * - return 1 if it successfully allocates a chunk,
4414 * - return errors including -ENOSPC otherwise.
4416 static int do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
4419 struct btrfs_fs_info *fs_info = trans->fs_info;
4420 struct btrfs_space_info *space_info;
4421 bool wait_for_alloc = false;
4422 bool should_alloc = false;
4425 /* Don't re-enter if we're already allocating a chunk */
4426 if (trans->allocating_chunk)
4429 space_info = __find_space_info(fs_info, flags);
4433 spin_lock(&space_info->lock);
4434 if (force < space_info->force_alloc)
4435 force = space_info->force_alloc;
4436 should_alloc = should_alloc_chunk(fs_info, space_info, force);
4437 if (space_info->full) {
4438 /* No more free physical space */
4443 spin_unlock(&space_info->lock);
4445 } else if (!should_alloc) {
4446 spin_unlock(&space_info->lock);
4448 } else if (space_info->chunk_alloc) {
4450 * Someone is already allocating, so we need to block
4451 * until this someone is finished and then loop to
4452 * recheck if we should continue with our allocation
4455 wait_for_alloc = true;
4456 spin_unlock(&space_info->lock);
4457 mutex_lock(&fs_info->chunk_mutex);
4458 mutex_unlock(&fs_info->chunk_mutex);
4460 /* Proceed with allocation */
4461 space_info->chunk_alloc = 1;
4462 wait_for_alloc = false;
4463 spin_unlock(&space_info->lock);
4467 } while (wait_for_alloc);
4469 mutex_lock(&fs_info->chunk_mutex);
4470 trans->allocating_chunk = true;
4473 * If we have mixed data/metadata chunks we want to make sure we keep
4474 * allocating mixed chunks instead of individual chunks.
4476 if (btrfs_mixed_space_info(space_info))
4477 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4480 * if we're doing a data chunk, go ahead and make sure that
4481 * we keep a reasonable number of metadata chunks allocated in the
4484 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4485 fs_info->data_chunk_allocations++;
4486 if (!(fs_info->data_chunk_allocations %
4487 fs_info->metadata_ratio))
4488 force_metadata_allocation(fs_info);
4492 * Check if we have enough space in SYSTEM chunk because we may need
4493 * to update devices.
4495 check_system_chunk(trans, flags);
4497 ret = btrfs_alloc_chunk(trans, flags);
4498 trans->allocating_chunk = false;
4500 spin_lock(&space_info->lock);
4503 space_info->full = 1;
4508 space_info->max_extent_size = 0;
4511 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4513 space_info->chunk_alloc = 0;
4514 spin_unlock(&space_info->lock);
4515 mutex_unlock(&fs_info->chunk_mutex);
4517 * When we allocate a new chunk we reserve space in the chunk block
4518 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4519 * add new nodes/leafs to it if we end up needing to do it when
4520 * inserting the chunk item and updating device items as part of the
4521 * second phase of chunk allocation, performed by
4522 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4523 * large number of new block groups to create in our transaction
4524 * handle's new_bgs list to avoid exhausting the chunk block reserve
4525 * in extreme cases - like having a single transaction create many new
4526 * block groups when starting to write out the free space caches of all
4527 * the block groups that were made dirty during the lifetime of the
4530 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
4531 btrfs_create_pending_block_groups(trans);
4536 static int can_overcommit(struct btrfs_fs_info *fs_info,
4537 struct btrfs_space_info *space_info, u64 bytes,
4538 enum btrfs_reserve_flush_enum flush,
4541 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4548 /* Don't overcommit when in mixed mode. */
4549 if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4553 profile = btrfs_system_alloc_profile(fs_info);
4555 profile = btrfs_metadata_alloc_profile(fs_info);
4557 used = btrfs_space_info_used(space_info, false);
4560 * We only want to allow over committing if we have lots of actual space
4561 * free, but if we don't have enough space to handle the global reserve
4562 * space then we could end up having a real enospc problem when trying
4563 * to allocate a chunk or some other such important allocation.
4565 spin_lock(&global_rsv->lock);
4566 space_size = calc_global_rsv_need_space(global_rsv);
4567 spin_unlock(&global_rsv->lock);
4568 if (used + space_size >= space_info->total_bytes)
4571 used += space_info->bytes_may_use;
4573 avail = atomic64_read(&fs_info->free_chunk_space);
4576 * If we have dup, raid1 or raid10 then only half of the free
4577 * space is actually usable. For raid56, the space info used
4578 * doesn't include the parity drive, so we don't have to
4581 factor = btrfs_bg_type_to_factor(profile);
4582 avail = div_u64(avail, factor);
4585 * If we aren't flushing all things, let us overcommit up to
4586 * 1/2th of the space. If we can flush, don't let us overcommit
4587 * too much, let it overcommit up to 1/8 of the space.
4589 if (flush == BTRFS_RESERVE_FLUSH_ALL)
4594 if (used + bytes < space_info->total_bytes + avail)
4599 static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
4600 unsigned long nr_pages, int nr_items)
4602 struct super_block *sb = fs_info->sb;
4604 if (down_read_trylock(&sb->s_umount)) {
4605 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4606 up_read(&sb->s_umount);
4609 * We needn't worry the filesystem going from r/w to r/o though
4610 * we don't acquire ->s_umount mutex, because the filesystem
4611 * should guarantee the delalloc inodes list be empty after
4612 * the filesystem is readonly(all dirty pages are written to
4615 btrfs_start_delalloc_roots(fs_info, nr_items);
4616 if (!current->journal_info)
4617 btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
4621 static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
4627 bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
4628 nr = div64_u64(to_reclaim, bytes);
4634 #define EXTENT_SIZE_PER_ITEM SZ_256K
4637 * shrink metadata reservation for delalloc
4639 static void shrink_delalloc(struct btrfs_fs_info *fs_info, u64 to_reclaim,
4640 u64 orig, bool wait_ordered)
4642 struct btrfs_space_info *space_info;
4643 struct btrfs_trans_handle *trans;
4649 unsigned long nr_pages;
4652 /* Calc the number of the pages we need flush for space reservation */
4653 items = calc_reclaim_items_nr(fs_info, to_reclaim);
4654 to_reclaim = items * EXTENT_SIZE_PER_ITEM;
4656 trans = (struct btrfs_trans_handle *)current->journal_info;
4657 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4659 delalloc_bytes = percpu_counter_sum_positive(
4660 &fs_info->delalloc_bytes);
4661 dio_bytes = percpu_counter_sum_positive(&fs_info->dio_bytes);
4662 if (delalloc_bytes == 0 && dio_bytes == 0) {
4666 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4671 * If we are doing more ordered than delalloc we need to just wait on
4672 * ordered extents, otherwise we'll waste time trying to flush delalloc
4673 * that likely won't give us the space back we need.
4675 if (dio_bytes > delalloc_bytes)
4676 wait_ordered = true;
4679 while ((delalloc_bytes || dio_bytes) && loops < 3) {
4680 nr_pages = min(delalloc_bytes, to_reclaim) >> PAGE_SHIFT;
4683 * Triggers inode writeback for up to nr_pages. This will invoke
4684 * ->writepages callback and trigger delalloc filling
4685 * (btrfs_run_delalloc_range()).
4687 btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
4690 * We need to wait for the compressed pages to start before
4693 async_pages = atomic_read(&fs_info->async_delalloc_pages);
4698 * Calculate how many compressed pages we want to be written
4699 * before we continue. I.e if there are more async pages than we
4700 * require wait_event will wait until nr_pages are written.
4702 if (async_pages <= nr_pages)
4705 async_pages -= nr_pages;
4707 wait_event(fs_info->async_submit_wait,
4708 atomic_read(&fs_info->async_delalloc_pages) <=
4711 spin_lock(&space_info->lock);
4712 if (list_empty(&space_info->tickets) &&
4713 list_empty(&space_info->priority_tickets)) {
4714 spin_unlock(&space_info->lock);
4717 spin_unlock(&space_info->lock);
4720 if (wait_ordered && !trans) {
4721 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4723 time_left = schedule_timeout_killable(1);
4727 delalloc_bytes = percpu_counter_sum_positive(
4728 &fs_info->delalloc_bytes);
4729 dio_bytes = percpu_counter_sum_positive(&fs_info->dio_bytes);
4733 struct reserve_ticket {
4737 struct list_head list;
4738 wait_queue_head_t wait;
4742 * maybe_commit_transaction - possibly commit the transaction if its ok to
4743 * @root - the root we're allocating for
4744 * @bytes - the number of bytes we want to reserve
4745 * @force - force the commit
4747 * This will check to make sure that committing the transaction will actually
4748 * get us somewhere and then commit the transaction if it does. Otherwise it
4749 * will return -ENOSPC.
4751 static int may_commit_transaction(struct btrfs_fs_info *fs_info,
4752 struct btrfs_space_info *space_info)
4754 struct reserve_ticket *ticket = NULL;
4755 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
4756 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
4757 struct btrfs_trans_handle *trans;
4759 u64 reclaim_bytes = 0;
4761 trans = (struct btrfs_trans_handle *)current->journal_info;
4765 spin_lock(&space_info->lock);
4766 if (!list_empty(&space_info->priority_tickets))
4767 ticket = list_first_entry(&space_info->priority_tickets,
4768 struct reserve_ticket, list);
4769 else if (!list_empty(&space_info->tickets))
4770 ticket = list_first_entry(&space_info->tickets,
4771 struct reserve_ticket, list);
4772 bytes_needed = (ticket) ? ticket->bytes : 0;
4773 spin_unlock(&space_info->lock);
4778 trans = btrfs_join_transaction(fs_info->extent_root);
4780 return PTR_ERR(trans);
4783 * See if there is enough pinned space to make this reservation, or if
4784 * we have block groups that are going to be freed, allowing us to
4785 * possibly do a chunk allocation the next loop through.
4787 if (test_bit(BTRFS_TRANS_HAVE_FREE_BGS, &trans->transaction->flags) ||
4788 __percpu_counter_compare(&space_info->total_bytes_pinned,
4790 BTRFS_TOTAL_BYTES_PINNED_BATCH) >= 0)
4794 * See if there is some space in the delayed insertion reservation for
4797 if (space_info != delayed_rsv->space_info)
4800 spin_lock(&delayed_rsv->lock);
4801 reclaim_bytes += delayed_rsv->reserved;
4802 spin_unlock(&delayed_rsv->lock);
4804 spin_lock(&delayed_refs_rsv->lock);
4805 reclaim_bytes += delayed_refs_rsv->reserved;
4806 spin_unlock(&delayed_refs_rsv->lock);
4807 if (reclaim_bytes >= bytes_needed)
4809 bytes_needed -= reclaim_bytes;
4811 if (__percpu_counter_compare(&space_info->total_bytes_pinned,
4813 BTRFS_TOTAL_BYTES_PINNED_BATCH) < 0)
4817 return btrfs_commit_transaction(trans);
4819 btrfs_end_transaction(trans);
4824 * Try to flush some data based on policy set by @state. This is only advisory
4825 * and may fail for various reasons. The caller is supposed to examine the
4826 * state of @space_info to detect the outcome.
4828 static void flush_space(struct btrfs_fs_info *fs_info,
4829 struct btrfs_space_info *space_info, u64 num_bytes,
4832 struct btrfs_root *root = fs_info->extent_root;
4833 struct btrfs_trans_handle *trans;
4838 case FLUSH_DELAYED_ITEMS_NR:
4839 case FLUSH_DELAYED_ITEMS:
4840 if (state == FLUSH_DELAYED_ITEMS_NR)
4841 nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
4845 trans = btrfs_join_transaction(root);
4846 if (IS_ERR(trans)) {
4847 ret = PTR_ERR(trans);
4850 ret = btrfs_run_delayed_items_nr(trans, nr);
4851 btrfs_end_transaction(trans);
4853 case FLUSH_DELALLOC:
4854 case FLUSH_DELALLOC_WAIT:
4855 shrink_delalloc(fs_info, num_bytes * 2, num_bytes,
4856 state == FLUSH_DELALLOC_WAIT);
4858 case FLUSH_DELAYED_REFS_NR:
4859 case FLUSH_DELAYED_REFS:
4860 trans = btrfs_join_transaction(root);
4861 if (IS_ERR(trans)) {
4862 ret = PTR_ERR(trans);
4865 if (state == FLUSH_DELAYED_REFS_NR)
4866 nr = calc_reclaim_items_nr(fs_info, num_bytes);
4869 btrfs_run_delayed_refs(trans, nr);
4870 btrfs_end_transaction(trans);
4873 case ALLOC_CHUNK_FORCE:
4874 trans = btrfs_join_transaction(root);
4875 if (IS_ERR(trans)) {
4876 ret = PTR_ERR(trans);
4879 ret = do_chunk_alloc(trans,
4880 btrfs_metadata_alloc_profile(fs_info),
4881 (state == ALLOC_CHUNK) ?
4882 CHUNK_ALLOC_NO_FORCE : CHUNK_ALLOC_FORCE);
4883 btrfs_end_transaction(trans);
4884 if (ret > 0 || ret == -ENOSPC)
4889 * If we have pending delayed iputs then we could free up a
4890 * bunch of pinned space, so make sure we run the iputs before
4891 * we do our pinned bytes check below.
4893 btrfs_run_delayed_iputs(fs_info);
4894 btrfs_wait_on_delayed_iputs(fs_info);
4896 ret = may_commit_transaction(fs_info, space_info);
4903 trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
4909 btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
4910 struct btrfs_space_info *space_info,
4913 struct reserve_ticket *ticket;
4918 list_for_each_entry(ticket, &space_info->tickets, list)
4919 to_reclaim += ticket->bytes;
4920 list_for_each_entry(ticket, &space_info->priority_tickets, list)
4921 to_reclaim += ticket->bytes;
4925 to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
4926 if (can_overcommit(fs_info, space_info, to_reclaim,
4927 BTRFS_RESERVE_FLUSH_ALL, system_chunk))
4930 used = btrfs_space_info_used(space_info, true);
4932 if (can_overcommit(fs_info, space_info, SZ_1M,
4933 BTRFS_RESERVE_FLUSH_ALL, system_chunk))
4934 expected = div_factor_fine(space_info->total_bytes, 95);
4936 expected = div_factor_fine(space_info->total_bytes, 90);
4938 if (used > expected)
4939 to_reclaim = used - expected;
4942 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4943 space_info->bytes_reserved);
4947 static inline int need_do_async_reclaim(struct btrfs_fs_info *fs_info,
4948 struct btrfs_space_info *space_info,
4949 u64 used, bool system_chunk)
4951 u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4953 /* If we're just plain full then async reclaim just slows us down. */
4954 if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
4957 if (!btrfs_calc_reclaim_metadata_size(fs_info, space_info,
4961 return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4962 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4965 static bool wake_all_tickets(struct list_head *head)
4967 struct reserve_ticket *ticket;
4969 while (!list_empty(head)) {
4970 ticket = list_first_entry(head, struct reserve_ticket, list);
4971 list_del_init(&ticket->list);
4972 ticket->error = -ENOSPC;
4973 wake_up(&ticket->wait);
4974 if (ticket->bytes != ticket->orig_bytes)
4981 * This is for normal flushers, we can wait all goddamned day if we want to. We
4982 * will loop and continuously try to flush as long as we are making progress.
4983 * We count progress as clearing off tickets each time we have to loop.
4985 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4987 struct btrfs_fs_info *fs_info;
4988 struct btrfs_space_info *space_info;
4991 int commit_cycles = 0;
4992 u64 last_tickets_id;
4994 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4995 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4997 spin_lock(&space_info->lock);
4998 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
5001 space_info->flush = 0;
5002 spin_unlock(&space_info->lock);
5005 last_tickets_id = space_info->tickets_id;
5006 spin_unlock(&space_info->lock);
5008 flush_state = FLUSH_DELAYED_ITEMS_NR;
5010 flush_space(fs_info, space_info, to_reclaim, flush_state);
5011 spin_lock(&space_info->lock);
5012 if (list_empty(&space_info->tickets)) {
5013 space_info->flush = 0;
5014 spin_unlock(&space_info->lock);
5017 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
5020 if (last_tickets_id == space_info->tickets_id) {
5023 last_tickets_id = space_info->tickets_id;
5024 flush_state = FLUSH_DELAYED_ITEMS_NR;
5030 * We don't want to force a chunk allocation until we've tried
5031 * pretty hard to reclaim space. Think of the case where we
5032 * freed up a bunch of space and so have a lot of pinned space
5033 * to reclaim. We would rather use that than possibly create a
5034 * underutilized metadata chunk. So if this is our first run
5035 * through the flushing state machine skip ALLOC_CHUNK_FORCE and
5036 * commit the transaction. If nothing has changed the next go
5037 * around then we can force a chunk allocation.
5039 if (flush_state == ALLOC_CHUNK_FORCE && !commit_cycles)
5042 if (flush_state > COMMIT_TRANS) {
5044 if (commit_cycles > 2) {
5045 if (wake_all_tickets(&space_info->tickets)) {
5046 flush_state = FLUSH_DELAYED_ITEMS_NR;
5049 space_info->flush = 0;
5052 flush_state = FLUSH_DELAYED_ITEMS_NR;
5055 spin_unlock(&space_info->lock);
5056 } while (flush_state <= COMMIT_TRANS);
5059 void btrfs_init_async_reclaim_work(struct work_struct *work)
5061 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5064 static const enum btrfs_flush_state priority_flush_states[] = {
5065 FLUSH_DELAYED_ITEMS_NR,
5066 FLUSH_DELAYED_ITEMS,
5070 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5071 struct btrfs_space_info *space_info,
5072 struct reserve_ticket *ticket)
5077 spin_lock(&space_info->lock);
5078 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
5081 spin_unlock(&space_info->lock);
5084 spin_unlock(&space_info->lock);
5088 flush_space(fs_info, space_info, to_reclaim,
5089 priority_flush_states[flush_state]);
5091 spin_lock(&space_info->lock);
5092 if (ticket->bytes == 0) {
5093 spin_unlock(&space_info->lock);
5096 spin_unlock(&space_info->lock);
5097 } while (flush_state < ARRAY_SIZE(priority_flush_states));
5100 static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5101 struct btrfs_space_info *space_info,
5102 struct reserve_ticket *ticket)
5106 u64 reclaim_bytes = 0;
5109 spin_lock(&space_info->lock);
5110 while (ticket->bytes > 0 && ticket->error == 0) {
5111 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5116 spin_unlock(&space_info->lock);
5120 finish_wait(&ticket->wait, &wait);
5121 spin_lock(&space_info->lock);
5124 ret = ticket->error;
5125 if (!list_empty(&ticket->list))
5126 list_del_init(&ticket->list);
5127 if (ticket->bytes && ticket->bytes < ticket->orig_bytes)
5128 reclaim_bytes = ticket->orig_bytes - ticket->bytes;
5129 spin_unlock(&space_info->lock);
5132 space_info_add_old_bytes(fs_info, space_info, reclaim_bytes);
5137 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5138 * @root - the root we're allocating for
5139 * @space_info - the space info we want to allocate from
5140 * @orig_bytes - the number of bytes we want
5141 * @flush - whether or not we can flush to make our reservation
5143 * This will reserve orig_bytes number of bytes from the space info associated
5144 * with the block_rsv. If there is not enough space it will make an attempt to
5145 * flush out space to make room. It will do this by flushing delalloc if
5146 * possible or committing the transaction. If flush is 0 then no attempts to
5147 * regain reservations will be made and this will fail if there is not enough
5150 static int __reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
5151 struct btrfs_space_info *space_info,
5153 enum btrfs_reserve_flush_enum flush,
5156 struct reserve_ticket ticket;
5158 u64 reclaim_bytes = 0;
5162 ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
5164 spin_lock(&space_info->lock);
5166 used = btrfs_space_info_used(space_info, true);
5169 * If we have enough space then hooray, make our reservation and carry
5170 * on. If not see if we can overcommit, and if we can, hooray carry on.
5171 * If not things get more complicated.
5173 if (used + orig_bytes <= space_info->total_bytes) {
5174 update_bytes_may_use(fs_info, space_info, orig_bytes);
5175 trace_btrfs_space_reservation(fs_info, "space_info",
5176 space_info->flags, orig_bytes, 1);
5178 } else if (can_overcommit(fs_info, space_info, orig_bytes, flush,
5180 update_bytes_may_use(fs_info, space_info, orig_bytes);
5181 trace_btrfs_space_reservation(fs_info, "space_info",
5182 space_info->flags, orig_bytes, 1);
5187 * If we couldn't make a reservation then setup our reservation ticket
5188 * and kick the async worker if it's not already running.
5190 * If we are a priority flusher then we just need to add our ticket to
5191 * the list and we will do our own flushing further down.
5193 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
5194 ticket.orig_bytes = orig_bytes;
5195 ticket.bytes = orig_bytes;
5197 init_waitqueue_head(&ticket.wait);
5198 if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5199 list_add_tail(&ticket.list, &space_info->tickets);
5200 if (!space_info->flush) {
5201 space_info->flush = 1;
5202 trace_btrfs_trigger_flush(fs_info,
5206 queue_work(system_unbound_wq,
5207 &fs_info->async_reclaim_work);
5210 list_add_tail(&ticket.list,
5211 &space_info->priority_tickets);
5213 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5216 * We will do the space reservation dance during log replay,
5217 * which means we won't have fs_info->fs_root set, so don't do
5218 * the async reclaim as we will panic.
5220 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
5221 need_do_async_reclaim(fs_info, space_info,
5222 used, system_chunk) &&
5223 !work_busy(&fs_info->async_reclaim_work)) {
5224 trace_btrfs_trigger_flush(fs_info, space_info->flags,
5225 orig_bytes, flush, "preempt");
5226 queue_work(system_unbound_wq,
5227 &fs_info->async_reclaim_work);
5230 spin_unlock(&space_info->lock);
5231 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
5234 if (flush == BTRFS_RESERVE_FLUSH_ALL)
5235 return wait_reserve_ticket(fs_info, space_info, &ticket);
5238 priority_reclaim_metadata_space(fs_info, space_info, &ticket);
5239 spin_lock(&space_info->lock);
5241 if (ticket.bytes < orig_bytes)
5242 reclaim_bytes = orig_bytes - ticket.bytes;
5243 list_del_init(&ticket.list);
5246 spin_unlock(&space_info->lock);
5249 space_info_add_old_bytes(fs_info, space_info, reclaim_bytes);
5250 ASSERT(list_empty(&ticket.list));
5255 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5256 * @root - the root we're allocating for
5257 * @block_rsv - the block_rsv we're allocating for
5258 * @orig_bytes - the number of bytes we want
5259 * @flush - whether or not we can flush to make our reservation
5261 * This will reserve orig_bytes number of bytes from the space info associated
5262 * with the block_rsv. If there is not enough space it will make an attempt to
5263 * flush out space to make room. It will do this by flushing delalloc if
5264 * possible or committing the transaction. If flush is 0 then no attempts to
5265 * regain reservations will be made and this will fail if there is not enough
5268 static int reserve_metadata_bytes(struct btrfs_root *root,
5269 struct btrfs_block_rsv *block_rsv,
5271 enum btrfs_reserve_flush_enum flush)
5273 struct btrfs_fs_info *fs_info = root->fs_info;
5274 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5276 bool system_chunk = (root == fs_info->chunk_root);
5278 ret = __reserve_metadata_bytes(fs_info, block_rsv->space_info,
5279 orig_bytes, flush, system_chunk);
5280 if (ret == -ENOSPC &&
5281 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5282 if (block_rsv != global_rsv &&
5283 !block_rsv_use_bytes(global_rsv, orig_bytes))
5286 if (ret == -ENOSPC) {
5287 trace_btrfs_space_reservation(fs_info, "space_info:enospc",
5288 block_rsv->space_info->flags,
5291 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG))
5292 dump_space_info(fs_info, block_rsv->space_info,
5298 static struct btrfs_block_rsv *get_block_rsv(
5299 const struct btrfs_trans_handle *trans,
5300 const struct btrfs_root *root)
5302 struct btrfs_fs_info *fs_info = root->fs_info;
5303 struct btrfs_block_rsv *block_rsv = NULL;
5305 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5306 (root == fs_info->csum_root && trans->adding_csums) ||
5307 (root == fs_info->uuid_root))
5308 block_rsv = trans->block_rsv;
5311 block_rsv = root->block_rsv;
5314 block_rsv = &fs_info->empty_block_rsv;
5319 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5323 spin_lock(&block_rsv->lock);
5324 if (block_rsv->reserved >= num_bytes) {
5325 block_rsv->reserved -= num_bytes;
5326 if (block_rsv->reserved < block_rsv->size)
5327 block_rsv->full = 0;
5330 spin_unlock(&block_rsv->lock);
5334 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5335 u64 num_bytes, bool update_size)
5337 spin_lock(&block_rsv->lock);
5338 block_rsv->reserved += num_bytes;
5340 block_rsv->size += num_bytes;
5341 else if (block_rsv->reserved >= block_rsv->size)
5342 block_rsv->full = 1;
5343 spin_unlock(&block_rsv->lock);
5346 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5347 struct btrfs_block_rsv *dest, u64 num_bytes,
5350 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5353 if (global_rsv->space_info != dest->space_info)
5356 spin_lock(&global_rsv->lock);
5357 min_bytes = div_factor(global_rsv->size, min_factor);
5358 if (global_rsv->reserved < min_bytes + num_bytes) {
5359 spin_unlock(&global_rsv->lock);
5362 global_rsv->reserved -= num_bytes;
5363 if (global_rsv->reserved < global_rsv->size)
5364 global_rsv->full = 0;
5365 spin_unlock(&global_rsv->lock);
5367 block_rsv_add_bytes(dest, num_bytes, true);
5372 * btrfs_migrate_to_delayed_refs_rsv - transfer bytes to our delayed refs rsv.
5373 * @fs_info - the fs info for our fs.
5374 * @src - the source block rsv to transfer from.
5375 * @num_bytes - the number of bytes to transfer.
5377 * This transfers up to the num_bytes amount from the src rsv to the
5378 * delayed_refs_rsv. Any extra bytes are returned to the space info.
5380 void btrfs_migrate_to_delayed_refs_rsv(struct btrfs_fs_info *fs_info,
5381 struct btrfs_block_rsv *src,
5384 struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
5387 spin_lock(&src->lock);
5388 src->reserved -= num_bytes;
5389 src->size -= num_bytes;
5390 spin_unlock(&src->lock);
5392 spin_lock(&delayed_refs_rsv->lock);
5393 if (delayed_refs_rsv->size > delayed_refs_rsv->reserved) {
5394 u64 delta = delayed_refs_rsv->size -
5395 delayed_refs_rsv->reserved;
5396 if (num_bytes > delta) {
5397 to_free = num_bytes - delta;
5401 to_free = num_bytes;
5406 delayed_refs_rsv->reserved += num_bytes;
5407 if (delayed_refs_rsv->reserved >= delayed_refs_rsv->size)
5408 delayed_refs_rsv->full = 1;
5409 spin_unlock(&delayed_refs_rsv->lock);
5412 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5415 space_info_add_old_bytes(fs_info, delayed_refs_rsv->space_info,
5420 * btrfs_delayed_refs_rsv_refill - refill based on our delayed refs usage.
5421 * @fs_info - the fs_info for our fs.
5422 * @flush - control how we can flush for this reservation.
5424 * This will refill the delayed block_rsv up to 1 items size worth of space and
5425 * will return -ENOSPC if we can't make the reservation.
5427 int btrfs_delayed_refs_rsv_refill(struct btrfs_fs_info *fs_info,
5428 enum btrfs_reserve_flush_enum flush)
5430 struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
5431 u64 limit = btrfs_calc_trans_metadata_size(fs_info, 1);
5435 spin_lock(&block_rsv->lock);
5436 if (block_rsv->reserved < block_rsv->size) {
5437 num_bytes = block_rsv->size - block_rsv->reserved;
5438 num_bytes = min(num_bytes, limit);
5440 spin_unlock(&block_rsv->lock);
5445 ret = reserve_metadata_bytes(fs_info->extent_root, block_rsv,
5449 block_rsv_add_bytes(block_rsv, num_bytes, 0);
5450 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5456 * This is for space we already have accounted in space_info->bytes_may_use, so
5457 * basically when we're returning space from block_rsv's.
5459 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5460 struct btrfs_space_info *space_info,
5463 struct reserve_ticket *ticket;
5464 struct list_head *head;
5466 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5467 bool check_overcommit = false;
5469 spin_lock(&space_info->lock);
5470 head = &space_info->priority_tickets;
5473 * If we are over our limit then we need to check and see if we can
5474 * overcommit, and if we can't then we just need to free up our space
5475 * and not satisfy any requests.
5477 used = btrfs_space_info_used(space_info, true);
5478 if (used - num_bytes >= space_info->total_bytes)
5479 check_overcommit = true;
5481 while (!list_empty(head) && num_bytes) {
5482 ticket = list_first_entry(head, struct reserve_ticket,
5485 * We use 0 bytes because this space is already reserved, so
5486 * adding the ticket space would be a double count.
5488 if (check_overcommit &&
5489 !can_overcommit(fs_info, space_info, 0, flush, false))
5491 if (num_bytes >= ticket->bytes) {
5492 list_del_init(&ticket->list);
5493 num_bytes -= ticket->bytes;
5495 space_info->tickets_id++;
5496 wake_up(&ticket->wait);
5498 ticket->bytes -= num_bytes;
5503 if (num_bytes && head == &space_info->priority_tickets) {
5504 head = &space_info->tickets;
5505 flush = BTRFS_RESERVE_FLUSH_ALL;
5508 update_bytes_may_use(fs_info, space_info, -num_bytes);
5509 trace_btrfs_space_reservation(fs_info, "space_info",
5510 space_info->flags, num_bytes, 0);
5511 spin_unlock(&space_info->lock);
5515 * This is for newly allocated space that isn't accounted in
5516 * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
5517 * we use this helper.
5519 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5520 struct btrfs_space_info *space_info,
5523 struct reserve_ticket *ticket;
5524 struct list_head *head = &space_info->priority_tickets;
5527 while (!list_empty(head) && num_bytes) {
5528 ticket = list_first_entry(head, struct reserve_ticket,
5530 if (num_bytes >= ticket->bytes) {
5531 trace_btrfs_space_reservation(fs_info, "space_info",
5534 list_del_init(&ticket->list);
5535 num_bytes -= ticket->bytes;
5536 update_bytes_may_use(fs_info, space_info,
5539 space_info->tickets_id++;
5540 wake_up(&ticket->wait);
5542 trace_btrfs_space_reservation(fs_info, "space_info",
5545 update_bytes_may_use(fs_info, space_info, num_bytes);
5546 ticket->bytes -= num_bytes;
5551 if (num_bytes && head == &space_info->priority_tickets) {
5552 head = &space_info->tickets;
5557 static u64 block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5558 struct btrfs_block_rsv *block_rsv,
5559 struct btrfs_block_rsv *dest, u64 num_bytes,
5560 u64 *qgroup_to_release_ret)
5562 struct btrfs_space_info *space_info = block_rsv->space_info;
5563 u64 qgroup_to_release = 0;
5566 spin_lock(&block_rsv->lock);
5567 if (num_bytes == (u64)-1) {
5568 num_bytes = block_rsv->size;
5569 qgroup_to_release = block_rsv->qgroup_rsv_size;
5571 block_rsv->size -= num_bytes;
5572 if (block_rsv->reserved >= block_rsv->size) {
5573 num_bytes = block_rsv->reserved - block_rsv->size;
5574 block_rsv->reserved = block_rsv->size;
5575 block_rsv->full = 1;
5579 if (block_rsv->qgroup_rsv_reserved >= block_rsv->qgroup_rsv_size) {
5580 qgroup_to_release = block_rsv->qgroup_rsv_reserved -
5581 block_rsv->qgroup_rsv_size;
5582 block_rsv->qgroup_rsv_reserved = block_rsv->qgroup_rsv_size;
5584 qgroup_to_release = 0;
5586 spin_unlock(&block_rsv->lock);
5589 if (num_bytes > 0) {
5591 spin_lock(&dest->lock);
5595 bytes_to_add = dest->size - dest->reserved;
5596 bytes_to_add = min(num_bytes, bytes_to_add);
5597 dest->reserved += bytes_to_add;
5598 if (dest->reserved >= dest->size)
5600 num_bytes -= bytes_to_add;
5602 spin_unlock(&dest->lock);
5605 space_info_add_old_bytes(fs_info, space_info,
5608 if (qgroup_to_release_ret)
5609 *qgroup_to_release_ret = qgroup_to_release;
5613 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5614 struct btrfs_block_rsv *dst, u64 num_bytes,
5619 ret = block_rsv_use_bytes(src, num_bytes);
5623 block_rsv_add_bytes(dst, num_bytes, update_size);
5627 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5629 memset(rsv, 0, sizeof(*rsv));
5630 spin_lock_init(&rsv->lock);
5634 void btrfs_init_metadata_block_rsv(struct btrfs_fs_info *fs_info,
5635 struct btrfs_block_rsv *rsv,
5636 unsigned short type)
5638 btrfs_init_block_rsv(rsv, type);
5639 rsv->space_info = __find_space_info(fs_info,
5640 BTRFS_BLOCK_GROUP_METADATA);
5643 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
5644 unsigned short type)
5646 struct btrfs_block_rsv *block_rsv;
5648 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5652 btrfs_init_metadata_block_rsv(fs_info, block_rsv, type);
5656 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
5657 struct btrfs_block_rsv *rsv)
5661 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5665 int btrfs_block_rsv_add(struct btrfs_root *root,
5666 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5667 enum btrfs_reserve_flush_enum flush)
5674 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5676 block_rsv_add_bytes(block_rsv, num_bytes, true);
5681 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
5689 spin_lock(&block_rsv->lock);
5690 num_bytes = div_factor(block_rsv->size, min_factor);
5691 if (block_rsv->reserved >= num_bytes)
5693 spin_unlock(&block_rsv->lock);
5698 int btrfs_block_rsv_refill(struct btrfs_root *root,
5699 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5700 enum btrfs_reserve_flush_enum flush)
5708 spin_lock(&block_rsv->lock);
5709 num_bytes = min_reserved;
5710 if (block_rsv->reserved >= num_bytes)
5713 num_bytes -= block_rsv->reserved;
5714 spin_unlock(&block_rsv->lock);
5719 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5721 block_rsv_add_bytes(block_rsv, num_bytes, false);
5728 static u64 __btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5729 struct btrfs_block_rsv *block_rsv,
5730 u64 num_bytes, u64 *qgroup_to_release)
5732 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5733 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
5734 struct btrfs_block_rsv *target = delayed_rsv;
5736 if (target->full || target == block_rsv)
5737 target = global_rsv;
5739 if (block_rsv->space_info != target->space_info)
5742 return block_rsv_release_bytes(fs_info, block_rsv, target, num_bytes,
5746 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5747 struct btrfs_block_rsv *block_rsv,
5750 __btrfs_block_rsv_release(fs_info, block_rsv, num_bytes, NULL);
5754 * btrfs_inode_rsv_release - release any excessive reservation.
5755 * @inode - the inode we need to release from.
5756 * @qgroup_free - free or convert qgroup meta.
5757 * Unlike normal operation, qgroup meta reservation needs to know if we are
5758 * freeing qgroup reservation or just converting it into per-trans. Normally
5759 * @qgroup_free is true for error handling, and false for normal release.
5761 * This is the same as btrfs_block_rsv_release, except that it handles the
5762 * tracepoint for the reservation.
5764 static void btrfs_inode_rsv_release(struct btrfs_inode *inode, bool qgroup_free)
5766 struct btrfs_fs_info *fs_info = inode->root->fs_info;
5767 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
5769 u64 qgroup_to_release = 0;
5772 * Since we statically set the block_rsv->size we just want to say we
5773 * are releasing 0 bytes, and then we'll just get the reservation over
5776 released = __btrfs_block_rsv_release(fs_info, block_rsv, 0,
5777 &qgroup_to_release);
5779 trace_btrfs_space_reservation(fs_info, "delalloc",
5780 btrfs_ino(inode), released, 0);
5782 btrfs_qgroup_free_meta_prealloc(inode->root, qgroup_to_release);
5784 btrfs_qgroup_convert_reserved_meta(inode->root,
5789 * btrfs_delayed_refs_rsv_release - release a ref head's reservation.
5790 * @fs_info - the fs_info for our fs.
5791 * @nr - the number of items to drop.
5793 * This drops the delayed ref head's count from the delayed refs rsv and frees
5794 * any excess reservation we had.
5796 void btrfs_delayed_refs_rsv_release(struct btrfs_fs_info *fs_info, int nr)
5798 struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
5799 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5800 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, nr);
5803 released = block_rsv_release_bytes(fs_info, block_rsv, global_rsv,
5806 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
5810 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5812 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5813 struct btrfs_space_info *sinfo = block_rsv->space_info;
5817 * The global block rsv is based on the size of the extent tree, the
5818 * checksum tree and the root tree. If the fs is empty we want to set
5819 * it to a minimal amount for safety.
5821 num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5822 btrfs_root_used(&fs_info->csum_root->root_item) +
5823 btrfs_root_used(&fs_info->tree_root->root_item);
5824 num_bytes = max_t(u64, num_bytes, SZ_16M);
5826 spin_lock(&sinfo->lock);
5827 spin_lock(&block_rsv->lock);
5829 block_rsv->size = min_t(u64, num_bytes, SZ_512M);
5831 if (block_rsv->reserved < block_rsv->size) {
5832 num_bytes = btrfs_space_info_used(sinfo, true);
5833 if (sinfo->total_bytes > num_bytes) {
5834 num_bytes = sinfo->total_bytes - num_bytes;
5835 num_bytes = min(num_bytes,
5836 block_rsv->size - block_rsv->reserved);
5837 block_rsv->reserved += num_bytes;
5838 update_bytes_may_use(fs_info, sinfo, num_bytes);
5839 trace_btrfs_space_reservation(fs_info, "space_info",
5840 sinfo->flags, num_bytes,
5843 } else if (block_rsv->reserved > block_rsv->size) {
5844 num_bytes = block_rsv->reserved - block_rsv->size;
5845 update_bytes_may_use(fs_info, sinfo, -num_bytes);
5846 trace_btrfs_space_reservation(fs_info, "space_info",
5847 sinfo->flags, num_bytes, 0);
5848 block_rsv->reserved = block_rsv->size;
5851 if (block_rsv->reserved == block_rsv->size)
5852 block_rsv->full = 1;
5854 block_rsv->full = 0;
5856 spin_unlock(&block_rsv->lock);
5857 spin_unlock(&sinfo->lock);
5860 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5862 struct btrfs_space_info *space_info;
5864 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5865 fs_info->chunk_block_rsv.space_info = space_info;
5867 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5868 fs_info->global_block_rsv.space_info = space_info;
5869 fs_info->trans_block_rsv.space_info = space_info;
5870 fs_info->empty_block_rsv.space_info = space_info;
5871 fs_info->delayed_block_rsv.space_info = space_info;
5872 fs_info->delayed_refs_rsv.space_info = space_info;
5874 fs_info->extent_root->block_rsv = &fs_info->delayed_refs_rsv;
5875 fs_info->csum_root->block_rsv = &fs_info->delayed_refs_rsv;
5876 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5877 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5878 if (fs_info->quota_root)
5879 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5880 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5882 update_global_block_rsv(fs_info);
5885 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5887 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5889 WARN_ON(fs_info->trans_block_rsv.size > 0);
5890 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5891 WARN_ON(fs_info->chunk_block_rsv.size > 0);
5892 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5893 WARN_ON(fs_info->delayed_block_rsv.size > 0);
5894 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5895 WARN_ON(fs_info->delayed_refs_rsv.reserved > 0);
5896 WARN_ON(fs_info->delayed_refs_rsv.size > 0);
5900 * btrfs_update_delayed_refs_rsv - adjust the size of the delayed refs rsv
5901 * @trans - the trans that may have generated delayed refs
5903 * This is to be called anytime we may have adjusted trans->delayed_ref_updates,
5904 * it'll calculate the additional size and add it to the delayed_refs_rsv.
5906 void btrfs_update_delayed_refs_rsv(struct btrfs_trans_handle *trans)
5908 struct btrfs_fs_info *fs_info = trans->fs_info;
5909 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
5912 if (!trans->delayed_ref_updates)
5915 num_bytes = btrfs_calc_trans_metadata_size(fs_info,
5916 trans->delayed_ref_updates);
5917 spin_lock(&delayed_rsv->lock);
5918 delayed_rsv->size += num_bytes;
5919 delayed_rsv->full = 0;
5920 spin_unlock(&delayed_rsv->lock);
5921 trans->delayed_ref_updates = 0;
5925 * To be called after all the new block groups attached to the transaction
5926 * handle have been created (btrfs_create_pending_block_groups()).
5928 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5930 struct btrfs_fs_info *fs_info = trans->fs_info;
5932 if (!trans->chunk_bytes_reserved)
5935 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5937 block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5938 trans->chunk_bytes_reserved, NULL);
5939 trans->chunk_bytes_reserved = 0;
5943 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5944 * root: the root of the parent directory
5945 * rsv: block reservation
5946 * items: the number of items that we need do reservation
5947 * use_global_rsv: allow fallback to the global block reservation
5949 * This function is used to reserve the space for snapshot/subvolume
5950 * creation and deletion. Those operations are different with the
5951 * common file/directory operations, they change two fs/file trees
5952 * and root tree, the number of items that the qgroup reserves is
5953 * different with the free space reservation. So we can not use
5954 * the space reservation mechanism in start_transaction().
5956 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5957 struct btrfs_block_rsv *rsv, int items,
5958 bool use_global_rsv)
5960 u64 qgroup_num_bytes = 0;
5963 struct btrfs_fs_info *fs_info = root->fs_info;
5964 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5966 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5967 /* One for parent inode, two for dir entries */
5968 qgroup_num_bytes = 3 * fs_info->nodesize;
5969 ret = btrfs_qgroup_reserve_meta_prealloc(root,
5970 qgroup_num_bytes, true);
5975 num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
5976 rsv->space_info = __find_space_info(fs_info,
5977 BTRFS_BLOCK_GROUP_METADATA);
5978 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5979 BTRFS_RESERVE_FLUSH_ALL);
5981 if (ret == -ENOSPC && use_global_rsv)
5982 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, true);
5984 if (ret && qgroup_num_bytes)
5985 btrfs_qgroup_free_meta_prealloc(root, qgroup_num_bytes);
5990 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
5991 struct btrfs_block_rsv *rsv)
5993 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5996 static void btrfs_calculate_inode_block_rsv_size(struct btrfs_fs_info *fs_info,
5997 struct btrfs_inode *inode)
5999 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
6000 u64 reserve_size = 0;
6001 u64 qgroup_rsv_size = 0;
6003 unsigned outstanding_extents;
6005 lockdep_assert_held(&inode->lock);
6006 outstanding_extents = inode->outstanding_extents;
6007 if (outstanding_extents)
6008 reserve_size = btrfs_calc_trans_metadata_size(fs_info,
6009 outstanding_extents + 1);
6010 csum_leaves = btrfs_csum_bytes_to_leaves(fs_info,
6012 reserve_size += btrfs_calc_trans_metadata_size(fs_info,
6015 * For qgroup rsv, the calculation is very simple:
6016 * account one nodesize for each outstanding extent
6018 * This is overestimating in most cases.
6020 qgroup_rsv_size = (u64)outstanding_extents * fs_info->nodesize;
6022 spin_lock(&block_rsv->lock);
6023 block_rsv->size = reserve_size;
6024 block_rsv->qgroup_rsv_size = qgroup_rsv_size;
6025 spin_unlock(&block_rsv->lock);
6028 static void calc_inode_reservations(struct btrfs_fs_info *fs_info,
6029 u64 num_bytes, u64 *meta_reserve,
6030 u64 *qgroup_reserve)
6032 u64 nr_extents = count_max_extents(num_bytes);
6033 u64 csum_leaves = btrfs_csum_bytes_to_leaves(fs_info, num_bytes);
6035 /* We add one for the inode update at finish ordered time */
6036 *meta_reserve = btrfs_calc_trans_metadata_size(fs_info,
6037 nr_extents + csum_leaves + 1);
6038 *qgroup_reserve = nr_extents * fs_info->nodesize;
6041 int btrfs_delalloc_reserve_metadata(struct btrfs_inode *inode, u64 num_bytes)
6043 struct btrfs_root *root = inode->root;
6044 struct btrfs_fs_info *fs_info = root->fs_info;
6045 struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
6046 u64 meta_reserve, qgroup_reserve;
6047 unsigned nr_extents;
6048 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
6050 bool delalloc_lock = true;
6052 /* If we are a free space inode we need to not flush since we will be in
6053 * the middle of a transaction commit. We also don't need the delalloc
6054 * mutex since we won't race with anybody. We need this mostly to make
6055 * lockdep shut its filthy mouth.
6057 * If we have a transaction open (can happen if we call truncate_block
6058 * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
6060 if (btrfs_is_free_space_inode(inode)) {
6061 flush = BTRFS_RESERVE_NO_FLUSH;
6062 delalloc_lock = false;
6064 if (current->journal_info)
6065 flush = BTRFS_RESERVE_FLUSH_LIMIT;
6067 if (btrfs_transaction_in_commit(fs_info))
6068 schedule_timeout(1);
6072 mutex_lock(&inode->delalloc_mutex);
6074 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6077 * We always want to do it this way, every other way is wrong and ends
6078 * in tears. Pre-reserving the amount we are going to add will always
6079 * be the right way, because otherwise if we have enough parallelism we
6080 * could end up with thousands of inodes all holding little bits of
6081 * reservations they were able to make previously and the only way to
6082 * reclaim that space is to ENOSPC out the operations and clear
6083 * everything out and try again, which is bad. This way we just
6084 * over-reserve slightly, and clean up the mess when we are done.
6086 calc_inode_reservations(fs_info, num_bytes, &meta_reserve,
6088 ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserve, true);
6091 ret = reserve_metadata_bytes(root, block_rsv, meta_reserve, flush);
6096 * Now we need to update our outstanding extents and csum bytes _first_
6097 * and then add the reservation to the block_rsv. This keeps us from
6098 * racing with an ordered completion or some such that would think it
6099 * needs to free the reservation we just made.
6101 spin_lock(&inode->lock);
6102 nr_extents = count_max_extents(num_bytes);
6103 btrfs_mod_outstanding_extents(inode, nr_extents);
6104 inode->csum_bytes += num_bytes;
6105 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6106 spin_unlock(&inode->lock);
6108 /* Now we can safely add our space to our block rsv */
6109 block_rsv_add_bytes(block_rsv, meta_reserve, false);
6110 trace_btrfs_space_reservation(root->fs_info, "delalloc",
6111 btrfs_ino(inode), meta_reserve, 1);
6113 spin_lock(&block_rsv->lock);
6114 block_rsv->qgroup_rsv_reserved += qgroup_reserve;
6115 spin_unlock(&block_rsv->lock);
6118 mutex_unlock(&inode->delalloc_mutex);
6121 btrfs_qgroup_free_meta_prealloc(root, qgroup_reserve);
6123 btrfs_inode_rsv_release(inode, true);
6125 mutex_unlock(&inode->delalloc_mutex);
6130 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
6131 * @inode: the inode to release the reservation for.
6132 * @num_bytes: the number of bytes we are releasing.
6133 * @qgroup_free: free qgroup reservation or convert it to per-trans reservation
6135 * This will release the metadata reservation for an inode. This can be called
6136 * once we complete IO for a given set of bytes to release their metadata
6137 * reservations, or on error for the same reason.
6139 void btrfs_delalloc_release_metadata(struct btrfs_inode *inode, u64 num_bytes,
6142 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6144 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6145 spin_lock(&inode->lock);
6146 inode->csum_bytes -= num_bytes;
6147 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6148 spin_unlock(&inode->lock);
6150 if (btrfs_is_testing(fs_info))
6153 btrfs_inode_rsv_release(inode, qgroup_free);
6157 * btrfs_delalloc_release_extents - release our outstanding_extents
6158 * @inode: the inode to balance the reservation for.
6159 * @num_bytes: the number of bytes we originally reserved with
6160 * @qgroup_free: do we need to free qgroup meta reservation or convert them.
6162 * When we reserve space we increase outstanding_extents for the extents we may
6163 * add. Once we've set the range as delalloc or created our ordered extents we
6164 * have outstanding_extents to track the real usage, so we use this to free our
6165 * temporarily tracked outstanding_extents. This _must_ be used in conjunction
6166 * with btrfs_delalloc_reserve_metadata.
6168 void btrfs_delalloc_release_extents(struct btrfs_inode *inode, u64 num_bytes,
6171 struct btrfs_fs_info *fs_info = inode->root->fs_info;
6172 unsigned num_extents;
6174 spin_lock(&inode->lock);
6175 num_extents = count_max_extents(num_bytes);
6176 btrfs_mod_outstanding_extents(inode, -num_extents);
6177 btrfs_calculate_inode_block_rsv_size(fs_info, inode);
6178 spin_unlock(&inode->lock);
6180 if (btrfs_is_testing(fs_info))
6183 btrfs_inode_rsv_release(inode, qgroup_free);
6187 * btrfs_delalloc_reserve_space - reserve data and metadata space for
6189 * @inode: inode we're writing to
6190 * @start: start range we are writing to
6191 * @len: how long the range we are writing to
6192 * @reserved: mandatory parameter, record actually reserved qgroup ranges of
6193 * current reservation.
6195 * This will do the following things
6197 * o reserve space in data space info for num bytes
6198 * and reserve precious corresponding qgroup space
6199 * (Done in check_data_free_space)
6201 * o reserve space for metadata space, based on the number of outstanding
6202 * extents and how much csums will be needed
6203 * also reserve metadata space in a per root over-reserve method.
6204 * o add to the inodes->delalloc_bytes
6205 * o add it to the fs_info's delalloc inodes list.
6206 * (Above 3 all done in delalloc_reserve_metadata)
6208 * Return 0 for success
6209 * Return <0 for error(-ENOSPC or -EQUOT)
6211 int btrfs_delalloc_reserve_space(struct inode *inode,
6212 struct extent_changeset **reserved, u64 start, u64 len)
6216 ret = btrfs_check_data_free_space(inode, reserved, start, len);
6219 ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
6221 btrfs_free_reserved_data_space(inode, *reserved, start, len);
6226 * btrfs_delalloc_release_space - release data and metadata space for delalloc
6227 * @inode: inode we're releasing space for
6228 * @start: start position of the space already reserved
6229 * @len: the len of the space already reserved
6230 * @release_bytes: the len of the space we consumed or didn't use
6232 * This function will release the metadata space that was not used and will
6233 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6234 * list if there are no delalloc bytes left.
6235 * Also it will handle the qgroup reserved space.
6237 void btrfs_delalloc_release_space(struct inode *inode,
6238 struct extent_changeset *reserved,
6239 u64 start, u64 len, bool qgroup_free)
6241 btrfs_delalloc_release_metadata(BTRFS_I(inode), len, qgroup_free);
6242 btrfs_free_reserved_data_space(inode, reserved, start, len);
6245 static int update_block_group(struct btrfs_trans_handle *trans,
6246 u64 bytenr, u64 num_bytes, int alloc)
6248 struct btrfs_fs_info *info = trans->fs_info;
6249 struct btrfs_block_group_cache *cache = NULL;
6250 u64 total = num_bytes;
6256 /* block accounting for super block */
6257 spin_lock(&info->delalloc_root_lock);
6258 old_val = btrfs_super_bytes_used(info->super_copy);
6260 old_val += num_bytes;
6262 old_val -= num_bytes;
6263 btrfs_set_super_bytes_used(info->super_copy, old_val);
6264 spin_unlock(&info->delalloc_root_lock);
6267 cache = btrfs_lookup_block_group(info, bytenr);
6272 factor = btrfs_bg_type_to_factor(cache->flags);
6275 * If this block group has free space cache written out, we
6276 * need to make sure to load it if we are removing space. This
6277 * is because we need the unpinning stage to actually add the
6278 * space back to the block group, otherwise we will leak space.
6280 if (!alloc && cache->cached == BTRFS_CACHE_NO)
6281 cache_block_group(cache, 1);
6283 byte_in_group = bytenr - cache->key.objectid;
6284 WARN_ON(byte_in_group > cache->key.offset);
6286 spin_lock(&cache->space_info->lock);
6287 spin_lock(&cache->lock);
6289 if (btrfs_test_opt(info, SPACE_CACHE) &&
6290 cache->disk_cache_state < BTRFS_DC_CLEAR)
6291 cache->disk_cache_state = BTRFS_DC_CLEAR;
6293 old_val = btrfs_block_group_used(&cache->item);
6294 num_bytes = min(total, cache->key.offset - byte_in_group);
6296 old_val += num_bytes;
6297 btrfs_set_block_group_used(&cache->item, old_val);
6298 cache->reserved -= num_bytes;
6299 cache->space_info->bytes_reserved -= num_bytes;
6300 cache->space_info->bytes_used += num_bytes;
6301 cache->space_info->disk_used += num_bytes * factor;
6302 spin_unlock(&cache->lock);
6303 spin_unlock(&cache->space_info->lock);
6305 old_val -= num_bytes;
6306 btrfs_set_block_group_used(&cache->item, old_val);
6307 cache->pinned += num_bytes;
6308 update_bytes_pinned(info, cache->space_info, num_bytes);
6309 cache->space_info->bytes_used -= num_bytes;
6310 cache->space_info->disk_used -= num_bytes * factor;
6311 spin_unlock(&cache->lock);
6312 spin_unlock(&cache->space_info->lock);
6314 trace_btrfs_space_reservation(info, "pinned",
6315 cache->space_info->flags,
6317 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
6319 BTRFS_TOTAL_BYTES_PINNED_BATCH);
6320 set_extent_dirty(info->pinned_extents,
6321 bytenr, bytenr + num_bytes - 1,
6322 GFP_NOFS | __GFP_NOFAIL);
6325 spin_lock(&trans->transaction->dirty_bgs_lock);
6326 if (list_empty(&cache->dirty_list)) {
6327 list_add_tail(&cache->dirty_list,
6328 &trans->transaction->dirty_bgs);
6329 trans->delayed_ref_updates++;
6330 btrfs_get_block_group(cache);
6332 spin_unlock(&trans->transaction->dirty_bgs_lock);
6335 * No longer have used bytes in this block group, queue it for
6336 * deletion. We do this after adding the block group to the
6337 * dirty list to avoid races between cleaner kthread and space
6340 if (!alloc && old_val == 0)
6341 btrfs_mark_bg_unused(cache);
6343 btrfs_put_block_group(cache);
6345 bytenr += num_bytes;
6348 /* Modified block groups are accounted for in the delayed_refs_rsv. */
6349 btrfs_update_delayed_refs_rsv(trans);
6353 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
6355 struct btrfs_block_group_cache *cache;
6358 spin_lock(&fs_info->block_group_cache_lock);
6359 bytenr = fs_info->first_logical_byte;
6360 spin_unlock(&fs_info->block_group_cache_lock);
6362 if (bytenr < (u64)-1)
6365 cache = btrfs_lookup_first_block_group(fs_info, search_start);
6369 bytenr = cache->key.objectid;
6370 btrfs_put_block_group(cache);
6375 static int pin_down_extent(struct btrfs_block_group_cache *cache,
6376 u64 bytenr, u64 num_bytes, int reserved)
6378 struct btrfs_fs_info *fs_info = cache->fs_info;
6380 spin_lock(&cache->space_info->lock);
6381 spin_lock(&cache->lock);
6382 cache->pinned += num_bytes;
6383 update_bytes_pinned(fs_info, cache->space_info, num_bytes);
6385 cache->reserved -= num_bytes;
6386 cache->space_info->bytes_reserved -= num_bytes;
6388 spin_unlock(&cache->lock);
6389 spin_unlock(&cache->space_info->lock);
6391 trace_btrfs_space_reservation(fs_info, "pinned",
6392 cache->space_info->flags, num_bytes, 1);
6393 percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
6394 num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
6395 set_extent_dirty(fs_info->pinned_extents, bytenr,
6396 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6401 * this function must be called within transaction
6403 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
6404 u64 bytenr, u64 num_bytes, int reserved)
6406 struct btrfs_block_group_cache *cache;
6408 cache = btrfs_lookup_block_group(fs_info, bytenr);
6409 BUG_ON(!cache); /* Logic error */
6411 pin_down_extent(cache, bytenr, num_bytes, reserved);
6413 btrfs_put_block_group(cache);
6418 * this function must be called within transaction
6420 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
6421 u64 bytenr, u64 num_bytes)
6423 struct btrfs_block_group_cache *cache;
6426 cache = btrfs_lookup_block_group(fs_info, bytenr);
6431 * pull in the free space cache (if any) so that our pin
6432 * removes the free space from the cache. We have load_only set
6433 * to one because the slow code to read in the free extents does check
6434 * the pinned extents.
6436 cache_block_group(cache, 1);
6438 pin_down_extent(cache, bytenr, num_bytes, 0);
6440 /* remove us from the free space cache (if we're there at all) */
6441 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6442 btrfs_put_block_group(cache);
6446 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
6447 u64 start, u64 num_bytes)
6450 struct btrfs_block_group_cache *block_group;
6451 struct btrfs_caching_control *caching_ctl;
6453 block_group = btrfs_lookup_block_group(fs_info, start);
6457 cache_block_group(block_group, 0);
6458 caching_ctl = get_caching_control(block_group);
6462 BUG_ON(!block_group_cache_done(block_group));
6463 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6465 mutex_lock(&caching_ctl->mutex);
6467 if (start >= caching_ctl->progress) {
6468 ret = add_excluded_extent(fs_info, start, num_bytes);
6469 } else if (start + num_bytes <= caching_ctl->progress) {
6470 ret = btrfs_remove_free_space(block_group,
6473 num_bytes = caching_ctl->progress - start;
6474 ret = btrfs_remove_free_space(block_group,
6479 num_bytes = (start + num_bytes) -
6480 caching_ctl->progress;
6481 start = caching_ctl->progress;
6482 ret = add_excluded_extent(fs_info, start, num_bytes);
6485 mutex_unlock(&caching_ctl->mutex);
6486 put_caching_control(caching_ctl);
6488 btrfs_put_block_group(block_group);
6492 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
6494 struct btrfs_fs_info *fs_info = eb->fs_info;
6495 struct btrfs_file_extent_item *item;
6496 struct btrfs_key key;
6501 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
6504 for (i = 0; i < btrfs_header_nritems(eb); i++) {
6505 btrfs_item_key_to_cpu(eb, &key, i);
6506 if (key.type != BTRFS_EXTENT_DATA_KEY)
6508 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6509 found_type = btrfs_file_extent_type(eb, item);
6510 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6512 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6514 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6515 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6516 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
6525 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6527 atomic_inc(&bg->reservations);
6530 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6533 struct btrfs_block_group_cache *bg;
6535 bg = btrfs_lookup_block_group(fs_info, start);
6537 if (atomic_dec_and_test(&bg->reservations))
6538 wake_up_var(&bg->reservations);
6539 btrfs_put_block_group(bg);
6542 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6544 struct btrfs_space_info *space_info = bg->space_info;
6548 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6552 * Our block group is read only but before we set it to read only,
6553 * some task might have had allocated an extent from it already, but it
6554 * has not yet created a respective ordered extent (and added it to a
6555 * root's list of ordered extents).
6556 * Therefore wait for any task currently allocating extents, since the
6557 * block group's reservations counter is incremented while a read lock
6558 * on the groups' semaphore is held and decremented after releasing
6559 * the read access on that semaphore and creating the ordered extent.
6561 down_write(&space_info->groups_sem);
6562 up_write(&space_info->groups_sem);
6564 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
6568 * btrfs_add_reserved_bytes - update the block_group and space info counters
6569 * @cache: The cache we are manipulating
6570 * @ram_bytes: The number of bytes of file content, and will be same to
6571 * @num_bytes except for the compress path.
6572 * @num_bytes: The number of bytes in question
6573 * @delalloc: The blocks are allocated for the delalloc write
6575 * This is called by the allocator when it reserves space. If this is a
6576 * reservation and the block group has become read only we cannot make the
6577 * reservation and return -EAGAIN, otherwise this function always succeeds.
6579 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
6580 u64 ram_bytes, u64 num_bytes, int delalloc)
6582 struct btrfs_space_info *space_info = cache->space_info;
6585 spin_lock(&space_info->lock);
6586 spin_lock(&cache->lock);
6590 cache->reserved += num_bytes;
6591 space_info->bytes_reserved += num_bytes;
6592 update_bytes_may_use(cache->fs_info, space_info, -ram_bytes);
6594 cache->delalloc_bytes += num_bytes;
6596 spin_unlock(&cache->lock);
6597 spin_unlock(&space_info->lock);
6602 * btrfs_free_reserved_bytes - update the block_group and space info counters
6603 * @cache: The cache we are manipulating
6604 * @num_bytes: The number of bytes in question
6605 * @delalloc: The blocks are allocated for the delalloc write
6607 * This is called by somebody who is freeing space that was never actually used
6608 * on disk. For example if you reserve some space for a new leaf in transaction
6609 * A and before transaction A commits you free that leaf, you call this with
6610 * reserve set to 0 in order to clear the reservation.
6613 static void btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6614 u64 num_bytes, int delalloc)
6616 struct btrfs_space_info *space_info = cache->space_info;
6618 spin_lock(&space_info->lock);
6619 spin_lock(&cache->lock);
6621 space_info->bytes_readonly += num_bytes;
6622 cache->reserved -= num_bytes;
6623 space_info->bytes_reserved -= num_bytes;
6624 space_info->max_extent_size = 0;
6627 cache->delalloc_bytes -= num_bytes;
6628 spin_unlock(&cache->lock);
6629 spin_unlock(&space_info->lock);
6631 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
6633 struct btrfs_caching_control *next;
6634 struct btrfs_caching_control *caching_ctl;
6635 struct btrfs_block_group_cache *cache;
6637 down_write(&fs_info->commit_root_sem);
6639 list_for_each_entry_safe(caching_ctl, next,
6640 &fs_info->caching_block_groups, list) {
6641 cache = caching_ctl->block_group;
6642 if (block_group_cache_done(cache)) {
6643 cache->last_byte_to_unpin = (u64)-1;
6644 list_del_init(&caching_ctl->list);
6645 put_caching_control(caching_ctl);
6647 cache->last_byte_to_unpin = caching_ctl->progress;
6651 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6652 fs_info->pinned_extents = &fs_info->freed_extents[1];
6654 fs_info->pinned_extents = &fs_info->freed_extents[0];
6656 up_write(&fs_info->commit_root_sem);
6658 update_global_block_rsv(fs_info);
6662 * Returns the free cluster for the given space info and sets empty_cluster to
6663 * what it should be based on the mount options.
6665 static struct btrfs_free_cluster *
6666 fetch_cluster_info(struct btrfs_fs_info *fs_info,
6667 struct btrfs_space_info *space_info, u64 *empty_cluster)
6669 struct btrfs_free_cluster *ret = NULL;
6672 if (btrfs_mixed_space_info(space_info))
6675 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6676 ret = &fs_info->meta_alloc_cluster;
6677 if (btrfs_test_opt(fs_info, SSD))
6678 *empty_cluster = SZ_2M;
6680 *empty_cluster = SZ_64K;
6681 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
6682 btrfs_test_opt(fs_info, SSD_SPREAD)) {
6683 *empty_cluster = SZ_2M;
6684 ret = &fs_info->data_alloc_cluster;
6690 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
6692 const bool return_free_space)
6694 struct btrfs_block_group_cache *cache = NULL;
6695 struct btrfs_space_info *space_info;
6696 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6697 struct btrfs_free_cluster *cluster = NULL;
6699 u64 total_unpinned = 0;
6700 u64 empty_cluster = 0;
6703 while (start <= end) {
6706 start >= cache->key.objectid + cache->key.offset) {
6708 btrfs_put_block_group(cache);
6710 cache = btrfs_lookup_block_group(fs_info, start);
6711 BUG_ON(!cache); /* Logic error */
6713 cluster = fetch_cluster_info(fs_info,
6716 empty_cluster <<= 1;
6719 len = cache->key.objectid + cache->key.offset - start;
6720 len = min(len, end + 1 - start);
6722 if (start < cache->last_byte_to_unpin) {
6723 len = min(len, cache->last_byte_to_unpin - start);
6724 if (return_free_space)
6725 btrfs_add_free_space(cache, start, len);
6729 total_unpinned += len;
6730 space_info = cache->space_info;
6733 * If this space cluster has been marked as fragmented and we've
6734 * unpinned enough in this block group to potentially allow a
6735 * cluster to be created inside of it go ahead and clear the
6738 if (cluster && cluster->fragmented &&
6739 total_unpinned > empty_cluster) {
6740 spin_lock(&cluster->lock);
6741 cluster->fragmented = 0;
6742 spin_unlock(&cluster->lock);
6745 spin_lock(&space_info->lock);
6746 spin_lock(&cache->lock);
6747 cache->pinned -= len;
6748 update_bytes_pinned(fs_info, space_info, -len);
6750 trace_btrfs_space_reservation(fs_info, "pinned",
6751 space_info->flags, len, 0);
6752 space_info->max_extent_size = 0;
6753 percpu_counter_add_batch(&space_info->total_bytes_pinned,
6754 -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
6756 space_info->bytes_readonly += len;
6759 spin_unlock(&cache->lock);
6760 if (!readonly && return_free_space &&
6761 global_rsv->space_info == space_info) {
6764 spin_lock(&global_rsv->lock);
6765 if (!global_rsv->full) {
6766 to_add = min(len, global_rsv->size -
6767 global_rsv->reserved);
6768 global_rsv->reserved += to_add;
6769 update_bytes_may_use(fs_info, space_info,
6771 if (global_rsv->reserved >= global_rsv->size)
6772 global_rsv->full = 1;
6773 trace_btrfs_space_reservation(fs_info,
6779 spin_unlock(&global_rsv->lock);
6780 /* Add to any tickets we may have */
6782 space_info_add_new_bytes(fs_info, space_info,
6785 spin_unlock(&space_info->lock);
6789 btrfs_put_block_group(cache);
6793 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
6795 struct btrfs_fs_info *fs_info = trans->fs_info;
6796 struct btrfs_block_group_cache *block_group, *tmp;
6797 struct list_head *deleted_bgs;
6798 struct extent_io_tree *unpin;
6803 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6804 unpin = &fs_info->freed_extents[1];
6806 unpin = &fs_info->freed_extents[0];
6808 while (!trans->aborted) {
6809 struct extent_state *cached_state = NULL;
6811 mutex_lock(&fs_info->unused_bg_unpin_mutex);
6812 ret = find_first_extent_bit(unpin, 0, &start, &end,
6813 EXTENT_DIRTY, &cached_state);
6815 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6819 if (btrfs_test_opt(fs_info, DISCARD))
6820 ret = btrfs_discard_extent(fs_info, start,
6821 end + 1 - start, NULL);
6823 clear_extent_dirty(unpin, start, end, &cached_state);
6824 unpin_extent_range(fs_info, start, end, true);
6825 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6826 free_extent_state(cached_state);
6831 * Transaction is finished. We don't need the lock anymore. We
6832 * do need to clean up the block groups in case of a transaction
6835 deleted_bgs = &trans->transaction->deleted_bgs;
6836 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6840 if (!trans->aborted)
6841 ret = btrfs_discard_extent(fs_info,
6842 block_group->key.objectid,
6843 block_group->key.offset,
6846 list_del_init(&block_group->bg_list);
6847 btrfs_put_block_group_trimming(block_group);
6848 btrfs_put_block_group(block_group);
6851 const char *errstr = btrfs_decode_error(ret);
6853 "discard failed while removing blockgroup: errno=%d %s",
6861 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6862 struct btrfs_delayed_ref_node *node, u64 parent,
6863 u64 root_objectid, u64 owner_objectid,
6864 u64 owner_offset, int refs_to_drop,
6865 struct btrfs_delayed_extent_op *extent_op)
6867 struct btrfs_fs_info *info = trans->fs_info;
6868 struct btrfs_key key;
6869 struct btrfs_path *path;
6870 struct btrfs_root *extent_root = info->extent_root;
6871 struct extent_buffer *leaf;
6872 struct btrfs_extent_item *ei;
6873 struct btrfs_extent_inline_ref *iref;
6876 int extent_slot = 0;
6877 int found_extent = 0;
6881 u64 bytenr = node->bytenr;
6882 u64 num_bytes = node->num_bytes;
6884 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
6886 path = btrfs_alloc_path();
6890 path->reada = READA_FORWARD;
6891 path->leave_spinning = 1;
6893 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6894 BUG_ON(!is_data && refs_to_drop != 1);
6897 skinny_metadata = false;
6899 ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
6900 parent, root_objectid, owner_objectid,
6903 extent_slot = path->slots[0];
6904 while (extent_slot >= 0) {
6905 btrfs_item_key_to_cpu(path->nodes[0], &key,
6907 if (key.objectid != bytenr)
6909 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6910 key.offset == num_bytes) {
6914 if (key.type == BTRFS_METADATA_ITEM_KEY &&
6915 key.offset == owner_objectid) {
6919 if (path->slots[0] - extent_slot > 5)
6924 if (!found_extent) {
6926 ret = remove_extent_backref(trans, path, NULL,
6928 is_data, &last_ref);
6930 btrfs_abort_transaction(trans, ret);
6933 btrfs_release_path(path);
6934 path->leave_spinning = 1;
6936 key.objectid = bytenr;
6937 key.type = BTRFS_EXTENT_ITEM_KEY;
6938 key.offset = num_bytes;
6940 if (!is_data && skinny_metadata) {
6941 key.type = BTRFS_METADATA_ITEM_KEY;
6942 key.offset = owner_objectid;
6945 ret = btrfs_search_slot(trans, extent_root,
6947 if (ret > 0 && skinny_metadata && path->slots[0]) {
6949 * Couldn't find our skinny metadata item,
6950 * see if we have ye olde extent item.
6953 btrfs_item_key_to_cpu(path->nodes[0], &key,
6955 if (key.objectid == bytenr &&
6956 key.type == BTRFS_EXTENT_ITEM_KEY &&
6957 key.offset == num_bytes)
6961 if (ret > 0 && skinny_metadata) {
6962 skinny_metadata = false;
6963 key.objectid = bytenr;
6964 key.type = BTRFS_EXTENT_ITEM_KEY;
6965 key.offset = num_bytes;
6966 btrfs_release_path(path);
6967 ret = btrfs_search_slot(trans, extent_root,
6973 "umm, got %d back from search, was looking for %llu",
6976 btrfs_print_leaf(path->nodes[0]);
6979 btrfs_abort_transaction(trans, ret);
6982 extent_slot = path->slots[0];
6984 } else if (WARN_ON(ret == -ENOENT)) {
6985 btrfs_print_leaf(path->nodes[0]);
6987 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
6988 bytenr, parent, root_objectid, owner_objectid,
6990 btrfs_abort_transaction(trans, ret);
6993 btrfs_abort_transaction(trans, ret);
6997 leaf = path->nodes[0];
6998 item_size = btrfs_item_size_nr(leaf, extent_slot);
6999 if (unlikely(item_size < sizeof(*ei))) {
7001 btrfs_print_v0_err(info);
7002 btrfs_abort_transaction(trans, ret);
7005 ei = btrfs_item_ptr(leaf, extent_slot,
7006 struct btrfs_extent_item);
7007 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
7008 key.type == BTRFS_EXTENT_ITEM_KEY) {
7009 struct btrfs_tree_block_info *bi;
7010 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
7011 bi = (struct btrfs_tree_block_info *)(ei + 1);
7012 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
7015 refs = btrfs_extent_refs(leaf, ei);
7016 if (refs < refs_to_drop) {
7018 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
7019 refs_to_drop, refs, bytenr);
7021 btrfs_abort_transaction(trans, ret);
7024 refs -= refs_to_drop;
7028 __run_delayed_extent_op(extent_op, leaf, ei);
7030 * In the case of inline back ref, reference count will
7031 * be updated by remove_extent_backref
7034 BUG_ON(!found_extent);
7036 btrfs_set_extent_refs(leaf, ei, refs);
7037 btrfs_mark_buffer_dirty(leaf);
7040 ret = remove_extent_backref(trans, path, iref,
7041 refs_to_drop, is_data,
7044 btrfs_abort_transaction(trans, ret);
7050 BUG_ON(is_data && refs_to_drop !=
7051 extent_data_ref_count(path, iref));
7053 BUG_ON(path->slots[0] != extent_slot);
7055 BUG_ON(path->slots[0] != extent_slot + 1);
7056 path->slots[0] = extent_slot;
7062 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
7065 btrfs_abort_transaction(trans, ret);
7068 btrfs_release_path(path);
7071 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
7073 btrfs_abort_transaction(trans, ret);
7078 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
7080 btrfs_abort_transaction(trans, ret);
7084 ret = update_block_group(trans, bytenr, num_bytes, 0);
7086 btrfs_abort_transaction(trans, ret);
7090 btrfs_release_path(path);
7093 btrfs_free_path(path);
7098 * when we free an block, it is possible (and likely) that we free the last
7099 * delayed ref for that extent as well. This searches the delayed ref tree for
7100 * a given extent, and if there are no other delayed refs to be processed, it
7101 * removes it from the tree.
7103 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
7106 struct btrfs_delayed_ref_head *head;
7107 struct btrfs_delayed_ref_root *delayed_refs;
7110 delayed_refs = &trans->transaction->delayed_refs;
7111 spin_lock(&delayed_refs->lock);
7112 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
7114 goto out_delayed_unlock;
7116 spin_lock(&head->lock);
7117 if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
7120 if (cleanup_extent_op(head) != NULL)
7124 * waiting for the lock here would deadlock. If someone else has it
7125 * locked they are already in the process of dropping it anyway
7127 if (!mutex_trylock(&head->mutex))
7130 btrfs_delete_ref_head(delayed_refs, head);
7131 head->processing = 0;
7133 spin_unlock(&head->lock);
7134 spin_unlock(&delayed_refs->lock);
7136 BUG_ON(head->extent_op);
7137 if (head->must_insert_reserved)
7140 btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
7141 mutex_unlock(&head->mutex);
7142 btrfs_put_delayed_ref_head(head);
7145 spin_unlock(&head->lock);
7148 spin_unlock(&delayed_refs->lock);
7152 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
7153 struct btrfs_root *root,
7154 struct extent_buffer *buf,
7155 u64 parent, int last_ref)
7157 struct btrfs_fs_info *fs_info = root->fs_info;
7158 struct btrfs_ref generic_ref = { 0 };
7162 btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
7163 buf->start, buf->len, parent);
7164 btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
7165 root->root_key.objectid);
7167 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7168 int old_ref_mod, new_ref_mod;
7170 btrfs_ref_tree_mod(fs_info, &generic_ref);
7171 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
7172 &old_ref_mod, &new_ref_mod);
7173 BUG_ON(ret); /* -ENOMEM */
7174 pin = old_ref_mod >= 0 && new_ref_mod < 0;
7177 if (last_ref && btrfs_header_generation(buf) == trans->transid) {
7178 struct btrfs_block_group_cache *cache;
7180 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7181 ret = check_ref_cleanup(trans, buf->start);
7187 cache = btrfs_lookup_block_group(fs_info, buf->start);
7189 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
7190 pin_down_extent(cache, buf->start, buf->len, 1);
7191 btrfs_put_block_group(cache);
7195 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
7197 btrfs_add_free_space(cache, buf->start, buf->len);
7198 btrfs_free_reserved_bytes(cache, buf->len, 0);
7199 btrfs_put_block_group(cache);
7200 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
7204 add_pinned_bytes(fs_info, &generic_ref);
7208 * Deleting the buffer, clear the corrupt flag since it doesn't
7211 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7215 /* Can return -ENOMEM */
7216 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
7218 struct btrfs_fs_info *fs_info = trans->fs_info;
7219 int old_ref_mod, new_ref_mod;
7222 if (btrfs_is_testing(fs_info))
7226 * tree log blocks never actually go into the extent allocation
7227 * tree, just update pinning info and exit early.
7229 if ((ref->type == BTRFS_REF_METADATA &&
7230 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
7231 (ref->type == BTRFS_REF_DATA &&
7232 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
7233 /* unlocks the pinned mutex */
7234 btrfs_pin_extent(fs_info, ref->bytenr, ref->len, 1);
7235 old_ref_mod = new_ref_mod = 0;
7237 } else if (ref->type == BTRFS_REF_METADATA) {
7238 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
7239 &old_ref_mod, &new_ref_mod);
7241 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
7242 &old_ref_mod, &new_ref_mod);
7245 if (!((ref->type == BTRFS_REF_METADATA &&
7246 ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
7247 (ref->type == BTRFS_REF_DATA &&
7248 ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
7249 btrfs_ref_tree_mod(fs_info, ref);
7251 if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
7252 add_pinned_bytes(fs_info, ref);
7258 * when we wait for progress in the block group caching, its because
7259 * our allocation attempt failed at least once. So, we must sleep
7260 * and let some progress happen before we try again.
7262 * This function will sleep at least once waiting for new free space to
7263 * show up, and then it will check the block group free space numbers
7264 * for our min num_bytes. Another option is to have it go ahead
7265 * and look in the rbtree for a free extent of a given size, but this
7268 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7269 * any of the information in this block group.
7271 static noinline void
7272 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7275 struct btrfs_caching_control *caching_ctl;
7277 caching_ctl = get_caching_control(cache);
7281 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
7282 (cache->free_space_ctl->free_space >= num_bytes));
7284 put_caching_control(caching_ctl);
7288 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7290 struct btrfs_caching_control *caching_ctl;
7293 caching_ctl = get_caching_control(cache);
7295 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
7297 wait_event(caching_ctl->wait, block_group_cache_done(cache));
7298 if (cache->cached == BTRFS_CACHE_ERROR)
7300 put_caching_control(caching_ctl);
7304 enum btrfs_loop_type {
7305 LOOP_CACHING_NOWAIT = 0,
7306 LOOP_CACHING_WAIT = 1,
7307 LOOP_ALLOC_CHUNK = 2,
7308 LOOP_NO_EMPTY_SIZE = 3,
7312 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7316 down_read(&cache->data_rwsem);
7320 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7323 btrfs_get_block_group(cache);
7325 down_read(&cache->data_rwsem);
7328 static struct btrfs_block_group_cache *
7329 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7330 struct btrfs_free_cluster *cluster,
7333 struct btrfs_block_group_cache *used_bg = NULL;
7335 spin_lock(&cluster->refill_lock);
7337 used_bg = cluster->block_group;
7341 if (used_bg == block_group)
7344 btrfs_get_block_group(used_bg);
7349 if (down_read_trylock(&used_bg->data_rwsem))
7352 spin_unlock(&cluster->refill_lock);
7354 /* We should only have one-level nested. */
7355 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
7357 spin_lock(&cluster->refill_lock);
7358 if (used_bg == cluster->block_group)
7361 up_read(&used_bg->data_rwsem);
7362 btrfs_put_block_group(used_bg);
7367 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7371 up_read(&cache->data_rwsem);
7372 btrfs_put_block_group(cache);
7376 * Structure used internally for find_free_extent() function. Wraps needed
7379 struct find_free_extent_ctl {
7380 /* Basic allocation info */
7387 /* Where to start the search inside the bg */
7390 /* For clustered allocation */
7393 bool have_caching_bg;
7394 bool orig_have_caching_bg;
7396 /* RAID index, converted from flags */
7400 * Current loop number, check find_free_extent_update_loop() for details
7405 * Whether we're refilling a cluster, if true we need to re-search
7406 * current block group but don't try to refill the cluster again.
7408 bool retry_clustered;
7411 * Whether we're updating free space cache, if true we need to re-search
7412 * current block group but don't try updating free space cache again.
7414 bool retry_unclustered;
7416 /* If current block group is cached */
7419 /* Max contiguous hole found */
7420 u64 max_extent_size;
7422 /* Total free space from free space cache, not always contiguous */
7423 u64 total_free_space;
7431 * Helper function for find_free_extent().
7433 * Return -ENOENT to inform caller that we need fallback to unclustered mode.
7434 * Return -EAGAIN to inform caller that we need to re-search this block group
7435 * Return >0 to inform caller that we find nothing
7436 * Return 0 means we have found a location and set ffe_ctl->found_offset.
7438 static int find_free_extent_clustered(struct btrfs_block_group_cache *bg,
7439 struct btrfs_free_cluster *last_ptr,
7440 struct find_free_extent_ctl *ffe_ctl,
7441 struct btrfs_block_group_cache **cluster_bg_ret)
7443 struct btrfs_block_group_cache *cluster_bg;
7444 u64 aligned_cluster;
7448 cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
7450 goto refill_cluster;
7451 if (cluster_bg != bg && (cluster_bg->ro ||
7452 !block_group_bits(cluster_bg, ffe_ctl->flags)))
7453 goto release_cluster;
7455 offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
7456 ffe_ctl->num_bytes, cluster_bg->key.objectid,
7457 &ffe_ctl->max_extent_size);
7459 /* We have a block, we're done */
7460 spin_unlock(&last_ptr->refill_lock);
7461 trace_btrfs_reserve_extent_cluster(cluster_bg,
7462 ffe_ctl->search_start, ffe_ctl->num_bytes);
7463 *cluster_bg_ret = cluster_bg;
7464 ffe_ctl->found_offset = offset;
7467 WARN_ON(last_ptr->block_group != cluster_bg);
7471 * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
7472 * lets just skip it and let the allocator find whatever block it can
7473 * find. If we reach this point, we will have tried the cluster
7474 * allocator plenty of times and not have found anything, so we are
7475 * likely way too fragmented for the clustering stuff to find anything.
7477 * However, if the cluster is taken from the current block group,
7478 * release the cluster first, so that we stand a better chance of
7479 * succeeding in the unclustered allocation.
7481 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
7482 spin_unlock(&last_ptr->refill_lock);
7483 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
7487 /* This cluster didn't work out, free it and start over */
7488 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7490 if (cluster_bg != bg)
7491 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
7494 if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
7495 spin_unlock(&last_ptr->refill_lock);
7499 aligned_cluster = max_t(u64,
7500 ffe_ctl->empty_cluster + ffe_ctl->empty_size,
7501 bg->full_stripe_len);
7502 ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
7503 ffe_ctl->num_bytes, aligned_cluster);
7505 /* Now pull our allocation out of this cluster */
7506 offset = btrfs_alloc_from_cluster(bg, last_ptr,
7507 ffe_ctl->num_bytes, ffe_ctl->search_start,
7508 &ffe_ctl->max_extent_size);
7510 /* We found one, proceed */
7511 spin_unlock(&last_ptr->refill_lock);
7512 trace_btrfs_reserve_extent_cluster(bg,
7513 ffe_ctl->search_start,
7514 ffe_ctl->num_bytes);
7515 ffe_ctl->found_offset = offset;
7518 } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
7519 !ffe_ctl->retry_clustered) {
7520 spin_unlock(&last_ptr->refill_lock);
7522 ffe_ctl->retry_clustered = true;
7523 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
7524 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
7528 * At this point we either didn't find a cluster or we weren't able to
7529 * allocate a block from our cluster. Free the cluster we've been
7530 * trying to use, and go to the next block group.
7532 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7533 spin_unlock(&last_ptr->refill_lock);
7538 * Return >0 to inform caller that we find nothing
7539 * Return 0 when we found an free extent and set ffe_ctrl->found_offset
7540 * Return -EAGAIN to inform caller that we need to re-search this block group
7542 static int find_free_extent_unclustered(struct btrfs_block_group_cache *bg,
7543 struct btrfs_free_cluster *last_ptr,
7544 struct find_free_extent_ctl *ffe_ctl)
7549 * We are doing an unclustered allocation, set the fragmented flag so
7550 * we don't bother trying to setup a cluster again until we get more
7553 if (unlikely(last_ptr)) {
7554 spin_lock(&last_ptr->lock);
7555 last_ptr->fragmented = 1;
7556 spin_unlock(&last_ptr->lock);
7558 if (ffe_ctl->cached) {
7559 struct btrfs_free_space_ctl *free_space_ctl;
7561 free_space_ctl = bg->free_space_ctl;
7562 spin_lock(&free_space_ctl->tree_lock);
7563 if (free_space_ctl->free_space <
7564 ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
7565 ffe_ctl->empty_size) {
7566 ffe_ctl->total_free_space = max_t(u64,
7567 ffe_ctl->total_free_space,
7568 free_space_ctl->free_space);
7569 spin_unlock(&free_space_ctl->tree_lock);
7572 spin_unlock(&free_space_ctl->tree_lock);
7575 offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
7576 ffe_ctl->num_bytes, ffe_ctl->empty_size,
7577 &ffe_ctl->max_extent_size);
7580 * If we didn't find a chunk, and we haven't failed on this block group
7581 * before, and this block group is in the middle of caching and we are
7582 * ok with waiting, then go ahead and wait for progress to be made, and
7583 * set @retry_unclustered to true.
7585 * If @retry_unclustered is true then we've already waited on this
7586 * block group once and should move on to the next block group.
7588 if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
7589 ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
7590 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
7591 ffe_ctl->empty_size);
7592 ffe_ctl->retry_unclustered = true;
7594 } else if (!offset) {
7597 ffe_ctl->found_offset = offset;
7602 * Return >0 means caller needs to re-search for free extent
7603 * Return 0 means we have the needed free extent.
7604 * Return <0 means we failed to locate any free extent.
7606 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
7607 struct btrfs_free_cluster *last_ptr,
7608 struct btrfs_key *ins,
7609 struct find_free_extent_ctl *ffe_ctl,
7610 int full_search, bool use_cluster)
7612 struct btrfs_root *root = fs_info->extent_root;
7615 if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
7616 ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
7617 ffe_ctl->orig_have_caching_bg = true;
7619 if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
7620 ffe_ctl->have_caching_bg)
7623 if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
7626 if (ins->objectid) {
7627 if (!use_cluster && last_ptr) {
7628 spin_lock(&last_ptr->lock);
7629 last_ptr->window_start = ins->objectid;
7630 spin_unlock(&last_ptr->lock);
7636 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7637 * caching kthreads as we move along
7638 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7639 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7640 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7643 if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
7645 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
7647 * We want to skip the LOOP_CACHING_WAIT step if we
7648 * don't have any uncached bgs and we've already done a
7649 * full search through.
7651 if (ffe_ctl->orig_have_caching_bg || !full_search)
7652 ffe_ctl->loop = LOOP_CACHING_WAIT;
7654 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
7659 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
7660 struct btrfs_trans_handle *trans;
7663 trans = current->journal_info;
7667 trans = btrfs_join_transaction(root);
7669 if (IS_ERR(trans)) {
7670 ret = PTR_ERR(trans);
7674 ret = do_chunk_alloc(trans, ffe_ctl->flags,
7678 * If we can't allocate a new chunk we've already looped
7679 * through at least once, move on to the NO_EMPTY_SIZE
7683 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
7685 /* Do not bail out on ENOSPC since we can do more. */
7686 if (ret < 0 && ret != -ENOSPC)
7687 btrfs_abort_transaction(trans, ret);
7691 btrfs_end_transaction(trans);
7696 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
7698 * Don't loop again if we already have no empty_size and
7701 if (ffe_ctl->empty_size == 0 &&
7702 ffe_ctl->empty_cluster == 0)
7704 ffe_ctl->empty_size = 0;
7705 ffe_ctl->empty_cluster = 0;
7713 * walks the btree of allocated extents and find a hole of a given size.
7714 * The key ins is changed to record the hole:
7715 * ins->objectid == start position
7716 * ins->flags = BTRFS_EXTENT_ITEM_KEY
7717 * ins->offset == the size of the hole.
7718 * Any available blocks before search_start are skipped.
7720 * If there is no suitable free space, we will record the max size of
7721 * the free space extent currently.
7723 * The overall logic and call chain:
7725 * find_free_extent()
7726 * |- Iterate through all block groups
7727 * | |- Get a valid block group
7728 * | |- Try to do clustered allocation in that block group
7729 * | |- Try to do unclustered allocation in that block group
7730 * | |- Check if the result is valid
7731 * | | |- If valid, then exit
7732 * | |- Jump to next block group
7734 * |- Push harder to find free extents
7735 * |- If not found, re-iterate all block groups
7737 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
7738 u64 ram_bytes, u64 num_bytes, u64 empty_size,
7739 u64 hint_byte, struct btrfs_key *ins,
7740 u64 flags, int delalloc)
7743 struct btrfs_free_cluster *last_ptr = NULL;
7744 struct btrfs_block_group_cache *block_group = NULL;
7745 struct find_free_extent_ctl ffe_ctl = {0};
7746 struct btrfs_space_info *space_info;
7747 bool use_cluster = true;
7748 bool full_search = false;
7750 WARN_ON(num_bytes < fs_info->sectorsize);
7752 ffe_ctl.ram_bytes = ram_bytes;
7753 ffe_ctl.num_bytes = num_bytes;
7754 ffe_ctl.empty_size = empty_size;
7755 ffe_ctl.flags = flags;
7756 ffe_ctl.search_start = 0;
7757 ffe_ctl.retry_clustered = false;
7758 ffe_ctl.retry_unclustered = false;
7759 ffe_ctl.delalloc = delalloc;
7760 ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
7761 ffe_ctl.have_caching_bg = false;
7762 ffe_ctl.orig_have_caching_bg = false;
7763 ffe_ctl.found_offset = 0;
7765 ins->type = BTRFS_EXTENT_ITEM_KEY;
7769 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
7771 space_info = __find_space_info(fs_info, flags);
7773 btrfs_err(fs_info, "No space info for %llu", flags);
7778 * If our free space is heavily fragmented we may not be able to make
7779 * big contiguous allocations, so instead of doing the expensive search
7780 * for free space, simply return ENOSPC with our max_extent_size so we
7781 * can go ahead and search for a more manageable chunk.
7783 * If our max_extent_size is large enough for our allocation simply
7784 * disable clustering since we will likely not be able to find enough
7785 * space to create a cluster and induce latency trying.
7787 if (unlikely(space_info->max_extent_size)) {
7788 spin_lock(&space_info->lock);
7789 if (space_info->max_extent_size &&
7790 num_bytes > space_info->max_extent_size) {
7791 ins->offset = space_info->max_extent_size;
7792 spin_unlock(&space_info->lock);
7794 } else if (space_info->max_extent_size) {
7795 use_cluster = false;
7797 spin_unlock(&space_info->lock);
7800 last_ptr = fetch_cluster_info(fs_info, space_info,
7801 &ffe_ctl.empty_cluster);
7803 spin_lock(&last_ptr->lock);
7804 if (last_ptr->block_group)
7805 hint_byte = last_ptr->window_start;
7806 if (last_ptr->fragmented) {
7808 * We still set window_start so we can keep track of the
7809 * last place we found an allocation to try and save
7812 hint_byte = last_ptr->window_start;
7813 use_cluster = false;
7815 spin_unlock(&last_ptr->lock);
7818 ffe_ctl.search_start = max(ffe_ctl.search_start,
7819 first_logical_byte(fs_info, 0));
7820 ffe_ctl.search_start = max(ffe_ctl.search_start, hint_byte);
7821 if (ffe_ctl.search_start == hint_byte) {
7822 block_group = btrfs_lookup_block_group(fs_info,
7823 ffe_ctl.search_start);
7825 * we don't want to use the block group if it doesn't match our
7826 * allocation bits, or if its not cached.
7828 * However if we are re-searching with an ideal block group
7829 * picked out then we don't care that the block group is cached.
7831 if (block_group && block_group_bits(block_group, flags) &&
7832 block_group->cached != BTRFS_CACHE_NO) {
7833 down_read(&space_info->groups_sem);
7834 if (list_empty(&block_group->list) ||
7837 * someone is removing this block group,
7838 * we can't jump into the have_block_group
7839 * target because our list pointers are not
7842 btrfs_put_block_group(block_group);
7843 up_read(&space_info->groups_sem);
7845 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
7846 block_group->flags);
7847 btrfs_lock_block_group(block_group, delalloc);
7848 goto have_block_group;
7850 } else if (block_group) {
7851 btrfs_put_block_group(block_group);
7855 ffe_ctl.have_caching_bg = false;
7856 if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
7859 down_read(&space_info->groups_sem);
7860 list_for_each_entry(block_group,
7861 &space_info->block_groups[ffe_ctl.index], list) {
7862 /* If the block group is read-only, we can skip it entirely. */
7863 if (unlikely(block_group->ro))
7866 btrfs_grab_block_group(block_group, delalloc);
7867 ffe_ctl.search_start = block_group->key.objectid;
7870 * this can happen if we end up cycling through all the
7871 * raid types, but we want to make sure we only allocate
7872 * for the proper type.
7874 if (!block_group_bits(block_group, flags)) {
7875 u64 extra = BTRFS_BLOCK_GROUP_DUP |
7876 BTRFS_BLOCK_GROUP_RAID1_MASK |
7877 BTRFS_BLOCK_GROUP_RAID56_MASK |
7878 BTRFS_BLOCK_GROUP_RAID10;
7881 * if they asked for extra copies and this block group
7882 * doesn't provide them, bail. This does allow us to
7883 * fill raid0 from raid1.
7885 if ((flags & extra) && !(block_group->flags & extra))
7890 ffe_ctl.cached = block_group_cache_done(block_group);
7891 if (unlikely(!ffe_ctl.cached)) {
7892 ffe_ctl.have_caching_bg = true;
7893 ret = cache_block_group(block_group, 0);
7898 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7902 * Ok we want to try and use the cluster allocator, so
7905 if (last_ptr && use_cluster) {
7906 struct btrfs_block_group_cache *cluster_bg = NULL;
7908 ret = find_free_extent_clustered(block_group, last_ptr,
7909 &ffe_ctl, &cluster_bg);
7912 if (cluster_bg && cluster_bg != block_group) {
7913 btrfs_release_block_group(block_group,
7915 block_group = cluster_bg;
7918 } else if (ret == -EAGAIN) {
7919 goto have_block_group;
7920 } else if (ret > 0) {
7923 /* ret == -ENOENT case falls through */
7926 ret = find_free_extent_unclustered(block_group, last_ptr,
7929 goto have_block_group;
7932 /* ret == 0 case falls through */
7934 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
7935 fs_info->stripesize);
7937 /* move on to the next group */
7938 if (ffe_ctl.search_start + num_bytes >
7939 block_group->key.objectid + block_group->key.offset) {
7940 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7945 if (ffe_ctl.found_offset < ffe_ctl.search_start)
7946 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7947 ffe_ctl.search_start - ffe_ctl.found_offset);
7949 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7950 num_bytes, delalloc);
7951 if (ret == -EAGAIN) {
7952 btrfs_add_free_space(block_group, ffe_ctl.found_offset,
7956 btrfs_inc_block_group_reservations(block_group);
7958 /* we are all good, lets return */
7959 ins->objectid = ffe_ctl.search_start;
7960 ins->offset = num_bytes;
7962 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
7964 btrfs_release_block_group(block_group, delalloc);
7967 ffe_ctl.retry_clustered = false;
7968 ffe_ctl.retry_unclustered = false;
7969 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
7971 btrfs_release_block_group(block_group, delalloc);
7974 up_read(&space_info->groups_sem);
7976 ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
7977 full_search, use_cluster);
7981 if (ret == -ENOSPC) {
7983 * Use ffe_ctl->total_free_space as fallback if we can't find
7984 * any contiguous hole.
7986 if (!ffe_ctl.max_extent_size)
7987 ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
7988 spin_lock(&space_info->lock);
7989 space_info->max_extent_size = ffe_ctl.max_extent_size;
7990 spin_unlock(&space_info->lock);
7991 ins->offset = ffe_ctl.max_extent_size;
7996 #define DUMP_BLOCK_RSV(fs_info, rsv_name) \
7998 struct btrfs_block_rsv *__rsv = &(fs_info)->rsv_name; \
7999 spin_lock(&__rsv->lock); \
8000 btrfs_info(fs_info, #rsv_name ": size %llu reserved %llu", \
8001 __rsv->size, __rsv->reserved); \
8002 spin_unlock(&__rsv->lock); \
8005 static void dump_space_info(struct btrfs_fs_info *fs_info,
8006 struct btrfs_space_info *info, u64 bytes,
8007 int dump_block_groups)
8009 struct btrfs_block_group_cache *cache;
8012 spin_lock(&info->lock);
8013 btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
8015 info->total_bytes - btrfs_space_info_used(info, true),
8016 info->full ? "" : "not ");
8018 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
8019 info->total_bytes, info->bytes_used, info->bytes_pinned,
8020 info->bytes_reserved, info->bytes_may_use,
8021 info->bytes_readonly);
8022 spin_unlock(&info->lock);
8024 DUMP_BLOCK_RSV(fs_info, global_block_rsv);
8025 DUMP_BLOCK_RSV(fs_info, trans_block_rsv);
8026 DUMP_BLOCK_RSV(fs_info, chunk_block_rsv);
8027 DUMP_BLOCK_RSV(fs_info, delayed_block_rsv);
8028 DUMP_BLOCK_RSV(fs_info, delayed_refs_rsv);
8030 if (!dump_block_groups)
8033 down_read(&info->groups_sem);
8035 list_for_each_entry(cache, &info->block_groups[index], list) {
8036 spin_lock(&cache->lock);
8038 "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
8039 cache->key.objectid, cache->key.offset,
8040 btrfs_block_group_used(&cache->item), cache->pinned,
8041 cache->reserved, cache->ro ? "[readonly]" : "");
8042 btrfs_dump_free_space(cache, bytes);
8043 spin_unlock(&cache->lock);
8045 if (++index < BTRFS_NR_RAID_TYPES)
8047 up_read(&info->groups_sem);
8051 * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
8052 * hole that is at least as big as @num_bytes.
8054 * @root - The root that will contain this extent
8056 * @ram_bytes - The amount of space in ram that @num_bytes take. This
8057 * is used for accounting purposes. This value differs
8058 * from @num_bytes only in the case of compressed extents.
8060 * @num_bytes - Number of bytes to allocate on-disk.
8062 * @min_alloc_size - Indicates the minimum amount of space that the
8063 * allocator should try to satisfy. In some cases
8064 * @num_bytes may be larger than what is required and if
8065 * the filesystem is fragmented then allocation fails.
8066 * However, the presence of @min_alloc_size gives a
8067 * chance to try and satisfy the smaller allocation.
8069 * @empty_size - A hint that you plan on doing more COW. This is the
8070 * size in bytes the allocator should try to find free
8071 * next to the block it returns. This is just a hint and
8072 * may be ignored by the allocator.
8074 * @hint_byte - Hint to the allocator to start searching above the byte
8075 * address passed. It might be ignored.
8077 * @ins - This key is modified to record the found hole. It will
8078 * have the following values:
8079 * ins->objectid == start position
8080 * ins->flags = BTRFS_EXTENT_ITEM_KEY
8081 * ins->offset == the size of the hole.
8083 * @is_data - Boolean flag indicating whether an extent is
8084 * allocated for data (true) or metadata (false)
8086 * @delalloc - Boolean flag indicating whether this allocation is for
8087 * delalloc or not. If 'true' data_rwsem of block groups
8088 * is going to be acquired.
8091 * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
8092 * case -ENOSPC is returned then @ins->offset will contain the size of the
8093 * largest available hole the allocator managed to find.
8095 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
8096 u64 num_bytes, u64 min_alloc_size,
8097 u64 empty_size, u64 hint_byte,
8098 struct btrfs_key *ins, int is_data, int delalloc)
8100 struct btrfs_fs_info *fs_info = root->fs_info;
8101 bool final_tried = num_bytes == min_alloc_size;
8105 flags = get_alloc_profile_by_root(root, is_data);
8107 WARN_ON(num_bytes < fs_info->sectorsize);
8108 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
8109 hint_byte, ins, flags, delalloc);
8110 if (!ret && !is_data) {
8111 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
8112 } else if (ret == -ENOSPC) {
8113 if (!final_tried && ins->offset) {
8114 num_bytes = min(num_bytes >> 1, ins->offset);
8115 num_bytes = round_down(num_bytes,
8116 fs_info->sectorsize);
8117 num_bytes = max(num_bytes, min_alloc_size);
8118 ram_bytes = num_bytes;
8119 if (num_bytes == min_alloc_size)
8122 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8123 struct btrfs_space_info *sinfo;
8125 sinfo = __find_space_info(fs_info, flags);
8127 "allocation failed flags %llu, wanted %llu",
8130 dump_space_info(fs_info, sinfo, num_bytes, 1);
8137 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8139 int pin, int delalloc)
8141 struct btrfs_block_group_cache *cache;
8144 cache = btrfs_lookup_block_group(fs_info, start);
8146 btrfs_err(fs_info, "Unable to find block group for %llu",
8152 pin_down_extent(cache, start, len, 1);
8154 if (btrfs_test_opt(fs_info, DISCARD))
8155 ret = btrfs_discard_extent(fs_info, start, len, NULL);
8156 btrfs_add_free_space(cache, start, len);
8157 btrfs_free_reserved_bytes(cache, len, delalloc);
8158 trace_btrfs_reserved_extent_free(fs_info, start, len);
8161 btrfs_put_block_group(cache);
8165 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8166 u64 start, u64 len, int delalloc)
8168 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
8171 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
8174 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
8177 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8178 u64 parent, u64 root_objectid,
8179 u64 flags, u64 owner, u64 offset,
8180 struct btrfs_key *ins, int ref_mod)
8182 struct btrfs_fs_info *fs_info = trans->fs_info;
8184 struct btrfs_extent_item *extent_item;
8185 struct btrfs_extent_inline_ref *iref;
8186 struct btrfs_path *path;
8187 struct extent_buffer *leaf;
8192 type = BTRFS_SHARED_DATA_REF_KEY;
8194 type = BTRFS_EXTENT_DATA_REF_KEY;
8196 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
8198 path = btrfs_alloc_path();
8202 path->leave_spinning = 1;
8203 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8206 btrfs_free_path(path);
8210 leaf = path->nodes[0];
8211 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8212 struct btrfs_extent_item);
8213 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
8214 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8215 btrfs_set_extent_flags(leaf, extent_item,
8216 flags | BTRFS_EXTENT_FLAG_DATA);
8218 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8219 btrfs_set_extent_inline_ref_type(leaf, iref, type);
8221 struct btrfs_shared_data_ref *ref;
8222 ref = (struct btrfs_shared_data_ref *)(iref + 1);
8223 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8224 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
8226 struct btrfs_extent_data_ref *ref;
8227 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
8228 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
8229 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
8230 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
8231 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
8234 btrfs_mark_buffer_dirty(path->nodes[0]);
8235 btrfs_free_path(path);
8237 ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
8241 ret = update_block_group(trans, ins->objectid, ins->offset, 1);
8242 if (ret) { /* -ENOENT, logic error */
8243 btrfs_err(fs_info, "update block group failed for %llu %llu",
8244 ins->objectid, ins->offset);
8247 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
8251 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
8252 struct btrfs_delayed_ref_node *node,
8253 struct btrfs_delayed_extent_op *extent_op)
8255 struct btrfs_fs_info *fs_info = trans->fs_info;
8257 struct btrfs_extent_item *extent_item;
8258 struct btrfs_key extent_key;
8259 struct btrfs_tree_block_info *block_info;
8260 struct btrfs_extent_inline_ref *iref;
8261 struct btrfs_path *path;
8262 struct extent_buffer *leaf;
8263 struct btrfs_delayed_tree_ref *ref;
8264 u32 size = sizeof(*extent_item) + sizeof(*iref);
8266 u64 flags = extent_op->flags_to_set;
8267 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8269 ref = btrfs_delayed_node_to_tree_ref(node);
8271 extent_key.objectid = node->bytenr;
8272 if (skinny_metadata) {
8273 extent_key.offset = ref->level;
8274 extent_key.type = BTRFS_METADATA_ITEM_KEY;
8275 num_bytes = fs_info->nodesize;
8277 extent_key.offset = node->num_bytes;
8278 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
8279 size += sizeof(*block_info);
8280 num_bytes = node->num_bytes;
8283 path = btrfs_alloc_path();
8287 path->leave_spinning = 1;
8288 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8291 btrfs_free_path(path);
8295 leaf = path->nodes[0];
8296 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8297 struct btrfs_extent_item);
8298 btrfs_set_extent_refs(leaf, extent_item, 1);
8299 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8300 btrfs_set_extent_flags(leaf, extent_item,
8301 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
8303 if (skinny_metadata) {
8304 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8306 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8307 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
8308 btrfs_set_tree_block_level(leaf, block_info, ref->level);
8309 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8312 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
8313 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8314 btrfs_set_extent_inline_ref_type(leaf, iref,
8315 BTRFS_SHARED_BLOCK_REF_KEY);
8316 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
8318 btrfs_set_extent_inline_ref_type(leaf, iref,
8319 BTRFS_TREE_BLOCK_REF_KEY);
8320 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
8323 btrfs_mark_buffer_dirty(leaf);
8324 btrfs_free_path(path);
8326 ret = remove_from_free_space_tree(trans, extent_key.objectid,
8331 ret = update_block_group(trans, extent_key.objectid,
8332 fs_info->nodesize, 1);
8333 if (ret) { /* -ENOENT, logic error */
8334 btrfs_err(fs_info, "update block group failed for %llu %llu",
8335 extent_key.objectid, extent_key.offset);
8339 trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
8344 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8345 struct btrfs_root *root, u64 owner,
8346 u64 offset, u64 ram_bytes,
8347 struct btrfs_key *ins)
8349 struct btrfs_ref generic_ref = { 0 };
8352 BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
8354 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
8355 ins->objectid, ins->offset, 0);
8356 btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
8357 btrfs_ref_tree_mod(root->fs_info, &generic_ref);
8358 ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
8359 ram_bytes, NULL, NULL);
8364 * this is used by the tree logging recovery code. It records that
8365 * an extent has been allocated and makes sure to clear the free
8366 * space cache bits as well
8368 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
8369 u64 root_objectid, u64 owner, u64 offset,
8370 struct btrfs_key *ins)
8372 struct btrfs_fs_info *fs_info = trans->fs_info;
8374 struct btrfs_block_group_cache *block_group;
8375 struct btrfs_space_info *space_info;
8378 * Mixed block groups will exclude before processing the log so we only
8379 * need to do the exclude dance if this fs isn't mixed.
8381 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8382 ret = __exclude_logged_extent(fs_info, ins->objectid,
8388 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8392 space_info = block_group->space_info;
8393 spin_lock(&space_info->lock);
8394 spin_lock(&block_group->lock);
8395 space_info->bytes_reserved += ins->offset;
8396 block_group->reserved += ins->offset;
8397 spin_unlock(&block_group->lock);
8398 spin_unlock(&space_info->lock);
8400 ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
8402 btrfs_put_block_group(block_group);
8406 static struct extent_buffer *
8407 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
8408 u64 bytenr, int level, u64 owner)
8410 struct btrfs_fs_info *fs_info = root->fs_info;
8411 struct extent_buffer *buf;
8413 buf = btrfs_find_create_tree_block(fs_info, bytenr);
8418 * Extra safety check in case the extent tree is corrupted and extent
8419 * allocator chooses to use a tree block which is already used and
8422 if (buf->lock_owner == current->pid) {
8423 btrfs_err_rl(fs_info,
8424 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
8425 buf->start, btrfs_header_owner(buf), current->pid);
8426 free_extent_buffer(buf);
8427 return ERR_PTR(-EUCLEAN);
8430 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
8431 btrfs_tree_lock(buf);
8432 btrfs_clean_tree_block(buf);
8433 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
8435 btrfs_set_lock_blocking_write(buf);
8436 set_extent_buffer_uptodate(buf);
8438 memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
8439 btrfs_set_header_level(buf, level);
8440 btrfs_set_header_bytenr(buf, buf->start);
8441 btrfs_set_header_generation(buf, trans->transid);
8442 btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
8443 btrfs_set_header_owner(buf, owner);
8444 write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
8445 write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
8446 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8447 buf->log_index = root->log_transid % 2;
8449 * we allow two log transactions at a time, use different
8450 * EXTENT bit to differentiate dirty pages.
8452 if (buf->log_index == 0)
8453 set_extent_dirty(&root->dirty_log_pages, buf->start,
8454 buf->start + buf->len - 1, GFP_NOFS);
8456 set_extent_new(&root->dirty_log_pages, buf->start,
8457 buf->start + buf->len - 1);
8459 buf->log_index = -1;
8460 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
8461 buf->start + buf->len - 1, GFP_NOFS);
8463 trans->dirty = true;
8464 /* this returns a buffer locked for blocking */
8468 static struct btrfs_block_rsv *
8469 use_block_rsv(struct btrfs_trans_handle *trans,
8470 struct btrfs_root *root, u32 blocksize)
8472 struct btrfs_fs_info *fs_info = root->fs_info;
8473 struct btrfs_block_rsv *block_rsv;
8474 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8476 bool global_updated = false;
8478 block_rsv = get_block_rsv(trans, root);
8480 if (unlikely(block_rsv->size == 0))
8483 ret = block_rsv_use_bytes(block_rsv, blocksize);
8487 if (block_rsv->failfast)
8488 return ERR_PTR(ret);
8490 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8491 global_updated = true;
8492 update_global_block_rsv(fs_info);
8497 * The global reserve still exists to save us from ourselves, so don't
8498 * warn_on if we are short on our delayed refs reserve.
8500 if (block_rsv->type != BTRFS_BLOCK_RSV_DELREFS &&
8501 btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8502 static DEFINE_RATELIMIT_STATE(_rs,
8503 DEFAULT_RATELIMIT_INTERVAL * 10,
8504 /*DEFAULT_RATELIMIT_BURST*/ 1);
8505 if (__ratelimit(&_rs))
8507 "BTRFS: block rsv returned %d\n", ret);
8510 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8511 BTRFS_RESERVE_NO_FLUSH);
8515 * If we couldn't reserve metadata bytes try and use some from
8516 * the global reserve if its space type is the same as the global
8519 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8520 block_rsv->space_info == global_rsv->space_info) {
8521 ret = block_rsv_use_bytes(global_rsv, blocksize);
8525 return ERR_PTR(ret);
8528 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8529 struct btrfs_block_rsv *block_rsv, u32 blocksize)
8531 block_rsv_add_bytes(block_rsv, blocksize, false);
8532 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0, NULL);
8536 * finds a free extent and does all the dirty work required for allocation
8537 * returns the tree buffer or an ERR_PTR on error.
8539 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
8540 struct btrfs_root *root,
8541 u64 parent, u64 root_objectid,
8542 const struct btrfs_disk_key *key,
8543 int level, u64 hint,
8546 struct btrfs_fs_info *fs_info = root->fs_info;
8547 struct btrfs_key ins;
8548 struct btrfs_block_rsv *block_rsv;
8549 struct extent_buffer *buf;
8550 struct btrfs_delayed_extent_op *extent_op;
8551 struct btrfs_ref generic_ref = { 0 };
8554 u32 blocksize = fs_info->nodesize;
8555 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8557 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8558 if (btrfs_is_testing(fs_info)) {
8559 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
8560 level, root_objectid);
8562 root->alloc_bytenr += blocksize;
8567 block_rsv = use_block_rsv(trans, root, blocksize);
8568 if (IS_ERR(block_rsv))
8569 return ERR_CAST(block_rsv);
8571 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
8572 empty_size, hint, &ins, 0, 0);
8576 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
8580 goto out_free_reserved;
8583 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8585 parent = ins.objectid;
8586 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8590 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
8591 extent_op = btrfs_alloc_delayed_extent_op();
8597 memcpy(&extent_op->key, key, sizeof(extent_op->key));
8599 memset(&extent_op->key, 0, sizeof(extent_op->key));
8600 extent_op->flags_to_set = flags;
8601 extent_op->update_key = skinny_metadata ? false : true;
8602 extent_op->update_flags = true;
8603 extent_op->is_data = false;
8604 extent_op->level = level;
8606 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
8607 ins.objectid, ins.offset, parent);
8608 generic_ref.real_root = root->root_key.objectid;
8609 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
8610 btrfs_ref_tree_mod(fs_info, &generic_ref);
8611 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
8612 extent_op, NULL, NULL);
8614 goto out_free_delayed;
8619 btrfs_free_delayed_extent_op(extent_op);
8621 free_extent_buffer(buf);
8623 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
8625 unuse_block_rsv(fs_info, block_rsv, blocksize);
8626 return ERR_PTR(ret);
8629 struct walk_control {
8630 u64 refs[BTRFS_MAX_LEVEL];
8631 u64 flags[BTRFS_MAX_LEVEL];
8632 struct btrfs_key update_progress;
8633 struct btrfs_key drop_progress;
8645 #define DROP_REFERENCE 1
8646 #define UPDATE_BACKREF 2
8648 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8649 struct btrfs_root *root,
8650 struct walk_control *wc,
8651 struct btrfs_path *path)
8653 struct btrfs_fs_info *fs_info = root->fs_info;
8659 struct btrfs_key key;
8660 struct extent_buffer *eb;
8665 if (path->slots[wc->level] < wc->reada_slot) {
8666 wc->reada_count = wc->reada_count * 2 / 3;
8667 wc->reada_count = max(wc->reada_count, 2);
8669 wc->reada_count = wc->reada_count * 3 / 2;
8670 wc->reada_count = min_t(int, wc->reada_count,
8671 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
8674 eb = path->nodes[wc->level];
8675 nritems = btrfs_header_nritems(eb);
8677 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8678 if (nread >= wc->reada_count)
8682 bytenr = btrfs_node_blockptr(eb, slot);
8683 generation = btrfs_node_ptr_generation(eb, slot);
8685 if (slot == path->slots[wc->level])
8688 if (wc->stage == UPDATE_BACKREF &&
8689 generation <= root->root_key.offset)
8692 /* We don't lock the tree block, it's OK to be racy here */
8693 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
8694 wc->level - 1, 1, &refs,
8696 /* We don't care about errors in readahead. */
8701 if (wc->stage == DROP_REFERENCE) {
8705 if (wc->level == 1 &&
8706 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8708 if (!wc->update_ref ||
8709 generation <= root->root_key.offset)
8711 btrfs_node_key_to_cpu(eb, &key, slot);
8712 ret = btrfs_comp_cpu_keys(&key,
8713 &wc->update_progress);
8717 if (wc->level == 1 &&
8718 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8722 readahead_tree_block(fs_info, bytenr);
8725 wc->reada_slot = slot;
8729 * helper to process tree block while walking down the tree.
8731 * when wc->stage == UPDATE_BACKREF, this function updates
8732 * back refs for pointers in the block.
8734 * NOTE: return value 1 means we should stop walking down.
8736 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8737 struct btrfs_root *root,
8738 struct btrfs_path *path,
8739 struct walk_control *wc, int lookup_info)
8741 struct btrfs_fs_info *fs_info = root->fs_info;
8742 int level = wc->level;
8743 struct extent_buffer *eb = path->nodes[level];
8744 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8747 if (wc->stage == UPDATE_BACKREF &&
8748 btrfs_header_owner(eb) != root->root_key.objectid)
8752 * when reference count of tree block is 1, it won't increase
8753 * again. once full backref flag is set, we never clear it.
8756 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8757 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8758 BUG_ON(!path->locks[level]);
8759 ret = btrfs_lookup_extent_info(trans, fs_info,
8760 eb->start, level, 1,
8763 BUG_ON(ret == -ENOMEM);
8766 BUG_ON(wc->refs[level] == 0);
8769 if (wc->stage == DROP_REFERENCE) {
8770 if (wc->refs[level] > 1)
8773 if (path->locks[level] && !wc->keep_locks) {
8774 btrfs_tree_unlock_rw(eb, path->locks[level]);
8775 path->locks[level] = 0;
8780 /* wc->stage == UPDATE_BACKREF */
8781 if (!(wc->flags[level] & flag)) {
8782 BUG_ON(!path->locks[level]);
8783 ret = btrfs_inc_ref(trans, root, eb, 1);
8784 BUG_ON(ret); /* -ENOMEM */
8785 ret = btrfs_dec_ref(trans, root, eb, 0);
8786 BUG_ON(ret); /* -ENOMEM */
8787 ret = btrfs_set_disk_extent_flags(trans, eb->start,
8789 btrfs_header_level(eb), 0);
8790 BUG_ON(ret); /* -ENOMEM */
8791 wc->flags[level] |= flag;
8795 * the block is shared by multiple trees, so it's not good to
8796 * keep the tree lock
8798 if (path->locks[level] && level > 0) {
8799 btrfs_tree_unlock_rw(eb, path->locks[level]);
8800 path->locks[level] = 0;
8806 * This is used to verify a ref exists for this root to deal with a bug where we
8807 * would have a drop_progress key that hadn't been updated properly.
8809 static int check_ref_exists(struct btrfs_trans_handle *trans,
8810 struct btrfs_root *root, u64 bytenr, u64 parent,
8813 struct btrfs_path *path;
8814 struct btrfs_extent_inline_ref *iref;
8817 path = btrfs_alloc_path();
8821 ret = lookup_extent_backref(trans, path, &iref, bytenr,
8822 root->fs_info->nodesize, parent,
8823 root->root_key.objectid, level, 0);
8824 btrfs_free_path(path);
8833 * helper to process tree block pointer.
8835 * when wc->stage == DROP_REFERENCE, this function checks
8836 * reference count of the block pointed to. if the block
8837 * is shared and we need update back refs for the subtree
8838 * rooted at the block, this function changes wc->stage to
8839 * UPDATE_BACKREF. if the block is shared and there is no
8840 * need to update back, this function drops the reference
8843 * NOTE: return value 1 means we should stop walking down.
8845 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8846 struct btrfs_root *root,
8847 struct btrfs_path *path,
8848 struct walk_control *wc, int *lookup_info)
8850 struct btrfs_fs_info *fs_info = root->fs_info;
8854 struct btrfs_key key;
8855 struct btrfs_key first_key;
8856 struct btrfs_ref ref = { 0 };
8857 struct extent_buffer *next;
8858 int level = wc->level;
8861 bool need_account = false;
8863 generation = btrfs_node_ptr_generation(path->nodes[level],
8864 path->slots[level]);
8866 * if the lower level block was created before the snapshot
8867 * was created, we know there is no need to update back refs
8870 if (wc->stage == UPDATE_BACKREF &&
8871 generation <= root->root_key.offset) {
8876 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8877 btrfs_node_key_to_cpu(path->nodes[level], &first_key,
8878 path->slots[level]);
8880 next = find_extent_buffer(fs_info, bytenr);
8882 next = btrfs_find_create_tree_block(fs_info, bytenr);
8884 return PTR_ERR(next);
8886 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8890 btrfs_tree_lock(next);
8891 btrfs_set_lock_blocking_write(next);
8893 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
8894 &wc->refs[level - 1],
8895 &wc->flags[level - 1]);
8899 if (unlikely(wc->refs[level - 1] == 0)) {
8900 btrfs_err(fs_info, "Missing references.");
8906 if (wc->stage == DROP_REFERENCE) {
8907 if (wc->refs[level - 1] > 1) {
8908 need_account = true;
8910 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8913 if (!wc->update_ref ||
8914 generation <= root->root_key.offset)
8917 btrfs_node_key_to_cpu(path->nodes[level], &key,
8918 path->slots[level]);
8919 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8923 wc->stage = UPDATE_BACKREF;
8924 wc->shared_level = level - 1;
8928 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8932 if (!btrfs_buffer_uptodate(next, generation, 0)) {
8933 btrfs_tree_unlock(next);
8934 free_extent_buffer(next);
8940 if (reada && level == 1)
8941 reada_walk_down(trans, root, wc, path);
8942 next = read_tree_block(fs_info, bytenr, generation, level - 1,
8945 return PTR_ERR(next);
8946 } else if (!extent_buffer_uptodate(next)) {
8947 free_extent_buffer(next);
8950 btrfs_tree_lock(next);
8951 btrfs_set_lock_blocking_write(next);
8955 ASSERT(level == btrfs_header_level(next));
8956 if (level != btrfs_header_level(next)) {
8957 btrfs_err(root->fs_info, "mismatched level");
8961 path->nodes[level] = next;
8962 path->slots[level] = 0;
8963 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8969 wc->refs[level - 1] = 0;
8970 wc->flags[level - 1] = 0;
8971 if (wc->stage == DROP_REFERENCE) {
8972 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8973 parent = path->nodes[level]->start;
8975 ASSERT(root->root_key.objectid ==
8976 btrfs_header_owner(path->nodes[level]));
8977 if (root->root_key.objectid !=
8978 btrfs_header_owner(path->nodes[level])) {
8979 btrfs_err(root->fs_info,
8980 "mismatched block owner");
8988 * If we had a drop_progress we need to verify the refs are set
8989 * as expected. If we find our ref then we know that from here
8990 * on out everything should be correct, and we can clear the
8993 if (wc->restarted) {
8994 ret = check_ref_exists(trans, root, bytenr, parent,
9005 * Reloc tree doesn't contribute to qgroup numbers, and we have
9006 * already accounted them at merge time (replace_path),
9007 * thus we could skip expensive subtree trace here.
9009 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
9011 ret = btrfs_qgroup_trace_subtree(trans, next,
9012 generation, level - 1);
9014 btrfs_err_rl(fs_info,
9015 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
9021 * We need to update the next key in our walk control so we can
9022 * update the drop_progress key accordingly. We don't care if
9023 * find_next_key doesn't find a key because that means we're at
9024 * the end and are going to clean up now.
9026 wc->drop_level = level;
9027 find_next_key(path, level, &wc->drop_progress);
9029 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
9030 fs_info->nodesize, parent);
9031 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
9032 ret = btrfs_free_extent(trans, &ref);
9041 btrfs_tree_unlock(next);
9042 free_extent_buffer(next);
9048 * helper to process tree block while walking up the tree.
9050 * when wc->stage == DROP_REFERENCE, this function drops
9051 * reference count on the block.
9053 * when wc->stage == UPDATE_BACKREF, this function changes
9054 * wc->stage back to DROP_REFERENCE if we changed wc->stage
9055 * to UPDATE_BACKREF previously while processing the block.
9057 * NOTE: return value 1 means we should stop walking up.
9059 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
9060 struct btrfs_root *root,
9061 struct btrfs_path *path,
9062 struct walk_control *wc)
9064 struct btrfs_fs_info *fs_info = root->fs_info;
9066 int level = wc->level;
9067 struct extent_buffer *eb = path->nodes[level];
9070 if (wc->stage == UPDATE_BACKREF) {
9071 BUG_ON(wc->shared_level < level);
9072 if (level < wc->shared_level)
9075 ret = find_next_key(path, level + 1, &wc->update_progress);
9079 wc->stage = DROP_REFERENCE;
9080 wc->shared_level = -1;
9081 path->slots[level] = 0;
9084 * check reference count again if the block isn't locked.
9085 * we should start walking down the tree again if reference
9088 if (!path->locks[level]) {
9090 btrfs_tree_lock(eb);
9091 btrfs_set_lock_blocking_write(eb);
9092 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9094 ret = btrfs_lookup_extent_info(trans, fs_info,
9095 eb->start, level, 1,
9099 btrfs_tree_unlock_rw(eb, path->locks[level]);
9100 path->locks[level] = 0;
9103 BUG_ON(wc->refs[level] == 0);
9104 if (wc->refs[level] == 1) {
9105 btrfs_tree_unlock_rw(eb, path->locks[level]);
9106 path->locks[level] = 0;
9112 /* wc->stage == DROP_REFERENCE */
9113 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
9115 if (wc->refs[level] == 1) {
9117 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9118 ret = btrfs_dec_ref(trans, root, eb, 1);
9120 ret = btrfs_dec_ref(trans, root, eb, 0);
9121 BUG_ON(ret); /* -ENOMEM */
9122 if (is_fstree(root->root_key.objectid)) {
9123 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
9125 btrfs_err_rl(fs_info,
9126 "error %d accounting leaf items, quota is out of sync, rescan required",
9131 /* make block locked assertion in btrfs_clean_tree_block happy */
9132 if (!path->locks[level] &&
9133 btrfs_header_generation(eb) == trans->transid) {
9134 btrfs_tree_lock(eb);
9135 btrfs_set_lock_blocking_write(eb);
9136 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9138 btrfs_clean_tree_block(eb);
9141 if (eb == root->node) {
9142 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9144 else if (root->root_key.objectid != btrfs_header_owner(eb))
9145 goto owner_mismatch;
9147 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
9148 parent = path->nodes[level + 1]->start;
9149 else if (root->root_key.objectid !=
9150 btrfs_header_owner(path->nodes[level + 1]))
9151 goto owner_mismatch;
9154 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
9156 wc->refs[level] = 0;
9157 wc->flags[level] = 0;
9161 btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
9162 btrfs_header_owner(eb), root->root_key.objectid);
9166 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
9167 struct btrfs_root *root,
9168 struct btrfs_path *path,
9169 struct walk_control *wc)
9171 int level = wc->level;
9172 int lookup_info = 1;
9175 while (level >= 0) {
9176 ret = walk_down_proc(trans, root, path, wc, lookup_info);
9183 if (path->slots[level] >=
9184 btrfs_header_nritems(path->nodes[level]))
9187 ret = do_walk_down(trans, root, path, wc, &lookup_info);
9189 path->slots[level]++;
9198 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
9199 struct btrfs_root *root,
9200 struct btrfs_path *path,
9201 struct walk_control *wc, int max_level)
9203 int level = wc->level;
9206 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
9207 while (level < max_level && path->nodes[level]) {
9209 if (path->slots[level] + 1 <
9210 btrfs_header_nritems(path->nodes[level])) {
9211 path->slots[level]++;
9214 ret = walk_up_proc(trans, root, path, wc);
9220 if (path->locks[level]) {
9221 btrfs_tree_unlock_rw(path->nodes[level],
9222 path->locks[level]);
9223 path->locks[level] = 0;
9225 free_extent_buffer(path->nodes[level]);
9226 path->nodes[level] = NULL;
9234 * drop a subvolume tree.
9236 * this function traverses the tree freeing any blocks that only
9237 * referenced by the tree.
9239 * when a shared tree block is found. this function decreases its
9240 * reference count by one. if update_ref is true, this function
9241 * also make sure backrefs for the shared block and all lower level
9242 * blocks are properly updated.
9244 * If called with for_reloc == 0, may exit early with -EAGAIN
9246 int btrfs_drop_snapshot(struct btrfs_root *root,
9247 struct btrfs_block_rsv *block_rsv, int update_ref,
9250 struct btrfs_fs_info *fs_info = root->fs_info;
9251 struct btrfs_path *path;
9252 struct btrfs_trans_handle *trans;
9253 struct btrfs_root *tree_root = fs_info->tree_root;
9254 struct btrfs_root_item *root_item = &root->root_item;
9255 struct walk_control *wc;
9256 struct btrfs_key key;
9260 bool root_dropped = false;
9262 btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
9264 path = btrfs_alloc_path();
9270 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9272 btrfs_free_path(path);
9277 trans = btrfs_start_transaction(tree_root, 0);
9278 if (IS_ERR(trans)) {
9279 err = PTR_ERR(trans);
9283 err = btrfs_run_delayed_items(trans);
9288 trans->block_rsv = block_rsv;
9291 * This will help us catch people modifying the fs tree while we're
9292 * dropping it. It is unsafe to mess with the fs tree while it's being
9293 * dropped as we unlock the root node and parent nodes as we walk down
9294 * the tree, assuming nothing will change. If something does change
9295 * then we'll have stale information and drop references to blocks we've
9298 set_bit(BTRFS_ROOT_DELETING, &root->state);
9299 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
9300 level = btrfs_header_level(root->node);
9301 path->nodes[level] = btrfs_lock_root_node(root);
9302 btrfs_set_lock_blocking_write(path->nodes[level]);
9303 path->slots[level] = 0;
9304 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9305 memset(&wc->update_progress, 0,
9306 sizeof(wc->update_progress));
9308 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
9309 memcpy(&wc->update_progress, &key,
9310 sizeof(wc->update_progress));
9312 level = root_item->drop_level;
9314 path->lowest_level = level;
9315 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
9316 path->lowest_level = 0;
9324 * unlock our path, this is safe because only this
9325 * function is allowed to delete this snapshot
9327 btrfs_unlock_up_safe(path, 0);
9329 level = btrfs_header_level(root->node);
9331 btrfs_tree_lock(path->nodes[level]);
9332 btrfs_set_lock_blocking_write(path->nodes[level]);
9333 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9335 ret = btrfs_lookup_extent_info(trans, fs_info,
9336 path->nodes[level]->start,
9337 level, 1, &wc->refs[level],
9343 BUG_ON(wc->refs[level] == 0);
9345 if (level == root_item->drop_level)
9348 btrfs_tree_unlock(path->nodes[level]);
9349 path->locks[level] = 0;
9350 WARN_ON(wc->refs[level] != 1);
9355 wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
9357 wc->shared_level = -1;
9358 wc->stage = DROP_REFERENCE;
9359 wc->update_ref = update_ref;
9361 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9365 ret = walk_down_tree(trans, root, path, wc);
9371 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9378 BUG_ON(wc->stage != DROP_REFERENCE);
9382 if (wc->stage == DROP_REFERENCE) {
9383 wc->drop_level = wc->level;
9384 btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
9386 path->slots[wc->drop_level]);
9388 btrfs_cpu_key_to_disk(&root_item->drop_progress,
9389 &wc->drop_progress);
9390 root_item->drop_level = wc->drop_level;
9392 BUG_ON(wc->level == 0);
9393 if (btrfs_should_end_transaction(trans) ||
9394 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
9395 ret = btrfs_update_root(trans, tree_root,
9399 btrfs_abort_transaction(trans, ret);
9404 btrfs_end_transaction_throttle(trans);
9405 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
9406 btrfs_debug(fs_info,
9407 "drop snapshot early exit");
9412 trans = btrfs_start_transaction(tree_root, 0);
9413 if (IS_ERR(trans)) {
9414 err = PTR_ERR(trans);
9418 trans->block_rsv = block_rsv;
9421 btrfs_release_path(path);
9425 ret = btrfs_del_root(trans, &root->root_key);
9427 btrfs_abort_transaction(trans, ret);
9432 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
9433 ret = btrfs_find_root(tree_root, &root->root_key, path,
9436 btrfs_abort_transaction(trans, ret);
9439 } else if (ret > 0) {
9440 /* if we fail to delete the orphan item this time
9441 * around, it'll get picked up the next time.
9443 * The most common failure here is just -ENOENT.
9445 btrfs_del_orphan_item(trans, tree_root,
9446 root->root_key.objectid);
9450 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
9451 btrfs_add_dropped_root(trans, root);
9453 free_extent_buffer(root->node);
9454 free_extent_buffer(root->commit_root);
9455 btrfs_put_fs_root(root);
9457 root_dropped = true;
9459 btrfs_end_transaction_throttle(trans);
9462 btrfs_free_path(path);
9465 * So if we need to stop dropping the snapshot for whatever reason we
9466 * need to make sure to add it back to the dead root list so that we
9467 * keep trying to do the work later. This also cleans up roots if we
9468 * don't have it in the radix (like when we recover after a power fail
9469 * or unmount) so we don't leak memory.
9471 if (!for_reloc && !root_dropped)
9472 btrfs_add_dead_root(root);
9473 if (err && err != -EAGAIN)
9474 btrfs_handle_fs_error(fs_info, err, NULL);
9479 * drop subtree rooted at tree block 'node'.
9481 * NOTE: this function will unlock and release tree block 'node'
9482 * only used by relocation code
9484 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9485 struct btrfs_root *root,
9486 struct extent_buffer *node,
9487 struct extent_buffer *parent)
9489 struct btrfs_fs_info *fs_info = root->fs_info;
9490 struct btrfs_path *path;
9491 struct walk_control *wc;
9497 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9499 path = btrfs_alloc_path();
9503 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9505 btrfs_free_path(path);
9509 btrfs_assert_tree_locked(parent);
9510 parent_level = btrfs_header_level(parent);
9511 extent_buffer_get(parent);
9512 path->nodes[parent_level] = parent;
9513 path->slots[parent_level] = btrfs_header_nritems(parent);
9515 btrfs_assert_tree_locked(node);
9516 level = btrfs_header_level(node);
9517 path->nodes[level] = node;
9518 path->slots[level] = 0;
9519 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9521 wc->refs[parent_level] = 1;
9522 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9524 wc->shared_level = -1;
9525 wc->stage = DROP_REFERENCE;
9528 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9531 wret = walk_down_tree(trans, root, path, wc);
9537 wret = walk_up_tree(trans, root, path, wc, parent_level);
9545 btrfs_free_path(path);
9549 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
9555 * if restripe for this chunk_type is on pick target profile and
9556 * return, otherwise do the usual balance
9558 stripped = get_restripe_target(fs_info, flags);
9560 return extended_to_chunk(stripped);
9562 num_devices = fs_info->fs_devices->rw_devices;
9564 stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
9565 BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
9567 if (num_devices == 1) {
9568 stripped |= BTRFS_BLOCK_GROUP_DUP;
9569 stripped = flags & ~stripped;
9571 /* turn raid0 into single device chunks */
9572 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9575 /* turn mirroring into duplication */
9576 if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
9577 BTRFS_BLOCK_GROUP_RAID10))
9578 return stripped | BTRFS_BLOCK_GROUP_DUP;
9580 /* they already had raid on here, just return */
9581 if (flags & stripped)
9584 stripped |= BTRFS_BLOCK_GROUP_DUP;
9585 stripped = flags & ~stripped;
9587 /* switch duplicated blocks with raid1 */
9588 if (flags & BTRFS_BLOCK_GROUP_DUP)
9589 return stripped | BTRFS_BLOCK_GROUP_RAID1;
9591 /* this is drive concat, leave it alone */
9597 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9599 struct btrfs_space_info *sinfo = cache->space_info;
9602 u64 min_allocable_bytes;
9606 * We need some metadata space and system metadata space for
9607 * allocating chunks in some corner cases until we force to set
9608 * it to be readonly.
9611 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9613 min_allocable_bytes = SZ_1M;
9615 min_allocable_bytes = 0;
9617 spin_lock(&sinfo->lock);
9618 spin_lock(&cache->lock);
9626 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9627 cache->bytes_super - btrfs_block_group_used(&cache->item);
9628 sinfo_used = btrfs_space_info_used(sinfo, true);
9630 if (sinfo_used + num_bytes + min_allocable_bytes <=
9631 sinfo->total_bytes) {
9632 sinfo->bytes_readonly += num_bytes;
9634 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9638 spin_unlock(&cache->lock);
9639 spin_unlock(&sinfo->lock);
9640 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
9641 btrfs_info(cache->fs_info,
9642 "unable to make block group %llu ro",
9643 cache->key.objectid);
9644 btrfs_info(cache->fs_info,
9645 "sinfo_used=%llu bg_num_bytes=%llu min_allocable=%llu",
9646 sinfo_used, num_bytes, min_allocable_bytes);
9647 dump_space_info(cache->fs_info, cache->space_info, 0, 0);
9652 int btrfs_inc_block_group_ro(struct btrfs_block_group_cache *cache)
9655 struct btrfs_fs_info *fs_info = cache->fs_info;
9656 struct btrfs_trans_handle *trans;
9661 trans = btrfs_join_transaction(fs_info->extent_root);
9663 return PTR_ERR(trans);
9666 * we're not allowed to set block groups readonly after the dirty
9667 * block groups cache has started writing. If it already started,
9668 * back off and let this transaction commit
9670 mutex_lock(&fs_info->ro_block_group_mutex);
9671 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
9672 u64 transid = trans->transid;
9674 mutex_unlock(&fs_info->ro_block_group_mutex);
9675 btrfs_end_transaction(trans);
9677 ret = btrfs_wait_for_commit(fs_info, transid);
9684 * if we are changing raid levels, try to allocate a corresponding
9685 * block group with the new raid level.
9687 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9688 if (alloc_flags != cache->flags) {
9689 ret = do_chunk_alloc(trans, alloc_flags,
9692 * ENOSPC is allowed here, we may have enough space
9693 * already allocated at the new raid level to
9702 ret = inc_block_group_ro(cache, 0);
9705 alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
9706 ret = do_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9709 ret = inc_block_group_ro(cache, 0);
9711 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9712 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9713 mutex_lock(&fs_info->chunk_mutex);
9714 check_system_chunk(trans, alloc_flags);
9715 mutex_unlock(&fs_info->chunk_mutex);
9717 mutex_unlock(&fs_info->ro_block_group_mutex);
9719 btrfs_end_transaction(trans);
9723 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
9725 u64 alloc_flags = get_alloc_profile(trans->fs_info, type);
9727 return do_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
9731 * helper to account the unused space of all the readonly block group in the
9732 * space_info. takes mirrors into account.
9734 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
9736 struct btrfs_block_group_cache *block_group;
9740 /* It's df, we don't care if it's racy */
9741 if (list_empty(&sinfo->ro_bgs))
9744 spin_lock(&sinfo->lock);
9745 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
9746 spin_lock(&block_group->lock);
9748 if (!block_group->ro) {
9749 spin_unlock(&block_group->lock);
9753 factor = btrfs_bg_type_to_factor(block_group->flags);
9754 free_bytes += (block_group->key.offset -
9755 btrfs_block_group_used(&block_group->item)) *
9758 spin_unlock(&block_group->lock);
9760 spin_unlock(&sinfo->lock);
9765 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
9767 struct btrfs_space_info *sinfo = cache->space_info;
9772 spin_lock(&sinfo->lock);
9773 spin_lock(&cache->lock);
9775 num_bytes = cache->key.offset - cache->reserved -
9776 cache->pinned - cache->bytes_super -
9777 btrfs_block_group_used(&cache->item);
9778 sinfo->bytes_readonly -= num_bytes;
9779 list_del_init(&cache->ro_list);
9781 spin_unlock(&cache->lock);
9782 spin_unlock(&sinfo->lock);
9786 * Checks to see if it's even possible to relocate this block group.
9788 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9789 * ok to go ahead and try.
9791 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
9793 struct btrfs_block_group_cache *block_group;
9794 struct btrfs_space_info *space_info;
9795 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
9796 struct btrfs_device *device;
9806 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
9808 block_group = btrfs_lookup_block_group(fs_info, bytenr);
9810 /* odd, couldn't find the block group, leave it alone */
9814 "can't find block group for bytenr %llu",
9819 min_free = btrfs_block_group_used(&block_group->item);
9821 /* no bytes used, we're good */
9825 space_info = block_group->space_info;
9826 spin_lock(&space_info->lock);
9828 full = space_info->full;
9831 * if this is the last block group we have in this space, we can't
9832 * relocate it unless we're able to allocate a new chunk below.
9834 * Otherwise, we need to make sure we have room in the space to handle
9835 * all of the extents from this block group. If we can, we're good
9837 if ((space_info->total_bytes != block_group->key.offset) &&
9838 (btrfs_space_info_used(space_info, false) + min_free <
9839 space_info->total_bytes)) {
9840 spin_unlock(&space_info->lock);
9843 spin_unlock(&space_info->lock);
9846 * ok we don't have enough space, but maybe we have free space on our
9847 * devices to allocate new chunks for relocation, so loop through our
9848 * alloc devices and guess if we have enough space. if this block
9849 * group is going to be restriped, run checks against the target
9850 * profile instead of the current one.
9862 target = get_restripe_target(fs_info, block_group->flags);
9864 index = btrfs_bg_flags_to_raid_index(extended_to_chunk(target));
9867 * this is just a balance, so if we were marked as full
9868 * we know there is no space for a new chunk
9873 "no space to alloc new chunk for block group %llu",
9874 block_group->key.objectid);
9878 index = btrfs_bg_flags_to_raid_index(block_group->flags);
9881 if (index == BTRFS_RAID_RAID10) {
9885 } else if (index == BTRFS_RAID_RAID1) {
9887 } else if (index == BTRFS_RAID_DUP) {
9890 } else if (index == BTRFS_RAID_RAID0) {
9891 dev_min = fs_devices->rw_devices;
9892 min_free = div64_u64(min_free, dev_min);
9895 mutex_lock(&fs_info->chunk_mutex);
9896 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
9900 * check to make sure we can actually find a chunk with enough
9901 * space to fit our block group in.
9903 if (device->total_bytes > device->bytes_used + min_free &&
9904 !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
9905 ret = find_free_dev_extent(device, min_free,
9910 if (dev_nr >= dev_min)
9916 if (debug && ret == -1)
9918 "no space to allocate a new chunk for block group %llu",
9919 block_group->key.objectid);
9920 mutex_unlock(&fs_info->chunk_mutex);
9922 btrfs_put_block_group(block_group);
9926 static int find_first_block_group(struct btrfs_fs_info *fs_info,
9927 struct btrfs_path *path,
9928 struct btrfs_key *key)
9930 struct btrfs_root *root = fs_info->extent_root;
9932 struct btrfs_key found_key;
9933 struct extent_buffer *leaf;
9934 struct btrfs_block_group_item bg;
9938 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9943 slot = path->slots[0];
9944 leaf = path->nodes[0];
9945 if (slot >= btrfs_header_nritems(leaf)) {
9946 ret = btrfs_next_leaf(root, path);
9953 btrfs_item_key_to_cpu(leaf, &found_key, slot);
9955 if (found_key.objectid >= key->objectid &&
9956 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9957 struct extent_map_tree *em_tree;
9958 struct extent_map *em;
9960 em_tree = &root->fs_info->mapping_tree;
9961 read_lock(&em_tree->lock);
9962 em = lookup_extent_mapping(em_tree, found_key.objectid,
9964 read_unlock(&em_tree->lock);
9967 "logical %llu len %llu found bg but no related chunk",
9968 found_key.objectid, found_key.offset);
9970 } else if (em->start != found_key.objectid ||
9971 em->len != found_key.offset) {
9973 "block group %llu len %llu mismatch with chunk %llu len %llu",
9974 found_key.objectid, found_key.offset,
9975 em->start, em->len);
9978 read_extent_buffer(leaf, &bg,
9979 btrfs_item_ptr_offset(leaf, slot),
9981 flags = btrfs_block_group_flags(&bg) &
9982 BTRFS_BLOCK_GROUP_TYPE_MASK;
9984 if (flags != (em->map_lookup->type &
9985 BTRFS_BLOCK_GROUP_TYPE_MASK)) {
9987 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
9989 found_key.offset, flags,
9990 (BTRFS_BLOCK_GROUP_TYPE_MASK &
9991 em->map_lookup->type));
9997 free_extent_map(em);
10006 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
10008 struct btrfs_block_group_cache *block_group;
10012 struct inode *inode;
10014 block_group = btrfs_lookup_first_block_group(info, last);
10015 while (block_group) {
10016 wait_block_group_cache_done(block_group);
10017 spin_lock(&block_group->lock);
10018 if (block_group->iref)
10020 spin_unlock(&block_group->lock);
10021 block_group = next_block_group(block_group);
10023 if (!block_group) {
10030 inode = block_group->inode;
10031 block_group->iref = 0;
10032 block_group->inode = NULL;
10033 spin_unlock(&block_group->lock);
10034 ASSERT(block_group->io_ctl.inode == NULL);
10036 last = block_group->key.objectid + block_group->key.offset;
10037 btrfs_put_block_group(block_group);
10042 * Must be called only after stopping all workers, since we could have block
10043 * group caching kthreads running, and therefore they could race with us if we
10044 * freed the block groups before stopping them.
10046 int btrfs_free_block_groups(struct btrfs_fs_info *info)
10048 struct btrfs_block_group_cache *block_group;
10049 struct btrfs_space_info *space_info;
10050 struct btrfs_caching_control *caching_ctl;
10053 down_write(&info->commit_root_sem);
10054 while (!list_empty(&info->caching_block_groups)) {
10055 caching_ctl = list_entry(info->caching_block_groups.next,
10056 struct btrfs_caching_control, list);
10057 list_del(&caching_ctl->list);
10058 put_caching_control(caching_ctl);
10060 up_write(&info->commit_root_sem);
10062 spin_lock(&info->unused_bgs_lock);
10063 while (!list_empty(&info->unused_bgs)) {
10064 block_group = list_first_entry(&info->unused_bgs,
10065 struct btrfs_block_group_cache,
10067 list_del_init(&block_group->bg_list);
10068 btrfs_put_block_group(block_group);
10070 spin_unlock(&info->unused_bgs_lock);
10072 spin_lock(&info->block_group_cache_lock);
10073 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
10074 block_group = rb_entry(n, struct btrfs_block_group_cache,
10076 rb_erase(&block_group->cache_node,
10077 &info->block_group_cache_tree);
10078 RB_CLEAR_NODE(&block_group->cache_node);
10079 spin_unlock(&info->block_group_cache_lock);
10081 down_write(&block_group->space_info->groups_sem);
10082 list_del(&block_group->list);
10083 up_write(&block_group->space_info->groups_sem);
10086 * We haven't cached this block group, which means we could
10087 * possibly have excluded extents on this block group.
10089 if (block_group->cached == BTRFS_CACHE_NO ||
10090 block_group->cached == BTRFS_CACHE_ERROR)
10091 free_excluded_extents(block_group);
10093 btrfs_remove_free_space_cache(block_group);
10094 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
10095 ASSERT(list_empty(&block_group->dirty_list));
10096 ASSERT(list_empty(&block_group->io_list));
10097 ASSERT(list_empty(&block_group->bg_list));
10098 ASSERT(atomic_read(&block_group->count) == 1);
10099 btrfs_put_block_group(block_group);
10101 spin_lock(&info->block_group_cache_lock);
10103 spin_unlock(&info->block_group_cache_lock);
10105 /* now that all the block groups are freed, go through and
10106 * free all the space_info structs. This is only called during
10107 * the final stages of unmount, and so we know nobody is
10108 * using them. We call synchronize_rcu() once before we start,
10109 * just to be on the safe side.
10113 release_global_block_rsv(info);
10115 while (!list_empty(&info->space_info)) {
10118 space_info = list_entry(info->space_info.next,
10119 struct btrfs_space_info,
10123 * Do not hide this behind enospc_debug, this is actually
10124 * important and indicates a real bug if this happens.
10126 if (WARN_ON(space_info->bytes_pinned > 0 ||
10127 space_info->bytes_reserved > 0 ||
10128 space_info->bytes_may_use > 0))
10129 dump_space_info(info, space_info, 0, 0);
10130 list_del(&space_info->list);
10131 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
10132 struct kobject *kobj;
10133 kobj = space_info->block_group_kobjs[i];
10134 space_info->block_group_kobjs[i] = NULL;
10140 kobject_del(&space_info->kobj);
10141 kobject_put(&space_info->kobj);
10146 /* link_block_group will queue up kobjects to add when we're reclaim-safe */
10147 void btrfs_add_raid_kobjects(struct btrfs_fs_info *fs_info)
10149 struct btrfs_space_info *space_info;
10150 struct raid_kobject *rkobj;
10154 spin_lock(&fs_info->pending_raid_kobjs_lock);
10155 list_splice_init(&fs_info->pending_raid_kobjs, &list);
10156 spin_unlock(&fs_info->pending_raid_kobjs_lock);
10158 list_for_each_entry(rkobj, &list, list) {
10159 space_info = __find_space_info(fs_info, rkobj->flags);
10161 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
10162 "%s", btrfs_bg_type_to_raid_name(rkobj->flags));
10164 kobject_put(&rkobj->kobj);
10169 btrfs_warn(fs_info,
10170 "failed to add kobject for block cache, ignoring");
10173 static void link_block_group(struct btrfs_block_group_cache *cache)
10175 struct btrfs_space_info *space_info = cache->space_info;
10176 struct btrfs_fs_info *fs_info = cache->fs_info;
10177 int index = btrfs_bg_flags_to_raid_index(cache->flags);
10178 bool first = false;
10180 down_write(&space_info->groups_sem);
10181 if (list_empty(&space_info->block_groups[index]))
10183 list_add_tail(&cache->list, &space_info->block_groups[index]);
10184 up_write(&space_info->groups_sem);
10187 struct raid_kobject *rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
10189 btrfs_warn(cache->fs_info,
10190 "couldn't alloc memory for raid level kobject");
10193 rkobj->flags = cache->flags;
10194 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
10196 spin_lock(&fs_info->pending_raid_kobjs_lock);
10197 list_add_tail(&rkobj->list, &fs_info->pending_raid_kobjs);
10198 spin_unlock(&fs_info->pending_raid_kobjs_lock);
10199 space_info->block_group_kobjs[index] = &rkobj->kobj;
10203 static struct btrfs_block_group_cache *
10204 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
10205 u64 start, u64 size)
10207 struct btrfs_block_group_cache *cache;
10209 cache = kzalloc(sizeof(*cache), GFP_NOFS);
10213 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
10215 if (!cache->free_space_ctl) {
10220 cache->key.objectid = start;
10221 cache->key.offset = size;
10222 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10224 cache->fs_info = fs_info;
10225 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
10226 set_free_space_tree_thresholds(cache);
10228 atomic_set(&cache->count, 1);
10229 spin_lock_init(&cache->lock);
10230 init_rwsem(&cache->data_rwsem);
10231 INIT_LIST_HEAD(&cache->list);
10232 INIT_LIST_HEAD(&cache->cluster_list);
10233 INIT_LIST_HEAD(&cache->bg_list);
10234 INIT_LIST_HEAD(&cache->ro_list);
10235 INIT_LIST_HEAD(&cache->dirty_list);
10236 INIT_LIST_HEAD(&cache->io_list);
10237 btrfs_init_free_space_ctl(cache);
10238 atomic_set(&cache->trimming, 0);
10239 mutex_init(&cache->free_space_lock);
10240 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
10247 * Iterate all chunks and verify that each of them has the corresponding block
10250 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
10252 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
10253 struct extent_map *em;
10254 struct btrfs_block_group_cache *bg;
10259 read_lock(&map_tree->lock);
10261 * lookup_extent_mapping will return the first extent map
10262 * intersecting the range, so setting @len to 1 is enough to
10263 * get the first chunk.
10265 em = lookup_extent_mapping(map_tree, start, 1);
10266 read_unlock(&map_tree->lock);
10270 bg = btrfs_lookup_block_group(fs_info, em->start);
10273 "chunk start=%llu len=%llu doesn't have corresponding block group",
10274 em->start, em->len);
10276 free_extent_map(em);
10279 if (bg->key.objectid != em->start ||
10280 bg->key.offset != em->len ||
10281 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
10282 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
10284 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
10285 em->start, em->len,
10286 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
10287 bg->key.objectid, bg->key.offset,
10288 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
10290 free_extent_map(em);
10291 btrfs_put_block_group(bg);
10294 start = em->start + em->len;
10295 free_extent_map(em);
10296 btrfs_put_block_group(bg);
10301 int btrfs_read_block_groups(struct btrfs_fs_info *info)
10303 struct btrfs_path *path;
10305 struct btrfs_block_group_cache *cache;
10306 struct btrfs_space_info *space_info;
10307 struct btrfs_key key;
10308 struct btrfs_key found_key;
10309 struct extent_buffer *leaf;
10310 int need_clear = 0;
10315 feature = btrfs_super_incompat_flags(info->super_copy);
10316 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
10320 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
10321 path = btrfs_alloc_path();
10324 path->reada = READA_FORWARD;
10326 cache_gen = btrfs_super_cache_generation(info->super_copy);
10327 if (btrfs_test_opt(info, SPACE_CACHE) &&
10328 btrfs_super_generation(info->super_copy) != cache_gen)
10330 if (btrfs_test_opt(info, CLEAR_CACHE))
10334 ret = find_first_block_group(info, path, &key);
10340 leaf = path->nodes[0];
10341 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
10343 cache = btrfs_create_block_group_cache(info, found_key.objectid,
10352 * When we mount with old space cache, we need to
10353 * set BTRFS_DC_CLEAR and set dirty flag.
10355 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
10356 * truncate the old free space cache inode and
10358 * b) Setting 'dirty flag' makes sure that we flush
10359 * the new space cache info onto disk.
10361 if (btrfs_test_opt(info, SPACE_CACHE))
10362 cache->disk_cache_state = BTRFS_DC_CLEAR;
10365 read_extent_buffer(leaf, &cache->item,
10366 btrfs_item_ptr_offset(leaf, path->slots[0]),
10367 sizeof(cache->item));
10368 cache->flags = btrfs_block_group_flags(&cache->item);
10370 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
10371 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
10373 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
10374 cache->key.objectid);
10379 key.objectid = found_key.objectid + found_key.offset;
10380 btrfs_release_path(path);
10383 * We need to exclude the super stripes now so that the space
10384 * info has super bytes accounted for, otherwise we'll think
10385 * we have more space than we actually do.
10387 ret = exclude_super_stripes(cache);
10390 * We may have excluded something, so call this just in
10393 free_excluded_extents(cache);
10394 btrfs_put_block_group(cache);
10399 * check for two cases, either we are full, and therefore
10400 * don't need to bother with the caching work since we won't
10401 * find any space, or we are empty, and we can just add all
10402 * the space in and be done with it. This saves us _a_lot_ of
10403 * time, particularly in the full case.
10405 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
10406 cache->last_byte_to_unpin = (u64)-1;
10407 cache->cached = BTRFS_CACHE_FINISHED;
10408 free_excluded_extents(cache);
10409 } else if (btrfs_block_group_used(&cache->item) == 0) {
10410 cache->last_byte_to_unpin = (u64)-1;
10411 cache->cached = BTRFS_CACHE_FINISHED;
10412 add_new_free_space(cache, found_key.objectid,
10413 found_key.objectid +
10415 free_excluded_extents(cache);
10418 ret = btrfs_add_block_group_cache(info, cache);
10420 btrfs_remove_free_space_cache(cache);
10421 btrfs_put_block_group(cache);
10425 trace_btrfs_add_block_group(info, cache, 0);
10426 update_space_info(info, cache->flags, found_key.offset,
10427 btrfs_block_group_used(&cache->item),
10428 cache->bytes_super, &space_info);
10430 cache->space_info = space_info;
10432 link_block_group(cache);
10434 set_avail_alloc_bits(info, cache->flags);
10435 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
10436 inc_block_group_ro(cache, 1);
10437 } else if (btrfs_block_group_used(&cache->item) == 0) {
10438 ASSERT(list_empty(&cache->bg_list));
10439 btrfs_mark_bg_unused(cache);
10443 list_for_each_entry_rcu(space_info, &info->space_info, list) {
10444 if (!(get_alloc_profile(info, space_info->flags) &
10445 (BTRFS_BLOCK_GROUP_RAID10 |
10446 BTRFS_BLOCK_GROUP_RAID1_MASK |
10447 BTRFS_BLOCK_GROUP_RAID56_MASK |
10448 BTRFS_BLOCK_GROUP_DUP)))
10451 * avoid allocating from un-mirrored block group if there are
10452 * mirrored block groups.
10454 list_for_each_entry(cache,
10455 &space_info->block_groups[BTRFS_RAID_RAID0],
10457 inc_block_group_ro(cache, 1);
10458 list_for_each_entry(cache,
10459 &space_info->block_groups[BTRFS_RAID_SINGLE],
10461 inc_block_group_ro(cache, 1);
10464 btrfs_add_raid_kobjects(info);
10465 init_global_block_rsv(info);
10466 ret = check_chunk_block_group_mappings(info);
10468 btrfs_free_path(path);
10472 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
10474 struct btrfs_fs_info *fs_info = trans->fs_info;
10475 struct btrfs_block_group_cache *block_group;
10476 struct btrfs_root *extent_root = fs_info->extent_root;
10477 struct btrfs_block_group_item item;
10478 struct btrfs_key key;
10481 if (!trans->can_flush_pending_bgs)
10484 while (!list_empty(&trans->new_bgs)) {
10485 block_group = list_first_entry(&trans->new_bgs,
10486 struct btrfs_block_group_cache,
10491 spin_lock(&block_group->lock);
10492 memcpy(&item, &block_group->item, sizeof(item));
10493 memcpy(&key, &block_group->key, sizeof(key));
10494 spin_unlock(&block_group->lock);
10496 ret = btrfs_insert_item(trans, extent_root, &key, &item,
10499 btrfs_abort_transaction(trans, ret);
10500 ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
10502 btrfs_abort_transaction(trans, ret);
10503 add_block_group_free_space(trans, block_group);
10504 /* already aborted the transaction if it failed. */
10506 btrfs_delayed_refs_rsv_release(fs_info, 1);
10507 list_del_init(&block_group->bg_list);
10509 btrfs_trans_release_chunk_metadata(trans);
10512 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
10513 u64 type, u64 chunk_offset, u64 size)
10515 struct btrfs_fs_info *fs_info = trans->fs_info;
10516 struct btrfs_block_group_cache *cache;
10519 btrfs_set_log_full_commit(trans);
10521 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
10525 btrfs_set_block_group_used(&cache->item, bytes_used);
10526 btrfs_set_block_group_chunk_objectid(&cache->item,
10527 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
10528 btrfs_set_block_group_flags(&cache->item, type);
10530 cache->flags = type;
10531 cache->last_byte_to_unpin = (u64)-1;
10532 cache->cached = BTRFS_CACHE_FINISHED;
10533 cache->needs_free_space = 1;
10534 ret = exclude_super_stripes(cache);
10537 * We may have excluded something, so call this just in
10540 free_excluded_extents(cache);
10541 btrfs_put_block_group(cache);
10545 add_new_free_space(cache, chunk_offset, chunk_offset + size);
10547 free_excluded_extents(cache);
10549 #ifdef CONFIG_BTRFS_DEBUG
10550 if (btrfs_should_fragment_free_space(cache)) {
10551 u64 new_bytes_used = size - bytes_used;
10553 bytes_used += new_bytes_used >> 1;
10554 fragment_free_space(cache);
10558 * Ensure the corresponding space_info object is created and
10559 * assigned to our block group. We want our bg to be added to the rbtree
10560 * with its ->space_info set.
10562 cache->space_info = __find_space_info(fs_info, cache->flags);
10563 ASSERT(cache->space_info);
10565 ret = btrfs_add_block_group_cache(fs_info, cache);
10567 btrfs_remove_free_space_cache(cache);
10568 btrfs_put_block_group(cache);
10573 * Now that our block group has its ->space_info set and is inserted in
10574 * the rbtree, update the space info's counters.
10576 trace_btrfs_add_block_group(fs_info, cache, 1);
10577 update_space_info(fs_info, cache->flags, size, bytes_used,
10578 cache->bytes_super, &cache->space_info);
10579 update_global_block_rsv(fs_info);
10581 link_block_group(cache);
10583 list_add_tail(&cache->bg_list, &trans->new_bgs);
10584 trans->delayed_ref_updates++;
10585 btrfs_update_delayed_refs_rsv(trans);
10587 set_avail_alloc_bits(fs_info, type);
10591 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10593 u64 extra_flags = chunk_to_extended(flags) &
10594 BTRFS_EXTENDED_PROFILE_MASK;
10596 write_seqlock(&fs_info->profiles_lock);
10597 if (flags & BTRFS_BLOCK_GROUP_DATA)
10598 fs_info->avail_data_alloc_bits &= ~extra_flags;
10599 if (flags & BTRFS_BLOCK_GROUP_METADATA)
10600 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10601 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10602 fs_info->avail_system_alloc_bits &= ~extra_flags;
10603 write_sequnlock(&fs_info->profiles_lock);
10607 * Clear incompat bits for the following feature(s):
10609 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
10610 * in the whole filesystem
10612 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
10614 if (flags & BTRFS_BLOCK_GROUP_RAID56_MASK) {
10615 struct list_head *head = &fs_info->space_info;
10616 struct btrfs_space_info *sinfo;
10618 list_for_each_entry_rcu(sinfo, head, list) {
10619 bool found = false;
10621 down_read(&sinfo->groups_sem);
10622 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
10624 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
10626 up_read(&sinfo->groups_sem);
10631 btrfs_clear_fs_incompat(fs_info, RAID56);
10635 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
10636 u64 group_start, struct extent_map *em)
10638 struct btrfs_fs_info *fs_info = trans->fs_info;
10639 struct btrfs_root *root = fs_info->extent_root;
10640 struct btrfs_path *path;
10641 struct btrfs_block_group_cache *block_group;
10642 struct btrfs_free_cluster *cluster;
10643 struct btrfs_root *tree_root = fs_info->tree_root;
10644 struct btrfs_key key;
10645 struct inode *inode;
10646 struct kobject *kobj = NULL;
10650 struct btrfs_caching_control *caching_ctl = NULL;
10652 bool remove_rsv = false;
10654 block_group = btrfs_lookup_block_group(fs_info, group_start);
10655 BUG_ON(!block_group);
10656 BUG_ON(!block_group->ro);
10658 trace_btrfs_remove_block_group(block_group);
10660 * Free the reserved super bytes from this block group before
10663 free_excluded_extents(block_group);
10664 btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
10665 block_group->key.offset);
10667 memcpy(&key, &block_group->key, sizeof(key));
10668 index = btrfs_bg_flags_to_raid_index(block_group->flags);
10669 factor = btrfs_bg_type_to_factor(block_group->flags);
10671 /* make sure this block group isn't part of an allocation cluster */
10672 cluster = &fs_info->data_alloc_cluster;
10673 spin_lock(&cluster->refill_lock);
10674 btrfs_return_cluster_to_free_space(block_group, cluster);
10675 spin_unlock(&cluster->refill_lock);
10678 * make sure this block group isn't part of a metadata
10679 * allocation cluster
10681 cluster = &fs_info->meta_alloc_cluster;
10682 spin_lock(&cluster->refill_lock);
10683 btrfs_return_cluster_to_free_space(block_group, cluster);
10684 spin_unlock(&cluster->refill_lock);
10686 path = btrfs_alloc_path();
10693 * get the inode first so any iput calls done for the io_list
10694 * aren't the final iput (no unlinks allowed now)
10696 inode = lookup_free_space_inode(block_group, path);
10698 mutex_lock(&trans->transaction->cache_write_mutex);
10700 * Make sure our free space cache IO is done before removing the
10703 spin_lock(&trans->transaction->dirty_bgs_lock);
10704 if (!list_empty(&block_group->io_list)) {
10705 list_del_init(&block_group->io_list);
10707 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10709 spin_unlock(&trans->transaction->dirty_bgs_lock);
10710 btrfs_wait_cache_io(trans, block_group, path);
10711 btrfs_put_block_group(block_group);
10712 spin_lock(&trans->transaction->dirty_bgs_lock);
10715 if (!list_empty(&block_group->dirty_list)) {
10716 list_del_init(&block_group->dirty_list);
10718 btrfs_put_block_group(block_group);
10720 spin_unlock(&trans->transaction->dirty_bgs_lock);
10721 mutex_unlock(&trans->transaction->cache_write_mutex);
10723 if (!IS_ERR(inode)) {
10724 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
10726 btrfs_add_delayed_iput(inode);
10729 clear_nlink(inode);
10730 /* One for the block groups ref */
10731 spin_lock(&block_group->lock);
10732 if (block_group->iref) {
10733 block_group->iref = 0;
10734 block_group->inode = NULL;
10735 spin_unlock(&block_group->lock);
10738 spin_unlock(&block_group->lock);
10740 /* One for our lookup ref */
10741 btrfs_add_delayed_iput(inode);
10744 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10745 key.offset = block_group->key.objectid;
10748 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10752 btrfs_release_path(path);
10754 ret = btrfs_del_item(trans, tree_root, path);
10757 btrfs_release_path(path);
10760 spin_lock(&fs_info->block_group_cache_lock);
10761 rb_erase(&block_group->cache_node,
10762 &fs_info->block_group_cache_tree);
10763 RB_CLEAR_NODE(&block_group->cache_node);
10765 if (fs_info->first_logical_byte == block_group->key.objectid)
10766 fs_info->first_logical_byte = (u64)-1;
10767 spin_unlock(&fs_info->block_group_cache_lock);
10769 down_write(&block_group->space_info->groups_sem);
10771 * we must use list_del_init so people can check to see if they
10772 * are still on the list after taking the semaphore
10774 list_del_init(&block_group->list);
10775 if (list_empty(&block_group->space_info->block_groups[index])) {
10776 kobj = block_group->space_info->block_group_kobjs[index];
10777 block_group->space_info->block_group_kobjs[index] = NULL;
10778 clear_avail_alloc_bits(fs_info, block_group->flags);
10780 up_write(&block_group->space_info->groups_sem);
10781 clear_incompat_bg_bits(fs_info, block_group->flags);
10787 if (block_group->has_caching_ctl)
10788 caching_ctl = get_caching_control(block_group);
10789 if (block_group->cached == BTRFS_CACHE_STARTED)
10790 wait_block_group_cache_done(block_group);
10791 if (block_group->has_caching_ctl) {
10792 down_write(&fs_info->commit_root_sem);
10793 if (!caching_ctl) {
10794 struct btrfs_caching_control *ctl;
10796 list_for_each_entry(ctl,
10797 &fs_info->caching_block_groups, list)
10798 if (ctl->block_group == block_group) {
10800 refcount_inc(&caching_ctl->count);
10805 list_del_init(&caching_ctl->list);
10806 up_write(&fs_info->commit_root_sem);
10808 /* Once for the caching bgs list and once for us. */
10809 put_caching_control(caching_ctl);
10810 put_caching_control(caching_ctl);
10814 spin_lock(&trans->transaction->dirty_bgs_lock);
10815 WARN_ON(!list_empty(&block_group->dirty_list));
10816 WARN_ON(!list_empty(&block_group->io_list));
10817 spin_unlock(&trans->transaction->dirty_bgs_lock);
10819 btrfs_remove_free_space_cache(block_group);
10821 spin_lock(&block_group->space_info->lock);
10822 list_del_init(&block_group->ro_list);
10824 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
10825 WARN_ON(block_group->space_info->total_bytes
10826 < block_group->key.offset);
10827 WARN_ON(block_group->space_info->bytes_readonly
10828 < block_group->key.offset);
10829 WARN_ON(block_group->space_info->disk_total
10830 < block_group->key.offset * factor);
10832 block_group->space_info->total_bytes -= block_group->key.offset;
10833 block_group->space_info->bytes_readonly -= block_group->key.offset;
10834 block_group->space_info->disk_total -= block_group->key.offset * factor;
10836 spin_unlock(&block_group->space_info->lock);
10838 memcpy(&key, &block_group->key, sizeof(key));
10840 mutex_lock(&fs_info->chunk_mutex);
10841 spin_lock(&block_group->lock);
10842 block_group->removed = 1;
10844 * At this point trimming can't start on this block group, because we
10845 * removed the block group from the tree fs_info->block_group_cache_tree
10846 * so no one can't find it anymore and even if someone already got this
10847 * block group before we removed it from the rbtree, they have already
10848 * incremented block_group->trimming - if they didn't, they won't find
10849 * any free space entries because we already removed them all when we
10850 * called btrfs_remove_free_space_cache().
10852 * And we must not remove the extent map from the fs_info->mapping_tree
10853 * to prevent the same logical address range and physical device space
10854 * ranges from being reused for a new block group. This is because our
10855 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10856 * completely transactionless, so while it is trimming a range the
10857 * currently running transaction might finish and a new one start,
10858 * allowing for new block groups to be created that can reuse the same
10859 * physical device locations unless we take this special care.
10861 * There may also be an implicit trim operation if the file system
10862 * is mounted with -odiscard. The same protections must remain
10863 * in place until the extents have been discarded completely when
10864 * the transaction commit has completed.
10866 remove_em = (atomic_read(&block_group->trimming) == 0);
10867 spin_unlock(&block_group->lock);
10869 mutex_unlock(&fs_info->chunk_mutex);
10871 ret = remove_block_group_free_space(trans, block_group);
10875 btrfs_put_block_group(block_group);
10876 btrfs_put_block_group(block_group);
10878 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10884 ret = btrfs_del_item(trans, root, path);
10889 struct extent_map_tree *em_tree;
10891 em_tree = &fs_info->mapping_tree;
10892 write_lock(&em_tree->lock);
10893 remove_extent_mapping(em_tree, em);
10894 write_unlock(&em_tree->lock);
10895 /* once for the tree */
10896 free_extent_map(em);
10900 btrfs_delayed_refs_rsv_release(fs_info, 1);
10901 btrfs_free_path(path);
10905 struct btrfs_trans_handle *
10906 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10907 const u64 chunk_offset)
10909 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
10910 struct extent_map *em;
10911 struct map_lookup *map;
10912 unsigned int num_items;
10914 read_lock(&em_tree->lock);
10915 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10916 read_unlock(&em_tree->lock);
10917 ASSERT(em && em->start == chunk_offset);
10920 * We need to reserve 3 + N units from the metadata space info in order
10921 * to remove a block group (done at btrfs_remove_chunk() and at
10922 * btrfs_remove_block_group()), which are used for:
10924 * 1 unit for adding the free space inode's orphan (located in the tree
10926 * 1 unit for deleting the block group item (located in the extent
10928 * 1 unit for deleting the free space item (located in tree of tree
10930 * N units for deleting N device extent items corresponding to each
10931 * stripe (located in the device tree).
10933 * In order to remove a block group we also need to reserve units in the
10934 * system space info in order to update the chunk tree (update one or
10935 * more device items and remove one chunk item), but this is done at
10936 * btrfs_remove_chunk() through a call to check_system_chunk().
10938 map = em->map_lookup;
10939 num_items = 3 + map->num_stripes;
10940 free_extent_map(em);
10942 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
10947 * Process the unused_bgs list and remove any that don't have any allocated
10948 * space inside of them.
10950 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10952 struct btrfs_block_group_cache *block_group;
10953 struct btrfs_space_info *space_info;
10954 struct btrfs_trans_handle *trans;
10957 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
10960 spin_lock(&fs_info->unused_bgs_lock);
10961 while (!list_empty(&fs_info->unused_bgs)) {
10965 block_group = list_first_entry(&fs_info->unused_bgs,
10966 struct btrfs_block_group_cache,
10968 list_del_init(&block_group->bg_list);
10970 space_info = block_group->space_info;
10972 if (ret || btrfs_mixed_space_info(space_info)) {
10973 btrfs_put_block_group(block_group);
10976 spin_unlock(&fs_info->unused_bgs_lock);
10978 mutex_lock(&fs_info->delete_unused_bgs_mutex);
10980 /* Don't want to race with allocators so take the groups_sem */
10981 down_write(&space_info->groups_sem);
10982 spin_lock(&block_group->lock);
10983 if (block_group->reserved || block_group->pinned ||
10984 btrfs_block_group_used(&block_group->item) ||
10986 list_is_singular(&block_group->list)) {
10988 * We want to bail if we made new allocations or have
10989 * outstanding allocations in this block group. We do
10990 * the ro check in case balance is currently acting on
10991 * this block group.
10993 trace_btrfs_skip_unused_block_group(block_group);
10994 spin_unlock(&block_group->lock);
10995 up_write(&space_info->groups_sem);
10998 spin_unlock(&block_group->lock);
11000 /* We don't want to force the issue, only flip if it's ok. */
11001 ret = inc_block_group_ro(block_group, 0);
11002 up_write(&space_info->groups_sem);
11009 * Want to do this before we do anything else so we can recover
11010 * properly if we fail to join the transaction.
11012 trans = btrfs_start_trans_remove_block_group(fs_info,
11013 block_group->key.objectid);
11014 if (IS_ERR(trans)) {
11015 btrfs_dec_block_group_ro(block_group);
11016 ret = PTR_ERR(trans);
11021 * We could have pending pinned extents for this block group,
11022 * just delete them, we don't care about them anymore.
11024 start = block_group->key.objectid;
11025 end = start + block_group->key.offset - 1;
11027 * Hold the unused_bg_unpin_mutex lock to avoid racing with
11028 * btrfs_finish_extent_commit(). If we are at transaction N,
11029 * another task might be running finish_extent_commit() for the
11030 * previous transaction N - 1, and have seen a range belonging
11031 * to the block group in freed_extents[] before we were able to
11032 * clear the whole block group range from freed_extents[]. This
11033 * means that task can lookup for the block group after we
11034 * unpinned it from freed_extents[] and removed it, leading to
11035 * a BUG_ON() at btrfs_unpin_extent_range().
11037 mutex_lock(&fs_info->unused_bg_unpin_mutex);
11038 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
11041 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11042 btrfs_dec_block_group_ro(block_group);
11045 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
11048 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11049 btrfs_dec_block_group_ro(block_group);
11052 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
11054 /* Reset pinned so btrfs_put_block_group doesn't complain */
11055 spin_lock(&space_info->lock);
11056 spin_lock(&block_group->lock);
11058 update_bytes_pinned(fs_info, space_info, -block_group->pinned);
11059 space_info->bytes_readonly += block_group->pinned;
11060 percpu_counter_add_batch(&space_info->total_bytes_pinned,
11061 -block_group->pinned,
11062 BTRFS_TOTAL_BYTES_PINNED_BATCH);
11063 block_group->pinned = 0;
11065 spin_unlock(&block_group->lock);
11066 spin_unlock(&space_info->lock);
11068 /* DISCARD can flip during remount */
11069 trimming = btrfs_test_opt(fs_info, DISCARD);
11071 /* Implicit trim during transaction commit. */
11073 btrfs_get_block_group_trimming(block_group);
11076 * Btrfs_remove_chunk will abort the transaction if things go
11079 ret = btrfs_remove_chunk(trans, block_group->key.objectid);
11083 btrfs_put_block_group_trimming(block_group);
11088 * If we're not mounted with -odiscard, we can just forget
11089 * about this block group. Otherwise we'll need to wait
11090 * until transaction commit to do the actual discard.
11093 spin_lock(&fs_info->unused_bgs_lock);
11095 * A concurrent scrub might have added us to the list
11096 * fs_info->unused_bgs, so use a list_move operation
11097 * to add the block group to the deleted_bgs list.
11099 list_move(&block_group->bg_list,
11100 &trans->transaction->deleted_bgs);
11101 spin_unlock(&fs_info->unused_bgs_lock);
11102 btrfs_get_block_group(block_group);
11105 btrfs_end_transaction(trans);
11107 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
11108 btrfs_put_block_group(block_group);
11109 spin_lock(&fs_info->unused_bgs_lock);
11111 spin_unlock(&fs_info->unused_bgs_lock);
11114 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
11116 struct btrfs_super_block *disk_super;
11122 disk_super = fs_info->super_copy;
11123 if (!btrfs_super_root(disk_super))
11126 features = btrfs_super_incompat_flags(disk_super);
11127 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
11130 flags = BTRFS_BLOCK_GROUP_SYSTEM;
11131 ret = create_space_info(fs_info, flags);
11136 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
11137 ret = create_space_info(fs_info, flags);
11139 flags = BTRFS_BLOCK_GROUP_METADATA;
11140 ret = create_space_info(fs_info, flags);
11144 flags = BTRFS_BLOCK_GROUP_DATA;
11145 ret = create_space_info(fs_info, flags);
11151 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
11152 u64 start, u64 end)
11154 return unpin_extent_range(fs_info, start, end, false);
11158 * It used to be that old block groups would be left around forever.
11159 * Iterating over them would be enough to trim unused space. Since we
11160 * now automatically remove them, we also need to iterate over unallocated
11163 * We don't want a transaction for this since the discard may take a
11164 * substantial amount of time. We don't require that a transaction be
11165 * running, but we do need to take a running transaction into account
11166 * to ensure that we're not discarding chunks that were released or
11167 * allocated in the current transaction.
11169 * Holding the chunks lock will prevent other threads from allocating
11170 * or releasing chunks, but it won't prevent a running transaction
11171 * from committing and releasing the memory that the pending chunks
11172 * list head uses. For that, we need to take a reference to the
11173 * transaction and hold the commit root sem. We only need to hold
11174 * it while performing the free space search since we have already
11175 * held back allocations.
11177 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
11179 u64 start = SZ_1M, len = 0, end = 0;
11184 /* Discard not supported = nothing to do. */
11185 if (!blk_queue_discard(bdev_get_queue(device->bdev)))
11188 /* Not writable = nothing to do. */
11189 if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
11192 /* No free space = nothing to do. */
11193 if (device->total_bytes <= device->bytes_used)
11199 struct btrfs_fs_info *fs_info = device->fs_info;
11202 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
11206 find_first_clear_extent_bit(&device->alloc_state, start,
11208 CHUNK_TRIMMED | CHUNK_ALLOCATED);
11210 /* Ensure we skip the reserved area in the first 1M */
11211 start = max_t(u64, start, SZ_1M);
11214 * If find_first_clear_extent_bit find a range that spans the
11215 * end of the device it will set end to -1, in this case it's up
11216 * to the caller to trim the value to the size of the device.
11218 end = min(end, device->total_bytes - 1);
11220 len = end - start + 1;
11222 /* We didn't find any extents */
11224 mutex_unlock(&fs_info->chunk_mutex);
11229 ret = btrfs_issue_discard(device->bdev, start, len,
11232 set_extent_bits(&device->alloc_state, start,
11235 mutex_unlock(&fs_info->chunk_mutex);
11243 if (fatal_signal_pending(current)) {
11244 ret = -ERESTARTSYS;
11255 * Trim the whole filesystem by:
11256 * 1) trimming the free space in each block group
11257 * 2) trimming the unallocated space on each device
11259 * This will also continue trimming even if a block group or device encounters
11260 * an error. The return value will be the last error, or 0 if nothing bad
11263 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
11265 struct btrfs_block_group_cache *cache = NULL;
11266 struct btrfs_device *device;
11267 struct list_head *devices;
11273 u64 dev_failed = 0;
11278 cache = btrfs_lookup_first_block_group(fs_info, range->start);
11279 for (; cache; cache = next_block_group(cache)) {
11280 if (cache->key.objectid >= (range->start + range->len)) {
11281 btrfs_put_block_group(cache);
11285 start = max(range->start, cache->key.objectid);
11286 end = min(range->start + range->len,
11287 cache->key.objectid + cache->key.offset);
11289 if (end - start >= range->minlen) {
11290 if (!block_group_cache_done(cache)) {
11291 ret = cache_block_group(cache, 0);
11297 ret = wait_block_group_cache_done(cache);
11304 ret = btrfs_trim_block_group(cache,
11310 trimmed += group_trimmed;
11320 btrfs_warn(fs_info,
11321 "failed to trim %llu block group(s), last error %d",
11322 bg_failed, bg_ret);
11323 mutex_lock(&fs_info->fs_devices->device_list_mutex);
11324 devices = &fs_info->fs_devices->devices;
11325 list_for_each_entry(device, devices, dev_list) {
11326 ret = btrfs_trim_free_extents(device, &group_trimmed);
11333 trimmed += group_trimmed;
11335 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
11338 btrfs_warn(fs_info,
11339 "failed to trim %llu device(s), last error %d",
11340 dev_failed, dev_ret);
11341 range->len = trimmed;
11348 * btrfs_{start,end}_write_no_snapshotting() are similar to
11349 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
11350 * data into the page cache through nocow before the subvolume is snapshoted,
11351 * but flush the data into disk after the snapshot creation, or to prevent
11352 * operations while snapshotting is ongoing and that cause the snapshot to be
11353 * inconsistent (writes followed by expanding truncates for example).
11355 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
11357 percpu_counter_dec(&root->subv_writers->counter);
11358 cond_wake_up(&root->subv_writers->wait);
11361 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
11363 if (atomic_read(&root->will_be_snapshotted))
11366 percpu_counter_inc(&root->subv_writers->counter);
11368 * Make sure counter is updated before we check for snapshot creation.
11371 if (atomic_read(&root->will_be_snapshotted)) {
11372 btrfs_end_write_no_snapshotting(root);
11378 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
11383 ret = btrfs_start_write_no_snapshotting(root);
11386 wait_var_event(&root->will_be_snapshotted,
11387 !atomic_read(&root->will_be_snapshotted));
11391 void btrfs_mark_bg_unused(struct btrfs_block_group_cache *bg)
11393 struct btrfs_fs_info *fs_info = bg->fs_info;
11395 spin_lock(&fs_info->unused_bgs_lock);
11396 if (list_empty(&bg->bg_list)) {
11397 btrfs_get_block_group(bg);
11398 trace_btrfs_add_unused_block_group(bg);
11399 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
11401 spin_unlock(&fs_info->unused_bgs_lock);