2 * Copyright (C) 2007 Oracle. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
18 #include <linux/sched.h>
19 #include <linux/pagemap.h>
20 #include <linux/writeback.h>
21 #include <linux/blkdev.h>
22 #include <linux/sort.h>
23 #include <linux/rcupdate.h>
24 #include <linux/kthread.h>
25 #include <linux/slab.h>
26 #include <linux/ratelimit.h>
27 #include <linux/percpu_counter.h>
32 #include "print-tree.h"
33 #include "transaction.h"
37 #include "free-space-cache.h"
40 #undef SCRAMBLE_DELAYED_REFS
43 * control flags for do_chunk_alloc's force field
44 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
45 * if we really need one.
47 * CHUNK_ALLOC_LIMITED means to only try and allocate one
48 * if we have very few chunks already allocated. This is
49 * used as part of the clustering code to help make sure
50 * we have a good pool of storage to cluster in, without
51 * filling the FS with empty chunks
53 * CHUNK_ALLOC_FORCE means it must try to allocate one
57 CHUNK_ALLOC_NO_FORCE = 0,
58 CHUNK_ALLOC_LIMITED = 1,
59 CHUNK_ALLOC_FORCE = 2,
63 * Control how reservations are dealt with.
65 * RESERVE_FREE - freeing a reservation.
66 * RESERVE_ALLOC - allocating space and we need to update bytes_may_use for
68 * RESERVE_ALLOC_NO_ACCOUNT - allocating space and we should not update
69 * bytes_may_use as the ENOSPC accounting is done elsewhere
74 RESERVE_ALLOC_NO_ACCOUNT = 2,
77 static int update_block_group(struct btrfs_root *root,
78 u64 bytenr, u64 num_bytes, int alloc);
79 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
80 struct btrfs_root *root,
81 u64 bytenr, u64 num_bytes, u64 parent,
82 u64 root_objectid, u64 owner_objectid,
83 u64 owner_offset, int refs_to_drop,
84 struct btrfs_delayed_extent_op *extra_op);
85 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
86 struct extent_buffer *leaf,
87 struct btrfs_extent_item *ei);
88 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
89 struct btrfs_root *root,
90 u64 parent, u64 root_objectid,
91 u64 flags, u64 owner, u64 offset,
92 struct btrfs_key *ins, int ref_mod);
93 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
94 struct btrfs_root *root,
95 u64 parent, u64 root_objectid,
96 u64 flags, struct btrfs_disk_key *key,
97 int level, struct btrfs_key *ins);
98 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
99 struct btrfs_root *extent_root, u64 flags,
101 static int find_next_key(struct btrfs_path *path, int level,
102 struct btrfs_key *key);
103 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
104 int dump_block_groups);
105 static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
106 u64 num_bytes, int reserve);
107 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
109 int btrfs_pin_extent(struct btrfs_root *root,
110 u64 bytenr, u64 num_bytes, int reserved);
113 block_group_cache_done(struct btrfs_block_group_cache *cache)
116 return cache->cached == BTRFS_CACHE_FINISHED;
119 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
121 return (cache->flags & bits) == bits;
124 static void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
126 atomic_inc(&cache->count);
129 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
131 if (atomic_dec_and_test(&cache->count)) {
132 WARN_ON(cache->pinned > 0);
133 WARN_ON(cache->reserved > 0);
134 kfree(cache->free_space_ctl);
140 * this adds the block group to the fs_info rb tree for the block group
143 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
144 struct btrfs_block_group_cache *block_group)
147 struct rb_node *parent = NULL;
148 struct btrfs_block_group_cache *cache;
150 spin_lock(&info->block_group_cache_lock);
151 p = &info->block_group_cache_tree.rb_node;
155 cache = rb_entry(parent, struct btrfs_block_group_cache,
157 if (block_group->key.objectid < cache->key.objectid) {
159 } else if (block_group->key.objectid > cache->key.objectid) {
162 spin_unlock(&info->block_group_cache_lock);
167 rb_link_node(&block_group->cache_node, parent, p);
168 rb_insert_color(&block_group->cache_node,
169 &info->block_group_cache_tree);
171 if (info->first_logical_byte > block_group->key.objectid)
172 info->first_logical_byte = block_group->key.objectid;
174 spin_unlock(&info->block_group_cache_lock);
180 * This will return the block group at or after bytenr if contains is 0, else
181 * it will return the block group that contains the bytenr
183 static struct btrfs_block_group_cache *
184 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
187 struct btrfs_block_group_cache *cache, *ret = NULL;
191 spin_lock(&info->block_group_cache_lock);
192 n = info->block_group_cache_tree.rb_node;
195 cache = rb_entry(n, struct btrfs_block_group_cache,
197 end = cache->key.objectid + cache->key.offset - 1;
198 start = cache->key.objectid;
200 if (bytenr < start) {
201 if (!contains && (!ret || start < ret->key.objectid))
204 } else if (bytenr > start) {
205 if (contains && bytenr <= end) {
216 btrfs_get_block_group(ret);
217 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
218 info->first_logical_byte = ret->key.objectid;
220 spin_unlock(&info->block_group_cache_lock);
225 static int add_excluded_extent(struct btrfs_root *root,
226 u64 start, u64 num_bytes)
228 u64 end = start + num_bytes - 1;
229 set_extent_bits(&root->fs_info->freed_extents[0],
230 start, end, EXTENT_UPTODATE, GFP_NOFS);
231 set_extent_bits(&root->fs_info->freed_extents[1],
232 start, end, EXTENT_UPTODATE, GFP_NOFS);
236 static void free_excluded_extents(struct btrfs_root *root,
237 struct btrfs_block_group_cache *cache)
241 start = cache->key.objectid;
242 end = start + cache->key.offset - 1;
244 clear_extent_bits(&root->fs_info->freed_extents[0],
245 start, end, EXTENT_UPTODATE, GFP_NOFS);
246 clear_extent_bits(&root->fs_info->freed_extents[1],
247 start, end, EXTENT_UPTODATE, GFP_NOFS);
250 static int exclude_super_stripes(struct btrfs_root *root,
251 struct btrfs_block_group_cache *cache)
258 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
259 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
260 cache->bytes_super += stripe_len;
261 ret = add_excluded_extent(root, cache->key.objectid,
267 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
268 bytenr = btrfs_sb_offset(i);
269 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
270 cache->key.objectid, bytenr,
271 0, &logical, &nr, &stripe_len);
278 if (logical[nr] > cache->key.objectid +
282 if (logical[nr] + stripe_len <= cache->key.objectid)
286 if (start < cache->key.objectid) {
287 start = cache->key.objectid;
288 len = (logical[nr] + stripe_len) - start;
290 len = min_t(u64, stripe_len,
291 cache->key.objectid +
292 cache->key.offset - start);
295 cache->bytes_super += len;
296 ret = add_excluded_extent(root, start, len);
308 static struct btrfs_caching_control *
309 get_caching_control(struct btrfs_block_group_cache *cache)
311 struct btrfs_caching_control *ctl;
313 spin_lock(&cache->lock);
314 if (cache->cached != BTRFS_CACHE_STARTED) {
315 spin_unlock(&cache->lock);
319 /* We're loading it the fast way, so we don't have a caching_ctl. */
320 if (!cache->caching_ctl) {
321 spin_unlock(&cache->lock);
325 ctl = cache->caching_ctl;
326 atomic_inc(&ctl->count);
327 spin_unlock(&cache->lock);
331 static void put_caching_control(struct btrfs_caching_control *ctl)
333 if (atomic_dec_and_test(&ctl->count))
338 * this is only called by cache_block_group, since we could have freed extents
339 * we need to check the pinned_extents for any extents that can't be used yet
340 * since their free space will be released as soon as the transaction commits.
342 static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
343 struct btrfs_fs_info *info, u64 start, u64 end)
345 u64 extent_start, extent_end, size, total_added = 0;
348 while (start < end) {
349 ret = find_first_extent_bit(info->pinned_extents, start,
350 &extent_start, &extent_end,
351 EXTENT_DIRTY | EXTENT_UPTODATE,
356 if (extent_start <= start) {
357 start = extent_end + 1;
358 } else if (extent_start > start && extent_start < end) {
359 size = extent_start - start;
361 ret = btrfs_add_free_space(block_group, start,
363 BUG_ON(ret); /* -ENOMEM or logic error */
364 start = extent_end + 1;
373 ret = btrfs_add_free_space(block_group, start, size);
374 BUG_ON(ret); /* -ENOMEM or logic error */
380 static noinline void caching_thread(struct btrfs_work *work)
382 struct btrfs_block_group_cache *block_group;
383 struct btrfs_fs_info *fs_info;
384 struct btrfs_caching_control *caching_ctl;
385 struct btrfs_root *extent_root;
386 struct btrfs_path *path;
387 struct extent_buffer *leaf;
388 struct btrfs_key key;
394 caching_ctl = container_of(work, struct btrfs_caching_control, work);
395 block_group = caching_ctl->block_group;
396 fs_info = block_group->fs_info;
397 extent_root = fs_info->extent_root;
399 path = btrfs_alloc_path();
403 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
406 * We don't want to deadlock with somebody trying to allocate a new
407 * extent for the extent root while also trying to search the extent
408 * root to add free space. So we skip locking and search the commit
409 * root, since its read-only
411 path->skip_locking = 1;
412 path->search_commit_root = 1;
417 key.type = BTRFS_EXTENT_ITEM_KEY;
419 mutex_lock(&caching_ctl->mutex);
420 /* need to make sure the commit_root doesn't disappear */
421 down_read(&fs_info->extent_commit_sem);
424 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
428 leaf = path->nodes[0];
429 nritems = btrfs_header_nritems(leaf);
432 if (btrfs_fs_closing(fs_info) > 1) {
437 if (path->slots[0] < nritems) {
438 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
440 ret = find_next_key(path, 0, &key);
444 if (need_resched()) {
445 caching_ctl->progress = last;
446 btrfs_release_path(path);
447 up_read(&fs_info->extent_commit_sem);
448 mutex_unlock(&caching_ctl->mutex);
453 ret = btrfs_next_leaf(extent_root, path);
458 leaf = path->nodes[0];
459 nritems = btrfs_header_nritems(leaf);
463 if (key.objectid < last) {
466 key.type = BTRFS_EXTENT_ITEM_KEY;
468 caching_ctl->progress = last;
469 btrfs_release_path(path);
473 if (key.objectid < block_group->key.objectid) {
478 if (key.objectid >= block_group->key.objectid +
479 block_group->key.offset)
482 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
483 key.type == BTRFS_METADATA_ITEM_KEY) {
484 total_found += add_new_free_space(block_group,
487 if (key.type == BTRFS_METADATA_ITEM_KEY)
488 last = key.objectid +
489 fs_info->tree_root->leafsize;
491 last = key.objectid + key.offset;
493 if (total_found > (1024 * 1024 * 2)) {
495 wake_up(&caching_ctl->wait);
502 total_found += add_new_free_space(block_group, fs_info, last,
503 block_group->key.objectid +
504 block_group->key.offset);
505 caching_ctl->progress = (u64)-1;
507 spin_lock(&block_group->lock);
508 block_group->caching_ctl = NULL;
509 block_group->cached = BTRFS_CACHE_FINISHED;
510 spin_unlock(&block_group->lock);
513 btrfs_free_path(path);
514 up_read(&fs_info->extent_commit_sem);
516 free_excluded_extents(extent_root, block_group);
518 mutex_unlock(&caching_ctl->mutex);
520 wake_up(&caching_ctl->wait);
522 put_caching_control(caching_ctl);
523 btrfs_put_block_group(block_group);
526 static int cache_block_group(struct btrfs_block_group_cache *cache,
530 struct btrfs_fs_info *fs_info = cache->fs_info;
531 struct btrfs_caching_control *caching_ctl;
534 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
538 INIT_LIST_HEAD(&caching_ctl->list);
539 mutex_init(&caching_ctl->mutex);
540 init_waitqueue_head(&caching_ctl->wait);
541 caching_ctl->block_group = cache;
542 caching_ctl->progress = cache->key.objectid;
543 atomic_set(&caching_ctl->count, 1);
544 caching_ctl->work.func = caching_thread;
546 spin_lock(&cache->lock);
548 * This should be a rare occasion, but this could happen I think in the
549 * case where one thread starts to load the space cache info, and then
550 * some other thread starts a transaction commit which tries to do an
551 * allocation while the other thread is still loading the space cache
552 * info. The previous loop should have kept us from choosing this block
553 * group, but if we've moved to the state where we will wait on caching
554 * block groups we need to first check if we're doing a fast load here,
555 * so we can wait for it to finish, otherwise we could end up allocating
556 * from a block group who's cache gets evicted for one reason or
559 while (cache->cached == BTRFS_CACHE_FAST) {
560 struct btrfs_caching_control *ctl;
562 ctl = cache->caching_ctl;
563 atomic_inc(&ctl->count);
564 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
565 spin_unlock(&cache->lock);
569 finish_wait(&ctl->wait, &wait);
570 put_caching_control(ctl);
571 spin_lock(&cache->lock);
574 if (cache->cached != BTRFS_CACHE_NO) {
575 spin_unlock(&cache->lock);
579 WARN_ON(cache->caching_ctl);
580 cache->caching_ctl = caching_ctl;
581 cache->cached = BTRFS_CACHE_FAST;
582 spin_unlock(&cache->lock);
584 if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
585 ret = load_free_space_cache(fs_info, cache);
587 spin_lock(&cache->lock);
589 cache->caching_ctl = NULL;
590 cache->cached = BTRFS_CACHE_FINISHED;
591 cache->last_byte_to_unpin = (u64)-1;
593 if (load_cache_only) {
594 cache->caching_ctl = NULL;
595 cache->cached = BTRFS_CACHE_NO;
597 cache->cached = BTRFS_CACHE_STARTED;
600 spin_unlock(&cache->lock);
601 wake_up(&caching_ctl->wait);
603 put_caching_control(caching_ctl);
604 free_excluded_extents(fs_info->extent_root, cache);
609 * We are not going to do the fast caching, set cached to the
610 * appropriate value and wakeup any waiters.
612 spin_lock(&cache->lock);
613 if (load_cache_only) {
614 cache->caching_ctl = NULL;
615 cache->cached = BTRFS_CACHE_NO;
617 cache->cached = BTRFS_CACHE_STARTED;
619 spin_unlock(&cache->lock);
620 wake_up(&caching_ctl->wait);
623 if (load_cache_only) {
624 put_caching_control(caching_ctl);
628 down_write(&fs_info->extent_commit_sem);
629 atomic_inc(&caching_ctl->count);
630 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
631 up_write(&fs_info->extent_commit_sem);
633 btrfs_get_block_group(cache);
635 btrfs_queue_worker(&fs_info->caching_workers, &caching_ctl->work);
641 * return the block group that starts at or after bytenr
643 static struct btrfs_block_group_cache *
644 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
646 struct btrfs_block_group_cache *cache;
648 cache = block_group_cache_tree_search(info, bytenr, 0);
654 * return the block group that contains the given bytenr
656 struct btrfs_block_group_cache *btrfs_lookup_block_group(
657 struct btrfs_fs_info *info,
660 struct btrfs_block_group_cache *cache;
662 cache = block_group_cache_tree_search(info, bytenr, 1);
667 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
670 struct list_head *head = &info->space_info;
671 struct btrfs_space_info *found;
673 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
676 list_for_each_entry_rcu(found, head, list) {
677 if (found->flags & flags) {
687 * after adding space to the filesystem, we need to clear the full flags
688 * on all the space infos.
690 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
692 struct list_head *head = &info->space_info;
693 struct btrfs_space_info *found;
696 list_for_each_entry_rcu(found, head, list)
701 /* simple helper to search for an existing extent at a given offset */
702 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
705 struct btrfs_key key;
706 struct btrfs_path *path;
708 path = btrfs_alloc_path();
712 key.objectid = start;
714 key.type = BTRFS_EXTENT_ITEM_KEY;
715 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
718 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
719 if (key.objectid == start &&
720 key.type == BTRFS_METADATA_ITEM_KEY)
723 btrfs_free_path(path);
728 * helper function to lookup reference count and flags of a tree block.
730 * the head node for delayed ref is used to store the sum of all the
731 * reference count modifications queued up in the rbtree. the head
732 * node may also store the extent flags to set. This way you can check
733 * to see what the reference count and extent flags would be if all of
734 * the delayed refs are not processed.
736 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
737 struct btrfs_root *root, u64 bytenr,
738 u64 offset, int metadata, u64 *refs, u64 *flags)
740 struct btrfs_delayed_ref_head *head;
741 struct btrfs_delayed_ref_root *delayed_refs;
742 struct btrfs_path *path;
743 struct btrfs_extent_item *ei;
744 struct extent_buffer *leaf;
745 struct btrfs_key key;
752 * If we don't have skinny metadata, don't bother doing anything
755 if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA)) {
756 offset = root->leafsize;
760 path = btrfs_alloc_path();
765 key.objectid = bytenr;
766 key.type = BTRFS_METADATA_ITEM_KEY;
769 key.objectid = bytenr;
770 key.type = BTRFS_EXTENT_ITEM_KEY;
775 path->skip_locking = 1;
776 path->search_commit_root = 1;
779 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
784 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
786 if (path->slots[0]) {
788 btrfs_item_key_to_cpu(path->nodes[0], &key,
790 if (key.objectid == bytenr &&
791 key.type == BTRFS_EXTENT_ITEM_KEY &&
792 key.offset == root->leafsize)
796 key.objectid = bytenr;
797 key.type = BTRFS_EXTENT_ITEM_KEY;
798 key.offset = root->leafsize;
799 btrfs_release_path(path);
805 leaf = path->nodes[0];
806 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
807 if (item_size >= sizeof(*ei)) {
808 ei = btrfs_item_ptr(leaf, path->slots[0],
809 struct btrfs_extent_item);
810 num_refs = btrfs_extent_refs(leaf, ei);
811 extent_flags = btrfs_extent_flags(leaf, ei);
813 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
814 struct btrfs_extent_item_v0 *ei0;
815 BUG_ON(item_size != sizeof(*ei0));
816 ei0 = btrfs_item_ptr(leaf, path->slots[0],
817 struct btrfs_extent_item_v0);
818 num_refs = btrfs_extent_refs_v0(leaf, ei0);
819 /* FIXME: this isn't correct for data */
820 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
825 BUG_ON(num_refs == 0);
835 delayed_refs = &trans->transaction->delayed_refs;
836 spin_lock(&delayed_refs->lock);
837 head = btrfs_find_delayed_ref_head(trans, bytenr);
839 if (!mutex_trylock(&head->mutex)) {
840 atomic_inc(&head->node.refs);
841 spin_unlock(&delayed_refs->lock);
843 btrfs_release_path(path);
846 * Mutex was contended, block until it's released and try
849 mutex_lock(&head->mutex);
850 mutex_unlock(&head->mutex);
851 btrfs_put_delayed_ref(&head->node);
854 if (head->extent_op && head->extent_op->update_flags)
855 extent_flags |= head->extent_op->flags_to_set;
857 BUG_ON(num_refs == 0);
859 num_refs += head->node.ref_mod;
860 mutex_unlock(&head->mutex);
862 spin_unlock(&delayed_refs->lock);
864 WARN_ON(num_refs == 0);
868 *flags = extent_flags;
870 btrfs_free_path(path);
875 * Back reference rules. Back refs have three main goals:
877 * 1) differentiate between all holders of references to an extent so that
878 * when a reference is dropped we can make sure it was a valid reference
879 * before freeing the extent.
881 * 2) Provide enough information to quickly find the holders of an extent
882 * if we notice a given block is corrupted or bad.
884 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
885 * maintenance. This is actually the same as #2, but with a slightly
886 * different use case.
888 * There are two kinds of back refs. The implicit back refs is optimized
889 * for pointers in non-shared tree blocks. For a given pointer in a block,
890 * back refs of this kind provide information about the block's owner tree
891 * and the pointer's key. These information allow us to find the block by
892 * b-tree searching. The full back refs is for pointers in tree blocks not
893 * referenced by their owner trees. The location of tree block is recorded
894 * in the back refs. Actually the full back refs is generic, and can be
895 * used in all cases the implicit back refs is used. The major shortcoming
896 * of the full back refs is its overhead. Every time a tree block gets
897 * COWed, we have to update back refs entry for all pointers in it.
899 * For a newly allocated tree block, we use implicit back refs for
900 * pointers in it. This means most tree related operations only involve
901 * implicit back refs. For a tree block created in old transaction, the
902 * only way to drop a reference to it is COW it. So we can detect the
903 * event that tree block loses its owner tree's reference and do the
904 * back refs conversion.
906 * When a tree block is COW'd through a tree, there are four cases:
908 * The reference count of the block is one and the tree is the block's
909 * owner tree. Nothing to do in this case.
911 * The reference count of the block is one and the tree is not the
912 * block's owner tree. In this case, full back refs is used for pointers
913 * in the block. Remove these full back refs, add implicit back refs for
914 * every pointers in the new block.
916 * The reference count of the block is greater than one and the tree is
917 * the block's owner tree. In this case, implicit back refs is used for
918 * pointers in the block. Add full back refs for every pointers in the
919 * block, increase lower level extents' reference counts. The original
920 * implicit back refs are entailed to the new block.
922 * The reference count of the block is greater than one and the tree is
923 * not the block's owner tree. Add implicit back refs for every pointer in
924 * the new block, increase lower level extents' reference count.
926 * Back Reference Key composing:
928 * The key objectid corresponds to the first byte in the extent,
929 * The key type is used to differentiate between types of back refs.
930 * There are different meanings of the key offset for different types
933 * File extents can be referenced by:
935 * - multiple snapshots, subvolumes, or different generations in one subvol
936 * - different files inside a single subvolume
937 * - different offsets inside a file (bookend extents in file.c)
939 * The extent ref structure for the implicit back refs has fields for:
941 * - Objectid of the subvolume root
942 * - objectid of the file holding the reference
943 * - original offset in the file
944 * - how many bookend extents
946 * The key offset for the implicit back refs is hash of the first
949 * The extent ref structure for the full back refs has field for:
951 * - number of pointers in the tree leaf
953 * The key offset for the implicit back refs is the first byte of
956 * When a file extent is allocated, The implicit back refs is used.
957 * the fields are filled in:
959 * (root_key.objectid, inode objectid, offset in file, 1)
961 * When a file extent is removed file truncation, we find the
962 * corresponding implicit back refs and check the following fields:
964 * (btrfs_header_owner(leaf), inode objectid, offset in file)
966 * Btree extents can be referenced by:
968 * - Different subvolumes
970 * Both the implicit back refs and the full back refs for tree blocks
971 * only consist of key. The key offset for the implicit back refs is
972 * objectid of block's owner tree. The key offset for the full back refs
973 * is the first byte of parent block.
975 * When implicit back refs is used, information about the lowest key and
976 * level of the tree block are required. These information are stored in
977 * tree block info structure.
980 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
981 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
982 struct btrfs_root *root,
983 struct btrfs_path *path,
984 u64 owner, u32 extra_size)
986 struct btrfs_extent_item *item;
987 struct btrfs_extent_item_v0 *ei0;
988 struct btrfs_extent_ref_v0 *ref0;
989 struct btrfs_tree_block_info *bi;
990 struct extent_buffer *leaf;
991 struct btrfs_key key;
992 struct btrfs_key found_key;
993 u32 new_size = sizeof(*item);
997 leaf = path->nodes[0];
998 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1000 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1001 ei0 = btrfs_item_ptr(leaf, path->slots[0],
1002 struct btrfs_extent_item_v0);
1003 refs = btrfs_extent_refs_v0(leaf, ei0);
1005 if (owner == (u64)-1) {
1007 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1008 ret = btrfs_next_leaf(root, path);
1011 BUG_ON(ret > 0); /* Corruption */
1012 leaf = path->nodes[0];
1014 btrfs_item_key_to_cpu(leaf, &found_key,
1016 BUG_ON(key.objectid != found_key.objectid);
1017 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1021 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1022 struct btrfs_extent_ref_v0);
1023 owner = btrfs_ref_objectid_v0(leaf, ref0);
1027 btrfs_release_path(path);
1029 if (owner < BTRFS_FIRST_FREE_OBJECTID)
1030 new_size += sizeof(*bi);
1032 new_size -= sizeof(*ei0);
1033 ret = btrfs_search_slot(trans, root, &key, path,
1034 new_size + extra_size, 1);
1037 BUG_ON(ret); /* Corruption */
1039 btrfs_extend_item(root, path, new_size);
1041 leaf = path->nodes[0];
1042 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1043 btrfs_set_extent_refs(leaf, item, refs);
1044 /* FIXME: get real generation */
1045 btrfs_set_extent_generation(leaf, item, 0);
1046 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1047 btrfs_set_extent_flags(leaf, item,
1048 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1049 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1050 bi = (struct btrfs_tree_block_info *)(item + 1);
1051 /* FIXME: get first key of the block */
1052 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
1053 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1055 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1057 btrfs_mark_buffer_dirty(leaf);
1062 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1064 u32 high_crc = ~(u32)0;
1065 u32 low_crc = ~(u32)0;
1068 lenum = cpu_to_le64(root_objectid);
1069 high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
1070 lenum = cpu_to_le64(owner);
1071 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1072 lenum = cpu_to_le64(offset);
1073 low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
1075 return ((u64)high_crc << 31) ^ (u64)low_crc;
1078 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1079 struct btrfs_extent_data_ref *ref)
1081 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1082 btrfs_extent_data_ref_objectid(leaf, ref),
1083 btrfs_extent_data_ref_offset(leaf, ref));
1086 static int match_extent_data_ref(struct extent_buffer *leaf,
1087 struct btrfs_extent_data_ref *ref,
1088 u64 root_objectid, u64 owner, u64 offset)
1090 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1091 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1092 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1097 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1098 struct btrfs_root *root,
1099 struct btrfs_path *path,
1100 u64 bytenr, u64 parent,
1102 u64 owner, u64 offset)
1104 struct btrfs_key key;
1105 struct btrfs_extent_data_ref *ref;
1106 struct extent_buffer *leaf;
1112 key.objectid = bytenr;
1114 key.type = BTRFS_SHARED_DATA_REF_KEY;
1115 key.offset = parent;
1117 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1118 key.offset = hash_extent_data_ref(root_objectid,
1123 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1132 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1133 key.type = BTRFS_EXTENT_REF_V0_KEY;
1134 btrfs_release_path(path);
1135 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1146 leaf = path->nodes[0];
1147 nritems = btrfs_header_nritems(leaf);
1149 if (path->slots[0] >= nritems) {
1150 ret = btrfs_next_leaf(root, path);
1156 leaf = path->nodes[0];
1157 nritems = btrfs_header_nritems(leaf);
1161 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1162 if (key.objectid != bytenr ||
1163 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1166 ref = btrfs_item_ptr(leaf, path->slots[0],
1167 struct btrfs_extent_data_ref);
1169 if (match_extent_data_ref(leaf, ref, root_objectid,
1172 btrfs_release_path(path);
1184 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1185 struct btrfs_root *root,
1186 struct btrfs_path *path,
1187 u64 bytenr, u64 parent,
1188 u64 root_objectid, u64 owner,
1189 u64 offset, int refs_to_add)
1191 struct btrfs_key key;
1192 struct extent_buffer *leaf;
1197 key.objectid = bytenr;
1199 key.type = BTRFS_SHARED_DATA_REF_KEY;
1200 key.offset = parent;
1201 size = sizeof(struct btrfs_shared_data_ref);
1203 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1204 key.offset = hash_extent_data_ref(root_objectid,
1206 size = sizeof(struct btrfs_extent_data_ref);
1209 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1210 if (ret && ret != -EEXIST)
1213 leaf = path->nodes[0];
1215 struct btrfs_shared_data_ref *ref;
1216 ref = btrfs_item_ptr(leaf, path->slots[0],
1217 struct btrfs_shared_data_ref);
1219 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1221 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1222 num_refs += refs_to_add;
1223 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1226 struct btrfs_extent_data_ref *ref;
1227 while (ret == -EEXIST) {
1228 ref = btrfs_item_ptr(leaf, path->slots[0],
1229 struct btrfs_extent_data_ref);
1230 if (match_extent_data_ref(leaf, ref, root_objectid,
1233 btrfs_release_path(path);
1235 ret = btrfs_insert_empty_item(trans, root, path, &key,
1237 if (ret && ret != -EEXIST)
1240 leaf = path->nodes[0];
1242 ref = btrfs_item_ptr(leaf, path->slots[0],
1243 struct btrfs_extent_data_ref);
1245 btrfs_set_extent_data_ref_root(leaf, ref,
1247 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1248 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1249 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1251 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1252 num_refs += refs_to_add;
1253 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1256 btrfs_mark_buffer_dirty(leaf);
1259 btrfs_release_path(path);
1263 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1264 struct btrfs_root *root,
1265 struct btrfs_path *path,
1268 struct btrfs_key key;
1269 struct btrfs_extent_data_ref *ref1 = NULL;
1270 struct btrfs_shared_data_ref *ref2 = NULL;
1271 struct extent_buffer *leaf;
1275 leaf = path->nodes[0];
1276 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1278 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1279 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1280 struct btrfs_extent_data_ref);
1281 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1282 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1283 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1284 struct btrfs_shared_data_ref);
1285 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1286 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1287 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1288 struct btrfs_extent_ref_v0 *ref0;
1289 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1290 struct btrfs_extent_ref_v0);
1291 num_refs = btrfs_ref_count_v0(leaf, ref0);
1297 BUG_ON(num_refs < refs_to_drop);
1298 num_refs -= refs_to_drop;
1300 if (num_refs == 0) {
1301 ret = btrfs_del_item(trans, root, path);
1303 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1304 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1305 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1306 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1307 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1309 struct btrfs_extent_ref_v0 *ref0;
1310 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1311 struct btrfs_extent_ref_v0);
1312 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1315 btrfs_mark_buffer_dirty(leaf);
1320 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1321 struct btrfs_path *path,
1322 struct btrfs_extent_inline_ref *iref)
1324 struct btrfs_key key;
1325 struct extent_buffer *leaf;
1326 struct btrfs_extent_data_ref *ref1;
1327 struct btrfs_shared_data_ref *ref2;
1330 leaf = path->nodes[0];
1331 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1333 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1334 BTRFS_EXTENT_DATA_REF_KEY) {
1335 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1336 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1338 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1339 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1341 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1342 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1343 struct btrfs_extent_data_ref);
1344 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1345 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1346 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1347 struct btrfs_shared_data_ref);
1348 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1349 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1350 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1351 struct btrfs_extent_ref_v0 *ref0;
1352 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1353 struct btrfs_extent_ref_v0);
1354 num_refs = btrfs_ref_count_v0(leaf, ref0);
1362 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1363 struct btrfs_root *root,
1364 struct btrfs_path *path,
1365 u64 bytenr, u64 parent,
1368 struct btrfs_key key;
1371 key.objectid = bytenr;
1373 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1374 key.offset = parent;
1376 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1377 key.offset = root_objectid;
1380 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1383 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1384 if (ret == -ENOENT && parent) {
1385 btrfs_release_path(path);
1386 key.type = BTRFS_EXTENT_REF_V0_KEY;
1387 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1395 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1396 struct btrfs_root *root,
1397 struct btrfs_path *path,
1398 u64 bytenr, u64 parent,
1401 struct btrfs_key key;
1404 key.objectid = bytenr;
1406 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1407 key.offset = parent;
1409 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1410 key.offset = root_objectid;
1413 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1414 btrfs_release_path(path);
1418 static inline int extent_ref_type(u64 parent, u64 owner)
1421 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1423 type = BTRFS_SHARED_BLOCK_REF_KEY;
1425 type = BTRFS_TREE_BLOCK_REF_KEY;
1428 type = BTRFS_SHARED_DATA_REF_KEY;
1430 type = BTRFS_EXTENT_DATA_REF_KEY;
1435 static int find_next_key(struct btrfs_path *path, int level,
1436 struct btrfs_key *key)
1439 for (; level < BTRFS_MAX_LEVEL; level++) {
1440 if (!path->nodes[level])
1442 if (path->slots[level] + 1 >=
1443 btrfs_header_nritems(path->nodes[level]))
1446 btrfs_item_key_to_cpu(path->nodes[level], key,
1447 path->slots[level] + 1);
1449 btrfs_node_key_to_cpu(path->nodes[level], key,
1450 path->slots[level] + 1);
1457 * look for inline back ref. if back ref is found, *ref_ret is set
1458 * to the address of inline back ref, and 0 is returned.
1460 * if back ref isn't found, *ref_ret is set to the address where it
1461 * should be inserted, and -ENOENT is returned.
1463 * if insert is true and there are too many inline back refs, the path
1464 * points to the extent item, and -EAGAIN is returned.
1466 * NOTE: inline back refs are ordered in the same way that back ref
1467 * items in the tree are ordered.
1469 static noinline_for_stack
1470 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1471 struct btrfs_root *root,
1472 struct btrfs_path *path,
1473 struct btrfs_extent_inline_ref **ref_ret,
1474 u64 bytenr, u64 num_bytes,
1475 u64 parent, u64 root_objectid,
1476 u64 owner, u64 offset, int insert)
1478 struct btrfs_key key;
1479 struct extent_buffer *leaf;
1480 struct btrfs_extent_item *ei;
1481 struct btrfs_extent_inline_ref *iref;
1491 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
1494 key.objectid = bytenr;
1495 key.type = BTRFS_EXTENT_ITEM_KEY;
1496 key.offset = num_bytes;
1498 want = extent_ref_type(parent, owner);
1500 extra_size = btrfs_extent_inline_ref_size(want);
1501 path->keep_locks = 1;
1506 * Owner is our parent level, so we can just add one to get the level
1507 * for the block we are interested in.
1509 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1510 key.type = BTRFS_METADATA_ITEM_KEY;
1515 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1522 * We may be a newly converted file system which still has the old fat
1523 * extent entries for metadata, so try and see if we have one of those.
1525 if (ret > 0 && skinny_metadata) {
1526 skinny_metadata = false;
1527 if (path->slots[0]) {
1529 btrfs_item_key_to_cpu(path->nodes[0], &key,
1531 if (key.objectid == bytenr &&
1532 key.type == BTRFS_EXTENT_ITEM_KEY &&
1533 key.offset == num_bytes)
1537 key.type = BTRFS_EXTENT_ITEM_KEY;
1538 key.offset = num_bytes;
1539 btrfs_release_path(path);
1544 if (ret && !insert) {
1553 leaf = path->nodes[0];
1554 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1555 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1556 if (item_size < sizeof(*ei)) {
1561 ret = convert_extent_item_v0(trans, root, path, owner,
1567 leaf = path->nodes[0];
1568 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1571 BUG_ON(item_size < sizeof(*ei));
1573 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1574 flags = btrfs_extent_flags(leaf, ei);
1576 ptr = (unsigned long)(ei + 1);
1577 end = (unsigned long)ei + item_size;
1579 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1580 ptr += sizeof(struct btrfs_tree_block_info);
1590 iref = (struct btrfs_extent_inline_ref *)ptr;
1591 type = btrfs_extent_inline_ref_type(leaf, iref);
1595 ptr += btrfs_extent_inline_ref_size(type);
1599 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1600 struct btrfs_extent_data_ref *dref;
1601 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1602 if (match_extent_data_ref(leaf, dref, root_objectid,
1607 if (hash_extent_data_ref_item(leaf, dref) <
1608 hash_extent_data_ref(root_objectid, owner, offset))
1612 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1614 if (parent == ref_offset) {
1618 if (ref_offset < parent)
1621 if (root_objectid == ref_offset) {
1625 if (ref_offset < root_objectid)
1629 ptr += btrfs_extent_inline_ref_size(type);
1631 if (err == -ENOENT && insert) {
1632 if (item_size + extra_size >=
1633 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1638 * To add new inline back ref, we have to make sure
1639 * there is no corresponding back ref item.
1640 * For simplicity, we just do not add new inline back
1641 * ref if there is any kind of item for this block
1643 if (find_next_key(path, 0, &key) == 0 &&
1644 key.objectid == bytenr &&
1645 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1650 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1653 path->keep_locks = 0;
1654 btrfs_unlock_up_safe(path, 1);
1660 * helper to add new inline back ref
1662 static noinline_for_stack
1663 void setup_inline_extent_backref(struct btrfs_root *root,
1664 struct btrfs_path *path,
1665 struct btrfs_extent_inline_ref *iref,
1666 u64 parent, u64 root_objectid,
1667 u64 owner, u64 offset, int refs_to_add,
1668 struct btrfs_delayed_extent_op *extent_op)
1670 struct extent_buffer *leaf;
1671 struct btrfs_extent_item *ei;
1674 unsigned long item_offset;
1679 leaf = path->nodes[0];
1680 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1681 item_offset = (unsigned long)iref - (unsigned long)ei;
1683 type = extent_ref_type(parent, owner);
1684 size = btrfs_extent_inline_ref_size(type);
1686 btrfs_extend_item(root, path, size);
1688 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1689 refs = btrfs_extent_refs(leaf, ei);
1690 refs += refs_to_add;
1691 btrfs_set_extent_refs(leaf, ei, refs);
1693 __run_delayed_extent_op(extent_op, leaf, ei);
1695 ptr = (unsigned long)ei + item_offset;
1696 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1697 if (ptr < end - size)
1698 memmove_extent_buffer(leaf, ptr + size, ptr,
1701 iref = (struct btrfs_extent_inline_ref *)ptr;
1702 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1703 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1704 struct btrfs_extent_data_ref *dref;
1705 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1706 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1707 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1708 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1709 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1710 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1711 struct btrfs_shared_data_ref *sref;
1712 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1713 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1714 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1715 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1716 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1718 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1720 btrfs_mark_buffer_dirty(leaf);
1723 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1724 struct btrfs_root *root,
1725 struct btrfs_path *path,
1726 struct btrfs_extent_inline_ref **ref_ret,
1727 u64 bytenr, u64 num_bytes, u64 parent,
1728 u64 root_objectid, u64 owner, u64 offset)
1732 ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1733 bytenr, num_bytes, parent,
1734 root_objectid, owner, offset, 0);
1738 btrfs_release_path(path);
1741 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1742 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1745 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1746 root_objectid, owner, offset);
1752 * helper to update/remove inline back ref
1754 static noinline_for_stack
1755 void update_inline_extent_backref(struct btrfs_root *root,
1756 struct btrfs_path *path,
1757 struct btrfs_extent_inline_ref *iref,
1759 struct btrfs_delayed_extent_op *extent_op)
1761 struct extent_buffer *leaf;
1762 struct btrfs_extent_item *ei;
1763 struct btrfs_extent_data_ref *dref = NULL;
1764 struct btrfs_shared_data_ref *sref = NULL;
1772 leaf = path->nodes[0];
1773 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1774 refs = btrfs_extent_refs(leaf, ei);
1775 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1776 refs += refs_to_mod;
1777 btrfs_set_extent_refs(leaf, ei, refs);
1779 __run_delayed_extent_op(extent_op, leaf, ei);
1781 type = btrfs_extent_inline_ref_type(leaf, iref);
1783 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1784 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1785 refs = btrfs_extent_data_ref_count(leaf, dref);
1786 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1787 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1788 refs = btrfs_shared_data_ref_count(leaf, sref);
1791 BUG_ON(refs_to_mod != -1);
1794 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1795 refs += refs_to_mod;
1798 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1799 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1801 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1803 size = btrfs_extent_inline_ref_size(type);
1804 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1805 ptr = (unsigned long)iref;
1806 end = (unsigned long)ei + item_size;
1807 if (ptr + size < end)
1808 memmove_extent_buffer(leaf, ptr, ptr + size,
1811 btrfs_truncate_item(root, path, item_size, 1);
1813 btrfs_mark_buffer_dirty(leaf);
1816 static noinline_for_stack
1817 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1818 struct btrfs_root *root,
1819 struct btrfs_path *path,
1820 u64 bytenr, u64 num_bytes, u64 parent,
1821 u64 root_objectid, u64 owner,
1822 u64 offset, int refs_to_add,
1823 struct btrfs_delayed_extent_op *extent_op)
1825 struct btrfs_extent_inline_ref *iref;
1828 ret = lookup_inline_extent_backref(trans, root, path, &iref,
1829 bytenr, num_bytes, parent,
1830 root_objectid, owner, offset, 1);
1832 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1833 update_inline_extent_backref(root, path, iref,
1834 refs_to_add, extent_op);
1835 } else if (ret == -ENOENT) {
1836 setup_inline_extent_backref(root, path, iref, parent,
1837 root_objectid, owner, offset,
1838 refs_to_add, extent_op);
1844 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1845 struct btrfs_root *root,
1846 struct btrfs_path *path,
1847 u64 bytenr, u64 parent, u64 root_objectid,
1848 u64 owner, u64 offset, int refs_to_add)
1851 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1852 BUG_ON(refs_to_add != 1);
1853 ret = insert_tree_block_ref(trans, root, path, bytenr,
1854 parent, root_objectid);
1856 ret = insert_extent_data_ref(trans, root, path, bytenr,
1857 parent, root_objectid,
1858 owner, offset, refs_to_add);
1863 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1864 struct btrfs_root *root,
1865 struct btrfs_path *path,
1866 struct btrfs_extent_inline_ref *iref,
1867 int refs_to_drop, int is_data)
1871 BUG_ON(!is_data && refs_to_drop != 1);
1873 update_inline_extent_backref(root, path, iref,
1874 -refs_to_drop, NULL);
1875 } else if (is_data) {
1876 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1878 ret = btrfs_del_item(trans, root, path);
1883 static int btrfs_issue_discard(struct block_device *bdev,
1886 return blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_NOFS, 0);
1889 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1890 u64 num_bytes, u64 *actual_bytes)
1893 u64 discarded_bytes = 0;
1894 struct btrfs_bio *bbio = NULL;
1897 /* Tell the block device(s) that the sectors can be discarded */
1898 ret = btrfs_map_block(root->fs_info, REQ_DISCARD,
1899 bytenr, &num_bytes, &bbio, 0);
1900 /* Error condition is -ENOMEM */
1902 struct btrfs_bio_stripe *stripe = bbio->stripes;
1906 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1907 if (!stripe->dev->can_discard)
1910 ret = btrfs_issue_discard(stripe->dev->bdev,
1914 discarded_bytes += stripe->length;
1915 else if (ret != -EOPNOTSUPP)
1916 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
1919 * Just in case we get back EOPNOTSUPP for some reason,
1920 * just ignore the return value so we don't screw up
1921 * people calling discard_extent.
1929 *actual_bytes = discarded_bytes;
1932 if (ret == -EOPNOTSUPP)
1937 /* Can return -ENOMEM */
1938 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1939 struct btrfs_root *root,
1940 u64 bytenr, u64 num_bytes, u64 parent,
1941 u64 root_objectid, u64 owner, u64 offset, int for_cow)
1944 struct btrfs_fs_info *fs_info = root->fs_info;
1946 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1947 root_objectid == BTRFS_TREE_LOG_OBJECTID);
1949 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1950 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
1952 parent, root_objectid, (int)owner,
1953 BTRFS_ADD_DELAYED_REF, NULL, for_cow);
1955 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
1957 parent, root_objectid, owner, offset,
1958 BTRFS_ADD_DELAYED_REF, NULL, for_cow);
1963 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1964 struct btrfs_root *root,
1965 u64 bytenr, u64 num_bytes,
1966 u64 parent, u64 root_objectid,
1967 u64 owner, u64 offset, int refs_to_add,
1968 struct btrfs_delayed_extent_op *extent_op)
1970 struct btrfs_path *path;
1971 struct extent_buffer *leaf;
1972 struct btrfs_extent_item *item;
1977 path = btrfs_alloc_path();
1982 path->leave_spinning = 1;
1983 /* this will setup the path even if it fails to insert the back ref */
1984 ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1985 path, bytenr, num_bytes, parent,
1986 root_objectid, owner, offset,
1987 refs_to_add, extent_op);
1991 if (ret != -EAGAIN) {
1996 leaf = path->nodes[0];
1997 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1998 refs = btrfs_extent_refs(leaf, item);
1999 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2001 __run_delayed_extent_op(extent_op, leaf, item);
2003 btrfs_mark_buffer_dirty(leaf);
2004 btrfs_release_path(path);
2007 path->leave_spinning = 1;
2009 /* now insert the actual backref */
2010 ret = insert_extent_backref(trans, root->fs_info->extent_root,
2011 path, bytenr, parent, root_objectid,
2012 owner, offset, refs_to_add);
2014 btrfs_abort_transaction(trans, root, ret);
2016 btrfs_free_path(path);
2020 static int run_delayed_data_ref(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,
2024 int insert_reserved)
2027 struct btrfs_delayed_data_ref *ref;
2028 struct btrfs_key ins;
2033 ins.objectid = node->bytenr;
2034 ins.offset = node->num_bytes;
2035 ins.type = BTRFS_EXTENT_ITEM_KEY;
2037 ref = btrfs_delayed_node_to_data_ref(node);
2038 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2039 parent = ref->parent;
2041 ref_root = ref->root;
2043 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2045 flags |= extent_op->flags_to_set;
2046 ret = alloc_reserved_file_extent(trans, root,
2047 parent, ref_root, flags,
2048 ref->objectid, ref->offset,
2049 &ins, node->ref_mod);
2050 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2051 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2052 node->num_bytes, parent,
2053 ref_root, ref->objectid,
2054 ref->offset, node->ref_mod,
2056 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2057 ret = __btrfs_free_extent(trans, root, node->bytenr,
2058 node->num_bytes, parent,
2059 ref_root, ref->objectid,
2060 ref->offset, node->ref_mod,
2068 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2069 struct extent_buffer *leaf,
2070 struct btrfs_extent_item *ei)
2072 u64 flags = btrfs_extent_flags(leaf, ei);
2073 if (extent_op->update_flags) {
2074 flags |= extent_op->flags_to_set;
2075 btrfs_set_extent_flags(leaf, ei, flags);
2078 if (extent_op->update_key) {
2079 struct btrfs_tree_block_info *bi;
2080 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2081 bi = (struct btrfs_tree_block_info *)(ei + 1);
2082 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2086 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2087 struct btrfs_root *root,
2088 struct btrfs_delayed_ref_node *node,
2089 struct btrfs_delayed_extent_op *extent_op)
2091 struct btrfs_key key;
2092 struct btrfs_path *path;
2093 struct btrfs_extent_item *ei;
2094 struct extent_buffer *leaf;
2098 int metadata = !extent_op->is_data;
2103 if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
2106 path = btrfs_alloc_path();
2110 key.objectid = node->bytenr;
2113 key.type = BTRFS_METADATA_ITEM_KEY;
2114 key.offset = extent_op->level;
2116 key.type = BTRFS_EXTENT_ITEM_KEY;
2117 key.offset = node->num_bytes;
2122 path->leave_spinning = 1;
2123 ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
2131 btrfs_release_path(path);
2134 key.offset = node->num_bytes;
2135 key.type = BTRFS_EXTENT_ITEM_KEY;
2142 leaf = path->nodes[0];
2143 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2144 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2145 if (item_size < sizeof(*ei)) {
2146 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
2152 leaf = path->nodes[0];
2153 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2156 BUG_ON(item_size < sizeof(*ei));
2157 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2158 __run_delayed_extent_op(extent_op, leaf, ei);
2160 btrfs_mark_buffer_dirty(leaf);
2162 btrfs_free_path(path);
2166 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2167 struct btrfs_root *root,
2168 struct btrfs_delayed_ref_node *node,
2169 struct btrfs_delayed_extent_op *extent_op,
2170 int insert_reserved)
2173 struct btrfs_delayed_tree_ref *ref;
2174 struct btrfs_key ins;
2177 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
2180 ref = btrfs_delayed_node_to_tree_ref(node);
2181 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2182 parent = ref->parent;
2184 ref_root = ref->root;
2186 ins.objectid = node->bytenr;
2187 if (skinny_metadata) {
2188 ins.offset = ref->level;
2189 ins.type = BTRFS_METADATA_ITEM_KEY;
2191 ins.offset = node->num_bytes;
2192 ins.type = BTRFS_EXTENT_ITEM_KEY;
2195 BUG_ON(node->ref_mod != 1);
2196 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2197 BUG_ON(!extent_op || !extent_op->update_flags);
2198 ret = alloc_reserved_tree_block(trans, root,
2200 extent_op->flags_to_set,
2203 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2204 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2205 node->num_bytes, parent, ref_root,
2206 ref->level, 0, 1, extent_op);
2207 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2208 ret = __btrfs_free_extent(trans, root, node->bytenr,
2209 node->num_bytes, parent, ref_root,
2210 ref->level, 0, 1, extent_op);
2217 /* helper function to actually process a single delayed ref entry */
2218 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2219 struct btrfs_root *root,
2220 struct btrfs_delayed_ref_node *node,
2221 struct btrfs_delayed_extent_op *extent_op,
2222 int insert_reserved)
2229 if (btrfs_delayed_ref_is_head(node)) {
2230 struct btrfs_delayed_ref_head *head;
2232 * we've hit the end of the chain and we were supposed
2233 * to insert this extent into the tree. But, it got
2234 * deleted before we ever needed to insert it, so all
2235 * we have to do is clean up the accounting
2238 head = btrfs_delayed_node_to_head(node);
2239 if (insert_reserved) {
2240 btrfs_pin_extent(root, node->bytenr,
2241 node->num_bytes, 1);
2242 if (head->is_data) {
2243 ret = btrfs_del_csums(trans, root,
2251 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2252 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2253 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2255 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2256 node->type == BTRFS_SHARED_DATA_REF_KEY)
2257 ret = run_delayed_data_ref(trans, root, node, extent_op,
2264 static noinline struct btrfs_delayed_ref_node *
2265 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2267 struct rb_node *node;
2268 struct btrfs_delayed_ref_node *ref;
2269 int action = BTRFS_ADD_DELAYED_REF;
2272 * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2273 * this prevents ref count from going down to zero when
2274 * there still are pending delayed ref.
2276 node = rb_prev(&head->node.rb_node);
2280 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2282 if (ref->bytenr != head->node.bytenr)
2284 if (ref->action == action)
2286 node = rb_prev(node);
2288 if (action == BTRFS_ADD_DELAYED_REF) {
2289 action = BTRFS_DROP_DELAYED_REF;
2296 * Returns 0 on success or if called with an already aborted transaction.
2297 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2299 static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
2300 struct btrfs_root *root,
2301 struct list_head *cluster)
2303 struct btrfs_delayed_ref_root *delayed_refs;
2304 struct btrfs_delayed_ref_node *ref;
2305 struct btrfs_delayed_ref_head *locked_ref = NULL;
2306 struct btrfs_delayed_extent_op *extent_op;
2307 struct btrfs_fs_info *fs_info = root->fs_info;
2310 int must_insert_reserved = 0;
2312 delayed_refs = &trans->transaction->delayed_refs;
2315 /* pick a new head ref from the cluster list */
2316 if (list_empty(cluster))
2319 locked_ref = list_entry(cluster->next,
2320 struct btrfs_delayed_ref_head, cluster);
2322 /* grab the lock that says we are going to process
2323 * all the refs for this head */
2324 ret = btrfs_delayed_ref_lock(trans, locked_ref);
2327 * we may have dropped the spin lock to get the head
2328 * mutex lock, and that might have given someone else
2329 * time to free the head. If that's true, it has been
2330 * removed from our list and we can move on.
2332 if (ret == -EAGAIN) {
2340 * We need to try and merge add/drops of the same ref since we
2341 * can run into issues with relocate dropping the implicit ref
2342 * and then it being added back again before the drop can
2343 * finish. If we merged anything we need to re-loop so we can
2346 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2350 * locked_ref is the head node, so we have to go one
2351 * node back for any delayed ref updates
2353 ref = select_delayed_ref(locked_ref);
2355 if (ref && ref->seq &&
2356 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
2358 * there are still refs with lower seq numbers in the
2359 * process of being added. Don't run this ref yet.
2361 list_del_init(&locked_ref->cluster);
2362 btrfs_delayed_ref_unlock(locked_ref);
2364 delayed_refs->num_heads_ready++;
2365 spin_unlock(&delayed_refs->lock);
2367 spin_lock(&delayed_refs->lock);
2372 * record the must insert reserved flag before we
2373 * drop the spin lock.
2375 must_insert_reserved = locked_ref->must_insert_reserved;
2376 locked_ref->must_insert_reserved = 0;
2378 extent_op = locked_ref->extent_op;
2379 locked_ref->extent_op = NULL;
2382 /* All delayed refs have been processed, Go ahead
2383 * and send the head node to run_one_delayed_ref,
2384 * so that any accounting fixes can happen
2386 ref = &locked_ref->node;
2388 if (extent_op && must_insert_reserved) {
2389 btrfs_free_delayed_extent_op(extent_op);
2394 spin_unlock(&delayed_refs->lock);
2396 ret = run_delayed_extent_op(trans, root,
2398 btrfs_free_delayed_extent_op(extent_op);
2401 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2402 spin_lock(&delayed_refs->lock);
2403 btrfs_delayed_ref_unlock(locked_ref);
2412 rb_erase(&ref->rb_node, &delayed_refs->root);
2413 delayed_refs->num_entries--;
2414 if (!btrfs_delayed_ref_is_head(ref)) {
2416 * when we play the delayed ref, also correct the
2419 switch (ref->action) {
2420 case BTRFS_ADD_DELAYED_REF:
2421 case BTRFS_ADD_DELAYED_EXTENT:
2422 locked_ref->node.ref_mod -= ref->ref_mod;
2424 case BTRFS_DROP_DELAYED_REF:
2425 locked_ref->node.ref_mod += ref->ref_mod;
2431 spin_unlock(&delayed_refs->lock);
2433 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2434 must_insert_reserved);
2436 btrfs_free_delayed_extent_op(extent_op);
2438 btrfs_delayed_ref_unlock(locked_ref);
2439 btrfs_put_delayed_ref(ref);
2440 btrfs_debug(fs_info, "run_one_delayed_ref returned %d", ret);
2441 spin_lock(&delayed_refs->lock);
2446 * If this node is a head, that means all the refs in this head
2447 * have been dealt with, and we will pick the next head to deal
2448 * with, so we must unlock the head and drop it from the cluster
2449 * list before we release it.
2451 if (btrfs_delayed_ref_is_head(ref)) {
2452 list_del_init(&locked_ref->cluster);
2453 btrfs_delayed_ref_unlock(locked_ref);
2456 btrfs_put_delayed_ref(ref);
2460 spin_lock(&delayed_refs->lock);
2465 #ifdef SCRAMBLE_DELAYED_REFS
2467 * Normally delayed refs get processed in ascending bytenr order. This
2468 * correlates in most cases to the order added. To expose dependencies on this
2469 * order, we start to process the tree in the middle instead of the beginning
2471 static u64 find_middle(struct rb_root *root)
2473 struct rb_node *n = root->rb_node;
2474 struct btrfs_delayed_ref_node *entry;
2477 u64 first = 0, last = 0;
2481 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2482 first = entry->bytenr;
2486 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2487 last = entry->bytenr;
2492 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2493 WARN_ON(!entry->in_tree);
2495 middle = entry->bytenr;
2508 int btrfs_delayed_refs_qgroup_accounting(struct btrfs_trans_handle *trans,
2509 struct btrfs_fs_info *fs_info)
2511 struct qgroup_update *qgroup_update;
2514 if (list_empty(&trans->qgroup_ref_list) !=
2515 !trans->delayed_ref_elem.seq) {
2516 /* list without seq or seq without list */
2518 "qgroup accounting update error, list is%s empty, seq is %#x.%x",
2519 list_empty(&trans->qgroup_ref_list) ? "" : " not",
2520 (u32)(trans->delayed_ref_elem.seq >> 32),
2521 (u32)trans->delayed_ref_elem.seq);
2525 if (!trans->delayed_ref_elem.seq)
2528 while (!list_empty(&trans->qgroup_ref_list)) {
2529 qgroup_update = list_first_entry(&trans->qgroup_ref_list,
2530 struct qgroup_update, list);
2531 list_del(&qgroup_update->list);
2533 ret = btrfs_qgroup_account_ref(
2534 trans, fs_info, qgroup_update->node,
2535 qgroup_update->extent_op);
2536 kfree(qgroup_update);
2539 btrfs_put_tree_mod_seq(fs_info, &trans->delayed_ref_elem);
2544 static int refs_newer(struct btrfs_delayed_ref_root *delayed_refs, int seq,
2547 int val = atomic_read(&delayed_refs->ref_seq);
2549 if (val < seq || val >= seq + count)
2554 static inline u64 heads_to_leaves(struct btrfs_root *root, u64 heads)
2558 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2559 sizeof(struct btrfs_extent_inline_ref));
2560 if (!btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
2561 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2564 * We don't ever fill up leaves all the way so multiply by 2 just to be
2565 * closer to what we're really going to want to ouse.
2567 return div64_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(root));
2570 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2571 struct btrfs_root *root)
2573 struct btrfs_block_rsv *global_rsv;
2574 u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2578 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
2579 num_heads = heads_to_leaves(root, num_heads);
2581 num_bytes += (num_heads - 1) * root->leafsize;
2583 global_rsv = &root->fs_info->global_block_rsv;
2586 * If we can't allocate any more chunks lets make sure we have _lots_ of
2587 * wiggle room since running delayed refs can create more delayed refs.
2589 if (global_rsv->space_info->full)
2592 spin_lock(&global_rsv->lock);
2593 if (global_rsv->reserved <= num_bytes)
2595 spin_unlock(&global_rsv->lock);
2600 * this starts processing the delayed reference count updates and
2601 * extent insertions we have queued up so far. count can be
2602 * 0, which means to process everything in the tree at the start
2603 * of the run (but not newly added entries), or it can be some target
2604 * number you'd like to process.
2606 * Returns 0 on success or if called with an aborted transaction
2607 * Returns <0 on error and aborts the transaction
2609 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2610 struct btrfs_root *root, unsigned long count)
2612 struct rb_node *node;
2613 struct btrfs_delayed_ref_root *delayed_refs;
2614 struct btrfs_delayed_ref_node *ref;
2615 struct list_head cluster;
2618 int run_all = count == (unsigned long)-1;
2622 /* We'll clean this up in btrfs_cleanup_transaction */
2626 if (root == root->fs_info->extent_root)
2627 root = root->fs_info->tree_root;
2629 btrfs_delayed_refs_qgroup_accounting(trans, root->fs_info);
2631 delayed_refs = &trans->transaction->delayed_refs;
2632 INIT_LIST_HEAD(&cluster);
2634 count = delayed_refs->num_entries * 2;
2638 if (!run_all && !run_most) {
2640 int seq = atomic_read(&delayed_refs->ref_seq);
2643 old = atomic_cmpxchg(&delayed_refs->procs_running_refs, 0, 1);
2645 DEFINE_WAIT(__wait);
2646 if (delayed_refs->flushing ||
2647 !btrfs_should_throttle_delayed_refs(trans, root))
2650 prepare_to_wait(&delayed_refs->wait, &__wait,
2651 TASK_UNINTERRUPTIBLE);
2653 old = atomic_cmpxchg(&delayed_refs->procs_running_refs, 0, 1);
2656 finish_wait(&delayed_refs->wait, &__wait);
2658 if (!refs_newer(delayed_refs, seq, 256))
2663 finish_wait(&delayed_refs->wait, &__wait);
2669 atomic_inc(&delayed_refs->procs_running_refs);
2674 spin_lock(&delayed_refs->lock);
2676 #ifdef SCRAMBLE_DELAYED_REFS
2677 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2681 if (!(run_all || run_most) &&
2682 !btrfs_should_throttle_delayed_refs(trans, root))
2686 * go find something we can process in the rbtree. We start at
2687 * the beginning of the tree, and then build a cluster
2688 * of refs to process starting at the first one we are able to
2691 delayed_start = delayed_refs->run_delayed_start;
2692 ret = btrfs_find_ref_cluster(trans, &cluster,
2693 delayed_refs->run_delayed_start);
2697 ret = run_clustered_refs(trans, root, &cluster);
2699 btrfs_release_ref_cluster(&cluster);
2700 spin_unlock(&delayed_refs->lock);
2701 btrfs_abort_transaction(trans, root, ret);
2702 atomic_dec(&delayed_refs->procs_running_refs);
2703 wake_up(&delayed_refs->wait);
2707 atomic_add(ret, &delayed_refs->ref_seq);
2709 count -= min_t(unsigned long, ret, count);
2714 if (delayed_start >= delayed_refs->run_delayed_start) {
2717 * btrfs_find_ref_cluster looped. let's do one
2718 * more cycle. if we don't run any delayed ref
2719 * during that cycle (because we can't because
2720 * all of them are blocked), bail out.
2725 * no runnable refs left, stop trying
2732 /* refs were run, let's reset staleness detection */
2738 if (!list_empty(&trans->new_bgs)) {
2739 spin_unlock(&delayed_refs->lock);
2740 btrfs_create_pending_block_groups(trans, root);
2741 spin_lock(&delayed_refs->lock);
2744 node = rb_first(&delayed_refs->root);
2747 count = (unsigned long)-1;
2750 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2752 if (btrfs_delayed_ref_is_head(ref)) {
2753 struct btrfs_delayed_ref_head *head;
2755 head = btrfs_delayed_node_to_head(ref);
2756 atomic_inc(&ref->refs);
2758 spin_unlock(&delayed_refs->lock);
2760 * Mutex was contended, block until it's
2761 * released and try again
2763 mutex_lock(&head->mutex);
2764 mutex_unlock(&head->mutex);
2766 btrfs_put_delayed_ref(ref);
2770 node = rb_next(node);
2772 spin_unlock(&delayed_refs->lock);
2773 schedule_timeout(1);
2777 atomic_dec(&delayed_refs->procs_running_refs);
2779 if (waitqueue_active(&delayed_refs->wait))
2780 wake_up(&delayed_refs->wait);
2782 spin_unlock(&delayed_refs->lock);
2783 assert_qgroups_uptodate(trans);
2787 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2788 struct btrfs_root *root,
2789 u64 bytenr, u64 num_bytes, u64 flags,
2790 int level, int is_data)
2792 struct btrfs_delayed_extent_op *extent_op;
2795 extent_op = btrfs_alloc_delayed_extent_op();
2799 extent_op->flags_to_set = flags;
2800 extent_op->update_flags = 1;
2801 extent_op->update_key = 0;
2802 extent_op->is_data = is_data ? 1 : 0;
2803 extent_op->level = level;
2805 ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
2806 num_bytes, extent_op);
2808 btrfs_free_delayed_extent_op(extent_op);
2812 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2813 struct btrfs_root *root,
2814 struct btrfs_path *path,
2815 u64 objectid, u64 offset, u64 bytenr)
2817 struct btrfs_delayed_ref_head *head;
2818 struct btrfs_delayed_ref_node *ref;
2819 struct btrfs_delayed_data_ref *data_ref;
2820 struct btrfs_delayed_ref_root *delayed_refs;
2821 struct rb_node *node;
2825 delayed_refs = &trans->transaction->delayed_refs;
2826 spin_lock(&delayed_refs->lock);
2827 head = btrfs_find_delayed_ref_head(trans, bytenr);
2831 if (!mutex_trylock(&head->mutex)) {
2832 atomic_inc(&head->node.refs);
2833 spin_unlock(&delayed_refs->lock);
2835 btrfs_release_path(path);
2838 * Mutex was contended, block until it's released and let
2841 mutex_lock(&head->mutex);
2842 mutex_unlock(&head->mutex);
2843 btrfs_put_delayed_ref(&head->node);
2847 node = rb_prev(&head->node.rb_node);
2851 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2853 if (ref->bytenr != bytenr)
2857 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2860 data_ref = btrfs_delayed_node_to_data_ref(ref);
2862 node = rb_prev(node);
2866 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2867 if (ref->bytenr == bytenr && ref->seq == seq)
2871 if (data_ref->root != root->root_key.objectid ||
2872 data_ref->objectid != objectid || data_ref->offset != offset)
2877 mutex_unlock(&head->mutex);
2879 spin_unlock(&delayed_refs->lock);
2883 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2884 struct btrfs_root *root,
2885 struct btrfs_path *path,
2886 u64 objectid, u64 offset, u64 bytenr)
2888 struct btrfs_root *extent_root = root->fs_info->extent_root;
2889 struct extent_buffer *leaf;
2890 struct btrfs_extent_data_ref *ref;
2891 struct btrfs_extent_inline_ref *iref;
2892 struct btrfs_extent_item *ei;
2893 struct btrfs_key key;
2897 key.objectid = bytenr;
2898 key.offset = (u64)-1;
2899 key.type = BTRFS_EXTENT_ITEM_KEY;
2901 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2904 BUG_ON(ret == 0); /* Corruption */
2907 if (path->slots[0] == 0)
2911 leaf = path->nodes[0];
2912 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2914 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2918 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2919 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2920 if (item_size < sizeof(*ei)) {
2921 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2925 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2927 if (item_size != sizeof(*ei) +
2928 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2931 if (btrfs_extent_generation(leaf, ei) <=
2932 btrfs_root_last_snapshot(&root->root_item))
2935 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2936 if (btrfs_extent_inline_ref_type(leaf, iref) !=
2937 BTRFS_EXTENT_DATA_REF_KEY)
2940 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2941 if (btrfs_extent_refs(leaf, ei) !=
2942 btrfs_extent_data_ref_count(leaf, ref) ||
2943 btrfs_extent_data_ref_root(leaf, ref) !=
2944 root->root_key.objectid ||
2945 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2946 btrfs_extent_data_ref_offset(leaf, ref) != offset)
2954 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2955 struct btrfs_root *root,
2956 u64 objectid, u64 offset, u64 bytenr)
2958 struct btrfs_path *path;
2962 path = btrfs_alloc_path();
2967 ret = check_committed_ref(trans, root, path, objectid,
2969 if (ret && ret != -ENOENT)
2972 ret2 = check_delayed_ref(trans, root, path, objectid,
2974 } while (ret2 == -EAGAIN);
2976 if (ret2 && ret2 != -ENOENT) {
2981 if (ret != -ENOENT || ret2 != -ENOENT)
2984 btrfs_free_path(path);
2985 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2990 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2991 struct btrfs_root *root,
2992 struct extent_buffer *buf,
2993 int full_backref, int inc, int for_cow)
3000 struct btrfs_key key;
3001 struct btrfs_file_extent_item *fi;
3005 int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
3006 u64, u64, u64, u64, u64, u64, int);
3008 ref_root = btrfs_header_owner(buf);
3009 nritems = btrfs_header_nritems(buf);
3010 level = btrfs_header_level(buf);
3012 if (!root->ref_cows && level == 0)
3016 process_func = btrfs_inc_extent_ref;
3018 process_func = btrfs_free_extent;
3021 parent = buf->start;
3025 for (i = 0; i < nritems; i++) {
3027 btrfs_item_key_to_cpu(buf, &key, i);
3028 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3030 fi = btrfs_item_ptr(buf, i,
3031 struct btrfs_file_extent_item);
3032 if (btrfs_file_extent_type(buf, fi) ==
3033 BTRFS_FILE_EXTENT_INLINE)
3035 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3039 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3040 key.offset -= btrfs_file_extent_offset(buf, fi);
3041 ret = process_func(trans, root, bytenr, num_bytes,
3042 parent, ref_root, key.objectid,
3043 key.offset, for_cow);
3047 bytenr = btrfs_node_blockptr(buf, i);
3048 num_bytes = btrfs_level_size(root, level - 1);
3049 ret = process_func(trans, root, bytenr, num_bytes,
3050 parent, ref_root, level - 1, 0,
3061 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3062 struct extent_buffer *buf, int full_backref, int for_cow)
3064 return __btrfs_mod_ref(trans, root, buf, full_backref, 1, for_cow);
3067 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3068 struct extent_buffer *buf, int full_backref, int for_cow)
3070 return __btrfs_mod_ref(trans, root, buf, full_backref, 0, for_cow);
3073 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3074 struct btrfs_root *root,
3075 struct btrfs_path *path,
3076 struct btrfs_block_group_cache *cache)
3079 struct btrfs_root *extent_root = root->fs_info->extent_root;
3081 struct extent_buffer *leaf;
3083 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3086 BUG_ON(ret); /* Corruption */
3088 leaf = path->nodes[0];
3089 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3090 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3091 btrfs_mark_buffer_dirty(leaf);
3092 btrfs_release_path(path);
3095 btrfs_abort_transaction(trans, root, ret);
3102 static struct btrfs_block_group_cache *
3103 next_block_group(struct btrfs_root *root,
3104 struct btrfs_block_group_cache *cache)
3106 struct rb_node *node;
3107 spin_lock(&root->fs_info->block_group_cache_lock);
3108 node = rb_next(&cache->cache_node);
3109 btrfs_put_block_group(cache);
3111 cache = rb_entry(node, struct btrfs_block_group_cache,
3113 btrfs_get_block_group(cache);
3116 spin_unlock(&root->fs_info->block_group_cache_lock);
3120 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3121 struct btrfs_trans_handle *trans,
3122 struct btrfs_path *path)
3124 struct btrfs_root *root = block_group->fs_info->tree_root;
3125 struct inode *inode = NULL;
3127 int dcs = BTRFS_DC_ERROR;
3133 * If this block group is smaller than 100 megs don't bother caching the
3136 if (block_group->key.offset < (100 * 1024 * 1024)) {
3137 spin_lock(&block_group->lock);
3138 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3139 spin_unlock(&block_group->lock);
3144 inode = lookup_free_space_inode(root, block_group, path);
3145 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3146 ret = PTR_ERR(inode);
3147 btrfs_release_path(path);
3151 if (IS_ERR(inode)) {
3155 if (block_group->ro)
3158 ret = create_free_space_inode(root, trans, block_group, path);
3164 /* We've already setup this transaction, go ahead and exit */
3165 if (block_group->cache_generation == trans->transid &&
3166 i_size_read(inode)) {
3167 dcs = BTRFS_DC_SETUP;
3172 * We want to set the generation to 0, that way if anything goes wrong
3173 * from here on out we know not to trust this cache when we load up next
3176 BTRFS_I(inode)->generation = 0;
3177 ret = btrfs_update_inode(trans, root, inode);
3180 if (i_size_read(inode) > 0) {
3181 ret = btrfs_check_trunc_cache_free_space(root,
3182 &root->fs_info->global_block_rsv);
3186 ret = btrfs_truncate_free_space_cache(root, trans, path,
3192 spin_lock(&block_group->lock);
3193 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3194 !btrfs_test_opt(root, SPACE_CACHE)) {
3196 * don't bother trying to write stuff out _if_
3197 * a) we're not cached,
3198 * b) we're with nospace_cache mount option.
3200 dcs = BTRFS_DC_WRITTEN;
3201 spin_unlock(&block_group->lock);
3204 spin_unlock(&block_group->lock);
3207 * Try to preallocate enough space based on how big the block group is.
3208 * Keep in mind this has to include any pinned space which could end up
3209 * taking up quite a bit since it's not folded into the other space
3212 num_pages = (int)div64_u64(block_group->key.offset, 256 * 1024 * 1024);
3217 num_pages *= PAGE_CACHE_SIZE;
3219 ret = btrfs_check_data_free_space(inode, num_pages);
3223 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3224 num_pages, num_pages,
3227 dcs = BTRFS_DC_SETUP;
3228 btrfs_free_reserved_data_space(inode, num_pages);
3233 btrfs_release_path(path);
3235 spin_lock(&block_group->lock);
3236 if (!ret && dcs == BTRFS_DC_SETUP)
3237 block_group->cache_generation = trans->transid;
3238 block_group->disk_cache_state = dcs;
3239 spin_unlock(&block_group->lock);
3244 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3245 struct btrfs_root *root)
3247 struct btrfs_block_group_cache *cache;
3249 struct btrfs_path *path;
3252 path = btrfs_alloc_path();
3258 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3260 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3262 cache = next_block_group(root, cache);
3270 err = cache_save_setup(cache, trans, path);
3271 last = cache->key.objectid + cache->key.offset;
3272 btrfs_put_block_group(cache);
3277 err = btrfs_run_delayed_refs(trans, root,
3279 if (err) /* File system offline */
3283 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3285 if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
3286 btrfs_put_block_group(cache);
3292 cache = next_block_group(root, cache);
3301 if (cache->disk_cache_state == BTRFS_DC_SETUP)
3302 cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
3304 last = cache->key.objectid + cache->key.offset;
3306 err = write_one_cache_group(trans, root, path, cache);
3307 if (err) /* File system offline */
3310 btrfs_put_block_group(cache);
3315 * I don't think this is needed since we're just marking our
3316 * preallocated extent as written, but just in case it can't
3320 err = btrfs_run_delayed_refs(trans, root,
3322 if (err) /* File system offline */
3326 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3329 * Really this shouldn't happen, but it could if we
3330 * couldn't write the entire preallocated extent and
3331 * splitting the extent resulted in a new block.
3334 btrfs_put_block_group(cache);
3337 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3339 cache = next_block_group(root, cache);
3348 err = btrfs_write_out_cache(root, trans, cache, path);
3351 * If we didn't have an error then the cache state is still
3352 * NEED_WRITE, so we can set it to WRITTEN.
3354 if (!err && cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3355 cache->disk_cache_state = BTRFS_DC_WRITTEN;
3356 last = cache->key.objectid + cache->key.offset;
3357 btrfs_put_block_group(cache);
3361 btrfs_free_path(path);
3365 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3367 struct btrfs_block_group_cache *block_group;
3370 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
3371 if (!block_group || block_group->ro)
3374 btrfs_put_block_group(block_group);
3378 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3379 u64 total_bytes, u64 bytes_used,
3380 struct btrfs_space_info **space_info)
3382 struct btrfs_space_info *found;
3387 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3388 BTRFS_BLOCK_GROUP_RAID10))
3393 found = __find_space_info(info, flags);
3395 spin_lock(&found->lock);
3396 found->total_bytes += total_bytes;
3397 found->disk_total += total_bytes * factor;
3398 found->bytes_used += bytes_used;
3399 found->disk_used += bytes_used * factor;
3401 spin_unlock(&found->lock);
3402 *space_info = found;
3405 found = kzalloc(sizeof(*found), GFP_NOFS);
3409 ret = percpu_counter_init(&found->total_bytes_pinned, 0);
3415 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3416 INIT_LIST_HEAD(&found->block_groups[i]);
3417 init_rwsem(&found->groups_sem);
3418 spin_lock_init(&found->lock);
3419 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3420 found->total_bytes = total_bytes;
3421 found->disk_total = total_bytes * factor;
3422 found->bytes_used = bytes_used;
3423 found->disk_used = bytes_used * factor;
3424 found->bytes_pinned = 0;
3425 found->bytes_reserved = 0;
3426 found->bytes_readonly = 0;
3427 found->bytes_may_use = 0;
3429 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3430 found->chunk_alloc = 0;
3432 init_waitqueue_head(&found->wait);
3433 *space_info = found;
3434 list_add_rcu(&found->list, &info->space_info);
3435 if (flags & BTRFS_BLOCK_GROUP_DATA)
3436 info->data_sinfo = found;
3440 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3442 u64 extra_flags = chunk_to_extended(flags) &
3443 BTRFS_EXTENDED_PROFILE_MASK;
3445 write_seqlock(&fs_info->profiles_lock);
3446 if (flags & BTRFS_BLOCK_GROUP_DATA)
3447 fs_info->avail_data_alloc_bits |= extra_flags;
3448 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3449 fs_info->avail_metadata_alloc_bits |= extra_flags;
3450 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3451 fs_info->avail_system_alloc_bits |= extra_flags;
3452 write_sequnlock(&fs_info->profiles_lock);
3456 * returns target flags in extended format or 0 if restripe for this
3457 * chunk_type is not in progress
3459 * should be called with either volume_mutex or balance_lock held
3461 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3463 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3469 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3470 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3471 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3472 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3473 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3474 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3475 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3476 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3477 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3484 * @flags: available profiles in extended format (see ctree.h)
3486 * Returns reduced profile in chunk format. If profile changing is in
3487 * progress (either running or paused) picks the target profile (if it's
3488 * already available), otherwise falls back to plain reducing.
3490 static u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
3493 * we add in the count of missing devices because we want
3494 * to make sure that any RAID levels on a degraded FS
3495 * continue to be honored.
3497 u64 num_devices = root->fs_info->fs_devices->rw_devices +
3498 root->fs_info->fs_devices->missing_devices;
3503 * see if restripe for this chunk_type is in progress, if so
3504 * try to reduce to the target profile
3506 spin_lock(&root->fs_info->balance_lock);
3507 target = get_restripe_target(root->fs_info, flags);
3509 /* pick target profile only if it's already available */
3510 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3511 spin_unlock(&root->fs_info->balance_lock);
3512 return extended_to_chunk(target);
3515 spin_unlock(&root->fs_info->balance_lock);
3517 /* First, mask out the RAID levels which aren't possible */
3518 if (num_devices == 1)
3519 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0 |
3520 BTRFS_BLOCK_GROUP_RAID5);
3521 if (num_devices < 3)
3522 flags &= ~BTRFS_BLOCK_GROUP_RAID6;
3523 if (num_devices < 4)
3524 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3526 tmp = flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3527 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID5 |
3528 BTRFS_BLOCK_GROUP_RAID6 | BTRFS_BLOCK_GROUP_RAID10);
3531 if (tmp & BTRFS_BLOCK_GROUP_RAID6)
3532 tmp = BTRFS_BLOCK_GROUP_RAID6;
3533 else if (tmp & BTRFS_BLOCK_GROUP_RAID5)
3534 tmp = BTRFS_BLOCK_GROUP_RAID5;
3535 else if (tmp & BTRFS_BLOCK_GROUP_RAID10)
3536 tmp = BTRFS_BLOCK_GROUP_RAID10;
3537 else if (tmp & BTRFS_BLOCK_GROUP_RAID1)
3538 tmp = BTRFS_BLOCK_GROUP_RAID1;
3539 else if (tmp & BTRFS_BLOCK_GROUP_RAID0)
3540 tmp = BTRFS_BLOCK_GROUP_RAID0;
3542 return extended_to_chunk(flags | tmp);
3545 static u64 get_alloc_profile(struct btrfs_root *root, u64 flags)
3550 seq = read_seqbegin(&root->fs_info->profiles_lock);
3552 if (flags & BTRFS_BLOCK_GROUP_DATA)
3553 flags |= root->fs_info->avail_data_alloc_bits;
3554 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3555 flags |= root->fs_info->avail_system_alloc_bits;
3556 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3557 flags |= root->fs_info->avail_metadata_alloc_bits;
3558 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
3560 return btrfs_reduce_alloc_profile(root, flags);
3563 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3569 flags = BTRFS_BLOCK_GROUP_DATA;
3570 else if (root == root->fs_info->chunk_root)
3571 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3573 flags = BTRFS_BLOCK_GROUP_METADATA;
3575 ret = get_alloc_profile(root, flags);
3580 * This will check the space that the inode allocates from to make sure we have
3581 * enough space for bytes.
3583 int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
3585 struct btrfs_space_info *data_sinfo;
3586 struct btrfs_root *root = BTRFS_I(inode)->root;
3587 struct btrfs_fs_info *fs_info = root->fs_info;
3589 int ret = 0, committed = 0, alloc_chunk = 1;
3591 /* make sure bytes are sectorsize aligned */
3592 bytes = ALIGN(bytes, root->sectorsize);
3594 if (root == root->fs_info->tree_root ||
3595 BTRFS_I(inode)->location.objectid == BTRFS_FREE_INO_OBJECTID) {
3600 data_sinfo = fs_info->data_sinfo;
3605 /* make sure we have enough space to handle the data first */
3606 spin_lock(&data_sinfo->lock);
3607 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3608 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3609 data_sinfo->bytes_may_use;
3611 if (used + bytes > data_sinfo->total_bytes) {
3612 struct btrfs_trans_handle *trans;
3615 * if we don't have enough free bytes in this space then we need
3616 * to alloc a new chunk.
3618 if (!data_sinfo->full && alloc_chunk) {
3621 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
3622 spin_unlock(&data_sinfo->lock);
3624 alloc_target = btrfs_get_alloc_profile(root, 1);
3625 trans = btrfs_join_transaction(root);
3627 return PTR_ERR(trans);
3629 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3631 CHUNK_ALLOC_NO_FORCE);
3632 btrfs_end_transaction(trans, root);
3641 data_sinfo = fs_info->data_sinfo;
3647 * If we don't have enough pinned space to deal with this
3648 * allocation don't bother committing the transaction.
3650 if (percpu_counter_compare(&data_sinfo->total_bytes_pinned,
3653 spin_unlock(&data_sinfo->lock);
3655 /* commit the current transaction and try again */
3658 !atomic_read(&root->fs_info->open_ioctl_trans)) {
3661 trans = btrfs_join_transaction(root);
3663 return PTR_ERR(trans);
3664 ret = btrfs_commit_transaction(trans, root);
3672 data_sinfo->bytes_may_use += bytes;
3673 trace_btrfs_space_reservation(root->fs_info, "space_info",
3674 data_sinfo->flags, bytes, 1);
3675 spin_unlock(&data_sinfo->lock);
3681 * Called if we need to clear a data reservation for this inode.
3683 void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
3685 struct btrfs_root *root = BTRFS_I(inode)->root;
3686 struct btrfs_space_info *data_sinfo;
3688 /* make sure bytes are sectorsize aligned */
3689 bytes = ALIGN(bytes, root->sectorsize);
3691 data_sinfo = root->fs_info->data_sinfo;
3692 spin_lock(&data_sinfo->lock);
3693 WARN_ON(data_sinfo->bytes_may_use < bytes);
3694 data_sinfo->bytes_may_use -= bytes;
3695 trace_btrfs_space_reservation(root->fs_info, "space_info",
3696 data_sinfo->flags, bytes, 0);
3697 spin_unlock(&data_sinfo->lock);
3700 static void force_metadata_allocation(struct btrfs_fs_info *info)
3702 struct list_head *head = &info->space_info;
3703 struct btrfs_space_info *found;
3706 list_for_each_entry_rcu(found, head, list) {
3707 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3708 found->force_alloc = CHUNK_ALLOC_FORCE;
3713 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
3715 return (global->size << 1);
3718 static int should_alloc_chunk(struct btrfs_root *root,
3719 struct btrfs_space_info *sinfo, int force)
3721 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3722 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
3723 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
3726 if (force == CHUNK_ALLOC_FORCE)
3730 * We need to take into account the global rsv because for all intents
3731 * and purposes it's used space. Don't worry about locking the
3732 * global_rsv, it doesn't change except when the transaction commits.
3734 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
3735 num_allocated += calc_global_rsv_need_space(global_rsv);
3738 * in limited mode, we want to have some free space up to
3739 * about 1% of the FS size.
3741 if (force == CHUNK_ALLOC_LIMITED) {
3742 thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
3743 thresh = max_t(u64, 64 * 1024 * 1024,
3744 div_factor_fine(thresh, 1));
3746 if (num_bytes - num_allocated < thresh)
3750 if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
3755 static u64 get_system_chunk_thresh(struct btrfs_root *root, u64 type)
3759 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
3760 BTRFS_BLOCK_GROUP_RAID0 |
3761 BTRFS_BLOCK_GROUP_RAID5 |
3762 BTRFS_BLOCK_GROUP_RAID6))
3763 num_dev = root->fs_info->fs_devices->rw_devices;
3764 else if (type & BTRFS_BLOCK_GROUP_RAID1)
3767 num_dev = 1; /* DUP or single */
3769 /* metadata for updaing devices and chunk tree */
3770 return btrfs_calc_trans_metadata_size(root, num_dev + 1);
3773 static void check_system_chunk(struct btrfs_trans_handle *trans,
3774 struct btrfs_root *root, u64 type)
3776 struct btrfs_space_info *info;
3780 info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3781 spin_lock(&info->lock);
3782 left = info->total_bytes - info->bytes_used - info->bytes_pinned -
3783 info->bytes_reserved - info->bytes_readonly;
3784 spin_unlock(&info->lock);
3786 thresh = get_system_chunk_thresh(root, type);
3787 if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
3788 btrfs_info(root->fs_info, "left=%llu, need=%llu, flags=%llu",
3789 left, thresh, type);
3790 dump_space_info(info, 0, 0);
3793 if (left < thresh) {
3796 flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
3797 btrfs_alloc_chunk(trans, root, flags);
3801 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
3802 struct btrfs_root *extent_root, u64 flags, int force)
3804 struct btrfs_space_info *space_info;
3805 struct btrfs_fs_info *fs_info = extent_root->fs_info;
3806 int wait_for_alloc = 0;
3809 /* Don't re-enter if we're already allocating a chunk */
3810 if (trans->allocating_chunk)
3813 space_info = __find_space_info(extent_root->fs_info, flags);
3815 ret = update_space_info(extent_root->fs_info, flags,
3817 BUG_ON(ret); /* -ENOMEM */
3819 BUG_ON(!space_info); /* Logic error */
3822 spin_lock(&space_info->lock);
3823 if (force < space_info->force_alloc)
3824 force = space_info->force_alloc;
3825 if (space_info->full) {
3826 spin_unlock(&space_info->lock);
3830 if (!should_alloc_chunk(extent_root, space_info, force)) {
3831 spin_unlock(&space_info->lock);
3833 } else if (space_info->chunk_alloc) {
3836 space_info->chunk_alloc = 1;
3839 spin_unlock(&space_info->lock);
3841 mutex_lock(&fs_info->chunk_mutex);
3844 * The chunk_mutex is held throughout the entirety of a chunk
3845 * allocation, so once we've acquired the chunk_mutex we know that the
3846 * other guy is done and we need to recheck and see if we should
3849 if (wait_for_alloc) {
3850 mutex_unlock(&fs_info->chunk_mutex);
3855 trans->allocating_chunk = true;
3858 * If we have mixed data/metadata chunks we want to make sure we keep
3859 * allocating mixed chunks instead of individual chunks.
3861 if (btrfs_mixed_space_info(space_info))
3862 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3865 * if we're doing a data chunk, go ahead and make sure that
3866 * we keep a reasonable number of metadata chunks allocated in the
3869 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3870 fs_info->data_chunk_allocations++;
3871 if (!(fs_info->data_chunk_allocations %
3872 fs_info->metadata_ratio))
3873 force_metadata_allocation(fs_info);
3877 * Check if we have enough space in SYSTEM chunk because we may need
3878 * to update devices.
3880 check_system_chunk(trans, extent_root, flags);
3882 ret = btrfs_alloc_chunk(trans, extent_root, flags);
3883 trans->allocating_chunk = false;
3885 spin_lock(&space_info->lock);
3886 if (ret < 0 && ret != -ENOSPC)
3889 space_info->full = 1;
3893 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3895 space_info->chunk_alloc = 0;
3896 spin_unlock(&space_info->lock);
3897 mutex_unlock(&fs_info->chunk_mutex);
3901 static int can_overcommit(struct btrfs_root *root,
3902 struct btrfs_space_info *space_info, u64 bytes,
3903 enum btrfs_reserve_flush_enum flush)
3905 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3906 u64 profile = btrfs_get_alloc_profile(root, 0);
3912 used = space_info->bytes_used + space_info->bytes_reserved +
3913 space_info->bytes_pinned + space_info->bytes_readonly;
3916 * We only want to allow over committing if we have lots of actual space
3917 * free, but if we don't have enough space to handle the global reserve
3918 * space then we could end up having a real enospc problem when trying
3919 * to allocate a chunk or some other such important allocation.
3921 spin_lock(&global_rsv->lock);
3922 space_size = calc_global_rsv_need_space(global_rsv);
3923 spin_unlock(&global_rsv->lock);
3924 if (used + space_size >= space_info->total_bytes)
3927 used += space_info->bytes_may_use;
3929 spin_lock(&root->fs_info->free_chunk_lock);
3930 avail = root->fs_info->free_chunk_space;
3931 spin_unlock(&root->fs_info->free_chunk_lock);
3934 * If we have dup, raid1 or raid10 then only half of the free
3935 * space is actually useable. For raid56, the space info used
3936 * doesn't include the parity drive, so we don't have to
3939 if (profile & (BTRFS_BLOCK_GROUP_DUP |
3940 BTRFS_BLOCK_GROUP_RAID1 |
3941 BTRFS_BLOCK_GROUP_RAID10))
3944 to_add = space_info->total_bytes;
3947 * If we aren't flushing all things, let us overcommit up to
3948 * 1/2th of the space. If we can flush, don't let us overcommit
3949 * too much, let it overcommit up to 1/8 of the space.
3951 if (flush == BTRFS_RESERVE_FLUSH_ALL)
3957 * Limit the overcommit to the amount of free space we could possibly
3958 * allocate for chunks.
3960 to_add = min(avail, to_add);
3962 if (used + bytes < space_info->total_bytes + to_add)
3967 static void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
3968 unsigned long nr_pages)
3970 struct super_block *sb = root->fs_info->sb;
3972 if (down_read_trylock(&sb->s_umount)) {
3973 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
3974 up_read(&sb->s_umount);
3977 * We needn't worry the filesystem going from r/w to r/o though
3978 * we don't acquire ->s_umount mutex, because the filesystem
3979 * should guarantee the delalloc inodes list be empty after
3980 * the filesystem is readonly(all dirty pages are written to
3983 btrfs_start_all_delalloc_inodes(root->fs_info, 0);
3984 if (!current->journal_info)
3985 btrfs_wait_all_ordered_extents(root->fs_info, 0);
3990 * shrink metadata reservation for delalloc
3992 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
3995 struct btrfs_block_rsv *block_rsv;
3996 struct btrfs_space_info *space_info;
3997 struct btrfs_trans_handle *trans;
4001 unsigned long nr_pages = (2 * 1024 * 1024) >> PAGE_CACHE_SHIFT;
4003 enum btrfs_reserve_flush_enum flush;
4005 trans = (struct btrfs_trans_handle *)current->journal_info;
4006 block_rsv = &root->fs_info->delalloc_block_rsv;
4007 space_info = block_rsv->space_info;
4010 delalloc_bytes = percpu_counter_sum_positive(
4011 &root->fs_info->delalloc_bytes);
4012 if (delalloc_bytes == 0) {
4015 btrfs_wait_all_ordered_extents(root->fs_info, 0);
4019 while (delalloc_bytes && loops < 3) {
4020 max_reclaim = min(delalloc_bytes, to_reclaim);
4021 nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
4022 btrfs_writeback_inodes_sb_nr(root, nr_pages);
4024 * We need to wait for the async pages to actually start before
4027 wait_event(root->fs_info->async_submit_wait,
4028 !atomic_read(&root->fs_info->async_delalloc_pages));
4031 flush = BTRFS_RESERVE_FLUSH_ALL;
4033 flush = BTRFS_RESERVE_NO_FLUSH;
4034 spin_lock(&space_info->lock);
4035 if (can_overcommit(root, space_info, orig, flush)) {
4036 spin_unlock(&space_info->lock);
4039 spin_unlock(&space_info->lock);
4042 if (wait_ordered && !trans) {
4043 btrfs_wait_all_ordered_extents(root->fs_info, 0);
4045 time_left = schedule_timeout_killable(1);
4050 delalloc_bytes = percpu_counter_sum_positive(
4051 &root->fs_info->delalloc_bytes);
4056 * maybe_commit_transaction - possibly commit the transaction if its ok to
4057 * @root - the root we're allocating for
4058 * @bytes - the number of bytes we want to reserve
4059 * @force - force the commit
4061 * This will check to make sure that committing the transaction will actually
4062 * get us somewhere and then commit the transaction if it does. Otherwise it
4063 * will return -ENOSPC.
4065 static int may_commit_transaction(struct btrfs_root *root,
4066 struct btrfs_space_info *space_info,
4067 u64 bytes, int force)
4069 struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
4070 struct btrfs_trans_handle *trans;
4072 trans = (struct btrfs_trans_handle *)current->journal_info;
4079 /* See if there is enough pinned space to make this reservation */
4080 spin_lock(&space_info->lock);
4081 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4083 spin_unlock(&space_info->lock);
4086 spin_unlock(&space_info->lock);
4089 * See if there is some space in the delayed insertion reservation for
4092 if (space_info != delayed_rsv->space_info)
4095 spin_lock(&space_info->lock);
4096 spin_lock(&delayed_rsv->lock);
4097 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4098 bytes - delayed_rsv->size) >= 0) {
4099 spin_unlock(&delayed_rsv->lock);
4100 spin_unlock(&space_info->lock);
4103 spin_unlock(&delayed_rsv->lock);
4104 spin_unlock(&space_info->lock);
4107 trans = btrfs_join_transaction(root);
4111 return btrfs_commit_transaction(trans, root);
4115 FLUSH_DELAYED_ITEMS_NR = 1,
4116 FLUSH_DELAYED_ITEMS = 2,
4118 FLUSH_DELALLOC_WAIT = 4,
4123 static int flush_space(struct btrfs_root *root,
4124 struct btrfs_space_info *space_info, u64 num_bytes,
4125 u64 orig_bytes, int state)
4127 struct btrfs_trans_handle *trans;
4132 case FLUSH_DELAYED_ITEMS_NR:
4133 case FLUSH_DELAYED_ITEMS:
4134 if (state == FLUSH_DELAYED_ITEMS_NR) {
4135 u64 bytes = btrfs_calc_trans_metadata_size(root, 1);
4137 nr = (int)div64_u64(num_bytes, bytes);
4144 trans = btrfs_join_transaction(root);
4145 if (IS_ERR(trans)) {
4146 ret = PTR_ERR(trans);
4149 ret = btrfs_run_delayed_items_nr(trans, root, nr);
4150 btrfs_end_transaction(trans, root);
4152 case FLUSH_DELALLOC:
4153 case FLUSH_DELALLOC_WAIT:
4154 shrink_delalloc(root, num_bytes, orig_bytes,
4155 state == FLUSH_DELALLOC_WAIT);
4158 trans = btrfs_join_transaction(root);
4159 if (IS_ERR(trans)) {
4160 ret = PTR_ERR(trans);
4163 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
4164 btrfs_get_alloc_profile(root, 0),
4165 CHUNK_ALLOC_NO_FORCE);
4166 btrfs_end_transaction(trans, root);
4171 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4181 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
4182 * @root - the root we're allocating for
4183 * @block_rsv - the block_rsv we're allocating for
4184 * @orig_bytes - the number of bytes we want
4185 * @flush - whether or not we can flush to make our reservation
4187 * This will reserve orgi_bytes number of bytes from the space info associated
4188 * with the block_rsv. If there is not enough space it will make an attempt to
4189 * flush out space to make room. It will do this by flushing delalloc if
4190 * possible or committing the transaction. If flush is 0 then no attempts to
4191 * regain reservations will be made and this will fail if there is not enough
4194 static int reserve_metadata_bytes(struct btrfs_root *root,
4195 struct btrfs_block_rsv *block_rsv,
4197 enum btrfs_reserve_flush_enum flush)
4199 struct btrfs_space_info *space_info = block_rsv->space_info;
4201 u64 num_bytes = orig_bytes;
4202 int flush_state = FLUSH_DELAYED_ITEMS_NR;
4204 bool flushing = false;
4208 spin_lock(&space_info->lock);
4210 * We only want to wait if somebody other than us is flushing and we
4211 * are actually allowed to flush all things.
4213 while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
4214 space_info->flush) {
4215 spin_unlock(&space_info->lock);
4217 * If we have a trans handle we can't wait because the flusher
4218 * may have to commit the transaction, which would mean we would
4219 * deadlock since we are waiting for the flusher to finish, but
4220 * hold the current transaction open.
4222 if (current->journal_info)
4224 ret = wait_event_killable(space_info->wait, !space_info->flush);
4225 /* Must have been killed, return */
4229 spin_lock(&space_info->lock);
4233 used = space_info->bytes_used + space_info->bytes_reserved +
4234 space_info->bytes_pinned + space_info->bytes_readonly +
4235 space_info->bytes_may_use;
4238 * The idea here is that we've not already over-reserved the block group
4239 * then we can go ahead and save our reservation first and then start
4240 * flushing if we need to. Otherwise if we've already overcommitted
4241 * lets start flushing stuff first and then come back and try to make
4244 if (used <= space_info->total_bytes) {
4245 if (used + orig_bytes <= space_info->total_bytes) {
4246 space_info->bytes_may_use += orig_bytes;
4247 trace_btrfs_space_reservation(root->fs_info,
4248 "space_info", space_info->flags, orig_bytes, 1);
4252 * Ok set num_bytes to orig_bytes since we aren't
4253 * overocmmitted, this way we only try and reclaim what
4256 num_bytes = orig_bytes;
4260 * Ok we're over committed, set num_bytes to the overcommitted
4261 * amount plus the amount of bytes that we need for this
4264 num_bytes = used - space_info->total_bytes +
4268 if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
4269 space_info->bytes_may_use += orig_bytes;
4270 trace_btrfs_space_reservation(root->fs_info, "space_info",
4271 space_info->flags, orig_bytes,
4277 * Couldn't make our reservation, save our place so while we're trying
4278 * to reclaim space we can actually use it instead of somebody else
4279 * stealing it from us.
4281 * We make the other tasks wait for the flush only when we can flush
4284 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
4286 space_info->flush = 1;
4289 spin_unlock(&space_info->lock);
4291 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
4294 ret = flush_space(root, space_info, num_bytes, orig_bytes,
4299 * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
4300 * would happen. So skip delalloc flush.
4302 if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4303 (flush_state == FLUSH_DELALLOC ||
4304 flush_state == FLUSH_DELALLOC_WAIT))
4305 flush_state = ALLOC_CHUNK;
4309 else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4310 flush_state < COMMIT_TRANS)
4312 else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
4313 flush_state <= COMMIT_TRANS)
4317 if (ret == -ENOSPC &&
4318 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
4319 struct btrfs_block_rsv *global_rsv =
4320 &root->fs_info->global_block_rsv;
4322 if (block_rsv != global_rsv &&
4323 !block_rsv_use_bytes(global_rsv, orig_bytes))
4327 spin_lock(&space_info->lock);
4328 space_info->flush = 0;
4329 wake_up_all(&space_info->wait);
4330 spin_unlock(&space_info->lock);
4335 static struct btrfs_block_rsv *get_block_rsv(
4336 const struct btrfs_trans_handle *trans,
4337 const struct btrfs_root *root)
4339 struct btrfs_block_rsv *block_rsv = NULL;
4342 block_rsv = trans->block_rsv;
4344 if (root == root->fs_info->csum_root && trans->adding_csums)
4345 block_rsv = trans->block_rsv;
4348 block_rsv = root->block_rsv;
4351 block_rsv = &root->fs_info->empty_block_rsv;
4356 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
4360 spin_lock(&block_rsv->lock);
4361 if (block_rsv->reserved >= num_bytes) {
4362 block_rsv->reserved -= num_bytes;
4363 if (block_rsv->reserved < block_rsv->size)
4364 block_rsv->full = 0;
4367 spin_unlock(&block_rsv->lock);
4371 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
4372 u64 num_bytes, int update_size)
4374 spin_lock(&block_rsv->lock);
4375 block_rsv->reserved += num_bytes;
4377 block_rsv->size += num_bytes;
4378 else if (block_rsv->reserved >= block_rsv->size)
4379 block_rsv->full = 1;
4380 spin_unlock(&block_rsv->lock);
4383 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
4384 struct btrfs_block_rsv *dest, u64 num_bytes,
4387 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4390 if (global_rsv->space_info != dest->space_info)
4393 spin_lock(&global_rsv->lock);
4394 min_bytes = div_factor(global_rsv->size, min_factor);
4395 if (global_rsv->reserved < min_bytes + num_bytes) {
4396 spin_unlock(&global_rsv->lock);
4399 global_rsv->reserved -= num_bytes;
4400 if (global_rsv->reserved < global_rsv->size)
4401 global_rsv->full = 0;
4402 spin_unlock(&global_rsv->lock);
4404 block_rsv_add_bytes(dest, num_bytes, 1);
4408 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
4409 struct btrfs_block_rsv *block_rsv,
4410 struct btrfs_block_rsv *dest, u64 num_bytes)
4412 struct btrfs_space_info *space_info = block_rsv->space_info;
4414 spin_lock(&block_rsv->lock);
4415 if (num_bytes == (u64)-1)
4416 num_bytes = block_rsv->size;
4417 block_rsv->size -= num_bytes;
4418 if (block_rsv->reserved >= block_rsv->size) {
4419 num_bytes = block_rsv->reserved - block_rsv->size;
4420 block_rsv->reserved = block_rsv->size;
4421 block_rsv->full = 1;
4425 spin_unlock(&block_rsv->lock);
4427 if (num_bytes > 0) {
4429 spin_lock(&dest->lock);
4433 bytes_to_add = dest->size - dest->reserved;
4434 bytes_to_add = min(num_bytes, bytes_to_add);
4435 dest->reserved += bytes_to_add;
4436 if (dest->reserved >= dest->size)
4438 num_bytes -= bytes_to_add;
4440 spin_unlock(&dest->lock);
4443 spin_lock(&space_info->lock);
4444 space_info->bytes_may_use -= num_bytes;
4445 trace_btrfs_space_reservation(fs_info, "space_info",
4446 space_info->flags, num_bytes, 0);
4447 space_info->reservation_progress++;
4448 spin_unlock(&space_info->lock);
4453 static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
4454 struct btrfs_block_rsv *dst, u64 num_bytes)
4458 ret = block_rsv_use_bytes(src, num_bytes);
4462 block_rsv_add_bytes(dst, num_bytes, 1);
4466 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
4468 memset(rsv, 0, sizeof(*rsv));
4469 spin_lock_init(&rsv->lock);
4473 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
4474 unsigned short type)
4476 struct btrfs_block_rsv *block_rsv;
4477 struct btrfs_fs_info *fs_info = root->fs_info;
4479 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
4483 btrfs_init_block_rsv(block_rsv, type);
4484 block_rsv->space_info = __find_space_info(fs_info,
4485 BTRFS_BLOCK_GROUP_METADATA);
4489 void btrfs_free_block_rsv(struct btrfs_root *root,
4490 struct btrfs_block_rsv *rsv)
4494 btrfs_block_rsv_release(root, rsv, (u64)-1);
4498 int btrfs_block_rsv_add(struct btrfs_root *root,
4499 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
4500 enum btrfs_reserve_flush_enum flush)
4507 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4509 block_rsv_add_bytes(block_rsv, num_bytes, 1);
4516 int btrfs_block_rsv_check(struct btrfs_root *root,
4517 struct btrfs_block_rsv *block_rsv, int min_factor)
4525 spin_lock(&block_rsv->lock);
4526 num_bytes = div_factor(block_rsv->size, min_factor);
4527 if (block_rsv->reserved >= num_bytes)
4529 spin_unlock(&block_rsv->lock);
4534 int btrfs_block_rsv_refill(struct btrfs_root *root,
4535 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
4536 enum btrfs_reserve_flush_enum flush)
4544 spin_lock(&block_rsv->lock);
4545 num_bytes = min_reserved;
4546 if (block_rsv->reserved >= num_bytes)
4549 num_bytes -= block_rsv->reserved;
4550 spin_unlock(&block_rsv->lock);
4555 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4557 block_rsv_add_bytes(block_rsv, num_bytes, 0);
4564 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
4565 struct btrfs_block_rsv *dst_rsv,
4568 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4571 void btrfs_block_rsv_release(struct btrfs_root *root,
4572 struct btrfs_block_rsv *block_rsv,
4575 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4576 if (global_rsv->full || global_rsv == block_rsv ||
4577 block_rsv->space_info != global_rsv->space_info)
4579 block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
4584 * helper to calculate size of global block reservation.
4585 * the desired value is sum of space used by extent tree,
4586 * checksum tree and root tree
4588 static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
4590 struct btrfs_space_info *sinfo;
4594 int csum_size = btrfs_super_csum_size(fs_info->super_copy);
4596 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
4597 spin_lock(&sinfo->lock);
4598 data_used = sinfo->bytes_used;
4599 spin_unlock(&sinfo->lock);
4601 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4602 spin_lock(&sinfo->lock);
4603 if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
4605 meta_used = sinfo->bytes_used;
4606 spin_unlock(&sinfo->lock);
4608 num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
4610 num_bytes += div64_u64(data_used + meta_used, 50);
4612 if (num_bytes * 3 > meta_used)
4613 num_bytes = div64_u64(meta_used, 3);
4615 return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
4618 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
4620 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4621 struct btrfs_space_info *sinfo = block_rsv->space_info;
4624 num_bytes = calc_global_metadata_size(fs_info);
4626 spin_lock(&sinfo->lock);
4627 spin_lock(&block_rsv->lock);
4629 block_rsv->size = min_t(u64, num_bytes, 512 * 1024 * 1024);
4631 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
4632 sinfo->bytes_reserved + sinfo->bytes_readonly +
4633 sinfo->bytes_may_use;
4635 if (sinfo->total_bytes > num_bytes) {
4636 num_bytes = sinfo->total_bytes - num_bytes;
4637 block_rsv->reserved += num_bytes;
4638 sinfo->bytes_may_use += num_bytes;
4639 trace_btrfs_space_reservation(fs_info, "space_info",
4640 sinfo->flags, num_bytes, 1);
4643 if (block_rsv->reserved >= block_rsv->size) {
4644 num_bytes = block_rsv->reserved - block_rsv->size;
4645 sinfo->bytes_may_use -= num_bytes;
4646 trace_btrfs_space_reservation(fs_info, "space_info",
4647 sinfo->flags, num_bytes, 0);
4648 sinfo->reservation_progress++;
4649 block_rsv->reserved = block_rsv->size;
4650 block_rsv->full = 1;
4653 spin_unlock(&block_rsv->lock);
4654 spin_unlock(&sinfo->lock);
4657 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
4659 struct btrfs_space_info *space_info;
4661 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4662 fs_info->chunk_block_rsv.space_info = space_info;
4664 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4665 fs_info->global_block_rsv.space_info = space_info;
4666 fs_info->delalloc_block_rsv.space_info = space_info;
4667 fs_info->trans_block_rsv.space_info = space_info;
4668 fs_info->empty_block_rsv.space_info = space_info;
4669 fs_info->delayed_block_rsv.space_info = space_info;
4671 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
4672 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
4673 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
4674 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
4675 if (fs_info->quota_root)
4676 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
4677 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
4679 update_global_block_rsv(fs_info);
4682 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
4684 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
4686 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
4687 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
4688 WARN_ON(fs_info->trans_block_rsv.size > 0);
4689 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
4690 WARN_ON(fs_info->chunk_block_rsv.size > 0);
4691 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
4692 WARN_ON(fs_info->delayed_block_rsv.size > 0);
4693 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
4696 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
4697 struct btrfs_root *root)
4699 if (!trans->block_rsv)
4702 if (!trans->bytes_reserved)
4705 trace_btrfs_space_reservation(root->fs_info, "transaction",
4706 trans->transid, trans->bytes_reserved, 0);
4707 btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
4708 trans->bytes_reserved = 0;
4711 /* Can only return 0 or -ENOSPC */
4712 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
4713 struct inode *inode)
4715 struct btrfs_root *root = BTRFS_I(inode)->root;
4716 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4717 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
4720 * We need to hold space in order to delete our orphan item once we've
4721 * added it, so this takes the reservation so we can release it later
4722 * when we are truly done with the orphan item.
4724 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
4725 trace_btrfs_space_reservation(root->fs_info, "orphan",
4726 btrfs_ino(inode), num_bytes, 1);
4727 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4730 void btrfs_orphan_release_metadata(struct inode *inode)
4732 struct btrfs_root *root = BTRFS_I(inode)->root;
4733 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
4734 trace_btrfs_space_reservation(root->fs_info, "orphan",
4735 btrfs_ino(inode), num_bytes, 0);
4736 btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
4740 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
4741 * root: the root of the parent directory
4742 * rsv: block reservation
4743 * items: the number of items that we need do reservation
4744 * qgroup_reserved: used to return the reserved size in qgroup
4746 * This function is used to reserve the space for snapshot/subvolume
4747 * creation and deletion. Those operations are different with the
4748 * common file/directory operations, they change two fs/file trees
4749 * and root tree, the number of items that the qgroup reserves is
4750 * different with the free space reservation. So we can not use
4751 * the space reseravtion mechanism in start_transaction().
4753 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
4754 struct btrfs_block_rsv *rsv,
4756 u64 *qgroup_reserved,
4757 bool use_global_rsv)
4761 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4763 if (root->fs_info->quota_enabled) {
4764 /* One for parent inode, two for dir entries */
4765 num_bytes = 3 * root->leafsize;
4766 ret = btrfs_qgroup_reserve(root, num_bytes);
4773 *qgroup_reserved = num_bytes;
4775 num_bytes = btrfs_calc_trans_metadata_size(root, items);
4776 rsv->space_info = __find_space_info(root->fs_info,
4777 BTRFS_BLOCK_GROUP_METADATA);
4778 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
4779 BTRFS_RESERVE_FLUSH_ALL);
4781 if (ret == -ENOSPC && use_global_rsv)
4782 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes);
4785 if (*qgroup_reserved)
4786 btrfs_qgroup_free(root, *qgroup_reserved);
4792 void btrfs_subvolume_release_metadata(struct btrfs_root *root,
4793 struct btrfs_block_rsv *rsv,
4794 u64 qgroup_reserved)
4796 btrfs_block_rsv_release(root, rsv, (u64)-1);
4797 if (qgroup_reserved)
4798 btrfs_qgroup_free(root, qgroup_reserved);
4802 * drop_outstanding_extent - drop an outstanding extent
4803 * @inode: the inode we're dropping the extent for
4805 * This is called when we are freeing up an outstanding extent, either called
4806 * after an error or after an extent is written. This will return the number of
4807 * reserved extents that need to be freed. This must be called with
4808 * BTRFS_I(inode)->lock held.
4810 static unsigned drop_outstanding_extent(struct inode *inode)
4812 unsigned drop_inode_space = 0;
4813 unsigned dropped_extents = 0;
4815 BUG_ON(!BTRFS_I(inode)->outstanding_extents);
4816 BTRFS_I(inode)->outstanding_extents--;
4818 if (BTRFS_I(inode)->outstanding_extents == 0 &&
4819 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4820 &BTRFS_I(inode)->runtime_flags))
4821 drop_inode_space = 1;
4824 * If we have more or the same amount of outsanding extents than we have
4825 * reserved then we need to leave the reserved extents count alone.
4827 if (BTRFS_I(inode)->outstanding_extents >=
4828 BTRFS_I(inode)->reserved_extents)
4829 return drop_inode_space;
4831 dropped_extents = BTRFS_I(inode)->reserved_extents -
4832 BTRFS_I(inode)->outstanding_extents;
4833 BTRFS_I(inode)->reserved_extents -= dropped_extents;
4834 return dropped_extents + drop_inode_space;
4838 * calc_csum_metadata_size - return the amount of metada space that must be
4839 * reserved/free'd for the given bytes.
4840 * @inode: the inode we're manipulating
4841 * @num_bytes: the number of bytes in question
4842 * @reserve: 1 if we are reserving space, 0 if we are freeing space
4844 * This adjusts the number of csum_bytes in the inode and then returns the
4845 * correct amount of metadata that must either be reserved or freed. We
4846 * calculate how many checksums we can fit into one leaf and then divide the
4847 * number of bytes that will need to be checksumed by this value to figure out
4848 * how many checksums will be required. If we are adding bytes then the number
4849 * may go up and we will return the number of additional bytes that must be
4850 * reserved. If it is going down we will return the number of bytes that must
4853 * This must be called with BTRFS_I(inode)->lock held.
4855 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
4858 struct btrfs_root *root = BTRFS_I(inode)->root;
4860 int num_csums_per_leaf;
4864 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
4865 BTRFS_I(inode)->csum_bytes == 0)
4868 old_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
4870 BTRFS_I(inode)->csum_bytes += num_bytes;
4872 BTRFS_I(inode)->csum_bytes -= num_bytes;
4873 csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
4874 num_csums_per_leaf = (int)div64_u64(csum_size,
4875 sizeof(struct btrfs_csum_item) +
4876 sizeof(struct btrfs_disk_key));
4877 num_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
4878 num_csums = num_csums + num_csums_per_leaf - 1;
4879 num_csums = num_csums / num_csums_per_leaf;
4881 old_csums = old_csums + num_csums_per_leaf - 1;
4882 old_csums = old_csums / num_csums_per_leaf;
4884 /* No change, no need to reserve more */
4885 if (old_csums == num_csums)
4889 return btrfs_calc_trans_metadata_size(root,
4890 num_csums - old_csums);
4892 return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
4895 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
4897 struct btrfs_root *root = BTRFS_I(inode)->root;
4898 struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
4901 unsigned nr_extents = 0;
4902 int extra_reserve = 0;
4903 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
4905 bool delalloc_lock = true;
4909 /* If we are a free space inode we need to not flush since we will be in
4910 * the middle of a transaction commit. We also don't need the delalloc
4911 * mutex since we won't race with anybody. We need this mostly to make
4912 * lockdep shut its filthy mouth.
4914 if (btrfs_is_free_space_inode(inode)) {
4915 flush = BTRFS_RESERVE_NO_FLUSH;
4916 delalloc_lock = false;
4919 if (flush != BTRFS_RESERVE_NO_FLUSH &&
4920 btrfs_transaction_in_commit(root->fs_info))
4921 schedule_timeout(1);
4924 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
4926 num_bytes = ALIGN(num_bytes, root->sectorsize);
4928 spin_lock(&BTRFS_I(inode)->lock);
4929 BTRFS_I(inode)->outstanding_extents++;
4931 if (BTRFS_I(inode)->outstanding_extents >
4932 BTRFS_I(inode)->reserved_extents)
4933 nr_extents = BTRFS_I(inode)->outstanding_extents -
4934 BTRFS_I(inode)->reserved_extents;
4937 * Add an item to reserve for updating the inode when we complete the
4940 if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4941 &BTRFS_I(inode)->runtime_flags)) {
4946 to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
4947 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
4948 csum_bytes = BTRFS_I(inode)->csum_bytes;
4949 spin_unlock(&BTRFS_I(inode)->lock);
4951 if (root->fs_info->quota_enabled) {
4952 ret = btrfs_qgroup_reserve(root, num_bytes +
4953 nr_extents * root->leafsize);
4958 ret = reserve_metadata_bytes(root, block_rsv, to_reserve, flush);
4959 if (unlikely(ret)) {
4960 if (root->fs_info->quota_enabled)
4961 btrfs_qgroup_free(root, num_bytes +
4962 nr_extents * root->leafsize);
4966 spin_lock(&BTRFS_I(inode)->lock);
4967 if (extra_reserve) {
4968 set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4969 &BTRFS_I(inode)->runtime_flags);
4972 BTRFS_I(inode)->reserved_extents += nr_extents;
4973 spin_unlock(&BTRFS_I(inode)->lock);
4976 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
4979 trace_btrfs_space_reservation(root->fs_info,"delalloc",
4980 btrfs_ino(inode), to_reserve, 1);
4981 block_rsv_add_bytes(block_rsv, to_reserve, 1);
4986 spin_lock(&BTRFS_I(inode)->lock);
4987 dropped = drop_outstanding_extent(inode);
4989 * If the inodes csum_bytes is the same as the original
4990 * csum_bytes then we know we haven't raced with any free()ers
4991 * so we can just reduce our inodes csum bytes and carry on.
4993 if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
4994 calc_csum_metadata_size(inode, num_bytes, 0);
4996 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
5000 * This is tricky, but first we need to figure out how much we
5001 * free'd from any free-ers that occured during this
5002 * reservation, so we reset ->csum_bytes to the csum_bytes
5003 * before we dropped our lock, and then call the free for the
5004 * number of bytes that were freed while we were trying our
5007 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
5008 BTRFS_I(inode)->csum_bytes = csum_bytes;
5009 to_free = calc_csum_metadata_size(inode, bytes, 0);
5013 * Now we need to see how much we would have freed had we not
5014 * been making this reservation and our ->csum_bytes were not
5015 * artificially inflated.
5017 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
5018 bytes = csum_bytes - orig_csum_bytes;
5019 bytes = calc_csum_metadata_size(inode, bytes, 0);
5022 * Now reset ->csum_bytes to what it should be. If bytes is
5023 * more than to_free then we would have free'd more space had we
5024 * not had an artificially high ->csum_bytes, so we need to free
5025 * the remainder. If bytes is the same or less then we don't
5026 * need to do anything, the other free-ers did the correct
5029 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
5030 if (bytes > to_free)
5031 to_free = bytes - to_free;
5035 spin_unlock(&BTRFS_I(inode)->lock);
5037 to_free += btrfs_calc_trans_metadata_size(root, dropped);
5040 btrfs_block_rsv_release(root, block_rsv, to_free);
5041 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5042 btrfs_ino(inode), to_free, 0);
5045 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
5050 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
5051 * @inode: the inode to release the reservation for
5052 * @num_bytes: the number of bytes we're releasing
5054 * This will release the metadata reservation for an inode. This can be called
5055 * once we complete IO for a given set of bytes to release their metadata
5058 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
5060 struct btrfs_root *root = BTRFS_I(inode)->root;
5064 num_bytes = ALIGN(num_bytes, root->sectorsize);
5065 spin_lock(&BTRFS_I(inode)->lock);
5066 dropped = drop_outstanding_extent(inode);
5069 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
5070 spin_unlock(&BTRFS_I(inode)->lock);
5072 to_free += btrfs_calc_trans_metadata_size(root, dropped);
5074 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5075 btrfs_ino(inode), to_free, 0);
5076 if (root->fs_info->quota_enabled) {
5077 btrfs_qgroup_free(root, num_bytes +
5078 dropped * root->leafsize);
5081 btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
5086 * btrfs_delalloc_reserve_space - reserve data and metadata space for delalloc
5087 * @inode: inode we're writing to
5088 * @num_bytes: the number of bytes we want to allocate
5090 * This will do the following things
5092 * o reserve space in the data space info for num_bytes
5093 * o reserve space in the metadata space info based on number of outstanding
5094 * extents and how much csums will be needed
5095 * o add to the inodes ->delalloc_bytes
5096 * o add it to the fs_info's delalloc inodes list.
5098 * This will return 0 for success and -ENOSPC if there is no space left.
5100 int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
5104 ret = btrfs_check_data_free_space(inode, num_bytes);
5108 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
5110 btrfs_free_reserved_data_space(inode, num_bytes);
5118 * btrfs_delalloc_release_space - release data and metadata space for delalloc
5119 * @inode: inode we're releasing space for
5120 * @num_bytes: the number of bytes we want to free up
5122 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
5123 * called in the case that we don't need the metadata AND data reservations
5124 * anymore. So if there is an error or we insert an inline extent.
5126 * This function will release the metadata space that was not used and will
5127 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
5128 * list if there are no delalloc bytes left.
5130 void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
5132 btrfs_delalloc_release_metadata(inode, num_bytes);
5133 btrfs_free_reserved_data_space(inode, num_bytes);
5136 static int update_block_group(struct btrfs_root *root,
5137 u64 bytenr, u64 num_bytes, int alloc)
5139 struct btrfs_block_group_cache *cache = NULL;
5140 struct btrfs_fs_info *info = root->fs_info;
5141 u64 total = num_bytes;
5146 /* block accounting for super block */
5147 spin_lock(&info->delalloc_root_lock);
5148 old_val = btrfs_super_bytes_used(info->super_copy);
5150 old_val += num_bytes;
5152 old_val -= num_bytes;
5153 btrfs_set_super_bytes_used(info->super_copy, old_val);
5154 spin_unlock(&info->delalloc_root_lock);
5157 cache = btrfs_lookup_block_group(info, bytenr);
5160 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
5161 BTRFS_BLOCK_GROUP_RAID1 |
5162 BTRFS_BLOCK_GROUP_RAID10))
5167 * If this block group has free space cache written out, we
5168 * need to make sure to load it if we are removing space. This
5169 * is because we need the unpinning stage to actually add the
5170 * space back to the block group, otherwise we will leak space.
5172 if (!alloc && cache->cached == BTRFS_CACHE_NO)
5173 cache_block_group(cache, 1);
5175 byte_in_group = bytenr - cache->key.objectid;
5176 WARN_ON(byte_in_group > cache->key.offset);
5178 spin_lock(&cache->space_info->lock);
5179 spin_lock(&cache->lock);
5181 if (btrfs_test_opt(root, SPACE_CACHE) &&
5182 cache->disk_cache_state < BTRFS_DC_CLEAR)
5183 cache->disk_cache_state = BTRFS_DC_CLEAR;
5186 old_val = btrfs_block_group_used(&cache->item);
5187 num_bytes = min(total, cache->key.offset - byte_in_group);
5189 old_val += num_bytes;
5190 btrfs_set_block_group_used(&cache->item, old_val);
5191 cache->reserved -= num_bytes;
5192 cache->space_info->bytes_reserved -= num_bytes;
5193 cache->space_info->bytes_used += num_bytes;
5194 cache->space_info->disk_used += num_bytes * factor;
5195 spin_unlock(&cache->lock);
5196 spin_unlock(&cache->space_info->lock);
5198 old_val -= num_bytes;
5199 btrfs_set_block_group_used(&cache->item, old_val);
5200 cache->pinned += num_bytes;
5201 cache->space_info->bytes_pinned += num_bytes;
5202 cache->space_info->bytes_used -= num_bytes;
5203 cache->space_info->disk_used -= num_bytes * factor;
5204 spin_unlock(&cache->lock);
5205 spin_unlock(&cache->space_info->lock);
5207 set_extent_dirty(info->pinned_extents,
5208 bytenr, bytenr + num_bytes - 1,
5209 GFP_NOFS | __GFP_NOFAIL);
5211 btrfs_put_block_group(cache);
5213 bytenr += num_bytes;
5218 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
5220 struct btrfs_block_group_cache *cache;
5223 spin_lock(&root->fs_info->block_group_cache_lock);
5224 bytenr = root->fs_info->first_logical_byte;
5225 spin_unlock(&root->fs_info->block_group_cache_lock);
5227 if (bytenr < (u64)-1)
5230 cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
5234 bytenr = cache->key.objectid;
5235 btrfs_put_block_group(cache);
5240 static int pin_down_extent(struct btrfs_root *root,
5241 struct btrfs_block_group_cache *cache,
5242 u64 bytenr, u64 num_bytes, int reserved)
5244 spin_lock(&cache->space_info->lock);
5245 spin_lock(&cache->lock);
5246 cache->pinned += num_bytes;
5247 cache->space_info->bytes_pinned += num_bytes;
5249 cache->reserved -= num_bytes;
5250 cache->space_info->bytes_reserved -= num_bytes;
5252 spin_unlock(&cache->lock);
5253 spin_unlock(&cache->space_info->lock);
5255 set_extent_dirty(root->fs_info->pinned_extents, bytenr,
5256 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
5261 * this function must be called within transaction
5263 int btrfs_pin_extent(struct btrfs_root *root,
5264 u64 bytenr, u64 num_bytes, int reserved)
5266 struct btrfs_block_group_cache *cache;
5268 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
5269 BUG_ON(!cache); /* Logic error */
5271 pin_down_extent(root, cache, bytenr, num_bytes, reserved);
5273 btrfs_put_block_group(cache);
5278 * this function must be called within transaction
5280 int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
5281 u64 bytenr, u64 num_bytes)
5283 struct btrfs_block_group_cache *cache;
5286 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
5291 * pull in the free space cache (if any) so that our pin
5292 * removes the free space from the cache. We have load_only set
5293 * to one because the slow code to read in the free extents does check
5294 * the pinned extents.
5296 cache_block_group(cache, 1);
5298 pin_down_extent(root, cache, bytenr, num_bytes, 0);
5300 /* remove us from the free space cache (if we're there at all) */
5301 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
5302 btrfs_put_block_group(cache);
5306 static int __exclude_logged_extent(struct btrfs_root *root, u64 start, u64 num_bytes)
5309 struct btrfs_block_group_cache *block_group;
5310 struct btrfs_caching_control *caching_ctl;
5312 block_group = btrfs_lookup_block_group(root->fs_info, start);
5316 cache_block_group(block_group, 0);
5317 caching_ctl = get_caching_control(block_group);
5321 BUG_ON(!block_group_cache_done(block_group));
5322 ret = btrfs_remove_free_space(block_group, start, num_bytes);
5324 mutex_lock(&caching_ctl->mutex);
5326 if (start >= caching_ctl->progress) {
5327 ret = add_excluded_extent(root, start, num_bytes);
5328 } else if (start + num_bytes <= caching_ctl->progress) {
5329 ret = btrfs_remove_free_space(block_group,
5332 num_bytes = caching_ctl->progress - start;
5333 ret = btrfs_remove_free_space(block_group,
5338 num_bytes = (start + num_bytes) -
5339 caching_ctl->progress;
5340 start = caching_ctl->progress;
5341 ret = add_excluded_extent(root, start, num_bytes);
5344 mutex_unlock(&caching_ctl->mutex);
5345 put_caching_control(caching_ctl);
5347 btrfs_put_block_group(block_group);
5351 int btrfs_exclude_logged_extents(struct btrfs_root *log,
5352 struct extent_buffer *eb)
5354 struct btrfs_file_extent_item *item;
5355 struct btrfs_key key;
5359 if (!btrfs_fs_incompat(log->fs_info, MIXED_GROUPS))
5362 for (i = 0; i < btrfs_header_nritems(eb); i++) {
5363 btrfs_item_key_to_cpu(eb, &key, i);
5364 if (key.type != BTRFS_EXTENT_DATA_KEY)
5366 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
5367 found_type = btrfs_file_extent_type(eb, item);
5368 if (found_type == BTRFS_FILE_EXTENT_INLINE)
5370 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
5372 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
5373 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
5374 __exclude_logged_extent(log, key.objectid, key.offset);
5381 * btrfs_update_reserved_bytes - update the block_group and space info counters
5382 * @cache: The cache we are manipulating
5383 * @num_bytes: The number of bytes in question
5384 * @reserve: One of the reservation enums
5386 * This is called by the allocator when it reserves space, or by somebody who is
5387 * freeing space that was never actually used on disk. For example if you
5388 * reserve some space for a new leaf in transaction A and before transaction A
5389 * commits you free that leaf, you call this with reserve set to 0 in order to
5390 * clear the reservation.
5392 * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
5393 * ENOSPC accounting. For data we handle the reservation through clearing the
5394 * delalloc bits in the io_tree. We have to do this since we could end up
5395 * allocating less disk space for the amount of data we have reserved in the
5396 * case of compression.
5398 * If this is a reservation and the block group has become read only we cannot
5399 * make the reservation and return -EAGAIN, otherwise this function always
5402 static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
5403 u64 num_bytes, int reserve)
5405 struct btrfs_space_info *space_info = cache->space_info;
5408 spin_lock(&space_info->lock);
5409 spin_lock(&cache->lock);
5410 if (reserve != RESERVE_FREE) {
5414 cache->reserved += num_bytes;
5415 space_info->bytes_reserved += num_bytes;
5416 if (reserve == RESERVE_ALLOC) {
5417 trace_btrfs_space_reservation(cache->fs_info,
5418 "space_info", space_info->flags,
5420 space_info->bytes_may_use -= num_bytes;
5425 space_info->bytes_readonly += num_bytes;
5426 cache->reserved -= num_bytes;
5427 space_info->bytes_reserved -= num_bytes;
5428 space_info->reservation_progress++;
5430 spin_unlock(&cache->lock);
5431 spin_unlock(&space_info->lock);
5435 void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
5436 struct btrfs_root *root)
5438 struct btrfs_fs_info *fs_info = root->fs_info;
5439 struct btrfs_caching_control *next;
5440 struct btrfs_caching_control *caching_ctl;
5441 struct btrfs_block_group_cache *cache;
5442 struct btrfs_space_info *space_info;
5444 down_write(&fs_info->extent_commit_sem);
5446 list_for_each_entry_safe(caching_ctl, next,
5447 &fs_info->caching_block_groups, list) {
5448 cache = caching_ctl->block_group;
5449 if (block_group_cache_done(cache)) {
5450 cache->last_byte_to_unpin = (u64)-1;
5451 list_del_init(&caching_ctl->list);
5452 put_caching_control(caching_ctl);
5454 cache->last_byte_to_unpin = caching_ctl->progress;
5458 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5459 fs_info->pinned_extents = &fs_info->freed_extents[1];
5461 fs_info->pinned_extents = &fs_info->freed_extents[0];
5463 up_write(&fs_info->extent_commit_sem);
5465 list_for_each_entry_rcu(space_info, &fs_info->space_info, list)
5466 percpu_counter_set(&space_info->total_bytes_pinned, 0);
5468 update_global_block_rsv(fs_info);
5471 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
5473 struct btrfs_fs_info *fs_info = root->fs_info;
5474 struct btrfs_block_group_cache *cache = NULL;
5475 struct btrfs_space_info *space_info;
5476 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5480 while (start <= end) {
5483 start >= cache->key.objectid + cache->key.offset) {
5485 btrfs_put_block_group(cache);
5486 cache = btrfs_lookup_block_group(fs_info, start);
5487 BUG_ON(!cache); /* Logic error */
5490 len = cache->key.objectid + cache->key.offset - start;
5491 len = min(len, end + 1 - start);
5493 if (start < cache->last_byte_to_unpin) {
5494 len = min(len, cache->last_byte_to_unpin - start);
5495 btrfs_add_free_space(cache, start, len);
5499 space_info = cache->space_info;
5501 spin_lock(&space_info->lock);
5502 spin_lock(&cache->lock);
5503 cache->pinned -= len;
5504 space_info->bytes_pinned -= len;
5506 space_info->bytes_readonly += len;
5509 spin_unlock(&cache->lock);
5510 if (!readonly && global_rsv->space_info == space_info) {
5511 spin_lock(&global_rsv->lock);
5512 if (!global_rsv->full) {
5513 len = min(len, global_rsv->size -
5514 global_rsv->reserved);
5515 global_rsv->reserved += len;
5516 space_info->bytes_may_use += len;
5517 if (global_rsv->reserved >= global_rsv->size)
5518 global_rsv->full = 1;
5520 spin_unlock(&global_rsv->lock);
5522 spin_unlock(&space_info->lock);
5526 btrfs_put_block_group(cache);
5530 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
5531 struct btrfs_root *root)
5533 struct btrfs_fs_info *fs_info = root->fs_info;
5534 struct extent_io_tree *unpin;
5542 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5543 unpin = &fs_info->freed_extents[1];
5545 unpin = &fs_info->freed_extents[0];
5548 ret = find_first_extent_bit(unpin, 0, &start, &end,
5549 EXTENT_DIRTY, NULL);
5553 if (btrfs_test_opt(root, DISCARD))
5554 ret = btrfs_discard_extent(root, start,
5555 end + 1 - start, NULL);
5557 clear_extent_dirty(unpin, start, end, GFP_NOFS);
5558 unpin_extent_range(root, start, end);
5565 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
5566 u64 owner, u64 root_objectid)
5568 struct btrfs_space_info *space_info;
5571 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
5572 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
5573 flags = BTRFS_BLOCK_GROUP_SYSTEM;
5575 flags = BTRFS_BLOCK_GROUP_METADATA;
5577 flags = BTRFS_BLOCK_GROUP_DATA;
5580 space_info = __find_space_info(fs_info, flags);
5581 BUG_ON(!space_info); /* Logic bug */
5582 percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
5586 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
5587 struct btrfs_root *root,
5588 u64 bytenr, u64 num_bytes, u64 parent,
5589 u64 root_objectid, u64 owner_objectid,
5590 u64 owner_offset, int refs_to_drop,
5591 struct btrfs_delayed_extent_op *extent_op)
5593 struct btrfs_key key;
5594 struct btrfs_path *path;
5595 struct btrfs_fs_info *info = root->fs_info;
5596 struct btrfs_root *extent_root = info->extent_root;
5597 struct extent_buffer *leaf;
5598 struct btrfs_extent_item *ei;
5599 struct btrfs_extent_inline_ref *iref;
5602 int extent_slot = 0;
5603 int found_extent = 0;
5607 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
5610 path = btrfs_alloc_path();
5615 path->leave_spinning = 1;
5617 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
5618 BUG_ON(!is_data && refs_to_drop != 1);
5621 skinny_metadata = 0;
5623 ret = lookup_extent_backref(trans, extent_root, path, &iref,
5624 bytenr, num_bytes, parent,
5625 root_objectid, owner_objectid,
5628 extent_slot = path->slots[0];
5629 while (extent_slot >= 0) {
5630 btrfs_item_key_to_cpu(path->nodes[0], &key,
5632 if (key.objectid != bytenr)
5634 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5635 key.offset == num_bytes) {
5639 if (key.type == BTRFS_METADATA_ITEM_KEY &&
5640 key.offset == owner_objectid) {
5644 if (path->slots[0] - extent_slot > 5)
5648 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5649 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
5650 if (found_extent && item_size < sizeof(*ei))
5653 if (!found_extent) {
5655 ret = remove_extent_backref(trans, extent_root, path,
5659 btrfs_abort_transaction(trans, extent_root, ret);
5662 btrfs_release_path(path);
5663 path->leave_spinning = 1;
5665 key.objectid = bytenr;
5666 key.type = BTRFS_EXTENT_ITEM_KEY;
5667 key.offset = num_bytes;
5669 if (!is_data && skinny_metadata) {
5670 key.type = BTRFS_METADATA_ITEM_KEY;
5671 key.offset = owner_objectid;
5674 ret = btrfs_search_slot(trans, extent_root,
5676 if (ret > 0 && skinny_metadata && path->slots[0]) {
5678 * Couldn't find our skinny metadata item,
5679 * see if we have ye olde extent item.
5682 btrfs_item_key_to_cpu(path->nodes[0], &key,
5684 if (key.objectid == bytenr &&
5685 key.type == BTRFS_EXTENT_ITEM_KEY &&
5686 key.offset == num_bytes)
5690 if (ret > 0 && skinny_metadata) {
5691 skinny_metadata = false;
5692 key.type = BTRFS_EXTENT_ITEM_KEY;
5693 key.offset = num_bytes;
5694 btrfs_release_path(path);
5695 ret = btrfs_search_slot(trans, extent_root,
5700 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
5701 ret, (unsigned long long)bytenr);
5703 btrfs_print_leaf(extent_root,
5707 btrfs_abort_transaction(trans, extent_root, ret);
5710 extent_slot = path->slots[0];
5712 } else if (ret == -ENOENT) {
5713 btrfs_print_leaf(extent_root, path->nodes[0]);
5716 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
5717 (unsigned long long)bytenr,
5718 (unsigned long long)parent,
5719 (unsigned long long)root_objectid,
5720 (unsigned long long)owner_objectid,
5721 (unsigned long long)owner_offset);
5723 btrfs_abort_transaction(trans, extent_root, ret);
5727 leaf = path->nodes[0];
5728 item_size = btrfs_item_size_nr(leaf, extent_slot);
5729 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5730 if (item_size < sizeof(*ei)) {
5731 BUG_ON(found_extent || extent_slot != path->slots[0]);
5732 ret = convert_extent_item_v0(trans, extent_root, path,
5735 btrfs_abort_transaction(trans, extent_root, ret);
5739 btrfs_release_path(path);
5740 path->leave_spinning = 1;
5742 key.objectid = bytenr;
5743 key.type = BTRFS_EXTENT_ITEM_KEY;
5744 key.offset = num_bytes;
5746 ret = btrfs_search_slot(trans, extent_root, &key, path,
5749 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
5750 ret, (unsigned long long)bytenr);
5751 btrfs_print_leaf(extent_root, path->nodes[0]);
5754 btrfs_abort_transaction(trans, extent_root, ret);
5758 extent_slot = path->slots[0];
5759 leaf = path->nodes[0];
5760 item_size = btrfs_item_size_nr(leaf, extent_slot);
5763 BUG_ON(item_size < sizeof(*ei));
5764 ei = btrfs_item_ptr(leaf, extent_slot,
5765 struct btrfs_extent_item);
5766 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
5767 key.type == BTRFS_EXTENT_ITEM_KEY) {
5768 struct btrfs_tree_block_info *bi;
5769 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
5770 bi = (struct btrfs_tree_block_info *)(ei + 1);
5771 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
5774 refs = btrfs_extent_refs(leaf, ei);
5775 if (refs < refs_to_drop) {
5776 btrfs_err(info, "trying to drop %d refs but we only have %Lu "
5777 "for bytenr %Lu\n", refs_to_drop, refs, bytenr);
5779 btrfs_abort_transaction(trans, extent_root, ret);
5782 refs -= refs_to_drop;
5786 __run_delayed_extent_op(extent_op, leaf, ei);
5788 * In the case of inline back ref, reference count will
5789 * be updated by remove_extent_backref
5792 BUG_ON(!found_extent);
5794 btrfs_set_extent_refs(leaf, ei, refs);
5795 btrfs_mark_buffer_dirty(leaf);
5798 ret = remove_extent_backref(trans, extent_root, path,
5802 btrfs_abort_transaction(trans, extent_root, ret);
5806 add_pinned_bytes(root->fs_info, -num_bytes, owner_objectid,
5810 BUG_ON(is_data && refs_to_drop !=
5811 extent_data_ref_count(root, path, iref));
5813 BUG_ON(path->slots[0] != extent_slot);
5815 BUG_ON(path->slots[0] != extent_slot + 1);
5816 path->slots[0] = extent_slot;
5821 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
5824 btrfs_abort_transaction(trans, extent_root, ret);
5827 btrfs_release_path(path);
5830 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
5832 btrfs_abort_transaction(trans, extent_root, ret);
5837 ret = update_block_group(root, bytenr, num_bytes, 0);
5839 btrfs_abort_transaction(trans, extent_root, ret);
5844 btrfs_free_path(path);
5849 * when we free an block, it is possible (and likely) that we free the last
5850 * delayed ref for that extent as well. This searches the delayed ref tree for
5851 * a given extent, and if there are no other delayed refs to be processed, it
5852 * removes it from the tree.
5854 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
5855 struct btrfs_root *root, u64 bytenr)
5857 struct btrfs_delayed_ref_head *head;
5858 struct btrfs_delayed_ref_root *delayed_refs;
5859 struct btrfs_delayed_ref_node *ref;
5860 struct rb_node *node;
5863 delayed_refs = &trans->transaction->delayed_refs;
5864 spin_lock(&delayed_refs->lock);
5865 head = btrfs_find_delayed_ref_head(trans, bytenr);
5869 node = rb_prev(&head->node.rb_node);
5873 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
5875 /* there are still entries for this ref, we can't drop it */
5876 if (ref->bytenr == bytenr)
5879 if (head->extent_op) {
5880 if (!head->must_insert_reserved)
5882 btrfs_free_delayed_extent_op(head->extent_op);
5883 head->extent_op = NULL;
5887 * waiting for the lock here would deadlock. If someone else has it
5888 * locked they are already in the process of dropping it anyway
5890 if (!mutex_trylock(&head->mutex))
5894 * at this point we have a head with no other entries. Go
5895 * ahead and process it.
5897 head->node.in_tree = 0;
5898 rb_erase(&head->node.rb_node, &delayed_refs->root);
5900 delayed_refs->num_entries--;
5903 * we don't take a ref on the node because we're removing it from the
5904 * tree, so we just steal the ref the tree was holding.
5906 delayed_refs->num_heads--;
5907 if (list_empty(&head->cluster))
5908 delayed_refs->num_heads_ready--;
5910 list_del_init(&head->cluster);
5911 spin_unlock(&delayed_refs->lock);
5913 BUG_ON(head->extent_op);
5914 if (head->must_insert_reserved)
5917 mutex_unlock(&head->mutex);
5918 btrfs_put_delayed_ref(&head->node);
5921 spin_unlock(&delayed_refs->lock);
5925 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
5926 struct btrfs_root *root,
5927 struct extent_buffer *buf,
5928 u64 parent, int last_ref)
5930 struct btrfs_block_group_cache *cache = NULL;
5934 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5935 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
5936 buf->start, buf->len,
5937 parent, root->root_key.objectid,
5938 btrfs_header_level(buf),
5939 BTRFS_DROP_DELAYED_REF, NULL, 0);
5940 BUG_ON(ret); /* -ENOMEM */
5946 cache = btrfs_lookup_block_group(root->fs_info, buf->start);
5948 if (btrfs_header_generation(buf) == trans->transid) {
5949 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5950 ret = check_ref_cleanup(trans, root, buf->start);
5955 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
5956 pin_down_extent(root, cache, buf->start, buf->len, 1);
5960 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
5962 btrfs_add_free_space(cache, buf->start, buf->len);
5963 btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE);
5968 add_pinned_bytes(root->fs_info, buf->len,
5969 btrfs_header_level(buf),
5970 root->root_key.objectid);
5973 * Deleting the buffer, clear the corrupt flag since it doesn't matter
5976 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
5977 btrfs_put_block_group(cache);
5980 /* Can return -ENOMEM */
5981 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5982 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
5983 u64 owner, u64 offset, int for_cow)
5986 struct btrfs_fs_info *fs_info = root->fs_info;
5988 add_pinned_bytes(root->fs_info, num_bytes, owner, root_objectid);
5991 * tree log blocks never actually go into the extent allocation
5992 * tree, just update pinning info and exit early.
5994 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
5995 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
5996 /* unlocks the pinned mutex */
5997 btrfs_pin_extent(root, bytenr, num_bytes, 1);
5999 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6000 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
6002 parent, root_objectid, (int)owner,
6003 BTRFS_DROP_DELAYED_REF, NULL, for_cow);
6005 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
6007 parent, root_objectid, owner,
6008 offset, BTRFS_DROP_DELAYED_REF,
6014 static u64 stripe_align(struct btrfs_root *root,
6015 struct btrfs_block_group_cache *cache,
6016 u64 val, u64 num_bytes)
6018 u64 ret = ALIGN(val, root->stripesize);
6023 * when we wait for progress in the block group caching, its because
6024 * our allocation attempt failed at least once. So, we must sleep
6025 * and let some progress happen before we try again.
6027 * This function will sleep at least once waiting for new free space to
6028 * show up, and then it will check the block group free space numbers
6029 * for our min num_bytes. Another option is to have it go ahead
6030 * and look in the rbtree for a free extent of a given size, but this
6034 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
6037 struct btrfs_caching_control *caching_ctl;
6039 caching_ctl = get_caching_control(cache);
6043 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
6044 (cache->free_space_ctl->free_space >= num_bytes));
6046 put_caching_control(caching_ctl);
6051 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
6053 struct btrfs_caching_control *caching_ctl;
6055 caching_ctl = get_caching_control(cache);
6059 wait_event(caching_ctl->wait, block_group_cache_done(cache));
6061 put_caching_control(caching_ctl);
6065 int __get_raid_index(u64 flags)
6067 if (flags & BTRFS_BLOCK_GROUP_RAID10)
6068 return BTRFS_RAID_RAID10;
6069 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
6070 return BTRFS_RAID_RAID1;
6071 else if (flags & BTRFS_BLOCK_GROUP_DUP)
6072 return BTRFS_RAID_DUP;
6073 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
6074 return BTRFS_RAID_RAID0;
6075 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
6076 return BTRFS_RAID_RAID5;
6077 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
6078 return BTRFS_RAID_RAID6;
6080 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
6083 static int get_block_group_index(struct btrfs_block_group_cache *cache)
6085 return __get_raid_index(cache->flags);
6088 enum btrfs_loop_type {
6089 LOOP_CACHING_NOWAIT = 0,
6090 LOOP_CACHING_WAIT = 1,
6091 LOOP_ALLOC_CHUNK = 2,
6092 LOOP_NO_EMPTY_SIZE = 3,
6096 * walks the btree of allocated extents and find a hole of a given size.
6097 * The key ins is changed to record the hole:
6098 * ins->objectid == block start
6099 * ins->flags = BTRFS_EXTENT_ITEM_KEY
6100 * ins->offset == number of blocks
6101 * Any available blocks before search_start are skipped.
6103 static noinline int find_free_extent(struct btrfs_trans_handle *trans,
6104 struct btrfs_root *orig_root,
6105 u64 num_bytes, u64 empty_size,
6106 u64 hint_byte, struct btrfs_key *ins,
6110 struct btrfs_root *root = orig_root->fs_info->extent_root;
6111 struct btrfs_free_cluster *last_ptr = NULL;
6112 struct btrfs_block_group_cache *block_group = NULL;
6113 struct btrfs_block_group_cache *used_block_group;
6114 u64 search_start = 0;
6115 int empty_cluster = 2 * 1024 * 1024;
6116 struct btrfs_space_info *space_info;
6118 int index = __get_raid_index(flags);
6119 int alloc_type = (flags & BTRFS_BLOCK_GROUP_DATA) ?
6120 RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
6121 bool found_uncached_bg = false;
6122 bool failed_cluster_refill = false;
6123 bool failed_alloc = false;
6124 bool use_cluster = true;
6125 bool have_caching_bg = false;
6127 WARN_ON(num_bytes < root->sectorsize);
6128 btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
6132 trace_find_free_extent(orig_root, num_bytes, empty_size, flags);
6134 space_info = __find_space_info(root->fs_info, flags);
6136 btrfs_err(root->fs_info, "No space info for %llu", flags);
6141 * If the space info is for both data and metadata it means we have a
6142 * small filesystem and we can't use the clustering stuff.
6144 if (btrfs_mixed_space_info(space_info))
6145 use_cluster = false;
6147 if (flags & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
6148 last_ptr = &root->fs_info->meta_alloc_cluster;
6149 if (!btrfs_test_opt(root, SSD))
6150 empty_cluster = 64 * 1024;
6153 if ((flags & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
6154 btrfs_test_opt(root, SSD)) {
6155 last_ptr = &root->fs_info->data_alloc_cluster;
6159 spin_lock(&last_ptr->lock);
6160 if (last_ptr->block_group)
6161 hint_byte = last_ptr->window_start;
6162 spin_unlock(&last_ptr->lock);
6165 search_start = max(search_start, first_logical_byte(root, 0));
6166 search_start = max(search_start, hint_byte);
6171 if (search_start == hint_byte) {
6172 block_group = btrfs_lookup_block_group(root->fs_info,
6174 used_block_group = block_group;
6176 * we don't want to use the block group if it doesn't match our
6177 * allocation bits, or if its not cached.
6179 * However if we are re-searching with an ideal block group
6180 * picked out then we don't care that the block group is cached.
6182 if (block_group && block_group_bits(block_group, flags) &&
6183 block_group->cached != BTRFS_CACHE_NO) {
6184 down_read(&space_info->groups_sem);
6185 if (list_empty(&block_group->list) ||
6188 * someone is removing this block group,
6189 * we can't jump into the have_block_group
6190 * target because our list pointers are not
6193 btrfs_put_block_group(block_group);
6194 up_read(&space_info->groups_sem);
6196 index = get_block_group_index(block_group);
6197 goto have_block_group;
6199 } else if (block_group) {
6200 btrfs_put_block_group(block_group);
6204 have_caching_bg = false;
6205 down_read(&space_info->groups_sem);
6206 list_for_each_entry(block_group, &space_info->block_groups[index],
6211 used_block_group = block_group;
6212 btrfs_get_block_group(block_group);
6213 search_start = block_group->key.objectid;
6216 * this can happen if we end up cycling through all the
6217 * raid types, but we want to make sure we only allocate
6218 * for the proper type.
6220 if (!block_group_bits(block_group, flags)) {
6221 u64 extra = BTRFS_BLOCK_GROUP_DUP |
6222 BTRFS_BLOCK_GROUP_RAID1 |
6223 BTRFS_BLOCK_GROUP_RAID5 |
6224 BTRFS_BLOCK_GROUP_RAID6 |
6225 BTRFS_BLOCK_GROUP_RAID10;
6228 * if they asked for extra copies and this block group
6229 * doesn't provide them, bail. This does allow us to
6230 * fill raid0 from raid1.
6232 if ((flags & extra) && !(block_group->flags & extra))
6237 cached = block_group_cache_done(block_group);
6238 if (unlikely(!cached)) {
6239 found_uncached_bg = true;
6240 ret = cache_block_group(block_group, 0);
6245 if (unlikely(block_group->ro))
6249 * Ok we want to try and use the cluster allocator, so
6253 unsigned long aligned_cluster;
6255 * the refill lock keeps out other
6256 * people trying to start a new cluster
6258 spin_lock(&last_ptr->refill_lock);
6259 used_block_group = last_ptr->block_group;
6260 if (used_block_group != block_group &&
6261 (!used_block_group ||
6262 used_block_group->ro ||
6263 !block_group_bits(used_block_group, flags))) {
6264 used_block_group = block_group;
6265 goto refill_cluster;
6268 if (used_block_group != block_group)
6269 btrfs_get_block_group(used_block_group);
6271 offset = btrfs_alloc_from_cluster(used_block_group,
6272 last_ptr, num_bytes, used_block_group->key.objectid);
6274 /* we have a block, we're done */
6275 spin_unlock(&last_ptr->refill_lock);
6276 trace_btrfs_reserve_extent_cluster(root,
6277 block_group, search_start, num_bytes);
6281 WARN_ON(last_ptr->block_group != used_block_group);
6282 if (used_block_group != block_group) {
6283 btrfs_put_block_group(used_block_group);
6284 used_block_group = block_group;
6287 BUG_ON(used_block_group != block_group);
6288 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
6289 * set up a new clusters, so lets just skip it
6290 * and let the allocator find whatever block
6291 * it can find. If we reach this point, we
6292 * will have tried the cluster allocator
6293 * plenty of times and not have found
6294 * anything, so we are likely way too
6295 * fragmented for the clustering stuff to find
6298 * However, if the cluster is taken from the
6299 * current block group, release the cluster
6300 * first, so that we stand a better chance of
6301 * succeeding in the unclustered
6303 if (loop >= LOOP_NO_EMPTY_SIZE &&
6304 last_ptr->block_group != block_group) {
6305 spin_unlock(&last_ptr->refill_lock);
6306 goto unclustered_alloc;
6310 * this cluster didn't work out, free it and
6313 btrfs_return_cluster_to_free_space(NULL, last_ptr);
6315 if (loop >= LOOP_NO_EMPTY_SIZE) {
6316 spin_unlock(&last_ptr->refill_lock);
6317 goto unclustered_alloc;
6320 aligned_cluster = max_t(unsigned long,
6321 empty_cluster + empty_size,
6322 block_group->full_stripe_len);
6324 /* allocate a cluster in this block group */
6325 ret = btrfs_find_space_cluster(trans, root,
6326 block_group, last_ptr,
6327 search_start, num_bytes,
6331 * now pull our allocation out of this
6334 offset = btrfs_alloc_from_cluster(block_group,
6335 last_ptr, num_bytes,
6338 /* we found one, proceed */
6339 spin_unlock(&last_ptr->refill_lock);
6340 trace_btrfs_reserve_extent_cluster(root,
6341 block_group, search_start,
6345 } else if (!cached && loop > LOOP_CACHING_NOWAIT
6346 && !failed_cluster_refill) {
6347 spin_unlock(&last_ptr->refill_lock);
6349 failed_cluster_refill = true;
6350 wait_block_group_cache_progress(block_group,
6351 num_bytes + empty_cluster + empty_size);
6352 goto have_block_group;
6356 * at this point we either didn't find a cluster
6357 * or we weren't able to allocate a block from our
6358 * cluster. Free the cluster we've been trying
6359 * to use, and go to the next block group
6361 btrfs_return_cluster_to_free_space(NULL, last_ptr);
6362 spin_unlock(&last_ptr->refill_lock);
6367 spin_lock(&block_group->free_space_ctl->tree_lock);
6369 block_group->free_space_ctl->free_space <
6370 num_bytes + empty_cluster + empty_size) {
6371 spin_unlock(&block_group->free_space_ctl->tree_lock);
6374 spin_unlock(&block_group->free_space_ctl->tree_lock);
6376 offset = btrfs_find_space_for_alloc(block_group, search_start,
6377 num_bytes, empty_size);
6379 * If we didn't find a chunk, and we haven't failed on this
6380 * block group before, and this block group is in the middle of
6381 * caching and we are ok with waiting, then go ahead and wait
6382 * for progress to be made, and set failed_alloc to true.
6384 * If failed_alloc is true then we've already waited on this
6385 * block group once and should move on to the next block group.
6387 if (!offset && !failed_alloc && !cached &&
6388 loop > LOOP_CACHING_NOWAIT) {
6389 wait_block_group_cache_progress(block_group,
6390 num_bytes + empty_size);
6391 failed_alloc = true;
6392 goto have_block_group;
6393 } else if (!offset) {
6395 have_caching_bg = true;
6399 search_start = stripe_align(root, used_block_group,
6402 /* move on to the next group */
6403 if (search_start + num_bytes >
6404 used_block_group->key.objectid + used_block_group->key.offset) {
6405 btrfs_add_free_space(used_block_group, offset, num_bytes);
6409 if (offset < search_start)
6410 btrfs_add_free_space(used_block_group, offset,
6411 search_start - offset);
6412 BUG_ON(offset > search_start);
6414 ret = btrfs_update_reserved_bytes(used_block_group, num_bytes,
6416 if (ret == -EAGAIN) {
6417 btrfs_add_free_space(used_block_group, offset, num_bytes);
6421 /* we are all good, lets return */
6422 ins->objectid = search_start;
6423 ins->offset = num_bytes;
6425 trace_btrfs_reserve_extent(orig_root, block_group,
6426 search_start, num_bytes);
6427 if (used_block_group != block_group)
6428 btrfs_put_block_group(used_block_group);
6429 btrfs_put_block_group(block_group);
6432 failed_cluster_refill = false;
6433 failed_alloc = false;
6434 BUG_ON(index != get_block_group_index(block_group));
6435 if (used_block_group != block_group)
6436 btrfs_put_block_group(used_block_group);
6437 btrfs_put_block_group(block_group);
6439 up_read(&space_info->groups_sem);
6441 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
6444 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
6448 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
6449 * caching kthreads as we move along
6450 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
6451 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
6452 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
6455 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
6458 if (loop == LOOP_ALLOC_CHUNK) {
6459 ret = do_chunk_alloc(trans, root, flags,
6462 * Do not bail out on ENOSPC since we
6463 * can do more things.
6465 if (ret < 0 && ret != -ENOSPC) {
6466 btrfs_abort_transaction(trans,
6472 if (loop == LOOP_NO_EMPTY_SIZE) {
6478 } else if (!ins->objectid) {
6480 } else if (ins->objectid) {
6488 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
6489 int dump_block_groups)
6491 struct btrfs_block_group_cache *cache;
6494 spin_lock(&info->lock);
6495 printk(KERN_INFO "space_info %llu has %llu free, is %sfull\n",
6496 (unsigned long long)info->flags,
6497 (unsigned long long)(info->total_bytes - info->bytes_used -
6498 info->bytes_pinned - info->bytes_reserved -
6499 info->bytes_readonly),
6500 (info->full) ? "" : "not ");
6501 printk(KERN_INFO "space_info total=%llu, used=%llu, pinned=%llu, "
6502 "reserved=%llu, may_use=%llu, readonly=%llu\n",
6503 (unsigned long long)info->total_bytes,
6504 (unsigned long long)info->bytes_used,
6505 (unsigned long long)info->bytes_pinned,
6506 (unsigned long long)info->bytes_reserved,
6507 (unsigned long long)info->bytes_may_use,
6508 (unsigned long long)info->bytes_readonly);
6509 spin_unlock(&info->lock);
6511 if (!dump_block_groups)
6514 down_read(&info->groups_sem);
6516 list_for_each_entry(cache, &info->block_groups[index], list) {
6517 spin_lock(&cache->lock);
6518 printk(KERN_INFO "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s\n",
6519 (unsigned long long)cache->key.objectid,
6520 (unsigned long long)cache->key.offset,
6521 (unsigned long long)btrfs_block_group_used(&cache->item),
6522 (unsigned long long)cache->pinned,
6523 (unsigned long long)cache->reserved,
6524 cache->ro ? "[readonly]" : "");
6525 btrfs_dump_free_space(cache, bytes);
6526 spin_unlock(&cache->lock);
6528 if (++index < BTRFS_NR_RAID_TYPES)
6530 up_read(&info->groups_sem);
6533 int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
6534 struct btrfs_root *root,
6535 u64 num_bytes, u64 min_alloc_size,
6536 u64 empty_size, u64 hint_byte,
6537 struct btrfs_key *ins, int is_data)
6539 bool final_tried = false;
6543 flags = btrfs_get_alloc_profile(root, is_data);
6545 WARN_ON(num_bytes < root->sectorsize);
6546 ret = find_free_extent(trans, root, num_bytes, empty_size,
6547 hint_byte, ins, flags);
6549 if (ret == -ENOSPC) {
6551 num_bytes = num_bytes >> 1;
6552 num_bytes = round_down(num_bytes, root->sectorsize);
6553 num_bytes = max(num_bytes, min_alloc_size);
6554 if (num_bytes == min_alloc_size)
6557 } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
6558 struct btrfs_space_info *sinfo;
6560 sinfo = __find_space_info(root->fs_info, flags);
6561 btrfs_err(root->fs_info, "allocation failed flags %llu, wanted %llu",
6562 (unsigned long long)flags,
6563 (unsigned long long)num_bytes);
6565 dump_space_info(sinfo, num_bytes, 1);
6569 trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
6574 static int __btrfs_free_reserved_extent(struct btrfs_root *root,
6575 u64 start, u64 len, int pin)
6577 struct btrfs_block_group_cache *cache;
6580 cache = btrfs_lookup_block_group(root->fs_info, start);
6582 btrfs_err(root->fs_info, "Unable to find block group for %llu",
6583 (unsigned long long)start);
6587 if (btrfs_test_opt(root, DISCARD))
6588 ret = btrfs_discard_extent(root, start, len, NULL);
6591 pin_down_extent(root, cache, start, len, 1);
6593 btrfs_add_free_space(cache, start, len);
6594 btrfs_update_reserved_bytes(cache, len, RESERVE_FREE);
6596 btrfs_put_block_group(cache);
6598 trace_btrfs_reserved_extent_free(root, start, len);
6603 int btrfs_free_reserved_extent(struct btrfs_root *root,
6606 return __btrfs_free_reserved_extent(root, start, len, 0);
6609 int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
6612 return __btrfs_free_reserved_extent(root, start, len, 1);
6615 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6616 struct btrfs_root *root,
6617 u64 parent, u64 root_objectid,
6618 u64 flags, u64 owner, u64 offset,
6619 struct btrfs_key *ins, int ref_mod)
6622 struct btrfs_fs_info *fs_info = root->fs_info;
6623 struct btrfs_extent_item *extent_item;
6624 struct btrfs_extent_inline_ref *iref;
6625 struct btrfs_path *path;
6626 struct extent_buffer *leaf;
6631 type = BTRFS_SHARED_DATA_REF_KEY;
6633 type = BTRFS_EXTENT_DATA_REF_KEY;
6635 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
6637 path = btrfs_alloc_path();
6641 path->leave_spinning = 1;
6642 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6645 btrfs_free_path(path);
6649 leaf = path->nodes[0];
6650 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6651 struct btrfs_extent_item);
6652 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
6653 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6654 btrfs_set_extent_flags(leaf, extent_item,
6655 flags | BTRFS_EXTENT_FLAG_DATA);
6657 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6658 btrfs_set_extent_inline_ref_type(leaf, iref, type);
6660 struct btrfs_shared_data_ref *ref;
6661 ref = (struct btrfs_shared_data_ref *)(iref + 1);
6662 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6663 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
6665 struct btrfs_extent_data_ref *ref;
6666 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
6667 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
6668 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
6669 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
6670 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
6673 btrfs_mark_buffer_dirty(path->nodes[0]);
6674 btrfs_free_path(path);
6676 ret = update_block_group(root, ins->objectid, ins->offset, 1);
6677 if (ret) { /* -ENOENT, logic error */
6678 btrfs_err(fs_info, "update block group failed for %llu %llu",
6679 (unsigned long long)ins->objectid,
6680 (unsigned long long)ins->offset);
6686 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
6687 struct btrfs_root *root,
6688 u64 parent, u64 root_objectid,
6689 u64 flags, struct btrfs_disk_key *key,
6690 int level, struct btrfs_key *ins)
6693 struct btrfs_fs_info *fs_info = root->fs_info;
6694 struct btrfs_extent_item *extent_item;
6695 struct btrfs_tree_block_info *block_info;
6696 struct btrfs_extent_inline_ref *iref;
6697 struct btrfs_path *path;
6698 struct extent_buffer *leaf;
6699 u32 size = sizeof(*extent_item) + sizeof(*iref);
6700 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
6703 if (!skinny_metadata)
6704 size += sizeof(*block_info);
6706 path = btrfs_alloc_path();
6710 path->leave_spinning = 1;
6711 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6714 btrfs_free_path(path);
6718 leaf = path->nodes[0];
6719 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6720 struct btrfs_extent_item);
6721 btrfs_set_extent_refs(leaf, extent_item, 1);
6722 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6723 btrfs_set_extent_flags(leaf, extent_item,
6724 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
6726 if (skinny_metadata) {
6727 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6729 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
6730 btrfs_set_tree_block_key(leaf, block_info, key);
6731 btrfs_set_tree_block_level(leaf, block_info, level);
6732 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
6736 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
6737 btrfs_set_extent_inline_ref_type(leaf, iref,
6738 BTRFS_SHARED_BLOCK_REF_KEY);
6739 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6741 btrfs_set_extent_inline_ref_type(leaf, iref,
6742 BTRFS_TREE_BLOCK_REF_KEY);
6743 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
6746 btrfs_mark_buffer_dirty(leaf);
6747 btrfs_free_path(path);
6749 ret = update_block_group(root, ins->objectid, root->leafsize, 1);
6750 if (ret) { /* -ENOENT, logic error */
6751 btrfs_err(fs_info, "update block group failed for %llu %llu",
6752 (unsigned long long)ins->objectid,
6753 (unsigned long long)ins->offset);
6759 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6760 struct btrfs_root *root,
6761 u64 root_objectid, u64 owner,
6762 u64 offset, struct btrfs_key *ins)
6766 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
6768 ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
6770 root_objectid, owner, offset,
6771 BTRFS_ADD_DELAYED_EXTENT, NULL, 0);
6776 * this is used by the tree logging recovery code. It records that
6777 * an extent has been allocated and makes sure to clear the free
6778 * space cache bits as well
6780 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
6781 struct btrfs_root *root,
6782 u64 root_objectid, u64 owner, u64 offset,
6783 struct btrfs_key *ins)
6786 struct btrfs_block_group_cache *block_group;
6789 * Mixed block groups will exclude before processing the log so we only
6790 * need to do the exlude dance if this fs isn't mixed.
6792 if (!btrfs_fs_incompat(root->fs_info, MIXED_GROUPS)) {
6793 ret = __exclude_logged_extent(root, ins->objectid, ins->offset);
6798 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
6802 ret = btrfs_update_reserved_bytes(block_group, ins->offset,
6803 RESERVE_ALLOC_NO_ACCOUNT);
6804 BUG_ON(ret); /* logic error */
6805 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
6806 0, owner, offset, ins, 1);
6807 btrfs_put_block_group(block_group);
6811 static struct extent_buffer *
6812 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
6813 u64 bytenr, u32 blocksize, int level)
6815 struct extent_buffer *buf;
6817 buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
6819 return ERR_PTR(-ENOMEM);
6820 btrfs_set_header_generation(buf, trans->transid);
6821 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
6822 btrfs_tree_lock(buf);
6823 clean_tree_block(trans, root, buf);
6824 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
6826 btrfs_set_lock_blocking(buf);
6827 btrfs_set_buffer_uptodate(buf);
6829 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
6831 * we allow two log transactions at a time, use different
6832 * EXENT bit to differentiate dirty pages.
6834 if (root->log_transid % 2 == 0)
6835 set_extent_dirty(&root->dirty_log_pages, buf->start,
6836 buf->start + buf->len - 1, GFP_NOFS);
6838 set_extent_new(&root->dirty_log_pages, buf->start,
6839 buf->start + buf->len - 1, GFP_NOFS);
6841 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
6842 buf->start + buf->len - 1, GFP_NOFS);
6844 trans->blocks_used++;
6845 /* this returns a buffer locked for blocking */
6849 static struct btrfs_block_rsv *
6850 use_block_rsv(struct btrfs_trans_handle *trans,
6851 struct btrfs_root *root, u32 blocksize)
6853 struct btrfs_block_rsv *block_rsv;
6854 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
6856 bool global_updated = false;
6858 block_rsv = get_block_rsv(trans, root);
6860 if (unlikely(block_rsv->size == 0))
6863 ret = block_rsv_use_bytes(block_rsv, blocksize);
6867 if (block_rsv->failfast)
6868 return ERR_PTR(ret);
6870 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
6871 global_updated = true;
6872 update_global_block_rsv(root->fs_info);
6876 if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
6877 static DEFINE_RATELIMIT_STATE(_rs,
6878 DEFAULT_RATELIMIT_INTERVAL * 10,
6879 /*DEFAULT_RATELIMIT_BURST*/ 1);
6880 if (__ratelimit(&_rs))
6882 "btrfs: block rsv returned %d\n", ret);
6885 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
6886 BTRFS_RESERVE_NO_FLUSH);
6890 * If we couldn't reserve metadata bytes try and use some from
6891 * the global reserve if its space type is the same as the global
6894 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
6895 block_rsv->space_info == global_rsv->space_info) {
6896 ret = block_rsv_use_bytes(global_rsv, blocksize);
6900 return ERR_PTR(ret);
6903 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
6904 struct btrfs_block_rsv *block_rsv, u32 blocksize)
6906 block_rsv_add_bytes(block_rsv, blocksize, 0);
6907 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
6911 * finds a free extent and does all the dirty work required for allocation
6912 * returns the key for the extent through ins, and a tree buffer for
6913 * the first block of the extent through buf.
6915 * returns the tree buffer or NULL.
6917 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
6918 struct btrfs_root *root, u32 blocksize,
6919 u64 parent, u64 root_objectid,
6920 struct btrfs_disk_key *key, int level,
6921 u64 hint, u64 empty_size)
6923 struct btrfs_key ins;
6924 struct btrfs_block_rsv *block_rsv;
6925 struct extent_buffer *buf;
6928 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
6931 block_rsv = use_block_rsv(trans, root, blocksize);
6932 if (IS_ERR(block_rsv))
6933 return ERR_CAST(block_rsv);
6935 ret = btrfs_reserve_extent(trans, root, blocksize, blocksize,
6936 empty_size, hint, &ins, 0);
6938 unuse_block_rsv(root->fs_info, block_rsv, blocksize);
6939 return ERR_PTR(ret);
6942 buf = btrfs_init_new_buffer(trans, root, ins.objectid,
6944 BUG_ON(IS_ERR(buf)); /* -ENOMEM */
6946 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
6948 parent = ins.objectid;
6949 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6953 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
6954 struct btrfs_delayed_extent_op *extent_op;
6955 extent_op = btrfs_alloc_delayed_extent_op();
6956 BUG_ON(!extent_op); /* -ENOMEM */
6958 memcpy(&extent_op->key, key, sizeof(extent_op->key));
6960 memset(&extent_op->key, 0, sizeof(extent_op->key));
6961 extent_op->flags_to_set = flags;
6962 if (skinny_metadata)
6963 extent_op->update_key = 0;
6965 extent_op->update_key = 1;
6966 extent_op->update_flags = 1;
6967 extent_op->is_data = 0;
6968 extent_op->level = level;
6970 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
6972 ins.offset, parent, root_objectid,
6973 level, BTRFS_ADD_DELAYED_EXTENT,
6975 BUG_ON(ret); /* -ENOMEM */
6980 struct walk_control {
6981 u64 refs[BTRFS_MAX_LEVEL];
6982 u64 flags[BTRFS_MAX_LEVEL];
6983 struct btrfs_key update_progress;
6994 #define DROP_REFERENCE 1
6995 #define UPDATE_BACKREF 2
6997 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
6998 struct btrfs_root *root,
6999 struct walk_control *wc,
7000 struct btrfs_path *path)
7008 struct btrfs_key key;
7009 struct extent_buffer *eb;
7014 if (path->slots[wc->level] < wc->reada_slot) {
7015 wc->reada_count = wc->reada_count * 2 / 3;
7016 wc->reada_count = max(wc->reada_count, 2);
7018 wc->reada_count = wc->reada_count * 3 / 2;
7019 wc->reada_count = min_t(int, wc->reada_count,
7020 BTRFS_NODEPTRS_PER_BLOCK(root));
7023 eb = path->nodes[wc->level];
7024 nritems = btrfs_header_nritems(eb);
7025 blocksize = btrfs_level_size(root, wc->level - 1);
7027 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
7028 if (nread >= wc->reada_count)
7032 bytenr = btrfs_node_blockptr(eb, slot);
7033 generation = btrfs_node_ptr_generation(eb, slot);
7035 if (slot == path->slots[wc->level])
7038 if (wc->stage == UPDATE_BACKREF &&
7039 generation <= root->root_key.offset)
7042 /* We don't lock the tree block, it's OK to be racy here */
7043 ret = btrfs_lookup_extent_info(trans, root, bytenr,
7044 wc->level - 1, 1, &refs,
7046 /* We don't care about errors in readahead. */
7051 if (wc->stage == DROP_REFERENCE) {
7055 if (wc->level == 1 &&
7056 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7058 if (!wc->update_ref ||
7059 generation <= root->root_key.offset)
7061 btrfs_node_key_to_cpu(eb, &key, slot);
7062 ret = btrfs_comp_cpu_keys(&key,
7063 &wc->update_progress);
7067 if (wc->level == 1 &&
7068 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7072 ret = readahead_tree_block(root, bytenr, blocksize,
7078 wc->reada_slot = slot;
7082 * helper to process tree block while walking down the tree.
7084 * when wc->stage == UPDATE_BACKREF, this function updates
7085 * back refs for pointers in the block.
7087 * NOTE: return value 1 means we should stop walking down.
7089 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
7090 struct btrfs_root *root,
7091 struct btrfs_path *path,
7092 struct walk_control *wc, int lookup_info)
7094 int level = wc->level;
7095 struct extent_buffer *eb = path->nodes[level];
7096 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7099 if (wc->stage == UPDATE_BACKREF &&
7100 btrfs_header_owner(eb) != root->root_key.objectid)
7104 * when reference count of tree block is 1, it won't increase
7105 * again. once full backref flag is set, we never clear it.
7108 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
7109 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
7110 BUG_ON(!path->locks[level]);
7111 ret = btrfs_lookup_extent_info(trans, root,
7112 eb->start, level, 1,
7115 BUG_ON(ret == -ENOMEM);
7118 BUG_ON(wc->refs[level] == 0);
7121 if (wc->stage == DROP_REFERENCE) {
7122 if (wc->refs[level] > 1)
7125 if (path->locks[level] && !wc->keep_locks) {
7126 btrfs_tree_unlock_rw(eb, path->locks[level]);
7127 path->locks[level] = 0;
7132 /* wc->stage == UPDATE_BACKREF */
7133 if (!(wc->flags[level] & flag)) {
7134 BUG_ON(!path->locks[level]);
7135 ret = btrfs_inc_ref(trans, root, eb, 1, wc->for_reloc);
7136 BUG_ON(ret); /* -ENOMEM */
7137 ret = btrfs_dec_ref(trans, root, eb, 0, wc->for_reloc);
7138 BUG_ON(ret); /* -ENOMEM */
7139 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
7141 btrfs_header_level(eb), 0);
7142 BUG_ON(ret); /* -ENOMEM */
7143 wc->flags[level] |= flag;
7147 * the block is shared by multiple trees, so it's not good to
7148 * keep the tree lock
7150 if (path->locks[level] && level > 0) {
7151 btrfs_tree_unlock_rw(eb, path->locks[level]);
7152 path->locks[level] = 0;
7158 * helper to process tree block pointer.
7160 * when wc->stage == DROP_REFERENCE, this function checks
7161 * reference count of the block pointed to. if the block
7162 * is shared and we need update back refs for the subtree
7163 * rooted at the block, this function changes wc->stage to
7164 * UPDATE_BACKREF. if the block is shared and there is no
7165 * need to update back, this function drops the reference
7168 * NOTE: return value 1 means we should stop walking down.
7170 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
7171 struct btrfs_root *root,
7172 struct btrfs_path *path,
7173 struct walk_control *wc, int *lookup_info)
7179 struct btrfs_key key;
7180 struct extent_buffer *next;
7181 int level = wc->level;
7185 generation = btrfs_node_ptr_generation(path->nodes[level],
7186 path->slots[level]);
7188 * if the lower level block was created before the snapshot
7189 * was created, we know there is no need to update back refs
7192 if (wc->stage == UPDATE_BACKREF &&
7193 generation <= root->root_key.offset) {
7198 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
7199 blocksize = btrfs_level_size(root, level - 1);
7201 next = btrfs_find_tree_block(root, bytenr, blocksize);
7203 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
7206 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
7210 btrfs_tree_lock(next);
7211 btrfs_set_lock_blocking(next);
7213 ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
7214 &wc->refs[level - 1],
7215 &wc->flags[level - 1]);
7217 btrfs_tree_unlock(next);
7221 if (unlikely(wc->refs[level - 1] == 0)) {
7222 btrfs_err(root->fs_info, "Missing references.");
7227 if (wc->stage == DROP_REFERENCE) {
7228 if (wc->refs[level - 1] > 1) {
7230 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7233 if (!wc->update_ref ||
7234 generation <= root->root_key.offset)
7237 btrfs_node_key_to_cpu(path->nodes[level], &key,
7238 path->slots[level]);
7239 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
7243 wc->stage = UPDATE_BACKREF;
7244 wc->shared_level = level - 1;
7248 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7252 if (!btrfs_buffer_uptodate(next, generation, 0)) {
7253 btrfs_tree_unlock(next);
7254 free_extent_buffer(next);
7260 if (reada && level == 1)
7261 reada_walk_down(trans, root, wc, path);
7262 next = read_tree_block(root, bytenr, blocksize, generation);
7263 if (!next || !extent_buffer_uptodate(next)) {
7264 free_extent_buffer(next);
7267 btrfs_tree_lock(next);
7268 btrfs_set_lock_blocking(next);
7272 BUG_ON(level != btrfs_header_level(next));
7273 path->nodes[level] = next;
7274 path->slots[level] = 0;
7275 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7281 wc->refs[level - 1] = 0;
7282 wc->flags[level - 1] = 0;
7283 if (wc->stage == DROP_REFERENCE) {
7284 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
7285 parent = path->nodes[level]->start;
7287 BUG_ON(root->root_key.objectid !=
7288 btrfs_header_owner(path->nodes[level]));
7292 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
7293 root->root_key.objectid, level - 1, 0, 0);
7294 BUG_ON(ret); /* -ENOMEM */
7296 btrfs_tree_unlock(next);
7297 free_extent_buffer(next);
7303 * helper to process tree block while walking up the tree.
7305 * when wc->stage == DROP_REFERENCE, this function drops
7306 * reference count on the block.
7308 * when wc->stage == UPDATE_BACKREF, this function changes
7309 * wc->stage back to DROP_REFERENCE if we changed wc->stage
7310 * to UPDATE_BACKREF previously while processing the block.
7312 * NOTE: return value 1 means we should stop walking up.
7314 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
7315 struct btrfs_root *root,
7316 struct btrfs_path *path,
7317 struct walk_control *wc)
7320 int level = wc->level;
7321 struct extent_buffer *eb = path->nodes[level];
7324 if (wc->stage == UPDATE_BACKREF) {
7325 BUG_ON(wc->shared_level < level);
7326 if (level < wc->shared_level)
7329 ret = find_next_key(path, level + 1, &wc->update_progress);
7333 wc->stage = DROP_REFERENCE;
7334 wc->shared_level = -1;
7335 path->slots[level] = 0;
7338 * check reference count again if the block isn't locked.
7339 * we should start walking down the tree again if reference
7342 if (!path->locks[level]) {
7344 btrfs_tree_lock(eb);
7345 btrfs_set_lock_blocking(eb);
7346 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7348 ret = btrfs_lookup_extent_info(trans, root,
7349 eb->start, level, 1,
7353 btrfs_tree_unlock_rw(eb, path->locks[level]);
7354 path->locks[level] = 0;
7357 BUG_ON(wc->refs[level] == 0);
7358 if (wc->refs[level] == 1) {
7359 btrfs_tree_unlock_rw(eb, path->locks[level]);
7360 path->locks[level] = 0;
7366 /* wc->stage == DROP_REFERENCE */
7367 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
7369 if (wc->refs[level] == 1) {
7371 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7372 ret = btrfs_dec_ref(trans, root, eb, 1,
7375 ret = btrfs_dec_ref(trans, root, eb, 0,
7377 BUG_ON(ret); /* -ENOMEM */
7379 /* make block locked assertion in clean_tree_block happy */
7380 if (!path->locks[level] &&
7381 btrfs_header_generation(eb) == trans->transid) {
7382 btrfs_tree_lock(eb);
7383 btrfs_set_lock_blocking(eb);
7384 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7386 clean_tree_block(trans, root, eb);
7389 if (eb == root->node) {
7390 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7393 BUG_ON(root->root_key.objectid !=
7394 btrfs_header_owner(eb));
7396 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7397 parent = path->nodes[level + 1]->start;
7399 BUG_ON(root->root_key.objectid !=
7400 btrfs_header_owner(path->nodes[level + 1]));
7403 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
7405 wc->refs[level] = 0;
7406 wc->flags[level] = 0;
7410 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
7411 struct btrfs_root *root,
7412 struct btrfs_path *path,
7413 struct walk_control *wc)
7415 int level = wc->level;
7416 int lookup_info = 1;
7419 while (level >= 0) {
7420 ret = walk_down_proc(trans, root, path, wc, lookup_info);
7427 if (path->slots[level] >=
7428 btrfs_header_nritems(path->nodes[level]))
7431 ret = do_walk_down(trans, root, path, wc, &lookup_info);
7433 path->slots[level]++;
7442 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
7443 struct btrfs_root *root,
7444 struct btrfs_path *path,
7445 struct walk_control *wc, int max_level)
7447 int level = wc->level;
7450 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
7451 while (level < max_level && path->nodes[level]) {
7453 if (path->slots[level] + 1 <
7454 btrfs_header_nritems(path->nodes[level])) {
7455 path->slots[level]++;
7458 ret = walk_up_proc(trans, root, path, wc);
7462 if (path->locks[level]) {
7463 btrfs_tree_unlock_rw(path->nodes[level],
7464 path->locks[level]);
7465 path->locks[level] = 0;
7467 free_extent_buffer(path->nodes[level]);
7468 path->nodes[level] = NULL;
7476 * drop a subvolume tree.
7478 * this function traverses the tree freeing any blocks that only
7479 * referenced by the tree.
7481 * when a shared tree block is found. this function decreases its
7482 * reference count by one. if update_ref is true, this function
7483 * also make sure backrefs for the shared block and all lower level
7484 * blocks are properly updated.
7486 * If called with for_reloc == 0, may exit early with -EAGAIN
7488 int btrfs_drop_snapshot(struct btrfs_root *root,
7489 struct btrfs_block_rsv *block_rsv, int update_ref,
7492 struct btrfs_path *path;
7493 struct btrfs_trans_handle *trans;
7494 struct btrfs_root *tree_root = root->fs_info->tree_root;
7495 struct btrfs_root_item *root_item = &root->root_item;
7496 struct walk_control *wc;
7497 struct btrfs_key key;
7501 bool root_dropped = false;
7503 path = btrfs_alloc_path();
7509 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7511 btrfs_free_path(path);
7516 trans = btrfs_start_transaction(tree_root, 0);
7517 if (IS_ERR(trans)) {
7518 err = PTR_ERR(trans);
7523 trans->block_rsv = block_rsv;
7525 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
7526 level = btrfs_header_level(root->node);
7527 path->nodes[level] = btrfs_lock_root_node(root);
7528 btrfs_set_lock_blocking(path->nodes[level]);
7529 path->slots[level] = 0;
7530 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7531 memset(&wc->update_progress, 0,
7532 sizeof(wc->update_progress));
7534 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
7535 memcpy(&wc->update_progress, &key,
7536 sizeof(wc->update_progress));
7538 level = root_item->drop_level;
7540 path->lowest_level = level;
7541 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7542 path->lowest_level = 0;
7550 * unlock our path, this is safe because only this
7551 * function is allowed to delete this snapshot
7553 btrfs_unlock_up_safe(path, 0);
7555 level = btrfs_header_level(root->node);
7557 btrfs_tree_lock(path->nodes[level]);
7558 btrfs_set_lock_blocking(path->nodes[level]);
7559 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7561 ret = btrfs_lookup_extent_info(trans, root,
7562 path->nodes[level]->start,
7563 level, 1, &wc->refs[level],
7569 BUG_ON(wc->refs[level] == 0);
7571 if (level == root_item->drop_level)
7574 btrfs_tree_unlock(path->nodes[level]);
7575 path->locks[level] = 0;
7576 WARN_ON(wc->refs[level] != 1);
7582 wc->shared_level = -1;
7583 wc->stage = DROP_REFERENCE;
7584 wc->update_ref = update_ref;
7586 wc->for_reloc = for_reloc;
7587 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
7591 ret = walk_down_tree(trans, root, path, wc);
7597 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
7604 BUG_ON(wc->stage != DROP_REFERENCE);
7608 if (wc->stage == DROP_REFERENCE) {
7610 btrfs_node_key(path->nodes[level],
7611 &root_item->drop_progress,
7612 path->slots[level]);
7613 root_item->drop_level = level;
7616 BUG_ON(wc->level == 0);
7617 if (btrfs_should_end_transaction(trans, tree_root) ||
7618 (!for_reloc && btrfs_need_cleaner_sleep(root))) {
7619 ret = btrfs_update_root(trans, tree_root,
7623 btrfs_abort_transaction(trans, tree_root, ret);
7628 btrfs_end_transaction_throttle(trans, tree_root);
7629 if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
7630 pr_debug("btrfs: drop snapshot early exit\n");
7635 trans = btrfs_start_transaction(tree_root, 0);
7636 if (IS_ERR(trans)) {
7637 err = PTR_ERR(trans);
7641 trans->block_rsv = block_rsv;
7644 btrfs_release_path(path);
7648 ret = btrfs_del_root(trans, tree_root, &root->root_key);
7650 btrfs_abort_transaction(trans, tree_root, ret);
7654 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
7655 ret = btrfs_find_root(tree_root, &root->root_key, path,
7658 btrfs_abort_transaction(trans, tree_root, ret);
7661 } else if (ret > 0) {
7662 /* if we fail to delete the orphan item this time
7663 * around, it'll get picked up the next time.
7665 * The most common failure here is just -ENOENT.
7667 btrfs_del_orphan_item(trans, tree_root,
7668 root->root_key.objectid);
7672 if (root->in_radix) {
7673 btrfs_drop_and_free_fs_root(tree_root->fs_info, root);
7675 free_extent_buffer(root->node);
7676 free_extent_buffer(root->commit_root);
7677 btrfs_put_fs_root(root);
7679 root_dropped = true;
7681 btrfs_end_transaction_throttle(trans, tree_root);
7684 btrfs_free_path(path);
7687 * So if we need to stop dropping the snapshot for whatever reason we
7688 * need to make sure to add it back to the dead root list so that we
7689 * keep trying to do the work later. This also cleans up roots if we
7690 * don't have it in the radix (like when we recover after a power fail
7691 * or unmount) so we don't leak memory.
7693 if (root_dropped == false)
7694 btrfs_add_dead_root(root);
7696 btrfs_std_error(root->fs_info, err);
7701 * drop subtree rooted at tree block 'node'.
7703 * NOTE: this function will unlock and release tree block 'node'
7704 * only used by relocation code
7706 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
7707 struct btrfs_root *root,
7708 struct extent_buffer *node,
7709 struct extent_buffer *parent)
7711 struct btrfs_path *path;
7712 struct walk_control *wc;
7718 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7720 path = btrfs_alloc_path();
7724 wc = kzalloc(sizeof(*wc), GFP_NOFS);
7726 btrfs_free_path(path);
7730 btrfs_assert_tree_locked(parent);
7731 parent_level = btrfs_header_level(parent);
7732 extent_buffer_get(parent);
7733 path->nodes[parent_level] = parent;
7734 path->slots[parent_level] = btrfs_header_nritems(parent);
7736 btrfs_assert_tree_locked(node);
7737 level = btrfs_header_level(node);
7738 path->nodes[level] = node;
7739 path->slots[level] = 0;
7740 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7742 wc->refs[parent_level] = 1;
7743 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7745 wc->shared_level = -1;
7746 wc->stage = DROP_REFERENCE;
7750 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
7753 wret = walk_down_tree(trans, root, path, wc);
7759 wret = walk_up_tree(trans, root, path, wc, parent_level);
7767 btrfs_free_path(path);
7771 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
7777 * if restripe for this chunk_type is on pick target profile and
7778 * return, otherwise do the usual balance
7780 stripped = get_restripe_target(root->fs_info, flags);
7782 return extended_to_chunk(stripped);
7785 * we add in the count of missing devices because we want
7786 * to make sure that any RAID levels on a degraded FS
7787 * continue to be honored.
7789 num_devices = root->fs_info->fs_devices->rw_devices +
7790 root->fs_info->fs_devices->missing_devices;
7792 stripped = BTRFS_BLOCK_GROUP_RAID0 |
7793 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
7794 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
7796 if (num_devices == 1) {
7797 stripped |= BTRFS_BLOCK_GROUP_DUP;
7798 stripped = flags & ~stripped;
7800 /* turn raid0 into single device chunks */
7801 if (flags & BTRFS_BLOCK_GROUP_RAID0)
7804 /* turn mirroring into duplication */
7805 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
7806 BTRFS_BLOCK_GROUP_RAID10))
7807 return stripped | BTRFS_BLOCK_GROUP_DUP;
7809 /* they already had raid on here, just return */
7810 if (flags & stripped)
7813 stripped |= BTRFS_BLOCK_GROUP_DUP;
7814 stripped = flags & ~stripped;
7816 /* switch duplicated blocks with raid1 */
7817 if (flags & BTRFS_BLOCK_GROUP_DUP)
7818 return stripped | BTRFS_BLOCK_GROUP_RAID1;
7820 /* this is drive concat, leave it alone */
7826 static int set_block_group_ro(struct btrfs_block_group_cache *cache, int force)
7828 struct btrfs_space_info *sinfo = cache->space_info;
7830 u64 min_allocable_bytes;
7835 * We need some metadata space and system metadata space for
7836 * allocating chunks in some corner cases until we force to set
7837 * it to be readonly.
7840 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
7842 min_allocable_bytes = 1 * 1024 * 1024;
7844 min_allocable_bytes = 0;
7846 spin_lock(&sinfo->lock);
7847 spin_lock(&cache->lock);
7854 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7855 cache->bytes_super - btrfs_block_group_used(&cache->item);
7857 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
7858 sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
7859 min_allocable_bytes <= sinfo->total_bytes) {
7860 sinfo->bytes_readonly += num_bytes;
7865 spin_unlock(&cache->lock);
7866 spin_unlock(&sinfo->lock);
7870 int btrfs_set_block_group_ro(struct btrfs_root *root,
7871 struct btrfs_block_group_cache *cache)
7874 struct btrfs_trans_handle *trans;
7880 trans = btrfs_join_transaction(root);
7882 return PTR_ERR(trans);
7884 alloc_flags = update_block_group_flags(root, cache->flags);
7885 if (alloc_flags != cache->flags) {
7886 ret = do_chunk_alloc(trans, root, alloc_flags,
7892 ret = set_block_group_ro(cache, 0);
7895 alloc_flags = get_alloc_profile(root, cache->space_info->flags);
7896 ret = do_chunk_alloc(trans, root, alloc_flags,
7900 ret = set_block_group_ro(cache, 0);
7902 btrfs_end_transaction(trans, root);
7906 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
7907 struct btrfs_root *root, u64 type)
7909 u64 alloc_flags = get_alloc_profile(root, type);
7910 return do_chunk_alloc(trans, root, alloc_flags,
7915 * helper to account the unused space of all the readonly block group in the
7916 * list. takes mirrors into account.
7918 static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
7920 struct btrfs_block_group_cache *block_group;
7924 list_for_each_entry(block_group, groups_list, list) {
7925 spin_lock(&block_group->lock);
7927 if (!block_group->ro) {
7928 spin_unlock(&block_group->lock);
7932 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
7933 BTRFS_BLOCK_GROUP_RAID10 |
7934 BTRFS_BLOCK_GROUP_DUP))
7939 free_bytes += (block_group->key.offset -
7940 btrfs_block_group_used(&block_group->item)) *
7943 spin_unlock(&block_group->lock);
7950 * helper to account the unused space of all the readonly block group in the
7951 * space_info. takes mirrors into account.
7953 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
7958 spin_lock(&sinfo->lock);
7960 for(i = 0; i < BTRFS_NR_RAID_TYPES; i++)
7961 if (!list_empty(&sinfo->block_groups[i]))
7962 free_bytes += __btrfs_get_ro_block_group_free_space(
7963 &sinfo->block_groups[i]);
7965 spin_unlock(&sinfo->lock);
7970 void btrfs_set_block_group_rw(struct btrfs_root *root,
7971 struct btrfs_block_group_cache *cache)
7973 struct btrfs_space_info *sinfo = cache->space_info;
7978 spin_lock(&sinfo->lock);
7979 spin_lock(&cache->lock);
7980 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7981 cache->bytes_super - btrfs_block_group_used(&cache->item);
7982 sinfo->bytes_readonly -= num_bytes;
7984 spin_unlock(&cache->lock);
7985 spin_unlock(&sinfo->lock);
7989 * checks to see if its even possible to relocate this block group.
7991 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
7992 * ok to go ahead and try.
7994 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
7996 struct btrfs_block_group_cache *block_group;
7997 struct btrfs_space_info *space_info;
7998 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
7999 struct btrfs_device *device;
8000 struct btrfs_trans_handle *trans;
8009 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
8011 /* odd, couldn't find the block group, leave it alone */
8015 min_free = btrfs_block_group_used(&block_group->item);
8017 /* no bytes used, we're good */
8021 space_info = block_group->space_info;
8022 spin_lock(&space_info->lock);
8024 full = space_info->full;
8027 * if this is the last block group we have in this space, we can't
8028 * relocate it unless we're able to allocate a new chunk below.
8030 * Otherwise, we need to make sure we have room in the space to handle
8031 * all of the extents from this block group. If we can, we're good
8033 if ((space_info->total_bytes != block_group->key.offset) &&
8034 (space_info->bytes_used + space_info->bytes_reserved +
8035 space_info->bytes_pinned + space_info->bytes_readonly +
8036 min_free < space_info->total_bytes)) {
8037 spin_unlock(&space_info->lock);
8040 spin_unlock(&space_info->lock);
8043 * ok we don't have enough space, but maybe we have free space on our
8044 * devices to allocate new chunks for relocation, so loop through our
8045 * alloc devices and guess if we have enough space. if this block
8046 * group is going to be restriped, run checks against the target
8047 * profile instead of the current one.
8059 target = get_restripe_target(root->fs_info, block_group->flags);
8061 index = __get_raid_index(extended_to_chunk(target));
8064 * this is just a balance, so if we were marked as full
8065 * we know there is no space for a new chunk
8070 index = get_block_group_index(block_group);
8073 if (index == BTRFS_RAID_RAID10) {
8077 } else if (index == BTRFS_RAID_RAID1) {
8079 } else if (index == BTRFS_RAID_DUP) {
8082 } else if (index == BTRFS_RAID_RAID0) {
8083 dev_min = fs_devices->rw_devices;
8084 do_div(min_free, dev_min);
8087 /* We need to do this so that we can look at pending chunks */
8088 trans = btrfs_join_transaction(root);
8089 if (IS_ERR(trans)) {
8090 ret = PTR_ERR(trans);
8094 mutex_lock(&root->fs_info->chunk_mutex);
8095 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
8099 * check to make sure we can actually find a chunk with enough
8100 * space to fit our block group in.
8102 if (device->total_bytes > device->bytes_used + min_free &&
8103 !device->is_tgtdev_for_dev_replace) {
8104 ret = find_free_dev_extent(trans, device, min_free,
8109 if (dev_nr >= dev_min)
8115 mutex_unlock(&root->fs_info->chunk_mutex);
8116 btrfs_end_transaction(trans, root);
8118 btrfs_put_block_group(block_group);
8122 static int find_first_block_group(struct btrfs_root *root,
8123 struct btrfs_path *path, struct btrfs_key *key)
8126 struct btrfs_key found_key;
8127 struct extent_buffer *leaf;
8130 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
8135 slot = path->slots[0];
8136 leaf = path->nodes[0];
8137 if (slot >= btrfs_header_nritems(leaf)) {
8138 ret = btrfs_next_leaf(root, path);
8145 btrfs_item_key_to_cpu(leaf, &found_key, slot);
8147 if (found_key.objectid >= key->objectid &&
8148 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
8158 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
8160 struct btrfs_block_group_cache *block_group;
8164 struct inode *inode;
8166 block_group = btrfs_lookup_first_block_group(info, last);
8167 while (block_group) {
8168 spin_lock(&block_group->lock);
8169 if (block_group->iref)
8171 spin_unlock(&block_group->lock);
8172 block_group = next_block_group(info->tree_root,
8182 inode = block_group->inode;
8183 block_group->iref = 0;
8184 block_group->inode = NULL;
8185 spin_unlock(&block_group->lock);
8187 last = block_group->key.objectid + block_group->key.offset;
8188 btrfs_put_block_group(block_group);
8192 int btrfs_free_block_groups(struct btrfs_fs_info *info)
8194 struct btrfs_block_group_cache *block_group;
8195 struct btrfs_space_info *space_info;
8196 struct btrfs_caching_control *caching_ctl;
8199 down_write(&info->extent_commit_sem);
8200 while (!list_empty(&info->caching_block_groups)) {
8201 caching_ctl = list_entry(info->caching_block_groups.next,
8202 struct btrfs_caching_control, list);
8203 list_del(&caching_ctl->list);
8204 put_caching_control(caching_ctl);
8206 up_write(&info->extent_commit_sem);
8208 spin_lock(&info->block_group_cache_lock);
8209 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
8210 block_group = rb_entry(n, struct btrfs_block_group_cache,
8212 rb_erase(&block_group->cache_node,
8213 &info->block_group_cache_tree);
8214 spin_unlock(&info->block_group_cache_lock);
8216 down_write(&block_group->space_info->groups_sem);
8217 list_del(&block_group->list);
8218 up_write(&block_group->space_info->groups_sem);
8220 if (block_group->cached == BTRFS_CACHE_STARTED)
8221 wait_block_group_cache_done(block_group);
8224 * We haven't cached this block group, which means we could
8225 * possibly have excluded extents on this block group.
8227 if (block_group->cached == BTRFS_CACHE_NO)
8228 free_excluded_extents(info->extent_root, block_group);
8230 btrfs_remove_free_space_cache(block_group);
8231 btrfs_put_block_group(block_group);
8233 spin_lock(&info->block_group_cache_lock);
8235 spin_unlock(&info->block_group_cache_lock);
8237 /* now that all the block groups are freed, go through and
8238 * free all the space_info structs. This is only called during
8239 * the final stages of unmount, and so we know nobody is
8240 * using them. We call synchronize_rcu() once before we start,
8241 * just to be on the safe side.
8245 release_global_block_rsv(info);
8247 while(!list_empty(&info->space_info)) {
8248 space_info = list_entry(info->space_info.next,
8249 struct btrfs_space_info,
8251 if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
8252 if (space_info->bytes_pinned > 0 ||
8253 space_info->bytes_reserved > 0 ||
8254 space_info->bytes_may_use > 0) {
8256 dump_space_info(space_info, 0, 0);
8259 percpu_counter_destroy(&space_info->total_bytes_pinned);
8260 list_del(&space_info->list);
8266 static void __link_block_group(struct btrfs_space_info *space_info,
8267 struct btrfs_block_group_cache *cache)
8269 int index = get_block_group_index(cache);
8271 down_write(&space_info->groups_sem);
8272 list_add_tail(&cache->list, &space_info->block_groups[index]);
8273 up_write(&space_info->groups_sem);
8276 int btrfs_read_block_groups(struct btrfs_root *root)
8278 struct btrfs_path *path;
8280 struct btrfs_block_group_cache *cache;
8281 struct btrfs_fs_info *info = root->fs_info;
8282 struct btrfs_space_info *space_info;
8283 struct btrfs_key key;
8284 struct btrfs_key found_key;
8285 struct extent_buffer *leaf;
8289 root = info->extent_root;
8292 btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
8293 path = btrfs_alloc_path();
8298 cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
8299 if (btrfs_test_opt(root, SPACE_CACHE) &&
8300 btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
8302 if (btrfs_test_opt(root, CLEAR_CACHE))
8306 ret = find_first_block_group(root, path, &key);
8311 leaf = path->nodes[0];
8312 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8313 cache = kzalloc(sizeof(*cache), GFP_NOFS);
8318 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
8320 if (!cache->free_space_ctl) {
8326 atomic_set(&cache->count, 1);
8327 spin_lock_init(&cache->lock);
8328 cache->fs_info = info;
8329 INIT_LIST_HEAD(&cache->list);
8330 INIT_LIST_HEAD(&cache->cluster_list);
8334 * When we mount with old space cache, we need to
8335 * set BTRFS_DC_CLEAR and set dirty flag.
8337 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
8338 * truncate the old free space cache inode and
8340 * b) Setting 'dirty flag' makes sure that we flush
8341 * the new space cache info onto disk.
8343 cache->disk_cache_state = BTRFS_DC_CLEAR;
8344 if (btrfs_test_opt(root, SPACE_CACHE))
8348 read_extent_buffer(leaf, &cache->item,
8349 btrfs_item_ptr_offset(leaf, path->slots[0]),
8350 sizeof(cache->item));
8351 memcpy(&cache->key, &found_key, sizeof(found_key));
8353 key.objectid = found_key.objectid + found_key.offset;
8354 btrfs_release_path(path);
8355 cache->flags = btrfs_block_group_flags(&cache->item);
8356 cache->sectorsize = root->sectorsize;
8357 cache->full_stripe_len = btrfs_full_stripe_len(root,
8358 &root->fs_info->mapping_tree,
8359 found_key.objectid);
8360 btrfs_init_free_space_ctl(cache);
8363 * We need to exclude the super stripes now so that the space
8364 * info has super bytes accounted for, otherwise we'll think
8365 * we have more space than we actually do.
8367 ret = exclude_super_stripes(root, cache);
8370 * We may have excluded something, so call this just in
8373 free_excluded_extents(root, cache);
8374 kfree(cache->free_space_ctl);
8380 * check for two cases, either we are full, and therefore
8381 * don't need to bother with the caching work since we won't
8382 * find any space, or we are empty, and we can just add all
8383 * the space in and be done with it. This saves us _alot_ of
8384 * time, particularly in the full case.
8386 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
8387 cache->last_byte_to_unpin = (u64)-1;
8388 cache->cached = BTRFS_CACHE_FINISHED;
8389 free_excluded_extents(root, cache);
8390 } else if (btrfs_block_group_used(&cache->item) == 0) {
8391 cache->last_byte_to_unpin = (u64)-1;
8392 cache->cached = BTRFS_CACHE_FINISHED;
8393 add_new_free_space(cache, root->fs_info,
8395 found_key.objectid +
8397 free_excluded_extents(root, cache);
8400 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8402 btrfs_remove_free_space_cache(cache);
8403 btrfs_put_block_group(cache);
8407 ret = update_space_info(info, cache->flags, found_key.offset,
8408 btrfs_block_group_used(&cache->item),
8411 btrfs_remove_free_space_cache(cache);
8412 spin_lock(&info->block_group_cache_lock);
8413 rb_erase(&cache->cache_node,
8414 &info->block_group_cache_tree);
8415 spin_unlock(&info->block_group_cache_lock);
8416 btrfs_put_block_group(cache);
8420 cache->space_info = space_info;
8421 spin_lock(&cache->space_info->lock);
8422 cache->space_info->bytes_readonly += cache->bytes_super;
8423 spin_unlock(&cache->space_info->lock);
8425 __link_block_group(space_info, cache);
8427 set_avail_alloc_bits(root->fs_info, cache->flags);
8428 if (btrfs_chunk_readonly(root, cache->key.objectid))
8429 set_block_group_ro(cache, 1);
8432 list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
8433 if (!(get_alloc_profile(root, space_info->flags) &
8434 (BTRFS_BLOCK_GROUP_RAID10 |
8435 BTRFS_BLOCK_GROUP_RAID1 |
8436 BTRFS_BLOCK_GROUP_RAID5 |
8437 BTRFS_BLOCK_GROUP_RAID6 |
8438 BTRFS_BLOCK_GROUP_DUP)))
8441 * avoid allocating from un-mirrored block group if there are
8442 * mirrored block groups.
8444 list_for_each_entry(cache, &space_info->block_groups[3], list)
8445 set_block_group_ro(cache, 1);
8446 list_for_each_entry(cache, &space_info->block_groups[4], list)
8447 set_block_group_ro(cache, 1);
8450 init_global_block_rsv(info);
8453 btrfs_free_path(path);
8457 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
8458 struct btrfs_root *root)
8460 struct btrfs_block_group_cache *block_group, *tmp;
8461 struct btrfs_root *extent_root = root->fs_info->extent_root;
8462 struct btrfs_block_group_item item;
8463 struct btrfs_key key;
8466 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs,
8468 list_del_init(&block_group->new_bg_list);
8473 spin_lock(&block_group->lock);
8474 memcpy(&item, &block_group->item, sizeof(item));
8475 memcpy(&key, &block_group->key, sizeof(key));
8476 spin_unlock(&block_group->lock);
8478 ret = btrfs_insert_item(trans, extent_root, &key, &item,
8481 btrfs_abort_transaction(trans, extent_root, ret);
8482 ret = btrfs_finish_chunk_alloc(trans, extent_root,
8483 key.objectid, key.offset);
8485 btrfs_abort_transaction(trans, extent_root, ret);
8489 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
8490 struct btrfs_root *root, u64 bytes_used,
8491 u64 type, u64 chunk_objectid, u64 chunk_offset,
8495 struct btrfs_root *extent_root;
8496 struct btrfs_block_group_cache *cache;
8498 extent_root = root->fs_info->extent_root;
8500 root->fs_info->last_trans_log_full_commit = trans->transid;
8502 cache = kzalloc(sizeof(*cache), GFP_NOFS);
8505 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
8507 if (!cache->free_space_ctl) {
8512 cache->key.objectid = chunk_offset;
8513 cache->key.offset = size;
8514 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8515 cache->sectorsize = root->sectorsize;
8516 cache->fs_info = root->fs_info;
8517 cache->full_stripe_len = btrfs_full_stripe_len(root,
8518 &root->fs_info->mapping_tree,
8521 atomic_set(&cache->count, 1);
8522 spin_lock_init(&cache->lock);
8523 INIT_LIST_HEAD(&cache->list);
8524 INIT_LIST_HEAD(&cache->cluster_list);
8525 INIT_LIST_HEAD(&cache->new_bg_list);
8527 btrfs_init_free_space_ctl(cache);
8529 btrfs_set_block_group_used(&cache->item, bytes_used);
8530 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
8531 cache->flags = type;
8532 btrfs_set_block_group_flags(&cache->item, type);
8534 cache->last_byte_to_unpin = (u64)-1;
8535 cache->cached = BTRFS_CACHE_FINISHED;
8536 ret = exclude_super_stripes(root, cache);
8539 * We may have excluded something, so call this just in
8542 free_excluded_extents(root, cache);
8543 kfree(cache->free_space_ctl);
8548 add_new_free_space(cache, root->fs_info, chunk_offset,
8549 chunk_offset + size);
8551 free_excluded_extents(root, cache);
8553 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8555 btrfs_remove_free_space_cache(cache);
8556 btrfs_put_block_group(cache);
8560 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
8561 &cache->space_info);
8563 btrfs_remove_free_space_cache(cache);
8564 spin_lock(&root->fs_info->block_group_cache_lock);
8565 rb_erase(&cache->cache_node,
8566 &root->fs_info->block_group_cache_tree);
8567 spin_unlock(&root->fs_info->block_group_cache_lock);
8568 btrfs_put_block_group(cache);
8571 update_global_block_rsv(root->fs_info);
8573 spin_lock(&cache->space_info->lock);
8574 cache->space_info->bytes_readonly += cache->bytes_super;
8575 spin_unlock(&cache->space_info->lock);
8577 __link_block_group(cache->space_info, cache);
8579 list_add_tail(&cache->new_bg_list, &trans->new_bgs);
8581 set_avail_alloc_bits(extent_root->fs_info, type);
8586 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
8588 u64 extra_flags = chunk_to_extended(flags) &
8589 BTRFS_EXTENDED_PROFILE_MASK;
8591 write_seqlock(&fs_info->profiles_lock);
8592 if (flags & BTRFS_BLOCK_GROUP_DATA)
8593 fs_info->avail_data_alloc_bits &= ~extra_flags;
8594 if (flags & BTRFS_BLOCK_GROUP_METADATA)
8595 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
8596 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
8597 fs_info->avail_system_alloc_bits &= ~extra_flags;
8598 write_sequnlock(&fs_info->profiles_lock);
8601 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8602 struct btrfs_root *root, u64 group_start)
8604 struct btrfs_path *path;
8605 struct btrfs_block_group_cache *block_group;
8606 struct btrfs_free_cluster *cluster;
8607 struct btrfs_root *tree_root = root->fs_info->tree_root;
8608 struct btrfs_key key;
8609 struct inode *inode;
8614 root = root->fs_info->extent_root;
8616 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
8617 BUG_ON(!block_group);
8618 BUG_ON(!block_group->ro);
8621 * Free the reserved super bytes from this block group before
8624 free_excluded_extents(root, block_group);
8626 memcpy(&key, &block_group->key, sizeof(key));
8627 index = get_block_group_index(block_group);
8628 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
8629 BTRFS_BLOCK_GROUP_RAID1 |
8630 BTRFS_BLOCK_GROUP_RAID10))
8635 /* make sure this block group isn't part of an allocation cluster */
8636 cluster = &root->fs_info->data_alloc_cluster;
8637 spin_lock(&cluster->refill_lock);
8638 btrfs_return_cluster_to_free_space(block_group, cluster);
8639 spin_unlock(&cluster->refill_lock);
8642 * make sure this block group isn't part of a metadata
8643 * allocation cluster
8645 cluster = &root->fs_info->meta_alloc_cluster;
8646 spin_lock(&cluster->refill_lock);
8647 btrfs_return_cluster_to_free_space(block_group, cluster);
8648 spin_unlock(&cluster->refill_lock);
8650 path = btrfs_alloc_path();
8656 inode = lookup_free_space_inode(tree_root, block_group, path);
8657 if (!IS_ERR(inode)) {
8658 ret = btrfs_orphan_add(trans, inode);
8660 btrfs_add_delayed_iput(inode);
8664 /* One for the block groups ref */
8665 spin_lock(&block_group->lock);
8666 if (block_group->iref) {
8667 block_group->iref = 0;
8668 block_group->inode = NULL;
8669 spin_unlock(&block_group->lock);
8672 spin_unlock(&block_group->lock);
8674 /* One for our lookup ref */
8675 btrfs_add_delayed_iput(inode);
8678 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8679 key.offset = block_group->key.objectid;
8682 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8686 btrfs_release_path(path);
8688 ret = btrfs_del_item(trans, tree_root, path);
8691 btrfs_release_path(path);
8694 spin_lock(&root->fs_info->block_group_cache_lock);
8695 rb_erase(&block_group->cache_node,
8696 &root->fs_info->block_group_cache_tree);
8698 if (root->fs_info->first_logical_byte == block_group->key.objectid)
8699 root->fs_info->first_logical_byte = (u64)-1;
8700 spin_unlock(&root->fs_info->block_group_cache_lock);
8702 down_write(&block_group->space_info->groups_sem);
8704 * we must use list_del_init so people can check to see if they
8705 * are still on the list after taking the semaphore
8707 list_del_init(&block_group->list);
8708 if (list_empty(&block_group->space_info->block_groups[index]))
8709 clear_avail_alloc_bits(root->fs_info, block_group->flags);
8710 up_write(&block_group->space_info->groups_sem);
8712 if (block_group->cached == BTRFS_CACHE_STARTED)
8713 wait_block_group_cache_done(block_group);
8715 btrfs_remove_free_space_cache(block_group);
8717 spin_lock(&block_group->space_info->lock);
8718 block_group->space_info->total_bytes -= block_group->key.offset;
8719 block_group->space_info->bytes_readonly -= block_group->key.offset;
8720 block_group->space_info->disk_total -= block_group->key.offset * factor;
8721 spin_unlock(&block_group->space_info->lock);
8723 memcpy(&key, &block_group->key, sizeof(key));
8725 btrfs_clear_space_info_full(root->fs_info);
8727 btrfs_put_block_group(block_group);
8728 btrfs_put_block_group(block_group);
8730 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8736 ret = btrfs_del_item(trans, root, path);
8738 btrfs_free_path(path);
8742 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
8744 struct btrfs_space_info *space_info;
8745 struct btrfs_super_block *disk_super;
8751 disk_super = fs_info->super_copy;
8752 if (!btrfs_super_root(disk_super))
8755 features = btrfs_super_incompat_flags(disk_super);
8756 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
8759 flags = BTRFS_BLOCK_GROUP_SYSTEM;
8760 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8765 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
8766 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8768 flags = BTRFS_BLOCK_GROUP_METADATA;
8769 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8773 flags = BTRFS_BLOCK_GROUP_DATA;
8774 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8780 int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
8782 return unpin_extent_range(root, start, end);
8785 int btrfs_error_discard_extent(struct btrfs_root *root, u64 bytenr,
8786 u64 num_bytes, u64 *actual_bytes)
8788 return btrfs_discard_extent(root, bytenr, num_bytes, actual_bytes);
8791 int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
8793 struct btrfs_fs_info *fs_info = root->fs_info;
8794 struct btrfs_block_group_cache *cache = NULL;
8799 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
8803 * try to trim all FS space, our block group may start from non-zero.
8805 if (range->len == total_bytes)
8806 cache = btrfs_lookup_first_block_group(fs_info, range->start);
8808 cache = btrfs_lookup_block_group(fs_info, range->start);
8811 if (cache->key.objectid >= (range->start + range->len)) {
8812 btrfs_put_block_group(cache);
8816 start = max(range->start, cache->key.objectid);
8817 end = min(range->start + range->len,
8818 cache->key.objectid + cache->key.offset);
8820 if (end - start >= range->minlen) {
8821 if (!block_group_cache_done(cache)) {
8822 ret = cache_block_group(cache, 0);
8824 btrfs_put_block_group(cache);
8827 ret = wait_block_group_cache_done(cache);
8829 btrfs_put_block_group(cache);
8833 ret = btrfs_trim_block_group(cache,
8839 trimmed += group_trimmed;
8841 btrfs_put_block_group(cache);
8846 cache = next_block_group(fs_info->tree_root, cache);
8849 range->len = trimmed;