blob: c99e293b50f5456669bdd75735b2ce5f5b11340b [file] [log] [blame]
David Brazdil0f672f62019-12-10 10:32:29 +00001// SPDX-License-Identifier: GPL-2.0
2
3#include "misc.h"
4#include "ctree.h"
5#include "block-group.h"
6#include "space-info.h"
7#include "disk-io.h"
8#include "free-space-cache.h"
9#include "free-space-tree.h"
David Brazdil0f672f62019-12-10 10:32:29 +000010#include "volumes.h"
11#include "transaction.h"
12#include "ref-verify.h"
13#include "sysfs.h"
14#include "tree-log.h"
15#include "delalloc-space.h"
Olivier Deprez157378f2022-04-04 15:47:50 +020016#include "discard.h"
17#include "raid56.h"
David Brazdil0f672f62019-12-10 10:32:29 +000018
19/*
20 * Return target flags in extended format or 0 if restripe for this chunk_type
21 * is not in progress
22 *
23 * Should be called with balance_lock held
24 */
25static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
26{
27 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
28 u64 target = 0;
29
30 if (!bctl)
31 return 0;
32
33 if (flags & BTRFS_BLOCK_GROUP_DATA &&
34 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
35 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
36 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
37 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
38 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
39 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
40 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
41 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
42 }
43
44 return target;
45}
46
47/*
48 * @flags: available profiles in extended format (see ctree.h)
49 *
50 * Return reduced profile in chunk format. If profile changing is in progress
51 * (either running or paused) picks the target profile (if it's already
52 * available), otherwise falls back to plain reducing.
53 */
54static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
55{
56 u64 num_devices = fs_info->fs_devices->rw_devices;
57 u64 target;
58 u64 raid_type;
59 u64 allowed = 0;
60
61 /*
62 * See if restripe for this chunk_type is in progress, if so try to
63 * reduce to the target profile
64 */
65 spin_lock(&fs_info->balance_lock);
66 target = get_restripe_target(fs_info, flags);
67 if (target) {
Olivier Deprez157378f2022-04-04 15:47:50 +020068 spin_unlock(&fs_info->balance_lock);
69 return extended_to_chunk(target);
David Brazdil0f672f62019-12-10 10:32:29 +000070 }
71 spin_unlock(&fs_info->balance_lock);
72
73 /* First, mask out the RAID levels which aren't possible */
74 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
75 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
76 allowed |= btrfs_raid_array[raid_type].bg_flag;
77 }
78 allowed &= flags;
79
80 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
81 allowed = BTRFS_BLOCK_GROUP_RAID6;
82 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
83 allowed = BTRFS_BLOCK_GROUP_RAID5;
84 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
85 allowed = BTRFS_BLOCK_GROUP_RAID10;
86 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
87 allowed = BTRFS_BLOCK_GROUP_RAID1;
88 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
89 allowed = BTRFS_BLOCK_GROUP_RAID0;
90
91 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
92
93 return extended_to_chunk(flags | allowed);
94}
95
Olivier Deprez157378f2022-04-04 15:47:50 +020096u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
David Brazdil0f672f62019-12-10 10:32:29 +000097{
98 unsigned seq;
99 u64 flags;
100
101 do {
102 flags = orig_flags;
103 seq = read_seqbegin(&fs_info->profiles_lock);
104
105 if (flags & BTRFS_BLOCK_GROUP_DATA)
106 flags |= fs_info->avail_data_alloc_bits;
107 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
108 flags |= fs_info->avail_system_alloc_bits;
109 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
110 flags |= fs_info->avail_metadata_alloc_bits;
111 } while (read_seqretry(&fs_info->profiles_lock, seq));
112
113 return btrfs_reduce_alloc_profile(fs_info, flags);
114}
115
Olivier Deprez157378f2022-04-04 15:47:50 +0200116void btrfs_get_block_group(struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +0000117{
Olivier Deprez157378f2022-04-04 15:47:50 +0200118 refcount_inc(&cache->refs);
David Brazdil0f672f62019-12-10 10:32:29 +0000119}
120
Olivier Deprez157378f2022-04-04 15:47:50 +0200121void btrfs_put_block_group(struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +0000122{
Olivier Deprez157378f2022-04-04 15:47:50 +0200123 if (refcount_dec_and_test(&cache->refs)) {
David Brazdil0f672f62019-12-10 10:32:29 +0000124 WARN_ON(cache->pinned > 0);
125 WARN_ON(cache->reserved > 0);
126
127 /*
Olivier Deprez157378f2022-04-04 15:47:50 +0200128 * A block_group shouldn't be on the discard_list anymore.
129 * Remove the block_group from the discard_list to prevent us
130 * from causing a panic due to NULL pointer dereference.
131 */
132 if (WARN_ON(!list_empty(&cache->discard_list)))
133 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
134 cache);
135
136 /*
David Brazdil0f672f62019-12-10 10:32:29 +0000137 * If not empty, someone is still holding mutex of
138 * full_stripe_lock, which can only be released by caller.
139 * And it will definitely cause use-after-free when caller
140 * tries to release full stripe lock.
141 *
142 * No better way to resolve, but only to warn.
143 */
144 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
145 kfree(cache->free_space_ctl);
146 kfree(cache);
147 }
148}
149
150/*
151 * This adds the block group to the fs_info rb tree for the block group cache
152 */
153static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
Olivier Deprez157378f2022-04-04 15:47:50 +0200154 struct btrfs_block_group *block_group)
David Brazdil0f672f62019-12-10 10:32:29 +0000155{
156 struct rb_node **p;
157 struct rb_node *parent = NULL;
Olivier Deprez157378f2022-04-04 15:47:50 +0200158 struct btrfs_block_group *cache;
159
160 ASSERT(block_group->length != 0);
David Brazdil0f672f62019-12-10 10:32:29 +0000161
162 spin_lock(&info->block_group_cache_lock);
163 p = &info->block_group_cache_tree.rb_node;
164
165 while (*p) {
166 parent = *p;
Olivier Deprez157378f2022-04-04 15:47:50 +0200167 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
168 if (block_group->start < cache->start) {
David Brazdil0f672f62019-12-10 10:32:29 +0000169 p = &(*p)->rb_left;
Olivier Deprez157378f2022-04-04 15:47:50 +0200170 } else if (block_group->start > cache->start) {
David Brazdil0f672f62019-12-10 10:32:29 +0000171 p = &(*p)->rb_right;
172 } else {
173 spin_unlock(&info->block_group_cache_lock);
174 return -EEXIST;
175 }
176 }
177
178 rb_link_node(&block_group->cache_node, parent, p);
179 rb_insert_color(&block_group->cache_node,
180 &info->block_group_cache_tree);
181
Olivier Deprez157378f2022-04-04 15:47:50 +0200182 if (info->first_logical_byte > block_group->start)
183 info->first_logical_byte = block_group->start;
David Brazdil0f672f62019-12-10 10:32:29 +0000184
185 spin_unlock(&info->block_group_cache_lock);
186
187 return 0;
188}
189
190/*
191 * This will return the block group at or after bytenr if contains is 0, else
192 * it will return the block group that contains the bytenr
193 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200194static struct btrfs_block_group *block_group_cache_tree_search(
David Brazdil0f672f62019-12-10 10:32:29 +0000195 struct btrfs_fs_info *info, u64 bytenr, int contains)
196{
Olivier Deprez157378f2022-04-04 15:47:50 +0200197 struct btrfs_block_group *cache, *ret = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +0000198 struct rb_node *n;
199 u64 end, start;
200
201 spin_lock(&info->block_group_cache_lock);
202 n = info->block_group_cache_tree.rb_node;
203
204 while (n) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200205 cache = rb_entry(n, struct btrfs_block_group, cache_node);
206 end = cache->start + cache->length - 1;
207 start = cache->start;
David Brazdil0f672f62019-12-10 10:32:29 +0000208
209 if (bytenr < start) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200210 if (!contains && (!ret || start < ret->start))
David Brazdil0f672f62019-12-10 10:32:29 +0000211 ret = cache;
212 n = n->rb_left;
213 } else if (bytenr > start) {
214 if (contains && bytenr <= end) {
215 ret = cache;
216 break;
217 }
218 n = n->rb_right;
219 } else {
220 ret = cache;
221 break;
222 }
223 }
224 if (ret) {
225 btrfs_get_block_group(ret);
Olivier Deprez157378f2022-04-04 15:47:50 +0200226 if (bytenr == 0 && info->first_logical_byte > ret->start)
227 info->first_logical_byte = ret->start;
David Brazdil0f672f62019-12-10 10:32:29 +0000228 }
229 spin_unlock(&info->block_group_cache_lock);
230
231 return ret;
232}
233
234/*
235 * Return the block group that starts at or after bytenr
236 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200237struct btrfs_block_group *btrfs_lookup_first_block_group(
David Brazdil0f672f62019-12-10 10:32:29 +0000238 struct btrfs_fs_info *info, u64 bytenr)
239{
240 return block_group_cache_tree_search(info, bytenr, 0);
241}
242
243/*
244 * Return the block group that contains the given bytenr
245 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200246struct btrfs_block_group *btrfs_lookup_block_group(
David Brazdil0f672f62019-12-10 10:32:29 +0000247 struct btrfs_fs_info *info, u64 bytenr)
248{
249 return block_group_cache_tree_search(info, bytenr, 1);
250}
251
Olivier Deprez157378f2022-04-04 15:47:50 +0200252struct btrfs_block_group *btrfs_next_block_group(
253 struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +0000254{
255 struct btrfs_fs_info *fs_info = cache->fs_info;
256 struct rb_node *node;
257
258 spin_lock(&fs_info->block_group_cache_lock);
259
260 /* If our block group was removed, we need a full search. */
261 if (RB_EMPTY_NODE(&cache->cache_node)) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200262 const u64 next_bytenr = cache->start + cache->length;
David Brazdil0f672f62019-12-10 10:32:29 +0000263
264 spin_unlock(&fs_info->block_group_cache_lock);
265 btrfs_put_block_group(cache);
266 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
267 }
268 node = rb_next(&cache->cache_node);
269 btrfs_put_block_group(cache);
270 if (node) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200271 cache = rb_entry(node, struct btrfs_block_group, cache_node);
David Brazdil0f672f62019-12-10 10:32:29 +0000272 btrfs_get_block_group(cache);
273 } else
274 cache = NULL;
275 spin_unlock(&fs_info->block_group_cache_lock);
276 return cache;
277}
278
279bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
280{
Olivier Deprez157378f2022-04-04 15:47:50 +0200281 struct btrfs_block_group *bg;
David Brazdil0f672f62019-12-10 10:32:29 +0000282 bool ret = true;
283
284 bg = btrfs_lookup_block_group(fs_info, bytenr);
285 if (!bg)
286 return false;
287
288 spin_lock(&bg->lock);
289 if (bg->ro)
290 ret = false;
291 else
292 atomic_inc(&bg->nocow_writers);
293 spin_unlock(&bg->lock);
294
295 /* No put on block group, done by btrfs_dec_nocow_writers */
296 if (!ret)
297 btrfs_put_block_group(bg);
298
299 return ret;
300}
301
302void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
303{
Olivier Deprez157378f2022-04-04 15:47:50 +0200304 struct btrfs_block_group *bg;
David Brazdil0f672f62019-12-10 10:32:29 +0000305
306 bg = btrfs_lookup_block_group(fs_info, bytenr);
307 ASSERT(bg);
308 if (atomic_dec_and_test(&bg->nocow_writers))
309 wake_up_var(&bg->nocow_writers);
310 /*
311 * Once for our lookup and once for the lookup done by a previous call
312 * to btrfs_inc_nocow_writers()
313 */
314 btrfs_put_block_group(bg);
315 btrfs_put_block_group(bg);
316}
317
Olivier Deprez157378f2022-04-04 15:47:50 +0200318void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
David Brazdil0f672f62019-12-10 10:32:29 +0000319{
320 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
321}
322
323void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
324 const u64 start)
325{
Olivier Deprez157378f2022-04-04 15:47:50 +0200326 struct btrfs_block_group *bg;
David Brazdil0f672f62019-12-10 10:32:29 +0000327
328 bg = btrfs_lookup_block_group(fs_info, start);
329 ASSERT(bg);
330 if (atomic_dec_and_test(&bg->reservations))
331 wake_up_var(&bg->reservations);
332 btrfs_put_block_group(bg);
333}
334
Olivier Deprez157378f2022-04-04 15:47:50 +0200335void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
David Brazdil0f672f62019-12-10 10:32:29 +0000336{
337 struct btrfs_space_info *space_info = bg->space_info;
338
339 ASSERT(bg->ro);
340
341 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
342 return;
343
344 /*
345 * Our block group is read only but before we set it to read only,
346 * some task might have had allocated an extent from it already, but it
347 * has not yet created a respective ordered extent (and added it to a
348 * root's list of ordered extents).
349 * Therefore wait for any task currently allocating extents, since the
350 * block group's reservations counter is incremented while a read lock
351 * on the groups' semaphore is held and decremented after releasing
352 * the read access on that semaphore and creating the ordered extent.
353 */
354 down_write(&space_info->groups_sem);
355 up_write(&space_info->groups_sem);
356
357 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
358}
359
360struct btrfs_caching_control *btrfs_get_caching_control(
Olivier Deprez157378f2022-04-04 15:47:50 +0200361 struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +0000362{
363 struct btrfs_caching_control *ctl;
364
365 spin_lock(&cache->lock);
366 if (!cache->caching_ctl) {
367 spin_unlock(&cache->lock);
368 return NULL;
369 }
370
371 ctl = cache->caching_ctl;
372 refcount_inc(&ctl->count);
373 spin_unlock(&cache->lock);
374 return ctl;
375}
376
377void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
378{
379 if (refcount_dec_and_test(&ctl->count))
380 kfree(ctl);
381}
382
383/*
384 * When we wait for progress in the block group caching, its because our
385 * allocation attempt failed at least once. So, we must sleep and let some
386 * progress happen before we try again.
387 *
388 * This function will sleep at least once waiting for new free space to show
389 * up, and then it will check the block group free space numbers for our min
390 * num_bytes. Another option is to have it go ahead and look in the rbtree for
391 * a free extent of a given size, but this is a good start.
392 *
393 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
394 * any of the information in this block group.
395 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200396void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
David Brazdil0f672f62019-12-10 10:32:29 +0000397 u64 num_bytes)
398{
399 struct btrfs_caching_control *caching_ctl;
400
401 caching_ctl = btrfs_get_caching_control(cache);
402 if (!caching_ctl)
403 return;
404
Olivier Deprez157378f2022-04-04 15:47:50 +0200405 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
David Brazdil0f672f62019-12-10 10:32:29 +0000406 (cache->free_space_ctl->free_space >= num_bytes));
407
408 btrfs_put_caching_control(caching_ctl);
409}
410
Olivier Deprez157378f2022-04-04 15:47:50 +0200411int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +0000412{
413 struct btrfs_caching_control *caching_ctl;
414 int ret = 0;
415
416 caching_ctl = btrfs_get_caching_control(cache);
417 if (!caching_ctl)
418 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
419
Olivier Deprez157378f2022-04-04 15:47:50 +0200420 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
David Brazdil0f672f62019-12-10 10:32:29 +0000421 if (cache->cached == BTRFS_CACHE_ERROR)
422 ret = -EIO;
423 btrfs_put_caching_control(caching_ctl);
424 return ret;
425}
426
427#ifdef CONFIG_BTRFS_DEBUG
Olivier Deprez157378f2022-04-04 15:47:50 +0200428static void fragment_free_space(struct btrfs_block_group *block_group)
David Brazdil0f672f62019-12-10 10:32:29 +0000429{
430 struct btrfs_fs_info *fs_info = block_group->fs_info;
Olivier Deprez157378f2022-04-04 15:47:50 +0200431 u64 start = block_group->start;
432 u64 len = block_group->length;
David Brazdil0f672f62019-12-10 10:32:29 +0000433 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
434 fs_info->nodesize : fs_info->sectorsize;
435 u64 step = chunk << 1;
436
437 while (len > chunk) {
438 btrfs_remove_free_space(block_group, start, chunk);
439 start += step;
440 if (len < step)
441 len = 0;
442 else
443 len -= step;
444 }
445}
446#endif
447
448/*
449 * This is only called by btrfs_cache_block_group, since we could have freed
450 * extents we need to check the pinned_extents for any extents that can't be
451 * used yet since their free space will be released as soon as the transaction
452 * commits.
453 */
Olivier Deprez157378f2022-04-04 15:47:50 +0200454u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
David Brazdil0f672f62019-12-10 10:32:29 +0000455{
456 struct btrfs_fs_info *info = block_group->fs_info;
457 u64 extent_start, extent_end, size, total_added = 0;
458 int ret;
459
460 while (start < end) {
Olivier Deprez157378f2022-04-04 15:47:50 +0200461 ret = find_first_extent_bit(&info->excluded_extents, start,
David Brazdil0f672f62019-12-10 10:32:29 +0000462 &extent_start, &extent_end,
463 EXTENT_DIRTY | EXTENT_UPTODATE,
464 NULL);
465 if (ret)
466 break;
467
468 if (extent_start <= start) {
469 start = extent_end + 1;
470 } else if (extent_start > start && extent_start < end) {
471 size = extent_start - start;
472 total_added += size;
Olivier Deprez157378f2022-04-04 15:47:50 +0200473 ret = btrfs_add_free_space_async_trimmed(block_group,
474 start, size);
David Brazdil0f672f62019-12-10 10:32:29 +0000475 BUG_ON(ret); /* -ENOMEM or logic error */
476 start = extent_end + 1;
477 } else {
478 break;
479 }
480 }
481
482 if (start < end) {
483 size = end - start;
484 total_added += size;
Olivier Deprez157378f2022-04-04 15:47:50 +0200485 ret = btrfs_add_free_space_async_trimmed(block_group, start,
486 size);
David Brazdil0f672f62019-12-10 10:32:29 +0000487 BUG_ON(ret); /* -ENOMEM or logic error */
488 }
489
490 return total_added;
491}
492
493static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
494{
Olivier Deprez157378f2022-04-04 15:47:50 +0200495 struct btrfs_block_group *block_group = caching_ctl->block_group;
David Brazdil0f672f62019-12-10 10:32:29 +0000496 struct btrfs_fs_info *fs_info = block_group->fs_info;
497 struct btrfs_root *extent_root = fs_info->extent_root;
498 struct btrfs_path *path;
499 struct extent_buffer *leaf;
500 struct btrfs_key key;
501 u64 total_found = 0;
502 u64 last = 0;
503 u32 nritems;
504 int ret;
505 bool wakeup = true;
506
507 path = btrfs_alloc_path();
508 if (!path)
509 return -ENOMEM;
510
Olivier Deprez157378f2022-04-04 15:47:50 +0200511 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
David Brazdil0f672f62019-12-10 10:32:29 +0000512
513#ifdef CONFIG_BTRFS_DEBUG
514 /*
515 * If we're fragmenting we don't want to make anybody think we can
516 * allocate from this block group until we've had a chance to fragment
517 * the free space.
518 */
519 if (btrfs_should_fragment_free_space(block_group))
520 wakeup = false;
521#endif
522 /*
523 * We don't want to deadlock with somebody trying to allocate a new
524 * extent for the extent root while also trying to search the extent
525 * root to add free space. So we skip locking and search the commit
526 * root, since its read-only
527 */
528 path->skip_locking = 1;
529 path->search_commit_root = 1;
530 path->reada = READA_FORWARD;
531
532 key.objectid = last;
533 key.offset = 0;
534 key.type = BTRFS_EXTENT_ITEM_KEY;
535
536next:
537 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
538 if (ret < 0)
539 goto out;
540
541 leaf = path->nodes[0];
542 nritems = btrfs_header_nritems(leaf);
543
544 while (1) {
545 if (btrfs_fs_closing(fs_info) > 1) {
546 last = (u64)-1;
547 break;
548 }
549
550 if (path->slots[0] < nritems) {
551 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
552 } else {
553 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
554 if (ret)
555 break;
556
557 if (need_resched() ||
558 rwsem_is_contended(&fs_info->commit_root_sem)) {
559 if (wakeup)
560 caching_ctl->progress = last;
561 btrfs_release_path(path);
562 up_read(&fs_info->commit_root_sem);
563 mutex_unlock(&caching_ctl->mutex);
564 cond_resched();
565 mutex_lock(&caching_ctl->mutex);
566 down_read(&fs_info->commit_root_sem);
567 goto next;
568 }
569
570 ret = btrfs_next_leaf(extent_root, path);
571 if (ret < 0)
572 goto out;
573 if (ret)
574 break;
575 leaf = path->nodes[0];
576 nritems = btrfs_header_nritems(leaf);
577 continue;
578 }
579
580 if (key.objectid < last) {
581 key.objectid = last;
582 key.offset = 0;
583 key.type = BTRFS_EXTENT_ITEM_KEY;
584
585 if (wakeup)
586 caching_ctl->progress = last;
587 btrfs_release_path(path);
588 goto next;
589 }
590
Olivier Deprez157378f2022-04-04 15:47:50 +0200591 if (key.objectid < block_group->start) {
David Brazdil0f672f62019-12-10 10:32:29 +0000592 path->slots[0]++;
593 continue;
594 }
595
Olivier Deprez157378f2022-04-04 15:47:50 +0200596 if (key.objectid >= block_group->start + block_group->length)
David Brazdil0f672f62019-12-10 10:32:29 +0000597 break;
598
599 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
600 key.type == BTRFS_METADATA_ITEM_KEY) {
601 total_found += add_new_free_space(block_group, last,
602 key.objectid);
603 if (key.type == BTRFS_METADATA_ITEM_KEY)
604 last = key.objectid +
605 fs_info->nodesize;
606 else
607 last = key.objectid + key.offset;
608
609 if (total_found > CACHING_CTL_WAKE_UP) {
610 total_found = 0;
611 if (wakeup)
612 wake_up(&caching_ctl->wait);
613 }
614 }
615 path->slots[0]++;
616 }
617 ret = 0;
618
619 total_found += add_new_free_space(block_group, last,
Olivier Deprez157378f2022-04-04 15:47:50 +0200620 block_group->start + block_group->length);
David Brazdil0f672f62019-12-10 10:32:29 +0000621 caching_ctl->progress = (u64)-1;
622
623out:
624 btrfs_free_path(path);
625 return ret;
626}
627
628static noinline void caching_thread(struct btrfs_work *work)
629{
Olivier Deprez157378f2022-04-04 15:47:50 +0200630 struct btrfs_block_group *block_group;
David Brazdil0f672f62019-12-10 10:32:29 +0000631 struct btrfs_fs_info *fs_info;
632 struct btrfs_caching_control *caching_ctl;
633 int ret;
634
635 caching_ctl = container_of(work, struct btrfs_caching_control, work);
636 block_group = caching_ctl->block_group;
637 fs_info = block_group->fs_info;
638
639 mutex_lock(&caching_ctl->mutex);
640 down_read(&fs_info->commit_root_sem);
641
Olivier Deprez0e641232021-09-23 10:07:05 +0200642 /*
643 * If we are in the transaction that populated the free space tree we
644 * can't actually cache from the free space tree as our commit root and
645 * real root are the same, so we could change the contents of the blocks
646 * while caching. Instead do the slow caching in this case, and after
647 * the transaction has committed we will be safe.
648 */
649 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
650 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
David Brazdil0f672f62019-12-10 10:32:29 +0000651 ret = load_free_space_tree(caching_ctl);
652 else
653 ret = load_extent_tree_free(caching_ctl);
654
655 spin_lock(&block_group->lock);
656 block_group->caching_ctl = NULL;
657 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
658 spin_unlock(&block_group->lock);
659
660#ifdef CONFIG_BTRFS_DEBUG
661 if (btrfs_should_fragment_free_space(block_group)) {
662 u64 bytes_used;
663
664 spin_lock(&block_group->space_info->lock);
665 spin_lock(&block_group->lock);
Olivier Deprez157378f2022-04-04 15:47:50 +0200666 bytes_used = block_group->length - block_group->used;
David Brazdil0f672f62019-12-10 10:32:29 +0000667 block_group->space_info->bytes_used += bytes_used >> 1;
668 spin_unlock(&block_group->lock);
669 spin_unlock(&block_group->space_info->lock);
670 fragment_free_space(block_group);
671 }
672#endif
673
674 caching_ctl->progress = (u64)-1;
675
676 up_read(&fs_info->commit_root_sem);
677 btrfs_free_excluded_extents(block_group);
678 mutex_unlock(&caching_ctl->mutex);
679
680 wake_up(&caching_ctl->wait);
681
682 btrfs_put_caching_control(caching_ctl);
683 btrfs_put_block_group(block_group);
684}
685
Olivier Deprez157378f2022-04-04 15:47:50 +0200686int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
David Brazdil0f672f62019-12-10 10:32:29 +0000687{
688 DEFINE_WAIT(wait);
689 struct btrfs_fs_info *fs_info = cache->fs_info;
690 struct btrfs_caching_control *caching_ctl;
691 int ret = 0;
692
693 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
694 if (!caching_ctl)
695 return -ENOMEM;
696
697 INIT_LIST_HEAD(&caching_ctl->list);
698 mutex_init(&caching_ctl->mutex);
699 init_waitqueue_head(&caching_ctl->wait);
700 caching_ctl->block_group = cache;
Olivier Deprez157378f2022-04-04 15:47:50 +0200701 caching_ctl->progress = cache->start;
David Brazdil0f672f62019-12-10 10:32:29 +0000702 refcount_set(&caching_ctl->count, 1);
Olivier Deprez0e641232021-09-23 10:07:05 +0200703 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
David Brazdil0f672f62019-12-10 10:32:29 +0000704
705 spin_lock(&cache->lock);
706 /*
707 * This should be a rare occasion, but this could happen I think in the
708 * case where one thread starts to load the space cache info, and then
709 * some other thread starts a transaction commit which tries to do an
710 * allocation while the other thread is still loading the space cache
711 * info. The previous loop should have kept us from choosing this block
712 * group, but if we've moved to the state where we will wait on caching
713 * block groups we need to first check if we're doing a fast load here,
714 * so we can wait for it to finish, otherwise we could end up allocating
715 * from a block group who's cache gets evicted for one reason or
716 * another.
717 */
718 while (cache->cached == BTRFS_CACHE_FAST) {
719 struct btrfs_caching_control *ctl;
720
721 ctl = cache->caching_ctl;
722 refcount_inc(&ctl->count);
723 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
724 spin_unlock(&cache->lock);
725
726 schedule();
727
728 finish_wait(&ctl->wait, &wait);
729 btrfs_put_caching_control(ctl);
730 spin_lock(&cache->lock);
731 }
732
733 if (cache->cached != BTRFS_CACHE_NO) {
734 spin_unlock(&cache->lock);
735 kfree(caching_ctl);
736 return 0;
737 }
738 WARN_ON(cache->caching_ctl);
739 cache->caching_ctl = caching_ctl;
740 cache->cached = BTRFS_CACHE_FAST;
741 spin_unlock(&cache->lock);
742
743 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
744 mutex_lock(&caching_ctl->mutex);
745 ret = load_free_space_cache(cache);
746
747 spin_lock(&cache->lock);
748 if (ret == 1) {
749 cache->caching_ctl = NULL;
750 cache->cached = BTRFS_CACHE_FINISHED;
751 cache->last_byte_to_unpin = (u64)-1;
752 caching_ctl->progress = (u64)-1;
753 } else {
754 if (load_cache_only) {
755 cache->caching_ctl = NULL;
756 cache->cached = BTRFS_CACHE_NO;
757 } else {
758 cache->cached = BTRFS_CACHE_STARTED;
759 cache->has_caching_ctl = 1;
760 }
761 }
762 spin_unlock(&cache->lock);
763#ifdef CONFIG_BTRFS_DEBUG
764 if (ret == 1 &&
765 btrfs_should_fragment_free_space(cache)) {
766 u64 bytes_used;
767
768 spin_lock(&cache->space_info->lock);
769 spin_lock(&cache->lock);
Olivier Deprez157378f2022-04-04 15:47:50 +0200770 bytes_used = cache->length - cache->used;
David Brazdil0f672f62019-12-10 10:32:29 +0000771 cache->space_info->bytes_used += bytes_used >> 1;
772 spin_unlock(&cache->lock);
773 spin_unlock(&cache->space_info->lock);
774 fragment_free_space(cache);
775 }
776#endif
777 mutex_unlock(&caching_ctl->mutex);
778
779 wake_up(&caching_ctl->wait);
780 if (ret == 1) {
781 btrfs_put_caching_control(caching_ctl);
782 btrfs_free_excluded_extents(cache);
783 return 0;
784 }
785 } else {
786 /*
787 * We're either using the free space tree or no caching at all.
788 * Set cached to the appropriate value and wakeup any waiters.
789 */
790 spin_lock(&cache->lock);
791 if (load_cache_only) {
792 cache->caching_ctl = NULL;
793 cache->cached = BTRFS_CACHE_NO;
794 } else {
795 cache->cached = BTRFS_CACHE_STARTED;
796 cache->has_caching_ctl = 1;
797 }
798 spin_unlock(&cache->lock);
799 wake_up(&caching_ctl->wait);
800 }
801
802 if (load_cache_only) {
803 btrfs_put_caching_control(caching_ctl);
804 return 0;
805 }
806
807 down_write(&fs_info->commit_root_sem);
808 refcount_inc(&caching_ctl->count);
809 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
810 up_write(&fs_info->commit_root_sem);
811
812 btrfs_get_block_group(cache);
813
814 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
815
816 return ret;
817}
818
819static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
820{
821 u64 extra_flags = chunk_to_extended(flags) &
822 BTRFS_EXTENDED_PROFILE_MASK;
823
824 write_seqlock(&fs_info->profiles_lock);
825 if (flags & BTRFS_BLOCK_GROUP_DATA)
826 fs_info->avail_data_alloc_bits &= ~extra_flags;
827 if (flags & BTRFS_BLOCK_GROUP_METADATA)
828 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
829 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
830 fs_info->avail_system_alloc_bits &= ~extra_flags;
831 write_sequnlock(&fs_info->profiles_lock);
832}
833
834/*
835 * Clear incompat bits for the following feature(s):
836 *
837 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
838 * in the whole filesystem
Olivier Deprez157378f2022-04-04 15:47:50 +0200839 *
840 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
David Brazdil0f672f62019-12-10 10:32:29 +0000841 */
842static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
843{
Olivier Deprez157378f2022-04-04 15:47:50 +0200844 bool found_raid56 = false;
845 bool found_raid1c34 = false;
846
847 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
848 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
849 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
David Brazdil0f672f62019-12-10 10:32:29 +0000850 struct list_head *head = &fs_info->space_info;
851 struct btrfs_space_info *sinfo;
852
853 list_for_each_entry_rcu(sinfo, head, list) {
David Brazdil0f672f62019-12-10 10:32:29 +0000854 down_read(&sinfo->groups_sem);
855 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
Olivier Deprez157378f2022-04-04 15:47:50 +0200856 found_raid56 = true;
David Brazdil0f672f62019-12-10 10:32:29 +0000857 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
Olivier Deprez157378f2022-04-04 15:47:50 +0200858 found_raid56 = true;
859 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
860 found_raid1c34 = true;
861 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
862 found_raid1c34 = true;
David Brazdil0f672f62019-12-10 10:32:29 +0000863 up_read(&sinfo->groups_sem);
David Brazdil0f672f62019-12-10 10:32:29 +0000864 }
Olivier Deprez157378f2022-04-04 15:47:50 +0200865 if (!found_raid56)
866 btrfs_clear_fs_incompat(fs_info, RAID56);
867 if (!found_raid1c34)
868 btrfs_clear_fs_incompat(fs_info, RAID1C34);
David Brazdil0f672f62019-12-10 10:32:29 +0000869 }
870}
871
Olivier Deprez157378f2022-04-04 15:47:50 +0200872static int remove_block_group_item(struct btrfs_trans_handle *trans,
873 struct btrfs_path *path,
874 struct btrfs_block_group *block_group)
875{
876 struct btrfs_fs_info *fs_info = trans->fs_info;
877 struct btrfs_root *root;
878 struct btrfs_key key;
879 int ret;
880
881 root = fs_info->extent_root;
882 key.objectid = block_group->start;
883 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
884 key.offset = block_group->length;
885
886 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
887 if (ret > 0)
888 ret = -ENOENT;
889 if (ret < 0)
890 return ret;
891
892 ret = btrfs_del_item(trans, root, path);
893 return ret;
894}
895
David Brazdil0f672f62019-12-10 10:32:29 +0000896int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
897 u64 group_start, struct extent_map *em)
898{
899 struct btrfs_fs_info *fs_info = trans->fs_info;
David Brazdil0f672f62019-12-10 10:32:29 +0000900 struct btrfs_path *path;
Olivier Deprez157378f2022-04-04 15:47:50 +0200901 struct btrfs_block_group *block_group;
David Brazdil0f672f62019-12-10 10:32:29 +0000902 struct btrfs_free_cluster *cluster;
903 struct btrfs_root *tree_root = fs_info->tree_root;
904 struct btrfs_key key;
905 struct inode *inode;
906 struct kobject *kobj = NULL;
907 int ret;
908 int index;
909 int factor;
910 struct btrfs_caching_control *caching_ctl = NULL;
911 bool remove_em;
912 bool remove_rsv = false;
913
914 block_group = btrfs_lookup_block_group(fs_info, group_start);
915 BUG_ON(!block_group);
916 BUG_ON(!block_group->ro);
917
918 trace_btrfs_remove_block_group(block_group);
919 /*
920 * Free the reserved super bytes from this block group before
921 * remove it.
922 */
923 btrfs_free_excluded_extents(block_group);
Olivier Deprez157378f2022-04-04 15:47:50 +0200924 btrfs_free_ref_tree_range(fs_info, block_group->start,
925 block_group->length);
David Brazdil0f672f62019-12-10 10:32:29 +0000926
David Brazdil0f672f62019-12-10 10:32:29 +0000927 index = btrfs_bg_flags_to_raid_index(block_group->flags);
928 factor = btrfs_bg_type_to_factor(block_group->flags);
929
930 /* make sure this block group isn't part of an allocation cluster */
931 cluster = &fs_info->data_alloc_cluster;
932 spin_lock(&cluster->refill_lock);
933 btrfs_return_cluster_to_free_space(block_group, cluster);
934 spin_unlock(&cluster->refill_lock);
935
936 /*
937 * make sure this block group isn't part of a metadata
938 * allocation cluster
939 */
940 cluster = &fs_info->meta_alloc_cluster;
941 spin_lock(&cluster->refill_lock);
942 btrfs_return_cluster_to_free_space(block_group, cluster);
943 spin_unlock(&cluster->refill_lock);
944
945 path = btrfs_alloc_path();
946 if (!path) {
947 ret = -ENOMEM;
948 goto out;
949 }
950
951 /*
952 * get the inode first so any iput calls done for the io_list
953 * aren't the final iput (no unlinks allowed now)
954 */
955 inode = lookup_free_space_inode(block_group, path);
956
957 mutex_lock(&trans->transaction->cache_write_mutex);
958 /*
959 * Make sure our free space cache IO is done before removing the
960 * free space inode
961 */
962 spin_lock(&trans->transaction->dirty_bgs_lock);
963 if (!list_empty(&block_group->io_list)) {
964 list_del_init(&block_group->io_list);
965
966 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
967
968 spin_unlock(&trans->transaction->dirty_bgs_lock);
969 btrfs_wait_cache_io(trans, block_group, path);
970 btrfs_put_block_group(block_group);
971 spin_lock(&trans->transaction->dirty_bgs_lock);
972 }
973
974 if (!list_empty(&block_group->dirty_list)) {
975 list_del_init(&block_group->dirty_list);
976 remove_rsv = true;
977 btrfs_put_block_group(block_group);
978 }
979 spin_unlock(&trans->transaction->dirty_bgs_lock);
980 mutex_unlock(&trans->transaction->cache_write_mutex);
981
982 if (!IS_ERR(inode)) {
983 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
984 if (ret) {
985 btrfs_add_delayed_iput(inode);
986 goto out;
987 }
988 clear_nlink(inode);
989 /* One for the block groups ref */
990 spin_lock(&block_group->lock);
991 if (block_group->iref) {
992 block_group->iref = 0;
993 block_group->inode = NULL;
994 spin_unlock(&block_group->lock);
995 iput(inode);
996 } else {
997 spin_unlock(&block_group->lock);
998 }
999 /* One for our lookup ref */
1000 btrfs_add_delayed_iput(inode);
1001 }
1002
1003 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
David Brazdil0f672f62019-12-10 10:32:29 +00001004 key.type = 0;
Olivier Deprez157378f2022-04-04 15:47:50 +02001005 key.offset = block_group->start;
David Brazdil0f672f62019-12-10 10:32:29 +00001006
1007 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
1008 if (ret < 0)
1009 goto out;
1010 if (ret > 0)
1011 btrfs_release_path(path);
1012 if (ret == 0) {
1013 ret = btrfs_del_item(trans, tree_root, path);
1014 if (ret)
1015 goto out;
1016 btrfs_release_path(path);
1017 }
1018
1019 spin_lock(&fs_info->block_group_cache_lock);
1020 rb_erase(&block_group->cache_node,
1021 &fs_info->block_group_cache_tree);
1022 RB_CLEAR_NODE(&block_group->cache_node);
1023
Olivier Deprez0e641232021-09-23 10:07:05 +02001024 /* Once for the block groups rbtree */
1025 btrfs_put_block_group(block_group);
1026
Olivier Deprez157378f2022-04-04 15:47:50 +02001027 if (fs_info->first_logical_byte == block_group->start)
David Brazdil0f672f62019-12-10 10:32:29 +00001028 fs_info->first_logical_byte = (u64)-1;
1029 spin_unlock(&fs_info->block_group_cache_lock);
1030
1031 down_write(&block_group->space_info->groups_sem);
1032 /*
1033 * we must use list_del_init so people can check to see if they
1034 * are still on the list after taking the semaphore
1035 */
1036 list_del_init(&block_group->list);
1037 if (list_empty(&block_group->space_info->block_groups[index])) {
1038 kobj = block_group->space_info->block_group_kobjs[index];
1039 block_group->space_info->block_group_kobjs[index] = NULL;
1040 clear_avail_alloc_bits(fs_info, block_group->flags);
1041 }
1042 up_write(&block_group->space_info->groups_sem);
1043 clear_incompat_bg_bits(fs_info, block_group->flags);
1044 if (kobj) {
1045 kobject_del(kobj);
1046 kobject_put(kobj);
1047 }
1048
1049 if (block_group->has_caching_ctl)
1050 caching_ctl = btrfs_get_caching_control(block_group);
1051 if (block_group->cached == BTRFS_CACHE_STARTED)
1052 btrfs_wait_block_group_cache_done(block_group);
1053 if (block_group->has_caching_ctl) {
1054 down_write(&fs_info->commit_root_sem);
1055 if (!caching_ctl) {
1056 struct btrfs_caching_control *ctl;
1057
1058 list_for_each_entry(ctl,
1059 &fs_info->caching_block_groups, list)
1060 if (ctl->block_group == block_group) {
1061 caching_ctl = ctl;
1062 refcount_inc(&caching_ctl->count);
1063 break;
1064 }
1065 }
1066 if (caching_ctl)
1067 list_del_init(&caching_ctl->list);
1068 up_write(&fs_info->commit_root_sem);
1069 if (caching_ctl) {
1070 /* Once for the caching bgs list and once for us. */
1071 btrfs_put_caching_control(caching_ctl);
1072 btrfs_put_caching_control(caching_ctl);
1073 }
1074 }
1075
1076 spin_lock(&trans->transaction->dirty_bgs_lock);
1077 WARN_ON(!list_empty(&block_group->dirty_list));
1078 WARN_ON(!list_empty(&block_group->io_list));
1079 spin_unlock(&trans->transaction->dirty_bgs_lock);
1080
1081 btrfs_remove_free_space_cache(block_group);
1082
1083 spin_lock(&block_group->space_info->lock);
1084 list_del_init(&block_group->ro_list);
1085
1086 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1087 WARN_ON(block_group->space_info->total_bytes
Olivier Deprez157378f2022-04-04 15:47:50 +02001088 < block_group->length);
David Brazdil0f672f62019-12-10 10:32:29 +00001089 WARN_ON(block_group->space_info->bytes_readonly
Olivier Deprez157378f2022-04-04 15:47:50 +02001090 < block_group->length);
David Brazdil0f672f62019-12-10 10:32:29 +00001091 WARN_ON(block_group->space_info->disk_total
Olivier Deprez157378f2022-04-04 15:47:50 +02001092 < block_group->length * factor);
David Brazdil0f672f62019-12-10 10:32:29 +00001093 }
Olivier Deprez157378f2022-04-04 15:47:50 +02001094 block_group->space_info->total_bytes -= block_group->length;
1095 block_group->space_info->bytes_readonly -= block_group->length;
1096 block_group->space_info->disk_total -= block_group->length * factor;
David Brazdil0f672f62019-12-10 10:32:29 +00001097
1098 spin_unlock(&block_group->space_info->lock);
1099
Olivier Deprez157378f2022-04-04 15:47:50 +02001100 /*
1101 * Remove the free space for the block group from the free space tree
1102 * and the block group's item from the extent tree before marking the
1103 * block group as removed. This is to prevent races with tasks that
1104 * freeze and unfreeze a block group, this task and another task
1105 * allocating a new block group - the unfreeze task ends up removing
1106 * the block group's extent map before the task calling this function
1107 * deletes the block group item from the extent tree, allowing for
1108 * another task to attempt to create another block group with the same
1109 * item key (and failing with -EEXIST and a transaction abort).
1110 */
1111 ret = remove_block_group_free_space(trans, block_group);
1112 if (ret)
1113 goto out;
David Brazdil0f672f62019-12-10 10:32:29 +00001114
Olivier Deprez157378f2022-04-04 15:47:50 +02001115 ret = remove_block_group_item(trans, path, block_group);
1116 if (ret < 0)
1117 goto out;
1118
David Brazdil0f672f62019-12-10 10:32:29 +00001119 spin_lock(&block_group->lock);
1120 block_group->removed = 1;
1121 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02001122 * At this point trimming or scrub can't start on this block group,
1123 * because we removed the block group from the rbtree
1124 * fs_info->block_group_cache_tree so no one can't find it anymore and
1125 * even if someone already got this block group before we removed it
1126 * from the rbtree, they have already incremented block_group->frozen -
1127 * if they didn't, for the trimming case they won't find any free space
1128 * entries because we already removed them all when we called
1129 * btrfs_remove_free_space_cache().
David Brazdil0f672f62019-12-10 10:32:29 +00001130 *
1131 * And we must not remove the extent map from the fs_info->mapping_tree
1132 * to prevent the same logical address range and physical device space
Olivier Deprez157378f2022-04-04 15:47:50 +02001133 * ranges from being reused for a new block group. This is needed to
1134 * avoid races with trimming and scrub.
1135 *
1136 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
David Brazdil0f672f62019-12-10 10:32:29 +00001137 * completely transactionless, so while it is trimming a range the
1138 * currently running transaction might finish and a new one start,
1139 * allowing for new block groups to be created that can reuse the same
1140 * physical device locations unless we take this special care.
1141 *
1142 * There may also be an implicit trim operation if the file system
1143 * is mounted with -odiscard. The same protections must remain
1144 * in place until the extents have been discarded completely when
1145 * the transaction commit has completed.
1146 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001147 remove_em = (atomic_read(&block_group->frozen) == 0);
David Brazdil0f672f62019-12-10 10:32:29 +00001148 spin_unlock(&block_group->lock);
1149
David Brazdil0f672f62019-12-10 10:32:29 +00001150 if (remove_em) {
1151 struct extent_map_tree *em_tree;
1152
1153 em_tree = &fs_info->mapping_tree;
1154 write_lock(&em_tree->lock);
1155 remove_extent_mapping(em_tree, em);
1156 write_unlock(&em_tree->lock);
1157 /* once for the tree */
1158 free_extent_map(em);
1159 }
Olivier Deprez0e641232021-09-23 10:07:05 +02001160
David Brazdil0f672f62019-12-10 10:32:29 +00001161out:
Olivier Deprez0e641232021-09-23 10:07:05 +02001162 /* Once for the lookup reference */
1163 btrfs_put_block_group(block_group);
David Brazdil0f672f62019-12-10 10:32:29 +00001164 if (remove_rsv)
1165 btrfs_delayed_refs_rsv_release(fs_info, 1);
1166 btrfs_free_path(path);
1167 return ret;
1168}
1169
1170struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1171 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1172{
1173 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1174 struct extent_map *em;
1175 struct map_lookup *map;
1176 unsigned int num_items;
1177
1178 read_lock(&em_tree->lock);
1179 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1180 read_unlock(&em_tree->lock);
1181 ASSERT(em && em->start == chunk_offset);
1182
1183 /*
1184 * We need to reserve 3 + N units from the metadata space info in order
1185 * to remove a block group (done at btrfs_remove_chunk() and at
1186 * btrfs_remove_block_group()), which are used for:
1187 *
1188 * 1 unit for adding the free space inode's orphan (located in the tree
1189 * of tree roots).
1190 * 1 unit for deleting the block group item (located in the extent
1191 * tree).
1192 * 1 unit for deleting the free space item (located in tree of tree
1193 * roots).
1194 * N units for deleting N device extent items corresponding to each
1195 * stripe (located in the device tree).
1196 *
1197 * In order to remove a block group we also need to reserve units in the
1198 * system space info in order to update the chunk tree (update one or
1199 * more device items and remove one chunk item), but this is done at
1200 * btrfs_remove_chunk() through a call to check_system_chunk().
1201 */
1202 map = em->map_lookup;
1203 num_items = 3 + map->num_stripes;
1204 free_extent_map(em);
1205
1206 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
Olivier Deprez0e641232021-09-23 10:07:05 +02001207 num_items);
David Brazdil0f672f62019-12-10 10:32:29 +00001208}
1209
1210/*
1211 * Mark block group @cache read-only, so later write won't happen to block
1212 * group @cache.
1213 *
1214 * If @force is not set, this function will only mark the block group readonly
1215 * if we have enough free space (1M) in other metadata/system block groups.
1216 * If @force is not set, this function will mark the block group readonly
1217 * without checking free space.
1218 *
1219 * NOTE: This function doesn't care if other block groups can contain all the
1220 * data in this block group. That check should be done by relocation routine,
1221 * not this function.
1222 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001223static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
David Brazdil0f672f62019-12-10 10:32:29 +00001224{
1225 struct btrfs_space_info *sinfo = cache->space_info;
1226 u64 num_bytes;
David Brazdil0f672f62019-12-10 10:32:29 +00001227 int ret = -ENOSPC;
1228
David Brazdil0f672f62019-12-10 10:32:29 +00001229 spin_lock(&sinfo->lock);
1230 spin_lock(&cache->lock);
1231
Olivier Deprez157378f2022-04-04 15:47:50 +02001232 if (cache->swap_extents) {
1233 ret = -ETXTBSY;
1234 goto out;
1235 }
1236
David Brazdil0f672f62019-12-10 10:32:29 +00001237 if (cache->ro) {
1238 cache->ro++;
1239 ret = 0;
1240 goto out;
1241 }
1242
Olivier Deprez157378f2022-04-04 15:47:50 +02001243 num_bytes = cache->length - cache->reserved - cache->pinned -
1244 cache->bytes_super - cache->used;
David Brazdil0f672f62019-12-10 10:32:29 +00001245
1246 /*
Olivier Deprez0e641232021-09-23 10:07:05 +02001247 * Data never overcommits, even in mixed mode, so do just the straight
1248 * check of left over space in how much we have allocated.
David Brazdil0f672f62019-12-10 10:32:29 +00001249 */
Olivier Deprez0e641232021-09-23 10:07:05 +02001250 if (force) {
1251 ret = 0;
1252 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1253 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1254
1255 /*
1256 * Here we make sure if we mark this bg RO, we still have enough
1257 * free space as buffer.
1258 */
1259 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1260 ret = 0;
1261 } else {
1262 /*
1263 * We overcommit metadata, so we need to do the
1264 * btrfs_can_overcommit check here, and we need to pass in
1265 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1266 * leeway to allow us to mark this block group as read only.
1267 */
1268 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1269 BTRFS_RESERVE_NO_FLUSH))
1270 ret = 0;
1271 }
1272
1273 if (!ret) {
David Brazdil0f672f62019-12-10 10:32:29 +00001274 sinfo->bytes_readonly += num_bytes;
1275 cache->ro++;
1276 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
David Brazdil0f672f62019-12-10 10:32:29 +00001277 }
1278out:
1279 spin_unlock(&cache->lock);
1280 spin_unlock(&sinfo->lock);
1281 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1282 btrfs_info(cache->fs_info,
Olivier Deprez157378f2022-04-04 15:47:50 +02001283 "unable to make block group %llu ro", cache->start);
David Brazdil0f672f62019-12-10 10:32:29 +00001284 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1285 }
1286 return ret;
1287}
1288
Olivier Deprez157378f2022-04-04 15:47:50 +02001289static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1290 struct btrfs_block_group *bg)
1291{
1292 struct btrfs_fs_info *fs_info = bg->fs_info;
1293 struct btrfs_transaction *prev_trans = NULL;
1294 const u64 start = bg->start;
1295 const u64 end = start + bg->length - 1;
1296 int ret;
1297
1298 spin_lock(&fs_info->trans_lock);
1299 if (trans->transaction->list.prev != &fs_info->trans_list) {
1300 prev_trans = list_last_entry(&trans->transaction->list,
1301 struct btrfs_transaction, list);
1302 refcount_inc(&prev_trans->use_count);
1303 }
1304 spin_unlock(&fs_info->trans_lock);
1305
1306 /*
1307 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1308 * btrfs_finish_extent_commit(). If we are at transaction N, another
1309 * task might be running finish_extent_commit() for the previous
1310 * transaction N - 1, and have seen a range belonging to the block
1311 * group in pinned_extents before we were able to clear the whole block
1312 * group range from pinned_extents. This means that task can lookup for
1313 * the block group after we unpinned it from pinned_extents and removed
1314 * it, leading to a BUG_ON() at unpin_extent_range().
1315 */
1316 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1317 if (prev_trans) {
1318 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1319 EXTENT_DIRTY);
1320 if (ret)
1321 goto out;
1322 }
1323
1324 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
1325 EXTENT_DIRTY);
1326out:
1327 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
1328 if (prev_trans)
1329 btrfs_put_transaction(prev_trans);
1330
1331 return ret == 0;
1332}
1333
David Brazdil0f672f62019-12-10 10:32:29 +00001334/*
1335 * Process the unused_bgs list and remove any that don't have any allocated
1336 * space inside of them.
1337 */
1338void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1339{
Olivier Deprez157378f2022-04-04 15:47:50 +02001340 struct btrfs_block_group *block_group;
David Brazdil0f672f62019-12-10 10:32:29 +00001341 struct btrfs_space_info *space_info;
1342 struct btrfs_trans_handle *trans;
Olivier Deprez157378f2022-04-04 15:47:50 +02001343 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
David Brazdil0f672f62019-12-10 10:32:29 +00001344 int ret = 0;
1345
1346 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1347 return;
1348
1349 spin_lock(&fs_info->unused_bgs_lock);
1350 while (!list_empty(&fs_info->unused_bgs)) {
David Brazdil0f672f62019-12-10 10:32:29 +00001351 int trimming;
1352
1353 block_group = list_first_entry(&fs_info->unused_bgs,
Olivier Deprez157378f2022-04-04 15:47:50 +02001354 struct btrfs_block_group,
David Brazdil0f672f62019-12-10 10:32:29 +00001355 bg_list);
1356 list_del_init(&block_group->bg_list);
1357
1358 space_info = block_group->space_info;
1359
1360 if (ret || btrfs_mixed_space_info(space_info)) {
1361 btrfs_put_block_group(block_group);
1362 continue;
1363 }
1364 spin_unlock(&fs_info->unused_bgs_lock);
1365
Olivier Deprez157378f2022-04-04 15:47:50 +02001366 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1367
David Brazdil0f672f62019-12-10 10:32:29 +00001368 mutex_lock(&fs_info->delete_unused_bgs_mutex);
1369
1370 /* Don't want to race with allocators so take the groups_sem */
1371 down_write(&space_info->groups_sem);
Olivier Deprez157378f2022-04-04 15:47:50 +02001372
1373 /*
1374 * Async discard moves the final block group discard to be prior
1375 * to the unused_bgs code path. Therefore, if it's not fully
1376 * trimmed, punt it back to the async discard lists.
1377 */
1378 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1379 !btrfs_is_free_space_trimmed(block_group)) {
1380 trace_btrfs_skip_unused_block_group(block_group);
1381 up_write(&space_info->groups_sem);
1382 /* Requeue if we failed because of async discard */
1383 btrfs_discard_queue_work(&fs_info->discard_ctl,
1384 block_group);
1385 goto next;
1386 }
1387
David Brazdil0f672f62019-12-10 10:32:29 +00001388 spin_lock(&block_group->lock);
1389 if (block_group->reserved || block_group->pinned ||
Olivier Deprez157378f2022-04-04 15:47:50 +02001390 block_group->used || block_group->ro ||
David Brazdil0f672f62019-12-10 10:32:29 +00001391 list_is_singular(&block_group->list)) {
1392 /*
1393 * We want to bail if we made new allocations or have
1394 * outstanding allocations in this block group. We do
1395 * the ro check in case balance is currently acting on
1396 * this block group.
1397 */
1398 trace_btrfs_skip_unused_block_group(block_group);
1399 spin_unlock(&block_group->lock);
1400 up_write(&space_info->groups_sem);
1401 goto next;
1402 }
1403 spin_unlock(&block_group->lock);
1404
1405 /* We don't want to force the issue, only flip if it's ok. */
1406 ret = inc_block_group_ro(block_group, 0);
1407 up_write(&space_info->groups_sem);
1408 if (ret < 0) {
1409 ret = 0;
1410 goto next;
1411 }
1412
1413 /*
1414 * Want to do this before we do anything else so we can recover
1415 * properly if we fail to join the transaction.
1416 */
1417 trans = btrfs_start_trans_remove_block_group(fs_info,
Olivier Deprez157378f2022-04-04 15:47:50 +02001418 block_group->start);
David Brazdil0f672f62019-12-10 10:32:29 +00001419 if (IS_ERR(trans)) {
1420 btrfs_dec_block_group_ro(block_group);
1421 ret = PTR_ERR(trans);
1422 goto next;
1423 }
1424
1425 /*
1426 * We could have pending pinned extents for this block group,
1427 * just delete them, we don't care about them anymore.
1428 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001429 if (!clean_pinned_extents(trans, block_group)) {
1430 btrfs_dec_block_group_ro(block_group);
1431 goto end_trans;
1432 }
1433
David Brazdil0f672f62019-12-10 10:32:29 +00001434 /*
Olivier Deprez157378f2022-04-04 15:47:50 +02001435 * At this point, the block_group is read only and should fail
1436 * new allocations. However, btrfs_finish_extent_commit() can
1437 * cause this block_group to be placed back on the discard
1438 * lists because now the block_group isn't fully discarded.
1439 * Bail here and try again later after discarding everything.
David Brazdil0f672f62019-12-10 10:32:29 +00001440 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001441 spin_lock(&fs_info->discard_ctl.lock);
1442 if (!list_empty(&block_group->discard_list)) {
1443 spin_unlock(&fs_info->discard_ctl.lock);
David Brazdil0f672f62019-12-10 10:32:29 +00001444 btrfs_dec_block_group_ro(block_group);
Olivier Deprez157378f2022-04-04 15:47:50 +02001445 btrfs_discard_queue_work(&fs_info->discard_ctl,
1446 block_group);
David Brazdil0f672f62019-12-10 10:32:29 +00001447 goto end_trans;
1448 }
Olivier Deprez157378f2022-04-04 15:47:50 +02001449 spin_unlock(&fs_info->discard_ctl.lock);
David Brazdil0f672f62019-12-10 10:32:29 +00001450
1451 /* Reset pinned so btrfs_put_block_group doesn't complain */
1452 spin_lock(&space_info->lock);
1453 spin_lock(&block_group->lock);
1454
1455 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1456 -block_group->pinned);
1457 space_info->bytes_readonly += block_group->pinned;
Olivier Deprez157378f2022-04-04 15:47:50 +02001458 __btrfs_mod_total_bytes_pinned(space_info, -block_group->pinned);
David Brazdil0f672f62019-12-10 10:32:29 +00001459 block_group->pinned = 0;
1460
1461 spin_unlock(&block_group->lock);
1462 spin_unlock(&space_info->lock);
1463
Olivier Deprez157378f2022-04-04 15:47:50 +02001464 /*
1465 * The normal path here is an unused block group is passed here,
1466 * then trimming is handled in the transaction commit path.
1467 * Async discard interposes before this to do the trimming
1468 * before coming down the unused block group path as trimming
1469 * will no longer be done later in the transaction commit path.
1470 */
1471 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1472 goto flip_async;
1473
David Brazdil0f672f62019-12-10 10:32:29 +00001474 /* DISCARD can flip during remount */
Olivier Deprez157378f2022-04-04 15:47:50 +02001475 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
David Brazdil0f672f62019-12-10 10:32:29 +00001476
1477 /* Implicit trim during transaction commit. */
1478 if (trimming)
Olivier Deprez157378f2022-04-04 15:47:50 +02001479 btrfs_freeze_block_group(block_group);
David Brazdil0f672f62019-12-10 10:32:29 +00001480
1481 /*
1482 * Btrfs_remove_chunk will abort the transaction if things go
1483 * horribly wrong.
1484 */
Olivier Deprez157378f2022-04-04 15:47:50 +02001485 ret = btrfs_remove_chunk(trans, block_group->start);
David Brazdil0f672f62019-12-10 10:32:29 +00001486
1487 if (ret) {
1488 if (trimming)
Olivier Deprez157378f2022-04-04 15:47:50 +02001489 btrfs_unfreeze_block_group(block_group);
David Brazdil0f672f62019-12-10 10:32:29 +00001490 goto end_trans;
1491 }
1492
1493 /*
1494 * If we're not mounted with -odiscard, we can just forget
1495 * about this block group. Otherwise we'll need to wait
1496 * until transaction commit to do the actual discard.
1497 */
1498 if (trimming) {
1499 spin_lock(&fs_info->unused_bgs_lock);
1500 /*
1501 * A concurrent scrub might have added us to the list
1502 * fs_info->unused_bgs, so use a list_move operation
1503 * to add the block group to the deleted_bgs list.
1504 */
1505 list_move(&block_group->bg_list,
1506 &trans->transaction->deleted_bgs);
1507 spin_unlock(&fs_info->unused_bgs_lock);
1508 btrfs_get_block_group(block_group);
1509 }
1510end_trans:
1511 btrfs_end_transaction(trans);
1512next:
1513 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1514 btrfs_put_block_group(block_group);
1515 spin_lock(&fs_info->unused_bgs_lock);
1516 }
1517 spin_unlock(&fs_info->unused_bgs_lock);
Olivier Deprez157378f2022-04-04 15:47:50 +02001518 return;
1519
1520flip_async:
1521 btrfs_end_transaction(trans);
1522 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1523 btrfs_put_block_group(block_group);
1524 btrfs_discard_punt_unused_bgs_list(fs_info);
David Brazdil0f672f62019-12-10 10:32:29 +00001525}
1526
Olivier Deprez157378f2022-04-04 15:47:50 +02001527void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
David Brazdil0f672f62019-12-10 10:32:29 +00001528{
1529 struct btrfs_fs_info *fs_info = bg->fs_info;
1530
1531 spin_lock(&fs_info->unused_bgs_lock);
1532 if (list_empty(&bg->bg_list)) {
1533 btrfs_get_block_group(bg);
1534 trace_btrfs_add_unused_block_group(bg);
1535 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1536 }
1537 spin_unlock(&fs_info->unused_bgs_lock);
1538}
1539
Olivier Deprez157378f2022-04-04 15:47:50 +02001540static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1541 struct btrfs_path *path)
1542{
1543 struct extent_map_tree *em_tree;
1544 struct extent_map *em;
1545 struct btrfs_block_group_item bg;
1546 struct extent_buffer *leaf;
1547 int slot;
1548 u64 flags;
1549 int ret = 0;
1550
1551 slot = path->slots[0];
1552 leaf = path->nodes[0];
1553
1554 em_tree = &fs_info->mapping_tree;
1555 read_lock(&em_tree->lock);
1556 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1557 read_unlock(&em_tree->lock);
1558 if (!em) {
1559 btrfs_err(fs_info,
1560 "logical %llu len %llu found bg but no related chunk",
1561 key->objectid, key->offset);
1562 return -ENOENT;
1563 }
1564
1565 if (em->start != key->objectid || em->len != key->offset) {
1566 btrfs_err(fs_info,
1567 "block group %llu len %llu mismatch with chunk %llu len %llu",
1568 key->objectid, key->offset, em->start, em->len);
1569 ret = -EUCLEAN;
1570 goto out_free_em;
1571 }
1572
1573 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1574 sizeof(bg));
1575 flags = btrfs_stack_block_group_flags(&bg) &
1576 BTRFS_BLOCK_GROUP_TYPE_MASK;
1577
1578 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1579 btrfs_err(fs_info,
1580"block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1581 key->objectid, key->offset, flags,
1582 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1583 ret = -EUCLEAN;
1584 }
1585
1586out_free_em:
1587 free_extent_map(em);
1588 return ret;
1589}
1590
David Brazdil0f672f62019-12-10 10:32:29 +00001591static int find_first_block_group(struct btrfs_fs_info *fs_info,
1592 struct btrfs_path *path,
1593 struct btrfs_key *key)
1594{
1595 struct btrfs_root *root = fs_info->extent_root;
Olivier Deprez157378f2022-04-04 15:47:50 +02001596 int ret;
David Brazdil0f672f62019-12-10 10:32:29 +00001597 struct btrfs_key found_key;
1598 struct extent_buffer *leaf;
David Brazdil0f672f62019-12-10 10:32:29 +00001599 int slot;
1600
1601 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1602 if (ret < 0)
Olivier Deprez157378f2022-04-04 15:47:50 +02001603 return ret;
David Brazdil0f672f62019-12-10 10:32:29 +00001604
1605 while (1) {
1606 slot = path->slots[0];
1607 leaf = path->nodes[0];
1608 if (slot >= btrfs_header_nritems(leaf)) {
1609 ret = btrfs_next_leaf(root, path);
1610 if (ret == 0)
1611 continue;
1612 if (ret < 0)
1613 goto out;
1614 break;
1615 }
1616 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1617
1618 if (found_key.objectid >= key->objectid &&
1619 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001620 ret = read_bg_from_eb(fs_info, &found_key, path);
1621 break;
David Brazdil0f672f62019-12-10 10:32:29 +00001622 }
Olivier Deprez157378f2022-04-04 15:47:50 +02001623
David Brazdil0f672f62019-12-10 10:32:29 +00001624 path->slots[0]++;
1625 }
1626out:
1627 return ret;
1628}
1629
1630static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1631{
1632 u64 extra_flags = chunk_to_extended(flags) &
1633 BTRFS_EXTENDED_PROFILE_MASK;
1634
1635 write_seqlock(&fs_info->profiles_lock);
1636 if (flags & BTRFS_BLOCK_GROUP_DATA)
1637 fs_info->avail_data_alloc_bits |= extra_flags;
1638 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1639 fs_info->avail_metadata_alloc_bits |= extra_flags;
1640 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1641 fs_info->avail_system_alloc_bits |= extra_flags;
1642 write_sequnlock(&fs_info->profiles_lock);
1643}
1644
Olivier Deprez157378f2022-04-04 15:47:50 +02001645/**
1646 * btrfs_rmap_block - Map a physical disk address to a list of logical addresses
1647 * @chunk_start: logical address of block group
1648 * @physical: physical address to map to logical addresses
1649 * @logical: return array of logical addresses which map to @physical
1650 * @naddrs: length of @logical
1651 * @stripe_len: size of IO stripe for the given block group
1652 *
1653 * Maps a particular @physical disk address to a list of @logical addresses.
1654 * Used primarily to exclude those portions of a block group that contain super
1655 * block copies.
1656 */
1657EXPORT_FOR_TESTS
1658int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1659 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1660{
1661 struct extent_map *em;
1662 struct map_lookup *map;
1663 u64 *buf;
1664 u64 bytenr;
1665 u64 data_stripe_length;
1666 u64 io_stripe_size;
1667 int i, nr = 0;
1668 int ret = 0;
1669
1670 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1671 if (IS_ERR(em))
1672 return -EIO;
1673
1674 map = em->map_lookup;
1675 data_stripe_length = em->orig_block_len;
1676 io_stripe_size = map->stripe_len;
1677
1678 /* For RAID5/6 adjust to a full IO stripe length */
1679 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1680 io_stripe_size = map->stripe_len * nr_data_stripes(map);
1681
1682 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1683 if (!buf) {
1684 ret = -ENOMEM;
1685 goto out;
1686 }
1687
1688 for (i = 0; i < map->num_stripes; i++) {
1689 bool already_inserted = false;
1690 u64 stripe_nr;
1691 int j;
1692
1693 if (!in_range(physical, map->stripes[i].physical,
1694 data_stripe_length))
1695 continue;
1696
1697 stripe_nr = physical - map->stripes[i].physical;
1698 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1699
1700 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1701 stripe_nr = stripe_nr * map->num_stripes + i;
1702 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1703 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1704 stripe_nr = stripe_nr * map->num_stripes + i;
1705 }
1706 /*
1707 * The remaining case would be for RAID56, multiply by
1708 * nr_data_stripes(). Alternatively, just use rmap_len below
1709 * instead of map->stripe_len
1710 */
1711
1712 bytenr = chunk_start + stripe_nr * io_stripe_size;
1713
1714 /* Ensure we don't add duplicate addresses */
1715 for (j = 0; j < nr; j++) {
1716 if (buf[j] == bytenr) {
1717 already_inserted = true;
1718 break;
1719 }
1720 }
1721
1722 if (!already_inserted)
1723 buf[nr++] = bytenr;
1724 }
1725
1726 *logical = buf;
1727 *naddrs = nr;
1728 *stripe_len = io_stripe_size;
1729out:
1730 free_extent_map(em);
1731 return ret;
1732}
1733
1734static int exclude_super_stripes(struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +00001735{
1736 struct btrfs_fs_info *fs_info = cache->fs_info;
1737 u64 bytenr;
1738 u64 *logical;
1739 int stripe_len;
1740 int i, nr, ret;
1741
Olivier Deprez157378f2022-04-04 15:47:50 +02001742 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1743 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
David Brazdil0f672f62019-12-10 10:32:29 +00001744 cache->bytes_super += stripe_len;
Olivier Deprez157378f2022-04-04 15:47:50 +02001745 ret = btrfs_add_excluded_extent(fs_info, cache->start,
David Brazdil0f672f62019-12-10 10:32:29 +00001746 stripe_len);
1747 if (ret)
1748 return ret;
1749 }
1750
1751 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1752 bytenr = btrfs_sb_offset(i);
Olivier Deprez157378f2022-04-04 15:47:50 +02001753 ret = btrfs_rmap_block(fs_info, cache->start,
David Brazdil0f672f62019-12-10 10:32:29 +00001754 bytenr, &logical, &nr, &stripe_len);
1755 if (ret)
1756 return ret;
1757
1758 while (nr--) {
Olivier Deprez157378f2022-04-04 15:47:50 +02001759 u64 len = min_t(u64, stripe_len,
1760 cache->start + cache->length - logical[nr]);
David Brazdil0f672f62019-12-10 10:32:29 +00001761
1762 cache->bytes_super += len;
Olivier Deprez157378f2022-04-04 15:47:50 +02001763 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1764 len);
David Brazdil0f672f62019-12-10 10:32:29 +00001765 if (ret) {
1766 kfree(logical);
1767 return ret;
1768 }
1769 }
1770
1771 kfree(logical);
1772 }
1773 return 0;
1774}
1775
Olivier Deprez157378f2022-04-04 15:47:50 +02001776static void link_block_group(struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +00001777{
1778 struct btrfs_space_info *space_info = cache->space_info;
1779 int index = btrfs_bg_flags_to_raid_index(cache->flags);
David Brazdil0f672f62019-12-10 10:32:29 +00001780
1781 down_write(&space_info->groups_sem);
David Brazdil0f672f62019-12-10 10:32:29 +00001782 list_add_tail(&cache->list, &space_info->block_groups[index]);
1783 up_write(&space_info->groups_sem);
David Brazdil0f672f62019-12-10 10:32:29 +00001784}
1785
Olivier Deprez157378f2022-04-04 15:47:50 +02001786static struct btrfs_block_group *btrfs_create_block_group_cache(
1787 struct btrfs_fs_info *fs_info, u64 start)
David Brazdil0f672f62019-12-10 10:32:29 +00001788{
Olivier Deprez157378f2022-04-04 15:47:50 +02001789 struct btrfs_block_group *cache;
David Brazdil0f672f62019-12-10 10:32:29 +00001790
1791 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1792 if (!cache)
1793 return NULL;
1794
1795 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1796 GFP_NOFS);
1797 if (!cache->free_space_ctl) {
1798 kfree(cache);
1799 return NULL;
1800 }
1801
Olivier Deprez157378f2022-04-04 15:47:50 +02001802 cache->start = start;
David Brazdil0f672f62019-12-10 10:32:29 +00001803
1804 cache->fs_info = fs_info;
1805 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
David Brazdil0f672f62019-12-10 10:32:29 +00001806
Olivier Deprez157378f2022-04-04 15:47:50 +02001807 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1808
1809 refcount_set(&cache->refs, 1);
David Brazdil0f672f62019-12-10 10:32:29 +00001810 spin_lock_init(&cache->lock);
1811 init_rwsem(&cache->data_rwsem);
1812 INIT_LIST_HEAD(&cache->list);
1813 INIT_LIST_HEAD(&cache->cluster_list);
1814 INIT_LIST_HEAD(&cache->bg_list);
1815 INIT_LIST_HEAD(&cache->ro_list);
Olivier Deprez157378f2022-04-04 15:47:50 +02001816 INIT_LIST_HEAD(&cache->discard_list);
David Brazdil0f672f62019-12-10 10:32:29 +00001817 INIT_LIST_HEAD(&cache->dirty_list);
1818 INIT_LIST_HEAD(&cache->io_list);
1819 btrfs_init_free_space_ctl(cache);
Olivier Deprez157378f2022-04-04 15:47:50 +02001820 atomic_set(&cache->frozen, 0);
David Brazdil0f672f62019-12-10 10:32:29 +00001821 mutex_init(&cache->free_space_lock);
1822 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1823
1824 return cache;
1825}
1826
1827/*
1828 * Iterate all chunks and verify that each of them has the corresponding block
1829 * group
1830 */
1831static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1832{
1833 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1834 struct extent_map *em;
Olivier Deprez157378f2022-04-04 15:47:50 +02001835 struct btrfs_block_group *bg;
David Brazdil0f672f62019-12-10 10:32:29 +00001836 u64 start = 0;
1837 int ret = 0;
1838
1839 while (1) {
1840 read_lock(&map_tree->lock);
1841 /*
1842 * lookup_extent_mapping will return the first extent map
1843 * intersecting the range, so setting @len to 1 is enough to
1844 * get the first chunk.
1845 */
1846 em = lookup_extent_mapping(map_tree, start, 1);
1847 read_unlock(&map_tree->lock);
1848 if (!em)
1849 break;
1850
1851 bg = btrfs_lookup_block_group(fs_info, em->start);
1852 if (!bg) {
1853 btrfs_err(fs_info,
1854 "chunk start=%llu len=%llu doesn't have corresponding block group",
1855 em->start, em->len);
1856 ret = -EUCLEAN;
1857 free_extent_map(em);
1858 break;
1859 }
Olivier Deprez157378f2022-04-04 15:47:50 +02001860 if (bg->start != em->start || bg->length != em->len ||
David Brazdil0f672f62019-12-10 10:32:29 +00001861 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1862 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1863 btrfs_err(fs_info,
1864"chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1865 em->start, em->len,
1866 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
Olivier Deprez157378f2022-04-04 15:47:50 +02001867 bg->start, bg->length,
David Brazdil0f672f62019-12-10 10:32:29 +00001868 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1869 ret = -EUCLEAN;
1870 free_extent_map(em);
1871 btrfs_put_block_group(bg);
1872 break;
1873 }
1874 start = em->start + em->len;
1875 free_extent_map(em);
1876 btrfs_put_block_group(bg);
1877 }
1878 return ret;
1879}
1880
Olivier Deprez157378f2022-04-04 15:47:50 +02001881static void read_block_group_item(struct btrfs_block_group *cache,
1882 struct btrfs_path *path,
1883 const struct btrfs_key *key)
1884{
1885 struct extent_buffer *leaf = path->nodes[0];
1886 struct btrfs_block_group_item bgi;
1887 int slot = path->slots[0];
1888
1889 cache->length = key->offset;
1890
1891 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1892 sizeof(bgi));
1893 cache->used = btrfs_stack_block_group_used(&bgi);
1894 cache->flags = btrfs_stack_block_group_flags(&bgi);
1895}
1896
1897static int read_one_block_group(struct btrfs_fs_info *info,
1898 struct btrfs_path *path,
1899 const struct btrfs_key *key,
1900 int need_clear)
1901{
1902 struct btrfs_block_group *cache;
1903 struct btrfs_space_info *space_info;
1904 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1905 int ret;
1906
1907 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
1908
1909 cache = btrfs_create_block_group_cache(info, key->objectid);
1910 if (!cache)
1911 return -ENOMEM;
1912
1913 read_block_group_item(cache, path, key);
1914
1915 set_free_space_tree_thresholds(cache);
1916
1917 if (need_clear) {
1918 /*
1919 * When we mount with old space cache, we need to
1920 * set BTRFS_DC_CLEAR and set dirty flag.
1921 *
1922 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1923 * truncate the old free space cache inode and
1924 * setup a new one.
1925 * b) Setting 'dirty flag' makes sure that we flush
1926 * the new space cache info onto disk.
1927 */
1928 if (btrfs_test_opt(info, SPACE_CACHE))
1929 cache->disk_cache_state = BTRFS_DC_CLEAR;
1930 }
1931 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1932 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1933 btrfs_err(info,
1934"bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1935 cache->start);
1936 ret = -EINVAL;
1937 goto error;
1938 }
1939
1940 /*
1941 * We need to exclude the super stripes now so that the space info has
1942 * super bytes accounted for, otherwise we'll think we have more space
1943 * than we actually do.
1944 */
1945 ret = exclude_super_stripes(cache);
1946 if (ret) {
1947 /* We may have excluded something, so call this just in case. */
1948 btrfs_free_excluded_extents(cache);
1949 goto error;
1950 }
1951
1952 /*
1953 * Check for two cases, either we are full, and therefore don't need
1954 * to bother with the caching work since we won't find any space, or we
1955 * are empty, and we can just add all the space in and be done with it.
1956 * This saves us _a_lot_ of time, particularly in the full case.
1957 */
1958 if (cache->length == cache->used) {
1959 cache->last_byte_to_unpin = (u64)-1;
1960 cache->cached = BTRFS_CACHE_FINISHED;
1961 btrfs_free_excluded_extents(cache);
1962 } else if (cache->used == 0) {
1963 cache->last_byte_to_unpin = (u64)-1;
1964 cache->cached = BTRFS_CACHE_FINISHED;
1965 add_new_free_space(cache, cache->start,
1966 cache->start + cache->length);
1967 btrfs_free_excluded_extents(cache);
1968 }
1969
1970 ret = btrfs_add_block_group_cache(info, cache);
1971 if (ret) {
1972 btrfs_remove_free_space_cache(cache);
1973 goto error;
1974 }
1975 trace_btrfs_add_block_group(info, cache, 0);
1976 btrfs_update_space_info(info, cache->flags, cache->length,
1977 cache->used, cache->bytes_super, &space_info);
1978
1979 cache->space_info = space_info;
1980
1981 link_block_group(cache);
1982
1983 set_avail_alloc_bits(info, cache->flags);
1984 if (btrfs_chunk_readonly(info, cache->start)) {
1985 inc_block_group_ro(cache, 1);
1986 } else if (cache->used == 0) {
1987 ASSERT(list_empty(&cache->bg_list));
1988 if (btrfs_test_opt(info, DISCARD_ASYNC))
1989 btrfs_discard_queue_work(&info->discard_ctl, cache);
1990 else
1991 btrfs_mark_bg_unused(cache);
1992 }
1993 return 0;
1994error:
1995 btrfs_put_block_group(cache);
1996 return ret;
1997}
1998
David Brazdil0f672f62019-12-10 10:32:29 +00001999int btrfs_read_block_groups(struct btrfs_fs_info *info)
2000{
2001 struct btrfs_path *path;
2002 int ret;
Olivier Deprez157378f2022-04-04 15:47:50 +02002003 struct btrfs_block_group *cache;
David Brazdil0f672f62019-12-10 10:32:29 +00002004 struct btrfs_space_info *space_info;
2005 struct btrfs_key key;
David Brazdil0f672f62019-12-10 10:32:29 +00002006 int need_clear = 0;
2007 u64 cache_gen;
David Brazdil0f672f62019-12-10 10:32:29 +00002008
2009 key.objectid = 0;
2010 key.offset = 0;
2011 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2012 path = btrfs_alloc_path();
2013 if (!path)
2014 return -ENOMEM;
David Brazdil0f672f62019-12-10 10:32:29 +00002015
2016 cache_gen = btrfs_super_cache_generation(info->super_copy);
2017 if (btrfs_test_opt(info, SPACE_CACHE) &&
2018 btrfs_super_generation(info->super_copy) != cache_gen)
2019 need_clear = 1;
2020 if (btrfs_test_opt(info, CLEAR_CACHE))
2021 need_clear = 1;
2022
2023 while (1) {
2024 ret = find_first_block_group(info, path, &key);
2025 if (ret > 0)
2026 break;
2027 if (ret != 0)
2028 goto error;
2029
Olivier Deprez157378f2022-04-04 15:47:50 +02002030 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
2031 ret = read_one_block_group(info, path, &key, need_clear);
2032 if (ret < 0)
David Brazdil0f672f62019-12-10 10:32:29 +00002033 goto error;
Olivier Deprez157378f2022-04-04 15:47:50 +02002034 key.objectid += key.offset;
2035 key.offset = 0;
David Brazdil0f672f62019-12-10 10:32:29 +00002036 btrfs_release_path(path);
David Brazdil0f672f62019-12-10 10:32:29 +00002037 }
Olivier Deprez157378f2022-04-04 15:47:50 +02002038 btrfs_release_path(path);
David Brazdil0f672f62019-12-10 10:32:29 +00002039
Olivier Deprez157378f2022-04-04 15:47:50 +02002040 list_for_each_entry(space_info, &info->space_info, list) {
2041 int i;
2042
2043 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2044 if (list_empty(&space_info->block_groups[i]))
2045 continue;
2046 cache = list_first_entry(&space_info->block_groups[i],
2047 struct btrfs_block_group,
2048 list);
2049 btrfs_sysfs_add_block_group_type(cache);
2050 }
2051
David Brazdil0f672f62019-12-10 10:32:29 +00002052 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2053 (BTRFS_BLOCK_GROUP_RAID10 |
2054 BTRFS_BLOCK_GROUP_RAID1_MASK |
2055 BTRFS_BLOCK_GROUP_RAID56_MASK |
2056 BTRFS_BLOCK_GROUP_DUP)))
2057 continue;
2058 /*
2059 * Avoid allocating from un-mirrored block group if there are
2060 * mirrored block groups.
2061 */
2062 list_for_each_entry(cache,
2063 &space_info->block_groups[BTRFS_RAID_RAID0],
2064 list)
2065 inc_block_group_ro(cache, 1);
2066 list_for_each_entry(cache,
2067 &space_info->block_groups[BTRFS_RAID_SINGLE],
2068 list)
2069 inc_block_group_ro(cache, 1);
2070 }
2071
2072 btrfs_init_global_block_rsv(info);
2073 ret = check_chunk_block_group_mappings(info);
2074error:
2075 btrfs_free_path(path);
2076 return ret;
2077}
2078
Olivier Deprez157378f2022-04-04 15:47:50 +02002079static int insert_block_group_item(struct btrfs_trans_handle *trans,
2080 struct btrfs_block_group *block_group)
2081{
2082 struct btrfs_fs_info *fs_info = trans->fs_info;
2083 struct btrfs_block_group_item bgi;
2084 struct btrfs_root *root;
2085 struct btrfs_key key;
2086
2087 spin_lock(&block_group->lock);
2088 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2089 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2090 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2091 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2092 key.objectid = block_group->start;
2093 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2094 key.offset = block_group->length;
2095 spin_unlock(&block_group->lock);
2096
2097 root = fs_info->extent_root;
2098 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2099}
2100
David Brazdil0f672f62019-12-10 10:32:29 +00002101void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2102{
2103 struct btrfs_fs_info *fs_info = trans->fs_info;
Olivier Deprez157378f2022-04-04 15:47:50 +02002104 struct btrfs_block_group *block_group;
David Brazdil0f672f62019-12-10 10:32:29 +00002105 int ret = 0;
2106
2107 if (!trans->can_flush_pending_bgs)
2108 return;
2109
2110 while (!list_empty(&trans->new_bgs)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002111 int index;
2112
David Brazdil0f672f62019-12-10 10:32:29 +00002113 block_group = list_first_entry(&trans->new_bgs,
Olivier Deprez157378f2022-04-04 15:47:50 +02002114 struct btrfs_block_group,
David Brazdil0f672f62019-12-10 10:32:29 +00002115 bg_list);
2116 if (ret)
2117 goto next;
2118
Olivier Deprez157378f2022-04-04 15:47:50 +02002119 index = btrfs_bg_flags_to_raid_index(block_group->flags);
David Brazdil0f672f62019-12-10 10:32:29 +00002120
Olivier Deprez157378f2022-04-04 15:47:50 +02002121 ret = insert_block_group_item(trans, block_group);
David Brazdil0f672f62019-12-10 10:32:29 +00002122 if (ret)
2123 btrfs_abort_transaction(trans, ret);
Olivier Deprez157378f2022-04-04 15:47:50 +02002124 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2125 block_group->length);
David Brazdil0f672f62019-12-10 10:32:29 +00002126 if (ret)
2127 btrfs_abort_transaction(trans, ret);
2128 add_block_group_free_space(trans, block_group);
Olivier Deprez157378f2022-04-04 15:47:50 +02002129
2130 /*
2131 * If we restriped during balance, we may have added a new raid
2132 * type, so now add the sysfs entries when it is safe to do so.
2133 * We don't have to worry about locking here as it's handled in
2134 * btrfs_sysfs_add_block_group_type.
2135 */
2136 if (block_group->space_info->block_group_kobjs[index] == NULL)
2137 btrfs_sysfs_add_block_group_type(block_group);
2138
David Brazdil0f672f62019-12-10 10:32:29 +00002139 /* Already aborted the transaction if it failed. */
2140next:
2141 btrfs_delayed_refs_rsv_release(fs_info, 1);
2142 list_del_init(&block_group->bg_list);
2143 }
2144 btrfs_trans_release_chunk_metadata(trans);
2145}
2146
2147int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2148 u64 type, u64 chunk_offset, u64 size)
2149{
2150 struct btrfs_fs_info *fs_info = trans->fs_info;
Olivier Deprez157378f2022-04-04 15:47:50 +02002151 struct btrfs_block_group *cache;
David Brazdil0f672f62019-12-10 10:32:29 +00002152 int ret;
2153
2154 btrfs_set_log_full_commit(trans);
2155
Olivier Deprez157378f2022-04-04 15:47:50 +02002156 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
David Brazdil0f672f62019-12-10 10:32:29 +00002157 if (!cache)
2158 return -ENOMEM;
2159
Olivier Deprez157378f2022-04-04 15:47:50 +02002160 cache->length = size;
2161 set_free_space_tree_thresholds(cache);
2162 cache->used = bytes_used;
David Brazdil0f672f62019-12-10 10:32:29 +00002163 cache->flags = type;
2164 cache->last_byte_to_unpin = (u64)-1;
2165 cache->cached = BTRFS_CACHE_FINISHED;
2166 cache->needs_free_space = 1;
2167 ret = exclude_super_stripes(cache);
2168 if (ret) {
2169 /* We may have excluded something, so call this just in case */
2170 btrfs_free_excluded_extents(cache);
2171 btrfs_put_block_group(cache);
2172 return ret;
2173 }
2174
2175 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2176
2177 btrfs_free_excluded_extents(cache);
2178
2179#ifdef CONFIG_BTRFS_DEBUG
2180 if (btrfs_should_fragment_free_space(cache)) {
2181 u64 new_bytes_used = size - bytes_used;
2182
2183 bytes_used += new_bytes_used >> 1;
2184 fragment_free_space(cache);
2185 }
2186#endif
2187 /*
2188 * Ensure the corresponding space_info object is created and
2189 * assigned to our block group. We want our bg to be added to the rbtree
2190 * with its ->space_info set.
2191 */
2192 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2193 ASSERT(cache->space_info);
2194
2195 ret = btrfs_add_block_group_cache(fs_info, cache);
2196 if (ret) {
2197 btrfs_remove_free_space_cache(cache);
2198 btrfs_put_block_group(cache);
2199 return ret;
2200 }
2201
2202 /*
2203 * Now that our block group has its ->space_info set and is inserted in
2204 * the rbtree, update the space info's counters.
2205 */
2206 trace_btrfs_add_block_group(fs_info, cache, 1);
2207 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2208 cache->bytes_super, &cache->space_info);
2209 btrfs_update_global_block_rsv(fs_info);
2210
2211 link_block_group(cache);
2212
2213 list_add_tail(&cache->bg_list, &trans->new_bgs);
2214 trans->delayed_ref_updates++;
2215 btrfs_update_delayed_refs_rsv(trans);
2216
2217 set_avail_alloc_bits(fs_info, type);
2218 return 0;
2219}
2220
Olivier Deprez0e641232021-09-23 10:07:05 +02002221/*
2222 * Mark one block group RO, can be called several times for the same block
2223 * group.
2224 *
2225 * @cache: the destination block group
2226 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2227 * ensure we still have some free space after marking this
2228 * block group RO.
2229 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002230int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
Olivier Deprez0e641232021-09-23 10:07:05 +02002231 bool do_chunk_alloc)
David Brazdil0f672f62019-12-10 10:32:29 +00002232{
2233 struct btrfs_fs_info *fs_info = cache->fs_info;
2234 struct btrfs_trans_handle *trans;
2235 u64 alloc_flags;
2236 int ret;
2237
2238again:
2239 trans = btrfs_join_transaction(fs_info->extent_root);
2240 if (IS_ERR(trans))
2241 return PTR_ERR(trans);
2242
2243 /*
2244 * we're not allowed to set block groups readonly after the dirty
2245 * block groups cache has started writing. If it already started,
2246 * back off and let this transaction commit
2247 */
2248 mutex_lock(&fs_info->ro_block_group_mutex);
2249 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2250 u64 transid = trans->transid;
2251
2252 mutex_unlock(&fs_info->ro_block_group_mutex);
2253 btrfs_end_transaction(trans);
2254
2255 ret = btrfs_wait_for_commit(fs_info, transid);
2256 if (ret)
2257 return ret;
2258 goto again;
2259 }
2260
Olivier Deprez0e641232021-09-23 10:07:05 +02002261 if (do_chunk_alloc) {
David Brazdil0f672f62019-12-10 10:32:29 +00002262 /*
Olivier Deprez0e641232021-09-23 10:07:05 +02002263 * If we are changing raid levels, try to allocate a
2264 * corresponding block group with the new raid level.
David Brazdil0f672f62019-12-10 10:32:29 +00002265 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002266 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
Olivier Deprez0e641232021-09-23 10:07:05 +02002267 if (alloc_flags != cache->flags) {
2268 ret = btrfs_chunk_alloc(trans, alloc_flags,
2269 CHUNK_ALLOC_FORCE);
2270 /*
2271 * ENOSPC is allowed here, we may have enough space
2272 * already allocated at the new raid level to carry on
2273 */
2274 if (ret == -ENOSPC)
2275 ret = 0;
2276 if (ret < 0)
2277 goto out;
2278 }
David Brazdil0f672f62019-12-10 10:32:29 +00002279 }
2280
Olivier Deprez157378f2022-04-04 15:47:50 +02002281 ret = inc_block_group_ro(cache, 0);
2282 if (!do_chunk_alloc || ret == -ETXTBSY)
Olivier Deprez0e641232021-09-23 10:07:05 +02002283 goto unlock_out;
David Brazdil0f672f62019-12-10 10:32:29 +00002284 if (!ret)
2285 goto out;
2286 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2287 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2288 if (ret < 0)
2289 goto out;
2290 ret = inc_block_group_ro(cache, 0);
Olivier Deprez157378f2022-04-04 15:47:50 +02002291 if (ret == -ETXTBSY)
2292 goto unlock_out;
David Brazdil0f672f62019-12-10 10:32:29 +00002293out:
2294 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002295 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
David Brazdil0f672f62019-12-10 10:32:29 +00002296 mutex_lock(&fs_info->chunk_mutex);
2297 check_system_chunk(trans, alloc_flags);
2298 mutex_unlock(&fs_info->chunk_mutex);
2299 }
Olivier Deprez0e641232021-09-23 10:07:05 +02002300unlock_out:
David Brazdil0f672f62019-12-10 10:32:29 +00002301 mutex_unlock(&fs_info->ro_block_group_mutex);
2302
2303 btrfs_end_transaction(trans);
2304 return ret;
2305}
2306
Olivier Deprez157378f2022-04-04 15:47:50 +02002307void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +00002308{
2309 struct btrfs_space_info *sinfo = cache->space_info;
2310 u64 num_bytes;
2311
2312 BUG_ON(!cache->ro);
2313
2314 spin_lock(&sinfo->lock);
2315 spin_lock(&cache->lock);
2316 if (!--cache->ro) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002317 num_bytes = cache->length - cache->reserved -
2318 cache->pinned - cache->bytes_super - cache->used;
David Brazdil0f672f62019-12-10 10:32:29 +00002319 sinfo->bytes_readonly -= num_bytes;
2320 list_del_init(&cache->ro_list);
2321 }
2322 spin_unlock(&cache->lock);
2323 spin_unlock(&sinfo->lock);
2324}
2325
Olivier Deprez157378f2022-04-04 15:47:50 +02002326static int update_block_group_item(struct btrfs_trans_handle *trans,
2327 struct btrfs_path *path,
2328 struct btrfs_block_group *cache)
David Brazdil0f672f62019-12-10 10:32:29 +00002329{
2330 struct btrfs_fs_info *fs_info = trans->fs_info;
2331 int ret;
Olivier Deprez157378f2022-04-04 15:47:50 +02002332 struct btrfs_root *root = fs_info->extent_root;
David Brazdil0f672f62019-12-10 10:32:29 +00002333 unsigned long bi;
2334 struct extent_buffer *leaf;
Olivier Deprez157378f2022-04-04 15:47:50 +02002335 struct btrfs_block_group_item bgi;
2336 struct btrfs_key key;
David Brazdil0f672f62019-12-10 10:32:29 +00002337
Olivier Deprez157378f2022-04-04 15:47:50 +02002338 key.objectid = cache->start;
2339 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2340 key.offset = cache->length;
2341
2342 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
David Brazdil0f672f62019-12-10 10:32:29 +00002343 if (ret) {
2344 if (ret > 0)
2345 ret = -ENOENT;
2346 goto fail;
2347 }
2348
2349 leaf = path->nodes[0];
2350 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
Olivier Deprez157378f2022-04-04 15:47:50 +02002351 btrfs_set_stack_block_group_used(&bgi, cache->used);
2352 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2353 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2354 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
2355 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
David Brazdil0f672f62019-12-10 10:32:29 +00002356 btrfs_mark_buffer_dirty(leaf);
2357fail:
2358 btrfs_release_path(path);
2359 return ret;
2360
2361}
2362
Olivier Deprez157378f2022-04-04 15:47:50 +02002363static int cache_save_setup(struct btrfs_block_group *block_group,
David Brazdil0f672f62019-12-10 10:32:29 +00002364 struct btrfs_trans_handle *trans,
2365 struct btrfs_path *path)
2366{
2367 struct btrfs_fs_info *fs_info = block_group->fs_info;
2368 struct btrfs_root *root = fs_info->tree_root;
2369 struct inode *inode = NULL;
2370 struct extent_changeset *data_reserved = NULL;
2371 u64 alloc_hint = 0;
2372 int dcs = BTRFS_DC_ERROR;
2373 u64 num_pages = 0;
2374 int retries = 0;
2375 int ret = 0;
2376
2377 /*
2378 * If this block group is smaller than 100 megs don't bother caching the
2379 * block group.
2380 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002381 if (block_group->length < (100 * SZ_1M)) {
David Brazdil0f672f62019-12-10 10:32:29 +00002382 spin_lock(&block_group->lock);
2383 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2384 spin_unlock(&block_group->lock);
2385 return 0;
2386 }
2387
Olivier Deprez0e641232021-09-23 10:07:05 +02002388 if (TRANS_ABORTED(trans))
David Brazdil0f672f62019-12-10 10:32:29 +00002389 return 0;
2390again:
2391 inode = lookup_free_space_inode(block_group, path);
2392 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2393 ret = PTR_ERR(inode);
2394 btrfs_release_path(path);
2395 goto out;
2396 }
2397
2398 if (IS_ERR(inode)) {
2399 BUG_ON(retries);
2400 retries++;
2401
2402 if (block_group->ro)
2403 goto out_free;
2404
2405 ret = create_free_space_inode(trans, block_group, path);
2406 if (ret)
2407 goto out_free;
2408 goto again;
2409 }
2410
2411 /*
2412 * We want to set the generation to 0, that way if anything goes wrong
2413 * from here on out we know not to trust this cache when we load up next
2414 * time.
2415 */
2416 BTRFS_I(inode)->generation = 0;
2417 ret = btrfs_update_inode(trans, root, inode);
2418 if (ret) {
2419 /*
2420 * So theoretically we could recover from this, simply set the
2421 * super cache generation to 0 so we know to invalidate the
2422 * cache, but then we'd have to keep track of the block groups
2423 * that fail this way so we know we _have_ to reset this cache
2424 * before the next commit or risk reading stale cache. So to
2425 * limit our exposure to horrible edge cases lets just abort the
2426 * transaction, this only happens in really bad situations
2427 * anyway.
2428 */
2429 btrfs_abort_transaction(trans, ret);
2430 goto out_put;
2431 }
2432 WARN_ON(ret);
2433
2434 /* We've already setup this transaction, go ahead and exit */
2435 if (block_group->cache_generation == trans->transid &&
2436 i_size_read(inode)) {
2437 dcs = BTRFS_DC_SETUP;
2438 goto out_put;
2439 }
2440
2441 if (i_size_read(inode) > 0) {
2442 ret = btrfs_check_trunc_cache_free_space(fs_info,
2443 &fs_info->global_block_rsv);
2444 if (ret)
2445 goto out_put;
2446
2447 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2448 if (ret)
2449 goto out_put;
2450 }
2451
2452 spin_lock(&block_group->lock);
2453 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2454 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2455 /*
2456 * don't bother trying to write stuff out _if_
2457 * a) we're not cached,
2458 * b) we're with nospace_cache mount option,
2459 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2460 */
2461 dcs = BTRFS_DC_WRITTEN;
2462 spin_unlock(&block_group->lock);
2463 goto out_put;
2464 }
2465 spin_unlock(&block_group->lock);
2466
2467 /*
2468 * We hit an ENOSPC when setting up the cache in this transaction, just
2469 * skip doing the setup, we've already cleared the cache so we're safe.
2470 */
2471 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2472 ret = -ENOSPC;
2473 goto out_put;
2474 }
2475
2476 /*
2477 * Try to preallocate enough space based on how big the block group is.
2478 * Keep in mind this has to include any pinned space which could end up
2479 * taking up quite a bit since it's not folded into the other space
2480 * cache.
2481 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002482 num_pages = div_u64(block_group->length, SZ_256M);
David Brazdil0f672f62019-12-10 10:32:29 +00002483 if (!num_pages)
2484 num_pages = 1;
2485
2486 num_pages *= 16;
2487 num_pages *= PAGE_SIZE;
2488
Olivier Deprez157378f2022-04-04 15:47:50 +02002489 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2490 num_pages);
David Brazdil0f672f62019-12-10 10:32:29 +00002491 if (ret)
2492 goto out_put;
2493
2494 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2495 num_pages, num_pages,
2496 &alloc_hint);
2497 /*
2498 * Our cache requires contiguous chunks so that we don't modify a bunch
2499 * of metadata or split extents when writing the cache out, which means
2500 * we can enospc if we are heavily fragmented in addition to just normal
2501 * out of space conditions. So if we hit this just skip setting up any
2502 * other block groups for this transaction, maybe we'll unpin enough
2503 * space the next time around.
2504 */
2505 if (!ret)
2506 dcs = BTRFS_DC_SETUP;
2507 else if (ret == -ENOSPC)
2508 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2509
2510out_put:
2511 iput(inode);
2512out_free:
2513 btrfs_release_path(path);
2514out:
2515 spin_lock(&block_group->lock);
2516 if (!ret && dcs == BTRFS_DC_SETUP)
2517 block_group->cache_generation = trans->transid;
2518 block_group->disk_cache_state = dcs;
2519 spin_unlock(&block_group->lock);
2520
2521 extent_changeset_free(data_reserved);
2522 return ret;
2523}
2524
2525int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2526{
2527 struct btrfs_fs_info *fs_info = trans->fs_info;
Olivier Deprez157378f2022-04-04 15:47:50 +02002528 struct btrfs_block_group *cache, *tmp;
David Brazdil0f672f62019-12-10 10:32:29 +00002529 struct btrfs_transaction *cur_trans = trans->transaction;
2530 struct btrfs_path *path;
2531
2532 if (list_empty(&cur_trans->dirty_bgs) ||
2533 !btrfs_test_opt(fs_info, SPACE_CACHE))
2534 return 0;
2535
2536 path = btrfs_alloc_path();
2537 if (!path)
2538 return -ENOMEM;
2539
2540 /* Could add new block groups, use _safe just in case */
2541 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2542 dirty_list) {
2543 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2544 cache_save_setup(cache, trans, path);
2545 }
2546
2547 btrfs_free_path(path);
2548 return 0;
2549}
2550
2551/*
2552 * Transaction commit does final block group cache writeback during a critical
2553 * section where nothing is allowed to change the FS. This is required in
2554 * order for the cache to actually match the block group, but can introduce a
2555 * lot of latency into the commit.
2556 *
2557 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2558 * There's a chance we'll have to redo some of it if the block group changes
2559 * again during the commit, but it greatly reduces the commit latency by
2560 * getting rid of the easy block groups while we're still allowing others to
2561 * join the commit.
2562 */
2563int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2564{
2565 struct btrfs_fs_info *fs_info = trans->fs_info;
Olivier Deprez157378f2022-04-04 15:47:50 +02002566 struct btrfs_block_group *cache;
David Brazdil0f672f62019-12-10 10:32:29 +00002567 struct btrfs_transaction *cur_trans = trans->transaction;
2568 int ret = 0;
2569 int should_put;
2570 struct btrfs_path *path = NULL;
2571 LIST_HEAD(dirty);
2572 struct list_head *io = &cur_trans->io_bgs;
2573 int num_started = 0;
2574 int loops = 0;
2575
2576 spin_lock(&cur_trans->dirty_bgs_lock);
2577 if (list_empty(&cur_trans->dirty_bgs)) {
2578 spin_unlock(&cur_trans->dirty_bgs_lock);
2579 return 0;
2580 }
2581 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2582 spin_unlock(&cur_trans->dirty_bgs_lock);
2583
2584again:
2585 /* Make sure all the block groups on our dirty list actually exist */
2586 btrfs_create_pending_block_groups(trans);
2587
2588 if (!path) {
2589 path = btrfs_alloc_path();
Olivier Deprez0e641232021-09-23 10:07:05 +02002590 if (!path) {
2591 ret = -ENOMEM;
2592 goto out;
2593 }
David Brazdil0f672f62019-12-10 10:32:29 +00002594 }
2595
2596 /*
2597 * cache_write_mutex is here only to save us from balance or automatic
2598 * removal of empty block groups deleting this block group while we are
2599 * writing out the cache
2600 */
2601 mutex_lock(&trans->transaction->cache_write_mutex);
2602 while (!list_empty(&dirty)) {
2603 bool drop_reserve = true;
2604
Olivier Deprez157378f2022-04-04 15:47:50 +02002605 cache = list_first_entry(&dirty, struct btrfs_block_group,
David Brazdil0f672f62019-12-10 10:32:29 +00002606 dirty_list);
2607 /*
2608 * This can happen if something re-dirties a block group that
2609 * is already under IO. Just wait for it to finish and then do
2610 * it all again
2611 */
2612 if (!list_empty(&cache->io_list)) {
2613 list_del_init(&cache->io_list);
2614 btrfs_wait_cache_io(trans, cache, path);
2615 btrfs_put_block_group(cache);
2616 }
2617
2618
2619 /*
2620 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2621 * it should update the cache_state. Don't delete until after
2622 * we wait.
2623 *
2624 * Since we're not running in the commit critical section
2625 * we need the dirty_bgs_lock to protect from update_block_group
2626 */
2627 spin_lock(&cur_trans->dirty_bgs_lock);
2628 list_del_init(&cache->dirty_list);
2629 spin_unlock(&cur_trans->dirty_bgs_lock);
2630
2631 should_put = 1;
2632
2633 cache_save_setup(cache, trans, path);
2634
2635 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2636 cache->io_ctl.inode = NULL;
2637 ret = btrfs_write_out_cache(trans, cache, path);
2638 if (ret == 0 && cache->io_ctl.inode) {
2639 num_started++;
2640 should_put = 0;
2641
2642 /*
2643 * The cache_write_mutex is protecting the
2644 * io_list, also refer to the definition of
2645 * btrfs_transaction::io_bgs for more details
2646 */
2647 list_add_tail(&cache->io_list, io);
2648 } else {
2649 /*
2650 * If we failed to write the cache, the
2651 * generation will be bad and life goes on
2652 */
2653 ret = 0;
2654 }
2655 }
2656 if (!ret) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002657 ret = update_block_group_item(trans, path, cache);
David Brazdil0f672f62019-12-10 10:32:29 +00002658 /*
2659 * Our block group might still be attached to the list
2660 * of new block groups in the transaction handle of some
2661 * other task (struct btrfs_trans_handle->new_bgs). This
2662 * means its block group item isn't yet in the extent
2663 * tree. If this happens ignore the error, as we will
2664 * try again later in the critical section of the
2665 * transaction commit.
2666 */
2667 if (ret == -ENOENT) {
2668 ret = 0;
2669 spin_lock(&cur_trans->dirty_bgs_lock);
2670 if (list_empty(&cache->dirty_list)) {
2671 list_add_tail(&cache->dirty_list,
2672 &cur_trans->dirty_bgs);
2673 btrfs_get_block_group(cache);
2674 drop_reserve = false;
2675 }
2676 spin_unlock(&cur_trans->dirty_bgs_lock);
2677 } else if (ret) {
2678 btrfs_abort_transaction(trans, ret);
2679 }
2680 }
2681
2682 /* If it's not on the io list, we need to put the block group */
2683 if (should_put)
2684 btrfs_put_block_group(cache);
2685 if (drop_reserve)
2686 btrfs_delayed_refs_rsv_release(fs_info, 1);
David Brazdil0f672f62019-12-10 10:32:29 +00002687 /*
2688 * Avoid blocking other tasks for too long. It might even save
2689 * us from writing caches for block groups that are going to be
2690 * removed.
2691 */
2692 mutex_unlock(&trans->transaction->cache_write_mutex);
Olivier Deprez0e641232021-09-23 10:07:05 +02002693 if (ret)
2694 goto out;
David Brazdil0f672f62019-12-10 10:32:29 +00002695 mutex_lock(&trans->transaction->cache_write_mutex);
2696 }
2697 mutex_unlock(&trans->transaction->cache_write_mutex);
2698
2699 /*
2700 * Go through delayed refs for all the stuff we've just kicked off
2701 * and then loop back (just once)
2702 */
Olivier Deprez0e641232021-09-23 10:07:05 +02002703 if (!ret)
2704 ret = btrfs_run_delayed_refs(trans, 0);
David Brazdil0f672f62019-12-10 10:32:29 +00002705 if (!ret && loops == 0) {
2706 loops++;
2707 spin_lock(&cur_trans->dirty_bgs_lock);
2708 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2709 /*
2710 * dirty_bgs_lock protects us from concurrent block group
2711 * deletes too (not just cache_write_mutex).
2712 */
2713 if (!list_empty(&dirty)) {
2714 spin_unlock(&cur_trans->dirty_bgs_lock);
2715 goto again;
2716 }
2717 spin_unlock(&cur_trans->dirty_bgs_lock);
Olivier Deprez0e641232021-09-23 10:07:05 +02002718 }
2719out:
2720 if (ret < 0) {
2721 spin_lock(&cur_trans->dirty_bgs_lock);
2722 list_splice_init(&dirty, &cur_trans->dirty_bgs);
2723 spin_unlock(&cur_trans->dirty_bgs_lock);
David Brazdil0f672f62019-12-10 10:32:29 +00002724 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2725 }
2726
2727 btrfs_free_path(path);
2728 return ret;
2729}
2730
2731int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2732{
2733 struct btrfs_fs_info *fs_info = trans->fs_info;
Olivier Deprez157378f2022-04-04 15:47:50 +02002734 struct btrfs_block_group *cache;
David Brazdil0f672f62019-12-10 10:32:29 +00002735 struct btrfs_transaction *cur_trans = trans->transaction;
2736 int ret = 0;
2737 int should_put;
2738 struct btrfs_path *path;
2739 struct list_head *io = &cur_trans->io_bgs;
2740 int num_started = 0;
2741
2742 path = btrfs_alloc_path();
2743 if (!path)
2744 return -ENOMEM;
2745
2746 /*
2747 * Even though we are in the critical section of the transaction commit,
2748 * we can still have concurrent tasks adding elements to this
2749 * transaction's list of dirty block groups. These tasks correspond to
2750 * endio free space workers started when writeback finishes for a
2751 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2752 * allocate new block groups as a result of COWing nodes of the root
2753 * tree when updating the free space inode. The writeback for the space
2754 * caches is triggered by an earlier call to
2755 * btrfs_start_dirty_block_groups() and iterations of the following
2756 * loop.
2757 * Also we want to do the cache_save_setup first and then run the
2758 * delayed refs to make sure we have the best chance at doing this all
2759 * in one shot.
2760 */
2761 spin_lock(&cur_trans->dirty_bgs_lock);
2762 while (!list_empty(&cur_trans->dirty_bgs)) {
2763 cache = list_first_entry(&cur_trans->dirty_bgs,
Olivier Deprez157378f2022-04-04 15:47:50 +02002764 struct btrfs_block_group,
David Brazdil0f672f62019-12-10 10:32:29 +00002765 dirty_list);
2766
2767 /*
2768 * This can happen if cache_save_setup re-dirties a block group
2769 * that is already under IO. Just wait for it to finish and
2770 * then do it all again
2771 */
2772 if (!list_empty(&cache->io_list)) {
2773 spin_unlock(&cur_trans->dirty_bgs_lock);
2774 list_del_init(&cache->io_list);
2775 btrfs_wait_cache_io(trans, cache, path);
2776 btrfs_put_block_group(cache);
2777 spin_lock(&cur_trans->dirty_bgs_lock);
2778 }
2779
2780 /*
2781 * Don't remove from the dirty list until after we've waited on
2782 * any pending IO
2783 */
2784 list_del_init(&cache->dirty_list);
2785 spin_unlock(&cur_trans->dirty_bgs_lock);
2786 should_put = 1;
2787
2788 cache_save_setup(cache, trans, path);
2789
2790 if (!ret)
2791 ret = btrfs_run_delayed_refs(trans,
2792 (unsigned long) -1);
2793
2794 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2795 cache->io_ctl.inode = NULL;
2796 ret = btrfs_write_out_cache(trans, cache, path);
2797 if (ret == 0 && cache->io_ctl.inode) {
2798 num_started++;
2799 should_put = 0;
2800 list_add_tail(&cache->io_list, io);
2801 } else {
2802 /*
2803 * If we failed to write the cache, the
2804 * generation will be bad and life goes on
2805 */
2806 ret = 0;
2807 }
2808 }
2809 if (!ret) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002810 ret = update_block_group_item(trans, path, cache);
David Brazdil0f672f62019-12-10 10:32:29 +00002811 /*
2812 * One of the free space endio workers might have
2813 * created a new block group while updating a free space
2814 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2815 * and hasn't released its transaction handle yet, in
2816 * which case the new block group is still attached to
2817 * its transaction handle and its creation has not
2818 * finished yet (no block group item in the extent tree
2819 * yet, etc). If this is the case, wait for all free
2820 * space endio workers to finish and retry. This is a
Olivier Deprez0e641232021-09-23 10:07:05 +02002821 * very rare case so no need for a more efficient and
David Brazdil0f672f62019-12-10 10:32:29 +00002822 * complex approach.
2823 */
2824 if (ret == -ENOENT) {
2825 wait_event(cur_trans->writer_wait,
2826 atomic_read(&cur_trans->num_writers) == 1);
Olivier Deprez157378f2022-04-04 15:47:50 +02002827 ret = update_block_group_item(trans, path, cache);
David Brazdil0f672f62019-12-10 10:32:29 +00002828 }
2829 if (ret)
2830 btrfs_abort_transaction(trans, ret);
2831 }
2832
2833 /* If its not on the io list, we need to put the block group */
2834 if (should_put)
2835 btrfs_put_block_group(cache);
2836 btrfs_delayed_refs_rsv_release(fs_info, 1);
2837 spin_lock(&cur_trans->dirty_bgs_lock);
2838 }
2839 spin_unlock(&cur_trans->dirty_bgs_lock);
2840
2841 /*
2842 * Refer to the definition of io_bgs member for details why it's safe
2843 * to use it without any locking
2844 */
2845 while (!list_empty(io)) {
Olivier Deprez157378f2022-04-04 15:47:50 +02002846 cache = list_first_entry(io, struct btrfs_block_group,
David Brazdil0f672f62019-12-10 10:32:29 +00002847 io_list);
2848 list_del_init(&cache->io_list);
2849 btrfs_wait_cache_io(trans, cache, path);
2850 btrfs_put_block_group(cache);
2851 }
2852
2853 btrfs_free_path(path);
2854 return ret;
2855}
2856
2857int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2858 u64 bytenr, u64 num_bytes, int alloc)
2859{
2860 struct btrfs_fs_info *info = trans->fs_info;
Olivier Deprez157378f2022-04-04 15:47:50 +02002861 struct btrfs_block_group *cache = NULL;
David Brazdil0f672f62019-12-10 10:32:29 +00002862 u64 total = num_bytes;
2863 u64 old_val;
2864 u64 byte_in_group;
2865 int factor;
2866 int ret = 0;
2867
2868 /* Block accounting for super block */
2869 spin_lock(&info->delalloc_root_lock);
2870 old_val = btrfs_super_bytes_used(info->super_copy);
2871 if (alloc)
2872 old_val += num_bytes;
2873 else
2874 old_val -= num_bytes;
2875 btrfs_set_super_bytes_used(info->super_copy, old_val);
2876 spin_unlock(&info->delalloc_root_lock);
2877
2878 while (total) {
2879 cache = btrfs_lookup_block_group(info, bytenr);
2880 if (!cache) {
2881 ret = -ENOENT;
2882 break;
2883 }
2884 factor = btrfs_bg_type_to_factor(cache->flags);
2885
2886 /*
2887 * If this block group has free space cache written out, we
2888 * need to make sure to load it if we are removing space. This
2889 * is because we need the unpinning stage to actually add the
2890 * space back to the block group, otherwise we will leak space.
2891 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002892 if (!alloc && !btrfs_block_group_done(cache))
David Brazdil0f672f62019-12-10 10:32:29 +00002893 btrfs_cache_block_group(cache, 1);
2894
Olivier Deprez157378f2022-04-04 15:47:50 +02002895 byte_in_group = bytenr - cache->start;
2896 WARN_ON(byte_in_group > cache->length);
David Brazdil0f672f62019-12-10 10:32:29 +00002897
2898 spin_lock(&cache->space_info->lock);
2899 spin_lock(&cache->lock);
2900
2901 if (btrfs_test_opt(info, SPACE_CACHE) &&
2902 cache->disk_cache_state < BTRFS_DC_CLEAR)
2903 cache->disk_cache_state = BTRFS_DC_CLEAR;
2904
Olivier Deprez157378f2022-04-04 15:47:50 +02002905 old_val = cache->used;
2906 num_bytes = min(total, cache->length - byte_in_group);
David Brazdil0f672f62019-12-10 10:32:29 +00002907 if (alloc) {
2908 old_val += num_bytes;
Olivier Deprez157378f2022-04-04 15:47:50 +02002909 cache->used = old_val;
David Brazdil0f672f62019-12-10 10:32:29 +00002910 cache->reserved -= num_bytes;
2911 cache->space_info->bytes_reserved -= num_bytes;
2912 cache->space_info->bytes_used += num_bytes;
2913 cache->space_info->disk_used += num_bytes * factor;
2914 spin_unlock(&cache->lock);
2915 spin_unlock(&cache->space_info->lock);
2916 } else {
2917 old_val -= num_bytes;
Olivier Deprez157378f2022-04-04 15:47:50 +02002918 cache->used = old_val;
David Brazdil0f672f62019-12-10 10:32:29 +00002919 cache->pinned += num_bytes;
2920 btrfs_space_info_update_bytes_pinned(info,
2921 cache->space_info, num_bytes);
2922 cache->space_info->bytes_used -= num_bytes;
2923 cache->space_info->disk_used -= num_bytes * factor;
2924 spin_unlock(&cache->lock);
2925 spin_unlock(&cache->space_info->lock);
2926
Olivier Deprez157378f2022-04-04 15:47:50 +02002927 __btrfs_mod_total_bytes_pinned(cache->space_info,
2928 num_bytes);
2929 set_extent_dirty(&trans->transaction->pinned_extents,
David Brazdil0f672f62019-12-10 10:32:29 +00002930 bytenr, bytenr + num_bytes - 1,
2931 GFP_NOFS | __GFP_NOFAIL);
2932 }
2933
2934 spin_lock(&trans->transaction->dirty_bgs_lock);
2935 if (list_empty(&cache->dirty_list)) {
2936 list_add_tail(&cache->dirty_list,
2937 &trans->transaction->dirty_bgs);
2938 trans->delayed_ref_updates++;
2939 btrfs_get_block_group(cache);
2940 }
2941 spin_unlock(&trans->transaction->dirty_bgs_lock);
2942
2943 /*
2944 * No longer have used bytes in this block group, queue it for
2945 * deletion. We do this after adding the block group to the
2946 * dirty list to avoid races between cleaner kthread and space
2947 * cache writeout.
2948 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002949 if (!alloc && old_val == 0) {
2950 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2951 btrfs_mark_bg_unused(cache);
2952 }
David Brazdil0f672f62019-12-10 10:32:29 +00002953
2954 btrfs_put_block_group(cache);
2955 total -= num_bytes;
2956 bytenr += num_bytes;
2957 }
2958
2959 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2960 btrfs_update_delayed_refs_rsv(trans);
2961 return ret;
2962}
2963
2964/**
2965 * btrfs_add_reserved_bytes - update the block_group and space info counters
2966 * @cache: The cache we are manipulating
2967 * @ram_bytes: The number of bytes of file content, and will be same to
2968 * @num_bytes except for the compress path.
2969 * @num_bytes: The number of bytes in question
2970 * @delalloc: The blocks are allocated for the delalloc write
2971 *
2972 * This is called by the allocator when it reserves space. If this is a
2973 * reservation and the block group has become read only we cannot make the
2974 * reservation and return -EAGAIN, otherwise this function always succeeds.
2975 */
Olivier Deprez157378f2022-04-04 15:47:50 +02002976int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
David Brazdil0f672f62019-12-10 10:32:29 +00002977 u64 ram_bytes, u64 num_bytes, int delalloc)
2978{
2979 struct btrfs_space_info *space_info = cache->space_info;
2980 int ret = 0;
2981
2982 spin_lock(&space_info->lock);
2983 spin_lock(&cache->lock);
2984 if (cache->ro) {
2985 ret = -EAGAIN;
2986 } else {
2987 cache->reserved += num_bytes;
2988 space_info->bytes_reserved += num_bytes;
2989 trace_btrfs_space_reservation(cache->fs_info, "space_info",
2990 space_info->flags, num_bytes, 1);
2991 btrfs_space_info_update_bytes_may_use(cache->fs_info,
2992 space_info, -ram_bytes);
2993 if (delalloc)
2994 cache->delalloc_bytes += num_bytes;
Olivier Deprez157378f2022-04-04 15:47:50 +02002995
2996 /*
2997 * Compression can use less space than we reserved, so wake
2998 * tickets if that happens
2999 */
3000 if (num_bytes < ram_bytes)
3001 btrfs_try_granting_tickets(cache->fs_info, space_info);
David Brazdil0f672f62019-12-10 10:32:29 +00003002 }
3003 spin_unlock(&cache->lock);
3004 spin_unlock(&space_info->lock);
3005 return ret;
3006}
3007
3008/**
3009 * btrfs_free_reserved_bytes - update the block_group and space info counters
3010 * @cache: The cache we are manipulating
3011 * @num_bytes: The number of bytes in question
3012 * @delalloc: The blocks are allocated for the delalloc write
3013 *
3014 * This is called by somebody who is freeing space that was never actually used
3015 * on disk. For example if you reserve some space for a new leaf in transaction
3016 * A and before transaction A commits you free that leaf, you call this with
3017 * reserve set to 0 in order to clear the reservation.
3018 */
Olivier Deprez157378f2022-04-04 15:47:50 +02003019void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
David Brazdil0f672f62019-12-10 10:32:29 +00003020 u64 num_bytes, int delalloc)
3021{
3022 struct btrfs_space_info *space_info = cache->space_info;
3023
3024 spin_lock(&space_info->lock);
3025 spin_lock(&cache->lock);
3026 if (cache->ro)
3027 space_info->bytes_readonly += num_bytes;
3028 cache->reserved -= num_bytes;
3029 space_info->bytes_reserved -= num_bytes;
3030 space_info->max_extent_size = 0;
3031
3032 if (delalloc)
3033 cache->delalloc_bytes -= num_bytes;
3034 spin_unlock(&cache->lock);
Olivier Deprez157378f2022-04-04 15:47:50 +02003035
3036 btrfs_try_granting_tickets(cache->fs_info, space_info);
David Brazdil0f672f62019-12-10 10:32:29 +00003037 spin_unlock(&space_info->lock);
3038}
3039
3040static void force_metadata_allocation(struct btrfs_fs_info *info)
3041{
3042 struct list_head *head = &info->space_info;
3043 struct btrfs_space_info *found;
3044
Olivier Deprez157378f2022-04-04 15:47:50 +02003045 list_for_each_entry(found, head, list) {
David Brazdil0f672f62019-12-10 10:32:29 +00003046 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3047 found->force_alloc = CHUNK_ALLOC_FORCE;
3048 }
David Brazdil0f672f62019-12-10 10:32:29 +00003049}
3050
3051static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3052 struct btrfs_space_info *sinfo, int force)
3053{
3054 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3055 u64 thresh;
3056
3057 if (force == CHUNK_ALLOC_FORCE)
3058 return 1;
3059
3060 /*
3061 * in limited mode, we want to have some free space up to
3062 * about 1% of the FS size.
3063 */
3064 if (force == CHUNK_ALLOC_LIMITED) {
3065 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3066 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3067
3068 if (sinfo->total_bytes - bytes_used < thresh)
3069 return 1;
3070 }
3071
3072 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3073 return 0;
3074 return 1;
3075}
3076
3077int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3078{
3079 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3080
3081 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3082}
3083
3084/*
3085 * If force is CHUNK_ALLOC_FORCE:
3086 * - return 1 if it successfully allocates a chunk,
3087 * - return errors including -ENOSPC otherwise.
3088 * If force is NOT CHUNK_ALLOC_FORCE:
3089 * - return 0 if it doesn't need to allocate a new chunk,
3090 * - return 1 if it successfully allocates a chunk,
3091 * - return errors including -ENOSPC otherwise.
3092 */
3093int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3094 enum btrfs_chunk_alloc_enum force)
3095{
3096 struct btrfs_fs_info *fs_info = trans->fs_info;
3097 struct btrfs_space_info *space_info;
3098 bool wait_for_alloc = false;
3099 bool should_alloc = false;
3100 int ret = 0;
3101
3102 /* Don't re-enter if we're already allocating a chunk */
3103 if (trans->allocating_chunk)
3104 return -ENOSPC;
3105
3106 space_info = btrfs_find_space_info(fs_info, flags);
3107 ASSERT(space_info);
3108
3109 do {
3110 spin_lock(&space_info->lock);
3111 if (force < space_info->force_alloc)
3112 force = space_info->force_alloc;
3113 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3114 if (space_info->full) {
3115 /* No more free physical space */
3116 if (should_alloc)
3117 ret = -ENOSPC;
3118 else
3119 ret = 0;
3120 spin_unlock(&space_info->lock);
3121 return ret;
3122 } else if (!should_alloc) {
3123 spin_unlock(&space_info->lock);
3124 return 0;
3125 } else if (space_info->chunk_alloc) {
3126 /*
3127 * Someone is already allocating, so we need to block
3128 * until this someone is finished and then loop to
3129 * recheck if we should continue with our allocation
3130 * attempt.
3131 */
3132 wait_for_alloc = true;
3133 spin_unlock(&space_info->lock);
3134 mutex_lock(&fs_info->chunk_mutex);
3135 mutex_unlock(&fs_info->chunk_mutex);
3136 } else {
3137 /* Proceed with allocation */
3138 space_info->chunk_alloc = 1;
3139 wait_for_alloc = false;
3140 spin_unlock(&space_info->lock);
3141 }
3142
3143 cond_resched();
3144 } while (wait_for_alloc);
3145
3146 mutex_lock(&fs_info->chunk_mutex);
3147 trans->allocating_chunk = true;
3148
3149 /*
3150 * If we have mixed data/metadata chunks we want to make sure we keep
3151 * allocating mixed chunks instead of individual chunks.
3152 */
3153 if (btrfs_mixed_space_info(space_info))
3154 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3155
3156 /*
3157 * if we're doing a data chunk, go ahead and make sure that
3158 * we keep a reasonable number of metadata chunks allocated in the
3159 * FS as well.
3160 */
3161 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3162 fs_info->data_chunk_allocations++;
3163 if (!(fs_info->data_chunk_allocations %
3164 fs_info->metadata_ratio))
3165 force_metadata_allocation(fs_info);
3166 }
3167
3168 /*
3169 * Check if we have enough space in SYSTEM chunk because we may need
3170 * to update devices.
3171 */
3172 check_system_chunk(trans, flags);
3173
3174 ret = btrfs_alloc_chunk(trans, flags);
3175 trans->allocating_chunk = false;
3176
3177 spin_lock(&space_info->lock);
3178 if (ret < 0) {
3179 if (ret == -ENOSPC)
3180 space_info->full = 1;
3181 else
3182 goto out;
3183 } else {
3184 ret = 1;
3185 space_info->max_extent_size = 0;
3186 }
3187
3188 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3189out:
3190 space_info->chunk_alloc = 0;
3191 spin_unlock(&space_info->lock);
3192 mutex_unlock(&fs_info->chunk_mutex);
3193 /*
3194 * When we allocate a new chunk we reserve space in the chunk block
3195 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3196 * add new nodes/leafs to it if we end up needing to do it when
3197 * inserting the chunk item and updating device items as part of the
3198 * second phase of chunk allocation, performed by
3199 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3200 * large number of new block groups to create in our transaction
3201 * handle's new_bgs list to avoid exhausting the chunk block reserve
3202 * in extreme cases - like having a single transaction create many new
3203 * block groups when starting to write out the free space caches of all
3204 * the block groups that were made dirty during the lifetime of the
3205 * transaction.
3206 */
3207 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3208 btrfs_create_pending_block_groups(trans);
3209
3210 return ret;
3211}
3212
3213static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3214{
3215 u64 num_dev;
3216
3217 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3218 if (!num_dev)
3219 num_dev = fs_info->fs_devices->rw_devices;
3220
3221 return num_dev;
3222}
3223
3224/*
Olivier Deprez157378f2022-04-04 15:47:50 +02003225 * Reserve space in the system space for allocating or removing a chunk
David Brazdil0f672f62019-12-10 10:32:29 +00003226 */
3227void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3228{
3229 struct btrfs_fs_info *fs_info = trans->fs_info;
3230 struct btrfs_space_info *info;
3231 u64 left;
3232 u64 thresh;
3233 int ret = 0;
3234 u64 num_devs;
3235
3236 /*
3237 * Needed because we can end up allocating a system chunk and for an
3238 * atomic and race free space reservation in the chunk block reserve.
3239 */
3240 lockdep_assert_held(&fs_info->chunk_mutex);
3241
3242 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3243 spin_lock(&info->lock);
3244 left = info->total_bytes - btrfs_space_info_used(info, true);
3245 spin_unlock(&info->lock);
3246
3247 num_devs = get_profile_num_devs(fs_info, type);
3248
3249 /* num_devs device items to update and 1 chunk item to add or remove */
3250 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3251 btrfs_calc_insert_metadata_size(fs_info, 1);
3252
3253 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3254 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3255 left, thresh, type);
3256 btrfs_dump_space_info(fs_info, info, 0, 0);
3257 }
3258
3259 if (left < thresh) {
3260 u64 flags = btrfs_system_alloc_profile(fs_info);
3261
3262 /*
3263 * Ignore failure to create system chunk. We might end up not
3264 * needing it, as we might not need to COW all nodes/leafs from
3265 * the paths we visit in the chunk tree (they were already COWed
3266 * or created in the current transaction for example).
3267 */
3268 ret = btrfs_alloc_chunk(trans, flags);
3269 }
3270
3271 if (!ret) {
3272 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3273 &fs_info->chunk_block_rsv,
3274 thresh, BTRFS_RESERVE_NO_FLUSH);
3275 if (!ret)
3276 trans->chunk_bytes_reserved += thresh;
3277 }
3278}
3279
3280void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3281{
Olivier Deprez157378f2022-04-04 15:47:50 +02003282 struct btrfs_block_group *block_group;
David Brazdil0f672f62019-12-10 10:32:29 +00003283 u64 last = 0;
3284
3285 while (1) {
3286 struct inode *inode;
3287
3288 block_group = btrfs_lookup_first_block_group(info, last);
3289 while (block_group) {
3290 btrfs_wait_block_group_cache_done(block_group);
3291 spin_lock(&block_group->lock);
3292 if (block_group->iref)
3293 break;
3294 spin_unlock(&block_group->lock);
3295 block_group = btrfs_next_block_group(block_group);
3296 }
3297 if (!block_group) {
3298 if (last == 0)
3299 break;
3300 last = 0;
3301 continue;
3302 }
3303
3304 inode = block_group->inode;
3305 block_group->iref = 0;
3306 block_group->inode = NULL;
3307 spin_unlock(&block_group->lock);
3308 ASSERT(block_group->io_ctl.inode == NULL);
3309 iput(inode);
Olivier Deprez157378f2022-04-04 15:47:50 +02003310 last = block_group->start + block_group->length;
David Brazdil0f672f62019-12-10 10:32:29 +00003311 btrfs_put_block_group(block_group);
3312 }
3313}
3314
3315/*
3316 * Must be called only after stopping all workers, since we could have block
3317 * group caching kthreads running, and therefore they could race with us if we
3318 * freed the block groups before stopping them.
3319 */
3320int btrfs_free_block_groups(struct btrfs_fs_info *info)
3321{
Olivier Deprez157378f2022-04-04 15:47:50 +02003322 struct btrfs_block_group *block_group;
David Brazdil0f672f62019-12-10 10:32:29 +00003323 struct btrfs_space_info *space_info;
3324 struct btrfs_caching_control *caching_ctl;
3325 struct rb_node *n;
3326
3327 down_write(&info->commit_root_sem);
3328 while (!list_empty(&info->caching_block_groups)) {
3329 caching_ctl = list_entry(info->caching_block_groups.next,
3330 struct btrfs_caching_control, list);
3331 list_del(&caching_ctl->list);
3332 btrfs_put_caching_control(caching_ctl);
3333 }
3334 up_write(&info->commit_root_sem);
3335
3336 spin_lock(&info->unused_bgs_lock);
3337 while (!list_empty(&info->unused_bgs)) {
3338 block_group = list_first_entry(&info->unused_bgs,
Olivier Deprez157378f2022-04-04 15:47:50 +02003339 struct btrfs_block_group,
David Brazdil0f672f62019-12-10 10:32:29 +00003340 bg_list);
3341 list_del_init(&block_group->bg_list);
3342 btrfs_put_block_group(block_group);
3343 }
3344 spin_unlock(&info->unused_bgs_lock);
3345
3346 spin_lock(&info->block_group_cache_lock);
3347 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
Olivier Deprez157378f2022-04-04 15:47:50 +02003348 block_group = rb_entry(n, struct btrfs_block_group,
David Brazdil0f672f62019-12-10 10:32:29 +00003349 cache_node);
3350 rb_erase(&block_group->cache_node,
3351 &info->block_group_cache_tree);
3352 RB_CLEAR_NODE(&block_group->cache_node);
3353 spin_unlock(&info->block_group_cache_lock);
3354
3355 down_write(&block_group->space_info->groups_sem);
3356 list_del(&block_group->list);
3357 up_write(&block_group->space_info->groups_sem);
3358
3359 /*
3360 * We haven't cached this block group, which means we could
3361 * possibly have excluded extents on this block group.
3362 */
3363 if (block_group->cached == BTRFS_CACHE_NO ||
3364 block_group->cached == BTRFS_CACHE_ERROR)
3365 btrfs_free_excluded_extents(block_group);
3366
3367 btrfs_remove_free_space_cache(block_group);
3368 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3369 ASSERT(list_empty(&block_group->dirty_list));
3370 ASSERT(list_empty(&block_group->io_list));
3371 ASSERT(list_empty(&block_group->bg_list));
Olivier Deprez157378f2022-04-04 15:47:50 +02003372 ASSERT(refcount_read(&block_group->refs) == 1);
3373 ASSERT(block_group->swap_extents == 0);
David Brazdil0f672f62019-12-10 10:32:29 +00003374 btrfs_put_block_group(block_group);
3375
3376 spin_lock(&info->block_group_cache_lock);
3377 }
3378 spin_unlock(&info->block_group_cache_lock);
3379
David Brazdil0f672f62019-12-10 10:32:29 +00003380 btrfs_release_global_block_rsv(info);
3381
3382 while (!list_empty(&info->space_info)) {
3383 space_info = list_entry(info->space_info.next,
3384 struct btrfs_space_info,
3385 list);
3386
3387 /*
3388 * Do not hide this behind enospc_debug, this is actually
3389 * important and indicates a real bug if this happens.
3390 */
3391 if (WARN_ON(space_info->bytes_pinned > 0 ||
3392 space_info->bytes_reserved > 0 ||
3393 space_info->bytes_may_use > 0))
3394 btrfs_dump_space_info(info, space_info, 0, 0);
Olivier Deprez157378f2022-04-04 15:47:50 +02003395 WARN_ON(space_info->reclaim_size > 0);
David Brazdil0f672f62019-12-10 10:32:29 +00003396 list_del(&space_info->list);
3397 btrfs_sysfs_remove_space_info(space_info);
3398 }
3399 return 0;
3400}
Olivier Deprez157378f2022-04-04 15:47:50 +02003401
3402void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3403{
3404 atomic_inc(&cache->frozen);
3405}
3406
3407void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3408{
3409 struct btrfs_fs_info *fs_info = block_group->fs_info;
3410 struct extent_map_tree *em_tree;
3411 struct extent_map *em;
3412 bool cleanup;
3413
3414 spin_lock(&block_group->lock);
3415 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3416 block_group->removed);
3417 spin_unlock(&block_group->lock);
3418
3419 if (cleanup) {
3420 em_tree = &fs_info->mapping_tree;
3421 write_lock(&em_tree->lock);
3422 em = lookup_extent_mapping(em_tree, block_group->start,
3423 1);
3424 BUG_ON(!em); /* logic error, can't happen */
3425 remove_extent_mapping(em_tree, em);
3426 write_unlock(&em_tree->lock);
3427
3428 /* once for us and once for the tree */
3429 free_extent_map(em);
3430 free_extent_map(em);
3431
3432 /*
3433 * We may have left one free space entry and other possible
3434 * tasks trimming this block group have left 1 entry each one.
3435 * Free them if any.
3436 */
3437 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
3438 }
3439}
3440
3441bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
3442{
3443 bool ret = true;
3444
3445 spin_lock(&bg->lock);
3446 if (bg->ro)
3447 ret = false;
3448 else
3449 bg->swap_extents++;
3450 spin_unlock(&bg->lock);
3451
3452 return ret;
3453}
3454
3455void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
3456{
3457 spin_lock(&bg->lock);
3458 ASSERT(!bg->ro);
3459 ASSERT(bg->swap_extents >= amount);
3460 bg->swap_extents -= amount;
3461 spin_unlock(&bg->lock);
3462}