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>
31 #include "print-tree.h"
32 #include "transaction.h"
36 #include "free-space-cache.h"
39 #undef SCRAMBLE_DELAYED_REFS
42 * control flags for do_chunk_alloc's force field
43 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
44 * if we really need one.
46 * CHUNK_ALLOC_LIMITED means to only try and allocate one
47 * if we have very few chunks already allocated. This is
48 * used as part of the clustering code to help make sure
49 * we have a good pool of storage to cluster in, without
50 * filling the FS with empty chunks
52 * CHUNK_ALLOC_FORCE means it must try to allocate one
56 CHUNK_ALLOC_NO_FORCE = 0,
57 CHUNK_ALLOC_LIMITED = 1,
58 CHUNK_ALLOC_FORCE = 2,
62 * Control how reservations are dealt with.
64 * RESERVE_FREE - freeing a reservation.
65 * RESERVE_ALLOC - allocating space and we need to update bytes_may_use for
67 * RESERVE_ALLOC_NO_ACCOUNT - allocating space and we should not update
68 * bytes_may_use as the ENOSPC accounting is done elsewhere
73 RESERVE_ALLOC_NO_ACCOUNT = 2,
76 static int update_block_group(struct btrfs_root *root,
77 u64 bytenr, u64 num_bytes, int alloc);
78 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
79 struct btrfs_root *root,
80 u64 bytenr, u64 num_bytes, u64 parent,
81 u64 root_objectid, u64 owner_objectid,
82 u64 owner_offset, int refs_to_drop,
83 struct btrfs_delayed_extent_op *extra_op);
84 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
85 struct extent_buffer *leaf,
86 struct btrfs_extent_item *ei);
87 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
88 struct btrfs_root *root,
89 u64 parent, u64 root_objectid,
90 u64 flags, u64 owner, u64 offset,
91 struct btrfs_key *ins, int ref_mod);
92 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
93 struct btrfs_root *root,
94 u64 parent, u64 root_objectid,
95 u64 flags, struct btrfs_disk_key *key,
96 int level, struct btrfs_key *ins);
97 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
98 struct btrfs_root *extent_root, u64 flags,
100 static int find_next_key(struct btrfs_path *path, int level,
101 struct btrfs_key *key);
102 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
103 int dump_block_groups);
104 static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
105 u64 num_bytes, int reserve);
106 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
110 block_group_cache_done(struct btrfs_block_group_cache *cache)
113 return cache->cached == BTRFS_CACHE_FINISHED;
116 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
118 return (cache->flags & bits) == bits;
121 static void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
123 atomic_inc(&cache->count);
126 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
128 if (atomic_dec_and_test(&cache->count)) {
129 WARN_ON(cache->pinned > 0);
130 WARN_ON(cache->reserved > 0);
131 kfree(cache->free_space_ctl);
137 * this adds the block group to the fs_info rb tree for the block group
140 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
141 struct btrfs_block_group_cache *block_group)
144 struct rb_node *parent = NULL;
145 struct btrfs_block_group_cache *cache;
147 spin_lock(&info->block_group_cache_lock);
148 p = &info->block_group_cache_tree.rb_node;
152 cache = rb_entry(parent, struct btrfs_block_group_cache,
154 if (block_group->key.objectid < cache->key.objectid) {
156 } else if (block_group->key.objectid > cache->key.objectid) {
159 spin_unlock(&info->block_group_cache_lock);
164 rb_link_node(&block_group->cache_node, parent, p);
165 rb_insert_color(&block_group->cache_node,
166 &info->block_group_cache_tree);
168 if (info->first_logical_byte > block_group->key.objectid)
169 info->first_logical_byte = block_group->key.objectid;
171 spin_unlock(&info->block_group_cache_lock);
177 * This will return the block group at or after bytenr if contains is 0, else
178 * it will return the block group that contains the bytenr
180 static struct btrfs_block_group_cache *
181 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
184 struct btrfs_block_group_cache *cache, *ret = NULL;
188 spin_lock(&info->block_group_cache_lock);
189 n = info->block_group_cache_tree.rb_node;
192 cache = rb_entry(n, struct btrfs_block_group_cache,
194 end = cache->key.objectid + cache->key.offset - 1;
195 start = cache->key.objectid;
197 if (bytenr < start) {
198 if (!contains && (!ret || start < ret->key.objectid))
201 } else if (bytenr > start) {
202 if (contains && bytenr <= end) {
213 btrfs_get_block_group(ret);
214 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
215 info->first_logical_byte = ret->key.objectid;
217 spin_unlock(&info->block_group_cache_lock);
222 static int add_excluded_extent(struct btrfs_root *root,
223 u64 start, u64 num_bytes)
225 u64 end = start + num_bytes - 1;
226 set_extent_bits(&root->fs_info->freed_extents[0],
227 start, end, EXTENT_UPTODATE, GFP_NOFS);
228 set_extent_bits(&root->fs_info->freed_extents[1],
229 start, end, EXTENT_UPTODATE, GFP_NOFS);
233 static void free_excluded_extents(struct btrfs_root *root,
234 struct btrfs_block_group_cache *cache)
238 start = cache->key.objectid;
239 end = start + cache->key.offset - 1;
241 clear_extent_bits(&root->fs_info->freed_extents[0],
242 start, end, EXTENT_UPTODATE, GFP_NOFS);
243 clear_extent_bits(&root->fs_info->freed_extents[1],
244 start, end, EXTENT_UPTODATE, GFP_NOFS);
247 static int exclude_super_stripes(struct btrfs_root *root,
248 struct btrfs_block_group_cache *cache)
255 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
256 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
257 cache->bytes_super += stripe_len;
258 ret = add_excluded_extent(root, cache->key.objectid,
264 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
265 bytenr = btrfs_sb_offset(i);
266 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
267 cache->key.objectid, bytenr,
268 0, &logical, &nr, &stripe_len);
273 cache->bytes_super += stripe_len;
274 ret = add_excluded_extent(root, logical[nr],
287 static struct btrfs_caching_control *
288 get_caching_control(struct btrfs_block_group_cache *cache)
290 struct btrfs_caching_control *ctl;
292 spin_lock(&cache->lock);
293 if (cache->cached != BTRFS_CACHE_STARTED) {
294 spin_unlock(&cache->lock);
298 /* We're loading it the fast way, so we don't have a caching_ctl. */
299 if (!cache->caching_ctl) {
300 spin_unlock(&cache->lock);
304 ctl = cache->caching_ctl;
305 atomic_inc(&ctl->count);
306 spin_unlock(&cache->lock);
310 static void put_caching_control(struct btrfs_caching_control *ctl)
312 if (atomic_dec_and_test(&ctl->count))
317 * this is only called by cache_block_group, since we could have freed extents
318 * we need to check the pinned_extents for any extents that can't be used yet
319 * since their free space will be released as soon as the transaction commits.
321 static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
322 struct btrfs_fs_info *info, u64 start, u64 end)
324 u64 extent_start, extent_end, size, total_added = 0;
327 while (start < end) {
328 ret = find_first_extent_bit(info->pinned_extents, start,
329 &extent_start, &extent_end,
330 EXTENT_DIRTY | EXTENT_UPTODATE,
335 if (extent_start <= start) {
336 start = extent_end + 1;
337 } else if (extent_start > start && extent_start < end) {
338 size = extent_start - start;
340 ret = btrfs_add_free_space(block_group, start,
342 BUG_ON(ret); /* -ENOMEM or logic error */
343 start = extent_end + 1;
352 ret = btrfs_add_free_space(block_group, start, size);
353 BUG_ON(ret); /* -ENOMEM or logic error */
359 static noinline void caching_thread(struct btrfs_work *work)
361 struct btrfs_block_group_cache *block_group;
362 struct btrfs_fs_info *fs_info;
363 struct btrfs_caching_control *caching_ctl;
364 struct btrfs_root *extent_root;
365 struct btrfs_path *path;
366 struct extent_buffer *leaf;
367 struct btrfs_key key;
373 caching_ctl = container_of(work, struct btrfs_caching_control, work);
374 block_group = caching_ctl->block_group;
375 fs_info = block_group->fs_info;
376 extent_root = fs_info->extent_root;
378 path = btrfs_alloc_path();
382 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
385 * We don't want to deadlock with somebody trying to allocate a new
386 * extent for the extent root while also trying to search the extent
387 * root to add free space. So we skip locking and search the commit
388 * root, since its read-only
390 path->skip_locking = 1;
391 path->search_commit_root = 1;
396 key.type = BTRFS_EXTENT_ITEM_KEY;
398 mutex_lock(&caching_ctl->mutex);
399 /* need to make sure the commit_root doesn't disappear */
400 down_read(&fs_info->extent_commit_sem);
402 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
406 leaf = path->nodes[0];
407 nritems = btrfs_header_nritems(leaf);
410 if (btrfs_fs_closing(fs_info) > 1) {
415 if (path->slots[0] < nritems) {
416 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
418 ret = find_next_key(path, 0, &key);
422 if (need_resched() ||
423 btrfs_next_leaf(extent_root, path)) {
424 caching_ctl->progress = last;
425 btrfs_release_path(path);
426 up_read(&fs_info->extent_commit_sem);
427 mutex_unlock(&caching_ctl->mutex);
431 leaf = path->nodes[0];
432 nritems = btrfs_header_nritems(leaf);
436 if (key.objectid < block_group->key.objectid) {
441 if (key.objectid >= block_group->key.objectid +
442 block_group->key.offset)
445 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
446 total_found += add_new_free_space(block_group,
449 last = key.objectid + key.offset;
451 if (total_found > (1024 * 1024 * 2)) {
453 wake_up(&caching_ctl->wait);
460 total_found += add_new_free_space(block_group, fs_info, last,
461 block_group->key.objectid +
462 block_group->key.offset);
463 caching_ctl->progress = (u64)-1;
465 spin_lock(&block_group->lock);
466 block_group->caching_ctl = NULL;
467 block_group->cached = BTRFS_CACHE_FINISHED;
468 spin_unlock(&block_group->lock);
471 btrfs_free_path(path);
472 up_read(&fs_info->extent_commit_sem);
474 free_excluded_extents(extent_root, block_group);
476 mutex_unlock(&caching_ctl->mutex);
478 wake_up(&caching_ctl->wait);
480 put_caching_control(caching_ctl);
481 btrfs_put_block_group(block_group);
484 static int cache_block_group(struct btrfs_block_group_cache *cache,
488 struct btrfs_fs_info *fs_info = cache->fs_info;
489 struct btrfs_caching_control *caching_ctl;
492 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
496 INIT_LIST_HEAD(&caching_ctl->list);
497 mutex_init(&caching_ctl->mutex);
498 init_waitqueue_head(&caching_ctl->wait);
499 caching_ctl->block_group = cache;
500 caching_ctl->progress = cache->key.objectid;
501 atomic_set(&caching_ctl->count, 1);
502 caching_ctl->work.func = caching_thread;
504 spin_lock(&cache->lock);
506 * This should be a rare occasion, but this could happen I think in the
507 * case where one thread starts to load the space cache info, and then
508 * some other thread starts a transaction commit which tries to do an
509 * allocation while the other thread is still loading the space cache
510 * info. The previous loop should have kept us from choosing this block
511 * group, but if we've moved to the state where we will wait on caching
512 * block groups we need to first check if we're doing a fast load here,
513 * so we can wait for it to finish, otherwise we could end up allocating
514 * from a block group who's cache gets evicted for one reason or
517 while (cache->cached == BTRFS_CACHE_FAST) {
518 struct btrfs_caching_control *ctl;
520 ctl = cache->caching_ctl;
521 atomic_inc(&ctl->count);
522 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
523 spin_unlock(&cache->lock);
527 finish_wait(&ctl->wait, &wait);
528 put_caching_control(ctl);
529 spin_lock(&cache->lock);
532 if (cache->cached != BTRFS_CACHE_NO) {
533 spin_unlock(&cache->lock);
537 WARN_ON(cache->caching_ctl);
538 cache->caching_ctl = caching_ctl;
539 cache->cached = BTRFS_CACHE_FAST;
540 spin_unlock(&cache->lock);
542 if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
543 ret = load_free_space_cache(fs_info, cache);
545 spin_lock(&cache->lock);
547 cache->caching_ctl = NULL;
548 cache->cached = BTRFS_CACHE_FINISHED;
549 cache->last_byte_to_unpin = (u64)-1;
551 if (load_cache_only) {
552 cache->caching_ctl = NULL;
553 cache->cached = BTRFS_CACHE_NO;
555 cache->cached = BTRFS_CACHE_STARTED;
558 spin_unlock(&cache->lock);
559 wake_up(&caching_ctl->wait);
561 put_caching_control(caching_ctl);
562 free_excluded_extents(fs_info->extent_root, cache);
567 * We are not going to do the fast caching, set cached to the
568 * appropriate value and wakeup any waiters.
570 spin_lock(&cache->lock);
571 if (load_cache_only) {
572 cache->caching_ctl = NULL;
573 cache->cached = BTRFS_CACHE_NO;
575 cache->cached = BTRFS_CACHE_STARTED;
577 spin_unlock(&cache->lock);
578 wake_up(&caching_ctl->wait);
581 if (load_cache_only) {
582 put_caching_control(caching_ctl);
586 down_write(&fs_info->extent_commit_sem);
587 atomic_inc(&caching_ctl->count);
588 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
589 up_write(&fs_info->extent_commit_sem);
591 btrfs_get_block_group(cache);
593 btrfs_queue_worker(&fs_info->caching_workers, &caching_ctl->work);
599 * return the block group that starts at or after bytenr
601 static struct btrfs_block_group_cache *
602 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
604 struct btrfs_block_group_cache *cache;
606 cache = block_group_cache_tree_search(info, bytenr, 0);
612 * return the block group that contains the given bytenr
614 struct btrfs_block_group_cache *btrfs_lookup_block_group(
615 struct btrfs_fs_info *info,
618 struct btrfs_block_group_cache *cache;
620 cache = block_group_cache_tree_search(info, bytenr, 1);
625 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
628 struct list_head *head = &info->space_info;
629 struct btrfs_space_info *found;
631 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
634 list_for_each_entry_rcu(found, head, list) {
635 if (found->flags & flags) {
645 * after adding space to the filesystem, we need to clear the full flags
646 * on all the space infos.
648 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
650 struct list_head *head = &info->space_info;
651 struct btrfs_space_info *found;
654 list_for_each_entry_rcu(found, head, list)
659 u64 btrfs_find_block_group(struct btrfs_root *root,
660 u64 search_start, u64 search_hint, int owner)
662 struct btrfs_block_group_cache *cache;
664 u64 last = max(search_hint, search_start);
671 cache = btrfs_lookup_first_block_group(root->fs_info, last);
675 spin_lock(&cache->lock);
676 last = cache->key.objectid + cache->key.offset;
677 used = btrfs_block_group_used(&cache->item);
679 if ((full_search || !cache->ro) &&
680 block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
681 if (used + cache->pinned + cache->reserved <
682 div_factor(cache->key.offset, factor)) {
683 group_start = cache->key.objectid;
684 spin_unlock(&cache->lock);
685 btrfs_put_block_group(cache);
689 spin_unlock(&cache->lock);
690 btrfs_put_block_group(cache);
698 if (!full_search && factor < 10) {
708 /* simple helper to search for an existing extent at a given offset */
709 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
712 struct btrfs_key key;
713 struct btrfs_path *path;
715 path = btrfs_alloc_path();
719 key.objectid = start;
721 btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
722 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
724 btrfs_free_path(path);
729 * helper function to lookup reference count and flags of extent.
731 * the head node for delayed ref is used to store the sum of all the
732 * reference count modifications queued up in the rbtree. the head
733 * node may also store the extent flags to set. This way you can check
734 * to see what the reference count and extent flags would be if all of
735 * the delayed refs are not processed.
737 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
738 struct btrfs_root *root, u64 bytenr,
739 u64 num_bytes, u64 *refs, u64 *flags)
741 struct btrfs_delayed_ref_head *head;
742 struct btrfs_delayed_ref_root *delayed_refs;
743 struct btrfs_path *path;
744 struct btrfs_extent_item *ei;
745 struct extent_buffer *leaf;
746 struct btrfs_key key;
752 path = btrfs_alloc_path();
756 key.objectid = bytenr;
757 key.type = BTRFS_EXTENT_ITEM_KEY;
758 key.offset = num_bytes;
760 path->skip_locking = 1;
761 path->search_commit_root = 1;
764 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
770 leaf = path->nodes[0];
771 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
772 if (item_size >= sizeof(*ei)) {
773 ei = btrfs_item_ptr(leaf, path->slots[0],
774 struct btrfs_extent_item);
775 num_refs = btrfs_extent_refs(leaf, ei);
776 extent_flags = btrfs_extent_flags(leaf, ei);
778 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
779 struct btrfs_extent_item_v0 *ei0;
780 BUG_ON(item_size != sizeof(*ei0));
781 ei0 = btrfs_item_ptr(leaf, path->slots[0],
782 struct btrfs_extent_item_v0);
783 num_refs = btrfs_extent_refs_v0(leaf, ei0);
784 /* FIXME: this isn't correct for data */
785 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
790 BUG_ON(num_refs == 0);
800 delayed_refs = &trans->transaction->delayed_refs;
801 spin_lock(&delayed_refs->lock);
802 head = btrfs_find_delayed_ref_head(trans, bytenr);
804 if (!mutex_trylock(&head->mutex)) {
805 atomic_inc(&head->node.refs);
806 spin_unlock(&delayed_refs->lock);
808 btrfs_release_path(path);
811 * Mutex was contended, block until it's released and try
814 mutex_lock(&head->mutex);
815 mutex_unlock(&head->mutex);
816 btrfs_put_delayed_ref(&head->node);
819 if (head->extent_op && head->extent_op->update_flags)
820 extent_flags |= head->extent_op->flags_to_set;
822 BUG_ON(num_refs == 0);
824 num_refs += head->node.ref_mod;
825 mutex_unlock(&head->mutex);
827 spin_unlock(&delayed_refs->lock);
829 WARN_ON(num_refs == 0);
833 *flags = extent_flags;
835 btrfs_free_path(path);
840 * Back reference rules. Back refs have three main goals:
842 * 1) differentiate between all holders of references to an extent so that
843 * when a reference is dropped we can make sure it was a valid reference
844 * before freeing the extent.
846 * 2) Provide enough information to quickly find the holders of an extent
847 * if we notice a given block is corrupted or bad.
849 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
850 * maintenance. This is actually the same as #2, but with a slightly
851 * different use case.
853 * There are two kinds of back refs. The implicit back refs is optimized
854 * for pointers in non-shared tree blocks. For a given pointer in a block,
855 * back refs of this kind provide information about the block's owner tree
856 * and the pointer's key. These information allow us to find the block by
857 * b-tree searching. The full back refs is for pointers in tree blocks not
858 * referenced by their owner trees. The location of tree block is recorded
859 * in the back refs. Actually the full back refs is generic, and can be
860 * used in all cases the implicit back refs is used. The major shortcoming
861 * of the full back refs is its overhead. Every time a tree block gets
862 * COWed, we have to update back refs entry for all pointers in it.
864 * For a newly allocated tree block, we use implicit back refs for
865 * pointers in it. This means most tree related operations only involve
866 * implicit back refs. For a tree block created in old transaction, the
867 * only way to drop a reference to it is COW it. So we can detect the
868 * event that tree block loses its owner tree's reference and do the
869 * back refs conversion.
871 * When a tree block is COW'd through a tree, there are four cases:
873 * The reference count of the block is one and the tree is the block's
874 * owner tree. Nothing to do in this case.
876 * The reference count of the block is one and the tree is not the
877 * block's owner tree. In this case, full back refs is used for pointers
878 * in the block. Remove these full back refs, add implicit back refs for
879 * every pointers in the new block.
881 * The reference count of the block is greater than one and the tree is
882 * the block's owner tree. In this case, implicit back refs is used for
883 * pointers in the block. Add full back refs for every pointers in the
884 * block, increase lower level extents' reference counts. The original
885 * implicit back refs are entailed to the new block.
887 * The reference count of the block is greater than one and the tree is
888 * not the block's owner tree. Add implicit back refs for every pointer in
889 * the new block, increase lower level extents' reference count.
891 * Back Reference Key composing:
893 * The key objectid corresponds to the first byte in the extent,
894 * The key type is used to differentiate between types of back refs.
895 * There are different meanings of the key offset for different types
898 * File extents can be referenced by:
900 * - multiple snapshots, subvolumes, or different generations in one subvol
901 * - different files inside a single subvolume
902 * - different offsets inside a file (bookend extents in file.c)
904 * The extent ref structure for the implicit back refs has fields for:
906 * - Objectid of the subvolume root
907 * - objectid of the file holding the reference
908 * - original offset in the file
909 * - how many bookend extents
911 * The key offset for the implicit back refs is hash of the first
914 * The extent ref structure for the full back refs has field for:
916 * - number of pointers in the tree leaf
918 * The key offset for the implicit back refs is the first byte of
921 * When a file extent is allocated, The implicit back refs is used.
922 * the fields are filled in:
924 * (root_key.objectid, inode objectid, offset in file, 1)
926 * When a file extent is removed file truncation, we find the
927 * corresponding implicit back refs and check the following fields:
929 * (btrfs_header_owner(leaf), inode objectid, offset in file)
931 * Btree extents can be referenced by:
933 * - Different subvolumes
935 * Both the implicit back refs and the full back refs for tree blocks
936 * only consist of key. The key offset for the implicit back refs is
937 * objectid of block's owner tree. The key offset for the full back refs
938 * is the first byte of parent block.
940 * When implicit back refs is used, information about the lowest key and
941 * level of the tree block are required. These information are stored in
942 * tree block info structure.
945 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
946 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
947 struct btrfs_root *root,
948 struct btrfs_path *path,
949 u64 owner, u32 extra_size)
951 struct btrfs_extent_item *item;
952 struct btrfs_extent_item_v0 *ei0;
953 struct btrfs_extent_ref_v0 *ref0;
954 struct btrfs_tree_block_info *bi;
955 struct extent_buffer *leaf;
956 struct btrfs_key key;
957 struct btrfs_key found_key;
958 u32 new_size = sizeof(*item);
962 leaf = path->nodes[0];
963 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
965 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
966 ei0 = btrfs_item_ptr(leaf, path->slots[0],
967 struct btrfs_extent_item_v0);
968 refs = btrfs_extent_refs_v0(leaf, ei0);
970 if (owner == (u64)-1) {
972 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
973 ret = btrfs_next_leaf(root, path);
976 BUG_ON(ret > 0); /* Corruption */
977 leaf = path->nodes[0];
979 btrfs_item_key_to_cpu(leaf, &found_key,
981 BUG_ON(key.objectid != found_key.objectid);
982 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
986 ref0 = btrfs_item_ptr(leaf, path->slots[0],
987 struct btrfs_extent_ref_v0);
988 owner = btrfs_ref_objectid_v0(leaf, ref0);
992 btrfs_release_path(path);
994 if (owner < BTRFS_FIRST_FREE_OBJECTID)
995 new_size += sizeof(*bi);
997 new_size -= sizeof(*ei0);
998 ret = btrfs_search_slot(trans, root, &key, path,
999 new_size + extra_size, 1);
1002 BUG_ON(ret); /* Corruption */
1004 btrfs_extend_item(trans, root, path, new_size);
1006 leaf = path->nodes[0];
1007 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1008 btrfs_set_extent_refs(leaf, item, refs);
1009 /* FIXME: get real generation */
1010 btrfs_set_extent_generation(leaf, item, 0);
1011 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1012 btrfs_set_extent_flags(leaf, item,
1013 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1014 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1015 bi = (struct btrfs_tree_block_info *)(item + 1);
1016 /* FIXME: get first key of the block */
1017 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
1018 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1020 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1022 btrfs_mark_buffer_dirty(leaf);
1027 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1029 u32 high_crc = ~(u32)0;
1030 u32 low_crc = ~(u32)0;
1033 lenum = cpu_to_le64(root_objectid);
1034 high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
1035 lenum = cpu_to_le64(owner);
1036 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1037 lenum = cpu_to_le64(offset);
1038 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1040 return ((u64)high_crc << 31) ^ (u64)low_crc;
1043 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1044 struct btrfs_extent_data_ref *ref)
1046 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1047 btrfs_extent_data_ref_objectid(leaf, ref),
1048 btrfs_extent_data_ref_offset(leaf, ref));
1051 static int match_extent_data_ref(struct extent_buffer *leaf,
1052 struct btrfs_extent_data_ref *ref,
1053 u64 root_objectid, u64 owner, u64 offset)
1055 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1056 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1057 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1062 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1063 struct btrfs_root *root,
1064 struct btrfs_path *path,
1065 u64 bytenr, u64 parent,
1067 u64 owner, u64 offset)
1069 struct btrfs_key key;
1070 struct btrfs_extent_data_ref *ref;
1071 struct extent_buffer *leaf;
1077 key.objectid = bytenr;
1079 key.type = BTRFS_SHARED_DATA_REF_KEY;
1080 key.offset = parent;
1082 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1083 key.offset = hash_extent_data_ref(root_objectid,
1088 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1097 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1098 key.type = BTRFS_EXTENT_REF_V0_KEY;
1099 btrfs_release_path(path);
1100 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1111 leaf = path->nodes[0];
1112 nritems = btrfs_header_nritems(leaf);
1114 if (path->slots[0] >= nritems) {
1115 ret = btrfs_next_leaf(root, path);
1121 leaf = path->nodes[0];
1122 nritems = btrfs_header_nritems(leaf);
1126 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1127 if (key.objectid != bytenr ||
1128 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1131 ref = btrfs_item_ptr(leaf, path->slots[0],
1132 struct btrfs_extent_data_ref);
1134 if (match_extent_data_ref(leaf, ref, root_objectid,
1137 btrfs_release_path(path);
1149 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1150 struct btrfs_root *root,
1151 struct btrfs_path *path,
1152 u64 bytenr, u64 parent,
1153 u64 root_objectid, u64 owner,
1154 u64 offset, int refs_to_add)
1156 struct btrfs_key key;
1157 struct extent_buffer *leaf;
1162 key.objectid = bytenr;
1164 key.type = BTRFS_SHARED_DATA_REF_KEY;
1165 key.offset = parent;
1166 size = sizeof(struct btrfs_shared_data_ref);
1168 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1169 key.offset = hash_extent_data_ref(root_objectid,
1171 size = sizeof(struct btrfs_extent_data_ref);
1174 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1175 if (ret && ret != -EEXIST)
1178 leaf = path->nodes[0];
1180 struct btrfs_shared_data_ref *ref;
1181 ref = btrfs_item_ptr(leaf, path->slots[0],
1182 struct btrfs_shared_data_ref);
1184 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1186 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1187 num_refs += refs_to_add;
1188 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1191 struct btrfs_extent_data_ref *ref;
1192 while (ret == -EEXIST) {
1193 ref = btrfs_item_ptr(leaf, path->slots[0],
1194 struct btrfs_extent_data_ref);
1195 if (match_extent_data_ref(leaf, ref, root_objectid,
1198 btrfs_release_path(path);
1200 ret = btrfs_insert_empty_item(trans, root, path, &key,
1202 if (ret && ret != -EEXIST)
1205 leaf = path->nodes[0];
1207 ref = btrfs_item_ptr(leaf, path->slots[0],
1208 struct btrfs_extent_data_ref);
1210 btrfs_set_extent_data_ref_root(leaf, ref,
1212 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1213 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1214 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1216 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1217 num_refs += refs_to_add;
1218 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1221 btrfs_mark_buffer_dirty(leaf);
1224 btrfs_release_path(path);
1228 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1229 struct btrfs_root *root,
1230 struct btrfs_path *path,
1233 struct btrfs_key key;
1234 struct btrfs_extent_data_ref *ref1 = NULL;
1235 struct btrfs_shared_data_ref *ref2 = NULL;
1236 struct extent_buffer *leaf;
1240 leaf = path->nodes[0];
1241 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1243 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1244 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1245 struct btrfs_extent_data_ref);
1246 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1247 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1248 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1249 struct btrfs_shared_data_ref);
1250 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1251 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1252 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1253 struct btrfs_extent_ref_v0 *ref0;
1254 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1255 struct btrfs_extent_ref_v0);
1256 num_refs = btrfs_ref_count_v0(leaf, ref0);
1262 BUG_ON(num_refs < refs_to_drop);
1263 num_refs -= refs_to_drop;
1265 if (num_refs == 0) {
1266 ret = btrfs_del_item(trans, root, path);
1268 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1269 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1270 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1271 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1272 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1274 struct btrfs_extent_ref_v0 *ref0;
1275 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1276 struct btrfs_extent_ref_v0);
1277 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1280 btrfs_mark_buffer_dirty(leaf);
1285 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1286 struct btrfs_path *path,
1287 struct btrfs_extent_inline_ref *iref)
1289 struct btrfs_key key;
1290 struct extent_buffer *leaf;
1291 struct btrfs_extent_data_ref *ref1;
1292 struct btrfs_shared_data_ref *ref2;
1295 leaf = path->nodes[0];
1296 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1298 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1299 BTRFS_EXTENT_DATA_REF_KEY) {
1300 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1301 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1303 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1304 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1306 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1307 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1308 struct btrfs_extent_data_ref);
1309 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1310 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1311 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1312 struct btrfs_shared_data_ref);
1313 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1314 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1315 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1316 struct btrfs_extent_ref_v0 *ref0;
1317 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1318 struct btrfs_extent_ref_v0);
1319 num_refs = btrfs_ref_count_v0(leaf, ref0);
1327 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1328 struct btrfs_root *root,
1329 struct btrfs_path *path,
1330 u64 bytenr, u64 parent,
1333 struct btrfs_key key;
1336 key.objectid = bytenr;
1338 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1339 key.offset = parent;
1341 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1342 key.offset = root_objectid;
1345 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1348 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1349 if (ret == -ENOENT && parent) {
1350 btrfs_release_path(path);
1351 key.type = BTRFS_EXTENT_REF_V0_KEY;
1352 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1360 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1361 struct btrfs_root *root,
1362 struct btrfs_path *path,
1363 u64 bytenr, u64 parent,
1366 struct btrfs_key key;
1369 key.objectid = bytenr;
1371 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1372 key.offset = parent;
1374 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1375 key.offset = root_objectid;
1378 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1379 btrfs_release_path(path);
1383 static inline int extent_ref_type(u64 parent, u64 owner)
1386 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1388 type = BTRFS_SHARED_BLOCK_REF_KEY;
1390 type = BTRFS_TREE_BLOCK_REF_KEY;
1393 type = BTRFS_SHARED_DATA_REF_KEY;
1395 type = BTRFS_EXTENT_DATA_REF_KEY;
1400 static int find_next_key(struct btrfs_path *path, int level,
1401 struct btrfs_key *key)
1404 for (; level < BTRFS_MAX_LEVEL; level++) {
1405 if (!path->nodes[level])
1407 if (path->slots[level] + 1 >=
1408 btrfs_header_nritems(path->nodes[level]))
1411 btrfs_item_key_to_cpu(path->nodes[level], key,
1412 path->slots[level] + 1);
1414 btrfs_node_key_to_cpu(path->nodes[level], key,
1415 path->slots[level] + 1);
1422 * look for inline back ref. if back ref is found, *ref_ret is set
1423 * to the address of inline back ref, and 0 is returned.
1425 * if back ref isn't found, *ref_ret is set to the address where it
1426 * should be inserted, and -ENOENT is returned.
1428 * if insert is true and there are too many inline back refs, the path
1429 * points to the extent item, and -EAGAIN is returned.
1431 * NOTE: inline back refs are ordered in the same way that back ref
1432 * items in the tree are ordered.
1434 static noinline_for_stack
1435 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1436 struct btrfs_root *root,
1437 struct btrfs_path *path,
1438 struct btrfs_extent_inline_ref **ref_ret,
1439 u64 bytenr, u64 num_bytes,
1440 u64 parent, u64 root_objectid,
1441 u64 owner, u64 offset, int insert)
1443 struct btrfs_key key;
1444 struct extent_buffer *leaf;
1445 struct btrfs_extent_item *ei;
1446 struct btrfs_extent_inline_ref *iref;
1457 key.objectid = bytenr;
1458 key.type = BTRFS_EXTENT_ITEM_KEY;
1459 key.offset = num_bytes;
1461 want = extent_ref_type(parent, owner);
1463 extra_size = btrfs_extent_inline_ref_size(want);
1464 path->keep_locks = 1;
1467 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1472 if (ret && !insert) {
1481 leaf = path->nodes[0];
1482 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1483 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1484 if (item_size < sizeof(*ei)) {
1489 ret = convert_extent_item_v0(trans, root, path, owner,
1495 leaf = path->nodes[0];
1496 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1499 BUG_ON(item_size < sizeof(*ei));
1501 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1502 flags = btrfs_extent_flags(leaf, ei);
1504 ptr = (unsigned long)(ei + 1);
1505 end = (unsigned long)ei + item_size;
1507 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1508 ptr += sizeof(struct btrfs_tree_block_info);
1511 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1520 iref = (struct btrfs_extent_inline_ref *)ptr;
1521 type = btrfs_extent_inline_ref_type(leaf, iref);
1525 ptr += btrfs_extent_inline_ref_size(type);
1529 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1530 struct btrfs_extent_data_ref *dref;
1531 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1532 if (match_extent_data_ref(leaf, dref, root_objectid,
1537 if (hash_extent_data_ref_item(leaf, dref) <
1538 hash_extent_data_ref(root_objectid, owner, offset))
1542 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1544 if (parent == ref_offset) {
1548 if (ref_offset < parent)
1551 if (root_objectid == ref_offset) {
1555 if (ref_offset < root_objectid)
1559 ptr += btrfs_extent_inline_ref_size(type);
1561 if (err == -ENOENT && insert) {
1562 if (item_size + extra_size >=
1563 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1568 * To add new inline back ref, we have to make sure
1569 * there is no corresponding back ref item.
1570 * For simplicity, we just do not add new inline back
1571 * ref if there is any kind of item for this block
1573 if (find_next_key(path, 0, &key) == 0 &&
1574 key.objectid == bytenr &&
1575 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1580 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1583 path->keep_locks = 0;
1584 btrfs_unlock_up_safe(path, 1);
1590 * helper to add new inline back ref
1592 static noinline_for_stack
1593 void setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1594 struct btrfs_root *root,
1595 struct btrfs_path *path,
1596 struct btrfs_extent_inline_ref *iref,
1597 u64 parent, u64 root_objectid,
1598 u64 owner, u64 offset, int refs_to_add,
1599 struct btrfs_delayed_extent_op *extent_op)
1601 struct extent_buffer *leaf;
1602 struct btrfs_extent_item *ei;
1605 unsigned long item_offset;
1610 leaf = path->nodes[0];
1611 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1612 item_offset = (unsigned long)iref - (unsigned long)ei;
1614 type = extent_ref_type(parent, owner);
1615 size = btrfs_extent_inline_ref_size(type);
1617 btrfs_extend_item(trans, root, path, size);
1619 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1620 refs = btrfs_extent_refs(leaf, ei);
1621 refs += refs_to_add;
1622 btrfs_set_extent_refs(leaf, ei, refs);
1624 __run_delayed_extent_op(extent_op, leaf, ei);
1626 ptr = (unsigned long)ei + item_offset;
1627 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1628 if (ptr < end - size)
1629 memmove_extent_buffer(leaf, ptr + size, ptr,
1632 iref = (struct btrfs_extent_inline_ref *)ptr;
1633 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1634 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1635 struct btrfs_extent_data_ref *dref;
1636 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1637 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1638 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1639 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1640 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1641 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1642 struct btrfs_shared_data_ref *sref;
1643 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1644 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1645 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1646 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1647 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1649 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1651 btrfs_mark_buffer_dirty(leaf);
1654 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1655 struct btrfs_root *root,
1656 struct btrfs_path *path,
1657 struct btrfs_extent_inline_ref **ref_ret,
1658 u64 bytenr, u64 num_bytes, u64 parent,
1659 u64 root_objectid, u64 owner, u64 offset)
1663 ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1664 bytenr, num_bytes, parent,
1665 root_objectid, owner, offset, 0);
1669 btrfs_release_path(path);
1672 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1673 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1676 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1677 root_objectid, owner, offset);
1683 * helper to update/remove inline back ref
1685 static noinline_for_stack
1686 void update_inline_extent_backref(struct btrfs_trans_handle *trans,
1687 struct btrfs_root *root,
1688 struct btrfs_path *path,
1689 struct btrfs_extent_inline_ref *iref,
1691 struct btrfs_delayed_extent_op *extent_op)
1693 struct extent_buffer *leaf;
1694 struct btrfs_extent_item *ei;
1695 struct btrfs_extent_data_ref *dref = NULL;
1696 struct btrfs_shared_data_ref *sref = NULL;
1704 leaf = path->nodes[0];
1705 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1706 refs = btrfs_extent_refs(leaf, ei);
1707 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1708 refs += refs_to_mod;
1709 btrfs_set_extent_refs(leaf, ei, refs);
1711 __run_delayed_extent_op(extent_op, leaf, ei);
1713 type = btrfs_extent_inline_ref_type(leaf, iref);
1715 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1716 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1717 refs = btrfs_extent_data_ref_count(leaf, dref);
1718 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1719 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1720 refs = btrfs_shared_data_ref_count(leaf, sref);
1723 BUG_ON(refs_to_mod != -1);
1726 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1727 refs += refs_to_mod;
1730 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1731 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1733 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1735 size = btrfs_extent_inline_ref_size(type);
1736 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1737 ptr = (unsigned long)iref;
1738 end = (unsigned long)ei + item_size;
1739 if (ptr + size < end)
1740 memmove_extent_buffer(leaf, ptr, ptr + size,
1743 btrfs_truncate_item(trans, root, path, item_size, 1);
1745 btrfs_mark_buffer_dirty(leaf);
1748 static noinline_for_stack
1749 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1750 struct btrfs_root *root,
1751 struct btrfs_path *path,
1752 u64 bytenr, u64 num_bytes, u64 parent,
1753 u64 root_objectid, u64 owner,
1754 u64 offset, int refs_to_add,
1755 struct btrfs_delayed_extent_op *extent_op)
1757 struct btrfs_extent_inline_ref *iref;
1760 ret = lookup_inline_extent_backref(trans, root, path, &iref,
1761 bytenr, num_bytes, parent,
1762 root_objectid, owner, offset, 1);
1764 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1765 update_inline_extent_backref(trans, root, path, iref,
1766 refs_to_add, extent_op);
1767 } else if (ret == -ENOENT) {
1768 setup_inline_extent_backref(trans, root, path, iref, parent,
1769 root_objectid, owner, offset,
1770 refs_to_add, extent_op);
1776 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1777 struct btrfs_root *root,
1778 struct btrfs_path *path,
1779 u64 bytenr, u64 parent, u64 root_objectid,
1780 u64 owner, u64 offset, int refs_to_add)
1783 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1784 BUG_ON(refs_to_add != 1);
1785 ret = insert_tree_block_ref(trans, root, path, bytenr,
1786 parent, root_objectid);
1788 ret = insert_extent_data_ref(trans, root, path, bytenr,
1789 parent, root_objectid,
1790 owner, offset, refs_to_add);
1795 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1796 struct btrfs_root *root,
1797 struct btrfs_path *path,
1798 struct btrfs_extent_inline_ref *iref,
1799 int refs_to_drop, int is_data)
1803 BUG_ON(!is_data && refs_to_drop != 1);
1805 update_inline_extent_backref(trans, root, path, iref,
1806 -refs_to_drop, NULL);
1807 } else if (is_data) {
1808 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1810 ret = btrfs_del_item(trans, root, path);
1815 static int btrfs_issue_discard(struct block_device *bdev,
1818 return blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_NOFS, 0);
1821 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1822 u64 num_bytes, u64 *actual_bytes)
1825 u64 discarded_bytes = 0;
1826 struct btrfs_bio *bbio = NULL;
1829 /* Tell the block device(s) that the sectors can be discarded */
1830 ret = btrfs_map_block(root->fs_info, REQ_DISCARD,
1831 bytenr, &num_bytes, &bbio, 0);
1832 /* Error condition is -ENOMEM */
1834 struct btrfs_bio_stripe *stripe = bbio->stripes;
1838 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1839 if (!stripe->dev->can_discard)
1842 ret = btrfs_issue_discard(stripe->dev->bdev,
1846 discarded_bytes += stripe->length;
1847 else if (ret != -EOPNOTSUPP)
1848 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
1851 * Just in case we get back EOPNOTSUPP for some reason,
1852 * just ignore the return value so we don't screw up
1853 * people calling discard_extent.
1861 *actual_bytes = discarded_bytes;
1864 if (ret == -EOPNOTSUPP)
1869 /* Can return -ENOMEM */
1870 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1871 struct btrfs_root *root,
1872 u64 bytenr, u64 num_bytes, u64 parent,
1873 u64 root_objectid, u64 owner, u64 offset, int for_cow)
1876 struct btrfs_fs_info *fs_info = root->fs_info;
1878 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1879 root_objectid == BTRFS_TREE_LOG_OBJECTID);
1881 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1882 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
1884 parent, root_objectid, (int)owner,
1885 BTRFS_ADD_DELAYED_REF, NULL, for_cow);
1887 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
1889 parent, root_objectid, owner, offset,
1890 BTRFS_ADD_DELAYED_REF, NULL, for_cow);
1895 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1896 struct btrfs_root *root,
1897 u64 bytenr, u64 num_bytes,
1898 u64 parent, u64 root_objectid,
1899 u64 owner, u64 offset, int refs_to_add,
1900 struct btrfs_delayed_extent_op *extent_op)
1902 struct btrfs_path *path;
1903 struct extent_buffer *leaf;
1904 struct btrfs_extent_item *item;
1909 path = btrfs_alloc_path();
1914 path->leave_spinning = 1;
1915 /* this will setup the path even if it fails to insert the back ref */
1916 ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1917 path, bytenr, num_bytes, parent,
1918 root_objectid, owner, offset,
1919 refs_to_add, extent_op);
1923 if (ret != -EAGAIN) {
1928 leaf = path->nodes[0];
1929 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1930 refs = btrfs_extent_refs(leaf, item);
1931 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1933 __run_delayed_extent_op(extent_op, leaf, item);
1935 btrfs_mark_buffer_dirty(leaf);
1936 btrfs_release_path(path);
1939 path->leave_spinning = 1;
1941 /* now insert the actual backref */
1942 ret = insert_extent_backref(trans, root->fs_info->extent_root,
1943 path, bytenr, parent, root_objectid,
1944 owner, offset, refs_to_add);
1946 btrfs_abort_transaction(trans, root, ret);
1948 btrfs_free_path(path);
1952 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1953 struct btrfs_root *root,
1954 struct btrfs_delayed_ref_node *node,
1955 struct btrfs_delayed_extent_op *extent_op,
1956 int insert_reserved)
1959 struct btrfs_delayed_data_ref *ref;
1960 struct btrfs_key ins;
1965 ins.objectid = node->bytenr;
1966 ins.offset = node->num_bytes;
1967 ins.type = BTRFS_EXTENT_ITEM_KEY;
1969 ref = btrfs_delayed_node_to_data_ref(node);
1970 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1971 parent = ref->parent;
1973 ref_root = ref->root;
1975 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1977 BUG_ON(extent_op->update_key);
1978 flags |= extent_op->flags_to_set;
1980 ret = alloc_reserved_file_extent(trans, root,
1981 parent, ref_root, flags,
1982 ref->objectid, ref->offset,
1983 &ins, node->ref_mod);
1984 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1985 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1986 node->num_bytes, parent,
1987 ref_root, ref->objectid,
1988 ref->offset, node->ref_mod,
1990 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1991 ret = __btrfs_free_extent(trans, root, node->bytenr,
1992 node->num_bytes, parent,
1993 ref_root, ref->objectid,
1994 ref->offset, node->ref_mod,
2002 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2003 struct extent_buffer *leaf,
2004 struct btrfs_extent_item *ei)
2006 u64 flags = btrfs_extent_flags(leaf, ei);
2007 if (extent_op->update_flags) {
2008 flags |= extent_op->flags_to_set;
2009 btrfs_set_extent_flags(leaf, ei, flags);
2012 if (extent_op->update_key) {
2013 struct btrfs_tree_block_info *bi;
2014 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2015 bi = (struct btrfs_tree_block_info *)(ei + 1);
2016 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2020 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2021 struct btrfs_root *root,
2022 struct btrfs_delayed_ref_node *node,
2023 struct btrfs_delayed_extent_op *extent_op)
2025 struct btrfs_key key;
2026 struct btrfs_path *path;
2027 struct btrfs_extent_item *ei;
2028 struct extent_buffer *leaf;
2036 path = btrfs_alloc_path();
2040 key.objectid = node->bytenr;
2041 key.type = BTRFS_EXTENT_ITEM_KEY;
2042 key.offset = node->num_bytes;
2045 path->leave_spinning = 1;
2046 ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
2057 leaf = path->nodes[0];
2058 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2059 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2060 if (item_size < sizeof(*ei)) {
2061 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
2067 leaf = path->nodes[0];
2068 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2071 BUG_ON(item_size < sizeof(*ei));
2072 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2073 __run_delayed_extent_op(extent_op, leaf, ei);
2075 btrfs_mark_buffer_dirty(leaf);
2077 btrfs_free_path(path);
2081 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2082 struct btrfs_root *root,
2083 struct btrfs_delayed_ref_node *node,
2084 struct btrfs_delayed_extent_op *extent_op,
2085 int insert_reserved)
2088 struct btrfs_delayed_tree_ref *ref;
2089 struct btrfs_key ins;
2093 ins.objectid = node->bytenr;
2094 ins.offset = node->num_bytes;
2095 ins.type = BTRFS_EXTENT_ITEM_KEY;
2097 ref = btrfs_delayed_node_to_tree_ref(node);
2098 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2099 parent = ref->parent;
2101 ref_root = ref->root;
2103 BUG_ON(node->ref_mod != 1);
2104 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2105 BUG_ON(!extent_op || !extent_op->update_flags ||
2106 !extent_op->update_key);
2107 ret = alloc_reserved_tree_block(trans, root,
2109 extent_op->flags_to_set,
2112 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2113 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2114 node->num_bytes, parent, ref_root,
2115 ref->level, 0, 1, extent_op);
2116 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2117 ret = __btrfs_free_extent(trans, root, node->bytenr,
2118 node->num_bytes, parent, ref_root,
2119 ref->level, 0, 1, extent_op);
2126 /* helper function to actually process a single delayed ref entry */
2127 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2128 struct btrfs_root *root,
2129 struct btrfs_delayed_ref_node *node,
2130 struct btrfs_delayed_extent_op *extent_op,
2131 int insert_reserved)
2138 if (btrfs_delayed_ref_is_head(node)) {
2139 struct btrfs_delayed_ref_head *head;
2141 * we've hit the end of the chain and we were supposed
2142 * to insert this extent into the tree. But, it got
2143 * deleted before we ever needed to insert it, so all
2144 * we have to do is clean up the accounting
2147 head = btrfs_delayed_node_to_head(node);
2148 if (insert_reserved) {
2149 btrfs_pin_extent(root, node->bytenr,
2150 node->num_bytes, 1);
2151 if (head->is_data) {
2152 ret = btrfs_del_csums(trans, root,
2160 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2161 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2162 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2164 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2165 node->type == BTRFS_SHARED_DATA_REF_KEY)
2166 ret = run_delayed_data_ref(trans, root, node, extent_op,
2173 static noinline struct btrfs_delayed_ref_node *
2174 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2176 struct rb_node *node;
2177 struct btrfs_delayed_ref_node *ref;
2178 int action = BTRFS_ADD_DELAYED_REF;
2181 * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2182 * this prevents ref count from going down to zero when
2183 * there still are pending delayed ref.
2185 node = rb_prev(&head->node.rb_node);
2189 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2191 if (ref->bytenr != head->node.bytenr)
2193 if (ref->action == action)
2195 node = rb_prev(node);
2197 if (action == BTRFS_ADD_DELAYED_REF) {
2198 action = BTRFS_DROP_DELAYED_REF;
2205 * Returns 0 on success or if called with an already aborted transaction.
2206 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2208 static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
2209 struct btrfs_root *root,
2210 struct list_head *cluster)
2212 struct btrfs_delayed_ref_root *delayed_refs;
2213 struct btrfs_delayed_ref_node *ref;
2214 struct btrfs_delayed_ref_head *locked_ref = NULL;
2215 struct btrfs_delayed_extent_op *extent_op;
2216 struct btrfs_fs_info *fs_info = root->fs_info;
2219 int must_insert_reserved = 0;
2221 delayed_refs = &trans->transaction->delayed_refs;
2224 /* pick a new head ref from the cluster list */
2225 if (list_empty(cluster))
2228 locked_ref = list_entry(cluster->next,
2229 struct btrfs_delayed_ref_head, cluster);
2231 /* grab the lock that says we are going to process
2232 * all the refs for this head */
2233 ret = btrfs_delayed_ref_lock(trans, locked_ref);
2236 * we may have dropped the spin lock to get the head
2237 * mutex lock, and that might have given someone else
2238 * time to free the head. If that's true, it has been
2239 * removed from our list and we can move on.
2241 if (ret == -EAGAIN) {
2249 * We need to try and merge add/drops of the same ref since we
2250 * can run into issues with relocate dropping the implicit ref
2251 * and then it being added back again before the drop can
2252 * finish. If we merged anything we need to re-loop so we can
2255 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2259 * locked_ref is the head node, so we have to go one
2260 * node back for any delayed ref updates
2262 ref = select_delayed_ref(locked_ref);
2264 if (ref && ref->seq &&
2265 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
2267 * there are still refs with lower seq numbers in the
2268 * process of being added. Don't run this ref yet.
2270 list_del_init(&locked_ref->cluster);
2271 btrfs_delayed_ref_unlock(locked_ref);
2273 delayed_refs->num_heads_ready++;
2274 spin_unlock(&delayed_refs->lock);
2276 spin_lock(&delayed_refs->lock);
2281 * record the must insert reserved flag before we
2282 * drop the spin lock.
2284 must_insert_reserved = locked_ref->must_insert_reserved;
2285 locked_ref->must_insert_reserved = 0;
2287 extent_op = locked_ref->extent_op;
2288 locked_ref->extent_op = NULL;
2291 /* All delayed refs have been processed, Go ahead
2292 * and send the head node to run_one_delayed_ref,
2293 * so that any accounting fixes can happen
2295 ref = &locked_ref->node;
2297 if (extent_op && must_insert_reserved) {
2298 btrfs_free_delayed_extent_op(extent_op);
2303 spin_unlock(&delayed_refs->lock);
2305 ret = run_delayed_extent_op(trans, root,
2307 btrfs_free_delayed_extent_op(extent_op);
2311 "btrfs: run_delayed_extent_op "
2312 "returned %d\n", ret);
2313 spin_lock(&delayed_refs->lock);
2314 btrfs_delayed_ref_unlock(locked_ref);
2323 rb_erase(&ref->rb_node, &delayed_refs->root);
2324 delayed_refs->num_entries--;
2325 if (!btrfs_delayed_ref_is_head(ref)) {
2327 * when we play the delayed ref, also correct the
2330 switch (ref->action) {
2331 case BTRFS_ADD_DELAYED_REF:
2332 case BTRFS_ADD_DELAYED_EXTENT:
2333 locked_ref->node.ref_mod -= ref->ref_mod;
2335 case BTRFS_DROP_DELAYED_REF:
2336 locked_ref->node.ref_mod += ref->ref_mod;
2342 spin_unlock(&delayed_refs->lock);
2344 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2345 must_insert_reserved);
2347 btrfs_free_delayed_extent_op(extent_op);
2349 btrfs_delayed_ref_unlock(locked_ref);
2350 btrfs_put_delayed_ref(ref);
2352 "btrfs: run_one_delayed_ref returned %d\n", ret);
2353 spin_lock(&delayed_refs->lock);
2358 * If this node is a head, that means all the refs in this head
2359 * have been dealt with, and we will pick the next head to deal
2360 * with, so we must unlock the head and drop it from the cluster
2361 * list before we release it.
2363 if (btrfs_delayed_ref_is_head(ref)) {
2364 list_del_init(&locked_ref->cluster);
2365 btrfs_delayed_ref_unlock(locked_ref);
2368 btrfs_put_delayed_ref(ref);
2372 spin_lock(&delayed_refs->lock);
2377 #ifdef SCRAMBLE_DELAYED_REFS
2379 * Normally delayed refs get processed in ascending bytenr order. This
2380 * correlates in most cases to the order added. To expose dependencies on this
2381 * order, we start to process the tree in the middle instead of the beginning
2383 static u64 find_middle(struct rb_root *root)
2385 struct rb_node *n = root->rb_node;
2386 struct btrfs_delayed_ref_node *entry;
2389 u64 first = 0, last = 0;
2393 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2394 first = entry->bytenr;
2398 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2399 last = entry->bytenr;
2404 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2405 WARN_ON(!entry->in_tree);
2407 middle = entry->bytenr;
2420 int btrfs_delayed_refs_qgroup_accounting(struct btrfs_trans_handle *trans,
2421 struct btrfs_fs_info *fs_info)
2423 struct qgroup_update *qgroup_update;
2426 if (list_empty(&trans->qgroup_ref_list) !=
2427 !trans->delayed_ref_elem.seq) {
2428 /* list without seq or seq without list */
2429 printk(KERN_ERR "btrfs: qgroup accounting update error, list is%s empty, seq is %llu\n",
2430 list_empty(&trans->qgroup_ref_list) ? "" : " not",
2431 trans->delayed_ref_elem.seq);
2435 if (!trans->delayed_ref_elem.seq)
2438 while (!list_empty(&trans->qgroup_ref_list)) {
2439 qgroup_update = list_first_entry(&trans->qgroup_ref_list,
2440 struct qgroup_update, list);
2441 list_del(&qgroup_update->list);
2443 ret = btrfs_qgroup_account_ref(
2444 trans, fs_info, qgroup_update->node,
2445 qgroup_update->extent_op);
2446 kfree(qgroup_update);
2449 btrfs_put_tree_mod_seq(fs_info, &trans->delayed_ref_elem);
2454 static int refs_newer(struct btrfs_delayed_ref_root *delayed_refs, int seq,
2457 int val = atomic_read(&delayed_refs->ref_seq);
2459 if (val < seq || val >= seq + count)
2465 * this starts processing the delayed reference count updates and
2466 * extent insertions we have queued up so far. count can be
2467 * 0, which means to process everything in the tree at the start
2468 * of the run (but not newly added entries), or it can be some target
2469 * number you'd like to process.
2471 * Returns 0 on success or if called with an aborted transaction
2472 * Returns <0 on error and aborts the transaction
2474 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2475 struct btrfs_root *root, unsigned long count)
2477 struct rb_node *node;
2478 struct btrfs_delayed_ref_root *delayed_refs;
2479 struct btrfs_delayed_ref_node *ref;
2480 struct list_head cluster;
2483 int run_all = count == (unsigned long)-1;
2487 /* We'll clean this up in btrfs_cleanup_transaction */
2491 if (root == root->fs_info->extent_root)
2492 root = root->fs_info->tree_root;
2494 btrfs_delayed_refs_qgroup_accounting(trans, root->fs_info);
2496 delayed_refs = &trans->transaction->delayed_refs;
2497 INIT_LIST_HEAD(&cluster);
2499 count = delayed_refs->num_entries * 2;
2503 if (!run_all && !run_most) {
2505 int seq = atomic_read(&delayed_refs->ref_seq);
2508 old = atomic_cmpxchg(&delayed_refs->procs_running_refs, 0, 1);
2510 DEFINE_WAIT(__wait);
2511 if (delayed_refs->num_entries < 16348)
2514 prepare_to_wait(&delayed_refs->wait, &__wait,
2515 TASK_UNINTERRUPTIBLE);
2517 old = atomic_cmpxchg(&delayed_refs->procs_running_refs, 0, 1);
2520 finish_wait(&delayed_refs->wait, &__wait);
2522 if (!refs_newer(delayed_refs, seq, 256))
2527 finish_wait(&delayed_refs->wait, &__wait);
2533 atomic_inc(&delayed_refs->procs_running_refs);
2538 spin_lock(&delayed_refs->lock);
2540 #ifdef SCRAMBLE_DELAYED_REFS
2541 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2545 if (!(run_all || run_most) &&
2546 delayed_refs->num_heads_ready < 64)
2550 * go find something we can process in the rbtree. We start at
2551 * the beginning of the tree, and then build a cluster
2552 * of refs to process starting at the first one we are able to
2555 delayed_start = delayed_refs->run_delayed_start;
2556 ret = btrfs_find_ref_cluster(trans, &cluster,
2557 delayed_refs->run_delayed_start);
2561 ret = run_clustered_refs(trans, root, &cluster);
2563 btrfs_release_ref_cluster(&cluster);
2564 spin_unlock(&delayed_refs->lock);
2565 btrfs_abort_transaction(trans, root, ret);
2566 atomic_dec(&delayed_refs->procs_running_refs);
2570 atomic_add(ret, &delayed_refs->ref_seq);
2572 count -= min_t(unsigned long, ret, count);
2577 if (delayed_start >= delayed_refs->run_delayed_start) {
2580 * btrfs_find_ref_cluster looped. let's do one
2581 * more cycle. if we don't run any delayed ref
2582 * during that cycle (because we can't because
2583 * all of them are blocked), bail out.
2588 * no runnable refs left, stop trying
2595 /* refs were run, let's reset staleness detection */
2601 if (!list_empty(&trans->new_bgs)) {
2602 spin_unlock(&delayed_refs->lock);
2603 btrfs_create_pending_block_groups(trans, root);
2604 spin_lock(&delayed_refs->lock);
2607 node = rb_first(&delayed_refs->root);
2610 count = (unsigned long)-1;
2613 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2615 if (btrfs_delayed_ref_is_head(ref)) {
2616 struct btrfs_delayed_ref_head *head;
2618 head = btrfs_delayed_node_to_head(ref);
2619 atomic_inc(&ref->refs);
2621 spin_unlock(&delayed_refs->lock);
2623 * Mutex was contended, block until it's
2624 * released and try again
2626 mutex_lock(&head->mutex);
2627 mutex_unlock(&head->mutex);
2629 btrfs_put_delayed_ref(ref);
2633 node = rb_next(node);
2635 spin_unlock(&delayed_refs->lock);
2636 schedule_timeout(1);
2640 atomic_dec(&delayed_refs->procs_running_refs);
2642 if (waitqueue_active(&delayed_refs->wait))
2643 wake_up(&delayed_refs->wait);
2645 spin_unlock(&delayed_refs->lock);
2646 assert_qgroups_uptodate(trans);
2650 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2651 struct btrfs_root *root,
2652 u64 bytenr, u64 num_bytes, u64 flags,
2655 struct btrfs_delayed_extent_op *extent_op;
2658 extent_op = btrfs_alloc_delayed_extent_op();
2662 extent_op->flags_to_set = flags;
2663 extent_op->update_flags = 1;
2664 extent_op->update_key = 0;
2665 extent_op->is_data = is_data ? 1 : 0;
2667 ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
2668 num_bytes, extent_op);
2670 btrfs_free_delayed_extent_op(extent_op);
2674 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2675 struct btrfs_root *root,
2676 struct btrfs_path *path,
2677 u64 objectid, u64 offset, u64 bytenr)
2679 struct btrfs_delayed_ref_head *head;
2680 struct btrfs_delayed_ref_node *ref;
2681 struct btrfs_delayed_data_ref *data_ref;
2682 struct btrfs_delayed_ref_root *delayed_refs;
2683 struct rb_node *node;
2687 delayed_refs = &trans->transaction->delayed_refs;
2688 spin_lock(&delayed_refs->lock);
2689 head = btrfs_find_delayed_ref_head(trans, bytenr);
2693 if (!mutex_trylock(&head->mutex)) {
2694 atomic_inc(&head->node.refs);
2695 spin_unlock(&delayed_refs->lock);
2697 btrfs_release_path(path);
2700 * Mutex was contended, block until it's released and let
2703 mutex_lock(&head->mutex);
2704 mutex_unlock(&head->mutex);
2705 btrfs_put_delayed_ref(&head->node);
2709 node = rb_prev(&head->node.rb_node);
2713 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2715 if (ref->bytenr != bytenr)
2719 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2722 data_ref = btrfs_delayed_node_to_data_ref(ref);
2724 node = rb_prev(node);
2728 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2729 if (ref->bytenr == bytenr && ref->seq == seq)
2733 if (data_ref->root != root->root_key.objectid ||
2734 data_ref->objectid != objectid || data_ref->offset != offset)
2739 mutex_unlock(&head->mutex);
2741 spin_unlock(&delayed_refs->lock);
2745 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2746 struct btrfs_root *root,
2747 struct btrfs_path *path,
2748 u64 objectid, u64 offset, u64 bytenr)
2750 struct btrfs_root *extent_root = root->fs_info->extent_root;
2751 struct extent_buffer *leaf;
2752 struct btrfs_extent_data_ref *ref;
2753 struct btrfs_extent_inline_ref *iref;
2754 struct btrfs_extent_item *ei;
2755 struct btrfs_key key;
2759 key.objectid = bytenr;
2760 key.offset = (u64)-1;
2761 key.type = BTRFS_EXTENT_ITEM_KEY;
2763 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2766 BUG_ON(ret == 0); /* Corruption */
2769 if (path->slots[0] == 0)
2773 leaf = path->nodes[0];
2774 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2776 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2780 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2781 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2782 if (item_size < sizeof(*ei)) {
2783 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2787 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2789 if (item_size != sizeof(*ei) +
2790 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2793 if (btrfs_extent_generation(leaf, ei) <=
2794 btrfs_root_last_snapshot(&root->root_item))
2797 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2798 if (btrfs_extent_inline_ref_type(leaf, iref) !=
2799 BTRFS_EXTENT_DATA_REF_KEY)
2802 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2803 if (btrfs_extent_refs(leaf, ei) !=
2804 btrfs_extent_data_ref_count(leaf, ref) ||
2805 btrfs_extent_data_ref_root(leaf, ref) !=
2806 root->root_key.objectid ||
2807 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2808 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2816 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2817 struct btrfs_root *root,
2818 u64 objectid, u64 offset, u64 bytenr)
2820 struct btrfs_path *path;
2824 path = btrfs_alloc_path();
2829 ret = check_committed_ref(trans, root, path, objectid,
2831 if (ret && ret != -ENOENT)
2834 ret2 = check_delayed_ref(trans, root, path, objectid,
2836 } while (ret2 == -EAGAIN);
2838 if (ret2 && ret2 != -ENOENT) {
2843 if (ret != -ENOENT || ret2 != -ENOENT)
2846 btrfs_free_path(path);
2847 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2852 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2853 struct btrfs_root *root,
2854 struct extent_buffer *buf,
2855 int full_backref, int inc, int for_cow)
2862 struct btrfs_key key;
2863 struct btrfs_file_extent_item *fi;
2867 int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2868 u64, u64, u64, u64, u64, u64, int);
2870 ref_root = btrfs_header_owner(buf);
2871 nritems = btrfs_header_nritems(buf);
2872 level = btrfs_header_level(buf);
2874 if (!root->ref_cows && level == 0)
2878 process_func = btrfs_inc_extent_ref;
2880 process_func = btrfs_free_extent;
2883 parent = buf->start;
2887 for (i = 0; i < nritems; i++) {
2889 btrfs_item_key_to_cpu(buf, &key, i);
2890 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2892 fi = btrfs_item_ptr(buf, i,
2893 struct btrfs_file_extent_item);
2894 if (btrfs_file_extent_type(buf, fi) ==
2895 BTRFS_FILE_EXTENT_INLINE)
2897 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2901 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2902 key.offset -= btrfs_file_extent_offset(buf, fi);
2903 ret = process_func(trans, root, bytenr, num_bytes,
2904 parent, ref_root, key.objectid,
2905 key.offset, for_cow);
2909 bytenr = btrfs_node_blockptr(buf, i);
2910 num_bytes = btrfs_level_size(root, level - 1);
2911 ret = process_func(trans, root, bytenr, num_bytes,
2912 parent, ref_root, level - 1, 0,
2923 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2924 struct extent_buffer *buf, int full_backref, int for_cow)
2926 return __btrfs_mod_ref(trans, root, buf, full_backref, 1, for_cow);
2929 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2930 struct extent_buffer *buf, int full_backref, int for_cow)
2932 return __btrfs_mod_ref(trans, root, buf, full_backref, 0, for_cow);
2935 static int write_one_cache_group(struct btrfs_trans_handle *trans,
2936 struct btrfs_root *root,
2937 struct btrfs_path *path,
2938 struct btrfs_block_group_cache *cache)
2941 struct btrfs_root *extent_root = root->fs_info->extent_root;
2943 struct extent_buffer *leaf;
2945 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
2948 BUG_ON(ret); /* Corruption */
2950 leaf = path->nodes[0];
2951 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2952 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2953 btrfs_mark_buffer_dirty(leaf);
2954 btrfs_release_path(path);
2957 btrfs_abort_transaction(trans, root, ret);
2964 static struct btrfs_block_group_cache *
2965 next_block_group(struct btrfs_root *root,
2966 struct btrfs_block_group_cache *cache)
2968 struct rb_node *node;
2969 spin_lock(&root->fs_info->block_group_cache_lock);
2970 node = rb_next(&cache->cache_node);
2971 btrfs_put_block_group(cache);
2973 cache = rb_entry(node, struct btrfs_block_group_cache,
2975 btrfs_get_block_group(cache);
2978 spin_unlock(&root->fs_info->block_group_cache_lock);
2982 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
2983 struct btrfs_trans_handle *trans,
2984 struct btrfs_path *path)
2986 struct btrfs_root *root = block_group->fs_info->tree_root;
2987 struct inode *inode = NULL;
2989 int dcs = BTRFS_DC_ERROR;
2995 * If this block group is smaller than 100 megs don't bother caching the
2998 if (block_group->key.offset < (100 * 1024 * 1024)) {
2999 spin_lock(&block_group->lock);
3000 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3001 spin_unlock(&block_group->lock);
3006 inode = lookup_free_space_inode(root, block_group, path);
3007 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3008 ret = PTR_ERR(inode);
3009 btrfs_release_path(path);
3013 if (IS_ERR(inode)) {
3017 if (block_group->ro)
3020 ret = create_free_space_inode(root, trans, block_group, path);
3026 /* We've already setup this transaction, go ahead and exit */
3027 if (block_group->cache_generation == trans->transid &&
3028 i_size_read(inode)) {
3029 dcs = BTRFS_DC_SETUP;
3034 * We want to set the generation to 0, that way if anything goes wrong
3035 * from here on out we know not to trust this cache when we load up next
3038 BTRFS_I(inode)->generation = 0;
3039 ret = btrfs_update_inode(trans, root, inode);
3042 if (i_size_read(inode) > 0) {
3043 ret = btrfs_truncate_free_space_cache(root, trans, path,
3049 spin_lock(&block_group->lock);
3050 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3051 !btrfs_test_opt(root, SPACE_CACHE)) {
3053 * don't bother trying to write stuff out _if_
3054 * a) we're not cached,
3055 * b) we're with nospace_cache mount option.
3057 dcs = BTRFS_DC_WRITTEN;
3058 spin_unlock(&block_group->lock);
3061 spin_unlock(&block_group->lock);
3064 * Try to preallocate enough space based on how big the block group is.
3065 * Keep in mind this has to include any pinned space which could end up
3066 * taking up quite a bit since it's not folded into the other space
3069 num_pages = (int)div64_u64(block_group->key.offset, 256 * 1024 * 1024);
3074 num_pages *= PAGE_CACHE_SIZE;
3076 ret = btrfs_check_data_free_space(inode, num_pages);
3080 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3081 num_pages, num_pages,
3084 dcs = BTRFS_DC_SETUP;
3085 btrfs_free_reserved_data_space(inode, num_pages);
3090 btrfs_release_path(path);
3092 spin_lock(&block_group->lock);
3093 if (!ret && dcs == BTRFS_DC_SETUP)
3094 block_group->cache_generation = trans->transid;
3095 block_group->disk_cache_state = dcs;
3096 spin_unlock(&block_group->lock);
3101 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3102 struct btrfs_root *root)
3104 struct btrfs_block_group_cache *cache;
3106 struct btrfs_path *path;
3109 path = btrfs_alloc_path();
3115 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3117 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3119 cache = next_block_group(root, cache);
3127 err = cache_save_setup(cache, trans, path);
3128 last = cache->key.objectid + cache->key.offset;
3129 btrfs_put_block_group(cache);
3134 err = btrfs_run_delayed_refs(trans, root,
3136 if (err) /* File system offline */
3140 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3142 if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
3143 btrfs_put_block_group(cache);
3149 cache = next_block_group(root, cache);
3158 if (cache->disk_cache_state == BTRFS_DC_SETUP)
3159 cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
3161 last = cache->key.objectid + cache->key.offset;
3163 err = write_one_cache_group(trans, root, path, cache);
3164 if (err) /* File system offline */
3167 btrfs_put_block_group(cache);
3172 * I don't think this is needed since we're just marking our
3173 * preallocated extent as written, but just in case it can't
3177 err = btrfs_run_delayed_refs(trans, root,
3179 if (err) /* File system offline */
3183 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3186 * Really this shouldn't happen, but it could if we
3187 * couldn't write the entire preallocated extent and
3188 * splitting the extent resulted in a new block.
3191 btrfs_put_block_group(cache);
3194 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3196 cache = next_block_group(root, cache);
3205 err = btrfs_write_out_cache(root, trans, cache, path);
3208 * If we didn't have an error then the cache state is still
3209 * NEED_WRITE, so we can set it to WRITTEN.
3211 if (!err && cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3212 cache->disk_cache_state = BTRFS_DC_WRITTEN;
3213 last = cache->key.objectid + cache->key.offset;
3214 btrfs_put_block_group(cache);
3218 btrfs_free_path(path);
3222 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3224 struct btrfs_block_group_cache *block_group;
3227 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
3228 if (!block_group || block_group->ro)
3231 btrfs_put_block_group(block_group);
3235 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3236 u64 total_bytes, u64 bytes_used,
3237 struct btrfs_space_info **space_info)
3239 struct btrfs_space_info *found;
3243 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3244 BTRFS_BLOCK_GROUP_RAID10))
3249 found = __find_space_info(info, flags);
3251 spin_lock(&found->lock);
3252 found->total_bytes += total_bytes;
3253 found->disk_total += total_bytes * factor;
3254 found->bytes_used += bytes_used;
3255 found->disk_used += bytes_used * factor;
3257 spin_unlock(&found->lock);
3258 *space_info = found;
3261 found = kzalloc(sizeof(*found), GFP_NOFS);
3265 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3266 INIT_LIST_HEAD(&found->block_groups[i]);
3267 init_rwsem(&found->groups_sem);
3268 spin_lock_init(&found->lock);
3269 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3270 found->total_bytes = total_bytes;
3271 found->disk_total = total_bytes * factor;
3272 found->bytes_used = bytes_used;
3273 found->disk_used = bytes_used * factor;
3274 found->bytes_pinned = 0;
3275 found->bytes_reserved = 0;
3276 found->bytes_readonly = 0;
3277 found->bytes_may_use = 0;
3279 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3280 found->chunk_alloc = 0;
3282 init_waitqueue_head(&found->wait);
3283 *space_info = found;
3284 list_add_rcu(&found->list, &info->space_info);
3285 if (flags & BTRFS_BLOCK_GROUP_DATA)
3286 info->data_sinfo = found;
3290 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3292 u64 extra_flags = chunk_to_extended(flags) &
3293 BTRFS_EXTENDED_PROFILE_MASK;
3295 write_seqlock(&fs_info->profiles_lock);
3296 if (flags & BTRFS_BLOCK_GROUP_DATA)
3297 fs_info->avail_data_alloc_bits |= extra_flags;
3298 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3299 fs_info->avail_metadata_alloc_bits |= extra_flags;
3300 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3301 fs_info->avail_system_alloc_bits |= extra_flags;
3302 write_sequnlock(&fs_info->profiles_lock);
3306 * returns target flags in extended format or 0 if restripe for this
3307 * chunk_type is not in progress
3309 * should be called with either volume_mutex or balance_lock held
3311 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3313 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3319 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3320 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3321 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3322 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3323 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3324 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3325 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3326 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3327 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3334 * @flags: available profiles in extended format (see ctree.h)
3336 * Returns reduced profile in chunk format. If profile changing is in
3337 * progress (either running or paused) picks the target profile (if it's
3338 * already available), otherwise falls back to plain reducing.
3340 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
3343 * we add in the count of missing devices because we want
3344 * to make sure that any RAID levels on a degraded FS
3345 * continue to be honored.
3347 u64 num_devices = root->fs_info->fs_devices->rw_devices +
3348 root->fs_info->fs_devices->missing_devices;
3353 * see if restripe for this chunk_type is in progress, if so
3354 * try to reduce to the target profile
3356 spin_lock(&root->fs_info->balance_lock);
3357 target = get_restripe_target(root->fs_info, flags);
3359 /* pick target profile only if it's already available */
3360 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3361 spin_unlock(&root->fs_info->balance_lock);
3362 return extended_to_chunk(target);
3365 spin_unlock(&root->fs_info->balance_lock);
3367 /* First, mask out the RAID levels which aren't possible */
3368 if (num_devices == 1)
3369 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0 |
3370 BTRFS_BLOCK_GROUP_RAID5);
3371 if (num_devices < 3)
3372 flags &= ~BTRFS_BLOCK_GROUP_RAID6;
3373 if (num_devices < 4)
3374 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3376 tmp = flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3377 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID5 |
3378 BTRFS_BLOCK_GROUP_RAID6 | BTRFS_BLOCK_GROUP_RAID10);
3381 if (tmp & BTRFS_BLOCK_GROUP_RAID6)
3382 tmp = BTRFS_BLOCK_GROUP_RAID6;
3383 else if (tmp & BTRFS_BLOCK_GROUP_RAID5)
3384 tmp = BTRFS_BLOCK_GROUP_RAID5;
3385 else if (tmp & BTRFS_BLOCK_GROUP_RAID10)
3386 tmp = BTRFS_BLOCK_GROUP_RAID10;
3387 else if (tmp & BTRFS_BLOCK_GROUP_RAID1)
3388 tmp = BTRFS_BLOCK_GROUP_RAID1;
3389 else if (tmp & BTRFS_BLOCK_GROUP_RAID0)
3390 tmp = BTRFS_BLOCK_GROUP_RAID0;
3392 return extended_to_chunk(flags | tmp);
3395 static u64 get_alloc_profile(struct btrfs_root *root, u64 flags)
3400 seq = read_seqbegin(&root->fs_info->profiles_lock);
3402 if (flags & BTRFS_BLOCK_GROUP_DATA)
3403 flags |= root->fs_info->avail_data_alloc_bits;
3404 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3405 flags |= root->fs_info->avail_system_alloc_bits;
3406 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3407 flags |= root->fs_info->avail_metadata_alloc_bits;
3408 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
3410 return btrfs_reduce_alloc_profile(root, flags);
3413 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3419 flags = BTRFS_BLOCK_GROUP_DATA;
3420 else if (root == root->fs_info->chunk_root)
3421 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3423 flags = BTRFS_BLOCK_GROUP_METADATA;
3425 ret = get_alloc_profile(root, flags);
3430 * This will check the space that the inode allocates from to make sure we have
3431 * enough space for bytes.
3433 int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
3435 struct btrfs_space_info *data_sinfo;
3436 struct btrfs_root *root = BTRFS_I(inode)->root;
3437 struct btrfs_fs_info *fs_info = root->fs_info;
3439 int ret = 0, committed = 0, alloc_chunk = 1;
3441 /* make sure bytes are sectorsize aligned */
3442 bytes = ALIGN(bytes, root->sectorsize);
3444 if (root == root->fs_info->tree_root ||
3445 BTRFS_I(inode)->location.objectid == BTRFS_FREE_INO_OBJECTID) {
3450 data_sinfo = fs_info->data_sinfo;
3455 /* make sure we have enough space to handle the data first */
3456 spin_lock(&data_sinfo->lock);
3457 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3458 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3459 data_sinfo->bytes_may_use;
3461 if (used + bytes > data_sinfo->total_bytes) {
3462 struct btrfs_trans_handle *trans;
3465 * if we don't have enough free bytes in this space then we need
3466 * to alloc a new chunk.
3468 if (!data_sinfo->full && alloc_chunk) {
3471 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
3472 spin_unlock(&data_sinfo->lock);
3474 alloc_target = btrfs_get_alloc_profile(root, 1);
3475 trans = btrfs_join_transaction(root);
3477 return PTR_ERR(trans);
3479 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3481 CHUNK_ALLOC_NO_FORCE);
3482 btrfs_end_transaction(trans, root);
3491 data_sinfo = fs_info->data_sinfo;
3497 * If we have less pinned bytes than we want to allocate then
3498 * don't bother committing the transaction, it won't help us.
3500 if (data_sinfo->bytes_pinned < bytes)
3502 spin_unlock(&data_sinfo->lock);
3504 /* commit the current transaction and try again */
3507 !atomic_read(&root->fs_info->open_ioctl_trans)) {
3509 trans = btrfs_join_transaction(root);
3511 return PTR_ERR(trans);
3512 ret = btrfs_commit_transaction(trans, root);
3520 data_sinfo->bytes_may_use += bytes;
3521 trace_btrfs_space_reservation(root->fs_info, "space_info",
3522 data_sinfo->flags, bytes, 1);
3523 spin_unlock(&data_sinfo->lock);
3529 * Called if we need to clear a data reservation for this inode.
3531 void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
3533 struct btrfs_root *root = BTRFS_I(inode)->root;
3534 struct btrfs_space_info *data_sinfo;
3536 /* make sure bytes are sectorsize aligned */
3537 bytes = ALIGN(bytes, root->sectorsize);
3539 data_sinfo = root->fs_info->data_sinfo;
3540 spin_lock(&data_sinfo->lock);
3541 data_sinfo->bytes_may_use -= bytes;
3542 trace_btrfs_space_reservation(root->fs_info, "space_info",
3543 data_sinfo->flags, bytes, 0);
3544 spin_unlock(&data_sinfo->lock);
3547 static void force_metadata_allocation(struct btrfs_fs_info *info)
3549 struct list_head *head = &info->space_info;
3550 struct btrfs_space_info *found;
3553 list_for_each_entry_rcu(found, head, list) {
3554 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3555 found->force_alloc = CHUNK_ALLOC_FORCE;
3560 static int should_alloc_chunk(struct btrfs_root *root,
3561 struct btrfs_space_info *sinfo, int force)
3563 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3564 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
3565 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
3568 if (force == CHUNK_ALLOC_FORCE)
3572 * We need to take into account the global rsv because for all intents
3573 * and purposes it's used space. Don't worry about locking the
3574 * global_rsv, it doesn't change except when the transaction commits.
3576 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
3577 num_allocated += global_rsv->size;
3580 * in limited mode, we want to have some free space up to
3581 * about 1% of the FS size.
3583 if (force == CHUNK_ALLOC_LIMITED) {
3584 thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
3585 thresh = max_t(u64, 64 * 1024 * 1024,
3586 div_factor_fine(thresh, 1));
3588 if (num_bytes - num_allocated < thresh)
3592 if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
3597 static u64 get_system_chunk_thresh(struct btrfs_root *root, u64 type)
3601 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
3602 BTRFS_BLOCK_GROUP_RAID0 |
3603 BTRFS_BLOCK_GROUP_RAID5 |
3604 BTRFS_BLOCK_GROUP_RAID6))
3605 num_dev = root->fs_info->fs_devices->rw_devices;
3606 else if (type & BTRFS_BLOCK_GROUP_RAID1)
3609 num_dev = 1; /* DUP or single */
3611 /* metadata for updaing devices and chunk tree */
3612 return btrfs_calc_trans_metadata_size(root, num_dev + 1);
3615 static void check_system_chunk(struct btrfs_trans_handle *trans,
3616 struct btrfs_root *root, u64 type)
3618 struct btrfs_space_info *info;
3622 info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3623 spin_lock(&info->lock);
3624 left = info->total_bytes - info->bytes_used - info->bytes_pinned -
3625 info->bytes_reserved - info->bytes_readonly;
3626 spin_unlock(&info->lock);
3628 thresh = get_system_chunk_thresh(root, type);
3629 if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
3630 printk(KERN_INFO "left=%llu, need=%llu, flags=%llu\n",
3631 left, thresh, type);
3632 dump_space_info(info, 0, 0);
3635 if (left < thresh) {
3638 flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
3639 btrfs_alloc_chunk(trans, root, flags);
3643 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
3644 struct btrfs_root *extent_root, u64 flags, int force)
3646 struct btrfs_space_info *space_info;
3647 struct btrfs_fs_info *fs_info = extent_root->fs_info;
3648 int wait_for_alloc = 0;
3651 /* Don't re-enter if we're already allocating a chunk */
3652 if (trans->allocating_chunk)
3655 space_info = __find_space_info(extent_root->fs_info, flags);
3657 ret = update_space_info(extent_root->fs_info, flags,
3659 BUG_ON(ret); /* -ENOMEM */
3661 BUG_ON(!space_info); /* Logic error */
3664 spin_lock(&space_info->lock);
3665 if (force < space_info->force_alloc)
3666 force = space_info->force_alloc;
3667 if (space_info->full) {
3668 spin_unlock(&space_info->lock);
3672 if (!should_alloc_chunk(extent_root, space_info, force)) {
3673 spin_unlock(&space_info->lock);
3675 } else if (space_info->chunk_alloc) {
3678 space_info->chunk_alloc = 1;
3681 spin_unlock(&space_info->lock);
3683 mutex_lock(&fs_info->chunk_mutex);
3686 * The chunk_mutex is held throughout the entirety of a chunk
3687 * allocation, so once we've acquired the chunk_mutex we know that the
3688 * other guy is done and we need to recheck and see if we should
3691 if (wait_for_alloc) {
3692 mutex_unlock(&fs_info->chunk_mutex);
3697 trans->allocating_chunk = true;
3700 * If we have mixed data/metadata chunks we want to make sure we keep
3701 * allocating mixed chunks instead of individual chunks.
3703 if (btrfs_mixed_space_info(space_info))
3704 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3707 * if we're doing a data chunk, go ahead and make sure that
3708 * we keep a reasonable number of metadata chunks allocated in the
3711 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3712 fs_info->data_chunk_allocations++;
3713 if (!(fs_info->data_chunk_allocations %
3714 fs_info->metadata_ratio))
3715 force_metadata_allocation(fs_info);
3719 * Check if we have enough space in SYSTEM chunk because we may need
3720 * to update devices.
3722 check_system_chunk(trans, extent_root, flags);
3724 ret = btrfs_alloc_chunk(trans, extent_root, flags);
3725 trans->allocating_chunk = false;
3727 spin_lock(&space_info->lock);
3728 if (ret < 0 && ret != -ENOSPC)
3731 space_info->full = 1;
3735 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3737 space_info->chunk_alloc = 0;
3738 spin_unlock(&space_info->lock);
3739 mutex_unlock(&fs_info->chunk_mutex);
3743 static int can_overcommit(struct btrfs_root *root,
3744 struct btrfs_space_info *space_info, u64 bytes,
3745 enum btrfs_reserve_flush_enum flush)
3747 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3748 u64 profile = btrfs_get_alloc_profile(root, 0);
3754 used = space_info->bytes_used + space_info->bytes_reserved +
3755 space_info->bytes_pinned + space_info->bytes_readonly;
3757 spin_lock(&global_rsv->lock);
3758 rsv_size = global_rsv->size;
3759 spin_unlock(&global_rsv->lock);
3762 * We only want to allow over committing if we have lots of actual space
3763 * free, but if we don't have enough space to handle the global reserve
3764 * space then we could end up having a real enospc problem when trying
3765 * to allocate a chunk or some other such important allocation.
3768 if (used + rsv_size >= space_info->total_bytes)
3771 used += space_info->bytes_may_use;
3773 spin_lock(&root->fs_info->free_chunk_lock);
3774 avail = root->fs_info->free_chunk_space;
3775 spin_unlock(&root->fs_info->free_chunk_lock);
3778 * If we have dup, raid1 or raid10 then only half of the free
3779 * space is actually useable. For raid56, the space info used
3780 * doesn't include the parity drive, so we don't have to
3783 if (profile & (BTRFS_BLOCK_GROUP_DUP |
3784 BTRFS_BLOCK_GROUP_RAID1 |
3785 BTRFS_BLOCK_GROUP_RAID10))
3788 to_add = space_info->total_bytes;
3791 * If we aren't flushing all things, let us overcommit up to
3792 * 1/2th of the space. If we can flush, don't let us overcommit
3793 * too much, let it overcommit up to 1/8 of the space.
3795 if (flush == BTRFS_RESERVE_FLUSH_ALL)
3801 * Limit the overcommit to the amount of free space we could possibly
3802 * allocate for chunks.
3804 to_add = min(avail, to_add);
3806 if (used + bytes < space_info->total_bytes + to_add)
3811 static inline int writeback_inodes_sb_nr_if_idle_safe(struct super_block *sb,
3812 unsigned long nr_pages,
3813 enum wb_reason reason)
3815 /* the flusher is dealing with the dirty inodes now. */
3816 if (writeback_in_progress(sb->s_bdi))
3819 if (down_read_trylock(&sb->s_umount)) {
3820 writeback_inodes_sb_nr(sb, nr_pages, reason);
3821 up_read(&sb->s_umount);
3828 void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
3829 unsigned long nr_pages)
3831 struct super_block *sb = root->fs_info->sb;
3834 /* If we can not start writeback, just sync all the delalloc file. */
3835 started = writeback_inodes_sb_nr_if_idle_safe(sb, nr_pages,
3836 WB_REASON_FS_FREE_SPACE);
3839 * We needn't worry the filesystem going from r/w to r/o though
3840 * we don't acquire ->s_umount mutex, because the filesystem
3841 * should guarantee the delalloc inodes list be empty after
3842 * the filesystem is readonly(all dirty pages are written to
3845 btrfs_start_delalloc_inodes(root, 0);
3846 btrfs_wait_ordered_extents(root, 0);
3851 * shrink metadata reservation for delalloc
3853 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
3856 struct btrfs_block_rsv *block_rsv;
3857 struct btrfs_space_info *space_info;
3858 struct btrfs_trans_handle *trans;
3862 unsigned long nr_pages = (2 * 1024 * 1024) >> PAGE_CACHE_SHIFT;
3864 enum btrfs_reserve_flush_enum flush;
3866 trans = (struct btrfs_trans_handle *)current->journal_info;
3867 block_rsv = &root->fs_info->delalloc_block_rsv;
3868 space_info = block_rsv->space_info;
3871 delalloc_bytes = percpu_counter_sum_positive(
3872 &root->fs_info->delalloc_bytes);
3873 if (delalloc_bytes == 0) {
3876 btrfs_wait_ordered_extents(root, 0);
3880 while (delalloc_bytes && loops < 3) {
3881 max_reclaim = min(delalloc_bytes, to_reclaim);
3882 nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
3883 btrfs_writeback_inodes_sb_nr(root, nr_pages);
3885 * We need to wait for the async pages to actually start before
3888 wait_event(root->fs_info->async_submit_wait,
3889 !atomic_read(&root->fs_info->async_delalloc_pages));
3892 flush = BTRFS_RESERVE_FLUSH_ALL;
3894 flush = BTRFS_RESERVE_NO_FLUSH;
3895 spin_lock(&space_info->lock);
3896 if (can_overcommit(root, space_info, orig, flush)) {
3897 spin_unlock(&space_info->lock);
3900 spin_unlock(&space_info->lock);
3903 if (wait_ordered && !trans) {
3904 btrfs_wait_ordered_extents(root, 0);
3906 time_left = schedule_timeout_killable(1);
3911 delalloc_bytes = percpu_counter_sum_positive(
3912 &root->fs_info->delalloc_bytes);
3917 * maybe_commit_transaction - possibly commit the transaction if its ok to
3918 * @root - the root we're allocating for
3919 * @bytes - the number of bytes we want to reserve
3920 * @force - force the commit
3922 * This will check to make sure that committing the transaction will actually
3923 * get us somewhere and then commit the transaction if it does. Otherwise it
3924 * will return -ENOSPC.
3926 static int may_commit_transaction(struct btrfs_root *root,
3927 struct btrfs_space_info *space_info,
3928 u64 bytes, int force)
3930 struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
3931 struct btrfs_trans_handle *trans;
3933 trans = (struct btrfs_trans_handle *)current->journal_info;
3940 /* See if there is enough pinned space to make this reservation */
3941 spin_lock(&space_info->lock);
3942 if (space_info->bytes_pinned >= bytes) {
3943 spin_unlock(&space_info->lock);
3946 spin_unlock(&space_info->lock);
3949 * See if there is some space in the delayed insertion reservation for
3952 if (space_info != delayed_rsv->space_info)
3955 spin_lock(&space_info->lock);
3956 spin_lock(&delayed_rsv->lock);
3957 if (space_info->bytes_pinned + delayed_rsv->size < bytes) {
3958 spin_unlock(&delayed_rsv->lock);
3959 spin_unlock(&space_info->lock);
3962 spin_unlock(&delayed_rsv->lock);
3963 spin_unlock(&space_info->lock);
3966 trans = btrfs_join_transaction(root);
3970 return btrfs_commit_transaction(trans, root);
3974 FLUSH_DELAYED_ITEMS_NR = 1,
3975 FLUSH_DELAYED_ITEMS = 2,
3977 FLUSH_DELALLOC_WAIT = 4,
3982 static int flush_space(struct btrfs_root *root,
3983 struct btrfs_space_info *space_info, u64 num_bytes,
3984 u64 orig_bytes, int state)
3986 struct btrfs_trans_handle *trans;
3991 case FLUSH_DELAYED_ITEMS_NR:
3992 case FLUSH_DELAYED_ITEMS:
3993 if (state == FLUSH_DELAYED_ITEMS_NR) {
3994 u64 bytes = btrfs_calc_trans_metadata_size(root, 1);
3996 nr = (int)div64_u64(num_bytes, bytes);
4003 trans = btrfs_join_transaction(root);
4004 if (IS_ERR(trans)) {
4005 ret = PTR_ERR(trans);
4008 ret = btrfs_run_delayed_items_nr(trans, root, nr);
4009 btrfs_end_transaction(trans, root);
4011 case FLUSH_DELALLOC:
4012 case FLUSH_DELALLOC_WAIT:
4013 shrink_delalloc(root, num_bytes, orig_bytes,
4014 state == FLUSH_DELALLOC_WAIT);
4017 trans = btrfs_join_transaction(root);
4018 if (IS_ERR(trans)) {
4019 ret = PTR_ERR(trans);
4022 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
4023 btrfs_get_alloc_profile(root, 0),
4024 CHUNK_ALLOC_NO_FORCE);
4025 btrfs_end_transaction(trans, root);
4030 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4040 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
4041 * @root - the root we're allocating for
4042 * @block_rsv - the block_rsv we're allocating for
4043 * @orig_bytes - the number of bytes we want
4044 * @flush - whether or not we can flush to make our reservation
4046 * This will reserve orgi_bytes number of bytes from the space info associated
4047 * with the block_rsv. If there is not enough space it will make an attempt to
4048 * flush out space to make room. It will do this by flushing delalloc if
4049 * possible or committing the transaction. If flush is 0 then no attempts to
4050 * regain reservations will be made and this will fail if there is not enough
4053 static int reserve_metadata_bytes(struct btrfs_root *root,
4054 struct btrfs_block_rsv *block_rsv,
4056 enum btrfs_reserve_flush_enum flush)
4058 struct btrfs_space_info *space_info = block_rsv->space_info;
4060 u64 num_bytes = orig_bytes;
4061 int flush_state = FLUSH_DELAYED_ITEMS_NR;
4063 bool flushing = false;
4067 spin_lock(&space_info->lock);
4069 * We only want to wait if somebody other than us is flushing and we
4070 * are actually allowed to flush all things.
4072 while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
4073 space_info->flush) {
4074 spin_unlock(&space_info->lock);
4076 * If we have a trans handle we can't wait because the flusher
4077 * may have to commit the transaction, which would mean we would
4078 * deadlock since we are waiting for the flusher to finish, but
4079 * hold the current transaction open.
4081 if (current->journal_info)
4083 ret = wait_event_killable(space_info->wait, !space_info->flush);
4084 /* Must have been killed, return */
4088 spin_lock(&space_info->lock);
4092 used = space_info->bytes_used + space_info->bytes_reserved +
4093 space_info->bytes_pinned + space_info->bytes_readonly +
4094 space_info->bytes_may_use;
4097 * The idea here is that we've not already over-reserved the block group
4098 * then we can go ahead and save our reservation first and then start
4099 * flushing if we need to. Otherwise if we've already overcommitted
4100 * lets start flushing stuff first and then come back and try to make
4103 if (used <= space_info->total_bytes) {
4104 if (used + orig_bytes <= space_info->total_bytes) {
4105 space_info->bytes_may_use += orig_bytes;
4106 trace_btrfs_space_reservation(root->fs_info,
4107 "space_info", space_info->flags, orig_bytes, 1);
4111 * Ok set num_bytes to orig_bytes since we aren't
4112 * overocmmitted, this way we only try and reclaim what
4115 num_bytes = orig_bytes;
4119 * Ok we're over committed, set num_bytes to the overcommitted
4120 * amount plus the amount of bytes that we need for this
4123 num_bytes = used - space_info->total_bytes +
4127 if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
4128 space_info->bytes_may_use += orig_bytes;
4129 trace_btrfs_space_reservation(root->fs_info, "space_info",
4130 space_info->flags, orig_bytes,
4136 * Couldn't make our reservation, save our place so while we're trying
4137 * to reclaim space we can actually use it instead of somebody else
4138 * stealing it from us.
4140 * We make the other tasks wait for the flush only when we can flush
4143 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
4145 space_info->flush = 1;
4148 spin_unlock(&space_info->lock);
4150 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
4153 ret = flush_space(root, space_info, num_bytes, orig_bytes,
4158 * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
4159 * would happen. So skip delalloc flush.
4161 if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4162 (flush_state == FLUSH_DELALLOC ||
4163 flush_state == FLUSH_DELALLOC_WAIT))
4164 flush_state = ALLOC_CHUNK;
4168 else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4169 flush_state < COMMIT_TRANS)
4171 else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
4172 flush_state <= COMMIT_TRANS)
4176 if (ret == -ENOSPC &&
4177 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
4178 struct btrfs_block_rsv *global_rsv =
4179 &root->fs_info->global_block_rsv;
4181 if (block_rsv != global_rsv &&
4182 !block_rsv_use_bytes(global_rsv, orig_bytes))
4186 spin_lock(&space_info->lock);
4187 space_info->flush = 0;
4188 wake_up_all(&space_info->wait);
4189 spin_unlock(&space_info->lock);
4194 static struct btrfs_block_rsv *get_block_rsv(
4195 const struct btrfs_trans_handle *trans,
4196 const struct btrfs_root *root)
4198 struct btrfs_block_rsv *block_rsv = NULL;
4201 block_rsv = trans->block_rsv;
4203 if (root == root->fs_info->csum_root && trans->adding_csums)
4204 block_rsv = trans->block_rsv;
4207 block_rsv = root->block_rsv;
4210 block_rsv = &root->fs_info->empty_block_rsv;
4215 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
4219 spin_lock(&block_rsv->lock);
4220 if (block_rsv->reserved >= num_bytes) {
4221 block_rsv->reserved -= num_bytes;
4222 if (block_rsv->reserved < block_rsv->size)
4223 block_rsv->full = 0;
4226 spin_unlock(&block_rsv->lock);
4230 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
4231 u64 num_bytes, int update_size)
4233 spin_lock(&block_rsv->lock);
4234 block_rsv->reserved += num_bytes;
4236 block_rsv->size += num_bytes;
4237 else if (block_rsv->reserved >= block_rsv->size)
4238 block_rsv->full = 1;
4239 spin_unlock(&block_rsv->lock);
4242 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
4243 struct btrfs_block_rsv *block_rsv,
4244 struct btrfs_block_rsv *dest, u64 num_bytes)
4246 struct btrfs_space_info *space_info = block_rsv->space_info;
4248 spin_lock(&block_rsv->lock);
4249 if (num_bytes == (u64)-1)
4250 num_bytes = block_rsv->size;
4251 block_rsv->size -= num_bytes;
4252 if (block_rsv->reserved >= block_rsv->size) {
4253 num_bytes = block_rsv->reserved - block_rsv->size;
4254 block_rsv->reserved = block_rsv->size;
4255 block_rsv->full = 1;
4259 spin_unlock(&block_rsv->lock);
4261 if (num_bytes > 0) {
4263 spin_lock(&dest->lock);
4267 bytes_to_add = dest->size - dest->reserved;
4268 bytes_to_add = min(num_bytes, bytes_to_add);
4269 dest->reserved += bytes_to_add;
4270 if (dest->reserved >= dest->size)
4272 num_bytes -= bytes_to_add;
4274 spin_unlock(&dest->lock);
4277 spin_lock(&space_info->lock);
4278 space_info->bytes_may_use -= num_bytes;
4279 trace_btrfs_space_reservation(fs_info, "space_info",
4280 space_info->flags, num_bytes, 0);
4281 space_info->reservation_progress++;
4282 spin_unlock(&space_info->lock);
4287 static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
4288 struct btrfs_block_rsv *dst, u64 num_bytes)
4292 ret = block_rsv_use_bytes(src, num_bytes);
4296 block_rsv_add_bytes(dst, num_bytes, 1);
4300 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
4302 memset(rsv, 0, sizeof(*rsv));
4303 spin_lock_init(&rsv->lock);
4307 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
4308 unsigned short type)
4310 struct btrfs_block_rsv *block_rsv;
4311 struct btrfs_fs_info *fs_info = root->fs_info;
4313 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
4317 btrfs_init_block_rsv(block_rsv, type);
4318 block_rsv->space_info = __find_space_info(fs_info,
4319 BTRFS_BLOCK_GROUP_METADATA);
4323 void btrfs_free_block_rsv(struct btrfs_root *root,
4324 struct btrfs_block_rsv *rsv)
4328 btrfs_block_rsv_release(root, rsv, (u64)-1);
4332 int btrfs_block_rsv_add(struct btrfs_root *root,
4333 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
4334 enum btrfs_reserve_flush_enum flush)
4341 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4343 block_rsv_add_bytes(block_rsv, num_bytes, 1);
4350 int btrfs_block_rsv_check(struct btrfs_root *root,
4351 struct btrfs_block_rsv *block_rsv, int min_factor)
4359 spin_lock(&block_rsv->lock);
4360 num_bytes = div_factor(block_rsv->size, min_factor);
4361 if (block_rsv->reserved >= num_bytes)
4363 spin_unlock(&block_rsv->lock);
4368 int btrfs_block_rsv_refill(struct btrfs_root *root,
4369 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
4370 enum btrfs_reserve_flush_enum flush)
4378 spin_lock(&block_rsv->lock);
4379 num_bytes = min_reserved;
4380 if (block_rsv->reserved >= num_bytes)
4383 num_bytes -= block_rsv->reserved;
4384 spin_unlock(&block_rsv->lock);
4389 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4391 block_rsv_add_bytes(block_rsv, num_bytes, 0);
4398 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
4399 struct btrfs_block_rsv *dst_rsv,
4402 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4405 void btrfs_block_rsv_release(struct btrfs_root *root,
4406 struct btrfs_block_rsv *block_rsv,
4409 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4410 if (global_rsv->full || global_rsv == block_rsv ||
4411 block_rsv->space_info != global_rsv->space_info)
4413 block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
4418 * helper to calculate size of global block reservation.
4419 * the desired value is sum of space used by extent tree,
4420 * checksum tree and root tree
4422 static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
4424 struct btrfs_space_info *sinfo;
4428 int csum_size = btrfs_super_csum_size(fs_info->super_copy);
4430 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
4431 spin_lock(&sinfo->lock);
4432 data_used = sinfo->bytes_used;
4433 spin_unlock(&sinfo->lock);
4435 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4436 spin_lock(&sinfo->lock);
4437 if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
4439 meta_used = sinfo->bytes_used;
4440 spin_unlock(&sinfo->lock);
4442 num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
4444 num_bytes += div64_u64(data_used + meta_used, 50);
4446 if (num_bytes * 3 > meta_used)
4447 num_bytes = div64_u64(meta_used, 3);
4449 return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
4452 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
4454 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4455 struct btrfs_space_info *sinfo = block_rsv->space_info;
4458 num_bytes = calc_global_metadata_size(fs_info);
4460 spin_lock(&sinfo->lock);
4461 spin_lock(&block_rsv->lock);
4463 block_rsv->size = min_t(u64, num_bytes, 512 * 1024 * 1024);
4465 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
4466 sinfo->bytes_reserved + sinfo->bytes_readonly +
4467 sinfo->bytes_may_use;
4469 if (sinfo->total_bytes > num_bytes) {
4470 num_bytes = sinfo->total_bytes - num_bytes;
4471 block_rsv->reserved += num_bytes;
4472 sinfo->bytes_may_use += num_bytes;
4473 trace_btrfs_space_reservation(fs_info, "space_info",
4474 sinfo->flags, num_bytes, 1);
4477 if (block_rsv->reserved >= block_rsv->size) {
4478 num_bytes = block_rsv->reserved - block_rsv->size;
4479 sinfo->bytes_may_use -= num_bytes;
4480 trace_btrfs_space_reservation(fs_info, "space_info",
4481 sinfo->flags, num_bytes, 0);
4482 sinfo->reservation_progress++;
4483 block_rsv->reserved = block_rsv->size;
4484 block_rsv->full = 1;
4487 spin_unlock(&block_rsv->lock);
4488 spin_unlock(&sinfo->lock);
4491 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
4493 struct btrfs_space_info *space_info;
4495 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4496 fs_info->chunk_block_rsv.space_info = space_info;
4498 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4499 fs_info->global_block_rsv.space_info = space_info;
4500 fs_info->delalloc_block_rsv.space_info = space_info;
4501 fs_info->trans_block_rsv.space_info = space_info;
4502 fs_info->empty_block_rsv.space_info = space_info;
4503 fs_info->delayed_block_rsv.space_info = space_info;
4505 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
4506 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
4507 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
4508 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
4509 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
4511 update_global_block_rsv(fs_info);
4514 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
4516 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
4518 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
4519 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
4520 WARN_ON(fs_info->trans_block_rsv.size > 0);
4521 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
4522 WARN_ON(fs_info->chunk_block_rsv.size > 0);
4523 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
4524 WARN_ON(fs_info->delayed_block_rsv.size > 0);
4525 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
4528 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
4529 struct btrfs_root *root)
4531 if (!trans->block_rsv)
4534 if (!trans->bytes_reserved)
4537 trace_btrfs_space_reservation(root->fs_info, "transaction",
4538 trans->transid, trans->bytes_reserved, 0);
4539 btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
4540 trans->bytes_reserved = 0;
4543 /* Can only return 0 or -ENOSPC */
4544 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
4545 struct inode *inode)
4547 struct btrfs_root *root = BTRFS_I(inode)->root;
4548 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4549 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
4552 * We need to hold space in order to delete our orphan item once we've
4553 * added it, so this takes the reservation so we can release it later
4554 * when we are truly done with the orphan item.
4556 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
4557 trace_btrfs_space_reservation(root->fs_info, "orphan",
4558 btrfs_ino(inode), num_bytes, 1);
4559 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4562 void btrfs_orphan_release_metadata(struct inode *inode)
4564 struct btrfs_root *root = BTRFS_I(inode)->root;
4565 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
4566 trace_btrfs_space_reservation(root->fs_info, "orphan",
4567 btrfs_ino(inode), num_bytes, 0);
4568 btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
4572 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
4573 * root: the root of the parent directory
4574 * rsv: block reservation
4575 * items: the number of items that we need do reservation
4576 * qgroup_reserved: used to return the reserved size in qgroup
4578 * This function is used to reserve the space for snapshot/subvolume
4579 * creation and deletion. Those operations are different with the
4580 * common file/directory operations, they change two fs/file trees
4581 * and root tree, the number of items that the qgroup reserves is
4582 * different with the free space reservation. So we can not use
4583 * the space reseravtion mechanism in start_transaction().
4585 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
4586 struct btrfs_block_rsv *rsv,
4588 u64 *qgroup_reserved)
4593 if (root->fs_info->quota_enabled) {
4594 /* One for parent inode, two for dir entries */
4595 num_bytes = 3 * root->leafsize;
4596 ret = btrfs_qgroup_reserve(root, num_bytes);
4603 *qgroup_reserved = num_bytes;
4605 num_bytes = btrfs_calc_trans_metadata_size(root, items);
4606 rsv->space_info = __find_space_info(root->fs_info,
4607 BTRFS_BLOCK_GROUP_METADATA);
4608 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
4609 BTRFS_RESERVE_FLUSH_ALL);
4611 if (*qgroup_reserved)
4612 btrfs_qgroup_free(root, *qgroup_reserved);
4618 void btrfs_subvolume_release_metadata(struct btrfs_root *root,
4619 struct btrfs_block_rsv *rsv,
4620 u64 qgroup_reserved)
4622 btrfs_block_rsv_release(root, rsv, (u64)-1);
4623 if (qgroup_reserved)
4624 btrfs_qgroup_free(root, qgroup_reserved);
4628 * drop_outstanding_extent - drop an outstanding extent
4629 * @inode: the inode we're dropping the extent for
4631 * This is called when we are freeing up an outstanding extent, either called
4632 * after an error or after an extent is written. This will return the number of
4633 * reserved extents that need to be freed. This must be called with
4634 * BTRFS_I(inode)->lock held.
4636 static unsigned drop_outstanding_extent(struct inode *inode)
4638 unsigned drop_inode_space = 0;
4639 unsigned dropped_extents = 0;
4641 BUG_ON(!BTRFS_I(inode)->outstanding_extents);
4642 BTRFS_I(inode)->outstanding_extents--;
4644 if (BTRFS_I(inode)->outstanding_extents == 0 &&
4645 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4646 &BTRFS_I(inode)->runtime_flags))
4647 drop_inode_space = 1;
4650 * If we have more or the same amount of outsanding extents than we have
4651 * reserved then we need to leave the reserved extents count alone.
4653 if (BTRFS_I(inode)->outstanding_extents >=
4654 BTRFS_I(inode)->reserved_extents)
4655 return drop_inode_space;
4657 dropped_extents = BTRFS_I(inode)->reserved_extents -
4658 BTRFS_I(inode)->outstanding_extents;
4659 BTRFS_I(inode)->reserved_extents -= dropped_extents;
4660 return dropped_extents + drop_inode_space;
4664 * calc_csum_metadata_size - return the amount of metada space that must be
4665 * reserved/free'd for the given bytes.
4666 * @inode: the inode we're manipulating
4667 * @num_bytes: the number of bytes in question
4668 * @reserve: 1 if we are reserving space, 0 if we are freeing space
4670 * This adjusts the number of csum_bytes in the inode and then returns the
4671 * correct amount of metadata that must either be reserved or freed. We
4672 * calculate how many checksums we can fit into one leaf and then divide the
4673 * number of bytes that will need to be checksumed by this value to figure out
4674 * how many checksums will be required. If we are adding bytes then the number
4675 * may go up and we will return the number of additional bytes that must be
4676 * reserved. If it is going down we will return the number of bytes that must
4679 * This must be called with BTRFS_I(inode)->lock held.
4681 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
4684 struct btrfs_root *root = BTRFS_I(inode)->root;
4686 int num_csums_per_leaf;
4690 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
4691 BTRFS_I(inode)->csum_bytes == 0)
4694 old_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
4696 BTRFS_I(inode)->csum_bytes += num_bytes;
4698 BTRFS_I(inode)->csum_bytes -= num_bytes;
4699 csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
4700 num_csums_per_leaf = (int)div64_u64(csum_size,
4701 sizeof(struct btrfs_csum_item) +
4702 sizeof(struct btrfs_disk_key));
4703 num_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
4704 num_csums = num_csums + num_csums_per_leaf - 1;
4705 num_csums = num_csums / num_csums_per_leaf;
4707 old_csums = old_csums + num_csums_per_leaf - 1;
4708 old_csums = old_csums / num_csums_per_leaf;
4710 /* No change, no need to reserve more */
4711 if (old_csums == num_csums)
4715 return btrfs_calc_trans_metadata_size(root,
4716 num_csums - old_csums);
4718 return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
4721 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
4723 struct btrfs_root *root = BTRFS_I(inode)->root;
4724 struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
4727 unsigned nr_extents = 0;
4728 int extra_reserve = 0;
4729 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
4731 bool delalloc_lock = true;
4735 /* If we are a free space inode we need to not flush since we will be in
4736 * the middle of a transaction commit. We also don't need the delalloc
4737 * mutex since we won't race with anybody. We need this mostly to make
4738 * lockdep shut its filthy mouth.
4740 if (btrfs_is_free_space_inode(inode)) {
4741 flush = BTRFS_RESERVE_NO_FLUSH;
4742 delalloc_lock = false;
4745 if (flush != BTRFS_RESERVE_NO_FLUSH &&
4746 btrfs_transaction_in_commit(root->fs_info))
4747 schedule_timeout(1);
4750 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
4752 num_bytes = ALIGN(num_bytes, root->sectorsize);
4754 spin_lock(&BTRFS_I(inode)->lock);
4755 BTRFS_I(inode)->outstanding_extents++;
4757 if (BTRFS_I(inode)->outstanding_extents >
4758 BTRFS_I(inode)->reserved_extents)
4759 nr_extents = BTRFS_I(inode)->outstanding_extents -
4760 BTRFS_I(inode)->reserved_extents;
4763 * Add an item to reserve for updating the inode when we complete the
4766 if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4767 &BTRFS_I(inode)->runtime_flags)) {
4772 to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
4773 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
4774 csum_bytes = BTRFS_I(inode)->csum_bytes;
4775 spin_unlock(&BTRFS_I(inode)->lock);
4777 if (root->fs_info->quota_enabled) {
4778 ret = btrfs_qgroup_reserve(root, num_bytes +
4779 nr_extents * root->leafsize);
4784 ret = reserve_metadata_bytes(root, block_rsv, to_reserve, flush);
4785 if (unlikely(ret)) {
4786 if (root->fs_info->quota_enabled)
4787 btrfs_qgroup_free(root, num_bytes +
4788 nr_extents * root->leafsize);
4792 spin_lock(&BTRFS_I(inode)->lock);
4793 if (extra_reserve) {
4794 set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4795 &BTRFS_I(inode)->runtime_flags);
4798 BTRFS_I(inode)->reserved_extents += nr_extents;
4799 spin_unlock(&BTRFS_I(inode)->lock);
4802 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
4805 trace_btrfs_space_reservation(root->fs_info,"delalloc",
4806 btrfs_ino(inode), to_reserve, 1);
4807 block_rsv_add_bytes(block_rsv, to_reserve, 1);
4812 spin_lock(&BTRFS_I(inode)->lock);
4813 dropped = drop_outstanding_extent(inode);
4815 * If the inodes csum_bytes is the same as the original
4816 * csum_bytes then we know we haven't raced with any free()ers
4817 * so we can just reduce our inodes csum bytes and carry on.
4819 if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
4820 calc_csum_metadata_size(inode, num_bytes, 0);
4822 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
4826 * This is tricky, but first we need to figure out how much we
4827 * free'd from any free-ers that occured during this
4828 * reservation, so we reset ->csum_bytes to the csum_bytes
4829 * before we dropped our lock, and then call the free for the
4830 * number of bytes that were freed while we were trying our
4833 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
4834 BTRFS_I(inode)->csum_bytes = csum_bytes;
4835 to_free = calc_csum_metadata_size(inode, bytes, 0);
4839 * Now we need to see how much we would have freed had we not
4840 * been making this reservation and our ->csum_bytes were not
4841 * artificially inflated.
4843 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
4844 bytes = csum_bytes - orig_csum_bytes;
4845 bytes = calc_csum_metadata_size(inode, bytes, 0);
4848 * Now reset ->csum_bytes to what it should be. If bytes is
4849 * more than to_free then we would have free'd more space had we
4850 * not had an artificially high ->csum_bytes, so we need to free
4851 * the remainder. If bytes is the same or less then we don't
4852 * need to do anything, the other free-ers did the correct
4855 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
4856 if (bytes > to_free)
4857 to_free = bytes - to_free;
4861 spin_unlock(&BTRFS_I(inode)->lock);
4863 to_free += btrfs_calc_trans_metadata_size(root, dropped);
4866 btrfs_block_rsv_release(root, block_rsv, to_free);
4867 trace_btrfs_space_reservation(root->fs_info, "delalloc",
4868 btrfs_ino(inode), to_free, 0);
4871 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
4876 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
4877 * @inode: the inode to release the reservation for
4878 * @num_bytes: the number of bytes we're releasing
4880 * This will release the metadata reservation for an inode. This can be called
4881 * once we complete IO for a given set of bytes to release their metadata
4884 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
4886 struct btrfs_root *root = BTRFS_I(inode)->root;
4890 num_bytes = ALIGN(num_bytes, root->sectorsize);
4891 spin_lock(&BTRFS_I(inode)->lock);
4892 dropped = drop_outstanding_extent(inode);
4895 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
4896 spin_unlock(&BTRFS_I(inode)->lock);
4898 to_free += btrfs_calc_trans_metadata_size(root, dropped);
4900 trace_btrfs_space_reservation(root->fs_info, "delalloc",
4901 btrfs_ino(inode), to_free, 0);
4902 if (root->fs_info->quota_enabled) {
4903 btrfs_qgroup_free(root, num_bytes +
4904 dropped * root->leafsize);
4907 btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
4912 * btrfs_delalloc_reserve_space - reserve data and metadata space for delalloc
4913 * @inode: inode we're writing to
4914 * @num_bytes: the number of bytes we want to allocate
4916 * This will do the following things
4918 * o reserve space in the data space info for num_bytes
4919 * o reserve space in the metadata space info based on number of outstanding
4920 * extents and how much csums will be needed
4921 * o add to the inodes ->delalloc_bytes
4922 * o add it to the fs_info's delalloc inodes list.
4924 * This will return 0 for success and -ENOSPC if there is no space left.
4926 int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
4930 ret = btrfs_check_data_free_space(inode, num_bytes);
4934 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
4936 btrfs_free_reserved_data_space(inode, num_bytes);
4944 * btrfs_delalloc_release_space - release data and metadata space for delalloc
4945 * @inode: inode we're releasing space for
4946 * @num_bytes: the number of bytes we want to free up
4948 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
4949 * called in the case that we don't need the metadata AND data reservations
4950 * anymore. So if there is an error or we insert an inline extent.
4952 * This function will release the metadata space that was not used and will
4953 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
4954 * list if there are no delalloc bytes left.
4956 void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
4958 btrfs_delalloc_release_metadata(inode, num_bytes);
4959 btrfs_free_reserved_data_space(inode, num_bytes);
4962 static int update_block_group(struct btrfs_root *root,
4963 u64 bytenr, u64 num_bytes, int alloc)
4965 struct btrfs_block_group_cache *cache = NULL;
4966 struct btrfs_fs_info *info = root->fs_info;
4967 u64 total = num_bytes;
4972 /* block accounting for super block */
4973 spin_lock(&info->delalloc_lock);
4974 old_val = btrfs_super_bytes_used(info->super_copy);
4976 old_val += num_bytes;
4978 old_val -= num_bytes;
4979 btrfs_set_super_bytes_used(info->super_copy, old_val);
4980 spin_unlock(&info->delalloc_lock);
4983 cache = btrfs_lookup_block_group(info, bytenr);
4986 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
4987 BTRFS_BLOCK_GROUP_RAID1 |
4988 BTRFS_BLOCK_GROUP_RAID10))
4993 * If this block group has free space cache written out, we
4994 * need to make sure to load it if we are removing space. This
4995 * is because we need the unpinning stage to actually add the
4996 * space back to the block group, otherwise we will leak space.
4998 if (!alloc && cache->cached == BTRFS_CACHE_NO)
4999 cache_block_group(cache, 1);
5001 byte_in_group = bytenr - cache->key.objectid;
5002 WARN_ON(byte_in_group > cache->key.offset);
5004 spin_lock(&cache->space_info->lock);
5005 spin_lock(&cache->lock);
5007 if (btrfs_test_opt(root, SPACE_CACHE) &&
5008 cache->disk_cache_state < BTRFS_DC_CLEAR)
5009 cache->disk_cache_state = BTRFS_DC_CLEAR;
5012 old_val = btrfs_block_group_used(&cache->item);
5013 num_bytes = min(total, cache->key.offset - byte_in_group);
5015 old_val += num_bytes;
5016 btrfs_set_block_group_used(&cache->item, old_val);
5017 cache->reserved -= num_bytes;
5018 cache->space_info->bytes_reserved -= num_bytes;
5019 cache->space_info->bytes_used += num_bytes;
5020 cache->space_info->disk_used += num_bytes * factor;
5021 spin_unlock(&cache->lock);
5022 spin_unlock(&cache->space_info->lock);
5024 old_val -= num_bytes;
5025 btrfs_set_block_group_used(&cache->item, old_val);
5026 cache->pinned += num_bytes;
5027 cache->space_info->bytes_pinned += num_bytes;
5028 cache->space_info->bytes_used -= num_bytes;
5029 cache->space_info->disk_used -= num_bytes * factor;
5030 spin_unlock(&cache->lock);
5031 spin_unlock(&cache->space_info->lock);
5033 set_extent_dirty(info->pinned_extents,
5034 bytenr, bytenr + num_bytes - 1,
5035 GFP_NOFS | __GFP_NOFAIL);
5037 btrfs_put_block_group(cache);
5039 bytenr += num_bytes;
5044 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
5046 struct btrfs_block_group_cache *cache;
5049 spin_lock(&root->fs_info->block_group_cache_lock);
5050 bytenr = root->fs_info->first_logical_byte;
5051 spin_unlock(&root->fs_info->block_group_cache_lock);
5053 if (bytenr < (u64)-1)
5056 cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
5060 bytenr = cache->key.objectid;
5061 btrfs_put_block_group(cache);
5066 static int pin_down_extent(struct btrfs_root *root,
5067 struct btrfs_block_group_cache *cache,
5068 u64 bytenr, u64 num_bytes, int reserved)
5070 spin_lock(&cache->space_info->lock);
5071 spin_lock(&cache->lock);
5072 cache->pinned += num_bytes;
5073 cache->space_info->bytes_pinned += num_bytes;
5075 cache->reserved -= num_bytes;
5076 cache->space_info->bytes_reserved -= num_bytes;
5078 spin_unlock(&cache->lock);
5079 spin_unlock(&cache->space_info->lock);
5081 set_extent_dirty(root->fs_info->pinned_extents, bytenr,
5082 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
5087 * this function must be called within transaction
5089 int btrfs_pin_extent(struct btrfs_root *root,
5090 u64 bytenr, u64 num_bytes, int reserved)
5092 struct btrfs_block_group_cache *cache;
5094 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
5095 BUG_ON(!cache); /* Logic error */
5097 pin_down_extent(root, cache, bytenr, num_bytes, reserved);
5099 btrfs_put_block_group(cache);
5104 * this function must be called within transaction
5106 int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
5107 u64 bytenr, u64 num_bytes)
5109 struct btrfs_block_group_cache *cache;
5111 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
5112 BUG_ON(!cache); /* Logic error */
5115 * pull in the free space cache (if any) so that our pin
5116 * removes the free space from the cache. We have load_only set
5117 * to one because the slow code to read in the free extents does check
5118 * the pinned extents.
5120 cache_block_group(cache, 1);
5122 pin_down_extent(root, cache, bytenr, num_bytes, 0);
5124 /* remove us from the free space cache (if we're there at all) */
5125 btrfs_remove_free_space(cache, bytenr, num_bytes);
5126 btrfs_put_block_group(cache);
5131 * btrfs_update_reserved_bytes - update the block_group and space info counters
5132 * @cache: The cache we are manipulating
5133 * @num_bytes: The number of bytes in question
5134 * @reserve: One of the reservation enums
5136 * This is called by the allocator when it reserves space, or by somebody who is
5137 * freeing space that was never actually used on disk. For example if you
5138 * reserve some space for a new leaf in transaction A and before transaction A
5139 * commits you free that leaf, you call this with reserve set to 0 in order to
5140 * clear the reservation.
5142 * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
5143 * ENOSPC accounting. For data we handle the reservation through clearing the
5144 * delalloc bits in the io_tree. We have to do this since we could end up
5145 * allocating less disk space for the amount of data we have reserved in the
5146 * case of compression.
5148 * If this is a reservation and the block group has become read only we cannot
5149 * make the reservation and return -EAGAIN, otherwise this function always
5152 static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
5153 u64 num_bytes, int reserve)
5155 struct btrfs_space_info *space_info = cache->space_info;
5158 spin_lock(&space_info->lock);
5159 spin_lock(&cache->lock);
5160 if (reserve != RESERVE_FREE) {
5164 cache->reserved += num_bytes;
5165 space_info->bytes_reserved += num_bytes;
5166 if (reserve == RESERVE_ALLOC) {
5167 trace_btrfs_space_reservation(cache->fs_info,
5168 "space_info", space_info->flags,
5170 space_info->bytes_may_use -= num_bytes;
5175 space_info->bytes_readonly += num_bytes;
5176 cache->reserved -= num_bytes;
5177 space_info->bytes_reserved -= num_bytes;
5178 space_info->reservation_progress++;
5180 spin_unlock(&cache->lock);
5181 spin_unlock(&space_info->lock);
5185 void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
5186 struct btrfs_root *root)
5188 struct btrfs_fs_info *fs_info = root->fs_info;
5189 struct btrfs_caching_control *next;
5190 struct btrfs_caching_control *caching_ctl;
5191 struct btrfs_block_group_cache *cache;
5193 down_write(&fs_info->extent_commit_sem);
5195 list_for_each_entry_safe(caching_ctl, next,
5196 &fs_info->caching_block_groups, list) {
5197 cache = caching_ctl->block_group;
5198 if (block_group_cache_done(cache)) {
5199 cache->last_byte_to_unpin = (u64)-1;
5200 list_del_init(&caching_ctl->list);
5201 put_caching_control(caching_ctl);
5203 cache->last_byte_to_unpin = caching_ctl->progress;
5207 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5208 fs_info->pinned_extents = &fs_info->freed_extents[1];
5210 fs_info->pinned_extents = &fs_info->freed_extents[0];
5212 up_write(&fs_info->extent_commit_sem);
5214 update_global_block_rsv(fs_info);
5217 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
5219 struct btrfs_fs_info *fs_info = root->fs_info;
5220 struct btrfs_block_group_cache *cache = NULL;
5221 struct btrfs_space_info *space_info;
5222 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5226 while (start <= end) {
5229 start >= cache->key.objectid + cache->key.offset) {
5231 btrfs_put_block_group(cache);
5232 cache = btrfs_lookup_block_group(fs_info, start);
5233 BUG_ON(!cache); /* Logic error */
5236 len = cache->key.objectid + cache->key.offset - start;
5237 len = min(len, end + 1 - start);
5239 if (start < cache->last_byte_to_unpin) {
5240 len = min(len, cache->last_byte_to_unpin - start);
5241 btrfs_add_free_space(cache, start, len);
5245 space_info = cache->space_info;
5247 spin_lock(&space_info->lock);
5248 spin_lock(&cache->lock);
5249 cache->pinned -= len;
5250 space_info->bytes_pinned -= len;
5252 space_info->bytes_readonly += len;
5255 spin_unlock(&cache->lock);
5256 if (!readonly && global_rsv->space_info == space_info) {
5257 spin_lock(&global_rsv->lock);
5258 if (!global_rsv->full) {
5259 len = min(len, global_rsv->size -
5260 global_rsv->reserved);
5261 global_rsv->reserved += len;
5262 space_info->bytes_may_use += len;
5263 if (global_rsv->reserved >= global_rsv->size)
5264 global_rsv->full = 1;
5266 spin_unlock(&global_rsv->lock);
5268 spin_unlock(&space_info->lock);
5272 btrfs_put_block_group(cache);
5276 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
5277 struct btrfs_root *root)
5279 struct btrfs_fs_info *fs_info = root->fs_info;
5280 struct extent_io_tree *unpin;
5288 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5289 unpin = &fs_info->freed_extents[1];
5291 unpin = &fs_info->freed_extents[0];
5294 ret = find_first_extent_bit(unpin, 0, &start, &end,
5295 EXTENT_DIRTY, NULL);
5299 if (btrfs_test_opt(root, DISCARD))
5300 ret = btrfs_discard_extent(root, start,
5301 end + 1 - start, NULL);
5303 clear_extent_dirty(unpin, start, end, GFP_NOFS);
5304 unpin_extent_range(root, start, end);
5311 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
5312 struct btrfs_root *root,
5313 u64 bytenr, u64 num_bytes, u64 parent,
5314 u64 root_objectid, u64 owner_objectid,
5315 u64 owner_offset, int refs_to_drop,
5316 struct btrfs_delayed_extent_op *extent_op)
5318 struct btrfs_key key;
5319 struct btrfs_path *path;
5320 struct btrfs_fs_info *info = root->fs_info;
5321 struct btrfs_root *extent_root = info->extent_root;
5322 struct extent_buffer *leaf;
5323 struct btrfs_extent_item *ei;
5324 struct btrfs_extent_inline_ref *iref;
5327 int extent_slot = 0;
5328 int found_extent = 0;
5333 path = btrfs_alloc_path();
5338 path->leave_spinning = 1;
5340 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
5341 BUG_ON(!is_data && refs_to_drop != 1);
5343 ret = lookup_extent_backref(trans, extent_root, path, &iref,
5344 bytenr, num_bytes, parent,
5345 root_objectid, owner_objectid,
5348 extent_slot = path->slots[0];
5349 while (extent_slot >= 0) {
5350 btrfs_item_key_to_cpu(path->nodes[0], &key,
5352 if (key.objectid != bytenr)
5354 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5355 key.offset == num_bytes) {
5359 if (path->slots[0] - extent_slot > 5)
5363 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5364 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
5365 if (found_extent && item_size < sizeof(*ei))
5368 if (!found_extent) {
5370 ret = remove_extent_backref(trans, extent_root, path,
5374 btrfs_abort_transaction(trans, extent_root, ret);
5377 btrfs_release_path(path);
5378 path->leave_spinning = 1;
5380 key.objectid = bytenr;
5381 key.type = BTRFS_EXTENT_ITEM_KEY;
5382 key.offset = num_bytes;
5384 ret = btrfs_search_slot(trans, extent_root,
5387 printk(KERN_ERR "umm, got %d back from search"
5388 ", was looking for %llu\n", ret,
5389 (unsigned long long)bytenr);
5391 btrfs_print_leaf(extent_root,
5395 btrfs_abort_transaction(trans, extent_root, ret);
5398 extent_slot = path->slots[0];
5400 } else if (ret == -ENOENT) {
5401 btrfs_print_leaf(extent_root, path->nodes[0]);
5403 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
5404 "parent %llu root %llu owner %llu offset %llu\n",
5405 (unsigned long long)bytenr,
5406 (unsigned long long)parent,
5407 (unsigned long long)root_objectid,
5408 (unsigned long long)owner_objectid,
5409 (unsigned long long)owner_offset);
5411 btrfs_abort_transaction(trans, extent_root, ret);
5415 leaf = path->nodes[0];
5416 item_size = btrfs_item_size_nr(leaf, extent_slot);
5417 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5418 if (item_size < sizeof(*ei)) {
5419 BUG_ON(found_extent || extent_slot != path->slots[0]);
5420 ret = convert_extent_item_v0(trans, extent_root, path,
5423 btrfs_abort_transaction(trans, extent_root, ret);
5427 btrfs_release_path(path);
5428 path->leave_spinning = 1;
5430 key.objectid = bytenr;
5431 key.type = BTRFS_EXTENT_ITEM_KEY;
5432 key.offset = num_bytes;
5434 ret = btrfs_search_slot(trans, extent_root, &key, path,
5437 printk(KERN_ERR "umm, got %d back from search"
5438 ", was looking for %llu\n", ret,
5439 (unsigned long long)bytenr);
5440 btrfs_print_leaf(extent_root, path->nodes[0]);
5443 btrfs_abort_transaction(trans, extent_root, ret);
5447 extent_slot = path->slots[0];
5448 leaf = path->nodes[0];
5449 item_size = btrfs_item_size_nr(leaf, extent_slot);
5452 BUG_ON(item_size < sizeof(*ei));
5453 ei = btrfs_item_ptr(leaf, extent_slot,
5454 struct btrfs_extent_item);
5455 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
5456 struct btrfs_tree_block_info *bi;
5457 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
5458 bi = (struct btrfs_tree_block_info *)(ei + 1);
5459 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
5462 refs = btrfs_extent_refs(leaf, ei);
5463 BUG_ON(refs < refs_to_drop);
5464 refs -= refs_to_drop;
5468 __run_delayed_extent_op(extent_op, leaf, ei);
5470 * In the case of inline back ref, reference count will
5471 * be updated by remove_extent_backref
5474 BUG_ON(!found_extent);
5476 btrfs_set_extent_refs(leaf, ei, refs);
5477 btrfs_mark_buffer_dirty(leaf);
5480 ret = remove_extent_backref(trans, extent_root, path,
5484 btrfs_abort_transaction(trans, extent_root, ret);
5490 BUG_ON(is_data && refs_to_drop !=
5491 extent_data_ref_count(root, path, iref));
5493 BUG_ON(path->slots[0] != extent_slot);
5495 BUG_ON(path->slots[0] != extent_slot + 1);
5496 path->slots[0] = extent_slot;
5501 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
5504 btrfs_abort_transaction(trans, extent_root, ret);
5507 btrfs_release_path(path);
5510 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
5512 btrfs_abort_transaction(trans, extent_root, ret);
5517 ret = update_block_group(root, bytenr, num_bytes, 0);
5519 btrfs_abort_transaction(trans, extent_root, ret);
5524 btrfs_free_path(path);
5529 * when we free an block, it is possible (and likely) that we free the last
5530 * delayed ref for that extent as well. This searches the delayed ref tree for
5531 * a given extent, and if there are no other delayed refs to be processed, it
5532 * removes it from the tree.
5534 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
5535 struct btrfs_root *root, u64 bytenr)
5537 struct btrfs_delayed_ref_head *head;
5538 struct btrfs_delayed_ref_root *delayed_refs;
5539 struct btrfs_delayed_ref_node *ref;
5540 struct rb_node *node;
5543 delayed_refs = &trans->transaction->delayed_refs;
5544 spin_lock(&delayed_refs->lock);
5545 head = btrfs_find_delayed_ref_head(trans, bytenr);
5549 node = rb_prev(&head->node.rb_node);
5553 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
5555 /* there are still entries for this ref, we can't drop it */
5556 if (ref->bytenr == bytenr)
5559 if (head->extent_op) {
5560 if (!head->must_insert_reserved)
5562 btrfs_free_delayed_extent_op(head->extent_op);
5563 head->extent_op = NULL;
5567 * waiting for the lock here would deadlock. If someone else has it
5568 * locked they are already in the process of dropping it anyway
5570 if (!mutex_trylock(&head->mutex))
5574 * at this point we have a head with no other entries. Go
5575 * ahead and process it.
5577 head->node.in_tree = 0;
5578 rb_erase(&head->node.rb_node, &delayed_refs->root);
5580 delayed_refs->num_entries--;
5583 * we don't take a ref on the node because we're removing it from the
5584 * tree, so we just steal the ref the tree was holding.
5586 delayed_refs->num_heads--;
5587 if (list_empty(&head->cluster))
5588 delayed_refs->num_heads_ready--;
5590 list_del_init(&head->cluster);
5591 spin_unlock(&delayed_refs->lock);
5593 BUG_ON(head->extent_op);
5594 if (head->must_insert_reserved)
5597 mutex_unlock(&head->mutex);
5598 btrfs_put_delayed_ref(&head->node);
5601 spin_unlock(&delayed_refs->lock);
5605 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
5606 struct btrfs_root *root,
5607 struct extent_buffer *buf,
5608 u64 parent, int last_ref)
5610 struct btrfs_block_group_cache *cache = NULL;
5613 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5614 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
5615 buf->start, buf->len,
5616 parent, root->root_key.objectid,
5617 btrfs_header_level(buf),
5618 BTRFS_DROP_DELAYED_REF, NULL, 0);
5619 BUG_ON(ret); /* -ENOMEM */
5625 cache = btrfs_lookup_block_group(root->fs_info, buf->start);
5627 if (btrfs_header_generation(buf) == trans->transid) {
5628 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5629 ret = check_ref_cleanup(trans, root, buf->start);
5634 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
5635 pin_down_extent(root, cache, buf->start, buf->len, 1);
5639 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
5641 btrfs_add_free_space(cache, buf->start, buf->len);
5642 btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE);
5646 * Deleting the buffer, clear the corrupt flag since it doesn't matter
5649 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
5650 btrfs_put_block_group(cache);
5653 /* Can return -ENOMEM */
5654 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5655 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
5656 u64 owner, u64 offset, int for_cow)
5659 struct btrfs_fs_info *fs_info = root->fs_info;
5662 * tree log blocks never actually go into the extent allocation
5663 * tree, just update pinning info and exit early.
5665 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
5666 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
5667 /* unlocks the pinned mutex */
5668 btrfs_pin_extent(root, bytenr, num_bytes, 1);
5670 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
5671 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
5673 parent, root_objectid, (int)owner,
5674 BTRFS_DROP_DELAYED_REF, NULL, for_cow);
5676 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
5678 parent, root_objectid, owner,
5679 offset, BTRFS_DROP_DELAYED_REF,
5685 static u64 stripe_align(struct btrfs_root *root,
5686 struct btrfs_block_group_cache *cache,
5687 u64 val, u64 num_bytes)
5689 u64 ret = ALIGN(val, root->stripesize);
5694 * when we wait for progress in the block group caching, its because
5695 * our allocation attempt failed at least once. So, we must sleep
5696 * and let some progress happen before we try again.
5698 * This function will sleep at least once waiting for new free space to
5699 * show up, and then it will check the block group free space numbers
5700 * for our min num_bytes. Another option is to have it go ahead
5701 * and look in the rbtree for a free extent of a given size, but this
5705 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
5708 struct btrfs_caching_control *caching_ctl;
5710 caching_ctl = get_caching_control(cache);
5714 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
5715 (cache->free_space_ctl->free_space >= num_bytes));
5717 put_caching_control(caching_ctl);
5722 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
5724 struct btrfs_caching_control *caching_ctl;
5726 caching_ctl = get_caching_control(cache);
5730 wait_event(caching_ctl->wait, block_group_cache_done(cache));
5732 put_caching_control(caching_ctl);
5736 int __get_raid_index(u64 flags)
5738 if (flags & BTRFS_BLOCK_GROUP_RAID10)
5739 return BTRFS_RAID_RAID10;
5740 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
5741 return BTRFS_RAID_RAID1;
5742 else if (flags & BTRFS_BLOCK_GROUP_DUP)
5743 return BTRFS_RAID_DUP;
5744 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
5745 return BTRFS_RAID_RAID0;
5746 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
5747 return BTRFS_RAID_RAID5;
5748 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
5749 return BTRFS_RAID_RAID6;
5751 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
5754 static int get_block_group_index(struct btrfs_block_group_cache *cache)
5756 return __get_raid_index(cache->flags);
5759 enum btrfs_loop_type {
5760 LOOP_CACHING_NOWAIT = 0,
5761 LOOP_CACHING_WAIT = 1,
5762 LOOP_ALLOC_CHUNK = 2,
5763 LOOP_NO_EMPTY_SIZE = 3,
5767 * walks the btree of allocated extents and find a hole of a given size.
5768 * The key ins is changed to record the hole:
5769 * ins->objectid == block start
5770 * ins->flags = BTRFS_EXTENT_ITEM_KEY
5771 * ins->offset == number of blocks
5772 * Any available blocks before search_start are skipped.
5774 static noinline int find_free_extent(struct btrfs_trans_handle *trans,
5775 struct btrfs_root *orig_root,
5776 u64 num_bytes, u64 empty_size,
5777 u64 hint_byte, struct btrfs_key *ins,
5781 struct btrfs_root *root = orig_root->fs_info->extent_root;
5782 struct btrfs_free_cluster *last_ptr = NULL;
5783 struct btrfs_block_group_cache *block_group = NULL;
5784 struct btrfs_block_group_cache *used_block_group;
5785 u64 search_start = 0;
5786 int empty_cluster = 2 * 1024 * 1024;
5787 struct btrfs_space_info *space_info;
5789 int index = __get_raid_index(data);
5790 int alloc_type = (data & BTRFS_BLOCK_GROUP_DATA) ?
5791 RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
5792 bool found_uncached_bg = false;
5793 bool failed_cluster_refill = false;
5794 bool failed_alloc = false;
5795 bool use_cluster = true;
5796 bool have_caching_bg = false;
5798 WARN_ON(num_bytes < root->sectorsize);
5799 btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
5803 trace_find_free_extent(orig_root, num_bytes, empty_size, data);
5805 space_info = __find_space_info(root->fs_info, data);
5807 printk(KERN_ERR "No space info for %llu\n", data);
5812 * If the space info is for both data and metadata it means we have a
5813 * small filesystem and we can't use the clustering stuff.
5815 if (btrfs_mixed_space_info(space_info))
5816 use_cluster = false;
5818 if (data & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
5819 last_ptr = &root->fs_info->meta_alloc_cluster;
5820 if (!btrfs_test_opt(root, SSD))
5821 empty_cluster = 64 * 1024;
5824 if ((data & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
5825 btrfs_test_opt(root, SSD)) {
5826 last_ptr = &root->fs_info->data_alloc_cluster;
5830 spin_lock(&last_ptr->lock);
5831 if (last_ptr->block_group)
5832 hint_byte = last_ptr->window_start;
5833 spin_unlock(&last_ptr->lock);
5836 search_start = max(search_start, first_logical_byte(root, 0));
5837 search_start = max(search_start, hint_byte);
5842 if (search_start == hint_byte) {
5843 block_group = btrfs_lookup_block_group(root->fs_info,
5845 used_block_group = block_group;
5847 * we don't want to use the block group if it doesn't match our
5848 * allocation bits, or if its not cached.
5850 * However if we are re-searching with an ideal block group
5851 * picked out then we don't care that the block group is cached.
5853 if (block_group && block_group_bits(block_group, data) &&
5854 block_group->cached != BTRFS_CACHE_NO) {
5855 down_read(&space_info->groups_sem);
5856 if (list_empty(&block_group->list) ||
5859 * someone is removing this block group,
5860 * we can't jump into the have_block_group
5861 * target because our list pointers are not
5864 btrfs_put_block_group(block_group);
5865 up_read(&space_info->groups_sem);
5867 index = get_block_group_index(block_group);
5868 goto have_block_group;
5870 } else if (block_group) {
5871 btrfs_put_block_group(block_group);
5875 have_caching_bg = false;
5876 down_read(&space_info->groups_sem);
5877 list_for_each_entry(block_group, &space_info->block_groups[index],
5882 used_block_group = block_group;
5883 btrfs_get_block_group(block_group);
5884 search_start = block_group->key.objectid;
5887 * this can happen if we end up cycling through all the
5888 * raid types, but we want to make sure we only allocate
5889 * for the proper type.
5891 if (!block_group_bits(block_group, data)) {
5892 u64 extra = BTRFS_BLOCK_GROUP_DUP |
5893 BTRFS_BLOCK_GROUP_RAID1 |
5894 BTRFS_BLOCK_GROUP_RAID5 |
5895 BTRFS_BLOCK_GROUP_RAID6 |
5896 BTRFS_BLOCK_GROUP_RAID10;
5899 * if they asked for extra copies and this block group
5900 * doesn't provide them, bail. This does allow us to
5901 * fill raid0 from raid1.
5903 if ((data & extra) && !(block_group->flags & extra))
5908 cached = block_group_cache_done(block_group);
5909 if (unlikely(!cached)) {
5910 found_uncached_bg = true;
5911 ret = cache_block_group(block_group, 0);
5916 if (unlikely(block_group->ro))
5920 * Ok we want to try and use the cluster allocator, so
5924 unsigned long aligned_cluster;
5926 * the refill lock keeps out other
5927 * people trying to start a new cluster
5929 spin_lock(&last_ptr->refill_lock);
5930 used_block_group = last_ptr->block_group;
5931 if (used_block_group != block_group &&
5932 (!used_block_group ||
5933 used_block_group->ro ||
5934 !block_group_bits(used_block_group, data))) {
5935 used_block_group = block_group;
5936 goto refill_cluster;
5939 if (used_block_group != block_group)
5940 btrfs_get_block_group(used_block_group);
5942 offset = btrfs_alloc_from_cluster(used_block_group,
5943 last_ptr, num_bytes, used_block_group->key.objectid);
5945 /* we have a block, we're done */
5946 spin_unlock(&last_ptr->refill_lock);
5947 trace_btrfs_reserve_extent_cluster(root,
5948 block_group, search_start, num_bytes);
5952 WARN_ON(last_ptr->block_group != used_block_group);
5953 if (used_block_group != block_group) {
5954 btrfs_put_block_group(used_block_group);
5955 used_block_group = block_group;
5958 BUG_ON(used_block_group != block_group);
5959 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
5960 * set up a new clusters, so lets just skip it
5961 * and let the allocator find whatever block
5962 * it can find. If we reach this point, we
5963 * will have tried the cluster allocator
5964 * plenty of times and not have found
5965 * anything, so we are likely way too
5966 * fragmented for the clustering stuff to find
5969 * However, if the cluster is taken from the
5970 * current block group, release the cluster
5971 * first, so that we stand a better chance of
5972 * succeeding in the unclustered
5974 if (loop >= LOOP_NO_EMPTY_SIZE &&
5975 last_ptr->block_group != block_group) {
5976 spin_unlock(&last_ptr->refill_lock);
5977 goto unclustered_alloc;
5981 * this cluster didn't work out, free it and
5984 btrfs_return_cluster_to_free_space(NULL, last_ptr);
5986 if (loop >= LOOP_NO_EMPTY_SIZE) {
5987 spin_unlock(&last_ptr->refill_lock);
5988 goto unclustered_alloc;
5991 aligned_cluster = max_t(unsigned long,
5992 empty_cluster + empty_size,
5993 block_group->full_stripe_len);
5995 /* allocate a cluster in this block group */
5996 ret = btrfs_find_space_cluster(trans, root,
5997 block_group, last_ptr,
5998 search_start, num_bytes,
6002 * now pull our allocation out of this
6005 offset = btrfs_alloc_from_cluster(block_group,
6006 last_ptr, num_bytes,
6009 /* we found one, proceed */
6010 spin_unlock(&last_ptr->refill_lock);
6011 trace_btrfs_reserve_extent_cluster(root,
6012 block_group, search_start,
6016 } else if (!cached && loop > LOOP_CACHING_NOWAIT
6017 && !failed_cluster_refill) {
6018 spin_unlock(&last_ptr->refill_lock);
6020 failed_cluster_refill = true;
6021 wait_block_group_cache_progress(block_group,
6022 num_bytes + empty_cluster + empty_size);
6023 goto have_block_group;
6027 * at this point we either didn't find a cluster
6028 * or we weren't able to allocate a block from our
6029 * cluster. Free the cluster we've been trying
6030 * to use, and go to the next block group
6032 btrfs_return_cluster_to_free_space(NULL, last_ptr);
6033 spin_unlock(&last_ptr->refill_lock);
6038 spin_lock(&block_group->free_space_ctl->tree_lock);
6040 block_group->free_space_ctl->free_space <
6041 num_bytes + empty_cluster + empty_size) {
6042 spin_unlock(&block_group->free_space_ctl->tree_lock);
6045 spin_unlock(&block_group->free_space_ctl->tree_lock);
6047 offset = btrfs_find_space_for_alloc(block_group, search_start,
6048 num_bytes, empty_size);
6050 * If we didn't find a chunk, and we haven't failed on this
6051 * block group before, and this block group is in the middle of
6052 * caching and we are ok with waiting, then go ahead and wait
6053 * for progress to be made, and set failed_alloc to true.
6055 * If failed_alloc is true then we've already waited on this
6056 * block group once and should move on to the next block group.
6058 if (!offset && !failed_alloc && !cached &&
6059 loop > LOOP_CACHING_NOWAIT) {
6060 wait_block_group_cache_progress(block_group,
6061 num_bytes + empty_size);
6062 failed_alloc = true;
6063 goto have_block_group;
6064 } else if (!offset) {
6066 have_caching_bg = true;
6070 search_start = stripe_align(root, used_block_group,
6073 /* move on to the next group */
6074 if (search_start + num_bytes >
6075 used_block_group->key.objectid + used_block_group->key.offset) {
6076 btrfs_add_free_space(used_block_group, offset, num_bytes);
6080 if (offset < search_start)
6081 btrfs_add_free_space(used_block_group, offset,
6082 search_start - offset);
6083 BUG_ON(offset > search_start);
6085 ret = btrfs_update_reserved_bytes(used_block_group, num_bytes,
6087 if (ret == -EAGAIN) {
6088 btrfs_add_free_space(used_block_group, offset, num_bytes);
6092 /* we are all good, lets return */
6093 ins->objectid = search_start;
6094 ins->offset = num_bytes;
6096 trace_btrfs_reserve_extent(orig_root, block_group,
6097 search_start, num_bytes);
6098 if (used_block_group != block_group)
6099 btrfs_put_block_group(used_block_group);
6100 btrfs_put_block_group(block_group);
6103 failed_cluster_refill = false;
6104 failed_alloc = false;
6105 BUG_ON(index != get_block_group_index(block_group));
6106 if (used_block_group != block_group)
6107 btrfs_put_block_group(used_block_group);
6108 btrfs_put_block_group(block_group);
6110 up_read(&space_info->groups_sem);
6112 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
6115 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
6119 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
6120 * caching kthreads as we move along
6121 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
6122 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
6123 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
6126 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
6129 if (loop == LOOP_ALLOC_CHUNK) {
6130 ret = do_chunk_alloc(trans, root, data,
6133 * Do not bail out on ENOSPC since we
6134 * can do more things.
6136 if (ret < 0 && ret != -ENOSPC) {
6137 btrfs_abort_transaction(trans,
6143 if (loop == LOOP_NO_EMPTY_SIZE) {
6149 } else if (!ins->objectid) {
6151 } else if (ins->objectid) {
6159 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
6160 int dump_block_groups)
6162 struct btrfs_block_group_cache *cache;
6165 spin_lock(&info->lock);
6166 printk(KERN_INFO "space_info %llu has %llu free, is %sfull\n",
6167 (unsigned long long)info->flags,
6168 (unsigned long long)(info->total_bytes - info->bytes_used -
6169 info->bytes_pinned - info->bytes_reserved -
6170 info->bytes_readonly),
6171 (info->full) ? "" : "not ");
6172 printk(KERN_INFO "space_info total=%llu, used=%llu, pinned=%llu, "
6173 "reserved=%llu, may_use=%llu, readonly=%llu\n",
6174 (unsigned long long)info->total_bytes,
6175 (unsigned long long)info->bytes_used,
6176 (unsigned long long)info->bytes_pinned,
6177 (unsigned long long)info->bytes_reserved,
6178 (unsigned long long)info->bytes_may_use,
6179 (unsigned long long)info->bytes_readonly);
6180 spin_unlock(&info->lock);
6182 if (!dump_block_groups)
6185 down_read(&info->groups_sem);
6187 list_for_each_entry(cache, &info->block_groups[index], list) {
6188 spin_lock(&cache->lock);
6189 printk(KERN_INFO "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s\n",
6190 (unsigned long long)cache->key.objectid,
6191 (unsigned long long)cache->key.offset,
6192 (unsigned long long)btrfs_block_group_used(&cache->item),
6193 (unsigned long long)cache->pinned,
6194 (unsigned long long)cache->reserved,
6195 cache->ro ? "[readonly]" : "");
6196 btrfs_dump_free_space(cache, bytes);
6197 spin_unlock(&cache->lock);
6199 if (++index < BTRFS_NR_RAID_TYPES)
6201 up_read(&info->groups_sem);
6204 int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
6205 struct btrfs_root *root,
6206 u64 num_bytes, u64 min_alloc_size,
6207 u64 empty_size, u64 hint_byte,
6208 struct btrfs_key *ins, u64 data)
6210 bool final_tried = false;
6213 data = btrfs_get_alloc_profile(root, data);
6215 WARN_ON(num_bytes < root->sectorsize);
6216 ret = find_free_extent(trans, root, num_bytes, empty_size,
6217 hint_byte, ins, data);
6219 if (ret == -ENOSPC) {
6221 num_bytes = num_bytes >> 1;
6222 num_bytes = round_down(num_bytes, root->sectorsize);
6223 num_bytes = max(num_bytes, min_alloc_size);
6224 if (num_bytes == min_alloc_size)
6227 } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
6228 struct btrfs_space_info *sinfo;
6230 sinfo = __find_space_info(root->fs_info, data);
6231 printk(KERN_ERR "btrfs allocation failed flags %llu, "
6232 "wanted %llu\n", (unsigned long long)data,
6233 (unsigned long long)num_bytes);
6235 dump_space_info(sinfo, num_bytes, 1);
6239 trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
6244 static int __btrfs_free_reserved_extent(struct btrfs_root *root,
6245 u64 start, u64 len, int pin)
6247 struct btrfs_block_group_cache *cache;
6250 cache = btrfs_lookup_block_group(root->fs_info, start);
6252 printk(KERN_ERR "Unable to find block group for %llu\n",
6253 (unsigned long long)start);
6257 if (btrfs_test_opt(root, DISCARD))
6258 ret = btrfs_discard_extent(root, start, len, NULL);
6261 pin_down_extent(root, cache, start, len, 1);
6263 btrfs_add_free_space(cache, start, len);
6264 btrfs_update_reserved_bytes(cache, len, RESERVE_FREE);
6266 btrfs_put_block_group(cache);
6268 trace_btrfs_reserved_extent_free(root, start, len);
6273 int btrfs_free_reserved_extent(struct btrfs_root *root,
6276 return __btrfs_free_reserved_extent(root, start, len, 0);
6279 int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
6282 return __btrfs_free_reserved_extent(root, start, len, 1);
6285 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6286 struct btrfs_root *root,
6287 u64 parent, u64 root_objectid,
6288 u64 flags, u64 owner, u64 offset,
6289 struct btrfs_key *ins, int ref_mod)
6292 struct btrfs_fs_info *fs_info = root->fs_info;
6293 struct btrfs_extent_item *extent_item;
6294 struct btrfs_extent_inline_ref *iref;
6295 struct btrfs_path *path;
6296 struct extent_buffer *leaf;
6301 type = BTRFS_SHARED_DATA_REF_KEY;
6303 type = BTRFS_EXTENT_DATA_REF_KEY;
6305 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
6307 path = btrfs_alloc_path();
6311 path->leave_spinning = 1;
6312 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6315 btrfs_free_path(path);
6319 leaf = path->nodes[0];
6320 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6321 struct btrfs_extent_item);
6322 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
6323 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6324 btrfs_set_extent_flags(leaf, extent_item,
6325 flags | BTRFS_EXTENT_FLAG_DATA);
6327 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6328 btrfs_set_extent_inline_ref_type(leaf, iref, type);
6330 struct btrfs_shared_data_ref *ref;
6331 ref = (struct btrfs_shared_data_ref *)(iref + 1);
6332 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6333 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
6335 struct btrfs_extent_data_ref *ref;
6336 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
6337 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
6338 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
6339 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
6340 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
6343 btrfs_mark_buffer_dirty(path->nodes[0]);
6344 btrfs_free_path(path);
6346 ret = update_block_group(root, ins->objectid, ins->offset, 1);
6347 if (ret) { /* -ENOENT, logic error */
6348 printk(KERN_ERR "btrfs update block group failed for %llu "
6349 "%llu\n", (unsigned long long)ins->objectid,
6350 (unsigned long long)ins->offset);
6356 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
6357 struct btrfs_root *root,
6358 u64 parent, u64 root_objectid,
6359 u64 flags, struct btrfs_disk_key *key,
6360 int level, struct btrfs_key *ins)
6363 struct btrfs_fs_info *fs_info = root->fs_info;
6364 struct btrfs_extent_item *extent_item;
6365 struct btrfs_tree_block_info *block_info;
6366 struct btrfs_extent_inline_ref *iref;
6367 struct btrfs_path *path;
6368 struct extent_buffer *leaf;
6369 u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
6371 path = btrfs_alloc_path();
6375 path->leave_spinning = 1;
6376 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6379 btrfs_free_path(path);
6383 leaf = path->nodes[0];
6384 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6385 struct btrfs_extent_item);
6386 btrfs_set_extent_refs(leaf, extent_item, 1);
6387 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6388 btrfs_set_extent_flags(leaf, extent_item,
6389 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
6390 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
6392 btrfs_set_tree_block_key(leaf, block_info, key);
6393 btrfs_set_tree_block_level(leaf, block_info, level);
6395 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
6397 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
6398 btrfs_set_extent_inline_ref_type(leaf, iref,
6399 BTRFS_SHARED_BLOCK_REF_KEY);
6400 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6402 btrfs_set_extent_inline_ref_type(leaf, iref,
6403 BTRFS_TREE_BLOCK_REF_KEY);
6404 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
6407 btrfs_mark_buffer_dirty(leaf);
6408 btrfs_free_path(path);
6410 ret = update_block_group(root, ins->objectid, ins->offset, 1);
6411 if (ret) { /* -ENOENT, logic error */
6412 printk(KERN_ERR "btrfs update block group failed for %llu "
6413 "%llu\n", (unsigned long long)ins->objectid,
6414 (unsigned long long)ins->offset);
6420 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6421 struct btrfs_root *root,
6422 u64 root_objectid, u64 owner,
6423 u64 offset, struct btrfs_key *ins)
6427 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
6429 ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
6431 root_objectid, owner, offset,
6432 BTRFS_ADD_DELAYED_EXTENT, NULL, 0);
6437 * this is used by the tree logging recovery code. It records that
6438 * an extent has been allocated and makes sure to clear the free
6439 * space cache bits as well
6441 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
6442 struct btrfs_root *root,
6443 u64 root_objectid, u64 owner, u64 offset,
6444 struct btrfs_key *ins)
6447 struct btrfs_block_group_cache *block_group;
6448 struct btrfs_caching_control *caching_ctl;
6449 u64 start = ins->objectid;
6450 u64 num_bytes = ins->offset;
6452 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
6453 cache_block_group(block_group, 0);
6454 caching_ctl = get_caching_control(block_group);
6457 BUG_ON(!block_group_cache_done(block_group));
6458 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6459 BUG_ON(ret); /* -ENOMEM */
6461 mutex_lock(&caching_ctl->mutex);
6463 if (start >= caching_ctl->progress) {
6464 ret = add_excluded_extent(root, start, num_bytes);
6465 BUG_ON(ret); /* -ENOMEM */
6466 } else if (start + num_bytes <= caching_ctl->progress) {
6467 ret = btrfs_remove_free_space(block_group,
6469 BUG_ON(ret); /* -ENOMEM */
6471 num_bytes = caching_ctl->progress - start;
6472 ret = btrfs_remove_free_space(block_group,
6474 BUG_ON(ret); /* -ENOMEM */
6476 start = caching_ctl->progress;
6477 num_bytes = ins->objectid + ins->offset -
6478 caching_ctl->progress;
6479 ret = add_excluded_extent(root, start, num_bytes);
6480 BUG_ON(ret); /* -ENOMEM */
6483 mutex_unlock(&caching_ctl->mutex);
6484 put_caching_control(caching_ctl);
6487 ret = btrfs_update_reserved_bytes(block_group, ins->offset,
6488 RESERVE_ALLOC_NO_ACCOUNT);
6489 BUG_ON(ret); /* logic error */
6490 btrfs_put_block_group(block_group);
6491 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
6492 0, owner, offset, ins, 1);
6496 struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
6497 struct btrfs_root *root,
6498 u64 bytenr, u32 blocksize,
6501 struct extent_buffer *buf;
6503 buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
6505 return ERR_PTR(-ENOMEM);
6506 btrfs_set_header_generation(buf, trans->transid);
6507 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
6508 btrfs_tree_lock(buf);
6509 clean_tree_block(trans, root, buf);
6510 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
6512 btrfs_set_lock_blocking(buf);
6513 btrfs_set_buffer_uptodate(buf);
6515 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
6517 * we allow two log transactions at a time, use different
6518 * EXENT bit to differentiate dirty pages.
6520 if (root->log_transid % 2 == 0)
6521 set_extent_dirty(&root->dirty_log_pages, buf->start,
6522 buf->start + buf->len - 1, GFP_NOFS);
6524 set_extent_new(&root->dirty_log_pages, buf->start,
6525 buf->start + buf->len - 1, GFP_NOFS);
6527 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
6528 buf->start + buf->len - 1, GFP_NOFS);
6530 trans->blocks_used++;
6531 /* this returns a buffer locked for blocking */
6535 static struct btrfs_block_rsv *
6536 use_block_rsv(struct btrfs_trans_handle *trans,
6537 struct btrfs_root *root, u32 blocksize)
6539 struct btrfs_block_rsv *block_rsv;
6540 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
6543 block_rsv = get_block_rsv(trans, root);
6545 if (block_rsv->size == 0) {
6546 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
6547 BTRFS_RESERVE_NO_FLUSH);
6549 * If we couldn't reserve metadata bytes try and use some from
6550 * the global reserve.
6552 if (ret && block_rsv != global_rsv) {
6553 ret = block_rsv_use_bytes(global_rsv, blocksize);
6556 return ERR_PTR(ret);
6558 return ERR_PTR(ret);
6563 ret = block_rsv_use_bytes(block_rsv, blocksize);
6566 if (ret && !block_rsv->failfast) {
6567 if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
6568 static DEFINE_RATELIMIT_STATE(_rs,
6569 DEFAULT_RATELIMIT_INTERVAL * 10,
6570 /*DEFAULT_RATELIMIT_BURST*/ 1);
6571 if (__ratelimit(&_rs))
6573 "btrfs: block rsv returned %d\n", ret);
6575 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
6576 BTRFS_RESERVE_NO_FLUSH);
6579 } else if (ret && block_rsv != global_rsv) {
6580 ret = block_rsv_use_bytes(global_rsv, blocksize);
6586 return ERR_PTR(-ENOSPC);
6589 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
6590 struct btrfs_block_rsv *block_rsv, u32 blocksize)
6592 block_rsv_add_bytes(block_rsv, blocksize, 0);
6593 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
6597 * finds a free extent and does all the dirty work required for allocation
6598 * returns the key for the extent through ins, and a tree buffer for
6599 * the first block of the extent through buf.
6601 * returns the tree buffer or NULL.
6603 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
6604 struct btrfs_root *root, u32 blocksize,
6605 u64 parent, u64 root_objectid,
6606 struct btrfs_disk_key *key, int level,
6607 u64 hint, u64 empty_size)
6609 struct btrfs_key ins;
6610 struct btrfs_block_rsv *block_rsv;
6611 struct extent_buffer *buf;
6616 block_rsv = use_block_rsv(trans, root, blocksize);
6617 if (IS_ERR(block_rsv))
6618 return ERR_CAST(block_rsv);
6620 ret = btrfs_reserve_extent(trans, root, blocksize, blocksize,
6621 empty_size, hint, &ins, 0);
6623 unuse_block_rsv(root->fs_info, block_rsv, blocksize);
6624 return ERR_PTR(ret);
6627 buf = btrfs_init_new_buffer(trans, root, ins.objectid,
6629 BUG_ON(IS_ERR(buf)); /* -ENOMEM */
6631 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
6633 parent = ins.objectid;
6634 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6638 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
6639 struct btrfs_delayed_extent_op *extent_op;
6640 extent_op = btrfs_alloc_delayed_extent_op();
6641 BUG_ON(!extent_op); /* -ENOMEM */
6643 memcpy(&extent_op->key, key, sizeof(extent_op->key));
6645 memset(&extent_op->key, 0, sizeof(extent_op->key));
6646 extent_op->flags_to_set = flags;
6647 extent_op->update_key = 1;
6648 extent_op->update_flags = 1;
6649 extent_op->is_data = 0;
6651 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
6653 ins.offset, parent, root_objectid,
6654 level, BTRFS_ADD_DELAYED_EXTENT,
6656 BUG_ON(ret); /* -ENOMEM */
6661 struct walk_control {
6662 u64 refs[BTRFS_MAX_LEVEL];
6663 u64 flags[BTRFS_MAX_LEVEL];
6664 struct btrfs_key update_progress;
6675 #define DROP_REFERENCE 1
6676 #define UPDATE_BACKREF 2
6678 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
6679 struct btrfs_root *root,
6680 struct walk_control *wc,
6681 struct btrfs_path *path)
6689 struct btrfs_key key;
6690 struct extent_buffer *eb;
6695 if (path->slots[wc->level] < wc->reada_slot) {
6696 wc->reada_count = wc->reada_count * 2 / 3;
6697 wc->reada_count = max(wc->reada_count, 2);
6699 wc->reada_count = wc->reada_count * 3 / 2;
6700 wc->reada_count = min_t(int, wc->reada_count,
6701 BTRFS_NODEPTRS_PER_BLOCK(root));
6704 eb = path->nodes[wc->level];
6705 nritems = btrfs_header_nritems(eb);
6706 blocksize = btrfs_level_size(root, wc->level - 1);
6708 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
6709 if (nread >= wc->reada_count)
6713 bytenr = btrfs_node_blockptr(eb, slot);
6714 generation = btrfs_node_ptr_generation(eb, slot);
6716 if (slot == path->slots[wc->level])
6719 if (wc->stage == UPDATE_BACKREF &&
6720 generation <= root->root_key.offset)
6723 /* We don't lock the tree block, it's OK to be racy here */
6724 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
6726 /* We don't care about errors in readahead. */
6731 if (wc->stage == DROP_REFERENCE) {
6735 if (wc->level == 1 &&
6736 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6738 if (!wc->update_ref ||
6739 generation <= root->root_key.offset)
6741 btrfs_node_key_to_cpu(eb, &key, slot);
6742 ret = btrfs_comp_cpu_keys(&key,
6743 &wc->update_progress);
6747 if (wc->level == 1 &&
6748 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6752 ret = readahead_tree_block(root, bytenr, blocksize,
6758 wc->reada_slot = slot;
6762 * hepler to process tree block while walking down the tree.
6764 * when wc->stage == UPDATE_BACKREF, this function updates
6765 * back refs for pointers in the block.
6767 * NOTE: return value 1 means we should stop walking down.
6769 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
6770 struct btrfs_root *root,
6771 struct btrfs_path *path,
6772 struct walk_control *wc, int lookup_info)
6774 int level = wc->level;
6775 struct extent_buffer *eb = path->nodes[level];
6776 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6779 if (wc->stage == UPDATE_BACKREF &&
6780 btrfs_header_owner(eb) != root->root_key.objectid)
6784 * when reference count of tree block is 1, it won't increase
6785 * again. once full backref flag is set, we never clear it.
6788 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
6789 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
6790 BUG_ON(!path->locks[level]);
6791 ret = btrfs_lookup_extent_info(trans, root,
6795 BUG_ON(ret == -ENOMEM);
6798 BUG_ON(wc->refs[level] == 0);
6801 if (wc->stage == DROP_REFERENCE) {
6802 if (wc->refs[level] > 1)
6805 if (path->locks[level] && !wc->keep_locks) {
6806 btrfs_tree_unlock_rw(eb, path->locks[level]);
6807 path->locks[level] = 0;
6812 /* wc->stage == UPDATE_BACKREF */
6813 if (!(wc->flags[level] & flag)) {
6814 BUG_ON(!path->locks[level]);
6815 ret = btrfs_inc_ref(trans, root, eb, 1, wc->for_reloc);
6816 BUG_ON(ret); /* -ENOMEM */
6817 ret = btrfs_dec_ref(trans, root, eb, 0, wc->for_reloc);
6818 BUG_ON(ret); /* -ENOMEM */
6819 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
6821 BUG_ON(ret); /* -ENOMEM */
6822 wc->flags[level] |= flag;
6826 * the block is shared by multiple trees, so it's not good to
6827 * keep the tree lock
6829 if (path->locks[level] && level > 0) {
6830 btrfs_tree_unlock_rw(eb, path->locks[level]);
6831 path->locks[level] = 0;
6837 * hepler to process tree block pointer.
6839 * when wc->stage == DROP_REFERENCE, this function checks
6840 * reference count of the block pointed to. if the block
6841 * is shared and we need update back refs for the subtree
6842 * rooted at the block, this function changes wc->stage to
6843 * UPDATE_BACKREF. if the block is shared and there is no
6844 * need to update back, this function drops the reference
6847 * NOTE: return value 1 means we should stop walking down.
6849 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
6850 struct btrfs_root *root,
6851 struct btrfs_path *path,
6852 struct walk_control *wc, int *lookup_info)
6858 struct btrfs_key key;
6859 struct extent_buffer *next;
6860 int level = wc->level;
6864 generation = btrfs_node_ptr_generation(path->nodes[level],
6865 path->slots[level]);
6867 * if the lower level block was created before the snapshot
6868 * was created, we know there is no need to update back refs
6871 if (wc->stage == UPDATE_BACKREF &&
6872 generation <= root->root_key.offset) {
6877 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
6878 blocksize = btrfs_level_size(root, level - 1);
6880 next = btrfs_find_tree_block(root, bytenr, blocksize);
6882 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
6887 btrfs_tree_lock(next);
6888 btrfs_set_lock_blocking(next);
6890 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
6891 &wc->refs[level - 1],
6892 &wc->flags[level - 1]);
6894 btrfs_tree_unlock(next);
6898 BUG_ON(wc->refs[level - 1] == 0);
6901 if (wc->stage == DROP_REFERENCE) {
6902 if (wc->refs[level - 1] > 1) {
6904 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6907 if (!wc->update_ref ||
6908 generation <= root->root_key.offset)
6911 btrfs_node_key_to_cpu(path->nodes[level], &key,
6912 path->slots[level]);
6913 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
6917 wc->stage = UPDATE_BACKREF;
6918 wc->shared_level = level - 1;
6922 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6926 if (!btrfs_buffer_uptodate(next, generation, 0)) {
6927 btrfs_tree_unlock(next);
6928 free_extent_buffer(next);
6934 if (reada && level == 1)
6935 reada_walk_down(trans, root, wc, path);
6936 next = read_tree_block(root, bytenr, blocksize, generation);
6939 btrfs_tree_lock(next);
6940 btrfs_set_lock_blocking(next);
6944 BUG_ON(level != btrfs_header_level(next));
6945 path->nodes[level] = next;
6946 path->slots[level] = 0;
6947 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6953 wc->refs[level - 1] = 0;
6954 wc->flags[level - 1] = 0;
6955 if (wc->stage == DROP_REFERENCE) {
6956 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6957 parent = path->nodes[level]->start;
6959 BUG_ON(root->root_key.objectid !=
6960 btrfs_header_owner(path->nodes[level]));
6964 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
6965 root->root_key.objectid, level - 1, 0, 0);
6966 BUG_ON(ret); /* -ENOMEM */
6968 btrfs_tree_unlock(next);
6969 free_extent_buffer(next);
6975 * hepler to process tree block while walking up the tree.
6977 * when wc->stage == DROP_REFERENCE, this function drops
6978 * reference count on the block.
6980 * when wc->stage == UPDATE_BACKREF, this function changes
6981 * wc->stage back to DROP_REFERENCE if we changed wc->stage
6982 * to UPDATE_BACKREF previously while processing the block.
6984 * NOTE: return value 1 means we should stop walking up.
6986 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6987 struct btrfs_root *root,
6988 struct btrfs_path *path,
6989 struct walk_control *wc)
6992 int level = wc->level;
6993 struct extent_buffer *eb = path->nodes[level];
6996 if (wc->stage == UPDATE_BACKREF) {
6997 BUG_ON(wc->shared_level < level);
6998 if (level < wc->shared_level)
7001 ret = find_next_key(path, level + 1, &wc->update_progress);
7005 wc->stage = DROP_REFERENCE;
7006 wc->shared_level = -1;
7007 path->slots[level] = 0;
7010 * check reference count again if the block isn't locked.
7011 * we should start walking down the tree again if reference
7014 if (!path->locks[level]) {
7016 btrfs_tree_lock(eb);
7017 btrfs_set_lock_blocking(eb);
7018 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7020 ret = btrfs_lookup_extent_info(trans, root,
7025 btrfs_tree_unlock_rw(eb, path->locks[level]);
7026 path->locks[level] = 0;
7029 BUG_ON(wc->refs[level] == 0);
7030 if (wc->refs[level] == 1) {
7031 btrfs_tree_unlock_rw(eb, path->locks[level]);
7032 path->locks[level] = 0;
7038 /* wc->stage == DROP_REFERENCE */
7039 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
7041 if (wc->refs[level] == 1) {
7043 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7044 ret = btrfs_dec_ref(trans, root, eb, 1,
7047 ret = btrfs_dec_ref(trans, root, eb, 0,
7049 BUG_ON(ret); /* -ENOMEM */
7051 /* make block locked assertion in clean_tree_block happy */
7052 if (!path->locks[level] &&
7053 btrfs_header_generation(eb) == trans->transid) {
7054 btrfs_tree_lock(eb);
7055 btrfs_set_lock_blocking(eb);
7056 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7058 clean_tree_block(trans, root, eb);
7061 if (eb == root->node) {
7062 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7065 BUG_ON(root->root_key.objectid !=
7066 btrfs_header_owner(eb));
7068 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7069 parent = path->nodes[level + 1]->start;
7071 BUG_ON(root->root_key.objectid !=
7072 btrfs_header_owner(path->nodes[level + 1]));
7075 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
7077 wc->refs[level] = 0;
7078 wc->flags[level] = 0;
7082 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
7083 struct btrfs_root *root,
7084 struct btrfs_path *path,
7085 struct walk_control *wc)
7087 int level = wc->level;
7088 int lookup_info = 1;
7091 while (level >= 0) {
7092 ret = walk_down_proc(trans, root, path, wc, lookup_info);
7099 if (path->slots[level] >=
7100 btrfs_header_nritems(path->nodes[level]))
7103 ret = do_walk_down(trans, root, path, wc, &lookup_info);
7105 path->slots[level]++;
7114 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
7115 struct btrfs_root *root,
7116 struct btrfs_path *path,
7117 struct walk_control *wc, int max_level)
7119 int level = wc->level;
7122 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
7123 while (level < max_level && path->nodes[level]) {
7125 if (path->slots[level] + 1 <
7126 btrfs_header_nritems(path->nodes[level])) {
7127 path->slots[level]++;
7130 ret = walk_up_proc(trans, root, path, wc);
7134 if (path->locks[level]) {
7135 btrfs_tree_unlock_rw(path->nodes[level],
7136 path->locks[level]);
7137 path->locks[level] = 0;
7139 free_extent_buffer(path->nodes[level]);
7140 path->nodes[level] = NULL;
7148 * drop a subvolume tree.
7150 * this function traverses the tree freeing any blocks that only
7151 * referenced by the tree.
7153 * when a shared tree block is found. this function decreases its
7154 * reference count by one. if update_ref is true, this function
7155 * also make sure backrefs for the shared block and all lower level
7156 * blocks are properly updated.
7158 int btrfs_drop_snapshot(struct btrfs_root *root,
7159 struct btrfs_block_rsv *block_rsv, int update_ref,
7162 struct btrfs_path *path;
7163 struct btrfs_trans_handle *trans;
7164 struct btrfs_root *tree_root = root->fs_info->tree_root;
7165 struct btrfs_root_item *root_item = &root->root_item;
7166 struct walk_control *wc;
7167 struct btrfs_key key;
7172 path = btrfs_alloc_path();
7178 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7180 btrfs_free_path(path);
7185 trans = btrfs_start_transaction(tree_root, 0);
7186 if (IS_ERR(trans)) {
7187 err = PTR_ERR(trans);
7192 trans->block_rsv = block_rsv;
7194 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
7195 level = btrfs_header_level(root->node);
7196 path->nodes[level] = btrfs_lock_root_node(root);
7197 btrfs_set_lock_blocking(path->nodes[level]);
7198 path->slots[level] = 0;
7199 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7200 memset(&wc->update_progress, 0,
7201 sizeof(wc->update_progress));
7203 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
7204 memcpy(&wc->update_progress, &key,
7205 sizeof(wc->update_progress));
7207 level = root_item->drop_level;
7209 path->lowest_level = level;
7210 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7211 path->lowest_level = 0;
7219 * unlock our path, this is safe because only this
7220 * function is allowed to delete this snapshot
7222 btrfs_unlock_up_safe(path, 0);
7224 level = btrfs_header_level(root->node);
7226 btrfs_tree_lock(path->nodes[level]);
7227 btrfs_set_lock_blocking(path->nodes[level]);
7229 ret = btrfs_lookup_extent_info(trans, root,
7230 path->nodes[level]->start,
7231 path->nodes[level]->len,
7238 BUG_ON(wc->refs[level] == 0);
7240 if (level == root_item->drop_level)
7243 btrfs_tree_unlock(path->nodes[level]);
7244 WARN_ON(wc->refs[level] != 1);
7250 wc->shared_level = -1;
7251 wc->stage = DROP_REFERENCE;
7252 wc->update_ref = update_ref;
7254 wc->for_reloc = for_reloc;
7255 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
7258 ret = walk_down_tree(trans, root, path, wc);
7264 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
7271 BUG_ON(wc->stage != DROP_REFERENCE);
7275 if (wc->stage == DROP_REFERENCE) {
7277 btrfs_node_key(path->nodes[level],
7278 &root_item->drop_progress,
7279 path->slots[level]);
7280 root_item->drop_level = level;
7283 BUG_ON(wc->level == 0);
7284 if (btrfs_should_end_transaction(trans, tree_root)) {
7285 ret = btrfs_update_root(trans, tree_root,
7289 btrfs_abort_transaction(trans, tree_root, ret);
7294 btrfs_end_transaction_throttle(trans, tree_root);
7295 trans = btrfs_start_transaction(tree_root, 0);
7296 if (IS_ERR(trans)) {
7297 err = PTR_ERR(trans);
7301 trans->block_rsv = block_rsv;
7304 btrfs_release_path(path);
7308 ret = btrfs_del_root(trans, tree_root, &root->root_key);
7310 btrfs_abort_transaction(trans, tree_root, ret);
7314 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
7315 ret = btrfs_find_last_root(tree_root, root->root_key.objectid,
7318 btrfs_abort_transaction(trans, tree_root, ret);
7321 } else if (ret > 0) {
7322 /* if we fail to delete the orphan item this time
7323 * around, it'll get picked up the next time.
7325 * The most common failure here is just -ENOENT.
7327 btrfs_del_orphan_item(trans, tree_root,
7328 root->root_key.objectid);
7332 if (root->in_radix) {
7333 btrfs_free_fs_root(tree_root->fs_info, root);
7335 free_extent_buffer(root->node);
7336 free_extent_buffer(root->commit_root);
7340 btrfs_end_transaction_throttle(trans, tree_root);
7343 btrfs_free_path(path);
7346 btrfs_std_error(root->fs_info, err);
7351 * drop subtree rooted at tree block 'node'.
7353 * NOTE: this function will unlock and release tree block 'node'
7354 * only used by relocation code
7356 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
7357 struct btrfs_root *root,
7358 struct extent_buffer *node,
7359 struct extent_buffer *parent)
7361 struct btrfs_path *path;
7362 struct walk_control *wc;
7368 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7370 path = btrfs_alloc_path();
7374 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7376 btrfs_free_path(path);
7380 btrfs_assert_tree_locked(parent);
7381 parent_level = btrfs_header_level(parent);
7382 extent_buffer_get(parent);
7383 path->nodes[parent_level] = parent;
7384 path->slots[parent_level] = btrfs_header_nritems(parent);
7386 btrfs_assert_tree_locked(node);
7387 level = btrfs_header_level(node);
7388 path->nodes[level] = node;
7389 path->slots[level] = 0;
7390 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7392 wc->refs[parent_level] = 1;
7393 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7395 wc->shared_level = -1;
7396 wc->stage = DROP_REFERENCE;
7400 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
7403 wret = walk_down_tree(trans, root, path, wc);
7409 wret = walk_up_tree(trans, root, path, wc, parent_level);
7417 btrfs_free_path(path);
7421 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
7427 * if restripe for this chunk_type is on pick target profile and
7428 * return, otherwise do the usual balance
7430 stripped = get_restripe_target(root->fs_info, flags);
7432 return extended_to_chunk(stripped);
7435 * we add in the count of missing devices because we want
7436 * to make sure that any RAID levels on a degraded FS
7437 * continue to be honored.
7439 num_devices = root->fs_info->fs_devices->rw_devices +
7440 root->fs_info->fs_devices->missing_devices;
7442 stripped = BTRFS_BLOCK_GROUP_RAID0 |
7443 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
7444 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
7446 if (num_devices == 1) {
7447 stripped |= BTRFS_BLOCK_GROUP_DUP;
7448 stripped = flags & ~stripped;
7450 /* turn raid0 into single device chunks */
7451 if (flags & BTRFS_BLOCK_GROUP_RAID0)
7454 /* turn mirroring into duplication */
7455 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
7456 BTRFS_BLOCK_GROUP_RAID10))
7457 return stripped | BTRFS_BLOCK_GROUP_DUP;
7459 /* they already had raid on here, just return */
7460 if (flags & stripped)
7463 stripped |= BTRFS_BLOCK_GROUP_DUP;
7464 stripped = flags & ~stripped;
7466 /* switch duplicated blocks with raid1 */
7467 if (flags & BTRFS_BLOCK_GROUP_DUP)
7468 return stripped | BTRFS_BLOCK_GROUP_RAID1;
7470 /* this is drive concat, leave it alone */
7476 static int set_block_group_ro(struct btrfs_block_group_cache *cache, int force)
7478 struct btrfs_space_info *sinfo = cache->space_info;
7480 u64 min_allocable_bytes;
7485 * We need some metadata space and system metadata space for
7486 * allocating chunks in some corner cases until we force to set
7487 * it to be readonly.
7490 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
7492 min_allocable_bytes = 1 * 1024 * 1024;
7494 min_allocable_bytes = 0;
7496 spin_lock(&sinfo->lock);
7497 spin_lock(&cache->lock);
7504 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7505 cache->bytes_super - btrfs_block_group_used(&cache->item);
7507 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
7508 sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
7509 min_allocable_bytes <= sinfo->total_bytes) {
7510 sinfo->bytes_readonly += num_bytes;
7515 spin_unlock(&cache->lock);
7516 spin_unlock(&sinfo->lock);
7520 int btrfs_set_block_group_ro(struct btrfs_root *root,
7521 struct btrfs_block_group_cache *cache)
7524 struct btrfs_trans_handle *trans;
7530 trans = btrfs_join_transaction(root);
7532 return PTR_ERR(trans);
7534 alloc_flags = update_block_group_flags(root, cache->flags);
7535 if (alloc_flags != cache->flags) {
7536 ret = do_chunk_alloc(trans, root, alloc_flags,
7542 ret = set_block_group_ro(cache, 0);
7545 alloc_flags = get_alloc_profile(root, cache->space_info->flags);
7546 ret = do_chunk_alloc(trans, root, alloc_flags,
7550 ret = set_block_group_ro(cache, 0);
7552 btrfs_end_transaction(trans, root);
7556 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
7557 struct btrfs_root *root, u64 type)
7559 u64 alloc_flags = get_alloc_profile(root, type);
7560 return do_chunk_alloc(trans, root, alloc_flags,
7565 * helper to account the unused space of all the readonly block group in the
7566 * list. takes mirrors into account.
7568 static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
7570 struct btrfs_block_group_cache *block_group;
7574 list_for_each_entry(block_group, groups_list, list) {
7575 spin_lock(&block_group->lock);
7577 if (!block_group->ro) {
7578 spin_unlock(&block_group->lock);
7582 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
7583 BTRFS_BLOCK_GROUP_RAID10 |
7584 BTRFS_BLOCK_GROUP_DUP))
7589 free_bytes += (block_group->key.offset -
7590 btrfs_block_group_used(&block_group->item)) *
7593 spin_unlock(&block_group->lock);
7600 * helper to account the unused space of all the readonly block group in the
7601 * space_info. takes mirrors into account.
7603 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
7608 spin_lock(&sinfo->lock);
7610 for(i = 0; i < BTRFS_NR_RAID_TYPES; i++)
7611 if (!list_empty(&sinfo->block_groups[i]))
7612 free_bytes += __btrfs_get_ro_block_group_free_space(
7613 &sinfo->block_groups[i]);
7615 spin_unlock(&sinfo->lock);
7620 void btrfs_set_block_group_rw(struct btrfs_root *root,
7621 struct btrfs_block_group_cache *cache)
7623 struct btrfs_space_info *sinfo = cache->space_info;
7628 spin_lock(&sinfo->lock);
7629 spin_lock(&cache->lock);
7630 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7631 cache->bytes_super - btrfs_block_group_used(&cache->item);
7632 sinfo->bytes_readonly -= num_bytes;
7634 spin_unlock(&cache->lock);
7635 spin_unlock(&sinfo->lock);
7639 * checks to see if its even possible to relocate this block group.
7641 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
7642 * ok to go ahead and try.
7644 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
7646 struct btrfs_block_group_cache *block_group;
7647 struct btrfs_space_info *space_info;
7648 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
7649 struct btrfs_device *device;
7658 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
7660 /* odd, couldn't find the block group, leave it alone */
7664 min_free = btrfs_block_group_used(&block_group->item);
7666 /* no bytes used, we're good */
7670 space_info = block_group->space_info;
7671 spin_lock(&space_info->lock);
7673 full = space_info->full;
7676 * if this is the last block group we have in this space, we can't
7677 * relocate it unless we're able to allocate a new chunk below.
7679 * Otherwise, we need to make sure we have room in the space to handle
7680 * all of the extents from this block group. If we can, we're good
7682 if ((space_info->total_bytes != block_group->key.offset) &&
7683 (space_info->bytes_used + space_info->bytes_reserved +
7684 space_info->bytes_pinned + space_info->bytes_readonly +
7685 min_free < space_info->total_bytes)) {
7686 spin_unlock(&space_info->lock);
7689 spin_unlock(&space_info->lock);
7692 * ok we don't have enough space, but maybe we have free space on our
7693 * devices to allocate new chunks for relocation, so loop through our
7694 * alloc devices and guess if we have enough space. if this block
7695 * group is going to be restriped, run checks against the target
7696 * profile instead of the current one.
7708 target = get_restripe_target(root->fs_info, block_group->flags);
7710 index = __get_raid_index(extended_to_chunk(target));
7713 * this is just a balance, so if we were marked as full
7714 * we know there is no space for a new chunk
7719 index = get_block_group_index(block_group);
7722 if (index == BTRFS_RAID_RAID10) {
7726 } else if (index == BTRFS_RAID_RAID1) {
7728 } else if (index == BTRFS_RAID_DUP) {
7731 } else if (index == BTRFS_RAID_RAID0) {
7732 dev_min = fs_devices->rw_devices;
7733 do_div(min_free, dev_min);
7736 mutex_lock(&root->fs_info->chunk_mutex);
7737 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7741 * check to make sure we can actually find a chunk with enough
7742 * space to fit our block group in.
7744 if (device->total_bytes > device->bytes_used + min_free &&
7745 !device->is_tgtdev_for_dev_replace) {
7746 ret = find_free_dev_extent(device, min_free,
7751 if (dev_nr >= dev_min)
7757 mutex_unlock(&root->fs_info->chunk_mutex);
7759 btrfs_put_block_group(block_group);
7763 static int find_first_block_group(struct btrfs_root *root,
7764 struct btrfs_path *path, struct btrfs_key *key)
7767 struct btrfs_key found_key;
7768 struct extent_buffer *leaf;
7771 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7776 slot = path->slots[0];
7777 leaf = path->nodes[0];
7778 if (slot >= btrfs_header_nritems(leaf)) {
7779 ret = btrfs_next_leaf(root, path);
7786 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7788 if (found_key.objectid >= key->objectid &&
7789 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
7799 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
7801 struct btrfs_block_group_cache *block_group;
7805 struct inode *inode;
7807 block_group = btrfs_lookup_first_block_group(info, last);
7808 while (block_group) {
7809 spin_lock(&block_group->lock);
7810 if (block_group->iref)
7812 spin_unlock(&block_group->lock);
7813 block_group = next_block_group(info->tree_root,
7823 inode = block_group->inode;
7824 block_group->iref = 0;
7825 block_group->inode = NULL;
7826 spin_unlock(&block_group->lock);
7828 last = block_group->key.objectid + block_group->key.offset;
7829 btrfs_put_block_group(block_group);
7833 int btrfs_free_block_groups(struct btrfs_fs_info *info)
7835 struct btrfs_block_group_cache *block_group;
7836 struct btrfs_space_info *space_info;
7837 struct btrfs_caching_control *caching_ctl;
7840 down_write(&info->extent_commit_sem);
7841 while (!list_empty(&info->caching_block_groups)) {
7842 caching_ctl = list_entry(info->caching_block_groups.next,
7843 struct btrfs_caching_control, list);
7844 list_del(&caching_ctl->list);
7845 put_caching_control(caching_ctl);
7847 up_write(&info->extent_commit_sem);
7849 spin_lock(&info->block_group_cache_lock);
7850 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
7851 block_group = rb_entry(n, struct btrfs_block_group_cache,
7853 rb_erase(&block_group->cache_node,
7854 &info->block_group_cache_tree);
7855 spin_unlock(&info->block_group_cache_lock);
7857 down_write(&block_group->space_info->groups_sem);
7858 list_del(&block_group->list);
7859 up_write(&block_group->space_info->groups_sem);
7861 if (block_group->cached == BTRFS_CACHE_STARTED)
7862 wait_block_group_cache_done(block_group);
7865 * We haven't cached this block group, which means we could
7866 * possibly have excluded extents on this block group.
7868 if (block_group->cached == BTRFS_CACHE_NO)
7869 free_excluded_extents(info->extent_root, block_group);
7871 btrfs_remove_free_space_cache(block_group);
7872 btrfs_put_block_group(block_group);
7874 spin_lock(&info->block_group_cache_lock);
7876 spin_unlock(&info->block_group_cache_lock);
7878 /* now that all the block groups are freed, go through and
7879 * free all the space_info structs. This is only called during
7880 * the final stages of unmount, and so we know nobody is
7881 * using them. We call synchronize_rcu() once before we start,
7882 * just to be on the safe side.
7886 release_global_block_rsv(info);
7888 while(!list_empty(&info->space_info)) {
7889 space_info = list_entry(info->space_info.next,
7890 struct btrfs_space_info,
7892 if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
7893 if (space_info->bytes_pinned > 0 ||
7894 space_info->bytes_reserved > 0 ||
7895 space_info->bytes_may_use > 0) {
7897 dump_space_info(space_info, 0, 0);
7900 list_del(&space_info->list);
7906 static void __link_block_group(struct btrfs_space_info *space_info,
7907 struct btrfs_block_group_cache *cache)
7909 int index = get_block_group_index(cache);
7911 down_write(&space_info->groups_sem);
7912 list_add_tail(&cache->list, &space_info->block_groups[index]);
7913 up_write(&space_info->groups_sem);
7916 int btrfs_read_block_groups(struct btrfs_root *root)
7918 struct btrfs_path *path;
7920 struct btrfs_block_group_cache *cache;
7921 struct btrfs_fs_info *info = root->fs_info;
7922 struct btrfs_space_info *space_info;
7923 struct btrfs_key key;
7924 struct btrfs_key found_key;
7925 struct extent_buffer *leaf;
7929 root = info->extent_root;
7932 btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
7933 path = btrfs_alloc_path();
7938 cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
7939 if (btrfs_test_opt(root, SPACE_CACHE) &&
7940 btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
7942 if (btrfs_test_opt(root, CLEAR_CACHE))
7946 ret = find_first_block_group(root, path, &key);
7951 leaf = path->nodes[0];
7952 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7953 cache = kzalloc(sizeof(*cache), GFP_NOFS);
7958 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
7960 if (!cache->free_space_ctl) {
7966 atomic_set(&cache->count, 1);
7967 spin_lock_init(&cache->lock);
7968 cache->fs_info = info;
7969 INIT_LIST_HEAD(&cache->list);
7970 INIT_LIST_HEAD(&cache->cluster_list);
7974 * When we mount with old space cache, we need to
7975 * set BTRFS_DC_CLEAR and set dirty flag.
7977 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
7978 * truncate the old free space cache inode and
7980 * b) Setting 'dirty flag' makes sure that we flush
7981 * the new space cache info onto disk.
7983 cache->disk_cache_state = BTRFS_DC_CLEAR;
7984 if (btrfs_test_opt(root, SPACE_CACHE))
7988 read_extent_buffer(leaf, &cache->item,
7989 btrfs_item_ptr_offset(leaf, path->slots[0]),
7990 sizeof(cache->item));
7991 memcpy(&cache->key, &found_key, sizeof(found_key));
7993 key.objectid = found_key.objectid + found_key.offset;
7994 btrfs_release_path(path);
7995 cache->flags = btrfs_block_group_flags(&cache->item);
7996 cache->sectorsize = root->sectorsize;
7997 cache->full_stripe_len = btrfs_full_stripe_len(root,
7998 &root->fs_info->mapping_tree,
7999 found_key.objectid);
8000 btrfs_init_free_space_ctl(cache);
8003 * We need to exclude the super stripes now so that the space
8004 * info has super bytes accounted for, otherwise we'll think
8005 * we have more space than we actually do.
8007 ret = exclude_super_stripes(root, cache);
8010 * We may have excluded something, so call this just in
8013 free_excluded_extents(root, cache);
8014 kfree(cache->free_space_ctl);
8020 * check for two cases, either we are full, and therefore
8021 * don't need to bother with the caching work since we won't
8022 * find any space, or we are empty, and we can just add all
8023 * the space in and be done with it. This saves us _alot_ of
8024 * time, particularly in the full case.
8026 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
8027 cache->last_byte_to_unpin = (u64)-1;
8028 cache->cached = BTRFS_CACHE_FINISHED;
8029 free_excluded_extents(root, cache);
8030 } else if (btrfs_block_group_used(&cache->item) == 0) {
8031 cache->last_byte_to_unpin = (u64)-1;
8032 cache->cached = BTRFS_CACHE_FINISHED;
8033 add_new_free_space(cache, root->fs_info,
8035 found_key.objectid +
8037 free_excluded_extents(root, cache);
8040 ret = update_space_info(info, cache->flags, found_key.offset,
8041 btrfs_block_group_used(&cache->item),
8043 BUG_ON(ret); /* -ENOMEM */
8044 cache->space_info = space_info;
8045 spin_lock(&cache->space_info->lock);
8046 cache->space_info->bytes_readonly += cache->bytes_super;
8047 spin_unlock(&cache->space_info->lock);
8049 __link_block_group(space_info, cache);
8051 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8052 BUG_ON(ret); /* Logic error */
8054 set_avail_alloc_bits(root->fs_info, cache->flags);
8055 if (btrfs_chunk_readonly(root, cache->key.objectid))
8056 set_block_group_ro(cache, 1);
8059 list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
8060 if (!(get_alloc_profile(root, space_info->flags) &
8061 (BTRFS_BLOCK_GROUP_RAID10 |
8062 BTRFS_BLOCK_GROUP_RAID1 |
8063 BTRFS_BLOCK_GROUP_RAID5 |
8064 BTRFS_BLOCK_GROUP_RAID6 |
8065 BTRFS_BLOCK_GROUP_DUP)))
8068 * avoid allocating from un-mirrored block group if there are
8069 * mirrored block groups.
8071 list_for_each_entry(cache, &space_info->block_groups[3], list)
8072 set_block_group_ro(cache, 1);
8073 list_for_each_entry(cache, &space_info->block_groups[4], list)
8074 set_block_group_ro(cache, 1);
8077 init_global_block_rsv(info);
8080 btrfs_free_path(path);
8084 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
8085 struct btrfs_root *root)
8087 struct btrfs_block_group_cache *block_group, *tmp;
8088 struct btrfs_root *extent_root = root->fs_info->extent_root;
8089 struct btrfs_block_group_item item;
8090 struct btrfs_key key;
8093 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs,
8095 list_del_init(&block_group->new_bg_list);
8100 spin_lock(&block_group->lock);
8101 memcpy(&item, &block_group->item, sizeof(item));
8102 memcpy(&key, &block_group->key, sizeof(key));
8103 spin_unlock(&block_group->lock);
8105 ret = btrfs_insert_item(trans, extent_root, &key, &item,
8108 btrfs_abort_transaction(trans, extent_root, ret);
8112 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
8113 struct btrfs_root *root, u64 bytes_used,
8114 u64 type, u64 chunk_objectid, u64 chunk_offset,
8118 struct btrfs_root *extent_root;
8119 struct btrfs_block_group_cache *cache;
8121 extent_root = root->fs_info->extent_root;
8123 root->fs_info->last_trans_log_full_commit = trans->transid;
8125 cache = kzalloc(sizeof(*cache), GFP_NOFS);
8128 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
8130 if (!cache->free_space_ctl) {
8135 cache->key.objectid = chunk_offset;
8136 cache->key.offset = size;
8137 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8138 cache->sectorsize = root->sectorsize;
8139 cache->fs_info = root->fs_info;
8140 cache->full_stripe_len = btrfs_full_stripe_len(root,
8141 &root->fs_info->mapping_tree,
8144 atomic_set(&cache->count, 1);
8145 spin_lock_init(&cache->lock);
8146 INIT_LIST_HEAD(&cache->list);
8147 INIT_LIST_HEAD(&cache->cluster_list);
8148 INIT_LIST_HEAD(&cache->new_bg_list);
8150 btrfs_init_free_space_ctl(cache);
8152 btrfs_set_block_group_used(&cache->item, bytes_used);
8153 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
8154 cache->flags = type;
8155 btrfs_set_block_group_flags(&cache->item, type);
8157 cache->last_byte_to_unpin = (u64)-1;
8158 cache->cached = BTRFS_CACHE_FINISHED;
8159 ret = exclude_super_stripes(root, cache);
8162 * We may have excluded something, so call this just in
8165 free_excluded_extents(root, cache);
8166 kfree(cache->free_space_ctl);
8171 add_new_free_space(cache, root->fs_info, chunk_offset,
8172 chunk_offset + size);
8174 free_excluded_extents(root, cache);
8176 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
8177 &cache->space_info);
8178 BUG_ON(ret); /* -ENOMEM */
8179 update_global_block_rsv(root->fs_info);
8181 spin_lock(&cache->space_info->lock);
8182 cache->space_info->bytes_readonly += cache->bytes_super;
8183 spin_unlock(&cache->space_info->lock);
8185 __link_block_group(cache->space_info, cache);
8187 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8188 BUG_ON(ret); /* Logic error */
8190 list_add_tail(&cache->new_bg_list, &trans->new_bgs);
8192 set_avail_alloc_bits(extent_root->fs_info, type);
8197 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
8199 u64 extra_flags = chunk_to_extended(flags) &
8200 BTRFS_EXTENDED_PROFILE_MASK;
8202 write_seqlock(&fs_info->profiles_lock);
8203 if (flags & BTRFS_BLOCK_GROUP_DATA)
8204 fs_info->avail_data_alloc_bits &= ~extra_flags;
8205 if (flags & BTRFS_BLOCK_GROUP_METADATA)
8206 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
8207 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
8208 fs_info->avail_system_alloc_bits &= ~extra_flags;
8209 write_sequnlock(&fs_info->profiles_lock);
8212 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8213 struct btrfs_root *root, u64 group_start)
8215 struct btrfs_path *path;
8216 struct btrfs_block_group_cache *block_group;
8217 struct btrfs_free_cluster *cluster;
8218 struct btrfs_root *tree_root = root->fs_info->tree_root;
8219 struct btrfs_key key;
8220 struct inode *inode;
8225 root = root->fs_info->extent_root;
8227 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
8228 BUG_ON(!block_group);
8229 BUG_ON(!block_group->ro);
8232 * Free the reserved super bytes from this block group before
8235 free_excluded_extents(root, block_group);
8237 memcpy(&key, &block_group->key, sizeof(key));
8238 index = get_block_group_index(block_group);
8239 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
8240 BTRFS_BLOCK_GROUP_RAID1 |
8241 BTRFS_BLOCK_GROUP_RAID10))
8246 /* make sure this block group isn't part of an allocation cluster */
8247 cluster = &root->fs_info->data_alloc_cluster;
8248 spin_lock(&cluster->refill_lock);
8249 btrfs_return_cluster_to_free_space(block_group, cluster);
8250 spin_unlock(&cluster->refill_lock);
8253 * make sure this block group isn't part of a metadata
8254 * allocation cluster
8256 cluster = &root->fs_info->meta_alloc_cluster;
8257 spin_lock(&cluster->refill_lock);
8258 btrfs_return_cluster_to_free_space(block_group, cluster);
8259 spin_unlock(&cluster->refill_lock);
8261 path = btrfs_alloc_path();
8267 inode = lookup_free_space_inode(tree_root, block_group, path);
8268 if (!IS_ERR(inode)) {
8269 ret = btrfs_orphan_add(trans, inode);
8271 btrfs_add_delayed_iput(inode);
8275 /* One for the block groups ref */
8276 spin_lock(&block_group->lock);
8277 if (block_group->iref) {
8278 block_group->iref = 0;
8279 block_group->inode = NULL;
8280 spin_unlock(&block_group->lock);
8283 spin_unlock(&block_group->lock);
8285 /* One for our lookup ref */
8286 btrfs_add_delayed_iput(inode);
8289 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8290 key.offset = block_group->key.objectid;
8293 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8297 btrfs_release_path(path);
8299 ret = btrfs_del_item(trans, tree_root, path);
8302 btrfs_release_path(path);
8305 spin_lock(&root->fs_info->block_group_cache_lock);
8306 rb_erase(&block_group->cache_node,
8307 &root->fs_info->block_group_cache_tree);
8309 if (root->fs_info->first_logical_byte == block_group->key.objectid)
8310 root->fs_info->first_logical_byte = (u64)-1;
8311 spin_unlock(&root->fs_info->block_group_cache_lock);
8313 down_write(&block_group->space_info->groups_sem);
8315 * we must use list_del_init so people can check to see if they
8316 * are still on the list after taking the semaphore
8318 list_del_init(&block_group->list);
8319 if (list_empty(&block_group->space_info->block_groups[index]))
8320 clear_avail_alloc_bits(root->fs_info, block_group->flags);
8321 up_write(&block_group->space_info->groups_sem);
8323 if (block_group->cached == BTRFS_CACHE_STARTED)
8324 wait_block_group_cache_done(block_group);
8326 btrfs_remove_free_space_cache(block_group);
8328 spin_lock(&block_group->space_info->lock);
8329 block_group->space_info->total_bytes -= block_group->key.offset;
8330 block_group->space_info->bytes_readonly -= block_group->key.offset;
8331 block_group->space_info->disk_total -= block_group->key.offset * factor;
8332 spin_unlock(&block_group->space_info->lock);
8334 memcpy(&key, &block_group->key, sizeof(key));
8336 btrfs_clear_space_info_full(root->fs_info);
8338 btrfs_put_block_group(block_group);
8339 btrfs_put_block_group(block_group);
8341 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8347 ret = btrfs_del_item(trans, root, path);
8349 btrfs_free_path(path);
8353 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
8355 struct btrfs_space_info *space_info;
8356 struct btrfs_super_block *disk_super;
8362 disk_super = fs_info->super_copy;
8363 if (!btrfs_super_root(disk_super))
8366 features = btrfs_super_incompat_flags(disk_super);
8367 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
8370 flags = BTRFS_BLOCK_GROUP_SYSTEM;
8371 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8376 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
8377 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8379 flags = BTRFS_BLOCK_GROUP_METADATA;
8380 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8384 flags = BTRFS_BLOCK_GROUP_DATA;
8385 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8391 int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
8393 return unpin_extent_range(root, start, end);
8396 int btrfs_error_discard_extent(struct btrfs_root *root, u64 bytenr,
8397 u64 num_bytes, u64 *actual_bytes)
8399 return btrfs_discard_extent(root, bytenr, num_bytes, actual_bytes);
8402 int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
8404 struct btrfs_fs_info *fs_info = root->fs_info;
8405 struct btrfs_block_group_cache *cache = NULL;
8410 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
8414 * try to trim all FS space, our block group may start from non-zero.
8416 if (range->len == total_bytes)
8417 cache = btrfs_lookup_first_block_group(fs_info, range->start);
8419 cache = btrfs_lookup_block_group(fs_info, range->start);
8422 if (cache->key.objectid >= (range->start + range->len)) {
8423 btrfs_put_block_group(cache);
8427 start = max(range->start, cache->key.objectid);
8428 end = min(range->start + range->len,
8429 cache->key.objectid + cache->key.offset);
8431 if (end - start >= range->minlen) {
8432 if (!block_group_cache_done(cache)) {
8433 ret = cache_block_group(cache, 0);
8435 wait_block_group_cache_done(cache);
8437 ret = btrfs_trim_block_group(cache,
8443 trimmed += group_trimmed;
8445 btrfs_put_block_group(cache);
8450 cache = next_block_group(fs_info->tree_root, cache);
8453 range->len = trimmed;