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