]> git.proxmox.com Git - mirror_ubuntu-hirsute-kernel.git/blame - fs/btrfs/free-space-cache.c
Merge tag 'timers_urgent_for_v5.11_rc5' of git://git.kernel.org/pub/scm/linux/kernel...
[mirror_ubuntu-hirsute-kernel.git] / fs / btrfs / free-space-cache.c
CommitLineData
c1d7c514 1// SPDX-License-Identifier: GPL-2.0
0f9dd46c
JB
2/*
3 * Copyright (C) 2008 Red Hat. All rights reserved.
0f9dd46c
JB
4 */
5
96303081 6#include <linux/pagemap.h>
0f9dd46c 7#include <linux/sched.h>
f361bf4a 8#include <linux/sched/signal.h>
5a0e3ad6 9#include <linux/slab.h>
96303081 10#include <linux/math64.h>
6ab60601 11#include <linux/ratelimit.h>
540adea3 12#include <linux/error-injection.h>
84de76a2 13#include <linux/sched/mm.h>
0f9dd46c 14#include "ctree.h"
fa9c0d79
CM
15#include "free-space-cache.h"
16#include "transaction.h"
0af3d00b 17#include "disk-io.h"
43be2146 18#include "extent_io.h"
04216820 19#include "volumes.h"
8719aaae 20#include "space-info.h"
86736342 21#include "delalloc-space.h"
aac0023c 22#include "block-group.h"
b0643e59 23#include "discard.h"
fa9c0d79 24
0ef6447a 25#define BITS_PER_BITMAP (PAGE_SIZE * 8UL)
5d90c5c7
DZ
26#define MAX_CACHE_BYTES_PER_GIG SZ_64K
27#define FORCE_EXTENT_THRESHOLD SZ_1M
0f9dd46c 28
55507ce3
FM
29struct btrfs_trim_range {
30 u64 start;
31 u64 bytes;
32 struct list_head list;
33};
34
34d52cb6 35static int link_free_space(struct btrfs_free_space_ctl *ctl,
0cb59c99 36 struct btrfs_free_space *info);
cd023e7b
JB
37static void unlink_free_space(struct btrfs_free_space_ctl *ctl,
38 struct btrfs_free_space *info);
cd79909b
JB
39static int search_bitmap(struct btrfs_free_space_ctl *ctl,
40 struct btrfs_free_space *bitmap_info, u64 *offset,
41 u64 *bytes, bool for_alloc);
42static void free_bitmap(struct btrfs_free_space_ctl *ctl,
43 struct btrfs_free_space *bitmap_info);
44static void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
45 struct btrfs_free_space *info, u64 offset,
46 u64 bytes);
0cb59c99 47
0414efae
LZ
48static struct inode *__lookup_free_space_inode(struct btrfs_root *root,
49 struct btrfs_path *path,
50 u64 offset)
0af3d00b 51{
0b246afa 52 struct btrfs_fs_info *fs_info = root->fs_info;
0af3d00b
JB
53 struct btrfs_key key;
54 struct btrfs_key location;
55 struct btrfs_disk_key disk_key;
56 struct btrfs_free_space_header *header;
57 struct extent_buffer *leaf;
58 struct inode *inode = NULL;
84de76a2 59 unsigned nofs_flag;
0af3d00b
JB
60 int ret;
61
0af3d00b 62 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
0414efae 63 key.offset = offset;
0af3d00b
JB
64 key.type = 0;
65
66 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
67 if (ret < 0)
68 return ERR_PTR(ret);
69 if (ret > 0) {
b3b4aa74 70 btrfs_release_path(path);
0af3d00b
JB
71 return ERR_PTR(-ENOENT);
72 }
73
74 leaf = path->nodes[0];
75 header = btrfs_item_ptr(leaf, path->slots[0],
76 struct btrfs_free_space_header);
77 btrfs_free_space_key(leaf, header, &disk_key);
78 btrfs_disk_key_to_cpu(&location, &disk_key);
b3b4aa74 79 btrfs_release_path(path);
0af3d00b 80
84de76a2
JB
81 /*
82 * We are often under a trans handle at this point, so we need to make
83 * sure NOFS is set to keep us from deadlocking.
84 */
85 nofs_flag = memalloc_nofs_save();
0202e83f 86 inode = btrfs_iget_path(fs_info->sb, location.objectid, root, path);
4222ea71 87 btrfs_release_path(path);
84de76a2 88 memalloc_nofs_restore(nofs_flag);
0af3d00b
JB
89 if (IS_ERR(inode))
90 return inode;
0af3d00b 91
528c0327 92 mapping_set_gfp_mask(inode->i_mapping,
c62d2555
MH
93 mapping_gfp_constraint(inode->i_mapping,
94 ~(__GFP_FS | __GFP_HIGHMEM)));
adae52b9 95
0414efae
LZ
96 return inode;
97}
98
32da5386 99struct inode *lookup_free_space_inode(struct btrfs_block_group *block_group,
7949f339 100 struct btrfs_path *path)
0414efae 101{
7949f339 102 struct btrfs_fs_info *fs_info = block_group->fs_info;
0414efae 103 struct inode *inode = NULL;
5b0e95bf 104 u32 flags = BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW;
0414efae
LZ
105
106 spin_lock(&block_group->lock);
107 if (block_group->inode)
108 inode = igrab(block_group->inode);
109 spin_unlock(&block_group->lock);
110 if (inode)
111 return inode;
112
77ab86bf 113 inode = __lookup_free_space_inode(fs_info->tree_root, path,
b3470b5d 114 block_group->start);
0414efae
LZ
115 if (IS_ERR(inode))
116 return inode;
117
0af3d00b 118 spin_lock(&block_group->lock);
5b0e95bf 119 if (!((BTRFS_I(inode)->flags & flags) == flags)) {
0b246afa 120 btrfs_info(fs_info, "Old style space inode found, converting.");
5b0e95bf
JB
121 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM |
122 BTRFS_INODE_NODATACOW;
2f356126
JB
123 block_group->disk_cache_state = BTRFS_DC_CLEAR;
124 }
125
300e4f8a 126 if (!block_group->iref) {
0af3d00b
JB
127 block_group->inode = igrab(inode);
128 block_group->iref = 1;
129 }
130 spin_unlock(&block_group->lock);
131
132 return inode;
133}
134
48a3b636
ES
135static int __create_free_space_inode(struct btrfs_root *root,
136 struct btrfs_trans_handle *trans,
137 struct btrfs_path *path,
138 u64 ino, u64 offset)
0af3d00b
JB
139{
140 struct btrfs_key key;
141 struct btrfs_disk_key disk_key;
142 struct btrfs_free_space_header *header;
143 struct btrfs_inode_item *inode_item;
144 struct extent_buffer *leaf;
f0d1219d
NB
145 /* We inline CRCs for the free disk space cache */
146 const u64 flags = BTRFS_INODE_NOCOMPRESS | BTRFS_INODE_PREALLOC |
147 BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW;
0af3d00b
JB
148 int ret;
149
0414efae 150 ret = btrfs_insert_empty_inode(trans, root, path, ino);
0af3d00b
JB
151 if (ret)
152 return ret;
153
154 leaf = path->nodes[0];
155 inode_item = btrfs_item_ptr(leaf, path->slots[0],
156 struct btrfs_inode_item);
157 btrfs_item_key(leaf, &disk_key, path->slots[0]);
b159fa28 158 memzero_extent_buffer(leaf, (unsigned long)inode_item,
0af3d00b
JB
159 sizeof(*inode_item));
160 btrfs_set_inode_generation(leaf, inode_item, trans->transid);
161 btrfs_set_inode_size(leaf, inode_item, 0);
162 btrfs_set_inode_nbytes(leaf, inode_item, 0);
163 btrfs_set_inode_uid(leaf, inode_item, 0);
164 btrfs_set_inode_gid(leaf, inode_item, 0);
165 btrfs_set_inode_mode(leaf, inode_item, S_IFREG | 0600);
5b0e95bf 166 btrfs_set_inode_flags(leaf, inode_item, flags);
0af3d00b
JB
167 btrfs_set_inode_nlink(leaf, inode_item, 1);
168 btrfs_set_inode_transid(leaf, inode_item, trans->transid);
0414efae 169 btrfs_set_inode_block_group(leaf, inode_item, offset);
0af3d00b 170 btrfs_mark_buffer_dirty(leaf);
b3b4aa74 171 btrfs_release_path(path);
0af3d00b
JB
172
173 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
0414efae 174 key.offset = offset;
0af3d00b 175 key.type = 0;
0af3d00b
JB
176 ret = btrfs_insert_empty_item(trans, root, path, &key,
177 sizeof(struct btrfs_free_space_header));
178 if (ret < 0) {
b3b4aa74 179 btrfs_release_path(path);
0af3d00b
JB
180 return ret;
181 }
c9dc4c65 182
0af3d00b
JB
183 leaf = path->nodes[0];
184 header = btrfs_item_ptr(leaf, path->slots[0],
185 struct btrfs_free_space_header);
b159fa28 186 memzero_extent_buffer(leaf, (unsigned long)header, sizeof(*header));
0af3d00b
JB
187 btrfs_set_free_space_key(leaf, header, &disk_key);
188 btrfs_mark_buffer_dirty(leaf);
b3b4aa74 189 btrfs_release_path(path);
0af3d00b
JB
190
191 return 0;
192}
193
4ca75f1b 194int create_free_space_inode(struct btrfs_trans_handle *trans,
32da5386 195 struct btrfs_block_group *block_group,
0414efae
LZ
196 struct btrfs_path *path)
197{
198 int ret;
199 u64 ino;
200
4ca75f1b 201 ret = btrfs_find_free_objectid(trans->fs_info->tree_root, &ino);
0414efae
LZ
202 if (ret < 0)
203 return ret;
204
4ca75f1b 205 return __create_free_space_inode(trans->fs_info->tree_root, trans, path,
b3470b5d 206 ino, block_group->start);
0414efae
LZ
207}
208
36b216c8
BB
209/*
210 * inode is an optional sink: if it is NULL, btrfs_remove_free_space_inode
211 * handles lookup, otherwise it takes ownership and iputs the inode.
212 * Don't reuse an inode pointer after passing it into this function.
213 */
214int btrfs_remove_free_space_inode(struct btrfs_trans_handle *trans,
215 struct inode *inode,
216 struct btrfs_block_group *block_group)
217{
218 struct btrfs_path *path;
219 struct btrfs_key key;
220 int ret = 0;
221
222 path = btrfs_alloc_path();
223 if (!path)
224 return -ENOMEM;
225
226 if (!inode)
227 inode = lookup_free_space_inode(block_group, path);
228 if (IS_ERR(inode)) {
229 if (PTR_ERR(inode) != -ENOENT)
230 ret = PTR_ERR(inode);
231 goto out;
232 }
233 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
234 if (ret) {
235 btrfs_add_delayed_iput(inode);
236 goto out;
237 }
238 clear_nlink(inode);
239 /* One for the block groups ref */
240 spin_lock(&block_group->lock);
241 if (block_group->iref) {
242 block_group->iref = 0;
243 block_group->inode = NULL;
244 spin_unlock(&block_group->lock);
245 iput(inode);
246 } else {
247 spin_unlock(&block_group->lock);
248 }
249 /* One for the lookup ref */
250 btrfs_add_delayed_iput(inode);
251
252 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
253 key.type = 0;
254 key.offset = block_group->start;
255 ret = btrfs_search_slot(trans, trans->fs_info->tree_root, &key, path,
256 -1, 1);
257 if (ret) {
258 if (ret > 0)
259 ret = 0;
260 goto out;
261 }
262 ret = btrfs_del_item(trans, trans->fs_info->tree_root, path);
263out:
264 btrfs_free_path(path);
265 return ret;
266}
267
2ff7e61e 268int btrfs_check_trunc_cache_free_space(struct btrfs_fs_info *fs_info,
7b61cd92 269 struct btrfs_block_rsv *rsv)
0af3d00b 270{
c8174313 271 u64 needed_bytes;
7b61cd92 272 int ret;
c8174313
JB
273
274 /* 1 for slack space, 1 for updating the inode */
2bd36e7b
JB
275 needed_bytes = btrfs_calc_insert_metadata_size(fs_info, 1) +
276 btrfs_calc_metadata_size(fs_info, 1);
c8174313 277
7b61cd92
MX
278 spin_lock(&rsv->lock);
279 if (rsv->reserved < needed_bytes)
280 ret = -ENOSPC;
281 else
282 ret = 0;
283 spin_unlock(&rsv->lock);
4b286cd1 284 return ret;
7b61cd92
MX
285}
286
77ab86bf 287int btrfs_truncate_free_space_cache(struct btrfs_trans_handle *trans,
32da5386 288 struct btrfs_block_group *block_group,
7b61cd92
MX
289 struct inode *inode)
290{
77ab86bf 291 struct btrfs_root *root = BTRFS_I(inode)->root;
7b61cd92 292 int ret = 0;
35c76642 293 bool locked = false;
1bbc621e 294
1bbc621e 295 if (block_group) {
21e75ffe
JM
296 struct btrfs_path *path = btrfs_alloc_path();
297
298 if (!path) {
299 ret = -ENOMEM;
300 goto fail;
301 }
35c76642 302 locked = true;
1bbc621e
CM
303 mutex_lock(&trans->transaction->cache_write_mutex);
304 if (!list_empty(&block_group->io_list)) {
305 list_del_init(&block_group->io_list);
306
afdb5718 307 btrfs_wait_cache_io(trans, block_group, path);
1bbc621e
CM
308 btrfs_put_block_group(block_group);
309 }
310
311 /*
312 * now that we've truncated the cache away, its no longer
313 * setup or written
314 */
315 spin_lock(&block_group->lock);
316 block_group->disk_cache_state = BTRFS_DC_CLEAR;
317 spin_unlock(&block_group->lock);
21e75ffe 318 btrfs_free_path(path);
1bbc621e 319 }
0af3d00b 320
6ef06d27 321 btrfs_i_size_write(BTRFS_I(inode), 0);
7caef267 322 truncate_pagecache(inode, 0);
0af3d00b
JB
323
324 /*
f7e9e8fc
OS
325 * We skip the throttling logic for free space cache inodes, so we don't
326 * need to check for -EAGAIN.
0af3d00b 327 */
50743398 328 ret = btrfs_truncate_inode_items(trans, root, BTRFS_I(inode),
0af3d00b 329 0, BTRFS_EXTENT_DATA_KEY);
35c76642
FM
330 if (ret)
331 goto fail;
0af3d00b 332
9a56fcd1 333 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
1bbc621e 334
1bbc621e 335fail:
35c76642
FM
336 if (locked)
337 mutex_unlock(&trans->transaction->cache_write_mutex);
79787eaa 338 if (ret)
66642832 339 btrfs_abort_transaction(trans, ret);
c8174313 340
82d5902d 341 return ret;
0af3d00b
JB
342}
343
1d480538 344static void readahead_cache(struct inode *inode)
9d66e233
JB
345{
346 struct file_ra_state *ra;
347 unsigned long last_index;
348
349 ra = kzalloc(sizeof(*ra), GFP_NOFS);
350 if (!ra)
1d480538 351 return;
9d66e233
JB
352
353 file_ra_state_init(ra, inode->i_mapping);
09cbfeaf 354 last_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
9d66e233
JB
355
356 page_cache_sync_readahead(inode->i_mapping, ra, NULL, 0, last_index);
357
358 kfree(ra);
9d66e233
JB
359}
360
4c6d1d85 361static int io_ctl_init(struct btrfs_io_ctl *io_ctl, struct inode *inode,
f15376df 362 int write)
a67509c3 363{
5349d6c3 364 int num_pages;
5349d6c3 365
09cbfeaf 366 num_pages = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
5349d6c3 367
8f6c72a9 368 /* Make sure we can fit our crcs and generation into the first page */
7dbdb443 369 if (write && (num_pages * sizeof(u32) + sizeof(u64)) > PAGE_SIZE)
5349d6c3
MX
370 return -ENOSPC;
371
4c6d1d85 372 memset(io_ctl, 0, sizeof(struct btrfs_io_ctl));
5349d6c3 373
31e818fe 374 io_ctl->pages = kcalloc(num_pages, sizeof(struct page *), GFP_NOFS);
a67509c3
JB
375 if (!io_ctl->pages)
376 return -ENOMEM;
5349d6c3
MX
377
378 io_ctl->num_pages = num_pages;
f15376df 379 io_ctl->fs_info = btrfs_sb(inode->i_sb);
c9dc4c65 380 io_ctl->inode = inode;
5349d6c3 381
a67509c3
JB
382 return 0;
383}
663faf9f 384ALLOW_ERROR_INJECTION(io_ctl_init, ERRNO);
a67509c3 385
4c6d1d85 386static void io_ctl_free(struct btrfs_io_ctl *io_ctl)
a67509c3
JB
387{
388 kfree(io_ctl->pages);
c9dc4c65 389 io_ctl->pages = NULL;
a67509c3
JB
390}
391
4c6d1d85 392static void io_ctl_unmap_page(struct btrfs_io_ctl *io_ctl)
a67509c3
JB
393{
394 if (io_ctl->cur) {
a67509c3
JB
395 io_ctl->cur = NULL;
396 io_ctl->orig = NULL;
397 }
398}
399
4c6d1d85 400static void io_ctl_map_page(struct btrfs_io_ctl *io_ctl, int clear)
a67509c3 401{
b12d6869 402 ASSERT(io_ctl->index < io_ctl->num_pages);
a67509c3 403 io_ctl->page = io_ctl->pages[io_ctl->index++];
2b108268 404 io_ctl->cur = page_address(io_ctl->page);
a67509c3 405 io_ctl->orig = io_ctl->cur;
09cbfeaf 406 io_ctl->size = PAGE_SIZE;
a67509c3 407 if (clear)
619a9742 408 clear_page(io_ctl->cur);
a67509c3
JB
409}
410
4c6d1d85 411static void io_ctl_drop_pages(struct btrfs_io_ctl *io_ctl)
a67509c3
JB
412{
413 int i;
414
415 io_ctl_unmap_page(io_ctl);
416
417 for (i = 0; i < io_ctl->num_pages; i++) {
a1ee5a45
LZ
418 if (io_ctl->pages[i]) {
419 ClearPageChecked(io_ctl->pages[i]);
420 unlock_page(io_ctl->pages[i]);
09cbfeaf 421 put_page(io_ctl->pages[i]);
a1ee5a45 422 }
a67509c3
JB
423 }
424}
425
7a195f6d 426static int io_ctl_prepare_pages(struct btrfs_io_ctl *io_ctl, bool uptodate)
a67509c3
JB
427{
428 struct page *page;
831fa14f 429 struct inode *inode = io_ctl->inode;
a67509c3
JB
430 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
431 int i;
432
433 for (i = 0; i < io_ctl->num_pages; i++) {
434 page = find_or_create_page(inode->i_mapping, i, mask);
435 if (!page) {
436 io_ctl_drop_pages(io_ctl);
437 return -ENOMEM;
438 }
439 io_ctl->pages[i] = page;
440 if (uptodate && !PageUptodate(page)) {
441 btrfs_readpage(NULL, page);
442 lock_page(page);
3797136b
JB
443 if (page->mapping != inode->i_mapping) {
444 btrfs_err(BTRFS_I(inode)->root->fs_info,
445 "free space cache page truncated");
446 io_ctl_drop_pages(io_ctl);
447 return -EIO;
448 }
a67509c3 449 if (!PageUptodate(page)) {
efe120a0
FH
450 btrfs_err(BTRFS_I(inode)->root->fs_info,
451 "error reading free space cache");
a67509c3
JB
452 io_ctl_drop_pages(io_ctl);
453 return -EIO;
454 }
455 }
456 }
457
f7d61dcd
JB
458 for (i = 0; i < io_ctl->num_pages; i++) {
459 clear_page_dirty_for_io(io_ctl->pages[i]);
460 set_page_extent_mapped(io_ctl->pages[i]);
461 }
462
a67509c3
JB
463 return 0;
464}
465
4c6d1d85 466static void io_ctl_set_generation(struct btrfs_io_ctl *io_ctl, u64 generation)
a67509c3 467{
a67509c3
JB
468 io_ctl_map_page(io_ctl, 1);
469
470 /*
5b0e95bf
JB
471 * Skip the csum areas. If we don't check crcs then we just have a
472 * 64bit chunk at the front of the first page.
a67509c3 473 */
7dbdb443
NB
474 io_ctl->cur += (sizeof(u32) * io_ctl->num_pages);
475 io_ctl->size -= sizeof(u64) + (sizeof(u32) * io_ctl->num_pages);
a67509c3 476
6994ca36 477 put_unaligned_le64(generation, io_ctl->cur);
a67509c3 478 io_ctl->cur += sizeof(u64);
a67509c3
JB
479}
480
4c6d1d85 481static int io_ctl_check_generation(struct btrfs_io_ctl *io_ctl, u64 generation)
a67509c3 482{
6994ca36 483 u64 cache_gen;
a67509c3 484
5b0e95bf
JB
485 /*
486 * Skip the crc area. If we don't check crcs then we just have a 64bit
487 * chunk at the front of the first page.
488 */
7dbdb443
NB
489 io_ctl->cur += sizeof(u32) * io_ctl->num_pages;
490 io_ctl->size -= sizeof(u64) + (sizeof(u32) * io_ctl->num_pages);
a67509c3 491
6994ca36
DS
492 cache_gen = get_unaligned_le64(io_ctl->cur);
493 if (cache_gen != generation) {
f15376df 494 btrfs_err_rl(io_ctl->fs_info,
94647322 495 "space cache generation (%llu) does not match inode (%llu)",
6994ca36 496 cache_gen, generation);
a67509c3
JB
497 io_ctl_unmap_page(io_ctl);
498 return -EIO;
499 }
500 io_ctl->cur += sizeof(u64);
5b0e95bf
JB
501 return 0;
502}
503
4c6d1d85 504static void io_ctl_set_crc(struct btrfs_io_ctl *io_ctl, int index)
5b0e95bf
JB
505{
506 u32 *tmp;
507 u32 crc = ~(u32)0;
508 unsigned offset = 0;
509
5b0e95bf 510 if (index == 0)
cb54f257 511 offset = sizeof(u32) * io_ctl->num_pages;
5b0e95bf 512
4bb3c2e2
JT
513 crc = btrfs_crc32c(crc, io_ctl->orig + offset, PAGE_SIZE - offset);
514 btrfs_crc32c_final(crc, (u8 *)&crc);
5b0e95bf 515 io_ctl_unmap_page(io_ctl);
2b108268 516 tmp = page_address(io_ctl->pages[0]);
5b0e95bf
JB
517 tmp += index;
518 *tmp = crc;
5b0e95bf
JB
519}
520
4c6d1d85 521static int io_ctl_check_crc(struct btrfs_io_ctl *io_ctl, int index)
5b0e95bf
JB
522{
523 u32 *tmp, val;
524 u32 crc = ~(u32)0;
525 unsigned offset = 0;
526
5b0e95bf
JB
527 if (index == 0)
528 offset = sizeof(u32) * io_ctl->num_pages;
529
2b108268 530 tmp = page_address(io_ctl->pages[0]);
5b0e95bf
JB
531 tmp += index;
532 val = *tmp;
5b0e95bf
JB
533
534 io_ctl_map_page(io_ctl, 0);
4bb3c2e2
JT
535 crc = btrfs_crc32c(crc, io_ctl->orig + offset, PAGE_SIZE - offset);
536 btrfs_crc32c_final(crc, (u8 *)&crc);
5b0e95bf 537 if (val != crc) {
f15376df 538 btrfs_err_rl(io_ctl->fs_info,
94647322 539 "csum mismatch on free space cache");
5b0e95bf
JB
540 io_ctl_unmap_page(io_ctl);
541 return -EIO;
542 }
543
a67509c3
JB
544 return 0;
545}
546
4c6d1d85 547static int io_ctl_add_entry(struct btrfs_io_ctl *io_ctl, u64 offset, u64 bytes,
a67509c3
JB
548 void *bitmap)
549{
550 struct btrfs_free_space_entry *entry;
551
552 if (!io_ctl->cur)
553 return -ENOSPC;
554
555 entry = io_ctl->cur;
6994ca36
DS
556 put_unaligned_le64(offset, &entry->offset);
557 put_unaligned_le64(bytes, &entry->bytes);
a67509c3
JB
558 entry->type = (bitmap) ? BTRFS_FREE_SPACE_BITMAP :
559 BTRFS_FREE_SPACE_EXTENT;
560 io_ctl->cur += sizeof(struct btrfs_free_space_entry);
561 io_ctl->size -= sizeof(struct btrfs_free_space_entry);
562
563 if (io_ctl->size >= sizeof(struct btrfs_free_space_entry))
564 return 0;
565
5b0e95bf 566 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
a67509c3
JB
567
568 /* No more pages to map */
569 if (io_ctl->index >= io_ctl->num_pages)
570 return 0;
571
572 /* map the next page */
573 io_ctl_map_page(io_ctl, 1);
574 return 0;
575}
576
4c6d1d85 577static int io_ctl_add_bitmap(struct btrfs_io_ctl *io_ctl, void *bitmap)
a67509c3
JB
578{
579 if (!io_ctl->cur)
580 return -ENOSPC;
581
582 /*
583 * If we aren't at the start of the current page, unmap this one and
584 * map the next one if there is any left.
585 */
586 if (io_ctl->cur != io_ctl->orig) {
5b0e95bf 587 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
a67509c3
JB
588 if (io_ctl->index >= io_ctl->num_pages)
589 return -ENOSPC;
590 io_ctl_map_page(io_ctl, 0);
591 }
592
69d24804 593 copy_page(io_ctl->cur, bitmap);
5b0e95bf 594 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
a67509c3
JB
595 if (io_ctl->index < io_ctl->num_pages)
596 io_ctl_map_page(io_ctl, 0);
597 return 0;
598}
599
4c6d1d85 600static void io_ctl_zero_remaining_pages(struct btrfs_io_ctl *io_ctl)
a67509c3 601{
5b0e95bf
JB
602 /*
603 * If we're not on the boundary we know we've modified the page and we
604 * need to crc the page.
605 */
606 if (io_ctl->cur != io_ctl->orig)
607 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
608 else
609 io_ctl_unmap_page(io_ctl);
a67509c3
JB
610
611 while (io_ctl->index < io_ctl->num_pages) {
612 io_ctl_map_page(io_ctl, 1);
5b0e95bf 613 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
a67509c3
JB
614 }
615}
616
4c6d1d85 617static int io_ctl_read_entry(struct btrfs_io_ctl *io_ctl,
5b0e95bf 618 struct btrfs_free_space *entry, u8 *type)
a67509c3
JB
619{
620 struct btrfs_free_space_entry *e;
2f120c05
JB
621 int ret;
622
623 if (!io_ctl->cur) {
624 ret = io_ctl_check_crc(io_ctl, io_ctl->index);
625 if (ret)
626 return ret;
627 }
a67509c3
JB
628
629 e = io_ctl->cur;
6994ca36
DS
630 entry->offset = get_unaligned_le64(&e->offset);
631 entry->bytes = get_unaligned_le64(&e->bytes);
5b0e95bf 632 *type = e->type;
a67509c3
JB
633 io_ctl->cur += sizeof(struct btrfs_free_space_entry);
634 io_ctl->size -= sizeof(struct btrfs_free_space_entry);
635
636 if (io_ctl->size >= sizeof(struct btrfs_free_space_entry))
5b0e95bf 637 return 0;
a67509c3
JB
638
639 io_ctl_unmap_page(io_ctl);
640
2f120c05 641 return 0;
a67509c3
JB
642}
643
4c6d1d85 644static int io_ctl_read_bitmap(struct btrfs_io_ctl *io_ctl,
5b0e95bf 645 struct btrfs_free_space *entry)
a67509c3 646{
5b0e95bf
JB
647 int ret;
648
5b0e95bf
JB
649 ret = io_ctl_check_crc(io_ctl, io_ctl->index);
650 if (ret)
651 return ret;
652
69d24804 653 copy_page(entry->bitmap, io_ctl->cur);
a67509c3 654 io_ctl_unmap_page(io_ctl);
5b0e95bf
JB
655
656 return 0;
a67509c3
JB
657}
658
fa598b06
DS
659static void recalculate_thresholds(struct btrfs_free_space_ctl *ctl)
660{
661 struct btrfs_block_group *block_group = ctl->private;
662 u64 max_bytes;
663 u64 bitmap_bytes;
664 u64 extent_bytes;
665 u64 size = block_group->length;
666 u64 bytes_per_bg = BITS_PER_BITMAP * ctl->unit;
667 u64 max_bitmaps = div64_u64(size + bytes_per_bg - 1, bytes_per_bg);
668
669 max_bitmaps = max_t(u64, max_bitmaps, 1);
670
671 ASSERT(ctl->total_bitmaps <= max_bitmaps);
672
673 /*
674 * We are trying to keep the total amount of memory used per 1GiB of
675 * space to be MAX_CACHE_BYTES_PER_GIG. However, with a reclamation
676 * mechanism of pulling extents >= FORCE_EXTENT_THRESHOLD out of
677 * bitmaps, we may end up using more memory than this.
678 */
679 if (size < SZ_1G)
680 max_bytes = MAX_CACHE_BYTES_PER_GIG;
681 else
682 max_bytes = MAX_CACHE_BYTES_PER_GIG * div_u64(size, SZ_1G);
683
684 bitmap_bytes = ctl->total_bitmaps * ctl->unit;
685
686 /*
687 * we want the extent entry threshold to always be at most 1/2 the max
688 * bytes we can have, or whatever is less than that.
689 */
690 extent_bytes = max_bytes - bitmap_bytes;
691 extent_bytes = min_t(u64, extent_bytes, max_bytes >> 1);
692
693 ctl->extents_thresh =
694 div_u64(extent_bytes, sizeof(struct btrfs_free_space));
695}
696
48a3b636
ES
697static int __load_free_space_cache(struct btrfs_root *root, struct inode *inode,
698 struct btrfs_free_space_ctl *ctl,
699 struct btrfs_path *path, u64 offset)
9d66e233 700{
3ffbd68c 701 struct btrfs_fs_info *fs_info = root->fs_info;
9d66e233
JB
702 struct btrfs_free_space_header *header;
703 struct extent_buffer *leaf;
4c6d1d85 704 struct btrfs_io_ctl io_ctl;
9d66e233 705 struct btrfs_key key;
a67509c3 706 struct btrfs_free_space *e, *n;
b76808fc 707 LIST_HEAD(bitmaps);
9d66e233
JB
708 u64 num_entries;
709 u64 num_bitmaps;
710 u64 generation;
a67509c3 711 u8 type;
f6a39829 712 int ret = 0;
9d66e233 713
9d66e233 714 /* Nothing in the space cache, goodbye */
0414efae 715 if (!i_size_read(inode))
a67509c3 716 return 0;
9d66e233
JB
717
718 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
0414efae 719 key.offset = offset;
9d66e233
JB
720 key.type = 0;
721
722 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
0414efae 723 if (ret < 0)
a67509c3 724 return 0;
0414efae 725 else if (ret > 0) {
945d8962 726 btrfs_release_path(path);
a67509c3 727 return 0;
9d66e233
JB
728 }
729
0414efae
LZ
730 ret = -1;
731
9d66e233
JB
732 leaf = path->nodes[0];
733 header = btrfs_item_ptr(leaf, path->slots[0],
734 struct btrfs_free_space_header);
735 num_entries = btrfs_free_space_entries(leaf, header);
736 num_bitmaps = btrfs_free_space_bitmaps(leaf, header);
737 generation = btrfs_free_space_generation(leaf, header);
945d8962 738 btrfs_release_path(path);
9d66e233 739
e570fd27 740 if (!BTRFS_I(inode)->generation) {
0b246afa 741 btrfs_info(fs_info,
913e1535 742 "the free space cache file (%llu) is invalid, skip it",
e570fd27
MX
743 offset);
744 return 0;
745 }
746
9d66e233 747 if (BTRFS_I(inode)->generation != generation) {
0b246afa
JM
748 btrfs_err(fs_info,
749 "free space inode generation (%llu) did not match free space cache generation (%llu)",
750 BTRFS_I(inode)->generation, generation);
a67509c3 751 return 0;
9d66e233
JB
752 }
753
754 if (!num_entries)
a67509c3 755 return 0;
9d66e233 756
f15376df 757 ret = io_ctl_init(&io_ctl, inode, 0);
706efc66
LZ
758 if (ret)
759 return ret;
760
1d480538 761 readahead_cache(inode);
9d66e233 762
7a195f6d 763 ret = io_ctl_prepare_pages(&io_ctl, true);
a67509c3
JB
764 if (ret)
765 goto out;
9d66e233 766
5b0e95bf
JB
767 ret = io_ctl_check_crc(&io_ctl, 0);
768 if (ret)
769 goto free_cache;
770
a67509c3
JB
771 ret = io_ctl_check_generation(&io_ctl, generation);
772 if (ret)
773 goto free_cache;
9d66e233 774
a67509c3
JB
775 while (num_entries) {
776 e = kmem_cache_zalloc(btrfs_free_space_cachep,
777 GFP_NOFS);
778 if (!e)
9d66e233 779 goto free_cache;
9d66e233 780
5b0e95bf
JB
781 ret = io_ctl_read_entry(&io_ctl, e, &type);
782 if (ret) {
783 kmem_cache_free(btrfs_free_space_cachep, e);
784 goto free_cache;
785 }
786
a67509c3
JB
787 if (!e->bytes) {
788 kmem_cache_free(btrfs_free_space_cachep, e);
789 goto free_cache;
9d66e233 790 }
a67509c3
JB
791
792 if (type == BTRFS_FREE_SPACE_EXTENT) {
793 spin_lock(&ctl->tree_lock);
794 ret = link_free_space(ctl, e);
795 spin_unlock(&ctl->tree_lock);
796 if (ret) {
0b246afa 797 btrfs_err(fs_info,
c2cf52eb 798 "Duplicate entries in free space cache, dumping");
a67509c3 799 kmem_cache_free(btrfs_free_space_cachep, e);
9d66e233
JB
800 goto free_cache;
801 }
a67509c3 802 } else {
b12d6869 803 ASSERT(num_bitmaps);
a67509c3 804 num_bitmaps--;
3acd4850
CL
805 e->bitmap = kmem_cache_zalloc(
806 btrfs_free_space_bitmap_cachep, GFP_NOFS);
a67509c3
JB
807 if (!e->bitmap) {
808 kmem_cache_free(
809 btrfs_free_space_cachep, e);
9d66e233
JB
810 goto free_cache;
811 }
a67509c3
JB
812 spin_lock(&ctl->tree_lock);
813 ret = link_free_space(ctl, e);
814 ctl->total_bitmaps++;
fa598b06 815 recalculate_thresholds(ctl);
a67509c3
JB
816 spin_unlock(&ctl->tree_lock);
817 if (ret) {
0b246afa 818 btrfs_err(fs_info,
c2cf52eb 819 "Duplicate entries in free space cache, dumping");
dc89e982 820 kmem_cache_free(btrfs_free_space_cachep, e);
9d66e233
JB
821 goto free_cache;
822 }
a67509c3 823 list_add_tail(&e->list, &bitmaps);
9d66e233
JB
824 }
825
a67509c3
JB
826 num_entries--;
827 }
9d66e233 828
2f120c05
JB
829 io_ctl_unmap_page(&io_ctl);
830
a67509c3
JB
831 /*
832 * We add the bitmaps at the end of the entries in order that
833 * the bitmap entries are added to the cache.
834 */
835 list_for_each_entry_safe(e, n, &bitmaps, list) {
9d66e233 836 list_del_init(&e->list);
5b0e95bf
JB
837 ret = io_ctl_read_bitmap(&io_ctl, e);
838 if (ret)
839 goto free_cache;
9d66e233
JB
840 }
841
a67509c3 842 io_ctl_drop_pages(&io_ctl);
9d66e233
JB
843 ret = 1;
844out:
a67509c3 845 io_ctl_free(&io_ctl);
9d66e233 846 return ret;
9d66e233 847free_cache:
a67509c3 848 io_ctl_drop_pages(&io_ctl);
0414efae 849 __btrfs_remove_free_space_cache(ctl);
9d66e233
JB
850 goto out;
851}
852
cd79909b
JB
853static int copy_free_space_cache(struct btrfs_block_group *block_group,
854 struct btrfs_free_space_ctl *ctl)
855{
856 struct btrfs_free_space *info;
857 struct rb_node *n;
858 int ret = 0;
859
860 while (!ret && (n = rb_first(&ctl->free_space_offset)) != NULL) {
861 info = rb_entry(n, struct btrfs_free_space, offset_index);
862 if (!info->bitmap) {
863 unlink_free_space(ctl, info);
864 ret = btrfs_add_free_space(block_group, info->offset,
865 info->bytes);
866 kmem_cache_free(btrfs_free_space_cachep, info);
867 } else {
868 u64 offset = info->offset;
869 u64 bytes = ctl->unit;
870
871 while (search_bitmap(ctl, info, &offset, &bytes,
872 false) == 0) {
873 ret = btrfs_add_free_space(block_group, offset,
874 bytes);
875 if (ret)
876 break;
877 bitmap_clear_bits(ctl, info, offset, bytes);
878 offset = info->offset;
879 bytes = ctl->unit;
880 }
881 free_bitmap(ctl, info);
882 }
883 cond_resched();
884 }
885 return ret;
886}
887
32da5386 888int load_free_space_cache(struct btrfs_block_group *block_group)
0cb59c99 889{
bb6cb1c5 890 struct btrfs_fs_info *fs_info = block_group->fs_info;
34d52cb6 891 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
cd79909b 892 struct btrfs_free_space_ctl tmp_ctl = {};
0414efae
LZ
893 struct inode *inode;
894 struct btrfs_path *path;
5b0e95bf 895 int ret = 0;
0414efae 896 bool matched;
bf38be65 897 u64 used = block_group->used;
0414efae 898
cd79909b
JB
899 /*
900 * Because we could potentially discard our loaded free space, we want
901 * to load everything into a temporary structure first, and then if it's
902 * valid copy it all into the actual free space ctl.
903 */
904 btrfs_init_free_space_ctl(block_group, &tmp_ctl);
905
0414efae
LZ
906 /*
907 * If this block group has been marked to be cleared for one reason or
908 * another then we can't trust the on disk cache, so just return.
909 */
9d66e233 910 spin_lock(&block_group->lock);
0414efae
LZ
911 if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
912 spin_unlock(&block_group->lock);
913 return 0;
914 }
9d66e233 915 spin_unlock(&block_group->lock);
0414efae
LZ
916
917 path = btrfs_alloc_path();
918 if (!path)
919 return 0;
d53ba474
JB
920 path->search_commit_root = 1;
921 path->skip_locking = 1;
0414efae 922
4222ea71
FM
923 /*
924 * We must pass a path with search_commit_root set to btrfs_iget in
925 * order to avoid a deadlock when allocating extents for the tree root.
926 *
927 * When we are COWing an extent buffer from the tree root, when looking
928 * for a free extent, at extent-tree.c:find_free_extent(), we can find
929 * block group without its free space cache loaded. When we find one
930 * we must load its space cache which requires reading its free space
931 * cache's inode item from the root tree. If this inode item is located
932 * in the same leaf that we started COWing before, then we end up in
933 * deadlock on the extent buffer (trying to read lock it when we
934 * previously write locked it).
935 *
936 * It's safe to read the inode item using the commit root because
937 * block groups, once loaded, stay in memory forever (until they are
938 * removed) as well as their space caches once loaded. New block groups
939 * once created get their ->cached field set to BTRFS_CACHE_FINISHED so
940 * we will never try to read their inode item while the fs is mounted.
941 */
7949f339 942 inode = lookup_free_space_inode(block_group, path);
0414efae
LZ
943 if (IS_ERR(inode)) {
944 btrfs_free_path(path);
945 return 0;
946 }
947
5b0e95bf
JB
948 /* We may have converted the inode and made the cache invalid. */
949 spin_lock(&block_group->lock);
950 if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
951 spin_unlock(&block_group->lock);
a7e221e9 952 btrfs_free_path(path);
5b0e95bf
JB
953 goto out;
954 }
955 spin_unlock(&block_group->lock);
956
cd79909b 957 ret = __load_free_space_cache(fs_info->tree_root, inode, &tmp_ctl,
b3470b5d 958 path, block_group->start);
0414efae
LZ
959 btrfs_free_path(path);
960 if (ret <= 0)
961 goto out;
962
cd79909b
JB
963 matched = (tmp_ctl.free_space == (block_group->length - used -
964 block_group->bytes_super));
0414efae 965
cd79909b
JB
966 if (matched) {
967 ret = copy_free_space_cache(block_group, &tmp_ctl);
968 /*
969 * ret == 1 means we successfully loaded the free space cache,
970 * so we need to re-set it here.
971 */
972 if (ret == 0)
973 ret = 1;
974 } else {
975 __btrfs_remove_free_space_cache(&tmp_ctl);
5d163e0e
JM
976 btrfs_warn(fs_info,
977 "block group %llu has wrong amount of free space",
b3470b5d 978 block_group->start);
0414efae
LZ
979 ret = -1;
980 }
981out:
982 if (ret < 0) {
983 /* This cache is bogus, make sure it gets cleared */
984 spin_lock(&block_group->lock);
985 block_group->disk_cache_state = BTRFS_DC_CLEAR;
986 spin_unlock(&block_group->lock);
82d5902d 987 ret = 0;
0414efae 988
5d163e0e
JM
989 btrfs_warn(fs_info,
990 "failed to load free space cache for block group %llu, rebuilding it now",
b3470b5d 991 block_group->start);
0414efae
LZ
992 }
993
66b53bae
JB
994 spin_lock(&ctl->tree_lock);
995 btrfs_discard_update_discardable(block_group);
996 spin_unlock(&ctl->tree_lock);
0414efae
LZ
997 iput(inode);
998 return ret;
9d66e233
JB
999}
1000
d4452bc5 1001static noinline_for_stack
4c6d1d85 1002int write_cache_extent_entries(struct btrfs_io_ctl *io_ctl,
d4452bc5 1003 struct btrfs_free_space_ctl *ctl,
32da5386 1004 struct btrfs_block_group *block_group,
d4452bc5
CM
1005 int *entries, int *bitmaps,
1006 struct list_head *bitmap_list)
0cb59c99 1007{
c09544e0 1008 int ret;
d4452bc5 1009 struct btrfs_free_cluster *cluster = NULL;
1bbc621e 1010 struct btrfs_free_cluster *cluster_locked = NULL;
d4452bc5 1011 struct rb_node *node = rb_first(&ctl->free_space_offset);
55507ce3 1012 struct btrfs_trim_range *trim_entry;
be1a12a0 1013
43be2146 1014 /* Get the cluster for this block_group if it exists */
d4452bc5 1015 if (block_group && !list_empty(&block_group->cluster_list)) {
43be2146
JB
1016 cluster = list_entry(block_group->cluster_list.next,
1017 struct btrfs_free_cluster,
1018 block_group_list);
d4452bc5 1019 }
43be2146 1020
f75b130e 1021 if (!node && cluster) {
1bbc621e
CM
1022 cluster_locked = cluster;
1023 spin_lock(&cluster_locked->lock);
f75b130e
JB
1024 node = rb_first(&cluster->root);
1025 cluster = NULL;
1026 }
1027
a67509c3
JB
1028 /* Write out the extent entries */
1029 while (node) {
1030 struct btrfs_free_space *e;
0cb59c99 1031
a67509c3 1032 e = rb_entry(node, struct btrfs_free_space, offset_index);
d4452bc5 1033 *entries += 1;
0cb59c99 1034
d4452bc5 1035 ret = io_ctl_add_entry(io_ctl, e->offset, e->bytes,
a67509c3
JB
1036 e->bitmap);
1037 if (ret)
d4452bc5 1038 goto fail;
2f356126 1039
a67509c3 1040 if (e->bitmap) {
d4452bc5
CM
1041 list_add_tail(&e->list, bitmap_list);
1042 *bitmaps += 1;
2f356126 1043 }
a67509c3
JB
1044 node = rb_next(node);
1045 if (!node && cluster) {
1046 node = rb_first(&cluster->root);
1bbc621e
CM
1047 cluster_locked = cluster;
1048 spin_lock(&cluster_locked->lock);
a67509c3 1049 cluster = NULL;
43be2146 1050 }
a67509c3 1051 }
1bbc621e
CM
1052 if (cluster_locked) {
1053 spin_unlock(&cluster_locked->lock);
1054 cluster_locked = NULL;
1055 }
55507ce3
FM
1056
1057 /*
1058 * Make sure we don't miss any range that was removed from our rbtree
1059 * because trimming is running. Otherwise after a umount+mount (or crash
1060 * after committing the transaction) we would leak free space and get
1061 * an inconsistent free space cache report from fsck.
1062 */
1063 list_for_each_entry(trim_entry, &ctl->trimming_ranges, list) {
1064 ret = io_ctl_add_entry(io_ctl, trim_entry->start,
1065 trim_entry->bytes, NULL);
1066 if (ret)
1067 goto fail;
1068 *entries += 1;
1069 }
1070
d4452bc5
CM
1071 return 0;
1072fail:
1bbc621e
CM
1073 if (cluster_locked)
1074 spin_unlock(&cluster_locked->lock);
d4452bc5
CM
1075 return -ENOSPC;
1076}
1077
1078static noinline_for_stack int
1079update_cache_item(struct btrfs_trans_handle *trans,
1080 struct btrfs_root *root,
1081 struct inode *inode,
1082 struct btrfs_path *path, u64 offset,
1083 int entries, int bitmaps)
1084{
1085 struct btrfs_key key;
1086 struct btrfs_free_space_header *header;
1087 struct extent_buffer *leaf;
1088 int ret;
1089
1090 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
1091 key.offset = offset;
1092 key.type = 0;
1093
1094 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1095 if (ret < 0) {
1096 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1,
e182163d 1097 EXTENT_DELALLOC, 0, 0, NULL);
d4452bc5
CM
1098 goto fail;
1099 }
1100 leaf = path->nodes[0];
1101 if (ret > 0) {
1102 struct btrfs_key found_key;
1103 ASSERT(path->slots[0]);
1104 path->slots[0]--;
1105 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1106 if (found_key.objectid != BTRFS_FREE_SPACE_OBJECTID ||
1107 found_key.offset != offset) {
1108 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0,
e182163d
OS
1109 inode->i_size - 1, EXTENT_DELALLOC, 0,
1110 0, NULL);
d4452bc5
CM
1111 btrfs_release_path(path);
1112 goto fail;
1113 }
1114 }
1115
1116 BTRFS_I(inode)->generation = trans->transid;
1117 header = btrfs_item_ptr(leaf, path->slots[0],
1118 struct btrfs_free_space_header);
1119 btrfs_set_free_space_entries(leaf, header, entries);
1120 btrfs_set_free_space_bitmaps(leaf, header, bitmaps);
1121 btrfs_set_free_space_generation(leaf, header, trans->transid);
1122 btrfs_mark_buffer_dirty(leaf);
1123 btrfs_release_path(path);
1124
1125 return 0;
1126
1127fail:
1128 return -1;
1129}
1130
6701bdb3 1131static noinline_for_stack int write_pinned_extent_entries(
6b45f641 1132 struct btrfs_trans_handle *trans,
32da5386 1133 struct btrfs_block_group *block_group,
4c6d1d85 1134 struct btrfs_io_ctl *io_ctl,
5349d6c3 1135 int *entries)
d4452bc5
CM
1136{
1137 u64 start, extent_start, extent_end, len;
d4452bc5
CM
1138 struct extent_io_tree *unpin = NULL;
1139 int ret;
43be2146 1140
5349d6c3
MX
1141 if (!block_group)
1142 return 0;
1143
a67509c3
JB
1144 /*
1145 * We want to add any pinned extents to our free space cache
1146 * so we don't leak the space
d4452bc5 1147 *
db804f23
LZ
1148 * We shouldn't have switched the pinned extents yet so this is the
1149 * right one
1150 */
fe119a6e 1151 unpin = &trans->transaction->pinned_extents;
db804f23 1152
b3470b5d 1153 start = block_group->start;
db804f23 1154
b3470b5d 1155 while (start < block_group->start + block_group->length) {
db804f23
LZ
1156 ret = find_first_extent_bit(unpin, start,
1157 &extent_start, &extent_end,
e6138876 1158 EXTENT_DIRTY, NULL);
5349d6c3
MX
1159 if (ret)
1160 return 0;
0cb59c99 1161
a67509c3 1162 /* This pinned extent is out of our range */
b3470b5d 1163 if (extent_start >= block_group->start + block_group->length)
5349d6c3 1164 return 0;
2f356126 1165
db804f23 1166 extent_start = max(extent_start, start);
b3470b5d
DS
1167 extent_end = min(block_group->start + block_group->length,
1168 extent_end + 1);
db804f23 1169 len = extent_end - extent_start;
0cb59c99 1170
d4452bc5
CM
1171 *entries += 1;
1172 ret = io_ctl_add_entry(io_ctl, extent_start, len, NULL);
a67509c3 1173 if (ret)
5349d6c3 1174 return -ENOSPC;
0cb59c99 1175
db804f23 1176 start = extent_end;
a67509c3 1177 }
0cb59c99 1178
5349d6c3
MX
1179 return 0;
1180}
1181
1182static noinline_for_stack int
4c6d1d85 1183write_bitmap_entries(struct btrfs_io_ctl *io_ctl, struct list_head *bitmap_list)
5349d6c3 1184{
7ae1681e 1185 struct btrfs_free_space *entry, *next;
5349d6c3
MX
1186 int ret;
1187
0cb59c99 1188 /* Write out the bitmaps */
7ae1681e 1189 list_for_each_entry_safe(entry, next, bitmap_list, list) {
d4452bc5 1190 ret = io_ctl_add_bitmap(io_ctl, entry->bitmap);
a67509c3 1191 if (ret)
5349d6c3 1192 return -ENOSPC;
0cb59c99 1193 list_del_init(&entry->list);
be1a12a0
JB
1194 }
1195
5349d6c3
MX
1196 return 0;
1197}
0cb59c99 1198
5349d6c3
MX
1199static int flush_dirty_cache(struct inode *inode)
1200{
1201 int ret;
be1a12a0 1202
0ef8b726 1203 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
5349d6c3 1204 if (ret)
0ef8b726 1205 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1,
e182163d 1206 EXTENT_DELALLOC, 0, 0, NULL);
0cb59c99 1207
5349d6c3 1208 return ret;
d4452bc5
CM
1209}
1210
1211static void noinline_for_stack
a3bdccc4 1212cleanup_bitmap_list(struct list_head *bitmap_list)
d4452bc5 1213{
7ae1681e 1214 struct btrfs_free_space *entry, *next;
5349d6c3 1215
7ae1681e 1216 list_for_each_entry_safe(entry, next, bitmap_list, list)
d4452bc5 1217 list_del_init(&entry->list);
a3bdccc4
CM
1218}
1219
1220static void noinline_for_stack
1221cleanup_write_cache_enospc(struct inode *inode,
1222 struct btrfs_io_ctl *io_ctl,
7bf1a159 1223 struct extent_state **cached_state)
a3bdccc4 1224{
d4452bc5
CM
1225 io_ctl_drop_pages(io_ctl);
1226 unlock_extent_cached(&BTRFS_I(inode)->io_tree, 0,
e43bbe5e 1227 i_size_read(inode) - 1, cached_state);
d4452bc5 1228}
549b4fdb 1229
afdb5718
JM
1230static int __btrfs_wait_cache_io(struct btrfs_root *root,
1231 struct btrfs_trans_handle *trans,
32da5386 1232 struct btrfs_block_group *block_group,
afdb5718
JM
1233 struct btrfs_io_ctl *io_ctl,
1234 struct btrfs_path *path, u64 offset)
c9dc4c65
CM
1235{
1236 int ret;
1237 struct inode *inode = io_ctl->inode;
1238
1bbc621e
CM
1239 if (!inode)
1240 return 0;
1241
c9dc4c65
CM
1242 /* Flush the dirty pages in the cache file. */
1243 ret = flush_dirty_cache(inode);
1244 if (ret)
1245 goto out;
1246
1247 /* Update the cache item to tell everyone this cache file is valid. */
1248 ret = update_cache_item(trans, root, inode, path, offset,
1249 io_ctl->entries, io_ctl->bitmaps);
1250out:
c9dc4c65
CM
1251 if (ret) {
1252 invalidate_inode_pages2(inode->i_mapping);
1253 BTRFS_I(inode)->generation = 0;
bbcd1f4d
FM
1254 if (block_group)
1255 btrfs_debug(root->fs_info,
2e69a7a6
FM
1256 "failed to write free space cache for block group %llu error %d",
1257 block_group->start, ret);
c9dc4c65 1258 }
9a56fcd1 1259 btrfs_update_inode(trans, root, BTRFS_I(inode));
c9dc4c65
CM
1260
1261 if (block_group) {
1bbc621e
CM
1262 /* the dirty list is protected by the dirty_bgs_lock */
1263 spin_lock(&trans->transaction->dirty_bgs_lock);
1264
1265 /* the disk_cache_state is protected by the block group lock */
c9dc4c65
CM
1266 spin_lock(&block_group->lock);
1267
1268 /*
1269 * only mark this as written if we didn't get put back on
1bbc621e
CM
1270 * the dirty list while waiting for IO. Otherwise our
1271 * cache state won't be right, and we won't get written again
c9dc4c65
CM
1272 */
1273 if (!ret && list_empty(&block_group->dirty_list))
1274 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1275 else if (ret)
1276 block_group->disk_cache_state = BTRFS_DC_ERROR;
1277
1278 spin_unlock(&block_group->lock);
1bbc621e 1279 spin_unlock(&trans->transaction->dirty_bgs_lock);
c9dc4c65
CM
1280 io_ctl->inode = NULL;
1281 iput(inode);
1282 }
1283
1284 return ret;
1285
1286}
1287
afdb5718 1288int btrfs_wait_cache_io(struct btrfs_trans_handle *trans,
32da5386 1289 struct btrfs_block_group *block_group,
afdb5718
JM
1290 struct btrfs_path *path)
1291{
1292 return __btrfs_wait_cache_io(block_group->fs_info->tree_root, trans,
1293 block_group, &block_group->io_ctl,
b3470b5d 1294 path, block_group->start);
afdb5718
JM
1295}
1296
d4452bc5
CM
1297/**
1298 * __btrfs_write_out_cache - write out cached info to an inode
1299 * @root - the root the inode belongs to
1300 * @ctl - the free space cache we are going to write out
1301 * @block_group - the block_group for this cache if it belongs to a block_group
1302 * @trans - the trans handle
d4452bc5
CM
1303 *
1304 * This function writes out a free space cache struct to disk for quick recovery
8cd1e731 1305 * on mount. This will return 0 if it was successful in writing the cache out,
b8605454 1306 * or an errno if it was not.
d4452bc5
CM
1307 */
1308static int __btrfs_write_out_cache(struct btrfs_root *root, struct inode *inode,
1309 struct btrfs_free_space_ctl *ctl,
32da5386 1310 struct btrfs_block_group *block_group,
c9dc4c65 1311 struct btrfs_io_ctl *io_ctl,
0e8d931a 1312 struct btrfs_trans_handle *trans)
d4452bc5
CM
1313{
1314 struct extent_state *cached_state = NULL;
5349d6c3 1315 LIST_HEAD(bitmap_list);
d4452bc5
CM
1316 int entries = 0;
1317 int bitmaps = 0;
1318 int ret;
c9dc4c65 1319 int must_iput = 0;
d4452bc5
CM
1320
1321 if (!i_size_read(inode))
b8605454 1322 return -EIO;
d4452bc5 1323
c9dc4c65 1324 WARN_ON(io_ctl->pages);
f15376df 1325 ret = io_ctl_init(io_ctl, inode, 1);
d4452bc5 1326 if (ret)
b8605454 1327 return ret;
d4452bc5 1328
e570fd27
MX
1329 if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA)) {
1330 down_write(&block_group->data_rwsem);
1331 spin_lock(&block_group->lock);
1332 if (block_group->delalloc_bytes) {
1333 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1334 spin_unlock(&block_group->lock);
1335 up_write(&block_group->data_rwsem);
1336 BTRFS_I(inode)->generation = 0;
1337 ret = 0;
c9dc4c65 1338 must_iput = 1;
e570fd27
MX
1339 goto out;
1340 }
1341 spin_unlock(&block_group->lock);
1342 }
1343
d4452bc5 1344 /* Lock all pages first so we can lock the extent safely. */
7a195f6d 1345 ret = io_ctl_prepare_pages(io_ctl, false);
b8605454 1346 if (ret)
b77000ed 1347 goto out_unlock;
d4452bc5
CM
1348
1349 lock_extent_bits(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1,
ff13db41 1350 &cached_state);
d4452bc5 1351
c9dc4c65 1352 io_ctl_set_generation(io_ctl, trans->transid);
d4452bc5 1353
55507ce3 1354 mutex_lock(&ctl->cache_writeout_mutex);
5349d6c3 1355 /* Write out the extent entries in the free space cache */
1bbc621e 1356 spin_lock(&ctl->tree_lock);
c9dc4c65 1357 ret = write_cache_extent_entries(io_ctl, ctl,
d4452bc5
CM
1358 block_group, &entries, &bitmaps,
1359 &bitmap_list);
a3bdccc4
CM
1360 if (ret)
1361 goto out_nospc_locked;
d4452bc5 1362
5349d6c3
MX
1363 /*
1364 * Some spaces that are freed in the current transaction are pinned,
1365 * they will be added into free space cache after the transaction is
1366 * committed, we shouldn't lose them.
1bbc621e
CM
1367 *
1368 * If this changes while we are working we'll get added back to
1369 * the dirty list and redo it. No locking needed
5349d6c3 1370 */
6b45f641 1371 ret = write_pinned_extent_entries(trans, block_group, io_ctl, &entries);
a3bdccc4
CM
1372 if (ret)
1373 goto out_nospc_locked;
5349d6c3 1374
55507ce3
FM
1375 /*
1376 * At last, we write out all the bitmaps and keep cache_writeout_mutex
1377 * locked while doing it because a concurrent trim can be manipulating
1378 * or freeing the bitmap.
1379 */
c9dc4c65 1380 ret = write_bitmap_entries(io_ctl, &bitmap_list);
1bbc621e 1381 spin_unlock(&ctl->tree_lock);
55507ce3 1382 mutex_unlock(&ctl->cache_writeout_mutex);
5349d6c3
MX
1383 if (ret)
1384 goto out_nospc;
1385
1386 /* Zero out the rest of the pages just to make sure */
c9dc4c65 1387 io_ctl_zero_remaining_pages(io_ctl);
d4452bc5 1388
5349d6c3 1389 /* Everything is written out, now we dirty the pages in the file. */
088545f6
NB
1390 ret = btrfs_dirty_pages(BTRFS_I(inode), io_ctl->pages,
1391 io_ctl->num_pages, 0, i_size_read(inode),
aa8c1a41 1392 &cached_state, false);
5349d6c3 1393 if (ret)
d4452bc5 1394 goto out_nospc;
5349d6c3 1395
e570fd27
MX
1396 if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA))
1397 up_write(&block_group->data_rwsem);
5349d6c3
MX
1398 /*
1399 * Release the pages and unlock the extent, we will flush
1400 * them out later
1401 */
c9dc4c65 1402 io_ctl_drop_pages(io_ctl);
bbc37d6e 1403 io_ctl_free(io_ctl);
5349d6c3
MX
1404
1405 unlock_extent_cached(&BTRFS_I(inode)->io_tree, 0,
e43bbe5e 1406 i_size_read(inode) - 1, &cached_state);
5349d6c3 1407
c9dc4c65
CM
1408 /*
1409 * at this point the pages are under IO and we're happy,
260db43c 1410 * The caller is responsible for waiting on them and updating
c9dc4c65
CM
1411 * the cache and the inode
1412 */
1413 io_ctl->entries = entries;
1414 io_ctl->bitmaps = bitmaps;
1415
1416 ret = btrfs_fdatawrite_range(inode, 0, (u64)-1);
5349d6c3 1417 if (ret)
d4452bc5
CM
1418 goto out;
1419
c9dc4c65
CM
1420 return 0;
1421
a3bdccc4
CM
1422out_nospc_locked:
1423 cleanup_bitmap_list(&bitmap_list);
1424 spin_unlock(&ctl->tree_lock);
1425 mutex_unlock(&ctl->cache_writeout_mutex);
1426
a67509c3 1427out_nospc:
7bf1a159 1428 cleanup_write_cache_enospc(inode, io_ctl, &cached_state);
e570fd27 1429
b77000ed 1430out_unlock:
e570fd27
MX
1431 if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA))
1432 up_write(&block_group->data_rwsem);
1433
fd8efa81
JT
1434out:
1435 io_ctl->inode = NULL;
1436 io_ctl_free(io_ctl);
1437 if (ret) {
1438 invalidate_inode_pages2(inode->i_mapping);
1439 BTRFS_I(inode)->generation = 0;
1440 }
9a56fcd1 1441 btrfs_update_inode(trans, root, BTRFS_I(inode));
fd8efa81
JT
1442 if (must_iput)
1443 iput(inode);
1444 return ret;
0414efae
LZ
1445}
1446
fe041534 1447int btrfs_write_out_cache(struct btrfs_trans_handle *trans,
32da5386 1448 struct btrfs_block_group *block_group,
0414efae
LZ
1449 struct btrfs_path *path)
1450{
fe041534 1451 struct btrfs_fs_info *fs_info = trans->fs_info;
0414efae
LZ
1452 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
1453 struct inode *inode;
1454 int ret = 0;
1455
0414efae
LZ
1456 spin_lock(&block_group->lock);
1457 if (block_group->disk_cache_state < BTRFS_DC_SETUP) {
1458 spin_unlock(&block_group->lock);
e570fd27
MX
1459 return 0;
1460 }
0414efae
LZ
1461 spin_unlock(&block_group->lock);
1462
7949f339 1463 inode = lookup_free_space_inode(block_group, path);
0414efae
LZ
1464 if (IS_ERR(inode))
1465 return 0;
1466
77ab86bf
JM
1467 ret = __btrfs_write_out_cache(fs_info->tree_root, inode, ctl,
1468 block_group, &block_group->io_ctl, trans);
c09544e0 1469 if (ret) {
bbcd1f4d 1470 btrfs_debug(fs_info,
2e69a7a6
FM
1471 "failed to write free space cache for block group %llu error %d",
1472 block_group->start, ret);
c9dc4c65
CM
1473 spin_lock(&block_group->lock);
1474 block_group->disk_cache_state = BTRFS_DC_ERROR;
1475 spin_unlock(&block_group->lock);
1476
1477 block_group->io_ctl.inode = NULL;
1478 iput(inode);
0414efae
LZ
1479 }
1480
c9dc4c65
CM
1481 /*
1482 * if ret == 0 the caller is expected to call btrfs_wait_cache_io
1483 * to wait for IO and put the inode
1484 */
1485
0cb59c99
JB
1486 return ret;
1487}
1488
34d52cb6 1489static inline unsigned long offset_to_bit(u64 bitmap_start, u32 unit,
96303081 1490 u64 offset)
0f9dd46c 1491{
b12d6869 1492 ASSERT(offset >= bitmap_start);
96303081 1493 offset -= bitmap_start;
34d52cb6 1494 return (unsigned long)(div_u64(offset, unit));
96303081 1495}
0f9dd46c 1496
34d52cb6 1497static inline unsigned long bytes_to_bits(u64 bytes, u32 unit)
96303081 1498{
34d52cb6 1499 return (unsigned long)(div_u64(bytes, unit));
96303081 1500}
0f9dd46c 1501
34d52cb6 1502static inline u64 offset_to_bitmap(struct btrfs_free_space_ctl *ctl,
96303081
JB
1503 u64 offset)
1504{
1505 u64 bitmap_start;
0ef6447a 1506 u64 bytes_per_bitmap;
0f9dd46c 1507
34d52cb6
LZ
1508 bytes_per_bitmap = BITS_PER_BITMAP * ctl->unit;
1509 bitmap_start = offset - ctl->start;
0ef6447a 1510 bitmap_start = div64_u64(bitmap_start, bytes_per_bitmap);
96303081 1511 bitmap_start *= bytes_per_bitmap;
34d52cb6 1512 bitmap_start += ctl->start;
0f9dd46c 1513
96303081 1514 return bitmap_start;
0f9dd46c
JB
1515}
1516
96303081
JB
1517static int tree_insert_offset(struct rb_root *root, u64 offset,
1518 struct rb_node *node, int bitmap)
0f9dd46c
JB
1519{
1520 struct rb_node **p = &root->rb_node;
1521 struct rb_node *parent = NULL;
1522 struct btrfs_free_space *info;
1523
1524 while (*p) {
1525 parent = *p;
96303081 1526 info = rb_entry(parent, struct btrfs_free_space, offset_index);
0f9dd46c 1527
96303081 1528 if (offset < info->offset) {
0f9dd46c 1529 p = &(*p)->rb_left;
96303081 1530 } else if (offset > info->offset) {
0f9dd46c 1531 p = &(*p)->rb_right;
96303081
JB
1532 } else {
1533 /*
1534 * we could have a bitmap entry and an extent entry
1535 * share the same offset. If this is the case, we want
1536 * the extent entry to always be found first if we do a
1537 * linear search through the tree, since we want to have
1538 * the quickest allocation time, and allocating from an
1539 * extent is faster than allocating from a bitmap. So
1540 * if we're inserting a bitmap and we find an entry at
1541 * this offset, we want to go right, or after this entry
1542 * logically. If we are inserting an extent and we've
1543 * found a bitmap, we want to go left, or before
1544 * logically.
1545 */
1546 if (bitmap) {
207dde82
JB
1547 if (info->bitmap) {
1548 WARN_ON_ONCE(1);
1549 return -EEXIST;
1550 }
96303081
JB
1551 p = &(*p)->rb_right;
1552 } else {
207dde82
JB
1553 if (!info->bitmap) {
1554 WARN_ON_ONCE(1);
1555 return -EEXIST;
1556 }
96303081
JB
1557 p = &(*p)->rb_left;
1558 }
1559 }
0f9dd46c
JB
1560 }
1561
1562 rb_link_node(node, parent, p);
1563 rb_insert_color(node, root);
1564
1565 return 0;
1566}
1567
1568/*
70cb0743
JB
1569 * searches the tree for the given offset.
1570 *
96303081
JB
1571 * fuzzy - If this is set, then we are trying to make an allocation, and we just
1572 * want a section that has at least bytes size and comes at or after the given
1573 * offset.
0f9dd46c 1574 */
96303081 1575static struct btrfs_free_space *
34d52cb6 1576tree_search_offset(struct btrfs_free_space_ctl *ctl,
96303081 1577 u64 offset, int bitmap_only, int fuzzy)
0f9dd46c 1578{
34d52cb6 1579 struct rb_node *n = ctl->free_space_offset.rb_node;
96303081
JB
1580 struct btrfs_free_space *entry, *prev = NULL;
1581
1582 /* find entry that is closest to the 'offset' */
1583 while (1) {
1584 if (!n) {
1585 entry = NULL;
1586 break;
1587 }
0f9dd46c 1588
0f9dd46c 1589 entry = rb_entry(n, struct btrfs_free_space, offset_index);
96303081 1590 prev = entry;
0f9dd46c 1591
96303081 1592 if (offset < entry->offset)
0f9dd46c 1593 n = n->rb_left;
96303081 1594 else if (offset > entry->offset)
0f9dd46c 1595 n = n->rb_right;
96303081 1596 else
0f9dd46c 1597 break;
0f9dd46c
JB
1598 }
1599
96303081
JB
1600 if (bitmap_only) {
1601 if (!entry)
1602 return NULL;
1603 if (entry->bitmap)
1604 return entry;
0f9dd46c 1605
96303081
JB
1606 /*
1607 * bitmap entry and extent entry may share same offset,
1608 * in that case, bitmap entry comes after extent entry.
1609 */
1610 n = rb_next(n);
1611 if (!n)
1612 return NULL;
1613 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1614 if (entry->offset != offset)
1615 return NULL;
0f9dd46c 1616
96303081
JB
1617 WARN_ON(!entry->bitmap);
1618 return entry;
1619 } else if (entry) {
1620 if (entry->bitmap) {
0f9dd46c 1621 /*
96303081
JB
1622 * if previous extent entry covers the offset,
1623 * we should return it instead of the bitmap entry
0f9dd46c 1624 */
de6c4115
MX
1625 n = rb_prev(&entry->offset_index);
1626 if (n) {
96303081
JB
1627 prev = rb_entry(n, struct btrfs_free_space,
1628 offset_index);
de6c4115
MX
1629 if (!prev->bitmap &&
1630 prev->offset + prev->bytes > offset)
1631 entry = prev;
0f9dd46c 1632 }
96303081
JB
1633 }
1634 return entry;
1635 }
1636
1637 if (!prev)
1638 return NULL;
1639
1640 /* find last entry before the 'offset' */
1641 entry = prev;
1642 if (entry->offset > offset) {
1643 n = rb_prev(&entry->offset_index);
1644 if (n) {
1645 entry = rb_entry(n, struct btrfs_free_space,
1646 offset_index);
b12d6869 1647 ASSERT(entry->offset <= offset);
0f9dd46c 1648 } else {
96303081
JB
1649 if (fuzzy)
1650 return entry;
1651 else
1652 return NULL;
0f9dd46c
JB
1653 }
1654 }
1655
96303081 1656 if (entry->bitmap) {
de6c4115
MX
1657 n = rb_prev(&entry->offset_index);
1658 if (n) {
96303081
JB
1659 prev = rb_entry(n, struct btrfs_free_space,
1660 offset_index);
de6c4115
MX
1661 if (!prev->bitmap &&
1662 prev->offset + prev->bytes > offset)
1663 return prev;
96303081 1664 }
34d52cb6 1665 if (entry->offset + BITS_PER_BITMAP * ctl->unit > offset)
96303081
JB
1666 return entry;
1667 } else if (entry->offset + entry->bytes > offset)
1668 return entry;
1669
1670 if (!fuzzy)
1671 return NULL;
1672
1673 while (1) {
1674 if (entry->bitmap) {
1675 if (entry->offset + BITS_PER_BITMAP *
34d52cb6 1676 ctl->unit > offset)
96303081
JB
1677 break;
1678 } else {
1679 if (entry->offset + entry->bytes > offset)
1680 break;
1681 }
1682
1683 n = rb_next(&entry->offset_index);
1684 if (!n)
1685 return NULL;
1686 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1687 }
1688 return entry;
0f9dd46c
JB
1689}
1690
f333adb5 1691static inline void
34d52cb6 1692__unlink_free_space(struct btrfs_free_space_ctl *ctl,
f333adb5 1693 struct btrfs_free_space *info)
0f9dd46c 1694{
34d52cb6
LZ
1695 rb_erase(&info->offset_index, &ctl->free_space_offset);
1696 ctl->free_extents--;
dfb79ddb 1697
5dc7c10b 1698 if (!info->bitmap && !btrfs_free_space_trimmed(info)) {
dfb79ddb 1699 ctl->discardable_extents[BTRFS_STAT_CURR]--;
5dc7c10b
DZ
1700 ctl->discardable_bytes[BTRFS_STAT_CURR] -= info->bytes;
1701 }
f333adb5
LZ
1702}
1703
34d52cb6 1704static void unlink_free_space(struct btrfs_free_space_ctl *ctl,
f333adb5
LZ
1705 struct btrfs_free_space *info)
1706{
34d52cb6
LZ
1707 __unlink_free_space(ctl, info);
1708 ctl->free_space -= info->bytes;
0f9dd46c
JB
1709}
1710
34d52cb6 1711static int link_free_space(struct btrfs_free_space_ctl *ctl,
0f9dd46c
JB
1712 struct btrfs_free_space *info)
1713{
1714 int ret = 0;
1715
b12d6869 1716 ASSERT(info->bytes || info->bitmap);
34d52cb6 1717 ret = tree_insert_offset(&ctl->free_space_offset, info->offset,
96303081 1718 &info->offset_index, (info->bitmap != NULL));
0f9dd46c
JB
1719 if (ret)
1720 return ret;
1721
5dc7c10b 1722 if (!info->bitmap && !btrfs_free_space_trimmed(info)) {
dfb79ddb 1723 ctl->discardable_extents[BTRFS_STAT_CURR]++;
5dc7c10b
DZ
1724 ctl->discardable_bytes[BTRFS_STAT_CURR] += info->bytes;
1725 }
dfb79ddb 1726
34d52cb6
LZ
1727 ctl->free_space += info->bytes;
1728 ctl->free_extents++;
96303081
JB
1729 return ret;
1730}
1731
bb3ac5a4
MX
1732static inline void __bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
1733 struct btrfs_free_space *info,
1734 u64 offset, u64 bytes)
96303081 1735{
dfb79ddb
DZ
1736 unsigned long start, count, end;
1737 int extent_delta = -1;
96303081 1738
34d52cb6
LZ
1739 start = offset_to_bit(info->offset, ctl->unit, offset);
1740 count = bytes_to_bits(bytes, ctl->unit);
dfb79ddb
DZ
1741 end = start + count;
1742 ASSERT(end <= BITS_PER_BITMAP);
96303081 1743
f38b6e75 1744 bitmap_clear(info->bitmap, start, count);
96303081
JB
1745
1746 info->bytes -= bytes;
553cceb4
JB
1747 if (info->max_extent_size > ctl->unit)
1748 info->max_extent_size = 0;
dfb79ddb
DZ
1749
1750 if (start && test_bit(start - 1, info->bitmap))
1751 extent_delta++;
1752
1753 if (end < BITS_PER_BITMAP && test_bit(end, info->bitmap))
1754 extent_delta++;
1755
1756 info->bitmap_extents += extent_delta;
5dc7c10b 1757 if (!btrfs_free_space_trimmed(info)) {
dfb79ddb 1758 ctl->discardable_extents[BTRFS_STAT_CURR] += extent_delta;
5dc7c10b
DZ
1759 ctl->discardable_bytes[BTRFS_STAT_CURR] -= bytes;
1760 }
bb3ac5a4
MX
1761}
1762
1763static void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
1764 struct btrfs_free_space *info, u64 offset,
1765 u64 bytes)
1766{
1767 __bitmap_clear_bits(ctl, info, offset, bytes);
34d52cb6 1768 ctl->free_space -= bytes;
96303081
JB
1769}
1770
34d52cb6 1771static void bitmap_set_bits(struct btrfs_free_space_ctl *ctl,
817d52f8
JB
1772 struct btrfs_free_space *info, u64 offset,
1773 u64 bytes)
96303081 1774{
dfb79ddb
DZ
1775 unsigned long start, count, end;
1776 int extent_delta = 1;
96303081 1777
34d52cb6
LZ
1778 start = offset_to_bit(info->offset, ctl->unit, offset);
1779 count = bytes_to_bits(bytes, ctl->unit);
dfb79ddb
DZ
1780 end = start + count;
1781 ASSERT(end <= BITS_PER_BITMAP);
96303081 1782
f38b6e75 1783 bitmap_set(info->bitmap, start, count);
96303081
JB
1784
1785 info->bytes += bytes;
34d52cb6 1786 ctl->free_space += bytes;
dfb79ddb
DZ
1787
1788 if (start && test_bit(start - 1, info->bitmap))
1789 extent_delta--;
1790
1791 if (end < BITS_PER_BITMAP && test_bit(end, info->bitmap))
1792 extent_delta--;
1793
1794 info->bitmap_extents += extent_delta;
5dc7c10b 1795 if (!btrfs_free_space_trimmed(info)) {
dfb79ddb 1796 ctl->discardable_extents[BTRFS_STAT_CURR] += extent_delta;
5dc7c10b
DZ
1797 ctl->discardable_bytes[BTRFS_STAT_CURR] += bytes;
1798 }
96303081
JB
1799}
1800
a4820398
MX
1801/*
1802 * If we can not find suitable extent, we will use bytes to record
1803 * the size of the max extent.
1804 */
34d52cb6 1805static int search_bitmap(struct btrfs_free_space_ctl *ctl,
96303081 1806 struct btrfs_free_space *bitmap_info, u64 *offset,
0584f718 1807 u64 *bytes, bool for_alloc)
96303081
JB
1808{
1809 unsigned long found_bits = 0;
a4820398 1810 unsigned long max_bits = 0;
96303081
JB
1811 unsigned long bits, i;
1812 unsigned long next_zero;
a4820398 1813 unsigned long extent_bits;
96303081 1814
cef40483
JB
1815 /*
1816 * Skip searching the bitmap if we don't have a contiguous section that
1817 * is large enough for this allocation.
1818 */
0584f718
JB
1819 if (for_alloc &&
1820 bitmap_info->max_extent_size &&
cef40483
JB
1821 bitmap_info->max_extent_size < *bytes) {
1822 *bytes = bitmap_info->max_extent_size;
1823 return -1;
1824 }
1825
34d52cb6 1826 i = offset_to_bit(bitmap_info->offset, ctl->unit,
96303081 1827 max_t(u64, *offset, bitmap_info->offset));
34d52cb6 1828 bits = bytes_to_bits(*bytes, ctl->unit);
96303081 1829
ebb3dad4 1830 for_each_set_bit_from(i, bitmap_info->bitmap, BITS_PER_BITMAP) {
0584f718
JB
1831 if (for_alloc && bits == 1) {
1832 found_bits = 1;
1833 break;
1834 }
96303081
JB
1835 next_zero = find_next_zero_bit(bitmap_info->bitmap,
1836 BITS_PER_BITMAP, i);
a4820398
MX
1837 extent_bits = next_zero - i;
1838 if (extent_bits >= bits) {
1839 found_bits = extent_bits;
96303081 1840 break;
a4820398
MX
1841 } else if (extent_bits > max_bits) {
1842 max_bits = extent_bits;
96303081
JB
1843 }
1844 i = next_zero;
1845 }
1846
1847 if (found_bits) {
34d52cb6
LZ
1848 *offset = (u64)(i * ctl->unit) + bitmap_info->offset;
1849 *bytes = (u64)(found_bits) * ctl->unit;
96303081
JB
1850 return 0;
1851 }
1852
a4820398 1853 *bytes = (u64)(max_bits) * ctl->unit;
cef40483 1854 bitmap_info->max_extent_size = *bytes;
96303081
JB
1855 return -1;
1856}
1857
ad22cf6e
JB
1858static inline u64 get_max_extent_size(struct btrfs_free_space *entry)
1859{
1860 if (entry->bitmap)
1861 return entry->max_extent_size;
1862 return entry->bytes;
1863}
1864
a4820398 1865/* Cache the size of the max extent in bytes */
34d52cb6 1866static struct btrfs_free_space *
53b381b3 1867find_free_space(struct btrfs_free_space_ctl *ctl, u64 *offset, u64 *bytes,
a4820398 1868 unsigned long align, u64 *max_extent_size)
96303081
JB
1869{
1870 struct btrfs_free_space *entry;
1871 struct rb_node *node;
53b381b3
DW
1872 u64 tmp;
1873 u64 align_off;
96303081
JB
1874 int ret;
1875
34d52cb6 1876 if (!ctl->free_space_offset.rb_node)
a4820398 1877 goto out;
96303081 1878
34d52cb6 1879 entry = tree_search_offset(ctl, offset_to_bitmap(ctl, *offset), 0, 1);
96303081 1880 if (!entry)
a4820398 1881 goto out;
96303081
JB
1882
1883 for (node = &entry->offset_index; node; node = rb_next(node)) {
1884 entry = rb_entry(node, struct btrfs_free_space, offset_index);
a4820398 1885 if (entry->bytes < *bytes) {
ad22cf6e
JB
1886 *max_extent_size = max(get_max_extent_size(entry),
1887 *max_extent_size);
96303081 1888 continue;
a4820398 1889 }
96303081 1890
53b381b3
DW
1891 /* make sure the space returned is big enough
1892 * to match our requested alignment
1893 */
1894 if (*bytes >= align) {
a4820398 1895 tmp = entry->offset - ctl->start + align - 1;
47c5713f 1896 tmp = div64_u64(tmp, align);
53b381b3
DW
1897 tmp = tmp * align + ctl->start;
1898 align_off = tmp - entry->offset;
1899 } else {
1900 align_off = 0;
1901 tmp = entry->offset;
1902 }
1903
a4820398 1904 if (entry->bytes < *bytes + align_off) {
ad22cf6e
JB
1905 *max_extent_size = max(get_max_extent_size(entry),
1906 *max_extent_size);
53b381b3 1907 continue;
a4820398 1908 }
53b381b3 1909
96303081 1910 if (entry->bitmap) {
a4820398
MX
1911 u64 size = *bytes;
1912
0584f718 1913 ret = search_bitmap(ctl, entry, &tmp, &size, true);
53b381b3
DW
1914 if (!ret) {
1915 *offset = tmp;
a4820398 1916 *bytes = size;
96303081 1917 return entry;
ad22cf6e
JB
1918 } else {
1919 *max_extent_size =
1920 max(get_max_extent_size(entry),
1921 *max_extent_size);
53b381b3 1922 }
96303081
JB
1923 continue;
1924 }
1925
53b381b3
DW
1926 *offset = tmp;
1927 *bytes = entry->bytes - align_off;
96303081
JB
1928 return entry;
1929 }
a4820398 1930out:
96303081
JB
1931 return NULL;
1932}
1933
34d52cb6 1934static void add_new_bitmap(struct btrfs_free_space_ctl *ctl,
96303081
JB
1935 struct btrfs_free_space *info, u64 offset)
1936{
34d52cb6 1937 info->offset = offset_to_bitmap(ctl, offset);
f019f426 1938 info->bytes = 0;
dfb79ddb 1939 info->bitmap_extents = 0;
f2d0f676 1940 INIT_LIST_HEAD(&info->list);
34d52cb6
LZ
1941 link_free_space(ctl, info);
1942 ctl->total_bitmaps++;
fa598b06 1943 recalculate_thresholds(ctl);
96303081
JB
1944}
1945
34d52cb6 1946static void free_bitmap(struct btrfs_free_space_ctl *ctl,
edf6e2d1
LZ
1947 struct btrfs_free_space *bitmap_info)
1948{
27f0afc7
DZ
1949 /*
1950 * Normally when this is called, the bitmap is completely empty. However,
1951 * if we are blowing up the free space cache for one reason or another
1952 * via __btrfs_remove_free_space_cache(), then it may not be freed and
1953 * we may leave stats on the table.
1954 */
1955 if (bitmap_info->bytes && !btrfs_free_space_trimmed(bitmap_info)) {
1956 ctl->discardable_extents[BTRFS_STAT_CURR] -=
1957 bitmap_info->bitmap_extents;
1958 ctl->discardable_bytes[BTRFS_STAT_CURR] -= bitmap_info->bytes;
1959
1960 }
34d52cb6 1961 unlink_free_space(ctl, bitmap_info);
3acd4850 1962 kmem_cache_free(btrfs_free_space_bitmap_cachep, bitmap_info->bitmap);
dc89e982 1963 kmem_cache_free(btrfs_free_space_cachep, bitmap_info);
34d52cb6 1964 ctl->total_bitmaps--;
fa598b06 1965 recalculate_thresholds(ctl);
edf6e2d1
LZ
1966}
1967
34d52cb6 1968static noinline int remove_from_bitmap(struct btrfs_free_space_ctl *ctl,
96303081
JB
1969 struct btrfs_free_space *bitmap_info,
1970 u64 *offset, u64 *bytes)
1971{
1972 u64 end;
6606bb97
JB
1973 u64 search_start, search_bytes;
1974 int ret;
96303081
JB
1975
1976again:
34d52cb6 1977 end = bitmap_info->offset + (u64)(BITS_PER_BITMAP * ctl->unit) - 1;
96303081 1978
6606bb97 1979 /*
bdb7d303
JB
1980 * We need to search for bits in this bitmap. We could only cover some
1981 * of the extent in this bitmap thanks to how we add space, so we need
1982 * to search for as much as it as we can and clear that amount, and then
1983 * go searching for the next bit.
6606bb97
JB
1984 */
1985 search_start = *offset;
bdb7d303 1986 search_bytes = ctl->unit;
13dbc089 1987 search_bytes = min(search_bytes, end - search_start + 1);
0584f718
JB
1988 ret = search_bitmap(ctl, bitmap_info, &search_start, &search_bytes,
1989 false);
b50c6e25
JB
1990 if (ret < 0 || search_start != *offset)
1991 return -EINVAL;
6606bb97 1992
bdb7d303
JB
1993 /* We may have found more bits than what we need */
1994 search_bytes = min(search_bytes, *bytes);
1995
1996 /* Cannot clear past the end of the bitmap */
1997 search_bytes = min(search_bytes, end - search_start + 1);
1998
1999 bitmap_clear_bits(ctl, bitmap_info, search_start, search_bytes);
2000 *offset += search_bytes;
2001 *bytes -= search_bytes;
96303081
JB
2002
2003 if (*bytes) {
6606bb97 2004 struct rb_node *next = rb_next(&bitmap_info->offset_index);
edf6e2d1 2005 if (!bitmap_info->bytes)
34d52cb6 2006 free_bitmap(ctl, bitmap_info);
96303081 2007
6606bb97
JB
2008 /*
2009 * no entry after this bitmap, but we still have bytes to
2010 * remove, so something has gone wrong.
2011 */
2012 if (!next)
96303081
JB
2013 return -EINVAL;
2014
6606bb97
JB
2015 bitmap_info = rb_entry(next, struct btrfs_free_space,
2016 offset_index);
2017
2018 /*
2019 * if the next entry isn't a bitmap we need to return to let the
2020 * extent stuff do its work.
2021 */
96303081
JB
2022 if (!bitmap_info->bitmap)
2023 return -EAGAIN;
2024
6606bb97
JB
2025 /*
2026 * Ok the next item is a bitmap, but it may not actually hold
2027 * the information for the rest of this free space stuff, so
2028 * look for it, and if we don't find it return so we can try
2029 * everything over again.
2030 */
2031 search_start = *offset;
bdb7d303 2032 search_bytes = ctl->unit;
34d52cb6 2033 ret = search_bitmap(ctl, bitmap_info, &search_start,
0584f718 2034 &search_bytes, false);
6606bb97
JB
2035 if (ret < 0 || search_start != *offset)
2036 return -EAGAIN;
2037
96303081 2038 goto again;
edf6e2d1 2039 } else if (!bitmap_info->bytes)
34d52cb6 2040 free_bitmap(ctl, bitmap_info);
96303081
JB
2041
2042 return 0;
2043}
2044
2cdc342c
JB
2045static u64 add_bytes_to_bitmap(struct btrfs_free_space_ctl *ctl,
2046 struct btrfs_free_space *info, u64 offset,
da080fe1 2047 u64 bytes, enum btrfs_trim_state trim_state)
2cdc342c
JB
2048{
2049 u64 bytes_to_set = 0;
2050 u64 end;
2051
da080fe1
DZ
2052 /*
2053 * This is a tradeoff to make bitmap trim state minimal. We mark the
2054 * whole bitmap untrimmed if at any point we add untrimmed regions.
2055 */
dfb79ddb 2056 if (trim_state == BTRFS_TRIM_STATE_UNTRIMMED) {
5dc7c10b 2057 if (btrfs_free_space_trimmed(info)) {
dfb79ddb
DZ
2058 ctl->discardable_extents[BTRFS_STAT_CURR] +=
2059 info->bitmap_extents;
5dc7c10b
DZ
2060 ctl->discardable_bytes[BTRFS_STAT_CURR] += info->bytes;
2061 }
da080fe1 2062 info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
dfb79ddb 2063 }
da080fe1 2064
2cdc342c
JB
2065 end = info->offset + (u64)(BITS_PER_BITMAP * ctl->unit);
2066
2067 bytes_to_set = min(end - offset, bytes);
2068
2069 bitmap_set_bits(ctl, info, offset, bytes_to_set);
2070
cef40483
JB
2071 /*
2072 * We set some bytes, we have no idea what the max extent size is
2073 * anymore.
2074 */
2075 info->max_extent_size = 0;
2076
2cdc342c
JB
2077 return bytes_to_set;
2078
2079}
2080
34d52cb6
LZ
2081static bool use_bitmap(struct btrfs_free_space_ctl *ctl,
2082 struct btrfs_free_space *info)
96303081 2083{
32da5386 2084 struct btrfs_block_group *block_group = ctl->private;
0b246afa 2085 struct btrfs_fs_info *fs_info = block_group->fs_info;
d0bd4560
JB
2086 bool forced = false;
2087
2088#ifdef CONFIG_BTRFS_DEBUG
2ff7e61e 2089 if (btrfs_should_fragment_free_space(block_group))
d0bd4560
JB
2090 forced = true;
2091#endif
96303081 2092
5d90c5c7
DZ
2093 /* This is a way to reclaim large regions from the bitmaps. */
2094 if (!forced && info->bytes >= FORCE_EXTENT_THRESHOLD)
2095 return false;
2096
96303081
JB
2097 /*
2098 * If we are below the extents threshold then we can add this as an
2099 * extent, and don't have to deal with the bitmap
2100 */
d0bd4560 2101 if (!forced && ctl->free_extents < ctl->extents_thresh) {
32cb0840
JB
2102 /*
2103 * If this block group has some small extents we don't want to
2104 * use up all of our free slots in the cache with them, we want
01327610 2105 * to reserve them to larger extents, however if we have plenty
32cb0840
JB
2106 * of cache left then go ahead an dadd them, no sense in adding
2107 * the overhead of a bitmap if we don't have to.
2108 */
f9bb615a
DZ
2109 if (info->bytes <= fs_info->sectorsize * 8) {
2110 if (ctl->free_extents * 3 <= ctl->extents_thresh)
34d52cb6 2111 return false;
32cb0840 2112 } else {
34d52cb6 2113 return false;
32cb0840
JB
2114 }
2115 }
96303081
JB
2116
2117 /*
dde5740f
JB
2118 * The original block groups from mkfs can be really small, like 8
2119 * megabytes, so don't bother with a bitmap for those entries. However
2120 * some block groups can be smaller than what a bitmap would cover but
2121 * are still large enough that they could overflow the 32k memory limit,
2122 * so allow those block groups to still be allowed to have a bitmap
2123 * entry.
96303081 2124 */
b3470b5d 2125 if (((BITS_PER_BITMAP * ctl->unit) >> 1) > block_group->length)
34d52cb6
LZ
2126 return false;
2127
2128 return true;
2129}
2130
20e5506b 2131static const struct btrfs_free_space_op free_space_op = {
2cdc342c
JB
2132 .use_bitmap = use_bitmap,
2133};
2134
34d52cb6
LZ
2135static int insert_into_bitmap(struct btrfs_free_space_ctl *ctl,
2136 struct btrfs_free_space *info)
2137{
2138 struct btrfs_free_space *bitmap_info;
32da5386 2139 struct btrfs_block_group *block_group = NULL;
34d52cb6 2140 int added = 0;
2cdc342c 2141 u64 bytes, offset, bytes_added;
da080fe1 2142 enum btrfs_trim_state trim_state;
34d52cb6 2143 int ret;
96303081
JB
2144
2145 bytes = info->bytes;
2146 offset = info->offset;
da080fe1 2147 trim_state = info->trim_state;
96303081 2148
34d52cb6
LZ
2149 if (!ctl->op->use_bitmap(ctl, info))
2150 return 0;
2151
2cdc342c
JB
2152 if (ctl->op == &free_space_op)
2153 block_group = ctl->private;
38e87880 2154again:
2cdc342c
JB
2155 /*
2156 * Since we link bitmaps right into the cluster we need to see if we
2157 * have a cluster here, and if so and it has our bitmap we need to add
2158 * the free space to that bitmap.
2159 */
2160 if (block_group && !list_empty(&block_group->cluster_list)) {
2161 struct btrfs_free_cluster *cluster;
2162 struct rb_node *node;
2163 struct btrfs_free_space *entry;
2164
2165 cluster = list_entry(block_group->cluster_list.next,
2166 struct btrfs_free_cluster,
2167 block_group_list);
2168 spin_lock(&cluster->lock);
2169 node = rb_first(&cluster->root);
2170 if (!node) {
2171 spin_unlock(&cluster->lock);
38e87880 2172 goto no_cluster_bitmap;
2cdc342c
JB
2173 }
2174
2175 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2176 if (!entry->bitmap) {
2177 spin_unlock(&cluster->lock);
38e87880 2178 goto no_cluster_bitmap;
2cdc342c
JB
2179 }
2180
2181 if (entry->offset == offset_to_bitmap(ctl, offset)) {
da080fe1
DZ
2182 bytes_added = add_bytes_to_bitmap(ctl, entry, offset,
2183 bytes, trim_state);
2cdc342c
JB
2184 bytes -= bytes_added;
2185 offset += bytes_added;
2186 }
2187 spin_unlock(&cluster->lock);
2188 if (!bytes) {
2189 ret = 1;
2190 goto out;
2191 }
2192 }
38e87880
CM
2193
2194no_cluster_bitmap:
34d52cb6 2195 bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
96303081
JB
2196 1, 0);
2197 if (!bitmap_info) {
b12d6869 2198 ASSERT(added == 0);
96303081
JB
2199 goto new_bitmap;
2200 }
2201
da080fe1
DZ
2202 bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes,
2203 trim_state);
2cdc342c
JB
2204 bytes -= bytes_added;
2205 offset += bytes_added;
2206 added = 0;
96303081
JB
2207
2208 if (!bytes) {
2209 ret = 1;
2210 goto out;
2211 } else
2212 goto again;
2213
2214new_bitmap:
2215 if (info && info->bitmap) {
34d52cb6 2216 add_new_bitmap(ctl, info, offset);
96303081
JB
2217 added = 1;
2218 info = NULL;
2219 goto again;
2220 } else {
34d52cb6 2221 spin_unlock(&ctl->tree_lock);
96303081
JB
2222
2223 /* no pre-allocated info, allocate a new one */
2224 if (!info) {
dc89e982
JB
2225 info = kmem_cache_zalloc(btrfs_free_space_cachep,
2226 GFP_NOFS);
96303081 2227 if (!info) {
34d52cb6 2228 spin_lock(&ctl->tree_lock);
96303081
JB
2229 ret = -ENOMEM;
2230 goto out;
2231 }
2232 }
2233
2234 /* allocate the bitmap */
3acd4850
CL
2235 info->bitmap = kmem_cache_zalloc(btrfs_free_space_bitmap_cachep,
2236 GFP_NOFS);
da080fe1 2237 info->trim_state = BTRFS_TRIM_STATE_TRIMMED;
34d52cb6 2238 spin_lock(&ctl->tree_lock);
96303081
JB
2239 if (!info->bitmap) {
2240 ret = -ENOMEM;
2241 goto out;
2242 }
2243 goto again;
2244 }
2245
2246out:
2247 if (info) {
3acd4850
CL
2248 if (info->bitmap)
2249 kmem_cache_free(btrfs_free_space_bitmap_cachep,
2250 info->bitmap);
dc89e982 2251 kmem_cache_free(btrfs_free_space_cachep, info);
96303081 2252 }
0f9dd46c
JB
2253
2254 return ret;
2255}
2256
a7ccb255
DZ
2257/*
2258 * Free space merging rules:
2259 * 1) Merge trimmed areas together
2260 * 2) Let untrimmed areas coalesce with trimmed areas
2261 * 3) Always pull neighboring regions from bitmaps
2262 *
2263 * The above rules are for when we merge free space based on btrfs_trim_state.
2264 * Rules 2 and 3 are subtle because they are suboptimal, but are done for the
2265 * same reason: to promote larger extent regions which makes life easier for
2266 * find_free_extent(). Rule 2 enables coalescing based on the common path
2267 * being returning free space from btrfs_finish_extent_commit(). So when free
2268 * space is trimmed, it will prevent aggregating trimmed new region and
2269 * untrimmed regions in the rb_tree. Rule 3 is purely to obtain larger extents
2270 * and provide find_free_extent() with the largest extents possible hoping for
2271 * the reuse path.
2272 */
945d8962 2273static bool try_merge_free_space(struct btrfs_free_space_ctl *ctl,
f333adb5 2274 struct btrfs_free_space *info, bool update_stat)
0f9dd46c 2275{
bf53d468 2276 struct btrfs_free_space *left_info = NULL;
120d66ee
LZ
2277 struct btrfs_free_space *right_info;
2278 bool merged = false;
2279 u64 offset = info->offset;
2280 u64 bytes = info->bytes;
a7ccb255 2281 const bool is_trimmed = btrfs_free_space_trimmed(info);
6226cb0a 2282
0f9dd46c
JB
2283 /*
2284 * first we want to see if there is free space adjacent to the range we
2285 * are adding, if there is remove that struct and add a new one to
2286 * cover the entire range
2287 */
34d52cb6 2288 right_info = tree_search_offset(ctl, offset + bytes, 0, 0);
96303081
JB
2289 if (right_info && rb_prev(&right_info->offset_index))
2290 left_info = rb_entry(rb_prev(&right_info->offset_index),
2291 struct btrfs_free_space, offset_index);
bf53d468 2292 else if (!right_info)
34d52cb6 2293 left_info = tree_search_offset(ctl, offset - 1, 0, 0);
0f9dd46c 2294
a7ccb255
DZ
2295 /* See try_merge_free_space() comment. */
2296 if (right_info && !right_info->bitmap &&
2297 (!is_trimmed || btrfs_free_space_trimmed(right_info))) {
f333adb5 2298 if (update_stat)
34d52cb6 2299 unlink_free_space(ctl, right_info);
f333adb5 2300 else
34d52cb6 2301 __unlink_free_space(ctl, right_info);
6226cb0a 2302 info->bytes += right_info->bytes;
dc89e982 2303 kmem_cache_free(btrfs_free_space_cachep, right_info);
120d66ee 2304 merged = true;
0f9dd46c
JB
2305 }
2306
a7ccb255 2307 /* See try_merge_free_space() comment. */
96303081 2308 if (left_info && !left_info->bitmap &&
a7ccb255
DZ
2309 left_info->offset + left_info->bytes == offset &&
2310 (!is_trimmed || btrfs_free_space_trimmed(left_info))) {
f333adb5 2311 if (update_stat)
34d52cb6 2312 unlink_free_space(ctl, left_info);
f333adb5 2313 else
34d52cb6 2314 __unlink_free_space(ctl, left_info);
6226cb0a
JB
2315 info->offset = left_info->offset;
2316 info->bytes += left_info->bytes;
dc89e982 2317 kmem_cache_free(btrfs_free_space_cachep, left_info);
120d66ee 2318 merged = true;
0f9dd46c
JB
2319 }
2320
120d66ee
LZ
2321 return merged;
2322}
2323
20005523
FM
2324static bool steal_from_bitmap_to_end(struct btrfs_free_space_ctl *ctl,
2325 struct btrfs_free_space *info,
2326 bool update_stat)
2327{
2328 struct btrfs_free_space *bitmap;
2329 unsigned long i;
2330 unsigned long j;
2331 const u64 end = info->offset + info->bytes;
2332 const u64 bitmap_offset = offset_to_bitmap(ctl, end);
2333 u64 bytes;
2334
2335 bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0);
2336 if (!bitmap)
2337 return false;
2338
2339 i = offset_to_bit(bitmap->offset, ctl->unit, end);
2340 j = find_next_zero_bit(bitmap->bitmap, BITS_PER_BITMAP, i);
2341 if (j == i)
2342 return false;
2343 bytes = (j - i) * ctl->unit;
2344 info->bytes += bytes;
2345
a7ccb255
DZ
2346 /* See try_merge_free_space() comment. */
2347 if (!btrfs_free_space_trimmed(bitmap))
2348 info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2349
20005523
FM
2350 if (update_stat)
2351 bitmap_clear_bits(ctl, bitmap, end, bytes);
2352 else
2353 __bitmap_clear_bits(ctl, bitmap, end, bytes);
2354
2355 if (!bitmap->bytes)
2356 free_bitmap(ctl, bitmap);
2357
2358 return true;
2359}
2360
2361static bool steal_from_bitmap_to_front(struct btrfs_free_space_ctl *ctl,
2362 struct btrfs_free_space *info,
2363 bool update_stat)
2364{
2365 struct btrfs_free_space *bitmap;
2366 u64 bitmap_offset;
2367 unsigned long i;
2368 unsigned long j;
2369 unsigned long prev_j;
2370 u64 bytes;
2371
2372 bitmap_offset = offset_to_bitmap(ctl, info->offset);
2373 /* If we're on a boundary, try the previous logical bitmap. */
2374 if (bitmap_offset == info->offset) {
2375 if (info->offset == 0)
2376 return false;
2377 bitmap_offset = offset_to_bitmap(ctl, info->offset - 1);
2378 }
2379
2380 bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0);
2381 if (!bitmap)
2382 return false;
2383
2384 i = offset_to_bit(bitmap->offset, ctl->unit, info->offset) - 1;
2385 j = 0;
2386 prev_j = (unsigned long)-1;
2387 for_each_clear_bit_from(j, bitmap->bitmap, BITS_PER_BITMAP) {
2388 if (j > i)
2389 break;
2390 prev_j = j;
2391 }
2392 if (prev_j == i)
2393 return false;
2394
2395 if (prev_j == (unsigned long)-1)
2396 bytes = (i + 1) * ctl->unit;
2397 else
2398 bytes = (i - prev_j) * ctl->unit;
2399
2400 info->offset -= bytes;
2401 info->bytes += bytes;
2402
a7ccb255
DZ
2403 /* See try_merge_free_space() comment. */
2404 if (!btrfs_free_space_trimmed(bitmap))
2405 info->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2406
20005523
FM
2407 if (update_stat)
2408 bitmap_clear_bits(ctl, bitmap, info->offset, bytes);
2409 else
2410 __bitmap_clear_bits(ctl, bitmap, info->offset, bytes);
2411
2412 if (!bitmap->bytes)
2413 free_bitmap(ctl, bitmap);
2414
2415 return true;
2416}
2417
2418/*
2419 * We prefer always to allocate from extent entries, both for clustered and
2420 * non-clustered allocation requests. So when attempting to add a new extent
2421 * entry, try to see if there's adjacent free space in bitmap entries, and if
2422 * there is, migrate that space from the bitmaps to the extent.
2423 * Like this we get better chances of satisfying space allocation requests
2424 * because we attempt to satisfy them based on a single cache entry, and never
2425 * on 2 or more entries - even if the entries represent a contiguous free space
2426 * region (e.g. 1 extent entry + 1 bitmap entry starting where the extent entry
2427 * ends).
2428 */
2429static void steal_from_bitmap(struct btrfs_free_space_ctl *ctl,
2430 struct btrfs_free_space *info,
2431 bool update_stat)
2432{
2433 /*
2434 * Only work with disconnected entries, as we can change their offset,
2435 * and must be extent entries.
2436 */
2437 ASSERT(!info->bitmap);
2438 ASSERT(RB_EMPTY_NODE(&info->offset_index));
2439
2440 if (ctl->total_bitmaps > 0) {
2441 bool stole_end;
2442 bool stole_front = false;
2443
2444 stole_end = steal_from_bitmap_to_end(ctl, info, update_stat);
2445 if (ctl->total_bitmaps > 0)
2446 stole_front = steal_from_bitmap_to_front(ctl, info,
2447 update_stat);
2448
2449 if (stole_end || stole_front)
2450 try_merge_free_space(ctl, info, update_stat);
2451 }
2452}
2453
ab8d0fc4
JM
2454int __btrfs_add_free_space(struct btrfs_fs_info *fs_info,
2455 struct btrfs_free_space_ctl *ctl,
a7ccb255
DZ
2456 u64 offset, u64 bytes,
2457 enum btrfs_trim_state trim_state)
120d66ee 2458{
b0643e59 2459 struct btrfs_block_group *block_group = ctl->private;
120d66ee
LZ
2460 struct btrfs_free_space *info;
2461 int ret = 0;
7fe6d45e 2462 u64 filter_bytes = bytes;
120d66ee 2463
dc89e982 2464 info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
120d66ee
LZ
2465 if (!info)
2466 return -ENOMEM;
2467
2468 info->offset = offset;
2469 info->bytes = bytes;
a7ccb255 2470 info->trim_state = trim_state;
20005523 2471 RB_CLEAR_NODE(&info->offset_index);
120d66ee 2472
34d52cb6 2473 spin_lock(&ctl->tree_lock);
120d66ee 2474
34d52cb6 2475 if (try_merge_free_space(ctl, info, true))
120d66ee
LZ
2476 goto link;
2477
2478 /*
2479 * There was no extent directly to the left or right of this new
2480 * extent then we know we're going to have to allocate a new extent, so
2481 * before we do that see if we need to drop this into a bitmap
2482 */
34d52cb6 2483 ret = insert_into_bitmap(ctl, info);
120d66ee
LZ
2484 if (ret < 0) {
2485 goto out;
2486 } else if (ret) {
2487 ret = 0;
2488 goto out;
2489 }
2490link:
20005523
FM
2491 /*
2492 * Only steal free space from adjacent bitmaps if we're sure we're not
2493 * going to add the new free space to existing bitmap entries - because
2494 * that would mean unnecessary work that would be reverted. Therefore
2495 * attempt to steal space from bitmaps if we're adding an extent entry.
2496 */
2497 steal_from_bitmap(ctl, info, true);
2498
7fe6d45e
DZ
2499 filter_bytes = max(filter_bytes, info->bytes);
2500
34d52cb6 2501 ret = link_free_space(ctl, info);
0f9dd46c 2502 if (ret)
dc89e982 2503 kmem_cache_free(btrfs_free_space_cachep, info);
96303081 2504out:
66b53bae 2505 btrfs_discard_update_discardable(block_group);
34d52cb6 2506 spin_unlock(&ctl->tree_lock);
6226cb0a 2507
0f9dd46c 2508 if (ret) {
ab8d0fc4 2509 btrfs_crit(fs_info, "unable to add free space :%d", ret);
b12d6869 2510 ASSERT(ret != -EEXIST);
0f9dd46c
JB
2511 }
2512
7fe6d45e
DZ
2513 if (trim_state != BTRFS_TRIM_STATE_TRIMMED) {
2514 btrfs_discard_check_filter(block_group, filter_bytes);
b0643e59 2515 btrfs_discard_queue_work(&fs_info->discard_ctl, block_group);
7fe6d45e 2516 }
b0643e59 2517
0f9dd46c
JB
2518 return ret;
2519}
2520
32da5386 2521int btrfs_add_free_space(struct btrfs_block_group *block_group,
478b4d9f
JB
2522 u64 bytenr, u64 size)
2523{
a7ccb255
DZ
2524 enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2525
2526 if (btrfs_test_opt(block_group->fs_info, DISCARD_SYNC))
2527 trim_state = BTRFS_TRIM_STATE_TRIMMED;
2528
478b4d9f
JB
2529 return __btrfs_add_free_space(block_group->fs_info,
2530 block_group->free_space_ctl,
a7ccb255 2531 bytenr, size, trim_state);
478b4d9f
JB
2532}
2533
b0643e59
DZ
2534/*
2535 * This is a subtle distinction because when adding free space back in general,
2536 * we want it to be added as untrimmed for async. But in the case where we add
2537 * it on loading of a block group, we want to consider it trimmed.
2538 */
2539int btrfs_add_free_space_async_trimmed(struct btrfs_block_group *block_group,
2540 u64 bytenr, u64 size)
2541{
2542 enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
2543
2544 if (btrfs_test_opt(block_group->fs_info, DISCARD_SYNC) ||
2545 btrfs_test_opt(block_group->fs_info, DISCARD_ASYNC))
2546 trim_state = BTRFS_TRIM_STATE_TRIMMED;
2547
2548 return __btrfs_add_free_space(block_group->fs_info,
2549 block_group->free_space_ctl,
2550 bytenr, size, trim_state);
2551}
2552
32da5386 2553int btrfs_remove_free_space(struct btrfs_block_group *block_group,
6226cb0a 2554 u64 offset, u64 bytes)
0f9dd46c 2555{
34d52cb6 2556 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
0f9dd46c 2557 struct btrfs_free_space *info;
b0175117
JB
2558 int ret;
2559 bool re_search = false;
0f9dd46c 2560
34d52cb6 2561 spin_lock(&ctl->tree_lock);
6226cb0a 2562
96303081 2563again:
b0175117 2564 ret = 0;
bdb7d303
JB
2565 if (!bytes)
2566 goto out_lock;
2567
34d52cb6 2568 info = tree_search_offset(ctl, offset, 0, 0);
96303081 2569 if (!info) {
6606bb97
JB
2570 /*
2571 * oops didn't find an extent that matched the space we wanted
2572 * to remove, look for a bitmap instead
2573 */
34d52cb6 2574 info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
6606bb97
JB
2575 1, 0);
2576 if (!info) {
b0175117
JB
2577 /*
2578 * If we found a partial bit of our free space in a
2579 * bitmap but then couldn't find the other part this may
2580 * be a problem, so WARN about it.
24a70313 2581 */
b0175117 2582 WARN_ON(re_search);
6606bb97
JB
2583 goto out_lock;
2584 }
96303081
JB
2585 }
2586
b0175117 2587 re_search = false;
bdb7d303 2588 if (!info->bitmap) {
34d52cb6 2589 unlink_free_space(ctl, info);
bdb7d303
JB
2590 if (offset == info->offset) {
2591 u64 to_free = min(bytes, info->bytes);
2592
2593 info->bytes -= to_free;
2594 info->offset += to_free;
2595 if (info->bytes) {
2596 ret = link_free_space(ctl, info);
2597 WARN_ON(ret);
2598 } else {
2599 kmem_cache_free(btrfs_free_space_cachep, info);
2600 }
0f9dd46c 2601
bdb7d303
JB
2602 offset += to_free;
2603 bytes -= to_free;
2604 goto again;
2605 } else {
2606 u64 old_end = info->bytes + info->offset;
9b49c9b9 2607
bdb7d303 2608 info->bytes = offset - info->offset;
34d52cb6 2609 ret = link_free_space(ctl, info);
96303081
JB
2610 WARN_ON(ret);
2611 if (ret)
2612 goto out_lock;
96303081 2613
bdb7d303
JB
2614 /* Not enough bytes in this entry to satisfy us */
2615 if (old_end < offset + bytes) {
2616 bytes -= old_end - offset;
2617 offset = old_end;
2618 goto again;
2619 } else if (old_end == offset + bytes) {
2620 /* all done */
2621 goto out_lock;
2622 }
2623 spin_unlock(&ctl->tree_lock);
2624
a7ccb255
DZ
2625 ret = __btrfs_add_free_space(block_group->fs_info, ctl,
2626 offset + bytes,
2627 old_end - (offset + bytes),
2628 info->trim_state);
bdb7d303
JB
2629 WARN_ON(ret);
2630 goto out;
2631 }
0f9dd46c 2632 }
96303081 2633
34d52cb6 2634 ret = remove_from_bitmap(ctl, info, &offset, &bytes);
b0175117
JB
2635 if (ret == -EAGAIN) {
2636 re_search = true;
96303081 2637 goto again;
b0175117 2638 }
96303081 2639out_lock:
66b53bae 2640 btrfs_discard_update_discardable(block_group);
34d52cb6 2641 spin_unlock(&ctl->tree_lock);
0f9dd46c 2642out:
25179201
JB
2643 return ret;
2644}
2645
32da5386 2646void btrfs_dump_free_space(struct btrfs_block_group *block_group,
0f9dd46c
JB
2647 u64 bytes)
2648{
0b246afa 2649 struct btrfs_fs_info *fs_info = block_group->fs_info;
34d52cb6 2650 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
0f9dd46c
JB
2651 struct btrfs_free_space *info;
2652 struct rb_node *n;
2653 int count = 0;
2654
9084cb6a 2655 spin_lock(&ctl->tree_lock);
34d52cb6 2656 for (n = rb_first(&ctl->free_space_offset); n; n = rb_next(n)) {
0f9dd46c 2657 info = rb_entry(n, struct btrfs_free_space, offset_index);
f6175efa 2658 if (info->bytes >= bytes && !block_group->ro)
0f9dd46c 2659 count++;
0b246afa 2660 btrfs_crit(fs_info, "entry offset %llu, bytes %llu, bitmap %s",
efe120a0 2661 info->offset, info->bytes,
96303081 2662 (info->bitmap) ? "yes" : "no");
0f9dd46c 2663 }
9084cb6a 2664 spin_unlock(&ctl->tree_lock);
0b246afa 2665 btrfs_info(fs_info, "block group has cluster?: %s",
96303081 2666 list_empty(&block_group->cluster_list) ? "no" : "yes");
0b246afa 2667 btrfs_info(fs_info,
efe120a0 2668 "%d blocks of free space at or bigger than bytes is", count);
0f9dd46c
JB
2669}
2670
cd79909b
JB
2671void btrfs_init_free_space_ctl(struct btrfs_block_group *block_group,
2672 struct btrfs_free_space_ctl *ctl)
0f9dd46c 2673{
0b246afa 2674 struct btrfs_fs_info *fs_info = block_group->fs_info;
0f9dd46c 2675
34d52cb6 2676 spin_lock_init(&ctl->tree_lock);
0b246afa 2677 ctl->unit = fs_info->sectorsize;
b3470b5d 2678 ctl->start = block_group->start;
34d52cb6
LZ
2679 ctl->private = block_group;
2680 ctl->op = &free_space_op;
55507ce3
FM
2681 INIT_LIST_HEAD(&ctl->trimming_ranges);
2682 mutex_init(&ctl->cache_writeout_mutex);
0f9dd46c 2683
34d52cb6
LZ
2684 /*
2685 * we only want to have 32k of ram per block group for keeping
2686 * track of free space, and if we pass 1/2 of that we want to
2687 * start converting things over to using bitmaps
2688 */
ee22184b 2689 ctl->extents_thresh = (SZ_32K / 2) / sizeof(struct btrfs_free_space);
0f9dd46c
JB
2690}
2691
fa9c0d79
CM
2692/*
2693 * for a given cluster, put all of its extents back into the free
2694 * space cache. If the block group passed doesn't match the block group
2695 * pointed to by the cluster, someone else raced in and freed the
2696 * cluster already. In that case, we just return without changing anything
2697 */
69b0e093 2698static void __btrfs_return_cluster_to_free_space(
32da5386 2699 struct btrfs_block_group *block_group,
fa9c0d79
CM
2700 struct btrfs_free_cluster *cluster)
2701{
34d52cb6 2702 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
fa9c0d79
CM
2703 struct btrfs_free_space *entry;
2704 struct rb_node *node;
2705
2706 spin_lock(&cluster->lock);
2707 if (cluster->block_group != block_group)
2708 goto out;
2709
96303081 2710 cluster->block_group = NULL;
fa9c0d79 2711 cluster->window_start = 0;
96303081 2712 list_del_init(&cluster->block_group_list);
96303081 2713
fa9c0d79 2714 node = rb_first(&cluster->root);
96303081 2715 while (node) {
4e69b598
JB
2716 bool bitmap;
2717
fa9c0d79
CM
2718 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2719 node = rb_next(&entry->offset_index);
2720 rb_erase(&entry->offset_index, &cluster->root);
20005523 2721 RB_CLEAR_NODE(&entry->offset_index);
4e69b598
JB
2722
2723 bitmap = (entry->bitmap != NULL);
20005523 2724 if (!bitmap) {
dfb79ddb 2725 /* Merging treats extents as if they were new */
5dc7c10b 2726 if (!btrfs_free_space_trimmed(entry)) {
dfb79ddb 2727 ctl->discardable_extents[BTRFS_STAT_CURR]--;
5dc7c10b
DZ
2728 ctl->discardable_bytes[BTRFS_STAT_CURR] -=
2729 entry->bytes;
2730 }
dfb79ddb 2731
34d52cb6 2732 try_merge_free_space(ctl, entry, false);
20005523 2733 steal_from_bitmap(ctl, entry, false);
dfb79ddb
DZ
2734
2735 /* As we insert directly, update these statistics */
5dc7c10b 2736 if (!btrfs_free_space_trimmed(entry)) {
dfb79ddb 2737 ctl->discardable_extents[BTRFS_STAT_CURR]++;
5dc7c10b
DZ
2738 ctl->discardable_bytes[BTRFS_STAT_CURR] +=
2739 entry->bytes;
2740 }
20005523 2741 }
34d52cb6 2742 tree_insert_offset(&ctl->free_space_offset,
4e69b598 2743 entry->offset, &entry->offset_index, bitmap);
fa9c0d79 2744 }
6bef4d31 2745 cluster->root = RB_ROOT;
96303081 2746
fa9c0d79
CM
2747out:
2748 spin_unlock(&cluster->lock);
96303081 2749 btrfs_put_block_group(block_group);
fa9c0d79
CM
2750}
2751
48a3b636
ES
2752static void __btrfs_remove_free_space_cache_locked(
2753 struct btrfs_free_space_ctl *ctl)
0f9dd46c
JB
2754{
2755 struct btrfs_free_space *info;
2756 struct rb_node *node;
581bb050 2757
581bb050
LZ
2758 while ((node = rb_last(&ctl->free_space_offset)) != NULL) {
2759 info = rb_entry(node, struct btrfs_free_space, offset_index);
9b90f513
JB
2760 if (!info->bitmap) {
2761 unlink_free_space(ctl, info);
2762 kmem_cache_free(btrfs_free_space_cachep, info);
2763 } else {
2764 free_bitmap(ctl, info);
2765 }
351810c1
DS
2766
2767 cond_resched_lock(&ctl->tree_lock);
581bb050 2768 }
09655373
CM
2769}
2770
2771void __btrfs_remove_free_space_cache(struct btrfs_free_space_ctl *ctl)
2772{
2773 spin_lock(&ctl->tree_lock);
2774 __btrfs_remove_free_space_cache_locked(ctl);
27f0afc7 2775 if (ctl->private)
66b53bae 2776 btrfs_discard_update_discardable(ctl->private);
581bb050
LZ
2777 spin_unlock(&ctl->tree_lock);
2778}
2779
32da5386 2780void btrfs_remove_free_space_cache(struct btrfs_block_group *block_group)
581bb050
LZ
2781{
2782 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
fa9c0d79 2783 struct btrfs_free_cluster *cluster;
96303081 2784 struct list_head *head;
0f9dd46c 2785
34d52cb6 2786 spin_lock(&ctl->tree_lock);
96303081
JB
2787 while ((head = block_group->cluster_list.next) !=
2788 &block_group->cluster_list) {
2789 cluster = list_entry(head, struct btrfs_free_cluster,
2790 block_group_list);
fa9c0d79
CM
2791
2792 WARN_ON(cluster->block_group != block_group);
2793 __btrfs_return_cluster_to_free_space(block_group, cluster);
351810c1
DS
2794
2795 cond_resched_lock(&ctl->tree_lock);
fa9c0d79 2796 }
09655373 2797 __btrfs_remove_free_space_cache_locked(ctl);
66b53bae 2798 btrfs_discard_update_discardable(block_group);
34d52cb6 2799 spin_unlock(&ctl->tree_lock);
fa9c0d79 2800
0f9dd46c
JB
2801}
2802
6e80d4f8
DZ
2803/**
2804 * btrfs_is_free_space_trimmed - see if everything is trimmed
2805 * @block_group: block_group of interest
2806 *
2807 * Walk @block_group's free space rb_tree to determine if everything is trimmed.
2808 */
2809bool btrfs_is_free_space_trimmed(struct btrfs_block_group *block_group)
2810{
2811 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2812 struct btrfs_free_space *info;
2813 struct rb_node *node;
2814 bool ret = true;
2815
2816 spin_lock(&ctl->tree_lock);
2817 node = rb_first(&ctl->free_space_offset);
2818
2819 while (node) {
2820 info = rb_entry(node, struct btrfs_free_space, offset_index);
2821
2822 if (!btrfs_free_space_trimmed(info)) {
2823 ret = false;
2824 break;
2825 }
2826
2827 node = rb_next(node);
2828 }
2829
2830 spin_unlock(&ctl->tree_lock);
2831 return ret;
2832}
2833
32da5386 2834u64 btrfs_find_space_for_alloc(struct btrfs_block_group *block_group,
a4820398
MX
2835 u64 offset, u64 bytes, u64 empty_size,
2836 u64 *max_extent_size)
0f9dd46c 2837{
34d52cb6 2838 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
9ddf648f
DZ
2839 struct btrfs_discard_ctl *discard_ctl =
2840 &block_group->fs_info->discard_ctl;
6226cb0a 2841 struct btrfs_free_space *entry = NULL;
96303081 2842 u64 bytes_search = bytes + empty_size;
6226cb0a 2843 u64 ret = 0;
53b381b3
DW
2844 u64 align_gap = 0;
2845 u64 align_gap_len = 0;
a7ccb255 2846 enum btrfs_trim_state align_gap_trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
0f9dd46c 2847
34d52cb6 2848 spin_lock(&ctl->tree_lock);
53b381b3 2849 entry = find_free_space(ctl, &offset, &bytes_search,
a4820398 2850 block_group->full_stripe_len, max_extent_size);
6226cb0a 2851 if (!entry)
96303081
JB
2852 goto out;
2853
2854 ret = offset;
2855 if (entry->bitmap) {
34d52cb6 2856 bitmap_clear_bits(ctl, entry, offset, bytes);
9ddf648f
DZ
2857
2858 if (!btrfs_free_space_trimmed(entry))
2859 atomic64_add(bytes, &discard_ctl->discard_bytes_saved);
2860
edf6e2d1 2861 if (!entry->bytes)
34d52cb6 2862 free_bitmap(ctl, entry);
96303081 2863 } else {
34d52cb6 2864 unlink_free_space(ctl, entry);
53b381b3
DW
2865 align_gap_len = offset - entry->offset;
2866 align_gap = entry->offset;
a7ccb255 2867 align_gap_trim_state = entry->trim_state;
53b381b3 2868
9ddf648f
DZ
2869 if (!btrfs_free_space_trimmed(entry))
2870 atomic64_add(bytes, &discard_ctl->discard_bytes_saved);
2871
53b381b3
DW
2872 entry->offset = offset + bytes;
2873 WARN_ON(entry->bytes < bytes + align_gap_len);
2874
2875 entry->bytes -= bytes + align_gap_len;
6226cb0a 2876 if (!entry->bytes)
dc89e982 2877 kmem_cache_free(btrfs_free_space_cachep, entry);
6226cb0a 2878 else
34d52cb6 2879 link_free_space(ctl, entry);
6226cb0a 2880 }
96303081 2881out:
66b53bae 2882 btrfs_discard_update_discardable(block_group);
34d52cb6 2883 spin_unlock(&ctl->tree_lock);
817d52f8 2884
53b381b3 2885 if (align_gap_len)
ab8d0fc4 2886 __btrfs_add_free_space(block_group->fs_info, ctl,
a7ccb255
DZ
2887 align_gap, align_gap_len,
2888 align_gap_trim_state);
0f9dd46c
JB
2889 return ret;
2890}
fa9c0d79
CM
2891
2892/*
2893 * given a cluster, put all of its extents back into the free space
2894 * cache. If a block group is passed, this function will only free
2895 * a cluster that belongs to the passed block group.
2896 *
2897 * Otherwise, it'll get a reference on the block group pointed to by the
2898 * cluster and remove the cluster from it.
2899 */
69b0e093 2900void btrfs_return_cluster_to_free_space(
32da5386 2901 struct btrfs_block_group *block_group,
fa9c0d79
CM
2902 struct btrfs_free_cluster *cluster)
2903{
34d52cb6 2904 struct btrfs_free_space_ctl *ctl;
fa9c0d79
CM
2905
2906 /* first, get a safe pointer to the block group */
2907 spin_lock(&cluster->lock);
2908 if (!block_group) {
2909 block_group = cluster->block_group;
2910 if (!block_group) {
2911 spin_unlock(&cluster->lock);
69b0e093 2912 return;
fa9c0d79
CM
2913 }
2914 } else if (cluster->block_group != block_group) {
2915 /* someone else has already freed it don't redo their work */
2916 spin_unlock(&cluster->lock);
69b0e093 2917 return;
fa9c0d79 2918 }
b5790d51 2919 btrfs_get_block_group(block_group);
fa9c0d79
CM
2920 spin_unlock(&cluster->lock);
2921
34d52cb6
LZ
2922 ctl = block_group->free_space_ctl;
2923
fa9c0d79 2924 /* now return any extents the cluster had on it */
34d52cb6 2925 spin_lock(&ctl->tree_lock);
69b0e093 2926 __btrfs_return_cluster_to_free_space(block_group, cluster);
34d52cb6 2927 spin_unlock(&ctl->tree_lock);
fa9c0d79 2928
6e80d4f8
DZ
2929 btrfs_discard_queue_work(&block_group->fs_info->discard_ctl, block_group);
2930
fa9c0d79
CM
2931 /* finally drop our ref */
2932 btrfs_put_block_group(block_group);
fa9c0d79
CM
2933}
2934
32da5386 2935static u64 btrfs_alloc_from_bitmap(struct btrfs_block_group *block_group,
96303081 2936 struct btrfs_free_cluster *cluster,
4e69b598 2937 struct btrfs_free_space *entry,
a4820398
MX
2938 u64 bytes, u64 min_start,
2939 u64 *max_extent_size)
96303081 2940{
34d52cb6 2941 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
96303081
JB
2942 int err;
2943 u64 search_start = cluster->window_start;
2944 u64 search_bytes = bytes;
2945 u64 ret = 0;
2946
96303081
JB
2947 search_start = min_start;
2948 search_bytes = bytes;
2949
0584f718 2950 err = search_bitmap(ctl, entry, &search_start, &search_bytes, true);
a4820398 2951 if (err) {
ad22cf6e
JB
2952 *max_extent_size = max(get_max_extent_size(entry),
2953 *max_extent_size);
4e69b598 2954 return 0;
a4820398 2955 }
96303081
JB
2956
2957 ret = search_start;
bb3ac5a4 2958 __bitmap_clear_bits(ctl, entry, ret, bytes);
96303081
JB
2959
2960 return ret;
2961}
2962
fa9c0d79
CM
2963/*
2964 * given a cluster, try to allocate 'bytes' from it, returns 0
2965 * if it couldn't find anything suitably large, or a logical disk offset
2966 * if things worked out
2967 */
32da5386 2968u64 btrfs_alloc_from_cluster(struct btrfs_block_group *block_group,
fa9c0d79 2969 struct btrfs_free_cluster *cluster, u64 bytes,
a4820398 2970 u64 min_start, u64 *max_extent_size)
fa9c0d79 2971{
34d52cb6 2972 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
9ddf648f
DZ
2973 struct btrfs_discard_ctl *discard_ctl =
2974 &block_group->fs_info->discard_ctl;
fa9c0d79
CM
2975 struct btrfs_free_space *entry = NULL;
2976 struct rb_node *node;
2977 u64 ret = 0;
2978
2979 spin_lock(&cluster->lock);
2980 if (bytes > cluster->max_size)
2981 goto out;
2982
2983 if (cluster->block_group != block_group)
2984 goto out;
2985
2986 node = rb_first(&cluster->root);
2987 if (!node)
2988 goto out;
2989
2990 entry = rb_entry(node, struct btrfs_free_space, offset_index);
67871254 2991 while (1) {
ad22cf6e
JB
2992 if (entry->bytes < bytes)
2993 *max_extent_size = max(get_max_extent_size(entry),
2994 *max_extent_size);
a4820398 2995
4e69b598
JB
2996 if (entry->bytes < bytes ||
2997 (!entry->bitmap && entry->offset < min_start)) {
fa9c0d79
CM
2998 node = rb_next(&entry->offset_index);
2999 if (!node)
3000 break;
3001 entry = rb_entry(node, struct btrfs_free_space,
3002 offset_index);
3003 continue;
3004 }
fa9c0d79 3005
4e69b598
JB
3006 if (entry->bitmap) {
3007 ret = btrfs_alloc_from_bitmap(block_group,
3008 cluster, entry, bytes,
a4820398
MX
3009 cluster->window_start,
3010 max_extent_size);
4e69b598 3011 if (ret == 0) {
4e69b598
JB
3012 node = rb_next(&entry->offset_index);
3013 if (!node)
3014 break;
3015 entry = rb_entry(node, struct btrfs_free_space,
3016 offset_index);
3017 continue;
3018 }
9b230628 3019 cluster->window_start += bytes;
4e69b598 3020 } else {
4e69b598
JB
3021 ret = entry->offset;
3022
3023 entry->offset += bytes;
3024 entry->bytes -= bytes;
3025 }
fa9c0d79 3026
5e71b5d5 3027 if (entry->bytes == 0)
fa9c0d79 3028 rb_erase(&entry->offset_index, &cluster->root);
fa9c0d79
CM
3029 break;
3030 }
3031out:
3032 spin_unlock(&cluster->lock);
96303081 3033
5e71b5d5
LZ
3034 if (!ret)
3035 return 0;
3036
34d52cb6 3037 spin_lock(&ctl->tree_lock);
5e71b5d5 3038
9ddf648f
DZ
3039 if (!btrfs_free_space_trimmed(entry))
3040 atomic64_add(bytes, &discard_ctl->discard_bytes_saved);
3041
34d52cb6 3042 ctl->free_space -= bytes;
5dc7c10b
DZ
3043 if (!entry->bitmap && !btrfs_free_space_trimmed(entry))
3044 ctl->discardable_bytes[BTRFS_STAT_CURR] -= bytes;
5e71b5d5 3045 if (entry->bytes == 0) {
34d52cb6 3046 ctl->free_extents--;
4e69b598 3047 if (entry->bitmap) {
3acd4850
CL
3048 kmem_cache_free(btrfs_free_space_bitmap_cachep,
3049 entry->bitmap);
34d52cb6 3050 ctl->total_bitmaps--;
fa598b06 3051 recalculate_thresholds(ctl);
dfb79ddb
DZ
3052 } else if (!btrfs_free_space_trimmed(entry)) {
3053 ctl->discardable_extents[BTRFS_STAT_CURR]--;
4e69b598 3054 }
dc89e982 3055 kmem_cache_free(btrfs_free_space_cachep, entry);
5e71b5d5
LZ
3056 }
3057
34d52cb6 3058 spin_unlock(&ctl->tree_lock);
5e71b5d5 3059
fa9c0d79
CM
3060 return ret;
3061}
3062
32da5386 3063static int btrfs_bitmap_cluster(struct btrfs_block_group *block_group,
96303081
JB
3064 struct btrfs_free_space *entry,
3065 struct btrfs_free_cluster *cluster,
1bb91902
AO
3066 u64 offset, u64 bytes,
3067 u64 cont1_bytes, u64 min_bytes)
96303081 3068{
34d52cb6 3069 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
96303081
JB
3070 unsigned long next_zero;
3071 unsigned long i;
1bb91902
AO
3072 unsigned long want_bits;
3073 unsigned long min_bits;
96303081 3074 unsigned long found_bits;
cef40483 3075 unsigned long max_bits = 0;
96303081
JB
3076 unsigned long start = 0;
3077 unsigned long total_found = 0;
4e69b598 3078 int ret;
96303081 3079
96009762 3080 i = offset_to_bit(entry->offset, ctl->unit,
96303081 3081 max_t(u64, offset, entry->offset));
96009762
WSH
3082 want_bits = bytes_to_bits(bytes, ctl->unit);
3083 min_bits = bytes_to_bits(min_bytes, ctl->unit);
96303081 3084
cef40483
JB
3085 /*
3086 * Don't bother looking for a cluster in this bitmap if it's heavily
3087 * fragmented.
3088 */
3089 if (entry->max_extent_size &&
3090 entry->max_extent_size < cont1_bytes)
3091 return -ENOSPC;
96303081
JB
3092again:
3093 found_bits = 0;
ebb3dad4 3094 for_each_set_bit_from(i, entry->bitmap, BITS_PER_BITMAP) {
96303081
JB
3095 next_zero = find_next_zero_bit(entry->bitmap,
3096 BITS_PER_BITMAP, i);
1bb91902 3097 if (next_zero - i >= min_bits) {
96303081 3098 found_bits = next_zero - i;
cef40483
JB
3099 if (found_bits > max_bits)
3100 max_bits = found_bits;
96303081
JB
3101 break;
3102 }
cef40483
JB
3103 if (next_zero - i > max_bits)
3104 max_bits = next_zero - i;
96303081
JB
3105 i = next_zero;
3106 }
3107
cef40483
JB
3108 if (!found_bits) {
3109 entry->max_extent_size = (u64)max_bits * ctl->unit;
4e69b598 3110 return -ENOSPC;
cef40483 3111 }
96303081 3112
1bb91902 3113 if (!total_found) {
96303081 3114 start = i;
b78d09bc 3115 cluster->max_size = 0;
96303081
JB
3116 }
3117
3118 total_found += found_bits;
3119
96009762
WSH
3120 if (cluster->max_size < found_bits * ctl->unit)
3121 cluster->max_size = found_bits * ctl->unit;
96303081 3122
1bb91902
AO
3123 if (total_found < want_bits || cluster->max_size < cont1_bytes) {
3124 i = next_zero + 1;
96303081
JB
3125 goto again;
3126 }
3127
96009762 3128 cluster->window_start = start * ctl->unit + entry->offset;
34d52cb6 3129 rb_erase(&entry->offset_index, &ctl->free_space_offset);
4e69b598
JB
3130 ret = tree_insert_offset(&cluster->root, entry->offset,
3131 &entry->offset_index, 1);
b12d6869 3132 ASSERT(!ret); /* -EEXIST; Logic error */
96303081 3133
3f7de037 3134 trace_btrfs_setup_cluster(block_group, cluster,
96009762 3135 total_found * ctl->unit, 1);
96303081
JB
3136 return 0;
3137}
3138
4e69b598
JB
3139/*
3140 * This searches the block group for just extents to fill the cluster with.
1bb91902
AO
3141 * Try to find a cluster with at least bytes total bytes, at least one
3142 * extent of cont1_bytes, and other clusters of at least min_bytes.
4e69b598 3143 */
3de85bb9 3144static noinline int
32da5386 3145setup_cluster_no_bitmap(struct btrfs_block_group *block_group,
3de85bb9
JB
3146 struct btrfs_free_cluster *cluster,
3147 struct list_head *bitmaps, u64 offset, u64 bytes,
1bb91902 3148 u64 cont1_bytes, u64 min_bytes)
4e69b598 3149{
34d52cb6 3150 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
4e69b598
JB
3151 struct btrfs_free_space *first = NULL;
3152 struct btrfs_free_space *entry = NULL;
4e69b598
JB
3153 struct btrfs_free_space *last;
3154 struct rb_node *node;
4e69b598
JB
3155 u64 window_free;
3156 u64 max_extent;
3f7de037 3157 u64 total_size = 0;
4e69b598 3158
34d52cb6 3159 entry = tree_search_offset(ctl, offset, 0, 1);
4e69b598
JB
3160 if (!entry)
3161 return -ENOSPC;
3162
3163 /*
3164 * We don't want bitmaps, so just move along until we find a normal
3165 * extent entry.
3166 */
1bb91902
AO
3167 while (entry->bitmap || entry->bytes < min_bytes) {
3168 if (entry->bitmap && list_empty(&entry->list))
86d4a77b 3169 list_add_tail(&entry->list, bitmaps);
4e69b598
JB
3170 node = rb_next(&entry->offset_index);
3171 if (!node)
3172 return -ENOSPC;
3173 entry = rb_entry(node, struct btrfs_free_space, offset_index);
3174 }
3175
4e69b598
JB
3176 window_free = entry->bytes;
3177 max_extent = entry->bytes;
3178 first = entry;
3179 last = entry;
4e69b598 3180
1bb91902
AO
3181 for (node = rb_next(&entry->offset_index); node;
3182 node = rb_next(&entry->offset_index)) {
4e69b598
JB
3183 entry = rb_entry(node, struct btrfs_free_space, offset_index);
3184
86d4a77b
JB
3185 if (entry->bitmap) {
3186 if (list_empty(&entry->list))
3187 list_add_tail(&entry->list, bitmaps);
4e69b598 3188 continue;
86d4a77b
JB
3189 }
3190
1bb91902
AO
3191 if (entry->bytes < min_bytes)
3192 continue;
3193
3194 last = entry;
3195 window_free += entry->bytes;
3196 if (entry->bytes > max_extent)
4e69b598 3197 max_extent = entry->bytes;
4e69b598
JB
3198 }
3199
1bb91902
AO
3200 if (window_free < bytes || max_extent < cont1_bytes)
3201 return -ENOSPC;
3202
4e69b598
JB
3203 cluster->window_start = first->offset;
3204
3205 node = &first->offset_index;
3206
3207 /*
3208 * now we've found our entries, pull them out of the free space
3209 * cache and put them into the cluster rbtree
3210 */
3211 do {
3212 int ret;
3213
3214 entry = rb_entry(node, struct btrfs_free_space, offset_index);
3215 node = rb_next(&entry->offset_index);
1bb91902 3216 if (entry->bitmap || entry->bytes < min_bytes)
4e69b598
JB
3217 continue;
3218
34d52cb6 3219 rb_erase(&entry->offset_index, &ctl->free_space_offset);
4e69b598
JB
3220 ret = tree_insert_offset(&cluster->root, entry->offset,
3221 &entry->offset_index, 0);
3f7de037 3222 total_size += entry->bytes;
b12d6869 3223 ASSERT(!ret); /* -EEXIST; Logic error */
4e69b598
JB
3224 } while (node && entry != last);
3225
3226 cluster->max_size = max_extent;
3f7de037 3227 trace_btrfs_setup_cluster(block_group, cluster, total_size, 0);
4e69b598
JB
3228 return 0;
3229}
3230
3231/*
3232 * This specifically looks for bitmaps that may work in the cluster, we assume
3233 * that we have already failed to find extents that will work.
3234 */
3de85bb9 3235static noinline int
32da5386 3236setup_cluster_bitmap(struct btrfs_block_group *block_group,
3de85bb9
JB
3237 struct btrfs_free_cluster *cluster,
3238 struct list_head *bitmaps, u64 offset, u64 bytes,
1bb91902 3239 u64 cont1_bytes, u64 min_bytes)
4e69b598 3240{
34d52cb6 3241 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
1b9b922a 3242 struct btrfs_free_space *entry = NULL;
4e69b598 3243 int ret = -ENOSPC;
0f0fbf1d 3244 u64 bitmap_offset = offset_to_bitmap(ctl, offset);
4e69b598 3245
34d52cb6 3246 if (ctl->total_bitmaps == 0)
4e69b598
JB
3247 return -ENOSPC;
3248
0f0fbf1d
LZ
3249 /*
3250 * The bitmap that covers offset won't be in the list unless offset
3251 * is just its start offset.
3252 */
1b9b922a
CM
3253 if (!list_empty(bitmaps))
3254 entry = list_first_entry(bitmaps, struct btrfs_free_space, list);
3255
3256 if (!entry || entry->offset != bitmap_offset) {
0f0fbf1d
LZ
3257 entry = tree_search_offset(ctl, bitmap_offset, 1, 0);
3258 if (entry && list_empty(&entry->list))
3259 list_add(&entry->list, bitmaps);
3260 }
3261
86d4a77b 3262 list_for_each_entry(entry, bitmaps, list) {
357b9784 3263 if (entry->bytes < bytes)
86d4a77b
JB
3264 continue;
3265 ret = btrfs_bitmap_cluster(block_group, entry, cluster, offset,
1bb91902 3266 bytes, cont1_bytes, min_bytes);
86d4a77b
JB
3267 if (!ret)
3268 return 0;
3269 }
3270
3271 /*
52621cb6
LZ
3272 * The bitmaps list has all the bitmaps that record free space
3273 * starting after offset, so no more search is required.
86d4a77b 3274 */
52621cb6 3275 return -ENOSPC;
4e69b598
JB
3276}
3277
fa9c0d79
CM
3278/*
3279 * here we try to find a cluster of blocks in a block group. The goal
1bb91902 3280 * is to find at least bytes+empty_size.
fa9c0d79
CM
3281 * We might not find them all in one contiguous area.
3282 *
3283 * returns zero and sets up cluster if things worked out, otherwise
3284 * it returns -enospc
3285 */
32da5386 3286int btrfs_find_space_cluster(struct btrfs_block_group *block_group,
fa9c0d79
CM
3287 struct btrfs_free_cluster *cluster,
3288 u64 offset, u64 bytes, u64 empty_size)
3289{
2ceeae2e 3290 struct btrfs_fs_info *fs_info = block_group->fs_info;
34d52cb6 3291 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
86d4a77b 3292 struct btrfs_free_space *entry, *tmp;
52621cb6 3293 LIST_HEAD(bitmaps);
fa9c0d79 3294 u64 min_bytes;
1bb91902 3295 u64 cont1_bytes;
fa9c0d79
CM
3296 int ret;
3297
1bb91902
AO
3298 /*
3299 * Choose the minimum extent size we'll require for this
3300 * cluster. For SSD_SPREAD, don't allow any fragmentation.
3301 * For metadata, allow allocates with smaller extents. For
3302 * data, keep it dense.
3303 */
0b246afa 3304 if (btrfs_test_opt(fs_info, SSD_SPREAD)) {
1bb91902 3305 cont1_bytes = min_bytes = bytes + empty_size;
451d7585 3306 } else if (block_group->flags & BTRFS_BLOCK_GROUP_METADATA) {
1bb91902 3307 cont1_bytes = bytes;
0b246afa 3308 min_bytes = fs_info->sectorsize;
1bb91902
AO
3309 } else {
3310 cont1_bytes = max(bytes, (bytes + empty_size) >> 2);
0b246afa 3311 min_bytes = fs_info->sectorsize;
1bb91902 3312 }
fa9c0d79 3313
34d52cb6 3314 spin_lock(&ctl->tree_lock);
7d0d2e8e
JB
3315
3316 /*
3317 * If we know we don't have enough space to make a cluster don't even
3318 * bother doing all the work to try and find one.
3319 */
1bb91902 3320 if (ctl->free_space < bytes) {
34d52cb6 3321 spin_unlock(&ctl->tree_lock);
7d0d2e8e
JB
3322 return -ENOSPC;
3323 }
3324
fa9c0d79
CM
3325 spin_lock(&cluster->lock);
3326
3327 /* someone already found a cluster, hooray */
3328 if (cluster->block_group) {
3329 ret = 0;
3330 goto out;
3331 }
fa9c0d79 3332
3f7de037
JB
3333 trace_btrfs_find_cluster(block_group, offset, bytes, empty_size,
3334 min_bytes);
3335
86d4a77b 3336 ret = setup_cluster_no_bitmap(block_group, cluster, &bitmaps, offset,
1bb91902
AO
3337 bytes + empty_size,
3338 cont1_bytes, min_bytes);
4e69b598 3339 if (ret)
86d4a77b 3340 ret = setup_cluster_bitmap(block_group, cluster, &bitmaps,
1bb91902
AO
3341 offset, bytes + empty_size,
3342 cont1_bytes, min_bytes);
86d4a77b
JB
3343
3344 /* Clear our temporary list */
3345 list_for_each_entry_safe(entry, tmp, &bitmaps, list)
3346 list_del_init(&entry->list);
fa9c0d79 3347
4e69b598 3348 if (!ret) {
b5790d51 3349 btrfs_get_block_group(block_group);
4e69b598
JB
3350 list_add_tail(&cluster->block_group_list,
3351 &block_group->cluster_list);
3352 cluster->block_group = block_group;
3f7de037
JB
3353 } else {
3354 trace_btrfs_failed_cluster_setup(block_group);
fa9c0d79 3355 }
fa9c0d79
CM
3356out:
3357 spin_unlock(&cluster->lock);
34d52cb6 3358 spin_unlock(&ctl->tree_lock);
fa9c0d79
CM
3359
3360 return ret;
3361}
3362
3363/*
3364 * simple code to zero out a cluster
3365 */
3366void btrfs_init_free_cluster(struct btrfs_free_cluster *cluster)
3367{
3368 spin_lock_init(&cluster->lock);
3369 spin_lock_init(&cluster->refill_lock);
6bef4d31 3370 cluster->root = RB_ROOT;
fa9c0d79 3371 cluster->max_size = 0;
c759c4e1 3372 cluster->fragmented = false;
fa9c0d79
CM
3373 INIT_LIST_HEAD(&cluster->block_group_list);
3374 cluster->block_group = NULL;
3375}
3376
32da5386 3377static int do_trimming(struct btrfs_block_group *block_group,
7fe1e641 3378 u64 *total_trimmed, u64 start, u64 bytes,
55507ce3 3379 u64 reserved_start, u64 reserved_bytes,
b0643e59 3380 enum btrfs_trim_state reserved_trim_state,
55507ce3 3381 struct btrfs_trim_range *trim_entry)
f7039b1d 3382{
7fe1e641 3383 struct btrfs_space_info *space_info = block_group->space_info;
f7039b1d 3384 struct btrfs_fs_info *fs_info = block_group->fs_info;
55507ce3 3385 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
7fe1e641
LZ
3386 int ret;
3387 int update = 0;
b0643e59
DZ
3388 const u64 end = start + bytes;
3389 const u64 reserved_end = reserved_start + reserved_bytes;
3390 enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
7fe1e641 3391 u64 trimmed = 0;
f7039b1d 3392
7fe1e641
LZ
3393 spin_lock(&space_info->lock);
3394 spin_lock(&block_group->lock);
3395 if (!block_group->ro) {
3396 block_group->reserved += reserved_bytes;
3397 space_info->bytes_reserved += reserved_bytes;
3398 update = 1;
3399 }
3400 spin_unlock(&block_group->lock);
3401 spin_unlock(&space_info->lock);
3402
2ff7e61e 3403 ret = btrfs_discard_extent(fs_info, start, bytes, &trimmed);
b0643e59 3404 if (!ret) {
7fe1e641 3405 *total_trimmed += trimmed;
b0643e59
DZ
3406 trim_state = BTRFS_TRIM_STATE_TRIMMED;
3407 }
7fe1e641 3408
55507ce3 3409 mutex_lock(&ctl->cache_writeout_mutex);
b0643e59
DZ
3410 if (reserved_start < start)
3411 __btrfs_add_free_space(fs_info, ctl, reserved_start,
3412 start - reserved_start,
3413 reserved_trim_state);
3414 if (start + bytes < reserved_start + reserved_bytes)
3415 __btrfs_add_free_space(fs_info, ctl, end, reserved_end - end,
3416 reserved_trim_state);
3417 __btrfs_add_free_space(fs_info, ctl, start, bytes, trim_state);
55507ce3
FM
3418 list_del(&trim_entry->list);
3419 mutex_unlock(&ctl->cache_writeout_mutex);
7fe1e641
LZ
3420
3421 if (update) {
3422 spin_lock(&space_info->lock);
3423 spin_lock(&block_group->lock);
3424 if (block_group->ro)
3425 space_info->bytes_readonly += reserved_bytes;
3426 block_group->reserved -= reserved_bytes;
3427 space_info->bytes_reserved -= reserved_bytes;
7fe1e641 3428 spin_unlock(&block_group->lock);
8f63a840 3429 spin_unlock(&space_info->lock);
7fe1e641
LZ
3430 }
3431
3432 return ret;
3433}
3434
2bee7eb8
DZ
3435/*
3436 * If @async is set, then we will trim 1 region and return.
3437 */
32da5386 3438static int trim_no_bitmap(struct btrfs_block_group *block_group,
2bee7eb8
DZ
3439 u64 *total_trimmed, u64 start, u64 end, u64 minlen,
3440 bool async)
7fe1e641 3441{
19b2a2c7
DZ
3442 struct btrfs_discard_ctl *discard_ctl =
3443 &block_group->fs_info->discard_ctl;
7fe1e641
LZ
3444 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3445 struct btrfs_free_space *entry;
3446 struct rb_node *node;
3447 int ret = 0;
3448 u64 extent_start;
3449 u64 extent_bytes;
b0643e59 3450 enum btrfs_trim_state extent_trim_state;
7fe1e641 3451 u64 bytes;
19b2a2c7 3452 const u64 max_discard_size = READ_ONCE(discard_ctl->max_discard_size);
f7039b1d
LD
3453
3454 while (start < end) {
55507ce3
FM
3455 struct btrfs_trim_range trim_entry;
3456
3457 mutex_lock(&ctl->cache_writeout_mutex);
34d52cb6 3458 spin_lock(&ctl->tree_lock);
f7039b1d 3459
2bee7eb8
DZ
3460 if (ctl->free_space < minlen)
3461 goto out_unlock;
f7039b1d 3462
34d52cb6 3463 entry = tree_search_offset(ctl, start, 0, 1);
2bee7eb8
DZ
3464 if (!entry)
3465 goto out_unlock;
f7039b1d 3466
2bee7eb8
DZ
3467 /* Skip bitmaps and if async, already trimmed entries */
3468 while (entry->bitmap ||
3469 (async && btrfs_free_space_trimmed(entry))) {
7fe1e641 3470 node = rb_next(&entry->offset_index);
2bee7eb8
DZ
3471 if (!node)
3472 goto out_unlock;
7fe1e641
LZ
3473 entry = rb_entry(node, struct btrfs_free_space,
3474 offset_index);
f7039b1d
LD
3475 }
3476
2bee7eb8
DZ
3477 if (entry->offset >= end)
3478 goto out_unlock;
f7039b1d 3479
7fe1e641
LZ
3480 extent_start = entry->offset;
3481 extent_bytes = entry->bytes;
b0643e59 3482 extent_trim_state = entry->trim_state;
4aa9ad52
DZ
3483 if (async) {
3484 start = entry->offset;
3485 bytes = entry->bytes;
3486 if (bytes < minlen) {
3487 spin_unlock(&ctl->tree_lock);
3488 mutex_unlock(&ctl->cache_writeout_mutex);
3489 goto next;
3490 }
3491 unlink_free_space(ctl, entry);
7fe6d45e
DZ
3492 /*
3493 * Let bytes = BTRFS_MAX_DISCARD_SIZE + X.
3494 * If X < BTRFS_ASYNC_DISCARD_MIN_FILTER, we won't trim
3495 * X when we come back around. So trim it now.
3496 */
3497 if (max_discard_size &&
3498 bytes >= (max_discard_size +
3499 BTRFS_ASYNC_DISCARD_MIN_FILTER)) {
19b2a2c7
DZ
3500 bytes = max_discard_size;
3501 extent_bytes = max_discard_size;
3502 entry->offset += max_discard_size;
3503 entry->bytes -= max_discard_size;
4aa9ad52
DZ
3504 link_free_space(ctl, entry);
3505 } else {
3506 kmem_cache_free(btrfs_free_space_cachep, entry);
3507 }
3508 } else {
3509 start = max(start, extent_start);
3510 bytes = min(extent_start + extent_bytes, end) - start;
3511 if (bytes < minlen) {
3512 spin_unlock(&ctl->tree_lock);
3513 mutex_unlock(&ctl->cache_writeout_mutex);
3514 goto next;
3515 }
f7039b1d 3516
4aa9ad52
DZ
3517 unlink_free_space(ctl, entry);
3518 kmem_cache_free(btrfs_free_space_cachep, entry);
3519 }
7fe1e641 3520
34d52cb6 3521 spin_unlock(&ctl->tree_lock);
55507ce3
FM
3522 trim_entry.start = extent_start;
3523 trim_entry.bytes = extent_bytes;
3524 list_add_tail(&trim_entry.list, &ctl->trimming_ranges);
3525 mutex_unlock(&ctl->cache_writeout_mutex);
f7039b1d 3526
7fe1e641 3527 ret = do_trimming(block_group, total_trimmed, start, bytes,
b0643e59
DZ
3528 extent_start, extent_bytes, extent_trim_state,
3529 &trim_entry);
2bee7eb8
DZ
3530 if (ret) {
3531 block_group->discard_cursor = start + bytes;
7fe1e641 3532 break;
2bee7eb8 3533 }
7fe1e641
LZ
3534next:
3535 start += bytes;
2bee7eb8
DZ
3536 block_group->discard_cursor = start;
3537 if (async && *total_trimmed)
3538 break;
f7039b1d 3539
7fe1e641
LZ
3540 if (fatal_signal_pending(current)) {
3541 ret = -ERESTARTSYS;
3542 break;
3543 }
3544
3545 cond_resched();
3546 }
2bee7eb8
DZ
3547
3548 return ret;
3549
3550out_unlock:
3551 block_group->discard_cursor = btrfs_block_group_end(block_group);
3552 spin_unlock(&ctl->tree_lock);
3553 mutex_unlock(&ctl->cache_writeout_mutex);
3554
7fe1e641
LZ
3555 return ret;
3556}
3557
da080fe1
DZ
3558/*
3559 * If we break out of trimming a bitmap prematurely, we should reset the
3560 * trimming bit. In a rather contrieved case, it's possible to race here so
3561 * reset the state to BTRFS_TRIM_STATE_UNTRIMMED.
3562 *
3563 * start = start of bitmap
3564 * end = near end of bitmap
3565 *
3566 * Thread 1: Thread 2:
3567 * trim_bitmaps(start)
3568 * trim_bitmaps(end)
3569 * end_trimming_bitmap()
3570 * reset_trimming_bitmap()
3571 */
3572static void reset_trimming_bitmap(struct btrfs_free_space_ctl *ctl, u64 offset)
3573{
3574 struct btrfs_free_space *entry;
3575
3576 spin_lock(&ctl->tree_lock);
3577 entry = tree_search_offset(ctl, offset, 1, 0);
dfb79ddb 3578 if (entry) {
5dc7c10b 3579 if (btrfs_free_space_trimmed(entry)) {
dfb79ddb
DZ
3580 ctl->discardable_extents[BTRFS_STAT_CURR] +=
3581 entry->bitmap_extents;
5dc7c10b
DZ
3582 ctl->discardable_bytes[BTRFS_STAT_CURR] += entry->bytes;
3583 }
da080fe1 3584 entry->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
dfb79ddb
DZ
3585 }
3586
da080fe1
DZ
3587 spin_unlock(&ctl->tree_lock);
3588}
3589
dfb79ddb
DZ
3590static void end_trimming_bitmap(struct btrfs_free_space_ctl *ctl,
3591 struct btrfs_free_space *entry)
da080fe1 3592{
dfb79ddb 3593 if (btrfs_free_space_trimming_bitmap(entry)) {
da080fe1 3594 entry->trim_state = BTRFS_TRIM_STATE_TRIMMED;
dfb79ddb
DZ
3595 ctl->discardable_extents[BTRFS_STAT_CURR] -=
3596 entry->bitmap_extents;
5dc7c10b 3597 ctl->discardable_bytes[BTRFS_STAT_CURR] -= entry->bytes;
dfb79ddb 3598 }
da080fe1
DZ
3599}
3600
2bee7eb8
DZ
3601/*
3602 * If @async is set, then we will trim 1 region and return.
3603 */
32da5386 3604static int trim_bitmaps(struct btrfs_block_group *block_group,
2bee7eb8 3605 u64 *total_trimmed, u64 start, u64 end, u64 minlen,
7fe6d45e 3606 u64 maxlen, bool async)
7fe1e641 3607{
19b2a2c7
DZ
3608 struct btrfs_discard_ctl *discard_ctl =
3609 &block_group->fs_info->discard_ctl;
7fe1e641
LZ
3610 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3611 struct btrfs_free_space *entry;
3612 int ret = 0;
3613 int ret2;
3614 u64 bytes;
3615 u64 offset = offset_to_bitmap(ctl, start);
19b2a2c7 3616 const u64 max_discard_size = READ_ONCE(discard_ctl->max_discard_size);
7fe1e641
LZ
3617
3618 while (offset < end) {
3619 bool next_bitmap = false;
55507ce3 3620 struct btrfs_trim_range trim_entry;
7fe1e641 3621
55507ce3 3622 mutex_lock(&ctl->cache_writeout_mutex);
7fe1e641
LZ
3623 spin_lock(&ctl->tree_lock);
3624
3625 if (ctl->free_space < minlen) {
2bee7eb8
DZ
3626 block_group->discard_cursor =
3627 btrfs_block_group_end(block_group);
7fe1e641 3628 spin_unlock(&ctl->tree_lock);
55507ce3 3629 mutex_unlock(&ctl->cache_writeout_mutex);
7fe1e641
LZ
3630 break;
3631 }
3632
3633 entry = tree_search_offset(ctl, offset, 1, 0);
7fe6d45e
DZ
3634 /*
3635 * Bitmaps are marked trimmed lossily now to prevent constant
3636 * discarding of the same bitmap (the reason why we are bound
3637 * by the filters). So, retrim the block group bitmaps when we
3638 * are preparing to punt to the unused_bgs list. This uses
3639 * @minlen to determine if we are in BTRFS_DISCARD_INDEX_UNUSED
3640 * which is the only discard index which sets minlen to 0.
3641 */
3642 if (!entry || (async && minlen && start == offset &&
2bee7eb8 3643 btrfs_free_space_trimmed(entry))) {
7fe1e641 3644 spin_unlock(&ctl->tree_lock);
55507ce3 3645 mutex_unlock(&ctl->cache_writeout_mutex);
7fe1e641
LZ
3646 next_bitmap = true;
3647 goto next;
3648 }
3649
da080fe1
DZ
3650 /*
3651 * Async discard bitmap trimming begins at by setting the start
3652 * to be key.objectid and the offset_to_bitmap() aligns to the
3653 * start of the bitmap. This lets us know we are fully
3654 * scanning the bitmap rather than only some portion of it.
3655 */
3656 if (start == offset)
3657 entry->trim_state = BTRFS_TRIM_STATE_TRIMMING;
3658
7fe1e641 3659 bytes = minlen;
0584f718 3660 ret2 = search_bitmap(ctl, entry, &start, &bytes, false);
7fe1e641 3661 if (ret2 || start >= end) {
da080fe1 3662 /*
7fe6d45e
DZ
3663 * We lossily consider a bitmap trimmed if we only skip
3664 * over regions <= BTRFS_ASYNC_DISCARD_MIN_FILTER.
da080fe1 3665 */
7fe6d45e 3666 if (ret2 && minlen <= BTRFS_ASYNC_DISCARD_MIN_FILTER)
dfb79ddb 3667 end_trimming_bitmap(ctl, entry);
da080fe1
DZ
3668 else
3669 entry->trim_state = BTRFS_TRIM_STATE_UNTRIMMED;
7fe1e641 3670 spin_unlock(&ctl->tree_lock);
55507ce3 3671 mutex_unlock(&ctl->cache_writeout_mutex);
7fe1e641
LZ
3672 next_bitmap = true;
3673 goto next;
3674 }
3675
2bee7eb8
DZ
3676 /*
3677 * We already trimmed a region, but are using the locking above
3678 * to reset the trim_state.
3679 */
3680 if (async && *total_trimmed) {
3681 spin_unlock(&ctl->tree_lock);
3682 mutex_unlock(&ctl->cache_writeout_mutex);
3683 goto out;
3684 }
3685
7fe1e641 3686 bytes = min(bytes, end - start);
7fe6d45e 3687 if (bytes < minlen || (async && maxlen && bytes > maxlen)) {
7fe1e641 3688 spin_unlock(&ctl->tree_lock);
55507ce3 3689 mutex_unlock(&ctl->cache_writeout_mutex);
7fe1e641
LZ
3690 goto next;
3691 }
3692
7fe6d45e
DZ
3693 /*
3694 * Let bytes = BTRFS_MAX_DISCARD_SIZE + X.
3695 * If X < @minlen, we won't trim X when we come back around.
3696 * So trim it now. We differ here from trimming extents as we
3697 * don't keep individual state per bit.
3698 */
3699 if (async &&
3700 max_discard_size &&
3701 bytes > (max_discard_size + minlen))
19b2a2c7 3702 bytes = max_discard_size;
4aa9ad52 3703
7fe1e641
LZ
3704 bitmap_clear_bits(ctl, entry, start, bytes);
3705 if (entry->bytes == 0)
3706 free_bitmap(ctl, entry);
3707
3708 spin_unlock(&ctl->tree_lock);
55507ce3
FM
3709 trim_entry.start = start;
3710 trim_entry.bytes = bytes;
3711 list_add_tail(&trim_entry.list, &ctl->trimming_ranges);
3712 mutex_unlock(&ctl->cache_writeout_mutex);
7fe1e641
LZ
3713
3714 ret = do_trimming(block_group, total_trimmed, start, bytes,
b0643e59 3715 start, bytes, 0, &trim_entry);
da080fe1
DZ
3716 if (ret) {
3717 reset_trimming_bitmap(ctl, offset);
2bee7eb8
DZ
3718 block_group->discard_cursor =
3719 btrfs_block_group_end(block_group);
7fe1e641 3720 break;
da080fe1 3721 }
7fe1e641
LZ
3722next:
3723 if (next_bitmap) {
3724 offset += BITS_PER_BITMAP * ctl->unit;
da080fe1 3725 start = offset;
7fe1e641
LZ
3726 } else {
3727 start += bytes;
f7039b1d 3728 }
2bee7eb8 3729 block_group->discard_cursor = start;
f7039b1d
LD
3730
3731 if (fatal_signal_pending(current)) {
da080fe1
DZ
3732 if (start != offset)
3733 reset_trimming_bitmap(ctl, offset);
f7039b1d
LD
3734 ret = -ERESTARTSYS;
3735 break;
3736 }
3737
3738 cond_resched();
3739 }
3740
2bee7eb8
DZ
3741 if (offset >= end)
3742 block_group->discard_cursor = end;
3743
3744out:
f7039b1d
LD
3745 return ret;
3746}
581bb050 3747
32da5386 3748int btrfs_trim_block_group(struct btrfs_block_group *block_group,
e33e17ee
JM
3749 u64 *trimmed, u64 start, u64 end, u64 minlen)
3750{
da080fe1 3751 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
e33e17ee 3752 int ret;
da080fe1 3753 u64 rem = 0;
e33e17ee
JM
3754
3755 *trimmed = 0;
3756
3757 spin_lock(&block_group->lock);
3758 if (block_group->removed) {
04216820 3759 spin_unlock(&block_group->lock);
e33e17ee 3760 return 0;
04216820 3761 }
6b7304af 3762 btrfs_freeze_block_group(block_group);
e33e17ee
JM
3763 spin_unlock(&block_group->lock);
3764
2bee7eb8 3765 ret = trim_no_bitmap(block_group, trimmed, start, end, minlen, false);
e33e17ee
JM
3766 if (ret)
3767 goto out;
7fe1e641 3768
7fe6d45e 3769 ret = trim_bitmaps(block_group, trimmed, start, end, minlen, 0, false);
da080fe1
DZ
3770 div64_u64_rem(end, BITS_PER_BITMAP * ctl->unit, &rem);
3771 /* If we ended in the middle of a bitmap, reset the trimming flag */
3772 if (rem)
3773 reset_trimming_bitmap(ctl, offset_to_bitmap(ctl, end));
e33e17ee 3774out:
6b7304af 3775 btrfs_unfreeze_block_group(block_group);
7fe1e641
LZ
3776 return ret;
3777}
3778
2bee7eb8
DZ
3779int btrfs_trim_block_group_extents(struct btrfs_block_group *block_group,
3780 u64 *trimmed, u64 start, u64 end, u64 minlen,
3781 bool async)
3782{
3783 int ret;
3784
3785 *trimmed = 0;
3786
3787 spin_lock(&block_group->lock);
3788 if (block_group->removed) {
3789 spin_unlock(&block_group->lock);
3790 return 0;
3791 }
6b7304af 3792 btrfs_freeze_block_group(block_group);
2bee7eb8
DZ
3793 spin_unlock(&block_group->lock);
3794
3795 ret = trim_no_bitmap(block_group, trimmed, start, end, minlen, async);
6b7304af 3796 btrfs_unfreeze_block_group(block_group);
2bee7eb8
DZ
3797
3798 return ret;
3799}
3800
3801int btrfs_trim_block_group_bitmaps(struct btrfs_block_group *block_group,
3802 u64 *trimmed, u64 start, u64 end, u64 minlen,
7fe6d45e 3803 u64 maxlen, bool async)
2bee7eb8
DZ
3804{
3805 int ret;
3806
3807 *trimmed = 0;
3808
3809 spin_lock(&block_group->lock);
3810 if (block_group->removed) {
3811 spin_unlock(&block_group->lock);
3812 return 0;
3813 }
6b7304af 3814 btrfs_freeze_block_group(block_group);
2bee7eb8
DZ
3815 spin_unlock(&block_group->lock);
3816
7fe6d45e
DZ
3817 ret = trim_bitmaps(block_group, trimmed, start, end, minlen, maxlen,
3818 async);
3819
6b7304af 3820 btrfs_unfreeze_block_group(block_group);
2bee7eb8
DZ
3821
3822 return ret;
3823}
3824
94846229
BB
3825bool btrfs_free_space_cache_v1_active(struct btrfs_fs_info *fs_info)
3826{
3827 return btrfs_super_cache_generation(fs_info->super_copy);
3828}
3829
36b216c8
BB
3830static int cleanup_free_space_cache_v1(struct btrfs_fs_info *fs_info,
3831 struct btrfs_trans_handle *trans)
3832{
3833 struct btrfs_block_group *block_group;
3834 struct rb_node *node;
3835 int ret;
3836
3837 btrfs_info(fs_info, "cleaning free space cache v1");
3838
3839 node = rb_first(&fs_info->block_group_cache_tree);
3840 while (node) {
3841 block_group = rb_entry(node, struct btrfs_block_group, cache_node);
3842 ret = btrfs_remove_free_space_inode(trans, NULL, block_group);
3843 if (ret)
3844 goto out;
3845 node = rb_next(node);
3846 }
3847out:
3848 return ret;
3849}
3850
94846229
BB
3851int btrfs_set_free_space_cache_v1_active(struct btrfs_fs_info *fs_info, bool active)
3852{
3853 struct btrfs_trans_handle *trans;
3854 int ret;
3855
3856 /*
36b216c8
BB
3857 * update_super_roots will appropriately set or unset
3858 * super_copy->cache_generation based on SPACE_CACHE and
3859 * BTRFS_FS_CLEANUP_SPACE_CACHE_V1. For this reason, we need a
3860 * transaction commit whether we are enabling space cache v1 and don't
3861 * have any other work to do, or are disabling it and removing free
3862 * space inodes.
94846229
BB
3863 */
3864 trans = btrfs_start_transaction(fs_info->tree_root, 0);
3865 if (IS_ERR(trans))
3866 return PTR_ERR(trans);
3867
36b216c8 3868 if (!active) {
94846229 3869 set_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags);
36b216c8
BB
3870 ret = cleanup_free_space_cache_v1(fs_info, trans);
3871 if (ret) {
3872 btrfs_abort_transaction(trans, ret);
3873 btrfs_end_transaction(trans);
3874 goto out;
3875 }
3876 }
94846229
BB
3877
3878 ret = btrfs_commit_transaction(trans);
36b216c8 3879out:
94846229
BB
3880 clear_bit(BTRFS_FS_CLEANUP_SPACE_CACHE_V1, &fs_info->flags);
3881
3882 return ret;
3883}
3884
74255aa0 3885#ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
dc11dd5d
JB
3886/*
3887 * Use this if you need to make a bitmap or extent entry specifically, it
3888 * doesn't do any of the merging that add_free_space does, this acts a lot like
3889 * how the free space cache loading stuff works, so you can get really weird
3890 * configurations.
3891 */
32da5386 3892int test_add_free_space_entry(struct btrfs_block_group *cache,
dc11dd5d 3893 u64 offset, u64 bytes, bool bitmap)
74255aa0 3894{
dc11dd5d
JB
3895 struct btrfs_free_space_ctl *ctl = cache->free_space_ctl;
3896 struct btrfs_free_space *info = NULL, *bitmap_info;
3897 void *map = NULL;
da080fe1 3898 enum btrfs_trim_state trim_state = BTRFS_TRIM_STATE_TRIMMED;
dc11dd5d
JB
3899 u64 bytes_added;
3900 int ret;
74255aa0 3901
dc11dd5d
JB
3902again:
3903 if (!info) {
3904 info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
3905 if (!info)
3906 return -ENOMEM;
74255aa0
JB
3907 }
3908
dc11dd5d
JB
3909 if (!bitmap) {
3910 spin_lock(&ctl->tree_lock);
3911 info->offset = offset;
3912 info->bytes = bytes;
cef40483 3913 info->max_extent_size = 0;
dc11dd5d
JB
3914 ret = link_free_space(ctl, info);
3915 spin_unlock(&ctl->tree_lock);
3916 if (ret)
3917 kmem_cache_free(btrfs_free_space_cachep, info);
3918 return ret;
3919 }
3920
3921 if (!map) {
3acd4850 3922 map = kmem_cache_zalloc(btrfs_free_space_bitmap_cachep, GFP_NOFS);
dc11dd5d
JB
3923 if (!map) {
3924 kmem_cache_free(btrfs_free_space_cachep, info);
3925 return -ENOMEM;
3926 }
3927 }
3928
3929 spin_lock(&ctl->tree_lock);
3930 bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
3931 1, 0);
3932 if (!bitmap_info) {
3933 info->bitmap = map;
3934 map = NULL;
3935 add_new_bitmap(ctl, info, offset);
3936 bitmap_info = info;
20005523 3937 info = NULL;
dc11dd5d 3938 }
74255aa0 3939
da080fe1
DZ
3940 bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes,
3941 trim_state);
cef40483 3942
dc11dd5d
JB
3943 bytes -= bytes_added;
3944 offset += bytes_added;
3945 spin_unlock(&ctl->tree_lock);
74255aa0 3946
dc11dd5d
JB
3947 if (bytes)
3948 goto again;
74255aa0 3949
20005523
FM
3950 if (info)
3951 kmem_cache_free(btrfs_free_space_cachep, info);
3acd4850
CL
3952 if (map)
3953 kmem_cache_free(btrfs_free_space_bitmap_cachep, map);
dc11dd5d 3954 return 0;
74255aa0
JB
3955}
3956
3957/*
3958 * Checks to see if the given range is in the free space cache. This is really
3959 * just used to check the absence of space, so if there is free space in the
3960 * range at all we will return 1.
3961 */
32da5386 3962int test_check_exists(struct btrfs_block_group *cache,
dc11dd5d 3963 u64 offset, u64 bytes)
74255aa0
JB
3964{
3965 struct btrfs_free_space_ctl *ctl = cache->free_space_ctl;
3966 struct btrfs_free_space *info;
3967 int ret = 0;
3968
3969 spin_lock(&ctl->tree_lock);
3970 info = tree_search_offset(ctl, offset, 0, 0);
3971 if (!info) {
3972 info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
3973 1, 0);
3974 if (!info)
3975 goto out;
3976 }
3977
3978have_info:
3979 if (info->bitmap) {
3980 u64 bit_off, bit_bytes;
3981 struct rb_node *n;
3982 struct btrfs_free_space *tmp;
3983
3984 bit_off = offset;
3985 bit_bytes = ctl->unit;
0584f718 3986 ret = search_bitmap(ctl, info, &bit_off, &bit_bytes, false);
74255aa0
JB
3987 if (!ret) {
3988 if (bit_off == offset) {
3989 ret = 1;
3990 goto out;
3991 } else if (bit_off > offset &&
3992 offset + bytes > bit_off) {
3993 ret = 1;
3994 goto out;
3995 }
3996 }
3997
3998 n = rb_prev(&info->offset_index);
3999 while (n) {
4000 tmp = rb_entry(n, struct btrfs_free_space,
4001 offset_index);
4002 if (tmp->offset + tmp->bytes < offset)
4003 break;
4004 if (offset + bytes < tmp->offset) {
5473e0c4 4005 n = rb_prev(&tmp->offset_index);
74255aa0
JB
4006 continue;
4007 }
4008 info = tmp;
4009 goto have_info;
4010 }
4011
4012 n = rb_next(&info->offset_index);
4013 while (n) {
4014 tmp = rb_entry(n, struct btrfs_free_space,
4015 offset_index);
4016 if (offset + bytes < tmp->offset)
4017 break;
4018 if (tmp->offset + tmp->bytes < offset) {
5473e0c4 4019 n = rb_next(&tmp->offset_index);
74255aa0
JB
4020 continue;
4021 }
4022 info = tmp;
4023 goto have_info;
4024 }
4025
20005523 4026 ret = 0;
74255aa0
JB
4027 goto out;
4028 }
4029
4030 if (info->offset == offset) {
4031 ret = 1;
4032 goto out;
4033 }
4034
4035 if (offset > info->offset && offset < info->offset + info->bytes)
4036 ret = 1;
4037out:
4038 spin_unlock(&ctl->tree_lock);
4039 return ret;
4040}
dc11dd5d 4041#endif /* CONFIG_BTRFS_FS_RUN_SANITY_TESTS */