blob: e4444d4dd4b59df3417a3ada7dfa42eb62af071b [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
728 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
729 if (!caching_ctl)
730 return -ENOMEM;
731
732 INIT_LIST_HEAD(&caching_ctl->list);
733 mutex_init(&caching_ctl->mutex);
734 init_waitqueue_head(&caching_ctl->wait);
735 caching_ctl->block_group = cache;
David Sterbab3470b52019-10-23 18:48:22 +0200736 caching_ctl->progress = cache->start;
Josef Bacike7478532020-10-23 09:58:10 -0400737 refcount_set(&caching_ctl->count, 2);
Omar Sandovala0cac0e2019-09-16 11:30:57 -0700738 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
Josef Bacik9f212462019-08-06 16:43:19 +0200739
740 spin_lock(&cache->lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200741 if (cache->cached != BTRFS_CACHE_NO) {
Josef Bacik9f212462019-08-06 16:43:19 +0200742 kfree(caching_ctl);
Josef Bacike7478532020-10-23 09:58:10 -0400743
744 caching_ctl = cache->caching_ctl;
745 if (caching_ctl)
746 refcount_inc(&caching_ctl->count);
747 spin_unlock(&cache->lock);
748 goto out;
Josef Bacik9f212462019-08-06 16:43:19 +0200749 }
750 WARN_ON(cache->caching_ctl);
751 cache->caching_ctl = caching_ctl;
Josef Bacike7478532020-10-23 09:58:10 -0400752 if (btrfs_test_opt(fs_info, SPACE_CACHE))
753 cache->cached = BTRFS_CACHE_FAST;
754 else
755 cache->cached = BTRFS_CACHE_STARTED;
756 cache->has_caching_ctl = 1;
Josef Bacik9f212462019-08-06 16:43:19 +0200757 spin_unlock(&cache->lock);
758
Josef Bacikbbb86a32020-10-23 09:58:11 -0400759 spin_lock(&fs_info->block_group_cache_lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200760 refcount_inc(&caching_ctl->count);
761 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
Josef Bacikbbb86a32020-10-23 09:58:11 -0400762 spin_unlock(&fs_info->block_group_cache_lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200763
764 btrfs_get_block_group(cache);
765
766 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
Josef Bacike7478532020-10-23 09:58:10 -0400767out:
768 if (load_cache_only && caching_ctl)
769 btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
770 if (caching_ctl)
771 btrfs_put_caching_control(caching_ctl);
Josef Bacik9f212462019-08-06 16:43:19 +0200772
773 return ret;
774}
Josef Bacike3e05202019-06-20 15:37:55 -0400775
776static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
777{
778 u64 extra_flags = chunk_to_extended(flags) &
779 BTRFS_EXTENDED_PROFILE_MASK;
780
781 write_seqlock(&fs_info->profiles_lock);
782 if (flags & BTRFS_BLOCK_GROUP_DATA)
783 fs_info->avail_data_alloc_bits &= ~extra_flags;
784 if (flags & BTRFS_BLOCK_GROUP_METADATA)
785 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
786 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
787 fs_info->avail_system_alloc_bits &= ~extra_flags;
788 write_sequnlock(&fs_info->profiles_lock);
789}
790
791/*
792 * Clear incompat bits for the following feature(s):
793 *
794 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
795 * in the whole filesystem
David Sterba9c907442019-10-31 15:52:01 +0100796 *
797 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
Josef Bacike3e05202019-06-20 15:37:55 -0400798 */
799static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
800{
David Sterba9c907442019-10-31 15:52:01 +0100801 bool found_raid56 = false;
802 bool found_raid1c34 = false;
803
804 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
805 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
806 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
Josef Bacike3e05202019-06-20 15:37:55 -0400807 struct list_head *head = &fs_info->space_info;
808 struct btrfs_space_info *sinfo;
809
810 list_for_each_entry_rcu(sinfo, head, list) {
Josef Bacike3e05202019-06-20 15:37:55 -0400811 down_read(&sinfo->groups_sem);
812 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
David Sterba9c907442019-10-31 15:52:01 +0100813 found_raid56 = true;
Josef Bacike3e05202019-06-20 15:37:55 -0400814 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
David Sterba9c907442019-10-31 15:52:01 +0100815 found_raid56 = true;
816 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
817 found_raid1c34 = true;
818 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
819 found_raid1c34 = true;
Josef Bacike3e05202019-06-20 15:37:55 -0400820 up_read(&sinfo->groups_sem);
Josef Bacike3e05202019-06-20 15:37:55 -0400821 }
Filipe Mananad8e6fd52020-03-20 18:43:48 +0000822 if (!found_raid56)
David Sterba9c907442019-10-31 15:52:01 +0100823 btrfs_clear_fs_incompat(fs_info, RAID56);
Filipe Mananad8e6fd52020-03-20 18:43:48 +0000824 if (!found_raid1c34)
David Sterba9c907442019-10-31 15:52:01 +0100825 btrfs_clear_fs_incompat(fs_info, RAID1C34);
Josef Bacike3e05202019-06-20 15:37:55 -0400826 }
827}
828
Qu Wenruo73576232020-05-05 07:58:21 +0800829static int remove_block_group_item(struct btrfs_trans_handle *trans,
830 struct btrfs_path *path,
831 struct btrfs_block_group *block_group)
832{
833 struct btrfs_fs_info *fs_info = trans->fs_info;
834 struct btrfs_root *root;
835 struct btrfs_key key;
836 int ret;
837
838 root = fs_info->extent_root;
839 key.objectid = block_group->start;
840 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
841 key.offset = block_group->length;
842
843 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
844 if (ret > 0)
845 ret = -ENOENT;
846 if (ret < 0)
847 return ret;
848
849 ret = btrfs_del_item(trans, root, path);
850 return ret;
851}
852
Josef Bacike3e05202019-06-20 15:37:55 -0400853int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
854 u64 group_start, struct extent_map *em)
855{
856 struct btrfs_fs_info *fs_info = trans->fs_info;
Josef Bacike3e05202019-06-20 15:37:55 -0400857 struct btrfs_path *path;
David Sterba32da53862019-10-29 19:20:18 +0100858 struct btrfs_block_group *block_group;
Josef Bacike3e05202019-06-20 15:37:55 -0400859 struct btrfs_free_cluster *cluster;
Josef Bacike3e05202019-06-20 15:37:55 -0400860 struct inode *inode;
861 struct kobject *kobj = NULL;
862 int ret;
863 int index;
864 int factor;
865 struct btrfs_caching_control *caching_ctl = NULL;
866 bool remove_em;
867 bool remove_rsv = false;
868
869 block_group = btrfs_lookup_block_group(fs_info, group_start);
870 BUG_ON(!block_group);
871 BUG_ON(!block_group->ro);
872
873 trace_btrfs_remove_block_group(block_group);
874 /*
875 * Free the reserved super bytes from this block group before
876 * remove it.
877 */
878 btrfs_free_excluded_extents(block_group);
David Sterbab3470b52019-10-23 18:48:22 +0200879 btrfs_free_ref_tree_range(fs_info, block_group->start,
880 block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -0400881
Josef Bacike3e05202019-06-20 15:37:55 -0400882 index = btrfs_bg_flags_to_raid_index(block_group->flags);
883 factor = btrfs_bg_type_to_factor(block_group->flags);
884
885 /* make sure this block group isn't part of an allocation cluster */
886 cluster = &fs_info->data_alloc_cluster;
887 spin_lock(&cluster->refill_lock);
888 btrfs_return_cluster_to_free_space(block_group, cluster);
889 spin_unlock(&cluster->refill_lock);
890
891 /*
892 * make sure this block group isn't part of a metadata
893 * allocation cluster
894 */
895 cluster = &fs_info->meta_alloc_cluster;
896 spin_lock(&cluster->refill_lock);
897 btrfs_return_cluster_to_free_space(block_group, cluster);
898 spin_unlock(&cluster->refill_lock);
899
900 path = btrfs_alloc_path();
901 if (!path) {
902 ret = -ENOMEM;
Filipe Manana9fecd132020-06-01 19:12:06 +0100903 goto out;
Josef Bacike3e05202019-06-20 15:37:55 -0400904 }
905
906 /*
907 * get the inode first so any iput calls done for the io_list
908 * aren't the final iput (no unlinks allowed now)
909 */
910 inode = lookup_free_space_inode(block_group, path);
911
912 mutex_lock(&trans->transaction->cache_write_mutex);
913 /*
914 * Make sure our free space cache IO is done before removing the
915 * free space inode
916 */
917 spin_lock(&trans->transaction->dirty_bgs_lock);
918 if (!list_empty(&block_group->io_list)) {
919 list_del_init(&block_group->io_list);
920
921 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
922
923 spin_unlock(&trans->transaction->dirty_bgs_lock);
924 btrfs_wait_cache_io(trans, block_group, path);
925 btrfs_put_block_group(block_group);
926 spin_lock(&trans->transaction->dirty_bgs_lock);
927 }
928
929 if (!list_empty(&block_group->dirty_list)) {
930 list_del_init(&block_group->dirty_list);
931 remove_rsv = true;
932 btrfs_put_block_group(block_group);
933 }
934 spin_unlock(&trans->transaction->dirty_bgs_lock);
935 mutex_unlock(&trans->transaction->cache_write_mutex);
936
Boris Burkov36b216c2020-11-18 15:06:25 -0800937 ret = btrfs_remove_free_space_inode(trans, inode, block_group);
938 if (ret)
Filipe Manana9fecd132020-06-01 19:12:06 +0100939 goto out;
Josef Bacike3e05202019-06-20 15:37:55 -0400940
941 spin_lock(&fs_info->block_group_cache_lock);
942 rb_erase(&block_group->cache_node,
943 &fs_info->block_group_cache_tree);
944 RB_CLEAR_NODE(&block_group->cache_node);
945
Filipe Manana9fecd132020-06-01 19:12:06 +0100946 /* Once for the block groups rbtree */
947 btrfs_put_block_group(block_group);
948
David Sterbab3470b52019-10-23 18:48:22 +0200949 if (fs_info->first_logical_byte == block_group->start)
Josef Bacike3e05202019-06-20 15:37:55 -0400950 fs_info->first_logical_byte = (u64)-1;
951 spin_unlock(&fs_info->block_group_cache_lock);
952
953 down_write(&block_group->space_info->groups_sem);
954 /*
955 * we must use list_del_init so people can check to see if they
956 * are still on the list after taking the semaphore
957 */
958 list_del_init(&block_group->list);
959 if (list_empty(&block_group->space_info->block_groups[index])) {
960 kobj = block_group->space_info->block_group_kobjs[index];
961 block_group->space_info->block_group_kobjs[index] = NULL;
962 clear_avail_alloc_bits(fs_info, block_group->flags);
963 }
964 up_write(&block_group->space_info->groups_sem);
965 clear_incompat_bg_bits(fs_info, block_group->flags);
966 if (kobj) {
967 kobject_del(kobj);
968 kobject_put(kobj);
969 }
970
971 if (block_group->has_caching_ctl)
972 caching_ctl = btrfs_get_caching_control(block_group);
973 if (block_group->cached == BTRFS_CACHE_STARTED)
974 btrfs_wait_block_group_cache_done(block_group);
975 if (block_group->has_caching_ctl) {
Josef Bacikbbb86a32020-10-23 09:58:11 -0400976 spin_lock(&fs_info->block_group_cache_lock);
Josef Bacike3e05202019-06-20 15:37:55 -0400977 if (!caching_ctl) {
978 struct btrfs_caching_control *ctl;
979
980 list_for_each_entry(ctl,
981 &fs_info->caching_block_groups, list)
982 if (ctl->block_group == block_group) {
983 caching_ctl = ctl;
984 refcount_inc(&caching_ctl->count);
985 break;
986 }
987 }
988 if (caching_ctl)
989 list_del_init(&caching_ctl->list);
Josef Bacikbbb86a32020-10-23 09:58:11 -0400990 spin_unlock(&fs_info->block_group_cache_lock);
Josef Bacike3e05202019-06-20 15:37:55 -0400991 if (caching_ctl) {
992 /* Once for the caching bgs list and once for us. */
993 btrfs_put_caching_control(caching_ctl);
994 btrfs_put_caching_control(caching_ctl);
995 }
996 }
997
998 spin_lock(&trans->transaction->dirty_bgs_lock);
999 WARN_ON(!list_empty(&block_group->dirty_list));
1000 WARN_ON(!list_empty(&block_group->io_list));
1001 spin_unlock(&trans->transaction->dirty_bgs_lock);
1002
1003 btrfs_remove_free_space_cache(block_group);
1004
1005 spin_lock(&block_group->space_info->lock);
1006 list_del_init(&block_group->ro_list);
1007
1008 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1009 WARN_ON(block_group->space_info->total_bytes
David Sterbab3470b52019-10-23 18:48:22 +02001010 < block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -04001011 WARN_ON(block_group->space_info->bytes_readonly
Naohiro Aota169e0da2021-02-04 19:21:52 +09001012 < block_group->length - block_group->zone_unusable);
1013 WARN_ON(block_group->space_info->bytes_zone_unusable
1014 < block_group->zone_unusable);
Josef Bacike3e05202019-06-20 15:37:55 -04001015 WARN_ON(block_group->space_info->disk_total
David Sterbab3470b52019-10-23 18:48:22 +02001016 < block_group->length * factor);
Josef Bacike3e05202019-06-20 15:37:55 -04001017 }
David Sterbab3470b52019-10-23 18:48:22 +02001018 block_group->space_info->total_bytes -= block_group->length;
Naohiro Aota169e0da2021-02-04 19:21:52 +09001019 block_group->space_info->bytes_readonly -=
1020 (block_group->length - block_group->zone_unusable);
1021 block_group->space_info->bytes_zone_unusable -=
1022 block_group->zone_unusable;
David Sterbab3470b52019-10-23 18:48:22 +02001023 block_group->space_info->disk_total -= block_group->length * factor;
Josef Bacike3e05202019-06-20 15:37:55 -04001024
1025 spin_unlock(&block_group->space_info->lock);
1026
Filipe Mananaffcb9d42020-06-01 19:12:19 +01001027 /*
1028 * Remove the free space for the block group from the free space tree
1029 * and the block group's item from the extent tree before marking the
1030 * block group as removed. This is to prevent races with tasks that
1031 * freeze and unfreeze a block group, this task and another task
1032 * allocating a new block group - the unfreeze task ends up removing
1033 * the block group's extent map before the task calling this function
1034 * deletes the block group item from the extent tree, allowing for
1035 * another task to attempt to create another block group with the same
1036 * item key (and failing with -EEXIST and a transaction abort).
1037 */
1038 ret = remove_block_group_free_space(trans, block_group);
1039 if (ret)
1040 goto out;
1041
1042 ret = remove_block_group_item(trans, path, block_group);
1043 if (ret < 0)
1044 goto out;
1045
Josef Bacike3e05202019-06-20 15:37:55 -04001046 spin_lock(&block_group->lock);
1047 block_group->removed = 1;
1048 /*
Filipe Manana6b7304a2020-05-08 11:01:47 +01001049 * At this point trimming or scrub can't start on this block group,
1050 * because we removed the block group from the rbtree
1051 * fs_info->block_group_cache_tree so no one can't find it anymore and
1052 * even if someone already got this block group before we removed it
1053 * from the rbtree, they have already incremented block_group->frozen -
1054 * if they didn't, for the trimming case they won't find any free space
1055 * entries because we already removed them all when we called
1056 * btrfs_remove_free_space_cache().
Josef Bacike3e05202019-06-20 15:37:55 -04001057 *
1058 * And we must not remove the extent map from the fs_info->mapping_tree
1059 * to prevent the same logical address range and physical device space
Filipe Manana6b7304a2020-05-08 11:01:47 +01001060 * ranges from being reused for a new block group. This is needed to
1061 * avoid races with trimming and scrub.
1062 *
1063 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
Josef Bacike3e05202019-06-20 15:37:55 -04001064 * completely transactionless, so while it is trimming a range the
1065 * currently running transaction might finish and a new one start,
1066 * allowing for new block groups to be created that can reuse the same
1067 * physical device locations unless we take this special care.
1068 *
1069 * There may also be an implicit trim operation if the file system
1070 * is mounted with -odiscard. The same protections must remain
1071 * in place until the extents have been discarded completely when
1072 * the transaction commit has completed.
1073 */
Filipe Manana6b7304a2020-05-08 11:01:47 +01001074 remove_em = (atomic_read(&block_group->frozen) == 0);
Josef Bacike3e05202019-06-20 15:37:55 -04001075 spin_unlock(&block_group->lock);
1076
Josef Bacike3e05202019-06-20 15:37:55 -04001077 if (remove_em) {
1078 struct extent_map_tree *em_tree;
1079
1080 em_tree = &fs_info->mapping_tree;
1081 write_lock(&em_tree->lock);
1082 remove_extent_mapping(em_tree, em);
1083 write_unlock(&em_tree->lock);
1084 /* once for the tree */
1085 free_extent_map(em);
1086 }
Xiyu Yangf6033c52020-04-21 10:54:11 +08001087
Filipe Manana9fecd132020-06-01 19:12:06 +01001088out:
Xiyu Yangf6033c52020-04-21 10:54:11 +08001089 /* Once for the lookup reference */
1090 btrfs_put_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001091 if (remove_rsv)
1092 btrfs_delayed_refs_rsv_release(fs_info, 1);
1093 btrfs_free_path(path);
1094 return ret;
1095}
1096
1097struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1098 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1099{
1100 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1101 struct extent_map *em;
1102 struct map_lookup *map;
1103 unsigned int num_items;
1104
1105 read_lock(&em_tree->lock);
1106 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1107 read_unlock(&em_tree->lock);
1108 ASSERT(em && em->start == chunk_offset);
1109
1110 /*
1111 * We need to reserve 3 + N units from the metadata space info in order
1112 * to remove a block group (done at btrfs_remove_chunk() and at
1113 * btrfs_remove_block_group()), which are used for:
1114 *
1115 * 1 unit for adding the free space inode's orphan (located in the tree
1116 * of tree roots).
1117 * 1 unit for deleting the block group item (located in the extent
1118 * tree).
1119 * 1 unit for deleting the free space item (located in tree of tree
1120 * roots).
1121 * N units for deleting N device extent items corresponding to each
1122 * stripe (located in the device tree).
1123 *
1124 * In order to remove a block group we also need to reserve units in the
1125 * system space info in order to update the chunk tree (update one or
1126 * more device items and remove one chunk item), but this is done at
1127 * btrfs_remove_chunk() through a call to check_system_chunk().
1128 */
1129 map = em->map_lookup;
1130 num_items = 3 + map->num_stripes;
1131 free_extent_map(em);
1132
1133 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
Josef Bacik7f9fe612020-03-13 15:58:05 -04001134 num_items);
Josef Bacike3e05202019-06-20 15:37:55 -04001135}
1136
1137/*
Josef Bacik26ce2092019-06-20 15:37:59 -04001138 * Mark block group @cache read-only, so later write won't happen to block
1139 * group @cache.
1140 *
1141 * If @force is not set, this function will only mark the block group readonly
1142 * if we have enough free space (1M) in other metadata/system block groups.
1143 * If @force is not set, this function will mark the block group readonly
1144 * without checking free space.
1145 *
1146 * NOTE: This function doesn't care if other block groups can contain all the
1147 * data in this block group. That check should be done by relocation routine,
1148 * not this function.
1149 */
David Sterba32da53862019-10-29 19:20:18 +01001150static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
Josef Bacik26ce2092019-06-20 15:37:59 -04001151{
1152 struct btrfs_space_info *sinfo = cache->space_info;
1153 u64 num_bytes;
Josef Bacik26ce2092019-06-20 15:37:59 -04001154 int ret = -ENOSPC;
1155
Josef Bacik26ce2092019-06-20 15:37:59 -04001156 spin_lock(&sinfo->lock);
1157 spin_lock(&cache->lock);
1158
1159 if (cache->ro) {
1160 cache->ro++;
1161 ret = 0;
1162 goto out;
1163 }
1164
David Sterbab3470b52019-10-23 18:48:22 +02001165 num_bytes = cache->length - cache->reserved - cache->pinned -
Naohiro Aota169e0da2021-02-04 19:21:52 +09001166 cache->bytes_super - cache->zone_unusable - cache->used;
Josef Bacik26ce2092019-06-20 15:37:59 -04001167
1168 /*
Josef Bacika30a3d22020-01-17 09:07:39 -05001169 * Data never overcommits, even in mixed mode, so do just the straight
1170 * check of left over space in how much we have allocated.
Josef Bacik26ce2092019-06-20 15:37:59 -04001171 */
Josef Bacika30a3d22020-01-17 09:07:39 -05001172 if (force) {
1173 ret = 0;
1174 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1175 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1176
1177 /*
1178 * Here we make sure if we mark this bg RO, we still have enough
1179 * free space as buffer.
1180 */
1181 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1182 ret = 0;
1183 } else {
1184 /*
1185 * We overcommit metadata, so we need to do the
1186 * btrfs_can_overcommit check here, and we need to pass in
1187 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1188 * leeway to allow us to mark this block group as read only.
1189 */
1190 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1191 BTRFS_RESERVE_NO_FLUSH))
1192 ret = 0;
1193 }
1194
1195 if (!ret) {
Josef Bacik26ce2092019-06-20 15:37:59 -04001196 sinfo->bytes_readonly += num_bytes;
Naohiro Aota169e0da2021-02-04 19:21:52 +09001197 if (btrfs_is_zoned(cache->fs_info)) {
1198 /* Migrate zone_unusable bytes to readonly */
1199 sinfo->bytes_readonly += cache->zone_unusable;
1200 sinfo->bytes_zone_unusable -= cache->zone_unusable;
1201 cache->zone_unusable = 0;
1202 }
Josef Bacik26ce2092019-06-20 15:37:59 -04001203 cache->ro++;
1204 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
Josef Bacik26ce2092019-06-20 15:37:59 -04001205 }
1206out:
1207 spin_unlock(&cache->lock);
1208 spin_unlock(&sinfo->lock);
1209 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1210 btrfs_info(cache->fs_info,
David Sterbab3470b52019-10-23 18:48:22 +02001211 "unable to make block group %llu ro", cache->start);
Josef Bacik26ce2092019-06-20 15:37:59 -04001212 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1213 }
1214 return ret;
1215}
1216
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001217static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1218 struct btrfs_block_group *bg)
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001219{
1220 struct btrfs_fs_info *fs_info = bg->fs_info;
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001221 struct btrfs_transaction *prev_trans = NULL;
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001222 const u64 start = bg->start;
1223 const u64 end = start + bg->length - 1;
1224 int ret;
1225
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001226 spin_lock(&fs_info->trans_lock);
1227 if (trans->transaction->list.prev != &fs_info->trans_list) {
1228 prev_trans = list_last_entry(&trans->transaction->list,
1229 struct btrfs_transaction, list);
1230 refcount_inc(&prev_trans->use_count);
1231 }
1232 spin_unlock(&fs_info->trans_lock);
1233
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001234 /*
1235 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1236 * btrfs_finish_extent_commit(). If we are at transaction N, another
1237 * task might be running finish_extent_commit() for the previous
1238 * transaction N - 1, and have seen a range belonging to the block
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001239 * group in pinned_extents before we were able to clear the whole block
1240 * group range from pinned_extents. This means that task can lookup for
1241 * the block group after we unpinned it from pinned_extents and removed
1242 * it, leading to a BUG_ON() at unpin_extent_range().
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001243 */
1244 mutex_lock(&fs_info->unused_bg_unpin_mutex);
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001245 if (prev_trans) {
1246 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1247 EXTENT_DIRTY);
1248 if (ret)
Filipe Manana534cf532020-04-17 16:36:50 +01001249 goto out;
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001250 }
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001251
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001252 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001253 EXTENT_DIRTY);
Filipe Manana534cf532020-04-17 16:36:50 +01001254out:
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001255 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
Filipe Manana5150bf12020-04-17 16:36:15 +01001256 if (prev_trans)
1257 btrfs_put_transaction(prev_trans);
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001258
Filipe Manana534cf532020-04-17 16:36:50 +01001259 return ret == 0;
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001260}
1261
Josef Bacik26ce2092019-06-20 15:37:59 -04001262/*
Josef Bacike3e05202019-06-20 15:37:55 -04001263 * Process the unused_bgs list and remove any that don't have any allocated
1264 * space inside of them.
1265 */
1266void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1267{
David Sterba32da53862019-10-29 19:20:18 +01001268 struct btrfs_block_group *block_group;
Josef Bacike3e05202019-06-20 15:37:55 -04001269 struct btrfs_space_info *space_info;
1270 struct btrfs_trans_handle *trans;
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001271 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
Josef Bacike3e05202019-06-20 15:37:55 -04001272 int ret = 0;
1273
1274 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1275 return;
1276
Josef Bacikddfd08c2020-12-18 14:24:19 -05001277 /*
1278 * Long running balances can keep us blocked here for eternity, so
1279 * simply skip deletion if we're unable to get the mutex.
1280 */
1281 if (!mutex_trylock(&fs_info->delete_unused_bgs_mutex))
1282 return;
1283
Josef Bacike3e05202019-06-20 15:37:55 -04001284 spin_lock(&fs_info->unused_bgs_lock);
1285 while (!list_empty(&fs_info->unused_bgs)) {
Josef Bacike3e05202019-06-20 15:37:55 -04001286 int trimming;
1287
1288 block_group = list_first_entry(&fs_info->unused_bgs,
David Sterba32da53862019-10-29 19:20:18 +01001289 struct btrfs_block_group,
Josef Bacike3e05202019-06-20 15:37:55 -04001290 bg_list);
1291 list_del_init(&block_group->bg_list);
1292
1293 space_info = block_group->space_info;
1294
1295 if (ret || btrfs_mixed_space_info(space_info)) {
1296 btrfs_put_block_group(block_group);
1297 continue;
1298 }
1299 spin_unlock(&fs_info->unused_bgs_lock);
1300
Dennis Zhoub0643e52019-12-13 16:22:14 -08001301 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1302
Josef Bacike3e05202019-06-20 15:37:55 -04001303 /* Don't want to race with allocators so take the groups_sem */
1304 down_write(&space_info->groups_sem);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001305
1306 /*
1307 * Async discard moves the final block group discard to be prior
1308 * to the unused_bgs code path. Therefore, if it's not fully
1309 * trimmed, punt it back to the async discard lists.
1310 */
1311 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1312 !btrfs_is_free_space_trimmed(block_group)) {
1313 trace_btrfs_skip_unused_block_group(block_group);
1314 up_write(&space_info->groups_sem);
1315 /* Requeue if we failed because of async discard */
1316 btrfs_discard_queue_work(&fs_info->discard_ctl,
1317 block_group);
1318 goto next;
1319 }
1320
Josef Bacike3e05202019-06-20 15:37:55 -04001321 spin_lock(&block_group->lock);
1322 if (block_group->reserved || block_group->pinned ||
David Sterbabf38be62019-10-23 18:48:11 +02001323 block_group->used || block_group->ro ||
Josef Bacike3e05202019-06-20 15:37:55 -04001324 list_is_singular(&block_group->list)) {
1325 /*
1326 * We want to bail if we made new allocations or have
1327 * outstanding allocations in this block group. We do
1328 * the ro check in case balance is currently acting on
1329 * this block group.
1330 */
1331 trace_btrfs_skip_unused_block_group(block_group);
1332 spin_unlock(&block_group->lock);
1333 up_write(&space_info->groups_sem);
1334 goto next;
1335 }
1336 spin_unlock(&block_group->lock);
1337
1338 /* We don't want to force the issue, only flip if it's ok. */
Josef Bacike11c0402019-06-20 15:38:07 -04001339 ret = inc_block_group_ro(block_group, 0);
Josef Bacike3e05202019-06-20 15:37:55 -04001340 up_write(&space_info->groups_sem);
1341 if (ret < 0) {
1342 ret = 0;
1343 goto next;
1344 }
1345
1346 /*
1347 * Want to do this before we do anything else so we can recover
1348 * properly if we fail to join the transaction.
1349 */
1350 trans = btrfs_start_trans_remove_block_group(fs_info,
David Sterbab3470b52019-10-23 18:48:22 +02001351 block_group->start);
Josef Bacike3e05202019-06-20 15:37:55 -04001352 if (IS_ERR(trans)) {
1353 btrfs_dec_block_group_ro(block_group);
1354 ret = PTR_ERR(trans);
1355 goto next;
1356 }
1357
1358 /*
1359 * We could have pending pinned extents for this block group,
1360 * just delete them, we don't care about them anymore.
1361 */
Filipe Manana534cf532020-04-17 16:36:50 +01001362 if (!clean_pinned_extents(trans, block_group)) {
1363 btrfs_dec_block_group_ro(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001364 goto end_trans;
Filipe Manana534cf532020-04-17 16:36:50 +01001365 }
Josef Bacike3e05202019-06-20 15:37:55 -04001366
Dennis Zhoub0643e52019-12-13 16:22:14 -08001367 /*
1368 * At this point, the block_group is read only and should fail
1369 * new allocations. However, btrfs_finish_extent_commit() can
1370 * cause this block_group to be placed back on the discard
1371 * lists because now the block_group isn't fully discarded.
1372 * Bail here and try again later after discarding everything.
1373 */
1374 spin_lock(&fs_info->discard_ctl.lock);
1375 if (!list_empty(&block_group->discard_list)) {
1376 spin_unlock(&fs_info->discard_ctl.lock);
1377 btrfs_dec_block_group_ro(block_group);
1378 btrfs_discard_queue_work(&fs_info->discard_ctl,
1379 block_group);
1380 goto end_trans;
1381 }
1382 spin_unlock(&fs_info->discard_ctl.lock);
1383
Josef Bacike3e05202019-06-20 15:37:55 -04001384 /* Reset pinned so btrfs_put_block_group doesn't complain */
1385 spin_lock(&space_info->lock);
1386 spin_lock(&block_group->lock);
1387
1388 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1389 -block_group->pinned);
1390 space_info->bytes_readonly += block_group->pinned;
Josef Bacik21873742021-01-15 16:48:55 -05001391 __btrfs_mod_total_bytes_pinned(space_info, -block_group->pinned);
Josef Bacike3e05202019-06-20 15:37:55 -04001392 block_group->pinned = 0;
1393
1394 spin_unlock(&block_group->lock);
1395 spin_unlock(&space_info->lock);
1396
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001397 /*
1398 * The normal path here is an unused block group is passed here,
1399 * then trimming is handled in the transaction commit path.
1400 * Async discard interposes before this to do the trimming
1401 * before coming down the unused block group path as trimming
1402 * will no longer be done later in the transaction commit path.
1403 */
1404 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1405 goto flip_async;
1406
Josef Bacike3e05202019-06-20 15:37:55 -04001407 /* DISCARD can flip during remount */
Dennis Zhou46b27f52019-12-13 16:22:11 -08001408 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
Josef Bacike3e05202019-06-20 15:37:55 -04001409
1410 /* Implicit trim during transaction commit. */
1411 if (trimming)
Filipe Manana6b7304a2020-05-08 11:01:47 +01001412 btrfs_freeze_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001413
1414 /*
1415 * Btrfs_remove_chunk will abort the transaction if things go
1416 * horribly wrong.
1417 */
David Sterbab3470b52019-10-23 18:48:22 +02001418 ret = btrfs_remove_chunk(trans, block_group->start);
Josef Bacike3e05202019-06-20 15:37:55 -04001419
1420 if (ret) {
1421 if (trimming)
Filipe Manana6b7304a2020-05-08 11:01:47 +01001422 btrfs_unfreeze_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001423 goto end_trans;
1424 }
1425
1426 /*
1427 * If we're not mounted with -odiscard, we can just forget
1428 * about this block group. Otherwise we'll need to wait
1429 * until transaction commit to do the actual discard.
1430 */
1431 if (trimming) {
1432 spin_lock(&fs_info->unused_bgs_lock);
1433 /*
1434 * A concurrent scrub might have added us to the list
1435 * fs_info->unused_bgs, so use a list_move operation
1436 * to add the block group to the deleted_bgs list.
1437 */
1438 list_move(&block_group->bg_list,
1439 &trans->transaction->deleted_bgs);
1440 spin_unlock(&fs_info->unused_bgs_lock);
1441 btrfs_get_block_group(block_group);
1442 }
1443end_trans:
1444 btrfs_end_transaction(trans);
1445next:
Josef Bacike3e05202019-06-20 15:37:55 -04001446 btrfs_put_block_group(block_group);
1447 spin_lock(&fs_info->unused_bgs_lock);
1448 }
1449 spin_unlock(&fs_info->unused_bgs_lock);
Josef Bacikddfd08c2020-12-18 14:24:19 -05001450 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001451 return;
1452
1453flip_async:
1454 btrfs_end_transaction(trans);
1455 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1456 btrfs_put_block_group(block_group);
1457 btrfs_discard_punt_unused_bgs_list(fs_info);
Josef Bacike3e05202019-06-20 15:37:55 -04001458}
1459
David Sterba32da53862019-10-29 19:20:18 +01001460void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
Josef Bacike3e05202019-06-20 15:37:55 -04001461{
1462 struct btrfs_fs_info *fs_info = bg->fs_info;
1463
1464 spin_lock(&fs_info->unused_bgs_lock);
1465 if (list_empty(&bg->bg_list)) {
1466 btrfs_get_block_group(bg);
1467 trace_btrfs_add_unused_block_group(bg);
1468 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1469 }
1470 spin_unlock(&fs_info->unused_bgs_lock);
1471}
Josef Bacik4358d9632019-06-20 15:37:57 -04001472
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001473static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1474 struct btrfs_path *path)
1475{
1476 struct extent_map_tree *em_tree;
1477 struct extent_map *em;
1478 struct btrfs_block_group_item bg;
1479 struct extent_buffer *leaf;
1480 int slot;
1481 u64 flags;
1482 int ret = 0;
1483
1484 slot = path->slots[0];
1485 leaf = path->nodes[0];
1486
1487 em_tree = &fs_info->mapping_tree;
1488 read_lock(&em_tree->lock);
1489 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1490 read_unlock(&em_tree->lock);
1491 if (!em) {
1492 btrfs_err(fs_info,
1493 "logical %llu len %llu found bg but no related chunk",
1494 key->objectid, key->offset);
1495 return -ENOENT;
1496 }
1497
1498 if (em->start != key->objectid || em->len != key->offset) {
1499 btrfs_err(fs_info,
1500 "block group %llu len %llu mismatch with chunk %llu len %llu",
1501 key->objectid, key->offset, em->start, em->len);
1502 ret = -EUCLEAN;
1503 goto out_free_em;
1504 }
1505
1506 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1507 sizeof(bg));
1508 flags = btrfs_stack_block_group_flags(&bg) &
1509 BTRFS_BLOCK_GROUP_TYPE_MASK;
1510
1511 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1512 btrfs_err(fs_info,
1513"block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1514 key->objectid, key->offset, flags,
1515 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1516 ret = -EUCLEAN;
1517 }
1518
1519out_free_em:
1520 free_extent_map(em);
1521 return ret;
1522}
1523
Josef Bacik4358d9632019-06-20 15:37:57 -04001524static int find_first_block_group(struct btrfs_fs_info *fs_info,
1525 struct btrfs_path *path,
1526 struct btrfs_key *key)
1527{
1528 struct btrfs_root *root = fs_info->extent_root;
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001529 int ret;
Josef Bacik4358d9632019-06-20 15:37:57 -04001530 struct btrfs_key found_key;
1531 struct extent_buffer *leaf;
Josef Bacik4358d9632019-06-20 15:37:57 -04001532 int slot;
1533
1534 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1535 if (ret < 0)
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001536 return ret;
Josef Bacik4358d9632019-06-20 15:37:57 -04001537
1538 while (1) {
1539 slot = path->slots[0];
1540 leaf = path->nodes[0];
1541 if (slot >= btrfs_header_nritems(leaf)) {
1542 ret = btrfs_next_leaf(root, path);
1543 if (ret == 0)
1544 continue;
1545 if (ret < 0)
1546 goto out;
1547 break;
1548 }
1549 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1550
1551 if (found_key.objectid >= key->objectid &&
1552 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001553 ret = read_bg_from_eb(fs_info, &found_key, path);
1554 break;
Josef Bacik4358d9632019-06-20 15:37:57 -04001555 }
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001556
Josef Bacik4358d9632019-06-20 15:37:57 -04001557 path->slots[0]++;
1558 }
1559out:
1560 return ret;
1561}
1562
1563static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1564{
1565 u64 extra_flags = chunk_to_extended(flags) &
1566 BTRFS_EXTENDED_PROFILE_MASK;
1567
1568 write_seqlock(&fs_info->profiles_lock);
1569 if (flags & BTRFS_BLOCK_GROUP_DATA)
1570 fs_info->avail_data_alloc_bits |= extra_flags;
1571 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1572 fs_info->avail_metadata_alloc_bits |= extra_flags;
1573 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1574 fs_info->avail_system_alloc_bits |= extra_flags;
1575 write_sequnlock(&fs_info->profiles_lock);
1576}
1577
Nikolay Borisov96a14332019-12-10 19:57:51 +02001578/**
Nikolay Borisov9ee9b972021-01-22 11:57:58 +02001579 * Map a physical disk address to a list of logical addresses
1580 *
1581 * @fs_info: the filesystem
Nikolay Borisov96a14332019-12-10 19:57:51 +02001582 * @chunk_start: logical address of block group
1583 * @physical: physical address to map to logical addresses
1584 * @logical: return array of logical addresses which map to @physical
1585 * @naddrs: length of @logical
1586 * @stripe_len: size of IO stripe for the given block group
1587 *
1588 * Maps a particular @physical disk address to a list of @logical addresses.
1589 * Used primarily to exclude those portions of a block group that contain super
1590 * block copies.
1591 */
1592EXPORT_FOR_TESTS
1593int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1594 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1595{
1596 struct extent_map *em;
1597 struct map_lookup *map;
1598 u64 *buf;
1599 u64 bytenr;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001600 u64 data_stripe_length;
1601 u64 io_stripe_size;
1602 int i, nr = 0;
1603 int ret = 0;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001604
1605 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1606 if (IS_ERR(em))
1607 return -EIO;
1608
1609 map = em->map_lookup;
Nikolay Borisov9e22b922020-04-03 16:40:34 +03001610 data_stripe_length = em->orig_block_len;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001611 io_stripe_size = map->stripe_len;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001612
Nikolay Borisov9e22b922020-04-03 16:40:34 +03001613 /* For RAID5/6 adjust to a full IO stripe length */
1614 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001615 io_stripe_size = map->stripe_len * nr_data_stripes(map);
Nikolay Borisov96a14332019-12-10 19:57:51 +02001616
1617 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001618 if (!buf) {
1619 ret = -ENOMEM;
1620 goto out;
1621 }
Nikolay Borisov96a14332019-12-10 19:57:51 +02001622
1623 for (i = 0; i < map->num_stripes; i++) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001624 bool already_inserted = false;
1625 u64 stripe_nr;
1626 int j;
1627
1628 if (!in_range(physical, map->stripes[i].physical,
1629 data_stripe_length))
Nikolay Borisov96a14332019-12-10 19:57:51 +02001630 continue;
1631
1632 stripe_nr = physical - map->stripes[i].physical;
1633 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1634
1635 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1636 stripe_nr = stripe_nr * map->num_stripes + i;
1637 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1638 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1639 stripe_nr = stripe_nr * map->num_stripes + i;
1640 }
1641 /*
1642 * The remaining case would be for RAID56, multiply by
1643 * nr_data_stripes(). Alternatively, just use rmap_len below
1644 * instead of map->stripe_len
1645 */
1646
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001647 bytenr = chunk_start + stripe_nr * io_stripe_size;
1648
1649 /* Ensure we don't add duplicate addresses */
Nikolay Borisov96a14332019-12-10 19:57:51 +02001650 for (j = 0; j < nr; j++) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001651 if (buf[j] == bytenr) {
1652 already_inserted = true;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001653 break;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001654 }
Nikolay Borisov96a14332019-12-10 19:57:51 +02001655 }
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001656
1657 if (!already_inserted)
Nikolay Borisov96a14332019-12-10 19:57:51 +02001658 buf[nr++] = bytenr;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001659 }
1660
1661 *logical = buf;
1662 *naddrs = nr;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001663 *stripe_len = io_stripe_size;
1664out:
Nikolay Borisov96a14332019-12-10 19:57:51 +02001665 free_extent_map(em);
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001666 return ret;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001667}
1668
David Sterba32da53862019-10-29 19:20:18 +01001669static int exclude_super_stripes(struct btrfs_block_group *cache)
Josef Bacik4358d9632019-06-20 15:37:57 -04001670{
1671 struct btrfs_fs_info *fs_info = cache->fs_info;
Naohiro Aota12659252020-11-10 20:26:14 +09001672 const bool zoned = btrfs_is_zoned(fs_info);
Josef Bacik4358d9632019-06-20 15:37:57 -04001673 u64 bytenr;
1674 u64 *logical;
1675 int stripe_len;
1676 int i, nr, ret;
1677
David Sterbab3470b52019-10-23 18:48:22 +02001678 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1679 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
Josef Bacik4358d9632019-06-20 15:37:57 -04001680 cache->bytes_super += stripe_len;
David Sterbab3470b52019-10-23 18:48:22 +02001681 ret = btrfs_add_excluded_extent(fs_info, cache->start,
Josef Bacik4358d9632019-06-20 15:37:57 -04001682 stripe_len);
1683 if (ret)
1684 return ret;
1685 }
1686
1687 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1688 bytenr = btrfs_sb_offset(i);
David Sterbab3470b52019-10-23 18:48:22 +02001689 ret = btrfs_rmap_block(fs_info, cache->start,
Josef Bacik4358d9632019-06-20 15:37:57 -04001690 bytenr, &logical, &nr, &stripe_len);
1691 if (ret)
1692 return ret;
1693
Naohiro Aota12659252020-11-10 20:26:14 +09001694 /* Shouldn't have super stripes in sequential zones */
1695 if (zoned && nr) {
1696 btrfs_err(fs_info,
1697 "zoned: block group %llu must not contain super block",
1698 cache->start);
1699 return -EUCLEAN;
1700 }
1701
Josef Bacik4358d9632019-06-20 15:37:57 -04001702 while (nr--) {
Nikolay Borisov96f9b0f2020-04-03 16:40:35 +03001703 u64 len = min_t(u64, stripe_len,
1704 cache->start + cache->length - logical[nr]);
Josef Bacik4358d9632019-06-20 15:37:57 -04001705
1706 cache->bytes_super += len;
Nikolay Borisov96f9b0f2020-04-03 16:40:35 +03001707 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1708 len);
Josef Bacik4358d9632019-06-20 15:37:57 -04001709 if (ret) {
1710 kfree(logical);
1711 return ret;
1712 }
1713 }
1714
1715 kfree(logical);
1716 }
1717 return 0;
1718}
1719
David Sterba32da53862019-10-29 19:20:18 +01001720static void link_block_group(struct btrfs_block_group *cache)
Josef Bacik4358d9632019-06-20 15:37:57 -04001721{
1722 struct btrfs_space_info *space_info = cache->space_info;
1723 int index = btrfs_bg_flags_to_raid_index(cache->flags);
Josef Bacik4358d9632019-06-20 15:37:57 -04001724
1725 down_write(&space_info->groups_sem);
Josef Bacik4358d9632019-06-20 15:37:57 -04001726 list_add_tail(&cache->list, &space_info->block_groups[index]);
1727 up_write(&space_info->groups_sem);
Josef Bacik4358d9632019-06-20 15:37:57 -04001728}
1729
David Sterba32da53862019-10-29 19:20:18 +01001730static struct btrfs_block_group *btrfs_create_block_group_cache(
Qu Wenruo9afc6642020-05-05 07:58:20 +08001731 struct btrfs_fs_info *fs_info, u64 start)
Josef Bacik4358d9632019-06-20 15:37:57 -04001732{
David Sterba32da53862019-10-29 19:20:18 +01001733 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04001734
1735 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1736 if (!cache)
1737 return NULL;
1738
1739 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1740 GFP_NOFS);
1741 if (!cache->free_space_ctl) {
1742 kfree(cache);
1743 return NULL;
1744 }
1745
David Sterbab3470b52019-10-23 18:48:22 +02001746 cache->start = start;
Josef Bacik4358d9632019-06-20 15:37:57 -04001747
1748 cache->fs_info = fs_info;
1749 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
Josef Bacik4358d9632019-06-20 15:37:57 -04001750
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001751 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1752
Josef Bacik48aaeeb2020-07-06 09:14:11 -04001753 refcount_set(&cache->refs, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04001754 spin_lock_init(&cache->lock);
1755 init_rwsem(&cache->data_rwsem);
1756 INIT_LIST_HEAD(&cache->list);
1757 INIT_LIST_HEAD(&cache->cluster_list);
1758 INIT_LIST_HEAD(&cache->bg_list);
1759 INIT_LIST_HEAD(&cache->ro_list);
Dennis Zhoub0643e52019-12-13 16:22:14 -08001760 INIT_LIST_HEAD(&cache->discard_list);
Josef Bacik4358d9632019-06-20 15:37:57 -04001761 INIT_LIST_HEAD(&cache->dirty_list);
1762 INIT_LIST_HEAD(&cache->io_list);
Josef Bacikcd799092020-10-23 09:58:08 -04001763 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
Filipe Manana6b7304a2020-05-08 11:01:47 +01001764 atomic_set(&cache->frozen, 0);
Josef Bacik4358d9632019-06-20 15:37:57 -04001765 mutex_init(&cache->free_space_lock);
1766 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1767
1768 return cache;
1769}
1770
1771/*
1772 * Iterate all chunks and verify that each of them has the corresponding block
1773 * group
1774 */
1775static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1776{
1777 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1778 struct extent_map *em;
David Sterba32da53862019-10-29 19:20:18 +01001779 struct btrfs_block_group *bg;
Josef Bacik4358d9632019-06-20 15:37:57 -04001780 u64 start = 0;
1781 int ret = 0;
1782
1783 while (1) {
1784 read_lock(&map_tree->lock);
1785 /*
1786 * lookup_extent_mapping will return the first extent map
1787 * intersecting the range, so setting @len to 1 is enough to
1788 * get the first chunk.
1789 */
1790 em = lookup_extent_mapping(map_tree, start, 1);
1791 read_unlock(&map_tree->lock);
1792 if (!em)
1793 break;
1794
1795 bg = btrfs_lookup_block_group(fs_info, em->start);
1796 if (!bg) {
1797 btrfs_err(fs_info,
1798 "chunk start=%llu len=%llu doesn't have corresponding block group",
1799 em->start, em->len);
1800 ret = -EUCLEAN;
1801 free_extent_map(em);
1802 break;
1803 }
David Sterbab3470b52019-10-23 18:48:22 +02001804 if (bg->start != em->start || bg->length != em->len ||
Josef Bacik4358d9632019-06-20 15:37:57 -04001805 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1806 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1807 btrfs_err(fs_info,
1808"chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1809 em->start, em->len,
1810 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
David Sterbab3470b52019-10-23 18:48:22 +02001811 bg->start, bg->length,
Josef Bacik4358d9632019-06-20 15:37:57 -04001812 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1813 ret = -EUCLEAN;
1814 free_extent_map(em);
1815 btrfs_put_block_group(bg);
1816 break;
1817 }
1818 start = em->start + em->len;
1819 free_extent_map(em);
1820 btrfs_put_block_group(bg);
1821 }
1822 return ret;
1823}
1824
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001825static int read_one_block_group(struct btrfs_fs_info *info,
Johannes Thumshirn4afd2fe2021-02-04 19:21:44 +09001826 struct btrfs_block_group_item *bgi,
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001827 const struct btrfs_key *key,
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001828 int need_clear)
1829{
David Sterba32da53862019-10-29 19:20:18 +01001830 struct btrfs_block_group *cache;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001831 struct btrfs_space_info *space_info;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001832 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001833 int ret;
1834
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001835 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001836
Qu Wenruo9afc6642020-05-05 07:58:20 +08001837 cache = btrfs_create_block_group_cache(info, key->objectid);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001838 if (!cache)
1839 return -ENOMEM;
1840
Johannes Thumshirn4afd2fe2021-02-04 19:21:44 +09001841 cache->length = key->offset;
1842 cache->used = btrfs_stack_block_group_used(bgi);
1843 cache->flags = btrfs_stack_block_group_flags(bgi);
Qu Wenruo9afc6642020-05-05 07:58:20 +08001844
Marcos Paulo de Souzae3e39c72020-08-21 11:54:44 -03001845 set_free_space_tree_thresholds(cache);
1846
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001847 if (need_clear) {
1848 /*
1849 * When we mount with old space cache, we need to
1850 * set BTRFS_DC_CLEAR and set dirty flag.
1851 *
1852 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1853 * truncate the old free space cache inode and
1854 * setup a new one.
1855 * b) Setting 'dirty flag' makes sure that we flush
1856 * the new space cache info onto disk.
1857 */
1858 if (btrfs_test_opt(info, SPACE_CACHE))
1859 cache->disk_cache_state = BTRFS_DC_CLEAR;
1860 }
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001861 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1862 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1863 btrfs_err(info,
1864"bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1865 cache->start);
1866 ret = -EINVAL;
1867 goto error;
1868 }
1869
Naohiro Aotaa94794d2021-02-04 19:21:51 +09001870 ret = btrfs_load_block_group_zone_info(cache, false);
Naohiro Aota08e11a32021-02-04 19:21:50 +09001871 if (ret) {
1872 btrfs_err(info, "zoned: failed to load zone info of bg %llu",
1873 cache->start);
1874 goto error;
1875 }
1876
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001877 /*
1878 * We need to exclude the super stripes now so that the space info has
1879 * super bytes accounted for, otherwise we'll think we have more space
1880 * than we actually do.
1881 */
1882 ret = exclude_super_stripes(cache);
1883 if (ret) {
1884 /* We may have excluded something, so call this just in case. */
1885 btrfs_free_excluded_extents(cache);
1886 goto error;
1887 }
1888
1889 /*
Naohiro Aota169e0da2021-02-04 19:21:52 +09001890 * For zoned filesystem, space after the allocation offset is the only
1891 * free space for a block group. So, we don't need any caching work.
1892 * btrfs_calc_zone_unusable() will set the amount of free space and
1893 * zone_unusable space.
1894 *
1895 * For regular filesystem, check for two cases, either we are full, and
1896 * therefore don't need to bother with the caching work since we won't
1897 * find any space, or we are empty, and we can just add all the space
1898 * in and be done with it. This saves us _a_lot_ of time, particularly
1899 * in the full case.
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001900 */
Naohiro Aota169e0da2021-02-04 19:21:52 +09001901 if (btrfs_is_zoned(info)) {
1902 btrfs_calc_zone_unusable(cache);
1903 } else if (cache->length == cache->used) {
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001904 cache->last_byte_to_unpin = (u64)-1;
1905 cache->cached = BTRFS_CACHE_FINISHED;
1906 btrfs_free_excluded_extents(cache);
1907 } else if (cache->used == 0) {
1908 cache->last_byte_to_unpin = (u64)-1;
1909 cache->cached = BTRFS_CACHE_FINISHED;
Qu Wenruo9afc6642020-05-05 07:58:20 +08001910 add_new_free_space(cache, cache->start,
1911 cache->start + cache->length);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001912 btrfs_free_excluded_extents(cache);
1913 }
1914
1915 ret = btrfs_add_block_group_cache(info, cache);
1916 if (ret) {
1917 btrfs_remove_free_space_cache(cache);
1918 goto error;
1919 }
1920 trace_btrfs_add_block_group(info, cache, 0);
Qu Wenruo9afc6642020-05-05 07:58:20 +08001921 btrfs_update_space_info(info, cache->flags, cache->length,
Naohiro Aota169e0da2021-02-04 19:21:52 +09001922 cache->used, cache->bytes_super,
1923 cache->zone_unusable, &space_info);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001924
1925 cache->space_info = space_info;
1926
1927 link_block_group(cache);
1928
1929 set_avail_alloc_bits(info, cache->flags);
1930 if (btrfs_chunk_readonly(info, cache->start)) {
1931 inc_block_group_ro(cache, 1);
1932 } else if (cache->used == 0) {
1933 ASSERT(list_empty(&cache->bg_list));
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001934 if (btrfs_test_opt(info, DISCARD_ASYNC))
1935 btrfs_discard_queue_work(&info->discard_ctl, cache);
1936 else
1937 btrfs_mark_bg_unused(cache);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001938 }
1939 return 0;
1940error:
1941 btrfs_put_block_group(cache);
1942 return ret;
1943}
1944
Josef Bacik42437a62020-10-16 11:29:18 -04001945static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
1946{
1947 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1948 struct btrfs_space_info *space_info;
1949 struct rb_node *node;
1950 int ret = 0;
1951
1952 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
1953 struct extent_map *em;
1954 struct map_lookup *map;
1955 struct btrfs_block_group *bg;
1956
1957 em = rb_entry(node, struct extent_map, rb_node);
1958 map = em->map_lookup;
1959 bg = btrfs_create_block_group_cache(fs_info, em->start);
1960 if (!bg) {
1961 ret = -ENOMEM;
1962 break;
1963 }
1964
1965 /* Fill dummy cache as FULL */
1966 bg->length = em->len;
1967 bg->flags = map->type;
1968 bg->last_byte_to_unpin = (u64)-1;
1969 bg->cached = BTRFS_CACHE_FINISHED;
1970 bg->used = em->len;
1971 bg->flags = map->type;
1972 ret = btrfs_add_block_group_cache(fs_info, bg);
1973 if (ret) {
1974 btrfs_remove_free_space_cache(bg);
1975 btrfs_put_block_group(bg);
1976 break;
1977 }
1978 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
Naohiro Aota169e0da2021-02-04 19:21:52 +09001979 0, 0, &space_info);
Josef Bacik42437a62020-10-16 11:29:18 -04001980 bg->space_info = space_info;
1981 link_block_group(bg);
1982
1983 set_avail_alloc_bits(fs_info, bg->flags);
1984 }
1985 if (!ret)
1986 btrfs_init_global_block_rsv(fs_info);
1987 return ret;
1988}
1989
Josef Bacik4358d9632019-06-20 15:37:57 -04001990int btrfs_read_block_groups(struct btrfs_fs_info *info)
1991{
1992 struct btrfs_path *path;
1993 int ret;
David Sterba32da53862019-10-29 19:20:18 +01001994 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04001995 struct btrfs_space_info *space_info;
1996 struct btrfs_key key;
Josef Bacik4358d9632019-06-20 15:37:57 -04001997 int need_clear = 0;
1998 u64 cache_gen;
Josef Bacik4358d9632019-06-20 15:37:57 -04001999
Josef Bacik42437a62020-10-16 11:29:18 -04002000 if (!info->extent_root)
2001 return fill_dummy_bgs(info);
2002
Josef Bacik4358d9632019-06-20 15:37:57 -04002003 key.objectid = 0;
2004 key.offset = 0;
2005 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2006 path = btrfs_alloc_path();
2007 if (!path)
2008 return -ENOMEM;
Josef Bacik4358d9632019-06-20 15:37:57 -04002009
2010 cache_gen = btrfs_super_cache_generation(info->super_copy);
2011 if (btrfs_test_opt(info, SPACE_CACHE) &&
2012 btrfs_super_generation(info->super_copy) != cache_gen)
2013 need_clear = 1;
2014 if (btrfs_test_opt(info, CLEAR_CACHE))
2015 need_clear = 1;
2016
2017 while (1) {
Johannes Thumshirn4afd2fe2021-02-04 19:21:44 +09002018 struct btrfs_block_group_item bgi;
2019 struct extent_buffer *leaf;
2020 int slot;
2021
Josef Bacik4358d9632019-06-20 15:37:57 -04002022 ret = find_first_block_group(info, path, &key);
2023 if (ret > 0)
2024 break;
2025 if (ret != 0)
2026 goto error;
2027
Johannes Thumshirn4afd2fe2021-02-04 19:21:44 +09002028 leaf = path->nodes[0];
2029 slot = path->slots[0];
2030
2031 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2032 sizeof(bgi));
2033
2034 btrfs_item_key_to_cpu(leaf, &key, slot);
2035 btrfs_release_path(path);
2036 ret = read_one_block_group(info, &bgi, &key, need_clear);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002037 if (ret < 0)
Josef Bacik4358d9632019-06-20 15:37:57 -04002038 goto error;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002039 key.objectid += key.offset;
2040 key.offset = 0;
Josef Bacik4358d9632019-06-20 15:37:57 -04002041 }
Josef Bacik7837fa82020-10-14 17:00:51 -04002042 btrfs_release_path(path);
Josef Bacik4358d9632019-06-20 15:37:57 -04002043
Josef Bacik72804902020-09-01 17:40:37 -04002044 list_for_each_entry(space_info, &info->space_info, list) {
Josef Bacik49ea1122020-09-01 17:40:38 -04002045 int i;
2046
2047 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2048 if (list_empty(&space_info->block_groups[i]))
2049 continue;
2050 cache = list_first_entry(&space_info->block_groups[i],
2051 struct btrfs_block_group,
2052 list);
2053 btrfs_sysfs_add_block_group_type(cache);
2054 }
2055
Josef Bacik4358d9632019-06-20 15:37:57 -04002056 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2057 (BTRFS_BLOCK_GROUP_RAID10 |
2058 BTRFS_BLOCK_GROUP_RAID1_MASK |
2059 BTRFS_BLOCK_GROUP_RAID56_MASK |
2060 BTRFS_BLOCK_GROUP_DUP)))
2061 continue;
2062 /*
2063 * Avoid allocating from un-mirrored block group if there are
2064 * mirrored block groups.
2065 */
2066 list_for_each_entry(cache,
2067 &space_info->block_groups[BTRFS_RAID_RAID0],
2068 list)
Josef Bacike11c0402019-06-20 15:38:07 -04002069 inc_block_group_ro(cache, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04002070 list_for_each_entry(cache,
2071 &space_info->block_groups[BTRFS_RAID_SINGLE],
2072 list)
Josef Bacike11c0402019-06-20 15:38:07 -04002073 inc_block_group_ro(cache, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04002074 }
2075
2076 btrfs_init_global_block_rsv(info);
2077 ret = check_chunk_block_group_mappings(info);
2078error:
2079 btrfs_free_path(path);
2080 return ret;
2081}
2082
Qu Wenruo97f47282020-05-05 07:58:22 +08002083static int insert_block_group_item(struct btrfs_trans_handle *trans,
2084 struct btrfs_block_group *block_group)
2085{
2086 struct btrfs_fs_info *fs_info = trans->fs_info;
2087 struct btrfs_block_group_item bgi;
2088 struct btrfs_root *root;
2089 struct btrfs_key key;
2090
2091 spin_lock(&block_group->lock);
2092 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2093 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2094 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2095 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2096 key.objectid = block_group->start;
2097 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2098 key.offset = block_group->length;
2099 spin_unlock(&block_group->lock);
2100
2101 root = fs_info->extent_root;
2102 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2103}
2104
Josef Bacik4358d9632019-06-20 15:37:57 -04002105void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2106{
2107 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002108 struct btrfs_block_group *block_group;
Josef Bacik4358d9632019-06-20 15:37:57 -04002109 int ret = 0;
2110
2111 if (!trans->can_flush_pending_bgs)
2112 return;
2113
2114 while (!list_empty(&trans->new_bgs)) {
Josef Bacik49ea1122020-09-01 17:40:38 -04002115 int index;
2116
Josef Bacik4358d9632019-06-20 15:37:57 -04002117 block_group = list_first_entry(&trans->new_bgs,
David Sterba32da53862019-10-29 19:20:18 +01002118 struct btrfs_block_group,
Josef Bacik4358d9632019-06-20 15:37:57 -04002119 bg_list);
2120 if (ret)
2121 goto next;
2122
Josef Bacik49ea1122020-09-01 17:40:38 -04002123 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2124
Qu Wenruo97f47282020-05-05 07:58:22 +08002125 ret = insert_block_group_item(trans, block_group);
Josef Bacik4358d9632019-06-20 15:37:57 -04002126 if (ret)
2127 btrfs_abort_transaction(trans, ret);
Qu Wenruo97f47282020-05-05 07:58:22 +08002128 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2129 block_group->length);
Josef Bacik4358d9632019-06-20 15:37:57 -04002130 if (ret)
2131 btrfs_abort_transaction(trans, ret);
2132 add_block_group_free_space(trans, block_group);
Josef Bacik49ea1122020-09-01 17:40:38 -04002133
2134 /*
2135 * If we restriped during balance, we may have added a new raid
2136 * type, so now add the sysfs entries when it is safe to do so.
2137 * We don't have to worry about locking here as it's handled in
2138 * btrfs_sysfs_add_block_group_type.
2139 */
2140 if (block_group->space_info->block_group_kobjs[index] == NULL)
2141 btrfs_sysfs_add_block_group_type(block_group);
2142
Josef Bacik4358d9632019-06-20 15:37:57 -04002143 /* Already aborted the transaction if it failed. */
2144next:
2145 btrfs_delayed_refs_rsv_release(fs_info, 1);
2146 list_del_init(&block_group->bg_list);
2147 }
2148 btrfs_trans_release_chunk_metadata(trans);
2149}
2150
2151int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2152 u64 type, u64 chunk_offset, u64 size)
2153{
2154 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002155 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04002156 int ret;
2157
2158 btrfs_set_log_full_commit(trans);
2159
Qu Wenruo9afc6642020-05-05 07:58:20 +08002160 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
Josef Bacik4358d9632019-06-20 15:37:57 -04002161 if (!cache)
2162 return -ENOMEM;
2163
Qu Wenruo9afc6642020-05-05 07:58:20 +08002164 cache->length = size;
Marcos Paulo de Souzae3e39c72020-08-21 11:54:44 -03002165 set_free_space_tree_thresholds(cache);
David Sterbabf38be62019-10-23 18:48:11 +02002166 cache->used = bytes_used;
Josef Bacik4358d9632019-06-20 15:37:57 -04002167 cache->flags = type;
2168 cache->last_byte_to_unpin = (u64)-1;
2169 cache->cached = BTRFS_CACHE_FINISHED;
Boris Burkov997e3e22020-11-18 15:06:18 -08002170 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
2171 cache->needs_free_space = 1;
Naohiro Aota08e11a32021-02-04 19:21:50 +09002172
Naohiro Aotaa94794d2021-02-04 19:21:51 +09002173 ret = btrfs_load_block_group_zone_info(cache, true);
Naohiro Aota08e11a32021-02-04 19:21:50 +09002174 if (ret) {
2175 btrfs_put_block_group(cache);
2176 return ret;
2177 }
2178
Josef Bacik4358d9632019-06-20 15:37:57 -04002179 ret = exclude_super_stripes(cache);
2180 if (ret) {
2181 /* We may have excluded something, so call this just in case */
2182 btrfs_free_excluded_extents(cache);
2183 btrfs_put_block_group(cache);
2184 return ret;
2185 }
2186
2187 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2188
2189 btrfs_free_excluded_extents(cache);
2190
2191#ifdef CONFIG_BTRFS_DEBUG
2192 if (btrfs_should_fragment_free_space(cache)) {
2193 u64 new_bytes_used = size - bytes_used;
2194
2195 bytes_used += new_bytes_used >> 1;
Josef Bacike11c0402019-06-20 15:38:07 -04002196 fragment_free_space(cache);
Josef Bacik4358d9632019-06-20 15:37:57 -04002197 }
2198#endif
2199 /*
2200 * Ensure the corresponding space_info object is created and
2201 * assigned to our block group. We want our bg to be added to the rbtree
2202 * with its ->space_info set.
2203 */
2204 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2205 ASSERT(cache->space_info);
2206
2207 ret = btrfs_add_block_group_cache(fs_info, cache);
2208 if (ret) {
2209 btrfs_remove_free_space_cache(cache);
2210 btrfs_put_block_group(cache);
2211 return ret;
2212 }
2213
2214 /*
2215 * Now that our block group has its ->space_info set and is inserted in
2216 * the rbtree, update the space info's counters.
2217 */
2218 trace_btrfs_add_block_group(fs_info, cache, 1);
2219 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
Naohiro Aota169e0da2021-02-04 19:21:52 +09002220 cache->bytes_super, 0, &cache->space_info);
Josef Bacik4358d9632019-06-20 15:37:57 -04002221 btrfs_update_global_block_rsv(fs_info);
2222
2223 link_block_group(cache);
2224
2225 list_add_tail(&cache->bg_list, &trans->new_bgs);
2226 trans->delayed_ref_updates++;
2227 btrfs_update_delayed_refs_rsv(trans);
2228
2229 set_avail_alloc_bits(fs_info, type);
2230 return 0;
2231}
Josef Bacik26ce2092019-06-20 15:37:59 -04002232
Qu Wenruob12de522019-11-15 10:09:00 +08002233/*
2234 * Mark one block group RO, can be called several times for the same block
2235 * group.
2236 *
2237 * @cache: the destination block group
2238 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2239 * ensure we still have some free space after marking this
2240 * block group RO.
2241 */
2242int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2243 bool do_chunk_alloc)
Josef Bacik26ce2092019-06-20 15:37:59 -04002244{
2245 struct btrfs_fs_info *fs_info = cache->fs_info;
2246 struct btrfs_trans_handle *trans;
2247 u64 alloc_flags;
2248 int ret;
2249
2250again:
2251 trans = btrfs_join_transaction(fs_info->extent_root);
2252 if (IS_ERR(trans))
2253 return PTR_ERR(trans);
2254
2255 /*
2256 * we're not allowed to set block groups readonly after the dirty
2257 * block groups cache has started writing. If it already started,
2258 * back off and let this transaction commit
2259 */
2260 mutex_lock(&fs_info->ro_block_group_mutex);
2261 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2262 u64 transid = trans->transid;
2263
2264 mutex_unlock(&fs_info->ro_block_group_mutex);
2265 btrfs_end_transaction(trans);
2266
2267 ret = btrfs_wait_for_commit(fs_info, transid);
2268 if (ret)
2269 return ret;
2270 goto again;
2271 }
2272
Qu Wenruob12de522019-11-15 10:09:00 +08002273 if (do_chunk_alloc) {
Josef Bacik26ce2092019-06-20 15:37:59 -04002274 /*
Qu Wenruob12de522019-11-15 10:09:00 +08002275 * If we are changing raid levels, try to allocate a
2276 * corresponding block group with the new raid level.
Josef Bacik26ce2092019-06-20 15:37:59 -04002277 */
Josef Bacik349e1202020-07-21 10:48:45 -04002278 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
Qu Wenruob12de522019-11-15 10:09:00 +08002279 if (alloc_flags != cache->flags) {
2280 ret = btrfs_chunk_alloc(trans, alloc_flags,
2281 CHUNK_ALLOC_FORCE);
2282 /*
2283 * ENOSPC is allowed here, we may have enough space
2284 * already allocated at the new raid level to carry on
2285 */
2286 if (ret == -ENOSPC)
2287 ret = 0;
2288 if (ret < 0)
2289 goto out;
2290 }
Josef Bacik26ce2092019-06-20 15:37:59 -04002291 }
2292
Josef Bacika7a63acc2020-01-17 09:07:38 -05002293 ret = inc_block_group_ro(cache, 0);
Qu Wenruob12de522019-11-15 10:09:00 +08002294 if (!do_chunk_alloc)
2295 goto unlock_out;
Josef Bacik26ce2092019-06-20 15:37:59 -04002296 if (!ret)
2297 goto out;
2298 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2299 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2300 if (ret < 0)
2301 goto out;
Josef Bacike11c0402019-06-20 15:38:07 -04002302 ret = inc_block_group_ro(cache, 0);
Josef Bacik26ce2092019-06-20 15:37:59 -04002303out:
2304 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
Josef Bacik349e1202020-07-21 10:48:45 -04002305 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
Josef Bacik26ce2092019-06-20 15:37:59 -04002306 mutex_lock(&fs_info->chunk_mutex);
2307 check_system_chunk(trans, alloc_flags);
2308 mutex_unlock(&fs_info->chunk_mutex);
2309 }
Qu Wenruob12de522019-11-15 10:09:00 +08002310unlock_out:
Josef Bacik26ce2092019-06-20 15:37:59 -04002311 mutex_unlock(&fs_info->ro_block_group_mutex);
2312
2313 btrfs_end_transaction(trans);
2314 return ret;
2315}
2316
David Sterba32da53862019-10-29 19:20:18 +01002317void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
Josef Bacik26ce2092019-06-20 15:37:59 -04002318{
2319 struct btrfs_space_info *sinfo = cache->space_info;
2320 u64 num_bytes;
2321
2322 BUG_ON(!cache->ro);
2323
2324 spin_lock(&sinfo->lock);
2325 spin_lock(&cache->lock);
2326 if (!--cache->ro) {
David Sterbab3470b52019-10-23 18:48:22 +02002327 num_bytes = cache->length - cache->reserved -
Naohiro Aota169e0da2021-02-04 19:21:52 +09002328 cache->pinned - cache->bytes_super -
2329 cache->zone_unusable - cache->used;
Josef Bacik26ce2092019-06-20 15:37:59 -04002330 sinfo->bytes_readonly -= num_bytes;
Naohiro Aota169e0da2021-02-04 19:21:52 +09002331 if (btrfs_is_zoned(cache->fs_info)) {
2332 /* Migrate zone_unusable bytes back */
2333 cache->zone_unusable = cache->alloc_offset - cache->used;
2334 sinfo->bytes_zone_unusable += cache->zone_unusable;
2335 sinfo->bytes_readonly -= cache->zone_unusable;
2336 }
Josef Bacik26ce2092019-06-20 15:37:59 -04002337 list_del_init(&cache->ro_list);
2338 }
2339 spin_unlock(&cache->lock);
2340 spin_unlock(&sinfo->lock);
2341}
Josef Bacik77745c02019-06-20 15:38:00 -04002342
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002343static int update_block_group_item(struct btrfs_trans_handle *trans,
2344 struct btrfs_path *path,
2345 struct btrfs_block_group *cache)
Josef Bacik77745c02019-06-20 15:38:00 -04002346{
2347 struct btrfs_fs_info *fs_info = trans->fs_info;
2348 int ret;
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002349 struct btrfs_root *root = fs_info->extent_root;
Josef Bacik77745c02019-06-20 15:38:00 -04002350 unsigned long bi;
2351 struct extent_buffer *leaf;
David Sterbabf38be62019-10-23 18:48:11 +02002352 struct btrfs_block_group_item bgi;
David Sterbab3470b52019-10-23 18:48:22 +02002353 struct btrfs_key key;
Josef Bacik77745c02019-06-20 15:38:00 -04002354
David Sterbab3470b52019-10-23 18:48:22 +02002355 key.objectid = cache->start;
2356 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2357 key.offset = cache->length;
2358
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002359 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
Josef Bacik77745c02019-06-20 15:38:00 -04002360 if (ret) {
2361 if (ret > 0)
2362 ret = -ENOENT;
2363 goto fail;
2364 }
2365
2366 leaf = path->nodes[0];
2367 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
David Sterbade0dc452019-10-23 18:48:18 +02002368 btrfs_set_stack_block_group_used(&bgi, cache->used);
2369 btrfs_set_stack_block_group_chunk_objectid(&bgi,
David Sterba3d976382019-10-23 18:48:15 +02002370 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
David Sterbade0dc452019-10-23 18:48:18 +02002371 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
David Sterbabf38be62019-10-23 18:48:11 +02002372 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
Josef Bacik77745c02019-06-20 15:38:00 -04002373 btrfs_mark_buffer_dirty(leaf);
2374fail:
2375 btrfs_release_path(path);
2376 return ret;
2377
2378}
2379
David Sterba32da53862019-10-29 19:20:18 +01002380static int cache_save_setup(struct btrfs_block_group *block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002381 struct btrfs_trans_handle *trans,
2382 struct btrfs_path *path)
2383{
2384 struct btrfs_fs_info *fs_info = block_group->fs_info;
2385 struct btrfs_root *root = fs_info->tree_root;
2386 struct inode *inode = NULL;
2387 struct extent_changeset *data_reserved = NULL;
2388 u64 alloc_hint = 0;
2389 int dcs = BTRFS_DC_ERROR;
2390 u64 num_pages = 0;
2391 int retries = 0;
2392 int ret = 0;
2393
Boris Burkovaf456a22020-11-18 15:06:26 -08002394 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2395 return 0;
2396
Josef Bacik77745c02019-06-20 15:38:00 -04002397 /*
2398 * If this block group is smaller than 100 megs don't bother caching the
2399 * block group.
2400 */
David Sterbab3470b52019-10-23 18:48:22 +02002401 if (block_group->length < (100 * SZ_1M)) {
Josef Bacik77745c02019-06-20 15:38:00 -04002402 spin_lock(&block_group->lock);
2403 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2404 spin_unlock(&block_group->lock);
2405 return 0;
2406 }
2407
David Sterbabf31f872020-02-05 17:34:34 +01002408 if (TRANS_ABORTED(trans))
Josef Bacik77745c02019-06-20 15:38:00 -04002409 return 0;
2410again:
2411 inode = lookup_free_space_inode(block_group, path);
2412 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2413 ret = PTR_ERR(inode);
2414 btrfs_release_path(path);
2415 goto out;
2416 }
2417
2418 if (IS_ERR(inode)) {
2419 BUG_ON(retries);
2420 retries++;
2421
2422 if (block_group->ro)
2423 goto out_free;
2424
2425 ret = create_free_space_inode(trans, block_group, path);
2426 if (ret)
2427 goto out_free;
2428 goto again;
2429 }
2430
2431 /*
2432 * We want to set the generation to 0, that way if anything goes wrong
2433 * from here on out we know not to trust this cache when we load up next
2434 * time.
2435 */
2436 BTRFS_I(inode)->generation = 0;
Nikolay Borisov9a56fcd2020-11-02 16:48:59 +02002437 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
Josef Bacik77745c02019-06-20 15:38:00 -04002438 if (ret) {
2439 /*
2440 * So theoretically we could recover from this, simply set the
2441 * super cache generation to 0 so we know to invalidate the
2442 * cache, but then we'd have to keep track of the block groups
2443 * that fail this way so we know we _have_ to reset this cache
2444 * before the next commit or risk reading stale cache. So to
2445 * limit our exposure to horrible edge cases lets just abort the
2446 * transaction, this only happens in really bad situations
2447 * anyway.
2448 */
2449 btrfs_abort_transaction(trans, ret);
2450 goto out_put;
2451 }
2452 WARN_ON(ret);
2453
2454 /* We've already setup this transaction, go ahead and exit */
2455 if (block_group->cache_generation == trans->transid &&
2456 i_size_read(inode)) {
2457 dcs = BTRFS_DC_SETUP;
2458 goto out_put;
2459 }
2460
2461 if (i_size_read(inode) > 0) {
2462 ret = btrfs_check_trunc_cache_free_space(fs_info,
2463 &fs_info->global_block_rsv);
2464 if (ret)
2465 goto out_put;
2466
2467 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2468 if (ret)
2469 goto out_put;
2470 }
2471
2472 spin_lock(&block_group->lock);
2473 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2474 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2475 /*
2476 * don't bother trying to write stuff out _if_
2477 * a) we're not cached,
2478 * b) we're with nospace_cache mount option,
2479 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2480 */
2481 dcs = BTRFS_DC_WRITTEN;
2482 spin_unlock(&block_group->lock);
2483 goto out_put;
2484 }
2485 spin_unlock(&block_group->lock);
2486
2487 /*
2488 * We hit an ENOSPC when setting up the cache in this transaction, just
2489 * skip doing the setup, we've already cleared the cache so we're safe.
2490 */
2491 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2492 ret = -ENOSPC;
2493 goto out_put;
2494 }
2495
2496 /*
2497 * Try to preallocate enough space based on how big the block group is.
2498 * Keep in mind this has to include any pinned space which could end up
2499 * taking up quite a bit since it's not folded into the other space
2500 * cache.
2501 */
David Sterbab3470b52019-10-23 18:48:22 +02002502 num_pages = div_u64(block_group->length, SZ_256M);
Josef Bacik77745c02019-06-20 15:38:00 -04002503 if (!num_pages)
2504 num_pages = 1;
2505
2506 num_pages *= 16;
2507 num_pages *= PAGE_SIZE;
2508
Nikolay Borisov36ea6f32020-06-03 08:55:41 +03002509 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2510 num_pages);
Josef Bacik77745c02019-06-20 15:38:00 -04002511 if (ret)
2512 goto out_put;
2513
2514 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2515 num_pages, num_pages,
2516 &alloc_hint);
2517 /*
2518 * Our cache requires contiguous chunks so that we don't modify a bunch
2519 * of metadata or split extents when writing the cache out, which means
2520 * we can enospc if we are heavily fragmented in addition to just normal
2521 * out of space conditions. So if we hit this just skip setting up any
2522 * other block groups for this transaction, maybe we'll unpin enough
2523 * space the next time around.
2524 */
2525 if (!ret)
2526 dcs = BTRFS_DC_SETUP;
2527 else if (ret == -ENOSPC)
2528 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2529
2530out_put:
2531 iput(inode);
2532out_free:
2533 btrfs_release_path(path);
2534out:
2535 spin_lock(&block_group->lock);
2536 if (!ret && dcs == BTRFS_DC_SETUP)
2537 block_group->cache_generation = trans->transid;
2538 block_group->disk_cache_state = dcs;
2539 spin_unlock(&block_group->lock);
2540
2541 extent_changeset_free(data_reserved);
2542 return ret;
2543}
2544
2545int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2546{
2547 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002548 struct btrfs_block_group *cache, *tmp;
Josef Bacik77745c02019-06-20 15:38:00 -04002549 struct btrfs_transaction *cur_trans = trans->transaction;
2550 struct btrfs_path *path;
2551
2552 if (list_empty(&cur_trans->dirty_bgs) ||
2553 !btrfs_test_opt(fs_info, SPACE_CACHE))
2554 return 0;
2555
2556 path = btrfs_alloc_path();
2557 if (!path)
2558 return -ENOMEM;
2559
2560 /* Could add new block groups, use _safe just in case */
2561 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2562 dirty_list) {
2563 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2564 cache_save_setup(cache, trans, path);
2565 }
2566
2567 btrfs_free_path(path);
2568 return 0;
2569}
2570
2571/*
2572 * Transaction commit does final block group cache writeback during a critical
2573 * section where nothing is allowed to change the FS. This is required in
2574 * order for the cache to actually match the block group, but can introduce a
2575 * lot of latency into the commit.
2576 *
2577 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2578 * There's a chance we'll have to redo some of it if the block group changes
2579 * again during the commit, but it greatly reduces the commit latency by
2580 * getting rid of the easy block groups while we're still allowing others to
2581 * join the commit.
2582 */
2583int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2584{
2585 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002586 struct btrfs_block_group *cache;
Josef Bacik77745c02019-06-20 15:38:00 -04002587 struct btrfs_transaction *cur_trans = trans->transaction;
2588 int ret = 0;
2589 int should_put;
2590 struct btrfs_path *path = NULL;
2591 LIST_HEAD(dirty);
2592 struct list_head *io = &cur_trans->io_bgs;
2593 int num_started = 0;
2594 int loops = 0;
2595
2596 spin_lock(&cur_trans->dirty_bgs_lock);
2597 if (list_empty(&cur_trans->dirty_bgs)) {
2598 spin_unlock(&cur_trans->dirty_bgs_lock);
2599 return 0;
2600 }
2601 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2602 spin_unlock(&cur_trans->dirty_bgs_lock);
2603
2604again:
2605 /* Make sure all the block groups on our dirty list actually exist */
2606 btrfs_create_pending_block_groups(trans);
2607
2608 if (!path) {
2609 path = btrfs_alloc_path();
Josef Bacik938fcbf2021-01-14 14:02:43 -05002610 if (!path) {
2611 ret = -ENOMEM;
2612 goto out;
2613 }
Josef Bacik77745c02019-06-20 15:38:00 -04002614 }
2615
2616 /*
2617 * cache_write_mutex is here only to save us from balance or automatic
2618 * removal of empty block groups deleting this block group while we are
2619 * writing out the cache
2620 */
2621 mutex_lock(&trans->transaction->cache_write_mutex);
2622 while (!list_empty(&dirty)) {
2623 bool drop_reserve = true;
2624
David Sterba32da53862019-10-29 19:20:18 +01002625 cache = list_first_entry(&dirty, struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002626 dirty_list);
2627 /*
2628 * This can happen if something re-dirties a block group that
2629 * is already under IO. Just wait for it to finish and then do
2630 * it all again
2631 */
2632 if (!list_empty(&cache->io_list)) {
2633 list_del_init(&cache->io_list);
2634 btrfs_wait_cache_io(trans, cache, path);
2635 btrfs_put_block_group(cache);
2636 }
2637
2638
2639 /*
2640 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2641 * it should update the cache_state. Don't delete until after
2642 * we wait.
2643 *
2644 * Since we're not running in the commit critical section
2645 * we need the dirty_bgs_lock to protect from update_block_group
2646 */
2647 spin_lock(&cur_trans->dirty_bgs_lock);
2648 list_del_init(&cache->dirty_list);
2649 spin_unlock(&cur_trans->dirty_bgs_lock);
2650
2651 should_put = 1;
2652
2653 cache_save_setup(cache, trans, path);
2654
2655 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2656 cache->io_ctl.inode = NULL;
2657 ret = btrfs_write_out_cache(trans, cache, path);
2658 if (ret == 0 && cache->io_ctl.inode) {
2659 num_started++;
2660 should_put = 0;
2661
2662 /*
2663 * The cache_write_mutex is protecting the
2664 * io_list, also refer to the definition of
2665 * btrfs_transaction::io_bgs for more details
2666 */
2667 list_add_tail(&cache->io_list, io);
2668 } else {
2669 /*
2670 * If we failed to write the cache, the
2671 * generation will be bad and life goes on
2672 */
2673 ret = 0;
2674 }
2675 }
2676 if (!ret) {
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002677 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002678 /*
2679 * Our block group might still be attached to the list
2680 * of new block groups in the transaction handle of some
2681 * other task (struct btrfs_trans_handle->new_bgs). This
2682 * means its block group item isn't yet in the extent
2683 * tree. If this happens ignore the error, as we will
2684 * try again later in the critical section of the
2685 * transaction commit.
2686 */
2687 if (ret == -ENOENT) {
2688 ret = 0;
2689 spin_lock(&cur_trans->dirty_bgs_lock);
2690 if (list_empty(&cache->dirty_list)) {
2691 list_add_tail(&cache->dirty_list,
2692 &cur_trans->dirty_bgs);
2693 btrfs_get_block_group(cache);
2694 drop_reserve = false;
2695 }
2696 spin_unlock(&cur_trans->dirty_bgs_lock);
2697 } else if (ret) {
2698 btrfs_abort_transaction(trans, ret);
2699 }
2700 }
2701
2702 /* If it's not on the io list, we need to put the block group */
2703 if (should_put)
2704 btrfs_put_block_group(cache);
2705 if (drop_reserve)
2706 btrfs_delayed_refs_rsv_release(fs_info, 1);
Josef Bacik77745c02019-06-20 15:38:00 -04002707 /*
2708 * Avoid blocking other tasks for too long. It might even save
2709 * us from writing caches for block groups that are going to be
2710 * removed.
2711 */
2712 mutex_unlock(&trans->transaction->cache_write_mutex);
Josef Bacik938fcbf2021-01-14 14:02:43 -05002713 if (ret)
2714 goto out;
Josef Bacik77745c02019-06-20 15:38:00 -04002715 mutex_lock(&trans->transaction->cache_write_mutex);
2716 }
2717 mutex_unlock(&trans->transaction->cache_write_mutex);
2718
2719 /*
2720 * Go through delayed refs for all the stuff we've just kicked off
2721 * and then loop back (just once)
2722 */
Josef Bacik34d1eb02020-12-16 11:22:17 -05002723 if (!ret)
2724 ret = btrfs_run_delayed_refs(trans, 0);
Josef Bacik77745c02019-06-20 15:38:00 -04002725 if (!ret && loops == 0) {
2726 loops++;
2727 spin_lock(&cur_trans->dirty_bgs_lock);
2728 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2729 /*
2730 * dirty_bgs_lock protects us from concurrent block group
2731 * deletes too (not just cache_write_mutex).
2732 */
2733 if (!list_empty(&dirty)) {
2734 spin_unlock(&cur_trans->dirty_bgs_lock);
2735 goto again;
2736 }
2737 spin_unlock(&cur_trans->dirty_bgs_lock);
Josef Bacik938fcbf2021-01-14 14:02:43 -05002738 }
2739out:
2740 if (ret < 0) {
2741 spin_lock(&cur_trans->dirty_bgs_lock);
2742 list_splice_init(&dirty, &cur_trans->dirty_bgs);
2743 spin_unlock(&cur_trans->dirty_bgs_lock);
Josef Bacik77745c02019-06-20 15:38:00 -04002744 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2745 }
2746
2747 btrfs_free_path(path);
2748 return ret;
2749}
2750
2751int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2752{
2753 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002754 struct btrfs_block_group *cache;
Josef Bacik77745c02019-06-20 15:38:00 -04002755 struct btrfs_transaction *cur_trans = trans->transaction;
2756 int ret = 0;
2757 int should_put;
2758 struct btrfs_path *path;
2759 struct list_head *io = &cur_trans->io_bgs;
2760 int num_started = 0;
2761
2762 path = btrfs_alloc_path();
2763 if (!path)
2764 return -ENOMEM;
2765
2766 /*
2767 * Even though we are in the critical section of the transaction commit,
2768 * we can still have concurrent tasks adding elements to this
2769 * transaction's list of dirty block groups. These tasks correspond to
2770 * endio free space workers started when writeback finishes for a
2771 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2772 * allocate new block groups as a result of COWing nodes of the root
2773 * tree when updating the free space inode. The writeback for the space
2774 * caches is triggered by an earlier call to
2775 * btrfs_start_dirty_block_groups() and iterations of the following
2776 * loop.
2777 * Also we want to do the cache_save_setup first and then run the
2778 * delayed refs to make sure we have the best chance at doing this all
2779 * in one shot.
2780 */
2781 spin_lock(&cur_trans->dirty_bgs_lock);
2782 while (!list_empty(&cur_trans->dirty_bgs)) {
2783 cache = list_first_entry(&cur_trans->dirty_bgs,
David Sterba32da53862019-10-29 19:20:18 +01002784 struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002785 dirty_list);
2786
2787 /*
2788 * This can happen if cache_save_setup re-dirties a block group
2789 * that is already under IO. Just wait for it to finish and
2790 * then do it all again
2791 */
2792 if (!list_empty(&cache->io_list)) {
2793 spin_unlock(&cur_trans->dirty_bgs_lock);
2794 list_del_init(&cache->io_list);
2795 btrfs_wait_cache_io(trans, cache, path);
2796 btrfs_put_block_group(cache);
2797 spin_lock(&cur_trans->dirty_bgs_lock);
2798 }
2799
2800 /*
2801 * Don't remove from the dirty list until after we've waited on
2802 * any pending IO
2803 */
2804 list_del_init(&cache->dirty_list);
2805 spin_unlock(&cur_trans->dirty_bgs_lock);
2806 should_put = 1;
2807
2808 cache_save_setup(cache, trans, path);
2809
2810 if (!ret)
2811 ret = btrfs_run_delayed_refs(trans,
2812 (unsigned long) -1);
2813
2814 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2815 cache->io_ctl.inode = NULL;
2816 ret = btrfs_write_out_cache(trans, cache, path);
2817 if (ret == 0 && cache->io_ctl.inode) {
2818 num_started++;
2819 should_put = 0;
2820 list_add_tail(&cache->io_list, io);
2821 } else {
2822 /*
2823 * If we failed to write the cache, the
2824 * generation will be bad and life goes on
2825 */
2826 ret = 0;
2827 }
2828 }
2829 if (!ret) {
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002830 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002831 /*
2832 * One of the free space endio workers might have
2833 * created a new block group while updating a free space
2834 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2835 * and hasn't released its transaction handle yet, in
2836 * which case the new block group is still attached to
2837 * its transaction handle and its creation has not
2838 * finished yet (no block group item in the extent tree
2839 * yet, etc). If this is the case, wait for all free
2840 * space endio workers to finish and retry. This is a
Randy Dunlap260db432020-08-04 19:48:34 -07002841 * very rare case so no need for a more efficient and
Josef Bacik77745c02019-06-20 15:38:00 -04002842 * complex approach.
2843 */
2844 if (ret == -ENOENT) {
2845 wait_event(cur_trans->writer_wait,
2846 atomic_read(&cur_trans->num_writers) == 1);
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002847 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002848 }
2849 if (ret)
2850 btrfs_abort_transaction(trans, ret);
2851 }
2852
2853 /* If its not on the io list, we need to put the block group */
2854 if (should_put)
2855 btrfs_put_block_group(cache);
2856 btrfs_delayed_refs_rsv_release(fs_info, 1);
2857 spin_lock(&cur_trans->dirty_bgs_lock);
2858 }
2859 spin_unlock(&cur_trans->dirty_bgs_lock);
2860
2861 /*
2862 * Refer to the definition of io_bgs member for details why it's safe
2863 * to use it without any locking
2864 */
2865 while (!list_empty(io)) {
David Sterba32da53862019-10-29 19:20:18 +01002866 cache = list_first_entry(io, struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002867 io_list);
2868 list_del_init(&cache->io_list);
2869 btrfs_wait_cache_io(trans, cache, path);
2870 btrfs_put_block_group(cache);
2871 }
2872
2873 btrfs_free_path(path);
2874 return ret;
2875}
Josef Bacik606d1bf2019-06-20 15:38:02 -04002876
2877int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2878 u64 bytenr, u64 num_bytes, int alloc)
2879{
2880 struct btrfs_fs_info *info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002881 struct btrfs_block_group *cache = NULL;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002882 u64 total = num_bytes;
2883 u64 old_val;
2884 u64 byte_in_group;
2885 int factor;
2886 int ret = 0;
2887
2888 /* Block accounting for super block */
2889 spin_lock(&info->delalloc_root_lock);
2890 old_val = btrfs_super_bytes_used(info->super_copy);
2891 if (alloc)
2892 old_val += num_bytes;
2893 else
2894 old_val -= num_bytes;
2895 btrfs_set_super_bytes_used(info->super_copy, old_val);
2896 spin_unlock(&info->delalloc_root_lock);
2897
2898 while (total) {
2899 cache = btrfs_lookup_block_group(info, bytenr);
2900 if (!cache) {
2901 ret = -ENOENT;
2902 break;
2903 }
2904 factor = btrfs_bg_type_to_factor(cache->flags);
2905
2906 /*
2907 * If this block group has free space cache written out, we
2908 * need to make sure to load it if we are removing space. This
2909 * is because we need the unpinning stage to actually add the
2910 * space back to the block group, otherwise we will leak space.
2911 */
David Sterba32da53862019-10-29 19:20:18 +01002912 if (!alloc && !btrfs_block_group_done(cache))
Josef Bacik606d1bf2019-06-20 15:38:02 -04002913 btrfs_cache_block_group(cache, 1);
2914
David Sterbab3470b52019-10-23 18:48:22 +02002915 byte_in_group = bytenr - cache->start;
2916 WARN_ON(byte_in_group > cache->length);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002917
2918 spin_lock(&cache->space_info->lock);
2919 spin_lock(&cache->lock);
2920
2921 if (btrfs_test_opt(info, SPACE_CACHE) &&
2922 cache->disk_cache_state < BTRFS_DC_CLEAR)
2923 cache->disk_cache_state = BTRFS_DC_CLEAR;
2924
David Sterbabf38be62019-10-23 18:48:11 +02002925 old_val = cache->used;
David Sterbab3470b52019-10-23 18:48:22 +02002926 num_bytes = min(total, cache->length - byte_in_group);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002927 if (alloc) {
2928 old_val += num_bytes;
David Sterbabf38be62019-10-23 18:48:11 +02002929 cache->used = old_val;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002930 cache->reserved -= num_bytes;
2931 cache->space_info->bytes_reserved -= num_bytes;
2932 cache->space_info->bytes_used += num_bytes;
2933 cache->space_info->disk_used += num_bytes * factor;
2934 spin_unlock(&cache->lock);
2935 spin_unlock(&cache->space_info->lock);
2936 } else {
2937 old_val -= num_bytes;
David Sterbabf38be62019-10-23 18:48:11 +02002938 cache->used = old_val;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002939 cache->pinned += num_bytes;
2940 btrfs_space_info_update_bytes_pinned(info,
2941 cache->space_info, num_bytes);
2942 cache->space_info->bytes_used -= num_bytes;
2943 cache->space_info->disk_used -= num_bytes * factor;
2944 spin_unlock(&cache->lock);
2945 spin_unlock(&cache->space_info->lock);
2946
Josef Bacik21873742021-01-15 16:48:55 -05002947 __btrfs_mod_total_bytes_pinned(cache->space_info,
2948 num_bytes);
Nikolay Borisovfe119a62020-01-20 16:09:18 +02002949 set_extent_dirty(&trans->transaction->pinned_extents,
Josef Bacik606d1bf2019-06-20 15:38:02 -04002950 bytenr, bytenr + num_bytes - 1,
2951 GFP_NOFS | __GFP_NOFAIL);
2952 }
2953
2954 spin_lock(&trans->transaction->dirty_bgs_lock);
2955 if (list_empty(&cache->dirty_list)) {
2956 list_add_tail(&cache->dirty_list,
2957 &trans->transaction->dirty_bgs);
2958 trans->delayed_ref_updates++;
2959 btrfs_get_block_group(cache);
2960 }
2961 spin_unlock(&trans->transaction->dirty_bgs_lock);
2962
2963 /*
2964 * No longer have used bytes in this block group, queue it for
2965 * deletion. We do this after adding the block group to the
2966 * dirty list to avoid races between cleaner kthread and space
2967 * cache writeout.
2968 */
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08002969 if (!alloc && old_val == 0) {
2970 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2971 btrfs_mark_bg_unused(cache);
2972 }
Josef Bacik606d1bf2019-06-20 15:38:02 -04002973
2974 btrfs_put_block_group(cache);
2975 total -= num_bytes;
2976 bytenr += num_bytes;
2977 }
2978
2979 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2980 btrfs_update_delayed_refs_rsv(trans);
2981 return ret;
2982}
2983
2984/**
2985 * btrfs_add_reserved_bytes - update the block_group and space info counters
2986 * @cache: The cache we are manipulating
2987 * @ram_bytes: The number of bytes of file content, and will be same to
2988 * @num_bytes except for the compress path.
2989 * @num_bytes: The number of bytes in question
2990 * @delalloc: The blocks are allocated for the delalloc write
2991 *
2992 * This is called by the allocator when it reserves space. If this is a
2993 * reservation and the block group has become read only we cannot make the
2994 * reservation and return -EAGAIN, otherwise this function always succeeds.
2995 */
David Sterba32da53862019-10-29 19:20:18 +01002996int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
Josef Bacik606d1bf2019-06-20 15:38:02 -04002997 u64 ram_bytes, u64 num_bytes, int delalloc)
2998{
2999 struct btrfs_space_info *space_info = cache->space_info;
3000 int ret = 0;
3001
3002 spin_lock(&space_info->lock);
3003 spin_lock(&cache->lock);
3004 if (cache->ro) {
3005 ret = -EAGAIN;
3006 } else {
3007 cache->reserved += num_bytes;
3008 space_info->bytes_reserved += num_bytes;
Josef Bacika43c3832019-08-22 15:10:56 -04003009 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3010 space_info->flags, num_bytes, 1);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003011 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3012 space_info, -ram_bytes);
3013 if (delalloc)
3014 cache->delalloc_bytes += num_bytes;
Josef Bacik99ffb432020-07-21 10:22:19 -04003015
3016 /*
3017 * Compression can use less space than we reserved, so wake
3018 * tickets if that happens
3019 */
3020 if (num_bytes < ram_bytes)
3021 btrfs_try_granting_tickets(cache->fs_info, space_info);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003022 }
3023 spin_unlock(&cache->lock);
3024 spin_unlock(&space_info->lock);
3025 return ret;
3026}
3027
3028/**
3029 * btrfs_free_reserved_bytes - update the block_group and space info counters
3030 * @cache: The cache we are manipulating
3031 * @num_bytes: The number of bytes in question
3032 * @delalloc: The blocks are allocated for the delalloc write
3033 *
3034 * This is called by somebody who is freeing space that was never actually used
3035 * on disk. For example if you reserve some space for a new leaf in transaction
3036 * A and before transaction A commits you free that leaf, you call this with
3037 * reserve set to 0 in order to clear the reservation.
3038 */
David Sterba32da53862019-10-29 19:20:18 +01003039void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
Josef Bacik606d1bf2019-06-20 15:38:02 -04003040 u64 num_bytes, int delalloc)
3041{
3042 struct btrfs_space_info *space_info = cache->space_info;
3043
3044 spin_lock(&space_info->lock);
3045 spin_lock(&cache->lock);
3046 if (cache->ro)
3047 space_info->bytes_readonly += num_bytes;
3048 cache->reserved -= num_bytes;
3049 space_info->bytes_reserved -= num_bytes;
3050 space_info->max_extent_size = 0;
3051
3052 if (delalloc)
3053 cache->delalloc_bytes -= num_bytes;
3054 spin_unlock(&cache->lock);
Josef Bacik33082342020-07-21 10:22:17 -04003055
3056 btrfs_try_granting_tickets(cache->fs_info, space_info);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003057 spin_unlock(&space_info->lock);
3058}
Josef Bacik07730d82019-06-20 15:38:04 -04003059
3060static void force_metadata_allocation(struct btrfs_fs_info *info)
3061{
3062 struct list_head *head = &info->space_info;
3063 struct btrfs_space_info *found;
3064
Josef Bacik72804902020-09-01 17:40:37 -04003065 list_for_each_entry(found, head, list) {
Josef Bacik07730d82019-06-20 15:38:04 -04003066 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3067 found->force_alloc = CHUNK_ALLOC_FORCE;
3068 }
Josef Bacik07730d82019-06-20 15:38:04 -04003069}
3070
3071static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3072 struct btrfs_space_info *sinfo, int force)
3073{
3074 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3075 u64 thresh;
3076
3077 if (force == CHUNK_ALLOC_FORCE)
3078 return 1;
3079
3080 /*
3081 * in limited mode, we want to have some free space up to
3082 * about 1% of the FS size.
3083 */
3084 if (force == CHUNK_ALLOC_LIMITED) {
3085 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3086 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3087
3088 if (sinfo->total_bytes - bytes_used < thresh)
3089 return 1;
3090 }
3091
3092 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3093 return 0;
3094 return 1;
3095}
3096
3097int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3098{
3099 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3100
3101 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3102}
3103
3104/*
3105 * If force is CHUNK_ALLOC_FORCE:
3106 * - return 1 if it successfully allocates a chunk,
3107 * - return errors including -ENOSPC otherwise.
3108 * If force is NOT CHUNK_ALLOC_FORCE:
3109 * - return 0 if it doesn't need to allocate a new chunk,
3110 * - return 1 if it successfully allocates a chunk,
3111 * - return errors including -ENOSPC otherwise.
3112 */
3113int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3114 enum btrfs_chunk_alloc_enum force)
3115{
3116 struct btrfs_fs_info *fs_info = trans->fs_info;
3117 struct btrfs_space_info *space_info;
3118 bool wait_for_alloc = false;
3119 bool should_alloc = false;
3120 int ret = 0;
3121
3122 /* Don't re-enter if we're already allocating a chunk */
3123 if (trans->allocating_chunk)
3124 return -ENOSPC;
3125
3126 space_info = btrfs_find_space_info(fs_info, flags);
3127 ASSERT(space_info);
3128
3129 do {
3130 spin_lock(&space_info->lock);
3131 if (force < space_info->force_alloc)
3132 force = space_info->force_alloc;
3133 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3134 if (space_info->full) {
3135 /* No more free physical space */
3136 if (should_alloc)
3137 ret = -ENOSPC;
3138 else
3139 ret = 0;
3140 spin_unlock(&space_info->lock);
3141 return ret;
3142 } else if (!should_alloc) {
3143 spin_unlock(&space_info->lock);
3144 return 0;
3145 } else if (space_info->chunk_alloc) {
3146 /*
3147 * Someone is already allocating, so we need to block
3148 * until this someone is finished and then loop to
3149 * recheck if we should continue with our allocation
3150 * attempt.
3151 */
3152 wait_for_alloc = true;
3153 spin_unlock(&space_info->lock);
3154 mutex_lock(&fs_info->chunk_mutex);
3155 mutex_unlock(&fs_info->chunk_mutex);
3156 } else {
3157 /* Proceed with allocation */
3158 space_info->chunk_alloc = 1;
3159 wait_for_alloc = false;
3160 spin_unlock(&space_info->lock);
3161 }
3162
3163 cond_resched();
3164 } while (wait_for_alloc);
3165
3166 mutex_lock(&fs_info->chunk_mutex);
3167 trans->allocating_chunk = true;
3168
3169 /*
3170 * If we have mixed data/metadata chunks we want to make sure we keep
3171 * allocating mixed chunks instead of individual chunks.
3172 */
3173 if (btrfs_mixed_space_info(space_info))
3174 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3175
3176 /*
3177 * if we're doing a data chunk, go ahead and make sure that
3178 * we keep a reasonable number of metadata chunks allocated in the
3179 * FS as well.
3180 */
3181 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3182 fs_info->data_chunk_allocations++;
3183 if (!(fs_info->data_chunk_allocations %
3184 fs_info->metadata_ratio))
3185 force_metadata_allocation(fs_info);
3186 }
3187
3188 /*
3189 * Check if we have enough space in SYSTEM chunk because we may need
3190 * to update devices.
3191 */
3192 check_system_chunk(trans, flags);
3193
3194 ret = btrfs_alloc_chunk(trans, flags);
3195 trans->allocating_chunk = false;
3196
3197 spin_lock(&space_info->lock);
3198 if (ret < 0) {
3199 if (ret == -ENOSPC)
3200 space_info->full = 1;
3201 else
3202 goto out;
3203 } else {
3204 ret = 1;
3205 space_info->max_extent_size = 0;
3206 }
3207
3208 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3209out:
3210 space_info->chunk_alloc = 0;
3211 spin_unlock(&space_info->lock);
3212 mutex_unlock(&fs_info->chunk_mutex);
3213 /*
3214 * When we allocate a new chunk we reserve space in the chunk block
3215 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3216 * add new nodes/leafs to it if we end up needing to do it when
3217 * inserting the chunk item and updating device items as part of the
3218 * second phase of chunk allocation, performed by
3219 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3220 * large number of new block groups to create in our transaction
3221 * handle's new_bgs list to avoid exhausting the chunk block reserve
3222 * in extreme cases - like having a single transaction create many new
3223 * block groups when starting to write out the free space caches of all
3224 * the block groups that were made dirty during the lifetime of the
3225 * transaction.
3226 */
3227 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3228 btrfs_create_pending_block_groups(trans);
3229
3230 return ret;
3231}
3232
3233static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3234{
3235 u64 num_dev;
3236
3237 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3238 if (!num_dev)
3239 num_dev = fs_info->fs_devices->rw_devices;
3240
3241 return num_dev;
3242}
3243
3244/*
Marcos Paulo de Souzaa9143bd2019-10-07 21:50:38 -03003245 * Reserve space in the system space for allocating or removing a chunk
Josef Bacik07730d82019-06-20 15:38:04 -04003246 */
3247void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3248{
3249 struct btrfs_fs_info *fs_info = trans->fs_info;
3250 struct btrfs_space_info *info;
3251 u64 left;
3252 u64 thresh;
3253 int ret = 0;
3254 u64 num_devs;
3255
3256 /*
3257 * Needed because we can end up allocating a system chunk and for an
3258 * atomic and race free space reservation in the chunk block reserve.
3259 */
3260 lockdep_assert_held(&fs_info->chunk_mutex);
3261
3262 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3263 spin_lock(&info->lock);
3264 left = info->total_bytes - btrfs_space_info_used(info, true);
3265 spin_unlock(&info->lock);
3266
3267 num_devs = get_profile_num_devs(fs_info, type);
3268
3269 /* num_devs device items to update and 1 chunk item to add or remove */
Josef Bacik2bd36e72019-08-22 15:14:33 -04003270 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3271 btrfs_calc_insert_metadata_size(fs_info, 1);
Josef Bacik07730d82019-06-20 15:38:04 -04003272
3273 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3274 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3275 left, thresh, type);
3276 btrfs_dump_space_info(fs_info, info, 0, 0);
3277 }
3278
3279 if (left < thresh) {
3280 u64 flags = btrfs_system_alloc_profile(fs_info);
3281
3282 /*
3283 * Ignore failure to create system chunk. We might end up not
3284 * needing it, as we might not need to COW all nodes/leafs from
3285 * the paths we visit in the chunk tree (they were already COWed
3286 * or created in the current transaction for example).
3287 */
3288 ret = btrfs_alloc_chunk(trans, flags);
3289 }
3290
3291 if (!ret) {
3292 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3293 &fs_info->chunk_block_rsv,
3294 thresh, BTRFS_RESERVE_NO_FLUSH);
3295 if (!ret)
3296 trans->chunk_bytes_reserved += thresh;
3297 }
3298}
3299
Josef Bacik3e43c272019-06-20 15:38:06 -04003300void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3301{
David Sterba32da53862019-10-29 19:20:18 +01003302 struct btrfs_block_group *block_group;
Josef Bacik3e43c272019-06-20 15:38:06 -04003303 u64 last = 0;
3304
3305 while (1) {
3306 struct inode *inode;
3307
3308 block_group = btrfs_lookup_first_block_group(info, last);
3309 while (block_group) {
3310 btrfs_wait_block_group_cache_done(block_group);
3311 spin_lock(&block_group->lock);
3312 if (block_group->iref)
3313 break;
3314 spin_unlock(&block_group->lock);
3315 block_group = btrfs_next_block_group(block_group);
3316 }
3317 if (!block_group) {
3318 if (last == 0)
3319 break;
3320 last = 0;
3321 continue;
3322 }
3323
3324 inode = block_group->inode;
3325 block_group->iref = 0;
3326 block_group->inode = NULL;
3327 spin_unlock(&block_group->lock);
3328 ASSERT(block_group->io_ctl.inode == NULL);
3329 iput(inode);
David Sterbab3470b52019-10-23 18:48:22 +02003330 last = block_group->start + block_group->length;
Josef Bacik3e43c272019-06-20 15:38:06 -04003331 btrfs_put_block_group(block_group);
3332 }
3333}
3334
3335/*
3336 * Must be called only after stopping all workers, since we could have block
3337 * group caching kthreads running, and therefore they could race with us if we
3338 * freed the block groups before stopping them.
3339 */
3340int btrfs_free_block_groups(struct btrfs_fs_info *info)
3341{
David Sterba32da53862019-10-29 19:20:18 +01003342 struct btrfs_block_group *block_group;
Josef Bacik3e43c272019-06-20 15:38:06 -04003343 struct btrfs_space_info *space_info;
3344 struct btrfs_caching_control *caching_ctl;
3345 struct rb_node *n;
3346
Josef Bacikbbb86a32020-10-23 09:58:11 -04003347 spin_lock(&info->block_group_cache_lock);
Josef Bacik3e43c272019-06-20 15:38:06 -04003348 while (!list_empty(&info->caching_block_groups)) {
3349 caching_ctl = list_entry(info->caching_block_groups.next,
3350 struct btrfs_caching_control, list);
3351 list_del(&caching_ctl->list);
3352 btrfs_put_caching_control(caching_ctl);
3353 }
Josef Bacikbbb86a32020-10-23 09:58:11 -04003354 spin_unlock(&info->block_group_cache_lock);
Josef Bacik3e43c272019-06-20 15:38:06 -04003355
3356 spin_lock(&info->unused_bgs_lock);
3357 while (!list_empty(&info->unused_bgs)) {
3358 block_group = list_first_entry(&info->unused_bgs,
David Sterba32da53862019-10-29 19:20:18 +01003359 struct btrfs_block_group,
Josef Bacik3e43c272019-06-20 15:38:06 -04003360 bg_list);
3361 list_del_init(&block_group->bg_list);
3362 btrfs_put_block_group(block_group);
3363 }
3364 spin_unlock(&info->unused_bgs_lock);
3365
3366 spin_lock(&info->block_group_cache_lock);
3367 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
David Sterba32da53862019-10-29 19:20:18 +01003368 block_group = rb_entry(n, struct btrfs_block_group,
Josef Bacik3e43c272019-06-20 15:38:06 -04003369 cache_node);
3370 rb_erase(&block_group->cache_node,
3371 &info->block_group_cache_tree);
3372 RB_CLEAR_NODE(&block_group->cache_node);
3373 spin_unlock(&info->block_group_cache_lock);
3374
3375 down_write(&block_group->space_info->groups_sem);
3376 list_del(&block_group->list);
3377 up_write(&block_group->space_info->groups_sem);
3378
3379 /*
3380 * We haven't cached this block group, which means we could
3381 * possibly have excluded extents on this block group.
3382 */
3383 if (block_group->cached == BTRFS_CACHE_NO ||
3384 block_group->cached == BTRFS_CACHE_ERROR)
3385 btrfs_free_excluded_extents(block_group);
3386
3387 btrfs_remove_free_space_cache(block_group);
3388 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3389 ASSERT(list_empty(&block_group->dirty_list));
3390 ASSERT(list_empty(&block_group->io_list));
3391 ASSERT(list_empty(&block_group->bg_list));
Josef Bacik48aaeeb2020-07-06 09:14:11 -04003392 ASSERT(refcount_read(&block_group->refs) == 1);
Josef Bacik3e43c272019-06-20 15:38:06 -04003393 btrfs_put_block_group(block_group);
3394
3395 spin_lock(&info->block_group_cache_lock);
3396 }
3397 spin_unlock(&info->block_group_cache_lock);
3398
Josef Bacik3e43c272019-06-20 15:38:06 -04003399 btrfs_release_global_block_rsv(info);
3400
3401 while (!list_empty(&info->space_info)) {
3402 space_info = list_entry(info->space_info.next,
3403 struct btrfs_space_info,
3404 list);
3405
3406 /*
3407 * Do not hide this behind enospc_debug, this is actually
3408 * important and indicates a real bug if this happens.
3409 */
3410 if (WARN_ON(space_info->bytes_pinned > 0 ||
3411 space_info->bytes_reserved > 0 ||
3412 space_info->bytes_may_use > 0))
3413 btrfs_dump_space_info(info, space_info, 0, 0);
Filipe Mananad611add2020-04-07 11:38:49 +01003414 WARN_ON(space_info->reclaim_size > 0);
Josef Bacik3e43c272019-06-20 15:38:06 -04003415 list_del(&space_info->list);
3416 btrfs_sysfs_remove_space_info(space_info);
3417 }
3418 return 0;
3419}
Filipe Manana684b7522020-05-08 11:01:59 +01003420
3421void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3422{
3423 atomic_inc(&cache->frozen);
3424}
3425
3426void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3427{
3428 struct btrfs_fs_info *fs_info = block_group->fs_info;
3429 struct extent_map_tree *em_tree;
3430 struct extent_map *em;
3431 bool cleanup;
3432
3433 spin_lock(&block_group->lock);
3434 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3435 block_group->removed);
3436 spin_unlock(&block_group->lock);
3437
3438 if (cleanup) {
Filipe Manana684b7522020-05-08 11:01:59 +01003439 em_tree = &fs_info->mapping_tree;
3440 write_lock(&em_tree->lock);
3441 em = lookup_extent_mapping(em_tree, block_group->start,
3442 1);
3443 BUG_ON(!em); /* logic error, can't happen */
3444 remove_extent_mapping(em_tree, em);
3445 write_unlock(&em_tree->lock);
Filipe Manana684b7522020-05-08 11:01:59 +01003446
3447 /* once for us and once for the tree */
3448 free_extent_map(em);
3449 free_extent_map(em);
3450
3451 /*
3452 * We may have left one free space entry and other possible
3453 * tasks trimming this block group have left 1 entry each one.
3454 * Free them if any.
3455 */
3456 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
3457 }
3458}