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