2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
18 #include <linux/sched.h>
19 #include <linux/pagemap.h>
20 #include <linux/writeback.h>
21 #include <linux/blkdev.h>
22 #include <linux/sort.h>
23 #include <linux/rcupdate.h>
24 #include <linux/kthread.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/percpu_counter.h>
31 #include "print-tree.h"
35 #include "free-space-cache.h"
36 #include "free-space-tree.h"
41 #undef SCRAMBLE_DELAYED_REFS
44 * control flags for do_chunk_alloc's force field
45 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
46 * if we really need one.
48 * CHUNK_ALLOC_LIMITED means to only try and allocate one
49 * if we have very few chunks already allocated. This is
50 * used as part of the clustering code to help make sure
51 * we have a good pool of storage to cluster in, without
52 * filling the FS with empty chunks
54 * CHUNK_ALLOC_FORCE means it must try to allocate one
58 CHUNK_ALLOC_NO_FORCE = 0,
59 CHUNK_ALLOC_LIMITED = 1,
60 CHUNK_ALLOC_FORCE = 2,
63 static int update_block_group(struct btrfs_trans_handle *trans,
64 struct btrfs_fs_info *fs_info, u64 bytenr,
65 u64 num_bytes, int alloc);
66 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
67 struct btrfs_fs_info *fs_info,
68 struct btrfs_delayed_ref_node *node, u64 parent,
69 u64 root_objectid, u64 owner_objectid,
70 u64 owner_offset, int refs_to_drop,
71 struct btrfs_delayed_extent_op *extra_op);
72 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
73 struct extent_buffer *leaf,
74 struct btrfs_extent_item *ei);
75 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
76 struct btrfs_fs_info *fs_info,
77 u64 parent, u64 root_objectid,
78 u64 flags, u64 owner, u64 offset,
79 struct btrfs_key *ins, int ref_mod);
80 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
81 struct btrfs_fs_info *fs_info,
82 u64 parent, u64 root_objectid,
83 u64 flags, struct btrfs_disk_key *key,
84 int level, struct btrfs_key *ins);
85 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
86 struct btrfs_fs_info *fs_info, u64 flags,
88 static int find_next_key(struct btrfs_path *path, int level,
89 struct btrfs_key *key);
90 static void dump_space_info(struct btrfs_fs_info *fs_info,
91 struct btrfs_space_info *info, u64 bytes,
92 int dump_block_groups);
93 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
94 u64 ram_bytes, u64 num_bytes, int delalloc);
95 static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
96 u64 num_bytes, int delalloc);
97 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
99 static int __reserve_metadata_bytes(struct btrfs_root *root,
100 struct btrfs_space_info *space_info,
102 enum btrfs_reserve_flush_enum flush);
103 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
104 struct btrfs_space_info *space_info,
106 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
107 struct btrfs_space_info *space_info,
111 block_group_cache_done(struct btrfs_block_group_cache *cache)
114 return cache->cached == BTRFS_CACHE_FINISHED ||
115 cache->cached == BTRFS_CACHE_ERROR;
118 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
120 return (cache->flags & bits) == bits;
123 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
125 atomic_inc(&cache->count);
128 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
130 if (atomic_dec_and_test(&cache->count)) {
131 WARN_ON(cache->pinned > 0);
132 WARN_ON(cache->reserved > 0);
133 kfree(cache->free_space_ctl);
139 * this adds the block group to the fs_info rb tree for the block group
142 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
143 struct btrfs_block_group_cache *block_group)
146 struct rb_node *parent = NULL;
147 struct btrfs_block_group_cache *cache;
149 spin_lock(&info->block_group_cache_lock);
150 p = &info->block_group_cache_tree.rb_node;
154 cache = rb_entry(parent, struct btrfs_block_group_cache,
156 if (block_group->key.objectid < cache->key.objectid) {
158 } else if (block_group->key.objectid > cache->key.objectid) {
161 spin_unlock(&info->block_group_cache_lock);
166 rb_link_node(&block_group->cache_node, parent, p);
167 rb_insert_color(&block_group->cache_node,
168 &info->block_group_cache_tree);
170 if (info->first_logical_byte > block_group->key.objectid)
171 info->first_logical_byte = block_group->key.objectid;
173 spin_unlock(&info->block_group_cache_lock);
179 * This will return the block group at or after bytenr if contains is 0, else
180 * it will return the block group that contains the bytenr
182 static struct btrfs_block_group_cache *
183 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
186 struct btrfs_block_group_cache *cache, *ret = NULL;
190 spin_lock(&info->block_group_cache_lock);
191 n = info->block_group_cache_tree.rb_node;
194 cache = rb_entry(n, struct btrfs_block_group_cache,
196 end = cache->key.objectid + cache->key.offset - 1;
197 start = cache->key.objectid;
199 if (bytenr < start) {
200 if (!contains && (!ret || start < ret->key.objectid))
203 } else if (bytenr > start) {
204 if (contains && bytenr <= end) {
215 btrfs_get_block_group(ret);
216 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
217 info->first_logical_byte = ret->key.objectid;
219 spin_unlock(&info->block_group_cache_lock);
224 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
225 u64 start, u64 num_bytes)
227 u64 end = start + num_bytes - 1;
228 set_extent_bits(&fs_info->freed_extents[0],
229 start, end, EXTENT_UPTODATE);
230 set_extent_bits(&fs_info->freed_extents[1],
231 start, end, EXTENT_UPTODATE);
235 static void free_excluded_extents(struct btrfs_fs_info *fs_info,
236 struct btrfs_block_group_cache *cache)
240 start = cache->key.objectid;
241 end = start + cache->key.offset - 1;
243 clear_extent_bits(&fs_info->freed_extents[0],
244 start, end, EXTENT_UPTODATE);
245 clear_extent_bits(&fs_info->freed_extents[1],
246 start, end, EXTENT_UPTODATE);
249 static int exclude_super_stripes(struct btrfs_fs_info *fs_info,
250 struct btrfs_block_group_cache *cache)
257 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
258 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
259 cache->bytes_super += stripe_len;
260 ret = add_excluded_extent(fs_info, cache->key.objectid,
266 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
267 bytenr = btrfs_sb_offset(i);
268 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
269 bytenr, 0, &logical, &nr, &stripe_len);
276 if (logical[nr] > cache->key.objectid +
280 if (logical[nr] + stripe_len <= cache->key.objectid)
284 if (start < cache->key.objectid) {
285 start = cache->key.objectid;
286 len = (logical[nr] + stripe_len) - start;
288 len = min_t(u64, stripe_len,
289 cache->key.objectid +
290 cache->key.offset - start);
293 cache->bytes_super += len;
294 ret = add_excluded_extent(fs_info, start, len);
306 static struct btrfs_caching_control *
307 get_caching_control(struct btrfs_block_group_cache *cache)
309 struct btrfs_caching_control *ctl;
311 spin_lock(&cache->lock);
312 if (!cache->caching_ctl) {
313 spin_unlock(&cache->lock);
317 ctl = cache->caching_ctl;
318 atomic_inc(&ctl->count);
319 spin_unlock(&cache->lock);
323 static void put_caching_control(struct btrfs_caching_control *ctl)
325 if (atomic_dec_and_test(&ctl->count))
329 #ifdef CONFIG_BTRFS_DEBUG
330 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
332 struct btrfs_fs_info *fs_info = block_group->fs_info;
333 u64 start = block_group->key.objectid;
334 u64 len = block_group->key.offset;
335 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
336 fs_info->nodesize : fs_info->sectorsize;
337 u64 step = chunk << 1;
339 while (len > chunk) {
340 btrfs_remove_free_space(block_group, start, chunk);
351 * this is only called by cache_block_group, since we could have freed extents
352 * we need to check the pinned_extents for any extents that can't be used yet
353 * since their free space will be released as soon as the transaction commits.
355 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
356 struct btrfs_fs_info *info, u64 start, u64 end)
358 u64 extent_start, extent_end, size, total_added = 0;
361 while (start < end) {
362 ret = find_first_extent_bit(info->pinned_extents, start,
363 &extent_start, &extent_end,
364 EXTENT_DIRTY | EXTENT_UPTODATE,
369 if (extent_start <= start) {
370 start = extent_end + 1;
371 } else if (extent_start > start && extent_start < end) {
372 size = extent_start - start;
374 ret = btrfs_add_free_space(block_group, start,
376 BUG_ON(ret); /* -ENOMEM or logic error */
377 start = extent_end + 1;
386 ret = btrfs_add_free_space(block_group, start, size);
387 BUG_ON(ret); /* -ENOMEM or logic error */
393 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
395 struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
396 struct btrfs_fs_info *fs_info = block_group->fs_info;
397 struct btrfs_root *extent_root = fs_info->extent_root;
398 struct btrfs_path *path;
399 struct extent_buffer *leaf;
400 struct btrfs_key key;
407 path = btrfs_alloc_path();
411 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
413 #ifdef CONFIG_BTRFS_DEBUG
415 * If we're fragmenting we don't want to make anybody think we can
416 * allocate from this block group until we've had a chance to fragment
419 if (btrfs_should_fragment_free_space(block_group))
423 * We don't want to deadlock with somebody trying to allocate a new
424 * extent for the extent root while also trying to search the extent
425 * root to add free space. So we skip locking and search the commit
426 * root, since its read-only
428 path->skip_locking = 1;
429 path->search_commit_root = 1;
430 path->reada = READA_FORWARD;
434 key.type = BTRFS_EXTENT_ITEM_KEY;
437 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
441 leaf = path->nodes[0];
442 nritems = btrfs_header_nritems(leaf);
445 if (btrfs_fs_closing(fs_info) > 1) {
450 if (path->slots[0] < nritems) {
451 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
453 ret = find_next_key(path, 0, &key);
457 if (need_resched() ||
458 rwsem_is_contended(&fs_info->commit_root_sem)) {
460 caching_ctl->progress = last;
461 btrfs_release_path(path);
462 up_read(&fs_info->commit_root_sem);
463 mutex_unlock(&caching_ctl->mutex);
465 mutex_lock(&caching_ctl->mutex);
466 down_read(&fs_info->commit_root_sem);
470 ret = btrfs_next_leaf(extent_root, path);
475 leaf = path->nodes[0];
476 nritems = btrfs_header_nritems(leaf);
480 if (key.objectid < last) {
483 key.type = BTRFS_EXTENT_ITEM_KEY;
486 caching_ctl->progress = last;
487 btrfs_release_path(path);
491 if (key.objectid < block_group->key.objectid) {
496 if (key.objectid >= block_group->key.objectid +
497 block_group->key.offset)
500 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
501 key.type == BTRFS_METADATA_ITEM_KEY) {
502 total_found += add_new_free_space(block_group,
505 if (key.type == BTRFS_METADATA_ITEM_KEY)
506 last = key.objectid +
509 last = key.objectid + key.offset;
511 if (total_found > CACHING_CTL_WAKE_UP) {
514 wake_up(&caching_ctl->wait);
521 total_found += add_new_free_space(block_group, fs_info, last,
522 block_group->key.objectid +
523 block_group->key.offset);
524 caching_ctl->progress = (u64)-1;
527 btrfs_free_path(path);
531 static noinline void caching_thread(struct btrfs_work *work)
533 struct btrfs_block_group_cache *block_group;
534 struct btrfs_fs_info *fs_info;
535 struct btrfs_caching_control *caching_ctl;
536 struct btrfs_root *extent_root;
539 caching_ctl = container_of(work, struct btrfs_caching_control, work);
540 block_group = caching_ctl->block_group;
541 fs_info = block_group->fs_info;
542 extent_root = fs_info->extent_root;
544 mutex_lock(&caching_ctl->mutex);
545 down_read(&fs_info->commit_root_sem);
547 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
548 ret = load_free_space_tree(caching_ctl);
550 ret = load_extent_tree_free(caching_ctl);
552 spin_lock(&block_group->lock);
553 block_group->caching_ctl = NULL;
554 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
555 spin_unlock(&block_group->lock);
557 #ifdef CONFIG_BTRFS_DEBUG
558 if (btrfs_should_fragment_free_space(block_group)) {
561 spin_lock(&block_group->space_info->lock);
562 spin_lock(&block_group->lock);
563 bytes_used = block_group->key.offset -
564 btrfs_block_group_used(&block_group->item);
565 block_group->space_info->bytes_used += bytes_used >> 1;
566 spin_unlock(&block_group->lock);
567 spin_unlock(&block_group->space_info->lock);
568 fragment_free_space(block_group);
572 caching_ctl->progress = (u64)-1;
574 up_read(&fs_info->commit_root_sem);
575 free_excluded_extents(fs_info, block_group);
576 mutex_unlock(&caching_ctl->mutex);
578 wake_up(&caching_ctl->wait);
580 put_caching_control(caching_ctl);
581 btrfs_put_block_group(block_group);
584 static int cache_block_group(struct btrfs_block_group_cache *cache,
588 struct btrfs_fs_info *fs_info = cache->fs_info;
589 struct btrfs_caching_control *caching_ctl;
592 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
596 INIT_LIST_HEAD(&caching_ctl->list);
597 mutex_init(&caching_ctl->mutex);
598 init_waitqueue_head(&caching_ctl->wait);
599 caching_ctl->block_group = cache;
600 caching_ctl->progress = cache->key.objectid;
601 atomic_set(&caching_ctl->count, 1);
602 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
603 caching_thread, NULL, NULL);
605 spin_lock(&cache->lock);
607 * This should be a rare occasion, but this could happen I think in the
608 * case where one thread starts to load the space cache info, and then
609 * some other thread starts a transaction commit which tries to do an
610 * allocation while the other thread is still loading the space cache
611 * info. The previous loop should have kept us from choosing this block
612 * group, but if we've moved to the state where we will wait on caching
613 * block groups we need to first check if we're doing a fast load here,
614 * so we can wait for it to finish, otherwise we could end up allocating
615 * from a block group who's cache gets evicted for one reason or
618 while (cache->cached == BTRFS_CACHE_FAST) {
619 struct btrfs_caching_control *ctl;
621 ctl = cache->caching_ctl;
622 atomic_inc(&ctl->count);
623 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
624 spin_unlock(&cache->lock);
628 finish_wait(&ctl->wait, &wait);
629 put_caching_control(ctl);
630 spin_lock(&cache->lock);
633 if (cache->cached != BTRFS_CACHE_NO) {
634 spin_unlock(&cache->lock);
638 WARN_ON(cache->caching_ctl);
639 cache->caching_ctl = caching_ctl;
640 cache->cached = BTRFS_CACHE_FAST;
641 spin_unlock(&cache->lock);
643 if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
644 mutex_lock(&caching_ctl->mutex);
645 ret = load_free_space_cache(fs_info, cache);
647 spin_lock(&cache->lock);
649 cache->caching_ctl = NULL;
650 cache->cached = BTRFS_CACHE_FINISHED;
651 cache->last_byte_to_unpin = (u64)-1;
652 caching_ctl->progress = (u64)-1;
654 if (load_cache_only) {
655 cache->caching_ctl = NULL;
656 cache->cached = BTRFS_CACHE_NO;
658 cache->cached = BTRFS_CACHE_STARTED;
659 cache->has_caching_ctl = 1;
662 spin_unlock(&cache->lock);
663 #ifdef CONFIG_BTRFS_DEBUG
665 btrfs_should_fragment_free_space(cache)) {
668 spin_lock(&cache->space_info->lock);
669 spin_lock(&cache->lock);
670 bytes_used = cache->key.offset -
671 btrfs_block_group_used(&cache->item);
672 cache->space_info->bytes_used += bytes_used >> 1;
673 spin_unlock(&cache->lock);
674 spin_unlock(&cache->space_info->lock);
675 fragment_free_space(cache);
678 mutex_unlock(&caching_ctl->mutex);
680 wake_up(&caching_ctl->wait);
682 put_caching_control(caching_ctl);
683 free_excluded_extents(fs_info, cache);
688 * We're either using the free space tree or no caching at all.
689 * Set cached to the appropriate value and wakeup any waiters.
691 spin_lock(&cache->lock);
692 if (load_cache_only) {
693 cache->caching_ctl = NULL;
694 cache->cached = BTRFS_CACHE_NO;
696 cache->cached = BTRFS_CACHE_STARTED;
697 cache->has_caching_ctl = 1;
699 spin_unlock(&cache->lock);
700 wake_up(&caching_ctl->wait);
703 if (load_cache_only) {
704 put_caching_control(caching_ctl);
708 down_write(&fs_info->commit_root_sem);
709 atomic_inc(&caching_ctl->count);
710 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
711 up_write(&fs_info->commit_root_sem);
713 btrfs_get_block_group(cache);
715 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
721 * return the block group that starts at or after bytenr
723 static struct btrfs_block_group_cache *
724 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
726 return block_group_cache_tree_search(info, bytenr, 0);
730 * return the block group that contains the given bytenr
732 struct btrfs_block_group_cache *btrfs_lookup_block_group(
733 struct btrfs_fs_info *info,
736 return block_group_cache_tree_search(info, bytenr, 1);
739 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
742 struct list_head *head = &info->space_info;
743 struct btrfs_space_info *found;
745 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
748 list_for_each_entry_rcu(found, head, list) {
749 if (found->flags & flags) {
759 * after adding space to the filesystem, we need to clear the full flags
760 * on all the space infos.
762 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
764 struct list_head *head = &info->space_info;
765 struct btrfs_space_info *found;
768 list_for_each_entry_rcu(found, head, list)
773 /* simple helper to search for an existing data extent at a given offset */
774 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
777 struct btrfs_key key;
778 struct btrfs_path *path;
780 path = btrfs_alloc_path();
784 key.objectid = start;
786 key.type = BTRFS_EXTENT_ITEM_KEY;
787 ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
788 btrfs_free_path(path);
793 * helper function to lookup reference count and flags of a tree block.
795 * the head node for delayed ref is used to store the sum of all the
796 * reference count modifications queued up in the rbtree. the head
797 * node may also store the extent flags to set. This way you can check
798 * to see what the reference count and extent flags would be if all of
799 * the delayed refs are not processed.
801 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
802 struct btrfs_fs_info *fs_info, u64 bytenr,
803 u64 offset, int metadata, u64 *refs, u64 *flags)
805 struct btrfs_delayed_ref_head *head;
806 struct btrfs_delayed_ref_root *delayed_refs;
807 struct btrfs_path *path;
808 struct btrfs_extent_item *ei;
809 struct extent_buffer *leaf;
810 struct btrfs_key key;
817 * If we don't have skinny metadata, don't bother doing anything
820 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
821 offset = fs_info->nodesize;
825 path = btrfs_alloc_path();
830 path->skip_locking = 1;
831 path->search_commit_root = 1;
835 key.objectid = bytenr;
838 key.type = BTRFS_METADATA_ITEM_KEY;
840 key.type = BTRFS_EXTENT_ITEM_KEY;
842 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
846 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
847 if (path->slots[0]) {
849 btrfs_item_key_to_cpu(path->nodes[0], &key,
851 if (key.objectid == bytenr &&
852 key.type == BTRFS_EXTENT_ITEM_KEY &&
853 key.offset == fs_info->nodesize)
859 leaf = path->nodes[0];
860 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
861 if (item_size >= sizeof(*ei)) {
862 ei = btrfs_item_ptr(leaf, path->slots[0],
863 struct btrfs_extent_item);
864 num_refs = btrfs_extent_refs(leaf, ei);
865 extent_flags = btrfs_extent_flags(leaf, ei);
867 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
868 struct btrfs_extent_item_v0 *ei0;
869 BUG_ON(item_size != sizeof(*ei0));
870 ei0 = btrfs_item_ptr(leaf, path->slots[0],
871 struct btrfs_extent_item_v0);
872 num_refs = btrfs_extent_refs_v0(leaf, ei0);
873 /* FIXME: this isn't correct for data */
874 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
879 BUG_ON(num_refs == 0);
889 delayed_refs = &trans->transaction->delayed_refs;
890 spin_lock(&delayed_refs->lock);
891 head = btrfs_find_delayed_ref_head(trans, bytenr);
893 if (!mutex_trylock(&head->mutex)) {
894 atomic_inc(&head->node.refs);
895 spin_unlock(&delayed_refs->lock);
897 btrfs_release_path(path);
900 * Mutex was contended, block until it's released and try
903 mutex_lock(&head->mutex);
904 mutex_unlock(&head->mutex);
905 btrfs_put_delayed_ref(&head->node);
908 spin_lock(&head->lock);
909 if (head->extent_op && head->extent_op->update_flags)
910 extent_flags |= head->extent_op->flags_to_set;
912 BUG_ON(num_refs == 0);
914 num_refs += head->node.ref_mod;
915 spin_unlock(&head->lock);
916 mutex_unlock(&head->mutex);
918 spin_unlock(&delayed_refs->lock);
920 WARN_ON(num_refs == 0);
924 *flags = extent_flags;
926 btrfs_free_path(path);
931 * Back reference rules. Back refs have three main goals:
933 * 1) differentiate between all holders of references to an extent so that
934 * when a reference is dropped we can make sure it was a valid reference
935 * before freeing the extent.
937 * 2) Provide enough information to quickly find the holders of an extent
938 * if we notice a given block is corrupted or bad.
940 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
941 * maintenance. This is actually the same as #2, but with a slightly
942 * different use case.
944 * There are two kinds of back refs. The implicit back refs is optimized
945 * for pointers in non-shared tree blocks. For a given pointer in a block,
946 * back refs of this kind provide information about the block's owner tree
947 * and the pointer's key. These information allow us to find the block by
948 * b-tree searching. The full back refs is for pointers in tree blocks not
949 * referenced by their owner trees. The location of tree block is recorded
950 * in the back refs. Actually the full back refs is generic, and can be
951 * used in all cases the implicit back refs is used. The major shortcoming
952 * of the full back refs is its overhead. Every time a tree block gets
953 * COWed, we have to update back refs entry for all pointers in it.
955 * For a newly allocated tree block, we use implicit back refs for
956 * pointers in it. This means most tree related operations only involve
957 * implicit back refs. For a tree block created in old transaction, the
958 * only way to drop a reference to it is COW it. So we can detect the
959 * event that tree block loses its owner tree's reference and do the
960 * back refs conversion.
962 * When a tree block is COWed through a tree, there are four cases:
964 * The reference count of the block is one and the tree is the block's
965 * owner tree. Nothing to do in this case.
967 * The reference count of the block is one and the tree is not the
968 * block's owner tree. In this case, full back refs is used for pointers
969 * in the block. Remove these full back refs, add implicit back refs for
970 * every pointers in the new block.
972 * The reference count of the block is greater than one and the tree is
973 * the block's owner tree. In this case, implicit back refs is used for
974 * pointers in the block. Add full back refs for every pointers in the
975 * block, increase lower level extents' reference counts. The original
976 * implicit back refs are entailed to the new block.
978 * The reference count of the block is greater than one and the tree is
979 * not the block's owner tree. Add implicit back refs for every pointer in
980 * the new block, increase lower level extents' reference count.
982 * Back Reference Key composing:
984 * The key objectid corresponds to the first byte in the extent,
985 * The key type is used to differentiate between types of back refs.
986 * There are different meanings of the key offset for different types
989 * File extents can be referenced by:
991 * - multiple snapshots, subvolumes, or different generations in one subvol
992 * - different files inside a single subvolume
993 * - different offsets inside a file (bookend extents in file.c)
995 * The extent ref structure for the implicit back refs has fields for:
997 * - Objectid of the subvolume root
998 * - objectid of the file holding the reference
999 * - original offset in the file
1000 * - how many bookend extents
1002 * The key offset for the implicit back refs is hash of the first
1005 * The extent ref structure for the full back refs has field for:
1007 * - number of pointers in the tree leaf
1009 * The key offset for the implicit back refs is the first byte of
1012 * When a file extent is allocated, The implicit back refs is used.
1013 * the fields are filled in:
1015 * (root_key.objectid, inode objectid, offset in file, 1)
1017 * When a file extent is removed file truncation, we find the
1018 * corresponding implicit back refs and check the following fields:
1020 * (btrfs_header_owner(leaf), inode objectid, offset in file)
1022 * Btree extents can be referenced by:
1024 * - Different subvolumes
1026 * Both the implicit back refs and the full back refs for tree blocks
1027 * only consist of key. The key offset for the implicit back refs is
1028 * objectid of block's owner tree. The key offset for the full back refs
1029 * is the first byte of parent block.
1031 * When implicit back refs is used, information about the lowest key and
1032 * level of the tree block are required. These information are stored in
1033 * tree block info structure.
1036 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1037 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
1038 struct btrfs_root *root,
1039 struct btrfs_path *path,
1040 u64 owner, u32 extra_size)
1042 struct btrfs_extent_item *item;
1043 struct btrfs_extent_item_v0 *ei0;
1044 struct btrfs_extent_ref_v0 *ref0;
1045 struct btrfs_tree_block_info *bi;
1046 struct extent_buffer *leaf;
1047 struct btrfs_key key;
1048 struct btrfs_key found_key;
1049 u32 new_size = sizeof(*item);
1053 leaf = path->nodes[0];
1054 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1056 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1057 ei0 = btrfs_item_ptr(leaf, path->slots[0],
1058 struct btrfs_extent_item_v0);
1059 refs = btrfs_extent_refs_v0(leaf, ei0);
1061 if (owner == (u64)-1) {
1063 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1064 ret = btrfs_next_leaf(root, path);
1067 BUG_ON(ret > 0); /* Corruption */
1068 leaf = path->nodes[0];
1070 btrfs_item_key_to_cpu(leaf, &found_key,
1072 BUG_ON(key.objectid != found_key.objectid);
1073 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1077 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1078 struct btrfs_extent_ref_v0);
1079 owner = btrfs_ref_objectid_v0(leaf, ref0);
1083 btrfs_release_path(path);
1085 if (owner < BTRFS_FIRST_FREE_OBJECTID)
1086 new_size += sizeof(*bi);
1088 new_size -= sizeof(*ei0);
1089 ret = btrfs_search_slot(trans, root, &key, path,
1090 new_size + extra_size, 1);
1093 BUG_ON(ret); /* Corruption */
1095 btrfs_extend_item(root->fs_info, path, new_size);
1097 leaf = path->nodes[0];
1098 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1099 btrfs_set_extent_refs(leaf, item, refs);
1100 /* FIXME: get real generation */
1101 btrfs_set_extent_generation(leaf, item, 0);
1102 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1103 btrfs_set_extent_flags(leaf, item,
1104 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1105 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1106 bi = (struct btrfs_tree_block_info *)(item + 1);
1107 /* FIXME: get first key of the block */
1108 memzero_extent_buffer(leaf, (unsigned long)bi, sizeof(*bi));
1109 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1111 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1113 btrfs_mark_buffer_dirty(leaf);
1118 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1120 u32 high_crc = ~(u32)0;
1121 u32 low_crc = ~(u32)0;
1124 lenum = cpu_to_le64(root_objectid);
1125 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1126 lenum = cpu_to_le64(owner);
1127 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1128 lenum = cpu_to_le64(offset);
1129 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1131 return ((u64)high_crc << 31) ^ (u64)low_crc;
1134 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1135 struct btrfs_extent_data_ref *ref)
1137 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1138 btrfs_extent_data_ref_objectid(leaf, ref),
1139 btrfs_extent_data_ref_offset(leaf, ref));
1142 static int match_extent_data_ref(struct extent_buffer *leaf,
1143 struct btrfs_extent_data_ref *ref,
1144 u64 root_objectid, u64 owner, u64 offset)
1146 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1147 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1148 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1153 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1154 struct btrfs_root *root,
1155 struct btrfs_path *path,
1156 u64 bytenr, u64 parent,
1158 u64 owner, u64 offset)
1160 struct btrfs_key key;
1161 struct btrfs_extent_data_ref *ref;
1162 struct extent_buffer *leaf;
1168 key.objectid = bytenr;
1170 key.type = BTRFS_SHARED_DATA_REF_KEY;
1171 key.offset = parent;
1173 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1174 key.offset = hash_extent_data_ref(root_objectid,
1179 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1188 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1189 key.type = BTRFS_EXTENT_REF_V0_KEY;
1190 btrfs_release_path(path);
1191 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1202 leaf = path->nodes[0];
1203 nritems = btrfs_header_nritems(leaf);
1205 if (path->slots[0] >= nritems) {
1206 ret = btrfs_next_leaf(root, path);
1212 leaf = path->nodes[0];
1213 nritems = btrfs_header_nritems(leaf);
1217 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1218 if (key.objectid != bytenr ||
1219 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1222 ref = btrfs_item_ptr(leaf, path->slots[0],
1223 struct btrfs_extent_data_ref);
1225 if (match_extent_data_ref(leaf, ref, root_objectid,
1228 btrfs_release_path(path);
1240 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1241 struct btrfs_root *root,
1242 struct btrfs_path *path,
1243 u64 bytenr, u64 parent,
1244 u64 root_objectid, u64 owner,
1245 u64 offset, int refs_to_add)
1247 struct btrfs_key key;
1248 struct extent_buffer *leaf;
1253 key.objectid = bytenr;
1255 key.type = BTRFS_SHARED_DATA_REF_KEY;
1256 key.offset = parent;
1257 size = sizeof(struct btrfs_shared_data_ref);
1259 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1260 key.offset = hash_extent_data_ref(root_objectid,
1262 size = sizeof(struct btrfs_extent_data_ref);
1265 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1266 if (ret && ret != -EEXIST)
1269 leaf = path->nodes[0];
1271 struct btrfs_shared_data_ref *ref;
1272 ref = btrfs_item_ptr(leaf, path->slots[0],
1273 struct btrfs_shared_data_ref);
1275 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1277 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1278 num_refs += refs_to_add;
1279 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1282 struct btrfs_extent_data_ref *ref;
1283 while (ret == -EEXIST) {
1284 ref = btrfs_item_ptr(leaf, path->slots[0],
1285 struct btrfs_extent_data_ref);
1286 if (match_extent_data_ref(leaf, ref, root_objectid,
1289 btrfs_release_path(path);
1291 ret = btrfs_insert_empty_item(trans, root, path, &key,
1293 if (ret && ret != -EEXIST)
1296 leaf = path->nodes[0];
1298 ref = btrfs_item_ptr(leaf, path->slots[0],
1299 struct btrfs_extent_data_ref);
1301 btrfs_set_extent_data_ref_root(leaf, ref,
1303 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1304 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1305 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1307 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1308 num_refs += refs_to_add;
1309 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1312 btrfs_mark_buffer_dirty(leaf);
1315 btrfs_release_path(path);
1319 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1320 struct btrfs_root *root,
1321 struct btrfs_path *path,
1322 int refs_to_drop, int *last_ref)
1324 struct btrfs_key key;
1325 struct btrfs_extent_data_ref *ref1 = NULL;
1326 struct btrfs_shared_data_ref *ref2 = NULL;
1327 struct extent_buffer *leaf;
1331 leaf = path->nodes[0];
1332 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1334 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1335 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1336 struct btrfs_extent_data_ref);
1337 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1338 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1339 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1340 struct btrfs_shared_data_ref);
1341 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1342 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1343 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1344 struct btrfs_extent_ref_v0 *ref0;
1345 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1346 struct btrfs_extent_ref_v0);
1347 num_refs = btrfs_ref_count_v0(leaf, ref0);
1353 BUG_ON(num_refs < refs_to_drop);
1354 num_refs -= refs_to_drop;
1356 if (num_refs == 0) {
1357 ret = btrfs_del_item(trans, root, path);
1360 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1361 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1362 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1363 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1364 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1366 struct btrfs_extent_ref_v0 *ref0;
1367 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1368 struct btrfs_extent_ref_v0);
1369 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1372 btrfs_mark_buffer_dirty(leaf);
1377 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1378 struct btrfs_extent_inline_ref *iref)
1380 struct btrfs_key key;
1381 struct extent_buffer *leaf;
1382 struct btrfs_extent_data_ref *ref1;
1383 struct btrfs_shared_data_ref *ref2;
1386 leaf = path->nodes[0];
1387 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1389 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1390 BTRFS_EXTENT_DATA_REF_KEY) {
1391 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1392 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1394 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1395 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1397 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1398 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1399 struct btrfs_extent_data_ref);
1400 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1401 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1402 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1403 struct btrfs_shared_data_ref);
1404 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1405 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1406 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1407 struct btrfs_extent_ref_v0 *ref0;
1408 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1409 struct btrfs_extent_ref_v0);
1410 num_refs = btrfs_ref_count_v0(leaf, ref0);
1418 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1419 struct btrfs_root *root,
1420 struct btrfs_path *path,
1421 u64 bytenr, u64 parent,
1424 struct btrfs_key key;
1427 key.objectid = bytenr;
1429 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1430 key.offset = parent;
1432 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1433 key.offset = root_objectid;
1436 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1439 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1440 if (ret == -ENOENT && parent) {
1441 btrfs_release_path(path);
1442 key.type = BTRFS_EXTENT_REF_V0_KEY;
1443 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1451 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1452 struct btrfs_root *root,
1453 struct btrfs_path *path,
1454 u64 bytenr, u64 parent,
1457 struct btrfs_key key;
1460 key.objectid = bytenr;
1462 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1463 key.offset = parent;
1465 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1466 key.offset = root_objectid;
1469 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1470 btrfs_release_path(path);
1474 static inline int extent_ref_type(u64 parent, u64 owner)
1477 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1479 type = BTRFS_SHARED_BLOCK_REF_KEY;
1481 type = BTRFS_TREE_BLOCK_REF_KEY;
1484 type = BTRFS_SHARED_DATA_REF_KEY;
1486 type = BTRFS_EXTENT_DATA_REF_KEY;
1491 static int find_next_key(struct btrfs_path *path, int level,
1492 struct btrfs_key *key)
1495 for (; level < BTRFS_MAX_LEVEL; level++) {
1496 if (!path->nodes[level])
1498 if (path->slots[level] + 1 >=
1499 btrfs_header_nritems(path->nodes[level]))
1502 btrfs_item_key_to_cpu(path->nodes[level], key,
1503 path->slots[level] + 1);
1505 btrfs_node_key_to_cpu(path->nodes[level], key,
1506 path->slots[level] + 1);
1513 * look for inline back ref. if back ref is found, *ref_ret is set
1514 * to the address of inline back ref, and 0 is returned.
1516 * if back ref isn't found, *ref_ret is set to the address where it
1517 * should be inserted, and -ENOENT is returned.
1519 * if insert is true and there are too many inline back refs, the path
1520 * points to the extent item, and -EAGAIN is returned.
1522 * NOTE: inline back refs are ordered in the same way that back ref
1523 * items in the tree are ordered.
1525 static noinline_for_stack
1526 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1527 struct btrfs_root *root,
1528 struct btrfs_path *path,
1529 struct btrfs_extent_inline_ref **ref_ret,
1530 u64 bytenr, u64 num_bytes,
1531 u64 parent, u64 root_objectid,
1532 u64 owner, u64 offset, int insert)
1534 struct btrfs_fs_info *fs_info = root->fs_info;
1535 struct btrfs_key key;
1536 struct extent_buffer *leaf;
1537 struct btrfs_extent_item *ei;
1538 struct btrfs_extent_inline_ref *iref;
1548 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1550 key.objectid = bytenr;
1551 key.type = BTRFS_EXTENT_ITEM_KEY;
1552 key.offset = num_bytes;
1554 want = extent_ref_type(parent, owner);
1556 extra_size = btrfs_extent_inline_ref_size(want);
1557 path->keep_locks = 1;
1562 * Owner is our parent level, so we can just add one to get the level
1563 * for the block we are interested in.
1565 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1566 key.type = BTRFS_METADATA_ITEM_KEY;
1571 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1578 * We may be a newly converted file system which still has the old fat
1579 * extent entries for metadata, so try and see if we have one of those.
1581 if (ret > 0 && skinny_metadata) {
1582 skinny_metadata = false;
1583 if (path->slots[0]) {
1585 btrfs_item_key_to_cpu(path->nodes[0], &key,
1587 if (key.objectid == bytenr &&
1588 key.type == BTRFS_EXTENT_ITEM_KEY &&
1589 key.offset == num_bytes)
1593 key.objectid = bytenr;
1594 key.type = BTRFS_EXTENT_ITEM_KEY;
1595 key.offset = num_bytes;
1596 btrfs_release_path(path);
1601 if (ret && !insert) {
1604 } else if (WARN_ON(ret)) {
1609 leaf = path->nodes[0];
1610 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1611 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1612 if (item_size < sizeof(*ei)) {
1617 ret = convert_extent_item_v0(trans, root, path, owner,
1623 leaf = path->nodes[0];
1624 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1627 BUG_ON(item_size < sizeof(*ei));
1629 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1630 flags = btrfs_extent_flags(leaf, ei);
1632 ptr = (unsigned long)(ei + 1);
1633 end = (unsigned long)ei + item_size;
1635 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1636 ptr += sizeof(struct btrfs_tree_block_info);
1646 iref = (struct btrfs_extent_inline_ref *)ptr;
1647 type = btrfs_extent_inline_ref_type(leaf, iref);
1651 ptr += btrfs_extent_inline_ref_size(type);
1655 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1656 struct btrfs_extent_data_ref *dref;
1657 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1658 if (match_extent_data_ref(leaf, dref, root_objectid,
1663 if (hash_extent_data_ref_item(leaf, dref) <
1664 hash_extent_data_ref(root_objectid, owner, offset))
1668 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1670 if (parent == ref_offset) {
1674 if (ref_offset < parent)
1677 if (root_objectid == ref_offset) {
1681 if (ref_offset < root_objectid)
1685 ptr += btrfs_extent_inline_ref_size(type);
1687 if (err == -ENOENT && insert) {
1688 if (item_size + extra_size >=
1689 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1694 * To add new inline back ref, we have to make sure
1695 * there is no corresponding back ref item.
1696 * For simplicity, we just do not add new inline back
1697 * ref if there is any kind of item for this block
1699 if (find_next_key(path, 0, &key) == 0 &&
1700 key.objectid == bytenr &&
1701 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1706 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1709 path->keep_locks = 0;
1710 btrfs_unlock_up_safe(path, 1);
1716 * helper to add new inline back ref
1718 static noinline_for_stack
1719 void setup_inline_extent_backref(struct btrfs_root *root,
1720 struct btrfs_path *path,
1721 struct btrfs_extent_inline_ref *iref,
1722 u64 parent, u64 root_objectid,
1723 u64 owner, u64 offset, int refs_to_add,
1724 struct btrfs_delayed_extent_op *extent_op)
1726 struct extent_buffer *leaf;
1727 struct btrfs_extent_item *ei;
1730 unsigned long item_offset;
1735 leaf = path->nodes[0];
1736 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1737 item_offset = (unsigned long)iref - (unsigned long)ei;
1739 type = extent_ref_type(parent, owner);
1740 size = btrfs_extent_inline_ref_size(type);
1742 btrfs_extend_item(root->fs_info, path, size);
1744 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1745 refs = btrfs_extent_refs(leaf, ei);
1746 refs += refs_to_add;
1747 btrfs_set_extent_refs(leaf, ei, refs);
1749 __run_delayed_extent_op(extent_op, leaf, ei);
1751 ptr = (unsigned long)ei + item_offset;
1752 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1753 if (ptr < end - size)
1754 memmove_extent_buffer(leaf, ptr + size, ptr,
1757 iref = (struct btrfs_extent_inline_ref *)ptr;
1758 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1759 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1760 struct btrfs_extent_data_ref *dref;
1761 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1762 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1763 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1764 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1765 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1766 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1767 struct btrfs_shared_data_ref *sref;
1768 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1769 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1770 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1771 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1772 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1774 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1776 btrfs_mark_buffer_dirty(leaf);
1779 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1780 struct btrfs_root *root,
1781 struct btrfs_path *path,
1782 struct btrfs_extent_inline_ref **ref_ret,
1783 u64 bytenr, u64 num_bytes, u64 parent,
1784 u64 root_objectid, u64 owner, u64 offset)
1788 ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1789 bytenr, num_bytes, parent,
1790 root_objectid, owner, offset, 0);
1794 btrfs_release_path(path);
1797 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1798 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1801 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1802 root_objectid, owner, offset);
1808 * helper to update/remove inline back ref
1810 static noinline_for_stack
1811 void update_inline_extent_backref(struct btrfs_root *root,
1812 struct btrfs_path *path,
1813 struct btrfs_extent_inline_ref *iref,
1815 struct btrfs_delayed_extent_op *extent_op,
1818 struct extent_buffer *leaf;
1819 struct btrfs_extent_item *ei;
1820 struct btrfs_extent_data_ref *dref = NULL;
1821 struct btrfs_shared_data_ref *sref = NULL;
1829 leaf = path->nodes[0];
1830 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1831 refs = btrfs_extent_refs(leaf, ei);
1832 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1833 refs += refs_to_mod;
1834 btrfs_set_extent_refs(leaf, ei, refs);
1836 __run_delayed_extent_op(extent_op, leaf, ei);
1838 type = btrfs_extent_inline_ref_type(leaf, iref);
1840 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1841 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1842 refs = btrfs_extent_data_ref_count(leaf, dref);
1843 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1844 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1845 refs = btrfs_shared_data_ref_count(leaf, sref);
1848 BUG_ON(refs_to_mod != -1);
1851 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1852 refs += refs_to_mod;
1855 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1856 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1858 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1861 size = btrfs_extent_inline_ref_size(type);
1862 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1863 ptr = (unsigned long)iref;
1864 end = (unsigned long)ei + item_size;
1865 if (ptr + size < end)
1866 memmove_extent_buffer(leaf, ptr, ptr + size,
1869 btrfs_truncate_item(root->fs_info, path, item_size, 1);
1871 btrfs_mark_buffer_dirty(leaf);
1874 static noinline_for_stack
1875 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1876 struct btrfs_root *root,
1877 struct btrfs_path *path,
1878 u64 bytenr, u64 num_bytes, u64 parent,
1879 u64 root_objectid, u64 owner,
1880 u64 offset, int refs_to_add,
1881 struct btrfs_delayed_extent_op *extent_op)
1883 struct btrfs_extent_inline_ref *iref;
1886 ret = lookup_inline_extent_backref(trans, root, path, &iref,
1887 bytenr, num_bytes, parent,
1888 root_objectid, owner, offset, 1);
1890 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1891 update_inline_extent_backref(root, path, iref,
1892 refs_to_add, extent_op, NULL);
1893 } else if (ret == -ENOENT) {
1894 setup_inline_extent_backref(root, path, iref, parent,
1895 root_objectid, owner, offset,
1896 refs_to_add, extent_op);
1902 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1903 struct btrfs_root *root,
1904 struct btrfs_path *path,
1905 u64 bytenr, u64 parent, u64 root_objectid,
1906 u64 owner, u64 offset, int refs_to_add)
1909 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1910 BUG_ON(refs_to_add != 1);
1911 ret = insert_tree_block_ref(trans, root, path, bytenr,
1912 parent, root_objectid);
1914 ret = insert_extent_data_ref(trans, root, path, bytenr,
1915 parent, root_objectid,
1916 owner, offset, refs_to_add);
1921 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1922 struct btrfs_root *root,
1923 struct btrfs_path *path,
1924 struct btrfs_extent_inline_ref *iref,
1925 int refs_to_drop, int is_data, int *last_ref)
1929 BUG_ON(!is_data && refs_to_drop != 1);
1931 update_inline_extent_backref(root, path, iref,
1932 -refs_to_drop, NULL, last_ref);
1933 } else if (is_data) {
1934 ret = remove_extent_data_ref(trans, root, path, refs_to_drop,
1938 ret = btrfs_del_item(trans, root, path);
1943 #define in_range(b, first, len) ((b) >= (first) && (b) < (first) + (len))
1944 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1945 u64 *discarded_bytes)
1948 u64 bytes_left, end;
1949 u64 aligned_start = ALIGN(start, 1 << 9);
1951 if (WARN_ON(start != aligned_start)) {
1952 len -= aligned_start - start;
1953 len = round_down(len, 1 << 9);
1954 start = aligned_start;
1957 *discarded_bytes = 0;
1965 /* Skip any superblocks on this device. */
1966 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1967 u64 sb_start = btrfs_sb_offset(j);
1968 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1969 u64 size = sb_start - start;
1971 if (!in_range(sb_start, start, bytes_left) &&
1972 !in_range(sb_end, start, bytes_left) &&
1973 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1977 * Superblock spans beginning of range. Adjust start and
1980 if (sb_start <= start) {
1981 start += sb_end - start;
1986 bytes_left = end - start;
1991 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1994 *discarded_bytes += size;
1995 else if (ret != -EOPNOTSUPP)
2004 bytes_left = end - start;
2008 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
2011 *discarded_bytes += bytes_left;
2016 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
2017 u64 num_bytes, u64 *actual_bytes)
2020 u64 discarded_bytes = 0;
2021 struct btrfs_bio *bbio = NULL;
2025 * Avoid races with device replace and make sure our bbio has devices
2026 * associated to its stripes that don't go away while we are discarding.
2028 btrfs_bio_counter_inc_blocked(fs_info);
2029 /* Tell the block device(s) that the sectors can be discarded */
2030 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2032 /* Error condition is -ENOMEM */
2034 struct btrfs_bio_stripe *stripe = bbio->stripes;
2038 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2040 if (!stripe->dev->can_discard)
2043 ret = btrfs_issue_discard(stripe->dev->bdev,
2048 discarded_bytes += bytes;
2049 else if (ret != -EOPNOTSUPP)
2050 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2053 * Just in case we get back EOPNOTSUPP for some reason,
2054 * just ignore the return value so we don't screw up
2055 * people calling discard_extent.
2059 btrfs_put_bbio(bbio);
2061 btrfs_bio_counter_dec(fs_info);
2064 *actual_bytes = discarded_bytes;
2067 if (ret == -EOPNOTSUPP)
2072 /* Can return -ENOMEM */
2073 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2074 struct btrfs_fs_info *fs_info,
2075 u64 bytenr, u64 num_bytes, u64 parent,
2076 u64 root_objectid, u64 owner, u64 offset)
2080 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2081 root_objectid == BTRFS_TREE_LOG_OBJECTID);
2083 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
2084 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
2086 parent, root_objectid, (int)owner,
2087 BTRFS_ADD_DELAYED_REF, NULL);
2089 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
2090 num_bytes, parent, root_objectid,
2092 BTRFS_ADD_DELAYED_REF, NULL);
2097 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2098 struct btrfs_fs_info *fs_info,
2099 struct btrfs_delayed_ref_node *node,
2100 u64 parent, u64 root_objectid,
2101 u64 owner, u64 offset, int refs_to_add,
2102 struct btrfs_delayed_extent_op *extent_op)
2104 struct btrfs_path *path;
2105 struct extent_buffer *leaf;
2106 struct btrfs_extent_item *item;
2107 struct btrfs_key key;
2108 u64 bytenr = node->bytenr;
2109 u64 num_bytes = node->num_bytes;
2113 path = btrfs_alloc_path();
2117 path->reada = READA_FORWARD;
2118 path->leave_spinning = 1;
2119 /* this will setup the path even if it fails to insert the back ref */
2120 ret = insert_inline_extent_backref(trans, fs_info->extent_root, path,
2121 bytenr, num_bytes, parent,
2122 root_objectid, owner, offset,
2123 refs_to_add, extent_op);
2124 if ((ret < 0 && ret != -EAGAIN) || !ret)
2128 * Ok we had -EAGAIN which means we didn't have space to insert and
2129 * inline extent ref, so just update the reference count and add a
2132 leaf = path->nodes[0];
2133 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2134 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2135 refs = btrfs_extent_refs(leaf, item);
2136 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2138 __run_delayed_extent_op(extent_op, leaf, item);
2140 btrfs_mark_buffer_dirty(leaf);
2141 btrfs_release_path(path);
2143 path->reada = READA_FORWARD;
2144 path->leave_spinning = 1;
2145 /* now insert the actual backref */
2146 ret = insert_extent_backref(trans, fs_info->extent_root,
2147 path, bytenr, parent, root_objectid,
2148 owner, offset, refs_to_add);
2150 btrfs_abort_transaction(trans, ret);
2152 btrfs_free_path(path);
2156 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2157 struct btrfs_fs_info *fs_info,
2158 struct btrfs_delayed_ref_node *node,
2159 struct btrfs_delayed_extent_op *extent_op,
2160 int insert_reserved)
2163 struct btrfs_delayed_data_ref *ref;
2164 struct btrfs_key ins;
2169 ins.objectid = node->bytenr;
2170 ins.offset = node->num_bytes;
2171 ins.type = BTRFS_EXTENT_ITEM_KEY;
2173 ref = btrfs_delayed_node_to_data_ref(node);
2174 trace_run_delayed_data_ref(fs_info, node, ref, node->action);
2176 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2177 parent = ref->parent;
2178 ref_root = ref->root;
2180 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2182 flags |= extent_op->flags_to_set;
2183 ret = alloc_reserved_file_extent(trans, fs_info,
2184 parent, ref_root, flags,
2185 ref->objectid, ref->offset,
2186 &ins, node->ref_mod);
2187 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2188 ret = __btrfs_inc_extent_ref(trans, fs_info, node, parent,
2189 ref_root, ref->objectid,
2190 ref->offset, node->ref_mod,
2192 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2193 ret = __btrfs_free_extent(trans, fs_info, node, parent,
2194 ref_root, ref->objectid,
2195 ref->offset, node->ref_mod,
2203 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2204 struct extent_buffer *leaf,
2205 struct btrfs_extent_item *ei)
2207 u64 flags = btrfs_extent_flags(leaf, ei);
2208 if (extent_op->update_flags) {
2209 flags |= extent_op->flags_to_set;
2210 btrfs_set_extent_flags(leaf, ei, flags);
2213 if (extent_op->update_key) {
2214 struct btrfs_tree_block_info *bi;
2215 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2216 bi = (struct btrfs_tree_block_info *)(ei + 1);
2217 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2221 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2222 struct btrfs_fs_info *fs_info,
2223 struct btrfs_delayed_ref_node *node,
2224 struct btrfs_delayed_extent_op *extent_op)
2226 struct btrfs_key key;
2227 struct btrfs_path *path;
2228 struct btrfs_extent_item *ei;
2229 struct extent_buffer *leaf;
2233 int metadata = !extent_op->is_data;
2238 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2241 path = btrfs_alloc_path();
2245 key.objectid = node->bytenr;
2248 key.type = BTRFS_METADATA_ITEM_KEY;
2249 key.offset = extent_op->level;
2251 key.type = BTRFS_EXTENT_ITEM_KEY;
2252 key.offset = node->num_bytes;
2256 path->reada = READA_FORWARD;
2257 path->leave_spinning = 1;
2258 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2265 if (path->slots[0] > 0) {
2267 btrfs_item_key_to_cpu(path->nodes[0], &key,
2269 if (key.objectid == node->bytenr &&
2270 key.type == BTRFS_EXTENT_ITEM_KEY &&
2271 key.offset == node->num_bytes)
2275 btrfs_release_path(path);
2278 key.objectid = node->bytenr;
2279 key.offset = node->num_bytes;
2280 key.type = BTRFS_EXTENT_ITEM_KEY;
2289 leaf = path->nodes[0];
2290 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2291 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2292 if (item_size < sizeof(*ei)) {
2293 ret = convert_extent_item_v0(trans, fs_info->extent_root,
2299 leaf = path->nodes[0];
2300 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2303 BUG_ON(item_size < sizeof(*ei));
2304 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2305 __run_delayed_extent_op(extent_op, leaf, ei);
2307 btrfs_mark_buffer_dirty(leaf);
2309 btrfs_free_path(path);
2313 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2314 struct btrfs_fs_info *fs_info,
2315 struct btrfs_delayed_ref_node *node,
2316 struct btrfs_delayed_extent_op *extent_op,
2317 int insert_reserved)
2320 struct btrfs_delayed_tree_ref *ref;
2321 struct btrfs_key ins;
2324 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
2326 ref = btrfs_delayed_node_to_tree_ref(node);
2327 trace_run_delayed_tree_ref(fs_info, node, ref, node->action);
2329 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2330 parent = ref->parent;
2331 ref_root = ref->root;
2333 ins.objectid = node->bytenr;
2334 if (skinny_metadata) {
2335 ins.offset = ref->level;
2336 ins.type = BTRFS_METADATA_ITEM_KEY;
2338 ins.offset = node->num_bytes;
2339 ins.type = BTRFS_EXTENT_ITEM_KEY;
2342 if (node->ref_mod != 1) {
2344 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2345 node->bytenr, node->ref_mod, node->action, ref_root,
2349 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2350 BUG_ON(!extent_op || !extent_op->update_flags);
2351 ret = alloc_reserved_tree_block(trans, fs_info,
2353 extent_op->flags_to_set,
2356 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2357 ret = __btrfs_inc_extent_ref(trans, fs_info, node,
2361 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2362 ret = __btrfs_free_extent(trans, fs_info, node,
2364 ref->level, 0, 1, extent_op);
2371 /* helper function to actually process a single delayed ref entry */
2372 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2373 struct btrfs_fs_info *fs_info,
2374 struct btrfs_delayed_ref_node *node,
2375 struct btrfs_delayed_extent_op *extent_op,
2376 int insert_reserved)
2380 if (trans->aborted) {
2381 if (insert_reserved)
2382 btrfs_pin_extent(fs_info, node->bytenr,
2383 node->num_bytes, 1);
2387 if (btrfs_delayed_ref_is_head(node)) {
2388 struct btrfs_delayed_ref_head *head;
2390 * we've hit the end of the chain and we were supposed
2391 * to insert this extent into the tree. But, it got
2392 * deleted before we ever needed to insert it, so all
2393 * we have to do is clean up the accounting
2396 head = btrfs_delayed_node_to_head(node);
2397 trace_run_delayed_ref_head(fs_info, node, head, node->action);
2399 if (insert_reserved) {
2400 btrfs_pin_extent(fs_info, node->bytenr,
2401 node->num_bytes, 1);
2402 if (head->is_data) {
2403 ret = btrfs_del_csums(trans, fs_info,
2409 /* Also free its reserved qgroup space */
2410 btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
2411 head->qgroup_reserved);
2415 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2416 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2417 ret = run_delayed_tree_ref(trans, fs_info, node, extent_op,
2419 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2420 node->type == BTRFS_SHARED_DATA_REF_KEY)
2421 ret = run_delayed_data_ref(trans, fs_info, node, extent_op,
2428 static inline struct btrfs_delayed_ref_node *
2429 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2431 struct btrfs_delayed_ref_node *ref;
2433 if (list_empty(&head->ref_list))
2437 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2438 * This is to prevent a ref count from going down to zero, which deletes
2439 * the extent item from the extent tree, when there still are references
2440 * to add, which would fail because they would not find the extent item.
2442 if (!list_empty(&head->ref_add_list))
2443 return list_first_entry(&head->ref_add_list,
2444 struct btrfs_delayed_ref_node, add_list);
2446 ref = list_first_entry(&head->ref_list, struct btrfs_delayed_ref_node,
2448 ASSERT(list_empty(&ref->add_list));
2453 * Returns 0 on success or if called with an already aborted transaction.
2454 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2456 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2457 struct btrfs_fs_info *fs_info,
2460 struct btrfs_delayed_ref_root *delayed_refs;
2461 struct btrfs_delayed_ref_node *ref;
2462 struct btrfs_delayed_ref_head *locked_ref = NULL;
2463 struct btrfs_delayed_extent_op *extent_op;
2464 ktime_t start = ktime_get();
2466 unsigned long count = 0;
2467 unsigned long actual_count = 0;
2468 int must_insert_reserved = 0;
2470 delayed_refs = &trans->transaction->delayed_refs;
2476 spin_lock(&delayed_refs->lock);
2477 locked_ref = btrfs_select_ref_head(trans);
2479 spin_unlock(&delayed_refs->lock);
2483 /* grab the lock that says we are going to process
2484 * all the refs for this head */
2485 ret = btrfs_delayed_ref_lock(trans, locked_ref);
2486 spin_unlock(&delayed_refs->lock);
2488 * we may have dropped the spin lock to get the head
2489 * mutex lock, and that might have given someone else
2490 * time to free the head. If that's true, it has been
2491 * removed from our list and we can move on.
2493 if (ret == -EAGAIN) {
2501 * We need to try and merge add/drops of the same ref since we
2502 * can run into issues with relocate dropping the implicit ref
2503 * and then it being added back again before the drop can
2504 * finish. If we merged anything we need to re-loop so we can
2506 * Or we can get node references of the same type that weren't
2507 * merged when created due to bumps in the tree mod seq, and
2508 * we need to merge them to prevent adding an inline extent
2509 * backref before dropping it (triggering a BUG_ON at
2510 * insert_inline_extent_backref()).
2512 spin_lock(&locked_ref->lock);
2513 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2517 * locked_ref is the head node, so we have to go one
2518 * node back for any delayed ref updates
2520 ref = select_delayed_ref(locked_ref);
2522 if (ref && ref->seq &&
2523 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
2524 spin_unlock(&locked_ref->lock);
2525 spin_lock(&delayed_refs->lock);
2526 locked_ref->processing = 0;
2527 delayed_refs->num_heads_ready++;
2528 spin_unlock(&delayed_refs->lock);
2529 btrfs_delayed_ref_unlock(locked_ref);
2537 * record the must insert reserved flag before we
2538 * drop the spin lock.
2540 must_insert_reserved = locked_ref->must_insert_reserved;
2541 locked_ref->must_insert_reserved = 0;
2543 extent_op = locked_ref->extent_op;
2544 locked_ref->extent_op = NULL;
2549 /* All delayed refs have been processed, Go ahead
2550 * and send the head node to run_one_delayed_ref,
2551 * so that any accounting fixes can happen
2553 ref = &locked_ref->node;
2555 if (extent_op && must_insert_reserved) {
2556 btrfs_free_delayed_extent_op(extent_op);
2561 spin_unlock(&locked_ref->lock);
2562 ret = run_delayed_extent_op(trans, fs_info,
2564 btrfs_free_delayed_extent_op(extent_op);
2568 * Need to reset must_insert_reserved if
2569 * there was an error so the abort stuff
2570 * can cleanup the reserved space
2573 if (must_insert_reserved)
2574 locked_ref->must_insert_reserved = 1;
2575 spin_lock(&delayed_refs->lock);
2576 locked_ref->processing = 0;
2577 delayed_refs->num_heads_ready++;
2578 spin_unlock(&delayed_refs->lock);
2579 btrfs_debug(fs_info,
2580 "run_delayed_extent_op returned %d",
2582 btrfs_delayed_ref_unlock(locked_ref);
2589 * Need to drop our head ref lock and re-acquire the
2590 * delayed ref lock and then re-check to make sure
2593 spin_unlock(&locked_ref->lock);
2594 spin_lock(&delayed_refs->lock);
2595 spin_lock(&locked_ref->lock);
2596 if (!list_empty(&locked_ref->ref_list) ||
2597 locked_ref->extent_op) {
2598 spin_unlock(&locked_ref->lock);
2599 spin_unlock(&delayed_refs->lock);
2603 delayed_refs->num_heads--;
2604 rb_erase(&locked_ref->href_node,
2605 &delayed_refs->href_root);
2606 spin_unlock(&delayed_refs->lock);
2610 list_del(&ref->list);
2611 if (!list_empty(&ref->add_list))
2612 list_del(&ref->add_list);
2614 atomic_dec(&delayed_refs->num_entries);
2616 if (!btrfs_delayed_ref_is_head(ref)) {
2618 * when we play the delayed ref, also correct the
2621 switch (ref->action) {
2622 case BTRFS_ADD_DELAYED_REF:
2623 case BTRFS_ADD_DELAYED_EXTENT:
2624 locked_ref->node.ref_mod -= ref->ref_mod;
2626 case BTRFS_DROP_DELAYED_REF:
2627 locked_ref->node.ref_mod += ref->ref_mod;
2633 spin_unlock(&locked_ref->lock);
2635 ret = run_one_delayed_ref(trans, fs_info, ref, extent_op,
2636 must_insert_reserved);
2638 btrfs_free_delayed_extent_op(extent_op);
2640 spin_lock(&delayed_refs->lock);
2641 locked_ref->processing = 0;
2642 delayed_refs->num_heads_ready++;
2643 spin_unlock(&delayed_refs->lock);
2644 btrfs_delayed_ref_unlock(locked_ref);
2645 btrfs_put_delayed_ref(ref);
2646 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2652 * If this node is a head, that means all the refs in this head
2653 * have been dealt with, and we will pick the next head to deal
2654 * with, so we must unlock the head and drop it from the cluster
2655 * list before we release it.
2657 if (btrfs_delayed_ref_is_head(ref)) {
2658 if (locked_ref->is_data &&
2659 locked_ref->total_ref_mod < 0) {
2660 spin_lock(&delayed_refs->lock);
2661 delayed_refs->pending_csums -= ref->num_bytes;
2662 spin_unlock(&delayed_refs->lock);
2664 btrfs_delayed_ref_unlock(locked_ref);
2667 btrfs_put_delayed_ref(ref);
2673 * We don't want to include ref heads since we can have empty ref heads
2674 * and those will drastically skew our runtime down since we just do
2675 * accounting, no actual extent tree updates.
2677 if (actual_count > 0) {
2678 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2682 * We weigh the current average higher than our current runtime
2683 * to avoid large swings in the average.
2685 spin_lock(&delayed_refs->lock);
2686 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2687 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2688 spin_unlock(&delayed_refs->lock);
2693 #ifdef SCRAMBLE_DELAYED_REFS
2695 * Normally delayed refs get processed in ascending bytenr order. This
2696 * correlates in most cases to the order added. To expose dependencies on this
2697 * order, we start to process the tree in the middle instead of the beginning
2699 static u64 find_middle(struct rb_root *root)
2701 struct rb_node *n = root->rb_node;
2702 struct btrfs_delayed_ref_node *entry;
2705 u64 first = 0, last = 0;
2709 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2710 first = entry->bytenr;
2714 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2715 last = entry->bytenr;
2720 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2721 WARN_ON(!entry->in_tree);
2723 middle = entry->bytenr;
2736 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2740 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2741 sizeof(struct btrfs_extent_inline_ref));
2742 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2743 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2746 * We don't ever fill up leaves all the way so multiply by 2 just to be
2747 * closer to what we're really going to want to use.
2749 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2753 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2754 * would require to store the csums for that many bytes.
2756 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2759 u64 num_csums_per_leaf;
2762 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2763 num_csums_per_leaf = div64_u64(csum_size,
2764 (u64)btrfs_super_csum_size(fs_info->super_copy));
2765 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2766 num_csums += num_csums_per_leaf - 1;
2767 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2771 int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2772 struct btrfs_fs_info *fs_info)
2774 struct btrfs_block_rsv *global_rsv;
2775 u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2776 u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
2777 u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
2778 u64 num_bytes, num_dirty_bgs_bytes;
2781 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
2782 num_heads = heads_to_leaves(fs_info, num_heads);
2784 num_bytes += (num_heads - 1) * fs_info->nodesize;
2786 num_bytes += btrfs_csum_bytes_to_leaves(fs_info, csum_bytes) *
2788 num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
2790 global_rsv = &fs_info->global_block_rsv;
2793 * If we can't allocate any more chunks lets make sure we have _lots_ of
2794 * wiggle room since running delayed refs can create more delayed refs.
2796 if (global_rsv->space_info->full) {
2797 num_dirty_bgs_bytes <<= 1;
2801 spin_lock(&global_rsv->lock);
2802 if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
2804 spin_unlock(&global_rsv->lock);
2808 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2809 struct btrfs_fs_info *fs_info)
2812 atomic_read(&trans->transaction->delayed_refs.num_entries);
2817 avg_runtime = fs_info->avg_delayed_ref_runtime;
2818 val = num_entries * avg_runtime;
2819 if (val >= NSEC_PER_SEC)
2821 if (val >= NSEC_PER_SEC / 2)
2824 return btrfs_check_space_for_delayed_refs(trans, fs_info);
2827 struct async_delayed_refs {
2828 struct btrfs_root *root;
2833 struct completion wait;
2834 struct btrfs_work work;
2837 static inline struct async_delayed_refs *
2838 to_async_delayed_refs(struct btrfs_work *work)
2840 return container_of(work, struct async_delayed_refs, work);
2843 static void delayed_ref_async_start(struct btrfs_work *work)
2845 struct async_delayed_refs *async = to_async_delayed_refs(work);
2846 struct btrfs_trans_handle *trans;
2847 struct btrfs_fs_info *fs_info = async->root->fs_info;
2850 /* if the commit is already started, we don't need to wait here */
2851 if (btrfs_transaction_blocked(fs_info))
2854 trans = btrfs_join_transaction(async->root);
2855 if (IS_ERR(trans)) {
2856 async->error = PTR_ERR(trans);
2861 * trans->sync means that when we call end_transaction, we won't
2862 * wait on delayed refs
2866 /* Don't bother flushing if we got into a different transaction */
2867 if (trans->transid > async->transid)
2870 ret = btrfs_run_delayed_refs(trans, fs_info, async->count);
2874 ret = btrfs_end_transaction(trans);
2875 if (ret && !async->error)
2879 complete(&async->wait);
2884 int btrfs_async_run_delayed_refs(struct btrfs_fs_info *fs_info,
2885 unsigned long count, u64 transid, int wait)
2887 struct async_delayed_refs *async;
2890 async = kmalloc(sizeof(*async), GFP_NOFS);
2894 async->root = fs_info->tree_root;
2895 async->count = count;
2897 async->transid = transid;
2902 init_completion(&async->wait);
2904 btrfs_init_work(&async->work, btrfs_extent_refs_helper,
2905 delayed_ref_async_start, NULL, NULL);
2907 btrfs_queue_work(fs_info->extent_workers, &async->work);
2910 wait_for_completion(&async->wait);
2919 * this starts processing the delayed reference count updates and
2920 * extent insertions we have queued up so far. count can be
2921 * 0, which means to process everything in the tree at the start
2922 * of the run (but not newly added entries), or it can be some target
2923 * number you'd like to process.
2925 * Returns 0 on success or if called with an aborted transaction
2926 * Returns <0 on error and aborts the transaction
2928 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2929 struct btrfs_fs_info *fs_info, unsigned long count)
2931 struct rb_node *node;
2932 struct btrfs_delayed_ref_root *delayed_refs;
2933 struct btrfs_delayed_ref_head *head;
2935 int run_all = count == (unsigned long)-1;
2936 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
2938 /* We'll clean this up in btrfs_cleanup_transaction */
2942 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2945 delayed_refs = &trans->transaction->delayed_refs;
2947 count = atomic_read(&delayed_refs->num_entries) * 2;
2950 #ifdef SCRAMBLE_DELAYED_REFS
2951 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2953 trans->can_flush_pending_bgs = false;
2954 ret = __btrfs_run_delayed_refs(trans, fs_info, count);
2956 btrfs_abort_transaction(trans, ret);
2961 if (!list_empty(&trans->new_bgs))
2962 btrfs_create_pending_block_groups(trans, fs_info);
2964 spin_lock(&delayed_refs->lock);
2965 node = rb_first(&delayed_refs->href_root);
2967 spin_unlock(&delayed_refs->lock);
2972 head = rb_entry(node, struct btrfs_delayed_ref_head,
2974 if (btrfs_delayed_ref_is_head(&head->node)) {
2975 struct btrfs_delayed_ref_node *ref;
2978 atomic_inc(&ref->refs);
2980 spin_unlock(&delayed_refs->lock);
2982 * Mutex was contended, block until it's
2983 * released and try again
2985 mutex_lock(&head->mutex);
2986 mutex_unlock(&head->mutex);
2988 btrfs_put_delayed_ref(ref);
2994 node = rb_next(node);
2996 spin_unlock(&delayed_refs->lock);
3001 assert_qgroups_uptodate(trans);
3002 trans->can_flush_pending_bgs = can_flush_pending_bgs;
3006 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
3007 struct btrfs_fs_info *fs_info,
3008 u64 bytenr, u64 num_bytes, u64 flags,
3009 int level, int is_data)
3011 struct btrfs_delayed_extent_op *extent_op;
3014 extent_op = btrfs_alloc_delayed_extent_op();
3018 extent_op->flags_to_set = flags;
3019 extent_op->update_flags = true;
3020 extent_op->update_key = false;
3021 extent_op->is_data = is_data ? true : false;
3022 extent_op->level = level;
3024 ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
3025 num_bytes, extent_op);
3027 btrfs_free_delayed_extent_op(extent_op);
3031 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
3032 struct btrfs_root *root,
3033 struct btrfs_path *path,
3034 u64 objectid, u64 offset, u64 bytenr)
3036 struct btrfs_delayed_ref_head *head;
3037 struct btrfs_delayed_ref_node *ref;
3038 struct btrfs_delayed_data_ref *data_ref;
3039 struct btrfs_delayed_ref_root *delayed_refs;
3042 delayed_refs = &trans->transaction->delayed_refs;
3043 spin_lock(&delayed_refs->lock);
3044 head = btrfs_find_delayed_ref_head(trans, bytenr);
3046 spin_unlock(&delayed_refs->lock);
3050 if (!mutex_trylock(&head->mutex)) {
3051 atomic_inc(&head->node.refs);
3052 spin_unlock(&delayed_refs->lock);
3054 btrfs_release_path(path);
3057 * Mutex was contended, block until it's released and let
3060 mutex_lock(&head->mutex);
3061 mutex_unlock(&head->mutex);
3062 btrfs_put_delayed_ref(&head->node);
3065 spin_unlock(&delayed_refs->lock);
3067 spin_lock(&head->lock);
3068 list_for_each_entry(ref, &head->ref_list, list) {
3069 /* If it's a shared ref we know a cross reference exists */
3070 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3075 data_ref = btrfs_delayed_node_to_data_ref(ref);
3078 * If our ref doesn't match the one we're currently looking at
3079 * then we have a cross reference.
3081 if (data_ref->root != root->root_key.objectid ||
3082 data_ref->objectid != objectid ||
3083 data_ref->offset != offset) {
3088 spin_unlock(&head->lock);
3089 mutex_unlock(&head->mutex);
3093 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
3094 struct btrfs_root *root,
3095 struct btrfs_path *path,
3096 u64 objectid, u64 offset, u64 bytenr)
3098 struct btrfs_fs_info *fs_info = root->fs_info;
3099 struct btrfs_root *extent_root = fs_info->extent_root;
3100 struct extent_buffer *leaf;
3101 struct btrfs_extent_data_ref *ref;
3102 struct btrfs_extent_inline_ref *iref;
3103 struct btrfs_extent_item *ei;
3104 struct btrfs_key key;
3108 key.objectid = bytenr;
3109 key.offset = (u64)-1;
3110 key.type = BTRFS_EXTENT_ITEM_KEY;
3112 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3115 BUG_ON(ret == 0); /* Corruption */
3118 if (path->slots[0] == 0)
3122 leaf = path->nodes[0];
3123 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3125 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3129 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3130 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3131 if (item_size < sizeof(*ei)) {
3132 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
3136 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3138 if (item_size != sizeof(*ei) +
3139 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3142 if (btrfs_extent_generation(leaf, ei) <=
3143 btrfs_root_last_snapshot(&root->root_item))
3146 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3147 if (btrfs_extent_inline_ref_type(leaf, iref) !=
3148 BTRFS_EXTENT_DATA_REF_KEY)
3151 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3152 if (btrfs_extent_refs(leaf, ei) !=
3153 btrfs_extent_data_ref_count(leaf, ref) ||
3154 btrfs_extent_data_ref_root(leaf, ref) !=
3155 root->root_key.objectid ||
3156 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3157 btrfs_extent_data_ref_offset(leaf, ref) != offset)
3165 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
3166 struct btrfs_root *root,
3167 u64 objectid, u64 offset, u64 bytenr)
3169 struct btrfs_path *path;
3173 path = btrfs_alloc_path();
3178 ret = check_committed_ref(trans, root, path, objectid,
3180 if (ret && ret != -ENOENT)
3183 ret2 = check_delayed_ref(trans, root, path, objectid,
3185 } while (ret2 == -EAGAIN);
3187 if (ret2 && ret2 != -ENOENT) {
3192 if (ret != -ENOENT || ret2 != -ENOENT)
3195 btrfs_free_path(path);
3196 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3201 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3202 struct btrfs_root *root,
3203 struct extent_buffer *buf,
3204 int full_backref, int inc)
3206 struct btrfs_fs_info *fs_info = root->fs_info;
3212 struct btrfs_key key;
3213 struct btrfs_file_extent_item *fi;
3217 int (*process_func)(struct btrfs_trans_handle *,
3218 struct btrfs_fs_info *,
3219 u64, u64, u64, u64, u64, u64);
3222 if (btrfs_is_testing(fs_info))
3225 ref_root = btrfs_header_owner(buf);
3226 nritems = btrfs_header_nritems(buf);
3227 level = btrfs_header_level(buf);
3229 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3233 process_func = btrfs_inc_extent_ref;
3235 process_func = btrfs_free_extent;
3238 parent = buf->start;
3242 for (i = 0; i < nritems; i++) {
3244 btrfs_item_key_to_cpu(buf, &key, i);
3245 if (key.type != BTRFS_EXTENT_DATA_KEY)
3247 fi = btrfs_item_ptr(buf, i,
3248 struct btrfs_file_extent_item);
3249 if (btrfs_file_extent_type(buf, fi) ==
3250 BTRFS_FILE_EXTENT_INLINE)
3252 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3256 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3257 key.offset -= btrfs_file_extent_offset(buf, fi);
3258 ret = process_func(trans, fs_info, bytenr, num_bytes,
3259 parent, ref_root, key.objectid,
3264 bytenr = btrfs_node_blockptr(buf, i);
3265 num_bytes = fs_info->nodesize;
3266 ret = process_func(trans, fs_info, bytenr, num_bytes,
3267 parent, ref_root, level - 1, 0);
3277 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3278 struct extent_buffer *buf, int full_backref)
3280 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3283 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3284 struct extent_buffer *buf, int full_backref)
3286 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3289 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3290 struct btrfs_fs_info *fs_info,
3291 struct btrfs_path *path,
3292 struct btrfs_block_group_cache *cache)
3295 struct btrfs_root *extent_root = fs_info->extent_root;
3297 struct extent_buffer *leaf;
3299 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3306 leaf = path->nodes[0];
3307 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3308 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3309 btrfs_mark_buffer_dirty(leaf);
3311 btrfs_release_path(path);
3316 static struct btrfs_block_group_cache *
3317 next_block_group(struct btrfs_fs_info *fs_info,
3318 struct btrfs_block_group_cache *cache)
3320 struct rb_node *node;
3322 spin_lock(&fs_info->block_group_cache_lock);
3324 /* If our block group was removed, we need a full search. */
3325 if (RB_EMPTY_NODE(&cache->cache_node)) {
3326 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3328 spin_unlock(&fs_info->block_group_cache_lock);
3329 btrfs_put_block_group(cache);
3330 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3332 node = rb_next(&cache->cache_node);
3333 btrfs_put_block_group(cache);
3335 cache = rb_entry(node, struct btrfs_block_group_cache,
3337 btrfs_get_block_group(cache);
3340 spin_unlock(&fs_info->block_group_cache_lock);
3344 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3345 struct btrfs_trans_handle *trans,
3346 struct btrfs_path *path)
3348 struct btrfs_fs_info *fs_info = block_group->fs_info;
3349 struct btrfs_root *root = fs_info->tree_root;
3350 struct inode *inode = NULL;
3352 int dcs = BTRFS_DC_ERROR;
3358 * If this block group is smaller than 100 megs don't bother caching the
3361 if (block_group->key.offset < (100 * SZ_1M)) {
3362 spin_lock(&block_group->lock);
3363 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3364 spin_unlock(&block_group->lock);
3371 inode = lookup_free_space_inode(root, block_group, path);
3372 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3373 ret = PTR_ERR(inode);
3374 btrfs_release_path(path);
3378 if (IS_ERR(inode)) {
3382 if (block_group->ro)
3385 ret = create_free_space_inode(root, trans, block_group, path);
3391 /* We've already setup this transaction, go ahead and exit */
3392 if (block_group->cache_generation == trans->transid &&
3393 i_size_read(inode)) {
3394 dcs = BTRFS_DC_SETUP;
3399 * We want to set the generation to 0, that way if anything goes wrong
3400 * from here on out we know not to trust this cache when we load up next
3403 BTRFS_I(inode)->generation = 0;
3404 ret = btrfs_update_inode(trans, root, inode);
3407 * So theoretically we could recover from this, simply set the
3408 * super cache generation to 0 so we know to invalidate the
3409 * cache, but then we'd have to keep track of the block groups
3410 * that fail this way so we know we _have_ to reset this cache
3411 * before the next commit or risk reading stale cache. So to
3412 * limit our exposure to horrible edge cases lets just abort the
3413 * transaction, this only happens in really bad situations
3416 btrfs_abort_transaction(trans, ret);
3421 if (i_size_read(inode) > 0) {
3422 ret = btrfs_check_trunc_cache_free_space(fs_info,
3423 &fs_info->global_block_rsv);
3427 ret = btrfs_truncate_free_space_cache(root, trans, NULL, inode);
3432 spin_lock(&block_group->lock);
3433 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3434 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3436 * don't bother trying to write stuff out _if_
3437 * a) we're not cached,
3438 * b) we're with nospace_cache mount option.
3440 dcs = BTRFS_DC_WRITTEN;
3441 spin_unlock(&block_group->lock);
3444 spin_unlock(&block_group->lock);
3447 * We hit an ENOSPC when setting up the cache in this transaction, just
3448 * skip doing the setup, we've already cleared the cache so we're safe.
3450 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3456 * Try to preallocate enough space based on how big the block group is.
3457 * Keep in mind this has to include any pinned space which could end up
3458 * taking up quite a bit since it's not folded into the other space
3461 num_pages = div_u64(block_group->key.offset, SZ_256M);
3466 num_pages *= PAGE_SIZE;
3468 ret = btrfs_check_data_free_space(inode, 0, num_pages);
3472 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3473 num_pages, num_pages,
3476 * Our cache requires contiguous chunks so that we don't modify a bunch
3477 * of metadata or split extents when writing the cache out, which means
3478 * we can enospc if we are heavily fragmented in addition to just normal
3479 * out of space conditions. So if we hit this just skip setting up any
3480 * other block groups for this transaction, maybe we'll unpin enough
3481 * space the next time around.
3484 dcs = BTRFS_DC_SETUP;
3485 else if (ret == -ENOSPC)
3486 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3491 btrfs_release_path(path);
3493 spin_lock(&block_group->lock);
3494 if (!ret && dcs == BTRFS_DC_SETUP)
3495 block_group->cache_generation = trans->transid;
3496 block_group->disk_cache_state = dcs;
3497 spin_unlock(&block_group->lock);
3502 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
3503 struct btrfs_fs_info *fs_info)
3505 struct btrfs_block_group_cache *cache, *tmp;
3506 struct btrfs_transaction *cur_trans = trans->transaction;
3507 struct btrfs_path *path;
3509 if (list_empty(&cur_trans->dirty_bgs) ||
3510 !btrfs_test_opt(fs_info, SPACE_CACHE))
3513 path = btrfs_alloc_path();
3517 /* Could add new block groups, use _safe just in case */
3518 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3520 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3521 cache_save_setup(cache, trans, path);
3524 btrfs_free_path(path);
3529 * transaction commit does final block group cache writeback during a
3530 * critical section where nothing is allowed to change the FS. This is
3531 * required in order for the cache to actually match the block group,
3532 * but can introduce a lot of latency into the commit.
3534 * So, btrfs_start_dirty_block_groups is here to kick off block group
3535 * cache IO. There's a chance we'll have to redo some of it if the
3536 * block group changes again during the commit, but it greatly reduces
3537 * the commit latency by getting rid of the easy block groups while
3538 * we're still allowing others to join the commit.
3540 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
3541 struct btrfs_fs_info *fs_info)
3543 struct btrfs_block_group_cache *cache;
3544 struct btrfs_transaction *cur_trans = trans->transaction;
3547 struct btrfs_path *path = NULL;
3549 struct list_head *io = &cur_trans->io_bgs;
3550 int num_started = 0;
3553 spin_lock(&cur_trans->dirty_bgs_lock);
3554 if (list_empty(&cur_trans->dirty_bgs)) {
3555 spin_unlock(&cur_trans->dirty_bgs_lock);
3558 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3559 spin_unlock(&cur_trans->dirty_bgs_lock);
3563 * make sure all the block groups on our dirty list actually
3566 btrfs_create_pending_block_groups(trans, fs_info);
3569 path = btrfs_alloc_path();
3575 * cache_write_mutex is here only to save us from balance or automatic
3576 * removal of empty block groups deleting this block group while we are
3577 * writing out the cache
3579 mutex_lock(&trans->transaction->cache_write_mutex);
3580 while (!list_empty(&dirty)) {
3581 cache = list_first_entry(&dirty,
3582 struct btrfs_block_group_cache,
3585 * this can happen if something re-dirties a block
3586 * group that is already under IO. Just wait for it to
3587 * finish and then do it all again
3589 if (!list_empty(&cache->io_list)) {
3590 list_del_init(&cache->io_list);
3591 btrfs_wait_cache_io(trans, cache, path);
3592 btrfs_put_block_group(cache);
3597 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3598 * if it should update the cache_state. Don't delete
3599 * until after we wait.
3601 * Since we're not running in the commit critical section
3602 * we need the dirty_bgs_lock to protect from update_block_group
3604 spin_lock(&cur_trans->dirty_bgs_lock);
3605 list_del_init(&cache->dirty_list);
3606 spin_unlock(&cur_trans->dirty_bgs_lock);
3610 cache_save_setup(cache, trans, path);
3612 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3613 cache->io_ctl.inode = NULL;
3614 ret = btrfs_write_out_cache(fs_info, trans,
3616 if (ret == 0 && cache->io_ctl.inode) {
3621 * the cache_write_mutex is protecting
3624 list_add_tail(&cache->io_list, io);
3627 * if we failed to write the cache, the
3628 * generation will be bad and life goes on
3634 ret = write_one_cache_group(trans, fs_info,
3637 * Our block group might still be attached to the list
3638 * of new block groups in the transaction handle of some
3639 * other task (struct btrfs_trans_handle->new_bgs). This
3640 * means its block group item isn't yet in the extent
3641 * tree. If this happens ignore the error, as we will
3642 * try again later in the critical section of the
3643 * transaction commit.
3645 if (ret == -ENOENT) {
3647 spin_lock(&cur_trans->dirty_bgs_lock);
3648 if (list_empty(&cache->dirty_list)) {
3649 list_add_tail(&cache->dirty_list,
3650 &cur_trans->dirty_bgs);
3651 btrfs_get_block_group(cache);
3653 spin_unlock(&cur_trans->dirty_bgs_lock);
3655 btrfs_abort_transaction(trans, ret);
3659 /* if its not on the io list, we need to put the block group */
3661 btrfs_put_block_group(cache);
3667 * Avoid blocking other tasks for too long. It might even save
3668 * us from writing caches for block groups that are going to be
3671 mutex_unlock(&trans->transaction->cache_write_mutex);
3672 mutex_lock(&trans->transaction->cache_write_mutex);
3674 mutex_unlock(&trans->transaction->cache_write_mutex);
3677 * go through delayed refs for all the stuff we've just kicked off
3678 * and then loop back (just once)
3680 ret = btrfs_run_delayed_refs(trans, fs_info, 0);
3681 if (!ret && loops == 0) {
3683 spin_lock(&cur_trans->dirty_bgs_lock);
3684 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3686 * dirty_bgs_lock protects us from concurrent block group
3687 * deletes too (not just cache_write_mutex).
3689 if (!list_empty(&dirty)) {
3690 spin_unlock(&cur_trans->dirty_bgs_lock);
3693 spin_unlock(&cur_trans->dirty_bgs_lock);
3694 } else if (ret < 0) {
3695 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3698 btrfs_free_path(path);
3702 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3703 struct btrfs_fs_info *fs_info)
3705 struct btrfs_block_group_cache *cache;
3706 struct btrfs_transaction *cur_trans = trans->transaction;
3709 struct btrfs_path *path;
3710 struct list_head *io = &cur_trans->io_bgs;
3711 int num_started = 0;
3713 path = btrfs_alloc_path();
3718 * Even though we are in the critical section of the transaction commit,
3719 * we can still have concurrent tasks adding elements to this
3720 * transaction's list of dirty block groups. These tasks correspond to
3721 * endio free space workers started when writeback finishes for a
3722 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3723 * allocate new block groups as a result of COWing nodes of the root
3724 * tree when updating the free space inode. The writeback for the space
3725 * caches is triggered by an earlier call to
3726 * btrfs_start_dirty_block_groups() and iterations of the following
3728 * Also we want to do the cache_save_setup first and then run the
3729 * delayed refs to make sure we have the best chance at doing this all
3732 spin_lock(&cur_trans->dirty_bgs_lock);
3733 while (!list_empty(&cur_trans->dirty_bgs)) {
3734 cache = list_first_entry(&cur_trans->dirty_bgs,
3735 struct btrfs_block_group_cache,
3739 * this can happen if cache_save_setup re-dirties a block
3740 * group that is already under IO. Just wait for it to
3741 * finish and then do it all again
3743 if (!list_empty(&cache->io_list)) {
3744 spin_unlock(&cur_trans->dirty_bgs_lock);
3745 list_del_init(&cache->io_list);
3746 btrfs_wait_cache_io(trans, cache, path);
3747 btrfs_put_block_group(cache);
3748 spin_lock(&cur_trans->dirty_bgs_lock);
3752 * don't remove from the dirty list until after we've waited
3755 list_del_init(&cache->dirty_list);
3756 spin_unlock(&cur_trans->dirty_bgs_lock);
3759 cache_save_setup(cache, trans, path);
3762 ret = btrfs_run_delayed_refs(trans, fs_info,
3763 (unsigned long) -1);
3765 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3766 cache->io_ctl.inode = NULL;
3767 ret = btrfs_write_out_cache(fs_info, trans,
3769 if (ret == 0 && cache->io_ctl.inode) {
3772 list_add_tail(&cache->io_list, io);
3775 * if we failed to write the cache, the
3776 * generation will be bad and life goes on
3782 ret = write_one_cache_group(trans, fs_info,
3785 * One of the free space endio workers might have
3786 * created a new block group while updating a free space
3787 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3788 * and hasn't released its transaction handle yet, in
3789 * which case the new block group is still attached to
3790 * its transaction handle and its creation has not
3791 * finished yet (no block group item in the extent tree
3792 * yet, etc). If this is the case, wait for all free
3793 * space endio workers to finish and retry. This is a
3794 * a very rare case so no need for a more efficient and
3797 if (ret == -ENOENT) {
3798 wait_event(cur_trans->writer_wait,
3799 atomic_read(&cur_trans->num_writers) == 1);
3800 ret = write_one_cache_group(trans, fs_info,
3804 btrfs_abort_transaction(trans, ret);
3807 /* if its not on the io list, we need to put the block group */
3809 btrfs_put_block_group(cache);
3810 spin_lock(&cur_trans->dirty_bgs_lock);
3812 spin_unlock(&cur_trans->dirty_bgs_lock);
3814 while (!list_empty(io)) {
3815 cache = list_first_entry(io, struct btrfs_block_group_cache,
3817 list_del_init(&cache->io_list);
3818 btrfs_wait_cache_io(trans, cache, path);
3819 btrfs_put_block_group(cache);
3822 btrfs_free_path(path);
3826 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3828 struct btrfs_block_group_cache *block_group;
3831 block_group = btrfs_lookup_block_group(fs_info, bytenr);
3832 if (!block_group || block_group->ro)
3835 btrfs_put_block_group(block_group);
3839 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3841 struct btrfs_block_group_cache *bg;
3844 bg = btrfs_lookup_block_group(fs_info, bytenr);
3848 spin_lock(&bg->lock);
3852 atomic_inc(&bg->nocow_writers);
3853 spin_unlock(&bg->lock);
3855 /* no put on block group, done by btrfs_dec_nocow_writers */
3857 btrfs_put_block_group(bg);
3863 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3865 struct btrfs_block_group_cache *bg;
3867 bg = btrfs_lookup_block_group(fs_info, bytenr);
3869 if (atomic_dec_and_test(&bg->nocow_writers))
3870 wake_up_atomic_t(&bg->nocow_writers);
3872 * Once for our lookup and once for the lookup done by a previous call
3873 * to btrfs_inc_nocow_writers()
3875 btrfs_put_block_group(bg);
3876 btrfs_put_block_group(bg);
3879 static int btrfs_wait_nocow_writers_atomic_t(atomic_t *a)
3885 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3887 wait_on_atomic_t(&bg->nocow_writers,
3888 btrfs_wait_nocow_writers_atomic_t,
3889 TASK_UNINTERRUPTIBLE);
3892 static const char *alloc_name(u64 flags)
3895 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3897 case BTRFS_BLOCK_GROUP_METADATA:
3899 case BTRFS_BLOCK_GROUP_DATA:
3901 case BTRFS_BLOCK_GROUP_SYSTEM:
3905 return "invalid-combination";
3909 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3910 u64 total_bytes, u64 bytes_used,
3912 struct btrfs_space_info **space_info)
3914 struct btrfs_space_info *found;
3919 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3920 BTRFS_BLOCK_GROUP_RAID10))
3925 found = __find_space_info(info, flags);
3927 spin_lock(&found->lock);
3928 found->total_bytes += total_bytes;
3929 found->disk_total += total_bytes * factor;
3930 found->bytes_used += bytes_used;
3931 found->disk_used += bytes_used * factor;
3932 found->bytes_readonly += bytes_readonly;
3933 if (total_bytes > 0)
3935 space_info_add_new_bytes(info, found, total_bytes -
3936 bytes_used - bytes_readonly);
3937 spin_unlock(&found->lock);
3938 *space_info = found;
3941 found = kzalloc(sizeof(*found), GFP_NOFS);
3945 ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
3951 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3952 INIT_LIST_HEAD(&found->block_groups[i]);
3953 init_rwsem(&found->groups_sem);
3954 spin_lock_init(&found->lock);
3955 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3956 found->total_bytes = total_bytes;
3957 found->disk_total = total_bytes * factor;
3958 found->bytes_used = bytes_used;
3959 found->disk_used = bytes_used * factor;
3960 found->bytes_pinned = 0;
3961 found->bytes_reserved = 0;
3962 found->bytes_readonly = bytes_readonly;
3963 found->bytes_may_use = 0;
3965 found->max_extent_size = 0;
3966 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3967 found->chunk_alloc = 0;
3969 init_waitqueue_head(&found->wait);
3970 INIT_LIST_HEAD(&found->ro_bgs);
3971 INIT_LIST_HEAD(&found->tickets);
3972 INIT_LIST_HEAD(&found->priority_tickets);
3974 ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
3975 info->space_info_kobj, "%s",
3976 alloc_name(found->flags));
3982 *space_info = found;
3983 list_add_rcu(&found->list, &info->space_info);
3984 if (flags & BTRFS_BLOCK_GROUP_DATA)
3985 info->data_sinfo = found;
3990 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3992 u64 extra_flags = chunk_to_extended(flags) &
3993 BTRFS_EXTENDED_PROFILE_MASK;
3995 write_seqlock(&fs_info->profiles_lock);
3996 if (flags & BTRFS_BLOCK_GROUP_DATA)
3997 fs_info->avail_data_alloc_bits |= extra_flags;
3998 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3999 fs_info->avail_metadata_alloc_bits |= extra_flags;
4000 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4001 fs_info->avail_system_alloc_bits |= extra_flags;
4002 write_sequnlock(&fs_info->profiles_lock);
4006 * returns target flags in extended format or 0 if restripe for this
4007 * chunk_type is not in progress
4009 * should be called with either volume_mutex or balance_lock held
4011 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
4013 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4019 if (flags & BTRFS_BLOCK_GROUP_DATA &&
4020 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4021 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
4022 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
4023 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4024 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
4025 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
4026 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4027 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
4034 * @flags: available profiles in extended format (see ctree.h)
4036 * Returns reduced profile in chunk format. If profile changing is in
4037 * progress (either running or paused) picks the target profile (if it's
4038 * already available), otherwise falls back to plain reducing.
4040 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
4042 u64 num_devices = fs_info->fs_devices->rw_devices;
4048 * see if restripe for this chunk_type is in progress, if so
4049 * try to reduce to the target profile
4051 spin_lock(&fs_info->balance_lock);
4052 target = get_restripe_target(fs_info, flags);
4054 /* pick target profile only if it's already available */
4055 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
4056 spin_unlock(&fs_info->balance_lock);
4057 return extended_to_chunk(target);
4060 spin_unlock(&fs_info->balance_lock);
4062 /* First, mask out the RAID levels which aren't possible */
4063 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4064 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
4065 allowed |= btrfs_raid_group[raid_type];
4069 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
4070 allowed = BTRFS_BLOCK_GROUP_RAID6;
4071 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
4072 allowed = BTRFS_BLOCK_GROUP_RAID5;
4073 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
4074 allowed = BTRFS_BLOCK_GROUP_RAID10;
4075 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
4076 allowed = BTRFS_BLOCK_GROUP_RAID1;
4077 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
4078 allowed = BTRFS_BLOCK_GROUP_RAID0;
4080 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4082 return extended_to_chunk(flags | allowed);
4085 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
4092 seq = read_seqbegin(&fs_info->profiles_lock);
4094 if (flags & BTRFS_BLOCK_GROUP_DATA)
4095 flags |= fs_info->avail_data_alloc_bits;
4096 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4097 flags |= fs_info->avail_system_alloc_bits;
4098 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
4099 flags |= fs_info->avail_metadata_alloc_bits;
4100 } while (read_seqretry(&fs_info->profiles_lock, seq));
4102 return btrfs_reduce_alloc_profile(fs_info, flags);
4105 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
4107 struct btrfs_fs_info *fs_info = root->fs_info;
4112 flags = BTRFS_BLOCK_GROUP_DATA;
4113 else if (root == fs_info->chunk_root)
4114 flags = BTRFS_BLOCK_GROUP_SYSTEM;
4116 flags = BTRFS_BLOCK_GROUP_METADATA;
4118 ret = get_alloc_profile(fs_info, flags);
4122 int btrfs_alloc_data_chunk_ondemand(struct inode *inode, u64 bytes)
4124 struct btrfs_space_info *data_sinfo;
4125 struct btrfs_root *root = BTRFS_I(inode)->root;
4126 struct btrfs_fs_info *fs_info = root->fs_info;
4129 int need_commit = 2;
4130 int have_pinned_space;
4132 /* make sure bytes are sectorsize aligned */
4133 bytes = ALIGN(bytes, fs_info->sectorsize);
4135 if (btrfs_is_free_space_inode(inode)) {
4137 ASSERT(current->journal_info);
4140 data_sinfo = fs_info->data_sinfo;
4145 /* make sure we have enough space to handle the data first */
4146 spin_lock(&data_sinfo->lock);
4147 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
4148 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
4149 data_sinfo->bytes_may_use;
4151 if (used + bytes > data_sinfo->total_bytes) {
4152 struct btrfs_trans_handle *trans;
4155 * if we don't have enough free bytes in this space then we need
4156 * to alloc a new chunk.
4158 if (!data_sinfo->full) {
4161 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4162 spin_unlock(&data_sinfo->lock);
4164 alloc_target = btrfs_get_alloc_profile(root, 1);
4166 * It is ugly that we don't call nolock join
4167 * transaction for the free space inode case here.
4168 * But it is safe because we only do the data space
4169 * reservation for the free space cache in the
4170 * transaction context, the common join transaction
4171 * just increase the counter of the current transaction
4172 * handler, doesn't try to acquire the trans_lock of
4175 trans = btrfs_join_transaction(root);
4177 return PTR_ERR(trans);
4179 ret = do_chunk_alloc(trans, fs_info, alloc_target,
4180 CHUNK_ALLOC_NO_FORCE);
4181 btrfs_end_transaction(trans);
4186 have_pinned_space = 1;
4192 data_sinfo = fs_info->data_sinfo;
4198 * If we don't have enough pinned space to deal with this
4199 * allocation, and no removed chunk in current transaction,
4200 * don't bother committing the transaction.
4202 have_pinned_space = percpu_counter_compare(
4203 &data_sinfo->total_bytes_pinned,
4204 used + bytes - data_sinfo->total_bytes);
4205 spin_unlock(&data_sinfo->lock);
4207 /* commit the current transaction and try again */
4210 !atomic_read(&fs_info->open_ioctl_trans)) {
4213 if (need_commit > 0) {
4214 btrfs_start_delalloc_roots(fs_info, 0, -1);
4215 btrfs_wait_ordered_roots(fs_info, -1, 0,
4219 trans = btrfs_join_transaction(root);
4221 return PTR_ERR(trans);
4222 if (have_pinned_space >= 0 ||
4223 test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4224 &trans->transaction->flags) ||
4226 ret = btrfs_commit_transaction(trans);
4230 * The cleaner kthread might still be doing iput
4231 * operations. Wait for it to finish so that
4232 * more space is released.
4234 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
4235 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
4238 btrfs_end_transaction(trans);
4242 trace_btrfs_space_reservation(fs_info,
4243 "space_info:enospc",
4244 data_sinfo->flags, bytes, 1);
4247 data_sinfo->bytes_may_use += bytes;
4248 trace_btrfs_space_reservation(fs_info, "space_info",
4249 data_sinfo->flags, bytes, 1);
4250 spin_unlock(&data_sinfo->lock);
4256 * New check_data_free_space() with ability for precious data reservation
4257 * Will replace old btrfs_check_data_free_space(), but for patch split,
4258 * add a new function first and then replace it.
4260 int btrfs_check_data_free_space(struct inode *inode, u64 start, u64 len)
4262 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4265 /* align the range */
4266 len = round_up(start + len, fs_info->sectorsize) -
4267 round_down(start, fs_info->sectorsize);
4268 start = round_down(start, fs_info->sectorsize);
4270 ret = btrfs_alloc_data_chunk_ondemand(inode, len);
4274 /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4275 ret = btrfs_qgroup_reserve_data(inode, start, len);
4277 btrfs_free_reserved_data_space_noquota(inode, start, len);
4282 * Called if we need to clear a data reservation for this inode
4283 * Normally in a error case.
4285 * This one will *NOT* use accurate qgroup reserved space API, just for case
4286 * which we can't sleep and is sure it won't affect qgroup reserved space.
4287 * Like clear_bit_hook().
4289 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4292 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4293 struct btrfs_space_info *data_sinfo;
4295 /* Make sure the range is aligned to sectorsize */
4296 len = round_up(start + len, fs_info->sectorsize) -
4297 round_down(start, fs_info->sectorsize);
4298 start = round_down(start, fs_info->sectorsize);
4300 data_sinfo = fs_info->data_sinfo;
4301 spin_lock(&data_sinfo->lock);
4302 if (WARN_ON(data_sinfo->bytes_may_use < len))
4303 data_sinfo->bytes_may_use = 0;
4305 data_sinfo->bytes_may_use -= len;
4306 trace_btrfs_space_reservation(fs_info, "space_info",
4307 data_sinfo->flags, len, 0);
4308 spin_unlock(&data_sinfo->lock);
4312 * Called if we need to clear a data reservation for this inode
4313 * Normally in a error case.
4315 * This one will handle the per-inode data rsv map for accurate reserved
4318 void btrfs_free_reserved_data_space(struct inode *inode, u64 start, u64 len)
4320 struct btrfs_root *root = BTRFS_I(inode)->root;
4322 /* Make sure the range is aligned to sectorsize */
4323 len = round_up(start + len, root->fs_info->sectorsize) -
4324 round_down(start, root->fs_info->sectorsize);
4325 start = round_down(start, root->fs_info->sectorsize);
4327 btrfs_free_reserved_data_space_noquota(inode, start, len);
4328 btrfs_qgroup_free_data(inode, start, len);
4331 static void force_metadata_allocation(struct btrfs_fs_info *info)
4333 struct list_head *head = &info->space_info;
4334 struct btrfs_space_info *found;
4337 list_for_each_entry_rcu(found, head, list) {
4338 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4339 found->force_alloc = CHUNK_ALLOC_FORCE;
4344 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4346 return (global->size << 1);
4349 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4350 struct btrfs_space_info *sinfo, int force)
4352 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4353 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
4354 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
4357 if (force == CHUNK_ALLOC_FORCE)
4361 * We need to take into account the global rsv because for all intents
4362 * and purposes it's used space. Don't worry about locking the
4363 * global_rsv, it doesn't change except when the transaction commits.
4365 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
4366 num_allocated += calc_global_rsv_need_space(global_rsv);
4369 * in limited mode, we want to have some free space up to
4370 * about 1% of the FS size.
4372 if (force == CHUNK_ALLOC_LIMITED) {
4373 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4374 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4376 if (num_bytes - num_allocated < thresh)
4380 if (num_allocated + SZ_2M < div_factor(num_bytes, 8))
4385 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4389 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4390 BTRFS_BLOCK_GROUP_RAID0 |
4391 BTRFS_BLOCK_GROUP_RAID5 |
4392 BTRFS_BLOCK_GROUP_RAID6))
4393 num_dev = fs_info->fs_devices->rw_devices;
4394 else if (type & BTRFS_BLOCK_GROUP_RAID1)
4397 num_dev = 1; /* DUP or single */
4403 * If @is_allocation is true, reserve space in the system space info necessary
4404 * for allocating a chunk, otherwise if it's false, reserve space necessary for
4407 void check_system_chunk(struct btrfs_trans_handle *trans,
4408 struct btrfs_fs_info *fs_info, u64 type)
4410 struct btrfs_space_info *info;
4417 * Needed because we can end up allocating a system chunk and for an
4418 * atomic and race free space reservation in the chunk block reserve.
4420 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
4422 info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4423 spin_lock(&info->lock);
4424 left = info->total_bytes - info->bytes_used - info->bytes_pinned -
4425 info->bytes_reserved - info->bytes_readonly -
4426 info->bytes_may_use;
4427 spin_unlock(&info->lock);
4429 num_devs = get_profile_num_devs(fs_info, type);
4431 /* num_devs device items to update and 1 chunk item to add or remove */
4432 thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4433 btrfs_calc_trans_metadata_size(fs_info, 1);
4435 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4436 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4437 left, thresh, type);
4438 dump_space_info(fs_info, info, 0, 0);
4441 if (left < thresh) {
4444 flags = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4446 * Ignore failure to create system chunk. We might end up not
4447 * needing it, as we might not need to COW all nodes/leafs from
4448 * the paths we visit in the chunk tree (they were already COWed
4449 * or created in the current transaction for example).
4451 ret = btrfs_alloc_chunk(trans, fs_info, flags);
4455 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4456 &fs_info->chunk_block_rsv,
4457 thresh, BTRFS_RESERVE_NO_FLUSH);
4459 trans->chunk_bytes_reserved += thresh;
4464 * If force is CHUNK_ALLOC_FORCE:
4465 * - return 1 if it successfully allocates a chunk,
4466 * - return errors including -ENOSPC otherwise.
4467 * If force is NOT CHUNK_ALLOC_FORCE:
4468 * - return 0 if it doesn't need to allocate a new chunk,
4469 * - return 1 if it successfully allocates a chunk,
4470 * - return errors including -ENOSPC otherwise.
4472 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
4473 struct btrfs_fs_info *fs_info, u64 flags, int force)
4475 struct btrfs_space_info *space_info;
4476 int wait_for_alloc = 0;
4479 /* Don't re-enter if we're already allocating a chunk */
4480 if (trans->allocating_chunk)
4483 space_info = __find_space_info(fs_info, flags);
4485 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
4486 BUG_ON(ret); /* -ENOMEM */
4488 BUG_ON(!space_info); /* Logic error */
4491 spin_lock(&space_info->lock);
4492 if (force < space_info->force_alloc)
4493 force = space_info->force_alloc;
4494 if (space_info->full) {
4495 if (should_alloc_chunk(fs_info, space_info, force))
4499 spin_unlock(&space_info->lock);
4503 if (!should_alloc_chunk(fs_info, space_info, force)) {
4504 spin_unlock(&space_info->lock);
4506 } else if (space_info->chunk_alloc) {
4509 space_info->chunk_alloc = 1;
4512 spin_unlock(&space_info->lock);
4514 mutex_lock(&fs_info->chunk_mutex);
4517 * The chunk_mutex is held throughout the entirety of a chunk
4518 * allocation, so once we've acquired the chunk_mutex we know that the
4519 * other guy is done and we need to recheck and see if we should
4522 if (wait_for_alloc) {
4523 mutex_unlock(&fs_info->chunk_mutex);
4528 trans->allocating_chunk = true;
4531 * If we have mixed data/metadata chunks we want to make sure we keep
4532 * allocating mixed chunks instead of individual chunks.
4534 if (btrfs_mixed_space_info(space_info))
4535 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4538 * if we're doing a data chunk, go ahead and make sure that
4539 * we keep a reasonable number of metadata chunks allocated in the
4542 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4543 fs_info->data_chunk_allocations++;
4544 if (!(fs_info->data_chunk_allocations %
4545 fs_info->metadata_ratio))
4546 force_metadata_allocation(fs_info);
4550 * Check if we have enough space in SYSTEM chunk because we may need
4551 * to update devices.
4553 check_system_chunk(trans, fs_info, flags);
4555 ret = btrfs_alloc_chunk(trans, fs_info, flags);
4556 trans->allocating_chunk = false;
4558 spin_lock(&space_info->lock);
4559 if (ret < 0 && ret != -ENOSPC)
4562 space_info->full = 1;
4566 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4568 space_info->chunk_alloc = 0;
4569 spin_unlock(&space_info->lock);
4570 mutex_unlock(&fs_info->chunk_mutex);
4572 * When we allocate a new chunk we reserve space in the chunk block
4573 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4574 * add new nodes/leafs to it if we end up needing to do it when
4575 * inserting the chunk item and updating device items as part of the
4576 * second phase of chunk allocation, performed by
4577 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4578 * large number of new block groups to create in our transaction
4579 * handle's new_bgs list to avoid exhausting the chunk block reserve
4580 * in extreme cases - like having a single transaction create many new
4581 * block groups when starting to write out the free space caches of all
4582 * the block groups that were made dirty during the lifetime of the
4585 if (trans->can_flush_pending_bgs &&
4586 trans->chunk_bytes_reserved >= (u64)SZ_2M) {
4587 btrfs_create_pending_block_groups(trans, fs_info);
4588 btrfs_trans_release_chunk_metadata(trans);
4593 static int can_overcommit(struct btrfs_root *root,
4594 struct btrfs_space_info *space_info, u64 bytes,
4595 enum btrfs_reserve_flush_enum flush)
4597 struct btrfs_fs_info *fs_info = root->fs_info;
4598 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4604 /* Don't overcommit when in mixed mode. */
4605 if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4608 profile = btrfs_get_alloc_profile(root, 0);
4609 used = space_info->bytes_used + space_info->bytes_reserved +
4610 space_info->bytes_pinned + space_info->bytes_readonly;
4613 * We only want to allow over committing if we have lots of actual space
4614 * free, but if we don't have enough space to handle the global reserve
4615 * space then we could end up having a real enospc problem when trying
4616 * to allocate a chunk or some other such important allocation.
4618 spin_lock(&global_rsv->lock);
4619 space_size = calc_global_rsv_need_space(global_rsv);
4620 spin_unlock(&global_rsv->lock);
4621 if (used + space_size >= space_info->total_bytes)
4624 used += space_info->bytes_may_use;
4626 spin_lock(&fs_info->free_chunk_lock);
4627 avail = fs_info->free_chunk_space;
4628 spin_unlock(&fs_info->free_chunk_lock);
4631 * If we have dup, raid1 or raid10 then only half of the free
4632 * space is actually useable. For raid56, the space info used
4633 * doesn't include the parity drive, so we don't have to
4636 if (profile & (BTRFS_BLOCK_GROUP_DUP |
4637 BTRFS_BLOCK_GROUP_RAID1 |
4638 BTRFS_BLOCK_GROUP_RAID10))
4642 * If we aren't flushing all things, let us overcommit up to
4643 * 1/2th of the space. If we can flush, don't let us overcommit
4644 * too much, let it overcommit up to 1/8 of the space.
4646 if (flush == BTRFS_RESERVE_FLUSH_ALL)
4651 if (used + bytes < space_info->total_bytes + avail)
4656 static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
4657 unsigned long nr_pages, int nr_items)
4659 struct super_block *sb = fs_info->sb;
4661 if (down_read_trylock(&sb->s_umount)) {
4662 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4663 up_read(&sb->s_umount);
4666 * We needn't worry the filesystem going from r/w to r/o though
4667 * we don't acquire ->s_umount mutex, because the filesystem
4668 * should guarantee the delalloc inodes list be empty after
4669 * the filesystem is readonly(all dirty pages are written to
4672 btrfs_start_delalloc_roots(fs_info, 0, nr_items);
4673 if (!current->journal_info)
4674 btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
4678 static inline int calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
4684 bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
4685 nr = (int)div64_u64(to_reclaim, bytes);
4691 #define EXTENT_SIZE_PER_ITEM SZ_256K
4694 * shrink metadata reservation for delalloc
4696 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
4699 struct btrfs_fs_info *fs_info = root->fs_info;
4700 struct btrfs_block_rsv *block_rsv;
4701 struct btrfs_space_info *space_info;
4702 struct btrfs_trans_handle *trans;
4706 unsigned long nr_pages;
4709 enum btrfs_reserve_flush_enum flush;
4711 /* Calc the number of the pages we need flush for space reservation */
4712 items = calc_reclaim_items_nr(fs_info, to_reclaim);
4713 to_reclaim = (u64)items * EXTENT_SIZE_PER_ITEM;
4715 trans = (struct btrfs_trans_handle *)current->journal_info;
4716 block_rsv = &fs_info->delalloc_block_rsv;
4717 space_info = block_rsv->space_info;
4719 delalloc_bytes = percpu_counter_sum_positive(
4720 &fs_info->delalloc_bytes);
4721 if (delalloc_bytes == 0) {
4725 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4730 while (delalloc_bytes && loops < 3) {
4731 max_reclaim = min(delalloc_bytes, to_reclaim);
4732 nr_pages = max_reclaim >> PAGE_SHIFT;
4733 btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
4735 * We need to wait for the async pages to actually start before
4738 max_reclaim = atomic_read(&fs_info->async_delalloc_pages);
4742 if (max_reclaim <= nr_pages)
4745 max_reclaim -= nr_pages;
4747 wait_event(fs_info->async_submit_wait,
4748 atomic_read(&fs_info->async_delalloc_pages) <=
4752 flush = BTRFS_RESERVE_FLUSH_ALL;
4754 flush = BTRFS_RESERVE_NO_FLUSH;
4755 spin_lock(&space_info->lock);
4756 if (can_overcommit(root, space_info, orig, flush)) {
4757 spin_unlock(&space_info->lock);
4760 if (list_empty(&space_info->tickets) &&
4761 list_empty(&space_info->priority_tickets)) {
4762 spin_unlock(&space_info->lock);
4765 spin_unlock(&space_info->lock);
4768 if (wait_ordered && !trans) {
4769 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4771 time_left = schedule_timeout_killable(1);
4775 delalloc_bytes = percpu_counter_sum_positive(
4776 &fs_info->delalloc_bytes);
4781 * maybe_commit_transaction - possibly commit the transaction if its ok to
4782 * @root - the root we're allocating for
4783 * @bytes - the number of bytes we want to reserve
4784 * @force - force the commit
4786 * This will check to make sure that committing the transaction will actually
4787 * get us somewhere and then commit the transaction if it does. Otherwise it
4788 * will return -ENOSPC.
4790 static int may_commit_transaction(struct btrfs_root *root,
4791 struct btrfs_space_info *space_info,
4792 u64 bytes, int force)
4794 struct btrfs_fs_info *fs_info = root->fs_info;
4795 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
4796 struct btrfs_trans_handle *trans;
4798 trans = (struct btrfs_trans_handle *)current->journal_info;
4805 /* See if there is enough pinned space to make this reservation */
4806 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4811 * See if there is some space in the delayed insertion reservation for
4814 if (space_info != delayed_rsv->space_info)
4817 spin_lock(&delayed_rsv->lock);
4818 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4819 bytes - delayed_rsv->size) >= 0) {
4820 spin_unlock(&delayed_rsv->lock);
4823 spin_unlock(&delayed_rsv->lock);
4826 trans = btrfs_join_transaction(root);
4830 return btrfs_commit_transaction(trans);
4833 struct reserve_ticket {
4836 struct list_head list;
4837 wait_queue_head_t wait;
4840 static int flush_space(struct btrfs_root *root,
4841 struct btrfs_space_info *space_info, u64 num_bytes,
4842 u64 orig_bytes, int state)
4844 struct btrfs_fs_info *fs_info = root->fs_info;
4845 struct btrfs_trans_handle *trans;
4850 case FLUSH_DELAYED_ITEMS_NR:
4851 case FLUSH_DELAYED_ITEMS:
4852 if (state == FLUSH_DELAYED_ITEMS_NR)
4853 nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
4857 trans = btrfs_join_transaction(root);
4858 if (IS_ERR(trans)) {
4859 ret = PTR_ERR(trans);
4862 ret = btrfs_run_delayed_items_nr(trans, fs_info, nr);
4863 btrfs_end_transaction(trans);
4865 case FLUSH_DELALLOC:
4866 case FLUSH_DELALLOC_WAIT:
4867 shrink_delalloc(root, num_bytes * 2, orig_bytes,
4868 state == FLUSH_DELALLOC_WAIT);
4871 trans = btrfs_join_transaction(root);
4872 if (IS_ERR(trans)) {
4873 ret = PTR_ERR(trans);
4876 ret = do_chunk_alloc(trans, fs_info,
4877 btrfs_get_alloc_profile(root, 0),
4878 CHUNK_ALLOC_NO_FORCE);
4879 btrfs_end_transaction(trans);
4880 if (ret > 0 || ret == -ENOSPC)
4884 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4891 trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes,
4892 orig_bytes, state, ret);
4897 btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
4898 struct btrfs_space_info *space_info)
4900 struct reserve_ticket *ticket;
4905 list_for_each_entry(ticket, &space_info->tickets, list)
4906 to_reclaim += ticket->bytes;
4907 list_for_each_entry(ticket, &space_info->priority_tickets, list)
4908 to_reclaim += ticket->bytes;
4912 to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
4913 if (can_overcommit(root, space_info, to_reclaim,
4914 BTRFS_RESERVE_FLUSH_ALL))
4917 used = space_info->bytes_used + space_info->bytes_reserved +
4918 space_info->bytes_pinned + space_info->bytes_readonly +
4919 space_info->bytes_may_use;
4920 if (can_overcommit(root, space_info, SZ_1M, BTRFS_RESERVE_FLUSH_ALL))
4921 expected = div_factor_fine(space_info->total_bytes, 95);
4923 expected = div_factor_fine(space_info->total_bytes, 90);
4925 if (used > expected)
4926 to_reclaim = used - expected;
4929 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4930 space_info->bytes_reserved);
4934 static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
4935 struct btrfs_root *root, u64 used)
4937 struct btrfs_fs_info *fs_info = root->fs_info;
4938 u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4940 /* If we're just plain full then async reclaim just slows us down. */
4941 if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
4944 if (!btrfs_calc_reclaim_metadata_size(root, space_info))
4947 return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4948 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4951 static void wake_all_tickets(struct list_head *head)
4953 struct reserve_ticket *ticket;
4955 while (!list_empty(head)) {
4956 ticket = list_first_entry(head, struct reserve_ticket, list);
4957 list_del_init(&ticket->list);
4958 ticket->error = -ENOSPC;
4959 wake_up(&ticket->wait);
4964 * This is for normal flushers, we can wait all goddamned day if we want to. We
4965 * will loop and continuously try to flush as long as we are making progress.
4966 * We count progress as clearing off tickets each time we have to loop.
4968 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4970 struct btrfs_fs_info *fs_info;
4971 struct btrfs_space_info *space_info;
4974 int commit_cycles = 0;
4975 u64 last_tickets_id;
4977 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4978 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4980 spin_lock(&space_info->lock);
4981 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
4984 space_info->flush = 0;
4985 spin_unlock(&space_info->lock);
4988 last_tickets_id = space_info->tickets_id;
4989 spin_unlock(&space_info->lock);
4991 flush_state = FLUSH_DELAYED_ITEMS_NR;
4993 struct reserve_ticket *ticket;
4996 ret = flush_space(fs_info->fs_root, space_info, to_reclaim,
4997 to_reclaim, flush_state);
4998 spin_lock(&space_info->lock);
4999 if (list_empty(&space_info->tickets)) {
5000 space_info->flush = 0;
5001 spin_unlock(&space_info->lock);
5004 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5006 ticket = list_first_entry(&space_info->tickets,
5007 struct reserve_ticket, list);
5008 if (last_tickets_id == space_info->tickets_id) {
5011 last_tickets_id = space_info->tickets_id;
5012 flush_state = FLUSH_DELAYED_ITEMS_NR;
5017 if (flush_state > COMMIT_TRANS) {
5019 if (commit_cycles > 2) {
5020 wake_all_tickets(&space_info->tickets);
5021 space_info->flush = 0;
5023 flush_state = FLUSH_DELAYED_ITEMS_NR;
5026 spin_unlock(&space_info->lock);
5027 } while (flush_state <= COMMIT_TRANS);
5030 void btrfs_init_async_reclaim_work(struct work_struct *work)
5032 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5035 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5036 struct btrfs_space_info *space_info,
5037 struct reserve_ticket *ticket)
5040 int flush_state = FLUSH_DELAYED_ITEMS_NR;
5042 spin_lock(&space_info->lock);
5043 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5046 spin_unlock(&space_info->lock);
5049 spin_unlock(&space_info->lock);
5052 flush_space(fs_info->fs_root, space_info, to_reclaim,
5053 to_reclaim, flush_state);
5055 spin_lock(&space_info->lock);
5056 if (ticket->bytes == 0) {
5057 spin_unlock(&space_info->lock);
5060 spin_unlock(&space_info->lock);
5063 * Priority flushers can't wait on delalloc without
5066 if (flush_state == FLUSH_DELALLOC ||
5067 flush_state == FLUSH_DELALLOC_WAIT)
5068 flush_state = ALLOC_CHUNK;
5069 } while (flush_state < COMMIT_TRANS);
5072 static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5073 struct btrfs_space_info *space_info,
5074 struct reserve_ticket *ticket, u64 orig_bytes)
5080 spin_lock(&space_info->lock);
5081 while (ticket->bytes > 0 && ticket->error == 0) {
5082 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5087 spin_unlock(&space_info->lock);
5091 finish_wait(&ticket->wait, &wait);
5092 spin_lock(&space_info->lock);
5095 ret = ticket->error;
5096 if (!list_empty(&ticket->list))
5097 list_del_init(&ticket->list);
5098 if (ticket->bytes && ticket->bytes < orig_bytes) {
5099 u64 num_bytes = orig_bytes - ticket->bytes;
5100 space_info->bytes_may_use -= num_bytes;
5101 trace_btrfs_space_reservation(fs_info, "space_info",
5102 space_info->flags, num_bytes, 0);
5104 spin_unlock(&space_info->lock);
5110 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5111 * @root - the root we're allocating for
5112 * @space_info - the space info we want to allocate from
5113 * @orig_bytes - the number of bytes we want
5114 * @flush - whether or not we can flush to make our reservation
5116 * This will reserve orig_bytes number of bytes from the space info associated
5117 * with the block_rsv. If there is not enough space it will make an attempt to
5118 * flush out space to make room. It will do this by flushing delalloc if
5119 * possible or committing the transaction. If flush is 0 then no attempts to
5120 * regain reservations will be made and this will fail if there is not enough
5123 static int __reserve_metadata_bytes(struct btrfs_root *root,
5124 struct btrfs_space_info *space_info,
5126 enum btrfs_reserve_flush_enum flush)
5128 struct btrfs_fs_info *fs_info = root->fs_info;
5129 struct reserve_ticket ticket;
5134 ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
5136 spin_lock(&space_info->lock);
5138 used = space_info->bytes_used + space_info->bytes_reserved +
5139 space_info->bytes_pinned + space_info->bytes_readonly +
5140 space_info->bytes_may_use;
5143 * If we have enough space then hooray, make our reservation and carry
5144 * on. If not see if we can overcommit, and if we can, hooray carry on.
5145 * If not things get more complicated.
5147 if (used + orig_bytes <= space_info->total_bytes) {
5148 space_info->bytes_may_use += orig_bytes;
5149 trace_btrfs_space_reservation(fs_info, "space_info",
5150 space_info->flags, orig_bytes, 1);
5152 } else if (can_overcommit(root, space_info, orig_bytes, flush)) {
5153 space_info->bytes_may_use += orig_bytes;
5154 trace_btrfs_space_reservation(fs_info, "space_info",
5155 space_info->flags, orig_bytes, 1);
5160 * If we couldn't make a reservation then setup our reservation ticket
5161 * and kick the async worker if it's not already running.
5163 * If we are a priority flusher then we just need to add our ticket to
5164 * the list and we will do our own flushing further down.
5166 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
5167 ticket.bytes = orig_bytes;
5169 init_waitqueue_head(&ticket.wait);
5170 if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5171 list_add_tail(&ticket.list, &space_info->tickets);
5172 if (!space_info->flush) {
5173 space_info->flush = 1;
5174 trace_btrfs_trigger_flush(fs_info,
5178 queue_work(system_unbound_wq,
5179 &root->fs_info->async_reclaim_work);
5182 list_add_tail(&ticket.list,
5183 &space_info->priority_tickets);
5185 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5188 * We will do the space reservation dance during log replay,
5189 * which means we won't have fs_info->fs_root set, so don't do
5190 * the async reclaim as we will panic.
5192 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
5193 need_do_async_reclaim(space_info, root, used) &&
5194 !work_busy(&fs_info->async_reclaim_work)) {
5195 trace_btrfs_trigger_flush(fs_info, space_info->flags,
5196 orig_bytes, flush, "preempt");
5197 queue_work(system_unbound_wq,
5198 &fs_info->async_reclaim_work);
5201 spin_unlock(&space_info->lock);
5202 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
5205 if (flush == BTRFS_RESERVE_FLUSH_ALL)
5206 return wait_reserve_ticket(fs_info, space_info, &ticket,
5210 priority_reclaim_metadata_space(fs_info, space_info, &ticket);
5211 spin_lock(&space_info->lock);
5213 if (ticket.bytes < orig_bytes) {
5214 u64 num_bytes = orig_bytes - ticket.bytes;
5215 space_info->bytes_may_use -= num_bytes;
5216 trace_btrfs_space_reservation(fs_info, "space_info",
5221 list_del_init(&ticket.list);
5224 spin_unlock(&space_info->lock);
5225 ASSERT(list_empty(&ticket.list));
5230 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5231 * @root - the root we're allocating for
5232 * @block_rsv - the block_rsv we're allocating for
5233 * @orig_bytes - the number of bytes we want
5234 * @flush - whether or not we can flush to make our reservation
5236 * This will reserve orgi_bytes number of bytes from the space info associated
5237 * with the block_rsv. If there is not enough space it will make an attempt to
5238 * flush out space to make room. It will do this by flushing delalloc if
5239 * possible or committing the transaction. If flush is 0 then no attempts to
5240 * regain reservations will be made and this will fail if there is not enough
5243 static int reserve_metadata_bytes(struct btrfs_root *root,
5244 struct btrfs_block_rsv *block_rsv,
5246 enum btrfs_reserve_flush_enum flush)
5248 struct btrfs_fs_info *fs_info = root->fs_info;
5249 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5252 ret = __reserve_metadata_bytes(root, block_rsv->space_info, orig_bytes,
5254 if (ret == -ENOSPC &&
5255 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5256 if (block_rsv != global_rsv &&
5257 !block_rsv_use_bytes(global_rsv, orig_bytes))
5261 trace_btrfs_space_reservation(fs_info, "space_info:enospc",
5262 block_rsv->space_info->flags,
5267 static struct btrfs_block_rsv *get_block_rsv(
5268 const struct btrfs_trans_handle *trans,
5269 const struct btrfs_root *root)
5271 struct btrfs_fs_info *fs_info = root->fs_info;
5272 struct btrfs_block_rsv *block_rsv = NULL;
5274 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5275 (root == fs_info->csum_root && trans->adding_csums) ||
5276 (root == fs_info->uuid_root))
5277 block_rsv = trans->block_rsv;
5280 block_rsv = root->block_rsv;
5283 block_rsv = &fs_info->empty_block_rsv;
5288 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5292 spin_lock(&block_rsv->lock);
5293 if (block_rsv->reserved >= num_bytes) {
5294 block_rsv->reserved -= num_bytes;
5295 if (block_rsv->reserved < block_rsv->size)
5296 block_rsv->full = 0;
5299 spin_unlock(&block_rsv->lock);
5303 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5304 u64 num_bytes, int update_size)
5306 spin_lock(&block_rsv->lock);
5307 block_rsv->reserved += num_bytes;
5309 block_rsv->size += num_bytes;
5310 else if (block_rsv->reserved >= block_rsv->size)
5311 block_rsv->full = 1;
5312 spin_unlock(&block_rsv->lock);
5315 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5316 struct btrfs_block_rsv *dest, u64 num_bytes,
5319 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5322 if (global_rsv->space_info != dest->space_info)
5325 spin_lock(&global_rsv->lock);
5326 min_bytes = div_factor(global_rsv->size, min_factor);
5327 if (global_rsv->reserved < min_bytes + num_bytes) {
5328 spin_unlock(&global_rsv->lock);
5331 global_rsv->reserved -= num_bytes;
5332 if (global_rsv->reserved < global_rsv->size)
5333 global_rsv->full = 0;
5334 spin_unlock(&global_rsv->lock);
5336 block_rsv_add_bytes(dest, num_bytes, 1);
5341 * This is for space we already have accounted in space_info->bytes_may_use, so
5342 * basically when we're returning space from block_rsv's.
5344 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5345 struct btrfs_space_info *space_info,
5348 struct reserve_ticket *ticket;
5349 struct list_head *head;
5351 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5352 bool check_overcommit = false;
5354 spin_lock(&space_info->lock);
5355 head = &space_info->priority_tickets;
5358 * If we are over our limit then we need to check and see if we can
5359 * overcommit, and if we can't then we just need to free up our space
5360 * and not satisfy any requests.
5362 used = space_info->bytes_used + space_info->bytes_reserved +
5363 space_info->bytes_pinned + space_info->bytes_readonly +
5364 space_info->bytes_may_use;
5365 if (used - num_bytes >= space_info->total_bytes)
5366 check_overcommit = true;
5368 while (!list_empty(head) && num_bytes) {
5369 ticket = list_first_entry(head, struct reserve_ticket,
5372 * We use 0 bytes because this space is already reserved, so
5373 * adding the ticket space would be a double count.
5375 if (check_overcommit &&
5376 !can_overcommit(fs_info->extent_root, space_info, 0,
5379 if (num_bytes >= ticket->bytes) {
5380 list_del_init(&ticket->list);
5381 num_bytes -= ticket->bytes;
5383 space_info->tickets_id++;
5384 wake_up(&ticket->wait);
5386 ticket->bytes -= num_bytes;
5391 if (num_bytes && head == &space_info->priority_tickets) {
5392 head = &space_info->tickets;
5393 flush = BTRFS_RESERVE_FLUSH_ALL;
5396 space_info->bytes_may_use -= num_bytes;
5397 trace_btrfs_space_reservation(fs_info, "space_info",
5398 space_info->flags, num_bytes, 0);
5399 spin_unlock(&space_info->lock);
5403 * This is for newly allocated space that isn't accounted in
5404 * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
5405 * we use this helper.
5407 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5408 struct btrfs_space_info *space_info,
5411 struct reserve_ticket *ticket;
5412 struct list_head *head = &space_info->priority_tickets;
5415 while (!list_empty(head) && num_bytes) {
5416 ticket = list_first_entry(head, struct reserve_ticket,
5418 if (num_bytes >= ticket->bytes) {
5419 trace_btrfs_space_reservation(fs_info, "space_info",
5422 list_del_init(&ticket->list);
5423 num_bytes -= ticket->bytes;
5424 space_info->bytes_may_use += ticket->bytes;
5426 space_info->tickets_id++;
5427 wake_up(&ticket->wait);
5429 trace_btrfs_space_reservation(fs_info, "space_info",
5432 space_info->bytes_may_use += num_bytes;
5433 ticket->bytes -= num_bytes;
5438 if (num_bytes && head == &space_info->priority_tickets) {
5439 head = &space_info->tickets;
5444 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5445 struct btrfs_block_rsv *block_rsv,
5446 struct btrfs_block_rsv *dest, u64 num_bytes)
5448 struct btrfs_space_info *space_info = block_rsv->space_info;
5450 spin_lock(&block_rsv->lock);
5451 if (num_bytes == (u64)-1)
5452 num_bytes = block_rsv->size;
5453 block_rsv->size -= num_bytes;
5454 if (block_rsv->reserved >= block_rsv->size) {
5455 num_bytes = block_rsv->reserved - block_rsv->size;
5456 block_rsv->reserved = block_rsv->size;
5457 block_rsv->full = 1;
5461 spin_unlock(&block_rsv->lock);
5463 if (num_bytes > 0) {
5465 spin_lock(&dest->lock);
5469 bytes_to_add = dest->size - dest->reserved;
5470 bytes_to_add = min(num_bytes, bytes_to_add);
5471 dest->reserved += bytes_to_add;
5472 if (dest->reserved >= dest->size)
5474 num_bytes -= bytes_to_add;
5476 spin_unlock(&dest->lock);
5479 space_info_add_old_bytes(fs_info, space_info,
5484 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5485 struct btrfs_block_rsv *dst, u64 num_bytes,
5490 ret = block_rsv_use_bytes(src, num_bytes);
5494 block_rsv_add_bytes(dst, num_bytes, update_size);
5498 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5500 memset(rsv, 0, sizeof(*rsv));
5501 spin_lock_init(&rsv->lock);
5505 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
5506 unsigned short type)
5508 struct btrfs_block_rsv *block_rsv;
5510 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5514 btrfs_init_block_rsv(block_rsv, type);
5515 block_rsv->space_info = __find_space_info(fs_info,
5516 BTRFS_BLOCK_GROUP_METADATA);
5520 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
5521 struct btrfs_block_rsv *rsv)
5525 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5529 void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
5534 int btrfs_block_rsv_add(struct btrfs_root *root,
5535 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5536 enum btrfs_reserve_flush_enum flush)
5543 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5545 block_rsv_add_bytes(block_rsv, num_bytes, 1);
5552 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
5560 spin_lock(&block_rsv->lock);
5561 num_bytes = div_factor(block_rsv->size, min_factor);
5562 if (block_rsv->reserved >= num_bytes)
5564 spin_unlock(&block_rsv->lock);
5569 int btrfs_block_rsv_refill(struct btrfs_root *root,
5570 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5571 enum btrfs_reserve_flush_enum flush)
5579 spin_lock(&block_rsv->lock);
5580 num_bytes = min_reserved;
5581 if (block_rsv->reserved >= num_bytes)
5584 num_bytes -= block_rsv->reserved;
5585 spin_unlock(&block_rsv->lock);
5590 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5592 block_rsv_add_bytes(block_rsv, num_bytes, 0);
5599 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5600 struct btrfs_block_rsv *block_rsv,
5603 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5605 if (global_rsv == block_rsv ||
5606 block_rsv->space_info != global_rsv->space_info)
5608 block_rsv_release_bytes(fs_info, block_rsv, global_rsv, num_bytes);
5611 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5613 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5614 struct btrfs_space_info *sinfo = block_rsv->space_info;
5618 * The global block rsv is based on the size of the extent tree, the
5619 * checksum tree and the root tree. If the fs is empty we want to set
5620 * it to a minimal amount for safety.
5622 num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5623 btrfs_root_used(&fs_info->csum_root->root_item) +
5624 btrfs_root_used(&fs_info->tree_root->root_item);
5625 num_bytes = max_t(u64, num_bytes, SZ_16M);
5627 spin_lock(&sinfo->lock);
5628 spin_lock(&block_rsv->lock);
5630 block_rsv->size = min_t(u64, num_bytes, SZ_512M);
5632 if (block_rsv->reserved < block_rsv->size) {
5633 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
5634 sinfo->bytes_reserved + sinfo->bytes_readonly +
5635 sinfo->bytes_may_use;
5636 if (sinfo->total_bytes > num_bytes) {
5637 num_bytes = sinfo->total_bytes - num_bytes;
5638 num_bytes = min(num_bytes,
5639 block_rsv->size - block_rsv->reserved);
5640 block_rsv->reserved += num_bytes;
5641 sinfo->bytes_may_use += num_bytes;
5642 trace_btrfs_space_reservation(fs_info, "space_info",
5643 sinfo->flags, num_bytes,
5646 } else if (block_rsv->reserved > block_rsv->size) {
5647 num_bytes = block_rsv->reserved - block_rsv->size;
5648 sinfo->bytes_may_use -= num_bytes;
5649 trace_btrfs_space_reservation(fs_info, "space_info",
5650 sinfo->flags, num_bytes, 0);
5651 block_rsv->reserved = block_rsv->size;
5654 if (block_rsv->reserved == block_rsv->size)
5655 block_rsv->full = 1;
5657 block_rsv->full = 0;
5659 spin_unlock(&block_rsv->lock);
5660 spin_unlock(&sinfo->lock);
5663 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5665 struct btrfs_space_info *space_info;
5667 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5668 fs_info->chunk_block_rsv.space_info = space_info;
5670 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5671 fs_info->global_block_rsv.space_info = space_info;
5672 fs_info->delalloc_block_rsv.space_info = space_info;
5673 fs_info->trans_block_rsv.space_info = space_info;
5674 fs_info->empty_block_rsv.space_info = space_info;
5675 fs_info->delayed_block_rsv.space_info = space_info;
5677 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
5678 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
5679 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5680 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5681 if (fs_info->quota_root)
5682 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5683 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5685 update_global_block_rsv(fs_info);
5688 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5690 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5692 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
5693 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
5694 WARN_ON(fs_info->trans_block_rsv.size > 0);
5695 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5696 WARN_ON(fs_info->chunk_block_rsv.size > 0);
5697 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5698 WARN_ON(fs_info->delayed_block_rsv.size > 0);
5699 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5702 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
5703 struct btrfs_fs_info *fs_info)
5705 if (!trans->block_rsv)
5708 if (!trans->bytes_reserved)
5711 trace_btrfs_space_reservation(fs_info, "transaction",
5712 trans->transid, trans->bytes_reserved, 0);
5713 btrfs_block_rsv_release(fs_info, trans->block_rsv,
5714 trans->bytes_reserved);
5715 trans->bytes_reserved = 0;
5719 * To be called after all the new block groups attached to the transaction
5720 * handle have been created (btrfs_create_pending_block_groups()).
5722 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5724 struct btrfs_fs_info *fs_info = trans->fs_info;
5726 if (!trans->chunk_bytes_reserved)
5729 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5731 block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5732 trans->chunk_bytes_reserved);
5733 trans->chunk_bytes_reserved = 0;
5736 /* Can only return 0 or -ENOSPC */
5737 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
5738 struct inode *inode)
5740 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5741 struct btrfs_root *root = BTRFS_I(inode)->root;
5743 * We always use trans->block_rsv here as we will have reserved space
5744 * for our orphan when starting the transaction, using get_block_rsv()
5745 * here will sometimes make us choose the wrong block rsv as we could be
5746 * doing a reloc inode for a non refcounted root.
5748 struct btrfs_block_rsv *src_rsv = trans->block_rsv;
5749 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
5752 * We need to hold space in order to delete our orphan item once we've
5753 * added it, so this takes the reservation so we can release it later
5754 * when we are truly done with the orphan item.
5756 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5758 trace_btrfs_space_reservation(fs_info, "orphan",
5759 btrfs_ino(inode), num_bytes, 1);
5760 return btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, 1);
5763 void btrfs_orphan_release_metadata(struct inode *inode)
5765 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5766 struct btrfs_root *root = BTRFS_I(inode)->root;
5767 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5769 trace_btrfs_space_reservation(fs_info, "orphan",
5770 btrfs_ino(inode), num_bytes, 0);
5771 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv, num_bytes);
5775 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5776 * root: the root of the parent directory
5777 * rsv: block reservation
5778 * items: the number of items that we need do reservation
5779 * qgroup_reserved: used to return the reserved size in qgroup
5781 * This function is used to reserve the space for snapshot/subvolume
5782 * creation and deletion. Those operations are different with the
5783 * common file/directory operations, they change two fs/file trees
5784 * and root tree, the number of items that the qgroup reserves is
5785 * different with the free space reservation. So we can not use
5786 * the space reservation mechanism in start_transaction().
5788 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5789 struct btrfs_block_rsv *rsv,
5791 u64 *qgroup_reserved,
5792 bool use_global_rsv)
5796 struct btrfs_fs_info *fs_info = root->fs_info;
5797 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5799 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5800 /* One for parent inode, two for dir entries */
5801 num_bytes = 3 * fs_info->nodesize;
5802 ret = btrfs_qgroup_reserve_meta(root, num_bytes);
5809 *qgroup_reserved = num_bytes;
5811 num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
5812 rsv->space_info = __find_space_info(fs_info,
5813 BTRFS_BLOCK_GROUP_METADATA);
5814 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5815 BTRFS_RESERVE_FLUSH_ALL);
5817 if (ret == -ENOSPC && use_global_rsv)
5818 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
5820 if (ret && *qgroup_reserved)
5821 btrfs_qgroup_free_meta(root, *qgroup_reserved);
5826 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
5827 struct btrfs_block_rsv *rsv,
5828 u64 qgroup_reserved)
5830 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5834 * drop_outstanding_extent - drop an outstanding extent
5835 * @inode: the inode we're dropping the extent for
5836 * @num_bytes: the number of bytes we're releasing.
5838 * This is called when we are freeing up an outstanding extent, either called
5839 * after an error or after an extent is written. This will return the number of
5840 * reserved extents that need to be freed. This must be called with
5841 * BTRFS_I(inode)->lock held.
5843 static unsigned drop_outstanding_extent(struct inode *inode, u64 num_bytes)
5845 unsigned drop_inode_space = 0;
5846 unsigned dropped_extents = 0;
5847 unsigned num_extents = 0;
5849 num_extents = (unsigned)div64_u64(num_bytes +
5850 BTRFS_MAX_EXTENT_SIZE - 1,
5851 BTRFS_MAX_EXTENT_SIZE);
5852 ASSERT(num_extents);
5853 ASSERT(BTRFS_I(inode)->outstanding_extents >= num_extents);
5854 BTRFS_I(inode)->outstanding_extents -= num_extents;
5856 if (BTRFS_I(inode)->outstanding_extents == 0 &&
5857 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5858 &BTRFS_I(inode)->runtime_flags))
5859 drop_inode_space = 1;
5862 * If we have more or the same amount of outstanding extents than we have
5863 * reserved then we need to leave the reserved extents count alone.
5865 if (BTRFS_I(inode)->outstanding_extents >=
5866 BTRFS_I(inode)->reserved_extents)
5867 return drop_inode_space;
5869 dropped_extents = BTRFS_I(inode)->reserved_extents -
5870 BTRFS_I(inode)->outstanding_extents;
5871 BTRFS_I(inode)->reserved_extents -= dropped_extents;
5872 return dropped_extents + drop_inode_space;
5876 * calc_csum_metadata_size - return the amount of metadata space that must be
5877 * reserved/freed for the given bytes.
5878 * @inode: the inode we're manipulating
5879 * @num_bytes: the number of bytes in question
5880 * @reserve: 1 if we are reserving space, 0 if we are freeing space
5882 * This adjusts the number of csum_bytes in the inode and then returns the
5883 * correct amount of metadata that must either be reserved or freed. We
5884 * calculate how many checksums we can fit into one leaf and then divide the
5885 * number of bytes that will need to be checksumed by this value to figure out
5886 * how many checksums will be required. If we are adding bytes then the number
5887 * may go up and we will return the number of additional bytes that must be
5888 * reserved. If it is going down we will return the number of bytes that must
5891 * This must be called with BTRFS_I(inode)->lock held.
5893 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
5896 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5897 u64 old_csums, num_csums;
5899 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
5900 BTRFS_I(inode)->csum_bytes == 0)
5903 old_csums = btrfs_csum_bytes_to_leaves(fs_info,
5904 BTRFS_I(inode)->csum_bytes);
5906 BTRFS_I(inode)->csum_bytes += num_bytes;
5908 BTRFS_I(inode)->csum_bytes -= num_bytes;
5909 num_csums = btrfs_csum_bytes_to_leaves(fs_info,
5910 BTRFS_I(inode)->csum_bytes);
5912 /* No change, no need to reserve more */
5913 if (old_csums == num_csums)
5917 return btrfs_calc_trans_metadata_size(fs_info,
5918 num_csums - old_csums);
5920 return btrfs_calc_trans_metadata_size(fs_info, old_csums - num_csums);
5923 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
5925 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5926 struct btrfs_root *root = BTRFS_I(inode)->root;
5927 struct btrfs_block_rsv *block_rsv = &fs_info->delalloc_block_rsv;
5930 unsigned nr_extents = 0;
5931 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
5933 bool delalloc_lock = true;
5936 bool release_extra = false;
5938 /* If we are a free space inode we need to not flush since we will be in
5939 * the middle of a transaction commit. We also don't need the delalloc
5940 * mutex since we won't race with anybody. We need this mostly to make
5941 * lockdep shut its filthy mouth.
5943 * If we have a transaction open (can happen if we call truncate_block
5944 * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
5946 if (btrfs_is_free_space_inode(inode)) {
5947 flush = BTRFS_RESERVE_NO_FLUSH;
5948 delalloc_lock = false;
5949 } else if (current->journal_info) {
5950 flush = BTRFS_RESERVE_FLUSH_LIMIT;
5953 if (flush != BTRFS_RESERVE_NO_FLUSH &&
5954 btrfs_transaction_in_commit(fs_info))
5955 schedule_timeout(1);
5958 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
5960 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5962 spin_lock(&BTRFS_I(inode)->lock);
5963 nr_extents = (unsigned)div64_u64(num_bytes +
5964 BTRFS_MAX_EXTENT_SIZE - 1,
5965 BTRFS_MAX_EXTENT_SIZE);
5966 BTRFS_I(inode)->outstanding_extents += nr_extents;
5969 if (BTRFS_I(inode)->outstanding_extents >
5970 BTRFS_I(inode)->reserved_extents)
5971 nr_extents += BTRFS_I(inode)->outstanding_extents -
5972 BTRFS_I(inode)->reserved_extents;
5974 /* We always want to reserve a slot for updating the inode. */
5975 to_reserve = btrfs_calc_trans_metadata_size(fs_info, nr_extents + 1);
5976 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
5977 csum_bytes = BTRFS_I(inode)->csum_bytes;
5978 spin_unlock(&BTRFS_I(inode)->lock);
5980 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5981 ret = btrfs_qgroup_reserve_meta(root,
5982 nr_extents * fs_info->nodesize);
5987 ret = btrfs_block_rsv_add(root, block_rsv, to_reserve, flush);
5988 if (unlikely(ret)) {
5989 btrfs_qgroup_free_meta(root,
5990 nr_extents * fs_info->nodesize);
5994 spin_lock(&BTRFS_I(inode)->lock);
5995 if (test_and_set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5996 &BTRFS_I(inode)->runtime_flags)) {
5997 to_reserve -= btrfs_calc_trans_metadata_size(fs_info, 1);
5998 release_extra = true;
6000 BTRFS_I(inode)->reserved_extents += nr_extents;
6001 spin_unlock(&BTRFS_I(inode)->lock);
6004 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
6007 trace_btrfs_space_reservation(fs_info, "delalloc",
6008 btrfs_ino(inode), to_reserve, 1);
6010 btrfs_block_rsv_release(fs_info, block_rsv,
6011 btrfs_calc_trans_metadata_size(fs_info, 1));
6015 spin_lock(&BTRFS_I(inode)->lock);
6016 dropped = drop_outstanding_extent(inode, num_bytes);
6018 * If the inodes csum_bytes is the same as the original
6019 * csum_bytes then we know we haven't raced with any free()ers
6020 * so we can just reduce our inodes csum bytes and carry on.
6022 if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
6023 calc_csum_metadata_size(inode, num_bytes, 0);
6025 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
6029 * This is tricky, but first we need to figure out how much we
6030 * freed from any free-ers that occurred during this
6031 * reservation, so we reset ->csum_bytes to the csum_bytes
6032 * before we dropped our lock, and then call the free for the
6033 * number of bytes that were freed while we were trying our
6036 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
6037 BTRFS_I(inode)->csum_bytes = csum_bytes;
6038 to_free = calc_csum_metadata_size(inode, bytes, 0);
6042 * Now we need to see how much we would have freed had we not
6043 * been making this reservation and our ->csum_bytes were not
6044 * artificially inflated.
6046 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
6047 bytes = csum_bytes - orig_csum_bytes;
6048 bytes = calc_csum_metadata_size(inode, bytes, 0);
6051 * Now reset ->csum_bytes to what it should be. If bytes is
6052 * more than to_free then we would have freed more space had we
6053 * not had an artificially high ->csum_bytes, so we need to free
6054 * the remainder. If bytes is the same or less then we don't
6055 * need to do anything, the other free-ers did the correct
6058 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
6059 if (bytes > to_free)
6060 to_free = bytes - to_free;
6064 spin_unlock(&BTRFS_I(inode)->lock);
6066 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
6069 btrfs_block_rsv_release(fs_info, block_rsv, to_free);
6070 trace_btrfs_space_reservation(fs_info, "delalloc",
6071 btrfs_ino(inode), to_free, 0);
6074 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
6079 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
6080 * @inode: the inode to release the reservation for
6081 * @num_bytes: the number of bytes we're releasing
6083 * This will release the metadata reservation for an inode. This can be called
6084 * once we complete IO for a given set of bytes to release their metadata
6087 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
6089 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6093 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6094 spin_lock(&BTRFS_I(inode)->lock);
6095 dropped = drop_outstanding_extent(inode, num_bytes);
6098 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
6099 spin_unlock(&BTRFS_I(inode)->lock);
6101 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
6103 if (btrfs_is_testing(fs_info))
6106 trace_btrfs_space_reservation(fs_info, "delalloc",
6107 btrfs_ino(inode), to_free, 0);
6109 btrfs_block_rsv_release(fs_info, &fs_info->delalloc_block_rsv, to_free);
6113 * btrfs_delalloc_reserve_space - reserve data and metadata space for
6115 * @inode: inode we're writing to
6116 * @start: start range we are writing to
6117 * @len: how long the range we are writing to
6119 * This will do the following things
6121 * o reserve space in data space info for num bytes
6122 * and reserve precious corresponding qgroup space
6123 * (Done in check_data_free_space)
6125 * o reserve space for metadata space, based on the number of outstanding
6126 * extents and how much csums will be needed
6127 * also reserve metadata space in a per root over-reserve method.
6128 * o add to the inodes->delalloc_bytes
6129 * o add it to the fs_info's delalloc inodes list.
6130 * (Above 3 all done in delalloc_reserve_metadata)
6132 * Return 0 for success
6133 * Return <0 for error(-ENOSPC or -EQUOT)
6135 int btrfs_delalloc_reserve_space(struct inode *inode, u64 start, u64 len)
6139 ret = btrfs_check_data_free_space(inode, start, len);
6142 ret = btrfs_delalloc_reserve_metadata(inode, len);
6144 btrfs_free_reserved_data_space(inode, start, len);
6149 * btrfs_delalloc_release_space - release data and metadata space for delalloc
6150 * @inode: inode we're releasing space for
6151 * @start: start position of the space already reserved
6152 * @len: the len of the space already reserved
6154 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
6155 * called in the case that we don't need the metadata AND data reservations
6156 * anymore. So if there is an error or we insert an inline extent.
6158 * This function will release the metadata space that was not used and will
6159 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6160 * list if there are no delalloc bytes left.
6161 * Also it will handle the qgroup reserved space.
6163 void btrfs_delalloc_release_space(struct inode *inode, u64 start, u64 len)
6165 btrfs_delalloc_release_metadata(inode, len);
6166 btrfs_free_reserved_data_space(inode, start, len);
6169 static int update_block_group(struct btrfs_trans_handle *trans,
6170 struct btrfs_fs_info *info, u64 bytenr,
6171 u64 num_bytes, int alloc)
6173 struct btrfs_block_group_cache *cache = NULL;
6174 u64 total = num_bytes;
6179 /* block accounting for super block */
6180 spin_lock(&info->delalloc_root_lock);
6181 old_val = btrfs_super_bytes_used(info->super_copy);
6183 old_val += num_bytes;
6185 old_val -= num_bytes;
6186 btrfs_set_super_bytes_used(info->super_copy, old_val);
6187 spin_unlock(&info->delalloc_root_lock);
6190 cache = btrfs_lookup_block_group(info, bytenr);
6193 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
6194 BTRFS_BLOCK_GROUP_RAID1 |
6195 BTRFS_BLOCK_GROUP_RAID10))
6200 * If this block group has free space cache written out, we
6201 * need to make sure to load it if we are removing space. This
6202 * is because we need the unpinning stage to actually add the
6203 * space back to the block group, otherwise we will leak space.
6205 if (!alloc && cache->cached == BTRFS_CACHE_NO)
6206 cache_block_group(cache, 1);
6208 byte_in_group = bytenr - cache->key.objectid;
6209 WARN_ON(byte_in_group > cache->key.offset);
6211 spin_lock(&cache->space_info->lock);
6212 spin_lock(&cache->lock);
6214 if (btrfs_test_opt(info, SPACE_CACHE) &&
6215 cache->disk_cache_state < BTRFS_DC_CLEAR)
6216 cache->disk_cache_state = BTRFS_DC_CLEAR;
6218 old_val = btrfs_block_group_used(&cache->item);
6219 num_bytes = min(total, cache->key.offset - byte_in_group);
6221 old_val += num_bytes;
6222 btrfs_set_block_group_used(&cache->item, old_val);
6223 cache->reserved -= num_bytes;
6224 cache->space_info->bytes_reserved -= num_bytes;
6225 cache->space_info->bytes_used += num_bytes;
6226 cache->space_info->disk_used += num_bytes * factor;
6227 spin_unlock(&cache->lock);
6228 spin_unlock(&cache->space_info->lock);
6230 old_val -= num_bytes;
6231 btrfs_set_block_group_used(&cache->item, old_val);
6232 cache->pinned += num_bytes;
6233 cache->space_info->bytes_pinned += num_bytes;
6234 cache->space_info->bytes_used -= num_bytes;
6235 cache->space_info->disk_used -= num_bytes * factor;
6236 spin_unlock(&cache->lock);
6237 spin_unlock(&cache->space_info->lock);
6239 trace_btrfs_space_reservation(info, "pinned",
6240 cache->space_info->flags,
6242 set_extent_dirty(info->pinned_extents,
6243 bytenr, bytenr + num_bytes - 1,
6244 GFP_NOFS | __GFP_NOFAIL);
6247 spin_lock(&trans->transaction->dirty_bgs_lock);
6248 if (list_empty(&cache->dirty_list)) {
6249 list_add_tail(&cache->dirty_list,
6250 &trans->transaction->dirty_bgs);
6251 trans->transaction->num_dirty_bgs++;
6252 btrfs_get_block_group(cache);
6254 spin_unlock(&trans->transaction->dirty_bgs_lock);
6257 * No longer have used bytes in this block group, queue it for
6258 * deletion. We do this after adding the block group to the
6259 * dirty list to avoid races between cleaner kthread and space
6262 if (!alloc && old_val == 0) {
6263 spin_lock(&info->unused_bgs_lock);
6264 if (list_empty(&cache->bg_list)) {
6265 btrfs_get_block_group(cache);
6266 list_add_tail(&cache->bg_list,
6269 spin_unlock(&info->unused_bgs_lock);
6272 btrfs_put_block_group(cache);
6274 bytenr += num_bytes;
6279 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
6281 struct btrfs_block_group_cache *cache;
6284 spin_lock(&fs_info->block_group_cache_lock);
6285 bytenr = fs_info->first_logical_byte;
6286 spin_unlock(&fs_info->block_group_cache_lock);
6288 if (bytenr < (u64)-1)
6291 cache = btrfs_lookup_first_block_group(fs_info, search_start);
6295 bytenr = cache->key.objectid;
6296 btrfs_put_block_group(cache);
6301 static int pin_down_extent(struct btrfs_fs_info *fs_info,
6302 struct btrfs_block_group_cache *cache,
6303 u64 bytenr, u64 num_bytes, int reserved)
6305 spin_lock(&cache->space_info->lock);
6306 spin_lock(&cache->lock);
6307 cache->pinned += num_bytes;
6308 cache->space_info->bytes_pinned += num_bytes;
6310 cache->reserved -= num_bytes;
6311 cache->space_info->bytes_reserved -= num_bytes;
6313 spin_unlock(&cache->lock);
6314 spin_unlock(&cache->space_info->lock);
6316 trace_btrfs_space_reservation(fs_info, "pinned",
6317 cache->space_info->flags, num_bytes, 1);
6318 set_extent_dirty(fs_info->pinned_extents, bytenr,
6319 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6324 * this function must be called within transaction
6326 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
6327 u64 bytenr, u64 num_bytes, int reserved)
6329 struct btrfs_block_group_cache *cache;
6331 cache = btrfs_lookup_block_group(fs_info, bytenr);
6332 BUG_ON(!cache); /* Logic error */
6334 pin_down_extent(fs_info, cache, bytenr, num_bytes, reserved);
6336 btrfs_put_block_group(cache);
6341 * this function must be called within transaction
6343 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
6344 u64 bytenr, u64 num_bytes)
6346 struct btrfs_block_group_cache *cache;
6349 cache = btrfs_lookup_block_group(fs_info, bytenr);
6354 * pull in the free space cache (if any) so that our pin
6355 * removes the free space from the cache. We have load_only set
6356 * to one because the slow code to read in the free extents does check
6357 * the pinned extents.
6359 cache_block_group(cache, 1);
6361 pin_down_extent(fs_info, cache, bytenr, num_bytes, 0);
6363 /* remove us from the free space cache (if we're there at all) */
6364 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6365 btrfs_put_block_group(cache);
6369 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
6370 u64 start, u64 num_bytes)
6373 struct btrfs_block_group_cache *block_group;
6374 struct btrfs_caching_control *caching_ctl;
6376 block_group = btrfs_lookup_block_group(fs_info, start);
6380 cache_block_group(block_group, 0);
6381 caching_ctl = get_caching_control(block_group);
6385 BUG_ON(!block_group_cache_done(block_group));
6386 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6388 mutex_lock(&caching_ctl->mutex);
6390 if (start >= caching_ctl->progress) {
6391 ret = add_excluded_extent(fs_info, start, num_bytes);
6392 } else if (start + num_bytes <= caching_ctl->progress) {
6393 ret = btrfs_remove_free_space(block_group,
6396 num_bytes = caching_ctl->progress - start;
6397 ret = btrfs_remove_free_space(block_group,
6402 num_bytes = (start + num_bytes) -
6403 caching_ctl->progress;
6404 start = caching_ctl->progress;
6405 ret = add_excluded_extent(fs_info, start, num_bytes);
6408 mutex_unlock(&caching_ctl->mutex);
6409 put_caching_control(caching_ctl);
6411 btrfs_put_block_group(block_group);
6415 int btrfs_exclude_logged_extents(struct btrfs_fs_info *fs_info,
6416 struct extent_buffer *eb)
6418 struct btrfs_file_extent_item *item;
6419 struct btrfs_key key;
6423 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
6426 for (i = 0; i < btrfs_header_nritems(eb); i++) {
6427 btrfs_item_key_to_cpu(eb, &key, i);
6428 if (key.type != BTRFS_EXTENT_DATA_KEY)
6430 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6431 found_type = btrfs_file_extent_type(eb, item);
6432 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6434 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6436 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6437 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6438 __exclude_logged_extent(fs_info, key.objectid, key.offset);
6445 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6447 atomic_inc(&bg->reservations);
6450 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6453 struct btrfs_block_group_cache *bg;
6455 bg = btrfs_lookup_block_group(fs_info, start);
6457 if (atomic_dec_and_test(&bg->reservations))
6458 wake_up_atomic_t(&bg->reservations);
6459 btrfs_put_block_group(bg);
6462 static int btrfs_wait_bg_reservations_atomic_t(atomic_t *a)
6468 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6470 struct btrfs_space_info *space_info = bg->space_info;
6474 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6478 * Our block group is read only but before we set it to read only,
6479 * some task might have had allocated an extent from it already, but it
6480 * has not yet created a respective ordered extent (and added it to a
6481 * root's list of ordered extents).
6482 * Therefore wait for any task currently allocating extents, since the
6483 * block group's reservations counter is incremented while a read lock
6484 * on the groups' semaphore is held and decremented after releasing
6485 * the read access on that semaphore and creating the ordered extent.
6487 down_write(&space_info->groups_sem);
6488 up_write(&space_info->groups_sem);
6490 wait_on_atomic_t(&bg->reservations,
6491 btrfs_wait_bg_reservations_atomic_t,
6492 TASK_UNINTERRUPTIBLE);
6496 * btrfs_add_reserved_bytes - update the block_group and space info counters
6497 * @cache: The cache we are manipulating
6498 * @ram_bytes: The number of bytes of file content, and will be same to
6499 * @num_bytes except for the compress path.
6500 * @num_bytes: The number of bytes in question
6501 * @delalloc: The blocks are allocated for the delalloc write
6503 * This is called by the allocator when it reserves space. If this is a
6504 * reservation and the block group has become read only we cannot make the
6505 * reservation and return -EAGAIN, otherwise this function always succeeds.
6507 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
6508 u64 ram_bytes, u64 num_bytes, int delalloc)
6510 struct btrfs_space_info *space_info = cache->space_info;
6513 spin_lock(&space_info->lock);
6514 spin_lock(&cache->lock);
6518 cache->reserved += num_bytes;
6519 space_info->bytes_reserved += num_bytes;
6521 trace_btrfs_space_reservation(cache->fs_info,
6522 "space_info", space_info->flags,
6524 space_info->bytes_may_use -= ram_bytes;
6526 cache->delalloc_bytes += num_bytes;
6528 spin_unlock(&cache->lock);
6529 spin_unlock(&space_info->lock);
6534 * btrfs_free_reserved_bytes - update the block_group and space info counters
6535 * @cache: The cache we are manipulating
6536 * @num_bytes: The number of bytes in question
6537 * @delalloc: The blocks are allocated for the delalloc write
6539 * This is called by somebody who is freeing space that was never actually used
6540 * on disk. For example if you reserve some space for a new leaf in transaction
6541 * A and before transaction A commits you free that leaf, you call this with
6542 * reserve set to 0 in order to clear the reservation.
6545 static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6546 u64 num_bytes, int delalloc)
6548 struct btrfs_space_info *space_info = cache->space_info;
6551 spin_lock(&space_info->lock);
6552 spin_lock(&cache->lock);
6554 space_info->bytes_readonly += num_bytes;
6555 cache->reserved -= num_bytes;
6556 space_info->bytes_reserved -= num_bytes;
6559 cache->delalloc_bytes -= num_bytes;
6560 spin_unlock(&cache->lock);
6561 spin_unlock(&space_info->lock);
6564 void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
6565 struct btrfs_fs_info *fs_info)
6567 struct btrfs_caching_control *next;
6568 struct btrfs_caching_control *caching_ctl;
6569 struct btrfs_block_group_cache *cache;
6571 down_write(&fs_info->commit_root_sem);
6573 list_for_each_entry_safe(caching_ctl, next,
6574 &fs_info->caching_block_groups, list) {
6575 cache = caching_ctl->block_group;
6576 if (block_group_cache_done(cache)) {
6577 cache->last_byte_to_unpin = (u64)-1;
6578 list_del_init(&caching_ctl->list);
6579 put_caching_control(caching_ctl);
6581 cache->last_byte_to_unpin = caching_ctl->progress;
6585 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6586 fs_info->pinned_extents = &fs_info->freed_extents[1];
6588 fs_info->pinned_extents = &fs_info->freed_extents[0];
6590 up_write(&fs_info->commit_root_sem);
6592 update_global_block_rsv(fs_info);
6596 * Returns the free cluster for the given space info and sets empty_cluster to
6597 * what it should be based on the mount options.
6599 static struct btrfs_free_cluster *
6600 fetch_cluster_info(struct btrfs_fs_info *fs_info,
6601 struct btrfs_space_info *space_info, u64 *empty_cluster)
6603 struct btrfs_free_cluster *ret = NULL;
6604 bool ssd = btrfs_test_opt(fs_info, SSD);
6607 if (btrfs_mixed_space_info(space_info))
6611 *empty_cluster = SZ_2M;
6612 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6613 ret = &fs_info->meta_alloc_cluster;
6615 *empty_cluster = SZ_64K;
6616 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && ssd) {
6617 ret = &fs_info->data_alloc_cluster;
6623 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
6625 const bool return_free_space)
6627 struct btrfs_block_group_cache *cache = NULL;
6628 struct btrfs_space_info *space_info;
6629 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6630 struct btrfs_free_cluster *cluster = NULL;
6632 u64 total_unpinned = 0;
6633 u64 empty_cluster = 0;
6636 while (start <= end) {
6639 start >= cache->key.objectid + cache->key.offset) {
6641 btrfs_put_block_group(cache);
6643 cache = btrfs_lookup_block_group(fs_info, start);
6644 BUG_ON(!cache); /* Logic error */
6646 cluster = fetch_cluster_info(fs_info,
6649 empty_cluster <<= 1;
6652 len = cache->key.objectid + cache->key.offset - start;
6653 len = min(len, end + 1 - start);
6655 if (start < cache->last_byte_to_unpin) {
6656 len = min(len, cache->last_byte_to_unpin - start);
6657 if (return_free_space)
6658 btrfs_add_free_space(cache, start, len);
6662 total_unpinned += len;
6663 space_info = cache->space_info;
6666 * If this space cluster has been marked as fragmented and we've
6667 * unpinned enough in this block group to potentially allow a
6668 * cluster to be created inside of it go ahead and clear the
6671 if (cluster && cluster->fragmented &&
6672 total_unpinned > empty_cluster) {
6673 spin_lock(&cluster->lock);
6674 cluster->fragmented = 0;
6675 spin_unlock(&cluster->lock);
6678 spin_lock(&space_info->lock);
6679 spin_lock(&cache->lock);
6680 cache->pinned -= len;
6681 space_info->bytes_pinned -= len;
6683 trace_btrfs_space_reservation(fs_info, "pinned",
6684 space_info->flags, len, 0);
6685 space_info->max_extent_size = 0;
6686 percpu_counter_add(&space_info->total_bytes_pinned, -len);
6688 space_info->bytes_readonly += len;
6691 spin_unlock(&cache->lock);
6692 if (!readonly && return_free_space &&
6693 global_rsv->space_info == space_info) {
6695 WARN_ON(!return_free_space);
6696 spin_lock(&global_rsv->lock);
6697 if (!global_rsv->full) {
6698 to_add = min(len, global_rsv->size -
6699 global_rsv->reserved);
6700 global_rsv->reserved += to_add;
6701 space_info->bytes_may_use += to_add;
6702 if (global_rsv->reserved >= global_rsv->size)
6703 global_rsv->full = 1;
6704 trace_btrfs_space_reservation(fs_info,
6710 spin_unlock(&global_rsv->lock);
6711 /* Add to any tickets we may have */
6713 space_info_add_new_bytes(fs_info, space_info,
6716 spin_unlock(&space_info->lock);
6720 btrfs_put_block_group(cache);
6724 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
6725 struct btrfs_fs_info *fs_info)
6727 struct btrfs_block_group_cache *block_group, *tmp;
6728 struct list_head *deleted_bgs;
6729 struct extent_io_tree *unpin;
6734 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6735 unpin = &fs_info->freed_extents[1];
6737 unpin = &fs_info->freed_extents[0];
6739 while (!trans->aborted) {
6740 mutex_lock(&fs_info->unused_bg_unpin_mutex);
6741 ret = find_first_extent_bit(unpin, 0, &start, &end,
6742 EXTENT_DIRTY, NULL);
6744 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6748 if (btrfs_test_opt(fs_info, DISCARD))
6749 ret = btrfs_discard_extent(fs_info, start,
6750 end + 1 - start, NULL);
6752 clear_extent_dirty(unpin, start, end);
6753 unpin_extent_range(fs_info, start, end, true);
6754 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6759 * Transaction is finished. We don't need the lock anymore. We
6760 * do need to clean up the block groups in case of a transaction
6763 deleted_bgs = &trans->transaction->deleted_bgs;
6764 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6768 if (!trans->aborted)
6769 ret = btrfs_discard_extent(fs_info,
6770 block_group->key.objectid,
6771 block_group->key.offset,
6774 list_del_init(&block_group->bg_list);
6775 btrfs_put_block_group_trimming(block_group);
6776 btrfs_put_block_group(block_group);
6779 const char *errstr = btrfs_decode_error(ret);
6781 "Discard failed while removing blockgroup: errno=%d %s\n",
6789 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
6790 u64 owner, u64 root_objectid)
6792 struct btrfs_space_info *space_info;
6795 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6796 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
6797 flags = BTRFS_BLOCK_GROUP_SYSTEM;
6799 flags = BTRFS_BLOCK_GROUP_METADATA;
6801 flags = BTRFS_BLOCK_GROUP_DATA;
6804 space_info = __find_space_info(fs_info, flags);
6805 BUG_ON(!space_info); /* Logic bug */
6806 percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
6810 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6811 struct btrfs_fs_info *info,
6812 struct btrfs_delayed_ref_node *node, u64 parent,
6813 u64 root_objectid, u64 owner_objectid,
6814 u64 owner_offset, int refs_to_drop,
6815 struct btrfs_delayed_extent_op *extent_op)
6817 struct btrfs_key key;
6818 struct btrfs_path *path;
6819 struct btrfs_root *extent_root = info->extent_root;
6820 struct extent_buffer *leaf;
6821 struct btrfs_extent_item *ei;
6822 struct btrfs_extent_inline_ref *iref;
6825 int extent_slot = 0;
6826 int found_extent = 0;
6830 u64 bytenr = node->bytenr;
6831 u64 num_bytes = node->num_bytes;
6833 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
6835 path = btrfs_alloc_path();
6839 path->reada = READA_FORWARD;
6840 path->leave_spinning = 1;
6842 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6843 BUG_ON(!is_data && refs_to_drop != 1);
6846 skinny_metadata = 0;
6848 ret = lookup_extent_backref(trans, extent_root, path, &iref,
6849 bytenr, num_bytes, parent,
6850 root_objectid, owner_objectid,
6853 extent_slot = path->slots[0];
6854 while (extent_slot >= 0) {
6855 btrfs_item_key_to_cpu(path->nodes[0], &key,
6857 if (key.objectid != bytenr)
6859 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6860 key.offset == num_bytes) {
6864 if (key.type == BTRFS_METADATA_ITEM_KEY &&
6865 key.offset == owner_objectid) {
6869 if (path->slots[0] - extent_slot > 5)
6873 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6874 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
6875 if (found_extent && item_size < sizeof(*ei))
6878 if (!found_extent) {
6880 ret = remove_extent_backref(trans, extent_root, path,
6882 is_data, &last_ref);
6884 btrfs_abort_transaction(trans, ret);
6887 btrfs_release_path(path);
6888 path->leave_spinning = 1;
6890 key.objectid = bytenr;
6891 key.type = BTRFS_EXTENT_ITEM_KEY;
6892 key.offset = num_bytes;
6894 if (!is_data && skinny_metadata) {
6895 key.type = BTRFS_METADATA_ITEM_KEY;
6896 key.offset = owner_objectid;
6899 ret = btrfs_search_slot(trans, extent_root,
6901 if (ret > 0 && skinny_metadata && path->slots[0]) {
6903 * Couldn't find our skinny metadata item,
6904 * see if we have ye olde extent item.
6907 btrfs_item_key_to_cpu(path->nodes[0], &key,
6909 if (key.objectid == bytenr &&
6910 key.type == BTRFS_EXTENT_ITEM_KEY &&
6911 key.offset == num_bytes)
6915 if (ret > 0 && skinny_metadata) {
6916 skinny_metadata = false;
6917 key.objectid = bytenr;
6918 key.type = BTRFS_EXTENT_ITEM_KEY;
6919 key.offset = num_bytes;
6920 btrfs_release_path(path);
6921 ret = btrfs_search_slot(trans, extent_root,
6927 "umm, got %d back from search, was looking for %llu",
6930 btrfs_print_leaf(info, path->nodes[0]);
6933 btrfs_abort_transaction(trans, ret);
6936 extent_slot = path->slots[0];
6938 } else if (WARN_ON(ret == -ENOENT)) {
6939 btrfs_print_leaf(info, path->nodes[0]);
6941 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
6942 bytenr, parent, root_objectid, owner_objectid,
6944 btrfs_abort_transaction(trans, ret);
6947 btrfs_abort_transaction(trans, ret);
6951 leaf = path->nodes[0];
6952 item_size = btrfs_item_size_nr(leaf, extent_slot);
6953 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6954 if (item_size < sizeof(*ei)) {
6955 BUG_ON(found_extent || extent_slot != path->slots[0]);
6956 ret = convert_extent_item_v0(trans, extent_root, path,
6959 btrfs_abort_transaction(trans, ret);
6963 btrfs_release_path(path);
6964 path->leave_spinning = 1;
6966 key.objectid = bytenr;
6967 key.type = BTRFS_EXTENT_ITEM_KEY;
6968 key.offset = num_bytes;
6970 ret = btrfs_search_slot(trans, extent_root, &key, path,
6974 "umm, got %d back from search, was looking for %llu",
6976 btrfs_print_leaf(info, path->nodes[0]);
6979 btrfs_abort_transaction(trans, ret);
6983 extent_slot = path->slots[0];
6984 leaf = path->nodes[0];
6985 item_size = btrfs_item_size_nr(leaf, extent_slot);
6988 BUG_ON(item_size < sizeof(*ei));
6989 ei = btrfs_item_ptr(leaf, extent_slot,
6990 struct btrfs_extent_item);
6991 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
6992 key.type == BTRFS_EXTENT_ITEM_KEY) {
6993 struct btrfs_tree_block_info *bi;
6994 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
6995 bi = (struct btrfs_tree_block_info *)(ei + 1);
6996 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
6999 refs = btrfs_extent_refs(leaf, ei);
7000 if (refs < refs_to_drop) {
7002 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
7003 refs_to_drop, refs, bytenr);
7005 btrfs_abort_transaction(trans, ret);
7008 refs -= refs_to_drop;
7012 __run_delayed_extent_op(extent_op, leaf, ei);
7014 * In the case of inline back ref, reference count will
7015 * be updated by remove_extent_backref
7018 BUG_ON(!found_extent);
7020 btrfs_set_extent_refs(leaf, ei, refs);
7021 btrfs_mark_buffer_dirty(leaf);
7024 ret = remove_extent_backref(trans, extent_root, path,
7026 is_data, &last_ref);
7028 btrfs_abort_transaction(trans, ret);
7032 add_pinned_bytes(info, -num_bytes, owner_objectid,
7036 BUG_ON(is_data && refs_to_drop !=
7037 extent_data_ref_count(path, iref));
7039 BUG_ON(path->slots[0] != extent_slot);
7041 BUG_ON(path->slots[0] != extent_slot + 1);
7042 path->slots[0] = extent_slot;
7048 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
7051 btrfs_abort_transaction(trans, ret);
7054 btrfs_release_path(path);
7057 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
7059 btrfs_abort_transaction(trans, ret);
7064 ret = add_to_free_space_tree(trans, info, bytenr, num_bytes);
7066 btrfs_abort_transaction(trans, ret);
7070 ret = update_block_group(trans, info, bytenr, num_bytes, 0);
7072 btrfs_abort_transaction(trans, ret);
7076 btrfs_release_path(path);
7079 btrfs_free_path(path);
7084 * when we free an block, it is possible (and likely) that we free the last
7085 * delayed ref for that extent as well. This searches the delayed ref tree for
7086 * a given extent, and if there are no other delayed refs to be processed, it
7087 * removes it from the tree.
7089 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
7092 struct btrfs_delayed_ref_head *head;
7093 struct btrfs_delayed_ref_root *delayed_refs;
7096 delayed_refs = &trans->transaction->delayed_refs;
7097 spin_lock(&delayed_refs->lock);
7098 head = btrfs_find_delayed_ref_head(trans, bytenr);
7100 goto out_delayed_unlock;
7102 spin_lock(&head->lock);
7103 if (!list_empty(&head->ref_list))
7106 if (head->extent_op) {
7107 if (!head->must_insert_reserved)
7109 btrfs_free_delayed_extent_op(head->extent_op);
7110 head->extent_op = NULL;
7114 * waiting for the lock here would deadlock. If someone else has it
7115 * locked they are already in the process of dropping it anyway
7117 if (!mutex_trylock(&head->mutex))
7121 * at this point we have a head with no other entries. Go
7122 * ahead and process it.
7124 head->node.in_tree = 0;
7125 rb_erase(&head->href_node, &delayed_refs->href_root);
7127 atomic_dec(&delayed_refs->num_entries);
7130 * we don't take a ref on the node because we're removing it from the
7131 * tree, so we just steal the ref the tree was holding.
7133 delayed_refs->num_heads--;
7134 if (head->processing == 0)
7135 delayed_refs->num_heads_ready--;
7136 head->processing = 0;
7137 spin_unlock(&head->lock);
7138 spin_unlock(&delayed_refs->lock);
7140 BUG_ON(head->extent_op);
7141 if (head->must_insert_reserved)
7144 mutex_unlock(&head->mutex);
7145 btrfs_put_delayed_ref(&head->node);
7148 spin_unlock(&head->lock);
7151 spin_unlock(&delayed_refs->lock);
7155 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
7156 struct btrfs_root *root,
7157 struct extent_buffer *buf,
7158 u64 parent, int last_ref)
7160 struct btrfs_fs_info *fs_info = root->fs_info;
7164 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7165 ret = btrfs_add_delayed_tree_ref(fs_info, trans,
7166 buf->start, buf->len,
7168 root->root_key.objectid,
7169 btrfs_header_level(buf),
7170 BTRFS_DROP_DELAYED_REF, NULL);
7171 BUG_ON(ret); /* -ENOMEM */
7177 if (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);
7186 cache = btrfs_lookup_block_group(fs_info, buf->start);
7188 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
7189 pin_down_extent(fs_info, cache, buf->start,
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);
7205 add_pinned_bytes(fs_info, buf->len, btrfs_header_level(buf),
7206 root->root_key.objectid);
7209 * Deleting the buffer, clear the corrupt flag since it doesn't matter
7212 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7215 /* Can return -ENOMEM */
7216 int btrfs_free_extent(struct btrfs_trans_handle *trans,
7217 struct btrfs_fs_info *fs_info,
7218 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
7219 u64 owner, u64 offset)
7223 if (btrfs_is_testing(fs_info))
7226 add_pinned_bytes(fs_info, num_bytes, owner, root_objectid);
7229 * tree log blocks never actually go into the extent allocation
7230 * tree, just update pinning info and exit early.
7232 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
7233 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
7234 /* unlocks the pinned mutex */
7235 btrfs_pin_extent(fs_info, bytenr, num_bytes, 1);
7237 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
7238 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
7240 parent, root_objectid, (int)owner,
7241 BTRFS_DROP_DELAYED_REF, NULL);
7243 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
7245 parent, root_objectid, owner,
7247 BTRFS_DROP_DELAYED_REF, NULL);
7253 * when we wait for progress in the block group caching, its because
7254 * our allocation attempt failed at least once. So, we must sleep
7255 * and let some progress happen before we try again.
7257 * This function will sleep at least once waiting for new free space to
7258 * show up, and then it will check the block group free space numbers
7259 * for our min num_bytes. Another option is to have it go ahead
7260 * and look in the rbtree for a free extent of a given size, but this
7263 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7264 * any of the information in this block group.
7266 static noinline void
7267 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7270 struct btrfs_caching_control *caching_ctl;
7272 caching_ctl = get_caching_control(cache);
7276 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
7277 (cache->free_space_ctl->free_space >= num_bytes));
7279 put_caching_control(caching_ctl);
7283 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7285 struct btrfs_caching_control *caching_ctl;
7288 caching_ctl = get_caching_control(cache);
7290 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
7292 wait_event(caching_ctl->wait, block_group_cache_done(cache));
7293 if (cache->cached == BTRFS_CACHE_ERROR)
7295 put_caching_control(caching_ctl);
7299 int __get_raid_index(u64 flags)
7301 if (flags & BTRFS_BLOCK_GROUP_RAID10)
7302 return BTRFS_RAID_RAID10;
7303 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
7304 return BTRFS_RAID_RAID1;
7305 else if (flags & BTRFS_BLOCK_GROUP_DUP)
7306 return BTRFS_RAID_DUP;
7307 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
7308 return BTRFS_RAID_RAID0;
7309 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
7310 return BTRFS_RAID_RAID5;
7311 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
7312 return BTRFS_RAID_RAID6;
7314 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
7317 int get_block_group_index(struct btrfs_block_group_cache *cache)
7319 return __get_raid_index(cache->flags);
7322 static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
7323 [BTRFS_RAID_RAID10] = "raid10",
7324 [BTRFS_RAID_RAID1] = "raid1",
7325 [BTRFS_RAID_DUP] = "dup",
7326 [BTRFS_RAID_RAID0] = "raid0",
7327 [BTRFS_RAID_SINGLE] = "single",
7328 [BTRFS_RAID_RAID5] = "raid5",
7329 [BTRFS_RAID_RAID6] = "raid6",
7332 static const char *get_raid_name(enum btrfs_raid_types type)
7334 if (type >= BTRFS_NR_RAID_TYPES)
7337 return btrfs_raid_type_names[type];
7340 enum btrfs_loop_type {
7341 LOOP_CACHING_NOWAIT = 0,
7342 LOOP_CACHING_WAIT = 1,
7343 LOOP_ALLOC_CHUNK = 2,
7344 LOOP_NO_EMPTY_SIZE = 3,
7348 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7352 down_read(&cache->data_rwsem);
7356 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7359 btrfs_get_block_group(cache);
7361 down_read(&cache->data_rwsem);
7364 static struct btrfs_block_group_cache *
7365 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7366 struct btrfs_free_cluster *cluster,
7369 struct btrfs_block_group_cache *used_bg = NULL;
7371 spin_lock(&cluster->refill_lock);
7373 used_bg = cluster->block_group;
7377 if (used_bg == block_group)
7380 btrfs_get_block_group(used_bg);
7385 if (down_read_trylock(&used_bg->data_rwsem))
7388 spin_unlock(&cluster->refill_lock);
7390 /* We should only have one-level nested. */
7391 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
7393 spin_lock(&cluster->refill_lock);
7394 if (used_bg == cluster->block_group)
7397 up_read(&used_bg->data_rwsem);
7398 btrfs_put_block_group(used_bg);
7403 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7407 up_read(&cache->data_rwsem);
7408 btrfs_put_block_group(cache);
7412 * walks the btree of allocated extents and find a hole of a given size.
7413 * The key ins is changed to record the hole:
7414 * ins->objectid == start position
7415 * ins->flags = BTRFS_EXTENT_ITEM_KEY
7416 * ins->offset == the size of the hole.
7417 * Any available blocks before search_start are skipped.
7419 * If there is no suitable free space, we will record the max size of
7420 * the free space extent currently.
7422 static noinline int find_free_extent(struct btrfs_root *orig_root,
7423 u64 ram_bytes, u64 num_bytes, u64 empty_size,
7424 u64 hint_byte, struct btrfs_key *ins,
7425 u64 flags, int delalloc)
7427 struct btrfs_fs_info *fs_info = orig_root->fs_info;
7429 struct btrfs_root *root = fs_info->extent_root;
7430 struct btrfs_free_cluster *last_ptr = NULL;
7431 struct btrfs_block_group_cache *block_group = NULL;
7432 u64 search_start = 0;
7433 u64 max_extent_size = 0;
7434 u64 empty_cluster = 0;
7435 struct btrfs_space_info *space_info;
7437 int index = __get_raid_index(flags);
7438 bool failed_cluster_refill = false;
7439 bool failed_alloc = false;
7440 bool use_cluster = true;
7441 bool have_caching_bg = false;
7442 bool orig_have_caching_bg = false;
7443 bool full_search = false;
7445 WARN_ON(num_bytes < fs_info->sectorsize);
7446 ins->type = BTRFS_EXTENT_ITEM_KEY;
7450 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
7452 space_info = __find_space_info(fs_info, flags);
7454 btrfs_err(fs_info, "No space info for %llu", flags);
7459 * If our free space is heavily fragmented we may not be able to make
7460 * big contiguous allocations, so instead of doing the expensive search
7461 * for free space, simply return ENOSPC with our max_extent_size so we
7462 * can go ahead and search for a more manageable chunk.
7464 * If our max_extent_size is large enough for our allocation simply
7465 * disable clustering since we will likely not be able to find enough
7466 * space to create a cluster and induce latency trying.
7468 if (unlikely(space_info->max_extent_size)) {
7469 spin_lock(&space_info->lock);
7470 if (space_info->max_extent_size &&
7471 num_bytes > space_info->max_extent_size) {
7472 ins->offset = space_info->max_extent_size;
7473 spin_unlock(&space_info->lock);
7475 } else if (space_info->max_extent_size) {
7476 use_cluster = false;
7478 spin_unlock(&space_info->lock);
7481 last_ptr = fetch_cluster_info(fs_info, space_info, &empty_cluster);
7483 spin_lock(&last_ptr->lock);
7484 if (last_ptr->block_group)
7485 hint_byte = last_ptr->window_start;
7486 if (last_ptr->fragmented) {
7488 * We still set window_start so we can keep track of the
7489 * last place we found an allocation to try and save
7492 hint_byte = last_ptr->window_start;
7493 use_cluster = false;
7495 spin_unlock(&last_ptr->lock);
7498 search_start = max(search_start, first_logical_byte(fs_info, 0));
7499 search_start = max(search_start, hint_byte);
7500 if (search_start == hint_byte) {
7501 block_group = btrfs_lookup_block_group(fs_info, search_start);
7503 * we don't want to use the block group if it doesn't match our
7504 * allocation bits, or if its not cached.
7506 * However if we are re-searching with an ideal block group
7507 * picked out then we don't care that the block group is cached.
7509 if (block_group && block_group_bits(block_group, flags) &&
7510 block_group->cached != BTRFS_CACHE_NO) {
7511 down_read(&space_info->groups_sem);
7512 if (list_empty(&block_group->list) ||
7515 * someone is removing this block group,
7516 * we can't jump into the have_block_group
7517 * target because our list pointers are not
7520 btrfs_put_block_group(block_group);
7521 up_read(&space_info->groups_sem);
7523 index = get_block_group_index(block_group);
7524 btrfs_lock_block_group(block_group, delalloc);
7525 goto have_block_group;
7527 } else if (block_group) {
7528 btrfs_put_block_group(block_group);
7532 have_caching_bg = false;
7533 if (index == 0 || index == __get_raid_index(flags))
7535 down_read(&space_info->groups_sem);
7536 list_for_each_entry(block_group, &space_info->block_groups[index],
7541 btrfs_grab_block_group(block_group, delalloc);
7542 search_start = block_group->key.objectid;
7545 * this can happen if we end up cycling through all the
7546 * raid types, but we want to make sure we only allocate
7547 * for the proper type.
7549 if (!block_group_bits(block_group, flags)) {
7550 u64 extra = BTRFS_BLOCK_GROUP_DUP |
7551 BTRFS_BLOCK_GROUP_RAID1 |
7552 BTRFS_BLOCK_GROUP_RAID5 |
7553 BTRFS_BLOCK_GROUP_RAID6 |
7554 BTRFS_BLOCK_GROUP_RAID10;
7557 * if they asked for extra copies and this block group
7558 * doesn't provide them, bail. This does allow us to
7559 * fill raid0 from raid1.
7561 if ((flags & extra) && !(block_group->flags & extra))
7566 cached = block_group_cache_done(block_group);
7567 if (unlikely(!cached)) {
7568 have_caching_bg = true;
7569 ret = cache_block_group(block_group, 0);
7574 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7576 if (unlikely(block_group->ro))
7580 * Ok we want to try and use the cluster allocator, so
7583 if (last_ptr && use_cluster) {
7584 struct btrfs_block_group_cache *used_block_group;
7585 unsigned long aligned_cluster;
7587 * the refill lock keeps out other
7588 * people trying to start a new cluster
7590 used_block_group = btrfs_lock_cluster(block_group,
7593 if (!used_block_group)
7594 goto refill_cluster;
7596 if (used_block_group != block_group &&
7597 (used_block_group->ro ||
7598 !block_group_bits(used_block_group, flags)))
7599 goto release_cluster;
7601 offset = btrfs_alloc_from_cluster(used_block_group,
7604 used_block_group->key.objectid,
7607 /* we have a block, we're done */
7608 spin_unlock(&last_ptr->refill_lock);
7609 trace_btrfs_reserve_extent_cluster(fs_info,
7611 search_start, num_bytes);
7612 if (used_block_group != block_group) {
7613 btrfs_release_block_group(block_group,
7615 block_group = used_block_group;
7620 WARN_ON(last_ptr->block_group != used_block_group);
7622 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
7623 * set up a new clusters, so lets just skip it
7624 * and let the allocator find whatever block
7625 * it can find. If we reach this point, we
7626 * will have tried the cluster allocator
7627 * plenty of times and not have found
7628 * anything, so we are likely way too
7629 * fragmented for the clustering stuff to find
7632 * However, if the cluster is taken from the
7633 * current block group, release the cluster
7634 * first, so that we stand a better chance of
7635 * succeeding in the unclustered
7637 if (loop >= LOOP_NO_EMPTY_SIZE &&
7638 used_block_group != block_group) {
7639 spin_unlock(&last_ptr->refill_lock);
7640 btrfs_release_block_group(used_block_group,
7642 goto unclustered_alloc;
7646 * this cluster didn't work out, free it and
7649 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7651 if (used_block_group != block_group)
7652 btrfs_release_block_group(used_block_group,
7655 if (loop >= LOOP_NO_EMPTY_SIZE) {
7656 spin_unlock(&last_ptr->refill_lock);
7657 goto unclustered_alloc;
7660 aligned_cluster = max_t(unsigned long,
7661 empty_cluster + empty_size,
7662 block_group->full_stripe_len);
7664 /* allocate a cluster in this block group */
7665 ret = btrfs_find_space_cluster(fs_info, block_group,
7666 last_ptr, search_start,
7671 * now pull our allocation out of this
7674 offset = btrfs_alloc_from_cluster(block_group,
7680 /* we found one, proceed */
7681 spin_unlock(&last_ptr->refill_lock);
7682 trace_btrfs_reserve_extent_cluster(fs_info,
7683 block_group, search_start,
7687 } else if (!cached && loop > LOOP_CACHING_NOWAIT
7688 && !failed_cluster_refill) {
7689 spin_unlock(&last_ptr->refill_lock);
7691 failed_cluster_refill = true;
7692 wait_block_group_cache_progress(block_group,
7693 num_bytes + empty_cluster + empty_size);
7694 goto have_block_group;
7698 * at this point we either didn't find a cluster
7699 * or we weren't able to allocate a block from our
7700 * cluster. Free the cluster we've been trying
7701 * to use, and go to the next block group
7703 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7704 spin_unlock(&last_ptr->refill_lock);
7710 * We are doing an unclustered alloc, set the fragmented flag so
7711 * we don't bother trying to setup a cluster again until we get
7714 if (unlikely(last_ptr)) {
7715 spin_lock(&last_ptr->lock);
7716 last_ptr->fragmented = 1;
7717 spin_unlock(&last_ptr->lock);
7719 spin_lock(&block_group->free_space_ctl->tree_lock);
7721 block_group->free_space_ctl->free_space <
7722 num_bytes + empty_cluster + empty_size) {
7723 if (block_group->free_space_ctl->free_space >
7726 block_group->free_space_ctl->free_space;
7727 spin_unlock(&block_group->free_space_ctl->tree_lock);
7730 spin_unlock(&block_group->free_space_ctl->tree_lock);
7732 offset = btrfs_find_space_for_alloc(block_group, search_start,
7733 num_bytes, empty_size,
7736 * If we didn't find a chunk, and we haven't failed on this
7737 * block group before, and this block group is in the middle of
7738 * caching and we are ok with waiting, then go ahead and wait
7739 * for progress to be made, and set failed_alloc to true.
7741 * If failed_alloc is true then we've already waited on this
7742 * block group once and should move on to the next block group.
7744 if (!offset && !failed_alloc && !cached &&
7745 loop > LOOP_CACHING_NOWAIT) {
7746 wait_block_group_cache_progress(block_group,
7747 num_bytes + empty_size);
7748 failed_alloc = true;
7749 goto have_block_group;
7750 } else if (!offset) {
7754 search_start = ALIGN(offset, fs_info->stripesize);
7756 /* move on to the next group */
7757 if (search_start + num_bytes >
7758 block_group->key.objectid + block_group->key.offset) {
7759 btrfs_add_free_space(block_group, offset, num_bytes);
7763 if (offset < search_start)
7764 btrfs_add_free_space(block_group, offset,
7765 search_start - offset);
7766 BUG_ON(offset > search_start);
7768 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7769 num_bytes, delalloc);
7770 if (ret == -EAGAIN) {
7771 btrfs_add_free_space(block_group, offset, num_bytes);
7774 btrfs_inc_block_group_reservations(block_group);
7776 /* we are all good, lets return */
7777 ins->objectid = search_start;
7778 ins->offset = num_bytes;
7780 trace_btrfs_reserve_extent(fs_info, block_group,
7781 search_start, num_bytes);
7782 btrfs_release_block_group(block_group, delalloc);
7785 failed_cluster_refill = false;
7786 failed_alloc = false;
7787 BUG_ON(index != get_block_group_index(block_group));
7788 btrfs_release_block_group(block_group, delalloc);
7790 up_read(&space_info->groups_sem);
7792 if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
7793 && !orig_have_caching_bg)
7794 orig_have_caching_bg = true;
7796 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
7799 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
7803 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7804 * caching kthreads as we move along
7805 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7806 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7807 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7810 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
7812 if (loop == LOOP_CACHING_NOWAIT) {
7814 * We want to skip the LOOP_CACHING_WAIT step if we
7815 * don't have any uncached bgs and we've already done a
7816 * full search through.
7818 if (orig_have_caching_bg || !full_search)
7819 loop = LOOP_CACHING_WAIT;
7821 loop = LOOP_ALLOC_CHUNK;
7826 if (loop == LOOP_ALLOC_CHUNK) {
7827 struct btrfs_trans_handle *trans;
7830 trans = current->journal_info;
7834 trans = btrfs_join_transaction(root);
7836 if (IS_ERR(trans)) {
7837 ret = PTR_ERR(trans);
7841 ret = do_chunk_alloc(trans, fs_info, flags,
7845 * If we can't allocate a new chunk we've already looped
7846 * through at least once, move on to the NO_EMPTY_SIZE
7850 loop = LOOP_NO_EMPTY_SIZE;
7853 * Do not bail out on ENOSPC since we
7854 * can do more things.
7856 if (ret < 0 && ret != -ENOSPC)
7857 btrfs_abort_transaction(trans, ret);
7861 btrfs_end_transaction(trans);
7866 if (loop == LOOP_NO_EMPTY_SIZE) {
7868 * Don't loop again if we already have no empty_size and
7871 if (empty_size == 0 &&
7872 empty_cluster == 0) {
7881 } else if (!ins->objectid) {
7883 } else if (ins->objectid) {
7884 if (!use_cluster && last_ptr) {
7885 spin_lock(&last_ptr->lock);
7886 last_ptr->window_start = ins->objectid;
7887 spin_unlock(&last_ptr->lock);
7892 if (ret == -ENOSPC) {
7893 spin_lock(&space_info->lock);
7894 space_info->max_extent_size = max_extent_size;
7895 spin_unlock(&space_info->lock);
7896 ins->offset = max_extent_size;
7901 static void dump_space_info(struct btrfs_fs_info *fs_info,
7902 struct btrfs_space_info *info, u64 bytes,
7903 int dump_block_groups)
7905 struct btrfs_block_group_cache *cache;
7908 spin_lock(&info->lock);
7909 btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
7911 info->total_bytes - info->bytes_used - info->bytes_pinned -
7912 info->bytes_reserved - info->bytes_readonly -
7913 info->bytes_may_use, (info->full) ? "" : "not ");
7915 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
7916 info->total_bytes, info->bytes_used, info->bytes_pinned,
7917 info->bytes_reserved, info->bytes_may_use,
7918 info->bytes_readonly);
7919 spin_unlock(&info->lock);
7921 if (!dump_block_groups)
7924 down_read(&info->groups_sem);
7926 list_for_each_entry(cache, &info->block_groups[index], list) {
7927 spin_lock(&cache->lock);
7929 "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
7930 cache->key.objectid, cache->key.offset,
7931 btrfs_block_group_used(&cache->item), cache->pinned,
7932 cache->reserved, cache->ro ? "[readonly]" : "");
7933 btrfs_dump_free_space(cache, bytes);
7934 spin_unlock(&cache->lock);
7936 if (++index < BTRFS_NR_RAID_TYPES)
7938 up_read(&info->groups_sem);
7941 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
7942 u64 num_bytes, u64 min_alloc_size,
7943 u64 empty_size, u64 hint_byte,
7944 struct btrfs_key *ins, int is_data, int delalloc)
7946 struct btrfs_fs_info *fs_info = root->fs_info;
7947 bool final_tried = num_bytes == min_alloc_size;
7951 flags = btrfs_get_alloc_profile(root, is_data);
7953 WARN_ON(num_bytes < fs_info->sectorsize);
7954 ret = find_free_extent(root, ram_bytes, num_bytes, empty_size,
7955 hint_byte, ins, flags, delalloc);
7956 if (!ret && !is_data) {
7957 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
7958 } else if (ret == -ENOSPC) {
7959 if (!final_tried && ins->offset) {
7960 num_bytes = min(num_bytes >> 1, ins->offset);
7961 num_bytes = round_down(num_bytes,
7962 fs_info->sectorsize);
7963 num_bytes = max(num_bytes, min_alloc_size);
7964 ram_bytes = num_bytes;
7965 if (num_bytes == min_alloc_size)
7968 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
7969 struct btrfs_space_info *sinfo;
7971 sinfo = __find_space_info(fs_info, flags);
7973 "allocation failed flags %llu, wanted %llu",
7976 dump_space_info(fs_info, sinfo, num_bytes, 1);
7983 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7985 int pin, int delalloc)
7987 struct btrfs_block_group_cache *cache;
7990 cache = btrfs_lookup_block_group(fs_info, start);
7992 btrfs_err(fs_info, "Unable to find block group for %llu",
7998 pin_down_extent(fs_info, cache, start, len, 1);
8000 if (btrfs_test_opt(fs_info, DISCARD))
8001 ret = btrfs_discard_extent(fs_info, start, len, NULL);
8002 btrfs_add_free_space(cache, start, len);
8003 btrfs_free_reserved_bytes(cache, len, delalloc);
8004 trace_btrfs_reserved_extent_free(fs_info, start, len);
8007 btrfs_put_block_group(cache);
8011 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8012 u64 start, u64 len, int delalloc)
8014 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
8017 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
8020 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
8023 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8024 struct btrfs_fs_info *fs_info,
8025 u64 parent, u64 root_objectid,
8026 u64 flags, u64 owner, u64 offset,
8027 struct btrfs_key *ins, int ref_mod)
8030 struct btrfs_extent_item *extent_item;
8031 struct btrfs_extent_inline_ref *iref;
8032 struct btrfs_path *path;
8033 struct extent_buffer *leaf;
8038 type = BTRFS_SHARED_DATA_REF_KEY;
8040 type = BTRFS_EXTENT_DATA_REF_KEY;
8042 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
8044 path = btrfs_alloc_path();
8048 path->leave_spinning = 1;
8049 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8052 btrfs_free_path(path);
8056 leaf = path->nodes[0];
8057 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8058 struct btrfs_extent_item);
8059 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
8060 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8061 btrfs_set_extent_flags(leaf, extent_item,
8062 flags | BTRFS_EXTENT_FLAG_DATA);
8064 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8065 btrfs_set_extent_inline_ref_type(leaf, iref, type);
8067 struct btrfs_shared_data_ref *ref;
8068 ref = (struct btrfs_shared_data_ref *)(iref + 1);
8069 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8070 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
8072 struct btrfs_extent_data_ref *ref;
8073 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
8074 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
8075 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
8076 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
8077 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
8080 btrfs_mark_buffer_dirty(path->nodes[0]);
8081 btrfs_free_path(path);
8083 ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8088 ret = update_block_group(trans, fs_info, ins->objectid, ins->offset, 1);
8089 if (ret) { /* -ENOENT, logic error */
8090 btrfs_err(fs_info, "update block group failed for %llu %llu",
8091 ins->objectid, ins->offset);
8094 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
8098 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
8099 struct btrfs_fs_info *fs_info,
8100 u64 parent, u64 root_objectid,
8101 u64 flags, struct btrfs_disk_key *key,
8102 int level, struct btrfs_key *ins)
8105 struct btrfs_extent_item *extent_item;
8106 struct btrfs_tree_block_info *block_info;
8107 struct btrfs_extent_inline_ref *iref;
8108 struct btrfs_path *path;
8109 struct extent_buffer *leaf;
8110 u32 size = sizeof(*extent_item) + sizeof(*iref);
8111 u64 num_bytes = ins->offset;
8112 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8114 if (!skinny_metadata)
8115 size += sizeof(*block_info);
8117 path = btrfs_alloc_path();
8119 btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
8124 path->leave_spinning = 1;
8125 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8128 btrfs_free_path(path);
8129 btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
8134 leaf = path->nodes[0];
8135 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8136 struct btrfs_extent_item);
8137 btrfs_set_extent_refs(leaf, extent_item, 1);
8138 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8139 btrfs_set_extent_flags(leaf, extent_item,
8140 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
8142 if (skinny_metadata) {
8143 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8144 num_bytes = fs_info->nodesize;
8146 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8147 btrfs_set_tree_block_key(leaf, block_info, key);
8148 btrfs_set_tree_block_level(leaf, block_info, level);
8149 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8153 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8154 btrfs_set_extent_inline_ref_type(leaf, iref,
8155 BTRFS_SHARED_BLOCK_REF_KEY);
8156 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8158 btrfs_set_extent_inline_ref_type(leaf, iref,
8159 BTRFS_TREE_BLOCK_REF_KEY);
8160 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
8163 btrfs_mark_buffer_dirty(leaf);
8164 btrfs_free_path(path);
8166 ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8171 ret = update_block_group(trans, fs_info, ins->objectid,
8172 fs_info->nodesize, 1);
8173 if (ret) { /* -ENOENT, logic error */
8174 btrfs_err(fs_info, "update block group failed for %llu %llu",
8175 ins->objectid, ins->offset);
8179 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid,
8184 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8185 u64 root_objectid, u64 owner,
8186 u64 offset, u64 ram_bytes,
8187 struct btrfs_key *ins)
8189 struct btrfs_fs_info *fs_info = trans->fs_info;
8192 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
8194 ret = btrfs_add_delayed_data_ref(fs_info, trans, ins->objectid,
8196 root_objectid, owner, offset,
8197 ram_bytes, BTRFS_ADD_DELAYED_EXTENT,
8203 * this is used by the tree logging recovery code. It records that
8204 * an extent has been allocated and makes sure to clear the free
8205 * space cache bits as well
8207 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
8208 struct btrfs_fs_info *fs_info,
8209 u64 root_objectid, u64 owner, u64 offset,
8210 struct btrfs_key *ins)
8213 struct btrfs_block_group_cache *block_group;
8214 struct btrfs_space_info *space_info;
8217 * Mixed block groups will exclude before processing the log so we only
8218 * need to do the exclude dance if this fs isn't mixed.
8220 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8221 ret = __exclude_logged_extent(fs_info, ins->objectid,
8227 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8231 space_info = block_group->space_info;
8232 spin_lock(&space_info->lock);
8233 spin_lock(&block_group->lock);
8234 space_info->bytes_reserved += ins->offset;
8235 block_group->reserved += ins->offset;
8236 spin_unlock(&block_group->lock);
8237 spin_unlock(&space_info->lock);
8239 ret = alloc_reserved_file_extent(trans, fs_info, 0, root_objectid,
8240 0, owner, offset, ins, 1);
8241 btrfs_put_block_group(block_group);
8245 static struct extent_buffer *
8246 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
8247 u64 bytenr, int level)
8249 struct btrfs_fs_info *fs_info = root->fs_info;
8250 struct extent_buffer *buf;
8252 buf = btrfs_find_create_tree_block(fs_info, bytenr);
8256 btrfs_set_header_generation(buf, trans->transid);
8257 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
8258 btrfs_tree_lock(buf);
8259 clean_tree_block(trans, fs_info, buf);
8260 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
8262 btrfs_set_lock_blocking(buf);
8263 set_extent_buffer_uptodate(buf);
8265 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8266 buf->log_index = root->log_transid % 2;
8268 * we allow two log transactions at a time, use different
8269 * EXENT bit to differentiate dirty pages.
8271 if (buf->log_index == 0)
8272 set_extent_dirty(&root->dirty_log_pages, buf->start,
8273 buf->start + buf->len - 1, GFP_NOFS);
8275 set_extent_new(&root->dirty_log_pages, buf->start,
8276 buf->start + buf->len - 1);
8278 buf->log_index = -1;
8279 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
8280 buf->start + buf->len - 1, GFP_NOFS);
8282 trans->dirty = true;
8283 /* this returns a buffer locked for blocking */
8287 static struct btrfs_block_rsv *
8288 use_block_rsv(struct btrfs_trans_handle *trans,
8289 struct btrfs_root *root, u32 blocksize)
8291 struct btrfs_fs_info *fs_info = root->fs_info;
8292 struct btrfs_block_rsv *block_rsv;
8293 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8295 bool global_updated = false;
8297 block_rsv = get_block_rsv(trans, root);
8299 if (unlikely(block_rsv->size == 0))
8302 ret = block_rsv_use_bytes(block_rsv, blocksize);
8306 if (block_rsv->failfast)
8307 return ERR_PTR(ret);
8309 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8310 global_updated = true;
8311 update_global_block_rsv(fs_info);
8315 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8316 static DEFINE_RATELIMIT_STATE(_rs,
8317 DEFAULT_RATELIMIT_INTERVAL * 10,
8318 /*DEFAULT_RATELIMIT_BURST*/ 1);
8319 if (__ratelimit(&_rs))
8321 "BTRFS: block rsv returned %d\n", ret);
8324 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8325 BTRFS_RESERVE_NO_FLUSH);
8329 * If we couldn't reserve metadata bytes try and use some from
8330 * the global reserve if its space type is the same as the global
8333 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8334 block_rsv->space_info == global_rsv->space_info) {
8335 ret = block_rsv_use_bytes(global_rsv, blocksize);
8339 return ERR_PTR(ret);
8342 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8343 struct btrfs_block_rsv *block_rsv, u32 blocksize)
8345 block_rsv_add_bytes(block_rsv, blocksize, 0);
8346 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
8350 * finds a free extent and does all the dirty work required for allocation
8351 * returns the tree buffer or an ERR_PTR on error.
8353 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
8354 struct btrfs_root *root,
8355 u64 parent, u64 root_objectid,
8356 struct btrfs_disk_key *key, int level,
8357 u64 hint, u64 empty_size)
8359 struct btrfs_fs_info *fs_info = root->fs_info;
8360 struct btrfs_key ins;
8361 struct btrfs_block_rsv *block_rsv;
8362 struct extent_buffer *buf;
8363 struct btrfs_delayed_extent_op *extent_op;
8366 u32 blocksize = fs_info->nodesize;
8367 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8369 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8370 if (btrfs_is_testing(fs_info)) {
8371 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
8374 root->alloc_bytenr += blocksize;
8379 block_rsv = use_block_rsv(trans, root, blocksize);
8380 if (IS_ERR(block_rsv))
8381 return ERR_CAST(block_rsv);
8383 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
8384 empty_size, hint, &ins, 0, 0);
8388 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
8391 goto out_free_reserved;
8394 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8396 parent = ins.objectid;
8397 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8401 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
8402 extent_op = btrfs_alloc_delayed_extent_op();
8408 memcpy(&extent_op->key, key, sizeof(extent_op->key));
8410 memset(&extent_op->key, 0, sizeof(extent_op->key));
8411 extent_op->flags_to_set = flags;
8412 extent_op->update_key = skinny_metadata ? false : true;
8413 extent_op->update_flags = true;
8414 extent_op->is_data = false;
8415 extent_op->level = level;
8417 ret = btrfs_add_delayed_tree_ref(fs_info, trans,
8418 ins.objectid, ins.offset,
8419 parent, root_objectid, level,
8420 BTRFS_ADD_DELAYED_EXTENT,
8423 goto out_free_delayed;
8428 btrfs_free_delayed_extent_op(extent_op);
8430 free_extent_buffer(buf);
8432 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
8434 unuse_block_rsv(fs_info, block_rsv, blocksize);
8435 return ERR_PTR(ret);
8438 struct walk_control {
8439 u64 refs[BTRFS_MAX_LEVEL];
8440 u64 flags[BTRFS_MAX_LEVEL];
8441 struct btrfs_key update_progress;
8452 #define DROP_REFERENCE 1
8453 #define UPDATE_BACKREF 2
8455 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8456 struct btrfs_root *root,
8457 struct walk_control *wc,
8458 struct btrfs_path *path)
8460 struct btrfs_fs_info *fs_info = root->fs_info;
8466 struct btrfs_key key;
8467 struct extent_buffer *eb;
8472 if (path->slots[wc->level] < wc->reada_slot) {
8473 wc->reada_count = wc->reada_count * 2 / 3;
8474 wc->reada_count = max(wc->reada_count, 2);
8476 wc->reada_count = wc->reada_count * 3 / 2;
8477 wc->reada_count = min_t(int, wc->reada_count,
8478 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
8481 eb = path->nodes[wc->level];
8482 nritems = btrfs_header_nritems(eb);
8484 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8485 if (nread >= wc->reada_count)
8489 bytenr = btrfs_node_blockptr(eb, slot);
8490 generation = btrfs_node_ptr_generation(eb, slot);
8492 if (slot == path->slots[wc->level])
8495 if (wc->stage == UPDATE_BACKREF &&
8496 generation <= root->root_key.offset)
8499 /* We don't lock the tree block, it's OK to be racy here */
8500 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
8501 wc->level - 1, 1, &refs,
8503 /* We don't care about errors in readahead. */
8508 if (wc->stage == DROP_REFERENCE) {
8512 if (wc->level == 1 &&
8513 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8515 if (!wc->update_ref ||
8516 generation <= root->root_key.offset)
8518 btrfs_node_key_to_cpu(eb, &key, slot);
8519 ret = btrfs_comp_cpu_keys(&key,
8520 &wc->update_progress);
8524 if (wc->level == 1 &&
8525 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8529 readahead_tree_block(fs_info, bytenr);
8532 wc->reada_slot = slot;
8536 * helper to process tree block while walking down the tree.
8538 * when wc->stage == UPDATE_BACKREF, this function updates
8539 * back refs for pointers in the block.
8541 * NOTE: return value 1 means we should stop walking down.
8543 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8544 struct btrfs_root *root,
8545 struct btrfs_path *path,
8546 struct walk_control *wc, int lookup_info)
8548 struct btrfs_fs_info *fs_info = root->fs_info;
8549 int level = wc->level;
8550 struct extent_buffer *eb = path->nodes[level];
8551 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8554 if (wc->stage == UPDATE_BACKREF &&
8555 btrfs_header_owner(eb) != root->root_key.objectid)
8559 * when reference count of tree block is 1, it won't increase
8560 * again. once full backref flag is set, we never clear it.
8563 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8564 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8565 BUG_ON(!path->locks[level]);
8566 ret = btrfs_lookup_extent_info(trans, fs_info,
8567 eb->start, level, 1,
8570 BUG_ON(ret == -ENOMEM);
8573 BUG_ON(wc->refs[level] == 0);
8576 if (wc->stage == DROP_REFERENCE) {
8577 if (wc->refs[level] > 1)
8580 if (path->locks[level] && !wc->keep_locks) {
8581 btrfs_tree_unlock_rw(eb, path->locks[level]);
8582 path->locks[level] = 0;
8587 /* wc->stage == UPDATE_BACKREF */
8588 if (!(wc->flags[level] & flag)) {
8589 BUG_ON(!path->locks[level]);
8590 ret = btrfs_inc_ref(trans, root, eb, 1);
8591 BUG_ON(ret); /* -ENOMEM */
8592 ret = btrfs_dec_ref(trans, root, eb, 0);
8593 BUG_ON(ret); /* -ENOMEM */
8594 ret = btrfs_set_disk_extent_flags(trans, fs_info, eb->start,
8596 btrfs_header_level(eb), 0);
8597 BUG_ON(ret); /* -ENOMEM */
8598 wc->flags[level] |= flag;
8602 * the block is shared by multiple trees, so it's not good to
8603 * keep the tree lock
8605 if (path->locks[level] && level > 0) {
8606 btrfs_tree_unlock_rw(eb, path->locks[level]);
8607 path->locks[level] = 0;
8613 * helper to process tree block pointer.
8615 * when wc->stage == DROP_REFERENCE, this function checks
8616 * reference count of the block pointed to. if the block
8617 * is shared and we need update back refs for the subtree
8618 * rooted at the block, this function changes wc->stage to
8619 * UPDATE_BACKREF. if the block is shared and there is no
8620 * need to update back, this function drops the reference
8623 * NOTE: return value 1 means we should stop walking down.
8625 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8626 struct btrfs_root *root,
8627 struct btrfs_path *path,
8628 struct walk_control *wc, int *lookup_info)
8630 struct btrfs_fs_info *fs_info = root->fs_info;
8635 struct btrfs_key key;
8636 struct extent_buffer *next;
8637 int level = wc->level;
8640 bool need_account = false;
8642 generation = btrfs_node_ptr_generation(path->nodes[level],
8643 path->slots[level]);
8645 * if the lower level block was created before the snapshot
8646 * was created, we know there is no need to update back refs
8649 if (wc->stage == UPDATE_BACKREF &&
8650 generation <= root->root_key.offset) {
8655 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8656 blocksize = fs_info->nodesize;
8658 next = find_extent_buffer(fs_info, bytenr);
8660 next = btrfs_find_create_tree_block(fs_info, bytenr);
8662 return PTR_ERR(next);
8664 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8668 btrfs_tree_lock(next);
8669 btrfs_set_lock_blocking(next);
8671 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
8672 &wc->refs[level - 1],
8673 &wc->flags[level - 1]);
8677 if (unlikely(wc->refs[level - 1] == 0)) {
8678 btrfs_err(fs_info, "Missing references.");
8684 if (wc->stage == DROP_REFERENCE) {
8685 if (wc->refs[level - 1] > 1) {
8686 need_account = true;
8688 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8691 if (!wc->update_ref ||
8692 generation <= root->root_key.offset)
8695 btrfs_node_key_to_cpu(path->nodes[level], &key,
8696 path->slots[level]);
8697 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8701 wc->stage = UPDATE_BACKREF;
8702 wc->shared_level = level - 1;
8706 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8710 if (!btrfs_buffer_uptodate(next, generation, 0)) {
8711 btrfs_tree_unlock(next);
8712 free_extent_buffer(next);
8718 if (reada && level == 1)
8719 reada_walk_down(trans, root, wc, path);
8720 next = read_tree_block(fs_info, bytenr, generation);
8722 return PTR_ERR(next);
8723 } else if (!extent_buffer_uptodate(next)) {
8724 free_extent_buffer(next);
8727 btrfs_tree_lock(next);
8728 btrfs_set_lock_blocking(next);
8732 ASSERT(level == btrfs_header_level(next));
8733 if (level != btrfs_header_level(next)) {
8734 btrfs_err(root->fs_info, "mismatched level");
8738 path->nodes[level] = next;
8739 path->slots[level] = 0;
8740 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8746 wc->refs[level - 1] = 0;
8747 wc->flags[level - 1] = 0;
8748 if (wc->stage == DROP_REFERENCE) {
8749 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8750 parent = path->nodes[level]->start;
8752 ASSERT(root->root_key.objectid ==
8753 btrfs_header_owner(path->nodes[level]));
8754 if (root->root_key.objectid !=
8755 btrfs_header_owner(path->nodes[level])) {
8756 btrfs_err(root->fs_info,
8757 "mismatched block owner");
8765 ret = btrfs_qgroup_trace_subtree(trans, root, next,
8766 generation, level - 1);
8768 btrfs_err_rl(fs_info,
8769 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
8773 ret = btrfs_free_extent(trans, fs_info, bytenr, blocksize,
8774 parent, root->root_key.objectid,
8784 btrfs_tree_unlock(next);
8785 free_extent_buffer(next);
8791 * helper to process tree block while walking up the tree.
8793 * when wc->stage == DROP_REFERENCE, this function drops
8794 * reference count on the block.
8796 * when wc->stage == UPDATE_BACKREF, this function changes
8797 * wc->stage back to DROP_REFERENCE if we changed wc->stage
8798 * to UPDATE_BACKREF previously while processing the block.
8800 * NOTE: return value 1 means we should stop walking up.
8802 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
8803 struct btrfs_root *root,
8804 struct btrfs_path *path,
8805 struct walk_control *wc)
8807 struct btrfs_fs_info *fs_info = root->fs_info;
8809 int level = wc->level;
8810 struct extent_buffer *eb = path->nodes[level];
8813 if (wc->stage == UPDATE_BACKREF) {
8814 BUG_ON(wc->shared_level < level);
8815 if (level < wc->shared_level)
8818 ret = find_next_key(path, level + 1, &wc->update_progress);
8822 wc->stage = DROP_REFERENCE;
8823 wc->shared_level = -1;
8824 path->slots[level] = 0;
8827 * check reference count again if the block isn't locked.
8828 * we should start walking down the tree again if reference
8831 if (!path->locks[level]) {
8833 btrfs_tree_lock(eb);
8834 btrfs_set_lock_blocking(eb);
8835 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8837 ret = btrfs_lookup_extent_info(trans, fs_info,
8838 eb->start, level, 1,
8842 btrfs_tree_unlock_rw(eb, path->locks[level]);
8843 path->locks[level] = 0;
8846 BUG_ON(wc->refs[level] == 0);
8847 if (wc->refs[level] == 1) {
8848 btrfs_tree_unlock_rw(eb, path->locks[level]);
8849 path->locks[level] = 0;
8855 /* wc->stage == DROP_REFERENCE */
8856 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
8858 if (wc->refs[level] == 1) {
8860 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8861 ret = btrfs_dec_ref(trans, root, eb, 1);
8863 ret = btrfs_dec_ref(trans, root, eb, 0);
8864 BUG_ON(ret); /* -ENOMEM */
8865 ret = btrfs_qgroup_trace_leaf_items(trans, fs_info, eb);
8867 btrfs_err_rl(fs_info,
8868 "error %d accounting leaf items. Quota is out of sync, rescan required.",
8872 /* make block locked assertion in clean_tree_block happy */
8873 if (!path->locks[level] &&
8874 btrfs_header_generation(eb) == trans->transid) {
8875 btrfs_tree_lock(eb);
8876 btrfs_set_lock_blocking(eb);
8877 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8879 clean_tree_block(trans, fs_info, eb);
8882 if (eb == root->node) {
8883 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8886 BUG_ON(root->root_key.objectid !=
8887 btrfs_header_owner(eb));
8889 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8890 parent = path->nodes[level + 1]->start;
8892 BUG_ON(root->root_key.objectid !=
8893 btrfs_header_owner(path->nodes[level + 1]));
8896 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
8898 wc->refs[level] = 0;
8899 wc->flags[level] = 0;
8903 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8904 struct btrfs_root *root,
8905 struct btrfs_path *path,
8906 struct walk_control *wc)
8908 int level = wc->level;
8909 int lookup_info = 1;
8912 while (level >= 0) {
8913 ret = walk_down_proc(trans, root, path, wc, lookup_info);
8920 if (path->slots[level] >=
8921 btrfs_header_nritems(path->nodes[level]))
8924 ret = do_walk_down(trans, root, path, wc, &lookup_info);
8926 path->slots[level]++;
8935 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
8936 struct btrfs_root *root,
8937 struct btrfs_path *path,
8938 struct walk_control *wc, int max_level)
8940 int level = wc->level;
8943 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8944 while (level < max_level && path->nodes[level]) {
8946 if (path->slots[level] + 1 <
8947 btrfs_header_nritems(path->nodes[level])) {
8948 path->slots[level]++;
8951 ret = walk_up_proc(trans, root, path, wc);
8955 if (path->locks[level]) {
8956 btrfs_tree_unlock_rw(path->nodes[level],
8957 path->locks[level]);
8958 path->locks[level] = 0;
8960 free_extent_buffer(path->nodes[level]);
8961 path->nodes[level] = NULL;
8969 * drop a subvolume tree.
8971 * this function traverses the tree freeing any blocks that only
8972 * referenced by the tree.
8974 * when a shared tree block is found. this function decreases its
8975 * reference count by one. if update_ref is true, this function
8976 * also make sure backrefs for the shared block and all lower level
8977 * blocks are properly updated.
8979 * If called with for_reloc == 0, may exit early with -EAGAIN
8981 int btrfs_drop_snapshot(struct btrfs_root *root,
8982 struct btrfs_block_rsv *block_rsv, int update_ref,
8985 struct btrfs_fs_info *fs_info = root->fs_info;
8986 struct btrfs_path *path;
8987 struct btrfs_trans_handle *trans;
8988 struct btrfs_root *tree_root = fs_info->tree_root;
8989 struct btrfs_root_item *root_item = &root->root_item;
8990 struct walk_control *wc;
8991 struct btrfs_key key;
8995 bool root_dropped = false;
8997 btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
8999 path = btrfs_alloc_path();
9005 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9007 btrfs_free_path(path);
9012 trans = btrfs_start_transaction(tree_root, 0);
9013 if (IS_ERR(trans)) {
9014 err = PTR_ERR(trans);
9019 trans->block_rsv = block_rsv;
9021 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
9022 level = btrfs_header_level(root->node);
9023 path->nodes[level] = btrfs_lock_root_node(root);
9024 btrfs_set_lock_blocking(path->nodes[level]);
9025 path->slots[level] = 0;
9026 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9027 memset(&wc->update_progress, 0,
9028 sizeof(wc->update_progress));
9030 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
9031 memcpy(&wc->update_progress, &key,
9032 sizeof(wc->update_progress));
9034 level = root_item->drop_level;
9036 path->lowest_level = level;
9037 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
9038 path->lowest_level = 0;
9046 * unlock our path, this is safe because only this
9047 * function is allowed to delete this snapshot
9049 btrfs_unlock_up_safe(path, 0);
9051 level = btrfs_header_level(root->node);
9053 btrfs_tree_lock(path->nodes[level]);
9054 btrfs_set_lock_blocking(path->nodes[level]);
9055 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9057 ret = btrfs_lookup_extent_info(trans, fs_info,
9058 path->nodes[level]->start,
9059 level, 1, &wc->refs[level],
9065 BUG_ON(wc->refs[level] == 0);
9067 if (level == root_item->drop_level)
9070 btrfs_tree_unlock(path->nodes[level]);
9071 path->locks[level] = 0;
9072 WARN_ON(wc->refs[level] != 1);
9078 wc->shared_level = -1;
9079 wc->stage = DROP_REFERENCE;
9080 wc->update_ref = update_ref;
9082 wc->for_reloc = for_reloc;
9083 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9087 ret = walk_down_tree(trans, root, path, wc);
9093 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9100 BUG_ON(wc->stage != DROP_REFERENCE);
9104 if (wc->stage == DROP_REFERENCE) {
9106 btrfs_node_key(path->nodes[level],
9107 &root_item->drop_progress,
9108 path->slots[level]);
9109 root_item->drop_level = level;
9112 BUG_ON(wc->level == 0);
9113 if (btrfs_should_end_transaction(trans) ||
9114 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
9115 ret = btrfs_update_root(trans, tree_root,
9119 btrfs_abort_transaction(trans, ret);
9124 btrfs_end_transaction_throttle(trans);
9125 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
9126 btrfs_debug(fs_info,
9127 "drop snapshot early exit");
9132 trans = btrfs_start_transaction(tree_root, 0);
9133 if (IS_ERR(trans)) {
9134 err = PTR_ERR(trans);
9138 trans->block_rsv = block_rsv;
9141 btrfs_release_path(path);
9145 ret = btrfs_del_root(trans, tree_root, &root->root_key);
9147 btrfs_abort_transaction(trans, ret);
9151 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
9152 ret = btrfs_find_root(tree_root, &root->root_key, path,
9155 btrfs_abort_transaction(trans, ret);
9158 } else if (ret > 0) {
9159 /* if we fail to delete the orphan item this time
9160 * around, it'll get picked up the next time.
9162 * The most common failure here is just -ENOENT.
9164 btrfs_del_orphan_item(trans, tree_root,
9165 root->root_key.objectid);
9169 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
9170 btrfs_add_dropped_root(trans, root);
9172 free_extent_buffer(root->node);
9173 free_extent_buffer(root->commit_root);
9174 btrfs_put_fs_root(root);
9176 root_dropped = true;
9178 btrfs_end_transaction_throttle(trans);
9181 btrfs_free_path(path);
9184 * So if we need to stop dropping the snapshot for whatever reason we
9185 * need to make sure to add it back to the dead root list so that we
9186 * keep trying to do the work later. This also cleans up roots if we
9187 * don't have it in the radix (like when we recover after a power fail
9188 * or unmount) so we don't leak memory.
9190 if (!for_reloc && root_dropped == false)
9191 btrfs_add_dead_root(root);
9192 if (err && err != -EAGAIN)
9193 btrfs_handle_fs_error(fs_info, err, NULL);
9198 * drop subtree rooted at tree block 'node'.
9200 * NOTE: this function will unlock and release tree block 'node'
9201 * only used by relocation code
9203 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9204 struct btrfs_root *root,
9205 struct extent_buffer *node,
9206 struct extent_buffer *parent)
9208 struct btrfs_fs_info *fs_info = root->fs_info;
9209 struct btrfs_path *path;
9210 struct walk_control *wc;
9216 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9218 path = btrfs_alloc_path();
9222 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9224 btrfs_free_path(path);
9228 btrfs_assert_tree_locked(parent);
9229 parent_level = btrfs_header_level(parent);
9230 extent_buffer_get(parent);
9231 path->nodes[parent_level] = parent;
9232 path->slots[parent_level] = btrfs_header_nritems(parent);
9234 btrfs_assert_tree_locked(node);
9235 level = btrfs_header_level(node);
9236 path->nodes[level] = node;
9237 path->slots[level] = 0;
9238 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9240 wc->refs[parent_level] = 1;
9241 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9243 wc->shared_level = -1;
9244 wc->stage = DROP_REFERENCE;
9248 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9251 wret = walk_down_tree(trans, root, path, wc);
9257 wret = walk_up_tree(trans, root, path, wc, parent_level);
9265 btrfs_free_path(path);
9269 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
9275 * if restripe for this chunk_type is on pick target profile and
9276 * return, otherwise do the usual balance
9278 stripped = get_restripe_target(fs_info, flags);
9280 return extended_to_chunk(stripped);
9282 num_devices = fs_info->fs_devices->rw_devices;
9284 stripped = BTRFS_BLOCK_GROUP_RAID0 |
9285 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
9286 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9288 if (num_devices == 1) {
9289 stripped |= BTRFS_BLOCK_GROUP_DUP;
9290 stripped = flags & ~stripped;
9292 /* turn raid0 into single device chunks */
9293 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9296 /* turn mirroring into duplication */
9297 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9298 BTRFS_BLOCK_GROUP_RAID10))
9299 return stripped | BTRFS_BLOCK_GROUP_DUP;
9301 /* they already had raid on here, just return */
9302 if (flags & stripped)
9305 stripped |= BTRFS_BLOCK_GROUP_DUP;
9306 stripped = flags & ~stripped;
9308 /* switch duplicated blocks with raid1 */
9309 if (flags & BTRFS_BLOCK_GROUP_DUP)
9310 return stripped | BTRFS_BLOCK_GROUP_RAID1;
9312 /* this is drive concat, leave it alone */
9318 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9320 struct btrfs_space_info *sinfo = cache->space_info;
9322 u64 min_allocable_bytes;
9326 * We need some metadata space and system metadata space for
9327 * allocating chunks in some corner cases until we force to set
9328 * it to be readonly.
9331 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9333 min_allocable_bytes = SZ_1M;
9335 min_allocable_bytes = 0;
9337 spin_lock(&sinfo->lock);
9338 spin_lock(&cache->lock);
9346 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9347 cache->bytes_super - btrfs_block_group_used(&cache->item);
9349 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
9350 sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
9351 min_allocable_bytes <= sinfo->total_bytes) {
9352 sinfo->bytes_readonly += num_bytes;
9354 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9358 spin_unlock(&cache->lock);
9359 spin_unlock(&sinfo->lock);
9363 int btrfs_inc_block_group_ro(struct btrfs_root *root,
9364 struct btrfs_block_group_cache *cache)
9367 struct btrfs_fs_info *fs_info = root->fs_info;
9368 struct btrfs_trans_handle *trans;
9373 trans = btrfs_join_transaction(root);
9375 return PTR_ERR(trans);
9378 * we're not allowed to set block groups readonly after the dirty
9379 * block groups cache has started writing. If it already started,
9380 * back off and let this transaction commit
9382 mutex_lock(&fs_info->ro_block_group_mutex);
9383 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
9384 u64 transid = trans->transid;
9386 mutex_unlock(&fs_info->ro_block_group_mutex);
9387 btrfs_end_transaction(trans);
9389 ret = btrfs_wait_for_commit(fs_info, transid);
9396 * if we are changing raid levels, try to allocate a corresponding
9397 * block group with the new raid level.
9399 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9400 if (alloc_flags != cache->flags) {
9401 ret = do_chunk_alloc(trans, fs_info, alloc_flags,
9404 * ENOSPC is allowed here, we may have enough space
9405 * already allocated at the new raid level to
9414 ret = inc_block_group_ro(cache, 0);
9417 alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
9418 ret = do_chunk_alloc(trans, fs_info, alloc_flags,
9422 ret = inc_block_group_ro(cache, 0);
9424 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9425 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9426 mutex_lock(&fs_info->chunk_mutex);
9427 check_system_chunk(trans, fs_info, alloc_flags);
9428 mutex_unlock(&fs_info->chunk_mutex);
9430 mutex_unlock(&fs_info->ro_block_group_mutex);
9432 btrfs_end_transaction(trans);
9436 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
9437 struct btrfs_fs_info *fs_info, u64 type)
9439 u64 alloc_flags = get_alloc_profile(fs_info, type);
9441 return do_chunk_alloc(trans, fs_info, alloc_flags, CHUNK_ALLOC_FORCE);
9445 * helper to account the unused space of all the readonly block group in the
9446 * space_info. takes mirrors into account.
9448 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
9450 struct btrfs_block_group_cache *block_group;
9454 /* It's df, we don't care if it's racy */
9455 if (list_empty(&sinfo->ro_bgs))
9458 spin_lock(&sinfo->lock);
9459 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
9460 spin_lock(&block_group->lock);
9462 if (!block_group->ro) {
9463 spin_unlock(&block_group->lock);
9467 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
9468 BTRFS_BLOCK_GROUP_RAID10 |
9469 BTRFS_BLOCK_GROUP_DUP))
9474 free_bytes += (block_group->key.offset -
9475 btrfs_block_group_used(&block_group->item)) *
9478 spin_unlock(&block_group->lock);
9480 spin_unlock(&sinfo->lock);
9485 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
9487 struct btrfs_space_info *sinfo = cache->space_info;
9492 spin_lock(&sinfo->lock);
9493 spin_lock(&cache->lock);
9495 num_bytes = cache->key.offset - cache->reserved -
9496 cache->pinned - cache->bytes_super -
9497 btrfs_block_group_used(&cache->item);
9498 sinfo->bytes_readonly -= num_bytes;
9499 list_del_init(&cache->ro_list);
9501 spin_unlock(&cache->lock);
9502 spin_unlock(&sinfo->lock);
9506 * checks to see if its even possible to relocate this block group.
9508 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9509 * ok to go ahead and try.
9511 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
9513 struct btrfs_root *root = fs_info->extent_root;
9514 struct btrfs_block_group_cache *block_group;
9515 struct btrfs_space_info *space_info;
9516 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
9517 struct btrfs_device *device;
9518 struct btrfs_trans_handle *trans;
9528 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
9530 block_group = btrfs_lookup_block_group(fs_info, bytenr);
9532 /* odd, couldn't find the block group, leave it alone */
9536 "can't find block group for bytenr %llu",
9541 min_free = btrfs_block_group_used(&block_group->item);
9543 /* no bytes used, we're good */
9547 space_info = block_group->space_info;
9548 spin_lock(&space_info->lock);
9550 full = space_info->full;
9553 * if this is the last block group we have in this space, we can't
9554 * relocate it unless we're able to allocate a new chunk below.
9556 * Otherwise, we need to make sure we have room in the space to handle
9557 * all of the extents from this block group. If we can, we're good
9559 if ((space_info->total_bytes != block_group->key.offset) &&
9560 (space_info->bytes_used + space_info->bytes_reserved +
9561 space_info->bytes_pinned + space_info->bytes_readonly +
9562 min_free < space_info->total_bytes)) {
9563 spin_unlock(&space_info->lock);
9566 spin_unlock(&space_info->lock);
9569 * ok we don't have enough space, but maybe we have free space on our
9570 * devices to allocate new chunks for relocation, so loop through our
9571 * alloc devices and guess if we have enough space. if this block
9572 * group is going to be restriped, run checks against the target
9573 * profile instead of the current one.
9585 target = get_restripe_target(fs_info, block_group->flags);
9587 index = __get_raid_index(extended_to_chunk(target));
9590 * this is just a balance, so if we were marked as full
9591 * we know there is no space for a new chunk
9596 "no space to alloc new chunk for block group %llu",
9597 block_group->key.objectid);
9601 index = get_block_group_index(block_group);
9604 if (index == BTRFS_RAID_RAID10) {
9608 } else if (index == BTRFS_RAID_RAID1) {
9610 } else if (index == BTRFS_RAID_DUP) {
9613 } else if (index == BTRFS_RAID_RAID0) {
9614 dev_min = fs_devices->rw_devices;
9615 min_free = div64_u64(min_free, dev_min);
9618 /* We need to do this so that we can look at pending chunks */
9619 trans = btrfs_join_transaction(root);
9620 if (IS_ERR(trans)) {
9621 ret = PTR_ERR(trans);
9625 mutex_lock(&fs_info->chunk_mutex);
9626 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
9630 * check to make sure we can actually find a chunk with enough
9631 * space to fit our block group in.
9633 if (device->total_bytes > device->bytes_used + min_free &&
9634 !device->is_tgtdev_for_dev_replace) {
9635 ret = find_free_dev_extent(trans, device, min_free,
9640 if (dev_nr >= dev_min)
9646 if (debug && ret == -1)
9648 "no space to allocate a new chunk for block group %llu",
9649 block_group->key.objectid);
9650 mutex_unlock(&fs_info->chunk_mutex);
9651 btrfs_end_transaction(trans);
9653 btrfs_put_block_group(block_group);
9657 static int find_first_block_group(struct btrfs_fs_info *fs_info,
9658 struct btrfs_path *path,
9659 struct btrfs_key *key)
9661 struct btrfs_root *root = fs_info->extent_root;
9663 struct btrfs_key found_key;
9664 struct extent_buffer *leaf;
9667 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9672 slot = path->slots[0];
9673 leaf = path->nodes[0];
9674 if (slot >= btrfs_header_nritems(leaf)) {
9675 ret = btrfs_next_leaf(root, path);
9682 btrfs_item_key_to_cpu(leaf, &found_key, slot);
9684 if (found_key.objectid >= key->objectid &&
9685 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9686 struct extent_map_tree *em_tree;
9687 struct extent_map *em;
9689 em_tree = &root->fs_info->mapping_tree.map_tree;
9690 read_lock(&em_tree->lock);
9691 em = lookup_extent_mapping(em_tree, found_key.objectid,
9693 read_unlock(&em_tree->lock);
9696 "logical %llu len %llu found bg but no related chunk",
9697 found_key.objectid, found_key.offset);
9702 free_extent_map(em);
9711 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
9713 struct btrfs_block_group_cache *block_group;
9717 struct inode *inode;
9719 block_group = btrfs_lookup_first_block_group(info, last);
9720 while (block_group) {
9721 spin_lock(&block_group->lock);
9722 if (block_group->iref)
9724 spin_unlock(&block_group->lock);
9725 block_group = next_block_group(info, block_group);
9734 inode = block_group->inode;
9735 block_group->iref = 0;
9736 block_group->inode = NULL;
9737 spin_unlock(&block_group->lock);
9738 ASSERT(block_group->io_ctl.inode == NULL);
9740 last = block_group->key.objectid + block_group->key.offset;
9741 btrfs_put_block_group(block_group);
9745 int btrfs_free_block_groups(struct btrfs_fs_info *info)
9747 struct btrfs_block_group_cache *block_group;
9748 struct btrfs_space_info *space_info;
9749 struct btrfs_caching_control *caching_ctl;
9752 down_write(&info->commit_root_sem);
9753 while (!list_empty(&info->caching_block_groups)) {
9754 caching_ctl = list_entry(info->caching_block_groups.next,
9755 struct btrfs_caching_control, list);
9756 list_del(&caching_ctl->list);
9757 put_caching_control(caching_ctl);
9759 up_write(&info->commit_root_sem);
9761 spin_lock(&info->unused_bgs_lock);
9762 while (!list_empty(&info->unused_bgs)) {
9763 block_group = list_first_entry(&info->unused_bgs,
9764 struct btrfs_block_group_cache,
9766 list_del_init(&block_group->bg_list);
9767 btrfs_put_block_group(block_group);
9769 spin_unlock(&info->unused_bgs_lock);
9771 spin_lock(&info->block_group_cache_lock);
9772 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
9773 block_group = rb_entry(n, struct btrfs_block_group_cache,
9775 rb_erase(&block_group->cache_node,
9776 &info->block_group_cache_tree);
9777 RB_CLEAR_NODE(&block_group->cache_node);
9778 spin_unlock(&info->block_group_cache_lock);
9780 down_write(&block_group->space_info->groups_sem);
9781 list_del(&block_group->list);
9782 up_write(&block_group->space_info->groups_sem);
9784 if (block_group->cached == BTRFS_CACHE_STARTED)
9785 wait_block_group_cache_done(block_group);
9788 * We haven't cached this block group, which means we could
9789 * possibly have excluded extents on this block group.
9791 if (block_group->cached == BTRFS_CACHE_NO ||
9792 block_group->cached == BTRFS_CACHE_ERROR)
9793 free_excluded_extents(info, block_group);
9795 btrfs_remove_free_space_cache(block_group);
9796 ASSERT(list_empty(&block_group->dirty_list));
9797 ASSERT(list_empty(&block_group->io_list));
9798 ASSERT(list_empty(&block_group->bg_list));
9799 ASSERT(atomic_read(&block_group->count) == 1);
9800 btrfs_put_block_group(block_group);
9802 spin_lock(&info->block_group_cache_lock);
9804 spin_unlock(&info->block_group_cache_lock);
9806 /* now that all the block groups are freed, go through and
9807 * free all the space_info structs. This is only called during
9808 * the final stages of unmount, and so we know nobody is
9809 * using them. We call synchronize_rcu() once before we start,
9810 * just to be on the safe side.
9814 release_global_block_rsv(info);
9816 while (!list_empty(&info->space_info)) {
9819 space_info = list_entry(info->space_info.next,
9820 struct btrfs_space_info,
9824 * Do not hide this behind enospc_debug, this is actually
9825 * important and indicates a real bug if this happens.
9827 if (WARN_ON(space_info->bytes_pinned > 0 ||
9828 space_info->bytes_reserved > 0 ||
9829 space_info->bytes_may_use > 0))
9830 dump_space_info(info, space_info, 0, 0);
9831 list_del(&space_info->list);
9832 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
9833 struct kobject *kobj;
9834 kobj = space_info->block_group_kobjs[i];
9835 space_info->block_group_kobjs[i] = NULL;
9841 kobject_del(&space_info->kobj);
9842 kobject_put(&space_info->kobj);
9847 static void __link_block_group(struct btrfs_space_info *space_info,
9848 struct btrfs_block_group_cache *cache)
9850 int index = get_block_group_index(cache);
9853 down_write(&space_info->groups_sem);
9854 if (list_empty(&space_info->block_groups[index]))
9856 list_add_tail(&cache->list, &space_info->block_groups[index]);
9857 up_write(&space_info->groups_sem);
9860 struct raid_kobject *rkobj;
9863 rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
9866 rkobj->raid_type = index;
9867 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
9868 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
9869 "%s", get_raid_name(index));
9871 kobject_put(&rkobj->kobj);
9874 space_info->block_group_kobjs[index] = &rkobj->kobj;
9879 btrfs_warn(cache->fs_info,
9880 "failed to add kobject for block cache, ignoring");
9883 static struct btrfs_block_group_cache *
9884 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
9885 u64 start, u64 size)
9887 struct btrfs_block_group_cache *cache;
9889 cache = kzalloc(sizeof(*cache), GFP_NOFS);
9893 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
9895 if (!cache->free_space_ctl) {
9900 cache->key.objectid = start;
9901 cache->key.offset = size;
9902 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9904 cache->sectorsize = fs_info->sectorsize;
9905 cache->fs_info = fs_info;
9906 cache->full_stripe_len = btrfs_full_stripe_len(fs_info,
9907 &fs_info->mapping_tree,
9909 set_free_space_tree_thresholds(cache);
9911 atomic_set(&cache->count, 1);
9912 spin_lock_init(&cache->lock);
9913 init_rwsem(&cache->data_rwsem);
9914 INIT_LIST_HEAD(&cache->list);
9915 INIT_LIST_HEAD(&cache->cluster_list);
9916 INIT_LIST_HEAD(&cache->bg_list);
9917 INIT_LIST_HEAD(&cache->ro_list);
9918 INIT_LIST_HEAD(&cache->dirty_list);
9919 INIT_LIST_HEAD(&cache->io_list);
9920 btrfs_init_free_space_ctl(cache);
9921 atomic_set(&cache->trimming, 0);
9922 mutex_init(&cache->free_space_lock);
9927 int btrfs_read_block_groups(struct btrfs_fs_info *info)
9929 struct btrfs_path *path;
9931 struct btrfs_block_group_cache *cache;
9932 struct btrfs_space_info *space_info;
9933 struct btrfs_key key;
9934 struct btrfs_key found_key;
9935 struct extent_buffer *leaf;
9941 feature = btrfs_super_incompat_flags(info->super_copy);
9942 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
9946 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9947 path = btrfs_alloc_path();
9950 path->reada = READA_FORWARD;
9952 cache_gen = btrfs_super_cache_generation(info->super_copy);
9953 if (btrfs_test_opt(info, SPACE_CACHE) &&
9954 btrfs_super_generation(info->super_copy) != cache_gen)
9956 if (btrfs_test_opt(info, CLEAR_CACHE))
9960 ret = find_first_block_group(info, path, &key);
9966 leaf = path->nodes[0];
9967 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9969 cache = btrfs_create_block_group_cache(info, found_key.objectid,
9978 * When we mount with old space cache, we need to
9979 * set BTRFS_DC_CLEAR and set dirty flag.
9981 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
9982 * truncate the old free space cache inode and
9984 * b) Setting 'dirty flag' makes sure that we flush
9985 * the new space cache info onto disk.
9987 if (btrfs_test_opt(info, SPACE_CACHE))
9988 cache->disk_cache_state = BTRFS_DC_CLEAR;
9991 read_extent_buffer(leaf, &cache->item,
9992 btrfs_item_ptr_offset(leaf, path->slots[0]),
9993 sizeof(cache->item));
9994 cache->flags = btrfs_block_group_flags(&cache->item);
9996 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
9997 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
9999 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
10000 cache->key.objectid);
10005 key.objectid = found_key.objectid + found_key.offset;
10006 btrfs_release_path(path);
10009 * We need to exclude the super stripes now so that the space
10010 * info has super bytes accounted for, otherwise we'll think
10011 * we have more space than we actually do.
10013 ret = exclude_super_stripes(info, cache);
10016 * We may have excluded something, so call this just in
10019 free_excluded_extents(info, cache);
10020 btrfs_put_block_group(cache);
10025 * check for two cases, either we are full, and therefore
10026 * don't need to bother with the caching work since we won't
10027 * find any space, or we are empty, and we can just add all
10028 * the space in and be done with it. This saves us _alot_ of
10029 * time, particularly in the full case.
10031 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
10032 cache->last_byte_to_unpin = (u64)-1;
10033 cache->cached = BTRFS_CACHE_FINISHED;
10034 free_excluded_extents(info, cache);
10035 } else if (btrfs_block_group_used(&cache->item) == 0) {
10036 cache->last_byte_to_unpin = (u64)-1;
10037 cache->cached = BTRFS_CACHE_FINISHED;
10038 add_new_free_space(cache, info,
10039 found_key.objectid,
10040 found_key.objectid +
10042 free_excluded_extents(info, cache);
10045 ret = btrfs_add_block_group_cache(info, cache);
10047 btrfs_remove_free_space_cache(cache);
10048 btrfs_put_block_group(cache);
10052 trace_btrfs_add_block_group(info, cache, 0);
10053 ret = update_space_info(info, cache->flags, found_key.offset,
10054 btrfs_block_group_used(&cache->item),
10055 cache->bytes_super, &space_info);
10057 btrfs_remove_free_space_cache(cache);
10058 spin_lock(&info->block_group_cache_lock);
10059 rb_erase(&cache->cache_node,
10060 &info->block_group_cache_tree);
10061 RB_CLEAR_NODE(&cache->cache_node);
10062 spin_unlock(&info->block_group_cache_lock);
10063 btrfs_put_block_group(cache);
10067 cache->space_info = space_info;
10069 __link_block_group(space_info, cache);
10071 set_avail_alloc_bits(info, cache->flags);
10072 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
10073 inc_block_group_ro(cache, 1);
10074 } else if (btrfs_block_group_used(&cache->item) == 0) {
10075 spin_lock(&info->unused_bgs_lock);
10076 /* Should always be true but just in case. */
10077 if (list_empty(&cache->bg_list)) {
10078 btrfs_get_block_group(cache);
10079 list_add_tail(&cache->bg_list,
10080 &info->unused_bgs);
10082 spin_unlock(&info->unused_bgs_lock);
10086 list_for_each_entry_rcu(space_info, &info->space_info, list) {
10087 if (!(get_alloc_profile(info, space_info->flags) &
10088 (BTRFS_BLOCK_GROUP_RAID10 |
10089 BTRFS_BLOCK_GROUP_RAID1 |
10090 BTRFS_BLOCK_GROUP_RAID5 |
10091 BTRFS_BLOCK_GROUP_RAID6 |
10092 BTRFS_BLOCK_GROUP_DUP)))
10095 * avoid allocating from un-mirrored block group if there are
10096 * mirrored block groups.
10098 list_for_each_entry(cache,
10099 &space_info->block_groups[BTRFS_RAID_RAID0],
10101 inc_block_group_ro(cache, 1);
10102 list_for_each_entry(cache,
10103 &space_info->block_groups[BTRFS_RAID_SINGLE],
10105 inc_block_group_ro(cache, 1);
10108 init_global_block_rsv(info);
10111 btrfs_free_path(path);
10115 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
10116 struct btrfs_fs_info *fs_info)
10118 struct btrfs_block_group_cache *block_group, *tmp;
10119 struct btrfs_root *extent_root = fs_info->extent_root;
10120 struct btrfs_block_group_item item;
10121 struct btrfs_key key;
10123 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
10125 trans->can_flush_pending_bgs = false;
10126 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
10130 spin_lock(&block_group->lock);
10131 memcpy(&item, &block_group->item, sizeof(item));
10132 memcpy(&key, &block_group->key, sizeof(key));
10133 spin_unlock(&block_group->lock);
10135 ret = btrfs_insert_item(trans, extent_root, &key, &item,
10138 btrfs_abort_transaction(trans, ret);
10139 ret = btrfs_finish_chunk_alloc(trans, fs_info, key.objectid,
10142 btrfs_abort_transaction(trans, ret);
10143 add_block_group_free_space(trans, fs_info, block_group);
10144 /* already aborted the transaction if it failed. */
10146 list_del_init(&block_group->bg_list);
10148 trans->can_flush_pending_bgs = can_flush_pending_bgs;
10151 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
10152 struct btrfs_fs_info *fs_info, u64 bytes_used,
10153 u64 type, u64 chunk_objectid, u64 chunk_offset,
10156 struct btrfs_block_group_cache *cache;
10159 btrfs_set_log_full_commit(fs_info, trans);
10161 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
10165 btrfs_set_block_group_used(&cache->item, bytes_used);
10166 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
10167 btrfs_set_block_group_flags(&cache->item, type);
10169 cache->flags = type;
10170 cache->last_byte_to_unpin = (u64)-1;
10171 cache->cached = BTRFS_CACHE_FINISHED;
10172 cache->needs_free_space = 1;
10173 ret = exclude_super_stripes(fs_info, cache);
10176 * We may have excluded something, so call this just in
10179 free_excluded_extents(fs_info, cache);
10180 btrfs_put_block_group(cache);
10184 add_new_free_space(cache, fs_info, chunk_offset, chunk_offset + size);
10186 free_excluded_extents(fs_info, cache);
10188 #ifdef CONFIG_BTRFS_DEBUG
10189 if (btrfs_should_fragment_free_space(cache)) {
10190 u64 new_bytes_used = size - bytes_used;
10192 bytes_used += new_bytes_used >> 1;
10193 fragment_free_space(cache);
10197 * Call to ensure the corresponding space_info object is created and
10198 * assigned to our block group, but don't update its counters just yet.
10199 * We want our bg to be added to the rbtree with its ->space_info set.
10201 ret = update_space_info(fs_info, cache->flags, 0, 0, 0,
10202 &cache->space_info);
10204 btrfs_remove_free_space_cache(cache);
10205 btrfs_put_block_group(cache);
10209 ret = btrfs_add_block_group_cache(fs_info, cache);
10211 btrfs_remove_free_space_cache(cache);
10212 btrfs_put_block_group(cache);
10217 * Now that our block group has its ->space_info set and is inserted in
10218 * the rbtree, update the space info's counters.
10220 trace_btrfs_add_block_group(fs_info, cache, 1);
10221 ret = update_space_info(fs_info, cache->flags, size, bytes_used,
10222 cache->bytes_super, &cache->space_info);
10224 btrfs_remove_free_space_cache(cache);
10225 spin_lock(&fs_info->block_group_cache_lock);
10226 rb_erase(&cache->cache_node,
10227 &fs_info->block_group_cache_tree);
10228 RB_CLEAR_NODE(&cache->cache_node);
10229 spin_unlock(&fs_info->block_group_cache_lock);
10230 btrfs_put_block_group(cache);
10233 update_global_block_rsv(fs_info);
10235 __link_block_group(cache->space_info, cache);
10237 list_add_tail(&cache->bg_list, &trans->new_bgs);
10239 set_avail_alloc_bits(fs_info, type);
10243 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10245 u64 extra_flags = chunk_to_extended(flags) &
10246 BTRFS_EXTENDED_PROFILE_MASK;
10248 write_seqlock(&fs_info->profiles_lock);
10249 if (flags & BTRFS_BLOCK_GROUP_DATA)
10250 fs_info->avail_data_alloc_bits &= ~extra_flags;
10251 if (flags & BTRFS_BLOCK_GROUP_METADATA)
10252 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10253 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10254 fs_info->avail_system_alloc_bits &= ~extra_flags;
10255 write_sequnlock(&fs_info->profiles_lock);
10258 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
10259 struct btrfs_fs_info *fs_info, u64 group_start,
10260 struct extent_map *em)
10262 struct btrfs_root *root = fs_info->extent_root;
10263 struct btrfs_path *path;
10264 struct btrfs_block_group_cache *block_group;
10265 struct btrfs_free_cluster *cluster;
10266 struct btrfs_root *tree_root = fs_info->tree_root;
10267 struct btrfs_key key;
10268 struct inode *inode;
10269 struct kobject *kobj = NULL;
10273 struct btrfs_caching_control *caching_ctl = NULL;
10276 block_group = btrfs_lookup_block_group(fs_info, group_start);
10277 BUG_ON(!block_group);
10278 BUG_ON(!block_group->ro);
10281 * Free the reserved super bytes from this block group before
10284 free_excluded_extents(fs_info, block_group);
10286 memcpy(&key, &block_group->key, sizeof(key));
10287 index = get_block_group_index(block_group);
10288 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
10289 BTRFS_BLOCK_GROUP_RAID1 |
10290 BTRFS_BLOCK_GROUP_RAID10))
10295 /* make sure this block group isn't part of an allocation cluster */
10296 cluster = &fs_info->data_alloc_cluster;
10297 spin_lock(&cluster->refill_lock);
10298 btrfs_return_cluster_to_free_space(block_group, cluster);
10299 spin_unlock(&cluster->refill_lock);
10302 * make sure this block group isn't part of a metadata
10303 * allocation cluster
10305 cluster = &fs_info->meta_alloc_cluster;
10306 spin_lock(&cluster->refill_lock);
10307 btrfs_return_cluster_to_free_space(block_group, cluster);
10308 spin_unlock(&cluster->refill_lock);
10310 path = btrfs_alloc_path();
10317 * get the inode first so any iput calls done for the io_list
10318 * aren't the final iput (no unlinks allowed now)
10320 inode = lookup_free_space_inode(tree_root, block_group, path);
10322 mutex_lock(&trans->transaction->cache_write_mutex);
10324 * make sure our free spache cache IO is done before remove the
10327 spin_lock(&trans->transaction->dirty_bgs_lock);
10328 if (!list_empty(&block_group->io_list)) {
10329 list_del_init(&block_group->io_list);
10331 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10333 spin_unlock(&trans->transaction->dirty_bgs_lock);
10334 btrfs_wait_cache_io(trans, block_group, path);
10335 btrfs_put_block_group(block_group);
10336 spin_lock(&trans->transaction->dirty_bgs_lock);
10339 if (!list_empty(&block_group->dirty_list)) {
10340 list_del_init(&block_group->dirty_list);
10341 btrfs_put_block_group(block_group);
10343 spin_unlock(&trans->transaction->dirty_bgs_lock);
10344 mutex_unlock(&trans->transaction->cache_write_mutex);
10346 if (!IS_ERR(inode)) {
10347 ret = btrfs_orphan_add(trans, inode);
10349 btrfs_add_delayed_iput(inode);
10352 clear_nlink(inode);
10353 /* One for the block groups ref */
10354 spin_lock(&block_group->lock);
10355 if (block_group->iref) {
10356 block_group->iref = 0;
10357 block_group->inode = NULL;
10358 spin_unlock(&block_group->lock);
10361 spin_unlock(&block_group->lock);
10363 /* One for our lookup ref */
10364 btrfs_add_delayed_iput(inode);
10367 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10368 key.offset = block_group->key.objectid;
10371 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10375 btrfs_release_path(path);
10377 ret = btrfs_del_item(trans, tree_root, path);
10380 btrfs_release_path(path);
10383 spin_lock(&fs_info->block_group_cache_lock);
10384 rb_erase(&block_group->cache_node,
10385 &fs_info->block_group_cache_tree);
10386 RB_CLEAR_NODE(&block_group->cache_node);
10388 if (fs_info->first_logical_byte == block_group->key.objectid)
10389 fs_info->first_logical_byte = (u64)-1;
10390 spin_unlock(&fs_info->block_group_cache_lock);
10392 down_write(&block_group->space_info->groups_sem);
10394 * we must use list_del_init so people can check to see if they
10395 * are still on the list after taking the semaphore
10397 list_del_init(&block_group->list);
10398 if (list_empty(&block_group->space_info->block_groups[index])) {
10399 kobj = block_group->space_info->block_group_kobjs[index];
10400 block_group->space_info->block_group_kobjs[index] = NULL;
10401 clear_avail_alloc_bits(fs_info, block_group->flags);
10403 up_write(&block_group->space_info->groups_sem);
10409 if (block_group->has_caching_ctl)
10410 caching_ctl = get_caching_control(block_group);
10411 if (block_group->cached == BTRFS_CACHE_STARTED)
10412 wait_block_group_cache_done(block_group);
10413 if (block_group->has_caching_ctl) {
10414 down_write(&fs_info->commit_root_sem);
10415 if (!caching_ctl) {
10416 struct btrfs_caching_control *ctl;
10418 list_for_each_entry(ctl,
10419 &fs_info->caching_block_groups, list)
10420 if (ctl->block_group == block_group) {
10422 atomic_inc(&caching_ctl->count);
10427 list_del_init(&caching_ctl->list);
10428 up_write(&fs_info->commit_root_sem);
10430 /* Once for the caching bgs list and once for us. */
10431 put_caching_control(caching_ctl);
10432 put_caching_control(caching_ctl);
10436 spin_lock(&trans->transaction->dirty_bgs_lock);
10437 if (!list_empty(&block_group->dirty_list)) {
10440 if (!list_empty(&block_group->io_list)) {
10443 spin_unlock(&trans->transaction->dirty_bgs_lock);
10444 btrfs_remove_free_space_cache(block_group);
10446 spin_lock(&block_group->space_info->lock);
10447 list_del_init(&block_group->ro_list);
10449 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
10450 WARN_ON(block_group->space_info->total_bytes
10451 < block_group->key.offset);
10452 WARN_ON(block_group->space_info->bytes_readonly
10453 < block_group->key.offset);
10454 WARN_ON(block_group->space_info->disk_total
10455 < block_group->key.offset * factor);
10457 block_group->space_info->total_bytes -= block_group->key.offset;
10458 block_group->space_info->bytes_readonly -= block_group->key.offset;
10459 block_group->space_info->disk_total -= block_group->key.offset * factor;
10461 spin_unlock(&block_group->space_info->lock);
10463 memcpy(&key, &block_group->key, sizeof(key));
10465 mutex_lock(&fs_info->chunk_mutex);
10466 if (!list_empty(&em->list)) {
10467 /* We're in the transaction->pending_chunks list. */
10468 free_extent_map(em);
10470 spin_lock(&block_group->lock);
10471 block_group->removed = 1;
10473 * At this point trimming can't start on this block group, because we
10474 * removed the block group from the tree fs_info->block_group_cache_tree
10475 * so no one can't find it anymore and even if someone already got this
10476 * block group before we removed it from the rbtree, they have already
10477 * incremented block_group->trimming - if they didn't, they won't find
10478 * any free space entries because we already removed them all when we
10479 * called btrfs_remove_free_space_cache().
10481 * And we must not remove the extent map from the fs_info->mapping_tree
10482 * to prevent the same logical address range and physical device space
10483 * ranges from being reused for a new block group. This is because our
10484 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10485 * completely transactionless, so while it is trimming a range the
10486 * currently running transaction might finish and a new one start,
10487 * allowing for new block groups to be created that can reuse the same
10488 * physical device locations unless we take this special care.
10490 * There may also be an implicit trim operation if the file system
10491 * is mounted with -odiscard. The same protections must remain
10492 * in place until the extents have been discarded completely when
10493 * the transaction commit has completed.
10495 remove_em = (atomic_read(&block_group->trimming) == 0);
10497 * Make sure a trimmer task always sees the em in the pinned_chunks list
10498 * if it sees block_group->removed == 1 (needs to lock block_group->lock
10499 * before checking block_group->removed).
10503 * Our em might be in trans->transaction->pending_chunks which
10504 * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
10505 * and so is the fs_info->pinned_chunks list.
10507 * So at this point we must be holding the chunk_mutex to avoid
10508 * any races with chunk allocation (more specifically at
10509 * volumes.c:contains_pending_extent()), to ensure it always
10510 * sees the em, either in the pending_chunks list or in the
10511 * pinned_chunks list.
10513 list_move_tail(&em->list, &fs_info->pinned_chunks);
10515 spin_unlock(&block_group->lock);
10518 struct extent_map_tree *em_tree;
10520 em_tree = &fs_info->mapping_tree.map_tree;
10521 write_lock(&em_tree->lock);
10523 * The em might be in the pending_chunks list, so make sure the
10524 * chunk mutex is locked, since remove_extent_mapping() will
10525 * delete us from that list.
10527 remove_extent_mapping(em_tree, em);
10528 write_unlock(&em_tree->lock);
10529 /* once for the tree */
10530 free_extent_map(em);
10533 mutex_unlock(&fs_info->chunk_mutex);
10535 ret = remove_block_group_free_space(trans, fs_info, block_group);
10539 btrfs_put_block_group(block_group);
10540 btrfs_put_block_group(block_group);
10542 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10548 ret = btrfs_del_item(trans, root, path);
10550 btrfs_free_path(path);
10554 struct btrfs_trans_handle *
10555 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10556 const u64 chunk_offset)
10558 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
10559 struct extent_map *em;
10560 struct map_lookup *map;
10561 unsigned int num_items;
10563 read_lock(&em_tree->lock);
10564 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10565 read_unlock(&em_tree->lock);
10566 ASSERT(em && em->start == chunk_offset);
10569 * We need to reserve 3 + N units from the metadata space info in order
10570 * to remove a block group (done at btrfs_remove_chunk() and at
10571 * btrfs_remove_block_group()), which are used for:
10573 * 1 unit for adding the free space inode's orphan (located in the tree
10575 * 1 unit for deleting the block group item (located in the extent
10577 * 1 unit for deleting the free space item (located in tree of tree
10579 * N units for deleting N device extent items corresponding to each
10580 * stripe (located in the device tree).
10582 * In order to remove a block group we also need to reserve units in the
10583 * system space info in order to update the chunk tree (update one or
10584 * more device items and remove one chunk item), but this is done at
10585 * btrfs_remove_chunk() through a call to check_system_chunk().
10587 map = em->map_lookup;
10588 num_items = 3 + map->num_stripes;
10589 free_extent_map(em);
10591 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
10596 * Process the unused_bgs list and remove any that don't have any allocated
10597 * space inside of them.
10599 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10601 struct btrfs_block_group_cache *block_group;
10602 struct btrfs_space_info *space_info;
10603 struct btrfs_trans_handle *trans;
10606 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
10609 spin_lock(&fs_info->unused_bgs_lock);
10610 while (!list_empty(&fs_info->unused_bgs)) {
10614 block_group = list_first_entry(&fs_info->unused_bgs,
10615 struct btrfs_block_group_cache,
10617 list_del_init(&block_group->bg_list);
10619 space_info = block_group->space_info;
10621 if (ret || btrfs_mixed_space_info(space_info)) {
10622 btrfs_put_block_group(block_group);
10625 spin_unlock(&fs_info->unused_bgs_lock);
10627 mutex_lock(&fs_info->delete_unused_bgs_mutex);
10629 /* Don't want to race with allocators so take the groups_sem */
10630 down_write(&space_info->groups_sem);
10631 spin_lock(&block_group->lock);
10632 if (block_group->reserved ||
10633 btrfs_block_group_used(&block_group->item) ||
10635 list_is_singular(&block_group->list)) {
10637 * We want to bail if we made new allocations or have
10638 * outstanding allocations in this block group. We do
10639 * the ro check in case balance is currently acting on
10640 * this block group.
10642 spin_unlock(&block_group->lock);
10643 up_write(&space_info->groups_sem);
10646 spin_unlock(&block_group->lock);
10648 /* We don't want to force the issue, only flip if it's ok. */
10649 ret = inc_block_group_ro(block_group, 0);
10650 up_write(&space_info->groups_sem);
10657 * Want to do this before we do anything else so we can recover
10658 * properly if we fail to join the transaction.
10660 trans = btrfs_start_trans_remove_block_group(fs_info,
10661 block_group->key.objectid);
10662 if (IS_ERR(trans)) {
10663 btrfs_dec_block_group_ro(block_group);
10664 ret = PTR_ERR(trans);
10669 * We could have pending pinned extents for this block group,
10670 * just delete them, we don't care about them anymore.
10672 start = block_group->key.objectid;
10673 end = start + block_group->key.offset - 1;
10675 * Hold the unused_bg_unpin_mutex lock to avoid racing with
10676 * btrfs_finish_extent_commit(). If we are at transaction N,
10677 * another task might be running finish_extent_commit() for the
10678 * previous transaction N - 1, and have seen a range belonging
10679 * to the block group in freed_extents[] before we were able to
10680 * clear the whole block group range from freed_extents[]. This
10681 * means that task can lookup for the block group after we
10682 * unpinned it from freed_extents[] and removed it, leading to
10683 * a BUG_ON() at btrfs_unpin_extent_range().
10685 mutex_lock(&fs_info->unused_bg_unpin_mutex);
10686 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
10689 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10690 btrfs_dec_block_group_ro(block_group);
10693 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
10696 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10697 btrfs_dec_block_group_ro(block_group);
10700 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10702 /* Reset pinned so btrfs_put_block_group doesn't complain */
10703 spin_lock(&space_info->lock);
10704 spin_lock(&block_group->lock);
10706 space_info->bytes_pinned -= block_group->pinned;
10707 space_info->bytes_readonly += block_group->pinned;
10708 percpu_counter_add(&space_info->total_bytes_pinned,
10709 -block_group->pinned);
10710 block_group->pinned = 0;
10712 spin_unlock(&block_group->lock);
10713 spin_unlock(&space_info->lock);
10715 /* DISCARD can flip during remount */
10716 trimming = btrfs_test_opt(fs_info, DISCARD);
10718 /* Implicit trim during transaction commit. */
10720 btrfs_get_block_group_trimming(block_group);
10723 * Btrfs_remove_chunk will abort the transaction if things go
10726 ret = btrfs_remove_chunk(trans, fs_info,
10727 block_group->key.objectid);
10731 btrfs_put_block_group_trimming(block_group);
10736 * If we're not mounted with -odiscard, we can just forget
10737 * about this block group. Otherwise we'll need to wait
10738 * until transaction commit to do the actual discard.
10741 spin_lock(&fs_info->unused_bgs_lock);
10743 * A concurrent scrub might have added us to the list
10744 * fs_info->unused_bgs, so use a list_move operation
10745 * to add the block group to the deleted_bgs list.
10747 list_move(&block_group->bg_list,
10748 &trans->transaction->deleted_bgs);
10749 spin_unlock(&fs_info->unused_bgs_lock);
10750 btrfs_get_block_group(block_group);
10753 btrfs_end_transaction(trans);
10755 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
10756 btrfs_put_block_group(block_group);
10757 spin_lock(&fs_info->unused_bgs_lock);
10759 spin_unlock(&fs_info->unused_bgs_lock);
10762 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
10764 struct btrfs_space_info *space_info;
10765 struct btrfs_super_block *disk_super;
10771 disk_super = fs_info->super_copy;
10772 if (!btrfs_super_root(disk_super))
10775 features = btrfs_super_incompat_flags(disk_super);
10776 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
10779 flags = BTRFS_BLOCK_GROUP_SYSTEM;
10780 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10785 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
10786 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10788 flags = BTRFS_BLOCK_GROUP_METADATA;
10789 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10793 flags = BTRFS_BLOCK_GROUP_DATA;
10794 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10800 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
10801 u64 start, u64 end)
10803 return unpin_extent_range(fs_info, start, end, false);
10807 * It used to be that old block groups would be left around forever.
10808 * Iterating over them would be enough to trim unused space. Since we
10809 * now automatically remove them, we also need to iterate over unallocated
10812 * We don't want a transaction for this since the discard may take a
10813 * substantial amount of time. We don't require that a transaction be
10814 * running, but we do need to take a running transaction into account
10815 * to ensure that we're not discarding chunks that were released in
10816 * the current transaction.
10818 * Holding the chunks lock will prevent other threads from allocating
10819 * or releasing chunks, but it won't prevent a running transaction
10820 * from committing and releasing the memory that the pending chunks
10821 * list head uses. For that, we need to take a reference to the
10824 static int btrfs_trim_free_extents(struct btrfs_device *device,
10825 u64 minlen, u64 *trimmed)
10827 u64 start = 0, len = 0;
10832 /* Not writeable = nothing to do. */
10833 if (!device->writeable)
10836 /* No free space = nothing to do. */
10837 if (device->total_bytes <= device->bytes_used)
10843 struct btrfs_fs_info *fs_info = device->fs_info;
10844 struct btrfs_transaction *trans;
10847 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
10851 down_read(&fs_info->commit_root_sem);
10853 spin_lock(&fs_info->trans_lock);
10854 trans = fs_info->running_transaction;
10856 atomic_inc(&trans->use_count);
10857 spin_unlock(&fs_info->trans_lock);
10859 ret = find_free_dev_extent_start(trans, device, minlen, start,
10862 btrfs_put_transaction(trans);
10865 up_read(&fs_info->commit_root_sem);
10866 mutex_unlock(&fs_info->chunk_mutex);
10867 if (ret == -ENOSPC)
10872 ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
10873 up_read(&fs_info->commit_root_sem);
10874 mutex_unlock(&fs_info->chunk_mutex);
10882 if (fatal_signal_pending(current)) {
10883 ret = -ERESTARTSYS;
10893 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
10895 struct btrfs_block_group_cache *cache = NULL;
10896 struct btrfs_device *device;
10897 struct list_head *devices;
10902 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
10906 * try to trim all FS space, our block group may start from non-zero.
10908 if (range->len == total_bytes)
10909 cache = btrfs_lookup_first_block_group(fs_info, range->start);
10911 cache = btrfs_lookup_block_group(fs_info, range->start);
10914 if (cache->key.objectid >= (range->start + range->len)) {
10915 btrfs_put_block_group(cache);
10919 start = max(range->start, cache->key.objectid);
10920 end = min(range->start + range->len,
10921 cache->key.objectid + cache->key.offset);
10923 if (end - start >= range->minlen) {
10924 if (!block_group_cache_done(cache)) {
10925 ret = cache_block_group(cache, 0);
10927 btrfs_put_block_group(cache);
10930 ret = wait_block_group_cache_done(cache);
10932 btrfs_put_block_group(cache);
10936 ret = btrfs_trim_block_group(cache,
10942 trimmed += group_trimmed;
10944 btrfs_put_block_group(cache);
10949 cache = next_block_group(fs_info, cache);
10952 mutex_lock(&fs_info->fs_devices->device_list_mutex);
10953 devices = &fs_info->fs_devices->alloc_list;
10954 list_for_each_entry(device, devices, dev_alloc_list) {
10955 ret = btrfs_trim_free_extents(device, range->minlen,
10960 trimmed += group_trimmed;
10962 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
10964 range->len = trimmed;
10969 * btrfs_{start,end}_write_no_snapshoting() are similar to
10970 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
10971 * data into the page cache through nocow before the subvolume is snapshoted,
10972 * but flush the data into disk after the snapshot creation, or to prevent
10973 * operations while snapshoting is ongoing and that cause the snapshot to be
10974 * inconsistent (writes followed by expanding truncates for example).
10976 void btrfs_end_write_no_snapshoting(struct btrfs_root *root)
10978 percpu_counter_dec(&root->subv_writers->counter);
10980 * Make sure counter is updated before we wake up waiters.
10983 if (waitqueue_active(&root->subv_writers->wait))
10984 wake_up(&root->subv_writers->wait);
10987 int btrfs_start_write_no_snapshoting(struct btrfs_root *root)
10989 if (atomic_read(&root->will_be_snapshoted))
10992 percpu_counter_inc(&root->subv_writers->counter);
10994 * Make sure counter is updated before we check for snapshot creation.
10997 if (atomic_read(&root->will_be_snapshoted)) {
10998 btrfs_end_write_no_snapshoting(root);
11004 static int wait_snapshoting_atomic_t(atomic_t *a)
11010 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
11015 ret = btrfs_start_write_no_snapshoting(root);
11018 wait_on_atomic_t(&root->will_be_snapshoted,
11019 wait_snapshoting_atomic_t,
11020 TASK_UNINTERRUPTIBLE);