blob: c42b6528552ffb50171fabdc42152f7d92f2f1c0 [file] [log] [blame]
Josef Bacik2e405ad2019-06-20 15:37:45 -04001// SPDX-License-Identifier: GPL-2.0
2
David Sterba784352f2019-08-21 18:54:28 +02003#include "misc.h"
Josef Bacik2e405ad2019-06-20 15:37:45 -04004#include "ctree.h"
5#include "block-group.h"
Josef Bacik3eeb3222019-06-20 15:37:47 -04006#include "space-info.h"
Josef Bacik9f212462019-08-06 16:43:19 +02007#include "disk-io.h"
8#include "free-space-cache.h"
9#include "free-space-tree.h"
Josef Bacike3e05202019-06-20 15:37:55 -040010#include "volumes.h"
11#include "transaction.h"
12#include "ref-verify.h"
Josef Bacik4358d9632019-06-20 15:37:57 -040013#include "sysfs.h"
14#include "tree-log.h"
Josef Bacik77745c02019-06-20 15:38:00 -040015#include "delalloc-space.h"
Dennis Zhoub0643e52019-12-13 16:22:14 -080016#include "discard.h"
Nikolay Borisov96a14332019-12-10 19:57:51 +020017#include "raid56.h"
Naohiro Aota08e11a32021-02-04 19:21:50 +090018#include "zoned.h"
Josef Bacik2e405ad2019-06-20 15:37:45 -040019
Josef Bacik878d7b62019-06-20 15:38:05 -040020/*
21 * Return target flags in extended format or 0 if restripe for this chunk_type
22 * is not in progress
23 *
24 * Should be called with balance_lock held
25 */
Josef Bacike11c0402019-06-20 15:38:07 -040026static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
Josef Bacik878d7b62019-06-20 15:38:05 -040027{
28 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
29 u64 target = 0;
30
31 if (!bctl)
32 return 0;
33
34 if (flags & BTRFS_BLOCK_GROUP_DATA &&
35 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
36 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
37 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
38 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
39 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
40 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
41 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
42 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
43 }
44
45 return target;
46}
47
48/*
49 * @flags: available profiles in extended format (see ctree.h)
50 *
51 * Return reduced profile in chunk format. If profile changing is in progress
52 * (either running or paused) picks the target profile (if it's already
53 * available), otherwise falls back to plain reducing.
54 */
55static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
56{
57 u64 num_devices = fs_info->fs_devices->rw_devices;
58 u64 target;
59 u64 raid_type;
60 u64 allowed = 0;
61
62 /*
63 * See if restripe for this chunk_type is in progress, if so try to
64 * reduce to the target profile
65 */
66 spin_lock(&fs_info->balance_lock);
Josef Bacike11c0402019-06-20 15:38:07 -040067 target = get_restripe_target(fs_info, flags);
Josef Bacik878d7b62019-06-20 15:38:05 -040068 if (target) {
Josef Bacik162e0a12020-07-21 10:48:46 -040069 spin_unlock(&fs_info->balance_lock);
70 return extended_to_chunk(target);
Josef Bacik878d7b62019-06-20 15:38:05 -040071 }
72 spin_unlock(&fs_info->balance_lock);
73
74 /* First, mask out the RAID levels which aren't possible */
75 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
76 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
77 allowed |= btrfs_raid_array[raid_type].bg_flag;
78 }
79 allowed &= flags;
80
81 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
82 allowed = BTRFS_BLOCK_GROUP_RAID6;
83 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
84 allowed = BTRFS_BLOCK_GROUP_RAID5;
85 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
86 allowed = BTRFS_BLOCK_GROUP_RAID10;
87 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
88 allowed = BTRFS_BLOCK_GROUP_RAID1;
89 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
90 allowed = BTRFS_BLOCK_GROUP_RAID0;
91
92 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
93
94 return extended_to_chunk(flags | allowed);
95}
96
Johannes Thumshirnef0a82d2020-01-02 17:14:57 +010097u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
Josef Bacik878d7b62019-06-20 15:38:05 -040098{
99 unsigned seq;
100 u64 flags;
101
102 do {
103 flags = orig_flags;
104 seq = read_seqbegin(&fs_info->profiles_lock);
105
106 if (flags & BTRFS_BLOCK_GROUP_DATA)
107 flags |= fs_info->avail_data_alloc_bits;
108 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
109 flags |= fs_info->avail_system_alloc_bits;
110 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
111 flags |= fs_info->avail_metadata_alloc_bits;
112 } while (read_seqretry(&fs_info->profiles_lock, seq));
113
114 return btrfs_reduce_alloc_profile(fs_info, flags);
115}
116
David Sterba32da53862019-10-29 19:20:18 +0100117void btrfs_get_block_group(struct btrfs_block_group *cache)
Josef Bacik3cad1282019-06-20 15:37:46 -0400118{
Josef Bacik48aaeeb2020-07-06 09:14:11 -0400119 refcount_inc(&cache->refs);
Josef Bacik3cad1282019-06-20 15:37:46 -0400120}
121
David Sterba32da53862019-10-29 19:20:18 +0100122void btrfs_put_block_group(struct btrfs_block_group *cache)
Josef Bacik3cad1282019-06-20 15:37:46 -0400123{
Josef Bacik48aaeeb2020-07-06 09:14:11 -0400124 if (refcount_dec_and_test(&cache->refs)) {
Josef Bacik3cad1282019-06-20 15:37:46 -0400125 WARN_ON(cache->pinned > 0);
126 WARN_ON(cache->reserved > 0);
127
128 /*
Dennis Zhoub0643e52019-12-13 16:22:14 -0800129 * A block_group shouldn't be on the discard_list anymore.
130 * Remove the block_group from the discard_list to prevent us
131 * from causing a panic due to NULL pointer dereference.
132 */
133 if (WARN_ON(!list_empty(&cache->discard_list)))
134 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
135 cache);
136
137 /*
Josef Bacik3cad1282019-06-20 15:37:46 -0400138 * If not empty, someone is still holding mutex of
139 * full_stripe_lock, which can only be released by caller.
140 * And it will definitely cause use-after-free when caller
141 * tries to release full stripe lock.
142 *
143 * No better way to resolve, but only to warn.
144 */
145 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
146 kfree(cache->free_space_ctl);
147 kfree(cache);
148 }
149}
150
Josef Bacik2e405ad2019-06-20 15:37:45 -0400151/*
Josef Bacik4358d9632019-06-20 15:37:57 -0400152 * This adds the block group to the fs_info rb tree for the block group cache
153 */
154static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
David Sterba32da53862019-10-29 19:20:18 +0100155 struct btrfs_block_group *block_group)
Josef Bacik4358d9632019-06-20 15:37:57 -0400156{
157 struct rb_node **p;
158 struct rb_node *parent = NULL;
David Sterba32da53862019-10-29 19:20:18 +0100159 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -0400160
Qu Wenruo9afc6642020-05-05 07:58:20 +0800161 ASSERT(block_group->length != 0);
162
Josef Bacik4358d9632019-06-20 15:37:57 -0400163 spin_lock(&info->block_group_cache_lock);
164 p = &info->block_group_cache_tree.rb_node;
165
166 while (*p) {
167 parent = *p;
David Sterba32da53862019-10-29 19:20:18 +0100168 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
David Sterbab3470b52019-10-23 18:48:22 +0200169 if (block_group->start < cache->start) {
Josef Bacik4358d9632019-06-20 15:37:57 -0400170 p = &(*p)->rb_left;
David Sterbab3470b52019-10-23 18:48:22 +0200171 } else if (block_group->start > cache->start) {
Josef Bacik4358d9632019-06-20 15:37:57 -0400172 p = &(*p)->rb_right;
173 } else {
174 spin_unlock(&info->block_group_cache_lock);
175 return -EEXIST;
176 }
177 }
178
179 rb_link_node(&block_group->cache_node, parent, p);
180 rb_insert_color(&block_group->cache_node,
181 &info->block_group_cache_tree);
182
David Sterbab3470b52019-10-23 18:48:22 +0200183 if (info->first_logical_byte > block_group->start)
184 info->first_logical_byte = block_group->start;
Josef Bacik4358d9632019-06-20 15:37:57 -0400185
186 spin_unlock(&info->block_group_cache_lock);
187
188 return 0;
189}
190
191/*
Josef Bacik2e405ad2019-06-20 15:37:45 -0400192 * This will return the block group at or after bytenr if contains is 0, else
193 * it will return the block group that contains the bytenr
194 */
David Sterba32da53862019-10-29 19:20:18 +0100195static struct btrfs_block_group *block_group_cache_tree_search(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400196 struct btrfs_fs_info *info, u64 bytenr, int contains)
197{
David Sterba32da53862019-10-29 19:20:18 +0100198 struct btrfs_block_group *cache, *ret = NULL;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400199 struct rb_node *n;
200 u64 end, start;
201
202 spin_lock(&info->block_group_cache_lock);
203 n = info->block_group_cache_tree.rb_node;
204
205 while (n) {
David Sterba32da53862019-10-29 19:20:18 +0100206 cache = rb_entry(n, struct btrfs_block_group, cache_node);
David Sterbab3470b52019-10-23 18:48:22 +0200207 end = cache->start + cache->length - 1;
208 start = cache->start;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400209
210 if (bytenr < start) {
David Sterbab3470b52019-10-23 18:48:22 +0200211 if (!contains && (!ret || start < ret->start))
Josef Bacik2e405ad2019-06-20 15:37:45 -0400212 ret = cache;
213 n = n->rb_left;
214 } else if (bytenr > start) {
215 if (contains && bytenr <= end) {
216 ret = cache;
217 break;
218 }
219 n = n->rb_right;
220 } else {
221 ret = cache;
222 break;
223 }
224 }
225 if (ret) {
226 btrfs_get_block_group(ret);
David Sterbab3470b52019-10-23 18:48:22 +0200227 if (bytenr == 0 && info->first_logical_byte > ret->start)
228 info->first_logical_byte = ret->start;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400229 }
230 spin_unlock(&info->block_group_cache_lock);
231
232 return ret;
233}
234
235/*
236 * Return the block group that starts at or after bytenr
237 */
David Sterba32da53862019-10-29 19:20:18 +0100238struct btrfs_block_group *btrfs_lookup_first_block_group(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400239 struct btrfs_fs_info *info, u64 bytenr)
240{
241 return block_group_cache_tree_search(info, bytenr, 0);
242}
243
244/*
245 * Return the block group that contains the given bytenr
246 */
David Sterba32da53862019-10-29 19:20:18 +0100247struct btrfs_block_group *btrfs_lookup_block_group(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400248 struct btrfs_fs_info *info, u64 bytenr)
249{
250 return block_group_cache_tree_search(info, bytenr, 1);
251}
252
David Sterba32da53862019-10-29 19:20:18 +0100253struct btrfs_block_group *btrfs_next_block_group(
254 struct btrfs_block_group *cache)
Josef Bacik2e405ad2019-06-20 15:37:45 -0400255{
256 struct btrfs_fs_info *fs_info = cache->fs_info;
257 struct rb_node *node;
258
259 spin_lock(&fs_info->block_group_cache_lock);
260
261 /* If our block group was removed, we need a full search. */
262 if (RB_EMPTY_NODE(&cache->cache_node)) {
David Sterbab3470b52019-10-23 18:48:22 +0200263 const u64 next_bytenr = cache->start + cache->length;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400264
265 spin_unlock(&fs_info->block_group_cache_lock);
266 btrfs_put_block_group(cache);
267 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
268 }
269 node = rb_next(&cache->cache_node);
270 btrfs_put_block_group(cache);
271 if (node) {
David Sterba32da53862019-10-29 19:20:18 +0100272 cache = rb_entry(node, struct btrfs_block_group, cache_node);
Josef Bacik2e405ad2019-06-20 15:37:45 -0400273 btrfs_get_block_group(cache);
274 } else
275 cache = NULL;
276 spin_unlock(&fs_info->block_group_cache_lock);
277 return cache;
278}
Josef Bacik3eeb3222019-06-20 15:37:47 -0400279
280bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
281{
David Sterba32da53862019-10-29 19:20:18 +0100282 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400283 bool ret = true;
284
285 bg = btrfs_lookup_block_group(fs_info, bytenr);
286 if (!bg)
287 return false;
288
289 spin_lock(&bg->lock);
290 if (bg->ro)
291 ret = false;
292 else
293 atomic_inc(&bg->nocow_writers);
294 spin_unlock(&bg->lock);
295
296 /* No put on block group, done by btrfs_dec_nocow_writers */
297 if (!ret)
298 btrfs_put_block_group(bg);
299
300 return ret;
301}
302
303void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
304{
David Sterba32da53862019-10-29 19:20:18 +0100305 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400306
307 bg = btrfs_lookup_block_group(fs_info, bytenr);
308 ASSERT(bg);
309 if (atomic_dec_and_test(&bg->nocow_writers))
310 wake_up_var(&bg->nocow_writers);
311 /*
312 * Once for our lookup and once for the lookup done by a previous call
313 * to btrfs_inc_nocow_writers()
314 */
315 btrfs_put_block_group(bg);
316 btrfs_put_block_group(bg);
317}
318
David Sterba32da53862019-10-29 19:20:18 +0100319void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
Josef Bacik3eeb3222019-06-20 15:37:47 -0400320{
321 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
322}
323
324void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
325 const u64 start)
326{
David Sterba32da53862019-10-29 19:20:18 +0100327 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400328
329 bg = btrfs_lookup_block_group(fs_info, start);
330 ASSERT(bg);
331 if (atomic_dec_and_test(&bg->reservations))
332 wake_up_var(&bg->reservations);
333 btrfs_put_block_group(bg);
334}
335
David Sterba32da53862019-10-29 19:20:18 +0100336void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
Josef Bacik3eeb3222019-06-20 15:37:47 -0400337{
338 struct btrfs_space_info *space_info = bg->space_info;
339
340 ASSERT(bg->ro);
341
342 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
343 return;
344
345 /*
346 * Our block group is read only but before we set it to read only,
347 * some task might have had allocated an extent from it already, but it
348 * has not yet created a respective ordered extent (and added it to a
349 * root's list of ordered extents).
350 * Therefore wait for any task currently allocating extents, since the
351 * block group's reservations counter is incremented while a read lock
352 * on the groups' semaphore is held and decremented after releasing
353 * the read access on that semaphore and creating the ordered extent.
354 */
355 down_write(&space_info->groups_sem);
356 up_write(&space_info->groups_sem);
357
358 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
359}
Josef Bacik9f212462019-08-06 16:43:19 +0200360
361struct btrfs_caching_control *btrfs_get_caching_control(
David Sterba32da53862019-10-29 19:20:18 +0100362 struct btrfs_block_group *cache)
Josef Bacik9f212462019-08-06 16:43:19 +0200363{
364 struct btrfs_caching_control *ctl;
365
366 spin_lock(&cache->lock);
367 if (!cache->caching_ctl) {
368 spin_unlock(&cache->lock);
369 return NULL;
370 }
371
372 ctl = cache->caching_ctl;
373 refcount_inc(&ctl->count);
374 spin_unlock(&cache->lock);
375 return ctl;
376}
377
378void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
379{
380 if (refcount_dec_and_test(&ctl->count))
381 kfree(ctl);
382}
383
384/*
385 * When we wait for progress in the block group caching, its because our
386 * allocation attempt failed at least once. So, we must sleep and let some
387 * progress happen before we try again.
388 *
389 * This function will sleep at least once waiting for new free space to show
390 * up, and then it will check the block group free space numbers for our min
391 * num_bytes. Another option is to have it go ahead and look in the rbtree for
392 * a free extent of a given size, but this is a good start.
393 *
394 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
395 * any of the information in this block group.
396 */
David Sterba32da53862019-10-29 19:20:18 +0100397void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
Josef Bacik9f212462019-08-06 16:43:19 +0200398 u64 num_bytes)
399{
400 struct btrfs_caching_control *caching_ctl;
401
402 caching_ctl = btrfs_get_caching_control(cache);
403 if (!caching_ctl)
404 return;
405
David Sterba32da53862019-10-29 19:20:18 +0100406 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
Josef Bacik9f212462019-08-06 16:43:19 +0200407 (cache->free_space_ctl->free_space >= num_bytes));
408
409 btrfs_put_caching_control(caching_ctl);
410}
411
David Sterba32da53862019-10-29 19:20:18 +0100412int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
Josef Bacik9f212462019-08-06 16:43:19 +0200413{
414 struct btrfs_caching_control *caching_ctl;
415 int ret = 0;
416
417 caching_ctl = btrfs_get_caching_control(cache);
418 if (!caching_ctl)
419 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
420
David Sterba32da53862019-10-29 19:20:18 +0100421 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
Josef Bacik9f212462019-08-06 16:43:19 +0200422 if (cache->cached == BTRFS_CACHE_ERROR)
423 ret = -EIO;
424 btrfs_put_caching_control(caching_ctl);
425 return ret;
426}
427
Josef Bacike7478532020-10-23 09:58:10 -0400428static bool space_cache_v1_done(struct btrfs_block_group *cache)
429{
430 bool ret;
431
432 spin_lock(&cache->lock);
433 ret = cache->cached != BTRFS_CACHE_FAST;
434 spin_unlock(&cache->lock);
435
436 return ret;
437}
438
439void btrfs_wait_space_cache_v1_finished(struct btrfs_block_group *cache,
440 struct btrfs_caching_control *caching_ctl)
441{
442 wait_event(caching_ctl->wait, space_cache_v1_done(cache));
443}
444
Josef Bacik9f212462019-08-06 16:43:19 +0200445#ifdef CONFIG_BTRFS_DEBUG
David Sterba32da53862019-10-29 19:20:18 +0100446static void fragment_free_space(struct btrfs_block_group *block_group)
Josef Bacik9f212462019-08-06 16:43:19 +0200447{
448 struct btrfs_fs_info *fs_info = block_group->fs_info;
David Sterbab3470b52019-10-23 18:48:22 +0200449 u64 start = block_group->start;
450 u64 len = block_group->length;
Josef Bacik9f212462019-08-06 16:43:19 +0200451 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
452 fs_info->nodesize : fs_info->sectorsize;
453 u64 step = chunk << 1;
454
455 while (len > chunk) {
456 btrfs_remove_free_space(block_group, start, chunk);
457 start += step;
458 if (len < step)
459 len = 0;
460 else
461 len -= step;
462 }
463}
464#endif
465
466/*
467 * This is only called by btrfs_cache_block_group, since we could have freed
468 * extents we need to check the pinned_extents for any extents that can't be
469 * used yet since their free space will be released as soon as the transaction
470 * commits.
471 */
David Sterba32da53862019-10-29 19:20:18 +0100472u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
Josef Bacik9f212462019-08-06 16:43:19 +0200473{
474 struct btrfs_fs_info *info = block_group->fs_info;
475 u64 extent_start, extent_end, size, total_added = 0;
476 int ret;
477
478 while (start < end) {
Nikolay Borisovfe119a62020-01-20 16:09:18 +0200479 ret = find_first_extent_bit(&info->excluded_extents, start,
Josef Bacik9f212462019-08-06 16:43:19 +0200480 &extent_start, &extent_end,
481 EXTENT_DIRTY | EXTENT_UPTODATE,
482 NULL);
483 if (ret)
484 break;
485
486 if (extent_start <= start) {
487 start = extent_end + 1;
488 } else if (extent_start > start && extent_start < end) {
489 size = extent_start - start;
490 total_added += size;
Dennis Zhoub0643e52019-12-13 16:22:14 -0800491 ret = btrfs_add_free_space_async_trimmed(block_group,
492 start, size);
Josef Bacik9f212462019-08-06 16:43:19 +0200493 BUG_ON(ret); /* -ENOMEM or logic error */
494 start = extent_end + 1;
495 } else {
496 break;
497 }
498 }
499
500 if (start < end) {
501 size = end - start;
502 total_added += size;
Dennis Zhoub0643e52019-12-13 16:22:14 -0800503 ret = btrfs_add_free_space_async_trimmed(block_group, start,
504 size);
Josef Bacik9f212462019-08-06 16:43:19 +0200505 BUG_ON(ret); /* -ENOMEM or logic error */
506 }
507
508 return total_added;
509}
510
511static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
512{
David Sterba32da53862019-10-29 19:20:18 +0100513 struct btrfs_block_group *block_group = caching_ctl->block_group;
Josef Bacik9f212462019-08-06 16:43:19 +0200514 struct btrfs_fs_info *fs_info = block_group->fs_info;
515 struct btrfs_root *extent_root = fs_info->extent_root;
516 struct btrfs_path *path;
517 struct extent_buffer *leaf;
518 struct btrfs_key key;
519 u64 total_found = 0;
520 u64 last = 0;
521 u32 nritems;
522 int ret;
523 bool wakeup = true;
524
525 path = btrfs_alloc_path();
526 if (!path)
527 return -ENOMEM;
528
David Sterbab3470b52019-10-23 18:48:22 +0200529 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
Josef Bacik9f212462019-08-06 16:43:19 +0200530
531#ifdef CONFIG_BTRFS_DEBUG
532 /*
533 * If we're fragmenting we don't want to make anybody think we can
534 * allocate from this block group until we've had a chance to fragment
535 * the free space.
536 */
537 if (btrfs_should_fragment_free_space(block_group))
538 wakeup = false;
539#endif
540 /*
541 * We don't want to deadlock with somebody trying to allocate a new
542 * extent for the extent root while also trying to search the extent
543 * root to add free space. So we skip locking and search the commit
544 * root, since its read-only
545 */
546 path->skip_locking = 1;
547 path->search_commit_root = 1;
548 path->reada = READA_FORWARD;
549
550 key.objectid = last;
551 key.offset = 0;
552 key.type = BTRFS_EXTENT_ITEM_KEY;
553
554next:
555 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
556 if (ret < 0)
557 goto out;
558
559 leaf = path->nodes[0];
560 nritems = btrfs_header_nritems(leaf);
561
562 while (1) {
563 if (btrfs_fs_closing(fs_info) > 1) {
564 last = (u64)-1;
565 break;
566 }
567
568 if (path->slots[0] < nritems) {
569 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
570 } else {
571 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
572 if (ret)
573 break;
574
575 if (need_resched() ||
576 rwsem_is_contended(&fs_info->commit_root_sem)) {
577 if (wakeup)
578 caching_ctl->progress = last;
579 btrfs_release_path(path);
580 up_read(&fs_info->commit_root_sem);
581 mutex_unlock(&caching_ctl->mutex);
582 cond_resched();
583 mutex_lock(&caching_ctl->mutex);
584 down_read(&fs_info->commit_root_sem);
585 goto next;
586 }
587
588 ret = btrfs_next_leaf(extent_root, path);
589 if (ret < 0)
590 goto out;
591 if (ret)
592 break;
593 leaf = path->nodes[0];
594 nritems = btrfs_header_nritems(leaf);
595 continue;
596 }
597
598 if (key.objectid < last) {
599 key.objectid = last;
600 key.offset = 0;
601 key.type = BTRFS_EXTENT_ITEM_KEY;
602
603 if (wakeup)
604 caching_ctl->progress = last;
605 btrfs_release_path(path);
606 goto next;
607 }
608
David Sterbab3470b52019-10-23 18:48:22 +0200609 if (key.objectid < block_group->start) {
Josef Bacik9f212462019-08-06 16:43:19 +0200610 path->slots[0]++;
611 continue;
612 }
613
David Sterbab3470b52019-10-23 18:48:22 +0200614 if (key.objectid >= block_group->start + block_group->length)
Josef Bacik9f212462019-08-06 16:43:19 +0200615 break;
616
617 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
618 key.type == BTRFS_METADATA_ITEM_KEY) {
619 total_found += add_new_free_space(block_group, last,
620 key.objectid);
621 if (key.type == BTRFS_METADATA_ITEM_KEY)
622 last = key.objectid +
623 fs_info->nodesize;
624 else
625 last = key.objectid + key.offset;
626
627 if (total_found > CACHING_CTL_WAKE_UP) {
628 total_found = 0;
629 if (wakeup)
630 wake_up(&caching_ctl->wait);
631 }
632 }
633 path->slots[0]++;
634 }
635 ret = 0;
636
637 total_found += add_new_free_space(block_group, last,
David Sterbab3470b52019-10-23 18:48:22 +0200638 block_group->start + block_group->length);
Josef Bacik9f212462019-08-06 16:43:19 +0200639 caching_ctl->progress = (u64)-1;
640
641out:
642 btrfs_free_path(path);
643 return ret;
644}
645
646static noinline void caching_thread(struct btrfs_work *work)
647{
David Sterba32da53862019-10-29 19:20:18 +0100648 struct btrfs_block_group *block_group;
Josef Bacik9f212462019-08-06 16:43:19 +0200649 struct btrfs_fs_info *fs_info;
650 struct btrfs_caching_control *caching_ctl;
651 int ret;
652
653 caching_ctl = container_of(work, struct btrfs_caching_control, work);
654 block_group = caching_ctl->block_group;
655 fs_info = block_group->fs_info;
656
657 mutex_lock(&caching_ctl->mutex);
658 down_read(&fs_info->commit_root_sem);
659
Josef Bacike7478532020-10-23 09:58:10 -0400660 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
661 ret = load_free_space_cache(block_group);
662 if (ret == 1) {
663 ret = 0;
664 goto done;
665 }
666
667 /*
668 * We failed to load the space cache, set ourselves to
669 * CACHE_STARTED and carry on.
670 */
671 spin_lock(&block_group->lock);
672 block_group->cached = BTRFS_CACHE_STARTED;
673 spin_unlock(&block_group->lock);
674 wake_up(&caching_ctl->wait);
675 }
676
Josef Bacik2f96e402021-01-15 16:26:17 -0500677 /*
678 * If we are in the transaction that populated the free space tree we
679 * can't actually cache from the free space tree as our commit root and
680 * real root are the same, so we could change the contents of the blocks
681 * while caching. Instead do the slow caching in this case, and after
682 * the transaction has committed we will be safe.
683 */
684 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
685 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
Josef Bacik9f212462019-08-06 16:43:19 +0200686 ret = load_free_space_tree(caching_ctl);
687 else
688 ret = load_extent_tree_free(caching_ctl);
Josef Bacike7478532020-10-23 09:58:10 -0400689done:
Josef Bacik9f212462019-08-06 16:43:19 +0200690 spin_lock(&block_group->lock);
691 block_group->caching_ctl = NULL;
692 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
693 spin_unlock(&block_group->lock);
694
695#ifdef CONFIG_BTRFS_DEBUG
696 if (btrfs_should_fragment_free_space(block_group)) {
697 u64 bytes_used;
698
699 spin_lock(&block_group->space_info->lock);
700 spin_lock(&block_group->lock);
David Sterbab3470b52019-10-23 18:48:22 +0200701 bytes_used = block_group->length - block_group->used;
Josef Bacik9f212462019-08-06 16:43:19 +0200702 block_group->space_info->bytes_used += bytes_used >> 1;
703 spin_unlock(&block_group->lock);
704 spin_unlock(&block_group->space_info->lock);
Josef Bacike11c0402019-06-20 15:38:07 -0400705 fragment_free_space(block_group);
Josef Bacik9f212462019-08-06 16:43:19 +0200706 }
707#endif
708
709 caching_ctl->progress = (u64)-1;
710
711 up_read(&fs_info->commit_root_sem);
712 btrfs_free_excluded_extents(block_group);
713 mutex_unlock(&caching_ctl->mutex);
714
715 wake_up(&caching_ctl->wait);
716
717 btrfs_put_caching_control(caching_ctl);
718 btrfs_put_block_group(block_group);
719}
720
David Sterba32da53862019-10-29 19:20:18 +0100721int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
Josef Bacik9f212462019-08-06 16:43:19 +0200722{
723 DEFINE_WAIT(wait);
724 struct btrfs_fs_info *fs_info = cache->fs_info;
Josef Bacike7478532020-10-23 09:58:10 -0400725 struct btrfs_caching_control *caching_ctl = NULL;
Josef Bacik9f212462019-08-06 16:43:19 +0200726 int ret = 0;
727
Naohiro Aota2eda5702021-02-04 19:21:53 +0900728 /* Allocator for zoned filesystems does not use the cache at all */
729 if (btrfs_is_zoned(fs_info))
730 return 0;
731
Josef Bacik9f212462019-08-06 16:43:19 +0200732 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
733 if (!caching_ctl)
734 return -ENOMEM;
735
736 INIT_LIST_HEAD(&caching_ctl->list);
737 mutex_init(&caching_ctl->mutex);
738 init_waitqueue_head(&caching_ctl->wait);
739 caching_ctl->block_group = cache;
David Sterbab3470b52019-10-23 18:48:22 +0200740 caching_ctl->progress = cache->start;
Josef Bacike7478532020-10-23 09:58:10 -0400741 refcount_set(&caching_ctl->count, 2);
Omar Sandovala0cac0e2019-09-16 11:30:57 -0700742 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
Josef Bacik9f212462019-08-06 16:43:19 +0200743
744 spin_lock(&cache->lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200745 if (cache->cached != BTRFS_CACHE_NO) {
Josef Bacik9f212462019-08-06 16:43:19 +0200746 kfree(caching_ctl);
Josef Bacike7478532020-10-23 09:58:10 -0400747
748 caching_ctl = cache->caching_ctl;
749 if (caching_ctl)
750 refcount_inc(&caching_ctl->count);
751 spin_unlock(&cache->lock);
752 goto out;
Josef Bacik9f212462019-08-06 16:43:19 +0200753 }
754 WARN_ON(cache->caching_ctl);
755 cache->caching_ctl = caching_ctl;
Josef Bacike7478532020-10-23 09:58:10 -0400756 if (btrfs_test_opt(fs_info, SPACE_CACHE))
757 cache->cached = BTRFS_CACHE_FAST;
758 else
759 cache->cached = BTRFS_CACHE_STARTED;
760 cache->has_caching_ctl = 1;
Josef Bacik9f212462019-08-06 16:43:19 +0200761 spin_unlock(&cache->lock);
762
Josef Bacikbbb86a32020-10-23 09:58:11 -0400763 spin_lock(&fs_info->block_group_cache_lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200764 refcount_inc(&caching_ctl->count);
765 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
Josef Bacikbbb86a32020-10-23 09:58:11 -0400766 spin_unlock(&fs_info->block_group_cache_lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200767
768 btrfs_get_block_group(cache);
769
770 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
Josef Bacike7478532020-10-23 09:58:10 -0400771out:
772 if (load_cache_only && caching_ctl)
773 btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
774 if (caching_ctl)
775 btrfs_put_caching_control(caching_ctl);
Josef Bacik9f212462019-08-06 16:43:19 +0200776
777 return ret;
778}
Josef Bacike3e05202019-06-20 15:37:55 -0400779
780static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
781{
782 u64 extra_flags = chunk_to_extended(flags) &
783 BTRFS_EXTENDED_PROFILE_MASK;
784
785 write_seqlock(&fs_info->profiles_lock);
786 if (flags & BTRFS_BLOCK_GROUP_DATA)
787 fs_info->avail_data_alloc_bits &= ~extra_flags;
788 if (flags & BTRFS_BLOCK_GROUP_METADATA)
789 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
790 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
791 fs_info->avail_system_alloc_bits &= ~extra_flags;
792 write_sequnlock(&fs_info->profiles_lock);
793}
794
795/*
796 * Clear incompat bits for the following feature(s):
797 *
798 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
799 * in the whole filesystem
David Sterba9c907442019-10-31 15:52:01 +0100800 *
801 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
Josef Bacike3e05202019-06-20 15:37:55 -0400802 */
803static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
804{
David Sterba9c907442019-10-31 15:52:01 +0100805 bool found_raid56 = false;
806 bool found_raid1c34 = false;
807
808 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
809 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
810 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
Josef Bacike3e05202019-06-20 15:37:55 -0400811 struct list_head *head = &fs_info->space_info;
812 struct btrfs_space_info *sinfo;
813
814 list_for_each_entry_rcu(sinfo, head, list) {
Josef Bacike3e05202019-06-20 15:37:55 -0400815 down_read(&sinfo->groups_sem);
816 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
David Sterba9c907442019-10-31 15:52:01 +0100817 found_raid56 = true;
Josef Bacike3e05202019-06-20 15:37:55 -0400818 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
David Sterba9c907442019-10-31 15:52:01 +0100819 found_raid56 = true;
820 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
821 found_raid1c34 = true;
822 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
823 found_raid1c34 = true;
Josef Bacike3e05202019-06-20 15:37:55 -0400824 up_read(&sinfo->groups_sem);
Josef Bacike3e05202019-06-20 15:37:55 -0400825 }
Filipe Mananad8e6fd52020-03-20 18:43:48 +0000826 if (!found_raid56)
David Sterba9c907442019-10-31 15:52:01 +0100827 btrfs_clear_fs_incompat(fs_info, RAID56);
Filipe Mananad8e6fd52020-03-20 18:43:48 +0000828 if (!found_raid1c34)
David Sterba9c907442019-10-31 15:52:01 +0100829 btrfs_clear_fs_incompat(fs_info, RAID1C34);
Josef Bacike3e05202019-06-20 15:37:55 -0400830 }
831}
832
Qu Wenruo73576232020-05-05 07:58:21 +0800833static int remove_block_group_item(struct btrfs_trans_handle *trans,
834 struct btrfs_path *path,
835 struct btrfs_block_group *block_group)
836{
837 struct btrfs_fs_info *fs_info = trans->fs_info;
838 struct btrfs_root *root;
839 struct btrfs_key key;
840 int ret;
841
842 root = fs_info->extent_root;
843 key.objectid = block_group->start;
844 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
845 key.offset = block_group->length;
846
847 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
848 if (ret > 0)
849 ret = -ENOENT;
850 if (ret < 0)
851 return ret;
852
853 ret = btrfs_del_item(trans, root, path);
854 return ret;
855}
856
Josef Bacike3e05202019-06-20 15:37:55 -0400857int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
858 u64 group_start, struct extent_map *em)
859{
860 struct btrfs_fs_info *fs_info = trans->fs_info;
Josef Bacike3e05202019-06-20 15:37:55 -0400861 struct btrfs_path *path;
David Sterba32da53862019-10-29 19:20:18 +0100862 struct btrfs_block_group *block_group;
Josef Bacike3e05202019-06-20 15:37:55 -0400863 struct btrfs_free_cluster *cluster;
Josef Bacike3e05202019-06-20 15:37:55 -0400864 struct inode *inode;
865 struct kobject *kobj = NULL;
866 int ret;
867 int index;
868 int factor;
869 struct btrfs_caching_control *caching_ctl = NULL;
870 bool remove_em;
871 bool remove_rsv = false;
872
873 block_group = btrfs_lookup_block_group(fs_info, group_start);
874 BUG_ON(!block_group);
875 BUG_ON(!block_group->ro);
876
877 trace_btrfs_remove_block_group(block_group);
878 /*
879 * Free the reserved super bytes from this block group before
880 * remove it.
881 */
882 btrfs_free_excluded_extents(block_group);
David Sterbab3470b52019-10-23 18:48:22 +0200883 btrfs_free_ref_tree_range(fs_info, block_group->start,
884 block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -0400885
Josef Bacike3e05202019-06-20 15:37:55 -0400886 index = btrfs_bg_flags_to_raid_index(block_group->flags);
887 factor = btrfs_bg_type_to_factor(block_group->flags);
888
889 /* make sure this block group isn't part of an allocation cluster */
890 cluster = &fs_info->data_alloc_cluster;
891 spin_lock(&cluster->refill_lock);
892 btrfs_return_cluster_to_free_space(block_group, cluster);
893 spin_unlock(&cluster->refill_lock);
894
895 /*
896 * make sure this block group isn't part of a metadata
897 * allocation cluster
898 */
899 cluster = &fs_info->meta_alloc_cluster;
900 spin_lock(&cluster->refill_lock);
901 btrfs_return_cluster_to_free_space(block_group, cluster);
902 spin_unlock(&cluster->refill_lock);
903
Naohiro Aota40ab3be2021-02-04 19:22:18 +0900904 btrfs_clear_treelog_bg(block_group);
905
Josef Bacike3e05202019-06-20 15:37:55 -0400906 path = btrfs_alloc_path();
907 if (!path) {
908 ret = -ENOMEM;
Filipe Manana9fecd132020-06-01 19:12:06 +0100909 goto out;
Josef Bacike3e05202019-06-20 15:37:55 -0400910 }
911
912 /*
913 * get the inode first so any iput calls done for the io_list
914 * aren't the final iput (no unlinks allowed now)
915 */
916 inode = lookup_free_space_inode(block_group, path);
917
918 mutex_lock(&trans->transaction->cache_write_mutex);
919 /*
920 * Make sure our free space cache IO is done before removing the
921 * free space inode
922 */
923 spin_lock(&trans->transaction->dirty_bgs_lock);
924 if (!list_empty(&block_group->io_list)) {
925 list_del_init(&block_group->io_list);
926
927 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
928
929 spin_unlock(&trans->transaction->dirty_bgs_lock);
930 btrfs_wait_cache_io(trans, block_group, path);
931 btrfs_put_block_group(block_group);
932 spin_lock(&trans->transaction->dirty_bgs_lock);
933 }
934
935 if (!list_empty(&block_group->dirty_list)) {
936 list_del_init(&block_group->dirty_list);
937 remove_rsv = true;
938 btrfs_put_block_group(block_group);
939 }
940 spin_unlock(&trans->transaction->dirty_bgs_lock);
941 mutex_unlock(&trans->transaction->cache_write_mutex);
942
Boris Burkov36b216c2020-11-18 15:06:25 -0800943 ret = btrfs_remove_free_space_inode(trans, inode, block_group);
944 if (ret)
Filipe Manana9fecd132020-06-01 19:12:06 +0100945 goto out;
Josef Bacike3e05202019-06-20 15:37:55 -0400946
947 spin_lock(&fs_info->block_group_cache_lock);
948 rb_erase(&block_group->cache_node,
949 &fs_info->block_group_cache_tree);
950 RB_CLEAR_NODE(&block_group->cache_node);
951
Filipe Manana9fecd132020-06-01 19:12:06 +0100952 /* Once for the block groups rbtree */
953 btrfs_put_block_group(block_group);
954
David Sterbab3470b52019-10-23 18:48:22 +0200955 if (fs_info->first_logical_byte == block_group->start)
Josef Bacike3e05202019-06-20 15:37:55 -0400956 fs_info->first_logical_byte = (u64)-1;
957 spin_unlock(&fs_info->block_group_cache_lock);
958
959 down_write(&block_group->space_info->groups_sem);
960 /*
961 * we must use list_del_init so people can check to see if they
962 * are still on the list after taking the semaphore
963 */
964 list_del_init(&block_group->list);
965 if (list_empty(&block_group->space_info->block_groups[index])) {
966 kobj = block_group->space_info->block_group_kobjs[index];
967 block_group->space_info->block_group_kobjs[index] = NULL;
968 clear_avail_alloc_bits(fs_info, block_group->flags);
969 }
970 up_write(&block_group->space_info->groups_sem);
971 clear_incompat_bg_bits(fs_info, block_group->flags);
972 if (kobj) {
973 kobject_del(kobj);
974 kobject_put(kobj);
975 }
976
977 if (block_group->has_caching_ctl)
978 caching_ctl = btrfs_get_caching_control(block_group);
979 if (block_group->cached == BTRFS_CACHE_STARTED)
980 btrfs_wait_block_group_cache_done(block_group);
981 if (block_group->has_caching_ctl) {
Josef Bacikbbb86a32020-10-23 09:58:11 -0400982 spin_lock(&fs_info->block_group_cache_lock);
Josef Bacike3e05202019-06-20 15:37:55 -0400983 if (!caching_ctl) {
984 struct btrfs_caching_control *ctl;
985
986 list_for_each_entry(ctl,
987 &fs_info->caching_block_groups, list)
988 if (ctl->block_group == block_group) {
989 caching_ctl = ctl;
990 refcount_inc(&caching_ctl->count);
991 break;
992 }
993 }
994 if (caching_ctl)
995 list_del_init(&caching_ctl->list);
Josef Bacikbbb86a32020-10-23 09:58:11 -0400996 spin_unlock(&fs_info->block_group_cache_lock);
Josef Bacike3e05202019-06-20 15:37:55 -0400997 if (caching_ctl) {
998 /* Once for the caching bgs list and once for us. */
999 btrfs_put_caching_control(caching_ctl);
1000 btrfs_put_caching_control(caching_ctl);
1001 }
1002 }
1003
1004 spin_lock(&trans->transaction->dirty_bgs_lock);
1005 WARN_ON(!list_empty(&block_group->dirty_list));
1006 WARN_ON(!list_empty(&block_group->io_list));
1007 spin_unlock(&trans->transaction->dirty_bgs_lock);
1008
1009 btrfs_remove_free_space_cache(block_group);
1010
1011 spin_lock(&block_group->space_info->lock);
1012 list_del_init(&block_group->ro_list);
1013
1014 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1015 WARN_ON(block_group->space_info->total_bytes
David Sterbab3470b52019-10-23 18:48:22 +02001016 < block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -04001017 WARN_ON(block_group->space_info->bytes_readonly
Naohiro Aota169e0da2021-02-04 19:21:52 +09001018 < block_group->length - block_group->zone_unusable);
1019 WARN_ON(block_group->space_info->bytes_zone_unusable
1020 < block_group->zone_unusable);
Josef Bacike3e05202019-06-20 15:37:55 -04001021 WARN_ON(block_group->space_info->disk_total
David Sterbab3470b52019-10-23 18:48:22 +02001022 < block_group->length * factor);
Josef Bacike3e05202019-06-20 15:37:55 -04001023 }
David Sterbab3470b52019-10-23 18:48:22 +02001024 block_group->space_info->total_bytes -= block_group->length;
Naohiro Aota169e0da2021-02-04 19:21:52 +09001025 block_group->space_info->bytes_readonly -=
1026 (block_group->length - block_group->zone_unusable);
1027 block_group->space_info->bytes_zone_unusable -=
1028 block_group->zone_unusable;
David Sterbab3470b52019-10-23 18:48:22 +02001029 block_group->space_info->disk_total -= block_group->length * factor;
Josef Bacike3e05202019-06-20 15:37:55 -04001030
1031 spin_unlock(&block_group->space_info->lock);
1032
Filipe Mananaffcb9d42020-06-01 19:12:19 +01001033 /*
1034 * Remove the free space for the block group from the free space tree
1035 * and the block group's item from the extent tree before marking the
1036 * block group as removed. This is to prevent races with tasks that
1037 * freeze and unfreeze a block group, this task and another task
1038 * allocating a new block group - the unfreeze task ends up removing
1039 * the block group's extent map before the task calling this function
1040 * deletes the block group item from the extent tree, allowing for
1041 * another task to attempt to create another block group with the same
1042 * item key (and failing with -EEXIST and a transaction abort).
1043 */
1044 ret = remove_block_group_free_space(trans, block_group);
1045 if (ret)
1046 goto out;
1047
1048 ret = remove_block_group_item(trans, path, block_group);
1049 if (ret < 0)
1050 goto out;
1051
Josef Bacike3e05202019-06-20 15:37:55 -04001052 spin_lock(&block_group->lock);
1053 block_group->removed = 1;
1054 /*
Filipe Manana6b7304a2020-05-08 11:01:47 +01001055 * At this point trimming or scrub can't start on this block group,
1056 * because we removed the block group from the rbtree
1057 * fs_info->block_group_cache_tree so no one can't find it anymore and
1058 * even if someone already got this block group before we removed it
1059 * from the rbtree, they have already incremented block_group->frozen -
1060 * if they didn't, for the trimming case they won't find any free space
1061 * entries because we already removed them all when we called
1062 * btrfs_remove_free_space_cache().
Josef Bacike3e05202019-06-20 15:37:55 -04001063 *
1064 * And we must not remove the extent map from the fs_info->mapping_tree
1065 * to prevent the same logical address range and physical device space
Filipe Manana6b7304a2020-05-08 11:01:47 +01001066 * ranges from being reused for a new block group. This is needed to
1067 * avoid races with trimming and scrub.
1068 *
1069 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
Josef Bacike3e05202019-06-20 15:37:55 -04001070 * completely transactionless, so while it is trimming a range the
1071 * currently running transaction might finish and a new one start,
1072 * allowing for new block groups to be created that can reuse the same
1073 * physical device locations unless we take this special care.
1074 *
1075 * There may also be an implicit trim operation if the file system
1076 * is mounted with -odiscard. The same protections must remain
1077 * in place until the extents have been discarded completely when
1078 * the transaction commit has completed.
1079 */
Filipe Manana6b7304a2020-05-08 11:01:47 +01001080 remove_em = (atomic_read(&block_group->frozen) == 0);
Josef Bacike3e05202019-06-20 15:37:55 -04001081 spin_unlock(&block_group->lock);
1082
Josef Bacike3e05202019-06-20 15:37:55 -04001083 if (remove_em) {
1084 struct extent_map_tree *em_tree;
1085
1086 em_tree = &fs_info->mapping_tree;
1087 write_lock(&em_tree->lock);
1088 remove_extent_mapping(em_tree, em);
1089 write_unlock(&em_tree->lock);
1090 /* once for the tree */
1091 free_extent_map(em);
1092 }
Xiyu Yangf6033c52020-04-21 10:54:11 +08001093
Filipe Manana9fecd132020-06-01 19:12:06 +01001094out:
Xiyu Yangf6033c52020-04-21 10:54:11 +08001095 /* Once for the lookup reference */
1096 btrfs_put_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001097 if (remove_rsv)
1098 btrfs_delayed_refs_rsv_release(fs_info, 1);
1099 btrfs_free_path(path);
1100 return ret;
1101}
1102
1103struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1104 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1105{
1106 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1107 struct extent_map *em;
1108 struct map_lookup *map;
1109 unsigned int num_items;
1110
1111 read_lock(&em_tree->lock);
1112 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1113 read_unlock(&em_tree->lock);
1114 ASSERT(em && em->start == chunk_offset);
1115
1116 /*
1117 * We need to reserve 3 + N units from the metadata space info in order
1118 * to remove a block group (done at btrfs_remove_chunk() and at
1119 * btrfs_remove_block_group()), which are used for:
1120 *
1121 * 1 unit for adding the free space inode's orphan (located in the tree
1122 * of tree roots).
1123 * 1 unit for deleting the block group item (located in the extent
1124 * tree).
1125 * 1 unit for deleting the free space item (located in tree of tree
1126 * roots).
1127 * N units for deleting N device extent items corresponding to each
1128 * stripe (located in the device tree).
1129 *
1130 * In order to remove a block group we also need to reserve units in the
1131 * system space info in order to update the chunk tree (update one or
1132 * more device items and remove one chunk item), but this is done at
1133 * btrfs_remove_chunk() through a call to check_system_chunk().
1134 */
1135 map = em->map_lookup;
1136 num_items = 3 + map->num_stripes;
1137 free_extent_map(em);
1138
1139 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
Josef Bacik7f9fe612020-03-13 15:58:05 -04001140 num_items);
Josef Bacike3e05202019-06-20 15:37:55 -04001141}
1142
1143/*
Josef Bacik26ce2092019-06-20 15:37:59 -04001144 * Mark block group @cache read-only, so later write won't happen to block
1145 * group @cache.
1146 *
1147 * If @force is not set, this function will only mark the block group readonly
1148 * if we have enough free space (1M) in other metadata/system block groups.
1149 * If @force is not set, this function will mark the block group readonly
1150 * without checking free space.
1151 *
1152 * NOTE: This function doesn't care if other block groups can contain all the
1153 * data in this block group. That check should be done by relocation routine,
1154 * not this function.
1155 */
David Sterba32da53862019-10-29 19:20:18 +01001156static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
Josef Bacik26ce2092019-06-20 15:37:59 -04001157{
1158 struct btrfs_space_info *sinfo = cache->space_info;
1159 u64 num_bytes;
Josef Bacik26ce2092019-06-20 15:37:59 -04001160 int ret = -ENOSPC;
1161
Josef Bacik26ce2092019-06-20 15:37:59 -04001162 spin_lock(&sinfo->lock);
1163 spin_lock(&cache->lock);
1164
Filipe Manana195a49e2021-02-05 12:55:37 +00001165 if (cache->swap_extents) {
1166 ret = -ETXTBSY;
1167 goto out;
1168 }
1169
Josef Bacik26ce2092019-06-20 15:37:59 -04001170 if (cache->ro) {
1171 cache->ro++;
1172 ret = 0;
1173 goto out;
1174 }
1175
David Sterbab3470b52019-10-23 18:48:22 +02001176 num_bytes = cache->length - cache->reserved - cache->pinned -
Naohiro Aota169e0da2021-02-04 19:21:52 +09001177 cache->bytes_super - cache->zone_unusable - cache->used;
Josef Bacik26ce2092019-06-20 15:37:59 -04001178
1179 /*
Josef Bacika30a3d22020-01-17 09:07:39 -05001180 * Data never overcommits, even in mixed mode, so do just the straight
1181 * check of left over space in how much we have allocated.
Josef Bacik26ce2092019-06-20 15:37:59 -04001182 */
Josef Bacika30a3d22020-01-17 09:07:39 -05001183 if (force) {
1184 ret = 0;
1185 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1186 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1187
1188 /*
1189 * Here we make sure if we mark this bg RO, we still have enough
1190 * free space as buffer.
1191 */
1192 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1193 ret = 0;
1194 } else {
1195 /*
1196 * We overcommit metadata, so we need to do the
1197 * btrfs_can_overcommit check here, and we need to pass in
1198 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1199 * leeway to allow us to mark this block group as read only.
1200 */
1201 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1202 BTRFS_RESERVE_NO_FLUSH))
1203 ret = 0;
1204 }
1205
1206 if (!ret) {
Josef Bacik26ce2092019-06-20 15:37:59 -04001207 sinfo->bytes_readonly += num_bytes;
Naohiro Aota169e0da2021-02-04 19:21:52 +09001208 if (btrfs_is_zoned(cache->fs_info)) {
1209 /* Migrate zone_unusable bytes to readonly */
1210 sinfo->bytes_readonly += cache->zone_unusable;
1211 sinfo->bytes_zone_unusable -= cache->zone_unusable;
1212 cache->zone_unusable = 0;
1213 }
Josef Bacik26ce2092019-06-20 15:37:59 -04001214 cache->ro++;
1215 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
Josef Bacik26ce2092019-06-20 15:37:59 -04001216 }
1217out:
1218 spin_unlock(&cache->lock);
1219 spin_unlock(&sinfo->lock);
1220 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1221 btrfs_info(cache->fs_info,
David Sterbab3470b52019-10-23 18:48:22 +02001222 "unable to make block group %llu ro", cache->start);
Josef Bacik26ce2092019-06-20 15:37:59 -04001223 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1224 }
1225 return ret;
1226}
1227
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001228static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1229 struct btrfs_block_group *bg)
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001230{
1231 struct btrfs_fs_info *fs_info = bg->fs_info;
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001232 struct btrfs_transaction *prev_trans = NULL;
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001233 const u64 start = bg->start;
1234 const u64 end = start + bg->length - 1;
1235 int ret;
1236
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001237 spin_lock(&fs_info->trans_lock);
1238 if (trans->transaction->list.prev != &fs_info->trans_list) {
1239 prev_trans = list_last_entry(&trans->transaction->list,
1240 struct btrfs_transaction, list);
1241 refcount_inc(&prev_trans->use_count);
1242 }
1243 spin_unlock(&fs_info->trans_lock);
1244
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001245 /*
1246 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1247 * btrfs_finish_extent_commit(). If we are at transaction N, another
1248 * task might be running finish_extent_commit() for the previous
1249 * transaction N - 1, and have seen a range belonging to the block
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001250 * group in pinned_extents before we were able to clear the whole block
1251 * group range from pinned_extents. This means that task can lookup for
1252 * the block group after we unpinned it from pinned_extents and removed
1253 * it, leading to a BUG_ON() at unpin_extent_range().
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001254 */
1255 mutex_lock(&fs_info->unused_bg_unpin_mutex);
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001256 if (prev_trans) {
1257 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1258 EXTENT_DIRTY);
1259 if (ret)
Filipe Manana534cf532020-04-17 16:36:50 +01001260 goto out;
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001261 }
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001262
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001263 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001264 EXTENT_DIRTY);
Filipe Manana534cf532020-04-17 16:36:50 +01001265out:
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001266 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
Filipe Manana5150bf12020-04-17 16:36:15 +01001267 if (prev_trans)
1268 btrfs_put_transaction(prev_trans);
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001269
Filipe Manana534cf532020-04-17 16:36:50 +01001270 return ret == 0;
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001271}
1272
Josef Bacik26ce2092019-06-20 15:37:59 -04001273/*
Josef Bacike3e05202019-06-20 15:37:55 -04001274 * Process the unused_bgs list and remove any that don't have any allocated
1275 * space inside of them.
1276 */
1277void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1278{
David Sterba32da53862019-10-29 19:20:18 +01001279 struct btrfs_block_group *block_group;
Josef Bacike3e05202019-06-20 15:37:55 -04001280 struct btrfs_space_info *space_info;
1281 struct btrfs_trans_handle *trans;
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001282 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
Josef Bacike3e05202019-06-20 15:37:55 -04001283 int ret = 0;
1284
1285 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1286 return;
1287
Josef Bacikddfd08c2020-12-18 14:24:19 -05001288 /*
1289 * Long running balances can keep us blocked here for eternity, so
1290 * simply skip deletion if we're unable to get the mutex.
1291 */
Johannes Thumshirnf3372062021-04-19 16:41:01 +09001292 if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
Josef Bacikddfd08c2020-12-18 14:24:19 -05001293 return;
1294
Josef Bacike3e05202019-06-20 15:37:55 -04001295 spin_lock(&fs_info->unused_bgs_lock);
1296 while (!list_empty(&fs_info->unused_bgs)) {
Josef Bacike3e05202019-06-20 15:37:55 -04001297 int trimming;
1298
1299 block_group = list_first_entry(&fs_info->unused_bgs,
David Sterba32da53862019-10-29 19:20:18 +01001300 struct btrfs_block_group,
Josef Bacike3e05202019-06-20 15:37:55 -04001301 bg_list);
1302 list_del_init(&block_group->bg_list);
1303
1304 space_info = block_group->space_info;
1305
1306 if (ret || btrfs_mixed_space_info(space_info)) {
1307 btrfs_put_block_group(block_group);
1308 continue;
1309 }
1310 spin_unlock(&fs_info->unused_bgs_lock);
1311
Dennis Zhoub0643e52019-12-13 16:22:14 -08001312 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1313
Josef Bacike3e05202019-06-20 15:37:55 -04001314 /* Don't want to race with allocators so take the groups_sem */
1315 down_write(&space_info->groups_sem);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001316
1317 /*
1318 * Async discard moves the final block group discard to be prior
1319 * to the unused_bgs code path. Therefore, if it's not fully
1320 * trimmed, punt it back to the async discard lists.
1321 */
1322 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1323 !btrfs_is_free_space_trimmed(block_group)) {
1324 trace_btrfs_skip_unused_block_group(block_group);
1325 up_write(&space_info->groups_sem);
1326 /* Requeue if we failed because of async discard */
1327 btrfs_discard_queue_work(&fs_info->discard_ctl,
1328 block_group);
1329 goto next;
1330 }
1331
Josef Bacike3e05202019-06-20 15:37:55 -04001332 spin_lock(&block_group->lock);
1333 if (block_group->reserved || block_group->pinned ||
David Sterbabf38be62019-10-23 18:48:11 +02001334 block_group->used || block_group->ro ||
Josef Bacike3e05202019-06-20 15:37:55 -04001335 list_is_singular(&block_group->list)) {
1336 /*
1337 * We want to bail if we made new allocations or have
1338 * outstanding allocations in this block group. We do
1339 * the ro check in case balance is currently acting on
1340 * this block group.
1341 */
1342 trace_btrfs_skip_unused_block_group(block_group);
1343 spin_unlock(&block_group->lock);
1344 up_write(&space_info->groups_sem);
1345 goto next;
1346 }
1347 spin_unlock(&block_group->lock);
1348
1349 /* We don't want to force the issue, only flip if it's ok. */
Josef Bacike11c0402019-06-20 15:38:07 -04001350 ret = inc_block_group_ro(block_group, 0);
Josef Bacike3e05202019-06-20 15:37:55 -04001351 up_write(&space_info->groups_sem);
1352 if (ret < 0) {
1353 ret = 0;
1354 goto next;
1355 }
1356
1357 /*
1358 * Want to do this before we do anything else so we can recover
1359 * properly if we fail to join the transaction.
1360 */
1361 trans = btrfs_start_trans_remove_block_group(fs_info,
David Sterbab3470b52019-10-23 18:48:22 +02001362 block_group->start);
Josef Bacike3e05202019-06-20 15:37:55 -04001363 if (IS_ERR(trans)) {
1364 btrfs_dec_block_group_ro(block_group);
1365 ret = PTR_ERR(trans);
1366 goto next;
1367 }
1368
1369 /*
1370 * We could have pending pinned extents for this block group,
1371 * just delete them, we don't care about them anymore.
1372 */
Filipe Manana534cf532020-04-17 16:36:50 +01001373 if (!clean_pinned_extents(trans, block_group)) {
1374 btrfs_dec_block_group_ro(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001375 goto end_trans;
Filipe Manana534cf532020-04-17 16:36:50 +01001376 }
Josef Bacike3e05202019-06-20 15:37:55 -04001377
Dennis Zhoub0643e52019-12-13 16:22:14 -08001378 /*
1379 * At this point, the block_group is read only and should fail
1380 * new allocations. However, btrfs_finish_extent_commit() can
1381 * cause this block_group to be placed back on the discard
1382 * lists because now the block_group isn't fully discarded.
1383 * Bail here and try again later after discarding everything.
1384 */
1385 spin_lock(&fs_info->discard_ctl.lock);
1386 if (!list_empty(&block_group->discard_list)) {
1387 spin_unlock(&fs_info->discard_ctl.lock);
1388 btrfs_dec_block_group_ro(block_group);
1389 btrfs_discard_queue_work(&fs_info->discard_ctl,
1390 block_group);
1391 goto end_trans;
1392 }
1393 spin_unlock(&fs_info->discard_ctl.lock);
1394
Josef Bacike3e05202019-06-20 15:37:55 -04001395 /* Reset pinned so btrfs_put_block_group doesn't complain */
1396 spin_lock(&space_info->lock);
1397 spin_lock(&block_group->lock);
1398
1399 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1400 -block_group->pinned);
1401 space_info->bytes_readonly += block_group->pinned;
Josef Bacik21873742021-01-15 16:48:55 -05001402 __btrfs_mod_total_bytes_pinned(space_info, -block_group->pinned);
Josef Bacike3e05202019-06-20 15:37:55 -04001403 block_group->pinned = 0;
1404
1405 spin_unlock(&block_group->lock);
1406 spin_unlock(&space_info->lock);
1407
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001408 /*
1409 * The normal path here is an unused block group is passed here,
1410 * then trimming is handled in the transaction commit path.
1411 * Async discard interposes before this to do the trimming
1412 * before coming down the unused block group path as trimming
1413 * will no longer be done later in the transaction commit path.
1414 */
1415 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1416 goto flip_async;
1417
Naohiro Aotadcba6e42021-02-04 19:21:56 +09001418 /*
1419 * DISCARD can flip during remount. On zoned filesystems, we
1420 * need to reset sequential-required zones.
1421 */
1422 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1423 btrfs_is_zoned(fs_info);
Josef Bacike3e05202019-06-20 15:37:55 -04001424
1425 /* Implicit trim during transaction commit. */
1426 if (trimming)
Filipe Manana6b7304a2020-05-08 11:01:47 +01001427 btrfs_freeze_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001428
1429 /*
1430 * Btrfs_remove_chunk will abort the transaction if things go
1431 * horribly wrong.
1432 */
David Sterbab3470b52019-10-23 18:48:22 +02001433 ret = btrfs_remove_chunk(trans, block_group->start);
Josef Bacike3e05202019-06-20 15:37:55 -04001434
1435 if (ret) {
1436 if (trimming)
Filipe Manana6b7304a2020-05-08 11:01:47 +01001437 btrfs_unfreeze_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001438 goto end_trans;
1439 }
1440
1441 /*
1442 * If we're not mounted with -odiscard, we can just forget
1443 * about this block group. Otherwise we'll need to wait
1444 * until transaction commit to do the actual discard.
1445 */
1446 if (trimming) {
1447 spin_lock(&fs_info->unused_bgs_lock);
1448 /*
1449 * A concurrent scrub might have added us to the list
1450 * fs_info->unused_bgs, so use a list_move operation
1451 * to add the block group to the deleted_bgs list.
1452 */
1453 list_move(&block_group->bg_list,
1454 &trans->transaction->deleted_bgs);
1455 spin_unlock(&fs_info->unused_bgs_lock);
1456 btrfs_get_block_group(block_group);
1457 }
1458end_trans:
1459 btrfs_end_transaction(trans);
1460next:
Josef Bacike3e05202019-06-20 15:37:55 -04001461 btrfs_put_block_group(block_group);
1462 spin_lock(&fs_info->unused_bgs_lock);
1463 }
1464 spin_unlock(&fs_info->unused_bgs_lock);
Johannes Thumshirnf3372062021-04-19 16:41:01 +09001465 mutex_unlock(&fs_info->reclaim_bgs_lock);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001466 return;
1467
1468flip_async:
1469 btrfs_end_transaction(trans);
Johannes Thumshirnf3372062021-04-19 16:41:01 +09001470 mutex_unlock(&fs_info->reclaim_bgs_lock);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001471 btrfs_put_block_group(block_group);
1472 btrfs_discard_punt_unused_bgs_list(fs_info);
Josef Bacike3e05202019-06-20 15:37:55 -04001473}
1474
David Sterba32da53862019-10-29 19:20:18 +01001475void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
Josef Bacike3e05202019-06-20 15:37:55 -04001476{
1477 struct btrfs_fs_info *fs_info = bg->fs_info;
1478
1479 spin_lock(&fs_info->unused_bgs_lock);
1480 if (list_empty(&bg->bg_list)) {
1481 btrfs_get_block_group(bg);
1482 trace_btrfs_add_unused_block_group(bg);
1483 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1484 }
1485 spin_unlock(&fs_info->unused_bgs_lock);
1486}
Josef Bacik4358d9632019-06-20 15:37:57 -04001487
Johannes Thumshirn18bb8bb2021-04-19 16:41:02 +09001488void btrfs_reclaim_bgs_work(struct work_struct *work)
1489{
1490 struct btrfs_fs_info *fs_info =
1491 container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
1492 struct btrfs_block_group *bg;
1493 struct btrfs_space_info *space_info;
1494 int ret;
1495
1496 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1497 return;
1498
1499 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE))
1500 return;
1501
1502 mutex_lock(&fs_info->reclaim_bgs_lock);
1503 spin_lock(&fs_info->unused_bgs_lock);
1504 while (!list_empty(&fs_info->reclaim_bgs)) {
1505 bg = list_first_entry(&fs_info->reclaim_bgs,
1506 struct btrfs_block_group,
1507 bg_list);
1508 list_del_init(&bg->bg_list);
1509
1510 space_info = bg->space_info;
1511 spin_unlock(&fs_info->unused_bgs_lock);
1512
1513 /* Don't race with allocators so take the groups_sem */
1514 down_write(&space_info->groups_sem);
1515
1516 spin_lock(&bg->lock);
1517 if (bg->reserved || bg->pinned || bg->ro) {
1518 /*
1519 * We want to bail if we made new allocations or have
1520 * outstanding allocations in this block group. We do
1521 * the ro check in case balance is currently acting on
1522 * this block group.
1523 */
1524 spin_unlock(&bg->lock);
1525 up_write(&space_info->groups_sem);
1526 goto next;
1527 }
1528 spin_unlock(&bg->lock);
1529
1530 /* Get out fast, in case we're unmounting the filesystem */
1531 if (btrfs_fs_closing(fs_info)) {
1532 up_write(&space_info->groups_sem);
1533 goto next;
1534 }
1535
1536 ret = inc_block_group_ro(bg, 0);
1537 up_write(&space_info->groups_sem);
1538 if (ret < 0)
1539 goto next;
1540
1541 btrfs_info(fs_info, "reclaiming chunk %llu with %llu%% used",
1542 bg->start, div_u64(bg->used * 100, bg->length));
1543 trace_btrfs_reclaim_block_group(bg);
1544 ret = btrfs_relocate_chunk(fs_info, bg->start);
1545 if (ret)
1546 btrfs_err(fs_info, "error relocating chunk %llu",
1547 bg->start);
1548
1549next:
1550 btrfs_put_block_group(bg);
1551 spin_lock(&fs_info->unused_bgs_lock);
1552 }
1553 spin_unlock(&fs_info->unused_bgs_lock);
1554 mutex_unlock(&fs_info->reclaim_bgs_lock);
1555 btrfs_exclop_finish(fs_info);
1556}
1557
1558void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
1559{
1560 spin_lock(&fs_info->unused_bgs_lock);
1561 if (!list_empty(&fs_info->reclaim_bgs))
1562 queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
1563 spin_unlock(&fs_info->unused_bgs_lock);
1564}
1565
1566void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
1567{
1568 struct btrfs_fs_info *fs_info = bg->fs_info;
1569
1570 spin_lock(&fs_info->unused_bgs_lock);
1571 if (list_empty(&bg->bg_list)) {
1572 btrfs_get_block_group(bg);
1573 trace_btrfs_add_reclaim_block_group(bg);
1574 list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
1575 }
1576 spin_unlock(&fs_info->unused_bgs_lock);
1577}
1578
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001579static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1580 struct btrfs_path *path)
1581{
1582 struct extent_map_tree *em_tree;
1583 struct extent_map *em;
1584 struct btrfs_block_group_item bg;
1585 struct extent_buffer *leaf;
1586 int slot;
1587 u64 flags;
1588 int ret = 0;
1589
1590 slot = path->slots[0];
1591 leaf = path->nodes[0];
1592
1593 em_tree = &fs_info->mapping_tree;
1594 read_lock(&em_tree->lock);
1595 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1596 read_unlock(&em_tree->lock);
1597 if (!em) {
1598 btrfs_err(fs_info,
1599 "logical %llu len %llu found bg but no related chunk",
1600 key->objectid, key->offset);
1601 return -ENOENT;
1602 }
1603
1604 if (em->start != key->objectid || em->len != key->offset) {
1605 btrfs_err(fs_info,
1606 "block group %llu len %llu mismatch with chunk %llu len %llu",
1607 key->objectid, key->offset, em->start, em->len);
1608 ret = -EUCLEAN;
1609 goto out_free_em;
1610 }
1611
1612 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1613 sizeof(bg));
1614 flags = btrfs_stack_block_group_flags(&bg) &
1615 BTRFS_BLOCK_GROUP_TYPE_MASK;
1616
1617 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1618 btrfs_err(fs_info,
1619"block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1620 key->objectid, key->offset, flags,
1621 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1622 ret = -EUCLEAN;
1623 }
1624
1625out_free_em:
1626 free_extent_map(em);
1627 return ret;
1628}
1629
Josef Bacik4358d9632019-06-20 15:37:57 -04001630static int find_first_block_group(struct btrfs_fs_info *fs_info,
1631 struct btrfs_path *path,
1632 struct btrfs_key *key)
1633{
1634 struct btrfs_root *root = fs_info->extent_root;
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001635 int ret;
Josef Bacik4358d9632019-06-20 15:37:57 -04001636 struct btrfs_key found_key;
1637 struct extent_buffer *leaf;
Josef Bacik4358d9632019-06-20 15:37:57 -04001638 int slot;
1639
1640 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1641 if (ret < 0)
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001642 return ret;
Josef Bacik4358d9632019-06-20 15:37:57 -04001643
1644 while (1) {
1645 slot = path->slots[0];
1646 leaf = path->nodes[0];
1647 if (slot >= btrfs_header_nritems(leaf)) {
1648 ret = btrfs_next_leaf(root, path);
1649 if (ret == 0)
1650 continue;
1651 if (ret < 0)
1652 goto out;
1653 break;
1654 }
1655 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1656
1657 if (found_key.objectid >= key->objectid &&
1658 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001659 ret = read_bg_from_eb(fs_info, &found_key, path);
1660 break;
Josef Bacik4358d9632019-06-20 15:37:57 -04001661 }
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001662
Josef Bacik4358d9632019-06-20 15:37:57 -04001663 path->slots[0]++;
1664 }
1665out:
1666 return ret;
1667}
1668
1669static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1670{
1671 u64 extra_flags = chunk_to_extended(flags) &
1672 BTRFS_EXTENDED_PROFILE_MASK;
1673
1674 write_seqlock(&fs_info->profiles_lock);
1675 if (flags & BTRFS_BLOCK_GROUP_DATA)
1676 fs_info->avail_data_alloc_bits |= extra_flags;
1677 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1678 fs_info->avail_metadata_alloc_bits |= extra_flags;
1679 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1680 fs_info->avail_system_alloc_bits |= extra_flags;
1681 write_sequnlock(&fs_info->profiles_lock);
1682}
1683
Nikolay Borisov96a14332019-12-10 19:57:51 +02001684/**
Nikolay Borisov9ee9b972021-01-22 11:57:58 +02001685 * Map a physical disk address to a list of logical addresses
1686 *
1687 * @fs_info: the filesystem
Nikolay Borisov96a14332019-12-10 19:57:51 +02001688 * @chunk_start: logical address of block group
Naohiro Aota138082f2021-02-04 19:22:02 +09001689 * @bdev: physical device to resolve, can be NULL to indicate any device
Nikolay Borisov96a14332019-12-10 19:57:51 +02001690 * @physical: physical address to map to logical addresses
1691 * @logical: return array of logical addresses which map to @physical
1692 * @naddrs: length of @logical
1693 * @stripe_len: size of IO stripe for the given block group
1694 *
1695 * Maps a particular @physical disk address to a list of @logical addresses.
1696 * Used primarily to exclude those portions of a block group that contain super
1697 * block copies.
1698 */
Nikolay Borisov96a14332019-12-10 19:57:51 +02001699int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
Naohiro Aota138082f2021-02-04 19:22:02 +09001700 struct block_device *bdev, u64 physical, u64 **logical,
1701 int *naddrs, int *stripe_len)
Nikolay Borisov96a14332019-12-10 19:57:51 +02001702{
1703 struct extent_map *em;
1704 struct map_lookup *map;
1705 u64 *buf;
1706 u64 bytenr;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001707 u64 data_stripe_length;
1708 u64 io_stripe_size;
1709 int i, nr = 0;
1710 int ret = 0;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001711
1712 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1713 if (IS_ERR(em))
1714 return -EIO;
1715
1716 map = em->map_lookup;
Nikolay Borisov9e22b922020-04-03 16:40:34 +03001717 data_stripe_length = em->orig_block_len;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001718 io_stripe_size = map->stripe_len;
Naohiro Aota138082f2021-02-04 19:22:02 +09001719 chunk_start = em->start;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001720
Nikolay Borisov9e22b922020-04-03 16:40:34 +03001721 /* For RAID5/6 adjust to a full IO stripe length */
1722 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001723 io_stripe_size = map->stripe_len * nr_data_stripes(map);
Nikolay Borisov96a14332019-12-10 19:57:51 +02001724
1725 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001726 if (!buf) {
1727 ret = -ENOMEM;
1728 goto out;
1729 }
Nikolay Borisov96a14332019-12-10 19:57:51 +02001730
1731 for (i = 0; i < map->num_stripes; i++) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001732 bool already_inserted = false;
1733 u64 stripe_nr;
Naohiro Aota138082f2021-02-04 19:22:02 +09001734 u64 offset;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001735 int j;
1736
1737 if (!in_range(physical, map->stripes[i].physical,
1738 data_stripe_length))
Nikolay Borisov96a14332019-12-10 19:57:51 +02001739 continue;
1740
Naohiro Aota138082f2021-02-04 19:22:02 +09001741 if (bdev && map->stripes[i].dev->bdev != bdev)
1742 continue;
1743
Nikolay Borisov96a14332019-12-10 19:57:51 +02001744 stripe_nr = physical - map->stripes[i].physical;
Naohiro Aota138082f2021-02-04 19:22:02 +09001745 stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
Nikolay Borisov96a14332019-12-10 19:57:51 +02001746
1747 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1748 stripe_nr = stripe_nr * map->num_stripes + i;
1749 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1750 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1751 stripe_nr = stripe_nr * map->num_stripes + i;
1752 }
1753 /*
1754 * The remaining case would be for RAID56, multiply by
1755 * nr_data_stripes(). Alternatively, just use rmap_len below
1756 * instead of map->stripe_len
1757 */
1758
Naohiro Aota138082f2021-02-04 19:22:02 +09001759 bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001760
1761 /* Ensure we don't add duplicate addresses */
Nikolay Borisov96a14332019-12-10 19:57:51 +02001762 for (j = 0; j < nr; j++) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001763 if (buf[j] == bytenr) {
1764 already_inserted = true;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001765 break;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001766 }
Nikolay Borisov96a14332019-12-10 19:57:51 +02001767 }
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001768
1769 if (!already_inserted)
Nikolay Borisov96a14332019-12-10 19:57:51 +02001770 buf[nr++] = bytenr;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001771 }
1772
1773 *logical = buf;
1774 *naddrs = nr;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001775 *stripe_len = io_stripe_size;
1776out:
Nikolay Borisov96a14332019-12-10 19:57:51 +02001777 free_extent_map(em);
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001778 return ret;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001779}
1780
David Sterba32da53862019-10-29 19:20:18 +01001781static int exclude_super_stripes(struct btrfs_block_group *cache)
Josef Bacik4358d9632019-06-20 15:37:57 -04001782{
1783 struct btrfs_fs_info *fs_info = cache->fs_info;
Naohiro Aota12659252020-11-10 20:26:14 +09001784 const bool zoned = btrfs_is_zoned(fs_info);
Josef Bacik4358d9632019-06-20 15:37:57 -04001785 u64 bytenr;
1786 u64 *logical;
1787 int stripe_len;
1788 int i, nr, ret;
1789
David Sterbab3470b52019-10-23 18:48:22 +02001790 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1791 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
Josef Bacik4358d9632019-06-20 15:37:57 -04001792 cache->bytes_super += stripe_len;
David Sterbab3470b52019-10-23 18:48:22 +02001793 ret = btrfs_add_excluded_extent(fs_info, cache->start,
Josef Bacik4358d9632019-06-20 15:37:57 -04001794 stripe_len);
1795 if (ret)
1796 return ret;
1797 }
1798
1799 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1800 bytenr = btrfs_sb_offset(i);
Naohiro Aota138082f2021-02-04 19:22:02 +09001801 ret = btrfs_rmap_block(fs_info, cache->start, NULL,
Josef Bacik4358d9632019-06-20 15:37:57 -04001802 bytenr, &logical, &nr, &stripe_len);
1803 if (ret)
1804 return ret;
1805
Naohiro Aota12659252020-11-10 20:26:14 +09001806 /* Shouldn't have super stripes in sequential zones */
1807 if (zoned && nr) {
1808 btrfs_err(fs_info,
1809 "zoned: block group %llu must not contain super block",
1810 cache->start);
1811 return -EUCLEAN;
1812 }
1813
Josef Bacik4358d9632019-06-20 15:37:57 -04001814 while (nr--) {
Nikolay Borisov96f9b0f2020-04-03 16:40:35 +03001815 u64 len = min_t(u64, stripe_len,
1816 cache->start + cache->length - logical[nr]);
Josef Bacik4358d9632019-06-20 15:37:57 -04001817
1818 cache->bytes_super += len;
Nikolay Borisov96f9b0f2020-04-03 16:40:35 +03001819 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1820 len);
Josef Bacik4358d9632019-06-20 15:37:57 -04001821 if (ret) {
1822 kfree(logical);
1823 return ret;
1824 }
1825 }
1826
1827 kfree(logical);
1828 }
1829 return 0;
1830}
1831
David Sterba32da53862019-10-29 19:20:18 +01001832static void link_block_group(struct btrfs_block_group *cache)
Josef Bacik4358d9632019-06-20 15:37:57 -04001833{
1834 struct btrfs_space_info *space_info = cache->space_info;
1835 int index = btrfs_bg_flags_to_raid_index(cache->flags);
Josef Bacik4358d9632019-06-20 15:37:57 -04001836
1837 down_write(&space_info->groups_sem);
Josef Bacik4358d9632019-06-20 15:37:57 -04001838 list_add_tail(&cache->list, &space_info->block_groups[index]);
1839 up_write(&space_info->groups_sem);
Josef Bacik4358d9632019-06-20 15:37:57 -04001840}
1841
David Sterba32da53862019-10-29 19:20:18 +01001842static struct btrfs_block_group *btrfs_create_block_group_cache(
Qu Wenruo9afc6642020-05-05 07:58:20 +08001843 struct btrfs_fs_info *fs_info, u64 start)
Josef Bacik4358d9632019-06-20 15:37:57 -04001844{
David Sterba32da53862019-10-29 19:20:18 +01001845 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04001846
1847 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1848 if (!cache)
1849 return NULL;
1850
1851 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1852 GFP_NOFS);
1853 if (!cache->free_space_ctl) {
1854 kfree(cache);
1855 return NULL;
1856 }
1857
David Sterbab3470b52019-10-23 18:48:22 +02001858 cache->start = start;
Josef Bacik4358d9632019-06-20 15:37:57 -04001859
1860 cache->fs_info = fs_info;
1861 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
Josef Bacik4358d9632019-06-20 15:37:57 -04001862
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001863 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1864
Josef Bacik48aaeeb2020-07-06 09:14:11 -04001865 refcount_set(&cache->refs, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04001866 spin_lock_init(&cache->lock);
1867 init_rwsem(&cache->data_rwsem);
1868 INIT_LIST_HEAD(&cache->list);
1869 INIT_LIST_HEAD(&cache->cluster_list);
1870 INIT_LIST_HEAD(&cache->bg_list);
1871 INIT_LIST_HEAD(&cache->ro_list);
Dennis Zhoub0643e52019-12-13 16:22:14 -08001872 INIT_LIST_HEAD(&cache->discard_list);
Josef Bacik4358d9632019-06-20 15:37:57 -04001873 INIT_LIST_HEAD(&cache->dirty_list);
1874 INIT_LIST_HEAD(&cache->io_list);
Josef Bacikcd799092020-10-23 09:58:08 -04001875 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
Filipe Manana6b7304a2020-05-08 11:01:47 +01001876 atomic_set(&cache->frozen, 0);
Josef Bacik4358d9632019-06-20 15:37:57 -04001877 mutex_init(&cache->free_space_lock);
1878 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1879
1880 return cache;
1881}
1882
1883/*
1884 * Iterate all chunks and verify that each of them has the corresponding block
1885 * group
1886 */
1887static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1888{
1889 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1890 struct extent_map *em;
David Sterba32da53862019-10-29 19:20:18 +01001891 struct btrfs_block_group *bg;
Josef Bacik4358d9632019-06-20 15:37:57 -04001892 u64 start = 0;
1893 int ret = 0;
1894
1895 while (1) {
1896 read_lock(&map_tree->lock);
1897 /*
1898 * lookup_extent_mapping will return the first extent map
1899 * intersecting the range, so setting @len to 1 is enough to
1900 * get the first chunk.
1901 */
1902 em = lookup_extent_mapping(map_tree, start, 1);
1903 read_unlock(&map_tree->lock);
1904 if (!em)
1905 break;
1906
1907 bg = btrfs_lookup_block_group(fs_info, em->start);
1908 if (!bg) {
1909 btrfs_err(fs_info,
1910 "chunk start=%llu len=%llu doesn't have corresponding block group",
1911 em->start, em->len);
1912 ret = -EUCLEAN;
1913 free_extent_map(em);
1914 break;
1915 }
David Sterbab3470b52019-10-23 18:48:22 +02001916 if (bg->start != em->start || bg->length != em->len ||
Josef Bacik4358d9632019-06-20 15:37:57 -04001917 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1918 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1919 btrfs_err(fs_info,
1920"chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1921 em->start, em->len,
1922 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
David Sterbab3470b52019-10-23 18:48:22 +02001923 bg->start, bg->length,
Josef Bacik4358d9632019-06-20 15:37:57 -04001924 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1925 ret = -EUCLEAN;
1926 free_extent_map(em);
1927 btrfs_put_block_group(bg);
1928 break;
1929 }
1930 start = em->start + em->len;
1931 free_extent_map(em);
1932 btrfs_put_block_group(bg);
1933 }
1934 return ret;
1935}
1936
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001937static int read_one_block_group(struct btrfs_fs_info *info,
Johannes Thumshirn4afd2fe2021-02-04 19:21:44 +09001938 struct btrfs_block_group_item *bgi,
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001939 const struct btrfs_key *key,
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001940 int need_clear)
1941{
David Sterba32da53862019-10-29 19:20:18 +01001942 struct btrfs_block_group *cache;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001943 struct btrfs_space_info *space_info;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001944 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001945 int ret;
1946
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001947 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001948
Qu Wenruo9afc6642020-05-05 07:58:20 +08001949 cache = btrfs_create_block_group_cache(info, key->objectid);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001950 if (!cache)
1951 return -ENOMEM;
1952
Johannes Thumshirn4afd2fe2021-02-04 19:21:44 +09001953 cache->length = key->offset;
1954 cache->used = btrfs_stack_block_group_used(bgi);
1955 cache->flags = btrfs_stack_block_group_flags(bgi);
Qu Wenruo9afc6642020-05-05 07:58:20 +08001956
Marcos Paulo de Souzae3e39c72020-08-21 11:54:44 -03001957 set_free_space_tree_thresholds(cache);
1958
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001959 if (need_clear) {
1960 /*
1961 * When we mount with old space cache, we need to
1962 * set BTRFS_DC_CLEAR and set dirty flag.
1963 *
1964 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1965 * truncate the old free space cache inode and
1966 * setup a new one.
1967 * b) Setting 'dirty flag' makes sure that we flush
1968 * the new space cache info onto disk.
1969 */
1970 if (btrfs_test_opt(info, SPACE_CACHE))
1971 cache->disk_cache_state = BTRFS_DC_CLEAR;
1972 }
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001973 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1974 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1975 btrfs_err(info,
1976"bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1977 cache->start);
1978 ret = -EINVAL;
1979 goto error;
1980 }
1981
Naohiro Aotaa94794d2021-02-04 19:21:51 +09001982 ret = btrfs_load_block_group_zone_info(cache, false);
Naohiro Aota08e11a32021-02-04 19:21:50 +09001983 if (ret) {
1984 btrfs_err(info, "zoned: failed to load zone info of bg %llu",
1985 cache->start);
1986 goto error;
1987 }
1988
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001989 /*
1990 * We need to exclude the super stripes now so that the space info has
1991 * super bytes accounted for, otherwise we'll think we have more space
1992 * than we actually do.
1993 */
1994 ret = exclude_super_stripes(cache);
1995 if (ret) {
1996 /* We may have excluded something, so call this just in case. */
1997 btrfs_free_excluded_extents(cache);
1998 goto error;
1999 }
2000
2001 /*
Naohiro Aota169e0da2021-02-04 19:21:52 +09002002 * For zoned filesystem, space after the allocation offset is the only
2003 * free space for a block group. So, we don't need any caching work.
2004 * btrfs_calc_zone_unusable() will set the amount of free space and
2005 * zone_unusable space.
2006 *
2007 * For regular filesystem, check for two cases, either we are full, and
2008 * therefore don't need to bother with the caching work since we won't
2009 * find any space, or we are empty, and we can just add all the space
2010 * in and be done with it. This saves us _a_lot_ of time, particularly
2011 * in the full case.
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002012 */
Naohiro Aota169e0da2021-02-04 19:21:52 +09002013 if (btrfs_is_zoned(info)) {
2014 btrfs_calc_zone_unusable(cache);
2015 } else if (cache->length == cache->used) {
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002016 cache->last_byte_to_unpin = (u64)-1;
2017 cache->cached = BTRFS_CACHE_FINISHED;
2018 btrfs_free_excluded_extents(cache);
2019 } else if (cache->used == 0) {
2020 cache->last_byte_to_unpin = (u64)-1;
2021 cache->cached = BTRFS_CACHE_FINISHED;
Qu Wenruo9afc6642020-05-05 07:58:20 +08002022 add_new_free_space(cache, cache->start,
2023 cache->start + cache->length);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002024 btrfs_free_excluded_extents(cache);
2025 }
2026
2027 ret = btrfs_add_block_group_cache(info, cache);
2028 if (ret) {
2029 btrfs_remove_free_space_cache(cache);
2030 goto error;
2031 }
2032 trace_btrfs_add_block_group(info, cache, 0);
Qu Wenruo9afc6642020-05-05 07:58:20 +08002033 btrfs_update_space_info(info, cache->flags, cache->length,
Naohiro Aota169e0da2021-02-04 19:21:52 +09002034 cache->used, cache->bytes_super,
2035 cache->zone_unusable, &space_info);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002036
2037 cache->space_info = space_info;
2038
2039 link_block_group(cache);
2040
2041 set_avail_alloc_bits(info, cache->flags);
2042 if (btrfs_chunk_readonly(info, cache->start)) {
2043 inc_block_group_ro(cache, 1);
2044 } else if (cache->used == 0) {
2045 ASSERT(list_empty(&cache->bg_list));
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08002046 if (btrfs_test_opt(info, DISCARD_ASYNC))
2047 btrfs_discard_queue_work(&info->discard_ctl, cache);
2048 else
2049 btrfs_mark_bg_unused(cache);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002050 }
2051 return 0;
2052error:
2053 btrfs_put_block_group(cache);
2054 return ret;
2055}
2056
Josef Bacik42437a62020-10-16 11:29:18 -04002057static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
2058{
2059 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
2060 struct btrfs_space_info *space_info;
2061 struct rb_node *node;
2062 int ret = 0;
2063
2064 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
2065 struct extent_map *em;
2066 struct map_lookup *map;
2067 struct btrfs_block_group *bg;
2068
2069 em = rb_entry(node, struct extent_map, rb_node);
2070 map = em->map_lookup;
2071 bg = btrfs_create_block_group_cache(fs_info, em->start);
2072 if (!bg) {
2073 ret = -ENOMEM;
2074 break;
2075 }
2076
2077 /* Fill dummy cache as FULL */
2078 bg->length = em->len;
2079 bg->flags = map->type;
2080 bg->last_byte_to_unpin = (u64)-1;
2081 bg->cached = BTRFS_CACHE_FINISHED;
2082 bg->used = em->len;
2083 bg->flags = map->type;
2084 ret = btrfs_add_block_group_cache(fs_info, bg);
2085 if (ret) {
2086 btrfs_remove_free_space_cache(bg);
2087 btrfs_put_block_group(bg);
2088 break;
2089 }
2090 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
Naohiro Aota169e0da2021-02-04 19:21:52 +09002091 0, 0, &space_info);
Josef Bacik42437a62020-10-16 11:29:18 -04002092 bg->space_info = space_info;
2093 link_block_group(bg);
2094
2095 set_avail_alloc_bits(fs_info, bg->flags);
2096 }
2097 if (!ret)
2098 btrfs_init_global_block_rsv(fs_info);
2099 return ret;
2100}
2101
Josef Bacik4358d9632019-06-20 15:37:57 -04002102int btrfs_read_block_groups(struct btrfs_fs_info *info)
2103{
2104 struct btrfs_path *path;
2105 int ret;
David Sterba32da53862019-10-29 19:20:18 +01002106 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04002107 struct btrfs_space_info *space_info;
2108 struct btrfs_key key;
Josef Bacik4358d9632019-06-20 15:37:57 -04002109 int need_clear = 0;
2110 u64 cache_gen;
Josef Bacik4358d9632019-06-20 15:37:57 -04002111
Josef Bacik42437a62020-10-16 11:29:18 -04002112 if (!info->extent_root)
2113 return fill_dummy_bgs(info);
2114
Josef Bacik4358d9632019-06-20 15:37:57 -04002115 key.objectid = 0;
2116 key.offset = 0;
2117 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2118 path = btrfs_alloc_path();
2119 if (!path)
2120 return -ENOMEM;
Josef Bacik4358d9632019-06-20 15:37:57 -04002121
2122 cache_gen = btrfs_super_cache_generation(info->super_copy);
2123 if (btrfs_test_opt(info, SPACE_CACHE) &&
2124 btrfs_super_generation(info->super_copy) != cache_gen)
2125 need_clear = 1;
2126 if (btrfs_test_opt(info, CLEAR_CACHE))
2127 need_clear = 1;
2128
2129 while (1) {
Johannes Thumshirn4afd2fe2021-02-04 19:21:44 +09002130 struct btrfs_block_group_item bgi;
2131 struct extent_buffer *leaf;
2132 int slot;
2133
Josef Bacik4358d9632019-06-20 15:37:57 -04002134 ret = find_first_block_group(info, path, &key);
2135 if (ret > 0)
2136 break;
2137 if (ret != 0)
2138 goto error;
2139
Johannes Thumshirn4afd2fe2021-02-04 19:21:44 +09002140 leaf = path->nodes[0];
2141 slot = path->slots[0];
2142
2143 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2144 sizeof(bgi));
2145
2146 btrfs_item_key_to_cpu(leaf, &key, slot);
2147 btrfs_release_path(path);
2148 ret = read_one_block_group(info, &bgi, &key, need_clear);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002149 if (ret < 0)
Josef Bacik4358d9632019-06-20 15:37:57 -04002150 goto error;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002151 key.objectid += key.offset;
2152 key.offset = 0;
Josef Bacik4358d9632019-06-20 15:37:57 -04002153 }
Josef Bacik7837fa82020-10-14 17:00:51 -04002154 btrfs_release_path(path);
Josef Bacik4358d9632019-06-20 15:37:57 -04002155
Josef Bacik72804902020-09-01 17:40:37 -04002156 list_for_each_entry(space_info, &info->space_info, list) {
Josef Bacik49ea1122020-09-01 17:40:38 -04002157 int i;
2158
2159 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2160 if (list_empty(&space_info->block_groups[i]))
2161 continue;
2162 cache = list_first_entry(&space_info->block_groups[i],
2163 struct btrfs_block_group,
2164 list);
2165 btrfs_sysfs_add_block_group_type(cache);
2166 }
2167
Josef Bacik4358d9632019-06-20 15:37:57 -04002168 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2169 (BTRFS_BLOCK_GROUP_RAID10 |
2170 BTRFS_BLOCK_GROUP_RAID1_MASK |
2171 BTRFS_BLOCK_GROUP_RAID56_MASK |
2172 BTRFS_BLOCK_GROUP_DUP)))
2173 continue;
2174 /*
2175 * Avoid allocating from un-mirrored block group if there are
2176 * mirrored block groups.
2177 */
2178 list_for_each_entry(cache,
2179 &space_info->block_groups[BTRFS_RAID_RAID0],
2180 list)
Josef Bacike11c0402019-06-20 15:38:07 -04002181 inc_block_group_ro(cache, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04002182 list_for_each_entry(cache,
2183 &space_info->block_groups[BTRFS_RAID_SINGLE],
2184 list)
Josef Bacike11c0402019-06-20 15:38:07 -04002185 inc_block_group_ro(cache, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04002186 }
2187
2188 btrfs_init_global_block_rsv(info);
2189 ret = check_chunk_block_group_mappings(info);
2190error:
2191 btrfs_free_path(path);
2192 return ret;
2193}
2194
Qu Wenruo97f47282020-05-05 07:58:22 +08002195static int insert_block_group_item(struct btrfs_trans_handle *trans,
2196 struct btrfs_block_group *block_group)
2197{
2198 struct btrfs_fs_info *fs_info = trans->fs_info;
2199 struct btrfs_block_group_item bgi;
2200 struct btrfs_root *root;
2201 struct btrfs_key key;
2202
2203 spin_lock(&block_group->lock);
2204 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2205 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2206 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2207 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2208 key.objectid = block_group->start;
2209 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2210 key.offset = block_group->length;
2211 spin_unlock(&block_group->lock);
2212
2213 root = fs_info->extent_root;
2214 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2215}
2216
Josef Bacik4358d9632019-06-20 15:37:57 -04002217void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2218{
2219 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002220 struct btrfs_block_group *block_group;
Josef Bacik4358d9632019-06-20 15:37:57 -04002221 int ret = 0;
2222
2223 if (!trans->can_flush_pending_bgs)
2224 return;
2225
2226 while (!list_empty(&trans->new_bgs)) {
Josef Bacik49ea1122020-09-01 17:40:38 -04002227 int index;
2228
Josef Bacik4358d9632019-06-20 15:37:57 -04002229 block_group = list_first_entry(&trans->new_bgs,
David Sterba32da53862019-10-29 19:20:18 +01002230 struct btrfs_block_group,
Josef Bacik4358d9632019-06-20 15:37:57 -04002231 bg_list);
2232 if (ret)
2233 goto next;
2234
Josef Bacik49ea1122020-09-01 17:40:38 -04002235 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2236
Qu Wenruo97f47282020-05-05 07:58:22 +08002237 ret = insert_block_group_item(trans, block_group);
Josef Bacik4358d9632019-06-20 15:37:57 -04002238 if (ret)
2239 btrfs_abort_transaction(trans, ret);
Qu Wenruo97f47282020-05-05 07:58:22 +08002240 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2241 block_group->length);
Josef Bacik4358d9632019-06-20 15:37:57 -04002242 if (ret)
2243 btrfs_abort_transaction(trans, ret);
2244 add_block_group_free_space(trans, block_group);
Josef Bacik49ea1122020-09-01 17:40:38 -04002245
2246 /*
2247 * If we restriped during balance, we may have added a new raid
2248 * type, so now add the sysfs entries when it is safe to do so.
2249 * We don't have to worry about locking here as it's handled in
2250 * btrfs_sysfs_add_block_group_type.
2251 */
2252 if (block_group->space_info->block_group_kobjs[index] == NULL)
2253 btrfs_sysfs_add_block_group_type(block_group);
2254
Josef Bacik4358d9632019-06-20 15:37:57 -04002255 /* Already aborted the transaction if it failed. */
2256next:
2257 btrfs_delayed_refs_rsv_release(fs_info, 1);
2258 list_del_init(&block_group->bg_list);
2259 }
2260 btrfs_trans_release_chunk_metadata(trans);
2261}
2262
2263int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2264 u64 type, u64 chunk_offset, u64 size)
2265{
2266 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002267 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04002268 int ret;
2269
2270 btrfs_set_log_full_commit(trans);
2271
Qu Wenruo9afc6642020-05-05 07:58:20 +08002272 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
Josef Bacik4358d9632019-06-20 15:37:57 -04002273 if (!cache)
2274 return -ENOMEM;
2275
Qu Wenruo9afc6642020-05-05 07:58:20 +08002276 cache->length = size;
Marcos Paulo de Souzae3e39c72020-08-21 11:54:44 -03002277 set_free_space_tree_thresholds(cache);
David Sterbabf38be62019-10-23 18:48:11 +02002278 cache->used = bytes_used;
Josef Bacik4358d9632019-06-20 15:37:57 -04002279 cache->flags = type;
2280 cache->last_byte_to_unpin = (u64)-1;
2281 cache->cached = BTRFS_CACHE_FINISHED;
Boris Burkov997e3e22020-11-18 15:06:18 -08002282 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2283 cache->needs_free_space = 1;
Naohiro Aota08e11a32021-02-04 19:21:50 +09002284
Naohiro Aotaa94794d2021-02-04 19:21:51 +09002285 ret = btrfs_load_block_group_zone_info(cache, true);
Naohiro Aota08e11a32021-02-04 19:21:50 +09002286 if (ret) {
2287 btrfs_put_block_group(cache);
2288 return ret;
2289 }
2290
Josef Bacik4358d9632019-06-20 15:37:57 -04002291 ret = exclude_super_stripes(cache);
2292 if (ret) {
2293 /* We may have excluded something, so call this just in case */
2294 btrfs_free_excluded_extents(cache);
2295 btrfs_put_block_group(cache);
2296 return ret;
2297 }
2298
2299 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2300
2301 btrfs_free_excluded_extents(cache);
2302
2303#ifdef CONFIG_BTRFS_DEBUG
2304 if (btrfs_should_fragment_free_space(cache)) {
2305 u64 new_bytes_used = size - bytes_used;
2306
2307 bytes_used += new_bytes_used >> 1;
Josef Bacike11c0402019-06-20 15:38:07 -04002308 fragment_free_space(cache);
Josef Bacik4358d9632019-06-20 15:37:57 -04002309 }
2310#endif
2311 /*
2312 * Ensure the corresponding space_info object is created and
2313 * assigned to our block group. We want our bg to be added to the rbtree
2314 * with its ->space_info set.
2315 */
2316 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2317 ASSERT(cache->space_info);
2318
2319 ret = btrfs_add_block_group_cache(fs_info, cache);
2320 if (ret) {
2321 btrfs_remove_free_space_cache(cache);
2322 btrfs_put_block_group(cache);
2323 return ret;
2324 }
2325
2326 /*
2327 * Now that our block group has its ->space_info set and is inserted in
2328 * the rbtree, update the space info's counters.
2329 */
2330 trace_btrfs_add_block_group(fs_info, cache, 1);
2331 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
Naohiro Aota169e0da2021-02-04 19:21:52 +09002332 cache->bytes_super, 0, &cache->space_info);
Josef Bacik4358d9632019-06-20 15:37:57 -04002333 btrfs_update_global_block_rsv(fs_info);
2334
2335 link_block_group(cache);
2336
2337 list_add_tail(&cache->bg_list, &trans->new_bgs);
2338 trans->delayed_ref_updates++;
2339 btrfs_update_delayed_refs_rsv(trans);
2340
2341 set_avail_alloc_bits(fs_info, type);
2342 return 0;
2343}
Josef Bacik26ce2092019-06-20 15:37:59 -04002344
Qu Wenruob12de522019-11-15 10:09:00 +08002345/*
2346 * Mark one block group RO, can be called several times for the same block
2347 * group.
2348 *
2349 * @cache: the destination block group
2350 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2351 * ensure we still have some free space after marking this
2352 * block group RO.
2353 */
2354int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2355 bool do_chunk_alloc)
Josef Bacik26ce2092019-06-20 15:37:59 -04002356{
2357 struct btrfs_fs_info *fs_info = cache->fs_info;
2358 struct btrfs_trans_handle *trans;
2359 u64 alloc_flags;
2360 int ret;
Nikolay Borisovb6e9f162021-02-17 15:12:50 +02002361 bool dirty_bg_running;
Josef Bacik26ce2092019-06-20 15:37:59 -04002362
Nikolay Borisovb6e9f162021-02-17 15:12:50 +02002363 do {
2364 trans = btrfs_join_transaction(fs_info->extent_root);
2365 if (IS_ERR(trans))
2366 return PTR_ERR(trans);
Josef Bacik26ce2092019-06-20 15:37:59 -04002367
Nikolay Borisovb6e9f162021-02-17 15:12:50 +02002368 dirty_bg_running = false;
Josef Bacik26ce2092019-06-20 15:37:59 -04002369
Nikolay Borisovb6e9f162021-02-17 15:12:50 +02002370 /*
2371 * We're not allowed to set block groups readonly after the dirty
2372 * block group cache has started writing. If it already started,
2373 * back off and let this transaction commit.
2374 */
2375 mutex_lock(&fs_info->ro_block_group_mutex);
2376 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2377 u64 transid = trans->transid;
Josef Bacik26ce2092019-06-20 15:37:59 -04002378
Nikolay Borisovb6e9f162021-02-17 15:12:50 +02002379 mutex_unlock(&fs_info->ro_block_group_mutex);
2380 btrfs_end_transaction(trans);
2381
2382 ret = btrfs_wait_for_commit(fs_info, transid);
2383 if (ret)
2384 return ret;
2385 dirty_bg_running = true;
2386 }
2387 } while (dirty_bg_running);
Josef Bacik26ce2092019-06-20 15:37:59 -04002388
Qu Wenruob12de522019-11-15 10:09:00 +08002389 if (do_chunk_alloc) {
Josef Bacik26ce2092019-06-20 15:37:59 -04002390 /*
Qu Wenruob12de522019-11-15 10:09:00 +08002391 * If we are changing raid levels, try to allocate a
2392 * corresponding block group with the new raid level.
Josef Bacik26ce2092019-06-20 15:37:59 -04002393 */
Josef Bacik349e1202020-07-21 10:48:45 -04002394 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
Qu Wenruob12de522019-11-15 10:09:00 +08002395 if (alloc_flags != cache->flags) {
2396 ret = btrfs_chunk_alloc(trans, alloc_flags,
2397 CHUNK_ALLOC_FORCE);
2398 /*
2399 * ENOSPC is allowed here, we may have enough space
2400 * already allocated at the new raid level to carry on
2401 */
2402 if (ret == -ENOSPC)
2403 ret = 0;
2404 if (ret < 0)
2405 goto out;
2406 }
Josef Bacik26ce2092019-06-20 15:37:59 -04002407 }
2408
Josef Bacika7a63acc2020-01-17 09:07:38 -05002409 ret = inc_block_group_ro(cache, 0);
Filipe Manana195a49e2021-02-05 12:55:37 +00002410 if (!do_chunk_alloc || ret == -ETXTBSY)
Qu Wenruob12de522019-11-15 10:09:00 +08002411 goto unlock_out;
Josef Bacik26ce2092019-06-20 15:37:59 -04002412 if (!ret)
2413 goto out;
2414 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2415 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2416 if (ret < 0)
2417 goto out;
Josef Bacike11c0402019-06-20 15:38:07 -04002418 ret = inc_block_group_ro(cache, 0);
Filipe Manana195a49e2021-02-05 12:55:37 +00002419 if (ret == -ETXTBSY)
2420 goto unlock_out;
Josef Bacik26ce2092019-06-20 15:37:59 -04002421out:
2422 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
Josef Bacik349e1202020-07-21 10:48:45 -04002423 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
Josef Bacik26ce2092019-06-20 15:37:59 -04002424 mutex_lock(&fs_info->chunk_mutex);
2425 check_system_chunk(trans, alloc_flags);
2426 mutex_unlock(&fs_info->chunk_mutex);
2427 }
Qu Wenruob12de522019-11-15 10:09:00 +08002428unlock_out:
Josef Bacik26ce2092019-06-20 15:37:59 -04002429 mutex_unlock(&fs_info->ro_block_group_mutex);
2430
2431 btrfs_end_transaction(trans);
2432 return ret;
2433}
2434
David Sterba32da53862019-10-29 19:20:18 +01002435void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
Josef Bacik26ce2092019-06-20 15:37:59 -04002436{
2437 struct btrfs_space_info *sinfo = cache->space_info;
2438 u64 num_bytes;
2439
2440 BUG_ON(!cache->ro);
2441
2442 spin_lock(&sinfo->lock);
2443 spin_lock(&cache->lock);
2444 if (!--cache->ro) {
Naohiro Aota169e0da2021-02-04 19:21:52 +09002445 if (btrfs_is_zoned(cache->fs_info)) {
2446 /* Migrate zone_unusable bytes back */
2447 cache->zone_unusable = cache->alloc_offset - cache->used;
2448 sinfo->bytes_zone_unusable += cache->zone_unusable;
2449 sinfo->bytes_readonly -= cache->zone_unusable;
2450 }
Naohiro Aotaf9f28e52021-06-17 13:56:18 +09002451 num_bytes = cache->length - cache->reserved -
2452 cache->pinned - cache->bytes_super -
2453 cache->zone_unusable - cache->used;
2454 sinfo->bytes_readonly -= num_bytes;
Josef Bacik26ce2092019-06-20 15:37:59 -04002455 list_del_init(&cache->ro_list);
2456 }
2457 spin_unlock(&cache->lock);
2458 spin_unlock(&sinfo->lock);
2459}
Josef Bacik77745c02019-06-20 15:38:00 -04002460
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002461static int update_block_group_item(struct btrfs_trans_handle *trans,
2462 struct btrfs_path *path,
2463 struct btrfs_block_group *cache)
Josef Bacik77745c02019-06-20 15:38:00 -04002464{
2465 struct btrfs_fs_info *fs_info = trans->fs_info;
2466 int ret;
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002467 struct btrfs_root *root = fs_info->extent_root;
Josef Bacik77745c02019-06-20 15:38:00 -04002468 unsigned long bi;
2469 struct extent_buffer *leaf;
David Sterbabf38be62019-10-23 18:48:11 +02002470 struct btrfs_block_group_item bgi;
David Sterbab3470b52019-10-23 18:48:22 +02002471 struct btrfs_key key;
Josef Bacik77745c02019-06-20 15:38:00 -04002472
David Sterbab3470b52019-10-23 18:48:22 +02002473 key.objectid = cache->start;
2474 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2475 key.offset = cache->length;
2476
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002477 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
Josef Bacik77745c02019-06-20 15:38:00 -04002478 if (ret) {
2479 if (ret > 0)
2480 ret = -ENOENT;
2481 goto fail;
2482 }
2483
2484 leaf = path->nodes[0];
2485 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
David Sterbade0dc452019-10-23 18:48:18 +02002486 btrfs_set_stack_block_group_used(&bgi, cache->used);
2487 btrfs_set_stack_block_group_chunk_objectid(&bgi,
David Sterba3d976382019-10-23 18:48:15 +02002488 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
David Sterbade0dc452019-10-23 18:48:18 +02002489 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
David Sterbabf38be62019-10-23 18:48:11 +02002490 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
Josef Bacik77745c02019-06-20 15:38:00 -04002491 btrfs_mark_buffer_dirty(leaf);
2492fail:
2493 btrfs_release_path(path);
2494 return ret;
2495
2496}
2497
David Sterba32da53862019-10-29 19:20:18 +01002498static int cache_save_setup(struct btrfs_block_group *block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002499 struct btrfs_trans_handle *trans,
2500 struct btrfs_path *path)
2501{
2502 struct btrfs_fs_info *fs_info = block_group->fs_info;
2503 struct btrfs_root *root = fs_info->tree_root;
2504 struct inode *inode = NULL;
2505 struct extent_changeset *data_reserved = NULL;
2506 u64 alloc_hint = 0;
2507 int dcs = BTRFS_DC_ERROR;
Qu Wenruo0044ae12021-04-13 14:23:14 +08002508 u64 cache_size = 0;
Josef Bacik77745c02019-06-20 15:38:00 -04002509 int retries = 0;
2510 int ret = 0;
2511
Boris Burkovaf456a22020-11-18 15:06:26 -08002512 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2513 return 0;
2514
Josef Bacik77745c02019-06-20 15:38:00 -04002515 /*
2516 * If this block group is smaller than 100 megs don't bother caching the
2517 * block group.
2518 */
David Sterbab3470b52019-10-23 18:48:22 +02002519 if (block_group->length < (100 * SZ_1M)) {
Josef Bacik77745c02019-06-20 15:38:00 -04002520 spin_lock(&block_group->lock);
2521 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2522 spin_unlock(&block_group->lock);
2523 return 0;
2524 }
2525
David Sterbabf31f872020-02-05 17:34:34 +01002526 if (TRANS_ABORTED(trans))
Josef Bacik77745c02019-06-20 15:38:00 -04002527 return 0;
2528again:
2529 inode = lookup_free_space_inode(block_group, path);
2530 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2531 ret = PTR_ERR(inode);
2532 btrfs_release_path(path);
2533 goto out;
2534 }
2535
2536 if (IS_ERR(inode)) {
2537 BUG_ON(retries);
2538 retries++;
2539
2540 if (block_group->ro)
2541 goto out_free;
2542
2543 ret = create_free_space_inode(trans, block_group, path);
2544 if (ret)
2545 goto out_free;
2546 goto again;
2547 }
2548
2549 /*
2550 * We want to set the generation to 0, that way if anything goes wrong
2551 * from here on out we know not to trust this cache when we load up next
2552 * time.
2553 */
2554 BTRFS_I(inode)->generation = 0;
Nikolay Borisov9a56fcd2020-11-02 16:48:59 +02002555 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
Josef Bacik77745c02019-06-20 15:38:00 -04002556 if (ret) {
2557 /*
2558 * So theoretically we could recover from this, simply set the
2559 * super cache generation to 0 so we know to invalidate the
2560 * cache, but then we'd have to keep track of the block groups
2561 * that fail this way so we know we _have_ to reset this cache
2562 * before the next commit or risk reading stale cache. So to
2563 * limit our exposure to horrible edge cases lets just abort the
2564 * transaction, this only happens in really bad situations
2565 * anyway.
2566 */
2567 btrfs_abort_transaction(trans, ret);
2568 goto out_put;
2569 }
2570 WARN_ON(ret);
2571
2572 /* We've already setup this transaction, go ahead and exit */
2573 if (block_group->cache_generation == trans->transid &&
2574 i_size_read(inode)) {
2575 dcs = BTRFS_DC_SETUP;
2576 goto out_put;
2577 }
2578
2579 if (i_size_read(inode) > 0) {
2580 ret = btrfs_check_trunc_cache_free_space(fs_info,
2581 &fs_info->global_block_rsv);
2582 if (ret)
2583 goto out_put;
2584
2585 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2586 if (ret)
2587 goto out_put;
2588 }
2589
2590 spin_lock(&block_group->lock);
2591 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2592 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2593 /*
2594 * don't bother trying to write stuff out _if_
2595 * a) we're not cached,
2596 * b) we're with nospace_cache mount option,
2597 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2598 */
2599 dcs = BTRFS_DC_WRITTEN;
2600 spin_unlock(&block_group->lock);
2601 goto out_put;
2602 }
2603 spin_unlock(&block_group->lock);
2604
2605 /*
2606 * We hit an ENOSPC when setting up the cache in this transaction, just
2607 * skip doing the setup, we've already cleared the cache so we're safe.
2608 */
2609 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2610 ret = -ENOSPC;
2611 goto out_put;
2612 }
2613
2614 /*
2615 * Try to preallocate enough space based on how big the block group is.
2616 * Keep in mind this has to include any pinned space which could end up
2617 * taking up quite a bit since it's not folded into the other space
2618 * cache.
2619 */
Qu Wenruo0044ae12021-04-13 14:23:14 +08002620 cache_size = div_u64(block_group->length, SZ_256M);
2621 if (!cache_size)
2622 cache_size = 1;
Josef Bacik77745c02019-06-20 15:38:00 -04002623
Qu Wenruo0044ae12021-04-13 14:23:14 +08002624 cache_size *= 16;
2625 cache_size *= fs_info->sectorsize;
Josef Bacik77745c02019-06-20 15:38:00 -04002626
Nikolay Borisov36ea6f32020-06-03 08:55:41 +03002627 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
Qu Wenruo0044ae12021-04-13 14:23:14 +08002628 cache_size);
Josef Bacik77745c02019-06-20 15:38:00 -04002629 if (ret)
2630 goto out_put;
2631
Qu Wenruo0044ae12021-04-13 14:23:14 +08002632 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
2633 cache_size, cache_size,
Josef Bacik77745c02019-06-20 15:38:00 -04002634 &alloc_hint);
2635 /*
2636 * Our cache requires contiguous chunks so that we don't modify a bunch
2637 * of metadata or split extents when writing the cache out, which means
2638 * we can enospc if we are heavily fragmented in addition to just normal
2639 * out of space conditions. So if we hit this just skip setting up any
2640 * other block groups for this transaction, maybe we'll unpin enough
2641 * space the next time around.
2642 */
2643 if (!ret)
2644 dcs = BTRFS_DC_SETUP;
2645 else if (ret == -ENOSPC)
2646 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2647
2648out_put:
2649 iput(inode);
2650out_free:
2651 btrfs_release_path(path);
2652out:
2653 spin_lock(&block_group->lock);
2654 if (!ret && dcs == BTRFS_DC_SETUP)
2655 block_group->cache_generation = trans->transid;
2656 block_group->disk_cache_state = dcs;
2657 spin_unlock(&block_group->lock);
2658
2659 extent_changeset_free(data_reserved);
2660 return ret;
2661}
2662
2663int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2664{
2665 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002666 struct btrfs_block_group *cache, *tmp;
Josef Bacik77745c02019-06-20 15:38:00 -04002667 struct btrfs_transaction *cur_trans = trans->transaction;
2668 struct btrfs_path *path;
2669
2670 if (list_empty(&cur_trans->dirty_bgs) ||
2671 !btrfs_test_opt(fs_info, SPACE_CACHE))
2672 return 0;
2673
2674 path = btrfs_alloc_path();
2675 if (!path)
2676 return -ENOMEM;
2677
2678 /* Could add new block groups, use _safe just in case */
2679 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2680 dirty_list) {
2681 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2682 cache_save_setup(cache, trans, path);
2683 }
2684
2685 btrfs_free_path(path);
2686 return 0;
2687}
2688
2689/*
2690 * Transaction commit does final block group cache writeback during a critical
2691 * section where nothing is allowed to change the FS. This is required in
2692 * order for the cache to actually match the block group, but can introduce a
2693 * lot of latency into the commit.
2694 *
2695 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2696 * There's a chance we'll have to redo some of it if the block group changes
2697 * again during the commit, but it greatly reduces the commit latency by
2698 * getting rid of the easy block groups while we're still allowing others to
2699 * join the commit.
2700 */
2701int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2702{
2703 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002704 struct btrfs_block_group *cache;
Josef Bacik77745c02019-06-20 15:38:00 -04002705 struct btrfs_transaction *cur_trans = trans->transaction;
2706 int ret = 0;
2707 int should_put;
2708 struct btrfs_path *path = NULL;
2709 LIST_HEAD(dirty);
2710 struct list_head *io = &cur_trans->io_bgs;
2711 int num_started = 0;
2712 int loops = 0;
2713
2714 spin_lock(&cur_trans->dirty_bgs_lock);
2715 if (list_empty(&cur_trans->dirty_bgs)) {
2716 spin_unlock(&cur_trans->dirty_bgs_lock);
2717 return 0;
2718 }
2719 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2720 spin_unlock(&cur_trans->dirty_bgs_lock);
2721
2722again:
2723 /* Make sure all the block groups on our dirty list actually exist */
2724 btrfs_create_pending_block_groups(trans);
2725
2726 if (!path) {
2727 path = btrfs_alloc_path();
Josef Bacik938fcbf2021-01-14 14:02:43 -05002728 if (!path) {
2729 ret = -ENOMEM;
2730 goto out;
2731 }
Josef Bacik77745c02019-06-20 15:38:00 -04002732 }
2733
2734 /*
2735 * cache_write_mutex is here only to save us from balance or automatic
2736 * removal of empty block groups deleting this block group while we are
2737 * writing out the cache
2738 */
2739 mutex_lock(&trans->transaction->cache_write_mutex);
2740 while (!list_empty(&dirty)) {
2741 bool drop_reserve = true;
2742
David Sterba32da53862019-10-29 19:20:18 +01002743 cache = list_first_entry(&dirty, struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002744 dirty_list);
2745 /*
2746 * This can happen if something re-dirties a block group that
2747 * is already under IO. Just wait for it to finish and then do
2748 * it all again
2749 */
2750 if (!list_empty(&cache->io_list)) {
2751 list_del_init(&cache->io_list);
2752 btrfs_wait_cache_io(trans, cache, path);
2753 btrfs_put_block_group(cache);
2754 }
2755
2756
2757 /*
2758 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2759 * it should update the cache_state. Don't delete until after
2760 * we wait.
2761 *
2762 * Since we're not running in the commit critical section
2763 * we need the dirty_bgs_lock to protect from update_block_group
2764 */
2765 spin_lock(&cur_trans->dirty_bgs_lock);
2766 list_del_init(&cache->dirty_list);
2767 spin_unlock(&cur_trans->dirty_bgs_lock);
2768
2769 should_put = 1;
2770
2771 cache_save_setup(cache, trans, path);
2772
2773 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2774 cache->io_ctl.inode = NULL;
2775 ret = btrfs_write_out_cache(trans, cache, path);
2776 if (ret == 0 && cache->io_ctl.inode) {
2777 num_started++;
2778 should_put = 0;
2779
2780 /*
2781 * The cache_write_mutex is protecting the
2782 * io_list, also refer to the definition of
2783 * btrfs_transaction::io_bgs for more details
2784 */
2785 list_add_tail(&cache->io_list, io);
2786 } else {
2787 /*
2788 * If we failed to write the cache, the
2789 * generation will be bad and life goes on
2790 */
2791 ret = 0;
2792 }
2793 }
2794 if (!ret) {
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002795 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002796 /*
2797 * Our block group might still be attached to the list
2798 * of new block groups in the transaction handle of some
2799 * other task (struct btrfs_trans_handle->new_bgs). This
2800 * means its block group item isn't yet in the extent
2801 * tree. If this happens ignore the error, as we will
2802 * try again later in the critical section of the
2803 * transaction commit.
2804 */
2805 if (ret == -ENOENT) {
2806 ret = 0;
2807 spin_lock(&cur_trans->dirty_bgs_lock);
2808 if (list_empty(&cache->dirty_list)) {
2809 list_add_tail(&cache->dirty_list,
2810 &cur_trans->dirty_bgs);
2811 btrfs_get_block_group(cache);
2812 drop_reserve = false;
2813 }
2814 spin_unlock(&cur_trans->dirty_bgs_lock);
2815 } else if (ret) {
2816 btrfs_abort_transaction(trans, ret);
2817 }
2818 }
2819
2820 /* If it's not on the io list, we need to put the block group */
2821 if (should_put)
2822 btrfs_put_block_group(cache);
2823 if (drop_reserve)
2824 btrfs_delayed_refs_rsv_release(fs_info, 1);
Josef Bacik77745c02019-06-20 15:38:00 -04002825 /*
2826 * Avoid blocking other tasks for too long. It might even save
2827 * us from writing caches for block groups that are going to be
2828 * removed.
2829 */
2830 mutex_unlock(&trans->transaction->cache_write_mutex);
Josef Bacik938fcbf2021-01-14 14:02:43 -05002831 if (ret)
2832 goto out;
Josef Bacik77745c02019-06-20 15:38:00 -04002833 mutex_lock(&trans->transaction->cache_write_mutex);
2834 }
2835 mutex_unlock(&trans->transaction->cache_write_mutex);
2836
2837 /*
2838 * Go through delayed refs for all the stuff we've just kicked off
2839 * and then loop back (just once)
2840 */
Josef Bacik34d1eb02020-12-16 11:22:17 -05002841 if (!ret)
2842 ret = btrfs_run_delayed_refs(trans, 0);
Josef Bacik77745c02019-06-20 15:38:00 -04002843 if (!ret && loops == 0) {
2844 loops++;
2845 spin_lock(&cur_trans->dirty_bgs_lock);
2846 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2847 /*
2848 * dirty_bgs_lock protects us from concurrent block group
2849 * deletes too (not just cache_write_mutex).
2850 */
2851 if (!list_empty(&dirty)) {
2852 spin_unlock(&cur_trans->dirty_bgs_lock);
2853 goto again;
2854 }
2855 spin_unlock(&cur_trans->dirty_bgs_lock);
Josef Bacik938fcbf2021-01-14 14:02:43 -05002856 }
2857out:
2858 if (ret < 0) {
2859 spin_lock(&cur_trans->dirty_bgs_lock);
2860 list_splice_init(&dirty, &cur_trans->dirty_bgs);
2861 spin_unlock(&cur_trans->dirty_bgs_lock);
Josef Bacik77745c02019-06-20 15:38:00 -04002862 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2863 }
2864
2865 btrfs_free_path(path);
2866 return ret;
2867}
2868
2869int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2870{
2871 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002872 struct btrfs_block_group *cache;
Josef Bacik77745c02019-06-20 15:38:00 -04002873 struct btrfs_transaction *cur_trans = trans->transaction;
2874 int ret = 0;
2875 int should_put;
2876 struct btrfs_path *path;
2877 struct list_head *io = &cur_trans->io_bgs;
2878 int num_started = 0;
2879
2880 path = btrfs_alloc_path();
2881 if (!path)
2882 return -ENOMEM;
2883
2884 /*
2885 * Even though we are in the critical section of the transaction commit,
2886 * we can still have concurrent tasks adding elements to this
2887 * transaction's list of dirty block groups. These tasks correspond to
2888 * endio free space workers started when writeback finishes for a
2889 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2890 * allocate new block groups as a result of COWing nodes of the root
2891 * tree when updating the free space inode. The writeback for the space
2892 * caches is triggered by an earlier call to
2893 * btrfs_start_dirty_block_groups() and iterations of the following
2894 * loop.
2895 * Also we want to do the cache_save_setup first and then run the
2896 * delayed refs to make sure we have the best chance at doing this all
2897 * in one shot.
2898 */
2899 spin_lock(&cur_trans->dirty_bgs_lock);
2900 while (!list_empty(&cur_trans->dirty_bgs)) {
2901 cache = list_first_entry(&cur_trans->dirty_bgs,
David Sterba32da53862019-10-29 19:20:18 +01002902 struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002903 dirty_list);
2904
2905 /*
2906 * This can happen if cache_save_setup re-dirties a block group
2907 * that is already under IO. Just wait for it to finish and
2908 * then do it all again
2909 */
2910 if (!list_empty(&cache->io_list)) {
2911 spin_unlock(&cur_trans->dirty_bgs_lock);
2912 list_del_init(&cache->io_list);
2913 btrfs_wait_cache_io(trans, cache, path);
2914 btrfs_put_block_group(cache);
2915 spin_lock(&cur_trans->dirty_bgs_lock);
2916 }
2917
2918 /*
2919 * Don't remove from the dirty list until after we've waited on
2920 * any pending IO
2921 */
2922 list_del_init(&cache->dirty_list);
2923 spin_unlock(&cur_trans->dirty_bgs_lock);
2924 should_put = 1;
2925
2926 cache_save_setup(cache, trans, path);
2927
2928 if (!ret)
2929 ret = btrfs_run_delayed_refs(trans,
2930 (unsigned long) -1);
2931
2932 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2933 cache->io_ctl.inode = NULL;
2934 ret = btrfs_write_out_cache(trans, cache, path);
2935 if (ret == 0 && cache->io_ctl.inode) {
2936 num_started++;
2937 should_put = 0;
2938 list_add_tail(&cache->io_list, io);
2939 } else {
2940 /*
2941 * If we failed to write the cache, the
2942 * generation will be bad and life goes on
2943 */
2944 ret = 0;
2945 }
2946 }
2947 if (!ret) {
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002948 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002949 /*
2950 * One of the free space endio workers might have
2951 * created a new block group while updating a free space
2952 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2953 * and hasn't released its transaction handle yet, in
2954 * which case the new block group is still attached to
2955 * its transaction handle and its creation has not
2956 * finished yet (no block group item in the extent tree
2957 * yet, etc). If this is the case, wait for all free
2958 * space endio workers to finish and retry. This is a
Randy Dunlap260db432020-08-04 19:48:34 -07002959 * very rare case so no need for a more efficient and
Josef Bacik77745c02019-06-20 15:38:00 -04002960 * complex approach.
2961 */
2962 if (ret == -ENOENT) {
2963 wait_event(cur_trans->writer_wait,
2964 atomic_read(&cur_trans->num_writers) == 1);
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002965 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002966 }
2967 if (ret)
2968 btrfs_abort_transaction(trans, ret);
2969 }
2970
2971 /* If its not on the io list, we need to put the block group */
2972 if (should_put)
2973 btrfs_put_block_group(cache);
2974 btrfs_delayed_refs_rsv_release(fs_info, 1);
2975 spin_lock(&cur_trans->dirty_bgs_lock);
2976 }
2977 spin_unlock(&cur_trans->dirty_bgs_lock);
2978
2979 /*
2980 * Refer to the definition of io_bgs member for details why it's safe
2981 * to use it without any locking
2982 */
2983 while (!list_empty(io)) {
David Sterba32da53862019-10-29 19:20:18 +01002984 cache = list_first_entry(io, struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002985 io_list);
2986 list_del_init(&cache->io_list);
2987 btrfs_wait_cache_io(trans, cache, path);
2988 btrfs_put_block_group(cache);
2989 }
2990
2991 btrfs_free_path(path);
2992 return ret;
2993}
Josef Bacik606d1bf2019-06-20 15:38:02 -04002994
2995int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2996 u64 bytenr, u64 num_bytes, int alloc)
2997{
2998 struct btrfs_fs_info *info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002999 struct btrfs_block_group *cache = NULL;
Josef Bacik606d1bf2019-06-20 15:38:02 -04003000 u64 total = num_bytes;
3001 u64 old_val;
3002 u64 byte_in_group;
3003 int factor;
3004 int ret = 0;
3005
3006 /* Block accounting for super block */
3007 spin_lock(&info->delalloc_root_lock);
3008 old_val = btrfs_super_bytes_used(info->super_copy);
3009 if (alloc)
3010 old_val += num_bytes;
3011 else
3012 old_val -= num_bytes;
3013 btrfs_set_super_bytes_used(info->super_copy, old_val);
3014 spin_unlock(&info->delalloc_root_lock);
3015
3016 while (total) {
3017 cache = btrfs_lookup_block_group(info, bytenr);
3018 if (!cache) {
3019 ret = -ENOENT;
3020 break;
3021 }
3022 factor = btrfs_bg_type_to_factor(cache->flags);
3023
3024 /*
3025 * If this block group has free space cache written out, we
3026 * need to make sure to load it if we are removing space. This
3027 * is because we need the unpinning stage to actually add the
3028 * space back to the block group, otherwise we will leak space.
3029 */
David Sterba32da53862019-10-29 19:20:18 +01003030 if (!alloc && !btrfs_block_group_done(cache))
Josef Bacik606d1bf2019-06-20 15:38:02 -04003031 btrfs_cache_block_group(cache, 1);
3032
David Sterbab3470b52019-10-23 18:48:22 +02003033 byte_in_group = bytenr - cache->start;
3034 WARN_ON(byte_in_group > cache->length);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003035
3036 spin_lock(&cache->space_info->lock);
3037 spin_lock(&cache->lock);
3038
3039 if (btrfs_test_opt(info, SPACE_CACHE) &&
3040 cache->disk_cache_state < BTRFS_DC_CLEAR)
3041 cache->disk_cache_state = BTRFS_DC_CLEAR;
3042
David Sterbabf38be62019-10-23 18:48:11 +02003043 old_val = cache->used;
David Sterbab3470b52019-10-23 18:48:22 +02003044 num_bytes = min(total, cache->length - byte_in_group);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003045 if (alloc) {
3046 old_val += num_bytes;
David Sterbabf38be62019-10-23 18:48:11 +02003047 cache->used = old_val;
Josef Bacik606d1bf2019-06-20 15:38:02 -04003048 cache->reserved -= num_bytes;
3049 cache->space_info->bytes_reserved -= num_bytes;
3050 cache->space_info->bytes_used += num_bytes;
3051 cache->space_info->disk_used += num_bytes * factor;
3052 spin_unlock(&cache->lock);
3053 spin_unlock(&cache->space_info->lock);
3054 } else {
3055 old_val -= num_bytes;
David Sterbabf38be62019-10-23 18:48:11 +02003056 cache->used = old_val;
Josef Bacik606d1bf2019-06-20 15:38:02 -04003057 cache->pinned += num_bytes;
3058 btrfs_space_info_update_bytes_pinned(info,
3059 cache->space_info, num_bytes);
3060 cache->space_info->bytes_used -= num_bytes;
3061 cache->space_info->disk_used -= num_bytes * factor;
3062 spin_unlock(&cache->lock);
3063 spin_unlock(&cache->space_info->lock);
3064
Josef Bacik21873742021-01-15 16:48:55 -05003065 __btrfs_mod_total_bytes_pinned(cache->space_info,
3066 num_bytes);
Nikolay Borisovfe119a62020-01-20 16:09:18 +02003067 set_extent_dirty(&trans->transaction->pinned_extents,
Josef Bacik606d1bf2019-06-20 15:38:02 -04003068 bytenr, bytenr + num_bytes - 1,
3069 GFP_NOFS | __GFP_NOFAIL);
3070 }
3071
3072 spin_lock(&trans->transaction->dirty_bgs_lock);
3073 if (list_empty(&cache->dirty_list)) {
3074 list_add_tail(&cache->dirty_list,
3075 &trans->transaction->dirty_bgs);
3076 trans->delayed_ref_updates++;
3077 btrfs_get_block_group(cache);
3078 }
3079 spin_unlock(&trans->transaction->dirty_bgs_lock);
3080
3081 /*
3082 * No longer have used bytes in this block group, queue it for
3083 * deletion. We do this after adding the block group to the
3084 * dirty list to avoid races between cleaner kthread and space
3085 * cache writeout.
3086 */
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08003087 if (!alloc && old_val == 0) {
3088 if (!btrfs_test_opt(info, DISCARD_ASYNC))
3089 btrfs_mark_bg_unused(cache);
3090 }
Josef Bacik606d1bf2019-06-20 15:38:02 -04003091
3092 btrfs_put_block_group(cache);
3093 total -= num_bytes;
3094 bytenr += num_bytes;
3095 }
3096
3097 /* Modified block groups are accounted for in the delayed_refs_rsv. */
3098 btrfs_update_delayed_refs_rsv(trans);
3099 return ret;
3100}
3101
3102/**
3103 * btrfs_add_reserved_bytes - update the block_group and space info counters
3104 * @cache: The cache we are manipulating
3105 * @ram_bytes: The number of bytes of file content, and will be same to
3106 * @num_bytes except for the compress path.
3107 * @num_bytes: The number of bytes in question
3108 * @delalloc: The blocks are allocated for the delalloc write
3109 *
3110 * This is called by the allocator when it reserves space. If this is a
3111 * reservation and the block group has become read only we cannot make the
3112 * reservation and return -EAGAIN, otherwise this function always succeeds.
3113 */
David Sterba32da53862019-10-29 19:20:18 +01003114int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
Josef Bacik606d1bf2019-06-20 15:38:02 -04003115 u64 ram_bytes, u64 num_bytes, int delalloc)
3116{
3117 struct btrfs_space_info *space_info = cache->space_info;
3118 int ret = 0;
3119
3120 spin_lock(&space_info->lock);
3121 spin_lock(&cache->lock);
3122 if (cache->ro) {
3123 ret = -EAGAIN;
3124 } else {
3125 cache->reserved += num_bytes;
3126 space_info->bytes_reserved += num_bytes;
Josef Bacika43c3832019-08-22 15:10:56 -04003127 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3128 space_info->flags, num_bytes, 1);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003129 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3130 space_info, -ram_bytes);
3131 if (delalloc)
3132 cache->delalloc_bytes += num_bytes;
Josef Bacik99ffb432020-07-21 10:22:19 -04003133
3134 /*
3135 * Compression can use less space than we reserved, so wake
3136 * tickets if that happens
3137 */
3138 if (num_bytes < ram_bytes)
3139 btrfs_try_granting_tickets(cache->fs_info, space_info);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003140 }
3141 spin_unlock(&cache->lock);
3142 spin_unlock(&space_info->lock);
3143 return ret;
3144}
3145
3146/**
3147 * btrfs_free_reserved_bytes - update the block_group and space info counters
3148 * @cache: The cache we are manipulating
3149 * @num_bytes: The number of bytes in question
3150 * @delalloc: The blocks are allocated for the delalloc write
3151 *
3152 * This is called by somebody who is freeing space that was never actually used
3153 * on disk. For example if you reserve some space for a new leaf in transaction
3154 * A and before transaction A commits you free that leaf, you call this with
3155 * reserve set to 0 in order to clear the reservation.
3156 */
David Sterba32da53862019-10-29 19:20:18 +01003157void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
Josef Bacik606d1bf2019-06-20 15:38:02 -04003158 u64 num_bytes, int delalloc)
3159{
3160 struct btrfs_space_info *space_info = cache->space_info;
3161
3162 spin_lock(&space_info->lock);
3163 spin_lock(&cache->lock);
3164 if (cache->ro)
3165 space_info->bytes_readonly += num_bytes;
3166 cache->reserved -= num_bytes;
3167 space_info->bytes_reserved -= num_bytes;
3168 space_info->max_extent_size = 0;
3169
3170 if (delalloc)
3171 cache->delalloc_bytes -= num_bytes;
3172 spin_unlock(&cache->lock);
Josef Bacik33082342020-07-21 10:22:17 -04003173
3174 btrfs_try_granting_tickets(cache->fs_info, space_info);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003175 spin_unlock(&space_info->lock);
3176}
Josef Bacik07730d82019-06-20 15:38:04 -04003177
3178static void force_metadata_allocation(struct btrfs_fs_info *info)
3179{
3180 struct list_head *head = &info->space_info;
3181 struct btrfs_space_info *found;
3182
Josef Bacik72804902020-09-01 17:40:37 -04003183 list_for_each_entry(found, head, list) {
Josef Bacik07730d82019-06-20 15:38:04 -04003184 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3185 found->force_alloc = CHUNK_ALLOC_FORCE;
3186 }
Josef Bacik07730d82019-06-20 15:38:04 -04003187}
3188
3189static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3190 struct btrfs_space_info *sinfo, int force)
3191{
3192 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3193 u64 thresh;
3194
3195 if (force == CHUNK_ALLOC_FORCE)
3196 return 1;
3197
3198 /*
3199 * in limited mode, we want to have some free space up to
3200 * about 1% of the FS size.
3201 */
3202 if (force == CHUNK_ALLOC_LIMITED) {
3203 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3204 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3205
3206 if (sinfo->total_bytes - bytes_used < thresh)
3207 return 1;
3208 }
3209
3210 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3211 return 0;
3212 return 1;
3213}
3214
3215int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3216{
3217 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3218
3219 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3220}
3221
3222/*
3223 * If force is CHUNK_ALLOC_FORCE:
3224 * - return 1 if it successfully allocates a chunk,
3225 * - return errors including -ENOSPC otherwise.
3226 * If force is NOT CHUNK_ALLOC_FORCE:
3227 * - return 0 if it doesn't need to allocate a new chunk,
3228 * - return 1 if it successfully allocates a chunk,
3229 * - return errors including -ENOSPC otherwise.
3230 */
3231int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3232 enum btrfs_chunk_alloc_enum force)
3233{
3234 struct btrfs_fs_info *fs_info = trans->fs_info;
3235 struct btrfs_space_info *space_info;
3236 bool wait_for_alloc = false;
3237 bool should_alloc = false;
3238 int ret = 0;
3239
3240 /* Don't re-enter if we're already allocating a chunk */
3241 if (trans->allocating_chunk)
3242 return -ENOSPC;
3243
3244 space_info = btrfs_find_space_info(fs_info, flags);
3245 ASSERT(space_info);
3246
3247 do {
3248 spin_lock(&space_info->lock);
3249 if (force < space_info->force_alloc)
3250 force = space_info->force_alloc;
3251 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3252 if (space_info->full) {
3253 /* No more free physical space */
3254 if (should_alloc)
3255 ret = -ENOSPC;
3256 else
3257 ret = 0;
3258 spin_unlock(&space_info->lock);
3259 return ret;
3260 } else if (!should_alloc) {
3261 spin_unlock(&space_info->lock);
3262 return 0;
3263 } else if (space_info->chunk_alloc) {
3264 /*
3265 * Someone is already allocating, so we need to block
3266 * until this someone is finished and then loop to
3267 * recheck if we should continue with our allocation
3268 * attempt.
3269 */
3270 wait_for_alloc = true;
3271 spin_unlock(&space_info->lock);
3272 mutex_lock(&fs_info->chunk_mutex);
3273 mutex_unlock(&fs_info->chunk_mutex);
3274 } else {
3275 /* Proceed with allocation */
3276 space_info->chunk_alloc = 1;
3277 wait_for_alloc = false;
3278 spin_unlock(&space_info->lock);
3279 }
3280
3281 cond_resched();
3282 } while (wait_for_alloc);
3283
3284 mutex_lock(&fs_info->chunk_mutex);
3285 trans->allocating_chunk = true;
3286
3287 /*
3288 * If we have mixed data/metadata chunks we want to make sure we keep
3289 * allocating mixed chunks instead of individual chunks.
3290 */
3291 if (btrfs_mixed_space_info(space_info))
3292 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3293
3294 /*
3295 * if we're doing a data chunk, go ahead and make sure that
3296 * we keep a reasonable number of metadata chunks allocated in the
3297 * FS as well.
3298 */
3299 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3300 fs_info->data_chunk_allocations++;
3301 if (!(fs_info->data_chunk_allocations %
3302 fs_info->metadata_ratio))
3303 force_metadata_allocation(fs_info);
3304 }
3305
3306 /*
3307 * Check if we have enough space in SYSTEM chunk because we may need
3308 * to update devices.
3309 */
3310 check_system_chunk(trans, flags);
3311
3312 ret = btrfs_alloc_chunk(trans, flags);
3313 trans->allocating_chunk = false;
3314
3315 spin_lock(&space_info->lock);
3316 if (ret < 0) {
3317 if (ret == -ENOSPC)
3318 space_info->full = 1;
3319 else
3320 goto out;
3321 } else {
3322 ret = 1;
3323 space_info->max_extent_size = 0;
3324 }
3325
3326 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3327out:
3328 space_info->chunk_alloc = 0;
3329 spin_unlock(&space_info->lock);
3330 mutex_unlock(&fs_info->chunk_mutex);
3331 /*
3332 * When we allocate a new chunk we reserve space in the chunk block
3333 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3334 * add new nodes/leafs to it if we end up needing to do it when
3335 * inserting the chunk item and updating device items as part of the
3336 * second phase of chunk allocation, performed by
3337 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3338 * large number of new block groups to create in our transaction
3339 * handle's new_bgs list to avoid exhausting the chunk block reserve
3340 * in extreme cases - like having a single transaction create many new
3341 * block groups when starting to write out the free space caches of all
3342 * the block groups that were made dirty during the lifetime of the
3343 * transaction.
3344 */
3345 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3346 btrfs_create_pending_block_groups(trans);
3347
3348 return ret;
3349}
3350
3351static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3352{
3353 u64 num_dev;
3354
3355 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3356 if (!num_dev)
3357 num_dev = fs_info->fs_devices->rw_devices;
3358
3359 return num_dev;
3360}
3361
3362/*
Marcos Paulo de Souzaa9143bd2019-10-07 21:50:38 -03003363 * Reserve space in the system space for allocating or removing a chunk
Josef Bacik07730d82019-06-20 15:38:04 -04003364 */
3365void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3366{
Filipe Mananaeafa4fd2021-03-31 11:55:50 +01003367 struct btrfs_transaction *cur_trans = trans->transaction;
Josef Bacik07730d82019-06-20 15:38:04 -04003368 struct btrfs_fs_info *fs_info = trans->fs_info;
3369 struct btrfs_space_info *info;
3370 u64 left;
3371 u64 thresh;
3372 int ret = 0;
3373 u64 num_devs;
3374
3375 /*
3376 * Needed because we can end up allocating a system chunk and for an
3377 * atomic and race free space reservation in the chunk block reserve.
3378 */
3379 lockdep_assert_held(&fs_info->chunk_mutex);
3380
3381 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
Filipe Mananaeafa4fd2021-03-31 11:55:50 +01003382again:
Josef Bacik07730d82019-06-20 15:38:04 -04003383 spin_lock(&info->lock);
3384 left = info->total_bytes - btrfs_space_info_used(info, true);
3385 spin_unlock(&info->lock);
3386
3387 num_devs = get_profile_num_devs(fs_info, type);
3388
3389 /* num_devs device items to update and 1 chunk item to add or remove */
Josef Bacik2bd36e72019-08-22 15:14:33 -04003390 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3391 btrfs_calc_insert_metadata_size(fs_info, 1);
Josef Bacik07730d82019-06-20 15:38:04 -04003392
3393 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3394 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3395 left, thresh, type);
3396 btrfs_dump_space_info(fs_info, info, 0, 0);
3397 }
3398
3399 if (left < thresh) {
3400 u64 flags = btrfs_system_alloc_profile(fs_info);
Filipe Mananaeafa4fd2021-03-31 11:55:50 +01003401 u64 reserved = atomic64_read(&cur_trans->chunk_bytes_reserved);
3402
3403 /*
3404 * If there's not available space for the chunk tree (system
3405 * space) and there are other tasks that reserved space for
3406 * creating a new system block group, wait for them to complete
3407 * the creation of their system block group and release excess
3408 * reserved space. We do this because:
3409 *
3410 * *) We can end up allocating more system chunks than necessary
3411 * when there are multiple tasks that are concurrently
3412 * allocating block groups, which can lead to exhaustion of
3413 * the system array in the superblock;
3414 *
3415 * *) If we allocate extra and unnecessary system block groups,
3416 * despite being empty for a long time, and possibly forever,
3417 * they end not being added to the list of unused block groups
3418 * because that typically happens only when deallocating the
3419 * last extent from a block group - which never happens since
3420 * we never allocate from them in the first place. The few
3421 * exceptions are when mounting a filesystem or running scrub,
3422 * which add unused block groups to the list of unused block
3423 * groups, to be deleted by the cleaner kthread.
3424 * And even when they are added to the list of unused block
3425 * groups, it can take a long time until they get deleted,
3426 * since the cleaner kthread might be sleeping or busy with
3427 * other work (deleting subvolumes, running delayed iputs,
3428 * defrag scheduling, etc);
3429 *
3430 * This is rare in practice, but can happen when too many tasks
3431 * are allocating blocks groups in parallel (via fallocate())
3432 * and before the one that reserved space for a new system block
3433 * group finishes the block group creation and releases the space
3434 * reserved in excess (at btrfs_create_pending_block_groups()),
3435 * other tasks end up here and see free system space temporarily
3436 * not enough for updating the chunk tree.
3437 *
3438 * We unlock the chunk mutex before waiting for such tasks and
3439 * lock it again after the wait, otherwise we would deadlock.
3440 * It is safe to do so because allocating a system chunk is the
3441 * first thing done while allocating a new block group.
3442 */
3443 if (reserved > trans->chunk_bytes_reserved) {
3444 const u64 min_needed = reserved - thresh;
3445
3446 mutex_unlock(&fs_info->chunk_mutex);
3447 wait_event(cur_trans->chunk_reserve_wait,
3448 atomic64_read(&cur_trans->chunk_bytes_reserved) <=
3449 min_needed);
3450 mutex_lock(&fs_info->chunk_mutex);
3451 goto again;
3452 }
Josef Bacik07730d82019-06-20 15:38:04 -04003453
3454 /*
3455 * Ignore failure to create system chunk. We might end up not
3456 * needing it, as we might not need to COW all nodes/leafs from
3457 * the paths we visit in the chunk tree (they were already COWed
3458 * or created in the current transaction for example).
3459 */
3460 ret = btrfs_alloc_chunk(trans, flags);
3461 }
3462
3463 if (!ret) {
3464 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3465 &fs_info->chunk_block_rsv,
3466 thresh, BTRFS_RESERVE_NO_FLUSH);
Filipe Mananaeafa4fd2021-03-31 11:55:50 +01003467 if (!ret) {
3468 atomic64_add(thresh, &cur_trans->chunk_bytes_reserved);
Josef Bacik07730d82019-06-20 15:38:04 -04003469 trans->chunk_bytes_reserved += thresh;
Filipe Mananaeafa4fd2021-03-31 11:55:50 +01003470 }
Josef Bacik07730d82019-06-20 15:38:04 -04003471 }
3472}
3473
Josef Bacik3e43c272019-06-20 15:38:06 -04003474void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3475{
David Sterba32da53862019-10-29 19:20:18 +01003476 struct btrfs_block_group *block_group;
Josef Bacik3e43c272019-06-20 15:38:06 -04003477 u64 last = 0;
3478
3479 while (1) {
3480 struct inode *inode;
3481
3482 block_group = btrfs_lookup_first_block_group(info, last);
3483 while (block_group) {
3484 btrfs_wait_block_group_cache_done(block_group);
3485 spin_lock(&block_group->lock);
3486 if (block_group->iref)
3487 break;
3488 spin_unlock(&block_group->lock);
3489 block_group = btrfs_next_block_group(block_group);
3490 }
3491 if (!block_group) {
3492 if (last == 0)
3493 break;
3494 last = 0;
3495 continue;
3496 }
3497
3498 inode = block_group->inode;
3499 block_group->iref = 0;
3500 block_group->inode = NULL;
3501 spin_unlock(&block_group->lock);
3502 ASSERT(block_group->io_ctl.inode == NULL);
3503 iput(inode);
David Sterbab3470b52019-10-23 18:48:22 +02003504 last = block_group->start + block_group->length;
Josef Bacik3e43c272019-06-20 15:38:06 -04003505 btrfs_put_block_group(block_group);
3506 }
3507}
3508
3509/*
3510 * Must be called only after stopping all workers, since we could have block
3511 * group caching kthreads running, and therefore they could race with us if we
3512 * freed the block groups before stopping them.
3513 */
3514int btrfs_free_block_groups(struct btrfs_fs_info *info)
3515{
David Sterba32da53862019-10-29 19:20:18 +01003516 struct btrfs_block_group *block_group;
Josef Bacik3e43c272019-06-20 15:38:06 -04003517 struct btrfs_space_info *space_info;
3518 struct btrfs_caching_control *caching_ctl;
3519 struct rb_node *n;
3520
Josef Bacikbbb86a32020-10-23 09:58:11 -04003521 spin_lock(&info->block_group_cache_lock);
Josef Bacik3e43c272019-06-20 15:38:06 -04003522 while (!list_empty(&info->caching_block_groups)) {
3523 caching_ctl = list_entry(info->caching_block_groups.next,
3524 struct btrfs_caching_control, list);
3525 list_del(&caching_ctl->list);
3526 btrfs_put_caching_control(caching_ctl);
3527 }
Josef Bacikbbb86a32020-10-23 09:58:11 -04003528 spin_unlock(&info->block_group_cache_lock);
Josef Bacik3e43c272019-06-20 15:38:06 -04003529
3530 spin_lock(&info->unused_bgs_lock);
3531 while (!list_empty(&info->unused_bgs)) {
3532 block_group = list_first_entry(&info->unused_bgs,
David Sterba32da53862019-10-29 19:20:18 +01003533 struct btrfs_block_group,
Josef Bacik3e43c272019-06-20 15:38:06 -04003534 bg_list);
3535 list_del_init(&block_group->bg_list);
3536 btrfs_put_block_group(block_group);
3537 }
3538 spin_unlock(&info->unused_bgs_lock);
3539
Johannes Thumshirn18bb8bb2021-04-19 16:41:02 +09003540 spin_lock(&info->unused_bgs_lock);
3541 while (!list_empty(&info->reclaim_bgs)) {
3542 block_group = list_first_entry(&info->reclaim_bgs,
3543 struct btrfs_block_group,
3544 bg_list);
3545 list_del_init(&block_group->bg_list);
3546 btrfs_put_block_group(block_group);
3547 }
3548 spin_unlock(&info->unused_bgs_lock);
3549
Josef Bacik3e43c272019-06-20 15:38:06 -04003550 spin_lock(&info->block_group_cache_lock);
3551 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
David Sterba32da53862019-10-29 19:20:18 +01003552 block_group = rb_entry(n, struct btrfs_block_group,
Josef Bacik3e43c272019-06-20 15:38:06 -04003553 cache_node);
3554 rb_erase(&block_group->cache_node,
3555 &info->block_group_cache_tree);
3556 RB_CLEAR_NODE(&block_group->cache_node);
3557 spin_unlock(&info->block_group_cache_lock);
3558
3559 down_write(&block_group->space_info->groups_sem);
3560 list_del(&block_group->list);
3561 up_write(&block_group->space_info->groups_sem);
3562
3563 /*
3564 * We haven't cached this block group, which means we could
3565 * possibly have excluded extents on this block group.
3566 */
3567 if (block_group->cached == BTRFS_CACHE_NO ||
3568 block_group->cached == BTRFS_CACHE_ERROR)
3569 btrfs_free_excluded_extents(block_group);
3570
3571 btrfs_remove_free_space_cache(block_group);
3572 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3573 ASSERT(list_empty(&block_group->dirty_list));
3574 ASSERT(list_empty(&block_group->io_list));
3575 ASSERT(list_empty(&block_group->bg_list));
Josef Bacik48aaeeb2020-07-06 09:14:11 -04003576 ASSERT(refcount_read(&block_group->refs) == 1);
Filipe Manana195a49e2021-02-05 12:55:37 +00003577 ASSERT(block_group->swap_extents == 0);
Josef Bacik3e43c272019-06-20 15:38:06 -04003578 btrfs_put_block_group(block_group);
3579
3580 spin_lock(&info->block_group_cache_lock);
3581 }
3582 spin_unlock(&info->block_group_cache_lock);
3583
Josef Bacik3e43c272019-06-20 15:38:06 -04003584 btrfs_release_global_block_rsv(info);
3585
3586 while (!list_empty(&info->space_info)) {
3587 space_info = list_entry(info->space_info.next,
3588 struct btrfs_space_info,
3589 list);
3590
3591 /*
3592 * Do not hide this behind enospc_debug, this is actually
3593 * important and indicates a real bug if this happens.
3594 */
3595 if (WARN_ON(space_info->bytes_pinned > 0 ||
3596 space_info->bytes_reserved > 0 ||
3597 space_info->bytes_may_use > 0))
3598 btrfs_dump_space_info(info, space_info, 0, 0);
Filipe Mananad611add2020-04-07 11:38:49 +01003599 WARN_ON(space_info->reclaim_size > 0);
Josef Bacik3e43c272019-06-20 15:38:06 -04003600 list_del(&space_info->list);
3601 btrfs_sysfs_remove_space_info(space_info);
3602 }
3603 return 0;
3604}
Filipe Manana684b7522020-05-08 11:01:59 +01003605
3606void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3607{
3608 atomic_inc(&cache->frozen);
3609}
3610
3611void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3612{
3613 struct btrfs_fs_info *fs_info = block_group->fs_info;
3614 struct extent_map_tree *em_tree;
3615 struct extent_map *em;
3616 bool cleanup;
3617
3618 spin_lock(&block_group->lock);
3619 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3620 block_group->removed);
3621 spin_unlock(&block_group->lock);
3622
3623 if (cleanup) {
Filipe Manana684b7522020-05-08 11:01:59 +01003624 em_tree = &fs_info->mapping_tree;
3625 write_lock(&em_tree->lock);
3626 em = lookup_extent_mapping(em_tree, block_group->start,
3627 1);
3628 BUG_ON(!em); /* logic error, can't happen */
3629 remove_extent_mapping(em_tree, em);
3630 write_unlock(&em_tree->lock);
Filipe Manana684b7522020-05-08 11:01:59 +01003631
3632 /* once for us and once for the tree */
3633 free_extent_map(em);
3634 free_extent_map(em);
3635
3636 /*
3637 * We may have left one free space entry and other possible
3638 * tasks trimming this block group have left 1 entry each one.
3639 * Free them if any.
3640 */
3641 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
3642 }
3643}
Filipe Manana195a49e2021-02-05 12:55:37 +00003644
3645bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
3646{
3647 bool ret = true;
3648
3649 spin_lock(&bg->lock);
3650 if (bg->ro)
3651 ret = false;
3652 else
3653 bg->swap_extents++;
3654 spin_unlock(&bg->lock);
3655
3656 return ret;
3657}
3658
3659void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
3660{
3661 spin_lock(&bg->lock);
3662 ASSERT(!bg->ro);
3663 ASSERT(bg->swap_extents >= amount);
3664 bg->swap_extents -= amount;
3665 spin_unlock(&bg->lock);
3666}