mm: fix exec activate_mm vs TLB shootdown and lazy tlb switching race
[linux/fpc-iii.git] / fs / btrfs / free-space-cache.c
blob9bf72a9088acac1ec6524267c883365438b29ae4
1 /*
2 * Copyright (C) 2008 Red Hat. All rights reserved.
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
19 #include <linux/pagemap.h>
20 #include <linux/sched.h>
21 #include <linux/sched/signal.h>
22 #include <linux/slab.h>
23 #include <linux/math64.h>
24 #include <linux/ratelimit.h>
25 #include <linux/sched/mm.h>
26 #include "ctree.h"
27 #include "free-space-cache.h"
28 #include "transaction.h"
29 #include "disk-io.h"
30 #include "extent_io.h"
31 #include "inode-map.h"
32 #include "volumes.h"
34 #define BITS_PER_BITMAP (PAGE_SIZE * 8UL)
35 #define MAX_CACHE_BYTES_PER_GIG SZ_32K
37 struct btrfs_trim_range {
38 u64 start;
39 u64 bytes;
40 struct list_head list;
43 static int link_free_space(struct btrfs_free_space_ctl *ctl,
44 struct btrfs_free_space *info);
45 static void unlink_free_space(struct btrfs_free_space_ctl *ctl,
46 struct btrfs_free_space *info);
47 static int btrfs_wait_cache_io_root(struct btrfs_root *root,
48 struct btrfs_trans_handle *trans,
49 struct btrfs_io_ctl *io_ctl,
50 struct btrfs_path *path);
52 static struct inode *__lookup_free_space_inode(struct btrfs_root *root,
53 struct btrfs_path *path,
54 u64 offset)
56 struct btrfs_fs_info *fs_info = root->fs_info;
57 struct btrfs_key key;
58 struct btrfs_key location;
59 struct btrfs_disk_key disk_key;
60 struct btrfs_free_space_header *header;
61 struct extent_buffer *leaf;
62 struct inode *inode = NULL;
63 unsigned nofs_flag;
64 int ret;
66 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
67 key.offset = offset;
68 key.type = 0;
70 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
71 if (ret < 0)
72 return ERR_PTR(ret);
73 if (ret > 0) {
74 btrfs_release_path(path);
75 return ERR_PTR(-ENOENT);
78 leaf = path->nodes[0];
79 header = btrfs_item_ptr(leaf, path->slots[0],
80 struct btrfs_free_space_header);
81 btrfs_free_space_key(leaf, header, &disk_key);
82 btrfs_disk_key_to_cpu(&location, &disk_key);
83 btrfs_release_path(path);
86 * We are often under a trans handle at this point, so we need to make
87 * sure NOFS is set to keep us from deadlocking.
89 nofs_flag = memalloc_nofs_save();
90 inode = btrfs_iget(fs_info->sb, &location, root, NULL);
91 memalloc_nofs_restore(nofs_flag);
92 if (IS_ERR(inode))
93 return inode;
94 if (is_bad_inode(inode)) {
95 iput(inode);
96 return ERR_PTR(-ENOENT);
99 mapping_set_gfp_mask(inode->i_mapping,
100 mapping_gfp_constraint(inode->i_mapping,
101 ~(__GFP_FS | __GFP_HIGHMEM)));
103 return inode;
106 struct inode *lookup_free_space_inode(struct btrfs_fs_info *fs_info,
107 struct btrfs_block_group_cache
108 *block_group, struct btrfs_path *path)
110 struct inode *inode = NULL;
111 u32 flags = BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW;
113 spin_lock(&block_group->lock);
114 if (block_group->inode)
115 inode = igrab(block_group->inode);
116 spin_unlock(&block_group->lock);
117 if (inode)
118 return inode;
120 inode = __lookup_free_space_inode(fs_info->tree_root, path,
121 block_group->key.objectid);
122 if (IS_ERR(inode))
123 return inode;
125 spin_lock(&block_group->lock);
126 if (!((BTRFS_I(inode)->flags & flags) == flags)) {
127 btrfs_info(fs_info, "Old style space inode found, converting.");
128 BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM |
129 BTRFS_INODE_NODATACOW;
130 block_group->disk_cache_state = BTRFS_DC_CLEAR;
133 if (!block_group->iref) {
134 block_group->inode = igrab(inode);
135 block_group->iref = 1;
137 spin_unlock(&block_group->lock);
139 return inode;
142 static int __create_free_space_inode(struct btrfs_root *root,
143 struct btrfs_trans_handle *trans,
144 struct btrfs_path *path,
145 u64 ino, u64 offset)
147 struct btrfs_key key;
148 struct btrfs_disk_key disk_key;
149 struct btrfs_free_space_header *header;
150 struct btrfs_inode_item *inode_item;
151 struct extent_buffer *leaf;
152 u64 flags = BTRFS_INODE_NOCOMPRESS | BTRFS_INODE_PREALLOC;
153 int ret;
155 ret = btrfs_insert_empty_inode(trans, root, path, ino);
156 if (ret)
157 return ret;
159 /* We inline crc's for the free disk space cache */
160 if (ino != BTRFS_FREE_INO_OBJECTID)
161 flags |= BTRFS_INODE_NODATASUM | BTRFS_INODE_NODATACOW;
163 leaf = path->nodes[0];
164 inode_item = btrfs_item_ptr(leaf, path->slots[0],
165 struct btrfs_inode_item);
166 btrfs_item_key(leaf, &disk_key, path->slots[0]);
167 memzero_extent_buffer(leaf, (unsigned long)inode_item,
168 sizeof(*inode_item));
169 btrfs_set_inode_generation(leaf, inode_item, trans->transid);
170 btrfs_set_inode_size(leaf, inode_item, 0);
171 btrfs_set_inode_nbytes(leaf, inode_item, 0);
172 btrfs_set_inode_uid(leaf, inode_item, 0);
173 btrfs_set_inode_gid(leaf, inode_item, 0);
174 btrfs_set_inode_mode(leaf, inode_item, S_IFREG | 0600);
175 btrfs_set_inode_flags(leaf, inode_item, flags);
176 btrfs_set_inode_nlink(leaf, inode_item, 1);
177 btrfs_set_inode_transid(leaf, inode_item, trans->transid);
178 btrfs_set_inode_block_group(leaf, inode_item, offset);
179 btrfs_mark_buffer_dirty(leaf);
180 btrfs_release_path(path);
182 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
183 key.offset = offset;
184 key.type = 0;
185 ret = btrfs_insert_empty_item(trans, root, path, &key,
186 sizeof(struct btrfs_free_space_header));
187 if (ret < 0) {
188 btrfs_release_path(path);
189 return ret;
192 leaf = path->nodes[0];
193 header = btrfs_item_ptr(leaf, path->slots[0],
194 struct btrfs_free_space_header);
195 memzero_extent_buffer(leaf, (unsigned long)header, sizeof(*header));
196 btrfs_set_free_space_key(leaf, header, &disk_key);
197 btrfs_mark_buffer_dirty(leaf);
198 btrfs_release_path(path);
200 return 0;
203 int create_free_space_inode(struct btrfs_fs_info *fs_info,
204 struct btrfs_trans_handle *trans,
205 struct btrfs_block_group_cache *block_group,
206 struct btrfs_path *path)
208 int ret;
209 u64 ino;
211 ret = btrfs_find_free_objectid(fs_info->tree_root, &ino);
212 if (ret < 0)
213 return ret;
215 return __create_free_space_inode(fs_info->tree_root, trans, path, ino,
216 block_group->key.objectid);
219 int btrfs_check_trunc_cache_free_space(struct btrfs_fs_info *fs_info,
220 struct btrfs_block_rsv *rsv)
222 u64 needed_bytes;
223 int ret;
225 /* 1 for slack space, 1 for updating the inode */
226 needed_bytes = btrfs_calc_trunc_metadata_size(fs_info, 1) +
227 btrfs_calc_trans_metadata_size(fs_info, 1);
229 spin_lock(&rsv->lock);
230 if (rsv->reserved < needed_bytes)
231 ret = -ENOSPC;
232 else
233 ret = 0;
234 spin_unlock(&rsv->lock);
235 return ret;
238 int btrfs_truncate_free_space_cache(struct btrfs_trans_handle *trans,
239 struct btrfs_block_group_cache *block_group,
240 struct inode *inode)
242 struct btrfs_root *root = BTRFS_I(inode)->root;
243 int ret = 0;
244 bool locked = false;
246 if (block_group) {
247 struct btrfs_path *path = btrfs_alloc_path();
249 if (!path) {
250 ret = -ENOMEM;
251 goto fail;
253 locked = true;
254 mutex_lock(&trans->transaction->cache_write_mutex);
255 if (!list_empty(&block_group->io_list)) {
256 list_del_init(&block_group->io_list);
258 btrfs_wait_cache_io(trans, block_group, path);
259 btrfs_put_block_group(block_group);
263 * now that we've truncated the cache away, its no longer
264 * setup or written
266 spin_lock(&block_group->lock);
267 block_group->disk_cache_state = BTRFS_DC_CLEAR;
268 spin_unlock(&block_group->lock);
269 btrfs_free_path(path);
272 btrfs_i_size_write(BTRFS_I(inode), 0);
273 truncate_pagecache(inode, 0);
276 * We don't need an orphan item because truncating the free space cache
277 * will never be split across transactions.
278 * We don't need to check for -EAGAIN because we're a free space
279 * cache inode
281 ret = btrfs_truncate_inode_items(trans, root, inode,
282 0, BTRFS_EXTENT_DATA_KEY);
283 if (ret)
284 goto fail;
286 ret = btrfs_update_inode(trans, root, inode);
288 fail:
289 if (locked)
290 mutex_unlock(&trans->transaction->cache_write_mutex);
291 if (ret)
292 btrfs_abort_transaction(trans, ret);
294 return ret;
297 static void readahead_cache(struct inode *inode)
299 struct file_ra_state *ra;
300 unsigned long last_index;
302 ra = kzalloc(sizeof(*ra), GFP_NOFS);
303 if (!ra)
304 return;
306 file_ra_state_init(ra, inode->i_mapping);
307 last_index = (i_size_read(inode) - 1) >> PAGE_SHIFT;
309 page_cache_sync_readahead(inode->i_mapping, ra, NULL, 0, last_index);
311 kfree(ra);
314 static int io_ctl_init(struct btrfs_io_ctl *io_ctl, struct inode *inode,
315 int write)
317 int num_pages;
318 int check_crcs = 0;
320 num_pages = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
322 if (btrfs_ino(BTRFS_I(inode)) != BTRFS_FREE_INO_OBJECTID)
323 check_crcs = 1;
325 /* Make sure we can fit our crcs into the first page */
326 if (write && check_crcs &&
327 (num_pages * sizeof(u32)) >= PAGE_SIZE)
328 return -ENOSPC;
330 memset(io_ctl, 0, sizeof(struct btrfs_io_ctl));
332 io_ctl->pages = kcalloc(num_pages, sizeof(struct page *), GFP_NOFS);
333 if (!io_ctl->pages)
334 return -ENOMEM;
336 io_ctl->num_pages = num_pages;
337 io_ctl->fs_info = btrfs_sb(inode->i_sb);
338 io_ctl->check_crcs = check_crcs;
339 io_ctl->inode = inode;
341 return 0;
344 static void io_ctl_free(struct btrfs_io_ctl *io_ctl)
346 kfree(io_ctl->pages);
347 io_ctl->pages = NULL;
350 static void io_ctl_unmap_page(struct btrfs_io_ctl *io_ctl)
352 if (io_ctl->cur) {
353 io_ctl->cur = NULL;
354 io_ctl->orig = NULL;
358 static void io_ctl_map_page(struct btrfs_io_ctl *io_ctl, int clear)
360 ASSERT(io_ctl->index < io_ctl->num_pages);
361 io_ctl->page = io_ctl->pages[io_ctl->index++];
362 io_ctl->cur = page_address(io_ctl->page);
363 io_ctl->orig = io_ctl->cur;
364 io_ctl->size = PAGE_SIZE;
365 if (clear)
366 clear_page(io_ctl->cur);
369 static void io_ctl_drop_pages(struct btrfs_io_ctl *io_ctl)
371 int i;
373 io_ctl_unmap_page(io_ctl);
375 for (i = 0; i < io_ctl->num_pages; i++) {
376 if (io_ctl->pages[i]) {
377 ClearPageChecked(io_ctl->pages[i]);
378 unlock_page(io_ctl->pages[i]);
379 put_page(io_ctl->pages[i]);
384 static int io_ctl_prepare_pages(struct btrfs_io_ctl *io_ctl, struct inode *inode,
385 int uptodate)
387 struct page *page;
388 gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
389 int i;
391 for (i = 0; i < io_ctl->num_pages; i++) {
392 page = find_or_create_page(inode->i_mapping, i, mask);
393 if (!page) {
394 io_ctl_drop_pages(io_ctl);
395 return -ENOMEM;
397 io_ctl->pages[i] = page;
398 if (uptodate && !PageUptodate(page)) {
399 btrfs_readpage(NULL, page);
400 lock_page(page);
401 if (page->mapping != inode->i_mapping) {
402 btrfs_err(BTRFS_I(inode)->root->fs_info,
403 "free space cache page truncated");
404 io_ctl_drop_pages(io_ctl);
405 return -EIO;
407 if (!PageUptodate(page)) {
408 btrfs_err(BTRFS_I(inode)->root->fs_info,
409 "error reading free space cache");
410 io_ctl_drop_pages(io_ctl);
411 return -EIO;
416 for (i = 0; i < io_ctl->num_pages; i++) {
417 clear_page_dirty_for_io(io_ctl->pages[i]);
418 set_page_extent_mapped(io_ctl->pages[i]);
421 return 0;
424 static void io_ctl_set_generation(struct btrfs_io_ctl *io_ctl, u64 generation)
426 __le64 *val;
428 io_ctl_map_page(io_ctl, 1);
431 * Skip the csum areas. If we don't check crcs then we just have a
432 * 64bit chunk at the front of the first page.
434 if (io_ctl->check_crcs) {
435 io_ctl->cur += (sizeof(u32) * io_ctl->num_pages);
436 io_ctl->size -= sizeof(u64) + (sizeof(u32) * io_ctl->num_pages);
437 } else {
438 io_ctl->cur += sizeof(u64);
439 io_ctl->size -= sizeof(u64) * 2;
442 val = io_ctl->cur;
443 *val = cpu_to_le64(generation);
444 io_ctl->cur += sizeof(u64);
447 static int io_ctl_check_generation(struct btrfs_io_ctl *io_ctl, u64 generation)
449 __le64 *gen;
452 * Skip the crc area. If we don't check crcs then we just have a 64bit
453 * chunk at the front of the first page.
455 if (io_ctl->check_crcs) {
456 io_ctl->cur += sizeof(u32) * io_ctl->num_pages;
457 io_ctl->size -= sizeof(u64) +
458 (sizeof(u32) * io_ctl->num_pages);
459 } else {
460 io_ctl->cur += sizeof(u64);
461 io_ctl->size -= sizeof(u64) * 2;
464 gen = io_ctl->cur;
465 if (le64_to_cpu(*gen) != generation) {
466 btrfs_err_rl(io_ctl->fs_info,
467 "space cache generation (%llu) does not match inode (%llu)",
468 *gen, generation);
469 io_ctl_unmap_page(io_ctl);
470 return -EIO;
472 io_ctl->cur += sizeof(u64);
473 return 0;
476 static void io_ctl_set_crc(struct btrfs_io_ctl *io_ctl, int index)
478 u32 *tmp;
479 u32 crc = ~(u32)0;
480 unsigned offset = 0;
482 if (!io_ctl->check_crcs) {
483 io_ctl_unmap_page(io_ctl);
484 return;
487 if (index == 0)
488 offset = sizeof(u32) * io_ctl->num_pages;
490 crc = btrfs_csum_data(io_ctl->orig + offset, crc,
491 PAGE_SIZE - offset);
492 btrfs_csum_final(crc, (u8 *)&crc);
493 io_ctl_unmap_page(io_ctl);
494 tmp = page_address(io_ctl->pages[0]);
495 tmp += index;
496 *tmp = crc;
499 static int io_ctl_check_crc(struct btrfs_io_ctl *io_ctl, int index)
501 u32 *tmp, val;
502 u32 crc = ~(u32)0;
503 unsigned offset = 0;
505 if (!io_ctl->check_crcs) {
506 io_ctl_map_page(io_ctl, 0);
507 return 0;
510 if (index == 0)
511 offset = sizeof(u32) * io_ctl->num_pages;
513 tmp = page_address(io_ctl->pages[0]);
514 tmp += index;
515 val = *tmp;
517 io_ctl_map_page(io_ctl, 0);
518 crc = btrfs_csum_data(io_ctl->orig + offset, crc,
519 PAGE_SIZE - offset);
520 btrfs_csum_final(crc, (u8 *)&crc);
521 if (val != crc) {
522 btrfs_err_rl(io_ctl->fs_info,
523 "csum mismatch on free space cache");
524 io_ctl_unmap_page(io_ctl);
525 return -EIO;
528 return 0;
531 static int io_ctl_add_entry(struct btrfs_io_ctl *io_ctl, u64 offset, u64 bytes,
532 void *bitmap)
534 struct btrfs_free_space_entry *entry;
536 if (!io_ctl->cur)
537 return -ENOSPC;
539 entry = io_ctl->cur;
540 entry->offset = cpu_to_le64(offset);
541 entry->bytes = cpu_to_le64(bytes);
542 entry->type = (bitmap) ? BTRFS_FREE_SPACE_BITMAP :
543 BTRFS_FREE_SPACE_EXTENT;
544 io_ctl->cur += sizeof(struct btrfs_free_space_entry);
545 io_ctl->size -= sizeof(struct btrfs_free_space_entry);
547 if (io_ctl->size >= sizeof(struct btrfs_free_space_entry))
548 return 0;
550 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
552 /* No more pages to map */
553 if (io_ctl->index >= io_ctl->num_pages)
554 return 0;
556 /* map the next page */
557 io_ctl_map_page(io_ctl, 1);
558 return 0;
561 static int io_ctl_add_bitmap(struct btrfs_io_ctl *io_ctl, void *bitmap)
563 if (!io_ctl->cur)
564 return -ENOSPC;
567 * If we aren't at the start of the current page, unmap this one and
568 * map the next one if there is any left.
570 if (io_ctl->cur != io_ctl->orig) {
571 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
572 if (io_ctl->index >= io_ctl->num_pages)
573 return -ENOSPC;
574 io_ctl_map_page(io_ctl, 0);
577 memcpy(io_ctl->cur, bitmap, PAGE_SIZE);
578 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
579 if (io_ctl->index < io_ctl->num_pages)
580 io_ctl_map_page(io_ctl, 0);
581 return 0;
584 static void io_ctl_zero_remaining_pages(struct btrfs_io_ctl *io_ctl)
587 * If we're not on the boundary we know we've modified the page and we
588 * need to crc the page.
590 if (io_ctl->cur != io_ctl->orig)
591 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
592 else
593 io_ctl_unmap_page(io_ctl);
595 while (io_ctl->index < io_ctl->num_pages) {
596 io_ctl_map_page(io_ctl, 1);
597 io_ctl_set_crc(io_ctl, io_ctl->index - 1);
601 static int io_ctl_read_entry(struct btrfs_io_ctl *io_ctl,
602 struct btrfs_free_space *entry, u8 *type)
604 struct btrfs_free_space_entry *e;
605 int ret;
607 if (!io_ctl->cur) {
608 ret = io_ctl_check_crc(io_ctl, io_ctl->index);
609 if (ret)
610 return ret;
613 e = io_ctl->cur;
614 entry->offset = le64_to_cpu(e->offset);
615 entry->bytes = le64_to_cpu(e->bytes);
616 *type = e->type;
617 io_ctl->cur += sizeof(struct btrfs_free_space_entry);
618 io_ctl->size -= sizeof(struct btrfs_free_space_entry);
620 if (io_ctl->size >= sizeof(struct btrfs_free_space_entry))
621 return 0;
623 io_ctl_unmap_page(io_ctl);
625 return 0;
628 static int io_ctl_read_bitmap(struct btrfs_io_ctl *io_ctl,
629 struct btrfs_free_space *entry)
631 int ret;
633 ret = io_ctl_check_crc(io_ctl, io_ctl->index);
634 if (ret)
635 return ret;
637 memcpy(entry->bitmap, io_ctl->cur, PAGE_SIZE);
638 io_ctl_unmap_page(io_ctl);
640 return 0;
644 * Since we attach pinned extents after the fact we can have contiguous sections
645 * of free space that are split up in entries. This poses a problem with the
646 * tree logging stuff since it could have allocated across what appears to be 2
647 * entries since we would have merged the entries when adding the pinned extents
648 * back to the free space cache. So run through the space cache that we just
649 * loaded and merge contiguous entries. This will make the log replay stuff not
650 * blow up and it will make for nicer allocator behavior.
652 static void merge_space_tree(struct btrfs_free_space_ctl *ctl)
654 struct btrfs_free_space *e, *prev = NULL;
655 struct rb_node *n;
657 again:
658 spin_lock(&ctl->tree_lock);
659 for (n = rb_first(&ctl->free_space_offset); n; n = rb_next(n)) {
660 e = rb_entry(n, struct btrfs_free_space, offset_index);
661 if (!prev)
662 goto next;
663 if (e->bitmap || prev->bitmap)
664 goto next;
665 if (prev->offset + prev->bytes == e->offset) {
666 unlink_free_space(ctl, prev);
667 unlink_free_space(ctl, e);
668 prev->bytes += e->bytes;
669 kmem_cache_free(btrfs_free_space_cachep, e);
670 link_free_space(ctl, prev);
671 prev = NULL;
672 spin_unlock(&ctl->tree_lock);
673 goto again;
675 next:
676 prev = e;
678 spin_unlock(&ctl->tree_lock);
681 static int __load_free_space_cache(struct btrfs_root *root, struct inode *inode,
682 struct btrfs_free_space_ctl *ctl,
683 struct btrfs_path *path, u64 offset)
685 struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
686 struct btrfs_free_space_header *header;
687 struct extent_buffer *leaf;
688 struct btrfs_io_ctl io_ctl;
689 struct btrfs_key key;
690 struct btrfs_free_space *e, *n;
691 LIST_HEAD(bitmaps);
692 u64 num_entries;
693 u64 num_bitmaps;
694 u64 generation;
695 u8 type;
696 int ret = 0;
698 /* Nothing in the space cache, goodbye */
699 if (!i_size_read(inode))
700 return 0;
702 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
703 key.offset = offset;
704 key.type = 0;
706 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
707 if (ret < 0)
708 return 0;
709 else if (ret > 0) {
710 btrfs_release_path(path);
711 return 0;
714 ret = -1;
716 leaf = path->nodes[0];
717 header = btrfs_item_ptr(leaf, path->slots[0],
718 struct btrfs_free_space_header);
719 num_entries = btrfs_free_space_entries(leaf, header);
720 num_bitmaps = btrfs_free_space_bitmaps(leaf, header);
721 generation = btrfs_free_space_generation(leaf, header);
722 btrfs_release_path(path);
724 if (!BTRFS_I(inode)->generation) {
725 btrfs_info(fs_info,
726 "the free space cache file (%llu) is invalid, skip it",
727 offset);
728 return 0;
731 if (BTRFS_I(inode)->generation != generation) {
732 btrfs_err(fs_info,
733 "free space inode generation (%llu) did not match free space cache generation (%llu)",
734 BTRFS_I(inode)->generation, generation);
735 return 0;
738 if (!num_entries)
739 return 0;
741 ret = io_ctl_init(&io_ctl, inode, 0);
742 if (ret)
743 return ret;
745 readahead_cache(inode);
747 ret = io_ctl_prepare_pages(&io_ctl, inode, 1);
748 if (ret)
749 goto out;
751 ret = io_ctl_check_crc(&io_ctl, 0);
752 if (ret)
753 goto free_cache;
755 ret = io_ctl_check_generation(&io_ctl, generation);
756 if (ret)
757 goto free_cache;
759 while (num_entries) {
760 e = kmem_cache_zalloc(btrfs_free_space_cachep,
761 GFP_NOFS);
762 if (!e)
763 goto free_cache;
765 ret = io_ctl_read_entry(&io_ctl, e, &type);
766 if (ret) {
767 kmem_cache_free(btrfs_free_space_cachep, e);
768 goto free_cache;
771 if (!e->bytes) {
772 kmem_cache_free(btrfs_free_space_cachep, e);
773 goto free_cache;
776 if (type == BTRFS_FREE_SPACE_EXTENT) {
777 spin_lock(&ctl->tree_lock);
778 ret = link_free_space(ctl, e);
779 spin_unlock(&ctl->tree_lock);
780 if (ret) {
781 btrfs_err(fs_info,
782 "Duplicate entries in free space cache, dumping");
783 kmem_cache_free(btrfs_free_space_cachep, e);
784 goto free_cache;
786 } else {
787 ASSERT(num_bitmaps);
788 num_bitmaps--;
789 e->bitmap = kzalloc(PAGE_SIZE, GFP_NOFS);
790 if (!e->bitmap) {
791 kmem_cache_free(
792 btrfs_free_space_cachep, e);
793 goto free_cache;
795 spin_lock(&ctl->tree_lock);
796 ret = link_free_space(ctl, e);
797 ctl->total_bitmaps++;
798 ctl->op->recalc_thresholds(ctl);
799 spin_unlock(&ctl->tree_lock);
800 if (ret) {
801 btrfs_err(fs_info,
802 "Duplicate entries in free space cache, dumping");
803 kmem_cache_free(btrfs_free_space_cachep, e);
804 goto free_cache;
806 list_add_tail(&e->list, &bitmaps);
809 num_entries--;
812 io_ctl_unmap_page(&io_ctl);
815 * We add the bitmaps at the end of the entries in order that
816 * the bitmap entries are added to the cache.
818 list_for_each_entry_safe(e, n, &bitmaps, list) {
819 list_del_init(&e->list);
820 ret = io_ctl_read_bitmap(&io_ctl, e);
821 if (ret)
822 goto free_cache;
825 io_ctl_drop_pages(&io_ctl);
826 merge_space_tree(ctl);
827 ret = 1;
828 out:
829 io_ctl_free(&io_ctl);
830 return ret;
831 free_cache:
832 io_ctl_drop_pages(&io_ctl);
833 __btrfs_remove_free_space_cache(ctl);
834 goto out;
837 int load_free_space_cache(struct btrfs_fs_info *fs_info,
838 struct btrfs_block_group_cache *block_group)
840 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
841 struct inode *inode;
842 struct btrfs_path *path;
843 int ret = 0;
844 bool matched;
845 u64 used = btrfs_block_group_used(&block_group->item);
848 * If this block group has been marked to be cleared for one reason or
849 * another then we can't trust the on disk cache, so just return.
851 spin_lock(&block_group->lock);
852 if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
853 spin_unlock(&block_group->lock);
854 return 0;
856 spin_unlock(&block_group->lock);
858 path = btrfs_alloc_path();
859 if (!path)
860 return 0;
861 path->search_commit_root = 1;
862 path->skip_locking = 1;
864 inode = lookup_free_space_inode(fs_info, block_group, path);
865 if (IS_ERR(inode)) {
866 btrfs_free_path(path);
867 return 0;
870 /* We may have converted the inode and made the cache invalid. */
871 spin_lock(&block_group->lock);
872 if (block_group->disk_cache_state != BTRFS_DC_WRITTEN) {
873 spin_unlock(&block_group->lock);
874 btrfs_free_path(path);
875 goto out;
877 spin_unlock(&block_group->lock);
879 ret = __load_free_space_cache(fs_info->tree_root, inode, ctl,
880 path, block_group->key.objectid);
881 btrfs_free_path(path);
882 if (ret <= 0)
883 goto out;
885 spin_lock(&ctl->tree_lock);
886 matched = (ctl->free_space == (block_group->key.offset - used -
887 block_group->bytes_super));
888 spin_unlock(&ctl->tree_lock);
890 if (!matched) {
891 __btrfs_remove_free_space_cache(ctl);
892 btrfs_warn(fs_info,
893 "block group %llu has wrong amount of free space",
894 block_group->key.objectid);
895 ret = -1;
897 out:
898 if (ret < 0) {
899 /* This cache is bogus, make sure it gets cleared */
900 spin_lock(&block_group->lock);
901 block_group->disk_cache_state = BTRFS_DC_CLEAR;
902 spin_unlock(&block_group->lock);
903 ret = 0;
905 btrfs_warn(fs_info,
906 "failed to load free space cache for block group %llu, rebuilding it now",
907 block_group->key.objectid);
910 iput(inode);
911 return ret;
914 static noinline_for_stack
915 int write_cache_extent_entries(struct btrfs_io_ctl *io_ctl,
916 struct btrfs_free_space_ctl *ctl,
917 struct btrfs_block_group_cache *block_group,
918 int *entries, int *bitmaps,
919 struct list_head *bitmap_list)
921 int ret;
922 struct btrfs_free_cluster *cluster = NULL;
923 struct btrfs_free_cluster *cluster_locked = NULL;
924 struct rb_node *node = rb_first(&ctl->free_space_offset);
925 struct btrfs_trim_range *trim_entry;
927 /* Get the cluster for this block_group if it exists */
928 if (block_group && !list_empty(&block_group->cluster_list)) {
929 cluster = list_entry(block_group->cluster_list.next,
930 struct btrfs_free_cluster,
931 block_group_list);
934 if (!node && cluster) {
935 cluster_locked = cluster;
936 spin_lock(&cluster_locked->lock);
937 node = rb_first(&cluster->root);
938 cluster = NULL;
941 /* Write out the extent entries */
942 while (node) {
943 struct btrfs_free_space *e;
945 e = rb_entry(node, struct btrfs_free_space, offset_index);
946 *entries += 1;
948 ret = io_ctl_add_entry(io_ctl, e->offset, e->bytes,
949 e->bitmap);
950 if (ret)
951 goto fail;
953 if (e->bitmap) {
954 list_add_tail(&e->list, bitmap_list);
955 *bitmaps += 1;
957 node = rb_next(node);
958 if (!node && cluster) {
959 node = rb_first(&cluster->root);
960 cluster_locked = cluster;
961 spin_lock(&cluster_locked->lock);
962 cluster = NULL;
965 if (cluster_locked) {
966 spin_unlock(&cluster_locked->lock);
967 cluster_locked = NULL;
971 * Make sure we don't miss any range that was removed from our rbtree
972 * because trimming is running. Otherwise after a umount+mount (or crash
973 * after committing the transaction) we would leak free space and get
974 * an inconsistent free space cache report from fsck.
976 list_for_each_entry(trim_entry, &ctl->trimming_ranges, list) {
977 ret = io_ctl_add_entry(io_ctl, trim_entry->start,
978 trim_entry->bytes, NULL);
979 if (ret)
980 goto fail;
981 *entries += 1;
984 return 0;
985 fail:
986 if (cluster_locked)
987 spin_unlock(&cluster_locked->lock);
988 return -ENOSPC;
991 static noinline_for_stack int
992 update_cache_item(struct btrfs_trans_handle *trans,
993 struct btrfs_root *root,
994 struct inode *inode,
995 struct btrfs_path *path, u64 offset,
996 int entries, int bitmaps)
998 struct btrfs_key key;
999 struct btrfs_free_space_header *header;
1000 struct extent_buffer *leaf;
1001 int ret;
1003 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
1004 key.offset = offset;
1005 key.type = 0;
1007 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
1008 if (ret < 0) {
1009 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1,
1010 EXTENT_DIRTY | EXTENT_DELALLOC, 0, 0, NULL,
1011 GFP_NOFS);
1012 goto fail;
1014 leaf = path->nodes[0];
1015 if (ret > 0) {
1016 struct btrfs_key found_key;
1017 ASSERT(path->slots[0]);
1018 path->slots[0]--;
1019 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1020 if (found_key.objectid != BTRFS_FREE_SPACE_OBJECTID ||
1021 found_key.offset != offset) {
1022 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0,
1023 inode->i_size - 1,
1024 EXTENT_DIRTY | EXTENT_DELALLOC, 0, 0,
1025 NULL, GFP_NOFS);
1026 btrfs_release_path(path);
1027 goto fail;
1031 BTRFS_I(inode)->generation = trans->transid;
1032 header = btrfs_item_ptr(leaf, path->slots[0],
1033 struct btrfs_free_space_header);
1034 btrfs_set_free_space_entries(leaf, header, entries);
1035 btrfs_set_free_space_bitmaps(leaf, header, bitmaps);
1036 btrfs_set_free_space_generation(leaf, header, trans->transid);
1037 btrfs_mark_buffer_dirty(leaf);
1038 btrfs_release_path(path);
1040 return 0;
1042 fail:
1043 return -1;
1046 static noinline_for_stack int
1047 write_pinned_extent_entries(struct btrfs_fs_info *fs_info,
1048 struct btrfs_block_group_cache *block_group,
1049 struct btrfs_io_ctl *io_ctl,
1050 int *entries)
1052 u64 start, extent_start, extent_end, len;
1053 struct extent_io_tree *unpin = NULL;
1054 int ret;
1056 if (!block_group)
1057 return 0;
1060 * We want to add any pinned extents to our free space cache
1061 * so we don't leak the space
1063 * We shouldn't have switched the pinned extents yet so this is the
1064 * right one
1066 unpin = fs_info->pinned_extents;
1068 start = block_group->key.objectid;
1070 while (start < block_group->key.objectid + block_group->key.offset) {
1071 ret = find_first_extent_bit(unpin, start,
1072 &extent_start, &extent_end,
1073 EXTENT_DIRTY, NULL);
1074 if (ret)
1075 return 0;
1077 /* This pinned extent is out of our range */
1078 if (extent_start >= block_group->key.objectid +
1079 block_group->key.offset)
1080 return 0;
1082 extent_start = max(extent_start, start);
1083 extent_end = min(block_group->key.objectid +
1084 block_group->key.offset, extent_end + 1);
1085 len = extent_end - extent_start;
1087 *entries += 1;
1088 ret = io_ctl_add_entry(io_ctl, extent_start, len, NULL);
1089 if (ret)
1090 return -ENOSPC;
1092 start = extent_end;
1095 return 0;
1098 static noinline_for_stack int
1099 write_bitmap_entries(struct btrfs_io_ctl *io_ctl, struct list_head *bitmap_list)
1101 struct btrfs_free_space *entry, *next;
1102 int ret;
1104 /* Write out the bitmaps */
1105 list_for_each_entry_safe(entry, next, bitmap_list, list) {
1106 ret = io_ctl_add_bitmap(io_ctl, entry->bitmap);
1107 if (ret)
1108 return -ENOSPC;
1109 list_del_init(&entry->list);
1112 return 0;
1115 static int flush_dirty_cache(struct inode *inode)
1117 int ret;
1119 ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
1120 if (ret)
1121 clear_extent_bit(&BTRFS_I(inode)->io_tree, 0, inode->i_size - 1,
1122 EXTENT_DIRTY | EXTENT_DELALLOC, 0, 0, NULL,
1123 GFP_NOFS);
1125 return ret;
1128 static void noinline_for_stack
1129 cleanup_bitmap_list(struct list_head *bitmap_list)
1131 struct btrfs_free_space *entry, *next;
1133 list_for_each_entry_safe(entry, next, bitmap_list, list)
1134 list_del_init(&entry->list);
1137 static void noinline_for_stack
1138 cleanup_write_cache_enospc(struct inode *inode,
1139 struct btrfs_io_ctl *io_ctl,
1140 struct extent_state **cached_state)
1142 io_ctl_drop_pages(io_ctl);
1143 unlock_extent_cached(&BTRFS_I(inode)->io_tree, 0,
1144 i_size_read(inode) - 1, cached_state,
1145 GFP_NOFS);
1148 static int __btrfs_wait_cache_io(struct btrfs_root *root,
1149 struct btrfs_trans_handle *trans,
1150 struct btrfs_block_group_cache *block_group,
1151 struct btrfs_io_ctl *io_ctl,
1152 struct btrfs_path *path, u64 offset)
1154 int ret;
1155 struct inode *inode = io_ctl->inode;
1156 struct btrfs_fs_info *fs_info;
1158 if (!inode)
1159 return 0;
1161 fs_info = btrfs_sb(inode->i_sb);
1163 /* Flush the dirty pages in the cache file. */
1164 ret = flush_dirty_cache(inode);
1165 if (ret)
1166 goto out;
1168 /* Update the cache item to tell everyone this cache file is valid. */
1169 ret = update_cache_item(trans, root, inode, path, offset,
1170 io_ctl->entries, io_ctl->bitmaps);
1171 out:
1172 if (ret) {
1173 invalidate_inode_pages2(inode->i_mapping);
1174 BTRFS_I(inode)->generation = 0;
1175 if (block_group) {
1176 #ifdef DEBUG
1177 btrfs_err(fs_info,
1178 "failed to write free space cache for block group %llu",
1179 block_group->key.objectid);
1180 #endif
1183 btrfs_update_inode(trans, root, inode);
1185 if (block_group) {
1186 /* the dirty list is protected by the dirty_bgs_lock */
1187 spin_lock(&trans->transaction->dirty_bgs_lock);
1189 /* the disk_cache_state is protected by the block group lock */
1190 spin_lock(&block_group->lock);
1193 * only mark this as written if we didn't get put back on
1194 * the dirty list while waiting for IO. Otherwise our
1195 * cache state won't be right, and we won't get written again
1197 if (!ret && list_empty(&block_group->dirty_list))
1198 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1199 else if (ret)
1200 block_group->disk_cache_state = BTRFS_DC_ERROR;
1202 spin_unlock(&block_group->lock);
1203 spin_unlock(&trans->transaction->dirty_bgs_lock);
1204 io_ctl->inode = NULL;
1205 iput(inode);
1208 return ret;
1212 static int btrfs_wait_cache_io_root(struct btrfs_root *root,
1213 struct btrfs_trans_handle *trans,
1214 struct btrfs_io_ctl *io_ctl,
1215 struct btrfs_path *path)
1217 return __btrfs_wait_cache_io(root, trans, NULL, io_ctl, path, 0);
1220 int btrfs_wait_cache_io(struct btrfs_trans_handle *trans,
1221 struct btrfs_block_group_cache *block_group,
1222 struct btrfs_path *path)
1224 return __btrfs_wait_cache_io(block_group->fs_info->tree_root, trans,
1225 block_group, &block_group->io_ctl,
1226 path, block_group->key.objectid);
1230 * __btrfs_write_out_cache - write out cached info to an inode
1231 * @root - the root the inode belongs to
1232 * @ctl - the free space cache we are going to write out
1233 * @block_group - the block_group for this cache if it belongs to a block_group
1234 * @trans - the trans handle
1236 * This function writes out a free space cache struct to disk for quick recovery
1237 * on mount. This will return 0 if it was successful in writing the cache out,
1238 * or an errno if it was not.
1240 static int __btrfs_write_out_cache(struct btrfs_root *root, struct inode *inode,
1241 struct btrfs_free_space_ctl *ctl,
1242 struct btrfs_block_group_cache *block_group,
1243 struct btrfs_io_ctl *io_ctl,
1244 struct btrfs_trans_handle *trans)
1246 struct btrfs_fs_info *fs_info = root->fs_info;
1247 struct extent_state *cached_state = NULL;
1248 LIST_HEAD(bitmap_list);
1249 int entries = 0;
1250 int bitmaps = 0;
1251 int ret;
1252 int must_iput = 0;
1254 if (!i_size_read(inode))
1255 return -EIO;
1257 WARN_ON(io_ctl->pages);
1258 ret = io_ctl_init(io_ctl, inode, 1);
1259 if (ret)
1260 return ret;
1262 if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA)) {
1263 down_write(&block_group->data_rwsem);
1264 spin_lock(&block_group->lock);
1265 if (block_group->delalloc_bytes) {
1266 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
1267 spin_unlock(&block_group->lock);
1268 up_write(&block_group->data_rwsem);
1269 BTRFS_I(inode)->generation = 0;
1270 ret = 0;
1271 must_iput = 1;
1272 goto out;
1274 spin_unlock(&block_group->lock);
1277 /* Lock all pages first so we can lock the extent safely. */
1278 ret = io_ctl_prepare_pages(io_ctl, inode, 0);
1279 if (ret)
1280 goto out_unlock;
1282 lock_extent_bits(&BTRFS_I(inode)->io_tree, 0, i_size_read(inode) - 1,
1283 &cached_state);
1285 io_ctl_set_generation(io_ctl, trans->transid);
1287 mutex_lock(&ctl->cache_writeout_mutex);
1288 /* Write out the extent entries in the free space cache */
1289 spin_lock(&ctl->tree_lock);
1290 ret = write_cache_extent_entries(io_ctl, ctl,
1291 block_group, &entries, &bitmaps,
1292 &bitmap_list);
1293 if (ret)
1294 goto out_nospc_locked;
1297 * Some spaces that are freed in the current transaction are pinned,
1298 * they will be added into free space cache after the transaction is
1299 * committed, we shouldn't lose them.
1301 * If this changes while we are working we'll get added back to
1302 * the dirty list and redo it. No locking needed
1304 ret = write_pinned_extent_entries(fs_info, block_group,
1305 io_ctl, &entries);
1306 if (ret)
1307 goto out_nospc_locked;
1310 * At last, we write out all the bitmaps and keep cache_writeout_mutex
1311 * locked while doing it because a concurrent trim can be manipulating
1312 * or freeing the bitmap.
1314 ret = write_bitmap_entries(io_ctl, &bitmap_list);
1315 spin_unlock(&ctl->tree_lock);
1316 mutex_unlock(&ctl->cache_writeout_mutex);
1317 if (ret)
1318 goto out_nospc;
1320 /* Zero out the rest of the pages just to make sure */
1321 io_ctl_zero_remaining_pages(io_ctl);
1323 /* Everything is written out, now we dirty the pages in the file. */
1324 ret = btrfs_dirty_pages(inode, io_ctl->pages, io_ctl->num_pages, 0,
1325 i_size_read(inode), &cached_state);
1326 if (ret)
1327 goto out_nospc;
1329 if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA))
1330 up_write(&block_group->data_rwsem);
1332 * Release the pages and unlock the extent, we will flush
1333 * them out later
1335 io_ctl_drop_pages(io_ctl);
1336 io_ctl_free(io_ctl);
1338 unlock_extent_cached(&BTRFS_I(inode)->io_tree, 0,
1339 i_size_read(inode) - 1, &cached_state, GFP_NOFS);
1342 * at this point the pages are under IO and we're happy,
1343 * The caller is responsible for waiting on them and updating the
1344 * the cache and the inode
1346 io_ctl->entries = entries;
1347 io_ctl->bitmaps = bitmaps;
1349 ret = btrfs_fdatawrite_range(inode, 0, (u64)-1);
1350 if (ret)
1351 goto out;
1353 return 0;
1355 out:
1356 io_ctl->inode = NULL;
1357 io_ctl_free(io_ctl);
1358 if (ret) {
1359 invalidate_inode_pages2(inode->i_mapping);
1360 BTRFS_I(inode)->generation = 0;
1362 btrfs_update_inode(trans, root, inode);
1363 if (must_iput)
1364 iput(inode);
1365 return ret;
1367 out_nospc_locked:
1368 cleanup_bitmap_list(&bitmap_list);
1369 spin_unlock(&ctl->tree_lock);
1370 mutex_unlock(&ctl->cache_writeout_mutex);
1372 out_nospc:
1373 cleanup_write_cache_enospc(inode, io_ctl, &cached_state);
1375 out_unlock:
1376 if (block_group && (block_group->flags & BTRFS_BLOCK_GROUP_DATA))
1377 up_write(&block_group->data_rwsem);
1379 goto out;
1382 int btrfs_write_out_cache(struct btrfs_fs_info *fs_info,
1383 struct btrfs_trans_handle *trans,
1384 struct btrfs_block_group_cache *block_group,
1385 struct btrfs_path *path)
1387 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
1388 struct inode *inode;
1389 int ret = 0;
1391 spin_lock(&block_group->lock);
1392 if (block_group->disk_cache_state < BTRFS_DC_SETUP) {
1393 spin_unlock(&block_group->lock);
1394 return 0;
1396 spin_unlock(&block_group->lock);
1398 inode = lookup_free_space_inode(fs_info, block_group, path);
1399 if (IS_ERR(inode))
1400 return 0;
1402 ret = __btrfs_write_out_cache(fs_info->tree_root, inode, ctl,
1403 block_group, &block_group->io_ctl, trans);
1404 if (ret) {
1405 #ifdef DEBUG
1406 btrfs_err(fs_info,
1407 "failed to write free space cache for block group %llu",
1408 block_group->key.objectid);
1409 #endif
1410 spin_lock(&block_group->lock);
1411 block_group->disk_cache_state = BTRFS_DC_ERROR;
1412 spin_unlock(&block_group->lock);
1414 block_group->io_ctl.inode = NULL;
1415 iput(inode);
1419 * if ret == 0 the caller is expected to call btrfs_wait_cache_io
1420 * to wait for IO and put the inode
1423 return ret;
1426 static inline unsigned long offset_to_bit(u64 bitmap_start, u32 unit,
1427 u64 offset)
1429 ASSERT(offset >= bitmap_start);
1430 offset -= bitmap_start;
1431 return (unsigned long)(div_u64(offset, unit));
1434 static inline unsigned long bytes_to_bits(u64 bytes, u32 unit)
1436 return (unsigned long)(div_u64(bytes, unit));
1439 static inline u64 offset_to_bitmap(struct btrfs_free_space_ctl *ctl,
1440 u64 offset)
1442 u64 bitmap_start;
1443 u64 bytes_per_bitmap;
1445 bytes_per_bitmap = BITS_PER_BITMAP * ctl->unit;
1446 bitmap_start = offset - ctl->start;
1447 bitmap_start = div64_u64(bitmap_start, bytes_per_bitmap);
1448 bitmap_start *= bytes_per_bitmap;
1449 bitmap_start += ctl->start;
1451 return bitmap_start;
1454 static int tree_insert_offset(struct rb_root *root, u64 offset,
1455 struct rb_node *node, int bitmap)
1457 struct rb_node **p = &root->rb_node;
1458 struct rb_node *parent = NULL;
1459 struct btrfs_free_space *info;
1461 while (*p) {
1462 parent = *p;
1463 info = rb_entry(parent, struct btrfs_free_space, offset_index);
1465 if (offset < info->offset) {
1466 p = &(*p)->rb_left;
1467 } else if (offset > info->offset) {
1468 p = &(*p)->rb_right;
1469 } else {
1471 * we could have a bitmap entry and an extent entry
1472 * share the same offset. If this is the case, we want
1473 * the extent entry to always be found first if we do a
1474 * linear search through the tree, since we want to have
1475 * the quickest allocation time, and allocating from an
1476 * extent is faster than allocating from a bitmap. So
1477 * if we're inserting a bitmap and we find an entry at
1478 * this offset, we want to go right, or after this entry
1479 * logically. If we are inserting an extent and we've
1480 * found a bitmap, we want to go left, or before
1481 * logically.
1483 if (bitmap) {
1484 if (info->bitmap) {
1485 WARN_ON_ONCE(1);
1486 return -EEXIST;
1488 p = &(*p)->rb_right;
1489 } else {
1490 if (!info->bitmap) {
1491 WARN_ON_ONCE(1);
1492 return -EEXIST;
1494 p = &(*p)->rb_left;
1499 rb_link_node(node, parent, p);
1500 rb_insert_color(node, root);
1502 return 0;
1506 * searches the tree for the given offset.
1508 * fuzzy - If this is set, then we are trying to make an allocation, and we just
1509 * want a section that has at least bytes size and comes at or after the given
1510 * offset.
1512 static struct btrfs_free_space *
1513 tree_search_offset(struct btrfs_free_space_ctl *ctl,
1514 u64 offset, int bitmap_only, int fuzzy)
1516 struct rb_node *n = ctl->free_space_offset.rb_node;
1517 struct btrfs_free_space *entry, *prev = NULL;
1519 /* find entry that is closest to the 'offset' */
1520 while (1) {
1521 if (!n) {
1522 entry = NULL;
1523 break;
1526 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1527 prev = entry;
1529 if (offset < entry->offset)
1530 n = n->rb_left;
1531 else if (offset > entry->offset)
1532 n = n->rb_right;
1533 else
1534 break;
1537 if (bitmap_only) {
1538 if (!entry)
1539 return NULL;
1540 if (entry->bitmap)
1541 return entry;
1544 * bitmap entry and extent entry may share same offset,
1545 * in that case, bitmap entry comes after extent entry.
1547 n = rb_next(n);
1548 if (!n)
1549 return NULL;
1550 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1551 if (entry->offset != offset)
1552 return NULL;
1554 WARN_ON(!entry->bitmap);
1555 return entry;
1556 } else if (entry) {
1557 if (entry->bitmap) {
1559 * if previous extent entry covers the offset,
1560 * we should return it instead of the bitmap entry
1562 n = rb_prev(&entry->offset_index);
1563 if (n) {
1564 prev = rb_entry(n, struct btrfs_free_space,
1565 offset_index);
1566 if (!prev->bitmap &&
1567 prev->offset + prev->bytes > offset)
1568 entry = prev;
1571 return entry;
1574 if (!prev)
1575 return NULL;
1577 /* find last entry before the 'offset' */
1578 entry = prev;
1579 if (entry->offset > offset) {
1580 n = rb_prev(&entry->offset_index);
1581 if (n) {
1582 entry = rb_entry(n, struct btrfs_free_space,
1583 offset_index);
1584 ASSERT(entry->offset <= offset);
1585 } else {
1586 if (fuzzy)
1587 return entry;
1588 else
1589 return NULL;
1593 if (entry->bitmap) {
1594 n = rb_prev(&entry->offset_index);
1595 if (n) {
1596 prev = rb_entry(n, struct btrfs_free_space,
1597 offset_index);
1598 if (!prev->bitmap &&
1599 prev->offset + prev->bytes > offset)
1600 return prev;
1602 if (entry->offset + BITS_PER_BITMAP * ctl->unit > offset)
1603 return entry;
1604 } else if (entry->offset + entry->bytes > offset)
1605 return entry;
1607 if (!fuzzy)
1608 return NULL;
1610 while (1) {
1611 if (entry->bitmap) {
1612 if (entry->offset + BITS_PER_BITMAP *
1613 ctl->unit > offset)
1614 break;
1615 } else {
1616 if (entry->offset + entry->bytes > offset)
1617 break;
1620 n = rb_next(&entry->offset_index);
1621 if (!n)
1622 return NULL;
1623 entry = rb_entry(n, struct btrfs_free_space, offset_index);
1625 return entry;
1628 static inline void
1629 __unlink_free_space(struct btrfs_free_space_ctl *ctl,
1630 struct btrfs_free_space *info)
1632 rb_erase(&info->offset_index, &ctl->free_space_offset);
1633 ctl->free_extents--;
1636 static void unlink_free_space(struct btrfs_free_space_ctl *ctl,
1637 struct btrfs_free_space *info)
1639 __unlink_free_space(ctl, info);
1640 ctl->free_space -= info->bytes;
1643 static int link_free_space(struct btrfs_free_space_ctl *ctl,
1644 struct btrfs_free_space *info)
1646 int ret = 0;
1648 ASSERT(info->bytes || info->bitmap);
1649 ret = tree_insert_offset(&ctl->free_space_offset, info->offset,
1650 &info->offset_index, (info->bitmap != NULL));
1651 if (ret)
1652 return ret;
1654 ctl->free_space += info->bytes;
1655 ctl->free_extents++;
1656 return ret;
1659 static void recalculate_thresholds(struct btrfs_free_space_ctl *ctl)
1661 struct btrfs_block_group_cache *block_group = ctl->private;
1662 u64 max_bytes;
1663 u64 bitmap_bytes;
1664 u64 extent_bytes;
1665 u64 size = block_group->key.offset;
1666 u64 bytes_per_bg = BITS_PER_BITMAP * ctl->unit;
1667 u64 max_bitmaps = div64_u64(size + bytes_per_bg - 1, bytes_per_bg);
1669 max_bitmaps = max_t(u64, max_bitmaps, 1);
1671 ASSERT(ctl->total_bitmaps <= max_bitmaps);
1674 * The goal is to keep the total amount of memory used per 1gb of space
1675 * at or below 32k, so we need to adjust how much memory we allow to be
1676 * used by extent based free space tracking
1678 if (size < SZ_1G)
1679 max_bytes = MAX_CACHE_BYTES_PER_GIG;
1680 else
1681 max_bytes = MAX_CACHE_BYTES_PER_GIG * div_u64(size, SZ_1G);
1684 * we want to account for 1 more bitmap than what we have so we can make
1685 * sure we don't go over our overall goal of MAX_CACHE_BYTES_PER_GIG as
1686 * we add more bitmaps.
1688 bitmap_bytes = (ctl->total_bitmaps + 1) * ctl->unit;
1690 if (bitmap_bytes >= max_bytes) {
1691 ctl->extents_thresh = 0;
1692 return;
1696 * we want the extent entry threshold to always be at most 1/2 the max
1697 * bytes we can have, or whatever is less than that.
1699 extent_bytes = max_bytes - bitmap_bytes;
1700 extent_bytes = min_t(u64, extent_bytes, max_bytes >> 1);
1702 ctl->extents_thresh =
1703 div_u64(extent_bytes, sizeof(struct btrfs_free_space));
1706 static inline void __bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
1707 struct btrfs_free_space *info,
1708 u64 offset, u64 bytes)
1710 unsigned long start, count;
1712 start = offset_to_bit(info->offset, ctl->unit, offset);
1713 count = bytes_to_bits(bytes, ctl->unit);
1714 ASSERT(start + count <= BITS_PER_BITMAP);
1716 bitmap_clear(info->bitmap, start, count);
1718 info->bytes -= bytes;
1719 if (info->max_extent_size > ctl->unit)
1720 info->max_extent_size = 0;
1723 static void bitmap_clear_bits(struct btrfs_free_space_ctl *ctl,
1724 struct btrfs_free_space *info, u64 offset,
1725 u64 bytes)
1727 __bitmap_clear_bits(ctl, info, offset, bytes);
1728 ctl->free_space -= bytes;
1731 static void bitmap_set_bits(struct btrfs_free_space_ctl *ctl,
1732 struct btrfs_free_space *info, u64 offset,
1733 u64 bytes)
1735 unsigned long start, count;
1737 start = offset_to_bit(info->offset, ctl->unit, offset);
1738 count = bytes_to_bits(bytes, ctl->unit);
1739 ASSERT(start + count <= BITS_PER_BITMAP);
1741 bitmap_set(info->bitmap, start, count);
1743 info->bytes += bytes;
1744 ctl->free_space += bytes;
1748 * If we can not find suitable extent, we will use bytes to record
1749 * the size of the max extent.
1751 static int search_bitmap(struct btrfs_free_space_ctl *ctl,
1752 struct btrfs_free_space *bitmap_info, u64 *offset,
1753 u64 *bytes, bool for_alloc)
1755 unsigned long found_bits = 0;
1756 unsigned long max_bits = 0;
1757 unsigned long bits, i;
1758 unsigned long next_zero;
1759 unsigned long extent_bits;
1762 * Skip searching the bitmap if we don't have a contiguous section that
1763 * is large enough for this allocation.
1765 if (for_alloc &&
1766 bitmap_info->max_extent_size &&
1767 bitmap_info->max_extent_size < *bytes) {
1768 *bytes = bitmap_info->max_extent_size;
1769 return -1;
1772 i = offset_to_bit(bitmap_info->offset, ctl->unit,
1773 max_t(u64, *offset, bitmap_info->offset));
1774 bits = bytes_to_bits(*bytes, ctl->unit);
1776 for_each_set_bit_from(i, bitmap_info->bitmap, BITS_PER_BITMAP) {
1777 if (for_alloc && bits == 1) {
1778 found_bits = 1;
1779 break;
1781 next_zero = find_next_zero_bit(bitmap_info->bitmap,
1782 BITS_PER_BITMAP, i);
1783 extent_bits = next_zero - i;
1784 if (extent_bits >= bits) {
1785 found_bits = extent_bits;
1786 break;
1787 } else if (extent_bits > max_bits) {
1788 max_bits = extent_bits;
1790 i = next_zero;
1793 if (found_bits) {
1794 *offset = (u64)(i * ctl->unit) + bitmap_info->offset;
1795 *bytes = (u64)(found_bits) * ctl->unit;
1796 return 0;
1799 *bytes = (u64)(max_bits) * ctl->unit;
1800 bitmap_info->max_extent_size = *bytes;
1801 return -1;
1804 static inline u64 get_max_extent_size(struct btrfs_free_space *entry)
1806 if (entry->bitmap)
1807 return entry->max_extent_size;
1808 return entry->bytes;
1811 /* Cache the size of the max extent in bytes */
1812 static struct btrfs_free_space *
1813 find_free_space(struct btrfs_free_space_ctl *ctl, u64 *offset, u64 *bytes,
1814 unsigned long align, u64 *max_extent_size)
1816 struct btrfs_free_space *entry;
1817 struct rb_node *node;
1818 u64 tmp;
1819 u64 align_off;
1820 int ret;
1822 if (!ctl->free_space_offset.rb_node)
1823 goto out;
1825 entry = tree_search_offset(ctl, offset_to_bitmap(ctl, *offset), 0, 1);
1826 if (!entry)
1827 goto out;
1829 for (node = &entry->offset_index; node; node = rb_next(node)) {
1830 entry = rb_entry(node, struct btrfs_free_space, offset_index);
1831 if (entry->bytes < *bytes) {
1832 *max_extent_size = max(get_max_extent_size(entry),
1833 *max_extent_size);
1834 continue;
1837 /* make sure the space returned is big enough
1838 * to match our requested alignment
1840 if (*bytes >= align) {
1841 tmp = entry->offset - ctl->start + align - 1;
1842 tmp = div64_u64(tmp, align);
1843 tmp = tmp * align + ctl->start;
1844 align_off = tmp - entry->offset;
1845 } else {
1846 align_off = 0;
1847 tmp = entry->offset;
1850 if (entry->bytes < *bytes + align_off) {
1851 *max_extent_size = max(get_max_extent_size(entry),
1852 *max_extent_size);
1853 continue;
1856 if (entry->bitmap) {
1857 u64 size = *bytes;
1859 ret = search_bitmap(ctl, entry, &tmp, &size, true);
1860 if (!ret) {
1861 *offset = tmp;
1862 *bytes = size;
1863 return entry;
1864 } else {
1865 *max_extent_size =
1866 max(get_max_extent_size(entry),
1867 *max_extent_size);
1869 continue;
1872 *offset = tmp;
1873 *bytes = entry->bytes - align_off;
1874 return entry;
1876 out:
1877 return NULL;
1880 static void add_new_bitmap(struct btrfs_free_space_ctl *ctl,
1881 struct btrfs_free_space *info, u64 offset)
1883 info->offset = offset_to_bitmap(ctl, offset);
1884 info->bytes = 0;
1885 INIT_LIST_HEAD(&info->list);
1886 link_free_space(ctl, info);
1887 ctl->total_bitmaps++;
1889 ctl->op->recalc_thresholds(ctl);
1892 static void free_bitmap(struct btrfs_free_space_ctl *ctl,
1893 struct btrfs_free_space *bitmap_info)
1895 unlink_free_space(ctl, bitmap_info);
1896 kfree(bitmap_info->bitmap);
1897 kmem_cache_free(btrfs_free_space_cachep, bitmap_info);
1898 ctl->total_bitmaps--;
1899 ctl->op->recalc_thresholds(ctl);
1902 static noinline int remove_from_bitmap(struct btrfs_free_space_ctl *ctl,
1903 struct btrfs_free_space *bitmap_info,
1904 u64 *offset, u64 *bytes)
1906 u64 end;
1907 u64 search_start, search_bytes;
1908 int ret;
1910 again:
1911 end = bitmap_info->offset + (u64)(BITS_PER_BITMAP * ctl->unit) - 1;
1914 * We need to search for bits in this bitmap. We could only cover some
1915 * of the extent in this bitmap thanks to how we add space, so we need
1916 * to search for as much as it as we can and clear that amount, and then
1917 * go searching for the next bit.
1919 search_start = *offset;
1920 search_bytes = ctl->unit;
1921 search_bytes = min(search_bytes, end - search_start + 1);
1922 ret = search_bitmap(ctl, bitmap_info, &search_start, &search_bytes,
1923 false);
1924 if (ret < 0 || search_start != *offset)
1925 return -EINVAL;
1927 /* We may have found more bits than what we need */
1928 search_bytes = min(search_bytes, *bytes);
1930 /* Cannot clear past the end of the bitmap */
1931 search_bytes = min(search_bytes, end - search_start + 1);
1933 bitmap_clear_bits(ctl, bitmap_info, search_start, search_bytes);
1934 *offset += search_bytes;
1935 *bytes -= search_bytes;
1937 if (*bytes) {
1938 struct rb_node *next = rb_next(&bitmap_info->offset_index);
1939 if (!bitmap_info->bytes)
1940 free_bitmap(ctl, bitmap_info);
1943 * no entry after this bitmap, but we still have bytes to
1944 * remove, so something has gone wrong.
1946 if (!next)
1947 return -EINVAL;
1949 bitmap_info = rb_entry(next, struct btrfs_free_space,
1950 offset_index);
1953 * if the next entry isn't a bitmap we need to return to let the
1954 * extent stuff do its work.
1956 if (!bitmap_info->bitmap)
1957 return -EAGAIN;
1960 * Ok the next item is a bitmap, but it may not actually hold
1961 * the information for the rest of this free space stuff, so
1962 * look for it, and if we don't find it return so we can try
1963 * everything over again.
1965 search_start = *offset;
1966 search_bytes = ctl->unit;
1967 ret = search_bitmap(ctl, bitmap_info, &search_start,
1968 &search_bytes, false);
1969 if (ret < 0 || search_start != *offset)
1970 return -EAGAIN;
1972 goto again;
1973 } else if (!bitmap_info->bytes)
1974 free_bitmap(ctl, bitmap_info);
1976 return 0;
1979 static u64 add_bytes_to_bitmap(struct btrfs_free_space_ctl *ctl,
1980 struct btrfs_free_space *info, u64 offset,
1981 u64 bytes)
1983 u64 bytes_to_set = 0;
1984 u64 end;
1986 end = info->offset + (u64)(BITS_PER_BITMAP * ctl->unit);
1988 bytes_to_set = min(end - offset, bytes);
1990 bitmap_set_bits(ctl, info, offset, bytes_to_set);
1993 * We set some bytes, we have no idea what the max extent size is
1994 * anymore.
1996 info->max_extent_size = 0;
1998 return bytes_to_set;
2002 static bool use_bitmap(struct btrfs_free_space_ctl *ctl,
2003 struct btrfs_free_space *info)
2005 struct btrfs_block_group_cache *block_group = ctl->private;
2006 struct btrfs_fs_info *fs_info = block_group->fs_info;
2007 bool forced = false;
2009 #ifdef CONFIG_BTRFS_DEBUG
2010 if (btrfs_should_fragment_free_space(block_group))
2011 forced = true;
2012 #endif
2015 * If we are below the extents threshold then we can add this as an
2016 * extent, and don't have to deal with the bitmap
2018 if (!forced && ctl->free_extents < ctl->extents_thresh) {
2020 * If this block group has some small extents we don't want to
2021 * use up all of our free slots in the cache with them, we want
2022 * to reserve them to larger extents, however if we have plenty
2023 * of cache left then go ahead an dadd them, no sense in adding
2024 * the overhead of a bitmap if we don't have to.
2026 if (info->bytes <= fs_info->sectorsize * 4) {
2027 if (ctl->free_extents * 2 <= ctl->extents_thresh)
2028 return false;
2029 } else {
2030 return false;
2035 * The original block groups from mkfs can be really small, like 8
2036 * megabytes, so don't bother with a bitmap for those entries. However
2037 * some block groups can be smaller than what a bitmap would cover but
2038 * are still large enough that they could overflow the 32k memory limit,
2039 * so allow those block groups to still be allowed to have a bitmap
2040 * entry.
2042 if (((BITS_PER_BITMAP * ctl->unit) >> 1) > block_group->key.offset)
2043 return false;
2045 return true;
2048 static const struct btrfs_free_space_op free_space_op = {
2049 .recalc_thresholds = recalculate_thresholds,
2050 .use_bitmap = use_bitmap,
2053 static int insert_into_bitmap(struct btrfs_free_space_ctl *ctl,
2054 struct btrfs_free_space *info)
2056 struct btrfs_free_space *bitmap_info;
2057 struct btrfs_block_group_cache *block_group = NULL;
2058 int added = 0;
2059 u64 bytes, offset, bytes_added;
2060 int ret;
2062 bytes = info->bytes;
2063 offset = info->offset;
2065 if (!ctl->op->use_bitmap(ctl, info))
2066 return 0;
2068 if (ctl->op == &free_space_op)
2069 block_group = ctl->private;
2070 again:
2072 * Since we link bitmaps right into the cluster we need to see if we
2073 * have a cluster here, and if so and it has our bitmap we need to add
2074 * the free space to that bitmap.
2076 if (block_group && !list_empty(&block_group->cluster_list)) {
2077 struct btrfs_free_cluster *cluster;
2078 struct rb_node *node;
2079 struct btrfs_free_space *entry;
2081 cluster = list_entry(block_group->cluster_list.next,
2082 struct btrfs_free_cluster,
2083 block_group_list);
2084 spin_lock(&cluster->lock);
2085 node = rb_first(&cluster->root);
2086 if (!node) {
2087 spin_unlock(&cluster->lock);
2088 goto no_cluster_bitmap;
2091 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2092 if (!entry->bitmap) {
2093 spin_unlock(&cluster->lock);
2094 goto no_cluster_bitmap;
2097 if (entry->offset == offset_to_bitmap(ctl, offset)) {
2098 bytes_added = add_bytes_to_bitmap(ctl, entry,
2099 offset, bytes);
2100 bytes -= bytes_added;
2101 offset += bytes_added;
2103 spin_unlock(&cluster->lock);
2104 if (!bytes) {
2105 ret = 1;
2106 goto out;
2110 no_cluster_bitmap:
2111 bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
2112 1, 0);
2113 if (!bitmap_info) {
2114 ASSERT(added == 0);
2115 goto new_bitmap;
2118 bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes);
2119 bytes -= bytes_added;
2120 offset += bytes_added;
2121 added = 0;
2123 if (!bytes) {
2124 ret = 1;
2125 goto out;
2126 } else
2127 goto again;
2129 new_bitmap:
2130 if (info && info->bitmap) {
2131 add_new_bitmap(ctl, info, offset);
2132 added = 1;
2133 info = NULL;
2134 goto again;
2135 } else {
2136 spin_unlock(&ctl->tree_lock);
2138 /* no pre-allocated info, allocate a new one */
2139 if (!info) {
2140 info = kmem_cache_zalloc(btrfs_free_space_cachep,
2141 GFP_NOFS);
2142 if (!info) {
2143 spin_lock(&ctl->tree_lock);
2144 ret = -ENOMEM;
2145 goto out;
2149 /* allocate the bitmap */
2150 info->bitmap = kzalloc(PAGE_SIZE, GFP_NOFS);
2151 spin_lock(&ctl->tree_lock);
2152 if (!info->bitmap) {
2153 ret = -ENOMEM;
2154 goto out;
2156 goto again;
2159 out:
2160 if (info) {
2161 if (info->bitmap)
2162 kfree(info->bitmap);
2163 kmem_cache_free(btrfs_free_space_cachep, info);
2166 return ret;
2169 static bool try_merge_free_space(struct btrfs_free_space_ctl *ctl,
2170 struct btrfs_free_space *info, bool update_stat)
2172 struct btrfs_free_space *left_info = NULL;
2173 struct btrfs_free_space *right_info;
2174 bool merged = false;
2175 u64 offset = info->offset;
2176 u64 bytes = info->bytes;
2179 * first we want to see if there is free space adjacent to the range we
2180 * are adding, if there is remove that struct and add a new one to
2181 * cover the entire range
2183 right_info = tree_search_offset(ctl, offset + bytes, 0, 0);
2184 if (right_info && rb_prev(&right_info->offset_index))
2185 left_info = rb_entry(rb_prev(&right_info->offset_index),
2186 struct btrfs_free_space, offset_index);
2187 else if (!right_info)
2188 left_info = tree_search_offset(ctl, offset - 1, 0, 0);
2190 if (right_info && !right_info->bitmap) {
2191 if (update_stat)
2192 unlink_free_space(ctl, right_info);
2193 else
2194 __unlink_free_space(ctl, right_info);
2195 info->bytes += right_info->bytes;
2196 kmem_cache_free(btrfs_free_space_cachep, right_info);
2197 merged = true;
2200 if (left_info && !left_info->bitmap &&
2201 left_info->offset + left_info->bytes == offset) {
2202 if (update_stat)
2203 unlink_free_space(ctl, left_info);
2204 else
2205 __unlink_free_space(ctl, left_info);
2206 info->offset = left_info->offset;
2207 info->bytes += left_info->bytes;
2208 kmem_cache_free(btrfs_free_space_cachep, left_info);
2209 merged = true;
2212 return merged;
2215 static bool steal_from_bitmap_to_end(struct btrfs_free_space_ctl *ctl,
2216 struct btrfs_free_space *info,
2217 bool update_stat)
2219 struct btrfs_free_space *bitmap;
2220 unsigned long i;
2221 unsigned long j;
2222 const u64 end = info->offset + info->bytes;
2223 const u64 bitmap_offset = offset_to_bitmap(ctl, end);
2224 u64 bytes;
2226 bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0);
2227 if (!bitmap)
2228 return false;
2230 i = offset_to_bit(bitmap->offset, ctl->unit, end);
2231 j = find_next_zero_bit(bitmap->bitmap, BITS_PER_BITMAP, i);
2232 if (j == i)
2233 return false;
2234 bytes = (j - i) * ctl->unit;
2235 info->bytes += bytes;
2237 if (update_stat)
2238 bitmap_clear_bits(ctl, bitmap, end, bytes);
2239 else
2240 __bitmap_clear_bits(ctl, bitmap, end, bytes);
2242 if (!bitmap->bytes)
2243 free_bitmap(ctl, bitmap);
2245 return true;
2248 static bool steal_from_bitmap_to_front(struct btrfs_free_space_ctl *ctl,
2249 struct btrfs_free_space *info,
2250 bool update_stat)
2252 struct btrfs_free_space *bitmap;
2253 u64 bitmap_offset;
2254 unsigned long i;
2255 unsigned long j;
2256 unsigned long prev_j;
2257 u64 bytes;
2259 bitmap_offset = offset_to_bitmap(ctl, info->offset);
2260 /* If we're on a boundary, try the previous logical bitmap. */
2261 if (bitmap_offset == info->offset) {
2262 if (info->offset == 0)
2263 return false;
2264 bitmap_offset = offset_to_bitmap(ctl, info->offset - 1);
2267 bitmap = tree_search_offset(ctl, bitmap_offset, 1, 0);
2268 if (!bitmap)
2269 return false;
2271 i = offset_to_bit(bitmap->offset, ctl->unit, info->offset) - 1;
2272 j = 0;
2273 prev_j = (unsigned long)-1;
2274 for_each_clear_bit_from(j, bitmap->bitmap, BITS_PER_BITMAP) {
2275 if (j > i)
2276 break;
2277 prev_j = j;
2279 if (prev_j == i)
2280 return false;
2282 if (prev_j == (unsigned long)-1)
2283 bytes = (i + 1) * ctl->unit;
2284 else
2285 bytes = (i - prev_j) * ctl->unit;
2287 info->offset -= bytes;
2288 info->bytes += bytes;
2290 if (update_stat)
2291 bitmap_clear_bits(ctl, bitmap, info->offset, bytes);
2292 else
2293 __bitmap_clear_bits(ctl, bitmap, info->offset, bytes);
2295 if (!bitmap->bytes)
2296 free_bitmap(ctl, bitmap);
2298 return true;
2302 * We prefer always to allocate from extent entries, both for clustered and
2303 * non-clustered allocation requests. So when attempting to add a new extent
2304 * entry, try to see if there's adjacent free space in bitmap entries, and if
2305 * there is, migrate that space from the bitmaps to the extent.
2306 * Like this we get better chances of satisfying space allocation requests
2307 * because we attempt to satisfy them based on a single cache entry, and never
2308 * on 2 or more entries - even if the entries represent a contiguous free space
2309 * region (e.g. 1 extent entry + 1 bitmap entry starting where the extent entry
2310 * ends).
2312 static void steal_from_bitmap(struct btrfs_free_space_ctl *ctl,
2313 struct btrfs_free_space *info,
2314 bool update_stat)
2317 * Only work with disconnected entries, as we can change their offset,
2318 * and must be extent entries.
2320 ASSERT(!info->bitmap);
2321 ASSERT(RB_EMPTY_NODE(&info->offset_index));
2323 if (ctl->total_bitmaps > 0) {
2324 bool stole_end;
2325 bool stole_front = false;
2327 stole_end = steal_from_bitmap_to_end(ctl, info, update_stat);
2328 if (ctl->total_bitmaps > 0)
2329 stole_front = steal_from_bitmap_to_front(ctl, info,
2330 update_stat);
2332 if (stole_end || stole_front)
2333 try_merge_free_space(ctl, info, update_stat);
2337 int __btrfs_add_free_space(struct btrfs_fs_info *fs_info,
2338 struct btrfs_free_space_ctl *ctl,
2339 u64 offset, u64 bytes)
2341 struct btrfs_free_space *info;
2342 int ret = 0;
2344 info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
2345 if (!info)
2346 return -ENOMEM;
2348 info->offset = offset;
2349 info->bytes = bytes;
2350 RB_CLEAR_NODE(&info->offset_index);
2352 spin_lock(&ctl->tree_lock);
2354 if (try_merge_free_space(ctl, info, true))
2355 goto link;
2358 * There was no extent directly to the left or right of this new
2359 * extent then we know we're going to have to allocate a new extent, so
2360 * before we do that see if we need to drop this into a bitmap
2362 ret = insert_into_bitmap(ctl, info);
2363 if (ret < 0) {
2364 goto out;
2365 } else if (ret) {
2366 ret = 0;
2367 goto out;
2369 link:
2371 * Only steal free space from adjacent bitmaps if we're sure we're not
2372 * going to add the new free space to existing bitmap entries - because
2373 * that would mean unnecessary work that would be reverted. Therefore
2374 * attempt to steal space from bitmaps if we're adding an extent entry.
2376 steal_from_bitmap(ctl, info, true);
2378 ret = link_free_space(ctl, info);
2379 if (ret)
2380 kmem_cache_free(btrfs_free_space_cachep, info);
2381 out:
2382 spin_unlock(&ctl->tree_lock);
2384 if (ret) {
2385 btrfs_crit(fs_info, "unable to add free space :%d", ret);
2386 ASSERT(ret != -EEXIST);
2389 return ret;
2392 int btrfs_remove_free_space(struct btrfs_block_group_cache *block_group,
2393 u64 offset, u64 bytes)
2395 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2396 struct btrfs_free_space *info;
2397 int ret;
2398 bool re_search = false;
2400 spin_lock(&ctl->tree_lock);
2402 again:
2403 ret = 0;
2404 if (!bytes)
2405 goto out_lock;
2407 info = tree_search_offset(ctl, offset, 0, 0);
2408 if (!info) {
2410 * oops didn't find an extent that matched the space we wanted
2411 * to remove, look for a bitmap instead
2413 info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
2414 1, 0);
2415 if (!info) {
2417 * If we found a partial bit of our free space in a
2418 * bitmap but then couldn't find the other part this may
2419 * be a problem, so WARN about it.
2421 WARN_ON(re_search);
2422 goto out_lock;
2426 re_search = false;
2427 if (!info->bitmap) {
2428 unlink_free_space(ctl, info);
2429 if (offset == info->offset) {
2430 u64 to_free = min(bytes, info->bytes);
2432 info->bytes -= to_free;
2433 info->offset += to_free;
2434 if (info->bytes) {
2435 ret = link_free_space(ctl, info);
2436 WARN_ON(ret);
2437 } else {
2438 kmem_cache_free(btrfs_free_space_cachep, info);
2441 offset += to_free;
2442 bytes -= to_free;
2443 goto again;
2444 } else {
2445 u64 old_end = info->bytes + info->offset;
2447 info->bytes = offset - info->offset;
2448 ret = link_free_space(ctl, info);
2449 WARN_ON(ret);
2450 if (ret)
2451 goto out_lock;
2453 /* Not enough bytes in this entry to satisfy us */
2454 if (old_end < offset + bytes) {
2455 bytes -= old_end - offset;
2456 offset = old_end;
2457 goto again;
2458 } else if (old_end == offset + bytes) {
2459 /* all done */
2460 goto out_lock;
2462 spin_unlock(&ctl->tree_lock);
2464 ret = btrfs_add_free_space(block_group, offset + bytes,
2465 old_end - (offset + bytes));
2466 WARN_ON(ret);
2467 goto out;
2471 ret = remove_from_bitmap(ctl, info, &offset, &bytes);
2472 if (ret == -EAGAIN) {
2473 re_search = true;
2474 goto again;
2476 out_lock:
2477 spin_unlock(&ctl->tree_lock);
2478 out:
2479 return ret;
2482 void btrfs_dump_free_space(struct btrfs_block_group_cache *block_group,
2483 u64 bytes)
2485 struct btrfs_fs_info *fs_info = block_group->fs_info;
2486 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2487 struct btrfs_free_space *info;
2488 struct rb_node *n;
2489 int count = 0;
2491 spin_lock(&ctl->tree_lock);
2492 for (n = rb_first(&ctl->free_space_offset); n; n = rb_next(n)) {
2493 info = rb_entry(n, struct btrfs_free_space, offset_index);
2494 if (info->bytes >= bytes && !block_group->ro)
2495 count++;
2496 btrfs_crit(fs_info, "entry offset %llu, bytes %llu, bitmap %s",
2497 info->offset, info->bytes,
2498 (info->bitmap) ? "yes" : "no");
2500 spin_unlock(&ctl->tree_lock);
2501 btrfs_info(fs_info, "block group has cluster?: %s",
2502 list_empty(&block_group->cluster_list) ? "no" : "yes");
2503 btrfs_info(fs_info,
2504 "%d blocks of free space at or bigger than bytes is", count);
2507 void btrfs_init_free_space_ctl(struct btrfs_block_group_cache *block_group)
2509 struct btrfs_fs_info *fs_info = block_group->fs_info;
2510 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2512 spin_lock_init(&ctl->tree_lock);
2513 ctl->unit = fs_info->sectorsize;
2514 ctl->start = block_group->key.objectid;
2515 ctl->private = block_group;
2516 ctl->op = &free_space_op;
2517 INIT_LIST_HEAD(&ctl->trimming_ranges);
2518 mutex_init(&ctl->cache_writeout_mutex);
2521 * we only want to have 32k of ram per block group for keeping
2522 * track of free space, and if we pass 1/2 of that we want to
2523 * start converting things over to using bitmaps
2525 ctl->extents_thresh = (SZ_32K / 2) / sizeof(struct btrfs_free_space);
2529 * for a given cluster, put all of its extents back into the free
2530 * space cache. If the block group passed doesn't match the block group
2531 * pointed to by the cluster, someone else raced in and freed the
2532 * cluster already. In that case, we just return without changing anything
2534 static int
2535 __btrfs_return_cluster_to_free_space(
2536 struct btrfs_block_group_cache *block_group,
2537 struct btrfs_free_cluster *cluster)
2539 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2540 struct btrfs_free_space *entry;
2541 struct rb_node *node;
2543 spin_lock(&cluster->lock);
2544 if (cluster->block_group != block_group)
2545 goto out;
2547 cluster->block_group = NULL;
2548 cluster->window_start = 0;
2549 list_del_init(&cluster->block_group_list);
2551 node = rb_first(&cluster->root);
2552 while (node) {
2553 bool bitmap;
2555 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2556 node = rb_next(&entry->offset_index);
2557 rb_erase(&entry->offset_index, &cluster->root);
2558 RB_CLEAR_NODE(&entry->offset_index);
2560 bitmap = (entry->bitmap != NULL);
2561 if (!bitmap) {
2562 try_merge_free_space(ctl, entry, false);
2563 steal_from_bitmap(ctl, entry, false);
2565 tree_insert_offset(&ctl->free_space_offset,
2566 entry->offset, &entry->offset_index, bitmap);
2568 cluster->root = RB_ROOT;
2570 out:
2571 spin_unlock(&cluster->lock);
2572 btrfs_put_block_group(block_group);
2573 return 0;
2576 static void __btrfs_remove_free_space_cache_locked(
2577 struct btrfs_free_space_ctl *ctl)
2579 struct btrfs_free_space *info;
2580 struct rb_node *node;
2582 while ((node = rb_last(&ctl->free_space_offset)) != NULL) {
2583 info = rb_entry(node, struct btrfs_free_space, offset_index);
2584 if (!info->bitmap) {
2585 unlink_free_space(ctl, info);
2586 kmem_cache_free(btrfs_free_space_cachep, info);
2587 } else {
2588 free_bitmap(ctl, info);
2591 cond_resched_lock(&ctl->tree_lock);
2595 void __btrfs_remove_free_space_cache(struct btrfs_free_space_ctl *ctl)
2597 spin_lock(&ctl->tree_lock);
2598 __btrfs_remove_free_space_cache_locked(ctl);
2599 spin_unlock(&ctl->tree_lock);
2602 void btrfs_remove_free_space_cache(struct btrfs_block_group_cache *block_group)
2604 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2605 struct btrfs_free_cluster *cluster;
2606 struct list_head *head;
2608 spin_lock(&ctl->tree_lock);
2609 while ((head = block_group->cluster_list.next) !=
2610 &block_group->cluster_list) {
2611 cluster = list_entry(head, struct btrfs_free_cluster,
2612 block_group_list);
2614 WARN_ON(cluster->block_group != block_group);
2615 __btrfs_return_cluster_to_free_space(block_group, cluster);
2617 cond_resched_lock(&ctl->tree_lock);
2619 __btrfs_remove_free_space_cache_locked(ctl);
2620 spin_unlock(&ctl->tree_lock);
2624 u64 btrfs_find_space_for_alloc(struct btrfs_block_group_cache *block_group,
2625 u64 offset, u64 bytes, u64 empty_size,
2626 u64 *max_extent_size)
2628 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2629 struct btrfs_free_space *entry = NULL;
2630 u64 bytes_search = bytes + empty_size;
2631 u64 ret = 0;
2632 u64 align_gap = 0;
2633 u64 align_gap_len = 0;
2635 spin_lock(&ctl->tree_lock);
2636 entry = find_free_space(ctl, &offset, &bytes_search,
2637 block_group->full_stripe_len, max_extent_size);
2638 if (!entry)
2639 goto out;
2641 ret = offset;
2642 if (entry->bitmap) {
2643 bitmap_clear_bits(ctl, entry, offset, bytes);
2644 if (!entry->bytes)
2645 free_bitmap(ctl, entry);
2646 } else {
2647 unlink_free_space(ctl, entry);
2648 align_gap_len = offset - entry->offset;
2649 align_gap = entry->offset;
2651 entry->offset = offset + bytes;
2652 WARN_ON(entry->bytes < bytes + align_gap_len);
2654 entry->bytes -= bytes + align_gap_len;
2655 if (!entry->bytes)
2656 kmem_cache_free(btrfs_free_space_cachep, entry);
2657 else
2658 link_free_space(ctl, entry);
2660 out:
2661 spin_unlock(&ctl->tree_lock);
2663 if (align_gap_len)
2664 __btrfs_add_free_space(block_group->fs_info, ctl,
2665 align_gap, align_gap_len);
2666 return ret;
2670 * given a cluster, put all of its extents back into the free space
2671 * cache. If a block group is passed, this function will only free
2672 * a cluster that belongs to the passed block group.
2674 * Otherwise, it'll get a reference on the block group pointed to by the
2675 * cluster and remove the cluster from it.
2677 int btrfs_return_cluster_to_free_space(
2678 struct btrfs_block_group_cache *block_group,
2679 struct btrfs_free_cluster *cluster)
2681 struct btrfs_free_space_ctl *ctl;
2682 int ret;
2684 /* first, get a safe pointer to the block group */
2685 spin_lock(&cluster->lock);
2686 if (!block_group) {
2687 block_group = cluster->block_group;
2688 if (!block_group) {
2689 spin_unlock(&cluster->lock);
2690 return 0;
2692 } else if (cluster->block_group != block_group) {
2693 /* someone else has already freed it don't redo their work */
2694 spin_unlock(&cluster->lock);
2695 return 0;
2697 atomic_inc(&block_group->count);
2698 spin_unlock(&cluster->lock);
2700 ctl = block_group->free_space_ctl;
2702 /* now return any extents the cluster had on it */
2703 spin_lock(&ctl->tree_lock);
2704 ret = __btrfs_return_cluster_to_free_space(block_group, cluster);
2705 spin_unlock(&ctl->tree_lock);
2707 /* finally drop our ref */
2708 btrfs_put_block_group(block_group);
2709 return ret;
2712 static u64 btrfs_alloc_from_bitmap(struct btrfs_block_group_cache *block_group,
2713 struct btrfs_free_cluster *cluster,
2714 struct btrfs_free_space *entry,
2715 u64 bytes, u64 min_start,
2716 u64 *max_extent_size)
2718 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2719 int err;
2720 u64 search_start = cluster->window_start;
2721 u64 search_bytes = bytes;
2722 u64 ret = 0;
2724 search_start = min_start;
2725 search_bytes = bytes;
2727 err = search_bitmap(ctl, entry, &search_start, &search_bytes, true);
2728 if (err) {
2729 *max_extent_size = max(get_max_extent_size(entry),
2730 *max_extent_size);
2731 return 0;
2734 ret = search_start;
2735 __bitmap_clear_bits(ctl, entry, ret, bytes);
2737 return ret;
2741 * given a cluster, try to allocate 'bytes' from it, returns 0
2742 * if it couldn't find anything suitably large, or a logical disk offset
2743 * if things worked out
2745 u64 btrfs_alloc_from_cluster(struct btrfs_block_group_cache *block_group,
2746 struct btrfs_free_cluster *cluster, u64 bytes,
2747 u64 min_start, u64 *max_extent_size)
2749 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2750 struct btrfs_free_space *entry = NULL;
2751 struct rb_node *node;
2752 u64 ret = 0;
2754 spin_lock(&cluster->lock);
2755 if (bytes > cluster->max_size)
2756 goto out;
2758 if (cluster->block_group != block_group)
2759 goto out;
2761 node = rb_first(&cluster->root);
2762 if (!node)
2763 goto out;
2765 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2766 while (1) {
2767 if (entry->bytes < bytes)
2768 *max_extent_size = max(get_max_extent_size(entry),
2769 *max_extent_size);
2771 if (entry->bytes < bytes ||
2772 (!entry->bitmap && entry->offset < min_start)) {
2773 node = rb_next(&entry->offset_index);
2774 if (!node)
2775 break;
2776 entry = rb_entry(node, struct btrfs_free_space,
2777 offset_index);
2778 continue;
2781 if (entry->bitmap) {
2782 ret = btrfs_alloc_from_bitmap(block_group,
2783 cluster, entry, bytes,
2784 cluster->window_start,
2785 max_extent_size);
2786 if (ret == 0) {
2787 node = rb_next(&entry->offset_index);
2788 if (!node)
2789 break;
2790 entry = rb_entry(node, struct btrfs_free_space,
2791 offset_index);
2792 continue;
2794 cluster->window_start += bytes;
2795 } else {
2796 ret = entry->offset;
2798 entry->offset += bytes;
2799 entry->bytes -= bytes;
2802 if (entry->bytes == 0)
2803 rb_erase(&entry->offset_index, &cluster->root);
2804 break;
2806 out:
2807 spin_unlock(&cluster->lock);
2809 if (!ret)
2810 return 0;
2812 spin_lock(&ctl->tree_lock);
2814 ctl->free_space -= bytes;
2815 if (entry->bytes == 0) {
2816 ctl->free_extents--;
2817 if (entry->bitmap) {
2818 kfree(entry->bitmap);
2819 ctl->total_bitmaps--;
2820 ctl->op->recalc_thresholds(ctl);
2822 kmem_cache_free(btrfs_free_space_cachep, entry);
2825 spin_unlock(&ctl->tree_lock);
2827 return ret;
2830 static int btrfs_bitmap_cluster(struct btrfs_block_group_cache *block_group,
2831 struct btrfs_free_space *entry,
2832 struct btrfs_free_cluster *cluster,
2833 u64 offset, u64 bytes,
2834 u64 cont1_bytes, u64 min_bytes)
2836 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2837 unsigned long next_zero;
2838 unsigned long i;
2839 unsigned long want_bits;
2840 unsigned long min_bits;
2841 unsigned long found_bits;
2842 unsigned long max_bits = 0;
2843 unsigned long start = 0;
2844 unsigned long total_found = 0;
2845 int ret;
2847 i = offset_to_bit(entry->offset, ctl->unit,
2848 max_t(u64, offset, entry->offset));
2849 want_bits = bytes_to_bits(bytes, ctl->unit);
2850 min_bits = bytes_to_bits(min_bytes, ctl->unit);
2853 * Don't bother looking for a cluster in this bitmap if it's heavily
2854 * fragmented.
2856 if (entry->max_extent_size &&
2857 entry->max_extent_size < cont1_bytes)
2858 return -ENOSPC;
2859 again:
2860 found_bits = 0;
2861 for_each_set_bit_from(i, entry->bitmap, BITS_PER_BITMAP) {
2862 next_zero = find_next_zero_bit(entry->bitmap,
2863 BITS_PER_BITMAP, i);
2864 if (next_zero - i >= min_bits) {
2865 found_bits = next_zero - i;
2866 if (found_bits > max_bits)
2867 max_bits = found_bits;
2868 break;
2870 if (next_zero - i > max_bits)
2871 max_bits = next_zero - i;
2872 i = next_zero;
2875 if (!found_bits) {
2876 entry->max_extent_size = (u64)max_bits * ctl->unit;
2877 return -ENOSPC;
2880 if (!total_found) {
2881 start = i;
2882 cluster->max_size = 0;
2885 total_found += found_bits;
2887 if (cluster->max_size < found_bits * ctl->unit)
2888 cluster->max_size = found_bits * ctl->unit;
2890 if (total_found < want_bits || cluster->max_size < cont1_bytes) {
2891 i = next_zero + 1;
2892 goto again;
2895 cluster->window_start = start * ctl->unit + entry->offset;
2896 rb_erase(&entry->offset_index, &ctl->free_space_offset);
2897 ret = tree_insert_offset(&cluster->root, entry->offset,
2898 &entry->offset_index, 1);
2899 ASSERT(!ret); /* -EEXIST; Logic error */
2901 trace_btrfs_setup_cluster(block_group, cluster,
2902 total_found * ctl->unit, 1);
2903 return 0;
2907 * This searches the block group for just extents to fill the cluster with.
2908 * Try to find a cluster with at least bytes total bytes, at least one
2909 * extent of cont1_bytes, and other clusters of at least min_bytes.
2911 static noinline int
2912 setup_cluster_no_bitmap(struct btrfs_block_group_cache *block_group,
2913 struct btrfs_free_cluster *cluster,
2914 struct list_head *bitmaps, u64 offset, u64 bytes,
2915 u64 cont1_bytes, u64 min_bytes)
2917 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
2918 struct btrfs_free_space *first = NULL;
2919 struct btrfs_free_space *entry = NULL;
2920 struct btrfs_free_space *last;
2921 struct rb_node *node;
2922 u64 window_free;
2923 u64 max_extent;
2924 u64 total_size = 0;
2926 entry = tree_search_offset(ctl, offset, 0, 1);
2927 if (!entry)
2928 return -ENOSPC;
2931 * We don't want bitmaps, so just move along until we find a normal
2932 * extent entry.
2934 while (entry->bitmap || entry->bytes < min_bytes) {
2935 if (entry->bitmap && list_empty(&entry->list))
2936 list_add_tail(&entry->list, bitmaps);
2937 node = rb_next(&entry->offset_index);
2938 if (!node)
2939 return -ENOSPC;
2940 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2943 window_free = entry->bytes;
2944 max_extent = entry->bytes;
2945 first = entry;
2946 last = entry;
2948 for (node = rb_next(&entry->offset_index); node;
2949 node = rb_next(&entry->offset_index)) {
2950 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2952 if (entry->bitmap) {
2953 if (list_empty(&entry->list))
2954 list_add_tail(&entry->list, bitmaps);
2955 continue;
2958 if (entry->bytes < min_bytes)
2959 continue;
2961 last = entry;
2962 window_free += entry->bytes;
2963 if (entry->bytes > max_extent)
2964 max_extent = entry->bytes;
2967 if (window_free < bytes || max_extent < cont1_bytes)
2968 return -ENOSPC;
2970 cluster->window_start = first->offset;
2972 node = &first->offset_index;
2975 * now we've found our entries, pull them out of the free space
2976 * cache and put them into the cluster rbtree
2978 do {
2979 int ret;
2981 entry = rb_entry(node, struct btrfs_free_space, offset_index);
2982 node = rb_next(&entry->offset_index);
2983 if (entry->bitmap || entry->bytes < min_bytes)
2984 continue;
2986 rb_erase(&entry->offset_index, &ctl->free_space_offset);
2987 ret = tree_insert_offset(&cluster->root, entry->offset,
2988 &entry->offset_index, 0);
2989 total_size += entry->bytes;
2990 ASSERT(!ret); /* -EEXIST; Logic error */
2991 } while (node && entry != last);
2993 cluster->max_size = max_extent;
2994 trace_btrfs_setup_cluster(block_group, cluster, total_size, 0);
2995 return 0;
2999 * This specifically looks for bitmaps that may work in the cluster, we assume
3000 * that we have already failed to find extents that will work.
3002 static noinline int
3003 setup_cluster_bitmap(struct btrfs_block_group_cache *block_group,
3004 struct btrfs_free_cluster *cluster,
3005 struct list_head *bitmaps, u64 offset, u64 bytes,
3006 u64 cont1_bytes, u64 min_bytes)
3008 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3009 struct btrfs_free_space *entry = NULL;
3010 int ret = -ENOSPC;
3011 u64 bitmap_offset = offset_to_bitmap(ctl, offset);
3013 if (ctl->total_bitmaps == 0)
3014 return -ENOSPC;
3017 * The bitmap that covers offset won't be in the list unless offset
3018 * is just its start offset.
3020 if (!list_empty(bitmaps))
3021 entry = list_first_entry(bitmaps, struct btrfs_free_space, list);
3023 if (!entry || entry->offset != bitmap_offset) {
3024 entry = tree_search_offset(ctl, bitmap_offset, 1, 0);
3025 if (entry && list_empty(&entry->list))
3026 list_add(&entry->list, bitmaps);
3029 list_for_each_entry(entry, bitmaps, list) {
3030 if (entry->bytes < bytes)
3031 continue;
3032 ret = btrfs_bitmap_cluster(block_group, entry, cluster, offset,
3033 bytes, cont1_bytes, min_bytes);
3034 if (!ret)
3035 return 0;
3039 * The bitmaps list has all the bitmaps that record free space
3040 * starting after offset, so no more search is required.
3042 return -ENOSPC;
3046 * here we try to find a cluster of blocks in a block group. The goal
3047 * is to find at least bytes+empty_size.
3048 * We might not find them all in one contiguous area.
3050 * returns zero and sets up cluster if things worked out, otherwise
3051 * it returns -enospc
3053 int btrfs_find_space_cluster(struct btrfs_fs_info *fs_info,
3054 struct btrfs_block_group_cache *block_group,
3055 struct btrfs_free_cluster *cluster,
3056 u64 offset, u64 bytes, u64 empty_size)
3058 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3059 struct btrfs_free_space *entry, *tmp;
3060 LIST_HEAD(bitmaps);
3061 u64 min_bytes;
3062 u64 cont1_bytes;
3063 int ret;
3066 * Choose the minimum extent size we'll require for this
3067 * cluster. For SSD_SPREAD, don't allow any fragmentation.
3068 * For metadata, allow allocates with smaller extents. For
3069 * data, keep it dense.
3071 if (btrfs_test_opt(fs_info, SSD_SPREAD)) {
3072 cont1_bytes = min_bytes = bytes + empty_size;
3073 } else if (block_group->flags & BTRFS_BLOCK_GROUP_METADATA) {
3074 cont1_bytes = bytes;
3075 min_bytes = fs_info->sectorsize;
3076 } else {
3077 cont1_bytes = max(bytes, (bytes + empty_size) >> 2);
3078 min_bytes = fs_info->sectorsize;
3081 spin_lock(&ctl->tree_lock);
3084 * If we know we don't have enough space to make a cluster don't even
3085 * bother doing all the work to try and find one.
3087 if (ctl->free_space < bytes) {
3088 spin_unlock(&ctl->tree_lock);
3089 return -ENOSPC;
3092 spin_lock(&cluster->lock);
3094 /* someone already found a cluster, hooray */
3095 if (cluster->block_group) {
3096 ret = 0;
3097 goto out;
3100 trace_btrfs_find_cluster(block_group, offset, bytes, empty_size,
3101 min_bytes);
3103 ret = setup_cluster_no_bitmap(block_group, cluster, &bitmaps, offset,
3104 bytes + empty_size,
3105 cont1_bytes, min_bytes);
3106 if (ret)
3107 ret = setup_cluster_bitmap(block_group, cluster, &bitmaps,
3108 offset, bytes + empty_size,
3109 cont1_bytes, min_bytes);
3111 /* Clear our temporary list */
3112 list_for_each_entry_safe(entry, tmp, &bitmaps, list)
3113 list_del_init(&entry->list);
3115 if (!ret) {
3116 atomic_inc(&block_group->count);
3117 list_add_tail(&cluster->block_group_list,
3118 &block_group->cluster_list);
3119 cluster->block_group = block_group;
3120 } else {
3121 trace_btrfs_failed_cluster_setup(block_group);
3123 out:
3124 spin_unlock(&cluster->lock);
3125 spin_unlock(&ctl->tree_lock);
3127 return ret;
3131 * simple code to zero out a cluster
3133 void btrfs_init_free_cluster(struct btrfs_free_cluster *cluster)
3135 spin_lock_init(&cluster->lock);
3136 spin_lock_init(&cluster->refill_lock);
3137 cluster->root = RB_ROOT;
3138 cluster->max_size = 0;
3139 cluster->fragmented = false;
3140 INIT_LIST_HEAD(&cluster->block_group_list);
3141 cluster->block_group = NULL;
3144 static int do_trimming(struct btrfs_block_group_cache *block_group,
3145 u64 *total_trimmed, u64 start, u64 bytes,
3146 u64 reserved_start, u64 reserved_bytes,
3147 struct btrfs_trim_range *trim_entry)
3149 struct btrfs_space_info *space_info = block_group->space_info;
3150 struct btrfs_fs_info *fs_info = block_group->fs_info;
3151 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3152 int ret;
3153 int update = 0;
3154 u64 trimmed = 0;
3156 spin_lock(&space_info->lock);
3157 spin_lock(&block_group->lock);
3158 if (!block_group->ro) {
3159 block_group->reserved += reserved_bytes;
3160 space_info->bytes_reserved += reserved_bytes;
3161 update = 1;
3163 spin_unlock(&block_group->lock);
3164 spin_unlock(&space_info->lock);
3166 ret = btrfs_discard_extent(fs_info, start, bytes, &trimmed);
3167 if (!ret)
3168 *total_trimmed += trimmed;
3170 mutex_lock(&ctl->cache_writeout_mutex);
3171 btrfs_add_free_space(block_group, reserved_start, reserved_bytes);
3172 list_del(&trim_entry->list);
3173 mutex_unlock(&ctl->cache_writeout_mutex);
3175 if (update) {
3176 spin_lock(&space_info->lock);
3177 spin_lock(&block_group->lock);
3178 if (block_group->ro)
3179 space_info->bytes_readonly += reserved_bytes;
3180 block_group->reserved -= reserved_bytes;
3181 space_info->bytes_reserved -= reserved_bytes;
3182 spin_unlock(&space_info->lock);
3183 spin_unlock(&block_group->lock);
3186 return ret;
3189 static int trim_no_bitmap(struct btrfs_block_group_cache *block_group,
3190 u64 *total_trimmed, u64 start, u64 end, u64 minlen)
3192 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3193 struct btrfs_free_space *entry;
3194 struct rb_node *node;
3195 int ret = 0;
3196 u64 extent_start;
3197 u64 extent_bytes;
3198 u64 bytes;
3200 while (start < end) {
3201 struct btrfs_trim_range trim_entry;
3203 mutex_lock(&ctl->cache_writeout_mutex);
3204 spin_lock(&ctl->tree_lock);
3206 if (ctl->free_space < minlen) {
3207 spin_unlock(&ctl->tree_lock);
3208 mutex_unlock(&ctl->cache_writeout_mutex);
3209 break;
3212 entry = tree_search_offset(ctl, start, 0, 1);
3213 if (!entry) {
3214 spin_unlock(&ctl->tree_lock);
3215 mutex_unlock(&ctl->cache_writeout_mutex);
3216 break;
3219 /* skip bitmaps */
3220 while (entry->bitmap) {
3221 node = rb_next(&entry->offset_index);
3222 if (!node) {
3223 spin_unlock(&ctl->tree_lock);
3224 mutex_unlock(&ctl->cache_writeout_mutex);
3225 goto out;
3227 entry = rb_entry(node, struct btrfs_free_space,
3228 offset_index);
3231 if (entry->offset >= end) {
3232 spin_unlock(&ctl->tree_lock);
3233 mutex_unlock(&ctl->cache_writeout_mutex);
3234 break;
3237 extent_start = entry->offset;
3238 extent_bytes = entry->bytes;
3239 start = max(start, extent_start);
3240 bytes = min(extent_start + extent_bytes, end) - start;
3241 if (bytes < minlen) {
3242 spin_unlock(&ctl->tree_lock);
3243 mutex_unlock(&ctl->cache_writeout_mutex);
3244 goto next;
3247 unlink_free_space(ctl, entry);
3248 kmem_cache_free(btrfs_free_space_cachep, entry);
3250 spin_unlock(&ctl->tree_lock);
3251 trim_entry.start = extent_start;
3252 trim_entry.bytes = extent_bytes;
3253 list_add_tail(&trim_entry.list, &ctl->trimming_ranges);
3254 mutex_unlock(&ctl->cache_writeout_mutex);
3256 ret = do_trimming(block_group, total_trimmed, start, bytes,
3257 extent_start, extent_bytes, &trim_entry);
3258 if (ret)
3259 break;
3260 next:
3261 start += bytes;
3263 if (fatal_signal_pending(current)) {
3264 ret = -ERESTARTSYS;
3265 break;
3268 cond_resched();
3270 out:
3271 return ret;
3274 static int trim_bitmaps(struct btrfs_block_group_cache *block_group,
3275 u64 *total_trimmed, u64 start, u64 end, u64 minlen)
3277 struct btrfs_free_space_ctl *ctl = block_group->free_space_ctl;
3278 struct btrfs_free_space *entry;
3279 int ret = 0;
3280 int ret2;
3281 u64 bytes;
3282 u64 offset = offset_to_bitmap(ctl, start);
3284 while (offset < end) {
3285 bool next_bitmap = false;
3286 struct btrfs_trim_range trim_entry;
3288 mutex_lock(&ctl->cache_writeout_mutex);
3289 spin_lock(&ctl->tree_lock);
3291 if (ctl->free_space < minlen) {
3292 spin_unlock(&ctl->tree_lock);
3293 mutex_unlock(&ctl->cache_writeout_mutex);
3294 break;
3297 entry = tree_search_offset(ctl, offset, 1, 0);
3298 if (!entry) {
3299 spin_unlock(&ctl->tree_lock);
3300 mutex_unlock(&ctl->cache_writeout_mutex);
3301 next_bitmap = true;
3302 goto next;
3305 bytes = minlen;
3306 ret2 = search_bitmap(ctl, entry, &start, &bytes, false);
3307 if (ret2 || start >= end) {
3308 spin_unlock(&ctl->tree_lock);
3309 mutex_unlock(&ctl->cache_writeout_mutex);
3310 next_bitmap = true;
3311 goto next;
3314 bytes = min(bytes, end - start);
3315 if (bytes < minlen) {
3316 spin_unlock(&ctl->tree_lock);
3317 mutex_unlock(&ctl->cache_writeout_mutex);
3318 goto next;
3321 bitmap_clear_bits(ctl, entry, start, bytes);
3322 if (entry->bytes == 0)
3323 free_bitmap(ctl, entry);
3325 spin_unlock(&ctl->tree_lock);
3326 trim_entry.start = start;
3327 trim_entry.bytes = bytes;
3328 list_add_tail(&trim_entry.list, &ctl->trimming_ranges);
3329 mutex_unlock(&ctl->cache_writeout_mutex);
3331 ret = do_trimming(block_group, total_trimmed, start, bytes,
3332 start, bytes, &trim_entry);
3333 if (ret)
3334 break;
3335 next:
3336 if (next_bitmap) {
3337 offset += BITS_PER_BITMAP * ctl->unit;
3338 } else {
3339 start += bytes;
3340 if (start >= offset + BITS_PER_BITMAP * ctl->unit)
3341 offset += BITS_PER_BITMAP * ctl->unit;
3344 if (fatal_signal_pending(current)) {
3345 ret = -ERESTARTSYS;
3346 break;
3349 cond_resched();
3352 return ret;
3355 void btrfs_get_block_group_trimming(struct btrfs_block_group_cache *cache)
3357 atomic_inc(&cache->trimming);
3360 void btrfs_put_block_group_trimming(struct btrfs_block_group_cache *block_group)
3362 struct btrfs_fs_info *fs_info = block_group->fs_info;
3363 struct extent_map_tree *em_tree;
3364 struct extent_map *em;
3365 bool cleanup;
3367 spin_lock(&block_group->lock);
3368 cleanup = (atomic_dec_and_test(&block_group->trimming) &&
3369 block_group->removed);
3370 spin_unlock(&block_group->lock);
3372 if (cleanup) {
3373 mutex_lock(&fs_info->chunk_mutex);
3374 em_tree = &fs_info->mapping_tree.map_tree;
3375 write_lock(&em_tree->lock);
3376 em = lookup_extent_mapping(em_tree, block_group->key.objectid,
3378 BUG_ON(!em); /* logic error, can't happen */
3380 * remove_extent_mapping() will delete us from the pinned_chunks
3381 * list, which is protected by the chunk mutex.
3383 remove_extent_mapping(em_tree, em);
3384 write_unlock(&em_tree->lock);
3385 mutex_unlock(&fs_info->chunk_mutex);
3387 /* once for us and once for the tree */
3388 free_extent_map(em);
3389 free_extent_map(em);
3392 * We've left one free space entry and other tasks trimming
3393 * this block group have left 1 entry each one. Free them.
3395 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
3399 int btrfs_trim_block_group(struct btrfs_block_group_cache *block_group,
3400 u64 *trimmed, u64 start, u64 end, u64 minlen)
3402 int ret;
3404 *trimmed = 0;
3406 spin_lock(&block_group->lock);
3407 if (block_group->removed) {
3408 spin_unlock(&block_group->lock);
3409 return 0;
3411 btrfs_get_block_group_trimming(block_group);
3412 spin_unlock(&block_group->lock);
3414 ret = trim_no_bitmap(block_group, trimmed, start, end, minlen);
3415 if (ret)
3416 goto out;
3418 ret = trim_bitmaps(block_group, trimmed, start, end, minlen);
3419 out:
3420 btrfs_put_block_group_trimming(block_group);
3421 return ret;
3425 * Find the left-most item in the cache tree, and then return the
3426 * smallest inode number in the item.
3428 * Note: the returned inode number may not be the smallest one in
3429 * the tree, if the left-most item is a bitmap.
3431 u64 btrfs_find_ino_for_alloc(struct btrfs_root *fs_root)
3433 struct btrfs_free_space_ctl *ctl = fs_root->free_ino_ctl;
3434 struct btrfs_free_space *entry = NULL;
3435 u64 ino = 0;
3437 spin_lock(&ctl->tree_lock);
3439 if (RB_EMPTY_ROOT(&ctl->free_space_offset))
3440 goto out;
3442 entry = rb_entry(rb_first(&ctl->free_space_offset),
3443 struct btrfs_free_space, offset_index);
3445 if (!entry->bitmap) {
3446 ino = entry->offset;
3448 unlink_free_space(ctl, entry);
3449 entry->offset++;
3450 entry->bytes--;
3451 if (!entry->bytes)
3452 kmem_cache_free(btrfs_free_space_cachep, entry);
3453 else
3454 link_free_space(ctl, entry);
3455 } else {
3456 u64 offset = 0;
3457 u64 count = 1;
3458 int ret;
3460 ret = search_bitmap(ctl, entry, &offset, &count, true);
3461 /* Logic error; Should be empty if it can't find anything */
3462 ASSERT(!ret);
3464 ino = offset;
3465 bitmap_clear_bits(ctl, entry, offset, 1);
3466 if (entry->bytes == 0)
3467 free_bitmap(ctl, entry);
3469 out:
3470 spin_unlock(&ctl->tree_lock);
3472 return ino;
3475 struct inode *lookup_free_ino_inode(struct btrfs_root *root,
3476 struct btrfs_path *path)
3478 struct inode *inode = NULL;
3480 spin_lock(&root->ino_cache_lock);
3481 if (root->ino_cache_inode)
3482 inode = igrab(root->ino_cache_inode);
3483 spin_unlock(&root->ino_cache_lock);
3484 if (inode)
3485 return inode;
3487 inode = __lookup_free_space_inode(root, path, 0);
3488 if (IS_ERR(inode))
3489 return inode;
3491 spin_lock(&root->ino_cache_lock);
3492 if (!btrfs_fs_closing(root->fs_info))
3493 root->ino_cache_inode = igrab(inode);
3494 spin_unlock(&root->ino_cache_lock);
3496 return inode;
3499 int create_free_ino_inode(struct btrfs_root *root,
3500 struct btrfs_trans_handle *trans,
3501 struct btrfs_path *path)
3503 return __create_free_space_inode(root, trans, path,
3504 BTRFS_FREE_INO_OBJECTID, 0);
3507 int load_free_ino_cache(struct btrfs_fs_info *fs_info, struct btrfs_root *root)
3509 struct btrfs_free_space_ctl *ctl = root->free_ino_ctl;
3510 struct btrfs_path *path;
3511 struct inode *inode;
3512 int ret = 0;
3513 u64 root_gen = btrfs_root_generation(&root->root_item);
3515 if (!btrfs_test_opt(fs_info, INODE_MAP_CACHE))
3516 return 0;
3519 * If we're unmounting then just return, since this does a search on the
3520 * normal root and not the commit root and we could deadlock.
3522 if (btrfs_fs_closing(fs_info))
3523 return 0;
3525 path = btrfs_alloc_path();
3526 if (!path)
3527 return 0;
3529 inode = lookup_free_ino_inode(root, path);
3530 if (IS_ERR(inode))
3531 goto out;
3533 if (root_gen != BTRFS_I(inode)->generation)
3534 goto out_put;
3536 ret = __load_free_space_cache(root, inode, ctl, path, 0);
3538 if (ret < 0)
3539 btrfs_err(fs_info,
3540 "failed to load free ino cache for root %llu",
3541 root->root_key.objectid);
3542 out_put:
3543 iput(inode);
3544 out:
3545 btrfs_free_path(path);
3546 return ret;
3549 int btrfs_write_out_ino_cache(struct btrfs_root *root,
3550 struct btrfs_trans_handle *trans,
3551 struct btrfs_path *path,
3552 struct inode *inode)
3554 struct btrfs_fs_info *fs_info = root->fs_info;
3555 struct btrfs_free_space_ctl *ctl = root->free_ino_ctl;
3556 int ret;
3557 struct btrfs_io_ctl io_ctl;
3558 bool release_metadata = true;
3560 if (!btrfs_test_opt(fs_info, INODE_MAP_CACHE))
3561 return 0;
3563 memset(&io_ctl, 0, sizeof(io_ctl));
3564 ret = __btrfs_write_out_cache(root, inode, ctl, NULL, &io_ctl, trans);
3565 if (!ret) {
3567 * At this point writepages() didn't error out, so our metadata
3568 * reservation is released when the writeback finishes, at
3569 * inode.c:btrfs_finish_ordered_io(), regardless of it finishing
3570 * with or without an error.
3572 release_metadata = false;
3573 ret = btrfs_wait_cache_io_root(root, trans, &io_ctl, path);
3576 if (ret) {
3577 if (release_metadata)
3578 btrfs_delalloc_release_metadata(BTRFS_I(inode),
3579 inode->i_size);
3580 #ifdef DEBUG
3581 btrfs_err(fs_info,
3582 "failed to write free ino cache for root %llu",
3583 root->root_key.objectid);
3584 #endif
3587 return ret;
3590 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
3592 * Use this if you need to make a bitmap or extent entry specifically, it
3593 * doesn't do any of the merging that add_free_space does, this acts a lot like
3594 * how the free space cache loading stuff works, so you can get really weird
3595 * configurations.
3597 int test_add_free_space_entry(struct btrfs_block_group_cache *cache,
3598 u64 offset, u64 bytes, bool bitmap)
3600 struct btrfs_free_space_ctl *ctl = cache->free_space_ctl;
3601 struct btrfs_free_space *info = NULL, *bitmap_info;
3602 void *map = NULL;
3603 u64 bytes_added;
3604 int ret;
3606 again:
3607 if (!info) {
3608 info = kmem_cache_zalloc(btrfs_free_space_cachep, GFP_NOFS);
3609 if (!info)
3610 return -ENOMEM;
3613 if (!bitmap) {
3614 spin_lock(&ctl->tree_lock);
3615 info->offset = offset;
3616 info->bytes = bytes;
3617 info->max_extent_size = 0;
3618 ret = link_free_space(ctl, info);
3619 spin_unlock(&ctl->tree_lock);
3620 if (ret)
3621 kmem_cache_free(btrfs_free_space_cachep, info);
3622 return ret;
3625 if (!map) {
3626 map = kzalloc(PAGE_SIZE, GFP_NOFS);
3627 if (!map) {
3628 kmem_cache_free(btrfs_free_space_cachep, info);
3629 return -ENOMEM;
3633 spin_lock(&ctl->tree_lock);
3634 bitmap_info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
3635 1, 0);
3636 if (!bitmap_info) {
3637 info->bitmap = map;
3638 map = NULL;
3639 add_new_bitmap(ctl, info, offset);
3640 bitmap_info = info;
3641 info = NULL;
3644 bytes_added = add_bytes_to_bitmap(ctl, bitmap_info, offset, bytes);
3646 bytes -= bytes_added;
3647 offset += bytes_added;
3648 spin_unlock(&ctl->tree_lock);
3650 if (bytes)
3651 goto again;
3653 if (info)
3654 kmem_cache_free(btrfs_free_space_cachep, info);
3655 if (map)
3656 kfree(map);
3657 return 0;
3661 * Checks to see if the given range is in the free space cache. This is really
3662 * just used to check the absence of space, so if there is free space in the
3663 * range at all we will return 1.
3665 int test_check_exists(struct btrfs_block_group_cache *cache,
3666 u64 offset, u64 bytes)
3668 struct btrfs_free_space_ctl *ctl = cache->free_space_ctl;
3669 struct btrfs_free_space *info;
3670 int ret = 0;
3672 spin_lock(&ctl->tree_lock);
3673 info = tree_search_offset(ctl, offset, 0, 0);
3674 if (!info) {
3675 info = tree_search_offset(ctl, offset_to_bitmap(ctl, offset),
3676 1, 0);
3677 if (!info)
3678 goto out;
3681 have_info:
3682 if (info->bitmap) {
3683 u64 bit_off, bit_bytes;
3684 struct rb_node *n;
3685 struct btrfs_free_space *tmp;
3687 bit_off = offset;
3688 bit_bytes = ctl->unit;
3689 ret = search_bitmap(ctl, info, &bit_off, &bit_bytes, false);
3690 if (!ret) {
3691 if (bit_off == offset) {
3692 ret = 1;
3693 goto out;
3694 } else if (bit_off > offset &&
3695 offset + bytes > bit_off) {
3696 ret = 1;
3697 goto out;
3701 n = rb_prev(&info->offset_index);
3702 while (n) {
3703 tmp = rb_entry(n, struct btrfs_free_space,
3704 offset_index);
3705 if (tmp->offset + tmp->bytes < offset)
3706 break;
3707 if (offset + bytes < tmp->offset) {
3708 n = rb_prev(&tmp->offset_index);
3709 continue;
3711 info = tmp;
3712 goto have_info;
3715 n = rb_next(&info->offset_index);
3716 while (n) {
3717 tmp = rb_entry(n, struct btrfs_free_space,
3718 offset_index);
3719 if (offset + bytes < tmp->offset)
3720 break;
3721 if (tmp->offset + tmp->bytes < offset) {
3722 n = rb_next(&tmp->offset_index);
3723 continue;
3725 info = tmp;
3726 goto have_info;
3729 ret = 0;
3730 goto out;
3733 if (info->offset == offset) {
3734 ret = 1;
3735 goto out;
3738 if (offset > info->offset && offset < info->offset + info->bytes)
3739 ret = 1;
3740 out:
3741 spin_unlock(&ctl->tree_lock);
3742 return ret;
3744 #endif /* CONFIG_BTRFS_FS_RUN_SANITY_TESTS */