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(delayed_refs, 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_fs_info *fs_info,
1039 struct btrfs_path *path,
1040 u64 owner, u32 extra_size)
1042 struct btrfs_root *root = fs_info->extent_root;
1043 struct btrfs_extent_item *item;
1044 struct btrfs_extent_item_v0 *ei0;
1045 struct btrfs_extent_ref_v0 *ref0;
1046 struct btrfs_tree_block_info *bi;
1047 struct extent_buffer *leaf;
1048 struct btrfs_key key;
1049 struct btrfs_key found_key;
1050 u32 new_size = sizeof(*item);
1054 leaf = path->nodes[0];
1055 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1057 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1058 ei0 = btrfs_item_ptr(leaf, path->slots[0],
1059 struct btrfs_extent_item_v0);
1060 refs = btrfs_extent_refs_v0(leaf, ei0);
1062 if (owner == (u64)-1) {
1064 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1065 ret = btrfs_next_leaf(root, path);
1068 BUG_ON(ret > 0); /* Corruption */
1069 leaf = path->nodes[0];
1071 btrfs_item_key_to_cpu(leaf, &found_key,
1073 BUG_ON(key.objectid != found_key.objectid);
1074 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1078 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1079 struct btrfs_extent_ref_v0);
1080 owner = btrfs_ref_objectid_v0(leaf, ref0);
1084 btrfs_release_path(path);
1086 if (owner < BTRFS_FIRST_FREE_OBJECTID)
1087 new_size += sizeof(*bi);
1089 new_size -= sizeof(*ei0);
1090 ret = btrfs_search_slot(trans, root, &key, path,
1091 new_size + extra_size, 1);
1094 BUG_ON(ret); /* Corruption */
1096 btrfs_extend_item(fs_info, path, new_size);
1098 leaf = path->nodes[0];
1099 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1100 btrfs_set_extent_refs(leaf, item, refs);
1101 /* FIXME: get real generation */
1102 btrfs_set_extent_generation(leaf, item, 0);
1103 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1104 btrfs_set_extent_flags(leaf, item,
1105 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1106 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1107 bi = (struct btrfs_tree_block_info *)(item + 1);
1108 /* FIXME: get first key of the block */
1109 memzero_extent_buffer(leaf, (unsigned long)bi, sizeof(*bi));
1110 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1112 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1114 btrfs_mark_buffer_dirty(leaf);
1119 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1121 u32 high_crc = ~(u32)0;
1122 u32 low_crc = ~(u32)0;
1125 lenum = cpu_to_le64(root_objectid);
1126 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1127 lenum = cpu_to_le64(owner);
1128 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1129 lenum = cpu_to_le64(offset);
1130 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1132 return ((u64)high_crc << 31) ^ (u64)low_crc;
1135 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1136 struct btrfs_extent_data_ref *ref)
1138 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1139 btrfs_extent_data_ref_objectid(leaf, ref),
1140 btrfs_extent_data_ref_offset(leaf, ref));
1143 static int match_extent_data_ref(struct extent_buffer *leaf,
1144 struct btrfs_extent_data_ref *ref,
1145 u64 root_objectid, u64 owner, u64 offset)
1147 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1148 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1149 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1154 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1155 struct btrfs_fs_info *fs_info,
1156 struct btrfs_path *path,
1157 u64 bytenr, u64 parent,
1159 u64 owner, u64 offset)
1161 struct btrfs_root *root = fs_info->extent_root;
1162 struct btrfs_key key;
1163 struct btrfs_extent_data_ref *ref;
1164 struct extent_buffer *leaf;
1170 key.objectid = bytenr;
1172 key.type = BTRFS_SHARED_DATA_REF_KEY;
1173 key.offset = parent;
1175 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1176 key.offset = hash_extent_data_ref(root_objectid,
1181 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1190 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1191 key.type = BTRFS_EXTENT_REF_V0_KEY;
1192 btrfs_release_path(path);
1193 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1204 leaf = path->nodes[0];
1205 nritems = btrfs_header_nritems(leaf);
1207 if (path->slots[0] >= nritems) {
1208 ret = btrfs_next_leaf(root, path);
1214 leaf = path->nodes[0];
1215 nritems = btrfs_header_nritems(leaf);
1219 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1220 if (key.objectid != bytenr ||
1221 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1224 ref = btrfs_item_ptr(leaf, path->slots[0],
1225 struct btrfs_extent_data_ref);
1227 if (match_extent_data_ref(leaf, ref, root_objectid,
1230 btrfs_release_path(path);
1242 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1243 struct btrfs_fs_info *fs_info,
1244 struct btrfs_path *path,
1245 u64 bytenr, u64 parent,
1246 u64 root_objectid, u64 owner,
1247 u64 offset, int refs_to_add)
1249 struct btrfs_root *root = fs_info->extent_root;
1250 struct btrfs_key key;
1251 struct extent_buffer *leaf;
1256 key.objectid = bytenr;
1258 key.type = BTRFS_SHARED_DATA_REF_KEY;
1259 key.offset = parent;
1260 size = sizeof(struct btrfs_shared_data_ref);
1262 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1263 key.offset = hash_extent_data_ref(root_objectid,
1265 size = sizeof(struct btrfs_extent_data_ref);
1268 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1269 if (ret && ret != -EEXIST)
1272 leaf = path->nodes[0];
1274 struct btrfs_shared_data_ref *ref;
1275 ref = btrfs_item_ptr(leaf, path->slots[0],
1276 struct btrfs_shared_data_ref);
1278 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1280 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1281 num_refs += refs_to_add;
1282 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1285 struct btrfs_extent_data_ref *ref;
1286 while (ret == -EEXIST) {
1287 ref = btrfs_item_ptr(leaf, path->slots[0],
1288 struct btrfs_extent_data_ref);
1289 if (match_extent_data_ref(leaf, ref, root_objectid,
1292 btrfs_release_path(path);
1294 ret = btrfs_insert_empty_item(trans, root, path, &key,
1296 if (ret && ret != -EEXIST)
1299 leaf = path->nodes[0];
1301 ref = btrfs_item_ptr(leaf, path->slots[0],
1302 struct btrfs_extent_data_ref);
1304 btrfs_set_extent_data_ref_root(leaf, ref,
1306 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1307 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1308 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1310 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1311 num_refs += refs_to_add;
1312 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1315 btrfs_mark_buffer_dirty(leaf);
1318 btrfs_release_path(path);
1322 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1323 struct btrfs_fs_info *fs_info,
1324 struct btrfs_path *path,
1325 int refs_to_drop, int *last_ref)
1327 struct btrfs_key key;
1328 struct btrfs_extent_data_ref *ref1 = NULL;
1329 struct btrfs_shared_data_ref *ref2 = NULL;
1330 struct extent_buffer *leaf;
1334 leaf = path->nodes[0];
1335 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1337 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1338 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1339 struct btrfs_extent_data_ref);
1340 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1341 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1342 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1343 struct btrfs_shared_data_ref);
1344 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1345 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1346 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1347 struct btrfs_extent_ref_v0 *ref0;
1348 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1349 struct btrfs_extent_ref_v0);
1350 num_refs = btrfs_ref_count_v0(leaf, ref0);
1356 BUG_ON(num_refs < refs_to_drop);
1357 num_refs -= refs_to_drop;
1359 if (num_refs == 0) {
1360 ret = btrfs_del_item(trans, fs_info->extent_root, path);
1363 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1364 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1365 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1366 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1367 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1369 struct btrfs_extent_ref_v0 *ref0;
1370 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1371 struct btrfs_extent_ref_v0);
1372 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1375 btrfs_mark_buffer_dirty(leaf);
1380 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1381 struct btrfs_extent_inline_ref *iref)
1383 struct btrfs_key key;
1384 struct extent_buffer *leaf;
1385 struct btrfs_extent_data_ref *ref1;
1386 struct btrfs_shared_data_ref *ref2;
1389 leaf = path->nodes[0];
1390 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1392 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1393 BTRFS_EXTENT_DATA_REF_KEY) {
1394 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1395 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1397 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1398 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1400 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1401 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1402 struct btrfs_extent_data_ref);
1403 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1404 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1405 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1406 struct btrfs_shared_data_ref);
1407 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1408 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1409 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1410 struct btrfs_extent_ref_v0 *ref0;
1411 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1412 struct btrfs_extent_ref_v0);
1413 num_refs = btrfs_ref_count_v0(leaf, ref0);
1421 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1422 struct btrfs_fs_info *fs_info,
1423 struct btrfs_path *path,
1424 u64 bytenr, u64 parent,
1427 struct btrfs_root *root = fs_info->extent_root;
1428 struct btrfs_key key;
1431 key.objectid = bytenr;
1433 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1434 key.offset = parent;
1436 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1437 key.offset = root_objectid;
1440 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1443 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1444 if (ret == -ENOENT && parent) {
1445 btrfs_release_path(path);
1446 key.type = BTRFS_EXTENT_REF_V0_KEY;
1447 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1455 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1456 struct btrfs_fs_info *fs_info,
1457 struct btrfs_path *path,
1458 u64 bytenr, u64 parent,
1461 struct btrfs_key key;
1464 key.objectid = bytenr;
1466 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1467 key.offset = parent;
1469 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1470 key.offset = root_objectid;
1473 ret = btrfs_insert_empty_item(trans, fs_info->extent_root,
1475 btrfs_release_path(path);
1479 static inline int extent_ref_type(u64 parent, u64 owner)
1482 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1484 type = BTRFS_SHARED_BLOCK_REF_KEY;
1486 type = BTRFS_TREE_BLOCK_REF_KEY;
1489 type = BTRFS_SHARED_DATA_REF_KEY;
1491 type = BTRFS_EXTENT_DATA_REF_KEY;
1496 static int find_next_key(struct btrfs_path *path, int level,
1497 struct btrfs_key *key)
1500 for (; level < BTRFS_MAX_LEVEL; level++) {
1501 if (!path->nodes[level])
1503 if (path->slots[level] + 1 >=
1504 btrfs_header_nritems(path->nodes[level]))
1507 btrfs_item_key_to_cpu(path->nodes[level], key,
1508 path->slots[level] + 1);
1510 btrfs_node_key_to_cpu(path->nodes[level], key,
1511 path->slots[level] + 1);
1518 * look for inline back ref. if back ref is found, *ref_ret is set
1519 * to the address of inline back ref, and 0 is returned.
1521 * if back ref isn't found, *ref_ret is set to the address where it
1522 * should be inserted, and -ENOENT is returned.
1524 * if insert is true and there are too many inline back refs, the path
1525 * points to the extent item, and -EAGAIN is returned.
1527 * NOTE: inline back refs are ordered in the same way that back ref
1528 * items in the tree are ordered.
1530 static noinline_for_stack
1531 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1532 struct btrfs_fs_info *fs_info,
1533 struct btrfs_path *path,
1534 struct btrfs_extent_inline_ref **ref_ret,
1535 u64 bytenr, u64 num_bytes,
1536 u64 parent, u64 root_objectid,
1537 u64 owner, u64 offset, int insert)
1539 struct btrfs_root *root = fs_info->extent_root;
1540 struct btrfs_key key;
1541 struct extent_buffer *leaf;
1542 struct btrfs_extent_item *ei;
1543 struct btrfs_extent_inline_ref *iref;
1553 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1555 key.objectid = bytenr;
1556 key.type = BTRFS_EXTENT_ITEM_KEY;
1557 key.offset = num_bytes;
1559 want = extent_ref_type(parent, owner);
1561 extra_size = btrfs_extent_inline_ref_size(want);
1562 path->keep_locks = 1;
1567 * Owner is our parent level, so we can just add one to get the level
1568 * for the block we are interested in.
1570 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1571 key.type = BTRFS_METADATA_ITEM_KEY;
1576 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1583 * We may be a newly converted file system which still has the old fat
1584 * extent entries for metadata, so try and see if we have one of those.
1586 if (ret > 0 && skinny_metadata) {
1587 skinny_metadata = false;
1588 if (path->slots[0]) {
1590 btrfs_item_key_to_cpu(path->nodes[0], &key,
1592 if (key.objectid == bytenr &&
1593 key.type == BTRFS_EXTENT_ITEM_KEY &&
1594 key.offset == num_bytes)
1598 key.objectid = bytenr;
1599 key.type = BTRFS_EXTENT_ITEM_KEY;
1600 key.offset = num_bytes;
1601 btrfs_release_path(path);
1606 if (ret && !insert) {
1609 } else if (WARN_ON(ret)) {
1614 leaf = path->nodes[0];
1615 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1616 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1617 if (item_size < sizeof(*ei)) {
1622 ret = convert_extent_item_v0(trans, fs_info, path, owner,
1628 leaf = path->nodes[0];
1629 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1632 BUG_ON(item_size < sizeof(*ei));
1634 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1635 flags = btrfs_extent_flags(leaf, ei);
1637 ptr = (unsigned long)(ei + 1);
1638 end = (unsigned long)ei + item_size;
1640 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1641 ptr += sizeof(struct btrfs_tree_block_info);
1651 iref = (struct btrfs_extent_inline_ref *)ptr;
1652 type = btrfs_extent_inline_ref_type(leaf, iref);
1656 ptr += btrfs_extent_inline_ref_size(type);
1660 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1661 struct btrfs_extent_data_ref *dref;
1662 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1663 if (match_extent_data_ref(leaf, dref, root_objectid,
1668 if (hash_extent_data_ref_item(leaf, dref) <
1669 hash_extent_data_ref(root_objectid, owner, offset))
1673 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1675 if (parent == ref_offset) {
1679 if (ref_offset < parent)
1682 if (root_objectid == ref_offset) {
1686 if (ref_offset < root_objectid)
1690 ptr += btrfs_extent_inline_ref_size(type);
1692 if (err == -ENOENT && insert) {
1693 if (item_size + extra_size >=
1694 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1699 * To add new inline back ref, we have to make sure
1700 * there is no corresponding back ref item.
1701 * For simplicity, we just do not add new inline back
1702 * ref if there is any kind of item for this block
1704 if (find_next_key(path, 0, &key) == 0 &&
1705 key.objectid == bytenr &&
1706 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1711 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1714 path->keep_locks = 0;
1715 btrfs_unlock_up_safe(path, 1);
1721 * helper to add new inline back ref
1723 static noinline_for_stack
1724 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1725 struct btrfs_path *path,
1726 struct btrfs_extent_inline_ref *iref,
1727 u64 parent, u64 root_objectid,
1728 u64 owner, u64 offset, int refs_to_add,
1729 struct btrfs_delayed_extent_op *extent_op)
1731 struct extent_buffer *leaf;
1732 struct btrfs_extent_item *ei;
1735 unsigned long item_offset;
1740 leaf = path->nodes[0];
1741 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1742 item_offset = (unsigned long)iref - (unsigned long)ei;
1744 type = extent_ref_type(parent, owner);
1745 size = btrfs_extent_inline_ref_size(type);
1747 btrfs_extend_item(fs_info, path, size);
1749 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1750 refs = btrfs_extent_refs(leaf, ei);
1751 refs += refs_to_add;
1752 btrfs_set_extent_refs(leaf, ei, refs);
1754 __run_delayed_extent_op(extent_op, leaf, ei);
1756 ptr = (unsigned long)ei + item_offset;
1757 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1758 if (ptr < end - size)
1759 memmove_extent_buffer(leaf, ptr + size, ptr,
1762 iref = (struct btrfs_extent_inline_ref *)ptr;
1763 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1764 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1765 struct btrfs_extent_data_ref *dref;
1766 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1767 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1768 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1769 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1770 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1771 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1772 struct btrfs_shared_data_ref *sref;
1773 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1774 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1775 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1776 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1777 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1779 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1781 btrfs_mark_buffer_dirty(leaf);
1784 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1785 struct btrfs_fs_info *fs_info,
1786 struct btrfs_path *path,
1787 struct btrfs_extent_inline_ref **ref_ret,
1788 u64 bytenr, u64 num_bytes, u64 parent,
1789 u64 root_objectid, u64 owner, u64 offset)
1793 ret = lookup_inline_extent_backref(trans, fs_info, path, ref_ret,
1794 bytenr, num_bytes, parent,
1795 root_objectid, owner, offset, 0);
1799 btrfs_release_path(path);
1802 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1803 ret = lookup_tree_block_ref(trans, fs_info, path, bytenr,
1804 parent, root_objectid);
1806 ret = lookup_extent_data_ref(trans, fs_info, path, bytenr,
1807 parent, root_objectid, owner,
1814 * helper to update/remove inline back ref
1816 static noinline_for_stack
1817 void update_inline_extent_backref(struct btrfs_fs_info *fs_info,
1818 struct btrfs_path *path,
1819 struct btrfs_extent_inline_ref *iref,
1821 struct btrfs_delayed_extent_op *extent_op,
1824 struct extent_buffer *leaf;
1825 struct btrfs_extent_item *ei;
1826 struct btrfs_extent_data_ref *dref = NULL;
1827 struct btrfs_shared_data_ref *sref = NULL;
1835 leaf = path->nodes[0];
1836 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1837 refs = btrfs_extent_refs(leaf, ei);
1838 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1839 refs += refs_to_mod;
1840 btrfs_set_extent_refs(leaf, ei, refs);
1842 __run_delayed_extent_op(extent_op, leaf, ei);
1844 type = btrfs_extent_inline_ref_type(leaf, iref);
1846 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1847 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1848 refs = btrfs_extent_data_ref_count(leaf, dref);
1849 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1850 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1851 refs = btrfs_shared_data_ref_count(leaf, sref);
1854 BUG_ON(refs_to_mod != -1);
1857 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1858 refs += refs_to_mod;
1861 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1862 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1864 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1867 size = btrfs_extent_inline_ref_size(type);
1868 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1869 ptr = (unsigned long)iref;
1870 end = (unsigned long)ei + item_size;
1871 if (ptr + size < end)
1872 memmove_extent_buffer(leaf, ptr, ptr + size,
1875 btrfs_truncate_item(fs_info, path, item_size, 1);
1877 btrfs_mark_buffer_dirty(leaf);
1880 static noinline_for_stack
1881 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1882 struct btrfs_fs_info *fs_info,
1883 struct btrfs_path *path,
1884 u64 bytenr, u64 num_bytes, u64 parent,
1885 u64 root_objectid, u64 owner,
1886 u64 offset, int refs_to_add,
1887 struct btrfs_delayed_extent_op *extent_op)
1889 struct btrfs_extent_inline_ref *iref;
1892 ret = lookup_inline_extent_backref(trans, fs_info, path, &iref,
1893 bytenr, num_bytes, parent,
1894 root_objectid, owner, offset, 1);
1896 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1897 update_inline_extent_backref(fs_info, path, iref,
1898 refs_to_add, extent_op, NULL);
1899 } else if (ret == -ENOENT) {
1900 setup_inline_extent_backref(fs_info, path, iref, parent,
1901 root_objectid, owner, offset,
1902 refs_to_add, extent_op);
1908 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1909 struct btrfs_fs_info *fs_info,
1910 struct btrfs_path *path,
1911 u64 bytenr, u64 parent, u64 root_objectid,
1912 u64 owner, u64 offset, int refs_to_add)
1915 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1916 BUG_ON(refs_to_add != 1);
1917 ret = insert_tree_block_ref(trans, fs_info, path, bytenr,
1918 parent, root_objectid);
1920 ret = insert_extent_data_ref(trans, fs_info, path, bytenr,
1921 parent, root_objectid,
1922 owner, offset, refs_to_add);
1927 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1928 struct btrfs_fs_info *fs_info,
1929 struct btrfs_path *path,
1930 struct btrfs_extent_inline_ref *iref,
1931 int refs_to_drop, int is_data, int *last_ref)
1935 BUG_ON(!is_data && refs_to_drop != 1);
1937 update_inline_extent_backref(fs_info, path, iref,
1938 -refs_to_drop, NULL, last_ref);
1939 } else if (is_data) {
1940 ret = remove_extent_data_ref(trans, fs_info, path, refs_to_drop,
1944 ret = btrfs_del_item(trans, fs_info->extent_root, path);
1949 #define in_range(b, first, len) ((b) >= (first) && (b) < (first) + (len))
1950 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1951 u64 *discarded_bytes)
1954 u64 bytes_left, end;
1955 u64 aligned_start = ALIGN(start, 1 << 9);
1957 if (WARN_ON(start != aligned_start)) {
1958 len -= aligned_start - start;
1959 len = round_down(len, 1 << 9);
1960 start = aligned_start;
1963 *discarded_bytes = 0;
1971 /* Skip any superblocks on this device. */
1972 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1973 u64 sb_start = btrfs_sb_offset(j);
1974 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1975 u64 size = sb_start - start;
1977 if (!in_range(sb_start, start, bytes_left) &&
1978 !in_range(sb_end, start, bytes_left) &&
1979 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1983 * Superblock spans beginning of range. Adjust start and
1986 if (sb_start <= start) {
1987 start += sb_end - start;
1992 bytes_left = end - start;
1997 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
2000 *discarded_bytes += size;
2001 else if (ret != -EOPNOTSUPP)
2010 bytes_left = end - start;
2014 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
2017 *discarded_bytes += bytes_left;
2022 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
2023 u64 num_bytes, u64 *actual_bytes)
2026 u64 discarded_bytes = 0;
2027 struct btrfs_bio *bbio = NULL;
2031 * Avoid races with device replace and make sure our bbio has devices
2032 * associated to its stripes that don't go away while we are discarding.
2034 btrfs_bio_counter_inc_blocked(fs_info);
2035 /* Tell the block device(s) that the sectors can be discarded */
2036 ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2038 /* Error condition is -ENOMEM */
2040 struct btrfs_bio_stripe *stripe = bbio->stripes;
2044 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2046 if (!stripe->dev->can_discard)
2049 ret = btrfs_issue_discard(stripe->dev->bdev,
2054 discarded_bytes += bytes;
2055 else if (ret != -EOPNOTSUPP)
2056 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2059 * Just in case we get back EOPNOTSUPP for some reason,
2060 * just ignore the return value so we don't screw up
2061 * people calling discard_extent.
2065 btrfs_put_bbio(bbio);
2067 btrfs_bio_counter_dec(fs_info);
2070 *actual_bytes = discarded_bytes;
2073 if (ret == -EOPNOTSUPP)
2078 /* Can return -ENOMEM */
2079 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2080 struct btrfs_fs_info *fs_info,
2081 u64 bytenr, u64 num_bytes, u64 parent,
2082 u64 root_objectid, u64 owner, u64 offset)
2086 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2087 root_objectid == BTRFS_TREE_LOG_OBJECTID);
2089 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
2090 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
2092 parent, root_objectid, (int)owner,
2093 BTRFS_ADD_DELAYED_REF, NULL);
2095 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
2096 num_bytes, parent, root_objectid,
2098 BTRFS_ADD_DELAYED_REF);
2103 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2104 struct btrfs_fs_info *fs_info,
2105 struct btrfs_delayed_ref_node *node,
2106 u64 parent, u64 root_objectid,
2107 u64 owner, u64 offset, int refs_to_add,
2108 struct btrfs_delayed_extent_op *extent_op)
2110 struct btrfs_path *path;
2111 struct extent_buffer *leaf;
2112 struct btrfs_extent_item *item;
2113 struct btrfs_key key;
2114 u64 bytenr = node->bytenr;
2115 u64 num_bytes = node->num_bytes;
2119 path = btrfs_alloc_path();
2123 path->reada = READA_FORWARD;
2124 path->leave_spinning = 1;
2125 /* this will setup the path even if it fails to insert the back ref */
2126 ret = insert_inline_extent_backref(trans, fs_info, path, bytenr,
2127 num_bytes, parent, root_objectid,
2129 refs_to_add, extent_op);
2130 if ((ret < 0 && ret != -EAGAIN) || !ret)
2134 * Ok we had -EAGAIN which means we didn't have space to insert and
2135 * inline extent ref, so just update the reference count and add a
2138 leaf = path->nodes[0];
2139 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2140 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2141 refs = btrfs_extent_refs(leaf, item);
2142 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2144 __run_delayed_extent_op(extent_op, leaf, item);
2146 btrfs_mark_buffer_dirty(leaf);
2147 btrfs_release_path(path);
2149 path->reada = READA_FORWARD;
2150 path->leave_spinning = 1;
2151 /* now insert the actual backref */
2152 ret = insert_extent_backref(trans, fs_info, path, bytenr, parent,
2153 root_objectid, owner, offset, refs_to_add);
2155 btrfs_abort_transaction(trans, ret);
2157 btrfs_free_path(path);
2161 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2162 struct btrfs_fs_info *fs_info,
2163 struct btrfs_delayed_ref_node *node,
2164 struct btrfs_delayed_extent_op *extent_op,
2165 int insert_reserved)
2168 struct btrfs_delayed_data_ref *ref;
2169 struct btrfs_key ins;
2174 ins.objectid = node->bytenr;
2175 ins.offset = node->num_bytes;
2176 ins.type = BTRFS_EXTENT_ITEM_KEY;
2178 ref = btrfs_delayed_node_to_data_ref(node);
2179 trace_run_delayed_data_ref(fs_info, node, ref, node->action);
2181 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2182 parent = ref->parent;
2183 ref_root = ref->root;
2185 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2187 flags |= extent_op->flags_to_set;
2188 ret = alloc_reserved_file_extent(trans, fs_info,
2189 parent, ref_root, flags,
2190 ref->objectid, ref->offset,
2191 &ins, node->ref_mod);
2192 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2193 ret = __btrfs_inc_extent_ref(trans, fs_info, node, parent,
2194 ref_root, ref->objectid,
2195 ref->offset, node->ref_mod,
2197 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2198 ret = __btrfs_free_extent(trans, fs_info, node, parent,
2199 ref_root, ref->objectid,
2200 ref->offset, node->ref_mod,
2208 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2209 struct extent_buffer *leaf,
2210 struct btrfs_extent_item *ei)
2212 u64 flags = btrfs_extent_flags(leaf, ei);
2213 if (extent_op->update_flags) {
2214 flags |= extent_op->flags_to_set;
2215 btrfs_set_extent_flags(leaf, ei, flags);
2218 if (extent_op->update_key) {
2219 struct btrfs_tree_block_info *bi;
2220 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2221 bi = (struct btrfs_tree_block_info *)(ei + 1);
2222 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2226 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2227 struct btrfs_fs_info *fs_info,
2228 struct btrfs_delayed_ref_node *node,
2229 struct btrfs_delayed_extent_op *extent_op)
2231 struct btrfs_key key;
2232 struct btrfs_path *path;
2233 struct btrfs_extent_item *ei;
2234 struct extent_buffer *leaf;
2238 int metadata = !extent_op->is_data;
2243 if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2246 path = btrfs_alloc_path();
2250 key.objectid = node->bytenr;
2253 key.type = BTRFS_METADATA_ITEM_KEY;
2254 key.offset = extent_op->level;
2256 key.type = BTRFS_EXTENT_ITEM_KEY;
2257 key.offset = node->num_bytes;
2261 path->reada = READA_FORWARD;
2262 path->leave_spinning = 1;
2263 ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2270 if (path->slots[0] > 0) {
2272 btrfs_item_key_to_cpu(path->nodes[0], &key,
2274 if (key.objectid == node->bytenr &&
2275 key.type == BTRFS_EXTENT_ITEM_KEY &&
2276 key.offset == node->num_bytes)
2280 btrfs_release_path(path);
2283 key.objectid = node->bytenr;
2284 key.offset = node->num_bytes;
2285 key.type = BTRFS_EXTENT_ITEM_KEY;
2294 leaf = path->nodes[0];
2295 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2296 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2297 if (item_size < sizeof(*ei)) {
2298 ret = convert_extent_item_v0(trans, fs_info, path, (u64)-1, 0);
2303 leaf = path->nodes[0];
2304 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2307 BUG_ON(item_size < sizeof(*ei));
2308 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2309 __run_delayed_extent_op(extent_op, leaf, ei);
2311 btrfs_mark_buffer_dirty(leaf);
2313 btrfs_free_path(path);
2317 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2318 struct btrfs_fs_info *fs_info,
2319 struct btrfs_delayed_ref_node *node,
2320 struct btrfs_delayed_extent_op *extent_op,
2321 int insert_reserved)
2324 struct btrfs_delayed_tree_ref *ref;
2325 struct btrfs_key ins;
2328 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
2330 ref = btrfs_delayed_node_to_tree_ref(node);
2331 trace_run_delayed_tree_ref(fs_info, node, ref, node->action);
2333 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2334 parent = ref->parent;
2335 ref_root = ref->root;
2337 ins.objectid = node->bytenr;
2338 if (skinny_metadata) {
2339 ins.offset = ref->level;
2340 ins.type = BTRFS_METADATA_ITEM_KEY;
2342 ins.offset = node->num_bytes;
2343 ins.type = BTRFS_EXTENT_ITEM_KEY;
2346 if (node->ref_mod != 1) {
2348 "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2349 node->bytenr, node->ref_mod, node->action, ref_root,
2353 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2354 BUG_ON(!extent_op || !extent_op->update_flags);
2355 ret = alloc_reserved_tree_block(trans, fs_info,
2357 extent_op->flags_to_set,
2360 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2361 ret = __btrfs_inc_extent_ref(trans, fs_info, node,
2365 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2366 ret = __btrfs_free_extent(trans, fs_info, node,
2368 ref->level, 0, 1, extent_op);
2375 /* helper function to actually process a single delayed ref entry */
2376 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2377 struct btrfs_fs_info *fs_info,
2378 struct btrfs_delayed_ref_node *node,
2379 struct btrfs_delayed_extent_op *extent_op,
2380 int insert_reserved)
2384 if (trans->aborted) {
2385 if (insert_reserved)
2386 btrfs_pin_extent(fs_info, node->bytenr,
2387 node->num_bytes, 1);
2391 if (btrfs_delayed_ref_is_head(node)) {
2392 struct btrfs_delayed_ref_head *head;
2394 * we've hit the end of the chain and we were supposed
2395 * to insert this extent into the tree. But, it got
2396 * deleted before we ever needed to insert it, so all
2397 * we have to do is clean up the accounting
2400 head = btrfs_delayed_node_to_head(node);
2401 trace_run_delayed_ref_head(fs_info, node, head, node->action);
2403 if (insert_reserved) {
2404 btrfs_pin_extent(fs_info, node->bytenr,
2405 node->num_bytes, 1);
2406 if (head->is_data) {
2407 ret = btrfs_del_csums(trans, fs_info,
2413 /* Also free its reserved qgroup space */
2414 btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
2415 head->qgroup_reserved);
2419 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2420 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2421 ret = run_delayed_tree_ref(trans, fs_info, node, extent_op,
2423 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2424 node->type == BTRFS_SHARED_DATA_REF_KEY)
2425 ret = run_delayed_data_ref(trans, fs_info, node, extent_op,
2432 static inline struct btrfs_delayed_ref_node *
2433 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2435 struct btrfs_delayed_ref_node *ref;
2437 if (list_empty(&head->ref_list))
2441 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2442 * This is to prevent a ref count from going down to zero, which deletes
2443 * the extent item from the extent tree, when there still are references
2444 * to add, which would fail because they would not find the extent item.
2446 if (!list_empty(&head->ref_add_list))
2447 return list_first_entry(&head->ref_add_list,
2448 struct btrfs_delayed_ref_node, add_list);
2450 ref = list_first_entry(&head->ref_list, struct btrfs_delayed_ref_node,
2452 ASSERT(list_empty(&ref->add_list));
2457 * Returns 0 on success or if called with an already aborted transaction.
2458 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2460 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2461 struct btrfs_fs_info *fs_info,
2464 struct btrfs_delayed_ref_root *delayed_refs;
2465 struct btrfs_delayed_ref_node *ref;
2466 struct btrfs_delayed_ref_head *locked_ref = NULL;
2467 struct btrfs_delayed_extent_op *extent_op;
2468 ktime_t start = ktime_get();
2470 unsigned long count = 0;
2471 unsigned long actual_count = 0;
2472 int must_insert_reserved = 0;
2474 delayed_refs = &trans->transaction->delayed_refs;
2480 spin_lock(&delayed_refs->lock);
2481 locked_ref = btrfs_select_ref_head(trans);
2483 spin_unlock(&delayed_refs->lock);
2487 /* grab the lock that says we are going to process
2488 * all the refs for this head */
2489 ret = btrfs_delayed_ref_lock(trans, locked_ref);
2490 spin_unlock(&delayed_refs->lock);
2492 * we may have dropped the spin lock to get the head
2493 * mutex lock, and that might have given someone else
2494 * time to free the head. If that's true, it has been
2495 * removed from our list and we can move on.
2497 if (ret == -EAGAIN) {
2505 * We need to try and merge add/drops of the same ref since we
2506 * can run into issues with relocate dropping the implicit ref
2507 * and then it being added back again before the drop can
2508 * finish. If we merged anything we need to re-loop so we can
2510 * Or we can get node references of the same type that weren't
2511 * merged when created due to bumps in the tree mod seq, and
2512 * we need to merge them to prevent adding an inline extent
2513 * backref before dropping it (triggering a BUG_ON at
2514 * insert_inline_extent_backref()).
2516 spin_lock(&locked_ref->lock);
2517 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2521 * locked_ref is the head node, so we have to go one
2522 * node back for any delayed ref updates
2524 ref = select_delayed_ref(locked_ref);
2526 if (ref && ref->seq &&
2527 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
2528 spin_unlock(&locked_ref->lock);
2529 spin_lock(&delayed_refs->lock);
2530 locked_ref->processing = 0;
2531 delayed_refs->num_heads_ready++;
2532 spin_unlock(&delayed_refs->lock);
2533 btrfs_delayed_ref_unlock(locked_ref);
2541 * record the must insert reserved flag before we
2542 * drop the spin lock.
2544 must_insert_reserved = locked_ref->must_insert_reserved;
2545 locked_ref->must_insert_reserved = 0;
2547 extent_op = locked_ref->extent_op;
2548 locked_ref->extent_op = NULL;
2553 /* All delayed refs have been processed, Go ahead
2554 * and send the head node to run_one_delayed_ref,
2555 * so that any accounting fixes can happen
2557 ref = &locked_ref->node;
2559 if (extent_op && must_insert_reserved) {
2560 btrfs_free_delayed_extent_op(extent_op);
2565 spin_unlock(&locked_ref->lock);
2566 ret = run_delayed_extent_op(trans, fs_info,
2568 btrfs_free_delayed_extent_op(extent_op);
2572 * Need to reset must_insert_reserved if
2573 * there was an error so the abort stuff
2574 * can cleanup the reserved space
2577 if (must_insert_reserved)
2578 locked_ref->must_insert_reserved = 1;
2579 spin_lock(&delayed_refs->lock);
2580 locked_ref->processing = 0;
2581 delayed_refs->num_heads_ready++;
2582 spin_unlock(&delayed_refs->lock);
2583 btrfs_debug(fs_info,
2584 "run_delayed_extent_op returned %d",
2586 btrfs_delayed_ref_unlock(locked_ref);
2593 * Need to drop our head ref lock and re-acquire the
2594 * delayed ref lock and then re-check to make sure
2597 spin_unlock(&locked_ref->lock);
2598 spin_lock(&delayed_refs->lock);
2599 spin_lock(&locked_ref->lock);
2600 if (!list_empty(&locked_ref->ref_list) ||
2601 locked_ref->extent_op) {
2602 spin_unlock(&locked_ref->lock);
2603 spin_unlock(&delayed_refs->lock);
2607 delayed_refs->num_heads--;
2608 rb_erase(&locked_ref->href_node,
2609 &delayed_refs->href_root);
2610 spin_unlock(&delayed_refs->lock);
2614 list_del(&ref->list);
2615 if (!list_empty(&ref->add_list))
2616 list_del(&ref->add_list);
2618 atomic_dec(&delayed_refs->num_entries);
2620 if (!btrfs_delayed_ref_is_head(ref)) {
2622 * when we play the delayed ref, also correct the
2625 switch (ref->action) {
2626 case BTRFS_ADD_DELAYED_REF:
2627 case BTRFS_ADD_DELAYED_EXTENT:
2628 locked_ref->node.ref_mod -= ref->ref_mod;
2630 case BTRFS_DROP_DELAYED_REF:
2631 locked_ref->node.ref_mod += ref->ref_mod;
2637 spin_unlock(&locked_ref->lock);
2639 ret = run_one_delayed_ref(trans, fs_info, ref, extent_op,
2640 must_insert_reserved);
2642 btrfs_free_delayed_extent_op(extent_op);
2644 spin_lock(&delayed_refs->lock);
2645 locked_ref->processing = 0;
2646 delayed_refs->num_heads_ready++;
2647 spin_unlock(&delayed_refs->lock);
2648 btrfs_delayed_ref_unlock(locked_ref);
2649 btrfs_put_delayed_ref(ref);
2650 btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2656 * If this node is a head, that means all the refs in this head
2657 * have been dealt with, and we will pick the next head to deal
2658 * with, so we must unlock the head and drop it from the cluster
2659 * list before we release it.
2661 if (btrfs_delayed_ref_is_head(ref)) {
2662 if (locked_ref->is_data &&
2663 locked_ref->total_ref_mod < 0) {
2664 spin_lock(&delayed_refs->lock);
2665 delayed_refs->pending_csums -= ref->num_bytes;
2666 spin_unlock(&delayed_refs->lock);
2668 btrfs_delayed_ref_unlock(locked_ref);
2671 btrfs_put_delayed_ref(ref);
2677 * We don't want to include ref heads since we can have empty ref heads
2678 * and those will drastically skew our runtime down since we just do
2679 * accounting, no actual extent tree updates.
2681 if (actual_count > 0) {
2682 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2686 * We weigh the current average higher than our current runtime
2687 * to avoid large swings in the average.
2689 spin_lock(&delayed_refs->lock);
2690 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2691 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
2692 spin_unlock(&delayed_refs->lock);
2697 #ifdef SCRAMBLE_DELAYED_REFS
2699 * Normally delayed refs get processed in ascending bytenr order. This
2700 * correlates in most cases to the order added. To expose dependencies on this
2701 * order, we start to process the tree in the middle instead of the beginning
2703 static u64 find_middle(struct rb_root *root)
2705 struct rb_node *n = root->rb_node;
2706 struct btrfs_delayed_ref_node *entry;
2709 u64 first = 0, last = 0;
2713 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2714 first = entry->bytenr;
2718 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2719 last = entry->bytenr;
2724 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2725 WARN_ON(!entry->in_tree);
2727 middle = entry->bytenr;
2740 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2744 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2745 sizeof(struct btrfs_extent_inline_ref));
2746 if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2747 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2750 * We don't ever fill up leaves all the way so multiply by 2 just to be
2751 * closer to what we're really going to want to use.
2753 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2757 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2758 * would require to store the csums for that many bytes.
2760 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2763 u64 num_csums_per_leaf;
2766 csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2767 num_csums_per_leaf = div64_u64(csum_size,
2768 (u64)btrfs_super_csum_size(fs_info->super_copy));
2769 num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2770 num_csums += num_csums_per_leaf - 1;
2771 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2775 int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2776 struct btrfs_fs_info *fs_info)
2778 struct btrfs_block_rsv *global_rsv;
2779 u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2780 u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
2781 u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
2782 u64 num_bytes, num_dirty_bgs_bytes;
2785 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
2786 num_heads = heads_to_leaves(fs_info, num_heads);
2788 num_bytes += (num_heads - 1) * fs_info->nodesize;
2790 num_bytes += btrfs_csum_bytes_to_leaves(fs_info, csum_bytes) *
2792 num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
2794 global_rsv = &fs_info->global_block_rsv;
2797 * If we can't allocate any more chunks lets make sure we have _lots_ of
2798 * wiggle room since running delayed refs can create more delayed refs.
2800 if (global_rsv->space_info->full) {
2801 num_dirty_bgs_bytes <<= 1;
2805 spin_lock(&global_rsv->lock);
2806 if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
2808 spin_unlock(&global_rsv->lock);
2812 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2813 struct btrfs_fs_info *fs_info)
2816 atomic_read(&trans->transaction->delayed_refs.num_entries);
2821 avg_runtime = fs_info->avg_delayed_ref_runtime;
2822 val = num_entries * avg_runtime;
2823 if (val >= NSEC_PER_SEC)
2825 if (val >= NSEC_PER_SEC / 2)
2828 return btrfs_check_space_for_delayed_refs(trans, fs_info);
2831 struct async_delayed_refs {
2832 struct btrfs_root *root;
2837 struct completion wait;
2838 struct btrfs_work work;
2841 static inline struct async_delayed_refs *
2842 to_async_delayed_refs(struct btrfs_work *work)
2844 return container_of(work, struct async_delayed_refs, work);
2847 static void delayed_ref_async_start(struct btrfs_work *work)
2849 struct async_delayed_refs *async = to_async_delayed_refs(work);
2850 struct btrfs_trans_handle *trans;
2851 struct btrfs_fs_info *fs_info = async->root->fs_info;
2854 /* if the commit is already started, we don't need to wait here */
2855 if (btrfs_transaction_blocked(fs_info))
2858 trans = btrfs_join_transaction(async->root);
2859 if (IS_ERR(trans)) {
2860 async->error = PTR_ERR(trans);
2865 * trans->sync means that when we call end_transaction, we won't
2866 * wait on delayed refs
2870 /* Don't bother flushing if we got into a different transaction */
2871 if (trans->transid > async->transid)
2874 ret = btrfs_run_delayed_refs(trans, fs_info, async->count);
2878 ret = btrfs_end_transaction(trans);
2879 if (ret && !async->error)
2883 complete(&async->wait);
2888 int btrfs_async_run_delayed_refs(struct btrfs_fs_info *fs_info,
2889 unsigned long count, u64 transid, int wait)
2891 struct async_delayed_refs *async;
2894 async = kmalloc(sizeof(*async), GFP_NOFS);
2898 async->root = fs_info->tree_root;
2899 async->count = count;
2901 async->transid = transid;
2906 init_completion(&async->wait);
2908 btrfs_init_work(&async->work, btrfs_extent_refs_helper,
2909 delayed_ref_async_start, NULL, NULL);
2911 btrfs_queue_work(fs_info->extent_workers, &async->work);
2914 wait_for_completion(&async->wait);
2923 * this starts processing the delayed reference count updates and
2924 * extent insertions we have queued up so far. count can be
2925 * 0, which means to process everything in the tree at the start
2926 * of the run (but not newly added entries), or it can be some target
2927 * number you'd like to process.
2929 * Returns 0 on success or if called with an aborted transaction
2930 * Returns <0 on error and aborts the transaction
2932 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2933 struct btrfs_fs_info *fs_info, unsigned long count)
2935 struct rb_node *node;
2936 struct btrfs_delayed_ref_root *delayed_refs;
2937 struct btrfs_delayed_ref_head *head;
2939 int run_all = count == (unsigned long)-1;
2940 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
2942 /* We'll clean this up in btrfs_cleanup_transaction */
2946 if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2949 delayed_refs = &trans->transaction->delayed_refs;
2951 count = atomic_read(&delayed_refs->num_entries) * 2;
2954 #ifdef SCRAMBLE_DELAYED_REFS
2955 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2957 trans->can_flush_pending_bgs = false;
2958 ret = __btrfs_run_delayed_refs(trans, fs_info, count);
2960 btrfs_abort_transaction(trans, ret);
2965 if (!list_empty(&trans->new_bgs))
2966 btrfs_create_pending_block_groups(trans, fs_info);
2968 spin_lock(&delayed_refs->lock);
2969 node = rb_first(&delayed_refs->href_root);
2971 spin_unlock(&delayed_refs->lock);
2976 head = rb_entry(node, struct btrfs_delayed_ref_head,
2978 if (btrfs_delayed_ref_is_head(&head->node)) {
2979 struct btrfs_delayed_ref_node *ref;
2982 atomic_inc(&ref->refs);
2984 spin_unlock(&delayed_refs->lock);
2986 * Mutex was contended, block until it's
2987 * released and try again
2989 mutex_lock(&head->mutex);
2990 mutex_unlock(&head->mutex);
2992 btrfs_put_delayed_ref(ref);
2998 node = rb_next(node);
3000 spin_unlock(&delayed_refs->lock);
3005 assert_qgroups_uptodate(trans);
3006 trans->can_flush_pending_bgs = can_flush_pending_bgs;
3010 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
3011 struct btrfs_fs_info *fs_info,
3012 u64 bytenr, u64 num_bytes, u64 flags,
3013 int level, int is_data)
3015 struct btrfs_delayed_extent_op *extent_op;
3018 extent_op = btrfs_alloc_delayed_extent_op();
3022 extent_op->flags_to_set = flags;
3023 extent_op->update_flags = true;
3024 extent_op->update_key = false;
3025 extent_op->is_data = is_data ? true : false;
3026 extent_op->level = level;
3028 ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
3029 num_bytes, extent_op);
3031 btrfs_free_delayed_extent_op(extent_op);
3035 static noinline int check_delayed_ref(struct btrfs_root *root,
3036 struct btrfs_path *path,
3037 u64 objectid, u64 offset, u64 bytenr)
3039 struct btrfs_delayed_ref_head *head;
3040 struct btrfs_delayed_ref_node *ref;
3041 struct btrfs_delayed_data_ref *data_ref;
3042 struct btrfs_delayed_ref_root *delayed_refs;
3043 struct btrfs_transaction *cur_trans;
3046 cur_trans = root->fs_info->running_transaction;
3050 delayed_refs = &cur_trans->delayed_refs;
3051 spin_lock(&delayed_refs->lock);
3052 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3054 spin_unlock(&delayed_refs->lock);
3058 if (!mutex_trylock(&head->mutex)) {
3059 atomic_inc(&head->node.refs);
3060 spin_unlock(&delayed_refs->lock);
3062 btrfs_release_path(path);
3065 * Mutex was contended, block until it's released and let
3068 mutex_lock(&head->mutex);
3069 mutex_unlock(&head->mutex);
3070 btrfs_put_delayed_ref(&head->node);
3073 spin_unlock(&delayed_refs->lock);
3075 spin_lock(&head->lock);
3076 list_for_each_entry(ref, &head->ref_list, list) {
3077 /* If it's a shared ref we know a cross reference exists */
3078 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3083 data_ref = btrfs_delayed_node_to_data_ref(ref);
3086 * If our ref doesn't match the one we're currently looking at
3087 * then we have a cross reference.
3089 if (data_ref->root != root->root_key.objectid ||
3090 data_ref->objectid != objectid ||
3091 data_ref->offset != offset) {
3096 spin_unlock(&head->lock);
3097 mutex_unlock(&head->mutex);
3101 static noinline int check_committed_ref(struct btrfs_root *root,
3102 struct btrfs_path *path,
3103 u64 objectid, u64 offset, u64 bytenr)
3105 struct btrfs_fs_info *fs_info = root->fs_info;
3106 struct btrfs_root *extent_root = fs_info->extent_root;
3107 struct extent_buffer *leaf;
3108 struct btrfs_extent_data_ref *ref;
3109 struct btrfs_extent_inline_ref *iref;
3110 struct btrfs_extent_item *ei;
3111 struct btrfs_key key;
3115 key.objectid = bytenr;
3116 key.offset = (u64)-1;
3117 key.type = BTRFS_EXTENT_ITEM_KEY;
3119 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3122 BUG_ON(ret == 0); /* Corruption */
3125 if (path->slots[0] == 0)
3129 leaf = path->nodes[0];
3130 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3132 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3136 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3137 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3138 if (item_size < sizeof(*ei)) {
3139 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
3143 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3145 if (item_size != sizeof(*ei) +
3146 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3149 if (btrfs_extent_generation(leaf, ei) <=
3150 btrfs_root_last_snapshot(&root->root_item))
3153 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3154 if (btrfs_extent_inline_ref_type(leaf, iref) !=
3155 BTRFS_EXTENT_DATA_REF_KEY)
3158 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3159 if (btrfs_extent_refs(leaf, ei) !=
3160 btrfs_extent_data_ref_count(leaf, ref) ||
3161 btrfs_extent_data_ref_root(leaf, ref) !=
3162 root->root_key.objectid ||
3163 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3164 btrfs_extent_data_ref_offset(leaf, ref) != offset)
3172 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3175 struct btrfs_path *path;
3179 path = btrfs_alloc_path();
3184 ret = check_committed_ref(root, path, objectid,
3186 if (ret && ret != -ENOENT)
3189 ret2 = check_delayed_ref(root, path, objectid,
3191 } while (ret2 == -EAGAIN);
3193 if (ret2 && ret2 != -ENOENT) {
3198 if (ret != -ENOENT || ret2 != -ENOENT)
3201 btrfs_free_path(path);
3202 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3207 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3208 struct btrfs_root *root,
3209 struct extent_buffer *buf,
3210 int full_backref, int inc)
3212 struct btrfs_fs_info *fs_info = root->fs_info;
3218 struct btrfs_key key;
3219 struct btrfs_file_extent_item *fi;
3223 int (*process_func)(struct btrfs_trans_handle *,
3224 struct btrfs_fs_info *,
3225 u64, u64, u64, u64, u64, u64);
3228 if (btrfs_is_testing(fs_info))
3231 ref_root = btrfs_header_owner(buf);
3232 nritems = btrfs_header_nritems(buf);
3233 level = btrfs_header_level(buf);
3235 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3239 process_func = btrfs_inc_extent_ref;
3241 process_func = btrfs_free_extent;
3244 parent = buf->start;
3248 for (i = 0; i < nritems; i++) {
3250 btrfs_item_key_to_cpu(buf, &key, i);
3251 if (key.type != BTRFS_EXTENT_DATA_KEY)
3253 fi = btrfs_item_ptr(buf, i,
3254 struct btrfs_file_extent_item);
3255 if (btrfs_file_extent_type(buf, fi) ==
3256 BTRFS_FILE_EXTENT_INLINE)
3258 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3262 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3263 key.offset -= btrfs_file_extent_offset(buf, fi);
3264 ret = process_func(trans, fs_info, bytenr, num_bytes,
3265 parent, ref_root, key.objectid,
3270 bytenr = btrfs_node_blockptr(buf, i);
3271 num_bytes = fs_info->nodesize;
3272 ret = process_func(trans, fs_info, bytenr, num_bytes,
3273 parent, ref_root, level - 1, 0);
3283 int btrfs_inc_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, 1);
3289 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3290 struct extent_buffer *buf, int full_backref)
3292 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3295 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3296 struct btrfs_fs_info *fs_info,
3297 struct btrfs_path *path,
3298 struct btrfs_block_group_cache *cache)
3301 struct btrfs_root *extent_root = fs_info->extent_root;
3303 struct extent_buffer *leaf;
3305 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3312 leaf = path->nodes[0];
3313 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3314 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3315 btrfs_mark_buffer_dirty(leaf);
3317 btrfs_release_path(path);
3322 static struct btrfs_block_group_cache *
3323 next_block_group(struct btrfs_fs_info *fs_info,
3324 struct btrfs_block_group_cache *cache)
3326 struct rb_node *node;
3328 spin_lock(&fs_info->block_group_cache_lock);
3330 /* If our block group was removed, we need a full search. */
3331 if (RB_EMPTY_NODE(&cache->cache_node)) {
3332 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3334 spin_unlock(&fs_info->block_group_cache_lock);
3335 btrfs_put_block_group(cache);
3336 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3338 node = rb_next(&cache->cache_node);
3339 btrfs_put_block_group(cache);
3341 cache = rb_entry(node, struct btrfs_block_group_cache,
3343 btrfs_get_block_group(cache);
3346 spin_unlock(&fs_info->block_group_cache_lock);
3350 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3351 struct btrfs_trans_handle *trans,
3352 struct btrfs_path *path)
3354 struct btrfs_fs_info *fs_info = block_group->fs_info;
3355 struct btrfs_root *root = fs_info->tree_root;
3356 struct inode *inode = NULL;
3358 int dcs = BTRFS_DC_ERROR;
3364 * If this block group is smaller than 100 megs don't bother caching the
3367 if (block_group->key.offset < (100 * SZ_1M)) {
3368 spin_lock(&block_group->lock);
3369 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3370 spin_unlock(&block_group->lock);
3377 inode = lookup_free_space_inode(fs_info, block_group, path);
3378 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3379 ret = PTR_ERR(inode);
3380 btrfs_release_path(path);
3384 if (IS_ERR(inode)) {
3388 if (block_group->ro)
3391 ret = create_free_space_inode(fs_info, trans, block_group,
3398 /* We've already setup this transaction, go ahead and exit */
3399 if (block_group->cache_generation == trans->transid &&
3400 i_size_read(inode)) {
3401 dcs = BTRFS_DC_SETUP;
3406 * We want to set the generation to 0, that way if anything goes wrong
3407 * from here on out we know not to trust this cache when we load up next
3410 BTRFS_I(inode)->generation = 0;
3411 ret = btrfs_update_inode(trans, root, inode);
3414 * So theoretically we could recover from this, simply set the
3415 * super cache generation to 0 so we know to invalidate the
3416 * cache, but then we'd have to keep track of the block groups
3417 * that fail this way so we know we _have_ to reset this cache
3418 * before the next commit or risk reading stale cache. So to
3419 * limit our exposure to horrible edge cases lets just abort the
3420 * transaction, this only happens in really bad situations
3423 btrfs_abort_transaction(trans, ret);
3428 if (i_size_read(inode) > 0) {
3429 ret = btrfs_check_trunc_cache_free_space(fs_info,
3430 &fs_info->global_block_rsv);
3434 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3439 spin_lock(&block_group->lock);
3440 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3441 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3443 * don't bother trying to write stuff out _if_
3444 * a) we're not cached,
3445 * b) we're with nospace_cache mount option.
3447 dcs = BTRFS_DC_WRITTEN;
3448 spin_unlock(&block_group->lock);
3451 spin_unlock(&block_group->lock);
3454 * We hit an ENOSPC when setting up the cache in this transaction, just
3455 * skip doing the setup, we've already cleared the cache so we're safe.
3457 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3463 * Try to preallocate enough space based on how big the block group is.
3464 * Keep in mind this has to include any pinned space which could end up
3465 * taking up quite a bit since it's not folded into the other space
3468 num_pages = div_u64(block_group->key.offset, SZ_256M);
3473 num_pages *= PAGE_SIZE;
3475 ret = btrfs_check_data_free_space(inode, 0, num_pages);
3479 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3480 num_pages, num_pages,
3483 * Our cache requires contiguous chunks so that we don't modify a bunch
3484 * of metadata or split extents when writing the cache out, which means
3485 * we can enospc if we are heavily fragmented in addition to just normal
3486 * out of space conditions. So if we hit this just skip setting up any
3487 * other block groups for this transaction, maybe we'll unpin enough
3488 * space the next time around.
3491 dcs = BTRFS_DC_SETUP;
3492 else if (ret == -ENOSPC)
3493 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3498 btrfs_release_path(path);
3500 spin_lock(&block_group->lock);
3501 if (!ret && dcs == BTRFS_DC_SETUP)
3502 block_group->cache_generation = trans->transid;
3503 block_group->disk_cache_state = dcs;
3504 spin_unlock(&block_group->lock);
3509 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
3510 struct btrfs_fs_info *fs_info)
3512 struct btrfs_block_group_cache *cache, *tmp;
3513 struct btrfs_transaction *cur_trans = trans->transaction;
3514 struct btrfs_path *path;
3516 if (list_empty(&cur_trans->dirty_bgs) ||
3517 !btrfs_test_opt(fs_info, SPACE_CACHE))
3520 path = btrfs_alloc_path();
3524 /* Could add new block groups, use _safe just in case */
3525 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3527 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3528 cache_save_setup(cache, trans, path);
3531 btrfs_free_path(path);
3536 * transaction commit does final block group cache writeback during a
3537 * critical section where nothing is allowed to change the FS. This is
3538 * required in order for the cache to actually match the block group,
3539 * but can introduce a lot of latency into the commit.
3541 * So, btrfs_start_dirty_block_groups is here to kick off block group
3542 * cache IO. There's a chance we'll have to redo some of it if the
3543 * block group changes again during the commit, but it greatly reduces
3544 * the commit latency by getting rid of the easy block groups while
3545 * we're still allowing others to join the commit.
3547 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
3548 struct btrfs_fs_info *fs_info)
3550 struct btrfs_block_group_cache *cache;
3551 struct btrfs_transaction *cur_trans = trans->transaction;
3554 struct btrfs_path *path = NULL;
3556 struct list_head *io = &cur_trans->io_bgs;
3557 int num_started = 0;
3560 spin_lock(&cur_trans->dirty_bgs_lock);
3561 if (list_empty(&cur_trans->dirty_bgs)) {
3562 spin_unlock(&cur_trans->dirty_bgs_lock);
3565 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3566 spin_unlock(&cur_trans->dirty_bgs_lock);
3570 * make sure all the block groups on our dirty list actually
3573 btrfs_create_pending_block_groups(trans, fs_info);
3576 path = btrfs_alloc_path();
3582 * cache_write_mutex is here only to save us from balance or automatic
3583 * removal of empty block groups deleting this block group while we are
3584 * writing out the cache
3586 mutex_lock(&trans->transaction->cache_write_mutex);
3587 while (!list_empty(&dirty)) {
3588 cache = list_first_entry(&dirty,
3589 struct btrfs_block_group_cache,
3592 * this can happen if something re-dirties a block
3593 * group that is already under IO. Just wait for it to
3594 * finish and then do it all again
3596 if (!list_empty(&cache->io_list)) {
3597 list_del_init(&cache->io_list);
3598 btrfs_wait_cache_io(trans, cache, path);
3599 btrfs_put_block_group(cache);
3604 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3605 * if it should update the cache_state. Don't delete
3606 * until after we wait.
3608 * Since we're not running in the commit critical section
3609 * we need the dirty_bgs_lock to protect from update_block_group
3611 spin_lock(&cur_trans->dirty_bgs_lock);
3612 list_del_init(&cache->dirty_list);
3613 spin_unlock(&cur_trans->dirty_bgs_lock);
3617 cache_save_setup(cache, trans, path);
3619 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3620 cache->io_ctl.inode = NULL;
3621 ret = btrfs_write_out_cache(fs_info, trans,
3623 if (ret == 0 && cache->io_ctl.inode) {
3628 * the cache_write_mutex is protecting
3631 list_add_tail(&cache->io_list, io);
3634 * if we failed to write the cache, the
3635 * generation will be bad and life goes on
3641 ret = write_one_cache_group(trans, fs_info,
3644 * Our block group might still be attached to the list
3645 * of new block groups in the transaction handle of some
3646 * other task (struct btrfs_trans_handle->new_bgs). This
3647 * means its block group item isn't yet in the extent
3648 * tree. If this happens ignore the error, as we will
3649 * try again later in the critical section of the
3650 * transaction commit.
3652 if (ret == -ENOENT) {
3654 spin_lock(&cur_trans->dirty_bgs_lock);
3655 if (list_empty(&cache->dirty_list)) {
3656 list_add_tail(&cache->dirty_list,
3657 &cur_trans->dirty_bgs);
3658 btrfs_get_block_group(cache);
3660 spin_unlock(&cur_trans->dirty_bgs_lock);
3662 btrfs_abort_transaction(trans, ret);
3666 /* if its not on the io list, we need to put the block group */
3668 btrfs_put_block_group(cache);
3674 * Avoid blocking other tasks for too long. It might even save
3675 * us from writing caches for block groups that are going to be
3678 mutex_unlock(&trans->transaction->cache_write_mutex);
3679 mutex_lock(&trans->transaction->cache_write_mutex);
3681 mutex_unlock(&trans->transaction->cache_write_mutex);
3684 * go through delayed refs for all the stuff we've just kicked off
3685 * and then loop back (just once)
3687 ret = btrfs_run_delayed_refs(trans, fs_info, 0);
3688 if (!ret && loops == 0) {
3690 spin_lock(&cur_trans->dirty_bgs_lock);
3691 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3693 * dirty_bgs_lock protects us from concurrent block group
3694 * deletes too (not just cache_write_mutex).
3696 if (!list_empty(&dirty)) {
3697 spin_unlock(&cur_trans->dirty_bgs_lock);
3700 spin_unlock(&cur_trans->dirty_bgs_lock);
3701 } else if (ret < 0) {
3702 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3705 btrfs_free_path(path);
3709 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3710 struct btrfs_fs_info *fs_info)
3712 struct btrfs_block_group_cache *cache;
3713 struct btrfs_transaction *cur_trans = trans->transaction;
3716 struct btrfs_path *path;
3717 struct list_head *io = &cur_trans->io_bgs;
3718 int num_started = 0;
3720 path = btrfs_alloc_path();
3725 * Even though we are in the critical section of the transaction commit,
3726 * we can still have concurrent tasks adding elements to this
3727 * transaction's list of dirty block groups. These tasks correspond to
3728 * endio free space workers started when writeback finishes for a
3729 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3730 * allocate new block groups as a result of COWing nodes of the root
3731 * tree when updating the free space inode. The writeback for the space
3732 * caches is triggered by an earlier call to
3733 * btrfs_start_dirty_block_groups() and iterations of the following
3735 * Also we want to do the cache_save_setup first and then run the
3736 * delayed refs to make sure we have the best chance at doing this all
3739 spin_lock(&cur_trans->dirty_bgs_lock);
3740 while (!list_empty(&cur_trans->dirty_bgs)) {
3741 cache = list_first_entry(&cur_trans->dirty_bgs,
3742 struct btrfs_block_group_cache,
3746 * this can happen if cache_save_setup re-dirties a block
3747 * group that is already under IO. Just wait for it to
3748 * finish and then do it all again
3750 if (!list_empty(&cache->io_list)) {
3751 spin_unlock(&cur_trans->dirty_bgs_lock);
3752 list_del_init(&cache->io_list);
3753 btrfs_wait_cache_io(trans, cache, path);
3754 btrfs_put_block_group(cache);
3755 spin_lock(&cur_trans->dirty_bgs_lock);
3759 * don't remove from the dirty list until after we've waited
3762 list_del_init(&cache->dirty_list);
3763 spin_unlock(&cur_trans->dirty_bgs_lock);
3766 cache_save_setup(cache, trans, path);
3769 ret = btrfs_run_delayed_refs(trans, fs_info,
3770 (unsigned long) -1);
3772 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3773 cache->io_ctl.inode = NULL;
3774 ret = btrfs_write_out_cache(fs_info, trans,
3776 if (ret == 0 && cache->io_ctl.inode) {
3779 list_add_tail(&cache->io_list, io);
3782 * if we failed to write the cache, the
3783 * generation will be bad and life goes on
3789 ret = write_one_cache_group(trans, fs_info,
3792 * One of the free space endio workers might have
3793 * created a new block group while updating a free space
3794 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3795 * and hasn't released its transaction handle yet, in
3796 * which case the new block group is still attached to
3797 * its transaction handle and its creation has not
3798 * finished yet (no block group item in the extent tree
3799 * yet, etc). If this is the case, wait for all free
3800 * space endio workers to finish and retry. This is a
3801 * a very rare case so no need for a more efficient and
3804 if (ret == -ENOENT) {
3805 wait_event(cur_trans->writer_wait,
3806 atomic_read(&cur_trans->num_writers) == 1);
3807 ret = write_one_cache_group(trans, fs_info,
3811 btrfs_abort_transaction(trans, ret);
3814 /* if its not on the io list, we need to put the block group */
3816 btrfs_put_block_group(cache);
3817 spin_lock(&cur_trans->dirty_bgs_lock);
3819 spin_unlock(&cur_trans->dirty_bgs_lock);
3821 while (!list_empty(io)) {
3822 cache = list_first_entry(io, struct btrfs_block_group_cache,
3824 list_del_init(&cache->io_list);
3825 btrfs_wait_cache_io(trans, cache, path);
3826 btrfs_put_block_group(cache);
3829 btrfs_free_path(path);
3833 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3835 struct btrfs_block_group_cache *block_group;
3838 block_group = btrfs_lookup_block_group(fs_info, bytenr);
3839 if (!block_group || block_group->ro)
3842 btrfs_put_block_group(block_group);
3846 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3848 struct btrfs_block_group_cache *bg;
3851 bg = btrfs_lookup_block_group(fs_info, bytenr);
3855 spin_lock(&bg->lock);
3859 atomic_inc(&bg->nocow_writers);
3860 spin_unlock(&bg->lock);
3862 /* no put on block group, done by btrfs_dec_nocow_writers */
3864 btrfs_put_block_group(bg);
3870 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3872 struct btrfs_block_group_cache *bg;
3874 bg = btrfs_lookup_block_group(fs_info, bytenr);
3876 if (atomic_dec_and_test(&bg->nocow_writers))
3877 wake_up_atomic_t(&bg->nocow_writers);
3879 * Once for our lookup and once for the lookup done by a previous call
3880 * to btrfs_inc_nocow_writers()
3882 btrfs_put_block_group(bg);
3883 btrfs_put_block_group(bg);
3886 static int btrfs_wait_nocow_writers_atomic_t(atomic_t *a)
3892 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3894 wait_on_atomic_t(&bg->nocow_writers,
3895 btrfs_wait_nocow_writers_atomic_t,
3896 TASK_UNINTERRUPTIBLE);
3899 static const char *alloc_name(u64 flags)
3902 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3904 case BTRFS_BLOCK_GROUP_METADATA:
3906 case BTRFS_BLOCK_GROUP_DATA:
3908 case BTRFS_BLOCK_GROUP_SYSTEM:
3912 return "invalid-combination";
3916 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3917 u64 total_bytes, u64 bytes_used,
3919 struct btrfs_space_info **space_info)
3921 struct btrfs_space_info *found;
3926 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3927 BTRFS_BLOCK_GROUP_RAID10))
3932 found = __find_space_info(info, flags);
3934 spin_lock(&found->lock);
3935 found->total_bytes += total_bytes;
3936 found->disk_total += total_bytes * factor;
3937 found->bytes_used += bytes_used;
3938 found->disk_used += bytes_used * factor;
3939 found->bytes_readonly += bytes_readonly;
3940 if (total_bytes > 0)
3942 space_info_add_new_bytes(info, found, total_bytes -
3943 bytes_used - bytes_readonly);
3944 spin_unlock(&found->lock);
3945 *space_info = found;
3948 found = kzalloc(sizeof(*found), GFP_NOFS);
3952 ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
3958 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3959 INIT_LIST_HEAD(&found->block_groups[i]);
3960 init_rwsem(&found->groups_sem);
3961 spin_lock_init(&found->lock);
3962 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3963 found->total_bytes = total_bytes;
3964 found->disk_total = total_bytes * factor;
3965 found->bytes_used = bytes_used;
3966 found->disk_used = bytes_used * factor;
3967 found->bytes_pinned = 0;
3968 found->bytes_reserved = 0;
3969 found->bytes_readonly = bytes_readonly;
3970 found->bytes_may_use = 0;
3972 found->max_extent_size = 0;
3973 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3974 found->chunk_alloc = 0;
3976 init_waitqueue_head(&found->wait);
3977 INIT_LIST_HEAD(&found->ro_bgs);
3978 INIT_LIST_HEAD(&found->tickets);
3979 INIT_LIST_HEAD(&found->priority_tickets);
3981 ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
3982 info->space_info_kobj, "%s",
3983 alloc_name(found->flags));
3989 *space_info = found;
3990 list_add_rcu(&found->list, &info->space_info);
3991 if (flags & BTRFS_BLOCK_GROUP_DATA)
3992 info->data_sinfo = found;
3997 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3999 u64 extra_flags = chunk_to_extended(flags) &
4000 BTRFS_EXTENDED_PROFILE_MASK;
4002 write_seqlock(&fs_info->profiles_lock);
4003 if (flags & BTRFS_BLOCK_GROUP_DATA)
4004 fs_info->avail_data_alloc_bits |= extra_flags;
4005 if (flags & BTRFS_BLOCK_GROUP_METADATA)
4006 fs_info->avail_metadata_alloc_bits |= extra_flags;
4007 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4008 fs_info->avail_system_alloc_bits |= extra_flags;
4009 write_sequnlock(&fs_info->profiles_lock);
4013 * returns target flags in extended format or 0 if restripe for this
4014 * chunk_type is not in progress
4016 * should be called with either volume_mutex or balance_lock held
4018 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
4020 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4026 if (flags & BTRFS_BLOCK_GROUP_DATA &&
4027 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4028 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
4029 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
4030 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4031 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
4032 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
4033 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4034 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
4041 * @flags: available profiles in extended format (see ctree.h)
4043 * Returns reduced profile in chunk format. If profile changing is in
4044 * progress (either running or paused) picks the target profile (if it's
4045 * already available), otherwise falls back to plain reducing.
4047 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
4049 u64 num_devices = fs_info->fs_devices->rw_devices;
4055 * see if restripe for this chunk_type is in progress, if so
4056 * try to reduce to the target profile
4058 spin_lock(&fs_info->balance_lock);
4059 target = get_restripe_target(fs_info, flags);
4061 /* pick target profile only if it's already available */
4062 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
4063 spin_unlock(&fs_info->balance_lock);
4064 return extended_to_chunk(target);
4067 spin_unlock(&fs_info->balance_lock);
4069 /* First, mask out the RAID levels which aren't possible */
4070 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4071 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
4072 allowed |= btrfs_raid_group[raid_type];
4076 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
4077 allowed = BTRFS_BLOCK_GROUP_RAID6;
4078 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
4079 allowed = BTRFS_BLOCK_GROUP_RAID5;
4080 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
4081 allowed = BTRFS_BLOCK_GROUP_RAID10;
4082 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
4083 allowed = BTRFS_BLOCK_GROUP_RAID1;
4084 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
4085 allowed = BTRFS_BLOCK_GROUP_RAID0;
4087 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4089 return extended_to_chunk(flags | allowed);
4092 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
4099 seq = read_seqbegin(&fs_info->profiles_lock);
4101 if (flags & BTRFS_BLOCK_GROUP_DATA)
4102 flags |= fs_info->avail_data_alloc_bits;
4103 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4104 flags |= fs_info->avail_system_alloc_bits;
4105 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
4106 flags |= fs_info->avail_metadata_alloc_bits;
4107 } while (read_seqretry(&fs_info->profiles_lock, seq));
4109 return btrfs_reduce_alloc_profile(fs_info, flags);
4112 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
4114 struct btrfs_fs_info *fs_info = root->fs_info;
4119 flags = BTRFS_BLOCK_GROUP_DATA;
4120 else if (root == fs_info->chunk_root)
4121 flags = BTRFS_BLOCK_GROUP_SYSTEM;
4123 flags = BTRFS_BLOCK_GROUP_METADATA;
4125 ret = get_alloc_profile(fs_info, flags);
4129 static u64 btrfs_space_info_used(struct btrfs_space_info *s_info,
4130 bool may_use_included)
4133 return s_info->bytes_used + s_info->bytes_reserved +
4134 s_info->bytes_pinned + s_info->bytes_readonly +
4135 (may_use_included ? s_info->bytes_may_use : 0);
4138 int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
4140 struct btrfs_space_info *data_sinfo;
4141 struct btrfs_root *root = inode->root;
4142 struct btrfs_fs_info *fs_info = root->fs_info;
4145 int need_commit = 2;
4146 int have_pinned_space;
4148 /* make sure bytes are sectorsize aligned */
4149 bytes = ALIGN(bytes, fs_info->sectorsize);
4151 if (btrfs_is_free_space_inode(inode)) {
4153 ASSERT(current->journal_info);
4156 data_sinfo = fs_info->data_sinfo;
4161 /* make sure we have enough space to handle the data first */
4162 spin_lock(&data_sinfo->lock);
4163 used = btrfs_space_info_used(data_sinfo, true);
4165 if (used + bytes > data_sinfo->total_bytes) {
4166 struct btrfs_trans_handle *trans;
4169 * if we don't have enough free bytes in this space then we need
4170 * to alloc a new chunk.
4172 if (!data_sinfo->full) {
4175 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4176 spin_unlock(&data_sinfo->lock);
4178 alloc_target = btrfs_get_alloc_profile(root, 1);
4180 * It is ugly that we don't call nolock join
4181 * transaction for the free space inode case here.
4182 * But it is safe because we only do the data space
4183 * reservation for the free space cache in the
4184 * transaction context, the common join transaction
4185 * just increase the counter of the current transaction
4186 * handler, doesn't try to acquire the trans_lock of
4189 trans = btrfs_join_transaction(root);
4191 return PTR_ERR(trans);
4193 ret = do_chunk_alloc(trans, fs_info, alloc_target,
4194 CHUNK_ALLOC_NO_FORCE);
4195 btrfs_end_transaction(trans);
4200 have_pinned_space = 1;
4206 data_sinfo = fs_info->data_sinfo;
4212 * If we don't have enough pinned space to deal with this
4213 * allocation, and no removed chunk in current transaction,
4214 * don't bother committing the transaction.
4216 have_pinned_space = percpu_counter_compare(
4217 &data_sinfo->total_bytes_pinned,
4218 used + bytes - data_sinfo->total_bytes);
4219 spin_unlock(&data_sinfo->lock);
4221 /* commit the current transaction and try again */
4224 !atomic_read(&fs_info->open_ioctl_trans)) {
4227 if (need_commit > 0) {
4228 btrfs_start_delalloc_roots(fs_info, 0, -1);
4229 btrfs_wait_ordered_roots(fs_info, -1, 0,
4233 trans = btrfs_join_transaction(root);
4235 return PTR_ERR(trans);
4236 if (have_pinned_space >= 0 ||
4237 test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4238 &trans->transaction->flags) ||
4240 ret = btrfs_commit_transaction(trans);
4244 * The cleaner kthread might still be doing iput
4245 * operations. Wait for it to finish so that
4246 * more space is released.
4248 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
4249 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
4252 btrfs_end_transaction(trans);
4256 trace_btrfs_space_reservation(fs_info,
4257 "space_info:enospc",
4258 data_sinfo->flags, bytes, 1);
4261 data_sinfo->bytes_may_use += bytes;
4262 trace_btrfs_space_reservation(fs_info, "space_info",
4263 data_sinfo->flags, bytes, 1);
4264 spin_unlock(&data_sinfo->lock);
4270 * New check_data_free_space() with ability for precious data reservation
4271 * Will replace old btrfs_check_data_free_space(), but for patch split,
4272 * add a new function first and then replace it.
4274 int btrfs_check_data_free_space(struct inode *inode, u64 start, u64 len)
4276 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4279 /* align the range */
4280 len = round_up(start + len, fs_info->sectorsize) -
4281 round_down(start, fs_info->sectorsize);
4282 start = round_down(start, fs_info->sectorsize);
4284 ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
4288 /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4289 ret = btrfs_qgroup_reserve_data(inode, start, len);
4291 btrfs_free_reserved_data_space_noquota(inode, start, len);
4296 * Called if we need to clear a data reservation for this inode
4297 * Normally in a error case.
4299 * This one will *NOT* use accurate qgroup reserved space API, just for case
4300 * which we can't sleep and is sure it won't affect qgroup reserved space.
4301 * Like clear_bit_hook().
4303 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4306 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4307 struct btrfs_space_info *data_sinfo;
4309 /* Make sure the range is aligned to sectorsize */
4310 len = round_up(start + len, fs_info->sectorsize) -
4311 round_down(start, fs_info->sectorsize);
4312 start = round_down(start, fs_info->sectorsize);
4314 data_sinfo = fs_info->data_sinfo;
4315 spin_lock(&data_sinfo->lock);
4316 if (WARN_ON(data_sinfo->bytes_may_use < len))
4317 data_sinfo->bytes_may_use = 0;
4319 data_sinfo->bytes_may_use -= len;
4320 trace_btrfs_space_reservation(fs_info, "space_info",
4321 data_sinfo->flags, len, 0);
4322 spin_unlock(&data_sinfo->lock);
4326 * Called if we need to clear a data reservation for this inode
4327 * Normally in a error case.
4329 * This one will handle the per-inode data rsv map for accurate reserved
4332 void btrfs_free_reserved_data_space(struct inode *inode, u64 start, u64 len)
4334 struct btrfs_root *root = BTRFS_I(inode)->root;
4336 /* Make sure the range is aligned to sectorsize */
4337 len = round_up(start + len, root->fs_info->sectorsize) -
4338 round_down(start, root->fs_info->sectorsize);
4339 start = round_down(start, root->fs_info->sectorsize);
4341 btrfs_free_reserved_data_space_noquota(inode, start, len);
4342 btrfs_qgroup_free_data(inode, start, len);
4345 static void force_metadata_allocation(struct btrfs_fs_info *info)
4347 struct list_head *head = &info->space_info;
4348 struct btrfs_space_info *found;
4351 list_for_each_entry_rcu(found, head, list) {
4352 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4353 found->force_alloc = CHUNK_ALLOC_FORCE;
4358 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4360 return (global->size << 1);
4363 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4364 struct btrfs_space_info *sinfo, int force)
4366 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4367 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
4368 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
4371 if (force == CHUNK_ALLOC_FORCE)
4375 * We need to take into account the global rsv because for all intents
4376 * and purposes it's used space. Don't worry about locking the
4377 * global_rsv, it doesn't change except when the transaction commits.
4379 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
4380 num_allocated += calc_global_rsv_need_space(global_rsv);
4383 * in limited mode, we want to have some free space up to
4384 * about 1% of the FS size.
4386 if (force == CHUNK_ALLOC_LIMITED) {
4387 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4388 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4390 if (num_bytes - num_allocated < thresh)
4394 if (num_allocated + SZ_2M < div_factor(num_bytes, 8))
4399 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4403 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4404 BTRFS_BLOCK_GROUP_RAID0 |
4405 BTRFS_BLOCK_GROUP_RAID5 |
4406 BTRFS_BLOCK_GROUP_RAID6))
4407 num_dev = fs_info->fs_devices->rw_devices;
4408 else if (type & BTRFS_BLOCK_GROUP_RAID1)
4411 num_dev = 1; /* DUP or single */
4417 * If @is_allocation is true, reserve space in the system space info necessary
4418 * for allocating a chunk, otherwise if it's false, reserve space necessary for
4421 void check_system_chunk(struct btrfs_trans_handle *trans,
4422 struct btrfs_fs_info *fs_info, u64 type)
4424 struct btrfs_space_info *info;
4431 * Needed because we can end up allocating a system chunk and for an
4432 * atomic and race free space reservation in the chunk block reserve.
4434 ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
4436 info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4437 spin_lock(&info->lock);
4438 left = info->total_bytes - btrfs_space_info_used(info, true);
4439 spin_unlock(&info->lock);
4441 num_devs = get_profile_num_devs(fs_info, type);
4443 /* num_devs device items to update and 1 chunk item to add or remove */
4444 thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4445 btrfs_calc_trans_metadata_size(fs_info, 1);
4447 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4448 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4449 left, thresh, type);
4450 dump_space_info(fs_info, info, 0, 0);
4453 if (left < thresh) {
4456 flags = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4458 * Ignore failure to create system chunk. We might end up not
4459 * needing it, as we might not need to COW all nodes/leafs from
4460 * the paths we visit in the chunk tree (they were already COWed
4461 * or created in the current transaction for example).
4463 ret = btrfs_alloc_chunk(trans, fs_info, flags);
4467 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4468 &fs_info->chunk_block_rsv,
4469 thresh, BTRFS_RESERVE_NO_FLUSH);
4471 trans->chunk_bytes_reserved += thresh;
4476 * If force is CHUNK_ALLOC_FORCE:
4477 * - return 1 if it successfully allocates a chunk,
4478 * - return errors including -ENOSPC otherwise.
4479 * If force is NOT CHUNK_ALLOC_FORCE:
4480 * - return 0 if it doesn't need to allocate a new chunk,
4481 * - return 1 if it successfully allocates a chunk,
4482 * - return errors including -ENOSPC otherwise.
4484 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
4485 struct btrfs_fs_info *fs_info, u64 flags, int force)
4487 struct btrfs_space_info *space_info;
4488 int wait_for_alloc = 0;
4491 /* Don't re-enter if we're already allocating a chunk */
4492 if (trans->allocating_chunk)
4495 space_info = __find_space_info(fs_info, flags);
4497 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
4498 BUG_ON(ret); /* -ENOMEM */
4500 BUG_ON(!space_info); /* Logic error */
4503 spin_lock(&space_info->lock);
4504 if (force < space_info->force_alloc)
4505 force = space_info->force_alloc;
4506 if (space_info->full) {
4507 if (should_alloc_chunk(fs_info, space_info, force))
4511 spin_unlock(&space_info->lock);
4515 if (!should_alloc_chunk(fs_info, space_info, force)) {
4516 spin_unlock(&space_info->lock);
4518 } else if (space_info->chunk_alloc) {
4521 space_info->chunk_alloc = 1;
4524 spin_unlock(&space_info->lock);
4526 mutex_lock(&fs_info->chunk_mutex);
4529 * The chunk_mutex is held throughout the entirety of a chunk
4530 * allocation, so once we've acquired the chunk_mutex we know that the
4531 * other guy is done and we need to recheck and see if we should
4534 if (wait_for_alloc) {
4535 mutex_unlock(&fs_info->chunk_mutex);
4540 trans->allocating_chunk = true;
4543 * If we have mixed data/metadata chunks we want to make sure we keep
4544 * allocating mixed chunks instead of individual chunks.
4546 if (btrfs_mixed_space_info(space_info))
4547 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4550 * if we're doing a data chunk, go ahead and make sure that
4551 * we keep a reasonable number of metadata chunks allocated in the
4554 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4555 fs_info->data_chunk_allocations++;
4556 if (!(fs_info->data_chunk_allocations %
4557 fs_info->metadata_ratio))
4558 force_metadata_allocation(fs_info);
4562 * Check if we have enough space in SYSTEM chunk because we may need
4563 * to update devices.
4565 check_system_chunk(trans, fs_info, flags);
4567 ret = btrfs_alloc_chunk(trans, fs_info, flags);
4568 trans->allocating_chunk = false;
4570 spin_lock(&space_info->lock);
4571 if (ret < 0 && ret != -ENOSPC)
4574 space_info->full = 1;
4578 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4580 space_info->chunk_alloc = 0;
4581 spin_unlock(&space_info->lock);
4582 mutex_unlock(&fs_info->chunk_mutex);
4584 * When we allocate a new chunk we reserve space in the chunk block
4585 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4586 * add new nodes/leafs to it if we end up needing to do it when
4587 * inserting the chunk item and updating device items as part of the
4588 * second phase of chunk allocation, performed by
4589 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4590 * large number of new block groups to create in our transaction
4591 * handle's new_bgs list to avoid exhausting the chunk block reserve
4592 * in extreme cases - like having a single transaction create many new
4593 * block groups when starting to write out the free space caches of all
4594 * the block groups that were made dirty during the lifetime of the
4597 if (trans->can_flush_pending_bgs &&
4598 trans->chunk_bytes_reserved >= (u64)SZ_2M) {
4599 btrfs_create_pending_block_groups(trans, fs_info);
4600 btrfs_trans_release_chunk_metadata(trans);
4605 static int can_overcommit(struct btrfs_root *root,
4606 struct btrfs_space_info *space_info, u64 bytes,
4607 enum btrfs_reserve_flush_enum flush)
4609 struct btrfs_fs_info *fs_info = root->fs_info;
4610 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4616 /* Don't overcommit when in mixed mode. */
4617 if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4620 profile = btrfs_get_alloc_profile(root, 0);
4621 used = btrfs_space_info_used(space_info, false);
4624 * We only want to allow over committing if we have lots of actual space
4625 * free, but if we don't have enough space to handle the global reserve
4626 * space then we could end up having a real enospc problem when trying
4627 * to allocate a chunk or some other such important allocation.
4629 spin_lock(&global_rsv->lock);
4630 space_size = calc_global_rsv_need_space(global_rsv);
4631 spin_unlock(&global_rsv->lock);
4632 if (used + space_size >= space_info->total_bytes)
4635 used += space_info->bytes_may_use;
4637 spin_lock(&fs_info->free_chunk_lock);
4638 avail = fs_info->free_chunk_space;
4639 spin_unlock(&fs_info->free_chunk_lock);
4642 * If we have dup, raid1 or raid10 then only half of the free
4643 * space is actually useable. For raid56, the space info used
4644 * doesn't include the parity drive, so we don't have to
4647 if (profile & (BTRFS_BLOCK_GROUP_DUP |
4648 BTRFS_BLOCK_GROUP_RAID1 |
4649 BTRFS_BLOCK_GROUP_RAID10))
4653 * If we aren't flushing all things, let us overcommit up to
4654 * 1/2th of the space. If we can flush, don't let us overcommit
4655 * too much, let it overcommit up to 1/8 of the space.
4657 if (flush == BTRFS_RESERVE_FLUSH_ALL)
4662 if (used + bytes < space_info->total_bytes + avail)
4667 static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
4668 unsigned long nr_pages, int nr_items)
4670 struct super_block *sb = fs_info->sb;
4672 if (down_read_trylock(&sb->s_umount)) {
4673 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4674 up_read(&sb->s_umount);
4677 * We needn't worry the filesystem going from r/w to r/o though
4678 * we don't acquire ->s_umount mutex, because the filesystem
4679 * should guarantee the delalloc inodes list be empty after
4680 * the filesystem is readonly(all dirty pages are written to
4683 btrfs_start_delalloc_roots(fs_info, 0, nr_items);
4684 if (!current->journal_info)
4685 btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
4689 static inline int calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
4695 bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
4696 nr = (int)div64_u64(to_reclaim, bytes);
4702 #define EXTENT_SIZE_PER_ITEM SZ_256K
4705 * shrink metadata reservation for delalloc
4707 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
4710 struct btrfs_fs_info *fs_info = root->fs_info;
4711 struct btrfs_block_rsv *block_rsv;
4712 struct btrfs_space_info *space_info;
4713 struct btrfs_trans_handle *trans;
4717 unsigned long nr_pages;
4720 enum btrfs_reserve_flush_enum flush;
4722 /* Calc the number of the pages we need flush for space reservation */
4723 items = calc_reclaim_items_nr(fs_info, to_reclaim);
4724 to_reclaim = (u64)items * EXTENT_SIZE_PER_ITEM;
4726 trans = (struct btrfs_trans_handle *)current->journal_info;
4727 block_rsv = &fs_info->delalloc_block_rsv;
4728 space_info = block_rsv->space_info;
4730 delalloc_bytes = percpu_counter_sum_positive(
4731 &fs_info->delalloc_bytes);
4732 if (delalloc_bytes == 0) {
4736 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4741 while (delalloc_bytes && loops < 3) {
4742 max_reclaim = min(delalloc_bytes, to_reclaim);
4743 nr_pages = max_reclaim >> PAGE_SHIFT;
4744 btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
4746 * We need to wait for the async pages to actually start before
4749 max_reclaim = atomic_read(&fs_info->async_delalloc_pages);
4753 if (max_reclaim <= nr_pages)
4756 max_reclaim -= nr_pages;
4758 wait_event(fs_info->async_submit_wait,
4759 atomic_read(&fs_info->async_delalloc_pages) <=
4763 flush = BTRFS_RESERVE_FLUSH_ALL;
4765 flush = BTRFS_RESERVE_NO_FLUSH;
4766 spin_lock(&space_info->lock);
4767 if (can_overcommit(root, space_info, orig, flush)) {
4768 spin_unlock(&space_info->lock);
4771 if (list_empty(&space_info->tickets) &&
4772 list_empty(&space_info->priority_tickets)) {
4773 spin_unlock(&space_info->lock);
4776 spin_unlock(&space_info->lock);
4779 if (wait_ordered && !trans) {
4780 btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4782 time_left = schedule_timeout_killable(1);
4786 delalloc_bytes = percpu_counter_sum_positive(
4787 &fs_info->delalloc_bytes);
4792 * maybe_commit_transaction - possibly commit the transaction if its ok to
4793 * @root - the root we're allocating for
4794 * @bytes - the number of bytes we want to reserve
4795 * @force - force the commit
4797 * This will check to make sure that committing the transaction will actually
4798 * get us somewhere and then commit the transaction if it does. Otherwise it
4799 * will return -ENOSPC.
4801 static int may_commit_transaction(struct btrfs_fs_info *fs_info,
4802 struct btrfs_space_info *space_info,
4803 u64 bytes, int force)
4805 struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
4806 struct btrfs_trans_handle *trans;
4808 trans = (struct btrfs_trans_handle *)current->journal_info;
4815 /* See if there is enough pinned space to make this reservation */
4816 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4821 * See if there is some space in the delayed insertion reservation for
4824 if (space_info != delayed_rsv->space_info)
4827 spin_lock(&delayed_rsv->lock);
4828 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4829 bytes - delayed_rsv->size) >= 0) {
4830 spin_unlock(&delayed_rsv->lock);
4833 spin_unlock(&delayed_rsv->lock);
4836 trans = btrfs_join_transaction(fs_info->fs_root);
4840 return btrfs_commit_transaction(trans);
4843 struct reserve_ticket {
4846 struct list_head list;
4847 wait_queue_head_t wait;
4850 static int flush_space(struct btrfs_fs_info *fs_info,
4851 struct btrfs_space_info *space_info, u64 num_bytes,
4852 u64 orig_bytes, int state)
4854 struct btrfs_root *root = fs_info->fs_root;
4855 struct btrfs_trans_handle *trans;
4860 case FLUSH_DELAYED_ITEMS_NR:
4861 case FLUSH_DELAYED_ITEMS:
4862 if (state == FLUSH_DELAYED_ITEMS_NR)
4863 nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
4867 trans = btrfs_join_transaction(root);
4868 if (IS_ERR(trans)) {
4869 ret = PTR_ERR(trans);
4872 ret = btrfs_run_delayed_items_nr(trans, fs_info, nr);
4873 btrfs_end_transaction(trans);
4875 case FLUSH_DELALLOC:
4876 case FLUSH_DELALLOC_WAIT:
4877 shrink_delalloc(root, num_bytes * 2, orig_bytes,
4878 state == FLUSH_DELALLOC_WAIT);
4881 trans = btrfs_join_transaction(root);
4882 if (IS_ERR(trans)) {
4883 ret = PTR_ERR(trans);
4886 ret = do_chunk_alloc(trans, fs_info,
4887 btrfs_get_alloc_profile(root, 0),
4888 CHUNK_ALLOC_NO_FORCE);
4889 btrfs_end_transaction(trans);
4890 if (ret > 0 || ret == -ENOSPC)
4894 ret = may_commit_transaction(fs_info, space_info,
4902 trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes,
4903 orig_bytes, state, ret);
4908 btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
4909 struct btrfs_space_info *space_info)
4911 struct reserve_ticket *ticket;
4916 list_for_each_entry(ticket, &space_info->tickets, list)
4917 to_reclaim += ticket->bytes;
4918 list_for_each_entry(ticket, &space_info->priority_tickets, list)
4919 to_reclaim += ticket->bytes;
4923 to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
4924 if (can_overcommit(root, space_info, to_reclaim,
4925 BTRFS_RESERVE_FLUSH_ALL))
4928 used = space_info->bytes_used + space_info->bytes_reserved +
4929 space_info->bytes_pinned + space_info->bytes_readonly +
4930 space_info->bytes_may_use;
4931 if (can_overcommit(root, space_info, SZ_1M, BTRFS_RESERVE_FLUSH_ALL))
4932 expected = div_factor_fine(space_info->total_bytes, 95);
4934 expected = div_factor_fine(space_info->total_bytes, 90);
4936 if (used > expected)
4937 to_reclaim = used - expected;
4940 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4941 space_info->bytes_reserved);
4945 static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
4946 struct btrfs_root *root, u64 used)
4948 struct btrfs_fs_info *fs_info = root->fs_info;
4949 u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4951 /* If we're just plain full then async reclaim just slows us down. */
4952 if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
4955 if (!btrfs_calc_reclaim_metadata_size(root, space_info))
4958 return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4959 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4962 static void wake_all_tickets(struct list_head *head)
4964 struct reserve_ticket *ticket;
4966 while (!list_empty(head)) {
4967 ticket = list_first_entry(head, struct reserve_ticket, list);
4968 list_del_init(&ticket->list);
4969 ticket->error = -ENOSPC;
4970 wake_up(&ticket->wait);
4975 * This is for normal flushers, we can wait all goddamned day if we want to. We
4976 * will loop and continuously try to flush as long as we are making progress.
4977 * We count progress as clearing off tickets each time we have to loop.
4979 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4981 struct btrfs_fs_info *fs_info;
4982 struct btrfs_space_info *space_info;
4985 int commit_cycles = 0;
4986 u64 last_tickets_id;
4988 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4989 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4991 spin_lock(&space_info->lock);
4992 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
4995 space_info->flush = 0;
4996 spin_unlock(&space_info->lock);
4999 last_tickets_id = space_info->tickets_id;
5000 spin_unlock(&space_info->lock);
5002 flush_state = FLUSH_DELAYED_ITEMS_NR;
5004 struct reserve_ticket *ticket;
5007 ret = flush_space(fs_info, space_info, to_reclaim, to_reclaim,
5009 spin_lock(&space_info->lock);
5010 if (list_empty(&space_info->tickets)) {
5011 space_info->flush = 0;
5012 spin_unlock(&space_info->lock);
5015 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5017 ticket = list_first_entry(&space_info->tickets,
5018 struct reserve_ticket, list);
5019 if (last_tickets_id == space_info->tickets_id) {
5022 last_tickets_id = space_info->tickets_id;
5023 flush_state = FLUSH_DELAYED_ITEMS_NR;
5028 if (flush_state > COMMIT_TRANS) {
5030 if (commit_cycles > 2) {
5031 wake_all_tickets(&space_info->tickets);
5032 space_info->flush = 0;
5034 flush_state = FLUSH_DELAYED_ITEMS_NR;
5037 spin_unlock(&space_info->lock);
5038 } while (flush_state <= COMMIT_TRANS);
5041 void btrfs_init_async_reclaim_work(struct work_struct *work)
5043 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5046 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5047 struct btrfs_space_info *space_info,
5048 struct reserve_ticket *ticket)
5051 int flush_state = FLUSH_DELAYED_ITEMS_NR;
5053 spin_lock(&space_info->lock);
5054 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5057 spin_unlock(&space_info->lock);
5060 spin_unlock(&space_info->lock);
5063 flush_space(fs_info, space_info, to_reclaim, to_reclaim,
5066 spin_lock(&space_info->lock);
5067 if (ticket->bytes == 0) {
5068 spin_unlock(&space_info->lock);
5071 spin_unlock(&space_info->lock);
5074 * Priority flushers can't wait on delalloc without
5077 if (flush_state == FLUSH_DELALLOC ||
5078 flush_state == FLUSH_DELALLOC_WAIT)
5079 flush_state = ALLOC_CHUNK;
5080 } while (flush_state < COMMIT_TRANS);
5083 static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5084 struct btrfs_space_info *space_info,
5085 struct reserve_ticket *ticket, u64 orig_bytes)
5091 spin_lock(&space_info->lock);
5092 while (ticket->bytes > 0 && ticket->error == 0) {
5093 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5098 spin_unlock(&space_info->lock);
5102 finish_wait(&ticket->wait, &wait);
5103 spin_lock(&space_info->lock);
5106 ret = ticket->error;
5107 if (!list_empty(&ticket->list))
5108 list_del_init(&ticket->list);
5109 if (ticket->bytes && ticket->bytes < orig_bytes) {
5110 u64 num_bytes = orig_bytes - ticket->bytes;
5111 space_info->bytes_may_use -= num_bytes;
5112 trace_btrfs_space_reservation(fs_info, "space_info",
5113 space_info->flags, num_bytes, 0);
5115 spin_unlock(&space_info->lock);
5121 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5122 * @root - the root we're allocating for
5123 * @space_info - the space info we want to allocate from
5124 * @orig_bytes - the number of bytes we want
5125 * @flush - whether or not we can flush to make our reservation
5127 * This will reserve orig_bytes number of bytes from the space info associated
5128 * with the block_rsv. If there is not enough space it will make an attempt to
5129 * flush out space to make room. It will do this by flushing delalloc if
5130 * possible or committing the transaction. If flush is 0 then no attempts to
5131 * regain reservations will be made and this will fail if there is not enough
5134 static int __reserve_metadata_bytes(struct btrfs_root *root,
5135 struct btrfs_space_info *space_info,
5137 enum btrfs_reserve_flush_enum flush)
5139 struct btrfs_fs_info *fs_info = root->fs_info;
5140 struct reserve_ticket ticket;
5145 ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
5147 spin_lock(&space_info->lock);
5149 used = btrfs_space_info_used(space_info, true);
5152 * If we have enough space then hooray, make our reservation and carry
5153 * on. If not see if we can overcommit, and if we can, hooray carry on.
5154 * If not things get more complicated.
5156 if (used + orig_bytes <= space_info->total_bytes) {
5157 space_info->bytes_may_use += orig_bytes;
5158 trace_btrfs_space_reservation(fs_info, "space_info",
5159 space_info->flags, orig_bytes, 1);
5161 } else if (can_overcommit(root, space_info, orig_bytes, flush)) {
5162 space_info->bytes_may_use += orig_bytes;
5163 trace_btrfs_space_reservation(fs_info, "space_info",
5164 space_info->flags, orig_bytes, 1);
5169 * If we couldn't make a reservation then setup our reservation ticket
5170 * and kick the async worker if it's not already running.
5172 * If we are a priority flusher then we just need to add our ticket to
5173 * the list and we will do our own flushing further down.
5175 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
5176 ticket.bytes = orig_bytes;
5178 init_waitqueue_head(&ticket.wait);
5179 if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5180 list_add_tail(&ticket.list, &space_info->tickets);
5181 if (!space_info->flush) {
5182 space_info->flush = 1;
5183 trace_btrfs_trigger_flush(fs_info,
5187 queue_work(system_unbound_wq,
5188 &root->fs_info->async_reclaim_work);
5191 list_add_tail(&ticket.list,
5192 &space_info->priority_tickets);
5194 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5197 * We will do the space reservation dance during log replay,
5198 * which means we won't have fs_info->fs_root set, so don't do
5199 * the async reclaim as we will panic.
5201 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
5202 need_do_async_reclaim(space_info, root, used) &&
5203 !work_busy(&fs_info->async_reclaim_work)) {
5204 trace_btrfs_trigger_flush(fs_info, space_info->flags,
5205 orig_bytes, flush, "preempt");
5206 queue_work(system_unbound_wq,
5207 &fs_info->async_reclaim_work);
5210 spin_unlock(&space_info->lock);
5211 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
5214 if (flush == BTRFS_RESERVE_FLUSH_ALL)
5215 return wait_reserve_ticket(fs_info, space_info, &ticket,
5219 priority_reclaim_metadata_space(fs_info, space_info, &ticket);
5220 spin_lock(&space_info->lock);
5222 if (ticket.bytes < orig_bytes) {
5223 u64 num_bytes = orig_bytes - ticket.bytes;
5224 space_info->bytes_may_use -= num_bytes;
5225 trace_btrfs_space_reservation(fs_info, "space_info",
5230 list_del_init(&ticket.list);
5233 spin_unlock(&space_info->lock);
5234 ASSERT(list_empty(&ticket.list));
5239 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5240 * @root - the root we're allocating for
5241 * @block_rsv - the block_rsv we're allocating for
5242 * @orig_bytes - the number of bytes we want
5243 * @flush - whether or not we can flush to make our reservation
5245 * This will reserve orgi_bytes number of bytes from the space info associated
5246 * with the block_rsv. If there is not enough space it will make an attempt to
5247 * flush out space to make room. It will do this by flushing delalloc if
5248 * possible or committing the transaction. If flush is 0 then no attempts to
5249 * regain reservations will be made and this will fail if there is not enough
5252 static int reserve_metadata_bytes(struct btrfs_root *root,
5253 struct btrfs_block_rsv *block_rsv,
5255 enum btrfs_reserve_flush_enum flush)
5257 struct btrfs_fs_info *fs_info = root->fs_info;
5258 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5261 ret = __reserve_metadata_bytes(root, block_rsv->space_info, orig_bytes,
5263 if (ret == -ENOSPC &&
5264 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5265 if (block_rsv != global_rsv &&
5266 !block_rsv_use_bytes(global_rsv, orig_bytes))
5270 trace_btrfs_space_reservation(fs_info, "space_info:enospc",
5271 block_rsv->space_info->flags,
5276 static struct btrfs_block_rsv *get_block_rsv(
5277 const struct btrfs_trans_handle *trans,
5278 const struct btrfs_root *root)
5280 struct btrfs_fs_info *fs_info = root->fs_info;
5281 struct btrfs_block_rsv *block_rsv = NULL;
5283 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5284 (root == fs_info->csum_root && trans->adding_csums) ||
5285 (root == fs_info->uuid_root))
5286 block_rsv = trans->block_rsv;
5289 block_rsv = root->block_rsv;
5292 block_rsv = &fs_info->empty_block_rsv;
5297 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5301 spin_lock(&block_rsv->lock);
5302 if (block_rsv->reserved >= num_bytes) {
5303 block_rsv->reserved -= num_bytes;
5304 if (block_rsv->reserved < block_rsv->size)
5305 block_rsv->full = 0;
5308 spin_unlock(&block_rsv->lock);
5312 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5313 u64 num_bytes, int update_size)
5315 spin_lock(&block_rsv->lock);
5316 block_rsv->reserved += num_bytes;
5318 block_rsv->size += num_bytes;
5319 else if (block_rsv->reserved >= block_rsv->size)
5320 block_rsv->full = 1;
5321 spin_unlock(&block_rsv->lock);
5324 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5325 struct btrfs_block_rsv *dest, u64 num_bytes,
5328 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5331 if (global_rsv->space_info != dest->space_info)
5334 spin_lock(&global_rsv->lock);
5335 min_bytes = div_factor(global_rsv->size, min_factor);
5336 if (global_rsv->reserved < min_bytes + num_bytes) {
5337 spin_unlock(&global_rsv->lock);
5340 global_rsv->reserved -= num_bytes;
5341 if (global_rsv->reserved < global_rsv->size)
5342 global_rsv->full = 0;
5343 spin_unlock(&global_rsv->lock);
5345 block_rsv_add_bytes(dest, num_bytes, 1);
5350 * This is for space we already have accounted in space_info->bytes_may_use, so
5351 * basically when we're returning space from block_rsv's.
5353 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5354 struct btrfs_space_info *space_info,
5357 struct reserve_ticket *ticket;
5358 struct list_head *head;
5360 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5361 bool check_overcommit = false;
5363 spin_lock(&space_info->lock);
5364 head = &space_info->priority_tickets;
5367 * If we are over our limit then we need to check and see if we can
5368 * overcommit, and if we can't then we just need to free up our space
5369 * and not satisfy any requests.
5371 used = space_info->bytes_used + space_info->bytes_reserved +
5372 space_info->bytes_pinned + space_info->bytes_readonly +
5373 space_info->bytes_may_use;
5374 if (used - num_bytes >= space_info->total_bytes)
5375 check_overcommit = true;
5377 while (!list_empty(head) && num_bytes) {
5378 ticket = list_first_entry(head, struct reserve_ticket,
5381 * We use 0 bytes because this space is already reserved, so
5382 * adding the ticket space would be a double count.
5384 if (check_overcommit &&
5385 !can_overcommit(fs_info->extent_root, space_info, 0,
5388 if (num_bytes >= ticket->bytes) {
5389 list_del_init(&ticket->list);
5390 num_bytes -= ticket->bytes;
5392 space_info->tickets_id++;
5393 wake_up(&ticket->wait);
5395 ticket->bytes -= num_bytes;
5400 if (num_bytes && head == &space_info->priority_tickets) {
5401 head = &space_info->tickets;
5402 flush = BTRFS_RESERVE_FLUSH_ALL;
5405 space_info->bytes_may_use -= num_bytes;
5406 trace_btrfs_space_reservation(fs_info, "space_info",
5407 space_info->flags, num_bytes, 0);
5408 spin_unlock(&space_info->lock);
5412 * This is for newly allocated space that isn't accounted in
5413 * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
5414 * we use this helper.
5416 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5417 struct btrfs_space_info *space_info,
5420 struct reserve_ticket *ticket;
5421 struct list_head *head = &space_info->priority_tickets;
5424 while (!list_empty(head) && num_bytes) {
5425 ticket = list_first_entry(head, struct reserve_ticket,
5427 if (num_bytes >= ticket->bytes) {
5428 trace_btrfs_space_reservation(fs_info, "space_info",
5431 list_del_init(&ticket->list);
5432 num_bytes -= ticket->bytes;
5433 space_info->bytes_may_use += ticket->bytes;
5435 space_info->tickets_id++;
5436 wake_up(&ticket->wait);
5438 trace_btrfs_space_reservation(fs_info, "space_info",
5441 space_info->bytes_may_use += num_bytes;
5442 ticket->bytes -= num_bytes;
5447 if (num_bytes && head == &space_info->priority_tickets) {
5448 head = &space_info->tickets;
5453 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5454 struct btrfs_block_rsv *block_rsv,
5455 struct btrfs_block_rsv *dest, u64 num_bytes)
5457 struct btrfs_space_info *space_info = block_rsv->space_info;
5459 spin_lock(&block_rsv->lock);
5460 if (num_bytes == (u64)-1)
5461 num_bytes = block_rsv->size;
5462 block_rsv->size -= num_bytes;
5463 if (block_rsv->reserved >= block_rsv->size) {
5464 num_bytes = block_rsv->reserved - block_rsv->size;
5465 block_rsv->reserved = block_rsv->size;
5466 block_rsv->full = 1;
5470 spin_unlock(&block_rsv->lock);
5472 if (num_bytes > 0) {
5474 spin_lock(&dest->lock);
5478 bytes_to_add = dest->size - dest->reserved;
5479 bytes_to_add = min(num_bytes, bytes_to_add);
5480 dest->reserved += bytes_to_add;
5481 if (dest->reserved >= dest->size)
5483 num_bytes -= bytes_to_add;
5485 spin_unlock(&dest->lock);
5488 space_info_add_old_bytes(fs_info, space_info,
5493 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5494 struct btrfs_block_rsv *dst, u64 num_bytes,
5499 ret = block_rsv_use_bytes(src, num_bytes);
5503 block_rsv_add_bytes(dst, num_bytes, update_size);
5507 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5509 memset(rsv, 0, sizeof(*rsv));
5510 spin_lock_init(&rsv->lock);
5514 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
5515 unsigned short type)
5517 struct btrfs_block_rsv *block_rsv;
5519 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5523 btrfs_init_block_rsv(block_rsv, type);
5524 block_rsv->space_info = __find_space_info(fs_info,
5525 BTRFS_BLOCK_GROUP_METADATA);
5529 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
5530 struct btrfs_block_rsv *rsv)
5534 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5538 void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
5543 int btrfs_block_rsv_add(struct btrfs_root *root,
5544 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5545 enum btrfs_reserve_flush_enum flush)
5552 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5554 block_rsv_add_bytes(block_rsv, num_bytes, 1);
5561 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
5569 spin_lock(&block_rsv->lock);
5570 num_bytes = div_factor(block_rsv->size, min_factor);
5571 if (block_rsv->reserved >= num_bytes)
5573 spin_unlock(&block_rsv->lock);
5578 int btrfs_block_rsv_refill(struct btrfs_root *root,
5579 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5580 enum btrfs_reserve_flush_enum flush)
5588 spin_lock(&block_rsv->lock);
5589 num_bytes = min_reserved;
5590 if (block_rsv->reserved >= num_bytes)
5593 num_bytes -= block_rsv->reserved;
5594 spin_unlock(&block_rsv->lock);
5599 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5601 block_rsv_add_bytes(block_rsv, num_bytes, 0);
5608 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5609 struct btrfs_block_rsv *block_rsv,
5612 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5614 if (global_rsv == block_rsv ||
5615 block_rsv->space_info != global_rsv->space_info)
5617 block_rsv_release_bytes(fs_info, block_rsv, global_rsv, num_bytes);
5620 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5622 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5623 struct btrfs_space_info *sinfo = block_rsv->space_info;
5627 * The global block rsv is based on the size of the extent tree, the
5628 * checksum tree and the root tree. If the fs is empty we want to set
5629 * it to a minimal amount for safety.
5631 num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5632 btrfs_root_used(&fs_info->csum_root->root_item) +
5633 btrfs_root_used(&fs_info->tree_root->root_item);
5634 num_bytes = max_t(u64, num_bytes, SZ_16M);
5636 spin_lock(&sinfo->lock);
5637 spin_lock(&block_rsv->lock);
5639 block_rsv->size = min_t(u64, num_bytes, SZ_512M);
5641 if (block_rsv->reserved < block_rsv->size) {
5642 num_bytes = btrfs_space_info_used(sinfo, true);
5643 if (sinfo->total_bytes > num_bytes) {
5644 num_bytes = sinfo->total_bytes - num_bytes;
5645 num_bytes = min(num_bytes,
5646 block_rsv->size - block_rsv->reserved);
5647 block_rsv->reserved += num_bytes;
5648 sinfo->bytes_may_use += num_bytes;
5649 trace_btrfs_space_reservation(fs_info, "space_info",
5650 sinfo->flags, num_bytes,
5653 } else if (block_rsv->reserved > block_rsv->size) {
5654 num_bytes = block_rsv->reserved - block_rsv->size;
5655 sinfo->bytes_may_use -= num_bytes;
5656 trace_btrfs_space_reservation(fs_info, "space_info",
5657 sinfo->flags, num_bytes, 0);
5658 block_rsv->reserved = block_rsv->size;
5661 if (block_rsv->reserved == block_rsv->size)
5662 block_rsv->full = 1;
5664 block_rsv->full = 0;
5666 spin_unlock(&block_rsv->lock);
5667 spin_unlock(&sinfo->lock);
5670 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5672 struct btrfs_space_info *space_info;
5674 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5675 fs_info->chunk_block_rsv.space_info = space_info;
5677 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5678 fs_info->global_block_rsv.space_info = space_info;
5679 fs_info->delalloc_block_rsv.space_info = space_info;
5680 fs_info->trans_block_rsv.space_info = space_info;
5681 fs_info->empty_block_rsv.space_info = space_info;
5682 fs_info->delayed_block_rsv.space_info = space_info;
5684 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
5685 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
5686 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5687 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5688 if (fs_info->quota_root)
5689 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5690 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5692 update_global_block_rsv(fs_info);
5695 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5697 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5699 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
5700 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
5701 WARN_ON(fs_info->trans_block_rsv.size > 0);
5702 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5703 WARN_ON(fs_info->chunk_block_rsv.size > 0);
5704 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5705 WARN_ON(fs_info->delayed_block_rsv.size > 0);
5706 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5709 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
5710 struct btrfs_fs_info *fs_info)
5712 if (!trans->block_rsv)
5715 if (!trans->bytes_reserved)
5718 trace_btrfs_space_reservation(fs_info, "transaction",
5719 trans->transid, trans->bytes_reserved, 0);
5720 btrfs_block_rsv_release(fs_info, trans->block_rsv,
5721 trans->bytes_reserved);
5722 trans->bytes_reserved = 0;
5726 * To be called after all the new block groups attached to the transaction
5727 * handle have been created (btrfs_create_pending_block_groups()).
5729 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5731 struct btrfs_fs_info *fs_info = trans->fs_info;
5733 if (!trans->chunk_bytes_reserved)
5736 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5738 block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5739 trans->chunk_bytes_reserved);
5740 trans->chunk_bytes_reserved = 0;
5743 /* Can only return 0 or -ENOSPC */
5744 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
5745 struct btrfs_inode *inode)
5747 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
5748 struct btrfs_root *root = inode->root;
5750 * We always use trans->block_rsv here as we will have reserved space
5751 * for our orphan when starting the transaction, using get_block_rsv()
5752 * here will sometimes make us choose the wrong block rsv as we could be
5753 * doing a reloc inode for a non refcounted root.
5755 struct btrfs_block_rsv *src_rsv = trans->block_rsv;
5756 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
5759 * We need to hold space in order to delete our orphan item once we've
5760 * added it, so this takes the reservation so we can release it later
5761 * when we are truly done with the orphan item.
5763 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5765 trace_btrfs_space_reservation(fs_info, "orphan", btrfs_ino(inode),
5767 return btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, 1);
5770 void btrfs_orphan_release_metadata(struct inode *inode)
5772 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5773 struct btrfs_root *root = BTRFS_I(inode)->root;
5774 u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5776 trace_btrfs_space_reservation(fs_info, "orphan",
5777 btrfs_ino(BTRFS_I(inode)), num_bytes, 0);
5778 btrfs_block_rsv_release(fs_info, root->orphan_block_rsv, num_bytes);
5782 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5783 * root: the root of the parent directory
5784 * rsv: block reservation
5785 * items: the number of items that we need do reservation
5786 * qgroup_reserved: used to return the reserved size in qgroup
5788 * This function is used to reserve the space for snapshot/subvolume
5789 * creation and deletion. Those operations are different with the
5790 * common file/directory operations, they change two fs/file trees
5791 * and root tree, the number of items that the qgroup reserves is
5792 * different with the free space reservation. So we can not use
5793 * the space reservation mechanism in start_transaction().
5795 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5796 struct btrfs_block_rsv *rsv,
5798 u64 *qgroup_reserved,
5799 bool use_global_rsv)
5803 struct btrfs_fs_info *fs_info = root->fs_info;
5804 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5806 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5807 /* One for parent inode, two for dir entries */
5808 num_bytes = 3 * fs_info->nodesize;
5809 ret = btrfs_qgroup_reserve_meta(root, num_bytes, true);
5816 *qgroup_reserved = num_bytes;
5818 num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
5819 rsv->space_info = __find_space_info(fs_info,
5820 BTRFS_BLOCK_GROUP_METADATA);
5821 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5822 BTRFS_RESERVE_FLUSH_ALL);
5824 if (ret == -ENOSPC && use_global_rsv)
5825 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
5827 if (ret && *qgroup_reserved)
5828 btrfs_qgroup_free_meta(root, *qgroup_reserved);
5833 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
5834 struct btrfs_block_rsv *rsv)
5836 btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5840 * drop_outstanding_extent - drop an outstanding extent
5841 * @inode: the inode we're dropping the extent for
5842 * @num_bytes: the number of bytes we're releasing.
5844 * This is called when we are freeing up an outstanding extent, either called
5845 * after an error or after an extent is written. This will return the number of
5846 * reserved extents that need to be freed. This must be called with
5847 * BTRFS_I(inode)->lock held.
5849 static unsigned drop_outstanding_extent(struct btrfs_inode *inode,
5852 unsigned drop_inode_space = 0;
5853 unsigned dropped_extents = 0;
5854 unsigned num_extents;
5856 num_extents = count_max_extents(num_bytes);
5857 ASSERT(num_extents);
5858 ASSERT(inode->outstanding_extents >= num_extents);
5859 inode->outstanding_extents -= num_extents;
5861 if (inode->outstanding_extents == 0 &&
5862 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5863 &inode->runtime_flags))
5864 drop_inode_space = 1;
5867 * If we have more or the same amount of outstanding extents than we have
5868 * reserved then we need to leave the reserved extents count alone.
5870 if (inode->outstanding_extents >= inode->reserved_extents)
5871 return drop_inode_space;
5873 dropped_extents = inode->reserved_extents - inode->outstanding_extents;
5874 inode->reserved_extents -= dropped_extents;
5875 return dropped_extents + drop_inode_space;
5879 * calc_csum_metadata_size - return the amount of metadata space that must be
5880 * reserved/freed for the given bytes.
5881 * @inode: the inode we're manipulating
5882 * @num_bytes: the number of bytes in question
5883 * @reserve: 1 if we are reserving space, 0 if we are freeing space
5885 * This adjusts the number of csum_bytes in the inode and then returns the
5886 * correct amount of metadata that must either be reserved or freed. We
5887 * calculate how many checksums we can fit into one leaf and then divide the
5888 * number of bytes that will need to be checksumed by this value to figure out
5889 * how many checksums will be required. If we are adding bytes then the number
5890 * may go up and we will return the number of additional bytes that must be
5891 * reserved. If it is going down we will return the number of bytes that must
5894 * This must be called with BTRFS_I(inode)->lock held.
5896 static u64 calc_csum_metadata_size(struct btrfs_inode *inode, u64 num_bytes,
5899 struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
5900 u64 old_csums, num_csums;
5902 if (inode->flags & BTRFS_INODE_NODATASUM && inode->csum_bytes == 0)
5905 old_csums = btrfs_csum_bytes_to_leaves(fs_info, inode->csum_bytes);
5907 inode->csum_bytes += num_bytes;
5909 inode->csum_bytes -= num_bytes;
5910 num_csums = btrfs_csum_bytes_to_leaves(fs_info, 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;
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(BTRFS_I(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 = count_max_extents(num_bytes);
5964 BTRFS_I(inode)->outstanding_extents += nr_extents;
5967 if (BTRFS_I(inode)->outstanding_extents >
5968 BTRFS_I(inode)->reserved_extents)
5969 nr_extents += BTRFS_I(inode)->outstanding_extents -
5970 BTRFS_I(inode)->reserved_extents;
5972 /* We always want to reserve a slot for updating the inode. */
5973 to_reserve = btrfs_calc_trans_metadata_size(fs_info, nr_extents + 1);
5974 to_reserve += calc_csum_metadata_size(BTRFS_I(inode), num_bytes, 1);
5975 csum_bytes = BTRFS_I(inode)->csum_bytes;
5976 spin_unlock(&BTRFS_I(inode)->lock);
5978 if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5979 ret = btrfs_qgroup_reserve_meta(root,
5980 nr_extents * fs_info->nodesize, true);
5985 ret = btrfs_block_rsv_add(root, block_rsv, to_reserve, flush);
5986 if (unlikely(ret)) {
5987 btrfs_qgroup_free_meta(root,
5988 nr_extents * fs_info->nodesize);
5992 spin_lock(&BTRFS_I(inode)->lock);
5993 if (test_and_set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5994 &BTRFS_I(inode)->runtime_flags)) {
5995 to_reserve -= btrfs_calc_trans_metadata_size(fs_info, 1);
5996 release_extra = true;
5998 BTRFS_I(inode)->reserved_extents += nr_extents;
5999 spin_unlock(&BTRFS_I(inode)->lock);
6002 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
6005 trace_btrfs_space_reservation(fs_info, "delalloc",
6006 btrfs_ino(BTRFS_I(inode)), to_reserve, 1);
6008 btrfs_block_rsv_release(fs_info, block_rsv,
6009 btrfs_calc_trans_metadata_size(fs_info, 1));
6013 spin_lock(&BTRFS_I(inode)->lock);
6014 dropped = drop_outstanding_extent(BTRFS_I(inode), num_bytes);
6016 * If the inodes csum_bytes is the same as the original
6017 * csum_bytes then we know we haven't raced with any free()ers
6018 * so we can just reduce our inodes csum bytes and carry on.
6020 if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
6021 calc_csum_metadata_size(BTRFS_I(inode), num_bytes, 0);
6023 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
6027 * This is tricky, but first we need to figure out how much we
6028 * freed from any free-ers that occurred during this
6029 * reservation, so we reset ->csum_bytes to the csum_bytes
6030 * before we dropped our lock, and then call the free for the
6031 * number of bytes that were freed while we were trying our
6034 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
6035 BTRFS_I(inode)->csum_bytes = csum_bytes;
6036 to_free = calc_csum_metadata_size(BTRFS_I(inode), bytes, 0);
6040 * Now we need to see how much we would have freed had we not
6041 * been making this reservation and our ->csum_bytes were not
6042 * artificially inflated.
6044 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
6045 bytes = csum_bytes - orig_csum_bytes;
6046 bytes = calc_csum_metadata_size(BTRFS_I(inode), bytes, 0);
6049 * Now reset ->csum_bytes to what it should be. If bytes is
6050 * more than to_free then we would have freed more space had we
6051 * not had an artificially high ->csum_bytes, so we need to free
6052 * the remainder. If bytes is the same or less then we don't
6053 * need to do anything, the other free-ers did the correct
6056 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
6057 if (bytes > to_free)
6058 to_free = bytes - to_free;
6062 spin_unlock(&BTRFS_I(inode)->lock);
6064 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
6067 btrfs_block_rsv_release(fs_info, block_rsv, to_free);
6068 trace_btrfs_space_reservation(fs_info, "delalloc",
6069 btrfs_ino(BTRFS_I(inode)), to_free, 0);
6072 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
6077 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
6078 * @inode: the inode to release the reservation for
6079 * @num_bytes: the number of bytes we're releasing
6081 * This will release the metadata reservation for an inode. This can be called
6082 * once we complete IO for a given set of bytes to release their metadata
6085 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
6087 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6091 num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6092 spin_lock(&BTRFS_I(inode)->lock);
6093 dropped = drop_outstanding_extent(BTRFS_I(inode), num_bytes);
6096 to_free = calc_csum_metadata_size(BTRFS_I(inode), num_bytes, 0);
6097 spin_unlock(&BTRFS_I(inode)->lock);
6099 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
6101 if (btrfs_is_testing(fs_info))
6104 trace_btrfs_space_reservation(fs_info, "delalloc",
6105 btrfs_ino(BTRFS_I(inode)), to_free, 0);
6107 btrfs_block_rsv_release(fs_info, &fs_info->delalloc_block_rsv, to_free);
6111 * btrfs_delalloc_reserve_space - reserve data and metadata space for
6113 * @inode: inode we're writing to
6114 * @start: start range we are writing to
6115 * @len: how long the range we are writing to
6117 * This will do the following things
6119 * o reserve space in data space info for num bytes
6120 * and reserve precious corresponding qgroup space
6121 * (Done in check_data_free_space)
6123 * o reserve space for metadata space, based on the number of outstanding
6124 * extents and how much csums will be needed
6125 * also reserve metadata space in a per root over-reserve method.
6126 * o add to the inodes->delalloc_bytes
6127 * o add it to the fs_info's delalloc inodes list.
6128 * (Above 3 all done in delalloc_reserve_metadata)
6130 * Return 0 for success
6131 * Return <0 for error(-ENOSPC or -EQUOT)
6133 int btrfs_delalloc_reserve_space(struct inode *inode, u64 start, u64 len)
6137 ret = btrfs_check_data_free_space(inode, start, len);
6140 ret = btrfs_delalloc_reserve_metadata(inode, len);
6142 btrfs_free_reserved_data_space(inode, start, len);
6147 * btrfs_delalloc_release_space - release data and metadata space for delalloc
6148 * @inode: inode we're releasing space for
6149 * @start: start position of the space already reserved
6150 * @len: the len of the space already reserved
6152 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
6153 * called in the case that we don't need the metadata AND data reservations
6154 * anymore. So if there is an error or we insert an inline extent.
6156 * This function will release the metadata space that was not used and will
6157 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6158 * list if there are no delalloc bytes left.
6159 * Also it will handle the qgroup reserved space.
6161 void btrfs_delalloc_release_space(struct inode *inode, u64 start, u64 len)
6163 btrfs_delalloc_release_metadata(inode, len);
6164 btrfs_free_reserved_data_space(inode, start, len);
6167 static int update_block_group(struct btrfs_trans_handle *trans,
6168 struct btrfs_fs_info *info, u64 bytenr,
6169 u64 num_bytes, int alloc)
6171 struct btrfs_block_group_cache *cache = NULL;
6172 u64 total = num_bytes;
6177 /* block accounting for super block */
6178 spin_lock(&info->delalloc_root_lock);
6179 old_val = btrfs_super_bytes_used(info->super_copy);
6181 old_val += num_bytes;
6183 old_val -= num_bytes;
6184 btrfs_set_super_bytes_used(info->super_copy, old_val);
6185 spin_unlock(&info->delalloc_root_lock);
6188 cache = btrfs_lookup_block_group(info, bytenr);
6191 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
6192 BTRFS_BLOCK_GROUP_RAID1 |
6193 BTRFS_BLOCK_GROUP_RAID10))
6198 * If this block group has free space cache written out, we
6199 * need to make sure to load it if we are removing space. This
6200 * is because we need the unpinning stage to actually add the
6201 * space back to the block group, otherwise we will leak space.
6203 if (!alloc && cache->cached == BTRFS_CACHE_NO)
6204 cache_block_group(cache, 1);
6206 byte_in_group = bytenr - cache->key.objectid;
6207 WARN_ON(byte_in_group > cache->key.offset);
6209 spin_lock(&cache->space_info->lock);
6210 spin_lock(&cache->lock);
6212 if (btrfs_test_opt(info, SPACE_CACHE) &&
6213 cache->disk_cache_state < BTRFS_DC_CLEAR)
6214 cache->disk_cache_state = BTRFS_DC_CLEAR;
6216 old_val = btrfs_block_group_used(&cache->item);
6217 num_bytes = min(total, cache->key.offset - byte_in_group);
6219 old_val += num_bytes;
6220 btrfs_set_block_group_used(&cache->item, old_val);
6221 cache->reserved -= num_bytes;
6222 cache->space_info->bytes_reserved -= num_bytes;
6223 cache->space_info->bytes_used += num_bytes;
6224 cache->space_info->disk_used += num_bytes * factor;
6225 spin_unlock(&cache->lock);
6226 spin_unlock(&cache->space_info->lock);
6228 old_val -= num_bytes;
6229 btrfs_set_block_group_used(&cache->item, old_val);
6230 cache->pinned += num_bytes;
6231 cache->space_info->bytes_pinned += num_bytes;
6232 cache->space_info->bytes_used -= num_bytes;
6233 cache->space_info->disk_used -= num_bytes * factor;
6234 spin_unlock(&cache->lock);
6235 spin_unlock(&cache->space_info->lock);
6237 trace_btrfs_space_reservation(info, "pinned",
6238 cache->space_info->flags,
6240 set_extent_dirty(info->pinned_extents,
6241 bytenr, bytenr + num_bytes - 1,
6242 GFP_NOFS | __GFP_NOFAIL);
6245 spin_lock(&trans->transaction->dirty_bgs_lock);
6246 if (list_empty(&cache->dirty_list)) {
6247 list_add_tail(&cache->dirty_list,
6248 &trans->transaction->dirty_bgs);
6249 trans->transaction->num_dirty_bgs++;
6250 btrfs_get_block_group(cache);
6252 spin_unlock(&trans->transaction->dirty_bgs_lock);
6255 * No longer have used bytes in this block group, queue it for
6256 * deletion. We do this after adding the block group to the
6257 * dirty list to avoid races between cleaner kthread and space
6260 if (!alloc && old_val == 0) {
6261 spin_lock(&info->unused_bgs_lock);
6262 if (list_empty(&cache->bg_list)) {
6263 btrfs_get_block_group(cache);
6264 list_add_tail(&cache->bg_list,
6267 spin_unlock(&info->unused_bgs_lock);
6270 btrfs_put_block_group(cache);
6272 bytenr += num_bytes;
6277 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
6279 struct btrfs_block_group_cache *cache;
6282 spin_lock(&fs_info->block_group_cache_lock);
6283 bytenr = fs_info->first_logical_byte;
6284 spin_unlock(&fs_info->block_group_cache_lock);
6286 if (bytenr < (u64)-1)
6289 cache = btrfs_lookup_first_block_group(fs_info, search_start);
6293 bytenr = cache->key.objectid;
6294 btrfs_put_block_group(cache);
6299 static int pin_down_extent(struct btrfs_fs_info *fs_info,
6300 struct btrfs_block_group_cache *cache,
6301 u64 bytenr, u64 num_bytes, int reserved)
6303 spin_lock(&cache->space_info->lock);
6304 spin_lock(&cache->lock);
6305 cache->pinned += num_bytes;
6306 cache->space_info->bytes_pinned += num_bytes;
6308 cache->reserved -= num_bytes;
6309 cache->space_info->bytes_reserved -= num_bytes;
6311 spin_unlock(&cache->lock);
6312 spin_unlock(&cache->space_info->lock);
6314 trace_btrfs_space_reservation(fs_info, "pinned",
6315 cache->space_info->flags, num_bytes, 1);
6316 set_extent_dirty(fs_info->pinned_extents, bytenr,
6317 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6322 * this function must be called within transaction
6324 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
6325 u64 bytenr, u64 num_bytes, int reserved)
6327 struct btrfs_block_group_cache *cache;
6329 cache = btrfs_lookup_block_group(fs_info, bytenr);
6330 BUG_ON(!cache); /* Logic error */
6332 pin_down_extent(fs_info, cache, bytenr, num_bytes, reserved);
6334 btrfs_put_block_group(cache);
6339 * this function must be called within transaction
6341 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
6342 u64 bytenr, u64 num_bytes)
6344 struct btrfs_block_group_cache *cache;
6347 cache = btrfs_lookup_block_group(fs_info, bytenr);
6352 * pull in the free space cache (if any) so that our pin
6353 * removes the free space from the cache. We have load_only set
6354 * to one because the slow code to read in the free extents does check
6355 * the pinned extents.
6357 cache_block_group(cache, 1);
6359 pin_down_extent(fs_info, cache, bytenr, num_bytes, 0);
6361 /* remove us from the free space cache (if we're there at all) */
6362 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6363 btrfs_put_block_group(cache);
6367 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
6368 u64 start, u64 num_bytes)
6371 struct btrfs_block_group_cache *block_group;
6372 struct btrfs_caching_control *caching_ctl;
6374 block_group = btrfs_lookup_block_group(fs_info, start);
6378 cache_block_group(block_group, 0);
6379 caching_ctl = get_caching_control(block_group);
6383 BUG_ON(!block_group_cache_done(block_group));
6384 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6386 mutex_lock(&caching_ctl->mutex);
6388 if (start >= caching_ctl->progress) {
6389 ret = add_excluded_extent(fs_info, start, num_bytes);
6390 } else if (start + num_bytes <= caching_ctl->progress) {
6391 ret = btrfs_remove_free_space(block_group,
6394 num_bytes = caching_ctl->progress - start;
6395 ret = btrfs_remove_free_space(block_group,
6400 num_bytes = (start + num_bytes) -
6401 caching_ctl->progress;
6402 start = caching_ctl->progress;
6403 ret = add_excluded_extent(fs_info, start, num_bytes);
6406 mutex_unlock(&caching_ctl->mutex);
6407 put_caching_control(caching_ctl);
6409 btrfs_put_block_group(block_group);
6413 int btrfs_exclude_logged_extents(struct btrfs_fs_info *fs_info,
6414 struct extent_buffer *eb)
6416 struct btrfs_file_extent_item *item;
6417 struct btrfs_key key;
6421 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
6424 for (i = 0; i < btrfs_header_nritems(eb); i++) {
6425 btrfs_item_key_to_cpu(eb, &key, i);
6426 if (key.type != BTRFS_EXTENT_DATA_KEY)
6428 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6429 found_type = btrfs_file_extent_type(eb, item);
6430 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6432 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6434 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6435 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6436 __exclude_logged_extent(fs_info, key.objectid, key.offset);
6443 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6445 atomic_inc(&bg->reservations);
6448 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6451 struct btrfs_block_group_cache *bg;
6453 bg = btrfs_lookup_block_group(fs_info, start);
6455 if (atomic_dec_and_test(&bg->reservations))
6456 wake_up_atomic_t(&bg->reservations);
6457 btrfs_put_block_group(bg);
6460 static int btrfs_wait_bg_reservations_atomic_t(atomic_t *a)
6466 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6468 struct btrfs_space_info *space_info = bg->space_info;
6472 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6476 * Our block group is read only but before we set it to read only,
6477 * some task might have had allocated an extent from it already, but it
6478 * has not yet created a respective ordered extent (and added it to a
6479 * root's list of ordered extents).
6480 * Therefore wait for any task currently allocating extents, since the
6481 * block group's reservations counter is incremented while a read lock
6482 * on the groups' semaphore is held and decremented after releasing
6483 * the read access on that semaphore and creating the ordered extent.
6485 down_write(&space_info->groups_sem);
6486 up_write(&space_info->groups_sem);
6488 wait_on_atomic_t(&bg->reservations,
6489 btrfs_wait_bg_reservations_atomic_t,
6490 TASK_UNINTERRUPTIBLE);
6494 * btrfs_add_reserved_bytes - update the block_group and space info counters
6495 * @cache: The cache we are manipulating
6496 * @ram_bytes: The number of bytes of file content, and will be same to
6497 * @num_bytes except for the compress path.
6498 * @num_bytes: The number of bytes in question
6499 * @delalloc: The blocks are allocated for the delalloc write
6501 * This is called by the allocator when it reserves space. If this is a
6502 * reservation and the block group has become read only we cannot make the
6503 * reservation and return -EAGAIN, otherwise this function always succeeds.
6505 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
6506 u64 ram_bytes, u64 num_bytes, int delalloc)
6508 struct btrfs_space_info *space_info = cache->space_info;
6511 spin_lock(&space_info->lock);
6512 spin_lock(&cache->lock);
6516 cache->reserved += num_bytes;
6517 space_info->bytes_reserved += num_bytes;
6519 trace_btrfs_space_reservation(cache->fs_info,
6520 "space_info", space_info->flags,
6522 space_info->bytes_may_use -= ram_bytes;
6524 cache->delalloc_bytes += num_bytes;
6526 spin_unlock(&cache->lock);
6527 spin_unlock(&space_info->lock);
6532 * btrfs_free_reserved_bytes - update the block_group and space info counters
6533 * @cache: The cache we are manipulating
6534 * @num_bytes: The number of bytes in question
6535 * @delalloc: The blocks are allocated for the delalloc write
6537 * This is called by somebody who is freeing space that was never actually used
6538 * on disk. For example if you reserve some space for a new leaf in transaction
6539 * A and before transaction A commits you free that leaf, you call this with
6540 * reserve set to 0 in order to clear the reservation.
6543 static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6544 u64 num_bytes, int delalloc)
6546 struct btrfs_space_info *space_info = cache->space_info;
6549 spin_lock(&space_info->lock);
6550 spin_lock(&cache->lock);
6552 space_info->bytes_readonly += num_bytes;
6553 cache->reserved -= num_bytes;
6554 space_info->bytes_reserved -= num_bytes;
6557 cache->delalloc_bytes -= num_bytes;
6558 spin_unlock(&cache->lock);
6559 spin_unlock(&space_info->lock);
6562 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
6564 struct btrfs_caching_control *next;
6565 struct btrfs_caching_control *caching_ctl;
6566 struct btrfs_block_group_cache *cache;
6568 down_write(&fs_info->commit_root_sem);
6570 list_for_each_entry_safe(caching_ctl, next,
6571 &fs_info->caching_block_groups, list) {
6572 cache = caching_ctl->block_group;
6573 if (block_group_cache_done(cache)) {
6574 cache->last_byte_to_unpin = (u64)-1;
6575 list_del_init(&caching_ctl->list);
6576 put_caching_control(caching_ctl);
6578 cache->last_byte_to_unpin = caching_ctl->progress;
6582 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6583 fs_info->pinned_extents = &fs_info->freed_extents[1];
6585 fs_info->pinned_extents = &fs_info->freed_extents[0];
6587 up_write(&fs_info->commit_root_sem);
6589 update_global_block_rsv(fs_info);
6593 * Returns the free cluster for the given space info and sets empty_cluster to
6594 * what it should be based on the mount options.
6596 static struct btrfs_free_cluster *
6597 fetch_cluster_info(struct btrfs_fs_info *fs_info,
6598 struct btrfs_space_info *space_info, u64 *empty_cluster)
6600 struct btrfs_free_cluster *ret = NULL;
6601 bool ssd = btrfs_test_opt(fs_info, SSD);
6604 if (btrfs_mixed_space_info(space_info))
6608 *empty_cluster = SZ_2M;
6609 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6610 ret = &fs_info->meta_alloc_cluster;
6612 *empty_cluster = SZ_64K;
6613 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && ssd) {
6614 ret = &fs_info->data_alloc_cluster;
6620 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
6622 const bool return_free_space)
6624 struct btrfs_block_group_cache *cache = NULL;
6625 struct btrfs_space_info *space_info;
6626 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6627 struct btrfs_free_cluster *cluster = NULL;
6629 u64 total_unpinned = 0;
6630 u64 empty_cluster = 0;
6633 while (start <= end) {
6636 start >= cache->key.objectid + cache->key.offset) {
6638 btrfs_put_block_group(cache);
6640 cache = btrfs_lookup_block_group(fs_info, start);
6641 BUG_ON(!cache); /* Logic error */
6643 cluster = fetch_cluster_info(fs_info,
6646 empty_cluster <<= 1;
6649 len = cache->key.objectid + cache->key.offset - start;
6650 len = min(len, end + 1 - start);
6652 if (start < cache->last_byte_to_unpin) {
6653 len = min(len, cache->last_byte_to_unpin - start);
6654 if (return_free_space)
6655 btrfs_add_free_space(cache, start, len);
6659 total_unpinned += len;
6660 space_info = cache->space_info;
6663 * If this space cluster has been marked as fragmented and we've
6664 * unpinned enough in this block group to potentially allow a
6665 * cluster to be created inside of it go ahead and clear the
6668 if (cluster && cluster->fragmented &&
6669 total_unpinned > empty_cluster) {
6670 spin_lock(&cluster->lock);
6671 cluster->fragmented = 0;
6672 spin_unlock(&cluster->lock);
6675 spin_lock(&space_info->lock);
6676 spin_lock(&cache->lock);
6677 cache->pinned -= len;
6678 space_info->bytes_pinned -= len;
6680 trace_btrfs_space_reservation(fs_info, "pinned",
6681 space_info->flags, len, 0);
6682 space_info->max_extent_size = 0;
6683 percpu_counter_add(&space_info->total_bytes_pinned, -len);
6685 space_info->bytes_readonly += len;
6688 spin_unlock(&cache->lock);
6689 if (!readonly && return_free_space &&
6690 global_rsv->space_info == space_info) {
6692 WARN_ON(!return_free_space);
6693 spin_lock(&global_rsv->lock);
6694 if (!global_rsv->full) {
6695 to_add = min(len, global_rsv->size -
6696 global_rsv->reserved);
6697 global_rsv->reserved += to_add;
6698 space_info->bytes_may_use += to_add;
6699 if (global_rsv->reserved >= global_rsv->size)
6700 global_rsv->full = 1;
6701 trace_btrfs_space_reservation(fs_info,
6707 spin_unlock(&global_rsv->lock);
6708 /* Add to any tickets we may have */
6710 space_info_add_new_bytes(fs_info, space_info,
6713 spin_unlock(&space_info->lock);
6717 btrfs_put_block_group(cache);
6721 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
6722 struct btrfs_fs_info *fs_info)
6724 struct btrfs_block_group_cache *block_group, *tmp;
6725 struct list_head *deleted_bgs;
6726 struct extent_io_tree *unpin;
6731 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6732 unpin = &fs_info->freed_extents[1];
6734 unpin = &fs_info->freed_extents[0];
6736 while (!trans->aborted) {
6737 mutex_lock(&fs_info->unused_bg_unpin_mutex);
6738 ret = find_first_extent_bit(unpin, 0, &start, &end,
6739 EXTENT_DIRTY, NULL);
6741 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6745 if (btrfs_test_opt(fs_info, DISCARD))
6746 ret = btrfs_discard_extent(fs_info, start,
6747 end + 1 - start, NULL);
6749 clear_extent_dirty(unpin, start, end);
6750 unpin_extent_range(fs_info, start, end, true);
6751 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6756 * Transaction is finished. We don't need the lock anymore. We
6757 * do need to clean up the block groups in case of a transaction
6760 deleted_bgs = &trans->transaction->deleted_bgs;
6761 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6765 if (!trans->aborted)
6766 ret = btrfs_discard_extent(fs_info,
6767 block_group->key.objectid,
6768 block_group->key.offset,
6771 list_del_init(&block_group->bg_list);
6772 btrfs_put_block_group_trimming(block_group);
6773 btrfs_put_block_group(block_group);
6776 const char *errstr = btrfs_decode_error(ret);
6778 "Discard failed while removing blockgroup: errno=%d %s\n",
6786 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
6787 u64 owner, u64 root_objectid)
6789 struct btrfs_space_info *space_info;
6792 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6793 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
6794 flags = BTRFS_BLOCK_GROUP_SYSTEM;
6796 flags = BTRFS_BLOCK_GROUP_METADATA;
6798 flags = BTRFS_BLOCK_GROUP_DATA;
6801 space_info = __find_space_info(fs_info, flags);
6802 BUG_ON(!space_info); /* Logic bug */
6803 percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
6807 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6808 struct btrfs_fs_info *info,
6809 struct btrfs_delayed_ref_node *node, u64 parent,
6810 u64 root_objectid, u64 owner_objectid,
6811 u64 owner_offset, int refs_to_drop,
6812 struct btrfs_delayed_extent_op *extent_op)
6814 struct btrfs_key key;
6815 struct btrfs_path *path;
6816 struct btrfs_root *extent_root = info->extent_root;
6817 struct extent_buffer *leaf;
6818 struct btrfs_extent_item *ei;
6819 struct btrfs_extent_inline_ref *iref;
6822 int extent_slot = 0;
6823 int found_extent = 0;
6827 u64 bytenr = node->bytenr;
6828 u64 num_bytes = node->num_bytes;
6830 bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
6832 path = btrfs_alloc_path();
6836 path->reada = READA_FORWARD;
6837 path->leave_spinning = 1;
6839 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6840 BUG_ON(!is_data && refs_to_drop != 1);
6843 skinny_metadata = 0;
6845 ret = lookup_extent_backref(trans, info, path, &iref,
6846 bytenr, num_bytes, parent,
6847 root_objectid, owner_objectid,
6850 extent_slot = path->slots[0];
6851 while (extent_slot >= 0) {
6852 btrfs_item_key_to_cpu(path->nodes[0], &key,
6854 if (key.objectid != bytenr)
6856 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6857 key.offset == num_bytes) {
6861 if (key.type == BTRFS_METADATA_ITEM_KEY &&
6862 key.offset == owner_objectid) {
6866 if (path->slots[0] - extent_slot > 5)
6870 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6871 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
6872 if (found_extent && item_size < sizeof(*ei))
6875 if (!found_extent) {
6877 ret = remove_extent_backref(trans, info, path, NULL,
6879 is_data, &last_ref);
6881 btrfs_abort_transaction(trans, ret);
6884 btrfs_release_path(path);
6885 path->leave_spinning = 1;
6887 key.objectid = bytenr;
6888 key.type = BTRFS_EXTENT_ITEM_KEY;
6889 key.offset = num_bytes;
6891 if (!is_data && skinny_metadata) {
6892 key.type = BTRFS_METADATA_ITEM_KEY;
6893 key.offset = owner_objectid;
6896 ret = btrfs_search_slot(trans, extent_root,
6898 if (ret > 0 && skinny_metadata && path->slots[0]) {
6900 * Couldn't find our skinny metadata item,
6901 * see if we have ye olde extent item.
6904 btrfs_item_key_to_cpu(path->nodes[0], &key,
6906 if (key.objectid == bytenr &&
6907 key.type == BTRFS_EXTENT_ITEM_KEY &&
6908 key.offset == num_bytes)
6912 if (ret > 0 && skinny_metadata) {
6913 skinny_metadata = false;
6914 key.objectid = bytenr;
6915 key.type = BTRFS_EXTENT_ITEM_KEY;
6916 key.offset = num_bytes;
6917 btrfs_release_path(path);
6918 ret = btrfs_search_slot(trans, extent_root,
6924 "umm, got %d back from search, was looking for %llu",
6927 btrfs_print_leaf(info, path->nodes[0]);
6930 btrfs_abort_transaction(trans, ret);
6933 extent_slot = path->slots[0];
6935 } else if (WARN_ON(ret == -ENOENT)) {
6936 btrfs_print_leaf(info, path->nodes[0]);
6938 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
6939 bytenr, parent, root_objectid, owner_objectid,
6941 btrfs_abort_transaction(trans, ret);
6944 btrfs_abort_transaction(trans, ret);
6948 leaf = path->nodes[0];
6949 item_size = btrfs_item_size_nr(leaf, extent_slot);
6950 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6951 if (item_size < sizeof(*ei)) {
6952 BUG_ON(found_extent || extent_slot != path->slots[0]);
6953 ret = convert_extent_item_v0(trans, info, path, owner_objectid,
6956 btrfs_abort_transaction(trans, ret);
6960 btrfs_release_path(path);
6961 path->leave_spinning = 1;
6963 key.objectid = bytenr;
6964 key.type = BTRFS_EXTENT_ITEM_KEY;
6965 key.offset = num_bytes;
6967 ret = btrfs_search_slot(trans, extent_root, &key, path,
6971 "umm, got %d back from search, was looking for %llu",
6973 btrfs_print_leaf(info, path->nodes[0]);
6976 btrfs_abort_transaction(trans, ret);
6980 extent_slot = path->slots[0];
6981 leaf = path->nodes[0];
6982 item_size = btrfs_item_size_nr(leaf, extent_slot);
6985 BUG_ON(item_size < sizeof(*ei));
6986 ei = btrfs_item_ptr(leaf, extent_slot,
6987 struct btrfs_extent_item);
6988 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
6989 key.type == BTRFS_EXTENT_ITEM_KEY) {
6990 struct btrfs_tree_block_info *bi;
6991 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
6992 bi = (struct btrfs_tree_block_info *)(ei + 1);
6993 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
6996 refs = btrfs_extent_refs(leaf, ei);
6997 if (refs < refs_to_drop) {
6999 "trying to drop %d refs but we only have %Lu for bytenr %Lu",
7000 refs_to_drop, refs, bytenr);
7002 btrfs_abort_transaction(trans, ret);
7005 refs -= refs_to_drop;
7009 __run_delayed_extent_op(extent_op, leaf, ei);
7011 * In the case of inline back ref, reference count will
7012 * be updated by remove_extent_backref
7015 BUG_ON(!found_extent);
7017 btrfs_set_extent_refs(leaf, ei, refs);
7018 btrfs_mark_buffer_dirty(leaf);
7021 ret = remove_extent_backref(trans, info, path,
7023 is_data, &last_ref);
7025 btrfs_abort_transaction(trans, ret);
7029 add_pinned_bytes(info, -num_bytes, owner_objectid,
7033 BUG_ON(is_data && refs_to_drop !=
7034 extent_data_ref_count(path, iref));
7036 BUG_ON(path->slots[0] != extent_slot);
7038 BUG_ON(path->slots[0] != extent_slot + 1);
7039 path->slots[0] = extent_slot;
7045 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
7048 btrfs_abort_transaction(trans, ret);
7051 btrfs_release_path(path);
7054 ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
7056 btrfs_abort_transaction(trans, ret);
7061 ret = add_to_free_space_tree(trans, info, bytenr, num_bytes);
7063 btrfs_abort_transaction(trans, ret);
7067 ret = update_block_group(trans, info, bytenr, num_bytes, 0);
7069 btrfs_abort_transaction(trans, ret);
7073 btrfs_release_path(path);
7076 btrfs_free_path(path);
7081 * when we free an block, it is possible (and likely) that we free the last
7082 * delayed ref for that extent as well. This searches the delayed ref tree for
7083 * a given extent, and if there are no other delayed refs to be processed, it
7084 * removes it from the tree.
7086 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
7089 struct btrfs_delayed_ref_head *head;
7090 struct btrfs_delayed_ref_root *delayed_refs;
7093 delayed_refs = &trans->transaction->delayed_refs;
7094 spin_lock(&delayed_refs->lock);
7095 head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
7097 goto out_delayed_unlock;
7099 spin_lock(&head->lock);
7100 if (!list_empty(&head->ref_list))
7103 if (head->extent_op) {
7104 if (!head->must_insert_reserved)
7106 btrfs_free_delayed_extent_op(head->extent_op);
7107 head->extent_op = NULL;
7111 * waiting for the lock here would deadlock. If someone else has it
7112 * locked they are already in the process of dropping it anyway
7114 if (!mutex_trylock(&head->mutex))
7118 * at this point we have a head with no other entries. Go
7119 * ahead and process it.
7121 head->node.in_tree = 0;
7122 rb_erase(&head->href_node, &delayed_refs->href_root);
7124 atomic_dec(&delayed_refs->num_entries);
7127 * we don't take a ref on the node because we're removing it from the
7128 * tree, so we just steal the ref the tree was holding.
7130 delayed_refs->num_heads--;
7131 if (head->processing == 0)
7132 delayed_refs->num_heads_ready--;
7133 head->processing = 0;
7134 spin_unlock(&head->lock);
7135 spin_unlock(&delayed_refs->lock);
7137 BUG_ON(head->extent_op);
7138 if (head->must_insert_reserved)
7141 mutex_unlock(&head->mutex);
7142 btrfs_put_delayed_ref(&head->node);
7145 spin_unlock(&head->lock);
7148 spin_unlock(&delayed_refs->lock);
7152 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
7153 struct btrfs_root *root,
7154 struct extent_buffer *buf,
7155 u64 parent, int last_ref)
7157 struct btrfs_fs_info *fs_info = root->fs_info;
7161 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7162 ret = btrfs_add_delayed_tree_ref(fs_info, trans,
7163 buf->start, buf->len,
7165 root->root_key.objectid,
7166 btrfs_header_level(buf),
7167 BTRFS_DROP_DELAYED_REF, NULL);
7168 BUG_ON(ret); /* -ENOMEM */
7174 if (btrfs_header_generation(buf) == trans->transid) {
7175 struct btrfs_block_group_cache *cache;
7177 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7178 ret = check_ref_cleanup(trans, buf->start);
7183 cache = btrfs_lookup_block_group(fs_info, buf->start);
7185 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
7186 pin_down_extent(fs_info, cache, buf->start,
7188 btrfs_put_block_group(cache);
7192 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
7194 btrfs_add_free_space(cache, buf->start, buf->len);
7195 btrfs_free_reserved_bytes(cache, buf->len, 0);
7196 btrfs_put_block_group(cache);
7197 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
7202 add_pinned_bytes(fs_info, buf->len, btrfs_header_level(buf),
7203 root->root_key.objectid);
7206 * Deleting the buffer, clear the corrupt flag since it doesn't matter
7209 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7212 /* Can return -ENOMEM */
7213 int btrfs_free_extent(struct btrfs_trans_handle *trans,
7214 struct btrfs_fs_info *fs_info,
7215 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
7216 u64 owner, u64 offset)
7220 if (btrfs_is_testing(fs_info))
7223 add_pinned_bytes(fs_info, num_bytes, owner, root_objectid);
7226 * tree log blocks never actually go into the extent allocation
7227 * tree, just update pinning info and exit early.
7229 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
7230 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
7231 /* unlocks the pinned mutex */
7232 btrfs_pin_extent(fs_info, bytenr, num_bytes, 1);
7234 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
7235 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
7237 parent, root_objectid, (int)owner,
7238 BTRFS_DROP_DELAYED_REF, NULL);
7240 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
7242 parent, root_objectid, owner,
7244 BTRFS_DROP_DELAYED_REF);
7250 * when we wait for progress in the block group caching, its because
7251 * our allocation attempt failed at least once. So, we must sleep
7252 * and let some progress happen before we try again.
7254 * This function will sleep at least once waiting for new free space to
7255 * show up, and then it will check the block group free space numbers
7256 * for our min num_bytes. Another option is to have it go ahead
7257 * and look in the rbtree for a free extent of a given size, but this
7260 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7261 * any of the information in this block group.
7263 static noinline void
7264 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7267 struct btrfs_caching_control *caching_ctl;
7269 caching_ctl = get_caching_control(cache);
7273 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
7274 (cache->free_space_ctl->free_space >= num_bytes));
7276 put_caching_control(caching_ctl);
7280 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7282 struct btrfs_caching_control *caching_ctl;
7285 caching_ctl = get_caching_control(cache);
7287 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
7289 wait_event(caching_ctl->wait, block_group_cache_done(cache));
7290 if (cache->cached == BTRFS_CACHE_ERROR)
7292 put_caching_control(caching_ctl);
7296 int __get_raid_index(u64 flags)
7298 if (flags & BTRFS_BLOCK_GROUP_RAID10)
7299 return BTRFS_RAID_RAID10;
7300 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
7301 return BTRFS_RAID_RAID1;
7302 else if (flags & BTRFS_BLOCK_GROUP_DUP)
7303 return BTRFS_RAID_DUP;
7304 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
7305 return BTRFS_RAID_RAID0;
7306 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
7307 return BTRFS_RAID_RAID5;
7308 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
7309 return BTRFS_RAID_RAID6;
7311 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
7314 int get_block_group_index(struct btrfs_block_group_cache *cache)
7316 return __get_raid_index(cache->flags);
7319 static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
7320 [BTRFS_RAID_RAID10] = "raid10",
7321 [BTRFS_RAID_RAID1] = "raid1",
7322 [BTRFS_RAID_DUP] = "dup",
7323 [BTRFS_RAID_RAID0] = "raid0",
7324 [BTRFS_RAID_SINGLE] = "single",
7325 [BTRFS_RAID_RAID5] = "raid5",
7326 [BTRFS_RAID_RAID6] = "raid6",
7329 static const char *get_raid_name(enum btrfs_raid_types type)
7331 if (type >= BTRFS_NR_RAID_TYPES)
7334 return btrfs_raid_type_names[type];
7337 enum btrfs_loop_type {
7338 LOOP_CACHING_NOWAIT = 0,
7339 LOOP_CACHING_WAIT = 1,
7340 LOOP_ALLOC_CHUNK = 2,
7341 LOOP_NO_EMPTY_SIZE = 3,
7345 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7349 down_read(&cache->data_rwsem);
7353 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7356 btrfs_get_block_group(cache);
7358 down_read(&cache->data_rwsem);
7361 static struct btrfs_block_group_cache *
7362 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7363 struct btrfs_free_cluster *cluster,
7366 struct btrfs_block_group_cache *used_bg = NULL;
7368 spin_lock(&cluster->refill_lock);
7370 used_bg = cluster->block_group;
7374 if (used_bg == block_group)
7377 btrfs_get_block_group(used_bg);
7382 if (down_read_trylock(&used_bg->data_rwsem))
7385 spin_unlock(&cluster->refill_lock);
7387 /* We should only have one-level nested. */
7388 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
7390 spin_lock(&cluster->refill_lock);
7391 if (used_bg == cluster->block_group)
7394 up_read(&used_bg->data_rwsem);
7395 btrfs_put_block_group(used_bg);
7400 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7404 up_read(&cache->data_rwsem);
7405 btrfs_put_block_group(cache);
7409 * walks the btree of allocated extents and find a hole of a given size.
7410 * The key ins is changed to record the hole:
7411 * ins->objectid == start position
7412 * ins->flags = BTRFS_EXTENT_ITEM_KEY
7413 * ins->offset == the size of the hole.
7414 * Any available blocks before search_start are skipped.
7416 * If there is no suitable free space, we will record the max size of
7417 * the free space extent currently.
7419 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
7420 u64 ram_bytes, u64 num_bytes, u64 empty_size,
7421 u64 hint_byte, struct btrfs_key *ins,
7422 u64 flags, int delalloc)
7425 struct btrfs_root *root = fs_info->extent_root;
7426 struct btrfs_free_cluster *last_ptr = NULL;
7427 struct btrfs_block_group_cache *block_group = NULL;
7428 u64 search_start = 0;
7429 u64 max_extent_size = 0;
7430 u64 empty_cluster = 0;
7431 struct btrfs_space_info *space_info;
7433 int index = __get_raid_index(flags);
7434 bool failed_cluster_refill = false;
7435 bool failed_alloc = false;
7436 bool use_cluster = true;
7437 bool have_caching_bg = false;
7438 bool orig_have_caching_bg = false;
7439 bool full_search = false;
7441 WARN_ON(num_bytes < fs_info->sectorsize);
7442 ins->type = BTRFS_EXTENT_ITEM_KEY;
7446 trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
7448 space_info = __find_space_info(fs_info, flags);
7450 btrfs_err(fs_info, "No space info for %llu", flags);
7455 * If our free space is heavily fragmented we may not be able to make
7456 * big contiguous allocations, so instead of doing the expensive search
7457 * for free space, simply return ENOSPC with our max_extent_size so we
7458 * can go ahead and search for a more manageable chunk.
7460 * If our max_extent_size is large enough for our allocation simply
7461 * disable clustering since we will likely not be able to find enough
7462 * space to create a cluster and induce latency trying.
7464 if (unlikely(space_info->max_extent_size)) {
7465 spin_lock(&space_info->lock);
7466 if (space_info->max_extent_size &&
7467 num_bytes > space_info->max_extent_size) {
7468 ins->offset = space_info->max_extent_size;
7469 spin_unlock(&space_info->lock);
7471 } else if (space_info->max_extent_size) {
7472 use_cluster = false;
7474 spin_unlock(&space_info->lock);
7477 last_ptr = fetch_cluster_info(fs_info, space_info, &empty_cluster);
7479 spin_lock(&last_ptr->lock);
7480 if (last_ptr->block_group)
7481 hint_byte = last_ptr->window_start;
7482 if (last_ptr->fragmented) {
7484 * We still set window_start so we can keep track of the
7485 * last place we found an allocation to try and save
7488 hint_byte = last_ptr->window_start;
7489 use_cluster = false;
7491 spin_unlock(&last_ptr->lock);
7494 search_start = max(search_start, first_logical_byte(fs_info, 0));
7495 search_start = max(search_start, hint_byte);
7496 if (search_start == hint_byte) {
7497 block_group = btrfs_lookup_block_group(fs_info, search_start);
7499 * we don't want to use the block group if it doesn't match our
7500 * allocation bits, or if its not cached.
7502 * However if we are re-searching with an ideal block group
7503 * picked out then we don't care that the block group is cached.
7505 if (block_group && block_group_bits(block_group, flags) &&
7506 block_group->cached != BTRFS_CACHE_NO) {
7507 down_read(&space_info->groups_sem);
7508 if (list_empty(&block_group->list) ||
7511 * someone is removing this block group,
7512 * we can't jump into the have_block_group
7513 * target because our list pointers are not
7516 btrfs_put_block_group(block_group);
7517 up_read(&space_info->groups_sem);
7519 index = get_block_group_index(block_group);
7520 btrfs_lock_block_group(block_group, delalloc);
7521 goto have_block_group;
7523 } else if (block_group) {
7524 btrfs_put_block_group(block_group);
7528 have_caching_bg = false;
7529 if (index == 0 || index == __get_raid_index(flags))
7531 down_read(&space_info->groups_sem);
7532 list_for_each_entry(block_group, &space_info->block_groups[index],
7537 btrfs_grab_block_group(block_group, delalloc);
7538 search_start = block_group->key.objectid;
7541 * this can happen if we end up cycling through all the
7542 * raid types, but we want to make sure we only allocate
7543 * for the proper type.
7545 if (!block_group_bits(block_group, flags)) {
7546 u64 extra = BTRFS_BLOCK_GROUP_DUP |
7547 BTRFS_BLOCK_GROUP_RAID1 |
7548 BTRFS_BLOCK_GROUP_RAID5 |
7549 BTRFS_BLOCK_GROUP_RAID6 |
7550 BTRFS_BLOCK_GROUP_RAID10;
7553 * if they asked for extra copies and this block group
7554 * doesn't provide them, bail. This does allow us to
7555 * fill raid0 from raid1.
7557 if ((flags & extra) && !(block_group->flags & extra))
7562 cached = block_group_cache_done(block_group);
7563 if (unlikely(!cached)) {
7564 have_caching_bg = true;
7565 ret = cache_block_group(block_group, 0);
7570 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7572 if (unlikely(block_group->ro))
7576 * Ok we want to try and use the cluster allocator, so
7579 if (last_ptr && use_cluster) {
7580 struct btrfs_block_group_cache *used_block_group;
7581 unsigned long aligned_cluster;
7583 * the refill lock keeps out other
7584 * people trying to start a new cluster
7586 used_block_group = btrfs_lock_cluster(block_group,
7589 if (!used_block_group)
7590 goto refill_cluster;
7592 if (used_block_group != block_group &&
7593 (used_block_group->ro ||
7594 !block_group_bits(used_block_group, flags)))
7595 goto release_cluster;
7597 offset = btrfs_alloc_from_cluster(used_block_group,
7600 used_block_group->key.objectid,
7603 /* we have a block, we're done */
7604 spin_unlock(&last_ptr->refill_lock);
7605 trace_btrfs_reserve_extent_cluster(fs_info,
7607 search_start, num_bytes);
7608 if (used_block_group != block_group) {
7609 btrfs_release_block_group(block_group,
7611 block_group = used_block_group;
7616 WARN_ON(last_ptr->block_group != used_block_group);
7618 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
7619 * set up a new clusters, so lets just skip it
7620 * and let the allocator find whatever block
7621 * it can find. If we reach this point, we
7622 * will have tried the cluster allocator
7623 * plenty of times and not have found
7624 * anything, so we are likely way too
7625 * fragmented for the clustering stuff to find
7628 * However, if the cluster is taken from the
7629 * current block group, release the cluster
7630 * first, so that we stand a better chance of
7631 * succeeding in the unclustered
7633 if (loop >= LOOP_NO_EMPTY_SIZE &&
7634 used_block_group != block_group) {
7635 spin_unlock(&last_ptr->refill_lock);
7636 btrfs_release_block_group(used_block_group,
7638 goto unclustered_alloc;
7642 * this cluster didn't work out, free it and
7645 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7647 if (used_block_group != block_group)
7648 btrfs_release_block_group(used_block_group,
7651 if (loop >= LOOP_NO_EMPTY_SIZE) {
7652 spin_unlock(&last_ptr->refill_lock);
7653 goto unclustered_alloc;
7656 aligned_cluster = max_t(unsigned long,
7657 empty_cluster + empty_size,
7658 block_group->full_stripe_len);
7660 /* allocate a cluster in this block group */
7661 ret = btrfs_find_space_cluster(fs_info, block_group,
7662 last_ptr, search_start,
7667 * now pull our allocation out of this
7670 offset = btrfs_alloc_from_cluster(block_group,
7676 /* we found one, proceed */
7677 spin_unlock(&last_ptr->refill_lock);
7678 trace_btrfs_reserve_extent_cluster(fs_info,
7679 block_group, search_start,
7683 } else if (!cached && loop > LOOP_CACHING_NOWAIT
7684 && !failed_cluster_refill) {
7685 spin_unlock(&last_ptr->refill_lock);
7687 failed_cluster_refill = true;
7688 wait_block_group_cache_progress(block_group,
7689 num_bytes + empty_cluster + empty_size);
7690 goto have_block_group;
7694 * at this point we either didn't find a cluster
7695 * or we weren't able to allocate a block from our
7696 * cluster. Free the cluster we've been trying
7697 * to use, and go to the next block group
7699 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7700 spin_unlock(&last_ptr->refill_lock);
7706 * We are doing an unclustered alloc, set the fragmented flag so
7707 * we don't bother trying to setup a cluster again until we get
7710 if (unlikely(last_ptr)) {
7711 spin_lock(&last_ptr->lock);
7712 last_ptr->fragmented = 1;
7713 spin_unlock(&last_ptr->lock);
7716 struct btrfs_free_space_ctl *ctl =
7717 block_group->free_space_ctl;
7719 spin_lock(&ctl->tree_lock);
7720 if (ctl->free_space <
7721 num_bytes + empty_cluster + empty_size) {
7722 if (ctl->free_space > max_extent_size)
7723 max_extent_size = ctl->free_space;
7724 spin_unlock(&ctl->tree_lock);
7727 spin_unlock(&ctl->tree_lock);
7730 offset = btrfs_find_space_for_alloc(block_group, search_start,
7731 num_bytes, empty_size,
7734 * If we didn't find a chunk, and we haven't failed on this
7735 * block group before, and this block group is in the middle of
7736 * caching and we are ok with waiting, then go ahead and wait
7737 * for progress to be made, and set failed_alloc to true.
7739 * If failed_alloc is true then we've already waited on this
7740 * block group once and should move on to the next block group.
7742 if (!offset && !failed_alloc && !cached &&
7743 loop > LOOP_CACHING_NOWAIT) {
7744 wait_block_group_cache_progress(block_group,
7745 num_bytes + empty_size);
7746 failed_alloc = true;
7747 goto have_block_group;
7748 } else if (!offset) {
7752 search_start = ALIGN(offset, fs_info->stripesize);
7754 /* move on to the next group */
7755 if (search_start + num_bytes >
7756 block_group->key.objectid + block_group->key.offset) {
7757 btrfs_add_free_space(block_group, offset, num_bytes);
7761 if (offset < search_start)
7762 btrfs_add_free_space(block_group, offset,
7763 search_start - offset);
7764 BUG_ON(offset > search_start);
7766 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7767 num_bytes, delalloc);
7768 if (ret == -EAGAIN) {
7769 btrfs_add_free_space(block_group, offset, num_bytes);
7772 btrfs_inc_block_group_reservations(block_group);
7774 /* we are all good, lets return */
7775 ins->objectid = search_start;
7776 ins->offset = num_bytes;
7778 trace_btrfs_reserve_extent(fs_info, block_group,
7779 search_start, num_bytes);
7780 btrfs_release_block_group(block_group, delalloc);
7783 failed_cluster_refill = false;
7784 failed_alloc = false;
7785 BUG_ON(index != get_block_group_index(block_group));
7786 btrfs_release_block_group(block_group, delalloc);
7788 up_read(&space_info->groups_sem);
7790 if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
7791 && !orig_have_caching_bg)
7792 orig_have_caching_bg = true;
7794 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
7797 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
7801 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7802 * caching kthreads as we move along
7803 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7804 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7805 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7808 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
7810 if (loop == LOOP_CACHING_NOWAIT) {
7812 * We want to skip the LOOP_CACHING_WAIT step if we
7813 * don't have any uncached bgs and we've already done a
7814 * full search through.
7816 if (orig_have_caching_bg || !full_search)
7817 loop = LOOP_CACHING_WAIT;
7819 loop = LOOP_ALLOC_CHUNK;
7824 if (loop == LOOP_ALLOC_CHUNK) {
7825 struct btrfs_trans_handle *trans;
7828 trans = current->journal_info;
7832 trans = btrfs_join_transaction(root);
7834 if (IS_ERR(trans)) {
7835 ret = PTR_ERR(trans);
7839 ret = do_chunk_alloc(trans, fs_info, flags,
7843 * If we can't allocate a new chunk we've already looped
7844 * through at least once, move on to the NO_EMPTY_SIZE
7848 loop = LOOP_NO_EMPTY_SIZE;
7851 * Do not bail out on ENOSPC since we
7852 * can do more things.
7854 if (ret < 0 && ret != -ENOSPC)
7855 btrfs_abort_transaction(trans, ret);
7859 btrfs_end_transaction(trans);
7864 if (loop == LOOP_NO_EMPTY_SIZE) {
7866 * Don't loop again if we already have no empty_size and
7869 if (empty_size == 0 &&
7870 empty_cluster == 0) {
7879 } else if (!ins->objectid) {
7881 } else if (ins->objectid) {
7882 if (!use_cluster && last_ptr) {
7883 spin_lock(&last_ptr->lock);
7884 last_ptr->window_start = ins->objectid;
7885 spin_unlock(&last_ptr->lock);
7890 if (ret == -ENOSPC) {
7891 spin_lock(&space_info->lock);
7892 space_info->max_extent_size = max_extent_size;
7893 spin_unlock(&space_info->lock);
7894 ins->offset = max_extent_size;
7899 static void dump_space_info(struct btrfs_fs_info *fs_info,
7900 struct btrfs_space_info *info, u64 bytes,
7901 int dump_block_groups)
7903 struct btrfs_block_group_cache *cache;
7906 spin_lock(&info->lock);
7907 btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
7909 info->total_bytes - btrfs_space_info_used(info, true),
7910 info->full ? "" : "not ");
7912 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
7913 info->total_bytes, info->bytes_used, info->bytes_pinned,
7914 info->bytes_reserved, info->bytes_may_use,
7915 info->bytes_readonly);
7916 spin_unlock(&info->lock);
7918 if (!dump_block_groups)
7921 down_read(&info->groups_sem);
7923 list_for_each_entry(cache, &info->block_groups[index], list) {
7924 spin_lock(&cache->lock);
7926 "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
7927 cache->key.objectid, cache->key.offset,
7928 btrfs_block_group_used(&cache->item), cache->pinned,
7929 cache->reserved, cache->ro ? "[readonly]" : "");
7930 btrfs_dump_free_space(cache, bytes);
7931 spin_unlock(&cache->lock);
7933 if (++index < BTRFS_NR_RAID_TYPES)
7935 up_read(&info->groups_sem);
7938 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
7939 u64 num_bytes, u64 min_alloc_size,
7940 u64 empty_size, u64 hint_byte,
7941 struct btrfs_key *ins, int is_data, int delalloc)
7943 struct btrfs_fs_info *fs_info = root->fs_info;
7944 bool final_tried = num_bytes == min_alloc_size;
7948 flags = btrfs_get_alloc_profile(root, is_data);
7950 WARN_ON(num_bytes < fs_info->sectorsize);
7951 ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
7952 hint_byte, ins, flags, delalloc);
7953 if (!ret && !is_data) {
7954 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
7955 } else if (ret == -ENOSPC) {
7956 if (!final_tried && ins->offset) {
7957 num_bytes = min(num_bytes >> 1, ins->offset);
7958 num_bytes = round_down(num_bytes,
7959 fs_info->sectorsize);
7960 num_bytes = max(num_bytes, min_alloc_size);
7961 ram_bytes = num_bytes;
7962 if (num_bytes == min_alloc_size)
7965 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
7966 struct btrfs_space_info *sinfo;
7968 sinfo = __find_space_info(fs_info, flags);
7970 "allocation failed flags %llu, wanted %llu",
7973 dump_space_info(fs_info, sinfo, num_bytes, 1);
7980 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7982 int pin, int delalloc)
7984 struct btrfs_block_group_cache *cache;
7987 cache = btrfs_lookup_block_group(fs_info, start);
7989 btrfs_err(fs_info, "Unable to find block group for %llu",
7995 pin_down_extent(fs_info, cache, start, len, 1);
7997 if (btrfs_test_opt(fs_info, DISCARD))
7998 ret = btrfs_discard_extent(fs_info, start, len, NULL);
7999 btrfs_add_free_space(cache, start, len);
8000 btrfs_free_reserved_bytes(cache, len, delalloc);
8001 trace_btrfs_reserved_extent_free(fs_info, start, len);
8004 btrfs_put_block_group(cache);
8008 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8009 u64 start, u64 len, int delalloc)
8011 return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
8014 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
8017 return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
8020 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8021 struct btrfs_fs_info *fs_info,
8022 u64 parent, u64 root_objectid,
8023 u64 flags, u64 owner, u64 offset,
8024 struct btrfs_key *ins, int ref_mod)
8027 struct btrfs_extent_item *extent_item;
8028 struct btrfs_extent_inline_ref *iref;
8029 struct btrfs_path *path;
8030 struct extent_buffer *leaf;
8035 type = BTRFS_SHARED_DATA_REF_KEY;
8037 type = BTRFS_EXTENT_DATA_REF_KEY;
8039 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
8041 path = btrfs_alloc_path();
8045 path->leave_spinning = 1;
8046 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8049 btrfs_free_path(path);
8053 leaf = path->nodes[0];
8054 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8055 struct btrfs_extent_item);
8056 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
8057 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8058 btrfs_set_extent_flags(leaf, extent_item,
8059 flags | BTRFS_EXTENT_FLAG_DATA);
8061 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8062 btrfs_set_extent_inline_ref_type(leaf, iref, type);
8064 struct btrfs_shared_data_ref *ref;
8065 ref = (struct btrfs_shared_data_ref *)(iref + 1);
8066 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8067 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
8069 struct btrfs_extent_data_ref *ref;
8070 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
8071 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
8072 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
8073 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
8074 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
8077 btrfs_mark_buffer_dirty(path->nodes[0]);
8078 btrfs_free_path(path);
8080 ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8085 ret = update_block_group(trans, fs_info, ins->objectid, ins->offset, 1);
8086 if (ret) { /* -ENOENT, logic error */
8087 btrfs_err(fs_info, "update block group failed for %llu %llu",
8088 ins->objectid, ins->offset);
8091 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
8095 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
8096 struct btrfs_fs_info *fs_info,
8097 u64 parent, u64 root_objectid,
8098 u64 flags, struct btrfs_disk_key *key,
8099 int level, struct btrfs_key *ins)
8102 struct btrfs_extent_item *extent_item;
8103 struct btrfs_tree_block_info *block_info;
8104 struct btrfs_extent_inline_ref *iref;
8105 struct btrfs_path *path;
8106 struct extent_buffer *leaf;
8107 u32 size = sizeof(*extent_item) + sizeof(*iref);
8108 u64 num_bytes = ins->offset;
8109 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8111 if (!skinny_metadata)
8112 size += sizeof(*block_info);
8114 path = btrfs_alloc_path();
8116 btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
8121 path->leave_spinning = 1;
8122 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8125 btrfs_free_path(path);
8126 btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
8131 leaf = path->nodes[0];
8132 extent_item = btrfs_item_ptr(leaf, path->slots[0],
8133 struct btrfs_extent_item);
8134 btrfs_set_extent_refs(leaf, extent_item, 1);
8135 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8136 btrfs_set_extent_flags(leaf, extent_item,
8137 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
8139 if (skinny_metadata) {
8140 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8141 num_bytes = fs_info->nodesize;
8143 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8144 btrfs_set_tree_block_key(leaf, block_info, key);
8145 btrfs_set_tree_block_level(leaf, block_info, level);
8146 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8150 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8151 btrfs_set_extent_inline_ref_type(leaf, iref,
8152 BTRFS_SHARED_BLOCK_REF_KEY);
8153 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8155 btrfs_set_extent_inline_ref_type(leaf, iref,
8156 BTRFS_TREE_BLOCK_REF_KEY);
8157 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
8160 btrfs_mark_buffer_dirty(leaf);
8161 btrfs_free_path(path);
8163 ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8168 ret = update_block_group(trans, fs_info, ins->objectid,
8169 fs_info->nodesize, 1);
8170 if (ret) { /* -ENOENT, logic error */
8171 btrfs_err(fs_info, "update block group failed for %llu %llu",
8172 ins->objectid, ins->offset);
8176 trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid,
8181 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8182 u64 root_objectid, u64 owner,
8183 u64 offset, u64 ram_bytes,
8184 struct btrfs_key *ins)
8186 struct btrfs_fs_info *fs_info = trans->fs_info;
8189 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
8191 ret = btrfs_add_delayed_data_ref(fs_info, trans, ins->objectid,
8193 root_objectid, owner, offset,
8194 ram_bytes, BTRFS_ADD_DELAYED_EXTENT);
8199 * this is used by the tree logging recovery code. It records that
8200 * an extent has been allocated and makes sure to clear the free
8201 * space cache bits as well
8203 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
8204 struct btrfs_fs_info *fs_info,
8205 u64 root_objectid, u64 owner, u64 offset,
8206 struct btrfs_key *ins)
8209 struct btrfs_block_group_cache *block_group;
8210 struct btrfs_space_info *space_info;
8213 * Mixed block groups will exclude before processing the log so we only
8214 * need to do the exclude dance if this fs isn't mixed.
8216 if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8217 ret = __exclude_logged_extent(fs_info, ins->objectid,
8223 block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8227 space_info = block_group->space_info;
8228 spin_lock(&space_info->lock);
8229 spin_lock(&block_group->lock);
8230 space_info->bytes_reserved += ins->offset;
8231 block_group->reserved += ins->offset;
8232 spin_unlock(&block_group->lock);
8233 spin_unlock(&space_info->lock);
8235 ret = alloc_reserved_file_extent(trans, fs_info, 0, root_objectid,
8236 0, owner, offset, ins, 1);
8237 btrfs_put_block_group(block_group);
8241 static struct extent_buffer *
8242 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
8243 u64 bytenr, int level)
8245 struct btrfs_fs_info *fs_info = root->fs_info;
8246 struct extent_buffer *buf;
8248 buf = btrfs_find_create_tree_block(fs_info, bytenr);
8252 btrfs_set_header_generation(buf, trans->transid);
8253 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
8254 btrfs_tree_lock(buf);
8255 clean_tree_block(fs_info, buf);
8256 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
8258 btrfs_set_lock_blocking(buf);
8259 set_extent_buffer_uptodate(buf);
8261 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8262 buf->log_index = root->log_transid % 2;
8264 * we allow two log transactions at a time, use different
8265 * EXENT bit to differentiate dirty pages.
8267 if (buf->log_index == 0)
8268 set_extent_dirty(&root->dirty_log_pages, buf->start,
8269 buf->start + buf->len - 1, GFP_NOFS);
8271 set_extent_new(&root->dirty_log_pages, buf->start,
8272 buf->start + buf->len - 1);
8274 buf->log_index = -1;
8275 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
8276 buf->start + buf->len - 1, GFP_NOFS);
8278 trans->dirty = true;
8279 /* this returns a buffer locked for blocking */
8283 static struct btrfs_block_rsv *
8284 use_block_rsv(struct btrfs_trans_handle *trans,
8285 struct btrfs_root *root, u32 blocksize)
8287 struct btrfs_fs_info *fs_info = root->fs_info;
8288 struct btrfs_block_rsv *block_rsv;
8289 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8291 bool global_updated = false;
8293 block_rsv = get_block_rsv(trans, root);
8295 if (unlikely(block_rsv->size == 0))
8298 ret = block_rsv_use_bytes(block_rsv, blocksize);
8302 if (block_rsv->failfast)
8303 return ERR_PTR(ret);
8305 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8306 global_updated = true;
8307 update_global_block_rsv(fs_info);
8311 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8312 static DEFINE_RATELIMIT_STATE(_rs,
8313 DEFAULT_RATELIMIT_INTERVAL * 10,
8314 /*DEFAULT_RATELIMIT_BURST*/ 1);
8315 if (__ratelimit(&_rs))
8317 "BTRFS: block rsv returned %d\n", ret);
8320 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8321 BTRFS_RESERVE_NO_FLUSH);
8325 * If we couldn't reserve metadata bytes try and use some from
8326 * the global reserve if its space type is the same as the global
8329 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8330 block_rsv->space_info == global_rsv->space_info) {
8331 ret = block_rsv_use_bytes(global_rsv, blocksize);
8335 return ERR_PTR(ret);
8338 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8339 struct btrfs_block_rsv *block_rsv, u32 blocksize)
8341 block_rsv_add_bytes(block_rsv, blocksize, 0);
8342 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
8346 * finds a free extent and does all the dirty work required for allocation
8347 * returns the tree buffer or an ERR_PTR on error.
8349 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
8350 struct btrfs_root *root,
8351 u64 parent, u64 root_objectid,
8352 const struct btrfs_disk_key *key,
8353 int level, u64 hint,
8356 struct btrfs_fs_info *fs_info = root->fs_info;
8357 struct btrfs_key ins;
8358 struct btrfs_block_rsv *block_rsv;
8359 struct extent_buffer *buf;
8360 struct btrfs_delayed_extent_op *extent_op;
8363 u32 blocksize = fs_info->nodesize;
8364 bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8366 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8367 if (btrfs_is_testing(fs_info)) {
8368 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
8371 root->alloc_bytenr += blocksize;
8376 block_rsv = use_block_rsv(trans, root, blocksize);
8377 if (IS_ERR(block_rsv))
8378 return ERR_CAST(block_rsv);
8380 ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
8381 empty_size, hint, &ins, 0, 0);
8385 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
8388 goto out_free_reserved;
8391 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8393 parent = ins.objectid;
8394 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8398 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
8399 extent_op = btrfs_alloc_delayed_extent_op();
8405 memcpy(&extent_op->key, key, sizeof(extent_op->key));
8407 memset(&extent_op->key, 0, sizeof(extent_op->key));
8408 extent_op->flags_to_set = flags;
8409 extent_op->update_key = skinny_metadata ? false : true;
8410 extent_op->update_flags = true;
8411 extent_op->is_data = false;
8412 extent_op->level = level;
8414 ret = btrfs_add_delayed_tree_ref(fs_info, trans,
8415 ins.objectid, ins.offset,
8416 parent, root_objectid, level,
8417 BTRFS_ADD_DELAYED_EXTENT,
8420 goto out_free_delayed;
8425 btrfs_free_delayed_extent_op(extent_op);
8427 free_extent_buffer(buf);
8429 btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
8431 unuse_block_rsv(fs_info, block_rsv, blocksize);
8432 return ERR_PTR(ret);
8435 struct walk_control {
8436 u64 refs[BTRFS_MAX_LEVEL];
8437 u64 flags[BTRFS_MAX_LEVEL];
8438 struct btrfs_key update_progress;
8449 #define DROP_REFERENCE 1
8450 #define UPDATE_BACKREF 2
8452 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8453 struct btrfs_root *root,
8454 struct walk_control *wc,
8455 struct btrfs_path *path)
8457 struct btrfs_fs_info *fs_info = root->fs_info;
8463 struct btrfs_key key;
8464 struct extent_buffer *eb;
8469 if (path->slots[wc->level] < wc->reada_slot) {
8470 wc->reada_count = wc->reada_count * 2 / 3;
8471 wc->reada_count = max(wc->reada_count, 2);
8473 wc->reada_count = wc->reada_count * 3 / 2;
8474 wc->reada_count = min_t(int, wc->reada_count,
8475 BTRFS_NODEPTRS_PER_BLOCK(fs_info));
8478 eb = path->nodes[wc->level];
8479 nritems = btrfs_header_nritems(eb);
8481 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8482 if (nread >= wc->reada_count)
8486 bytenr = btrfs_node_blockptr(eb, slot);
8487 generation = btrfs_node_ptr_generation(eb, slot);
8489 if (slot == path->slots[wc->level])
8492 if (wc->stage == UPDATE_BACKREF &&
8493 generation <= root->root_key.offset)
8496 /* We don't lock the tree block, it's OK to be racy here */
8497 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
8498 wc->level - 1, 1, &refs,
8500 /* We don't care about errors in readahead. */
8505 if (wc->stage == DROP_REFERENCE) {
8509 if (wc->level == 1 &&
8510 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8512 if (!wc->update_ref ||
8513 generation <= root->root_key.offset)
8515 btrfs_node_key_to_cpu(eb, &key, slot);
8516 ret = btrfs_comp_cpu_keys(&key,
8517 &wc->update_progress);
8521 if (wc->level == 1 &&
8522 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8526 readahead_tree_block(fs_info, bytenr);
8529 wc->reada_slot = slot;
8533 * helper to process tree block while walking down the tree.
8535 * when wc->stage == UPDATE_BACKREF, this function updates
8536 * back refs for pointers in the block.
8538 * NOTE: return value 1 means we should stop walking down.
8540 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8541 struct btrfs_root *root,
8542 struct btrfs_path *path,
8543 struct walk_control *wc, int lookup_info)
8545 struct btrfs_fs_info *fs_info = root->fs_info;
8546 int level = wc->level;
8547 struct extent_buffer *eb = path->nodes[level];
8548 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8551 if (wc->stage == UPDATE_BACKREF &&
8552 btrfs_header_owner(eb) != root->root_key.objectid)
8556 * when reference count of tree block is 1, it won't increase
8557 * again. once full backref flag is set, we never clear it.
8560 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8561 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8562 BUG_ON(!path->locks[level]);
8563 ret = btrfs_lookup_extent_info(trans, fs_info,
8564 eb->start, level, 1,
8567 BUG_ON(ret == -ENOMEM);
8570 BUG_ON(wc->refs[level] == 0);
8573 if (wc->stage == DROP_REFERENCE) {
8574 if (wc->refs[level] > 1)
8577 if (path->locks[level] && !wc->keep_locks) {
8578 btrfs_tree_unlock_rw(eb, path->locks[level]);
8579 path->locks[level] = 0;
8584 /* wc->stage == UPDATE_BACKREF */
8585 if (!(wc->flags[level] & flag)) {
8586 BUG_ON(!path->locks[level]);
8587 ret = btrfs_inc_ref(trans, root, eb, 1);
8588 BUG_ON(ret); /* -ENOMEM */
8589 ret = btrfs_dec_ref(trans, root, eb, 0);
8590 BUG_ON(ret); /* -ENOMEM */
8591 ret = btrfs_set_disk_extent_flags(trans, fs_info, eb->start,
8593 btrfs_header_level(eb), 0);
8594 BUG_ON(ret); /* -ENOMEM */
8595 wc->flags[level] |= flag;
8599 * the block is shared by multiple trees, so it's not good to
8600 * keep the tree lock
8602 if (path->locks[level] && level > 0) {
8603 btrfs_tree_unlock_rw(eb, path->locks[level]);
8604 path->locks[level] = 0;
8610 * helper to process tree block pointer.
8612 * when wc->stage == DROP_REFERENCE, this function checks
8613 * reference count of the block pointed to. if the block
8614 * is shared and we need update back refs for the subtree
8615 * rooted at the block, this function changes wc->stage to
8616 * UPDATE_BACKREF. if the block is shared and there is no
8617 * need to update back, this function drops the reference
8620 * NOTE: return value 1 means we should stop walking down.
8622 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8623 struct btrfs_root *root,
8624 struct btrfs_path *path,
8625 struct walk_control *wc, int *lookup_info)
8627 struct btrfs_fs_info *fs_info = root->fs_info;
8632 struct btrfs_key key;
8633 struct extent_buffer *next;
8634 int level = wc->level;
8637 bool need_account = false;
8639 generation = btrfs_node_ptr_generation(path->nodes[level],
8640 path->slots[level]);
8642 * if the lower level block was created before the snapshot
8643 * was created, we know there is no need to update back refs
8646 if (wc->stage == UPDATE_BACKREF &&
8647 generation <= root->root_key.offset) {
8652 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8653 blocksize = fs_info->nodesize;
8655 next = find_extent_buffer(fs_info, bytenr);
8657 next = btrfs_find_create_tree_block(fs_info, bytenr);
8659 return PTR_ERR(next);
8661 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8665 btrfs_tree_lock(next);
8666 btrfs_set_lock_blocking(next);
8668 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
8669 &wc->refs[level - 1],
8670 &wc->flags[level - 1]);
8674 if (unlikely(wc->refs[level - 1] == 0)) {
8675 btrfs_err(fs_info, "Missing references.");
8681 if (wc->stage == DROP_REFERENCE) {
8682 if (wc->refs[level - 1] > 1) {
8683 need_account = true;
8685 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8688 if (!wc->update_ref ||
8689 generation <= root->root_key.offset)
8692 btrfs_node_key_to_cpu(path->nodes[level], &key,
8693 path->slots[level]);
8694 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8698 wc->stage = UPDATE_BACKREF;
8699 wc->shared_level = level - 1;
8703 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8707 if (!btrfs_buffer_uptodate(next, generation, 0)) {
8708 btrfs_tree_unlock(next);
8709 free_extent_buffer(next);
8715 if (reada && level == 1)
8716 reada_walk_down(trans, root, wc, path);
8717 next = read_tree_block(fs_info, bytenr, generation);
8719 return PTR_ERR(next);
8720 } else if (!extent_buffer_uptodate(next)) {
8721 free_extent_buffer(next);
8724 btrfs_tree_lock(next);
8725 btrfs_set_lock_blocking(next);
8729 ASSERT(level == btrfs_header_level(next));
8730 if (level != btrfs_header_level(next)) {
8731 btrfs_err(root->fs_info, "mismatched level");
8735 path->nodes[level] = next;
8736 path->slots[level] = 0;
8737 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8743 wc->refs[level - 1] = 0;
8744 wc->flags[level - 1] = 0;
8745 if (wc->stage == DROP_REFERENCE) {
8746 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8747 parent = path->nodes[level]->start;
8749 ASSERT(root->root_key.objectid ==
8750 btrfs_header_owner(path->nodes[level]));
8751 if (root->root_key.objectid !=
8752 btrfs_header_owner(path->nodes[level])) {
8753 btrfs_err(root->fs_info,
8754 "mismatched block owner");
8762 ret = btrfs_qgroup_trace_subtree(trans, root, next,
8763 generation, level - 1);
8765 btrfs_err_rl(fs_info,
8766 "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
8770 ret = btrfs_free_extent(trans, fs_info, bytenr, blocksize,
8771 parent, root->root_key.objectid,
8781 btrfs_tree_unlock(next);
8782 free_extent_buffer(next);
8788 * helper to process tree block while walking up the tree.
8790 * when wc->stage == DROP_REFERENCE, this function drops
8791 * reference count on the block.
8793 * when wc->stage == UPDATE_BACKREF, this function changes
8794 * wc->stage back to DROP_REFERENCE if we changed wc->stage
8795 * to UPDATE_BACKREF previously while processing the block.
8797 * NOTE: return value 1 means we should stop walking up.
8799 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
8800 struct btrfs_root *root,
8801 struct btrfs_path *path,
8802 struct walk_control *wc)
8804 struct btrfs_fs_info *fs_info = root->fs_info;
8806 int level = wc->level;
8807 struct extent_buffer *eb = path->nodes[level];
8810 if (wc->stage == UPDATE_BACKREF) {
8811 BUG_ON(wc->shared_level < level);
8812 if (level < wc->shared_level)
8815 ret = find_next_key(path, level + 1, &wc->update_progress);
8819 wc->stage = DROP_REFERENCE;
8820 wc->shared_level = -1;
8821 path->slots[level] = 0;
8824 * check reference count again if the block isn't locked.
8825 * we should start walking down the tree again if reference
8828 if (!path->locks[level]) {
8830 btrfs_tree_lock(eb);
8831 btrfs_set_lock_blocking(eb);
8832 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8834 ret = btrfs_lookup_extent_info(trans, fs_info,
8835 eb->start, level, 1,
8839 btrfs_tree_unlock_rw(eb, path->locks[level]);
8840 path->locks[level] = 0;
8843 BUG_ON(wc->refs[level] == 0);
8844 if (wc->refs[level] == 1) {
8845 btrfs_tree_unlock_rw(eb, path->locks[level]);
8846 path->locks[level] = 0;
8852 /* wc->stage == DROP_REFERENCE */
8853 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
8855 if (wc->refs[level] == 1) {
8857 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8858 ret = btrfs_dec_ref(trans, root, eb, 1);
8860 ret = btrfs_dec_ref(trans, root, eb, 0);
8861 BUG_ON(ret); /* -ENOMEM */
8862 ret = btrfs_qgroup_trace_leaf_items(trans, fs_info, eb);
8864 btrfs_err_rl(fs_info,
8865 "error %d accounting leaf items. Quota is out of sync, rescan required.",
8869 /* make block locked assertion in clean_tree_block happy */
8870 if (!path->locks[level] &&
8871 btrfs_header_generation(eb) == trans->transid) {
8872 btrfs_tree_lock(eb);
8873 btrfs_set_lock_blocking(eb);
8874 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8876 clean_tree_block(fs_info, eb);
8879 if (eb == root->node) {
8880 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8883 BUG_ON(root->root_key.objectid !=
8884 btrfs_header_owner(eb));
8886 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8887 parent = path->nodes[level + 1]->start;
8889 BUG_ON(root->root_key.objectid !=
8890 btrfs_header_owner(path->nodes[level + 1]));
8893 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
8895 wc->refs[level] = 0;
8896 wc->flags[level] = 0;
8900 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8901 struct btrfs_root *root,
8902 struct btrfs_path *path,
8903 struct walk_control *wc)
8905 int level = wc->level;
8906 int lookup_info = 1;
8909 while (level >= 0) {
8910 ret = walk_down_proc(trans, root, path, wc, lookup_info);
8917 if (path->slots[level] >=
8918 btrfs_header_nritems(path->nodes[level]))
8921 ret = do_walk_down(trans, root, path, wc, &lookup_info);
8923 path->slots[level]++;
8932 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
8933 struct btrfs_root *root,
8934 struct btrfs_path *path,
8935 struct walk_control *wc, int max_level)
8937 int level = wc->level;
8940 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8941 while (level < max_level && path->nodes[level]) {
8943 if (path->slots[level] + 1 <
8944 btrfs_header_nritems(path->nodes[level])) {
8945 path->slots[level]++;
8948 ret = walk_up_proc(trans, root, path, wc);
8952 if (path->locks[level]) {
8953 btrfs_tree_unlock_rw(path->nodes[level],
8954 path->locks[level]);
8955 path->locks[level] = 0;
8957 free_extent_buffer(path->nodes[level]);
8958 path->nodes[level] = NULL;
8966 * drop a subvolume tree.
8968 * this function traverses the tree freeing any blocks that only
8969 * referenced by the tree.
8971 * when a shared tree block is found. this function decreases its
8972 * reference count by one. if update_ref is true, this function
8973 * also make sure backrefs for the shared block and all lower level
8974 * blocks are properly updated.
8976 * If called with for_reloc == 0, may exit early with -EAGAIN
8978 int btrfs_drop_snapshot(struct btrfs_root *root,
8979 struct btrfs_block_rsv *block_rsv, int update_ref,
8982 struct btrfs_fs_info *fs_info = root->fs_info;
8983 struct btrfs_path *path;
8984 struct btrfs_trans_handle *trans;
8985 struct btrfs_root *tree_root = fs_info->tree_root;
8986 struct btrfs_root_item *root_item = &root->root_item;
8987 struct walk_control *wc;
8988 struct btrfs_key key;
8992 bool root_dropped = false;
8994 btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
8996 path = btrfs_alloc_path();
9002 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9004 btrfs_free_path(path);
9009 trans = btrfs_start_transaction(tree_root, 0);
9010 if (IS_ERR(trans)) {
9011 err = PTR_ERR(trans);
9016 trans->block_rsv = block_rsv;
9018 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
9019 level = btrfs_header_level(root->node);
9020 path->nodes[level] = btrfs_lock_root_node(root);
9021 btrfs_set_lock_blocking(path->nodes[level]);
9022 path->slots[level] = 0;
9023 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9024 memset(&wc->update_progress, 0,
9025 sizeof(wc->update_progress));
9027 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
9028 memcpy(&wc->update_progress, &key,
9029 sizeof(wc->update_progress));
9031 level = root_item->drop_level;
9033 path->lowest_level = level;
9034 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
9035 path->lowest_level = 0;
9043 * unlock our path, this is safe because only this
9044 * function is allowed to delete this snapshot
9046 btrfs_unlock_up_safe(path, 0);
9048 level = btrfs_header_level(root->node);
9050 btrfs_tree_lock(path->nodes[level]);
9051 btrfs_set_lock_blocking(path->nodes[level]);
9052 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9054 ret = btrfs_lookup_extent_info(trans, fs_info,
9055 path->nodes[level]->start,
9056 level, 1, &wc->refs[level],
9062 BUG_ON(wc->refs[level] == 0);
9064 if (level == root_item->drop_level)
9067 btrfs_tree_unlock(path->nodes[level]);
9068 path->locks[level] = 0;
9069 WARN_ON(wc->refs[level] != 1);
9075 wc->shared_level = -1;
9076 wc->stage = DROP_REFERENCE;
9077 wc->update_ref = update_ref;
9079 wc->for_reloc = for_reloc;
9080 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9084 ret = walk_down_tree(trans, root, path, wc);
9090 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9097 BUG_ON(wc->stage != DROP_REFERENCE);
9101 if (wc->stage == DROP_REFERENCE) {
9103 btrfs_node_key(path->nodes[level],
9104 &root_item->drop_progress,
9105 path->slots[level]);
9106 root_item->drop_level = level;
9109 BUG_ON(wc->level == 0);
9110 if (btrfs_should_end_transaction(trans) ||
9111 (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
9112 ret = btrfs_update_root(trans, tree_root,
9116 btrfs_abort_transaction(trans, ret);
9121 btrfs_end_transaction_throttle(trans);
9122 if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
9123 btrfs_debug(fs_info,
9124 "drop snapshot early exit");
9129 trans = btrfs_start_transaction(tree_root, 0);
9130 if (IS_ERR(trans)) {
9131 err = PTR_ERR(trans);
9135 trans->block_rsv = block_rsv;
9138 btrfs_release_path(path);
9142 ret = btrfs_del_root(trans, tree_root, &root->root_key);
9144 btrfs_abort_transaction(trans, ret);
9148 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
9149 ret = btrfs_find_root(tree_root, &root->root_key, path,
9152 btrfs_abort_transaction(trans, ret);
9155 } else if (ret > 0) {
9156 /* if we fail to delete the orphan item this time
9157 * around, it'll get picked up the next time.
9159 * The most common failure here is just -ENOENT.
9161 btrfs_del_orphan_item(trans, tree_root,
9162 root->root_key.objectid);
9166 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
9167 btrfs_add_dropped_root(trans, root);
9169 free_extent_buffer(root->node);
9170 free_extent_buffer(root->commit_root);
9171 btrfs_put_fs_root(root);
9173 root_dropped = true;
9175 btrfs_end_transaction_throttle(trans);
9178 btrfs_free_path(path);
9181 * So if we need to stop dropping the snapshot for whatever reason we
9182 * need to make sure to add it back to the dead root list so that we
9183 * keep trying to do the work later. This also cleans up roots if we
9184 * don't have it in the radix (like when we recover after a power fail
9185 * or unmount) so we don't leak memory.
9187 if (!for_reloc && root_dropped == false)
9188 btrfs_add_dead_root(root);
9189 if (err && err != -EAGAIN)
9190 btrfs_handle_fs_error(fs_info, err, NULL);
9195 * drop subtree rooted at tree block 'node'.
9197 * NOTE: this function will unlock and release tree block 'node'
9198 * only used by relocation code
9200 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9201 struct btrfs_root *root,
9202 struct extent_buffer *node,
9203 struct extent_buffer *parent)
9205 struct btrfs_fs_info *fs_info = root->fs_info;
9206 struct btrfs_path *path;
9207 struct walk_control *wc;
9213 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9215 path = btrfs_alloc_path();
9219 wc = kzalloc(sizeof(*wc), GFP_NOFS);
9221 btrfs_free_path(path);
9225 btrfs_assert_tree_locked(parent);
9226 parent_level = btrfs_header_level(parent);
9227 extent_buffer_get(parent);
9228 path->nodes[parent_level] = parent;
9229 path->slots[parent_level] = btrfs_header_nritems(parent);
9231 btrfs_assert_tree_locked(node);
9232 level = btrfs_header_level(node);
9233 path->nodes[level] = node;
9234 path->slots[level] = 0;
9235 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9237 wc->refs[parent_level] = 1;
9238 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9240 wc->shared_level = -1;
9241 wc->stage = DROP_REFERENCE;
9245 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9248 wret = walk_down_tree(trans, root, path, wc);
9254 wret = walk_up_tree(trans, root, path, wc, parent_level);
9262 btrfs_free_path(path);
9266 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
9272 * if restripe for this chunk_type is on pick target profile and
9273 * return, otherwise do the usual balance
9275 stripped = get_restripe_target(fs_info, flags);
9277 return extended_to_chunk(stripped);
9279 num_devices = fs_info->fs_devices->rw_devices;
9281 stripped = BTRFS_BLOCK_GROUP_RAID0 |
9282 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
9283 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9285 if (num_devices == 1) {
9286 stripped |= BTRFS_BLOCK_GROUP_DUP;
9287 stripped = flags & ~stripped;
9289 /* turn raid0 into single device chunks */
9290 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9293 /* turn mirroring into duplication */
9294 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9295 BTRFS_BLOCK_GROUP_RAID10))
9296 return stripped | BTRFS_BLOCK_GROUP_DUP;
9298 /* they already had raid on here, just return */
9299 if (flags & stripped)
9302 stripped |= BTRFS_BLOCK_GROUP_DUP;
9303 stripped = flags & ~stripped;
9305 /* switch duplicated blocks with raid1 */
9306 if (flags & BTRFS_BLOCK_GROUP_DUP)
9307 return stripped | BTRFS_BLOCK_GROUP_RAID1;
9309 /* this is drive concat, leave it alone */
9315 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9317 struct btrfs_space_info *sinfo = cache->space_info;
9319 u64 min_allocable_bytes;
9323 * We need some metadata space and system metadata space for
9324 * allocating chunks in some corner cases until we force to set
9325 * it to be readonly.
9328 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9330 min_allocable_bytes = SZ_1M;
9332 min_allocable_bytes = 0;
9334 spin_lock(&sinfo->lock);
9335 spin_lock(&cache->lock);
9343 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9344 cache->bytes_super - btrfs_block_group_used(&cache->item);
9346 if (btrfs_space_info_used(sinfo, true) + num_bytes +
9347 min_allocable_bytes <= sinfo->total_bytes) {
9348 sinfo->bytes_readonly += num_bytes;
9350 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9354 spin_unlock(&cache->lock);
9355 spin_unlock(&sinfo->lock);
9359 int btrfs_inc_block_group_ro(struct btrfs_fs_info *fs_info,
9360 struct btrfs_block_group_cache *cache)
9363 struct btrfs_trans_handle *trans;
9368 trans = btrfs_join_transaction(fs_info->extent_root);
9370 return PTR_ERR(trans);
9373 * we're not allowed to set block groups readonly after the dirty
9374 * block groups cache has started writing. If it already started,
9375 * back off and let this transaction commit
9377 mutex_lock(&fs_info->ro_block_group_mutex);
9378 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
9379 u64 transid = trans->transid;
9381 mutex_unlock(&fs_info->ro_block_group_mutex);
9382 btrfs_end_transaction(trans);
9384 ret = btrfs_wait_for_commit(fs_info, transid);
9391 * if we are changing raid levels, try to allocate a corresponding
9392 * block group with the new raid level.
9394 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9395 if (alloc_flags != cache->flags) {
9396 ret = do_chunk_alloc(trans, fs_info, alloc_flags,
9399 * ENOSPC is allowed here, we may have enough space
9400 * already allocated at the new raid level to
9409 ret = inc_block_group_ro(cache, 0);
9412 alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
9413 ret = do_chunk_alloc(trans, fs_info, alloc_flags,
9417 ret = inc_block_group_ro(cache, 0);
9419 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9420 alloc_flags = update_block_group_flags(fs_info, cache->flags);
9421 mutex_lock(&fs_info->chunk_mutex);
9422 check_system_chunk(trans, fs_info, alloc_flags);
9423 mutex_unlock(&fs_info->chunk_mutex);
9425 mutex_unlock(&fs_info->ro_block_group_mutex);
9427 btrfs_end_transaction(trans);
9431 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
9432 struct btrfs_fs_info *fs_info, u64 type)
9434 u64 alloc_flags = get_alloc_profile(fs_info, type);
9436 return do_chunk_alloc(trans, fs_info, alloc_flags, CHUNK_ALLOC_FORCE);
9440 * helper to account the unused space of all the readonly block group in the
9441 * space_info. takes mirrors into account.
9443 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
9445 struct btrfs_block_group_cache *block_group;
9449 /* It's df, we don't care if it's racy */
9450 if (list_empty(&sinfo->ro_bgs))
9453 spin_lock(&sinfo->lock);
9454 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
9455 spin_lock(&block_group->lock);
9457 if (!block_group->ro) {
9458 spin_unlock(&block_group->lock);
9462 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
9463 BTRFS_BLOCK_GROUP_RAID10 |
9464 BTRFS_BLOCK_GROUP_DUP))
9469 free_bytes += (block_group->key.offset -
9470 btrfs_block_group_used(&block_group->item)) *
9473 spin_unlock(&block_group->lock);
9475 spin_unlock(&sinfo->lock);
9480 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
9482 struct btrfs_space_info *sinfo = cache->space_info;
9487 spin_lock(&sinfo->lock);
9488 spin_lock(&cache->lock);
9490 num_bytes = cache->key.offset - cache->reserved -
9491 cache->pinned - cache->bytes_super -
9492 btrfs_block_group_used(&cache->item);
9493 sinfo->bytes_readonly -= num_bytes;
9494 list_del_init(&cache->ro_list);
9496 spin_unlock(&cache->lock);
9497 spin_unlock(&sinfo->lock);
9501 * checks to see if its even possible to relocate this block group.
9503 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9504 * ok to go ahead and try.
9506 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
9508 struct btrfs_root *root = fs_info->extent_root;
9509 struct btrfs_block_group_cache *block_group;
9510 struct btrfs_space_info *space_info;
9511 struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
9512 struct btrfs_device *device;
9513 struct btrfs_trans_handle *trans;
9523 debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
9525 block_group = btrfs_lookup_block_group(fs_info, bytenr);
9527 /* odd, couldn't find the block group, leave it alone */
9531 "can't find block group for bytenr %llu",
9536 min_free = btrfs_block_group_used(&block_group->item);
9538 /* no bytes used, we're good */
9542 space_info = block_group->space_info;
9543 spin_lock(&space_info->lock);
9545 full = space_info->full;
9548 * if this is the last block group we have in this space, we can't
9549 * relocate it unless we're able to allocate a new chunk below.
9551 * Otherwise, we need to make sure we have room in the space to handle
9552 * all of the extents from this block group. If we can, we're good
9554 if ((space_info->total_bytes != block_group->key.offset) &&
9555 (btrfs_space_info_used(space_info, false) + min_free <
9556 space_info->total_bytes)) {
9557 spin_unlock(&space_info->lock);
9560 spin_unlock(&space_info->lock);
9563 * ok we don't have enough space, but maybe we have free space on our
9564 * devices to allocate new chunks for relocation, so loop through our
9565 * alloc devices and guess if we have enough space. if this block
9566 * group is going to be restriped, run checks against the target
9567 * profile instead of the current one.
9579 target = get_restripe_target(fs_info, block_group->flags);
9581 index = __get_raid_index(extended_to_chunk(target));
9584 * this is just a balance, so if we were marked as full
9585 * we know there is no space for a new chunk
9590 "no space to alloc new chunk for block group %llu",
9591 block_group->key.objectid);
9595 index = get_block_group_index(block_group);
9598 if (index == BTRFS_RAID_RAID10) {
9602 } else if (index == BTRFS_RAID_RAID1) {
9604 } else if (index == BTRFS_RAID_DUP) {
9607 } else if (index == BTRFS_RAID_RAID0) {
9608 dev_min = fs_devices->rw_devices;
9609 min_free = div64_u64(min_free, dev_min);
9612 /* We need to do this so that we can look at pending chunks */
9613 trans = btrfs_join_transaction(root);
9614 if (IS_ERR(trans)) {
9615 ret = PTR_ERR(trans);
9619 mutex_lock(&fs_info->chunk_mutex);
9620 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
9624 * check to make sure we can actually find a chunk with enough
9625 * space to fit our block group in.
9627 if (device->total_bytes > device->bytes_used + min_free &&
9628 !device->is_tgtdev_for_dev_replace) {
9629 ret = find_free_dev_extent(trans, device, min_free,
9634 if (dev_nr >= dev_min)
9640 if (debug && ret == -1)
9642 "no space to allocate a new chunk for block group %llu",
9643 block_group->key.objectid);
9644 mutex_unlock(&fs_info->chunk_mutex);
9645 btrfs_end_transaction(trans);
9647 btrfs_put_block_group(block_group);
9651 static int find_first_block_group(struct btrfs_fs_info *fs_info,
9652 struct btrfs_path *path,
9653 struct btrfs_key *key)
9655 struct btrfs_root *root = fs_info->extent_root;
9657 struct btrfs_key found_key;
9658 struct extent_buffer *leaf;
9661 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9666 slot = path->slots[0];
9667 leaf = path->nodes[0];
9668 if (slot >= btrfs_header_nritems(leaf)) {
9669 ret = btrfs_next_leaf(root, path);
9676 btrfs_item_key_to_cpu(leaf, &found_key, slot);
9678 if (found_key.objectid >= key->objectid &&
9679 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9680 struct extent_map_tree *em_tree;
9681 struct extent_map *em;
9683 em_tree = &root->fs_info->mapping_tree.map_tree;
9684 read_lock(&em_tree->lock);
9685 em = lookup_extent_mapping(em_tree, found_key.objectid,
9687 read_unlock(&em_tree->lock);
9690 "logical %llu len %llu found bg but no related chunk",
9691 found_key.objectid, found_key.offset);
9696 free_extent_map(em);
9705 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
9707 struct btrfs_block_group_cache *block_group;
9711 struct inode *inode;
9713 block_group = btrfs_lookup_first_block_group(info, last);
9714 while (block_group) {
9715 spin_lock(&block_group->lock);
9716 if (block_group->iref)
9718 spin_unlock(&block_group->lock);
9719 block_group = next_block_group(info, block_group);
9728 inode = block_group->inode;
9729 block_group->iref = 0;
9730 block_group->inode = NULL;
9731 spin_unlock(&block_group->lock);
9732 ASSERT(block_group->io_ctl.inode == NULL);
9734 last = block_group->key.objectid + block_group->key.offset;
9735 btrfs_put_block_group(block_group);
9739 int btrfs_free_block_groups(struct btrfs_fs_info *info)
9741 struct btrfs_block_group_cache *block_group;
9742 struct btrfs_space_info *space_info;
9743 struct btrfs_caching_control *caching_ctl;
9746 down_write(&info->commit_root_sem);
9747 while (!list_empty(&info->caching_block_groups)) {
9748 caching_ctl = list_entry(info->caching_block_groups.next,
9749 struct btrfs_caching_control, list);
9750 list_del(&caching_ctl->list);
9751 put_caching_control(caching_ctl);
9753 up_write(&info->commit_root_sem);
9755 spin_lock(&info->unused_bgs_lock);
9756 while (!list_empty(&info->unused_bgs)) {
9757 block_group = list_first_entry(&info->unused_bgs,
9758 struct btrfs_block_group_cache,
9760 list_del_init(&block_group->bg_list);
9761 btrfs_put_block_group(block_group);
9763 spin_unlock(&info->unused_bgs_lock);
9765 spin_lock(&info->block_group_cache_lock);
9766 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
9767 block_group = rb_entry(n, struct btrfs_block_group_cache,
9769 rb_erase(&block_group->cache_node,
9770 &info->block_group_cache_tree);
9771 RB_CLEAR_NODE(&block_group->cache_node);
9772 spin_unlock(&info->block_group_cache_lock);
9774 down_write(&block_group->space_info->groups_sem);
9775 list_del(&block_group->list);
9776 up_write(&block_group->space_info->groups_sem);
9778 if (block_group->cached == BTRFS_CACHE_STARTED)
9779 wait_block_group_cache_done(block_group);
9782 * We haven't cached this block group, which means we could
9783 * possibly have excluded extents on this block group.
9785 if (block_group->cached == BTRFS_CACHE_NO ||
9786 block_group->cached == BTRFS_CACHE_ERROR)
9787 free_excluded_extents(info, block_group);
9789 btrfs_remove_free_space_cache(block_group);
9790 ASSERT(list_empty(&block_group->dirty_list));
9791 ASSERT(list_empty(&block_group->io_list));
9792 ASSERT(list_empty(&block_group->bg_list));
9793 ASSERT(atomic_read(&block_group->count) == 1);
9794 btrfs_put_block_group(block_group);
9796 spin_lock(&info->block_group_cache_lock);
9798 spin_unlock(&info->block_group_cache_lock);
9800 /* now that all the block groups are freed, go through and
9801 * free all the space_info structs. This is only called during
9802 * the final stages of unmount, and so we know nobody is
9803 * using them. We call synchronize_rcu() once before we start,
9804 * just to be on the safe side.
9808 release_global_block_rsv(info);
9810 while (!list_empty(&info->space_info)) {
9813 space_info = list_entry(info->space_info.next,
9814 struct btrfs_space_info,
9818 * Do not hide this behind enospc_debug, this is actually
9819 * important and indicates a real bug if this happens.
9821 if (WARN_ON(space_info->bytes_pinned > 0 ||
9822 space_info->bytes_reserved > 0 ||
9823 space_info->bytes_may_use > 0))
9824 dump_space_info(info, space_info, 0, 0);
9825 list_del(&space_info->list);
9826 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
9827 struct kobject *kobj;
9828 kobj = space_info->block_group_kobjs[i];
9829 space_info->block_group_kobjs[i] = NULL;
9835 kobject_del(&space_info->kobj);
9836 kobject_put(&space_info->kobj);
9841 static void __link_block_group(struct btrfs_space_info *space_info,
9842 struct btrfs_block_group_cache *cache)
9844 int index = get_block_group_index(cache);
9847 down_write(&space_info->groups_sem);
9848 if (list_empty(&space_info->block_groups[index]))
9850 list_add_tail(&cache->list, &space_info->block_groups[index]);
9851 up_write(&space_info->groups_sem);
9854 struct raid_kobject *rkobj;
9857 rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
9860 rkobj->raid_type = index;
9861 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
9862 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
9863 "%s", get_raid_name(index));
9865 kobject_put(&rkobj->kobj);
9868 space_info->block_group_kobjs[index] = &rkobj->kobj;
9873 btrfs_warn(cache->fs_info,
9874 "failed to add kobject for block cache, ignoring");
9877 static struct btrfs_block_group_cache *
9878 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
9879 u64 start, u64 size)
9881 struct btrfs_block_group_cache *cache;
9883 cache = kzalloc(sizeof(*cache), GFP_NOFS);
9887 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
9889 if (!cache->free_space_ctl) {
9894 cache->key.objectid = start;
9895 cache->key.offset = size;
9896 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9898 cache->sectorsize = fs_info->sectorsize;
9899 cache->fs_info = fs_info;
9900 cache->full_stripe_len = btrfs_full_stripe_len(fs_info,
9901 &fs_info->mapping_tree,
9903 set_free_space_tree_thresholds(cache);
9905 atomic_set(&cache->count, 1);
9906 spin_lock_init(&cache->lock);
9907 init_rwsem(&cache->data_rwsem);
9908 INIT_LIST_HEAD(&cache->list);
9909 INIT_LIST_HEAD(&cache->cluster_list);
9910 INIT_LIST_HEAD(&cache->bg_list);
9911 INIT_LIST_HEAD(&cache->ro_list);
9912 INIT_LIST_HEAD(&cache->dirty_list);
9913 INIT_LIST_HEAD(&cache->io_list);
9914 btrfs_init_free_space_ctl(cache);
9915 atomic_set(&cache->trimming, 0);
9916 mutex_init(&cache->free_space_lock);
9921 int btrfs_read_block_groups(struct btrfs_fs_info *info)
9923 struct btrfs_path *path;
9925 struct btrfs_block_group_cache *cache;
9926 struct btrfs_space_info *space_info;
9927 struct btrfs_key key;
9928 struct btrfs_key found_key;
9929 struct extent_buffer *leaf;
9935 feature = btrfs_super_incompat_flags(info->super_copy);
9936 mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
9940 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9941 path = btrfs_alloc_path();
9944 path->reada = READA_FORWARD;
9946 cache_gen = btrfs_super_cache_generation(info->super_copy);
9947 if (btrfs_test_opt(info, SPACE_CACHE) &&
9948 btrfs_super_generation(info->super_copy) != cache_gen)
9950 if (btrfs_test_opt(info, CLEAR_CACHE))
9954 ret = find_first_block_group(info, path, &key);
9960 leaf = path->nodes[0];
9961 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9963 cache = btrfs_create_block_group_cache(info, found_key.objectid,
9972 * When we mount with old space cache, we need to
9973 * set BTRFS_DC_CLEAR and set dirty flag.
9975 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
9976 * truncate the old free space cache inode and
9978 * b) Setting 'dirty flag' makes sure that we flush
9979 * the new space cache info onto disk.
9981 if (btrfs_test_opt(info, SPACE_CACHE))
9982 cache->disk_cache_state = BTRFS_DC_CLEAR;
9985 read_extent_buffer(leaf, &cache->item,
9986 btrfs_item_ptr_offset(leaf, path->slots[0]),
9987 sizeof(cache->item));
9988 cache->flags = btrfs_block_group_flags(&cache->item);
9990 ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
9991 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
9993 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
9994 cache->key.objectid);
9999 key.objectid = found_key.objectid + found_key.offset;
10000 btrfs_release_path(path);
10003 * We need to exclude the super stripes now so that the space
10004 * info has super bytes accounted for, otherwise we'll think
10005 * we have more space than we actually do.
10007 ret = exclude_super_stripes(info, cache);
10010 * We may have excluded something, so call this just in
10013 free_excluded_extents(info, cache);
10014 btrfs_put_block_group(cache);
10019 * check for two cases, either we are full, and therefore
10020 * don't need to bother with the caching work since we won't
10021 * find any space, or we are empty, and we can just add all
10022 * the space in and be done with it. This saves us _alot_ of
10023 * time, particularly in the full case.
10025 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
10026 cache->last_byte_to_unpin = (u64)-1;
10027 cache->cached = BTRFS_CACHE_FINISHED;
10028 free_excluded_extents(info, cache);
10029 } else if (btrfs_block_group_used(&cache->item) == 0) {
10030 cache->last_byte_to_unpin = (u64)-1;
10031 cache->cached = BTRFS_CACHE_FINISHED;
10032 add_new_free_space(cache, info,
10033 found_key.objectid,
10034 found_key.objectid +
10036 free_excluded_extents(info, cache);
10039 ret = btrfs_add_block_group_cache(info, cache);
10041 btrfs_remove_free_space_cache(cache);
10042 btrfs_put_block_group(cache);
10046 trace_btrfs_add_block_group(info, cache, 0);
10047 ret = update_space_info(info, cache->flags, found_key.offset,
10048 btrfs_block_group_used(&cache->item),
10049 cache->bytes_super, &space_info);
10051 btrfs_remove_free_space_cache(cache);
10052 spin_lock(&info->block_group_cache_lock);
10053 rb_erase(&cache->cache_node,
10054 &info->block_group_cache_tree);
10055 RB_CLEAR_NODE(&cache->cache_node);
10056 spin_unlock(&info->block_group_cache_lock);
10057 btrfs_put_block_group(cache);
10061 cache->space_info = space_info;
10063 __link_block_group(space_info, cache);
10065 set_avail_alloc_bits(info, cache->flags);
10066 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
10067 inc_block_group_ro(cache, 1);
10068 } else if (btrfs_block_group_used(&cache->item) == 0) {
10069 spin_lock(&info->unused_bgs_lock);
10070 /* Should always be true but just in case. */
10071 if (list_empty(&cache->bg_list)) {
10072 btrfs_get_block_group(cache);
10073 list_add_tail(&cache->bg_list,
10074 &info->unused_bgs);
10076 spin_unlock(&info->unused_bgs_lock);
10080 list_for_each_entry_rcu(space_info, &info->space_info, list) {
10081 if (!(get_alloc_profile(info, space_info->flags) &
10082 (BTRFS_BLOCK_GROUP_RAID10 |
10083 BTRFS_BLOCK_GROUP_RAID1 |
10084 BTRFS_BLOCK_GROUP_RAID5 |
10085 BTRFS_BLOCK_GROUP_RAID6 |
10086 BTRFS_BLOCK_GROUP_DUP)))
10089 * avoid allocating from un-mirrored block group if there are
10090 * mirrored block groups.
10092 list_for_each_entry(cache,
10093 &space_info->block_groups[BTRFS_RAID_RAID0],
10095 inc_block_group_ro(cache, 1);
10096 list_for_each_entry(cache,
10097 &space_info->block_groups[BTRFS_RAID_SINGLE],
10099 inc_block_group_ro(cache, 1);
10102 init_global_block_rsv(info);
10105 btrfs_free_path(path);
10109 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
10110 struct btrfs_fs_info *fs_info)
10112 struct btrfs_block_group_cache *block_group, *tmp;
10113 struct btrfs_root *extent_root = fs_info->extent_root;
10114 struct btrfs_block_group_item item;
10115 struct btrfs_key key;
10117 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
10119 trans->can_flush_pending_bgs = false;
10120 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
10124 spin_lock(&block_group->lock);
10125 memcpy(&item, &block_group->item, sizeof(item));
10126 memcpy(&key, &block_group->key, sizeof(key));
10127 spin_unlock(&block_group->lock);
10129 ret = btrfs_insert_item(trans, extent_root, &key, &item,
10132 btrfs_abort_transaction(trans, ret);
10133 ret = btrfs_finish_chunk_alloc(trans, fs_info, key.objectid,
10136 btrfs_abort_transaction(trans, ret);
10137 add_block_group_free_space(trans, fs_info, block_group);
10138 /* already aborted the transaction if it failed. */
10140 list_del_init(&block_group->bg_list);
10142 trans->can_flush_pending_bgs = can_flush_pending_bgs;
10145 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
10146 struct btrfs_fs_info *fs_info, u64 bytes_used,
10147 u64 type, u64 chunk_objectid, u64 chunk_offset,
10150 struct btrfs_block_group_cache *cache;
10153 btrfs_set_log_full_commit(fs_info, trans);
10155 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
10159 btrfs_set_block_group_used(&cache->item, bytes_used);
10160 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
10161 btrfs_set_block_group_flags(&cache->item, type);
10163 cache->flags = type;
10164 cache->last_byte_to_unpin = (u64)-1;
10165 cache->cached = BTRFS_CACHE_FINISHED;
10166 cache->needs_free_space = 1;
10167 ret = exclude_super_stripes(fs_info, cache);
10170 * We may have excluded something, so call this just in
10173 free_excluded_extents(fs_info, cache);
10174 btrfs_put_block_group(cache);
10178 add_new_free_space(cache, fs_info, chunk_offset, chunk_offset + size);
10180 free_excluded_extents(fs_info, cache);
10182 #ifdef CONFIG_BTRFS_DEBUG
10183 if (btrfs_should_fragment_free_space(cache)) {
10184 u64 new_bytes_used = size - bytes_used;
10186 bytes_used += new_bytes_used >> 1;
10187 fragment_free_space(cache);
10191 * Call to ensure the corresponding space_info object is created and
10192 * assigned to our block group, but don't update its counters just yet.
10193 * We want our bg to be added to the rbtree with its ->space_info set.
10195 ret = update_space_info(fs_info, cache->flags, 0, 0, 0,
10196 &cache->space_info);
10198 btrfs_remove_free_space_cache(cache);
10199 btrfs_put_block_group(cache);
10203 ret = btrfs_add_block_group_cache(fs_info, cache);
10205 btrfs_remove_free_space_cache(cache);
10206 btrfs_put_block_group(cache);
10211 * Now that our block group has its ->space_info set and is inserted in
10212 * the rbtree, update the space info's counters.
10214 trace_btrfs_add_block_group(fs_info, cache, 1);
10215 ret = update_space_info(fs_info, cache->flags, size, bytes_used,
10216 cache->bytes_super, &cache->space_info);
10218 btrfs_remove_free_space_cache(cache);
10219 spin_lock(&fs_info->block_group_cache_lock);
10220 rb_erase(&cache->cache_node,
10221 &fs_info->block_group_cache_tree);
10222 RB_CLEAR_NODE(&cache->cache_node);
10223 spin_unlock(&fs_info->block_group_cache_lock);
10224 btrfs_put_block_group(cache);
10227 update_global_block_rsv(fs_info);
10229 __link_block_group(cache->space_info, cache);
10231 list_add_tail(&cache->bg_list, &trans->new_bgs);
10233 set_avail_alloc_bits(fs_info, type);
10237 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10239 u64 extra_flags = chunk_to_extended(flags) &
10240 BTRFS_EXTENDED_PROFILE_MASK;
10242 write_seqlock(&fs_info->profiles_lock);
10243 if (flags & BTRFS_BLOCK_GROUP_DATA)
10244 fs_info->avail_data_alloc_bits &= ~extra_flags;
10245 if (flags & BTRFS_BLOCK_GROUP_METADATA)
10246 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10247 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10248 fs_info->avail_system_alloc_bits &= ~extra_flags;
10249 write_sequnlock(&fs_info->profiles_lock);
10252 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
10253 struct btrfs_fs_info *fs_info, u64 group_start,
10254 struct extent_map *em)
10256 struct btrfs_root *root = fs_info->extent_root;
10257 struct btrfs_path *path;
10258 struct btrfs_block_group_cache *block_group;
10259 struct btrfs_free_cluster *cluster;
10260 struct btrfs_root *tree_root = fs_info->tree_root;
10261 struct btrfs_key key;
10262 struct inode *inode;
10263 struct kobject *kobj = NULL;
10267 struct btrfs_caching_control *caching_ctl = NULL;
10270 block_group = btrfs_lookup_block_group(fs_info, group_start);
10271 BUG_ON(!block_group);
10272 BUG_ON(!block_group->ro);
10275 * Free the reserved super bytes from this block group before
10278 free_excluded_extents(fs_info, block_group);
10280 memcpy(&key, &block_group->key, sizeof(key));
10281 index = get_block_group_index(block_group);
10282 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
10283 BTRFS_BLOCK_GROUP_RAID1 |
10284 BTRFS_BLOCK_GROUP_RAID10))
10289 /* make sure this block group isn't part of an allocation cluster */
10290 cluster = &fs_info->data_alloc_cluster;
10291 spin_lock(&cluster->refill_lock);
10292 btrfs_return_cluster_to_free_space(block_group, cluster);
10293 spin_unlock(&cluster->refill_lock);
10296 * make sure this block group isn't part of a metadata
10297 * allocation cluster
10299 cluster = &fs_info->meta_alloc_cluster;
10300 spin_lock(&cluster->refill_lock);
10301 btrfs_return_cluster_to_free_space(block_group, cluster);
10302 spin_unlock(&cluster->refill_lock);
10304 path = btrfs_alloc_path();
10311 * get the inode first so any iput calls done for the io_list
10312 * aren't the final iput (no unlinks allowed now)
10314 inode = lookup_free_space_inode(fs_info, block_group, path);
10316 mutex_lock(&trans->transaction->cache_write_mutex);
10318 * make sure our free spache cache IO is done before remove the
10321 spin_lock(&trans->transaction->dirty_bgs_lock);
10322 if (!list_empty(&block_group->io_list)) {
10323 list_del_init(&block_group->io_list);
10325 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10327 spin_unlock(&trans->transaction->dirty_bgs_lock);
10328 btrfs_wait_cache_io(trans, block_group, path);
10329 btrfs_put_block_group(block_group);
10330 spin_lock(&trans->transaction->dirty_bgs_lock);
10333 if (!list_empty(&block_group->dirty_list)) {
10334 list_del_init(&block_group->dirty_list);
10335 btrfs_put_block_group(block_group);
10337 spin_unlock(&trans->transaction->dirty_bgs_lock);
10338 mutex_unlock(&trans->transaction->cache_write_mutex);
10340 if (!IS_ERR(inode)) {
10341 ret = btrfs_orphan_add(trans, inode);
10343 btrfs_add_delayed_iput(inode);
10346 clear_nlink(inode);
10347 /* One for the block groups ref */
10348 spin_lock(&block_group->lock);
10349 if (block_group->iref) {
10350 block_group->iref = 0;
10351 block_group->inode = NULL;
10352 spin_unlock(&block_group->lock);
10355 spin_unlock(&block_group->lock);
10357 /* One for our lookup ref */
10358 btrfs_add_delayed_iput(inode);
10361 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10362 key.offset = block_group->key.objectid;
10365 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10369 btrfs_release_path(path);
10371 ret = btrfs_del_item(trans, tree_root, path);
10374 btrfs_release_path(path);
10377 spin_lock(&fs_info->block_group_cache_lock);
10378 rb_erase(&block_group->cache_node,
10379 &fs_info->block_group_cache_tree);
10380 RB_CLEAR_NODE(&block_group->cache_node);
10382 if (fs_info->first_logical_byte == block_group->key.objectid)
10383 fs_info->first_logical_byte = (u64)-1;
10384 spin_unlock(&fs_info->block_group_cache_lock);
10386 down_write(&block_group->space_info->groups_sem);
10388 * we must use list_del_init so people can check to see if they
10389 * are still on the list after taking the semaphore
10391 list_del_init(&block_group->list);
10392 if (list_empty(&block_group->space_info->block_groups[index])) {
10393 kobj = block_group->space_info->block_group_kobjs[index];
10394 block_group->space_info->block_group_kobjs[index] = NULL;
10395 clear_avail_alloc_bits(fs_info, block_group->flags);
10397 up_write(&block_group->space_info->groups_sem);
10403 if (block_group->has_caching_ctl)
10404 caching_ctl = get_caching_control(block_group);
10405 if (block_group->cached == BTRFS_CACHE_STARTED)
10406 wait_block_group_cache_done(block_group);
10407 if (block_group->has_caching_ctl) {
10408 down_write(&fs_info->commit_root_sem);
10409 if (!caching_ctl) {
10410 struct btrfs_caching_control *ctl;
10412 list_for_each_entry(ctl,
10413 &fs_info->caching_block_groups, list)
10414 if (ctl->block_group == block_group) {
10416 atomic_inc(&caching_ctl->count);
10421 list_del_init(&caching_ctl->list);
10422 up_write(&fs_info->commit_root_sem);
10424 /* Once for the caching bgs list and once for us. */
10425 put_caching_control(caching_ctl);
10426 put_caching_control(caching_ctl);
10430 spin_lock(&trans->transaction->dirty_bgs_lock);
10431 if (!list_empty(&block_group->dirty_list)) {
10434 if (!list_empty(&block_group->io_list)) {
10437 spin_unlock(&trans->transaction->dirty_bgs_lock);
10438 btrfs_remove_free_space_cache(block_group);
10440 spin_lock(&block_group->space_info->lock);
10441 list_del_init(&block_group->ro_list);
10443 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
10444 WARN_ON(block_group->space_info->total_bytes
10445 < block_group->key.offset);
10446 WARN_ON(block_group->space_info->bytes_readonly
10447 < block_group->key.offset);
10448 WARN_ON(block_group->space_info->disk_total
10449 < block_group->key.offset * factor);
10451 block_group->space_info->total_bytes -= block_group->key.offset;
10452 block_group->space_info->bytes_readonly -= block_group->key.offset;
10453 block_group->space_info->disk_total -= block_group->key.offset * factor;
10455 spin_unlock(&block_group->space_info->lock);
10457 memcpy(&key, &block_group->key, sizeof(key));
10459 mutex_lock(&fs_info->chunk_mutex);
10460 if (!list_empty(&em->list)) {
10461 /* We're in the transaction->pending_chunks list. */
10462 free_extent_map(em);
10464 spin_lock(&block_group->lock);
10465 block_group->removed = 1;
10467 * At this point trimming can't start on this block group, because we
10468 * removed the block group from the tree fs_info->block_group_cache_tree
10469 * so no one can't find it anymore and even if someone already got this
10470 * block group before we removed it from the rbtree, they have already
10471 * incremented block_group->trimming - if they didn't, they won't find
10472 * any free space entries because we already removed them all when we
10473 * called btrfs_remove_free_space_cache().
10475 * And we must not remove the extent map from the fs_info->mapping_tree
10476 * to prevent the same logical address range and physical device space
10477 * ranges from being reused for a new block group. This is because our
10478 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10479 * completely transactionless, so while it is trimming a range the
10480 * currently running transaction might finish and a new one start,
10481 * allowing for new block groups to be created that can reuse the same
10482 * physical device locations unless we take this special care.
10484 * There may also be an implicit trim operation if the file system
10485 * is mounted with -odiscard. The same protections must remain
10486 * in place until the extents have been discarded completely when
10487 * the transaction commit has completed.
10489 remove_em = (atomic_read(&block_group->trimming) == 0);
10491 * Make sure a trimmer task always sees the em in the pinned_chunks list
10492 * if it sees block_group->removed == 1 (needs to lock block_group->lock
10493 * before checking block_group->removed).
10497 * Our em might be in trans->transaction->pending_chunks which
10498 * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
10499 * and so is the fs_info->pinned_chunks list.
10501 * So at this point we must be holding the chunk_mutex to avoid
10502 * any races with chunk allocation (more specifically at
10503 * volumes.c:contains_pending_extent()), to ensure it always
10504 * sees the em, either in the pending_chunks list or in the
10505 * pinned_chunks list.
10507 list_move_tail(&em->list, &fs_info->pinned_chunks);
10509 spin_unlock(&block_group->lock);
10512 struct extent_map_tree *em_tree;
10514 em_tree = &fs_info->mapping_tree.map_tree;
10515 write_lock(&em_tree->lock);
10517 * The em might be in the pending_chunks list, so make sure the
10518 * chunk mutex is locked, since remove_extent_mapping() will
10519 * delete us from that list.
10521 remove_extent_mapping(em_tree, em);
10522 write_unlock(&em_tree->lock);
10523 /* once for the tree */
10524 free_extent_map(em);
10527 mutex_unlock(&fs_info->chunk_mutex);
10529 ret = remove_block_group_free_space(trans, fs_info, block_group);
10533 btrfs_put_block_group(block_group);
10534 btrfs_put_block_group(block_group);
10536 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10542 ret = btrfs_del_item(trans, root, path);
10544 btrfs_free_path(path);
10548 struct btrfs_trans_handle *
10549 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10550 const u64 chunk_offset)
10552 struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
10553 struct extent_map *em;
10554 struct map_lookup *map;
10555 unsigned int num_items;
10557 read_lock(&em_tree->lock);
10558 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10559 read_unlock(&em_tree->lock);
10560 ASSERT(em && em->start == chunk_offset);
10563 * We need to reserve 3 + N units from the metadata space info in order
10564 * to remove a block group (done at btrfs_remove_chunk() and at
10565 * btrfs_remove_block_group()), which are used for:
10567 * 1 unit for adding the free space inode's orphan (located in the tree
10569 * 1 unit for deleting the block group item (located in the extent
10571 * 1 unit for deleting the free space item (located in tree of tree
10573 * N units for deleting N device extent items corresponding to each
10574 * stripe (located in the device tree).
10576 * In order to remove a block group we also need to reserve units in the
10577 * system space info in order to update the chunk tree (update one or
10578 * more device items and remove one chunk item), but this is done at
10579 * btrfs_remove_chunk() through a call to check_system_chunk().
10581 map = em->map_lookup;
10582 num_items = 3 + map->num_stripes;
10583 free_extent_map(em);
10585 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
10590 * Process the unused_bgs list and remove any that don't have any allocated
10591 * space inside of them.
10593 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10595 struct btrfs_block_group_cache *block_group;
10596 struct btrfs_space_info *space_info;
10597 struct btrfs_trans_handle *trans;
10600 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
10603 spin_lock(&fs_info->unused_bgs_lock);
10604 while (!list_empty(&fs_info->unused_bgs)) {
10608 block_group = list_first_entry(&fs_info->unused_bgs,
10609 struct btrfs_block_group_cache,
10611 list_del_init(&block_group->bg_list);
10613 space_info = block_group->space_info;
10615 if (ret || btrfs_mixed_space_info(space_info)) {
10616 btrfs_put_block_group(block_group);
10619 spin_unlock(&fs_info->unused_bgs_lock);
10621 mutex_lock(&fs_info->delete_unused_bgs_mutex);
10623 /* Don't want to race with allocators so take the groups_sem */
10624 down_write(&space_info->groups_sem);
10625 spin_lock(&block_group->lock);
10626 if (block_group->reserved ||
10627 btrfs_block_group_used(&block_group->item) ||
10629 list_is_singular(&block_group->list)) {
10631 * We want to bail if we made new allocations or have
10632 * outstanding allocations in this block group. We do
10633 * the ro check in case balance is currently acting on
10634 * this block group.
10636 spin_unlock(&block_group->lock);
10637 up_write(&space_info->groups_sem);
10640 spin_unlock(&block_group->lock);
10642 /* We don't want to force the issue, only flip if it's ok. */
10643 ret = inc_block_group_ro(block_group, 0);
10644 up_write(&space_info->groups_sem);
10651 * Want to do this before we do anything else so we can recover
10652 * properly if we fail to join the transaction.
10654 trans = btrfs_start_trans_remove_block_group(fs_info,
10655 block_group->key.objectid);
10656 if (IS_ERR(trans)) {
10657 btrfs_dec_block_group_ro(block_group);
10658 ret = PTR_ERR(trans);
10663 * We could have pending pinned extents for this block group,
10664 * just delete them, we don't care about them anymore.
10666 start = block_group->key.objectid;
10667 end = start + block_group->key.offset - 1;
10669 * Hold the unused_bg_unpin_mutex lock to avoid racing with
10670 * btrfs_finish_extent_commit(). If we are at transaction N,
10671 * another task might be running finish_extent_commit() for the
10672 * previous transaction N - 1, and have seen a range belonging
10673 * to the block group in freed_extents[] before we were able to
10674 * clear the whole block group range from freed_extents[]. This
10675 * means that task can lookup for the block group after we
10676 * unpinned it from freed_extents[] and removed it, leading to
10677 * a BUG_ON() at btrfs_unpin_extent_range().
10679 mutex_lock(&fs_info->unused_bg_unpin_mutex);
10680 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
10683 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10684 btrfs_dec_block_group_ro(block_group);
10687 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
10690 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10691 btrfs_dec_block_group_ro(block_group);
10694 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10696 /* Reset pinned so btrfs_put_block_group doesn't complain */
10697 spin_lock(&space_info->lock);
10698 spin_lock(&block_group->lock);
10700 space_info->bytes_pinned -= block_group->pinned;
10701 space_info->bytes_readonly += block_group->pinned;
10702 percpu_counter_add(&space_info->total_bytes_pinned,
10703 -block_group->pinned);
10704 block_group->pinned = 0;
10706 spin_unlock(&block_group->lock);
10707 spin_unlock(&space_info->lock);
10709 /* DISCARD can flip during remount */
10710 trimming = btrfs_test_opt(fs_info, DISCARD);
10712 /* Implicit trim during transaction commit. */
10714 btrfs_get_block_group_trimming(block_group);
10717 * Btrfs_remove_chunk will abort the transaction if things go
10720 ret = btrfs_remove_chunk(trans, fs_info,
10721 block_group->key.objectid);
10725 btrfs_put_block_group_trimming(block_group);
10730 * If we're not mounted with -odiscard, we can just forget
10731 * about this block group. Otherwise we'll need to wait
10732 * until transaction commit to do the actual discard.
10735 spin_lock(&fs_info->unused_bgs_lock);
10737 * A concurrent scrub might have added us to the list
10738 * fs_info->unused_bgs, so use a list_move operation
10739 * to add the block group to the deleted_bgs list.
10741 list_move(&block_group->bg_list,
10742 &trans->transaction->deleted_bgs);
10743 spin_unlock(&fs_info->unused_bgs_lock);
10744 btrfs_get_block_group(block_group);
10747 btrfs_end_transaction(trans);
10749 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
10750 btrfs_put_block_group(block_group);
10751 spin_lock(&fs_info->unused_bgs_lock);
10753 spin_unlock(&fs_info->unused_bgs_lock);
10756 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
10758 struct btrfs_space_info *space_info;
10759 struct btrfs_super_block *disk_super;
10765 disk_super = fs_info->super_copy;
10766 if (!btrfs_super_root(disk_super))
10769 features = btrfs_super_incompat_flags(disk_super);
10770 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
10773 flags = BTRFS_BLOCK_GROUP_SYSTEM;
10774 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10779 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
10780 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10782 flags = BTRFS_BLOCK_GROUP_METADATA;
10783 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10787 flags = BTRFS_BLOCK_GROUP_DATA;
10788 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
10794 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
10795 u64 start, u64 end)
10797 return unpin_extent_range(fs_info, start, end, false);
10801 * It used to be that old block groups would be left around forever.
10802 * Iterating over them would be enough to trim unused space. Since we
10803 * now automatically remove them, we also need to iterate over unallocated
10806 * We don't want a transaction for this since the discard may take a
10807 * substantial amount of time. We don't require that a transaction be
10808 * running, but we do need to take a running transaction into account
10809 * to ensure that we're not discarding chunks that were released in
10810 * the current transaction.
10812 * Holding the chunks lock will prevent other threads from allocating
10813 * or releasing chunks, but it won't prevent a running transaction
10814 * from committing and releasing the memory that the pending chunks
10815 * list head uses. For that, we need to take a reference to the
10818 static int btrfs_trim_free_extents(struct btrfs_device *device,
10819 u64 minlen, u64 *trimmed)
10821 u64 start = 0, len = 0;
10826 /* Not writeable = nothing to do. */
10827 if (!device->writeable)
10830 /* No free space = nothing to do. */
10831 if (device->total_bytes <= device->bytes_used)
10837 struct btrfs_fs_info *fs_info = device->fs_info;
10838 struct btrfs_transaction *trans;
10841 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
10845 down_read(&fs_info->commit_root_sem);
10847 spin_lock(&fs_info->trans_lock);
10848 trans = fs_info->running_transaction;
10850 atomic_inc(&trans->use_count);
10851 spin_unlock(&fs_info->trans_lock);
10853 ret = find_free_dev_extent_start(trans, device, minlen, start,
10856 btrfs_put_transaction(trans);
10859 up_read(&fs_info->commit_root_sem);
10860 mutex_unlock(&fs_info->chunk_mutex);
10861 if (ret == -ENOSPC)
10866 ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
10867 up_read(&fs_info->commit_root_sem);
10868 mutex_unlock(&fs_info->chunk_mutex);
10876 if (fatal_signal_pending(current)) {
10877 ret = -ERESTARTSYS;
10887 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
10889 struct btrfs_block_group_cache *cache = NULL;
10890 struct btrfs_device *device;
10891 struct list_head *devices;
10896 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
10900 * try to trim all FS space, our block group may start from non-zero.
10902 if (range->len == total_bytes)
10903 cache = btrfs_lookup_first_block_group(fs_info, range->start);
10905 cache = btrfs_lookup_block_group(fs_info, range->start);
10908 if (cache->key.objectid >= (range->start + range->len)) {
10909 btrfs_put_block_group(cache);
10913 start = max(range->start, cache->key.objectid);
10914 end = min(range->start + range->len,
10915 cache->key.objectid + cache->key.offset);
10917 if (end - start >= range->minlen) {
10918 if (!block_group_cache_done(cache)) {
10919 ret = cache_block_group(cache, 0);
10921 btrfs_put_block_group(cache);
10924 ret = wait_block_group_cache_done(cache);
10926 btrfs_put_block_group(cache);
10930 ret = btrfs_trim_block_group(cache,
10936 trimmed += group_trimmed;
10938 btrfs_put_block_group(cache);
10943 cache = next_block_group(fs_info, cache);
10946 mutex_lock(&fs_info->fs_devices->device_list_mutex);
10947 devices = &fs_info->fs_devices->alloc_list;
10948 list_for_each_entry(device, devices, dev_alloc_list) {
10949 ret = btrfs_trim_free_extents(device, range->minlen,
10954 trimmed += group_trimmed;
10956 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
10958 range->len = trimmed;
10963 * btrfs_{start,end}_write_no_snapshoting() are similar to
10964 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
10965 * data into the page cache through nocow before the subvolume is snapshoted,
10966 * but flush the data into disk after the snapshot creation, or to prevent
10967 * operations while snapshoting is ongoing and that cause the snapshot to be
10968 * inconsistent (writes followed by expanding truncates for example).
10970 void btrfs_end_write_no_snapshoting(struct btrfs_root *root)
10972 percpu_counter_dec(&root->subv_writers->counter);
10974 * Make sure counter is updated before we wake up waiters.
10977 if (waitqueue_active(&root->subv_writers->wait))
10978 wake_up(&root->subv_writers->wait);
10981 int btrfs_start_write_no_snapshoting(struct btrfs_root *root)
10983 if (atomic_read(&root->will_be_snapshoted))
10986 percpu_counter_inc(&root->subv_writers->counter);
10988 * Make sure counter is updated before we check for snapshot creation.
10991 if (atomic_read(&root->will_be_snapshoted)) {
10992 btrfs_end_write_no_snapshoting(root);
10998 static int wait_snapshoting_atomic_t(atomic_t *a)
11004 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
11009 ret = btrfs_start_write_no_snapshoting(root);
11012 wait_on_atomic_t(&root->will_be_snapshoted,
11013 wait_snapshoting_atomic_t,
11014 TASK_UNINTERRUPTIBLE);