xref: /openbmc/linux/fs/btrfs/free-space-cache.c (revision 278002edb19bce2c628fafb0af936e77000f3a5b)
1c1d7c514SDavid Sterba // SPDX-License-Identifier: GPL-2.0
20f9dd46cSJosef Bacik /*
30f9dd46cSJosef Bacik  * Copyright (C) 2008 Red Hat.  All rights reserved.
40f9dd46cSJosef Bacik  */
50f9dd46cSJosef Bacik 
696303081SJosef Bacik #include <linux/pagemap.h>
70f9dd46cSJosef Bacik #include <linux/sched.h>
8f361bf4aSIngo Molnar #include <linux/sched/signal.h>
95a0e3ad6STejun Heo #include <linux/slab.h>
1096303081SJosef Bacik #include <linux/math64.h>
116ab60601SJosef Bacik #include <linux/ratelimit.h>
12540adea3SMasami Hiramatsu #include <linux/error-injection.h>
1384de76a2SJosef Bacik #include <linux/sched/mm.h>
14ec8eb376SJosef Bacik #include "ctree.h"
15ec8eb376SJosef Bacik #include "fs.h"
169b569ea0SJosef Bacik #include "messages.h"
1718bb8bbfSJohannes Thumshirn #include "misc.h"
18fa9c0d79SChris Mason #include "free-space-cache.h"
19fa9c0d79SChris Mason #include "transaction.h"
200af3d00bSJosef Bacik #include "disk-io.h"
2143be2146SJosef Bacik #include "extent_io.h"
2204216820SFilipe Manana #include "volumes.h"
238719aaaeSJosef Bacik #include "space-info.h"
2486736342SJosef Bacik #include "delalloc-space.h"
25aac0023cSJosef Bacik #include "block-group.h"
26b0643e59SDennis Zhou #include "discard.h"
27e4f94347SQu Wenruo #include "subpage.h"
2826c2c454SJosef Bacik #include "inode-item.h"
2907e81dc9SJosef Bacik #include "accessors.h"
307c8ede16SJosef Bacik #include "file-item.h"
31af142b6fSJosef Bacik #include "file.h"
327f0add25SJosef Bacik #include "super.h"
33fa9c0d79SChris Mason 
340ef6447aSFeifei Xu #define BITS_PER_BITMAP		(PAGE_SIZE * 8UL)
355d90c5c7SDennis Zhou #define MAX_CACHE_BYTES_PER_GIG	SZ_64K
365d90c5c7SDennis Zhou #define FORCE_EXTENT_THRESHOLD	SZ_1M
3796303081SJosef Bacik 
38eda517fdSJosef Bacik static struct kmem_cache *btrfs_free_space_cachep;
39eda517fdSJosef Bacik static struct kmem_cache *btrfs_free_space_bitmap_cachep;
40eda517fdSJosef Bacik 
4155507ce3SFilipe Manana struct btrfs_trim_range {
4255507ce3SFilipe Manana 	u64 start;
4355507ce3SFilipe Manana 	u64 bytes;
4455507ce3SFilipe Manana 	struct list_head list;
4555507ce3SFilipe Manana };
4655507ce3SFilipe Manana 
4734d52cb6SLi Zefan static int link_free_space(struct btrfs_free_space_ctl *ctl,
480cb59c99SJosef Bacik 			   struct btrfs_free_space *info);
49cd023e7bSJosef Bacik static void unlink_free_space(struct btrfs_free_space_ctl *ctl,
5032e1649bSNikolay Borisov 			      struct btrfs_free_space *info, bool update_stat);
51cd79909bSJosef Bacik static int search_bitmap(struct btrfs_free_space_ctl *ctl,
52cd79909bSJosef Bacik 			 struct btrfs_free_space *bitmap_info, u64 *offset,
53cd79909bSJosef Bacik 			 u64 *bytes, bool for_alloc);
54cd79909bSJosef Bacik static void free_bitmap(struct btrfs_free_space_ctl *ctl,
55cd79909bSJosef Bacik 			struct btrfs_free_space *bitmap_info);
56cd79909bSJosef Bacik static void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
57cd79909bSJosef Bacik 			      struct btrfs_free_space *info, u64 offset,
58f594f13cSNikolay Borisov 			      u64 bytes, bool update_stats);
590cb59c99SJosef Bacik 
__btrfs_remove_free_space_cache(struct btrfs_free_space_ctl * ctl)60fc80f7acSJosef Bacik static void __btrfs_remove_free_space_cache(struct btrfs_free_space_ctl *ctl)
618a1ae278SJosef Bacik {
628a1ae278SJosef Bacik 	struct btrfs_free_space *info;
638a1ae278SJosef Bacik 	struct rb_node *node;
648a1ae278SJosef Bacik 
658a1ae278SJosef Bacik 	while ((node = rb_last(&ctl->free_space_offset)) != NULL) {
668a1ae278SJosef Bacik 		info = rb_entry(node, struct btrfs_free_space, offset_index);
678a1ae278SJosef Bacik 		if (!info->bitmap) {
688a1ae278SJosef Bacik 			unlink_free_space(ctl, info, true);
698a1ae278SJosef Bacik 			kmem_cache_free(btrfs_free_space_cachep, info);
708a1ae278SJosef Bacik 		} else {
718a1ae278SJosef Bacik 			free_bitmap(ctl, info);
728a1ae278SJosef Bacik 		}
738a1ae278SJosef Bacik 
748a1ae278SJosef Bacik 		cond_resched_lock(&ctl->tree_lock);
758a1ae278SJosef Bacik 	}
768a1ae278SJosef Bacik }
778a1ae278SJosef Bacik 
__lookup_free_space_inode(struct btrfs_root * root,struct btrfs_path * path,u64 offset)780414efaeSLi Zefan static struct inode *__lookup_free_space_inode(struct btrfs_root *root,
790414efaeSLi Zefan 					       struct btrfs_path *path,
800414efaeSLi Zefan 					       u64 offset)
810af3d00bSJosef Bacik {
820b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = root->fs_info;
830af3d00bSJosef Bacik 	struct btrfs_key key;
840af3d00bSJosef Bacik 	struct btrfs_key location;
850af3d00bSJosef Bacik 	struct btrfs_disk_key disk_key;
860af3d00bSJosef Bacik 	struct btrfs_free_space_header *header;
870af3d00bSJosef Bacik 	struct extent_buffer *leaf;
880af3d00bSJosef Bacik 	struct inode *inode = NULL;
8984de76a2SJosef Bacik 	unsigned nofs_flag;
900af3d00bSJosef Bacik 	int ret;
910af3d00bSJosef Bacik 
920af3d00bSJosef Bacik 	key.objectid = BTRFS_FREE_SPACE_OBJECTID;
930414efaeSLi Zefan 	key.offset = offset;
940af3d00bSJosef Bacik 	key.type = 0;
950af3d00bSJosef Bacik 
960af3d00bSJosef Bacik 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
970af3d00bSJosef Bacik 	if (ret < 0)
980af3d00bSJosef Bacik 		return ERR_PTR(ret);
990af3d00bSJosef Bacik 	if (ret > 0) {
100b3b4aa74SDavid Sterba 		btrfs_release_path(path);
1010af3d00bSJosef Bacik 		return ERR_PTR(-ENOENT);
1020af3d00bSJosef Bacik 	}
1030af3d00bSJosef Bacik 
1040af3d00bSJosef Bacik 	leaf = path->nodes[0];
1050af3d00bSJosef Bacik 	header = btrfs_item_ptr(leaf, path->slots[0],
1060af3d00bSJosef Bacik 				struct btrfs_free_space_header);
1070af3d00bSJosef Bacik 	btrfs_free_space_key(leaf, header, &disk_key);
1080af3d00bSJosef Bacik 	btrfs_disk_key_to_cpu(&location, &disk_key);
109b3b4aa74SDavid Sterba 	btrfs_release_path(path);
1100af3d00bSJosef Bacik 
11184de76a2SJosef Bacik 	/*
11284de76a2SJosef Bacik 	 * We are often under a trans handle at this point, so we need to make
11384de76a2SJosef Bacik 	 * sure NOFS is set to keep us from deadlocking.
11484de76a2SJosef Bacik 	 */
11584de76a2SJosef Bacik 	nofs_flag = memalloc_nofs_save();
1160202e83fSDavid Sterba 	inode = btrfs_iget_path(fs_info->sb, location.objectid, root, path);
1174222ea71SFilipe Manana 	btrfs_release_path(path);
11884de76a2SJosef Bacik 	memalloc_nofs_restore(nofs_flag);
1190af3d00bSJosef Bacik 	if (IS_ERR(inode))
1200af3d00bSJosef Bacik 		return inode;
1210af3d00bSJosef Bacik 
122528c0327SAl Viro 	mapping_set_gfp_mask(inode->i_mapping,
123c62d2555SMichal Hocko 			mapping_gfp_constraint(inode->i_mapping,
124c62d2555SMichal Hocko 			~(__GFP_FS | __GFP_HIGHMEM)));
125adae52b9SMiao Xie 
1260414efaeSLi Zefan 	return inode;
1270414efaeSLi Zefan }
1280414efaeSLi Zefan 
lookup_free_space_inode(struct btrfs_block_group * block_group,struct btrfs_path * path)12932da5386SDavid Sterba struct inode *lookup_free_space_inode(struct btrfs_block_group *block_group,
1307949f339SDavid Sterba 		struct btrfs_path *path)
1310414efaeSLi Zefan {
1327949f339SDavid Sterba 	struct btrfs_fs_info *fs_info = block_group->fs_info;
1330414efaeSLi Zefan 	struct inode *inode = NULL;
1345b0e95bfSJosef Bacik 	u32 flags = BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW;
1350414efaeSLi Zefan 
1360414efaeSLi Zefan 	spin_lock(&block_group->lock);
1370414efaeSLi Zefan 	if (block_group->inode)
1380414efaeSLi Zefan 		inode = igrab(block_group->inode);
1390414efaeSLi Zefan 	spin_unlock(&block_group->lock);
1400414efaeSLi Zefan 	if (inode)
1410414efaeSLi Zefan 		return inode;
1420414efaeSLi Zefan 
14377ab86bfSJeff Mahoney 	inode = __lookup_free_space_inode(fs_info->tree_root, path,
144b3470b5dSDavid Sterba 					  block_group->start);
1450414efaeSLi Zefan 	if (IS_ERR(inode))
1460414efaeSLi Zefan 		return inode;
1470414efaeSLi Zefan 
1480af3d00bSJosef Bacik 	spin_lock(&block_group->lock);
1495b0e95bfSJosef Bacik 	if (!((BTRFS_I(inode)->flags & flags) == flags)) {
1500b246afaSJeff Mahoney 		btrfs_info(fs_info, "Old style space inode found, converting.");
1515b0e95bfSJosef Bacik 		BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM |
1525b0e95bfSJosef Bacik 			BTRFS_INODE_NODATACOW;
1532f356126SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_CLEAR;
1542f356126SJosef Bacik 	}
1552f356126SJosef Bacik 
1563349b57fSJosef Bacik 	if (!test_and_set_bit(BLOCK_GROUP_FLAG_IREF, &block_group->runtime_flags))
1570af3d00bSJosef Bacik 		block_group->inode = igrab(inode);
1580af3d00bSJosef Bacik 	spin_unlock(&block_group->lock);
1590af3d00bSJosef Bacik 
1600af3d00bSJosef Bacik 	return inode;
1610af3d00bSJosef Bacik }
1620af3d00bSJosef Bacik 
__create_free_space_inode(struct btrfs_root * root,struct btrfs_trans_handle * trans,struct btrfs_path * path,u64 ino,u64 offset)16348a3b636SEric Sandeen static int __create_free_space_inode(struct btrfs_root *root,
1640af3d00bSJosef Bacik 				     struct btrfs_trans_handle *trans,
16548a3b636SEric Sandeen 				     struct btrfs_path *path,
16648a3b636SEric Sandeen 				     u64 ino, u64 offset)
1670af3d00bSJosef Bacik {
1680af3d00bSJosef Bacik 	struct btrfs_key key;
1690af3d00bSJosef Bacik 	struct btrfs_disk_key disk_key;
1700af3d00bSJosef Bacik 	struct btrfs_free_space_header *header;
1710af3d00bSJosef Bacik 	struct btrfs_inode_item *inode_item;
1720af3d00bSJosef Bacik 	struct extent_buffer *leaf;
173f0d1219dSNikolay Borisov 	/* We inline CRCs for the free disk space cache */
174f0d1219dSNikolay Borisov 	const u64 flags = BTRFS_INODE_NOCOMPRESS | BTRFS_INODE_PREALLOC |
175f0d1219dSNikolay Borisov 			  BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW;
1760af3d00bSJosef Bacik 	int ret;
1770af3d00bSJosef Bacik 
1780414efaeSLi Zefan 	ret = btrfs_insert_empty_inode(trans, root, path, ino);
1790af3d00bSJosef Bacik 	if (ret)
1800af3d00bSJosef Bacik 		return ret;
1810af3d00bSJosef Bacik 
1820af3d00bSJosef Bacik 	leaf = path->nodes[0];
1830af3d00bSJosef Bacik 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
1840af3d00bSJosef Bacik 				    struct btrfs_inode_item);
1850af3d00bSJosef Bacik 	btrfs_item_key(leaf, &disk_key, path->slots[0]);
186b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, (unsigned long)inode_item,
1870af3d00bSJosef Bacik 			     sizeof(*inode_item));
1880af3d00bSJosef Bacik 	btrfs_set_inode_generation(leaf, inode_item, trans->transid);
1890af3d00bSJosef Bacik 	btrfs_set_inode_size(leaf, inode_item, 0);
1900af3d00bSJosef Bacik 	btrfs_set_inode_nbytes(leaf, inode_item, 0);
1910af3d00bSJosef Bacik 	btrfs_set_inode_uid(leaf, inode_item, 0);
1920af3d00bSJosef Bacik 	btrfs_set_inode_gid(leaf, inode_item, 0);
1930af3d00bSJosef Bacik 	btrfs_set_inode_mode(leaf, inode_item, S_IFREG | 0600);
1945b0e95bfSJosef Bacik 	btrfs_set_inode_flags(leaf, inode_item, flags);
1950af3d00bSJosef Bacik 	btrfs_set_inode_nlink(leaf, inode_item, 1);
1960af3d00bSJosef Bacik 	btrfs_set_inode_transid(leaf, inode_item, trans->transid);
1970414efaeSLi Zefan 	btrfs_set_inode_block_group(leaf, inode_item, offset);
198d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
199b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2000af3d00bSJosef Bacik 
2010af3d00bSJosef Bacik 	key.objectid = BTRFS_FREE_SPACE_OBJECTID;
2020414efaeSLi Zefan 	key.offset = offset;
2030af3d00bSJosef Bacik 	key.type = 0;
2040af3d00bSJosef Bacik 	ret = btrfs_insert_empty_item(trans, root, path, &key,
2050af3d00bSJosef Bacik 				      sizeof(struct btrfs_free_space_header));
2060af3d00bSJosef Bacik 	if (ret < 0) {
207b3b4aa74SDavid Sterba 		btrfs_release_path(path);
2080af3d00bSJosef Bacik 		return ret;
2090af3d00bSJosef Bacik 	}
210c9dc4c65SChris Mason 
2110af3d00bSJosef Bacik 	leaf = path->nodes[0];
2120af3d00bSJosef Bacik 	header = btrfs_item_ptr(leaf, path->slots[0],
2130af3d00bSJosef Bacik 				struct btrfs_free_space_header);
214b159fa28SDavid Sterba 	memzero_extent_buffer(leaf, (unsigned long)header, sizeof(*header));
2150af3d00bSJosef Bacik 	btrfs_set_free_space_key(leaf, header, &disk_key);
216d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
217b3b4aa74SDavid Sterba 	btrfs_release_path(path);
2180af3d00bSJosef Bacik 
2190af3d00bSJosef Bacik 	return 0;
2200af3d00bSJosef Bacik }
2210af3d00bSJosef Bacik 
create_free_space_inode(struct btrfs_trans_handle * trans,struct btrfs_block_group * block_group,struct btrfs_path * path)2224ca75f1bSDavid Sterba int create_free_space_inode(struct btrfs_trans_handle *trans,
22332da5386SDavid Sterba 			    struct btrfs_block_group *block_group,
2240414efaeSLi Zefan 			    struct btrfs_path *path)
2250414efaeSLi Zefan {
2260414efaeSLi Zefan 	int ret;
2270414efaeSLi Zefan 	u64 ino;
2280414efaeSLi Zefan 
229543068a2SNikolay Borisov 	ret = btrfs_get_free_objectid(trans->fs_info->tree_root, &ino);
2300414efaeSLi Zefan 	if (ret < 0)
2310414efaeSLi Zefan 		return ret;
2320414efaeSLi Zefan 
2334ca75f1bSDavid Sterba 	return __create_free_space_inode(trans->fs_info->tree_root, trans, path,
234b3470b5dSDavid Sterba 					 ino, block_group->start);
2350414efaeSLi Zefan }
2360414efaeSLi Zefan 
23736b216c8SBoris Burkov /*
23836b216c8SBoris Burkov  * inode is an optional sink: if it is NULL, btrfs_remove_free_space_inode
23936b216c8SBoris Burkov  * handles lookup, otherwise it takes ownership and iputs the inode.
24036b216c8SBoris Burkov  * Don't reuse an inode pointer after passing it into this function.
24136b216c8SBoris Burkov  */
btrfs_remove_free_space_inode(struct btrfs_trans_handle * trans,struct inode * inode,struct btrfs_block_group * block_group)24236b216c8SBoris Burkov int btrfs_remove_free_space_inode(struct btrfs_trans_handle *trans,
24336b216c8SBoris Burkov 				  struct inode *inode,
24436b216c8SBoris Burkov 				  struct btrfs_block_group *block_group)
24536b216c8SBoris Burkov {
24636b216c8SBoris Burkov 	struct btrfs_path *path;
24736b216c8SBoris Burkov 	struct btrfs_key key;
24836b216c8SBoris Burkov 	int ret = 0;
24936b216c8SBoris Burkov 
25036b216c8SBoris Burkov 	path = btrfs_alloc_path();
25136b216c8SBoris Burkov 	if (!path)
25236b216c8SBoris Burkov 		return -ENOMEM;
25336b216c8SBoris Burkov 
25436b216c8SBoris Burkov 	if (!inode)
25536b216c8SBoris Burkov 		inode = lookup_free_space_inode(block_group, path);
25636b216c8SBoris Burkov 	if (IS_ERR(inode)) {
25736b216c8SBoris Burkov 		if (PTR_ERR(inode) != -ENOENT)
25836b216c8SBoris Burkov 			ret = PTR_ERR(inode);
25936b216c8SBoris Burkov 		goto out;
26036b216c8SBoris Burkov 	}
26136b216c8SBoris Burkov 	ret = btrfs_orphan_add(trans, BTRFS_I(inode));
26236b216c8SBoris Burkov 	if (ret) {
263e55cf7caSDavid Sterba 		btrfs_add_delayed_iput(BTRFS_I(inode));
26436b216c8SBoris Burkov 		goto out;
26536b216c8SBoris Burkov 	}
26636b216c8SBoris Burkov 	clear_nlink(inode);
26736b216c8SBoris Burkov 	/* One for the block groups ref */
26836b216c8SBoris Burkov 	spin_lock(&block_group->lock);
2693349b57fSJosef Bacik 	if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF, &block_group->runtime_flags)) {
27036b216c8SBoris Burkov 		block_group->inode = NULL;
27136b216c8SBoris Burkov 		spin_unlock(&block_group->lock);
27236b216c8SBoris Burkov 		iput(inode);
27336b216c8SBoris Burkov 	} else {
27436b216c8SBoris Burkov 		spin_unlock(&block_group->lock);
27536b216c8SBoris Burkov 	}
27636b216c8SBoris Burkov 	/* One for the lookup ref */
277e55cf7caSDavid Sterba 	btrfs_add_delayed_iput(BTRFS_I(inode));
27836b216c8SBoris Burkov 
27936b216c8SBoris Burkov 	key.objectid = BTRFS_FREE_SPACE_OBJECTID;
28036b216c8SBoris Burkov 	key.type = 0;
28136b216c8SBoris Burkov 	key.offset = block_group->start;
28236b216c8SBoris Burkov 	ret = btrfs_search_slot(trans, trans->fs_info->tree_root, &key, path,
28336b216c8SBoris Burkov 				-1, 1);
28436b216c8SBoris Burkov 	if (ret) {
28536b216c8SBoris Burkov 		if (ret > 0)
28636b216c8SBoris Burkov 			ret = 0;
28736b216c8SBoris Burkov 		goto out;
28836b216c8SBoris Burkov 	}
28936b216c8SBoris Burkov 	ret = btrfs_del_item(trans, trans->fs_info->tree_root, path);
29036b216c8SBoris Burkov out:
29136b216c8SBoris Burkov 	btrfs_free_path(path);
29236b216c8SBoris Burkov 	return ret;
29336b216c8SBoris Burkov }
29436b216c8SBoris Burkov 
btrfs_truncate_free_space_cache(struct btrfs_trans_handle * trans,struct btrfs_block_group * block_group,struct inode * vfs_inode)29577ab86bfSJeff Mahoney int btrfs_truncate_free_space_cache(struct btrfs_trans_handle *trans,
29632da5386SDavid Sterba 				    struct btrfs_block_group *block_group,
2979a4a1429SJosef Bacik 				    struct inode *vfs_inode)
2987b61cd92SMiao Xie {
299d9ac19c3SJosef Bacik 	struct btrfs_truncate_control control = {
30071d18b53SJosef Bacik 		.inode = BTRFS_I(vfs_inode),
301d9ac19c3SJosef Bacik 		.new_size = 0,
302487e81d2SJosef Bacik 		.ino = btrfs_ino(BTRFS_I(vfs_inode)),
303d9ac19c3SJosef Bacik 		.min_type = BTRFS_EXTENT_DATA_KEY,
304655807b8SJosef Bacik 		.clear_extent_range = true,
305d9ac19c3SJosef Bacik 	};
3069a4a1429SJosef Bacik 	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
3079a4a1429SJosef Bacik 	struct btrfs_root *root = inode->root;
3089a4a1429SJosef Bacik 	struct extent_state *cached_state = NULL;
3097b61cd92SMiao Xie 	int ret = 0;
31035c76642SFilipe Manana 	bool locked = false;
3111bbc621eSChris Mason 
31221e75ffeSJeff Mahoney 	if (block_group) {
31321e75ffeSJeff Mahoney 		struct btrfs_path *path = btrfs_alloc_path();
31421e75ffeSJeff Mahoney 
3151bbc621eSChris Mason 		if (!path) {
3161bbc621eSChris Mason 			ret = -ENOMEM;
3171bbc621eSChris Mason 			goto fail;
3181bbc621eSChris Mason 		}
31935c76642SFilipe Manana 		locked = true;
3201bbc621eSChris Mason 		mutex_lock(&trans->transaction->cache_write_mutex);
3211bbc621eSChris Mason 		if (!list_empty(&block_group->io_list)) {
3221bbc621eSChris Mason 			list_del_init(&block_group->io_list);
3231bbc621eSChris Mason 
324afdb5718SJeff Mahoney 			btrfs_wait_cache_io(trans, block_group, path);
3251bbc621eSChris Mason 			btrfs_put_block_group(block_group);
3261bbc621eSChris Mason 		}
3271bbc621eSChris Mason 
3281bbc621eSChris Mason 		/*
3291bbc621eSChris Mason 		 * now that we've truncated the cache away, its no longer
3301bbc621eSChris Mason 		 * setup or written
3311bbc621eSChris Mason 		 */
3321bbc621eSChris Mason 		spin_lock(&block_group->lock);
3331bbc621eSChris Mason 		block_group->disk_cache_state = BTRFS_DC_CLEAR;
3341bbc621eSChris Mason 		spin_unlock(&block_group->lock);
3351bbc621eSChris Mason 		btrfs_free_path(path);
33621e75ffeSJeff Mahoney 	}
3370af3d00bSJosef Bacik 
3389a4a1429SJosef Bacik 	btrfs_i_size_write(inode, 0);
3399a4a1429SJosef Bacik 	truncate_pagecache(vfs_inode, 0);
3409a4a1429SJosef Bacik 
341570eb97bSJosef Bacik 	lock_extent(&inode->io_tree, 0, (u64)-1, &cached_state);
3424c0c8cfcSFilipe Manana 	btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
3430af3d00bSJosef Bacik 
3440af3d00bSJosef Bacik 	/*
345f7e9e8fcSOmar Sandoval 	 * We skip the throttling logic for free space cache inodes, so we don't
346f7e9e8fcSOmar Sandoval 	 * need to check for -EAGAIN.
3470af3d00bSJosef Bacik 	 */
34871d18b53SJosef Bacik 	ret = btrfs_truncate_inode_items(trans, root, &control);
349c2ddb612SJosef Bacik 
350462b728eSJosef Bacik 	inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
351c2ddb612SJosef Bacik 	btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
352c2ddb612SJosef Bacik 
353570eb97bSJosef Bacik 	unlock_extent(&inode->io_tree, 0, (u64)-1, &cached_state);
35435c76642SFilipe Manana 	if (ret)
35535c76642SFilipe Manana 		goto fail;
3560af3d00bSJosef Bacik 
3579a4a1429SJosef Bacik 	ret = btrfs_update_inode(trans, root, inode);
3581bbc621eSChris Mason 
3591bbc621eSChris Mason fail:
36035c76642SFilipe Manana 	if (locked)
36135c76642SFilipe Manana 		mutex_unlock(&trans->transaction->cache_write_mutex);
36279787eaaSJeff Mahoney 	if (ret)
36366642832SJeff Mahoney 		btrfs_abort_transaction(trans, ret);
364c8174313SJosef Bacik 
36582d5902dSLi Zefan 	return ret;
3660af3d00bSJosef Bacik }
3670af3d00bSJosef Bacik 
readahead_cache(struct inode * inode)3681d480538SDavid Sterba static void readahead_cache(struct inode *inode)
3699d66e233SJosef Bacik {
37098caf953SGoldwyn Rodrigues 	struct file_ra_state ra;
3719d66e233SJosef Bacik 	unsigned long last_index;
3729d66e233SJosef Bacik 
37398caf953SGoldwyn Rodrigues 	file_ra_state_init(&ra, inode->i_mapping);
37409cbfeafSKirill A. Shutemov 	last_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
3759d66e233SJosef Bacik 
37698caf953SGoldwyn Rodrigues 	page_cache_sync_readahead(inode->i_mapping, &ra, NULL, 0, last_index);
3779d66e233SJosef Bacik }
3789d66e233SJosef Bacik 
io_ctl_init(struct btrfs_io_ctl * io_ctl,struct inode * inode,int write)3794c6d1d85SChris Mason static int io_ctl_init(struct btrfs_io_ctl *io_ctl, struct inode *inode,
380f15376dfSJeff Mahoney 		       int write)
381a67509c3SJosef Bacik {
3825349d6c3SMiao Xie 	int num_pages;
3835349d6c3SMiao Xie 
38409cbfeafSKirill A. Shutemov 	num_pages = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
3855349d6c3SMiao Xie 
3868f6c72a9SZhihui Zhang 	/* Make sure we can fit our crcs and generation into the first page */
3877dbdb443SNikolay Borisov 	if (write && (num_pages * sizeof(u32) + sizeof(u64)) > PAGE_SIZE)
3885349d6c3SMiao Xie 		return -ENOSPC;
3895349d6c3SMiao Xie 
3904c6d1d85SChris Mason 	memset(io_ctl, 0, sizeof(struct btrfs_io_ctl));
3915349d6c3SMiao Xie 
39231e818feSDavid Sterba 	io_ctl->pages = kcalloc(num_pages, sizeof(struct page *), GFP_NOFS);
393a67509c3SJosef Bacik 	if (!io_ctl->pages)
394a67509c3SJosef Bacik 		return -ENOMEM;
3955349d6c3SMiao Xie 
3965349d6c3SMiao Xie 	io_ctl->num_pages = num_pages;
397f15376dfSJeff Mahoney 	io_ctl->fs_info = btrfs_sb(inode->i_sb);
398c9dc4c65SChris Mason 	io_ctl->inode = inode;
3995349d6c3SMiao Xie 
400a67509c3SJosef Bacik 	return 0;
401a67509c3SJosef Bacik }
402663faf9fSMasami Hiramatsu ALLOW_ERROR_INJECTION(io_ctl_init, ERRNO);
403a67509c3SJosef Bacik 
io_ctl_free(struct btrfs_io_ctl * io_ctl)4044c6d1d85SChris Mason static void io_ctl_free(struct btrfs_io_ctl *io_ctl)
405a67509c3SJosef Bacik {
406a67509c3SJosef Bacik 	kfree(io_ctl->pages);
407c9dc4c65SChris Mason 	io_ctl->pages = NULL;
408a67509c3SJosef Bacik }
409a67509c3SJosef Bacik 
io_ctl_unmap_page(struct btrfs_io_ctl * io_ctl)4104c6d1d85SChris Mason static void io_ctl_unmap_page(struct btrfs_io_ctl *io_ctl)
411a67509c3SJosef Bacik {
412a67509c3SJosef Bacik 	if (io_ctl->cur) {
413a67509c3SJosef Bacik 		io_ctl->cur = NULL;
414a67509c3SJosef Bacik 		io_ctl->orig = NULL;
415a67509c3SJosef Bacik 	}
416a67509c3SJosef Bacik }
417a67509c3SJosef Bacik 
io_ctl_map_page(struct btrfs_io_ctl * io_ctl,int clear)4184c6d1d85SChris Mason static void io_ctl_map_page(struct btrfs_io_ctl *io_ctl, int clear)
419a67509c3SJosef Bacik {
420b12d6869SJosef Bacik 	ASSERT(io_ctl->index < io_ctl->num_pages);
421a67509c3SJosef Bacik 	io_ctl->page = io_ctl->pages[io_ctl->index++];
4222b108268SChris Mason 	io_ctl->cur = page_address(io_ctl->page);
423a67509c3SJosef Bacik 	io_ctl->orig = io_ctl->cur;
42409cbfeafSKirill A. Shutemov 	io_ctl->size = PAGE_SIZE;
425a67509c3SJosef Bacik 	if (clear)
426619a9742SDavid Sterba 		clear_page(io_ctl->cur);
427a67509c3SJosef Bacik }
428a67509c3SJosef Bacik 
io_ctl_drop_pages(struct btrfs_io_ctl * io_ctl)4294c6d1d85SChris Mason static void io_ctl_drop_pages(struct btrfs_io_ctl *io_ctl)
430a67509c3SJosef Bacik {
431a67509c3SJosef Bacik 	int i;
432a67509c3SJosef Bacik 
433a67509c3SJosef Bacik 	io_ctl_unmap_page(io_ctl);
434a67509c3SJosef Bacik 
435a67509c3SJosef Bacik 	for (i = 0; i < io_ctl->num_pages; i++) {
436a1ee5a45SLi Zefan 		if (io_ctl->pages[i]) {
437e4f94347SQu Wenruo 			btrfs_page_clear_checked(io_ctl->fs_info,
438e4f94347SQu Wenruo 					io_ctl->pages[i],
439e4f94347SQu Wenruo 					page_offset(io_ctl->pages[i]),
440e4f94347SQu Wenruo 					PAGE_SIZE);
441a67509c3SJosef Bacik 			unlock_page(io_ctl->pages[i]);
44209cbfeafSKirill A. Shutemov 			put_page(io_ctl->pages[i]);
443a67509c3SJosef Bacik 		}
444a67509c3SJosef Bacik 	}
445a1ee5a45SLi Zefan }
446a67509c3SJosef Bacik 
io_ctl_prepare_pages(struct btrfs_io_ctl * io_ctl,bool uptodate)4477a195f6dSJohannes Thumshirn static int io_ctl_prepare_pages(struct btrfs_io_ctl *io_ctl, bool uptodate)
448a67509c3SJosef Bacik {
449a67509c3SJosef Bacik 	struct page *page;
450831fa14fSJohannes Thumshirn 	struct inode *inode = io_ctl->inode;
451a67509c3SJosef Bacik 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
452a67509c3SJosef Bacik 	int i;
453a67509c3SJosef Bacik 
454a67509c3SJosef Bacik 	for (i = 0; i < io_ctl->num_pages; i++) {
45532443de3SQu Wenruo 		int ret;
45632443de3SQu Wenruo 
457a67509c3SJosef Bacik 		page = find_or_create_page(inode->i_mapping, i, mask);
458a67509c3SJosef Bacik 		if (!page) {
459a67509c3SJosef Bacik 			io_ctl_drop_pages(io_ctl);
460a67509c3SJosef Bacik 			return -ENOMEM;
461a67509c3SJosef Bacik 		}
46232443de3SQu Wenruo 
46332443de3SQu Wenruo 		ret = set_page_extent_mapped(page);
46432443de3SQu Wenruo 		if (ret < 0) {
46532443de3SQu Wenruo 			unlock_page(page);
46632443de3SQu Wenruo 			put_page(page);
46732443de3SQu Wenruo 			io_ctl_drop_pages(io_ctl);
46832443de3SQu Wenruo 			return ret;
46932443de3SQu Wenruo 		}
47032443de3SQu Wenruo 
471a67509c3SJosef Bacik 		io_ctl->pages[i] = page;
472a67509c3SJosef Bacik 		if (uptodate && !PageUptodate(page)) {
473fb12489bSMatthew Wilcox (Oracle) 			btrfs_read_folio(NULL, page_folio(page));
474a67509c3SJosef Bacik 			lock_page(page);
4753797136bSJosef Bacik 			if (page->mapping != inode->i_mapping) {
4763797136bSJosef Bacik 				btrfs_err(BTRFS_I(inode)->root->fs_info,
4773797136bSJosef Bacik 					  "free space cache page truncated");
4783797136bSJosef Bacik 				io_ctl_drop_pages(io_ctl);
4793797136bSJosef Bacik 				return -EIO;
4803797136bSJosef Bacik 			}
481a67509c3SJosef Bacik 			if (!PageUptodate(page)) {
482efe120a0SFrank Holton 				btrfs_err(BTRFS_I(inode)->root->fs_info,
483efe120a0SFrank Holton 					   "error reading free space cache");
484a67509c3SJosef Bacik 				io_ctl_drop_pages(io_ctl);
485a67509c3SJosef Bacik 				return -EIO;
486a67509c3SJosef Bacik 			}
487a67509c3SJosef Bacik 		}
488a67509c3SJosef Bacik 	}
489a67509c3SJosef Bacik 
49032443de3SQu Wenruo 	for (i = 0; i < io_ctl->num_pages; i++)
491f7d61dcdSJosef Bacik 		clear_page_dirty_for_io(io_ctl->pages[i]);
492f7d61dcdSJosef Bacik 
493a67509c3SJosef Bacik 	return 0;
494a67509c3SJosef Bacik }
495a67509c3SJosef Bacik 
io_ctl_set_generation(struct btrfs_io_ctl * io_ctl,u64 generation)4964c6d1d85SChris Mason static void io_ctl_set_generation(struct btrfs_io_ctl *io_ctl, u64 generation)
497a67509c3SJosef Bacik {
498a67509c3SJosef Bacik 	io_ctl_map_page(io_ctl, 1);
499a67509c3SJosef Bacik 
500a67509c3SJosef Bacik 	/*
5015b0e95bfSJosef Bacik 	 * Skip the csum areas.  If we don't check crcs then we just have a
5025b0e95bfSJosef Bacik 	 * 64bit chunk at the front of the first page.
503a67509c3SJosef Bacik 	 */
5045b0e95bfSJosef Bacik 	io_ctl->cur += (sizeof(u32) * io_ctl->num_pages);
5055b0e95bfSJosef Bacik 	io_ctl->size -= sizeof(u64) + (sizeof(u32) * io_ctl->num_pages);
506a67509c3SJosef Bacik 
5076994ca36SDavid Sterba 	put_unaligned_le64(generation, io_ctl->cur);
508a67509c3SJosef Bacik 	io_ctl->cur += sizeof(u64);
509a67509c3SJosef Bacik }
510a67509c3SJosef Bacik 
io_ctl_check_generation(struct btrfs_io_ctl * io_ctl,u64 generation)5114c6d1d85SChris Mason static int io_ctl_check_generation(struct btrfs_io_ctl *io_ctl, u64 generation)
512a67509c3SJosef Bacik {
5136994ca36SDavid Sterba 	u64 cache_gen;
514a67509c3SJosef Bacik 
5155b0e95bfSJosef Bacik 	/*
5165b0e95bfSJosef Bacik 	 * Skip the crc area.  If we don't check crcs then we just have a 64bit
5175b0e95bfSJosef Bacik 	 * chunk at the front of the first page.
5185b0e95bfSJosef Bacik 	 */
5195b0e95bfSJosef Bacik 	io_ctl->cur += sizeof(u32) * io_ctl->num_pages;
5207dbdb443SNikolay Borisov 	io_ctl->size -= sizeof(u64) + (sizeof(u32) * io_ctl->num_pages);
5215b0e95bfSJosef Bacik 
5226994ca36SDavid Sterba 	cache_gen = get_unaligned_le64(io_ctl->cur);
5236994ca36SDavid Sterba 	if (cache_gen != generation) {
524f15376dfSJeff Mahoney 		btrfs_err_rl(io_ctl->fs_info,
52594647322SDavid Sterba 			"space cache generation (%llu) does not match inode (%llu)",
5266994ca36SDavid Sterba 				cache_gen, generation);
527a67509c3SJosef Bacik 		io_ctl_unmap_page(io_ctl);
528a67509c3SJosef Bacik 		return -EIO;
529a67509c3SJosef Bacik 	}
530a67509c3SJosef Bacik 	io_ctl->cur += sizeof(u64);
5315b0e95bfSJosef Bacik 	return 0;
5325b0e95bfSJosef Bacik }
5335b0e95bfSJosef Bacik 
io_ctl_set_crc(struct btrfs_io_ctl * io_ctl,int index)5344c6d1d85SChris Mason static void io_ctl_set_crc(struct btrfs_io_ctl *io_ctl, int index)
5355b0e95bfSJosef Bacik {
5365b0e95bfSJosef Bacik 	u32 *tmp;
5375b0e95bfSJosef Bacik 	u32 crc = ~(u32)0;
5385b0e95bfSJosef Bacik 	unsigned offset = 0;
5395b0e95bfSJosef Bacik 
5405b0e95bfSJosef Bacik 	if (index == 0)
541cb54f257SJustin P. Mattock 		offset = sizeof(u32) * io_ctl->num_pages;
5425b0e95bfSJosef Bacik 
5434bb3c2e2SJohannes Thumshirn 	crc = btrfs_crc32c(crc, io_ctl->orig + offset, PAGE_SIZE - offset);
5444bb3c2e2SJohannes Thumshirn 	btrfs_crc32c_final(crc, (u8 *)&crc);
5455b0e95bfSJosef Bacik 	io_ctl_unmap_page(io_ctl);
5462b108268SChris Mason 	tmp = page_address(io_ctl->pages[0]);
5475b0e95bfSJosef Bacik 	tmp += index;
5485b0e95bfSJosef Bacik 	*tmp = crc;
5495b0e95bfSJosef Bacik }
5505b0e95bfSJosef Bacik 
io_ctl_check_crc(struct btrfs_io_ctl * io_ctl,int index)5514c6d1d85SChris Mason static int io_ctl_check_crc(struct btrfs_io_ctl *io_ctl, int index)
5525b0e95bfSJosef Bacik {
5535b0e95bfSJosef Bacik 	u32 *tmp, val;
5545b0e95bfSJosef Bacik 	u32 crc = ~(u32)0;
5555b0e95bfSJosef Bacik 	unsigned offset = 0;
5565b0e95bfSJosef Bacik 
5575b0e95bfSJosef Bacik 	if (index == 0)
5585b0e95bfSJosef Bacik 		offset = sizeof(u32) * io_ctl->num_pages;
5595b0e95bfSJosef Bacik 
5602b108268SChris Mason 	tmp = page_address(io_ctl->pages[0]);
5615b0e95bfSJosef Bacik 	tmp += index;
5625b0e95bfSJosef Bacik 	val = *tmp;
5635b0e95bfSJosef Bacik 
5645b0e95bfSJosef Bacik 	io_ctl_map_page(io_ctl, 0);
5654bb3c2e2SJohannes Thumshirn 	crc = btrfs_crc32c(crc, io_ctl->orig + offset, PAGE_SIZE - offset);
5664bb3c2e2SJohannes Thumshirn 	btrfs_crc32c_final(crc, (u8 *)&crc);
5675b0e95bfSJosef Bacik 	if (val != crc) {
568f15376dfSJeff Mahoney 		btrfs_err_rl(io_ctl->fs_info,
56994647322SDavid Sterba 			"csum mismatch on free space cache");
5705b0e95bfSJosef Bacik 		io_ctl_unmap_page(io_ctl);
5715b0e95bfSJosef Bacik 		return -EIO;
5725b0e95bfSJosef Bacik 	}
5735b0e95bfSJosef Bacik 
574a67509c3SJosef Bacik 	return 0;
575a67509c3SJosef Bacik }
576a67509c3SJosef Bacik 
io_ctl_add_entry(struct btrfs_io_ctl * io_ctl,u64 offset,u64 bytes,void * bitmap)5774c6d1d85SChris Mason static int io_ctl_add_entry(struct btrfs_io_ctl *io_ctl, u64 offset, u64 bytes,
578a67509c3SJosef Bacik 			    void *bitmap)
579a67509c3SJosef Bacik {
580a67509c3SJosef Bacik 	struct btrfs_free_space_entry *entry;
581a67509c3SJosef Bacik 
582a67509c3SJosef Bacik 	if (!io_ctl->cur)
583a67509c3SJosef Bacik 		return -ENOSPC;
584a67509c3SJosef Bacik 
585a67509c3SJosef Bacik 	entry = io_ctl->cur;
5866994ca36SDavid Sterba 	put_unaligned_le64(offset, &entry->offset);
5876994ca36SDavid Sterba 	put_unaligned_le64(bytes, &entry->bytes);
588a67509c3SJosef Bacik 	entry->type = (bitmap) ? BTRFS_FREE_SPACE_BITMAP :
589a67509c3SJosef Bacik 		BTRFS_FREE_SPACE_EXTENT;
590a67509c3SJosef Bacik 	io_ctl->cur += sizeof(struct btrfs_free_space_entry);
591a67509c3SJosef Bacik 	io_ctl->size -= sizeof(struct btrfs_free_space_entry);
592a67509c3SJosef Bacik 
593a67509c3SJosef Bacik 	if (io_ctl->size >= sizeof(struct btrfs_free_space_entry))
594a67509c3SJosef Bacik 		return 0;
595a67509c3SJosef Bacik 
5965b0e95bfSJosef Bacik 	io_ctl_set_crc(io_ctl, io_ctl->index - 1);
597a67509c3SJosef Bacik 
598a67509c3SJosef Bacik 	/* No more pages to map */
599a67509c3SJosef Bacik 	if (io_ctl->index >= io_ctl->num_pages)
600a67509c3SJosef Bacik 		return 0;
601a67509c3SJosef Bacik 
602a67509c3SJosef Bacik 	/* map the next page */
603a67509c3SJosef Bacik 	io_ctl_map_page(io_ctl, 1);
604a67509c3SJosef Bacik 	return 0;
605a67509c3SJosef Bacik }
606a67509c3SJosef Bacik 
io_ctl_add_bitmap(struct btrfs_io_ctl * io_ctl,void * bitmap)6074c6d1d85SChris Mason static int io_ctl_add_bitmap(struct btrfs_io_ctl *io_ctl, void *bitmap)
608a67509c3SJosef Bacik {
609a67509c3SJosef Bacik 	if (!io_ctl->cur)
610a67509c3SJosef Bacik 		return -ENOSPC;
611a67509c3SJosef Bacik 
612a67509c3SJosef Bacik 	/*
613a67509c3SJosef Bacik 	 * If we aren't at the start of the current page, unmap this one and
614a67509c3SJosef Bacik 	 * map the next one if there is any left.
615a67509c3SJosef Bacik 	 */
616a67509c3SJosef Bacik 	if (io_ctl->cur != io_ctl->orig) {
6175b0e95bfSJosef Bacik 		io_ctl_set_crc(io_ctl, io_ctl->index - 1);
618a67509c3SJosef Bacik 		if (io_ctl->index >= io_ctl->num_pages)
619a67509c3SJosef Bacik 			return -ENOSPC;
620a67509c3SJosef Bacik 		io_ctl_map_page(io_ctl, 0);
621a67509c3SJosef Bacik 	}
622a67509c3SJosef Bacik 
62369d24804SDavid Sterba 	copy_page(io_ctl->cur, bitmap);
6245b0e95bfSJosef Bacik 	io_ctl_set_crc(io_ctl, io_ctl->index - 1);
625a67509c3SJosef Bacik 	if (io_ctl->index < io_ctl->num_pages)
626a67509c3SJosef Bacik 		io_ctl_map_page(io_ctl, 0);
627a67509c3SJosef Bacik 	return 0;
628a67509c3SJosef Bacik }
629a67509c3SJosef Bacik 
io_ctl_zero_remaining_pages(struct btrfs_io_ctl * io_ctl)6304c6d1d85SChris Mason static void io_ctl_zero_remaining_pages(struct btrfs_io_ctl *io_ctl)
631a67509c3SJosef Bacik {
6325b0e95bfSJosef Bacik 	/*
6335b0e95bfSJosef Bacik 	 * If we're not on the boundary we know we've modified the page and we
6345b0e95bfSJosef Bacik 	 * need to crc the page.
6355b0e95bfSJosef Bacik 	 */
6365b0e95bfSJosef Bacik 	if (io_ctl->cur != io_ctl->orig)
6375b0e95bfSJosef Bacik 		io_ctl_set_crc(io_ctl, io_ctl->index - 1);
6385b0e95bfSJosef Bacik 	else
639a67509c3SJosef Bacik 		io_ctl_unmap_page(io_ctl);
640a67509c3SJosef Bacik 
641a67509c3SJosef Bacik 	while (io_ctl->index < io_ctl->num_pages) {
642a67509c3SJosef Bacik 		io_ctl_map_page(io_ctl, 1);
6435b0e95bfSJosef Bacik 		io_ctl_set_crc(io_ctl, io_ctl->index - 1);
644a67509c3SJosef Bacik 	}
645a67509c3SJosef Bacik }
646a67509c3SJosef Bacik 
io_ctl_read_entry(struct btrfs_io_ctl * io_ctl,struct btrfs_free_space * entry,u8 * type)6474c6d1d85SChris Mason static int io_ctl_read_entry(struct btrfs_io_ctl *io_ctl,
6485b0e95bfSJosef Bacik 			    struct btrfs_free_space *entry, u8 *type)
649a67509c3SJosef Bacik {
650a67509c3SJosef Bacik 	struct btrfs_free_space_entry *e;
6512f120c05SJosef Bacik 	int ret;
6522f120c05SJosef Bacik 
6532f120c05SJosef Bacik 	if (!io_ctl->cur) {
6542f120c05SJosef Bacik 		ret = io_ctl_check_crc(io_ctl, io_ctl->index);
6552f120c05SJosef Bacik 		if (ret)
6562f120c05SJosef Bacik 			return ret;
6572f120c05SJosef Bacik 	}
658a67509c3SJosef Bacik 
659a67509c3SJosef Bacik 	e = io_ctl->cur;
6606994ca36SDavid Sterba 	entry->offset = get_unaligned_le64(&e->offset);
6616994ca36SDavid Sterba 	entry->bytes = get_unaligned_le64(&e->bytes);
6625b0e95bfSJosef Bacik 	*type = e->type;
663a67509c3SJosef Bacik 	io_ctl->cur += sizeof(struct btrfs_free_space_entry);
664a67509c3SJosef Bacik 	io_ctl->size -= sizeof(struct btrfs_free_space_entry);
665a67509c3SJosef Bacik 
666a67509c3SJosef Bacik 	if (io_ctl->size >= sizeof(struct btrfs_free_space_entry))
6675b0e95bfSJosef Bacik 		return 0;
668a67509c3SJosef Bacik 
669a67509c3SJosef Bacik 	io_ctl_unmap_page(io_ctl);
670a67509c3SJosef Bacik 
6715b0e95bfSJosef Bacik 	return 0;
672a67509c3SJosef Bacik }
673a67509c3SJosef Bacik 
io_ctl_read_bitmap(struct btrfs_io_ctl * io_ctl,struct btrfs_free_space * entry)6744c6d1d85SChris Mason static int io_ctl_read_bitmap(struct btrfs_io_ctl *io_ctl,
675a67509c3SJosef Bacik 			      struct btrfs_free_space *entry)
676a67509c3SJosef Bacik {
6775b0e95bfSJosef Bacik 	int ret;
6785b0e95bfSJosef Bacik 
6795b0e95bfSJosef Bacik 	ret = io_ctl_check_crc(io_ctl, io_ctl->index);
6805b0e95bfSJosef Bacik 	if (ret)
6815b0e95bfSJosef Bacik 		return ret;
6825b0e95bfSJosef Bacik 
68369d24804SDavid Sterba 	copy_page(entry->bitmap, io_ctl->cur);
684a67509c3SJosef Bacik 	io_ctl_unmap_page(io_ctl);
6855b0e95bfSJosef Bacik 
6865b0e95bfSJosef Bacik 	return 0;
687a67509c3SJosef Bacik }
688a67509c3SJosef Bacik 
recalculate_thresholds(struct btrfs_free_space_ctl * ctl)689fa598b06SDavid Sterba static void recalculate_thresholds(struct btrfs_free_space_ctl *ctl)
690fa598b06SDavid Sterba {
691364be842SNikolay Borisov 	struct btrfs_block_group *block_group = ctl->block_group;
692fa598b06SDavid Sterba 	u64 max_bytes;
693fa598b06SDavid Sterba 	u64 bitmap_bytes;
694fa598b06SDavid Sterba 	u64 extent_bytes;
695fa598b06SDavid Sterba 	u64 size = block_group->length;
696fa598b06SDavid Sterba 	u64 bytes_per_bg = BITS_PER_BITMAP * ctl->unit;
697fa598b06SDavid Sterba 	u64 max_bitmaps = div64_u64(size + bytes_per_bg - 1, bytes_per_bg);
698fa598b06SDavid Sterba 
699fa598b06SDavid Sterba 	max_bitmaps = max_t(u64, max_bitmaps, 1);
700fa598b06SDavid Sterba 
70162cd9d44SQu Wenruo 	if (ctl->total_bitmaps > max_bitmaps)
70262cd9d44SQu Wenruo 		btrfs_err(block_group->fs_info,
70362cd9d44SQu Wenruo "invalid free space control: bg start=%llu len=%llu total_bitmaps=%u unit=%u max_bitmaps=%llu bytes_per_bg=%llu",
70462cd9d44SQu Wenruo 			  block_group->start, block_group->length,
70562cd9d44SQu Wenruo 			  ctl->total_bitmaps, ctl->unit, max_bitmaps,
70662cd9d44SQu Wenruo 			  bytes_per_bg);
707fa598b06SDavid Sterba 	ASSERT(ctl->total_bitmaps <= max_bitmaps);
708fa598b06SDavid Sterba 
709fa598b06SDavid Sterba 	/*
710fa598b06SDavid Sterba 	 * We are trying to keep the total amount of memory used per 1GiB of
711fa598b06SDavid Sterba 	 * space to be MAX_CACHE_BYTES_PER_GIG.  However, with a reclamation
712fa598b06SDavid Sterba 	 * mechanism of pulling extents >= FORCE_EXTENT_THRESHOLD out of
713fa598b06SDavid Sterba 	 * bitmaps, we may end up using more memory than this.
714fa598b06SDavid Sterba 	 */
715fa598b06SDavid Sterba 	if (size < SZ_1G)
716fa598b06SDavid Sterba 		max_bytes = MAX_CACHE_BYTES_PER_GIG;
717fa598b06SDavid Sterba 	else
718fa598b06SDavid Sterba 		max_bytes = MAX_CACHE_BYTES_PER_GIG * div_u64(size, SZ_1G);
719fa598b06SDavid Sterba 
720fa598b06SDavid Sterba 	bitmap_bytes = ctl->total_bitmaps * ctl->unit;
721fa598b06SDavid Sterba 
722fa598b06SDavid Sterba 	/*
723fa598b06SDavid Sterba 	 * we want the extent entry threshold to always be at most 1/2 the max
724fa598b06SDavid Sterba 	 * bytes we can have, or whatever is less than that.
725fa598b06SDavid Sterba 	 */
726fa598b06SDavid Sterba 	extent_bytes = max_bytes - bitmap_bytes;
727fa598b06SDavid Sterba 	extent_bytes = min_t(u64, extent_bytes, max_bytes >> 1);
728fa598b06SDavid Sterba 
729fa598b06SDavid Sterba 	ctl->extents_thresh =
730fa598b06SDavid Sterba 		div_u64(extent_bytes, sizeof(struct btrfs_free_space));
731fa598b06SDavid Sterba }
732fa598b06SDavid Sterba 
__load_free_space_cache(struct btrfs_root * root,struct inode * inode,struct btrfs_free_space_ctl * ctl,struct btrfs_path * path,u64 offset)73348a3b636SEric Sandeen static int __load_free_space_cache(struct btrfs_root *root, struct inode *inode,
7340414efaeSLi Zefan 				   struct btrfs_free_space_ctl *ctl,
7350414efaeSLi Zefan 				   struct btrfs_path *path, u64 offset)
7369d66e233SJosef Bacik {
7373ffbd68cSDavid Sterba 	struct btrfs_fs_info *fs_info = root->fs_info;
7389d66e233SJosef Bacik 	struct btrfs_free_space_header *header;
7399d66e233SJosef Bacik 	struct extent_buffer *leaf;
7404c6d1d85SChris Mason 	struct btrfs_io_ctl io_ctl;
7419d66e233SJosef Bacik 	struct btrfs_key key;
742a67509c3SJosef Bacik 	struct btrfs_free_space *e, *n;
743b76808fcSGui Hecheng 	LIST_HEAD(bitmaps);
7449d66e233SJosef Bacik 	u64 num_entries;
7459d66e233SJosef Bacik 	u64 num_bitmaps;
7469d66e233SJosef Bacik 	u64 generation;
747a67509c3SJosef Bacik 	u8 type;
748f6a39829SJosef Bacik 	int ret = 0;
7499d66e233SJosef Bacik 
7509d66e233SJosef Bacik 	/* Nothing in the space cache, goodbye */
7510414efaeSLi Zefan 	if (!i_size_read(inode))
752a67509c3SJosef Bacik 		return 0;
7539d66e233SJosef Bacik 
7549d66e233SJosef Bacik 	key.objectid = BTRFS_FREE_SPACE_OBJECTID;
7550414efaeSLi Zefan 	key.offset = offset;
7569d66e233SJosef Bacik 	key.type = 0;
7579d66e233SJosef Bacik 
7589d66e233SJosef Bacik 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7590414efaeSLi Zefan 	if (ret < 0)
760a67509c3SJosef Bacik 		return 0;
7610414efaeSLi Zefan 	else if (ret > 0) {
762945d8962SChris Mason 		btrfs_release_path(path);
763a67509c3SJosef Bacik 		return 0;
7649d66e233SJosef Bacik 	}
7659d66e233SJosef Bacik 
7660414efaeSLi Zefan 	ret = -1;
7670414efaeSLi Zefan 
7689d66e233SJosef Bacik 	leaf = path->nodes[0];
7699d66e233SJosef Bacik 	header = btrfs_item_ptr(leaf, path->slots[0],
7709d66e233SJosef Bacik 				struct btrfs_free_space_header);
7719d66e233SJosef Bacik 	num_entries = btrfs_free_space_entries(leaf, header);
7729d66e233SJosef Bacik 	num_bitmaps = btrfs_free_space_bitmaps(leaf, header);
7739d66e233SJosef Bacik 	generation = btrfs_free_space_generation(leaf, header);
774945d8962SChris Mason 	btrfs_release_path(path);
7759d66e233SJosef Bacik 
776e570fd27SMiao Xie 	if (!BTRFS_I(inode)->generation) {
7770b246afaSJeff Mahoney 		btrfs_info(fs_info,
778913e1535SDavid Sterba 			   "the free space cache file (%llu) is invalid, skip it",
779e570fd27SMiao Xie 			   offset);
780e570fd27SMiao Xie 		return 0;
781e570fd27SMiao Xie 	}
782e570fd27SMiao Xie 
7839d66e233SJosef Bacik 	if (BTRFS_I(inode)->generation != generation) {
7840b246afaSJeff Mahoney 		btrfs_err(fs_info,
7855d163e0eSJeff Mahoney 			  "free space inode generation (%llu) did not match free space cache generation (%llu)",
786c1c9ff7cSGeert Uytterhoeven 			  BTRFS_I(inode)->generation, generation);
787a67509c3SJosef Bacik 		return 0;
7889d66e233SJosef Bacik 	}
7899d66e233SJosef Bacik 
7909d66e233SJosef Bacik 	if (!num_entries)
791a67509c3SJosef Bacik 		return 0;
7929d66e233SJosef Bacik 
793f15376dfSJeff Mahoney 	ret = io_ctl_init(&io_ctl, inode, 0);
794706efc66SLi Zefan 	if (ret)
795706efc66SLi Zefan 		return ret;
796706efc66SLi Zefan 
7971d480538SDavid Sterba 	readahead_cache(inode);
7989d66e233SJosef Bacik 
7997a195f6dSJohannes Thumshirn 	ret = io_ctl_prepare_pages(&io_ctl, true);
800a67509c3SJosef Bacik 	if (ret)
801a67509c3SJosef Bacik 		goto out;
8029d66e233SJosef Bacik 
8035b0e95bfSJosef Bacik 	ret = io_ctl_check_crc(&io_ctl, 0);
8045b0e95bfSJosef Bacik 	if (ret)
8055b0e95bfSJosef Bacik 		goto free_cache;
8065b0e95bfSJosef Bacik 
807a67509c3SJosef Bacik 	ret = io_ctl_check_generation(&io_ctl, generation);
808a67509c3SJosef Bacik 	if (ret)
8099d66e233SJosef Bacik 		goto free_cache;
8109d66e233SJosef Bacik 
811a67509c3SJosef Bacik 	while (num_entries) {
812dc89e982SJosef Bacik 		e = kmem_cache_zalloc(btrfs_free_space_cachep,
813dc89e982SJosef Bacik 				      GFP_NOFS);
8143cc64e7eSZhihao Cheng 		if (!e) {
8153cc64e7eSZhihao Cheng 			ret = -ENOMEM;
8169d66e233SJosef Bacik 			goto free_cache;
8173cc64e7eSZhihao Cheng 		}
8189d66e233SJosef Bacik 
8195b0e95bfSJosef Bacik 		ret = io_ctl_read_entry(&io_ctl, e, &type);
8205b0e95bfSJosef Bacik 		if (ret) {
8215b0e95bfSJosef Bacik 			kmem_cache_free(btrfs_free_space_cachep, e);
8225b0e95bfSJosef Bacik 			goto free_cache;
8235b0e95bfSJosef Bacik 		}
8245b0e95bfSJosef Bacik 
8259d66e233SJosef Bacik 		if (!e->bytes) {
8263cc64e7eSZhihao Cheng 			ret = -1;
827dc89e982SJosef Bacik 			kmem_cache_free(btrfs_free_space_cachep, e);
8289d66e233SJosef Bacik 			goto free_cache;
8299d66e233SJosef Bacik 		}
8309d66e233SJosef Bacik 
831a67509c3SJosef Bacik 		if (type == BTRFS_FREE_SPACE_EXTENT) {
83234d52cb6SLi Zefan 			spin_lock(&ctl->tree_lock);
83334d52cb6SLi Zefan 			ret = link_free_space(ctl, e);
83434d52cb6SLi Zefan 			spin_unlock(&ctl->tree_lock);
835207dde82SJosef Bacik 			if (ret) {
8360b246afaSJeff Mahoney 				btrfs_err(fs_info,
837c2cf52ebSSimon Kirby 					"Duplicate entries in free space cache, dumping");
838a67509c3SJosef Bacik 				kmem_cache_free(btrfs_free_space_cachep, e);
839207dde82SJosef Bacik 				goto free_cache;
840207dde82SJosef Bacik 			}
8419d66e233SJosef Bacik 		} else {
842b12d6869SJosef Bacik 			ASSERT(num_bitmaps);
843a67509c3SJosef Bacik 			num_bitmaps--;
8443acd4850SChristophe Leroy 			e->bitmap = kmem_cache_zalloc(
8453acd4850SChristophe Leroy 					btrfs_free_space_bitmap_cachep, GFP_NOFS);
8469d66e233SJosef Bacik 			if (!e->bitmap) {
8473cc64e7eSZhihao Cheng 				ret = -ENOMEM;
848dc89e982SJosef Bacik 				kmem_cache_free(
849dc89e982SJosef Bacik 					btrfs_free_space_cachep, e);
8509d66e233SJosef Bacik 				goto free_cache;
8519d66e233SJosef Bacik 			}
85234d52cb6SLi Zefan 			spin_lock(&ctl->tree_lock);
853f6a39829SJosef Bacik 			ret = link_free_space(ctl, e);
854207dde82SJosef Bacik 			if (ret) {
8550004ff15SFilipe Manana 				spin_unlock(&ctl->tree_lock);
8560b246afaSJeff Mahoney 				btrfs_err(fs_info,
857c2cf52ebSSimon Kirby 					"Duplicate entries in free space cache, dumping");
858d9e84607SFilipe Manana 				kmem_cache_free(btrfs_free_space_bitmap_cachep, e->bitmap);
859a67509c3SJosef Bacik 				kmem_cache_free(btrfs_free_space_cachep, e);
860207dde82SJosef Bacik 				goto free_cache;
861207dde82SJosef Bacik 			}
8620004ff15SFilipe Manana 			ctl->total_bitmaps++;
8630004ff15SFilipe Manana 			recalculate_thresholds(ctl);
8640004ff15SFilipe Manana 			spin_unlock(&ctl->tree_lock);
865f6a39829SJosef Bacik 			list_add_tail(&e->list, &bitmaps);
8669d66e233SJosef Bacik 		}
8679d66e233SJosef Bacik 
8689d66e233SJosef Bacik 		num_entries--;
8699d66e233SJosef Bacik 	}
8709d66e233SJosef Bacik 
8712f120c05SJosef Bacik 	io_ctl_unmap_page(&io_ctl);
8722f120c05SJosef Bacik 
8739d66e233SJosef Bacik 	/*
8749d66e233SJosef Bacik 	 * We add the bitmaps at the end of the entries in order that
8759d66e233SJosef Bacik 	 * the bitmap entries are added to the cache.
8769d66e233SJosef Bacik 	 */
877a67509c3SJosef Bacik 	list_for_each_entry_safe(e, n, &bitmaps, list) {
8789d66e233SJosef Bacik 		list_del_init(&e->list);
8795b0e95bfSJosef Bacik 		ret = io_ctl_read_bitmap(&io_ctl, e);
8805b0e95bfSJosef Bacik 		if (ret)
8815b0e95bfSJosef Bacik 			goto free_cache;
8829d66e233SJosef Bacik 	}
8839d66e233SJosef Bacik 
884a67509c3SJosef Bacik 	io_ctl_drop_pages(&io_ctl);
8859d66e233SJosef Bacik 	ret = 1;
8869d66e233SJosef Bacik out:
887a67509c3SJosef Bacik 	io_ctl_free(&io_ctl);
8889d66e233SJosef Bacik 	return ret;
8899d66e233SJosef Bacik free_cache:
890a67509c3SJosef Bacik 	io_ctl_drop_pages(&io_ctl);
8918a1ae278SJosef Bacik 
8928a1ae278SJosef Bacik 	spin_lock(&ctl->tree_lock);
893fc80f7acSJosef Bacik 	__btrfs_remove_free_space_cache(ctl);
8948a1ae278SJosef Bacik 	spin_unlock(&ctl->tree_lock);
8950414efaeSLi Zefan 	goto out;
8960414efaeSLi Zefan }
8970414efaeSLi Zefan 
copy_free_space_cache(struct btrfs_block_group * block_group,struct btrfs_free_space_ctl * ctl)898cd79909bSJosef Bacik static int copy_free_space_cache(struct btrfs_block_group *block_group,
899cd79909bSJosef Bacik 				 struct btrfs_free_space_ctl *ctl)
900cd79909bSJosef Bacik {
901cd79909bSJosef Bacik 	struct btrfs_free_space *info;
902cd79909bSJosef Bacik 	struct rb_node *n;
903cd79909bSJosef Bacik 	int ret = 0;
904cd79909bSJosef Bacik 
905cd79909bSJosef Bacik 	while (!ret && (n = rb_first(&ctl->free_space_offset)) != NULL) {
906cd79909bSJosef Bacik 		info = rb_entry(n, struct btrfs_free_space, offset_index);
907cd79909bSJosef Bacik 		if (!info->bitmap) {
908fbb2e654SFilipe Manana 			const u64 offset = info->offset;
909fbb2e654SFilipe Manana 			const u64 bytes = info->bytes;
910fbb2e654SFilipe Manana 
91132e1649bSNikolay Borisov 			unlink_free_space(ctl, info, true);
9127e5ba559SFilipe Manana 			spin_unlock(&ctl->tree_lock);
913cd79909bSJosef Bacik 			kmem_cache_free(btrfs_free_space_cachep, info);
914fbb2e654SFilipe Manana 			ret = btrfs_add_free_space(block_group, offset, bytes);
9157e5ba559SFilipe Manana 			spin_lock(&ctl->tree_lock);
916cd79909bSJosef Bacik 		} else {
917cd79909bSJosef Bacik 			u64 offset = info->offset;
918cd79909bSJosef Bacik 			u64 bytes = ctl->unit;
919cd79909bSJosef Bacik 
9207e5ba559SFilipe Manana 			ret = search_bitmap(ctl, info, &offset, &bytes, false);
9217e5ba559SFilipe Manana 			if (ret == 0) {
9227e5ba559SFilipe Manana 				bitmap_clear_bits(ctl, info, offset, bytes, true);
9237e5ba559SFilipe Manana 				spin_unlock(&ctl->tree_lock);
924cd79909bSJosef Bacik 				ret = btrfs_add_free_space(block_group, offset,
925cd79909bSJosef Bacik 							   bytes);
9267e5ba559SFilipe Manana 				spin_lock(&ctl->tree_lock);
9277e5ba559SFilipe Manana 			} else {
928cd79909bSJosef Bacik 				free_bitmap(ctl, info);
9297e5ba559SFilipe Manana 				ret = 0;
930cd79909bSJosef Bacik 			}
9317e5ba559SFilipe Manana 		}
9327e5ba559SFilipe Manana 		cond_resched_lock(&ctl->tree_lock);
933cd79909bSJosef Bacik 	}
934cd79909bSJosef Bacik 	return ret;
935cd79909bSJosef Bacik }
936cd79909bSJosef Bacik 
9379d7464c8SIoannis Angelakopoulos static struct lock_class_key btrfs_free_space_inode_key;
9389d7464c8SIoannis Angelakopoulos 
load_free_space_cache(struct btrfs_block_group * block_group)93932da5386SDavid Sterba int load_free_space_cache(struct btrfs_block_group *block_group)
9400414efaeSLi Zefan {
941bb6cb1c5SDavid Sterba 	struct btrfs_fs_info *fs_info = block_group->fs_info;
9420414efaeSLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
943cd79909bSJosef Bacik 	struct btrfs_free_space_ctl tmp_ctl = {};
9440414efaeSLi Zefan 	struct inode *inode;
9450414efaeSLi Zefan 	struct btrfs_path *path;
9465b0e95bfSJosef Bacik 	int ret = 0;
9470414efaeSLi Zefan 	bool matched;
948bf38be65SDavid Sterba 	u64 used = block_group->used;
9490414efaeSLi Zefan 
9500414efaeSLi Zefan 	/*
951cd79909bSJosef Bacik 	 * Because we could potentially discard our loaded free space, we want
952cd79909bSJosef Bacik 	 * to load everything into a temporary structure first, and then if it's
953cd79909bSJosef Bacik 	 * valid copy it all into the actual free space ctl.
954cd79909bSJosef Bacik 	 */
955cd79909bSJosef Bacik 	btrfs_init_free_space_ctl(block_group, &tmp_ctl);
956cd79909bSJosef Bacik 
957cd79909bSJosef Bacik 	/*
9580414efaeSLi Zefan 	 * If this block group has been marked to be cleared for one reason or
9590414efaeSLi Zefan 	 * another then we can't trust the on disk cache, so just return.
9600414efaeSLi Zefan 	 */
9610414efaeSLi Zefan 	spin_lock(&block_group->lock);
9620414efaeSLi Zefan 	if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
9630414efaeSLi Zefan 		spin_unlock(&block_group->lock);
9640414efaeSLi Zefan 		return 0;
9650414efaeSLi Zefan 	}
9660414efaeSLi Zefan 	spin_unlock(&block_group->lock);
9670414efaeSLi Zefan 
9680414efaeSLi Zefan 	path = btrfs_alloc_path();
9690414efaeSLi Zefan 	if (!path)
9700414efaeSLi Zefan 		return 0;
971d53ba474SJosef Bacik 	path->search_commit_root = 1;
972d53ba474SJosef Bacik 	path->skip_locking = 1;
9730414efaeSLi Zefan 
9744222ea71SFilipe Manana 	/*
9754222ea71SFilipe Manana 	 * We must pass a path with search_commit_root set to btrfs_iget in
9764222ea71SFilipe Manana 	 * order to avoid a deadlock when allocating extents for the tree root.
9774222ea71SFilipe Manana 	 *
9784222ea71SFilipe Manana 	 * When we are COWing an extent buffer from the tree root, when looking
9794222ea71SFilipe Manana 	 * for a free extent, at extent-tree.c:find_free_extent(), we can find
9804222ea71SFilipe Manana 	 * block group without its free space cache loaded. When we find one
9814222ea71SFilipe Manana 	 * we must load its space cache which requires reading its free space
9824222ea71SFilipe Manana 	 * cache's inode item from the root tree. If this inode item is located
9834222ea71SFilipe Manana 	 * in the same leaf that we started COWing before, then we end up in
9844222ea71SFilipe Manana 	 * deadlock on the extent buffer (trying to read lock it when we
9854222ea71SFilipe Manana 	 * previously write locked it).
9864222ea71SFilipe Manana 	 *
9874222ea71SFilipe Manana 	 * It's safe to read the inode item using the commit root because
9884222ea71SFilipe Manana 	 * block groups, once loaded, stay in memory forever (until they are
9894222ea71SFilipe Manana 	 * removed) as well as their space caches once loaded. New block groups
9904222ea71SFilipe Manana 	 * once created get their ->cached field set to BTRFS_CACHE_FINISHED so
9914222ea71SFilipe Manana 	 * we will never try to read their inode item while the fs is mounted.
9924222ea71SFilipe Manana 	 */
9937949f339SDavid Sterba 	inode = lookup_free_space_inode(block_group, path);
9940414efaeSLi Zefan 	if (IS_ERR(inode)) {
9950414efaeSLi Zefan 		btrfs_free_path(path);
9960414efaeSLi Zefan 		return 0;
9970414efaeSLi Zefan 	}
9980414efaeSLi Zefan 
9995b0e95bfSJosef Bacik 	/* We may have converted the inode and made the cache invalid. */
10005b0e95bfSJosef Bacik 	spin_lock(&block_group->lock);
10015b0e95bfSJosef Bacik 	if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
10025b0e95bfSJosef Bacik 		spin_unlock(&block_group->lock);
1003a7e221e9STsutomu Itoh 		btrfs_free_path(path);
10045b0e95bfSJosef Bacik 		goto out;
10055b0e95bfSJosef Bacik 	}
10065b0e95bfSJosef Bacik 	spin_unlock(&block_group->lock);
10075b0e95bfSJosef Bacik 
10089d7464c8SIoannis Angelakopoulos 	/*
10099d7464c8SIoannis Angelakopoulos 	 * Reinitialize the class of struct inode's mapping->invalidate_lock for
10109d7464c8SIoannis Angelakopoulos 	 * free space inodes to prevent false positives related to locks for normal
10119d7464c8SIoannis Angelakopoulos 	 * inodes.
10129d7464c8SIoannis Angelakopoulos 	 */
10139d7464c8SIoannis Angelakopoulos 	lockdep_set_class(&(&inode->i_data)->invalidate_lock,
10149d7464c8SIoannis Angelakopoulos 			  &btrfs_free_space_inode_key);
10159d7464c8SIoannis Angelakopoulos 
1016cd79909bSJosef Bacik 	ret = __load_free_space_cache(fs_info->tree_root, inode, &tmp_ctl,
1017b3470b5dSDavid Sterba 				      path, block_group->start);
10180414efaeSLi Zefan 	btrfs_free_path(path);
10190414efaeSLi Zefan 	if (ret <= 0)
10200414efaeSLi Zefan 		goto out;
10210414efaeSLi Zefan 
1022cd79909bSJosef Bacik 	matched = (tmp_ctl.free_space == (block_group->length - used -
10230414efaeSLi Zefan 					  block_group->bytes_super));
10240414efaeSLi Zefan 
1025cd79909bSJosef Bacik 	if (matched) {
10267e5ba559SFilipe Manana 		spin_lock(&tmp_ctl.tree_lock);
1027cd79909bSJosef Bacik 		ret = copy_free_space_cache(block_group, &tmp_ctl);
10287e5ba559SFilipe Manana 		spin_unlock(&tmp_ctl.tree_lock);
1029cd79909bSJosef Bacik 		/*
1030cd79909bSJosef Bacik 		 * ret == 1 means we successfully loaded the free space cache,
1031cd79909bSJosef Bacik 		 * so we need to re-set it here.
1032cd79909bSJosef Bacik 		 */
1033cd79909bSJosef Bacik 		if (ret == 0)
1034cd79909bSJosef Bacik 			ret = 1;
1035cd79909bSJosef Bacik 	} else {
10368a1ae278SJosef Bacik 		/*
10378a1ae278SJosef Bacik 		 * We need to call the _locked variant so we don't try to update
10388a1ae278SJosef Bacik 		 * the discard counters.
10398a1ae278SJosef Bacik 		 */
10408a1ae278SJosef Bacik 		spin_lock(&tmp_ctl.tree_lock);
1041cd79909bSJosef Bacik 		__btrfs_remove_free_space_cache(&tmp_ctl);
10428a1ae278SJosef Bacik 		spin_unlock(&tmp_ctl.tree_lock);
10435d163e0eSJeff Mahoney 		btrfs_warn(fs_info,
10445d163e0eSJeff Mahoney 			   "block group %llu has wrong amount of free space",
1045b3470b5dSDavid Sterba 			   block_group->start);
10460414efaeSLi Zefan 		ret = -1;
10470414efaeSLi Zefan 	}
10480414efaeSLi Zefan out:
10490414efaeSLi Zefan 	if (ret < 0) {
10509d66e233SJosef Bacik 		/* This cache is bogus, make sure it gets cleared */
10519d66e233SJosef Bacik 		spin_lock(&block_group->lock);
10529d66e233SJosef Bacik 		block_group->disk_cache_state = BTRFS_DC_CLEAR;
10539d66e233SJosef Bacik 		spin_unlock(&block_group->lock);
105482d5902dSLi Zefan 		ret = 0;
10550414efaeSLi Zefan 
10565d163e0eSJeff Mahoney 		btrfs_warn(fs_info,
10575d163e0eSJeff Mahoney 			   "failed to load free space cache for block group %llu, rebuilding it now",
1058b3470b5dSDavid Sterba 			   block_group->start);
10599d66e233SJosef Bacik 	}
10609d66e233SJosef Bacik 
106166b53baeSJosef Bacik 	spin_lock(&ctl->tree_lock);
106266b53baeSJosef Bacik 	btrfs_discard_update_discardable(block_group);
106366b53baeSJosef Bacik 	spin_unlock(&ctl->tree_lock);
10640414efaeSLi Zefan 	iput(inode);
10650414efaeSLi Zefan 	return ret;
10660414efaeSLi Zefan }
10670414efaeSLi Zefan 
1068d4452bc5SChris Mason static noinline_for_stack
write_cache_extent_entries(struct btrfs_io_ctl * io_ctl,struct btrfs_free_space_ctl * ctl,struct btrfs_block_group * block_group,int * entries,int * bitmaps,struct list_head * bitmap_list)10694c6d1d85SChris Mason int write_cache_extent_entries(struct btrfs_io_ctl *io_ctl,
10700414efaeSLi Zefan 			      struct btrfs_free_space_ctl *ctl,
107132da5386SDavid Sterba 			      struct btrfs_block_group *block_group,
1072d4452bc5SChris Mason 			      int *entries, int *bitmaps,
1073d4452bc5SChris Mason 			      struct list_head *bitmap_list)
10740cb59c99SJosef Bacik {
1075c09544e0SJosef Bacik 	int ret;
1076d4452bc5SChris Mason 	struct btrfs_free_cluster *cluster = NULL;
10771bbc621eSChris Mason 	struct btrfs_free_cluster *cluster_locked = NULL;
1078d4452bc5SChris Mason 	struct rb_node *node = rb_first(&ctl->free_space_offset);
107955507ce3SFilipe Manana 	struct btrfs_trim_range *trim_entry;
1080be1a12a0SJosef Bacik 
108143be2146SJosef Bacik 	/* Get the cluster for this block_group if it exists */
1082d4452bc5SChris Mason 	if (block_group && !list_empty(&block_group->cluster_list)) {
108343be2146SJosef Bacik 		cluster = list_entry(block_group->cluster_list.next,
108443be2146SJosef Bacik 				     struct btrfs_free_cluster,
108543be2146SJosef Bacik 				     block_group_list);
1086d4452bc5SChris Mason 	}
108743be2146SJosef Bacik 
1088f75b130eSJosef Bacik 	if (!node && cluster) {
10891bbc621eSChris Mason 		cluster_locked = cluster;
10901bbc621eSChris Mason 		spin_lock(&cluster_locked->lock);
1091f75b130eSJosef Bacik 		node = rb_first(&cluster->root);
1092f75b130eSJosef Bacik 		cluster = NULL;
1093f75b130eSJosef Bacik 	}
1094f75b130eSJosef Bacik 
10950cb59c99SJosef Bacik 	/* Write out the extent entries */
1096a67509c3SJosef Bacik 	while (node) {
10970cb59c99SJosef Bacik 		struct btrfs_free_space *e;
10980cb59c99SJosef Bacik 
10990cb59c99SJosef Bacik 		e = rb_entry(node, struct btrfs_free_space, offset_index);
1100d4452bc5SChris Mason 		*entries += 1;
11010cb59c99SJosef Bacik 
1102d4452bc5SChris Mason 		ret = io_ctl_add_entry(io_ctl, e->offset, e->bytes,
1103a67509c3SJosef Bacik 				       e->bitmap);
1104a67509c3SJosef Bacik 		if (ret)
1105d4452bc5SChris Mason 			goto fail;
1106a67509c3SJosef Bacik 
11070cb59c99SJosef Bacik 		if (e->bitmap) {
1108d4452bc5SChris Mason 			list_add_tail(&e->list, bitmap_list);
1109d4452bc5SChris Mason 			*bitmaps += 1;
11100cb59c99SJosef Bacik 		}
11110cb59c99SJosef Bacik 		node = rb_next(node);
111243be2146SJosef Bacik 		if (!node && cluster) {
111343be2146SJosef Bacik 			node = rb_first(&cluster->root);
11141bbc621eSChris Mason 			cluster_locked = cluster;
11151bbc621eSChris Mason 			spin_lock(&cluster_locked->lock);
111643be2146SJosef Bacik 			cluster = NULL;
111743be2146SJosef Bacik 		}
111843be2146SJosef Bacik 	}
11191bbc621eSChris Mason 	if (cluster_locked) {
11201bbc621eSChris Mason 		spin_unlock(&cluster_locked->lock);
11211bbc621eSChris Mason 		cluster_locked = NULL;
11221bbc621eSChris Mason 	}
112355507ce3SFilipe Manana 
112455507ce3SFilipe Manana 	/*
112555507ce3SFilipe Manana 	 * Make sure we don't miss any range that was removed from our rbtree
112655507ce3SFilipe Manana 	 * because trimming is running. Otherwise after a umount+mount (or crash
112755507ce3SFilipe Manana 	 * after committing the transaction) we would leak free space and get
112855507ce3SFilipe Manana 	 * an inconsistent free space cache report from fsck.
112955507ce3SFilipe Manana 	 */
113055507ce3SFilipe Manana 	list_for_each_entry(trim_entry, &ctl->trimming_ranges, list) {
113155507ce3SFilipe Manana 		ret = io_ctl_add_entry(io_ctl, trim_entry->start,
113255507ce3SFilipe Manana 				       trim_entry->bytes, NULL);
113355507ce3SFilipe Manana 		if (ret)
113455507ce3SFilipe Manana 			goto fail;
113555507ce3SFilipe Manana 		*entries += 1;
113655507ce3SFilipe Manana 	}
113755507ce3SFilipe Manana 
1138d4452bc5SChris Mason 	return 0;
1139d4452bc5SChris Mason fail:
11401bbc621eSChris Mason 	if (cluster_locked)
11411bbc621eSChris Mason 		spin_unlock(&cluster_locked->lock);
1142d4452bc5SChris Mason 	return -ENOSPC;
1143d4452bc5SChris Mason }
1144d4452bc5SChris Mason 
1145d4452bc5SChris Mason static noinline_for_stack int
update_cache_item(struct btrfs_trans_handle * trans,struct btrfs_root * root,struct inode * inode,struct btrfs_path * path,u64 offset,int entries,int bitmaps)1146d4452bc5SChris Mason update_cache_item(struct btrfs_trans_handle *trans,
1147d4452bc5SChris Mason 		  struct btrfs_root *root,
1148d4452bc5SChris Mason 		  struct inode *inode,
1149d4452bc5SChris Mason 		  struct btrfs_path *path, u64 offset,
1150d4452bc5SChris Mason 		  int entries, int bitmaps)
1151d4452bc5SChris Mason {
1152d4452bc5SChris Mason 	struct btrfs_key key;
1153d4452bc5SChris Mason 	struct btrfs_free_space_header *header;
1154d4452bc5SChris Mason 	struct extent_buffer *leaf;
1155d4452bc5SChris Mason 	int ret;
1156d4452bc5SChris Mason 
1157d4452bc5SChris Mason 	key.objectid = BTRFS_FREE_SPACE_OBJECTID;
1158d4452bc5SChris Mason 	key.offset = offset;
1159d4452bc5SChris Mason 	key.type = 0;
1160d4452bc5SChris Mason 
1161d4452bc5SChris Mason 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1162d4452bc5SChris Mason 	if (ret < 0) {
1163d4452bc5SChris Mason 		clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1,
1164bd015294SJosef Bacik 				 EXTENT_DELALLOC, NULL);
1165d4452bc5SChris Mason 		goto fail;
1166d4452bc5SChris Mason 	}
1167d4452bc5SChris Mason 	leaf = path->nodes[0];
1168d4452bc5SChris Mason 	if (ret > 0) {
1169d4452bc5SChris Mason 		struct btrfs_key found_key;
1170d4452bc5SChris Mason 		ASSERT(path->slots[0]);
1171d4452bc5SChris Mason 		path->slots[0]--;
1172d4452bc5SChris Mason 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1173d4452bc5SChris Mason 		if (found_key.objectid != BTRFS_FREE_SPACE_OBJECTID ||
1174d4452bc5SChris Mason 		    found_key.offset != offset) {
1175d4452bc5SChris Mason 			clear_extent_bit(&BTRFS_I(inode)->io_tree, 0,
1176bd015294SJosef Bacik 					 inode->i_size - 1, EXTENT_DELALLOC,
1177dbbf4992SJosef Bacik 					 NULL);
1178d4452bc5SChris Mason 			btrfs_release_path(path);
1179d4452bc5SChris Mason 			goto fail;
1180d4452bc5SChris Mason 		}
1181d4452bc5SChris Mason 	}
1182d4452bc5SChris Mason 
1183d4452bc5SChris Mason 	BTRFS_I(inode)->generation = trans->transid;
1184d4452bc5SChris Mason 	header = btrfs_item_ptr(leaf, path->slots[0],
1185d4452bc5SChris Mason 				struct btrfs_free_space_header);
1186d4452bc5SChris Mason 	btrfs_set_free_space_entries(leaf, header, entries);
1187d4452bc5SChris Mason 	btrfs_set_free_space_bitmaps(leaf, header, bitmaps);
1188d4452bc5SChris Mason 	btrfs_set_free_space_generation(leaf, header, trans->transid);
1189d5e09e38SFilipe Manana 	btrfs_mark_buffer_dirty(trans, leaf);
1190d4452bc5SChris Mason 	btrfs_release_path(path);
1191d4452bc5SChris Mason 
1192d4452bc5SChris Mason 	return 0;
1193d4452bc5SChris Mason 
1194d4452bc5SChris Mason fail:
1195d4452bc5SChris Mason 	return -1;
1196d4452bc5SChris Mason }
1197d4452bc5SChris Mason 
write_pinned_extent_entries(struct btrfs_trans_handle * trans,struct btrfs_block_group * block_group,struct btrfs_io_ctl * io_ctl,int * entries)11986701bdb3SDavid Sterba static noinline_for_stack int write_pinned_extent_entries(
11996b45f641SNikolay Borisov 			    struct btrfs_trans_handle *trans,
120032da5386SDavid Sterba 			    struct btrfs_block_group *block_group,
12014c6d1d85SChris Mason 			    struct btrfs_io_ctl *io_ctl,
1202d4452bc5SChris Mason 			    int *entries)
1203d4452bc5SChris Mason {
1204d4452bc5SChris Mason 	u64 start, extent_start, extent_end, len;
1205d4452bc5SChris Mason 	struct extent_io_tree *unpin = NULL;
1206d4452bc5SChris Mason 	int ret;
120743be2146SJosef Bacik 
12085349d6c3SMiao Xie 	if (!block_group)
12095349d6c3SMiao Xie 		return 0;
12105349d6c3SMiao Xie 
121143be2146SJosef Bacik 	/*
121243be2146SJosef Bacik 	 * We want to add any pinned extents to our free space cache
121343be2146SJosef Bacik 	 * so we don't leak the space
1214d4452bc5SChris Mason 	 *
1215db804f23SLi Zefan 	 * We shouldn't have switched the pinned extents yet so this is the
1216db804f23SLi Zefan 	 * right one
1217db804f23SLi Zefan 	 */
1218fe119a6eSNikolay Borisov 	unpin = &trans->transaction->pinned_extents;
1219db804f23SLi Zefan 
1220b3470b5dSDavid Sterba 	start = block_group->start;
1221db804f23SLi Zefan 
1222b3470b5dSDavid Sterba 	while (start < block_group->start + block_group->length) {
1223e5860f82SFilipe Manana 		if (!find_first_extent_bit(unpin, start,
1224db804f23SLi Zefan 					   &extent_start, &extent_end,
1225e5860f82SFilipe Manana 					   EXTENT_DIRTY, NULL))
12265349d6c3SMiao Xie 			return 0;
122743be2146SJosef Bacik 
122843be2146SJosef Bacik 		/* This pinned extent is out of our range */
1229b3470b5dSDavid Sterba 		if (extent_start >= block_group->start + block_group->length)
12305349d6c3SMiao Xie 			return 0;
123143be2146SJosef Bacik 
1232db804f23SLi Zefan 		extent_start = max(extent_start, start);
1233b3470b5dSDavid Sterba 		extent_end = min(block_group->start + block_group->length,
1234b3470b5dSDavid Sterba 				 extent_end + 1);
1235db804f23SLi Zefan 		len = extent_end - extent_start;
123643be2146SJosef Bacik 
1237d4452bc5SChris Mason 		*entries += 1;
1238d4452bc5SChris Mason 		ret = io_ctl_add_entry(io_ctl, extent_start, len, NULL);
1239a67509c3SJosef Bacik 		if (ret)
12405349d6c3SMiao Xie 			return -ENOSPC;
124143be2146SJosef Bacik 
1242db804f23SLi Zefan 		start = extent_end;
12430cb59c99SJosef Bacik 	}
12440cb59c99SJosef Bacik 
12455349d6c3SMiao Xie 	return 0;
12465349d6c3SMiao Xie }
12475349d6c3SMiao Xie 
12485349d6c3SMiao Xie static noinline_for_stack int
write_bitmap_entries(struct btrfs_io_ctl * io_ctl,struct list_head * bitmap_list)12494c6d1d85SChris Mason write_bitmap_entries(struct btrfs_io_ctl *io_ctl, struct list_head *bitmap_list)
12505349d6c3SMiao Xie {
12517ae1681eSGeliang Tang 	struct btrfs_free_space *entry, *next;
12525349d6c3SMiao Xie 	int ret;
12535349d6c3SMiao Xie 
12540cb59c99SJosef Bacik 	/* Write out the bitmaps */
12557ae1681eSGeliang Tang 	list_for_each_entry_safe(entry, next, bitmap_list, list) {
1256d4452bc5SChris Mason 		ret = io_ctl_add_bitmap(io_ctl, entry->bitmap);
1257a67509c3SJosef Bacik 		if (ret)
12585349d6c3SMiao Xie 			return -ENOSPC;
12590cb59c99SJosef Bacik 		list_del_init(&entry->list);
1260be1a12a0SJosef Bacik 	}
1261be1a12a0SJosef Bacik 
12625349d6c3SMiao Xie 	return 0;
12635349d6c3SMiao Xie }
12640cb59c99SJosef Bacik 
flush_dirty_cache(struct inode * inode)12655349d6c3SMiao Xie static int flush_dirty_cache(struct inode *inode)
12665349d6c3SMiao Xie {
12675349d6c3SMiao Xie 	int ret;
1268be1a12a0SJosef Bacik 
12690ef8b726SJosef Bacik 	ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
12705349d6c3SMiao Xie 	if (ret)
12710ef8b726SJosef Bacik 		clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1,
1272bd015294SJosef Bacik 				 EXTENT_DELALLOC, NULL);
1273d4452bc5SChris Mason 
12745349d6c3SMiao Xie 	return ret;
12750ef8b726SJosef Bacik }
12760cb59c99SJosef Bacik 
1277d4452bc5SChris Mason static void noinline_for_stack
cleanup_bitmap_list(struct list_head * bitmap_list)1278a3bdccc4SChris Mason cleanup_bitmap_list(struct list_head *bitmap_list)
1279d4452bc5SChris Mason {
12807ae1681eSGeliang Tang 	struct btrfs_free_space *entry, *next;
12815349d6c3SMiao Xie 
12827ae1681eSGeliang Tang 	list_for_each_entry_safe(entry, next, bitmap_list, list)
1283d4452bc5SChris Mason 		list_del_init(&entry->list);
1284d4452bc5SChris Mason }
1285a3bdccc4SChris Mason 
1286a3bdccc4SChris Mason static void noinline_for_stack
cleanup_write_cache_enospc(struct inode * inode,struct btrfs_io_ctl * io_ctl,struct extent_state ** cached_state)1287a3bdccc4SChris Mason cleanup_write_cache_enospc(struct inode *inode,
1288a3bdccc4SChris Mason 			   struct btrfs_io_ctl *io_ctl,
12897bf1a159SDavid Sterba 			   struct extent_state **cached_state)
1290a3bdccc4SChris Mason {
1291d4452bc5SChris Mason 	io_ctl_drop_pages(io_ctl);
1292570eb97bSJosef Bacik 	unlock_extent(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1,
1293570eb97bSJosef Bacik 		      cached_state);
12940cb59c99SJosef Bacik }
1295549b4fdbSJosef Bacik 
__btrfs_wait_cache_io(struct btrfs_root * root,struct btrfs_trans_handle * trans,struct btrfs_block_group * block_group,struct btrfs_io_ctl * io_ctl,struct btrfs_path * path,u64 offset)1296afdb5718SJeff Mahoney static int __btrfs_wait_cache_io(struct btrfs_root *root,
1297c9dc4c65SChris Mason 				 struct btrfs_trans_handle *trans,
129832da5386SDavid Sterba 				 struct btrfs_block_group *block_group,
1299c9dc4c65SChris Mason 				 struct btrfs_io_ctl *io_ctl,
1300c9dc4c65SChris Mason 				 struct btrfs_path *path, u64 offset)
1301c9dc4c65SChris Mason {
1302c9dc4c65SChris Mason 	int ret;
1303c9dc4c65SChris Mason 	struct inode *inode = io_ctl->inode;
1304c9dc4c65SChris Mason 
13051bbc621eSChris Mason 	if (!inode)
13061bbc621eSChris Mason 		return 0;
13071bbc621eSChris Mason 
1308c9dc4c65SChris Mason 	/* Flush the dirty pages in the cache file. */
1309c9dc4c65SChris Mason 	ret = flush_dirty_cache(inode);
1310c9dc4c65SChris Mason 	if (ret)
1311c9dc4c65SChris Mason 		goto out;
1312c9dc4c65SChris Mason 
1313c9dc4c65SChris Mason 	/* Update the cache item to tell everyone this cache file is valid. */
1314c9dc4c65SChris Mason 	ret = update_cache_item(trans, root, inode, path, offset,
1315c9dc4c65SChris Mason 				io_ctl->entries, io_ctl->bitmaps);
1316c9dc4c65SChris Mason out:
1317c9dc4c65SChris Mason 	if (ret) {
1318c9dc4c65SChris Mason 		invalidate_inode_pages2(inode->i_mapping);
1319c9dc4c65SChris Mason 		BTRFS_I(inode)->generation = 0;
1320bbcd1f4dSFilipe Manana 		if (block_group)
1321bbcd1f4dSFilipe Manana 			btrfs_debug(root->fs_info,
13222e69a7a6SFilipe Manana 	  "failed to write free space cache for block group %llu error %d",
13232e69a7a6SFilipe Manana 				  block_group->start, ret);
1324c9dc4c65SChris Mason 	}
13259a56fcd1SNikolay Borisov 	btrfs_update_inode(trans, root, BTRFS_I(inode));
1326c9dc4c65SChris Mason 
1327c9dc4c65SChris Mason 	if (block_group) {
13281bbc621eSChris Mason 		/* the dirty list is protected by the dirty_bgs_lock */
13291bbc621eSChris Mason 		spin_lock(&trans->transaction->dirty_bgs_lock);
13301bbc621eSChris Mason 
13311bbc621eSChris Mason 		/* the disk_cache_state is protected by the block group lock */
1332c9dc4c65SChris Mason 		spin_lock(&block_group->lock);
1333c9dc4c65SChris Mason 
1334c9dc4c65SChris Mason 		/*
1335c9dc4c65SChris Mason 		 * only mark this as written if we didn't get put back on
13361bbc621eSChris Mason 		 * the dirty list while waiting for IO.   Otherwise our
13371bbc621eSChris Mason 		 * cache state won't be right, and we won't get written again
1338c9dc4c65SChris Mason 		 */
1339c9dc4c65SChris Mason 		if (!ret && list_empty(&block_group->dirty_list))
1340c9dc4c65SChris Mason 			block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1341c9dc4c65SChris Mason 		else if (ret)
1342c9dc4c65SChris Mason 			block_group->disk_cache_state = BTRFS_DC_ERROR;
1343c9dc4c65SChris Mason 
1344c9dc4c65SChris Mason 		spin_unlock(&block_group->lock);
13451bbc621eSChris Mason 		spin_unlock(&trans->transaction->dirty_bgs_lock);
1346c9dc4c65SChris Mason 		io_ctl->inode = NULL;
1347c9dc4c65SChris Mason 		iput(inode);
1348c9dc4c65SChris Mason 	}
1349c9dc4c65SChris Mason 
1350c9dc4c65SChris Mason 	return ret;
1351c9dc4c65SChris Mason 
1352c9dc4c65SChris Mason }
1353c9dc4c65SChris Mason 
btrfs_wait_cache_io(struct btrfs_trans_handle * trans,struct btrfs_block_group * block_group,struct btrfs_path * path)1354afdb5718SJeff Mahoney int btrfs_wait_cache_io(struct btrfs_trans_handle *trans,
135532da5386SDavid Sterba 			struct btrfs_block_group *block_group,
1356afdb5718SJeff Mahoney 			struct btrfs_path *path)
1357afdb5718SJeff Mahoney {
1358afdb5718SJeff Mahoney 	return __btrfs_wait_cache_io(block_group->fs_info->tree_root, trans,
1359afdb5718SJeff Mahoney 				     block_group, &block_group->io_ctl,
1360b3470b5dSDavid Sterba 				     path, block_group->start);
1361afdb5718SJeff Mahoney }
1362afdb5718SJeff Mahoney 
136343dd529aSDavid Sterba /*
136443dd529aSDavid Sterba  * Write out cached info to an inode.
1365f092cf3cSNikolay Borisov  *
1366f092cf3cSNikolay Borisov  * @root:        root the inode belongs to
1367f092cf3cSNikolay Borisov  * @inode:       freespace inode we are writing out
1368f092cf3cSNikolay Borisov  * @ctl:         free space cache we are going to write out
1369f092cf3cSNikolay Borisov  * @block_group: block_group for this cache if it belongs to a block_group
1370f092cf3cSNikolay Borisov  * @io_ctl:      holds context for the io
1371f092cf3cSNikolay Borisov  * @trans:       the trans handle
1372d4452bc5SChris Mason  *
1373d4452bc5SChris Mason  * This function writes out a free space cache struct to disk for quick recovery
13748cd1e731SGeliang Tang  * on mount.  This will return 0 if it was successful in writing the cache out,
1375b8605454SOmar Sandoval  * or an errno if it was not.
1376d4452bc5SChris Mason  */
__btrfs_write_out_cache(struct btrfs_root * root,struct inode * inode,struct btrfs_free_space_ctl * ctl,struct btrfs_block_group * block_group,struct btrfs_io_ctl * io_ctl,struct btrfs_trans_handle * trans)1377d4452bc5SChris Mason static int __btrfs_write_out_cache(struct btrfs_root *root, struct inode *inode,
1378d4452bc5SChris Mason 				   struct btrfs_free_space_ctl *ctl,
137932da5386SDavid Sterba 				   struct btrfs_block_group *block_group,
1380c9dc4c65SChris Mason 				   struct btrfs_io_ctl *io_ctl,
13810e8d931aSDavid Sterba 				   struct btrfs_trans_handle *trans)
1382d4452bc5SChris Mason {
1383d4452bc5SChris Mason 	struct extent_state *cached_state = NULL;
13845349d6c3SMiao Xie 	LIST_HEAD(bitmap_list);
1385d4452bc5SChris Mason 	int entries = 0;
1386d4452bc5SChris Mason 	int bitmaps = 0;
1387d4452bc5SChris Mason 	int ret;
1388c9dc4c65SChris Mason 	int must_iput = 0;
1389d4452bc5SChris Mason 
1390d4452bc5SChris Mason 	if (!i_size_read(inode))
1391b8605454SOmar Sandoval 		return -EIO;
1392d4452bc5SChris Mason 
1393c9dc4c65SChris Mason 	WARN_ON(io_ctl->pages);
1394f15376dfSJeff Mahoney 	ret = io_ctl_init(io_ctl, inode, 1);
1395d4452bc5SChris Mason 	if (ret)
1396b8605454SOmar Sandoval 		return ret;
1397d4452bc5SChris Mason 
1398e570fd27SMiao Xie 	if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA)) {
1399e570fd27SMiao Xie 		down_write(&block_group->data_rwsem);
1400e570fd27SMiao Xie 		spin_lock(&block_group->lock);
1401e570fd27SMiao Xie 		if (block_group->delalloc_bytes) {
1402e570fd27SMiao Xie 			block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1403e570fd27SMiao Xie 			spin_unlock(&block_group->lock);
1404e570fd27SMiao Xie 			up_write(&block_group->data_rwsem);
1405e570fd27SMiao Xie 			BTRFS_I(inode)->generation = 0;
1406e570fd27SMiao Xie 			ret = 0;
1407c9dc4c65SChris Mason 			must_iput = 1;
1408e570fd27SMiao Xie 			goto out;
1409e570fd27SMiao Xie 		}
1410e570fd27SMiao Xie 		spin_unlock(&block_group->lock);
1411e570fd27SMiao Xie 	}
1412e570fd27SMiao Xie 
1413d4452bc5SChris Mason 	/* Lock all pages first so we can lock the extent safely. */
14147a195f6dSJohannes Thumshirn 	ret = io_ctl_prepare_pages(io_ctl, false);
1415b8605454SOmar Sandoval 	if (ret)
1416b77000edSJosef Bacik 		goto out_unlock;
1417d4452bc5SChris Mason 
1418570eb97bSJosef Bacik 	lock_extent(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1,
1419ff13db41SDavid Sterba 		    &cached_state);
1420d4452bc5SChris Mason 
1421c9dc4c65SChris Mason 	io_ctl_set_generation(io_ctl, trans->transid);
1422d4452bc5SChris Mason 
142355507ce3SFilipe Manana 	mutex_lock(&ctl->cache_writeout_mutex);
14245349d6c3SMiao Xie 	/* Write out the extent entries in the free space cache */
14251bbc621eSChris Mason 	spin_lock(&ctl->tree_lock);
1426c9dc4c65SChris Mason 	ret = write_cache_extent_entries(io_ctl, ctl,
1427d4452bc5SChris Mason 					 block_group, &entries, &bitmaps,
1428d4452bc5SChris Mason 					 &bitmap_list);
1429a3bdccc4SChris Mason 	if (ret)
1430a3bdccc4SChris Mason 		goto out_nospc_locked;
1431d4452bc5SChris Mason 
14325349d6c3SMiao Xie 	/*
14335349d6c3SMiao Xie 	 * Some spaces that are freed in the current transaction are pinned,
14345349d6c3SMiao Xie 	 * they will be added into free space cache after the transaction is
14355349d6c3SMiao Xie 	 * committed, we shouldn't lose them.
14361bbc621eSChris Mason 	 *
14371bbc621eSChris Mason 	 * If this changes while we are working we'll get added back to
14381bbc621eSChris Mason 	 * the dirty list and redo it.  No locking needed
14395349d6c3SMiao Xie 	 */
14406b45f641SNikolay Borisov 	ret = write_pinned_extent_entries(trans, block_group, io_ctl, &entries);
1441a3bdccc4SChris Mason 	if (ret)
1442a3bdccc4SChris Mason 		goto out_nospc_locked;
14435349d6c3SMiao Xie 
144455507ce3SFilipe Manana 	/*
144555507ce3SFilipe Manana 	 * At last, we write out all the bitmaps and keep cache_writeout_mutex
144655507ce3SFilipe Manana 	 * locked while doing it because a concurrent trim can be manipulating
144755507ce3SFilipe Manana 	 * or freeing the bitmap.
144855507ce3SFilipe Manana 	 */
1449c9dc4c65SChris Mason 	ret = write_bitmap_entries(io_ctl, &bitmap_list);
14501bbc621eSChris Mason 	spin_unlock(&ctl->tree_lock);
145155507ce3SFilipe Manana 	mutex_unlock(&ctl->cache_writeout_mutex);
14525349d6c3SMiao Xie 	if (ret)
14535349d6c3SMiao Xie 		goto out_nospc;
14545349d6c3SMiao Xie 
14555349d6c3SMiao Xie 	/* Zero out the rest of the pages just to make sure */
1456c9dc4c65SChris Mason 	io_ctl_zero_remaining_pages(io_ctl);
14575349d6c3SMiao Xie 
14585349d6c3SMiao Xie 	/* Everything is written out, now we dirty the pages in the file. */
1459088545f6SNikolay Borisov 	ret = btrfs_dirty_pages(BTRFS_I(inode), io_ctl->pages,
1460088545f6SNikolay Borisov 				io_ctl->num_pages, 0, i_size_read(inode),
1461aa8c1a41SGoldwyn Rodrigues 				&cached_state, false);
14625349d6c3SMiao Xie 	if (ret)
14635349d6c3SMiao Xie 		goto out_nospc;
14645349d6c3SMiao Xie 
1465e570fd27SMiao Xie 	if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA))
1466e570fd27SMiao Xie 		up_write(&block_group->data_rwsem);
14675349d6c3SMiao Xie 	/*
14685349d6c3SMiao Xie 	 * Release the pages and unlock the extent, we will flush
14695349d6c3SMiao Xie 	 * them out later
14705349d6c3SMiao Xie 	 */
1471c9dc4c65SChris Mason 	io_ctl_drop_pages(io_ctl);
1472bbc37d6eSFilipe Manana 	io_ctl_free(io_ctl);
14735349d6c3SMiao Xie 
1474570eb97bSJosef Bacik 	unlock_extent(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1,
1475570eb97bSJosef Bacik 		      &cached_state);
14765349d6c3SMiao Xie 
1477c9dc4c65SChris Mason 	/*
1478c9dc4c65SChris Mason 	 * at this point the pages are under IO and we're happy,
1479260db43cSRandy Dunlap 	 * The caller is responsible for waiting on them and updating
1480c9dc4c65SChris Mason 	 * the cache and the inode
1481c9dc4c65SChris Mason 	 */
1482c9dc4c65SChris Mason 	io_ctl->entries = entries;
1483c9dc4c65SChris Mason 	io_ctl->bitmaps = bitmaps;
1484c9dc4c65SChris Mason 
1485c9dc4c65SChris Mason 	ret = btrfs_fdatawrite_range(inode, 0, (u64)-1);
14865349d6c3SMiao Xie 	if (ret)
1487d4452bc5SChris Mason 		goto out;
1488d4452bc5SChris Mason 
1489c9dc4c65SChris Mason 	return 0;
1490c9dc4c65SChris Mason 
1491a3bdccc4SChris Mason out_nospc_locked:
1492a3bdccc4SChris Mason 	cleanup_bitmap_list(&bitmap_list);
1493a3bdccc4SChris Mason 	spin_unlock(&ctl->tree_lock);
1494a3bdccc4SChris Mason 	mutex_unlock(&ctl->cache_writeout_mutex);
1495a3bdccc4SChris Mason 
1496a67509c3SJosef Bacik out_nospc:
14977bf1a159SDavid Sterba 	cleanup_write_cache_enospc(inode, io_ctl, &cached_state);
1498e570fd27SMiao Xie 
1499b77000edSJosef Bacik out_unlock:
1500e570fd27SMiao Xie 	if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA))
1501e570fd27SMiao Xie 		up_write(&block_group->data_rwsem);
1502e570fd27SMiao Xie 
1503fd8efa81SJohannes Thumshirn out:
1504fd8efa81SJohannes Thumshirn 	io_ctl->inode = NULL;
1505fd8efa81SJohannes Thumshirn 	io_ctl_free(io_ctl);
1506fd8efa81SJohannes Thumshirn 	if (ret) {
1507fd8efa81SJohannes Thumshirn 		invalidate_inode_pages2(inode->i_mapping);
1508fd8efa81SJohannes Thumshirn 		BTRFS_I(inode)->generation = 0;
1509fd8efa81SJohannes Thumshirn 	}
15109a56fcd1SNikolay Borisov 	btrfs_update_inode(trans, root, BTRFS_I(inode));
1511fd8efa81SJohannes Thumshirn 	if (must_iput)
1512fd8efa81SJohannes Thumshirn 		iput(inode);
1513fd8efa81SJohannes Thumshirn 	return ret;
15140414efaeSLi Zefan }
15150414efaeSLi Zefan 
btrfs_write_out_cache(struct btrfs_trans_handle * trans,struct btrfs_block_group * block_group,struct btrfs_path * path)1516fe041534SDavid Sterba int btrfs_write_out_cache(struct btrfs_trans_handle *trans,
151732da5386SDavid Sterba 			  struct btrfs_block_group *block_group,
15180414efaeSLi Zefan 			  struct btrfs_path *path)
15190414efaeSLi Zefan {
1520fe041534SDavid Sterba 	struct btrfs_fs_info *fs_info = trans->fs_info;
15210414efaeSLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
15220414efaeSLi Zefan 	struct inode *inode;
15230414efaeSLi Zefan 	int ret = 0;
15240414efaeSLi Zefan 
15250414efaeSLi Zefan 	spin_lock(&block_group->lock);
15260414efaeSLi Zefan 	if (block_group->disk_cache_state < BTRFS_DC_SETUP) {
15270414efaeSLi Zefan 		spin_unlock(&block_group->lock);
15280414efaeSLi Zefan 		return 0;
15290414efaeSLi Zefan 	}
15300414efaeSLi Zefan 	spin_unlock(&block_group->lock);
15310414efaeSLi Zefan 
15327949f339SDavid Sterba 	inode = lookup_free_space_inode(block_group, path);
15330414efaeSLi Zefan 	if (IS_ERR(inode))
15340414efaeSLi Zefan 		return 0;
15350414efaeSLi Zefan 
153677ab86bfSJeff Mahoney 	ret = __btrfs_write_out_cache(fs_info->tree_root, inode, ctl,
153777ab86bfSJeff Mahoney 				block_group, &block_group->io_ctl, trans);
1538c09544e0SJosef Bacik 	if (ret) {
1539bbcd1f4dSFilipe Manana 		btrfs_debug(fs_info,
15402e69a7a6SFilipe Manana 	  "failed to write free space cache for block group %llu error %d",
15412e69a7a6SFilipe Manana 			  block_group->start, ret);
1542c9dc4c65SChris Mason 		spin_lock(&block_group->lock);
1543c9dc4c65SChris Mason 		block_group->disk_cache_state = BTRFS_DC_ERROR;
1544c9dc4c65SChris Mason 		spin_unlock(&block_group->lock);
1545c9dc4c65SChris Mason 
1546c9dc4c65SChris Mason 		block_group->io_ctl.inode = NULL;
1547c9dc4c65SChris Mason 		iput(inode);
15480414efaeSLi Zefan 	}
15490414efaeSLi Zefan 
1550c9dc4c65SChris Mason 	/*
1551c9dc4c65SChris Mason 	 * if ret == 0 the caller is expected to call btrfs_wait_cache_io
1552c9dc4c65SChris Mason 	 * to wait for IO and put the inode
1553c9dc4c65SChris Mason 	 */
1554c9dc4c65SChris Mason 
15550cb59c99SJosef Bacik 	return ret;
15560cb59c99SJosef Bacik }
15570cb59c99SJosef Bacik 
offset_to_bit(u64 bitmap_start,u32 unit,u64 offset)155834d52cb6SLi Zefan static inline unsigned long offset_to_bit(u64 bitmap_start, u32 unit,
155996303081SJosef Bacik 					  u64 offset)
156096303081SJosef Bacik {
1561b12d6869SJosef Bacik 	ASSERT(offset >= bitmap_start);
156296303081SJosef Bacik 	offset -= bitmap_start;
156334d52cb6SLi Zefan 	return (unsigned long)(div_u64(offset, unit));
156496303081SJosef Bacik }
156596303081SJosef Bacik 
bytes_to_bits(u64 bytes,u32 unit)156634d52cb6SLi Zefan static inline unsigned long bytes_to_bits(u64 bytes, u32 unit)
156796303081SJosef Bacik {
156834d52cb6SLi Zefan 	return (unsigned long)(div_u64(bytes, unit));
156996303081SJosef Bacik }
157096303081SJosef Bacik 
offset_to_bitmap(struct btrfs_free_space_ctl * ctl,u64 offset)157134d52cb6SLi Zefan static inline u64 offset_to_bitmap(struct btrfs_free_space_ctl *ctl,
157296303081SJosef Bacik 				   u64 offset)
157396303081SJosef Bacik {
157496303081SJosef Bacik 	u64 bitmap_start;
15750ef6447aSFeifei Xu 	u64 bytes_per_bitmap;
157696303081SJosef Bacik 
157734d52cb6SLi Zefan 	bytes_per_bitmap = BITS_PER_BITMAP * ctl->unit;
157834d52cb6SLi Zefan 	bitmap_start = offset - ctl->start;
15790ef6447aSFeifei Xu 	bitmap_start = div64_u64(bitmap_start, bytes_per_bitmap);
158096303081SJosef Bacik 	bitmap_start *= bytes_per_bitmap;
158134d52cb6SLi Zefan 	bitmap_start += ctl->start;
158296303081SJosef Bacik 
158396303081SJosef Bacik 	return bitmap_start;
158496303081SJosef Bacik }
15850f9dd46cSJosef Bacik 
tree_insert_offset(struct btrfs_free_space_ctl * ctl,struct btrfs_free_cluster * cluster,struct btrfs_free_space * new_entry)158613c2018fSFilipe Manana static int tree_insert_offset(struct btrfs_free_space_ctl *ctl,
158713c2018fSFilipe Manana 			      struct btrfs_free_cluster *cluster,
15880d6bac4dSFilipe Manana 			      struct btrfs_free_space *new_entry)
15890f9dd46cSJosef Bacik {
159013c2018fSFilipe Manana 	struct rb_root *root;
159113c2018fSFilipe Manana 	struct rb_node **p;
15920f9dd46cSJosef Bacik 	struct rb_node *parent = NULL;
15930f9dd46cSJosef Bacik 
159413c2018fSFilipe Manana 	lockdep_assert_held(&ctl->tree_lock);
159513c2018fSFilipe Manana 
159613c2018fSFilipe Manana 	if (cluster) {
159713c2018fSFilipe Manana 		lockdep_assert_held(&cluster->lock);
159813c2018fSFilipe Manana 		root = &cluster->root;
159913c2018fSFilipe Manana 	} else {
160013c2018fSFilipe Manana 		root = &ctl->free_space_offset;
160113c2018fSFilipe Manana 	}
160213c2018fSFilipe Manana 
160313c2018fSFilipe Manana 	p = &root->rb_node;
160413c2018fSFilipe Manana 
16050f9dd46cSJosef Bacik 	while (*p) {
16060d6bac4dSFilipe Manana 		struct btrfs_free_space *info;
16070d6bac4dSFilipe Manana 
16080f9dd46cSJosef Bacik 		parent = *p;
16090f9dd46cSJosef Bacik 		info = rb_entry(parent, struct btrfs_free_space, offset_index);
16100f9dd46cSJosef Bacik 
16110d6bac4dSFilipe Manana 		if (new_entry->offset < info->offset) {
16120f9dd46cSJosef Bacik 			p = &(*p)->rb_left;
16130d6bac4dSFilipe Manana 		} else if (new_entry->offset > info->offset) {
16140f9dd46cSJosef Bacik 			p = &(*p)->rb_right;
161596303081SJosef Bacik 		} else {
161696303081SJosef Bacik 			/*
161796303081SJosef Bacik 			 * we could have a bitmap entry and an extent entry
161896303081SJosef Bacik 			 * share the same offset.  If this is the case, we want
161996303081SJosef Bacik 			 * the extent entry to always be found first if we do a
162096303081SJosef Bacik 			 * linear search through the tree, since we want to have
162196303081SJosef Bacik 			 * the quickest allocation time, and allocating from an
162296303081SJosef Bacik 			 * extent is faster than allocating from a bitmap.  So
162396303081SJosef Bacik 			 * if we're inserting a bitmap and we find an entry at
162496303081SJosef Bacik 			 * this offset, we want to go right, or after this entry
162596303081SJosef Bacik 			 * logically.  If we are inserting an extent and we've
162696303081SJosef Bacik 			 * found a bitmap, we want to go left, or before
162796303081SJosef Bacik 			 * logically.
162896303081SJosef Bacik 			 */
16290d6bac4dSFilipe Manana 			if (new_entry->bitmap) {
1630207dde82SJosef Bacik 				if (info->bitmap) {
1631207dde82SJosef Bacik 					WARN_ON_ONCE(1);
1632207dde82SJosef Bacik 					return -EEXIST;
1633207dde82SJosef Bacik 				}
163496303081SJosef Bacik 				p = &(*p)->rb_right;
163596303081SJosef Bacik 			} else {
1636207dde82SJosef Bacik 				if (!info->bitmap) {
1637207dde82SJosef Bacik 					WARN_ON_ONCE(1);
1638207dde82SJosef Bacik 					return -EEXIST;
1639207dde82SJosef Bacik 				}
16400f9dd46cSJosef Bacik 				p = &(*p)->rb_left;
164196303081SJosef Bacik 			}
164296303081SJosef Bacik 		}
16430f9dd46cSJosef Bacik 	}
16440f9dd46cSJosef Bacik 
16450d6bac4dSFilipe Manana 	rb_link_node(&new_entry->offset_index, parent, p);
16460d6bac4dSFilipe Manana 	rb_insert_color(&new_entry->offset_index, root);
16470f9dd46cSJosef Bacik 
16480f9dd46cSJosef Bacik 	return 0;
16490f9dd46cSJosef Bacik }
16500f9dd46cSJosef Bacik 
16510f9dd46cSJosef Bacik /*
165259c7b566SJosef Bacik  * This is a little subtle.  We *only* have ->max_extent_size set if we actually
165359c7b566SJosef Bacik  * searched through the bitmap and figured out the largest ->max_extent_size,
165459c7b566SJosef Bacik  * otherwise it's 0.  In the case that it's 0 we don't want to tell the
165559c7b566SJosef Bacik  * allocator the wrong thing, we want to use the actual real max_extent_size
165659c7b566SJosef Bacik  * we've found already if it's larger, or we want to use ->bytes.
165759c7b566SJosef Bacik  *
165859c7b566SJosef Bacik  * This matters because find_free_space() will skip entries who's ->bytes is
165959c7b566SJosef Bacik  * less than the required bytes.  So if we didn't search down this bitmap, we
166059c7b566SJosef Bacik  * may pick some previous entry that has a smaller ->max_extent_size than we
166159c7b566SJosef Bacik  * have.  For example, assume we have two entries, one that has
166259c7b566SJosef Bacik  * ->max_extent_size set to 4K and ->bytes set to 1M.  A second entry hasn't set
166359c7b566SJosef Bacik  * ->max_extent_size yet, has ->bytes set to 8K and it's contiguous.  We will
166459c7b566SJosef Bacik  *  call into find_free_space(), and return with max_extent_size == 4K, because
166559c7b566SJosef Bacik  *  that first bitmap entry had ->max_extent_size set, but the second one did
166659c7b566SJosef Bacik  *  not.  If instead we returned 8K we'd come in searching for 8K, and find the
166759c7b566SJosef Bacik  *  8K contiguous range.
166859c7b566SJosef Bacik  *
166959c7b566SJosef Bacik  *  Consider the other case, we have 2 8K chunks in that second entry and still
167059c7b566SJosef Bacik  *  don't have ->max_extent_size set.  We'll return 16K, and the next time the
167159c7b566SJosef Bacik  *  allocator comes in it'll fully search our second bitmap, and this time it'll
167259c7b566SJosef Bacik  *  get an uptodate value of 8K as the maximum chunk size.  Then we'll get the
167359c7b566SJosef Bacik  *  right allocation the next loop through.
167459c7b566SJosef Bacik  */
get_max_extent_size(const struct btrfs_free_space * entry)167559c7b566SJosef Bacik static inline u64 get_max_extent_size(const struct btrfs_free_space *entry)
167659c7b566SJosef Bacik {
167759c7b566SJosef Bacik 	if (entry->bitmap && entry->max_extent_size)
167859c7b566SJosef Bacik 		return entry->max_extent_size;
167959c7b566SJosef Bacik 	return entry->bytes;
168059c7b566SJosef Bacik }
168159c7b566SJosef Bacik 
168259c7b566SJosef Bacik /*
168359c7b566SJosef Bacik  * We want the largest entry to be leftmost, so this is inverted from what you'd
168459c7b566SJosef Bacik  * normally expect.
168559c7b566SJosef Bacik  */
entry_less(struct rb_node * node,const struct rb_node * parent)168659c7b566SJosef Bacik static bool entry_less(struct rb_node *node, const struct rb_node *parent)
168759c7b566SJosef Bacik {
168859c7b566SJosef Bacik 	const struct btrfs_free_space *entry, *exist;
168959c7b566SJosef Bacik 
169059c7b566SJosef Bacik 	entry = rb_entry(node, struct btrfs_free_space, bytes_index);
169159c7b566SJosef Bacik 	exist = rb_entry(parent, struct btrfs_free_space, bytes_index);
169259c7b566SJosef Bacik 	return get_max_extent_size(exist) < get_max_extent_size(entry);
169359c7b566SJosef Bacik }
169459c7b566SJosef Bacik 
169559c7b566SJosef Bacik /*
169670cb0743SJosef Bacik  * searches the tree for the given offset.
169770cb0743SJosef Bacik  *
169896303081SJosef Bacik  * fuzzy - If this is set, then we are trying to make an allocation, and we just
169996303081SJosef Bacik  * want a section that has at least bytes size and comes at or after the given
170096303081SJosef Bacik  * offset.
17010f9dd46cSJosef Bacik  */
170296303081SJosef Bacik static struct btrfs_free_space *
tree_search_offset(struct btrfs_free_space_ctl * ctl,u64 offset,int bitmap_only,int fuzzy)170334d52cb6SLi Zefan tree_search_offset(struct btrfs_free_space_ctl *ctl,
170496303081SJosef Bacik 		   u64 offset, int bitmap_only, int fuzzy)
17050f9dd46cSJosef Bacik {
170634d52cb6SLi Zefan 	struct rb_node *n = ctl->free_space_offset.rb_node;
1707f1a8fc62SNikolay Borisov 	struct btrfs_free_space *entry = NULL, *prev = NULL;
17080f9dd46cSJosef Bacik 
170991de9e97SFilipe Manana 	lockdep_assert_held(&ctl->tree_lock);
171091de9e97SFilipe Manana 
171196303081SJosef Bacik 	/* find entry that is closest to the 'offset' */
1712f1a8fc62SNikolay Borisov 	while (n) {
17130f9dd46cSJosef Bacik 		entry = rb_entry(n, struct btrfs_free_space, offset_index);
171496303081SJosef Bacik 		prev = entry;
17150f9dd46cSJosef Bacik 
171696303081SJosef Bacik 		if (offset < entry->offset)
17170f9dd46cSJosef Bacik 			n = n->rb_left;
171896303081SJosef Bacik 		else if (offset > entry->offset)
171996303081SJosef Bacik 			n = n->rb_right;
172096303081SJosef Bacik 		else
17210f9dd46cSJosef Bacik 			break;
1722f1a8fc62SNikolay Borisov 
1723f1a8fc62SNikolay Borisov 		entry = NULL;
17240f9dd46cSJosef Bacik 	}
172596303081SJosef Bacik 
172696303081SJosef Bacik 	if (bitmap_only) {
172796303081SJosef Bacik 		if (!entry)
172896303081SJosef Bacik 			return NULL;
172996303081SJosef Bacik 		if (entry->bitmap)
173096303081SJosef Bacik 			return entry;
173196303081SJosef Bacik 
173296303081SJosef Bacik 		/*
173396303081SJosef Bacik 		 * bitmap entry and extent entry may share same offset,
173496303081SJosef Bacik 		 * in that case, bitmap entry comes after extent entry.
173596303081SJosef Bacik 		 */
173696303081SJosef Bacik 		n = rb_next(n);
173796303081SJosef Bacik 		if (!n)
173896303081SJosef Bacik 			return NULL;
173996303081SJosef Bacik 		entry = rb_entry(n, struct btrfs_free_space, offset_index);
174096303081SJosef Bacik 		if (entry->offset != offset)
174196303081SJosef Bacik 			return NULL;
174296303081SJosef Bacik 
174396303081SJosef Bacik 		WARN_ON(!entry->bitmap);
174496303081SJosef Bacik 		return entry;
174596303081SJosef Bacik 	} else if (entry) {
174696303081SJosef Bacik 		if (entry->bitmap) {
174796303081SJosef Bacik 			/*
174896303081SJosef Bacik 			 * if previous extent entry covers the offset,
174996303081SJosef Bacik 			 * we should return it instead of the bitmap entry
175096303081SJosef Bacik 			 */
1751de6c4115SMiao Xie 			n = rb_prev(&entry->offset_index);
1752de6c4115SMiao Xie 			if (n) {
175396303081SJosef Bacik 				prev = rb_entry(n, struct btrfs_free_space,
175496303081SJosef Bacik 						offset_index);
1755de6c4115SMiao Xie 				if (!prev->bitmap &&
1756de6c4115SMiao Xie 				    prev->offset + prev->bytes > offset)
175796303081SJosef Bacik 					entry = prev;
17580f9dd46cSJosef Bacik 			}
175996303081SJosef Bacik 		}
176096303081SJosef Bacik 		return entry;
17610f9dd46cSJosef Bacik 	}
17620f9dd46cSJosef Bacik 
176396303081SJosef Bacik 	if (!prev)
176496303081SJosef Bacik 		return NULL;
17650f9dd46cSJosef Bacik 
176696303081SJosef Bacik 	/* find last entry before the 'offset' */
176796303081SJosef Bacik 	entry = prev;
176896303081SJosef Bacik 	if (entry->offset > offset) {
176996303081SJosef Bacik 		n = rb_prev(&entry->offset_index);
177096303081SJosef Bacik 		if (n) {
177196303081SJosef Bacik 			entry = rb_entry(n, struct btrfs_free_space,
177296303081SJosef Bacik 					offset_index);
1773b12d6869SJosef Bacik 			ASSERT(entry->offset <= offset);
17740f9dd46cSJosef Bacik 		} else {
177596303081SJosef Bacik 			if (fuzzy)
177696303081SJosef Bacik 				return entry;
177796303081SJosef Bacik 			else
177896303081SJosef Bacik 				return NULL;
17790f9dd46cSJosef Bacik 		}
17800f9dd46cSJosef Bacik 	}
17810f9dd46cSJosef Bacik 
178296303081SJosef Bacik 	if (entry->bitmap) {
1783de6c4115SMiao Xie 		n = rb_prev(&entry->offset_index);
1784de6c4115SMiao Xie 		if (n) {
178596303081SJosef Bacik 			prev = rb_entry(n, struct btrfs_free_space,
178696303081SJosef Bacik 					offset_index);
1787de6c4115SMiao Xie 			if (!prev->bitmap &&
1788de6c4115SMiao Xie 			    prev->offset + prev->bytes > offset)
178996303081SJosef Bacik 				return prev;
179096303081SJosef Bacik 		}
179134d52cb6SLi Zefan 		if (entry->offset + BITS_PER_BITMAP * ctl->unit > offset)
179296303081SJosef Bacik 			return entry;
179396303081SJosef Bacik 	} else if (entry->offset + entry->bytes > offset)
179496303081SJosef Bacik 		return entry;
179596303081SJosef Bacik 
179696303081SJosef Bacik 	if (!fuzzy)
179796303081SJosef Bacik 		return NULL;
179896303081SJosef Bacik 
179996303081SJosef Bacik 	while (1) {
1800167c0bd3SNikolay Borisov 		n = rb_next(&entry->offset_index);
1801167c0bd3SNikolay Borisov 		if (!n)
1802167c0bd3SNikolay Borisov 			return NULL;
1803167c0bd3SNikolay Borisov 		entry = rb_entry(n, struct btrfs_free_space, offset_index);
180496303081SJosef Bacik 		if (entry->bitmap) {
180596303081SJosef Bacik 			if (entry->offset + BITS_PER_BITMAP *
180634d52cb6SLi Zefan 			    ctl->unit > offset)
180796303081SJosef Bacik 				break;
180896303081SJosef Bacik 		} else {
180996303081SJosef Bacik 			if (entry->offset + entry->bytes > offset)
181096303081SJosef Bacik 				break;
181196303081SJosef Bacik 		}
181296303081SJosef Bacik 	}
181396303081SJosef Bacik 	return entry;
18140f9dd46cSJosef Bacik }
18150f9dd46cSJosef Bacik 
unlink_free_space(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,bool update_stat)181632e1649bSNikolay Borisov static inline void unlink_free_space(struct btrfs_free_space_ctl *ctl,
181732e1649bSNikolay Borisov 				     struct btrfs_free_space *info,
181832e1649bSNikolay Borisov 				     bool update_stat)
18190f9dd46cSJosef Bacik {
18207e5ba559SFilipe Manana 	lockdep_assert_held(&ctl->tree_lock);
18217e5ba559SFilipe Manana 
182234d52cb6SLi Zefan 	rb_erase(&info->offset_index, &ctl->free_space_offset);
182359c7b566SJosef Bacik 	rb_erase_cached(&info->bytes_index, &ctl->free_space_bytes);
182434d52cb6SLi Zefan 	ctl->free_extents--;
1825dfb79ddbSDennis Zhou 
18265dc7c10bSDennis Zhou 	if (!info->bitmap && !btrfs_free_space_trimmed(info)) {
1827dfb79ddbSDennis Zhou 		ctl->discardable_extents[BTRFS_STAT_CURR]--;
18285dc7c10bSDennis Zhou 		ctl->discardable_bytes[BTRFS_STAT_CURR] -= info->bytes;
18295dc7c10bSDennis Zhou 	}
1830f333adb5SLi Zefan 
183132e1649bSNikolay Borisov 	if (update_stat)
183234d52cb6SLi Zefan 		ctl->free_space -= info->bytes;
18330f9dd46cSJosef Bacik }
18340f9dd46cSJosef Bacik 
link_free_space(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info)183534d52cb6SLi Zefan static int link_free_space(struct btrfs_free_space_ctl *ctl,
18360f9dd46cSJosef Bacik 			   struct btrfs_free_space *info)
18370f9dd46cSJosef Bacik {
18380f9dd46cSJosef Bacik 	int ret = 0;
18390f9dd46cSJosef Bacik 
18409649bd9aSFilipe Manana 	lockdep_assert_held(&ctl->tree_lock);
18419649bd9aSFilipe Manana 
1842b12d6869SJosef Bacik 	ASSERT(info->bytes || info->bitmap);
184313c2018fSFilipe Manana 	ret = tree_insert_offset(ctl, NULL, info);
18440f9dd46cSJosef Bacik 	if (ret)
18450f9dd46cSJosef Bacik 		return ret;
18460f9dd46cSJosef Bacik 
184759c7b566SJosef Bacik 	rb_add_cached(&info->bytes_index, &ctl->free_space_bytes, entry_less);
184859c7b566SJosef Bacik 
18495dc7c10bSDennis Zhou 	if (!info->bitmap && !btrfs_free_space_trimmed(info)) {
1850dfb79ddbSDennis Zhou 		ctl->discardable_extents[BTRFS_STAT_CURR]++;
18515dc7c10bSDennis Zhou 		ctl->discardable_bytes[BTRFS_STAT_CURR] += info->bytes;
18525dc7c10bSDennis Zhou 	}
1853dfb79ddbSDennis Zhou 
185434d52cb6SLi Zefan 	ctl->free_space += info->bytes;
185534d52cb6SLi Zefan 	ctl->free_extents++;
18560f9dd46cSJosef Bacik 	return ret;
185796303081SJosef Bacik }
185896303081SJosef Bacik 
relink_bitmap_entry(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info)185959c7b566SJosef Bacik static void relink_bitmap_entry(struct btrfs_free_space_ctl *ctl,
186059c7b566SJosef Bacik 				struct btrfs_free_space *info)
186159c7b566SJosef Bacik {
186259c7b566SJosef Bacik 	ASSERT(info->bitmap);
186359c7b566SJosef Bacik 
186459c7b566SJosef Bacik 	/*
186559c7b566SJosef Bacik 	 * If our entry is empty it's because we're on a cluster and we don't
186659c7b566SJosef Bacik 	 * want to re-link it into our ctl bytes index.
186759c7b566SJosef Bacik 	 */
186859c7b566SJosef Bacik 	if (RB_EMPTY_NODE(&info->bytes_index))
186959c7b566SJosef Bacik 		return;
187059c7b566SJosef Bacik 
18717e5ba559SFilipe Manana 	lockdep_assert_held(&ctl->tree_lock);
18727e5ba559SFilipe Manana 
187359c7b566SJosef Bacik 	rb_erase_cached(&info->bytes_index, &ctl->free_space_bytes);
187459c7b566SJosef Bacik 	rb_add_cached(&info->bytes_index, &ctl->free_space_bytes, entry_less);
187559c7b566SJosef Bacik }
187659c7b566SJosef Bacik 
bitmap_clear_bits(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,u64 offset,u64 bytes,bool update_stat)1877f594f13cSNikolay Borisov static inline void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
1878bb3ac5a4SMiao Xie 				     struct btrfs_free_space *info,
1879f594f13cSNikolay Borisov 				     u64 offset, u64 bytes, bool update_stat)
188096303081SJosef Bacik {
1881dfb79ddbSDennis Zhou 	unsigned long start, count, end;
1882dfb79ddbSDennis Zhou 	int extent_delta = -1;
188396303081SJosef Bacik 
188434d52cb6SLi Zefan 	start = offset_to_bit(info->offset, ctl->unit, offset);
188534d52cb6SLi Zefan 	count = bytes_to_bits(bytes, ctl->unit);
1886dfb79ddbSDennis Zhou 	end = start + count;
1887dfb79ddbSDennis Zhou 	ASSERT(end <= BITS_PER_BITMAP);
188896303081SJosef Bacik 
1889f38b6e75SLi Zefan 	bitmap_clear(info->bitmap, start, count);
189096303081SJosef Bacik 
189196303081SJosef Bacik 	info->bytes -= bytes;
1892553cceb4SJosef Bacik 	if (info->max_extent_size > ctl->unit)
1893553cceb4SJosef Bacik 		info->max_extent_size = 0;
1894dfb79ddbSDennis Zhou 
189559c7b566SJosef Bacik 	relink_bitmap_entry(ctl, info);
189659c7b566SJosef Bacik 
1897dfb79ddbSDennis Zhou 	if (start && test_bit(start - 1, info->bitmap))
1898dfb79ddbSDennis Zhou 		extent_delta++;
1899dfb79ddbSDennis Zhou 
1900dfb79ddbSDennis Zhou 	if (end < BITS_PER_BITMAP && test_bit(end, info->bitmap))
1901dfb79ddbSDennis Zhou 		extent_delta++;
1902dfb79ddbSDennis Zhou 
1903dfb79ddbSDennis Zhou 	info->bitmap_extents += extent_delta;
19045dc7c10bSDennis Zhou 	if (!btrfs_free_space_trimmed(info)) {
1905dfb79ddbSDennis Zhou 		ctl->discardable_extents[BTRFS_STAT_CURR] += extent_delta;
19065dc7c10bSDennis Zhou 		ctl->discardable_bytes[BTRFS_STAT_CURR] -= bytes;
19075dc7c10bSDennis Zhou 	}
1908bb3ac5a4SMiao Xie 
1909f594f13cSNikolay Borisov 	if (update_stat)
191034d52cb6SLi Zefan 		ctl->free_space -= bytes;
191196303081SJosef Bacik }
191296303081SJosef Bacik 
btrfs_bitmap_set_bits(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,u64 offset,u64 bytes)1913ef725854SAlexander Lobakin static void btrfs_bitmap_set_bits(struct btrfs_free_space_ctl *ctl,
1914817d52f8SJosef Bacik 				  struct btrfs_free_space *info, u64 offset,
1915817d52f8SJosef Bacik 				  u64 bytes)
191696303081SJosef Bacik {
1917dfb79ddbSDennis Zhou 	unsigned long start, count, end;
1918dfb79ddbSDennis Zhou 	int extent_delta = 1;
191996303081SJosef Bacik 
192034d52cb6SLi Zefan 	start = offset_to_bit(info->offset, ctl->unit, offset);
192134d52cb6SLi Zefan 	count = bytes_to_bits(bytes, ctl->unit);
1922dfb79ddbSDennis Zhou 	end = start + count;
1923dfb79ddbSDennis Zhou 	ASSERT(end <= BITS_PER_BITMAP);
192496303081SJosef Bacik 
1925f38b6e75SLi Zefan 	bitmap_set(info->bitmap, start, count);
192696303081SJosef Bacik 
192759c7b566SJosef Bacik 	/*
192859c7b566SJosef Bacik 	 * We set some bytes, we have no idea what the max extent size is
192959c7b566SJosef Bacik 	 * anymore.
193059c7b566SJosef Bacik 	 */
193159c7b566SJosef Bacik 	info->max_extent_size = 0;
193296303081SJosef Bacik 	info->bytes += bytes;
193334d52cb6SLi Zefan 	ctl->free_space += bytes;
1934dfb79ddbSDennis Zhou 
193559c7b566SJosef Bacik 	relink_bitmap_entry(ctl, info);
193659c7b566SJosef Bacik 
1937dfb79ddbSDennis Zhou 	if (start && test_bit(start - 1, info->bitmap))
1938dfb79ddbSDennis Zhou 		extent_delta--;
1939dfb79ddbSDennis Zhou 
1940dfb79ddbSDennis Zhou 	if (end < BITS_PER_BITMAP && test_bit(end, info->bitmap))
1941dfb79ddbSDennis Zhou 		extent_delta--;
1942dfb79ddbSDennis Zhou 
1943dfb79ddbSDennis Zhou 	info->bitmap_extents += extent_delta;
19445dc7c10bSDennis Zhou 	if (!btrfs_free_space_trimmed(info)) {
1945dfb79ddbSDennis Zhou 		ctl->discardable_extents[BTRFS_STAT_CURR] += extent_delta;
19465dc7c10bSDennis Zhou 		ctl->discardable_bytes[BTRFS_STAT_CURR] += bytes;
19475dc7c10bSDennis Zhou 	}
194896303081SJosef Bacik }
194996303081SJosef Bacik 
1950a4820398SMiao Xie /*
1951a4820398SMiao Xie  * If we can not find suitable extent, we will use bytes to record
1952a4820398SMiao Xie  * the size of the max extent.
1953a4820398SMiao Xie  */
search_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * bitmap_info,u64 * offset,u64 * bytes,bool for_alloc)195434d52cb6SLi Zefan static int search_bitmap(struct btrfs_free_space_ctl *ctl,
195596303081SJosef Bacik 			 struct btrfs_free_space *bitmap_info, u64 *offset,
19560584f718SJosef Bacik 			 u64 *bytes, bool for_alloc)
195796303081SJosef Bacik {
195896303081SJosef Bacik 	unsigned long found_bits = 0;
1959a4820398SMiao Xie 	unsigned long max_bits = 0;
196096303081SJosef Bacik 	unsigned long bits, i;
196196303081SJosef Bacik 	unsigned long next_zero;
1962a4820398SMiao Xie 	unsigned long extent_bits;
196396303081SJosef Bacik 
1964cef40483SJosef Bacik 	/*
1965cef40483SJosef Bacik 	 * Skip searching the bitmap if we don't have a contiguous section that
1966cef40483SJosef Bacik 	 * is large enough for this allocation.
1967cef40483SJosef Bacik 	 */
19680584f718SJosef Bacik 	if (for_alloc &&
19690584f718SJosef Bacik 	    bitmap_info->max_extent_size &&
1970cef40483SJosef Bacik 	    bitmap_info->max_extent_size < *bytes) {
1971cef40483SJosef Bacik 		*bytes = bitmap_info->max_extent_size;
1972cef40483SJosef Bacik 		return -1;
1973cef40483SJosef Bacik 	}
1974cef40483SJosef Bacik 
197534d52cb6SLi Zefan 	i = offset_to_bit(bitmap_info->offset, ctl->unit,
197696303081SJosef Bacik 			  max_t(u64, *offset, bitmap_info->offset));
197734d52cb6SLi Zefan 	bits = bytes_to_bits(*bytes, ctl->unit);
197896303081SJosef Bacik 
1979ebb3dad4SWei Yongjun 	for_each_set_bit_from(i, bitmap_info->bitmap, BITS_PER_BITMAP) {
19800584f718SJosef Bacik 		if (for_alloc && bits == 1) {
19810584f718SJosef Bacik 			found_bits = 1;
19820584f718SJosef Bacik 			break;
19830584f718SJosef Bacik 		}
198496303081SJosef Bacik 		next_zero = find_next_zero_bit(bitmap_info->bitmap,
198596303081SJosef Bacik 					       BITS_PER_BITMAP, i);
1986a4820398SMiao Xie 		extent_bits = next_zero - i;
1987a4820398SMiao Xie 		if (extent_bits >= bits) {
1988a4820398SMiao Xie 			found_bits = extent_bits;
198996303081SJosef Bacik 			break;
1990a4820398SMiao Xie 		} else if (extent_bits > max_bits) {
1991a4820398SMiao Xie 			max_bits = extent_bits;
199296303081SJosef Bacik 		}
199396303081SJosef Bacik 		i = next_zero;
199496303081SJosef Bacik 	}
199596303081SJosef Bacik 
199696303081SJosef Bacik 	if (found_bits) {
199734d52cb6SLi Zefan 		*offset = (u64)(i * ctl->unit) + bitmap_info->offset;
199834d52cb6SLi Zefan 		*bytes = (u64)(found_bits) * ctl->unit;
199996303081SJosef Bacik 		return 0;
200096303081SJosef Bacik 	}
200196303081SJosef Bacik 
2002a4820398SMiao Xie 	*bytes = (u64)(max_bits) * ctl->unit;
2003cef40483SJosef Bacik 	bitmap_info->max_extent_size = *bytes;
200459c7b566SJosef Bacik 	relink_bitmap_entry(ctl, bitmap_info);
200596303081SJosef Bacik 	return -1;
200696303081SJosef Bacik }
200796303081SJosef Bacik 
2008a4820398SMiao Xie /* Cache the size of the max extent in bytes */
200934d52cb6SLi Zefan static struct btrfs_free_space *
find_free_space(struct btrfs_free_space_ctl * ctl,u64 * offset,u64 * bytes,unsigned long align,u64 * max_extent_size,bool use_bytes_index)201053b381b3SDavid Woodhouse find_free_space(struct btrfs_free_space_ctl *ctl, u64 *offset, u64 *bytes,
201159c7b566SJosef Bacik 		unsigned long align, u64 *max_extent_size, bool use_bytes_index)
201296303081SJosef Bacik {
201396303081SJosef Bacik 	struct btrfs_free_space *entry;
201496303081SJosef Bacik 	struct rb_node *node;
201553b381b3SDavid Woodhouse 	u64 tmp;
201653b381b3SDavid Woodhouse 	u64 align_off;
201796303081SJosef Bacik 	int ret;
201896303081SJosef Bacik 
201934d52cb6SLi Zefan 	if (!ctl->free_space_offset.rb_node)
2020a4820398SMiao Xie 		goto out;
202159c7b566SJosef Bacik again:
202259c7b566SJosef Bacik 	if (use_bytes_index) {
202359c7b566SJosef Bacik 		node = rb_first_cached(&ctl->free_space_bytes);
202459c7b566SJosef Bacik 	} else {
202559c7b566SJosef Bacik 		entry = tree_search_offset(ctl, offset_to_bitmap(ctl, *offset),
202659c7b566SJosef Bacik 					   0, 1);
202796303081SJosef Bacik 		if (!entry)
2028a4820398SMiao Xie 			goto out;
202959c7b566SJosef Bacik 		node = &entry->offset_index;
203059c7b566SJosef Bacik 	}
203196303081SJosef Bacik 
203259c7b566SJosef Bacik 	for (; node; node = rb_next(node)) {
203359c7b566SJosef Bacik 		if (use_bytes_index)
203459c7b566SJosef Bacik 			entry = rb_entry(node, struct btrfs_free_space,
203559c7b566SJosef Bacik 					 bytes_index);
203659c7b566SJosef Bacik 		else
203759c7b566SJosef Bacik 			entry = rb_entry(node, struct btrfs_free_space,
203859c7b566SJosef Bacik 					 offset_index);
203959c7b566SJosef Bacik 
204059c7b566SJosef Bacik 		/*
204159c7b566SJosef Bacik 		 * If we are using the bytes index then all subsequent entries
204259c7b566SJosef Bacik 		 * in this tree are going to be < bytes, so simply set the max
204359c7b566SJosef Bacik 		 * extent size and exit the loop.
204459c7b566SJosef Bacik 		 *
204559c7b566SJosef Bacik 		 * If we're using the offset index then we need to keep going
204659c7b566SJosef Bacik 		 * through the rest of the tree.
204759c7b566SJosef Bacik 		 */
2048a4820398SMiao Xie 		if (entry->bytes < *bytes) {
2049ad22cf6eSJosef Bacik 			*max_extent_size = max(get_max_extent_size(entry),
2050ad22cf6eSJosef Bacik 					       *max_extent_size);
205159c7b566SJosef Bacik 			if (use_bytes_index)
205259c7b566SJosef Bacik 				break;
205396303081SJosef Bacik 			continue;
2054a4820398SMiao Xie 		}
205596303081SJosef Bacik 
205653b381b3SDavid Woodhouse 		/* make sure the space returned is big enough
205753b381b3SDavid Woodhouse 		 * to match our requested alignment
205853b381b3SDavid Woodhouse 		 */
205953b381b3SDavid Woodhouse 		if (*bytes >= align) {
2060a4820398SMiao Xie 			tmp = entry->offset - ctl->start + align - 1;
206147c5713fSDavid Sterba 			tmp = div64_u64(tmp, align);
206253b381b3SDavid Woodhouse 			tmp = tmp * align + ctl->start;
206353b381b3SDavid Woodhouse 			align_off = tmp - entry->offset;
206453b381b3SDavid Woodhouse 		} else {
206553b381b3SDavid Woodhouse 			align_off = 0;
206653b381b3SDavid Woodhouse 			tmp = entry->offset;
206753b381b3SDavid Woodhouse 		}
206853b381b3SDavid Woodhouse 
206959c7b566SJosef Bacik 		/*
207059c7b566SJosef Bacik 		 * We don't break here if we're using the bytes index because we
207159c7b566SJosef Bacik 		 * may have another entry that has the correct alignment that is
207259c7b566SJosef Bacik 		 * the right size, so we don't want to miss that possibility.
207359c7b566SJosef Bacik 		 * At worst this adds another loop through the logic, but if we
207459c7b566SJosef Bacik 		 * broke here we could prematurely ENOSPC.
207559c7b566SJosef Bacik 		 */
2076a4820398SMiao Xie 		if (entry->bytes < *bytes + align_off) {
2077ad22cf6eSJosef Bacik 			*max_extent_size = max(get_max_extent_size(entry),
2078ad22cf6eSJosef Bacik 					       *max_extent_size);
207953b381b3SDavid Woodhouse 			continue;
2080a4820398SMiao Xie 		}
208153b381b3SDavid Woodhouse 
208296303081SJosef Bacik 		if (entry->bitmap) {
208359c7b566SJosef Bacik 			struct rb_node *old_next = rb_next(node);
2084a4820398SMiao Xie 			u64 size = *bytes;
2085a4820398SMiao Xie 
20860584f718SJosef Bacik 			ret = search_bitmap(ctl, entry, &tmp, &size, true);
208753b381b3SDavid Woodhouse 			if (!ret) {
208853b381b3SDavid Woodhouse 				*offset = tmp;
2089a4820398SMiao Xie 				*bytes = size;
209096303081SJosef Bacik 				return entry;
2091ad22cf6eSJosef Bacik 			} else {
2092ad22cf6eSJosef Bacik 				*max_extent_size =
2093ad22cf6eSJosef Bacik 					max(get_max_extent_size(entry),
2094ad22cf6eSJosef Bacik 					    *max_extent_size);
209553b381b3SDavid Woodhouse 			}
209659c7b566SJosef Bacik 
209759c7b566SJosef Bacik 			/*
209859c7b566SJosef Bacik 			 * The bitmap may have gotten re-arranged in the space
209959c7b566SJosef Bacik 			 * index here because the max_extent_size may have been
210059c7b566SJosef Bacik 			 * updated.  Start from the beginning again if this
210159c7b566SJosef Bacik 			 * happened.
210259c7b566SJosef Bacik 			 */
210359c7b566SJosef Bacik 			if (use_bytes_index && old_next != rb_next(node))
210459c7b566SJosef Bacik 				goto again;
210596303081SJosef Bacik 			continue;
210696303081SJosef Bacik 		}
210796303081SJosef Bacik 
210853b381b3SDavid Woodhouse 		*offset = tmp;
210953b381b3SDavid Woodhouse 		*bytes = entry->bytes - align_off;
211096303081SJosef Bacik 		return entry;
211196303081SJosef Bacik 	}
2112a4820398SMiao Xie out:
211396303081SJosef Bacik 	return NULL;
211496303081SJosef Bacik }
211596303081SJosef Bacik 
add_new_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,u64 offset)211634d52cb6SLi Zefan static void add_new_bitmap(struct btrfs_free_space_ctl *ctl,
211796303081SJosef Bacik 			   struct btrfs_free_space *info, u64 offset)
211896303081SJosef Bacik {
211934d52cb6SLi Zefan 	info->offset = offset_to_bitmap(ctl, offset);
2120f019f426SJosef Bacik 	info->bytes = 0;
2121dfb79ddbSDennis Zhou 	info->bitmap_extents = 0;
2122f2d0f676SAlexandre Oliva 	INIT_LIST_HEAD(&info->list);
212334d52cb6SLi Zefan 	link_free_space(ctl, info);
212434d52cb6SLi Zefan 	ctl->total_bitmaps++;
2125fa598b06SDavid Sterba 	recalculate_thresholds(ctl);
212696303081SJosef Bacik }
212796303081SJosef Bacik 
free_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * bitmap_info)212834d52cb6SLi Zefan static void free_bitmap(struct btrfs_free_space_ctl *ctl,
2129edf6e2d1SLi Zefan 			struct btrfs_free_space *bitmap_info)
2130edf6e2d1SLi Zefan {
213127f0afc7SDennis Zhou 	/*
213227f0afc7SDennis Zhou 	 * Normally when this is called, the bitmap is completely empty. However,
213327f0afc7SDennis Zhou 	 * if we are blowing up the free space cache for one reason or another
213427f0afc7SDennis Zhou 	 * via __btrfs_remove_free_space_cache(), then it may not be freed and
213527f0afc7SDennis Zhou 	 * we may leave stats on the table.
213627f0afc7SDennis Zhou 	 */
213727f0afc7SDennis Zhou 	if (bitmap_info->bytes && !btrfs_free_space_trimmed(bitmap_info)) {
213827f0afc7SDennis Zhou 		ctl->discardable_extents[BTRFS_STAT_CURR] -=
213927f0afc7SDennis Zhou 			bitmap_info->bitmap_extents;
214027f0afc7SDennis Zhou 		ctl->discardable_bytes[BTRFS_STAT_CURR] -= bitmap_info->bytes;
214127f0afc7SDennis Zhou 
214227f0afc7SDennis Zhou 	}
214332e1649bSNikolay Borisov 	unlink_free_space(ctl, bitmap_info, true);
21443acd4850SChristophe Leroy 	kmem_cache_free(btrfs_free_space_bitmap_cachep, bitmap_info->bitmap);
2145dc89e982SJosef Bacik 	kmem_cache_free(btrfs_free_space_cachep, bitmap_info);
214634d52cb6SLi Zefan 	ctl->total_bitmaps--;
2147fa598b06SDavid Sterba 	recalculate_thresholds(ctl);
2148edf6e2d1SLi Zefan }
2149edf6e2d1SLi Zefan 
remove_from_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * bitmap_info,u64 * offset,u64 * bytes)215034d52cb6SLi Zefan static noinline int remove_from_bitmap(struct btrfs_free_space_ctl *ctl,
215196303081SJosef Bacik 			      struct btrfs_free_space *bitmap_info,
215296303081SJosef Bacik 			      u64 *offset, u64 *bytes)
215396303081SJosef Bacik {
215496303081SJosef Bacik 	u64 end;
21556606bb97SJosef Bacik 	u64 search_start, search_bytes;
21566606bb97SJosef Bacik 	int ret;
215796303081SJosef Bacik 
215896303081SJosef Bacik again:
215934d52cb6SLi Zefan 	end = bitmap_info->offset + (u64)(BITS_PER_BITMAP * ctl->unit) - 1;
216096303081SJosef Bacik 
21616606bb97SJosef Bacik 	/*
2162bdb7d303SJosef Bacik 	 * We need to search for bits in this bitmap.  We could only cover some
2163bdb7d303SJosef Bacik 	 * of the extent in this bitmap thanks to how we add space, so we need
2164bdb7d303SJosef Bacik 	 * to search for as much as it as we can and clear that amount, and then
2165bdb7d303SJosef Bacik 	 * go searching for the next bit.
21666606bb97SJosef Bacik 	 */
21676606bb97SJosef Bacik 	search_start = *offset;
2168bdb7d303SJosef Bacik 	search_bytes = ctl->unit;
216913dbc089SJosef Bacik 	search_bytes = min(search_bytes, end - search_start + 1);
21700584f718SJosef Bacik 	ret = search_bitmap(ctl, bitmap_info, &search_start, &search_bytes,
21710584f718SJosef Bacik 			    false);
2172b50c6e25SJosef Bacik 	if (ret < 0 || search_start != *offset)
2173b50c6e25SJosef Bacik 		return -EINVAL;
21746606bb97SJosef Bacik 
2175bdb7d303SJosef Bacik 	/* We may have found more bits than what we need */
2176bdb7d303SJosef Bacik 	search_bytes = min(search_bytes, *bytes);
2177bdb7d303SJosef Bacik 
2178bdb7d303SJosef Bacik 	/* Cannot clear past the end of the bitmap */
2179bdb7d303SJosef Bacik 	search_bytes = min(search_bytes, end - search_start + 1);
2180bdb7d303SJosef Bacik 
2181f594f13cSNikolay Borisov 	bitmap_clear_bits(ctl, bitmap_info, search_start, search_bytes, true);
2182bdb7d303SJosef Bacik 	*offset += search_bytes;
2183bdb7d303SJosef Bacik 	*bytes -= search_bytes;
218496303081SJosef Bacik 
218596303081SJosef Bacik 	if (*bytes) {
21866606bb97SJosef Bacik 		struct rb_node *next = rb_next(&bitmap_info->offset_index);
2187edf6e2d1SLi Zefan 		if (!bitmap_info->bytes)
218834d52cb6SLi Zefan 			free_bitmap(ctl, bitmap_info);
218996303081SJosef Bacik 
21906606bb97SJosef Bacik 		/*
21916606bb97SJosef Bacik 		 * no entry after this bitmap, but we still have bytes to
21926606bb97SJosef Bacik 		 * remove, so something has gone wrong.
21936606bb97SJosef Bacik 		 */
21946606bb97SJosef Bacik 		if (!next)
219596303081SJosef Bacik 			return -EINVAL;
219696303081SJosef Bacik 
21976606bb97SJosef Bacik 		bitmap_info = rb_entry(next, struct btrfs_free_space,
21986606bb97SJosef Bacik 				       offset_index);
21996606bb97SJosef Bacik 
22006606bb97SJosef Bacik 		/*
22016606bb97SJosef Bacik 		 * if the next entry isn't a bitmap we need to return to let the
22026606bb97SJosef Bacik 		 * extent stuff do its work.
22036606bb97SJosef Bacik 		 */
220496303081SJosef Bacik 		if (!bitmap_info->bitmap)
220596303081SJosef Bacik 			return -EAGAIN;
220696303081SJosef Bacik 
22076606bb97SJosef Bacik 		/*
22086606bb97SJosef Bacik 		 * Ok the next item is a bitmap, but it may not actually hold
22096606bb97SJosef Bacik 		 * the information for the rest of this free space stuff, so
22106606bb97SJosef Bacik 		 * look for it, and if we don't find it return so we can try
22116606bb97SJosef Bacik 		 * everything over again.
22126606bb97SJosef Bacik 		 */
22136606bb97SJosef Bacik 		search_start = *offset;
2214bdb7d303SJosef Bacik 		search_bytes = ctl->unit;
221534d52cb6SLi Zefan 		ret = search_bitmap(ctl, bitmap_info, &search_start,
22160584f718SJosef Bacik 				    &search_bytes, false);
22176606bb97SJosef Bacik 		if (ret < 0 || search_start != *offset)
22186606bb97SJosef Bacik 			return -EAGAIN;
22196606bb97SJosef Bacik 
222096303081SJosef Bacik 		goto again;
2221edf6e2d1SLi Zefan 	} else if (!bitmap_info->bytes)
222234d52cb6SLi Zefan 		free_bitmap(ctl, bitmap_info);
222396303081SJosef Bacik 
222496303081SJosef Bacik 	return 0;
222596303081SJosef Bacik }
222696303081SJosef Bacik 
add_bytes_to_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,u64 offset,u64 bytes,enum btrfs_trim_state trim_state)22272cdc342cSJosef Bacik static u64 add_bytes_to_bitmap(struct btrfs_free_space_ctl *ctl,
22282cdc342cSJosef Bacik 			       struct btrfs_free_space *info, u64 offset,
2229da080fe1SDennis Zhou 			       u64 bytes, enum btrfs_trim_state trim_state)
22302cdc342cSJosef Bacik {
22312cdc342cSJosef Bacik 	u64 bytes_to_set = 0;
22322cdc342cSJosef Bacik 	u64 end;
22332cdc342cSJosef Bacik 
2234da080fe1SDennis Zhou 	/*
2235da080fe1SDennis Zhou 	 * This is a tradeoff to make bitmap trim state minimal.  We mark the
2236da080fe1SDennis Zhou 	 * whole bitmap untrimmed if at any point we add untrimmed regions.
2237da080fe1SDennis Zhou 	 */
2238dfb79ddbSDennis Zhou 	if (trim_state == BTRFS_TRIM_STATE_UNTRIMMED) {
22395dc7c10bSDennis Zhou 		if (btrfs_free_space_trimmed(info)) {
2240dfb79ddbSDennis Zhou 			ctl->discardable_extents[BTRFS_STAT_CURR] +=
2241dfb79ddbSDennis Zhou 				info->bitmap_extents;
22425dc7c10bSDennis Zhou 			ctl->discardable_bytes[BTRFS_STAT_CURR] += info->bytes;
22435dc7c10bSDennis Zhou 		}
2244da080fe1SDennis Zhou 		info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2245dfb79ddbSDennis Zhou 	}
2246da080fe1SDennis Zhou 
22472cdc342cSJosef Bacik 	end = info->offset + (u64)(BITS_PER_BITMAP * ctl->unit);
22482cdc342cSJosef Bacik 
22492cdc342cSJosef Bacik 	bytes_to_set = min(end - offset, bytes);
22502cdc342cSJosef Bacik 
2251ef725854SAlexander Lobakin 	btrfs_bitmap_set_bits(ctl, info, offset, bytes_to_set);
22522cdc342cSJosef Bacik 
22532cdc342cSJosef Bacik 	return bytes_to_set;
22542cdc342cSJosef Bacik 
22552cdc342cSJosef Bacik }
22562cdc342cSJosef Bacik 
use_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info)225734d52cb6SLi Zefan static bool use_bitmap(struct btrfs_free_space_ctl *ctl,
225896303081SJosef Bacik 		      struct btrfs_free_space *info)
225996303081SJosef Bacik {
2260364be842SNikolay Borisov 	struct btrfs_block_group *block_group = ctl->block_group;
22610b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = block_group->fs_info;
2262d0bd4560SJosef Bacik 	bool forced = false;
2263d0bd4560SJosef Bacik 
2264d0bd4560SJosef Bacik #ifdef CONFIG_BTRFS_DEBUG
22652ff7e61eSJeff Mahoney 	if (btrfs_should_fragment_free_space(block_group))
2266d0bd4560SJosef Bacik 		forced = true;
2267d0bd4560SJosef Bacik #endif
226896303081SJosef Bacik 
22695d90c5c7SDennis Zhou 	/* This is a way to reclaim large regions from the bitmaps. */
22705d90c5c7SDennis Zhou 	if (!forced && info->bytes >= FORCE_EXTENT_THRESHOLD)
22715d90c5c7SDennis Zhou 		return false;
22725d90c5c7SDennis Zhou 
227396303081SJosef Bacik 	/*
227496303081SJosef Bacik 	 * If we are below the extents threshold then we can add this as an
227596303081SJosef Bacik 	 * extent, and don't have to deal with the bitmap
227696303081SJosef Bacik 	 */
2277d0bd4560SJosef Bacik 	if (!forced && ctl->free_extents < ctl->extents_thresh) {
227832cb0840SJosef Bacik 		/*
227932cb0840SJosef Bacik 		 * If this block group has some small extents we don't want to
228032cb0840SJosef Bacik 		 * use up all of our free slots in the cache with them, we want
228101327610SNicholas D Steeves 		 * to reserve them to larger extents, however if we have plenty
228232cb0840SJosef Bacik 		 * of cache left then go ahead an dadd them, no sense in adding
228332cb0840SJosef Bacik 		 * the overhead of a bitmap if we don't have to.
228432cb0840SJosef Bacik 		 */
2285f9bb615aSDennis Zhou 		if (info->bytes <= fs_info->sectorsize * 8) {
2286f9bb615aSDennis Zhou 			if (ctl->free_extents * 3 <= ctl->extents_thresh)
228734d52cb6SLi Zefan 				return false;
228832cb0840SJosef Bacik 		} else {
228934d52cb6SLi Zefan 			return false;
229032cb0840SJosef Bacik 		}
229132cb0840SJosef Bacik 	}
229296303081SJosef Bacik 
229396303081SJosef Bacik 	/*
2294dde5740fSJosef Bacik 	 * The original block groups from mkfs can be really small, like 8
2295dde5740fSJosef Bacik 	 * megabytes, so don't bother with a bitmap for those entries.  However
2296dde5740fSJosef Bacik 	 * some block groups can be smaller than what a bitmap would cover but
2297dde5740fSJosef Bacik 	 * are still large enough that they could overflow the 32k memory limit,
2298dde5740fSJosef Bacik 	 * so allow those block groups to still be allowed to have a bitmap
2299dde5740fSJosef Bacik 	 * entry.
230096303081SJosef Bacik 	 */
2301b3470b5dSDavid Sterba 	if (((BITS_PER_BITMAP * ctl->unit) >> 1) > block_group->length)
230234d52cb6SLi Zefan 		return false;
230334d52cb6SLi Zefan 
230434d52cb6SLi Zefan 	return true;
230534d52cb6SLi Zefan }
230634d52cb6SLi Zefan 
230720e5506bSDavid Sterba static const struct btrfs_free_space_op free_space_op = {
23082cdc342cSJosef Bacik 	.use_bitmap		= use_bitmap,
23092cdc342cSJosef Bacik };
23102cdc342cSJosef Bacik 
insert_into_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info)231134d52cb6SLi Zefan static int insert_into_bitmap(struct btrfs_free_space_ctl *ctl,
231234d52cb6SLi Zefan 			      struct btrfs_free_space *info)
231334d52cb6SLi Zefan {
231434d52cb6SLi Zefan 	struct btrfs_free_space *bitmap_info;
231532da5386SDavid Sterba 	struct btrfs_block_group *block_group = NULL;
231634d52cb6SLi Zefan 	int added = 0;
23172cdc342cSJosef Bacik 	u64 bytes, offset, bytes_added;
2318da080fe1SDennis Zhou 	enum btrfs_trim_state trim_state;
231934d52cb6SLi Zefan 	int ret;
232096303081SJosef Bacik 
232196303081SJosef Bacik 	bytes = info->bytes;
232296303081SJosef Bacik 	offset = info->offset;
2323da080fe1SDennis Zhou 	trim_state = info->trim_state;
232496303081SJosef Bacik 
232534d52cb6SLi Zefan 	if (!ctl->op->use_bitmap(ctl, info))
232634d52cb6SLi Zefan 		return 0;
232734d52cb6SLi Zefan 
23282cdc342cSJosef Bacik 	if (ctl->op == &free_space_op)
2329364be842SNikolay Borisov 		block_group = ctl->block_group;
233038e87880SChris Mason again:
23312cdc342cSJosef Bacik 	/*
23322cdc342cSJosef Bacik 	 * Since we link bitmaps right into the cluster we need to see if we
23332cdc342cSJosef Bacik 	 * have a cluster here, and if so and it has our bitmap we need to add
23342cdc342cSJosef Bacik 	 * the free space to that bitmap.
23352cdc342cSJosef Bacik 	 */
23362cdc342cSJosef Bacik 	if (block_group && !list_empty(&block_group->cluster_list)) {
23372cdc342cSJosef Bacik 		struct btrfs_free_cluster *cluster;
23382cdc342cSJosef Bacik 		struct rb_node *node;
23392cdc342cSJosef Bacik 		struct btrfs_free_space *entry;
23402cdc342cSJosef Bacik 
23412cdc342cSJosef Bacik 		cluster = list_entry(block_group->cluster_list.next,
23422cdc342cSJosef Bacik 				     struct btrfs_free_cluster,
23432cdc342cSJosef Bacik 				     block_group_list);
23442cdc342cSJosef Bacik 		spin_lock(&cluster->lock);
23452cdc342cSJosef Bacik 		node = rb_first(&cluster->root);
23462cdc342cSJosef Bacik 		if (!node) {
23472cdc342cSJosef Bacik 			spin_unlock(&cluster->lock);
234838e87880SChris Mason 			goto no_cluster_bitmap;
23492cdc342cSJosef Bacik 		}
23502cdc342cSJosef Bacik 
23512cdc342cSJosef Bacik 		entry = rb_entry(node, struct btrfs_free_space, offset_index);
23522cdc342cSJosef Bacik 		if (!entry->bitmap) {
23532cdc342cSJosef Bacik 			spin_unlock(&cluster->lock);
235438e87880SChris Mason 			goto no_cluster_bitmap;
23552cdc342cSJosef Bacik 		}
23562cdc342cSJosef Bacik 
23572cdc342cSJosef Bacik 		if (entry->offset == offset_to_bitmap(ctl, offset)) {
2358da080fe1SDennis Zhou 			bytes_added = add_bytes_to_bitmap(ctl, entry, offset,
2359da080fe1SDennis Zhou 							  bytes, trim_state);
23602cdc342cSJosef Bacik 			bytes -= bytes_added;
23612cdc342cSJosef Bacik 			offset += bytes_added;
23622cdc342cSJosef Bacik 		}
23632cdc342cSJosef Bacik 		spin_unlock(&cluster->lock);
23642cdc342cSJosef Bacik 		if (!bytes) {
23652cdc342cSJosef Bacik 			ret = 1;
23662cdc342cSJosef Bacik 			goto out;
23672cdc342cSJosef Bacik 		}
23682cdc342cSJosef Bacik 	}
236938e87880SChris Mason 
237038e87880SChris Mason no_cluster_bitmap:
237134d52cb6SLi Zefan 	bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
237296303081SJosef Bacik 					 1, 0);
237396303081SJosef Bacik 	if (!bitmap_info) {
2374b12d6869SJosef Bacik 		ASSERT(added == 0);
237596303081SJosef Bacik 		goto new_bitmap;
237696303081SJosef Bacik 	}
237796303081SJosef Bacik 
2378da080fe1SDennis Zhou 	bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes,
2379da080fe1SDennis Zhou 					  trim_state);
23802cdc342cSJosef Bacik 	bytes -= bytes_added;
23812cdc342cSJosef Bacik 	offset += bytes_added;
238296303081SJosef Bacik 	added = 0;
238396303081SJosef Bacik 
238496303081SJosef Bacik 	if (!bytes) {
238596303081SJosef Bacik 		ret = 1;
238696303081SJosef Bacik 		goto out;
238796303081SJosef Bacik 	} else
238896303081SJosef Bacik 		goto again;
238996303081SJosef Bacik 
239096303081SJosef Bacik new_bitmap:
239196303081SJosef Bacik 	if (info && info->bitmap) {
239234d52cb6SLi Zefan 		add_new_bitmap(ctl, info, offset);
239396303081SJosef Bacik 		added = 1;
239496303081SJosef Bacik 		info = NULL;
239596303081SJosef Bacik 		goto again;
239696303081SJosef Bacik 	} else {
239734d52cb6SLi Zefan 		spin_unlock(&ctl->tree_lock);
239896303081SJosef Bacik 
239996303081SJosef Bacik 		/* no pre-allocated info, allocate a new one */
240096303081SJosef Bacik 		if (!info) {
2401dc89e982SJosef Bacik 			info = kmem_cache_zalloc(btrfs_free_space_cachep,
240296303081SJosef Bacik 						 GFP_NOFS);
240396303081SJosef Bacik 			if (!info) {
240434d52cb6SLi Zefan 				spin_lock(&ctl->tree_lock);
240596303081SJosef Bacik 				ret = -ENOMEM;
240696303081SJosef Bacik 				goto out;
240796303081SJosef Bacik 			}
240896303081SJosef Bacik 		}
240996303081SJosef Bacik 
241096303081SJosef Bacik 		/* allocate the bitmap */
24113acd4850SChristophe Leroy 		info->bitmap = kmem_cache_zalloc(btrfs_free_space_bitmap_cachep,
24123acd4850SChristophe Leroy 						 GFP_NOFS);
2413da080fe1SDennis Zhou 		info->trim_state = BTRFS_TRIM_STATE_TRIMMED;
241434d52cb6SLi Zefan 		spin_lock(&ctl->tree_lock);
241596303081SJosef Bacik 		if (!info->bitmap) {
241696303081SJosef Bacik 			ret = -ENOMEM;
241796303081SJosef Bacik 			goto out;
241896303081SJosef Bacik 		}
241996303081SJosef Bacik 		goto again;
242096303081SJosef Bacik 	}
242196303081SJosef Bacik 
242296303081SJosef Bacik out:
242396303081SJosef Bacik 	if (info) {
24243acd4850SChristophe Leroy 		if (info->bitmap)
24253acd4850SChristophe Leroy 			kmem_cache_free(btrfs_free_space_bitmap_cachep,
24263acd4850SChristophe Leroy 					info->bitmap);
2427dc89e982SJosef Bacik 		kmem_cache_free(btrfs_free_space_cachep, info);
242896303081SJosef Bacik 	}
24290f9dd46cSJosef Bacik 
24300f9dd46cSJosef Bacik 	return ret;
24310f9dd46cSJosef Bacik }
24320f9dd46cSJosef Bacik 
2433a7ccb255SDennis Zhou /*
2434a7ccb255SDennis Zhou  * Free space merging rules:
2435a7ccb255SDennis Zhou  *  1) Merge trimmed areas together
2436a7ccb255SDennis Zhou  *  2) Let untrimmed areas coalesce with trimmed areas
2437a7ccb255SDennis Zhou  *  3) Always pull neighboring regions from bitmaps
2438a7ccb255SDennis Zhou  *
2439a7ccb255SDennis Zhou  * The above rules are for when we merge free space based on btrfs_trim_state.
2440a7ccb255SDennis Zhou  * Rules 2 and 3 are subtle because they are suboptimal, but are done for the
2441a7ccb255SDennis Zhou  * same reason: to promote larger extent regions which makes life easier for
2442a7ccb255SDennis Zhou  * find_free_extent().  Rule 2 enables coalescing based on the common path
2443a7ccb255SDennis Zhou  * being returning free space from btrfs_finish_extent_commit().  So when free
2444a7ccb255SDennis Zhou  * space is trimmed, it will prevent aggregating trimmed new region and
2445a7ccb255SDennis Zhou  * untrimmed regions in the rb_tree.  Rule 3 is purely to obtain larger extents
2446a7ccb255SDennis Zhou  * and provide find_free_extent() with the largest extents possible hoping for
2447a7ccb255SDennis Zhou  * the reuse path.
2448a7ccb255SDennis Zhou  */
try_merge_free_space(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,bool update_stat)2449945d8962SChris Mason static bool try_merge_free_space(struct btrfs_free_space_ctl *ctl,
2450f333adb5SLi Zefan 			  struct btrfs_free_space *info, bool update_stat)
24510f9dd46cSJosef Bacik {
2452bf53d468SJosef Bacik 	struct btrfs_free_space *left_info = NULL;
2453120d66eeSLi Zefan 	struct btrfs_free_space *right_info;
2454120d66eeSLi Zefan 	bool merged = false;
2455120d66eeSLi Zefan 	u64 offset = info->offset;
2456120d66eeSLi Zefan 	u64 bytes = info->bytes;
2457a7ccb255SDennis Zhou 	const bool is_trimmed = btrfs_free_space_trimmed(info);
24589085f425SFilipe Manana 	struct rb_node *right_prev = NULL;
24596226cb0aSJosef Bacik 
24600f9dd46cSJosef Bacik 	/*
24610f9dd46cSJosef Bacik 	 * first we want to see if there is free space adjacent to the range we
24620f9dd46cSJosef Bacik 	 * are adding, if there is remove that struct and add a new one to
24630f9dd46cSJosef Bacik 	 * cover the entire range
24640f9dd46cSJosef Bacik 	 */
246534d52cb6SLi Zefan 	right_info = tree_search_offset(ctl, offset + bytes, 0, 0);
24669085f425SFilipe Manana 	if (right_info)
24679085f425SFilipe Manana 		right_prev = rb_prev(&right_info->offset_index);
24689085f425SFilipe Manana 
24699085f425SFilipe Manana 	if (right_prev)
24709085f425SFilipe Manana 		left_info = rb_entry(right_prev, struct btrfs_free_space, offset_index);
2471bf53d468SJosef Bacik 	else if (!right_info)
247234d52cb6SLi Zefan 		left_info = tree_search_offset(ctl, offset - 1, 0, 0);
24730f9dd46cSJosef Bacik 
2474a7ccb255SDennis Zhou 	/* See try_merge_free_space() comment. */
2475a7ccb255SDennis Zhou 	if (right_info && !right_info->bitmap &&
2476a7ccb255SDennis Zhou 	    (!is_trimmed || btrfs_free_space_trimmed(right_info))) {
247732e1649bSNikolay Borisov 		unlink_free_space(ctl, right_info, update_stat);
24786226cb0aSJosef Bacik 		info->bytes += right_info->bytes;
2479dc89e982SJosef Bacik 		kmem_cache_free(btrfs_free_space_cachep, right_info);
2480120d66eeSLi Zefan 		merged = true;
24810f9dd46cSJosef Bacik 	}
24820f9dd46cSJosef Bacik 
2483a7ccb255SDennis Zhou 	/* See try_merge_free_space() comment. */
248496303081SJosef Bacik 	if (left_info && !left_info->bitmap &&
2485a7ccb255SDennis Zhou 	    left_info->offset + left_info->bytes == offset &&
2486a7ccb255SDennis Zhou 	    (!is_trimmed || btrfs_free_space_trimmed(left_info))) {
248732e1649bSNikolay Borisov 		unlink_free_space(ctl, left_info, update_stat);
24880f9dd46cSJosef Bacik 		info->offset = left_info->offset;
24890f9dd46cSJosef Bacik 		info->bytes += left_info->bytes;
2490dc89e982SJosef Bacik 		kmem_cache_free(btrfs_free_space_cachep, left_info);
2491120d66eeSLi Zefan 		merged = true;
24920f9dd46cSJosef Bacik 	}
24930f9dd46cSJosef Bacik 
2494120d66eeSLi Zefan 	return merged;
2495120d66eeSLi Zefan }
2496120d66eeSLi Zefan 
steal_from_bitmap_to_end(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,bool update_stat)249720005523SFilipe Manana static bool steal_from_bitmap_to_end(struct btrfs_free_space_ctl *ctl,
249820005523SFilipe Manana 				     struct btrfs_free_space *info,
249920005523SFilipe Manana 				     bool update_stat)
250020005523SFilipe Manana {
250120005523SFilipe Manana 	struct btrfs_free_space *bitmap;
250220005523SFilipe Manana 	unsigned long i;
250320005523SFilipe Manana 	unsigned long j;
250420005523SFilipe Manana 	const u64 end = info->offset + info->bytes;
250520005523SFilipe Manana 	const u64 bitmap_offset = offset_to_bitmap(ctl, end);
250620005523SFilipe Manana 	u64 bytes;
250720005523SFilipe Manana 
250820005523SFilipe Manana 	bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0);
250920005523SFilipe Manana 	if (!bitmap)
251020005523SFilipe Manana 		return false;
251120005523SFilipe Manana 
251220005523SFilipe Manana 	i = offset_to_bit(bitmap->offset, ctl->unit, end);
251320005523SFilipe Manana 	j = find_next_zero_bit(bitmap->bitmap, BITS_PER_BITMAP, i);
251420005523SFilipe Manana 	if (j == i)
251520005523SFilipe Manana 		return false;
251620005523SFilipe Manana 	bytes = (j - i) * ctl->unit;
251720005523SFilipe Manana 	info->bytes += bytes;
251820005523SFilipe Manana 
2519a7ccb255SDennis Zhou 	/* See try_merge_free_space() comment. */
2520a7ccb255SDennis Zhou 	if (!btrfs_free_space_trimmed(bitmap))
2521a7ccb255SDennis Zhou 		info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2522a7ccb255SDennis Zhou 
2523f594f13cSNikolay Borisov 	bitmap_clear_bits(ctl, bitmap, end, bytes, update_stat);
252420005523SFilipe Manana 
252520005523SFilipe Manana 	if (!bitmap->bytes)
252620005523SFilipe Manana 		free_bitmap(ctl, bitmap);
252720005523SFilipe Manana 
252820005523SFilipe Manana 	return true;
252920005523SFilipe Manana }
253020005523SFilipe Manana 
steal_from_bitmap_to_front(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,bool update_stat)253120005523SFilipe Manana static bool steal_from_bitmap_to_front(struct btrfs_free_space_ctl *ctl,
253220005523SFilipe Manana 				       struct btrfs_free_space *info,
253320005523SFilipe Manana 				       bool update_stat)
253420005523SFilipe Manana {
253520005523SFilipe Manana 	struct btrfs_free_space *bitmap;
253620005523SFilipe Manana 	u64 bitmap_offset;
253720005523SFilipe Manana 	unsigned long i;
253820005523SFilipe Manana 	unsigned long j;
253920005523SFilipe Manana 	unsigned long prev_j;
254020005523SFilipe Manana 	u64 bytes;
254120005523SFilipe Manana 
254220005523SFilipe Manana 	bitmap_offset = offset_to_bitmap(ctl, info->offset);
254320005523SFilipe Manana 	/* If we're on a boundary, try the previous logical bitmap. */
254420005523SFilipe Manana 	if (bitmap_offset == info->offset) {
254520005523SFilipe Manana 		if (info->offset == 0)
254620005523SFilipe Manana 			return false;
254720005523SFilipe Manana 		bitmap_offset = offset_to_bitmap(ctl, info->offset - 1);
254820005523SFilipe Manana 	}
254920005523SFilipe Manana 
255020005523SFilipe Manana 	bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0);
255120005523SFilipe Manana 	if (!bitmap)
255220005523SFilipe Manana 		return false;
255320005523SFilipe Manana 
255420005523SFilipe Manana 	i = offset_to_bit(bitmap->offset, ctl->unit, info->offset) - 1;
255520005523SFilipe Manana 	j = 0;
255620005523SFilipe Manana 	prev_j = (unsigned long)-1;
255720005523SFilipe Manana 	for_each_clear_bit_from(j, bitmap->bitmap, BITS_PER_BITMAP) {
255820005523SFilipe Manana 		if (j > i)
255920005523SFilipe Manana 			break;
256020005523SFilipe Manana 		prev_j = j;
256120005523SFilipe Manana 	}
256220005523SFilipe Manana 	if (prev_j == i)
256320005523SFilipe Manana 		return false;
256420005523SFilipe Manana 
256520005523SFilipe Manana 	if (prev_j == (unsigned long)-1)
256620005523SFilipe Manana 		bytes = (i + 1) * ctl->unit;
256720005523SFilipe Manana 	else
256820005523SFilipe Manana 		bytes = (i - prev_j) * ctl->unit;
256920005523SFilipe Manana 
257020005523SFilipe Manana 	info->offset -= bytes;
257120005523SFilipe Manana 	info->bytes += bytes;
257220005523SFilipe Manana 
2573a7ccb255SDennis Zhou 	/* See try_merge_free_space() comment. */
2574a7ccb255SDennis Zhou 	if (!btrfs_free_space_trimmed(bitmap))
2575a7ccb255SDennis Zhou 		info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2576a7ccb255SDennis Zhou 
2577f594f13cSNikolay Borisov 	bitmap_clear_bits(ctl, bitmap, info->offset, bytes, update_stat);
257820005523SFilipe Manana 
257920005523SFilipe Manana 	if (!bitmap->bytes)
258020005523SFilipe Manana 		free_bitmap(ctl, bitmap);
258120005523SFilipe Manana 
258220005523SFilipe Manana 	return true;
258320005523SFilipe Manana }
258420005523SFilipe Manana 
258520005523SFilipe Manana /*
258620005523SFilipe Manana  * We prefer always to allocate from extent entries, both for clustered and
258720005523SFilipe Manana  * non-clustered allocation requests. So when attempting to add a new extent
258820005523SFilipe Manana  * entry, try to see if there's adjacent free space in bitmap entries, and if
258920005523SFilipe Manana  * there is, migrate that space from the bitmaps to the extent.
259020005523SFilipe Manana  * Like this we get better chances of satisfying space allocation requests
259120005523SFilipe Manana  * because we attempt to satisfy them based on a single cache entry, and never
259220005523SFilipe Manana  * on 2 or more entries - even if the entries represent a contiguous free space
259320005523SFilipe Manana  * region (e.g. 1 extent entry + 1 bitmap entry starting where the extent entry
259420005523SFilipe Manana  * ends).
259520005523SFilipe Manana  */
steal_from_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * info,bool update_stat)259620005523SFilipe Manana static void steal_from_bitmap(struct btrfs_free_space_ctl *ctl,
259720005523SFilipe Manana 			      struct btrfs_free_space *info,
259820005523SFilipe Manana 			      bool update_stat)
259920005523SFilipe Manana {
260020005523SFilipe Manana 	/*
260120005523SFilipe Manana 	 * Only work with disconnected entries, as we can change their offset,
260220005523SFilipe Manana 	 * and must be extent entries.
260320005523SFilipe Manana 	 */
260420005523SFilipe Manana 	ASSERT(!info->bitmap);
260520005523SFilipe Manana 	ASSERT(RB_EMPTY_NODE(&info->offset_index));
260620005523SFilipe Manana 
260720005523SFilipe Manana 	if (ctl->total_bitmaps > 0) {
260820005523SFilipe Manana 		bool stole_end;
260920005523SFilipe Manana 		bool stole_front = false;
261020005523SFilipe Manana 
261120005523SFilipe Manana 		stole_end = steal_from_bitmap_to_end(ctl, info, update_stat);
261220005523SFilipe Manana 		if (ctl->total_bitmaps > 0)
261320005523SFilipe Manana 			stole_front = steal_from_bitmap_to_front(ctl, info,
261420005523SFilipe Manana 								 update_stat);
261520005523SFilipe Manana 
261620005523SFilipe Manana 		if (stole_end || stole_front)
261720005523SFilipe Manana 			try_merge_free_space(ctl, info, update_stat);
261820005523SFilipe Manana 	}
261920005523SFilipe Manana }
262020005523SFilipe Manana 
__btrfs_add_free_space(struct btrfs_block_group * block_group,u64 offset,u64 bytes,enum btrfs_trim_state trim_state)2621290ef19aSNikolay Borisov int __btrfs_add_free_space(struct btrfs_block_group *block_group,
2622a7ccb255SDennis Zhou 			   u64 offset, u64 bytes,
2623a7ccb255SDennis Zhou 			   enum btrfs_trim_state trim_state)
2624120d66eeSLi Zefan {
2625290ef19aSNikolay Borisov 	struct btrfs_fs_info *fs_info = block_group->fs_info;
2626290ef19aSNikolay Borisov 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2627120d66eeSLi Zefan 	struct btrfs_free_space *info;
2628120d66eeSLi Zefan 	int ret = 0;
26297fe6d45eSDennis Zhou 	u64 filter_bytes = bytes;
2630120d66eeSLi Zefan 
2631169e0da9SNaohiro Aota 	ASSERT(!btrfs_is_zoned(fs_info));
2632169e0da9SNaohiro Aota 
2633dc89e982SJosef Bacik 	info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
2634120d66eeSLi Zefan 	if (!info)
2635120d66eeSLi Zefan 		return -ENOMEM;
2636120d66eeSLi Zefan 
2637120d66eeSLi Zefan 	info->offset = offset;
2638120d66eeSLi Zefan 	info->bytes = bytes;
2639a7ccb255SDennis Zhou 	info->trim_state = trim_state;
264020005523SFilipe Manana 	RB_CLEAR_NODE(&info->offset_index);
264159c7b566SJosef Bacik 	RB_CLEAR_NODE(&info->bytes_index);
2642120d66eeSLi Zefan 
264334d52cb6SLi Zefan 	spin_lock(&ctl->tree_lock);
2644120d66eeSLi Zefan 
264534d52cb6SLi Zefan 	if (try_merge_free_space(ctl, info, true))
2646120d66eeSLi Zefan 		goto link;
2647120d66eeSLi Zefan 
2648120d66eeSLi Zefan 	/*
2649120d66eeSLi Zefan 	 * There was no extent directly to the left or right of this new
2650120d66eeSLi Zefan 	 * extent then we know we're going to have to allocate a new extent, so
2651120d66eeSLi Zefan 	 * before we do that see if we need to drop this into a bitmap
2652120d66eeSLi Zefan 	 */
265334d52cb6SLi Zefan 	ret = insert_into_bitmap(ctl, info);
2654120d66eeSLi Zefan 	if (ret < 0) {
2655120d66eeSLi Zefan 		goto out;
2656120d66eeSLi Zefan 	} else if (ret) {
2657120d66eeSLi Zefan 		ret = 0;
2658120d66eeSLi Zefan 		goto out;
2659120d66eeSLi Zefan 	}
2660120d66eeSLi Zefan link:
266120005523SFilipe Manana 	/*
266220005523SFilipe Manana 	 * Only steal free space from adjacent bitmaps if we're sure we're not
266320005523SFilipe Manana 	 * going to add the new free space to existing bitmap entries - because
266420005523SFilipe Manana 	 * that would mean unnecessary work that would be reverted. Therefore
266520005523SFilipe Manana 	 * attempt to steal space from bitmaps if we're adding an extent entry.
266620005523SFilipe Manana 	 */
266720005523SFilipe Manana 	steal_from_bitmap(ctl, info, true);
266820005523SFilipe Manana 
26697fe6d45eSDennis Zhou 	filter_bytes = max(filter_bytes, info->bytes);
26707fe6d45eSDennis Zhou 
267134d52cb6SLi Zefan 	ret = link_free_space(ctl, info);
26720f9dd46cSJosef Bacik 	if (ret)
2673dc89e982SJosef Bacik 		kmem_cache_free(btrfs_free_space_cachep, info);
267496303081SJosef Bacik out:
267566b53baeSJosef Bacik 	btrfs_discard_update_discardable(block_group);
267634d52cb6SLi Zefan 	spin_unlock(&ctl->tree_lock);
26776226cb0aSJosef Bacik 
26780f9dd46cSJosef Bacik 	if (ret) {
2679ab8d0fc4SJeff Mahoney 		btrfs_crit(fs_info, "unable to add free space :%d", ret);
2680b12d6869SJosef Bacik 		ASSERT(ret != -EEXIST);
26810f9dd46cSJosef Bacik 	}
26820f9dd46cSJosef Bacik 
26837fe6d45eSDennis Zhou 	if (trim_state != BTRFS_TRIM_STATE_TRIMMED) {
26847fe6d45eSDennis Zhou 		btrfs_discard_check_filter(block_group, filter_bytes);
2685b0643e59SDennis Zhou 		btrfs_discard_queue_work(&fs_info->discard_ctl, block_group);
26867fe6d45eSDennis Zhou 	}
2687b0643e59SDennis Zhou 
26880f9dd46cSJosef Bacik 	return ret;
26890f9dd46cSJosef Bacik }
26900f9dd46cSJosef Bacik 
__btrfs_add_free_space_zoned(struct btrfs_block_group * block_group,u64 bytenr,u64 size,bool used)2691169e0da9SNaohiro Aota static int __btrfs_add_free_space_zoned(struct btrfs_block_group *block_group,
2692169e0da9SNaohiro Aota 					u64 bytenr, u64 size, bool used)
2693169e0da9SNaohiro Aota {
2694bb5a098dSJosef Bacik 	struct btrfs_space_info *sinfo = block_group->space_info;
2695169e0da9SNaohiro Aota 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2696169e0da9SNaohiro Aota 	u64 offset = bytenr - block_group->start;
2697169e0da9SNaohiro Aota 	u64 to_free, to_unusable;
2698bb5a098dSJosef Bacik 	int bg_reclaim_threshold = 0;
26999baca56eSNaohiro Aota 	bool initial;
2700d8da0e85SNaohiro Aota 	u64 reclaimable_unusable;
270198173255SNaohiro Aota 
27029baca56eSNaohiro Aota 	spin_lock(&block_group->lock);
2703169e0da9SNaohiro Aota 
27049baca56eSNaohiro Aota 	initial = ((size == block_group->length) && (block_group->alloc_offset == 0));
27059baca56eSNaohiro Aota 	WARN_ON(!initial && offset + size > block_group->zone_capacity);
2706bb5a098dSJosef Bacik 	if (!initial)
2707bb5a098dSJosef Bacik 		bg_reclaim_threshold = READ_ONCE(sinfo->bg_reclaim_threshold);
2708bb5a098dSJosef Bacik 
2709169e0da9SNaohiro Aota 	if (!used)
2710169e0da9SNaohiro Aota 		to_free = size;
271198173255SNaohiro Aota 	else if (initial)
271298173255SNaohiro Aota 		to_free = block_group->zone_capacity;
2713169e0da9SNaohiro Aota 	else if (offset >= block_group->alloc_offset)
2714169e0da9SNaohiro Aota 		to_free = size;
2715169e0da9SNaohiro Aota 	else if (offset + size <= block_group->alloc_offset)
2716169e0da9SNaohiro Aota 		to_free = 0;
2717169e0da9SNaohiro Aota 	else
2718169e0da9SNaohiro Aota 		to_free = offset + size - block_group->alloc_offset;
2719169e0da9SNaohiro Aota 	to_unusable = size - to_free;
2720169e0da9SNaohiro Aota 
27219baca56eSNaohiro Aota 	spin_lock(&ctl->tree_lock);
2722169e0da9SNaohiro Aota 	ctl->free_space += to_free;
27239baca56eSNaohiro Aota 	spin_unlock(&ctl->tree_lock);
2724badae9c8SNaohiro Aota 	/*
2725badae9c8SNaohiro Aota 	 * If the block group is read-only, we should account freed space into
2726badae9c8SNaohiro Aota 	 * bytes_readonly.
2727badae9c8SNaohiro Aota 	 */
2728ae29e6f7SNaohiro Aota 	if (!block_group->ro) {
2729169e0da9SNaohiro Aota 		block_group->zone_unusable += to_unusable;
2730ae29e6f7SNaohiro Aota 		WARN_ON(block_group->zone_unusable > block_group->length);
2731ae29e6f7SNaohiro Aota 	}
2732169e0da9SNaohiro Aota 	if (!used) {
2733169e0da9SNaohiro Aota 		block_group->alloc_offset -= size;
2734169e0da9SNaohiro Aota 	}
2735169e0da9SNaohiro Aota 
2736d8da0e85SNaohiro Aota 	reclaimable_unusable = block_group->zone_unusable -
2737d8da0e85SNaohiro Aota 			       (block_group->length - block_group->zone_capacity);
2738169e0da9SNaohiro Aota 	/* All the region is now unusable. Mark it as unused and reclaim */
27396a8ebc77SNaohiro Aota 	if (block_group->zone_unusable == block_group->length) {
2740169e0da9SNaohiro Aota 		btrfs_mark_bg_unused(block_group);
274177233c2dSJohannes Thumshirn 	} else if (bg_reclaim_threshold &&
2742d8da0e85SNaohiro Aota 		   reclaimable_unusable >=
2743428c8e03SDavid Sterba 		   mult_perc(block_group->zone_capacity, bg_reclaim_threshold)) {
274418bb8bbfSJohannes Thumshirn 		btrfs_mark_bg_to_reclaim(block_group);
274518bb8bbfSJohannes Thumshirn 	}
2746169e0da9SNaohiro Aota 
27479baca56eSNaohiro Aota 	spin_unlock(&block_group->lock);
27489baca56eSNaohiro Aota 
2749169e0da9SNaohiro Aota 	return 0;
2750169e0da9SNaohiro Aota }
2751169e0da9SNaohiro Aota 
btrfs_add_free_space(struct btrfs_block_group * block_group,u64 bytenr,u64 size)275232da5386SDavid Sterba int btrfs_add_free_space(struct btrfs_block_group *block_group,
2753478b4d9fSJosef Bacik 			 u64 bytenr, u64 size)
2754478b4d9fSJosef Bacik {
2755a7ccb255SDennis Zhou 	enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2756a7ccb255SDennis Zhou 
2757169e0da9SNaohiro Aota 	if (btrfs_is_zoned(block_group->fs_info))
2758169e0da9SNaohiro Aota 		return __btrfs_add_free_space_zoned(block_group, bytenr, size,
2759169e0da9SNaohiro Aota 						    true);
2760169e0da9SNaohiro Aota 
2761a7ccb255SDennis Zhou 	if (btrfs_test_opt(block_group->fs_info, DISCARD_SYNC))
2762a7ccb255SDennis Zhou 		trim_state = BTRFS_TRIM_STATE_TRIMMED;
2763a7ccb255SDennis Zhou 
2764290ef19aSNikolay Borisov 	return __btrfs_add_free_space(block_group, bytenr, size, trim_state);
2765478b4d9fSJosef Bacik }
2766478b4d9fSJosef Bacik 
btrfs_add_free_space_unused(struct btrfs_block_group * block_group,u64 bytenr,u64 size)2767169e0da9SNaohiro Aota int btrfs_add_free_space_unused(struct btrfs_block_group *block_group,
2768169e0da9SNaohiro Aota 				u64 bytenr, u64 size)
2769169e0da9SNaohiro Aota {
2770169e0da9SNaohiro Aota 	if (btrfs_is_zoned(block_group->fs_info))
2771169e0da9SNaohiro Aota 		return __btrfs_add_free_space_zoned(block_group, bytenr, size,
2772169e0da9SNaohiro Aota 						    false);
2773169e0da9SNaohiro Aota 
2774169e0da9SNaohiro Aota 	return btrfs_add_free_space(block_group, bytenr, size);
2775169e0da9SNaohiro Aota }
2776169e0da9SNaohiro Aota 
2777b0643e59SDennis Zhou /*
2778b0643e59SDennis Zhou  * This is a subtle distinction because when adding free space back in general,
2779b0643e59SDennis Zhou  * we want it to be added as untrimmed for async. But in the case where we add
2780b0643e59SDennis Zhou  * it on loading of a block group, we want to consider it trimmed.
2781b0643e59SDennis Zhou  */
btrfs_add_free_space_async_trimmed(struct btrfs_block_group * block_group,u64 bytenr,u64 size)2782b0643e59SDennis Zhou int btrfs_add_free_space_async_trimmed(struct btrfs_block_group *block_group,
2783b0643e59SDennis Zhou 				       u64 bytenr, u64 size)
2784b0643e59SDennis Zhou {
2785b0643e59SDennis Zhou 	enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2786b0643e59SDennis Zhou 
2787169e0da9SNaohiro Aota 	if (btrfs_is_zoned(block_group->fs_info))
2788169e0da9SNaohiro Aota 		return __btrfs_add_free_space_zoned(block_group, bytenr, size,
2789169e0da9SNaohiro Aota 						    true);
2790169e0da9SNaohiro Aota 
2791b0643e59SDennis Zhou 	if (btrfs_test_opt(block_group->fs_info, DISCARD_SYNC) ||
2792b0643e59SDennis Zhou 	    btrfs_test_opt(block_group->fs_info, DISCARD_ASYNC))
2793b0643e59SDennis Zhou 		trim_state = BTRFS_TRIM_STATE_TRIMMED;
2794b0643e59SDennis Zhou 
2795290ef19aSNikolay Borisov 	return __btrfs_add_free_space(block_group, bytenr, size, trim_state);
2796b0643e59SDennis Zhou }
2797b0643e59SDennis Zhou 
btrfs_remove_free_space(struct btrfs_block_group * block_group,u64 offset,u64 bytes)279832da5386SDavid Sterba int btrfs_remove_free_space(struct btrfs_block_group *block_group,
27990f9dd46cSJosef Bacik 			    u64 offset, u64 bytes)
28000f9dd46cSJosef Bacik {
280134d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
28020f9dd46cSJosef Bacik 	struct btrfs_free_space *info;
2803b0175117SJosef Bacik 	int ret;
2804b0175117SJosef Bacik 	bool re_search = false;
28050f9dd46cSJosef Bacik 
2806011b41bfSNaohiro Aota 	if (btrfs_is_zoned(block_group->fs_info)) {
2807011b41bfSNaohiro Aota 		/*
2808011b41bfSNaohiro Aota 		 * This can happen with conventional zones when replaying log.
2809011b41bfSNaohiro Aota 		 * Since the allocation info of tree-log nodes are not recorded
2810011b41bfSNaohiro Aota 		 * to the extent-tree, calculate_alloc_pointer() failed to
2811011b41bfSNaohiro Aota 		 * advance the allocation pointer after last allocated tree log
2812011b41bfSNaohiro Aota 		 * node blocks.
2813011b41bfSNaohiro Aota 		 *
2814011b41bfSNaohiro Aota 		 * This function is called from
2815011b41bfSNaohiro Aota 		 * btrfs_pin_extent_for_log_replay() when replaying the log.
2816011b41bfSNaohiro Aota 		 * Advance the pointer not to overwrite the tree-log nodes.
2817011b41bfSNaohiro Aota 		 */
28180ae79c6fSNaohiro Aota 		if (block_group->start + block_group->alloc_offset <
28190ae79c6fSNaohiro Aota 		    offset + bytes) {
28200ae79c6fSNaohiro Aota 			block_group->alloc_offset =
28210ae79c6fSNaohiro Aota 				offset + bytes - block_group->start;
28220ae79c6fSNaohiro Aota 		}
2823169e0da9SNaohiro Aota 		return 0;
2824011b41bfSNaohiro Aota 	}
2825169e0da9SNaohiro Aota 
282634d52cb6SLi Zefan 	spin_lock(&ctl->tree_lock);
28276226cb0aSJosef Bacik 
282896303081SJosef Bacik again:
2829b0175117SJosef Bacik 	ret = 0;
2830bdb7d303SJosef Bacik 	if (!bytes)
2831bdb7d303SJosef Bacik 		goto out_lock;
2832bdb7d303SJosef Bacik 
283334d52cb6SLi Zefan 	info = tree_search_offset(ctl, offset, 0, 0);
283496303081SJosef Bacik 	if (!info) {
28356606bb97SJosef Bacik 		/*
28366606bb97SJosef Bacik 		 * oops didn't find an extent that matched the space we wanted
28376606bb97SJosef Bacik 		 * to remove, look for a bitmap instead
28386606bb97SJosef Bacik 		 */
283934d52cb6SLi Zefan 		info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
28406606bb97SJosef Bacik 					  1, 0);
28416606bb97SJosef Bacik 		if (!info) {
2842b0175117SJosef Bacik 			/*
2843b0175117SJosef Bacik 			 * If we found a partial bit of our free space in a
2844b0175117SJosef Bacik 			 * bitmap but then couldn't find the other part this may
2845b0175117SJosef Bacik 			 * be a problem, so WARN about it.
284624a70313SChris Mason 			 */
2847b0175117SJosef Bacik 			WARN_ON(re_search);
284896303081SJosef Bacik 			goto out_lock;
284996303081SJosef Bacik 		}
28506606bb97SJosef Bacik 	}
285196303081SJosef Bacik 
2852b0175117SJosef Bacik 	re_search = false;
2853bdb7d303SJosef Bacik 	if (!info->bitmap) {
285432e1649bSNikolay Borisov 		unlink_free_space(ctl, info, true);
2855bdb7d303SJosef Bacik 		if (offset == info->offset) {
2856bdb7d303SJosef Bacik 			u64 to_free = min(bytes, info->bytes);
28570f9dd46cSJosef Bacik 
2858bdb7d303SJosef Bacik 			info->bytes -= to_free;
2859bdb7d303SJosef Bacik 			info->offset += to_free;
2860bdb7d303SJosef Bacik 			if (info->bytes) {
28611eae31e9SChris Mason 				ret = link_free_space(ctl, info);
28621eae31e9SChris Mason 				WARN_ON(ret);
2863bdb7d303SJosef Bacik 			} else {
2864bdb7d303SJosef Bacik 				kmem_cache_free(btrfs_free_space_cachep, info);
286596303081SJosef Bacik 			}
28660f9dd46cSJosef Bacik 
2867bdb7d303SJosef Bacik 			offset += to_free;
2868bdb7d303SJosef Bacik 			bytes -= to_free;
2869bdb7d303SJosef Bacik 			goto again;
2870bdb7d303SJosef Bacik 		} else {
2871bdb7d303SJosef Bacik 			u64 old_end = info->bytes + info->offset;
28729b49c9b9SChris Mason 
2873bdb7d303SJosef Bacik 			info->bytes = offset - info->offset;
287434d52cb6SLi Zefan 			ret = link_free_space(ctl, info);
287596303081SJosef Bacik 			WARN_ON(ret);
287696303081SJosef Bacik 			if (ret)
287796303081SJosef Bacik 				goto out_lock;
2878bdb7d303SJosef Bacik 
2879bdb7d303SJosef Bacik 			/* Not enough bytes in this entry to satisfy us */
2880bdb7d303SJosef Bacik 			if (old_end < offset + bytes) {
2881bdb7d303SJosef Bacik 				bytes -= old_end - offset;
2882bdb7d303SJosef Bacik 				offset = old_end;
2883bdb7d303SJosef Bacik 				goto again;
2884bdb7d303SJosef Bacik 			} else if (old_end == offset + bytes) {
2885bdb7d303SJosef Bacik 				/* all done */
2886bdb7d303SJosef Bacik 				goto out_lock;
28879b49c9b9SChris Mason 			}
288834d52cb6SLi Zefan 			spin_unlock(&ctl->tree_lock);
288996303081SJosef Bacik 
2890290ef19aSNikolay Borisov 			ret = __btrfs_add_free_space(block_group,
2891a7ccb255SDennis Zhou 						     offset + bytes,
2892a7ccb255SDennis Zhou 						     old_end - (offset + bytes),
2893a7ccb255SDennis Zhou 						     info->trim_state);
2894bdb7d303SJosef Bacik 			WARN_ON(ret);
289596303081SJosef Bacik 			goto out;
289696303081SJosef Bacik 		}
2897bdb7d303SJosef Bacik 	}
289896303081SJosef Bacik 
289934d52cb6SLi Zefan 	ret = remove_from_bitmap(ctl, info, &offset, &bytes);
2900b0175117SJosef Bacik 	if (ret == -EAGAIN) {
2901b0175117SJosef Bacik 		re_search = true;
290296303081SJosef Bacik 		goto again;
2903b0175117SJosef Bacik 	}
290496303081SJosef Bacik out_lock:
290566b53baeSJosef Bacik 	btrfs_discard_update_discardable(block_group);
290634d52cb6SLi Zefan 	spin_unlock(&ctl->tree_lock);
29070f9dd46cSJosef Bacik out:
290825179201SJosef Bacik 	return ret;
290925179201SJosef Bacik }
291025179201SJosef Bacik 
btrfs_dump_free_space(struct btrfs_block_group * block_group,u64 bytes)291132da5386SDavid Sterba void btrfs_dump_free_space(struct btrfs_block_group *block_group,
29120f9dd46cSJosef Bacik 			   u64 bytes)
29130f9dd46cSJosef Bacik {
29140b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = block_group->fs_info;
291534d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
29160f9dd46cSJosef Bacik 	struct btrfs_free_space *info;
29170f9dd46cSJosef Bacik 	struct rb_node *n;
29180f9dd46cSJosef Bacik 	int count = 0;
29190f9dd46cSJosef Bacik 
2920169e0da9SNaohiro Aota 	/*
2921169e0da9SNaohiro Aota 	 * Zoned btrfs does not use free space tree and cluster. Just print
2922169e0da9SNaohiro Aota 	 * out the free space after the allocation offset.
2923169e0da9SNaohiro Aota 	 */
2924169e0da9SNaohiro Aota 	if (btrfs_is_zoned(fs_info)) {
2925afba2bc0SNaohiro Aota 		btrfs_info(fs_info, "free space %llu active %d",
2926afba2bc0SNaohiro Aota 			   block_group->zone_capacity - block_group->alloc_offset,
29273349b57fSJosef Bacik 			   test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
29283349b57fSJosef Bacik 				    &block_group->runtime_flags));
2929169e0da9SNaohiro Aota 		return;
2930169e0da9SNaohiro Aota 	}
2931169e0da9SNaohiro Aota 
29329084cb6aSFilipe Manana 	spin_lock(&ctl->tree_lock);
293334d52cb6SLi Zefan 	for (n = rb_first(&ctl->free_space_offset); n; n = rb_next(n)) {
29340f9dd46cSJosef Bacik 		info = rb_entry(n, struct btrfs_free_space, offset_index);
2935f6175efaSLiu Bo 		if (info->bytes >= bytes && !block_group->ro)
29360f9dd46cSJosef Bacik 			count++;
29370b246afaSJeff Mahoney 		btrfs_crit(fs_info, "entry offset %llu, bytes %llu, bitmap %s",
2938c1c9ff7cSGeert Uytterhoeven 			   info->offset, info->bytes,
293996303081SJosef Bacik 		       (info->bitmap) ? "yes" : "no");
29400f9dd46cSJosef Bacik 	}
29419084cb6aSFilipe Manana 	spin_unlock(&ctl->tree_lock);
29420b246afaSJeff Mahoney 	btrfs_info(fs_info, "block group has cluster?: %s",
294396303081SJosef Bacik 	       list_empty(&block_group->cluster_list) ? "no" : "yes");
29440b246afaSJeff Mahoney 	btrfs_info(fs_info,
29454d2024e9SFilipe Manana 		   "%d free space entries at or bigger than %llu bytes",
29464d2024e9SFilipe Manana 		   count, bytes);
29470f9dd46cSJosef Bacik }
29480f9dd46cSJosef Bacik 
btrfs_init_free_space_ctl(struct btrfs_block_group * block_group,struct btrfs_free_space_ctl * ctl)2949cd79909bSJosef Bacik void btrfs_init_free_space_ctl(struct btrfs_block_group *block_group,
2950cd79909bSJosef Bacik 			       struct btrfs_free_space_ctl *ctl)
29510f9dd46cSJosef Bacik {
29520b246afaSJeff Mahoney 	struct btrfs_fs_info *fs_info = block_group->fs_info;
29530f9dd46cSJosef Bacik 
295434d52cb6SLi Zefan 	spin_lock_init(&ctl->tree_lock);
29550b246afaSJeff Mahoney 	ctl->unit = fs_info->sectorsize;
2956b3470b5dSDavid Sterba 	ctl->start = block_group->start;
2957364be842SNikolay Borisov 	ctl->block_group = block_group;
295834d52cb6SLi Zefan 	ctl->op = &free_space_op;
295959c7b566SJosef Bacik 	ctl->free_space_bytes = RB_ROOT_CACHED;
296055507ce3SFilipe Manana 	INIT_LIST_HEAD(&ctl->trimming_ranges);
296155507ce3SFilipe Manana 	mutex_init(&ctl->cache_writeout_mutex);
29620f9dd46cSJosef Bacik 
296334d52cb6SLi Zefan 	/*
296434d52cb6SLi Zefan 	 * we only want to have 32k of ram per block group for keeping
296534d52cb6SLi Zefan 	 * track of free space, and if we pass 1/2 of that we want to
296634d52cb6SLi Zefan 	 * start converting things over to using bitmaps
296734d52cb6SLi Zefan 	 */
2968ee22184bSByongho Lee 	ctl->extents_thresh = (SZ_32K / 2) / sizeof(struct btrfs_free_space);
29690f9dd46cSJosef Bacik }
29700f9dd46cSJosef Bacik 
2971fa9c0d79SChris Mason /*
2972fa9c0d79SChris Mason  * for a given cluster, put all of its extents back into the free
2973fa9c0d79SChris Mason  * space cache.  If the block group passed doesn't match the block group
2974fa9c0d79SChris Mason  * pointed to by the cluster, someone else raced in and freed the
2975fa9c0d79SChris Mason  * cluster already.  In that case, we just return without changing anything
2976fa9c0d79SChris Mason  */
__btrfs_return_cluster_to_free_space(struct btrfs_block_group * block_group,struct btrfs_free_cluster * cluster)297769b0e093SAnand Jain static void __btrfs_return_cluster_to_free_space(
297832da5386SDavid Sterba 			     struct btrfs_block_group *block_group,
2979fa9c0d79SChris Mason 			     struct btrfs_free_cluster *cluster)
2980fa9c0d79SChris Mason {
29817e5ba559SFilipe Manana 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2982fa9c0d79SChris Mason 	struct rb_node *node;
2983fa9c0d79SChris Mason 
29847e5ba559SFilipe Manana 	lockdep_assert_held(&ctl->tree_lock);
29857e5ba559SFilipe Manana 
2986fa9c0d79SChris Mason 	spin_lock(&cluster->lock);
298795c85fbaSJosef Bacik 	if (cluster->block_group != block_group) {
298895c85fbaSJosef Bacik 		spin_unlock(&cluster->lock);
298995c85fbaSJosef Bacik 		return;
299095c85fbaSJosef Bacik 	}
2991fa9c0d79SChris Mason 
299296303081SJosef Bacik 	cluster->block_group = NULL;
2993fa9c0d79SChris Mason 	cluster->window_start = 0;
299496303081SJosef Bacik 	list_del_init(&cluster->block_group_list);
299596303081SJosef Bacik 
2996fa9c0d79SChris Mason 	node = rb_first(&cluster->root);
2997fa9c0d79SChris Mason 	while (node) {
29980d6bac4dSFilipe Manana 		struct btrfs_free_space *entry;
29994e69b598SJosef Bacik 
3000fa9c0d79SChris Mason 		entry = rb_entry(node, struct btrfs_free_space, offset_index);
3001fa9c0d79SChris Mason 		node = rb_next(&entry->offset_index);
3002fa9c0d79SChris Mason 		rb_erase(&entry->offset_index, &cluster->root);
300320005523SFilipe Manana 		RB_CLEAR_NODE(&entry->offset_index);
30044e69b598SJosef Bacik 
30050d6bac4dSFilipe Manana 		if (!entry->bitmap) {
3006dfb79ddbSDennis Zhou 			/* Merging treats extents as if they were new */
30075dc7c10bSDennis Zhou 			if (!btrfs_free_space_trimmed(entry)) {
3008dfb79ddbSDennis Zhou 				ctl->discardable_extents[BTRFS_STAT_CURR]--;
30095dc7c10bSDennis Zhou 				ctl->discardable_bytes[BTRFS_STAT_CURR] -=
30105dc7c10bSDennis Zhou 					entry->bytes;
30115dc7c10bSDennis Zhou 			}
3012dfb79ddbSDennis Zhou 
301334d52cb6SLi Zefan 			try_merge_free_space(ctl, entry, false);
301420005523SFilipe Manana 			steal_from_bitmap(ctl, entry, false);
3015dfb79ddbSDennis Zhou 
3016dfb79ddbSDennis Zhou 			/* As we insert directly, update these statistics */
30175dc7c10bSDennis Zhou 			if (!btrfs_free_space_trimmed(entry)) {
3018dfb79ddbSDennis Zhou 				ctl->discardable_extents[BTRFS_STAT_CURR]++;
30195dc7c10bSDennis Zhou 				ctl->discardable_bytes[BTRFS_STAT_CURR] +=
30205dc7c10bSDennis Zhou 					entry->bytes;
30215dc7c10bSDennis Zhou 			}
302220005523SFilipe Manana 		}
302313c2018fSFilipe Manana 		tree_insert_offset(ctl, NULL, entry);
302459c7b566SJosef Bacik 		rb_add_cached(&entry->bytes_index, &ctl->free_space_bytes,
302559c7b566SJosef Bacik 			      entry_less);
3026fa9c0d79SChris Mason 	}
30276bef4d31SEric Paris 	cluster->root = RB_ROOT;
3028fa9c0d79SChris Mason 	spin_unlock(&cluster->lock);
302996303081SJosef Bacik 	btrfs_put_block_group(block_group);
3030fa9c0d79SChris Mason }
3031fa9c0d79SChris Mason 
btrfs_remove_free_space_cache(struct btrfs_block_group * block_group)303232da5386SDavid Sterba void btrfs_remove_free_space_cache(struct btrfs_block_group *block_group)
30330f9dd46cSJosef Bacik {
303434d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3035fa9c0d79SChris Mason 	struct btrfs_free_cluster *cluster;
303696303081SJosef Bacik 	struct list_head *head;
30370f9dd46cSJosef Bacik 
303834d52cb6SLi Zefan 	spin_lock(&ctl->tree_lock);
303996303081SJosef Bacik 	while ((head = block_group->cluster_list.next) !=
304096303081SJosef Bacik 	       &block_group->cluster_list) {
304196303081SJosef Bacik 		cluster = list_entry(head, struct btrfs_free_cluster,
304296303081SJosef Bacik 				     block_group_list);
3043fa9c0d79SChris Mason 
3044fa9c0d79SChris Mason 		WARN_ON(cluster->block_group != block_group);
3045fa9c0d79SChris Mason 		__btrfs_return_cluster_to_free_space(block_group, cluster);
3046351810c1SDavid Sterba 
3047351810c1SDavid Sterba 		cond_resched_lock(&ctl->tree_lock);
3048fa9c0d79SChris Mason 	}
3049fc80f7acSJosef Bacik 	__btrfs_remove_free_space_cache(ctl);
305066b53baeSJosef Bacik 	btrfs_discard_update_discardable(block_group);
305134d52cb6SLi Zefan 	spin_unlock(&ctl->tree_lock);
3052fa9c0d79SChris Mason 
30530f9dd46cSJosef Bacik }
30540f9dd46cSJosef Bacik 
305543dd529aSDavid Sterba /*
30566e80d4f8SDennis Zhou  * Walk @block_group's free space rb_tree to determine if everything is trimmed.
30576e80d4f8SDennis Zhou  */
btrfs_is_free_space_trimmed(struct btrfs_block_group * block_group)30586e80d4f8SDennis Zhou bool btrfs_is_free_space_trimmed(struct btrfs_block_group *block_group)
30596e80d4f8SDennis Zhou {
30606e80d4f8SDennis Zhou 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
30616e80d4f8SDennis Zhou 	struct btrfs_free_space *info;
30626e80d4f8SDennis Zhou 	struct rb_node *node;
30636e80d4f8SDennis Zhou 	bool ret = true;
30646e80d4f8SDennis Zhou 
30656e80d4f8SDennis Zhou 	spin_lock(&ctl->tree_lock);
30666e80d4f8SDennis Zhou 	node = rb_first(&ctl->free_space_offset);
30676e80d4f8SDennis Zhou 
30686e80d4f8SDennis Zhou 	while (node) {
30696e80d4f8SDennis Zhou 		info = rb_entry(node, struct btrfs_free_space, offset_index);
30706e80d4f8SDennis Zhou 
30716e80d4f8SDennis Zhou 		if (!btrfs_free_space_trimmed(info)) {
30726e80d4f8SDennis Zhou 			ret = false;
30736e80d4f8SDennis Zhou 			break;
30746e80d4f8SDennis Zhou 		}
30756e80d4f8SDennis Zhou 
30766e80d4f8SDennis Zhou 		node = rb_next(node);
30776e80d4f8SDennis Zhou 	}
30786e80d4f8SDennis Zhou 
30796e80d4f8SDennis Zhou 	spin_unlock(&ctl->tree_lock);
30806e80d4f8SDennis Zhou 	return ret;
30816e80d4f8SDennis Zhou }
30826e80d4f8SDennis Zhou 
btrfs_find_space_for_alloc(struct btrfs_block_group * block_group,u64 offset,u64 bytes,u64 empty_size,u64 * max_extent_size)308332da5386SDavid Sterba u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group,
3084a4820398SMiao Xie 			       u64 offset, u64 bytes, u64 empty_size,
3085a4820398SMiao Xie 			       u64 *max_extent_size)
30860f9dd46cSJosef Bacik {
308734d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
30889ddf648fSDennis Zhou 	struct btrfs_discard_ctl *discard_ctl =
30899ddf648fSDennis Zhou 					&block_group->fs_info->discard_ctl;
30906226cb0aSJosef Bacik 	struct btrfs_free_space *entry = NULL;
309196303081SJosef Bacik 	u64 bytes_search = bytes + empty_size;
30926226cb0aSJosef Bacik 	u64 ret = 0;
309353b381b3SDavid Woodhouse 	u64 align_gap = 0;
309453b381b3SDavid Woodhouse 	u64 align_gap_len = 0;
3095a7ccb255SDennis Zhou 	enum btrfs_trim_state align_gap_trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
309659c7b566SJosef Bacik 	bool use_bytes_index = (offset == block_group->start);
30970f9dd46cSJosef Bacik 
30982eda5708SNaohiro Aota 	ASSERT(!btrfs_is_zoned(block_group->fs_info));
30992eda5708SNaohiro Aota 
310034d52cb6SLi Zefan 	spin_lock(&ctl->tree_lock);
310153b381b3SDavid Woodhouse 	entry = find_free_space(ctl, &offset, &bytes_search,
310259c7b566SJosef Bacik 				block_group->full_stripe_len, max_extent_size,
310359c7b566SJosef Bacik 				use_bytes_index);
31046226cb0aSJosef Bacik 	if (!entry)
310596303081SJosef Bacik 		goto out;
310696303081SJosef Bacik 
310796303081SJosef Bacik 	ret = offset;
310896303081SJosef Bacik 	if (entry->bitmap) {
3109f594f13cSNikolay Borisov 		bitmap_clear_bits(ctl, entry, offset, bytes, true);
31109ddf648fSDennis Zhou 
31119ddf648fSDennis Zhou 		if (!btrfs_free_space_trimmed(entry))
31129ddf648fSDennis Zhou 			atomic64_add(bytes, &discard_ctl->discard_bytes_saved);
31139ddf648fSDennis Zhou 
3114edf6e2d1SLi Zefan 		if (!entry->bytes)
311534d52cb6SLi Zefan 			free_bitmap(ctl, entry);
311696303081SJosef Bacik 	} else {
311732e1649bSNikolay Borisov 		unlink_free_space(ctl, entry, true);
311853b381b3SDavid Woodhouse 		align_gap_len = offset - entry->offset;
311953b381b3SDavid Woodhouse 		align_gap = entry->offset;
3120a7ccb255SDennis Zhou 		align_gap_trim_state = entry->trim_state;
312153b381b3SDavid Woodhouse 
31229ddf648fSDennis Zhou 		if (!btrfs_free_space_trimmed(entry))
31239ddf648fSDennis Zhou 			atomic64_add(bytes, &discard_ctl->discard_bytes_saved);
31249ddf648fSDennis Zhou 
312553b381b3SDavid Woodhouse 		entry->offset = offset + bytes;
312653b381b3SDavid Woodhouse 		WARN_ON(entry->bytes < bytes + align_gap_len);
312753b381b3SDavid Woodhouse 
312853b381b3SDavid Woodhouse 		entry->bytes -= bytes + align_gap_len;
31296226cb0aSJosef Bacik 		if (!entry->bytes)
3130dc89e982SJosef Bacik 			kmem_cache_free(btrfs_free_space_cachep, entry);
31316226cb0aSJosef Bacik 		else
313234d52cb6SLi Zefan 			link_free_space(ctl, entry);
31330f9dd46cSJosef Bacik 	}
313496303081SJosef Bacik out:
313566b53baeSJosef Bacik 	btrfs_discard_update_discardable(block_group);
313634d52cb6SLi Zefan 	spin_unlock(&ctl->tree_lock);
3137817d52f8SJosef Bacik 
313853b381b3SDavid Woodhouse 	if (align_gap_len)
3139290ef19aSNikolay Borisov 		__btrfs_add_free_space(block_group, align_gap, align_gap_len,
3140a7ccb255SDennis Zhou 				       align_gap_trim_state);
31410f9dd46cSJosef Bacik 	return ret;
31420f9dd46cSJosef Bacik }
3143fa9c0d79SChris Mason 
3144fa9c0d79SChris Mason /*
3145fa9c0d79SChris Mason  * given a cluster, put all of its extents back into the free space
3146fa9c0d79SChris Mason  * cache.  If a block group is passed, this function will only free
3147fa9c0d79SChris Mason  * a cluster that belongs to the passed block group.
3148fa9c0d79SChris Mason  *
3149fa9c0d79SChris Mason  * Otherwise, it'll get a reference on the block group pointed to by the
3150fa9c0d79SChris Mason  * cluster and remove the cluster from it.
3151fa9c0d79SChris Mason  */
btrfs_return_cluster_to_free_space(struct btrfs_block_group * block_group,struct btrfs_free_cluster * cluster)315269b0e093SAnand Jain void btrfs_return_cluster_to_free_space(
315332da5386SDavid Sterba 			       struct btrfs_block_group *block_group,
3154fa9c0d79SChris Mason 			       struct btrfs_free_cluster *cluster)
3155fa9c0d79SChris Mason {
315634d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl;
3157fa9c0d79SChris Mason 
3158fa9c0d79SChris Mason 	/* first, get a safe pointer to the block group */
3159fa9c0d79SChris Mason 	spin_lock(&cluster->lock);
3160fa9c0d79SChris Mason 	if (!block_group) {
3161fa9c0d79SChris Mason 		block_group = cluster->block_group;
3162fa9c0d79SChris Mason 		if (!block_group) {
3163fa9c0d79SChris Mason 			spin_unlock(&cluster->lock);
316469b0e093SAnand Jain 			return;
3165fa9c0d79SChris Mason 		}
3166fa9c0d79SChris Mason 	} else if (cluster->block_group != block_group) {
3167fa9c0d79SChris Mason 		/* someone else has already freed it don't redo their work */
3168fa9c0d79SChris Mason 		spin_unlock(&cluster->lock);
316969b0e093SAnand Jain 		return;
3170fa9c0d79SChris Mason 	}
3171b5790d51SAnand Jain 	btrfs_get_block_group(block_group);
3172fa9c0d79SChris Mason 	spin_unlock(&cluster->lock);
3173fa9c0d79SChris Mason 
317434d52cb6SLi Zefan 	ctl = block_group->free_space_ctl;
317534d52cb6SLi Zefan 
3176fa9c0d79SChris Mason 	/* now return any extents the cluster had on it */
317734d52cb6SLi Zefan 	spin_lock(&ctl->tree_lock);
317869b0e093SAnand Jain 	__btrfs_return_cluster_to_free_space(block_group, cluster);
317934d52cb6SLi Zefan 	spin_unlock(&ctl->tree_lock);
3180fa9c0d79SChris Mason 
31816e80d4f8SDennis Zhou 	btrfs_discard_queue_work(&block_group->fs_info->discard_ctl, block_group);
31826e80d4f8SDennis Zhou 
3183fa9c0d79SChris Mason 	/* finally drop our ref */
3184fa9c0d79SChris Mason 	btrfs_put_block_group(block_group);
3185fa9c0d79SChris Mason }
3186fa9c0d79SChris Mason 
btrfs_alloc_from_bitmap(struct btrfs_block_group * block_group,struct btrfs_free_cluster * cluster,struct btrfs_free_space * entry,u64 bytes,u64 min_start,u64 * max_extent_size)318732da5386SDavid Sterba static u64 btrfs_alloc_from_bitmap(struct btrfs_block_group *block_group,
318896303081SJosef Bacik 				   struct btrfs_free_cluster *cluster,
31894e69b598SJosef Bacik 				   struct btrfs_free_space *entry,
3190a4820398SMiao Xie 				   u64 bytes, u64 min_start,
3191a4820398SMiao Xie 				   u64 *max_extent_size)
319296303081SJosef Bacik {
319334d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
319496303081SJosef Bacik 	int err;
319596303081SJosef Bacik 	u64 search_start = cluster->window_start;
319696303081SJosef Bacik 	u64 search_bytes = bytes;
319796303081SJosef Bacik 	u64 ret = 0;
319896303081SJosef Bacik 
319996303081SJosef Bacik 	search_start = min_start;
320096303081SJosef Bacik 	search_bytes = bytes;
320196303081SJosef Bacik 
32020584f718SJosef Bacik 	err = search_bitmap(ctl, entry, &search_start, &search_bytes, true);
3203a4820398SMiao Xie 	if (err) {
3204ad22cf6eSJosef Bacik 		*max_extent_size = max(get_max_extent_size(entry),
3205ad22cf6eSJosef Bacik 				       *max_extent_size);
32064e69b598SJosef Bacik 		return 0;
3207a4820398SMiao Xie 	}
320896303081SJosef Bacik 
320996303081SJosef Bacik 	ret = search_start;
3210f594f13cSNikolay Borisov 	bitmap_clear_bits(ctl, entry, ret, bytes, false);
321196303081SJosef Bacik 
321296303081SJosef Bacik 	return ret;
321396303081SJosef Bacik }
321496303081SJosef Bacik 
3215fa9c0d79SChris Mason /*
3216fa9c0d79SChris Mason  * given a cluster, try to allocate 'bytes' from it, returns 0
3217fa9c0d79SChris Mason  * if it couldn't find anything suitably large, or a logical disk offset
3218fa9c0d79SChris Mason  * if things worked out
3219fa9c0d79SChris Mason  */
btrfs_alloc_from_cluster(struct btrfs_block_group * block_group,struct btrfs_free_cluster * cluster,u64 bytes,u64 min_start,u64 * max_extent_size)322032da5386SDavid Sterba u64 btrfs_alloc_from_cluster(struct btrfs_block_group *block_group,
3221fa9c0d79SChris Mason 			     struct btrfs_free_cluster *cluster, u64 bytes,
3222a4820398SMiao Xie 			     u64 min_start, u64 *max_extent_size)
3223fa9c0d79SChris Mason {
322434d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
32259ddf648fSDennis Zhou 	struct btrfs_discard_ctl *discard_ctl =
32269ddf648fSDennis Zhou 					&block_group->fs_info->discard_ctl;
3227fa9c0d79SChris Mason 	struct btrfs_free_space *entry = NULL;
3228fa9c0d79SChris Mason 	struct rb_node *node;
3229fa9c0d79SChris Mason 	u64 ret = 0;
3230fa9c0d79SChris Mason 
32312eda5708SNaohiro Aota 	ASSERT(!btrfs_is_zoned(block_group->fs_info));
32322eda5708SNaohiro Aota 
3233fa9c0d79SChris Mason 	spin_lock(&cluster->lock);
3234fa9c0d79SChris Mason 	if (bytes > cluster->max_size)
3235fa9c0d79SChris Mason 		goto out;
3236fa9c0d79SChris Mason 
3237fa9c0d79SChris Mason 	if (cluster->block_group != block_group)
3238fa9c0d79SChris Mason 		goto out;
3239fa9c0d79SChris Mason 
3240fa9c0d79SChris Mason 	node = rb_first(&cluster->root);
3241fa9c0d79SChris Mason 	if (!node)
3242fa9c0d79SChris Mason 		goto out;
3243fa9c0d79SChris Mason 
3244fa9c0d79SChris Mason 	entry = rb_entry(node, struct btrfs_free_space, offset_index);
3245fa9c0d79SChris Mason 	while (1) {
3246ad22cf6eSJosef Bacik 		if (entry->bytes < bytes)
3247ad22cf6eSJosef Bacik 			*max_extent_size = max(get_max_extent_size(entry),
3248ad22cf6eSJosef Bacik 					       *max_extent_size);
3249a4820398SMiao Xie 
32504e69b598SJosef Bacik 		if (entry->bytes < bytes ||
32514e69b598SJosef Bacik 		    (!entry->bitmap && entry->offset < min_start)) {
3252fa9c0d79SChris Mason 			node = rb_next(&entry->offset_index);
3253fa9c0d79SChris Mason 			if (!node)
3254fa9c0d79SChris Mason 				break;
3255fa9c0d79SChris Mason 			entry = rb_entry(node, struct btrfs_free_space,
3256fa9c0d79SChris Mason 					 offset_index);
3257fa9c0d79SChris Mason 			continue;
3258fa9c0d79SChris Mason 		}
32594e69b598SJosef Bacik 
32604e69b598SJosef Bacik 		if (entry->bitmap) {
32614e69b598SJosef Bacik 			ret = btrfs_alloc_from_bitmap(block_group,
32624e69b598SJosef Bacik 						      cluster, entry, bytes,
3263a4820398SMiao Xie 						      cluster->window_start,
3264a4820398SMiao Xie 						      max_extent_size);
32654e69b598SJosef Bacik 			if (ret == 0) {
32664e69b598SJosef Bacik 				node = rb_next(&entry->offset_index);
32674e69b598SJosef Bacik 				if (!node)
32684e69b598SJosef Bacik 					break;
32694e69b598SJosef Bacik 				entry = rb_entry(node, struct btrfs_free_space,
32704e69b598SJosef Bacik 						 offset_index);
32714e69b598SJosef Bacik 				continue;
32724e69b598SJosef Bacik 			}
32739b230628SJosef Bacik 			cluster->window_start += bytes;
32744e69b598SJosef Bacik 		} else {
3275fa9c0d79SChris Mason 			ret = entry->offset;
3276fa9c0d79SChris Mason 
3277fa9c0d79SChris Mason 			entry->offset += bytes;
3278fa9c0d79SChris Mason 			entry->bytes -= bytes;
32794e69b598SJosef Bacik 		}
3280fa9c0d79SChris Mason 
3281fa9c0d79SChris Mason 		break;
3282fa9c0d79SChris Mason 	}
3283fa9c0d79SChris Mason out:
3284fa9c0d79SChris Mason 	spin_unlock(&cluster->lock);
328596303081SJosef Bacik 
32865e71b5d5SLi Zefan 	if (!ret)
32875e71b5d5SLi Zefan 		return 0;
32885e71b5d5SLi Zefan 
328934d52cb6SLi Zefan 	spin_lock(&ctl->tree_lock);
32905e71b5d5SLi Zefan 
32919ddf648fSDennis Zhou 	if (!btrfs_free_space_trimmed(entry))
32929ddf648fSDennis Zhou 		atomic64_add(bytes, &discard_ctl->discard_bytes_saved);
32939ddf648fSDennis Zhou 
329434d52cb6SLi Zefan 	ctl->free_space -= bytes;
32955dc7c10bSDennis Zhou 	if (!entry->bitmap && !btrfs_free_space_trimmed(entry))
32965dc7c10bSDennis Zhou 		ctl->discardable_bytes[BTRFS_STAT_CURR] -= bytes;
32973c179165SNikolay Borisov 
32983c179165SNikolay Borisov 	spin_lock(&cluster->lock);
32995e71b5d5SLi Zefan 	if (entry->bytes == 0) {
33003c179165SNikolay Borisov 		rb_erase(&entry->offset_index, &cluster->root);
330134d52cb6SLi Zefan 		ctl->free_extents--;
33024e69b598SJosef Bacik 		if (entry->bitmap) {
33033acd4850SChristophe Leroy 			kmem_cache_free(btrfs_free_space_bitmap_cachep,
33043acd4850SChristophe Leroy 					entry->bitmap);
330534d52cb6SLi Zefan 			ctl->total_bitmaps--;
3306fa598b06SDavid Sterba 			recalculate_thresholds(ctl);
3307dfb79ddbSDennis Zhou 		} else if (!btrfs_free_space_trimmed(entry)) {
3308dfb79ddbSDennis Zhou 			ctl->discardable_extents[BTRFS_STAT_CURR]--;
33094e69b598SJosef Bacik 		}
3310dc89e982SJosef Bacik 		kmem_cache_free(btrfs_free_space_cachep, entry);
33115e71b5d5SLi Zefan 	}
33125e71b5d5SLi Zefan 
33133c179165SNikolay Borisov 	spin_unlock(&cluster->lock);
331434d52cb6SLi Zefan 	spin_unlock(&ctl->tree_lock);
33155e71b5d5SLi Zefan 
3316fa9c0d79SChris Mason 	return ret;
3317fa9c0d79SChris Mason }
3318fa9c0d79SChris Mason 
btrfs_bitmap_cluster(struct btrfs_block_group * block_group,struct btrfs_free_space * entry,struct btrfs_free_cluster * cluster,u64 offset,u64 bytes,u64 cont1_bytes,u64 min_bytes)331932da5386SDavid Sterba static int btrfs_bitmap_cluster(struct btrfs_block_group *block_group,
332096303081SJosef Bacik 				struct btrfs_free_space *entry,
332196303081SJosef Bacik 				struct btrfs_free_cluster *cluster,
33221bb91902SAlexandre Oliva 				u64 offset, u64 bytes,
33231bb91902SAlexandre Oliva 				u64 cont1_bytes, u64 min_bytes)
332496303081SJosef Bacik {
332534d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
332696303081SJosef Bacik 	unsigned long next_zero;
332796303081SJosef Bacik 	unsigned long i;
33281bb91902SAlexandre Oliva 	unsigned long want_bits;
33291bb91902SAlexandre Oliva 	unsigned long min_bits;
333096303081SJosef Bacik 	unsigned long found_bits;
3331cef40483SJosef Bacik 	unsigned long max_bits = 0;
333296303081SJosef Bacik 	unsigned long start = 0;
333396303081SJosef Bacik 	unsigned long total_found = 0;
33344e69b598SJosef Bacik 	int ret;
333596303081SJosef Bacik 
33367e5ba559SFilipe Manana 	lockdep_assert_held(&ctl->tree_lock);
33377e5ba559SFilipe Manana 
333896009762SWang Sheng-Hui 	i = offset_to_bit(entry->offset, ctl->unit,
333996303081SJosef Bacik 			  max_t(u64, offset, entry->offset));
334096009762SWang Sheng-Hui 	want_bits = bytes_to_bits(bytes, ctl->unit);
334196009762SWang Sheng-Hui 	min_bits = bytes_to_bits(min_bytes, ctl->unit);
334296303081SJosef Bacik 
3343cef40483SJosef Bacik 	/*
3344cef40483SJosef Bacik 	 * Don't bother looking for a cluster in this bitmap if it's heavily
3345cef40483SJosef Bacik 	 * fragmented.
3346cef40483SJosef Bacik 	 */
3347cef40483SJosef Bacik 	if (entry->max_extent_size &&
3348cef40483SJosef Bacik 	    entry->max_extent_size < cont1_bytes)
3349cef40483SJosef Bacik 		return -ENOSPC;
335096303081SJosef Bacik again:
335196303081SJosef Bacik 	found_bits = 0;
3352ebb3dad4SWei Yongjun 	for_each_set_bit_from(i, entry->bitmap, BITS_PER_BITMAP) {
335396303081SJosef Bacik 		next_zero = find_next_zero_bit(entry->bitmap,
335496303081SJosef Bacik 					       BITS_PER_BITMAP, i);
33551bb91902SAlexandre Oliva 		if (next_zero - i >= min_bits) {
335696303081SJosef Bacik 			found_bits = next_zero - i;
3357cef40483SJosef Bacik 			if (found_bits > max_bits)
3358cef40483SJosef Bacik 				max_bits = found_bits;
335996303081SJosef Bacik 			break;
336096303081SJosef Bacik 		}
3361cef40483SJosef Bacik 		if (next_zero - i > max_bits)
3362cef40483SJosef Bacik 			max_bits = next_zero - i;
336396303081SJosef Bacik 		i = next_zero;
336496303081SJosef Bacik 	}
336596303081SJosef Bacik 
3366cef40483SJosef Bacik 	if (!found_bits) {
3367cef40483SJosef Bacik 		entry->max_extent_size = (u64)max_bits * ctl->unit;
33684e69b598SJosef Bacik 		return -ENOSPC;
3369cef40483SJosef Bacik 	}
337096303081SJosef Bacik 
33711bb91902SAlexandre Oliva 	if (!total_found) {
337296303081SJosef Bacik 		start = i;
3373b78d09bcSAlexandre Oliva 		cluster->max_size = 0;
337496303081SJosef Bacik 	}
337596303081SJosef Bacik 
337696303081SJosef Bacik 	total_found += found_bits;
337796303081SJosef Bacik 
337896009762SWang Sheng-Hui 	if (cluster->max_size < found_bits * ctl->unit)
337996009762SWang Sheng-Hui 		cluster->max_size = found_bits * ctl->unit;
338096303081SJosef Bacik 
33811bb91902SAlexandre Oliva 	if (total_found < want_bits || cluster->max_size < cont1_bytes) {
33821bb91902SAlexandre Oliva 		i = next_zero + 1;
338396303081SJosef Bacik 		goto again;
338496303081SJosef Bacik 	}
338596303081SJosef Bacik 
338696009762SWang Sheng-Hui 	cluster->window_start = start * ctl->unit + entry->offset;
338734d52cb6SLi Zefan 	rb_erase(&entry->offset_index, &ctl->free_space_offset);
338859c7b566SJosef Bacik 	rb_erase_cached(&entry->bytes_index, &ctl->free_space_bytes);
338959c7b566SJosef Bacik 
339059c7b566SJosef Bacik 	/*
339159c7b566SJosef Bacik 	 * We need to know if we're currently on the normal space index when we
339259c7b566SJosef Bacik 	 * manipulate the bitmap so that we know we need to remove and re-insert
339359c7b566SJosef Bacik 	 * it into the space_index tree.  Clear the bytes_index node here so the
339459c7b566SJosef Bacik 	 * bitmap manipulation helpers know not to mess with the space_index
339559c7b566SJosef Bacik 	 * until this bitmap entry is added back into the normal cache.
339659c7b566SJosef Bacik 	 */
339759c7b566SJosef Bacik 	RB_CLEAR_NODE(&entry->bytes_index);
339859c7b566SJosef Bacik 
339913c2018fSFilipe Manana 	ret = tree_insert_offset(ctl, cluster, entry);
3400b12d6869SJosef Bacik 	ASSERT(!ret); /* -EEXIST; Logic error */
340196303081SJosef Bacik 
34023f7de037SJosef Bacik 	trace_btrfs_setup_cluster(block_group, cluster,
340396009762SWang Sheng-Hui 				  total_found * ctl->unit, 1);
340496303081SJosef Bacik 	return 0;
340596303081SJosef Bacik }
340696303081SJosef Bacik 
3407fa9c0d79SChris Mason /*
34084e69b598SJosef Bacik  * This searches the block group for just extents to fill the cluster with.
34091bb91902SAlexandre Oliva  * Try to find a cluster with at least bytes total bytes, at least one
34101bb91902SAlexandre Oliva  * extent of cont1_bytes, and other clusters of at least min_bytes.
34114e69b598SJosef Bacik  */
34123de85bb9SJosef Bacik static noinline int
setup_cluster_no_bitmap(struct btrfs_block_group * block_group,struct btrfs_free_cluster * cluster,struct list_head * bitmaps,u64 offset,u64 bytes,u64 cont1_bytes,u64 min_bytes)341332da5386SDavid Sterba setup_cluster_no_bitmap(struct btrfs_block_group *block_group,
34144e69b598SJosef Bacik 			struct btrfs_free_cluster *cluster,
34153de85bb9SJosef Bacik 			struct list_head *bitmaps, u64 offset, u64 bytes,
34161bb91902SAlexandre Oliva 			u64 cont1_bytes, u64 min_bytes)
34174e69b598SJosef Bacik {
341834d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
34194e69b598SJosef Bacik 	struct btrfs_free_space *first = NULL;
34204e69b598SJosef Bacik 	struct btrfs_free_space *entry = NULL;
34214e69b598SJosef Bacik 	struct btrfs_free_space *last;
34224e69b598SJosef Bacik 	struct rb_node *node;
34234e69b598SJosef Bacik 	u64 window_free;
34244e69b598SJosef Bacik 	u64 max_extent;
34253f7de037SJosef Bacik 	u64 total_size = 0;
34264e69b598SJosef Bacik 
34277e5ba559SFilipe Manana 	lockdep_assert_held(&ctl->tree_lock);
34287e5ba559SFilipe Manana 
342934d52cb6SLi Zefan 	entry = tree_search_offset(ctl, offset, 0, 1);
34304e69b598SJosef Bacik 	if (!entry)
34314e69b598SJosef Bacik 		return -ENOSPC;
34324e69b598SJosef Bacik 
34334e69b598SJosef Bacik 	/*
34344e69b598SJosef Bacik 	 * We don't want bitmaps, so just move along until we find a normal
34354e69b598SJosef Bacik 	 * extent entry.
34364e69b598SJosef Bacik 	 */
34371bb91902SAlexandre Oliva 	while (entry->bitmap || entry->bytes < min_bytes) {
34381bb91902SAlexandre Oliva 		if (entry->bitmap && list_empty(&entry->list))
343986d4a77bSJosef Bacik 			list_add_tail(&entry->list, bitmaps);
34404e69b598SJosef Bacik 		node = rb_next(&entry->offset_index);
34414e69b598SJosef Bacik 		if (!node)
34424e69b598SJosef Bacik 			return -ENOSPC;
34434e69b598SJosef Bacik 		entry = rb_entry(node, struct btrfs_free_space, offset_index);
34444e69b598SJosef Bacik 	}
34454e69b598SJosef Bacik 
34464e69b598SJosef Bacik 	window_free = entry->bytes;
34474e69b598SJosef Bacik 	max_extent = entry->bytes;
34484e69b598SJosef Bacik 	first = entry;
34494e69b598SJosef Bacik 	last = entry;
34504e69b598SJosef Bacik 
34511bb91902SAlexandre Oliva 	for (node = rb_next(&entry->offset_index); node;
34521bb91902SAlexandre Oliva 	     node = rb_next(&entry->offset_index)) {
34534e69b598SJosef Bacik 		entry = rb_entry(node, struct btrfs_free_space, offset_index);
34544e69b598SJosef Bacik 
345586d4a77bSJosef Bacik 		if (entry->bitmap) {
345686d4a77bSJosef Bacik 			if (list_empty(&entry->list))
345786d4a77bSJosef Bacik 				list_add_tail(&entry->list, bitmaps);
34584e69b598SJosef Bacik 			continue;
345986d4a77bSJosef Bacik 		}
346086d4a77bSJosef Bacik 
34611bb91902SAlexandre Oliva 		if (entry->bytes < min_bytes)
34621bb91902SAlexandre Oliva 			continue;
34631bb91902SAlexandre Oliva 
34644e69b598SJosef Bacik 		last = entry;
34654e69b598SJosef Bacik 		window_free += entry->bytes;
34664e69b598SJosef Bacik 		if (entry->bytes > max_extent)
34674e69b598SJosef Bacik 			max_extent = entry->bytes;
34684e69b598SJosef Bacik 	}
34691bb91902SAlexandre Oliva 
34701bb91902SAlexandre Oliva 	if (window_free < bytes || max_extent < cont1_bytes)
34711bb91902SAlexandre Oliva 		return -ENOSPC;
34724e69b598SJosef Bacik 
34734e69b598SJosef Bacik 	cluster->window_start = first->offset;
34744e69b598SJosef Bacik 
34754e69b598SJosef Bacik 	node = &first->offset_index;
34764e69b598SJosef Bacik 
34774e69b598SJosef Bacik 	/*
34784e69b598SJosef Bacik 	 * now we've found our entries, pull them out of the free space
34794e69b598SJosef Bacik 	 * cache and put them into the cluster rbtree
34804e69b598SJosef Bacik 	 */
34814e69b598SJosef Bacik 	do {
34824e69b598SJosef Bacik 		int ret;
34834e69b598SJosef Bacik 
34844e69b598SJosef Bacik 		entry = rb_entry(node, struct btrfs_free_space, offset_index);
34854e69b598SJosef Bacik 		node = rb_next(&entry->offset_index);
34861bb91902SAlexandre Oliva 		if (entry->bitmap || entry->bytes < min_bytes)
34874e69b598SJosef Bacik 			continue;
34884e69b598SJosef Bacik 
348934d52cb6SLi Zefan 		rb_erase(&entry->offset_index, &ctl->free_space_offset);
349059c7b566SJosef Bacik 		rb_erase_cached(&entry->bytes_index, &ctl->free_space_bytes);
349113c2018fSFilipe Manana 		ret = tree_insert_offset(ctl, cluster, entry);
34923f7de037SJosef Bacik 		total_size += entry->bytes;
3493b12d6869SJosef Bacik 		ASSERT(!ret); /* -EEXIST; Logic error */
34944e69b598SJosef Bacik 	} while (node && entry != last);
34954e69b598SJosef Bacik 
34964e69b598SJosef Bacik 	cluster->max_size = max_extent;
34973f7de037SJosef Bacik 	trace_btrfs_setup_cluster(block_group, cluster, total_size, 0);
34984e69b598SJosef Bacik 	return 0;
34994e69b598SJosef Bacik }
35004e69b598SJosef Bacik 
35014e69b598SJosef Bacik /*
35024e69b598SJosef Bacik  * This specifically looks for bitmaps that may work in the cluster, we assume
35034e69b598SJosef Bacik  * that we have already failed to find extents that will work.
35044e69b598SJosef Bacik  */
35053de85bb9SJosef Bacik static noinline int
setup_cluster_bitmap(struct btrfs_block_group * block_group,struct btrfs_free_cluster * cluster,struct list_head * bitmaps,u64 offset,u64 bytes,u64 cont1_bytes,u64 min_bytes)350632da5386SDavid Sterba setup_cluster_bitmap(struct btrfs_block_group *block_group,
35074e69b598SJosef Bacik 		     struct btrfs_free_cluster *cluster,
35083de85bb9SJosef Bacik 		     struct list_head *bitmaps, u64 offset, u64 bytes,
35091bb91902SAlexandre Oliva 		     u64 cont1_bytes, u64 min_bytes)
35104e69b598SJosef Bacik {
351134d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
35121b9b922aSChris Mason 	struct btrfs_free_space *entry = NULL;
35134e69b598SJosef Bacik 	int ret = -ENOSPC;
35140f0fbf1dSLi Zefan 	u64 bitmap_offset = offset_to_bitmap(ctl, offset);
35154e69b598SJosef Bacik 
351634d52cb6SLi Zefan 	if (ctl->total_bitmaps == 0)
35174e69b598SJosef Bacik 		return -ENOSPC;
35184e69b598SJosef Bacik 
351986d4a77bSJosef Bacik 	/*
35200f0fbf1dSLi Zefan 	 * The bitmap that covers offset won't be in the list unless offset
35210f0fbf1dSLi Zefan 	 * is just its start offset.
35220f0fbf1dSLi Zefan 	 */
35231b9b922aSChris Mason 	if (!list_empty(bitmaps))
35240f0fbf1dSLi Zefan 		entry = list_first_entry(bitmaps, struct btrfs_free_space, list);
35251b9b922aSChris Mason 
35261b9b922aSChris Mason 	if (!entry || entry->offset != bitmap_offset) {
35270f0fbf1dSLi Zefan 		entry = tree_search_offset(ctl, bitmap_offset, 1, 0);
35280f0fbf1dSLi Zefan 		if (entry && list_empty(&entry->list))
35290f0fbf1dSLi Zefan 			list_add(&entry->list, bitmaps);
35300f0fbf1dSLi Zefan 	}
35310f0fbf1dSLi Zefan 
353286d4a77bSJosef Bacik 	list_for_each_entry(entry, bitmaps, list) {
3533357b9784SJosef Bacik 		if (entry->bytes < bytes)
353486d4a77bSJosef Bacik 			continue;
353586d4a77bSJosef Bacik 		ret = btrfs_bitmap_cluster(block_group, entry, cluster, offset,
35361bb91902SAlexandre Oliva 					   bytes, cont1_bytes, min_bytes);
353786d4a77bSJosef Bacik 		if (!ret)
353886d4a77bSJosef Bacik 			return 0;
353986d4a77bSJosef Bacik 	}
354086d4a77bSJosef Bacik 
354186d4a77bSJosef Bacik 	/*
354252621cb6SLi Zefan 	 * The bitmaps list has all the bitmaps that record free space
354352621cb6SLi Zefan 	 * starting after offset, so no more search is required.
354486d4a77bSJosef Bacik 	 */
354586d4a77bSJosef Bacik 	return -ENOSPC;
35464e69b598SJosef Bacik }
35474e69b598SJosef Bacik 
35484e69b598SJosef Bacik /*
3549fa9c0d79SChris Mason  * here we try to find a cluster of blocks in a block group.  The goal
35501bb91902SAlexandre Oliva  * is to find at least bytes+empty_size.
3551fa9c0d79SChris Mason  * We might not find them all in one contiguous area.
3552fa9c0d79SChris Mason  *
3553fa9c0d79SChris Mason  * returns zero and sets up cluster if things worked out, otherwise
3554fa9c0d79SChris Mason  * it returns -enospc
3555fa9c0d79SChris Mason  */
btrfs_find_space_cluster(struct btrfs_block_group * block_group,struct btrfs_free_cluster * cluster,u64 offset,u64 bytes,u64 empty_size)355632da5386SDavid Sterba int btrfs_find_space_cluster(struct btrfs_block_group *block_group,
3557fa9c0d79SChris Mason 			     struct btrfs_free_cluster *cluster,
3558fa9c0d79SChris Mason 			     u64 offset, u64 bytes, u64 empty_size)
3559fa9c0d79SChris Mason {
35602ceeae2eSDavid Sterba 	struct btrfs_fs_info *fs_info = block_group->fs_info;
356134d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
356286d4a77bSJosef Bacik 	struct btrfs_free_space *entry, *tmp;
356352621cb6SLi Zefan 	LIST_HEAD(bitmaps);
3564fa9c0d79SChris Mason 	u64 min_bytes;
35651bb91902SAlexandre Oliva 	u64 cont1_bytes;
3566fa9c0d79SChris Mason 	int ret;
3567fa9c0d79SChris Mason 
3568fa9c0d79SChris Mason 	/*
35691bb91902SAlexandre Oliva 	 * Choose the minimum extent size we'll require for this
35701bb91902SAlexandre Oliva 	 * cluster.  For SSD_SPREAD, don't allow any fragmentation.
35711bb91902SAlexandre Oliva 	 * For metadata, allow allocates with smaller extents.  For
35721bb91902SAlexandre Oliva 	 * data, keep it dense.
3573fa9c0d79SChris Mason 	 */
35740b246afaSJeff Mahoney 	if (btrfs_test_opt(fs_info, SSD_SPREAD)) {
3575c1867eb3SDavid Sterba 		cont1_bytes = bytes + empty_size;
3576c1867eb3SDavid Sterba 		min_bytes = cont1_bytes;
35771bb91902SAlexandre Oliva 	} else if (block_group->flags & BTRFS_BLOCK_GROUP_METADATA) {
35781bb91902SAlexandre Oliva 		cont1_bytes = bytes;
35790b246afaSJeff Mahoney 		min_bytes = fs_info->sectorsize;
35801bb91902SAlexandre Oliva 	} else {
35811bb91902SAlexandre Oliva 		cont1_bytes = max(bytes, (bytes + empty_size) >> 2);
35820b246afaSJeff Mahoney 		min_bytes = fs_info->sectorsize;
35831bb91902SAlexandre Oliva 	}
3584fa9c0d79SChris Mason 
358534d52cb6SLi Zefan 	spin_lock(&ctl->tree_lock);
35867d0d2e8eSJosef Bacik 
35877d0d2e8eSJosef Bacik 	/*
35887d0d2e8eSJosef Bacik 	 * If we know we don't have enough space to make a cluster don't even
35897d0d2e8eSJosef Bacik 	 * bother doing all the work to try and find one.
35907d0d2e8eSJosef Bacik 	 */
35911bb91902SAlexandre Oliva 	if (ctl->free_space < bytes) {
359234d52cb6SLi Zefan 		spin_unlock(&ctl->tree_lock);
35937d0d2e8eSJosef Bacik 		return -ENOSPC;
35947d0d2e8eSJosef Bacik 	}
35957d0d2e8eSJosef Bacik 
3596fa9c0d79SChris Mason 	spin_lock(&cluster->lock);
3597fa9c0d79SChris Mason 
3598fa9c0d79SChris Mason 	/* someone already found a cluster, hooray */
3599fa9c0d79SChris Mason 	if (cluster->block_group) {
3600fa9c0d79SChris Mason 		ret = 0;
3601fa9c0d79SChris Mason 		goto out;
3602fa9c0d79SChris Mason 	}
360396303081SJosef Bacik 
36043f7de037SJosef Bacik 	trace_btrfs_find_cluster(block_group, offset, bytes, empty_size,
36053f7de037SJosef Bacik 				 min_bytes);
36063f7de037SJosef Bacik 
360786d4a77bSJosef Bacik 	ret = setup_cluster_no_bitmap(block_group, cluster, &bitmaps, offset,
36081bb91902SAlexandre Oliva 				      bytes + empty_size,
36091bb91902SAlexandre Oliva 				      cont1_bytes, min_bytes);
361086d4a77bSJosef Bacik 	if (ret)
361186d4a77bSJosef Bacik 		ret = setup_cluster_bitmap(block_group, cluster, &bitmaps,
36121bb91902SAlexandre Oliva 					   offset, bytes + empty_size,
36131bb91902SAlexandre Oliva 					   cont1_bytes, min_bytes);
361486d4a77bSJosef Bacik 
361586d4a77bSJosef Bacik 	/* Clear our temporary list */
361686d4a77bSJosef Bacik 	list_for_each_entry_safe(entry, tmp, &bitmaps, list)
361786d4a77bSJosef Bacik 		list_del_init(&entry->list);
361896303081SJosef Bacik 
36194e69b598SJosef Bacik 	if (!ret) {
3620b5790d51SAnand Jain 		btrfs_get_block_group(block_group);
36214e69b598SJosef Bacik 		list_add_tail(&cluster->block_group_list,
36224e69b598SJosef Bacik 			      &block_group->cluster_list);
3623fa9c0d79SChris Mason 		cluster->block_group = block_group;
36243f7de037SJosef Bacik 	} else {
36253f7de037SJosef Bacik 		trace_btrfs_failed_cluster_setup(block_group);
36264e69b598SJosef Bacik 	}
3627fa9c0d79SChris Mason out:
3628fa9c0d79SChris Mason 	spin_unlock(&cluster->lock);
362934d52cb6SLi Zefan 	spin_unlock(&ctl->tree_lock);
3630fa9c0d79SChris Mason 
3631fa9c0d79SChris Mason 	return ret;
3632fa9c0d79SChris Mason }
3633fa9c0d79SChris Mason 
3634fa9c0d79SChris Mason /*
3635fa9c0d79SChris Mason  * simple code to zero out a cluster
3636fa9c0d79SChris Mason  */
btrfs_init_free_cluster(struct btrfs_free_cluster * cluster)3637fa9c0d79SChris Mason void btrfs_init_free_cluster(struct btrfs_free_cluster *cluster)
3638fa9c0d79SChris Mason {
3639fa9c0d79SChris Mason 	spin_lock_init(&cluster->lock);
3640fa9c0d79SChris Mason 	spin_lock_init(&cluster->refill_lock);
36416bef4d31SEric Paris 	cluster->root = RB_ROOT;
3642fa9c0d79SChris Mason 	cluster->max_size = 0;
3643c759c4e1SJosef Bacik 	cluster->fragmented = false;
3644fa9c0d79SChris Mason 	INIT_LIST_HEAD(&cluster->block_group_list);
3645fa9c0d79SChris Mason 	cluster->block_group = NULL;
3646fa9c0d79SChris Mason }
3647fa9c0d79SChris Mason 
do_trimming(struct btrfs_block_group * block_group,u64 * total_trimmed,u64 start,u64 bytes,u64 reserved_start,u64 reserved_bytes,enum btrfs_trim_state reserved_trim_state,struct btrfs_trim_range * trim_entry)364832da5386SDavid Sterba static int do_trimming(struct btrfs_block_group *block_group,
36497fe1e641SLi Zefan 		       u64 *total_trimmed, u64 start, u64 bytes,
365055507ce3SFilipe Manana 		       u64 reserved_start, u64 reserved_bytes,
3651b0643e59SDennis Zhou 		       enum btrfs_trim_state reserved_trim_state,
365255507ce3SFilipe Manana 		       struct btrfs_trim_range *trim_entry)
36537fe1e641SLi Zefan {
36547fe1e641SLi Zefan 	struct btrfs_space_info *space_info = block_group->space_info;
36557fe1e641SLi Zefan 	struct btrfs_fs_info *fs_info = block_group->fs_info;
365655507ce3SFilipe Manana 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
36577fe1e641SLi Zefan 	int ret;
36587fe1e641SLi Zefan 	int update = 0;
3659b0643e59SDennis Zhou 	const u64 end = start + bytes;
3660b0643e59SDennis Zhou 	const u64 reserved_end = reserved_start + reserved_bytes;
3661b0643e59SDennis Zhou 	enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
36627fe1e641SLi Zefan 	u64 trimmed = 0;
36637fe1e641SLi Zefan 
36647fe1e641SLi Zefan 	spin_lock(&space_info->lock);
36657fe1e641SLi Zefan 	spin_lock(&block_group->lock);
36667fe1e641SLi Zefan 	if (!block_group->ro) {
36677fe1e641SLi Zefan 		block_group->reserved += reserved_bytes;
36687fe1e641SLi Zefan 		space_info->bytes_reserved += reserved_bytes;
36697fe1e641SLi Zefan 		update = 1;
36707fe1e641SLi Zefan 	}
36717fe1e641SLi Zefan 	spin_unlock(&block_group->lock);
36727fe1e641SLi Zefan 	spin_unlock(&space_info->lock);
36737fe1e641SLi Zefan 
36742ff7e61eSJeff Mahoney 	ret = btrfs_discard_extent(fs_info, start, bytes, &trimmed);
3675b0643e59SDennis Zhou 	if (!ret) {
36767fe1e641SLi Zefan 		*total_trimmed += trimmed;
3677b0643e59SDennis Zhou 		trim_state = BTRFS_TRIM_STATE_TRIMMED;
3678b0643e59SDennis Zhou 	}
36797fe1e641SLi Zefan 
368055507ce3SFilipe Manana 	mutex_lock(&ctl->cache_writeout_mutex);
3681b0643e59SDennis Zhou 	if (reserved_start < start)
3682290ef19aSNikolay Borisov 		__btrfs_add_free_space(block_group, reserved_start,
3683b0643e59SDennis Zhou 				       start - reserved_start,
3684b0643e59SDennis Zhou 				       reserved_trim_state);
3685b77433b1SFilipe Manana 	if (end < reserved_end)
3686290ef19aSNikolay Borisov 		__btrfs_add_free_space(block_group, end, reserved_end - end,
3687b0643e59SDennis Zhou 				       reserved_trim_state);
3688290ef19aSNikolay Borisov 	__btrfs_add_free_space(block_group, start, bytes, trim_state);
368955507ce3SFilipe Manana 	list_del(&trim_entry->list);
369055507ce3SFilipe Manana 	mutex_unlock(&ctl->cache_writeout_mutex);
36917fe1e641SLi Zefan 
36927fe1e641SLi Zefan 	if (update) {
36937fe1e641SLi Zefan 		spin_lock(&space_info->lock);
36947fe1e641SLi Zefan 		spin_lock(&block_group->lock);
36957fe1e641SLi Zefan 		if (block_group->ro)
36967fe1e641SLi Zefan 			space_info->bytes_readonly += reserved_bytes;
36977fe1e641SLi Zefan 		block_group->reserved -= reserved_bytes;
36987fe1e641SLi Zefan 		space_info->bytes_reserved -= reserved_bytes;
36997fe1e641SLi Zefan 		spin_unlock(&block_group->lock);
37008f63a840SSu Yue 		spin_unlock(&space_info->lock);
37017fe1e641SLi Zefan 	}
37027fe1e641SLi Zefan 
37037fe1e641SLi Zefan 	return ret;
37047fe1e641SLi Zefan }
37057fe1e641SLi Zefan 
37062bee7eb8SDennis Zhou /*
37072bee7eb8SDennis Zhou  * If @async is set, then we will trim 1 region and return.
37082bee7eb8SDennis Zhou  */
trim_no_bitmap(struct btrfs_block_group * block_group,u64 * total_trimmed,u64 start,u64 end,u64 minlen,bool async)370932da5386SDavid Sterba static int trim_no_bitmap(struct btrfs_block_group *block_group,
37102bee7eb8SDennis Zhou 			  u64 *total_trimmed, u64 start, u64 end, u64 minlen,
37112bee7eb8SDennis Zhou 			  bool async)
3712f7039b1dSLi Dongyang {
371319b2a2c7SDennis Zhou 	struct btrfs_discard_ctl *discard_ctl =
371419b2a2c7SDennis Zhou 					&block_group->fs_info->discard_ctl;
371534d52cb6SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
37167fe1e641SLi Zefan 	struct btrfs_free_space *entry;
37177fe1e641SLi Zefan 	struct rb_node *node;
3718f7039b1dSLi Dongyang 	int ret = 0;
37197fe1e641SLi Zefan 	u64 extent_start;
37207fe1e641SLi Zefan 	u64 extent_bytes;
3721b0643e59SDennis Zhou 	enum btrfs_trim_state extent_trim_state;
37227fe1e641SLi Zefan 	u64 bytes;
372319b2a2c7SDennis Zhou 	const u64 max_discard_size = READ_ONCE(discard_ctl->max_discard_size);
3724f7039b1dSLi Dongyang 
3725f7039b1dSLi Dongyang 	while (start < end) {
372655507ce3SFilipe Manana 		struct btrfs_trim_range trim_entry;
372755507ce3SFilipe Manana 
372855507ce3SFilipe Manana 		mutex_lock(&ctl->cache_writeout_mutex);
372934d52cb6SLi Zefan 		spin_lock(&ctl->tree_lock);
3730f7039b1dSLi Dongyang 
37312bee7eb8SDennis Zhou 		if (ctl->free_space < minlen)
37322bee7eb8SDennis Zhou 			goto out_unlock;
3733f7039b1dSLi Dongyang 
373434d52cb6SLi Zefan 		entry = tree_search_offset(ctl, start, 0, 1);
37352bee7eb8SDennis Zhou 		if (!entry)
37362bee7eb8SDennis Zhou 			goto out_unlock;
3737f7039b1dSLi Dongyang 
37382bee7eb8SDennis Zhou 		/* Skip bitmaps and if async, already trimmed entries */
37392bee7eb8SDennis Zhou 		while (entry->bitmap ||
37402bee7eb8SDennis Zhou 		       (async && btrfs_free_space_trimmed(entry))) {
37417fe1e641SLi Zefan 			node = rb_next(&entry->offset_index);
37422bee7eb8SDennis Zhou 			if (!node)
37432bee7eb8SDennis Zhou 				goto out_unlock;
37447fe1e641SLi Zefan 			entry = rb_entry(node, struct btrfs_free_space,
37457fe1e641SLi Zefan 					 offset_index);
37467fe1e641SLi Zefan 		}
37477fe1e641SLi Zefan 
37482bee7eb8SDennis Zhou 		if (entry->offset >= end)
37492bee7eb8SDennis Zhou 			goto out_unlock;
37507fe1e641SLi Zefan 
37517fe1e641SLi Zefan 		extent_start = entry->offset;
37527fe1e641SLi Zefan 		extent_bytes = entry->bytes;
3753b0643e59SDennis Zhou 		extent_trim_state = entry->trim_state;
37544aa9ad52SDennis Zhou 		if (async) {
37554aa9ad52SDennis Zhou 			start = entry->offset;
37564aa9ad52SDennis Zhou 			bytes = entry->bytes;
37574aa9ad52SDennis Zhou 			if (bytes < minlen) {
37584aa9ad52SDennis Zhou 				spin_unlock(&ctl->tree_lock);
37594aa9ad52SDennis Zhou 				mutex_unlock(&ctl->cache_writeout_mutex);
37604aa9ad52SDennis Zhou 				goto next;
37614aa9ad52SDennis Zhou 			}
376232e1649bSNikolay Borisov 			unlink_free_space(ctl, entry, true);
37637fe6d45eSDennis Zhou 			/*
37647fe6d45eSDennis Zhou 			 * Let bytes = BTRFS_MAX_DISCARD_SIZE + X.
37657fe6d45eSDennis Zhou 			 * If X < BTRFS_ASYNC_DISCARD_MIN_FILTER, we won't trim
37667fe6d45eSDennis Zhou 			 * X when we come back around.  So trim it now.
37677fe6d45eSDennis Zhou 			 */
37687fe6d45eSDennis Zhou 			if (max_discard_size &&
37697fe6d45eSDennis Zhou 			    bytes >= (max_discard_size +
37707fe6d45eSDennis Zhou 				      BTRFS_ASYNC_DISCARD_MIN_FILTER)) {
377119b2a2c7SDennis Zhou 				bytes = max_discard_size;
377219b2a2c7SDennis Zhou 				extent_bytes = max_discard_size;
377319b2a2c7SDennis Zhou 				entry->offset += max_discard_size;
377419b2a2c7SDennis Zhou 				entry->bytes -= max_discard_size;
37754aa9ad52SDennis Zhou 				link_free_space(ctl, entry);
37764aa9ad52SDennis Zhou 			} else {
37774aa9ad52SDennis Zhou 				kmem_cache_free(btrfs_free_space_cachep, entry);
37784aa9ad52SDennis Zhou 			}
37794aa9ad52SDennis Zhou 		} else {
37807fe1e641SLi Zefan 			start = max(start, extent_start);
37817fe1e641SLi Zefan 			bytes = min(extent_start + extent_bytes, end) - start;
37827fe1e641SLi Zefan 			if (bytes < minlen) {
378334d52cb6SLi Zefan 				spin_unlock(&ctl->tree_lock);
378455507ce3SFilipe Manana 				mutex_unlock(&ctl->cache_writeout_mutex);
37857fe1e641SLi Zefan 				goto next;
3786f7039b1dSLi Dongyang 			}
37877fe1e641SLi Zefan 
378832e1649bSNikolay Borisov 			unlink_free_space(ctl, entry, true);
3789f789b684SLi Zefan 			kmem_cache_free(btrfs_free_space_cachep, entry);
37904aa9ad52SDennis Zhou 		}
3791f7039b1dSLi Dongyang 
379234d52cb6SLi Zefan 		spin_unlock(&ctl->tree_lock);
379355507ce3SFilipe Manana 		trim_entry.start = extent_start;
379455507ce3SFilipe Manana 		trim_entry.bytes = extent_bytes;
379555507ce3SFilipe Manana 		list_add_tail(&trim_entry.list, &ctl->trimming_ranges);
379655507ce3SFilipe Manana 		mutex_unlock(&ctl->cache_writeout_mutex);
3797f7039b1dSLi Dongyang 
37987fe1e641SLi Zefan 		ret = do_trimming(block_group, total_trimmed, start, bytes,
3799b0643e59SDennis Zhou 				  extent_start, extent_bytes, extent_trim_state,
3800b0643e59SDennis Zhou 				  &trim_entry);
38012bee7eb8SDennis Zhou 		if (ret) {
38022bee7eb8SDennis Zhou 			block_group->discard_cursor = start + bytes;
3803f7039b1dSLi Dongyang 			break;
38042bee7eb8SDennis Zhou 		}
38057fe1e641SLi Zefan next:
3806f7039b1dSLi Dongyang 		start += bytes;
38072bee7eb8SDennis Zhou 		block_group->discard_cursor = start;
38082bee7eb8SDennis Zhou 		if (async && *total_trimmed)
38092bee7eb8SDennis Zhou 			break;
3810f7039b1dSLi Dongyang 
3811*7a670b42SLuca Stefani 		if (btrfs_trim_interrupted()) {
3812f7039b1dSLi Dongyang 			ret = -ERESTARTSYS;
3813f7039b1dSLi Dongyang 			break;
3814f7039b1dSLi Dongyang 		}
3815f7039b1dSLi Dongyang 
3816f7039b1dSLi Dongyang 		cond_resched();
3817f7039b1dSLi Dongyang 	}
38182bee7eb8SDennis Zhou 
38192bee7eb8SDennis Zhou 	return ret;
38202bee7eb8SDennis Zhou 
38212bee7eb8SDennis Zhou out_unlock:
38222bee7eb8SDennis Zhou 	block_group->discard_cursor = btrfs_block_group_end(block_group);
38232bee7eb8SDennis Zhou 	spin_unlock(&ctl->tree_lock);
38242bee7eb8SDennis Zhou 	mutex_unlock(&ctl->cache_writeout_mutex);
38252bee7eb8SDennis Zhou 
38267fe1e641SLi Zefan 	return ret;
38277fe1e641SLi Zefan }
38287fe1e641SLi Zefan 
3829da080fe1SDennis Zhou /*
3830da080fe1SDennis Zhou  * If we break out of trimming a bitmap prematurely, we should reset the
3831da080fe1SDennis Zhou  * trimming bit.  In a rather contrieved case, it's possible to race here so
3832da080fe1SDennis Zhou  * reset the state to BTRFS_TRIM_STATE_UNTRIMMED.
3833da080fe1SDennis Zhou  *
3834da080fe1SDennis Zhou  * start = start of bitmap
3835da080fe1SDennis Zhou  * end = near end of bitmap
3836da080fe1SDennis Zhou  *
3837da080fe1SDennis Zhou  * Thread 1:			Thread 2:
3838da080fe1SDennis Zhou  * trim_bitmaps(start)
3839da080fe1SDennis Zhou  *				trim_bitmaps(end)
3840da080fe1SDennis Zhou  *				end_trimming_bitmap()
3841da080fe1SDennis Zhou  * reset_trimming_bitmap()
3842da080fe1SDennis Zhou  */
reset_trimming_bitmap(struct btrfs_free_space_ctl * ctl,u64 offset)3843da080fe1SDennis Zhou static void reset_trimming_bitmap(struct btrfs_free_space_ctl *ctl, u64 offset)
3844da080fe1SDennis Zhou {
3845da080fe1SDennis Zhou 	struct btrfs_free_space *entry;
3846da080fe1SDennis Zhou 
3847da080fe1SDennis Zhou 	spin_lock(&ctl->tree_lock);
3848da080fe1SDennis Zhou 	entry = tree_search_offset(ctl, offset, 1, 0);
3849dfb79ddbSDennis Zhou 	if (entry) {
38505dc7c10bSDennis Zhou 		if (btrfs_free_space_trimmed(entry)) {
3851dfb79ddbSDennis Zhou 			ctl->discardable_extents[BTRFS_STAT_CURR] +=
3852dfb79ddbSDennis Zhou 				entry->bitmap_extents;
38535dc7c10bSDennis Zhou 			ctl->discardable_bytes[BTRFS_STAT_CURR] += entry->bytes;
38545dc7c10bSDennis Zhou 		}
3855da080fe1SDennis Zhou 		entry->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
3856dfb79ddbSDennis Zhou 	}
3857dfb79ddbSDennis Zhou 
3858da080fe1SDennis Zhou 	spin_unlock(&ctl->tree_lock);
3859da080fe1SDennis Zhou }
3860da080fe1SDennis Zhou 
end_trimming_bitmap(struct btrfs_free_space_ctl * ctl,struct btrfs_free_space * entry)3861dfb79ddbSDennis Zhou static void end_trimming_bitmap(struct btrfs_free_space_ctl *ctl,
3862dfb79ddbSDennis Zhou 				struct btrfs_free_space *entry)
3863da080fe1SDennis Zhou {
3864dfb79ddbSDennis Zhou 	if (btrfs_free_space_trimming_bitmap(entry)) {
3865da080fe1SDennis Zhou 		entry->trim_state = BTRFS_TRIM_STATE_TRIMMED;
3866dfb79ddbSDennis Zhou 		ctl->discardable_extents[BTRFS_STAT_CURR] -=
3867dfb79ddbSDennis Zhou 			entry->bitmap_extents;
38685dc7c10bSDennis Zhou 		ctl->discardable_bytes[BTRFS_STAT_CURR] -= entry->bytes;
3869dfb79ddbSDennis Zhou 	}
3870da080fe1SDennis Zhou }
3871da080fe1SDennis Zhou 
38722bee7eb8SDennis Zhou /*
38732bee7eb8SDennis Zhou  * If @async is set, then we will trim 1 region and return.
38742bee7eb8SDennis Zhou  */
trim_bitmaps(struct btrfs_block_group * block_group,u64 * total_trimmed,u64 start,u64 end,u64 minlen,u64 maxlen,bool async)387532da5386SDavid Sterba static int trim_bitmaps(struct btrfs_block_group *block_group,
38762bee7eb8SDennis Zhou 			u64 *total_trimmed, u64 start, u64 end, u64 minlen,
38777fe6d45eSDennis Zhou 			u64 maxlen, bool async)
38787fe1e641SLi Zefan {
387919b2a2c7SDennis Zhou 	struct btrfs_discard_ctl *discard_ctl =
388019b2a2c7SDennis Zhou 					&block_group->fs_info->discard_ctl;
38817fe1e641SLi Zefan 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
38827fe1e641SLi Zefan 	struct btrfs_free_space *entry;
38837fe1e641SLi Zefan 	int ret = 0;
38847fe1e641SLi Zefan 	int ret2;
38857fe1e641SLi Zefan 	u64 bytes;
38867fe1e641SLi Zefan 	u64 offset = offset_to_bitmap(ctl, start);
388719b2a2c7SDennis Zhou 	const u64 max_discard_size = READ_ONCE(discard_ctl->max_discard_size);
38887fe1e641SLi Zefan 
38897fe1e641SLi Zefan 	while (offset < end) {
38907fe1e641SLi Zefan 		bool next_bitmap = false;
389155507ce3SFilipe Manana 		struct btrfs_trim_range trim_entry;
38927fe1e641SLi Zefan 
389355507ce3SFilipe Manana 		mutex_lock(&ctl->cache_writeout_mutex);
38947fe1e641SLi Zefan 		spin_lock(&ctl->tree_lock);
38957fe1e641SLi Zefan 
38967fe1e641SLi Zefan 		if (ctl->free_space < minlen) {
38972bee7eb8SDennis Zhou 			block_group->discard_cursor =
38982bee7eb8SDennis Zhou 				btrfs_block_group_end(block_group);
38997fe1e641SLi Zefan 			spin_unlock(&ctl->tree_lock);
390055507ce3SFilipe Manana 			mutex_unlock(&ctl->cache_writeout_mutex);
39017fe1e641SLi Zefan 			break;
39027fe1e641SLi Zefan 		}
39037fe1e641SLi Zefan 
39047fe1e641SLi Zefan 		entry = tree_search_offset(ctl, offset, 1, 0);
39057fe6d45eSDennis Zhou 		/*
39067fe6d45eSDennis Zhou 		 * Bitmaps are marked trimmed lossily now to prevent constant
39077fe6d45eSDennis Zhou 		 * discarding of the same bitmap (the reason why we are bound
39087fe6d45eSDennis Zhou 		 * by the filters).  So, retrim the block group bitmaps when we
39097fe6d45eSDennis Zhou 		 * are preparing to punt to the unused_bgs list.  This uses
39107fe6d45eSDennis Zhou 		 * @minlen to determine if we are in BTRFS_DISCARD_INDEX_UNUSED
39117fe6d45eSDennis Zhou 		 * which is the only discard index which sets minlen to 0.
39127fe6d45eSDennis Zhou 		 */
39137fe6d45eSDennis Zhou 		if (!entry || (async && minlen && start == offset &&
39142bee7eb8SDennis Zhou 			       btrfs_free_space_trimmed(entry))) {
39157fe1e641SLi Zefan 			spin_unlock(&ctl->tree_lock);
391655507ce3SFilipe Manana 			mutex_unlock(&ctl->cache_writeout_mutex);
39177fe1e641SLi Zefan 			next_bitmap = true;
39187fe1e641SLi Zefan 			goto next;
39197fe1e641SLi Zefan 		}
39207fe1e641SLi Zefan 
3921da080fe1SDennis Zhou 		/*
3922da080fe1SDennis Zhou 		 * Async discard bitmap trimming begins at by setting the start
3923da080fe1SDennis Zhou 		 * to be key.objectid and the offset_to_bitmap() aligns to the
3924da080fe1SDennis Zhou 		 * start of the bitmap.  This lets us know we are fully
3925da080fe1SDennis Zhou 		 * scanning the bitmap rather than only some portion of it.
3926da080fe1SDennis Zhou 		 */
3927da080fe1SDennis Zhou 		if (start == offset)
3928da080fe1SDennis Zhou 			entry->trim_state = BTRFS_TRIM_STATE_TRIMMING;
3929da080fe1SDennis Zhou 
39307fe1e641SLi Zefan 		bytes = minlen;
39310584f718SJosef Bacik 		ret2 = search_bitmap(ctl, entry, &start, &bytes, false);
39327fe1e641SLi Zefan 		if (ret2 || start >= end) {
3933da080fe1SDennis Zhou 			/*
39347fe6d45eSDennis Zhou 			 * We lossily consider a bitmap trimmed if we only skip
39357fe6d45eSDennis Zhou 			 * over regions <= BTRFS_ASYNC_DISCARD_MIN_FILTER.
3936da080fe1SDennis Zhou 			 */
39377fe6d45eSDennis Zhou 			if (ret2 && minlen <= BTRFS_ASYNC_DISCARD_MIN_FILTER)
3938dfb79ddbSDennis Zhou 				end_trimming_bitmap(ctl, entry);
3939da080fe1SDennis Zhou 			else
3940da080fe1SDennis Zhou 				entry->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
39417fe1e641SLi Zefan 			spin_unlock(&ctl->tree_lock);
394255507ce3SFilipe Manana 			mutex_unlock(&ctl->cache_writeout_mutex);
39437fe1e641SLi Zefan 			next_bitmap = true;
39447fe1e641SLi Zefan 			goto next;
39457fe1e641SLi Zefan 		}
39467fe1e641SLi Zefan 
39472bee7eb8SDennis Zhou 		/*
39482bee7eb8SDennis Zhou 		 * We already trimmed a region, but are using the locking above
39492bee7eb8SDennis Zhou 		 * to reset the trim_state.
39502bee7eb8SDennis Zhou 		 */
39512bee7eb8SDennis Zhou 		if (async && *total_trimmed) {
39522bee7eb8SDennis Zhou 			spin_unlock(&ctl->tree_lock);
39532bee7eb8SDennis Zhou 			mutex_unlock(&ctl->cache_writeout_mutex);
39542bee7eb8SDennis Zhou 			goto out;
39552bee7eb8SDennis Zhou 		}
39562bee7eb8SDennis Zhou 
39577fe1e641SLi Zefan 		bytes = min(bytes, end - start);
39587fe6d45eSDennis Zhou 		if (bytes < minlen || (async && maxlen && bytes > maxlen)) {
39597fe1e641SLi Zefan 			spin_unlock(&ctl->tree_lock);
396055507ce3SFilipe Manana 			mutex_unlock(&ctl->cache_writeout_mutex);
39617fe1e641SLi Zefan 			goto next;
39627fe1e641SLi Zefan 		}
39637fe1e641SLi Zefan 
39647fe6d45eSDennis Zhou 		/*
39657fe6d45eSDennis Zhou 		 * Let bytes = BTRFS_MAX_DISCARD_SIZE + X.
39667fe6d45eSDennis Zhou 		 * If X < @minlen, we won't trim X when we come back around.
39677fe6d45eSDennis Zhou 		 * So trim it now.  We differ here from trimming extents as we
39687fe6d45eSDennis Zhou 		 * don't keep individual state per bit.
39697fe6d45eSDennis Zhou 		 */
39707fe6d45eSDennis Zhou 		if (async &&
39717fe6d45eSDennis Zhou 		    max_discard_size &&
39727fe6d45eSDennis Zhou 		    bytes > (max_discard_size + minlen))
397319b2a2c7SDennis Zhou 			bytes = max_discard_size;
39744aa9ad52SDennis Zhou 
3975f594f13cSNikolay Borisov 		bitmap_clear_bits(ctl, entry, start, bytes, true);
39767fe1e641SLi Zefan 		if (entry->bytes == 0)
39777fe1e641SLi Zefan 			free_bitmap(ctl, entry);
39787fe1e641SLi Zefan 
39797fe1e641SLi Zefan 		spin_unlock(&ctl->tree_lock);
398055507ce3SFilipe Manana 		trim_entry.start = start;
398155507ce3SFilipe Manana 		trim_entry.bytes = bytes;
398255507ce3SFilipe Manana 		list_add_tail(&trim_entry.list, &ctl->trimming_ranges);
398355507ce3SFilipe Manana 		mutex_unlock(&ctl->cache_writeout_mutex);
39847fe1e641SLi Zefan 
39857fe1e641SLi Zefan 		ret = do_trimming(block_group, total_trimmed, start, bytes,
3986b0643e59SDennis Zhou 				  start, bytes, 0, &trim_entry);
3987da080fe1SDennis Zhou 		if (ret) {
3988da080fe1SDennis Zhou 			reset_trimming_bitmap(ctl, offset);
39892bee7eb8SDennis Zhou 			block_group->discard_cursor =
39902bee7eb8SDennis Zhou 				btrfs_block_group_end(block_group);
39917fe1e641SLi Zefan 			break;
3992da080fe1SDennis Zhou 		}
39937fe1e641SLi Zefan next:
39947fe1e641SLi Zefan 		if (next_bitmap) {
39957fe1e641SLi Zefan 			offset += BITS_PER_BITMAP * ctl->unit;
3996da080fe1SDennis Zhou 			start = offset;
39977fe1e641SLi Zefan 		} else {
39987fe1e641SLi Zefan 			start += bytes;
39997fe1e641SLi Zefan 		}
40002bee7eb8SDennis Zhou 		block_group->discard_cursor = start;
40017fe1e641SLi Zefan 
4002*7a670b42SLuca Stefani 		if (btrfs_trim_interrupted()) {
4003da080fe1SDennis Zhou 			if (start != offset)
4004da080fe1SDennis Zhou 				reset_trimming_bitmap(ctl, offset);
40057fe1e641SLi Zefan 			ret = -ERESTARTSYS;
40067fe1e641SLi Zefan 			break;
40077fe1e641SLi Zefan 		}
40087fe1e641SLi Zefan 
40097fe1e641SLi Zefan 		cond_resched();
40107fe1e641SLi Zefan 	}
40117fe1e641SLi Zefan 
40122bee7eb8SDennis Zhou 	if (offset >= end)
40132bee7eb8SDennis Zhou 		block_group->discard_cursor = end;
40142bee7eb8SDennis Zhou 
40152bee7eb8SDennis Zhou out:
40167fe1e641SLi Zefan 	return ret;
40177fe1e641SLi Zefan }
40187fe1e641SLi Zefan 
btrfs_trim_block_group(struct btrfs_block_group * block_group,u64 * trimmed,u64 start,u64 end,u64 minlen)401932da5386SDavid Sterba int btrfs_trim_block_group(struct btrfs_block_group *block_group,
4020e33e17eeSJeff Mahoney 			   u64 *trimmed, u64 start, u64 end, u64 minlen)
4021e33e17eeSJeff Mahoney {
4022da080fe1SDennis Zhou 	struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
4023e33e17eeSJeff Mahoney 	int ret;
4024da080fe1SDennis Zhou 	u64 rem = 0;
4025e33e17eeSJeff Mahoney 
40262eda5708SNaohiro Aota 	ASSERT(!btrfs_is_zoned(block_group->fs_info));
40272eda5708SNaohiro Aota 
4028e33e17eeSJeff Mahoney 	*trimmed = 0;
4029e33e17eeSJeff Mahoney 
4030e33e17eeSJeff Mahoney 	spin_lock(&block_group->lock);
40313349b57fSJosef Bacik 	if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags)) {
4032e33e17eeSJeff Mahoney 		spin_unlock(&block_group->lock);
4033e33e17eeSJeff Mahoney 		return 0;
4034e33e17eeSJeff Mahoney 	}
40356b7304afSFilipe Manana 	btrfs_freeze_block_group(block_group);
4036e33e17eeSJeff Mahoney 	spin_unlock(&block_group->lock);
4037e33e17eeSJeff Mahoney 
40382bee7eb8SDennis Zhou 	ret = trim_no_bitmap(block_group, trimmed, start, end, minlen, false);
4039e33e17eeSJeff Mahoney 	if (ret)
4040e33e17eeSJeff Mahoney 		goto out;
4041e33e17eeSJeff Mahoney 
40427fe6d45eSDennis Zhou 	ret = trim_bitmaps(block_group, trimmed, start, end, minlen, 0, false);
4043da080fe1SDennis Zhou 	div64_u64_rem(end, BITS_PER_BITMAP * ctl->unit, &rem);
4044da080fe1SDennis Zhou 	/* If we ended in the middle of a bitmap, reset the trimming flag */
4045da080fe1SDennis Zhou 	if (rem)
4046da080fe1SDennis Zhou 		reset_trimming_bitmap(ctl, offset_to_bitmap(ctl, end));
4047e33e17eeSJeff Mahoney out:
40486b7304afSFilipe Manana 	btrfs_unfreeze_block_group(block_group);
4049f7039b1dSLi Dongyang 	return ret;
4050f7039b1dSLi Dongyang }
4051581bb050SLi Zefan 
btrfs_trim_block_group_extents(struct btrfs_block_group * block_group,u64 * trimmed,u64 start,u64 end,u64 minlen,bool async)40522bee7eb8SDennis Zhou int btrfs_trim_block_group_extents(struct btrfs_block_group *block_group,
40532bee7eb8SDennis Zhou 				   u64 *trimmed, u64 start, u64 end, u64 minlen,
40542bee7eb8SDennis Zhou 				   bool async)
40552bee7eb8SDennis Zhou {
40562bee7eb8SDennis Zhou 	int ret;
40572bee7eb8SDennis Zhou 
40582bee7eb8SDennis Zhou 	*trimmed = 0;
40592bee7eb8SDennis Zhou 
40602bee7eb8SDennis Zhou 	spin_lock(&block_group->lock);
40613349b57fSJosef Bacik 	if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags)) {
40622bee7eb8SDennis Zhou 		spin_unlock(&block_group->lock);
40632bee7eb8SDennis Zhou 		return 0;
40642bee7eb8SDennis Zhou 	}
40656b7304afSFilipe Manana 	btrfs_freeze_block_group(block_group);
40662bee7eb8SDennis Zhou 	spin_unlock(&block_group->lock);
40672bee7eb8SDennis Zhou 
40682bee7eb8SDennis Zhou 	ret = trim_no_bitmap(block_group, trimmed, start, end, minlen, async);
40696b7304afSFilipe Manana 	btrfs_unfreeze_block_group(block_group);
40702bee7eb8SDennis Zhou 
40712bee7eb8SDennis Zhou 	return ret;
40722bee7eb8SDennis Zhou }
40732bee7eb8SDennis Zhou 
btrfs_trim_block_group_bitmaps(struct btrfs_block_group * block_group,u64 * trimmed,u64 start,u64 end,u64 minlen,u64 maxlen,bool async)40742bee7eb8SDennis Zhou int btrfs_trim_block_group_bitmaps(struct btrfs_block_group *block_group,
40752bee7eb8SDennis Zhou 				   u64 *trimmed, u64 start, u64 end, u64 minlen,
40767fe6d45eSDennis Zhou 				   u64 maxlen, bool async)
40772bee7eb8SDennis Zhou {
40782bee7eb8SDennis Zhou 	int ret;
40792bee7eb8SDennis Zhou 
40802bee7eb8SDennis Zhou 	*trimmed = 0;
40812bee7eb8SDennis Zhou 
40822bee7eb8SDennis Zhou 	spin_lock(&block_group->lock);
40833349b57fSJosef Bacik 	if (test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags)) {
40842bee7eb8SDennis Zhou 		spin_unlock(&block_group->lock);
40852bee7eb8SDennis Zhou 		return 0;
40862bee7eb8SDennis Zhou 	}
40876b7304afSFilipe Manana 	btrfs_freeze_block_group(block_group);
40882bee7eb8SDennis Zhou 	spin_unlock(&block_group->lock);
40892bee7eb8SDennis Zhou 
40907fe6d45eSDennis Zhou 	ret = trim_bitmaps(block_group, trimmed, start, end, minlen, maxlen,
40917fe6d45eSDennis Zhou 			   async);
40927fe6d45eSDennis Zhou 
40936b7304afSFilipe Manana 	btrfs_unfreeze_block_group(block_group);
40942bee7eb8SDennis Zhou 
40952bee7eb8SDennis Zhou 	return ret;
40962bee7eb8SDennis Zhou }
40972bee7eb8SDennis Zhou 
btrfs_free_space_cache_v1_active(struct btrfs_fs_info * fs_info)409894846229SBoris Burkov bool btrfs_free_space_cache_v1_active(struct btrfs_fs_info *fs_info)
409994846229SBoris Burkov {
410094846229SBoris Burkov 	return btrfs_super_cache_generation(fs_info->super_copy);
410194846229SBoris Burkov }
410294846229SBoris Burkov 
cleanup_free_space_cache_v1(struct btrfs_fs_info * fs_info,struct btrfs_trans_handle * trans)410336b216c8SBoris Burkov static int cleanup_free_space_cache_v1(struct btrfs_fs_info *fs_info,
410436b216c8SBoris Burkov 				       struct btrfs_trans_handle *trans)
410536b216c8SBoris Burkov {
410636b216c8SBoris Burkov 	struct btrfs_block_group *block_group;
410736b216c8SBoris Burkov 	struct rb_node *node;
410877364fafSTom Rix 	int ret = 0;
410936b216c8SBoris Burkov 
411036b216c8SBoris Burkov 	btrfs_info(fs_info, "cleaning free space cache v1");
411136b216c8SBoris Burkov 
411208dddb29SFilipe Manana 	node = rb_first_cached(&fs_info->block_group_cache_tree);
411336b216c8SBoris Burkov 	while (node) {
411436b216c8SBoris Burkov 		block_group = rb_entry(node, struct btrfs_block_group, cache_node);
411536b216c8SBoris Burkov 		ret = btrfs_remove_free_space_inode(trans, NULL, block_group);
411636b216c8SBoris Burkov 		if (ret)
411736b216c8SBoris Burkov 			goto out;
411836b216c8SBoris Burkov 		node = rb_next(node);
411936b216c8SBoris Burkov 	}
412036b216c8SBoris Burkov out:
412136b216c8SBoris Burkov 	return ret;
412236b216c8SBoris Burkov }
412336b216c8SBoris Burkov 
btrfs_set_free_space_cache_v1_active(struct btrfs_fs_info * fs_info,bool active)412494846229SBoris Burkov int btrfs_set_free_space_cache_v1_active(struct btrfs_fs_info *fs_info, bool active)
412594846229SBoris Burkov {
412694846229SBoris Burkov 	struct btrfs_trans_handle *trans;
412794846229SBoris Burkov 	int ret;
412894846229SBoris Burkov 
412994846229SBoris Burkov 	/*
413036b216c8SBoris Burkov 	 * update_super_roots will appropriately set or unset
413136b216c8SBoris Burkov 	 * super_copy->cache_generation based on SPACE_CACHE and
413236b216c8SBoris Burkov 	 * BTRFS_FS_CLEANUP_SPACE_CACHE_V1. For this reason, we need a
413336b216c8SBoris Burkov 	 * transaction commit whether we are enabling space cache v1 and don't
413436b216c8SBoris Burkov 	 * have any other work to do, or are disabling it and removing free
413536b216c8SBoris Burkov 	 * space inodes.
413694846229SBoris Burkov 	 */
413794846229SBoris Burkov 	trans = btrfs_start_transaction(fs_info->tree_root, 0);
413894846229SBoris Burkov 	if (IS_ERR(trans))
413994846229SBoris Burkov 		return PTR_ERR(trans);
414094846229SBoris Burkov 
414136b216c8SBoris Burkov 	if (!active) {
414294846229SBoris Burkov 		set_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags);
414336b216c8SBoris Burkov 		ret = cleanup_free_space_cache_v1(fs_info, trans);
414436b216c8SBoris Burkov 		if (ret) {
414536b216c8SBoris Burkov 			btrfs_abort_transaction(trans, ret);
414636b216c8SBoris Burkov 			btrfs_end_transaction(trans);
414736b216c8SBoris Burkov 			goto out;
414836b216c8SBoris Burkov 		}
414936b216c8SBoris Burkov 	}
415094846229SBoris Burkov 
415194846229SBoris Burkov 	ret = btrfs_commit_transaction(trans);
415236b216c8SBoris Burkov out:
415394846229SBoris Burkov 	clear_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags);
415494846229SBoris Burkov 
415594846229SBoris Burkov 	return ret;
415694846229SBoris Burkov }
415794846229SBoris Burkov 
btrfs_free_space_init(void)4158eda517fdSJosef Bacik int __init btrfs_free_space_init(void)
4159eda517fdSJosef Bacik {
4160eda517fdSJosef Bacik 	btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
4161eda517fdSJosef Bacik 			sizeof(struct btrfs_free_space), 0,
4162eda517fdSJosef Bacik 			SLAB_MEM_SPREAD, NULL);
4163eda517fdSJosef Bacik 	if (!btrfs_free_space_cachep)
4164eda517fdSJosef Bacik 		return -ENOMEM;
4165eda517fdSJosef Bacik 
4166eda517fdSJosef Bacik 	btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
4167eda517fdSJosef Bacik 							PAGE_SIZE, PAGE_SIZE,
4168eda517fdSJosef Bacik 							SLAB_MEM_SPREAD, NULL);
4169eda517fdSJosef Bacik 	if (!btrfs_free_space_bitmap_cachep) {
4170eda517fdSJosef Bacik 		kmem_cache_destroy(btrfs_free_space_cachep);
4171eda517fdSJosef Bacik 		return -ENOMEM;
4172eda517fdSJosef Bacik 	}
4173eda517fdSJosef Bacik 
4174eda517fdSJosef Bacik 	return 0;
4175eda517fdSJosef Bacik }
4176eda517fdSJosef Bacik 
btrfs_free_space_exit(void)4177eda517fdSJosef Bacik void __cold btrfs_free_space_exit(void)
4178eda517fdSJosef Bacik {
4179eda517fdSJosef Bacik 	kmem_cache_destroy(btrfs_free_space_cachep);
4180eda517fdSJosef Bacik 	kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
4181eda517fdSJosef Bacik }
4182eda517fdSJosef Bacik 
418374255aa0SJosef Bacik #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
4184dc11dd5dSJosef Bacik /*
4185dc11dd5dSJosef Bacik  * Use this if you need to make a bitmap or extent entry specifically, it
4186dc11dd5dSJosef Bacik  * doesn't do any of the merging that add_free_space does, this acts a lot like
4187dc11dd5dSJosef Bacik  * how the free space cache loading stuff works, so you can get really weird
4188dc11dd5dSJosef Bacik  * configurations.
4189dc11dd5dSJosef Bacik  */
test_add_free_space_entry(struct btrfs_block_group * cache,u64 offset,u64 bytes,bool bitmap)419032da5386SDavid Sterba int test_add_free_space_entry(struct btrfs_block_group *cache,
4191dc11dd5dSJosef Bacik 			      u64 offset, u64 bytes, bool bitmap)
419274255aa0SJosef Bacik {
4193dc11dd5dSJosef Bacik 	struct btrfs_free_space_ctl *ctl = cache->free_space_ctl;
4194dc11dd5dSJosef Bacik 	struct btrfs_free_space *info = NULL, *bitmap_info;
4195dc11dd5dSJosef Bacik 	void *map = NULL;
4196da080fe1SDennis Zhou 	enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_TRIMMED;
4197dc11dd5dSJosef Bacik 	u64 bytes_added;
4198dc11dd5dSJosef Bacik 	int ret;
419974255aa0SJosef Bacik 
4200dc11dd5dSJosef Bacik again:
4201dc11dd5dSJosef Bacik 	if (!info) {
4202dc11dd5dSJosef Bacik 		info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
4203dc11dd5dSJosef Bacik 		if (!info)
4204dc11dd5dSJosef Bacik 			return -ENOMEM;
420574255aa0SJosef Bacik 	}
420674255aa0SJosef Bacik 
4207dc11dd5dSJosef Bacik 	if (!bitmap) {
4208dc11dd5dSJosef Bacik 		spin_lock(&ctl->tree_lock);
4209dc11dd5dSJosef Bacik 		info->offset = offset;
4210dc11dd5dSJosef Bacik 		info->bytes = bytes;
4211cef40483SJosef Bacik 		info->max_extent_size = 0;
4212dc11dd5dSJosef Bacik 		ret = link_free_space(ctl, info);
4213dc11dd5dSJosef Bacik 		spin_unlock(&ctl->tree_lock);
4214dc11dd5dSJosef Bacik 		if (ret)
4215dc11dd5dSJosef Bacik 			kmem_cache_free(btrfs_free_space_cachep, info);
4216dc11dd5dSJosef Bacik 		return ret;
4217dc11dd5dSJosef Bacik 	}
421874255aa0SJosef Bacik 
4219dc11dd5dSJosef Bacik 	if (!map) {
42203acd4850SChristophe Leroy 		map = kmem_cache_zalloc(btrfs_free_space_bitmap_cachep, GFP_NOFS);
4221dc11dd5dSJosef Bacik 		if (!map) {
4222dc11dd5dSJosef Bacik 			kmem_cache_free(btrfs_free_space_cachep, info);
4223dc11dd5dSJosef Bacik 			return -ENOMEM;
4224dc11dd5dSJosef Bacik 		}
4225dc11dd5dSJosef Bacik 	}
422674255aa0SJosef Bacik 
4227dc11dd5dSJosef Bacik 	spin_lock(&ctl->tree_lock);
4228dc11dd5dSJosef Bacik 	bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
4229dc11dd5dSJosef Bacik 					 1, 0);
4230dc11dd5dSJosef Bacik 	if (!bitmap_info) {
4231dc11dd5dSJosef Bacik 		info->bitmap = map;
4232dc11dd5dSJosef Bacik 		map = NULL;
4233dc11dd5dSJosef Bacik 		add_new_bitmap(ctl, info, offset);
4234dc11dd5dSJosef Bacik 		bitmap_info = info;
423520005523SFilipe Manana 		info = NULL;
4236dc11dd5dSJosef Bacik 	}
423774255aa0SJosef Bacik 
4238da080fe1SDennis Zhou 	bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes,
4239da080fe1SDennis Zhou 					  trim_state);
4240cef40483SJosef Bacik 
4241dc11dd5dSJosef Bacik 	bytes -= bytes_added;
4242dc11dd5dSJosef Bacik 	offset += bytes_added;
4243dc11dd5dSJosef Bacik 	spin_unlock(&ctl->tree_lock);
4244dc11dd5dSJosef Bacik 
4245dc11dd5dSJosef Bacik 	if (bytes)
4246dc11dd5dSJosef Bacik 		goto again;
4247dc11dd5dSJosef Bacik 
424820005523SFilipe Manana 	if (info)
424920005523SFilipe Manana 		kmem_cache_free(btrfs_free_space_cachep, info);
42503acd4850SChristophe Leroy 	if (map)
42513acd4850SChristophe Leroy 		kmem_cache_free(btrfs_free_space_bitmap_cachep, map);
4252dc11dd5dSJosef Bacik 	return 0;
425374255aa0SJosef Bacik }
425474255aa0SJosef Bacik 
425574255aa0SJosef Bacik /*
425674255aa0SJosef Bacik  * Checks to see if the given range is in the free space cache.  This is really
425774255aa0SJosef Bacik  * just used to check the absence of space, so if there is free space in the
425874255aa0SJosef Bacik  * range at all we will return 1.
425974255aa0SJosef Bacik  */
test_check_exists(struct btrfs_block_group * cache,u64 offset,u64 bytes)426032da5386SDavid Sterba int test_check_exists(struct btrfs_block_group *cache,
4261dc11dd5dSJosef Bacik 		      u64 offset, u64 bytes)
426274255aa0SJosef Bacik {
426374255aa0SJosef Bacik 	struct btrfs_free_space_ctl *ctl = cache->free_space_ctl;
426474255aa0SJosef Bacik 	struct btrfs_free_space *info;
426574255aa0SJosef Bacik 	int ret = 0;
426674255aa0SJosef Bacik 
426774255aa0SJosef Bacik 	spin_lock(&ctl->tree_lock);
426874255aa0SJosef Bacik 	info = tree_search_offset(ctl, offset, 0, 0);
426974255aa0SJosef Bacik 	if (!info) {
427074255aa0SJosef Bacik 		info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
427174255aa0SJosef Bacik 					  1, 0);
427274255aa0SJosef Bacik 		if (!info)
427374255aa0SJosef Bacik 			goto out;
427474255aa0SJosef Bacik 	}
427574255aa0SJosef Bacik 
427674255aa0SJosef Bacik have_info:
427774255aa0SJosef Bacik 	if (info->bitmap) {
427874255aa0SJosef Bacik 		u64 bit_off, bit_bytes;
427974255aa0SJosef Bacik 		struct rb_node *n;
428074255aa0SJosef Bacik 		struct btrfs_free_space *tmp;
428174255aa0SJosef Bacik 
428274255aa0SJosef Bacik 		bit_off = offset;
428374255aa0SJosef Bacik 		bit_bytes = ctl->unit;
42840584f718SJosef Bacik 		ret = search_bitmap(ctl, info, &bit_off, &bit_bytes, false);
428574255aa0SJosef Bacik 		if (!ret) {
428674255aa0SJosef Bacik 			if (bit_off == offset) {
428774255aa0SJosef Bacik 				ret = 1;
428874255aa0SJosef Bacik 				goto out;
428974255aa0SJosef Bacik 			} else if (bit_off > offset &&
429074255aa0SJosef Bacik 				   offset + bytes > bit_off) {
429174255aa0SJosef Bacik 				ret = 1;
429274255aa0SJosef Bacik 				goto out;
429374255aa0SJosef Bacik 			}
429474255aa0SJosef Bacik 		}
429574255aa0SJosef Bacik 
429674255aa0SJosef Bacik 		n = rb_prev(&info->offset_index);
429774255aa0SJosef Bacik 		while (n) {
429874255aa0SJosef Bacik 			tmp = rb_entry(n, struct btrfs_free_space,
429974255aa0SJosef Bacik 				       offset_index);
430074255aa0SJosef Bacik 			if (tmp->offset + tmp->bytes < offset)
430174255aa0SJosef Bacik 				break;
430274255aa0SJosef Bacik 			if (offset + bytes < tmp->offset) {
43035473e0c4SFeifei Xu 				n = rb_prev(&tmp->offset_index);
430474255aa0SJosef Bacik 				continue;
430574255aa0SJosef Bacik 			}
430674255aa0SJosef Bacik 			info = tmp;
430774255aa0SJosef Bacik 			goto have_info;
430874255aa0SJosef Bacik 		}
430974255aa0SJosef Bacik 
431074255aa0SJosef Bacik 		n = rb_next(&info->offset_index);
431174255aa0SJosef Bacik 		while (n) {
431274255aa0SJosef Bacik 			tmp = rb_entry(n, struct btrfs_free_space,
431374255aa0SJosef Bacik 				       offset_index);
431474255aa0SJosef Bacik 			if (offset + bytes < tmp->offset)
431574255aa0SJosef Bacik 				break;
431674255aa0SJosef Bacik 			if (tmp->offset + tmp->bytes < offset) {
43175473e0c4SFeifei Xu 				n = rb_next(&tmp->offset_index);
431874255aa0SJosef Bacik 				continue;
431974255aa0SJosef Bacik 			}
432074255aa0SJosef Bacik 			info = tmp;
432174255aa0SJosef Bacik 			goto have_info;
432274255aa0SJosef Bacik 		}
432374255aa0SJosef Bacik 
432420005523SFilipe Manana 		ret = 0;
432574255aa0SJosef Bacik 		goto out;
432674255aa0SJosef Bacik 	}
432774255aa0SJosef Bacik 
432874255aa0SJosef Bacik 	if (info->offset == offset) {
432974255aa0SJosef Bacik 		ret = 1;
433074255aa0SJosef Bacik 		goto out;
433174255aa0SJosef Bacik 	}
433274255aa0SJosef Bacik 
433374255aa0SJosef Bacik 	if (offset > info->offset && offset < info->offset + info->bytes)
433474255aa0SJosef Bacik 		ret = 1;
433574255aa0SJosef Bacik out:
433674255aa0SJosef Bacik 	spin_unlock(&ctl->tree_lock);
433774255aa0SJosef Bacik 	return ret;
433874255aa0SJosef Bacik }
4339dc11dd5dSJosef Bacik #endif /* CONFIG_BTRFS_FS_RUN_SANITY_TESTS */
4340