blob: 9c3523b6e0169995331d76d5f6fcf88c9d064055 [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"
Josef Bacik2e405ad2019-06-20 15:37:45 -040018
Josef Bacik878d7b62019-06-20 15:38:05 -040019/*
20 * Return target flags in extended format or 0 if restripe for this chunk_type
21 * is not in progress
22 *
23 * Should be called with balance_lock held
24 */
Josef Bacike11c0402019-06-20 15:38:07 -040025static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
Josef Bacik878d7b62019-06-20 15:38:05 -040026{
27 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
28 u64 target = 0;
29
30 if (!bctl)
31 return 0;
32
33 if (flags & BTRFS_BLOCK_GROUP_DATA &&
34 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
35 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
36 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
37 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
38 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
39 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
40 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
41 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
42 }
43
44 return target;
45}
46
47/*
48 * @flags: available profiles in extended format (see ctree.h)
49 *
50 * Return reduced profile in chunk format. If profile changing is in progress
51 * (either running or paused) picks the target profile (if it's already
52 * available), otherwise falls back to plain reducing.
53 */
54static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
55{
56 u64 num_devices = fs_info->fs_devices->rw_devices;
57 u64 target;
58 u64 raid_type;
59 u64 allowed = 0;
60
61 /*
62 * See if restripe for this chunk_type is in progress, if so try to
63 * reduce to the target profile
64 */
65 spin_lock(&fs_info->balance_lock);
Josef Bacike11c0402019-06-20 15:38:07 -040066 target = get_restripe_target(fs_info, flags);
Josef Bacik878d7b62019-06-20 15:38:05 -040067 if (target) {
Josef Bacik162e0a12020-07-21 10:48:46 -040068 spin_unlock(&fs_info->balance_lock);
69 return extended_to_chunk(target);
Josef Bacik878d7b62019-06-20 15:38:05 -040070 }
71 spin_unlock(&fs_info->balance_lock);
72
73 /* First, mask out the RAID levels which aren't possible */
74 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
75 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
76 allowed |= btrfs_raid_array[raid_type].bg_flag;
77 }
78 allowed &= flags;
79
80 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
81 allowed = BTRFS_BLOCK_GROUP_RAID6;
82 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
83 allowed = BTRFS_BLOCK_GROUP_RAID5;
84 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
85 allowed = BTRFS_BLOCK_GROUP_RAID10;
86 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
87 allowed = BTRFS_BLOCK_GROUP_RAID1;
88 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
89 allowed = BTRFS_BLOCK_GROUP_RAID0;
90
91 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
92
93 return extended_to_chunk(flags | allowed);
94}
95
Johannes Thumshirnef0a82d2020-01-02 17:14:57 +010096u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
Josef Bacik878d7b62019-06-20 15:38:05 -040097{
98 unsigned seq;
99 u64 flags;
100
101 do {
102 flags = orig_flags;
103 seq = read_seqbegin(&fs_info->profiles_lock);
104
105 if (flags & BTRFS_BLOCK_GROUP_DATA)
106 flags |= fs_info->avail_data_alloc_bits;
107 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
108 flags |= fs_info->avail_system_alloc_bits;
109 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
110 flags |= fs_info->avail_metadata_alloc_bits;
111 } while (read_seqretry(&fs_info->profiles_lock, seq));
112
113 return btrfs_reduce_alloc_profile(fs_info, flags);
114}
115
David Sterba32da53862019-10-29 19:20:18 +0100116void btrfs_get_block_group(struct btrfs_block_group *cache)
Josef Bacik3cad1282019-06-20 15:37:46 -0400117{
Josef Bacik48aaeeb2020-07-06 09:14:11 -0400118 refcount_inc(&cache->refs);
Josef Bacik3cad1282019-06-20 15:37:46 -0400119}
120
David Sterba32da53862019-10-29 19:20:18 +0100121void btrfs_put_block_group(struct btrfs_block_group *cache)
Josef Bacik3cad1282019-06-20 15:37:46 -0400122{
Josef Bacik48aaeeb2020-07-06 09:14:11 -0400123 if (refcount_dec_and_test(&cache->refs)) {
Josef Bacik3cad1282019-06-20 15:37:46 -0400124 WARN_ON(cache->pinned > 0);
125 WARN_ON(cache->reserved > 0);
126
127 /*
Dennis Zhoub0643e52019-12-13 16:22:14 -0800128 * A block_group shouldn't be on the discard_list anymore.
129 * Remove the block_group from the discard_list to prevent us
130 * from causing a panic due to NULL pointer dereference.
131 */
132 if (WARN_ON(!list_empty(&cache->discard_list)))
133 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
134 cache);
135
136 /*
Josef Bacik3cad1282019-06-20 15:37:46 -0400137 * If not empty, someone is still holding mutex of
138 * full_stripe_lock, which can only be released by caller.
139 * And it will definitely cause use-after-free when caller
140 * tries to release full stripe lock.
141 *
142 * No better way to resolve, but only to warn.
143 */
144 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
145 kfree(cache->free_space_ctl);
146 kfree(cache);
147 }
148}
149
Josef Bacik2e405ad2019-06-20 15:37:45 -0400150/*
Josef Bacik4358d9632019-06-20 15:37:57 -0400151 * This adds the block group to the fs_info rb tree for the block group cache
152 */
153static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
David Sterba32da53862019-10-29 19:20:18 +0100154 struct btrfs_block_group *block_group)
Josef Bacik4358d9632019-06-20 15:37:57 -0400155{
156 struct rb_node **p;
157 struct rb_node *parent = NULL;
David Sterba32da53862019-10-29 19:20:18 +0100158 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -0400159
Qu Wenruo9afc6642020-05-05 07:58:20 +0800160 ASSERT(block_group->length != 0);
161
Josef Bacik4358d9632019-06-20 15:37:57 -0400162 spin_lock(&info->block_group_cache_lock);
163 p = &info->block_group_cache_tree.rb_node;
164
165 while (*p) {
166 parent = *p;
David Sterba32da53862019-10-29 19:20:18 +0100167 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
David Sterbab3470b52019-10-23 18:48:22 +0200168 if (block_group->start < cache->start) {
Josef Bacik4358d9632019-06-20 15:37:57 -0400169 p = &(*p)->rb_left;
David Sterbab3470b52019-10-23 18:48:22 +0200170 } else if (block_group->start > cache->start) {
Josef Bacik4358d9632019-06-20 15:37:57 -0400171 p = &(*p)->rb_right;
172 } else {
173 spin_unlock(&info->block_group_cache_lock);
174 return -EEXIST;
175 }
176 }
177
178 rb_link_node(&block_group->cache_node, parent, p);
179 rb_insert_color(&block_group->cache_node,
180 &info->block_group_cache_tree);
181
David Sterbab3470b52019-10-23 18:48:22 +0200182 if (info->first_logical_byte > block_group->start)
183 info->first_logical_byte = block_group->start;
Josef Bacik4358d9632019-06-20 15:37:57 -0400184
185 spin_unlock(&info->block_group_cache_lock);
186
187 return 0;
188}
189
190/*
Josef Bacik2e405ad2019-06-20 15:37:45 -0400191 * This will return the block group at or after bytenr if contains is 0, else
192 * it will return the block group that contains the bytenr
193 */
David Sterba32da53862019-10-29 19:20:18 +0100194static struct btrfs_block_group *block_group_cache_tree_search(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400195 struct btrfs_fs_info *info, u64 bytenr, int contains)
196{
David Sterba32da53862019-10-29 19:20:18 +0100197 struct btrfs_block_group *cache, *ret = NULL;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400198 struct rb_node *n;
199 u64 end, start;
200
201 spin_lock(&info->block_group_cache_lock);
202 n = info->block_group_cache_tree.rb_node;
203
204 while (n) {
David Sterba32da53862019-10-29 19:20:18 +0100205 cache = rb_entry(n, struct btrfs_block_group, cache_node);
David Sterbab3470b52019-10-23 18:48:22 +0200206 end = cache->start + cache->length - 1;
207 start = cache->start;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400208
209 if (bytenr < start) {
David Sterbab3470b52019-10-23 18:48:22 +0200210 if (!contains && (!ret || start < ret->start))
Josef Bacik2e405ad2019-06-20 15:37:45 -0400211 ret = cache;
212 n = n->rb_left;
213 } else if (bytenr > start) {
214 if (contains && bytenr <= end) {
215 ret = cache;
216 break;
217 }
218 n = n->rb_right;
219 } else {
220 ret = cache;
221 break;
222 }
223 }
224 if (ret) {
225 btrfs_get_block_group(ret);
David Sterbab3470b52019-10-23 18:48:22 +0200226 if (bytenr == 0 && info->first_logical_byte > ret->start)
227 info->first_logical_byte = ret->start;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400228 }
229 spin_unlock(&info->block_group_cache_lock);
230
231 return ret;
232}
233
234/*
235 * Return the block group that starts at or after bytenr
236 */
David Sterba32da53862019-10-29 19:20:18 +0100237struct btrfs_block_group *btrfs_lookup_first_block_group(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400238 struct btrfs_fs_info *info, u64 bytenr)
239{
240 return block_group_cache_tree_search(info, bytenr, 0);
241}
242
243/*
244 * Return the block group that contains the given bytenr
245 */
David Sterba32da53862019-10-29 19:20:18 +0100246struct btrfs_block_group *btrfs_lookup_block_group(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400247 struct btrfs_fs_info *info, u64 bytenr)
248{
249 return block_group_cache_tree_search(info, bytenr, 1);
250}
251
David Sterba32da53862019-10-29 19:20:18 +0100252struct btrfs_block_group *btrfs_next_block_group(
253 struct btrfs_block_group *cache)
Josef Bacik2e405ad2019-06-20 15:37:45 -0400254{
255 struct btrfs_fs_info *fs_info = cache->fs_info;
256 struct rb_node *node;
257
258 spin_lock(&fs_info->block_group_cache_lock);
259
260 /* If our block group was removed, we need a full search. */
261 if (RB_EMPTY_NODE(&cache->cache_node)) {
David Sterbab3470b52019-10-23 18:48:22 +0200262 const u64 next_bytenr = cache->start + cache->length;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400263
264 spin_unlock(&fs_info->block_group_cache_lock);
265 btrfs_put_block_group(cache);
266 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
267 }
268 node = rb_next(&cache->cache_node);
269 btrfs_put_block_group(cache);
270 if (node) {
David Sterba32da53862019-10-29 19:20:18 +0100271 cache = rb_entry(node, struct btrfs_block_group, cache_node);
Josef Bacik2e405ad2019-06-20 15:37:45 -0400272 btrfs_get_block_group(cache);
273 } else
274 cache = NULL;
275 spin_unlock(&fs_info->block_group_cache_lock);
276 return cache;
277}
Josef Bacik3eeb3222019-06-20 15:37:47 -0400278
279bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
280{
David Sterba32da53862019-10-29 19:20:18 +0100281 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400282 bool ret = true;
283
284 bg = btrfs_lookup_block_group(fs_info, bytenr);
285 if (!bg)
286 return false;
287
288 spin_lock(&bg->lock);
289 if (bg->ro)
290 ret = false;
291 else
292 atomic_inc(&bg->nocow_writers);
293 spin_unlock(&bg->lock);
294
295 /* No put on block group, done by btrfs_dec_nocow_writers */
296 if (!ret)
297 btrfs_put_block_group(bg);
298
299 return ret;
300}
301
302void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
303{
David Sterba32da53862019-10-29 19:20:18 +0100304 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400305
306 bg = btrfs_lookup_block_group(fs_info, bytenr);
307 ASSERT(bg);
308 if (atomic_dec_and_test(&bg->nocow_writers))
309 wake_up_var(&bg->nocow_writers);
310 /*
311 * Once for our lookup and once for the lookup done by a previous call
312 * to btrfs_inc_nocow_writers()
313 */
314 btrfs_put_block_group(bg);
315 btrfs_put_block_group(bg);
316}
317
David Sterba32da53862019-10-29 19:20:18 +0100318void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
Josef Bacik3eeb3222019-06-20 15:37:47 -0400319{
320 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
321}
322
323void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
324 const u64 start)
325{
David Sterba32da53862019-10-29 19:20:18 +0100326 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400327
328 bg = btrfs_lookup_block_group(fs_info, start);
329 ASSERT(bg);
330 if (atomic_dec_and_test(&bg->reservations))
331 wake_up_var(&bg->reservations);
332 btrfs_put_block_group(bg);
333}
334
David Sterba32da53862019-10-29 19:20:18 +0100335void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
Josef Bacik3eeb3222019-06-20 15:37:47 -0400336{
337 struct btrfs_space_info *space_info = bg->space_info;
338
339 ASSERT(bg->ro);
340
341 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
342 return;
343
344 /*
345 * Our block group is read only but before we set it to read only,
346 * some task might have had allocated an extent from it already, but it
347 * has not yet created a respective ordered extent (and added it to a
348 * root's list of ordered extents).
349 * Therefore wait for any task currently allocating extents, since the
350 * block group's reservations counter is incremented while a read lock
351 * on the groups' semaphore is held and decremented after releasing
352 * the read access on that semaphore and creating the ordered extent.
353 */
354 down_write(&space_info->groups_sem);
355 up_write(&space_info->groups_sem);
356
357 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
358}
Josef Bacik9f212462019-08-06 16:43:19 +0200359
360struct btrfs_caching_control *btrfs_get_caching_control(
David Sterba32da53862019-10-29 19:20:18 +0100361 struct btrfs_block_group *cache)
Josef Bacik9f212462019-08-06 16:43:19 +0200362{
363 struct btrfs_caching_control *ctl;
364
365 spin_lock(&cache->lock);
366 if (!cache->caching_ctl) {
367 spin_unlock(&cache->lock);
368 return NULL;
369 }
370
371 ctl = cache->caching_ctl;
372 refcount_inc(&ctl->count);
373 spin_unlock(&cache->lock);
374 return ctl;
375}
376
377void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
378{
379 if (refcount_dec_and_test(&ctl->count))
380 kfree(ctl);
381}
382
383/*
384 * When we wait for progress in the block group caching, its because our
385 * allocation attempt failed at least once. So, we must sleep and let some
386 * progress happen before we try again.
387 *
388 * This function will sleep at least once waiting for new free space to show
389 * up, and then it will check the block group free space numbers for our min
390 * num_bytes. Another option is to have it go ahead and look in the rbtree for
391 * a free extent of a given size, but this is a good start.
392 *
393 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
394 * any of the information in this block group.
395 */
David Sterba32da53862019-10-29 19:20:18 +0100396void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
Josef Bacik9f212462019-08-06 16:43:19 +0200397 u64 num_bytes)
398{
399 struct btrfs_caching_control *caching_ctl;
400
401 caching_ctl = btrfs_get_caching_control(cache);
402 if (!caching_ctl)
403 return;
404
David Sterba32da53862019-10-29 19:20:18 +0100405 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
Josef Bacik9f212462019-08-06 16:43:19 +0200406 (cache->free_space_ctl->free_space >= num_bytes));
407
408 btrfs_put_caching_control(caching_ctl);
409}
410
David Sterba32da53862019-10-29 19:20:18 +0100411int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
Josef Bacik9f212462019-08-06 16:43:19 +0200412{
413 struct btrfs_caching_control *caching_ctl;
414 int ret = 0;
415
416 caching_ctl = btrfs_get_caching_control(cache);
417 if (!caching_ctl)
418 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
419
David Sterba32da53862019-10-29 19:20:18 +0100420 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
Josef Bacik9f212462019-08-06 16:43:19 +0200421 if (cache->cached == BTRFS_CACHE_ERROR)
422 ret = -EIO;
423 btrfs_put_caching_control(caching_ctl);
424 return ret;
425}
426
Josef Bacike7478532020-10-23 09:58:10 -0400427static bool space_cache_v1_done(struct btrfs_block_group *cache)
428{
429 bool ret;
430
431 spin_lock(&cache->lock);
432 ret = cache->cached != BTRFS_CACHE_FAST;
433 spin_unlock(&cache->lock);
434
435 return ret;
436}
437
438void btrfs_wait_space_cache_v1_finished(struct btrfs_block_group *cache,
439 struct btrfs_caching_control *caching_ctl)
440{
441 wait_event(caching_ctl->wait, space_cache_v1_done(cache));
442}
443
Josef Bacik9f212462019-08-06 16:43:19 +0200444#ifdef CONFIG_BTRFS_DEBUG
David Sterba32da53862019-10-29 19:20:18 +0100445static void fragment_free_space(struct btrfs_block_group *block_group)
Josef Bacik9f212462019-08-06 16:43:19 +0200446{
447 struct btrfs_fs_info *fs_info = block_group->fs_info;
David Sterbab3470b52019-10-23 18:48:22 +0200448 u64 start = block_group->start;
449 u64 len = block_group->length;
Josef Bacik9f212462019-08-06 16:43:19 +0200450 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
451 fs_info->nodesize : fs_info->sectorsize;
452 u64 step = chunk << 1;
453
454 while (len > chunk) {
455 btrfs_remove_free_space(block_group, start, chunk);
456 start += step;
457 if (len < step)
458 len = 0;
459 else
460 len -= step;
461 }
462}
463#endif
464
465/*
466 * This is only called by btrfs_cache_block_group, since we could have freed
467 * extents we need to check the pinned_extents for any extents that can't be
468 * used yet since their free space will be released as soon as the transaction
469 * commits.
470 */
David Sterba32da53862019-10-29 19:20:18 +0100471u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
Josef Bacik9f212462019-08-06 16:43:19 +0200472{
473 struct btrfs_fs_info *info = block_group->fs_info;
474 u64 extent_start, extent_end, size, total_added = 0;
475 int ret;
476
477 while (start < end) {
Nikolay Borisovfe119a62020-01-20 16:09:18 +0200478 ret = find_first_extent_bit(&info->excluded_extents, start,
Josef Bacik9f212462019-08-06 16:43:19 +0200479 &extent_start, &extent_end,
480 EXTENT_DIRTY | EXTENT_UPTODATE,
481 NULL);
482 if (ret)
483 break;
484
485 if (extent_start <= start) {
486 start = extent_end + 1;
487 } else if (extent_start > start && extent_start < end) {
488 size = extent_start - start;
489 total_added += size;
Dennis Zhoub0643e52019-12-13 16:22:14 -0800490 ret = btrfs_add_free_space_async_trimmed(block_group,
491 start, size);
Josef Bacik9f212462019-08-06 16:43:19 +0200492 BUG_ON(ret); /* -ENOMEM or logic error */
493 start = extent_end + 1;
494 } else {
495 break;
496 }
497 }
498
499 if (start < end) {
500 size = end - start;
501 total_added += size;
Dennis Zhoub0643e52019-12-13 16:22:14 -0800502 ret = btrfs_add_free_space_async_trimmed(block_group, start,
503 size);
Josef Bacik9f212462019-08-06 16:43:19 +0200504 BUG_ON(ret); /* -ENOMEM or logic error */
505 }
506
507 return total_added;
508}
509
510static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
511{
David Sterba32da53862019-10-29 19:20:18 +0100512 struct btrfs_block_group *block_group = caching_ctl->block_group;
Josef Bacik9f212462019-08-06 16:43:19 +0200513 struct btrfs_fs_info *fs_info = block_group->fs_info;
514 struct btrfs_root *extent_root = fs_info->extent_root;
515 struct btrfs_path *path;
516 struct extent_buffer *leaf;
517 struct btrfs_key key;
518 u64 total_found = 0;
519 u64 last = 0;
520 u32 nritems;
521 int ret;
522 bool wakeup = true;
523
524 path = btrfs_alloc_path();
525 if (!path)
526 return -ENOMEM;
527
David Sterbab3470b52019-10-23 18:48:22 +0200528 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
Josef Bacik9f212462019-08-06 16:43:19 +0200529
530#ifdef CONFIG_BTRFS_DEBUG
531 /*
532 * If we're fragmenting we don't want to make anybody think we can
533 * allocate from this block group until we've had a chance to fragment
534 * the free space.
535 */
536 if (btrfs_should_fragment_free_space(block_group))
537 wakeup = false;
538#endif
539 /*
540 * We don't want to deadlock with somebody trying to allocate a new
541 * extent for the extent root while also trying to search the extent
542 * root to add free space. So we skip locking and search the commit
543 * root, since its read-only
544 */
545 path->skip_locking = 1;
546 path->search_commit_root = 1;
547 path->reada = READA_FORWARD;
548
549 key.objectid = last;
550 key.offset = 0;
551 key.type = BTRFS_EXTENT_ITEM_KEY;
552
553next:
554 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
555 if (ret < 0)
556 goto out;
557
558 leaf = path->nodes[0];
559 nritems = btrfs_header_nritems(leaf);
560
561 while (1) {
562 if (btrfs_fs_closing(fs_info) > 1) {
563 last = (u64)-1;
564 break;
565 }
566
567 if (path->slots[0] < nritems) {
568 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
569 } else {
570 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
571 if (ret)
572 break;
573
574 if (need_resched() ||
575 rwsem_is_contended(&fs_info->commit_root_sem)) {
576 if (wakeup)
577 caching_ctl->progress = last;
578 btrfs_release_path(path);
579 up_read(&fs_info->commit_root_sem);
580 mutex_unlock(&caching_ctl->mutex);
581 cond_resched();
582 mutex_lock(&caching_ctl->mutex);
583 down_read(&fs_info->commit_root_sem);
584 goto next;
585 }
586
587 ret = btrfs_next_leaf(extent_root, path);
588 if (ret < 0)
589 goto out;
590 if (ret)
591 break;
592 leaf = path->nodes[0];
593 nritems = btrfs_header_nritems(leaf);
594 continue;
595 }
596
597 if (key.objectid < last) {
598 key.objectid = last;
599 key.offset = 0;
600 key.type = BTRFS_EXTENT_ITEM_KEY;
601
602 if (wakeup)
603 caching_ctl->progress = last;
604 btrfs_release_path(path);
605 goto next;
606 }
607
David Sterbab3470b52019-10-23 18:48:22 +0200608 if (key.objectid < block_group->start) {
Josef Bacik9f212462019-08-06 16:43:19 +0200609 path->slots[0]++;
610 continue;
611 }
612
David Sterbab3470b52019-10-23 18:48:22 +0200613 if (key.objectid >= block_group->start + block_group->length)
Josef Bacik9f212462019-08-06 16:43:19 +0200614 break;
615
616 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
617 key.type == BTRFS_METADATA_ITEM_KEY) {
618 total_found += add_new_free_space(block_group, last,
619 key.objectid);
620 if (key.type == BTRFS_METADATA_ITEM_KEY)
621 last = key.objectid +
622 fs_info->nodesize;
623 else
624 last = key.objectid + key.offset;
625
626 if (total_found > CACHING_CTL_WAKE_UP) {
627 total_found = 0;
628 if (wakeup)
629 wake_up(&caching_ctl->wait);
630 }
631 }
632 path->slots[0]++;
633 }
634 ret = 0;
635
636 total_found += add_new_free_space(block_group, last,
David Sterbab3470b52019-10-23 18:48:22 +0200637 block_group->start + block_group->length);
Josef Bacik9f212462019-08-06 16:43:19 +0200638 caching_ctl->progress = (u64)-1;
639
640out:
641 btrfs_free_path(path);
642 return ret;
643}
644
645static noinline void caching_thread(struct btrfs_work *work)
646{
David Sterba32da53862019-10-29 19:20:18 +0100647 struct btrfs_block_group *block_group;
Josef Bacik9f212462019-08-06 16:43:19 +0200648 struct btrfs_fs_info *fs_info;
649 struct btrfs_caching_control *caching_ctl;
650 int ret;
651
652 caching_ctl = container_of(work, struct btrfs_caching_control, work);
653 block_group = caching_ctl->block_group;
654 fs_info = block_group->fs_info;
655
656 mutex_lock(&caching_ctl->mutex);
657 down_read(&fs_info->commit_root_sem);
658
Josef Bacike7478532020-10-23 09:58:10 -0400659 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
660 ret = load_free_space_cache(block_group);
661 if (ret == 1) {
662 ret = 0;
663 goto done;
664 }
665
666 /*
667 * We failed to load the space cache, set ourselves to
668 * CACHE_STARTED and carry on.
669 */
670 spin_lock(&block_group->lock);
671 block_group->cached = BTRFS_CACHE_STARTED;
672 spin_unlock(&block_group->lock);
673 wake_up(&caching_ctl->wait);
674 }
675
Josef Bacik9f212462019-08-06 16:43:19 +0200676 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
677 ret = load_free_space_tree(caching_ctl);
678 else
679 ret = load_extent_tree_free(caching_ctl);
Josef Bacike7478532020-10-23 09:58:10 -0400680done:
Josef Bacik9f212462019-08-06 16:43:19 +0200681 spin_lock(&block_group->lock);
682 block_group->caching_ctl = NULL;
683 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
684 spin_unlock(&block_group->lock);
685
686#ifdef CONFIG_BTRFS_DEBUG
687 if (btrfs_should_fragment_free_space(block_group)) {
688 u64 bytes_used;
689
690 spin_lock(&block_group->space_info->lock);
691 spin_lock(&block_group->lock);
David Sterbab3470b52019-10-23 18:48:22 +0200692 bytes_used = block_group->length - block_group->used;
Josef Bacik9f212462019-08-06 16:43:19 +0200693 block_group->space_info->bytes_used += bytes_used >> 1;
694 spin_unlock(&block_group->lock);
695 spin_unlock(&block_group->space_info->lock);
Josef Bacike11c0402019-06-20 15:38:07 -0400696 fragment_free_space(block_group);
Josef Bacik9f212462019-08-06 16:43:19 +0200697 }
698#endif
699
700 caching_ctl->progress = (u64)-1;
701
702 up_read(&fs_info->commit_root_sem);
703 btrfs_free_excluded_extents(block_group);
704 mutex_unlock(&caching_ctl->mutex);
705
706 wake_up(&caching_ctl->wait);
707
708 btrfs_put_caching_control(caching_ctl);
709 btrfs_put_block_group(block_group);
710}
711
David Sterba32da53862019-10-29 19:20:18 +0100712int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
Josef Bacik9f212462019-08-06 16:43:19 +0200713{
714 DEFINE_WAIT(wait);
715 struct btrfs_fs_info *fs_info = cache->fs_info;
Josef Bacike7478532020-10-23 09:58:10 -0400716 struct btrfs_caching_control *caching_ctl = NULL;
Josef Bacik9f212462019-08-06 16:43:19 +0200717 int ret = 0;
718
719 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
720 if (!caching_ctl)
721 return -ENOMEM;
722
723 INIT_LIST_HEAD(&caching_ctl->list);
724 mutex_init(&caching_ctl->mutex);
725 init_waitqueue_head(&caching_ctl->wait);
726 caching_ctl->block_group = cache;
David Sterbab3470b52019-10-23 18:48:22 +0200727 caching_ctl->progress = cache->start;
Josef Bacike7478532020-10-23 09:58:10 -0400728 refcount_set(&caching_ctl->count, 2);
Omar Sandovala0cac0e2019-09-16 11:30:57 -0700729 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
Josef Bacik9f212462019-08-06 16:43:19 +0200730
731 spin_lock(&cache->lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200732 if (cache->cached != BTRFS_CACHE_NO) {
Josef Bacik9f212462019-08-06 16:43:19 +0200733 kfree(caching_ctl);
Josef Bacike7478532020-10-23 09:58:10 -0400734
735 caching_ctl = cache->caching_ctl;
736 if (caching_ctl)
737 refcount_inc(&caching_ctl->count);
738 spin_unlock(&cache->lock);
739 goto out;
Josef Bacik9f212462019-08-06 16:43:19 +0200740 }
741 WARN_ON(cache->caching_ctl);
742 cache->caching_ctl = caching_ctl;
Josef Bacike7478532020-10-23 09:58:10 -0400743 if (btrfs_test_opt(fs_info, SPACE_CACHE))
744 cache->cached = BTRFS_CACHE_FAST;
745 else
746 cache->cached = BTRFS_CACHE_STARTED;
747 cache->has_caching_ctl = 1;
Josef Bacik9f212462019-08-06 16:43:19 +0200748 spin_unlock(&cache->lock);
749
Josef Bacikbbb86a32020-10-23 09:58:11 -0400750 spin_lock(&fs_info->block_group_cache_lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200751 refcount_inc(&caching_ctl->count);
752 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
Josef Bacikbbb86a32020-10-23 09:58:11 -0400753 spin_unlock(&fs_info->block_group_cache_lock);
Josef Bacik9f212462019-08-06 16:43:19 +0200754
755 btrfs_get_block_group(cache);
756
757 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
Josef Bacike7478532020-10-23 09:58:10 -0400758out:
759 if (load_cache_only && caching_ctl)
760 btrfs_wait_space_cache_v1_finished(cache, caching_ctl);
761 if (caching_ctl)
762 btrfs_put_caching_control(caching_ctl);
Josef Bacik9f212462019-08-06 16:43:19 +0200763
764 return ret;
765}
Josef Bacike3e05202019-06-20 15:37:55 -0400766
767static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
768{
769 u64 extra_flags = chunk_to_extended(flags) &
770 BTRFS_EXTENDED_PROFILE_MASK;
771
772 write_seqlock(&fs_info->profiles_lock);
773 if (flags & BTRFS_BLOCK_GROUP_DATA)
774 fs_info->avail_data_alloc_bits &= ~extra_flags;
775 if (flags & BTRFS_BLOCK_GROUP_METADATA)
776 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
777 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
778 fs_info->avail_system_alloc_bits &= ~extra_flags;
779 write_sequnlock(&fs_info->profiles_lock);
780}
781
782/*
783 * Clear incompat bits for the following feature(s):
784 *
785 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
786 * in the whole filesystem
David Sterba9c907442019-10-31 15:52:01 +0100787 *
788 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
Josef Bacike3e05202019-06-20 15:37:55 -0400789 */
790static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
791{
David Sterba9c907442019-10-31 15:52:01 +0100792 bool found_raid56 = false;
793 bool found_raid1c34 = false;
794
795 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
796 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
797 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
Josef Bacike3e05202019-06-20 15:37:55 -0400798 struct list_head *head = &fs_info->space_info;
799 struct btrfs_space_info *sinfo;
800
801 list_for_each_entry_rcu(sinfo, head, list) {
Josef Bacike3e05202019-06-20 15:37:55 -0400802 down_read(&sinfo->groups_sem);
803 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
David Sterba9c907442019-10-31 15:52:01 +0100804 found_raid56 = true;
Josef Bacike3e05202019-06-20 15:37:55 -0400805 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
David Sterba9c907442019-10-31 15:52:01 +0100806 found_raid56 = true;
807 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
808 found_raid1c34 = true;
809 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
810 found_raid1c34 = true;
Josef Bacike3e05202019-06-20 15:37:55 -0400811 up_read(&sinfo->groups_sem);
Josef Bacike3e05202019-06-20 15:37:55 -0400812 }
Filipe Mananad8e6fd52020-03-20 18:43:48 +0000813 if (!found_raid56)
David Sterba9c907442019-10-31 15:52:01 +0100814 btrfs_clear_fs_incompat(fs_info, RAID56);
Filipe Mananad8e6fd52020-03-20 18:43:48 +0000815 if (!found_raid1c34)
David Sterba9c907442019-10-31 15:52:01 +0100816 btrfs_clear_fs_incompat(fs_info, RAID1C34);
Josef Bacike3e05202019-06-20 15:37:55 -0400817 }
818}
819
Qu Wenruo73576232020-05-05 07:58:21 +0800820static int remove_block_group_item(struct btrfs_trans_handle *trans,
821 struct btrfs_path *path,
822 struct btrfs_block_group *block_group)
823{
824 struct btrfs_fs_info *fs_info = trans->fs_info;
825 struct btrfs_root *root;
826 struct btrfs_key key;
827 int ret;
828
829 root = fs_info->extent_root;
830 key.objectid = block_group->start;
831 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
832 key.offset = block_group->length;
833
834 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
835 if (ret > 0)
836 ret = -ENOENT;
837 if (ret < 0)
838 return ret;
839
840 ret = btrfs_del_item(trans, root, path);
841 return ret;
842}
843
Josef Bacike3e05202019-06-20 15:37:55 -0400844int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
845 u64 group_start, struct extent_map *em)
846{
847 struct btrfs_fs_info *fs_info = trans->fs_info;
Josef Bacike3e05202019-06-20 15:37:55 -0400848 struct btrfs_path *path;
David Sterba32da53862019-10-29 19:20:18 +0100849 struct btrfs_block_group *block_group;
Josef Bacike3e05202019-06-20 15:37:55 -0400850 struct btrfs_free_cluster *cluster;
851 struct btrfs_root *tree_root = fs_info->tree_root;
852 struct btrfs_key key;
853 struct inode *inode;
854 struct kobject *kobj = NULL;
855 int ret;
856 int index;
857 int factor;
858 struct btrfs_caching_control *caching_ctl = NULL;
859 bool remove_em;
860 bool remove_rsv = false;
861
862 block_group = btrfs_lookup_block_group(fs_info, group_start);
863 BUG_ON(!block_group);
864 BUG_ON(!block_group->ro);
865
866 trace_btrfs_remove_block_group(block_group);
867 /*
868 * Free the reserved super bytes from this block group before
869 * remove it.
870 */
871 btrfs_free_excluded_extents(block_group);
David Sterbab3470b52019-10-23 18:48:22 +0200872 btrfs_free_ref_tree_range(fs_info, block_group->start,
873 block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -0400874
Josef Bacike3e05202019-06-20 15:37:55 -0400875 index = btrfs_bg_flags_to_raid_index(block_group->flags);
876 factor = btrfs_bg_type_to_factor(block_group->flags);
877
878 /* make sure this block group isn't part of an allocation cluster */
879 cluster = &fs_info->data_alloc_cluster;
880 spin_lock(&cluster->refill_lock);
881 btrfs_return_cluster_to_free_space(block_group, cluster);
882 spin_unlock(&cluster->refill_lock);
883
884 /*
885 * make sure this block group isn't part of a metadata
886 * allocation cluster
887 */
888 cluster = &fs_info->meta_alloc_cluster;
889 spin_lock(&cluster->refill_lock);
890 btrfs_return_cluster_to_free_space(block_group, cluster);
891 spin_unlock(&cluster->refill_lock);
892
893 path = btrfs_alloc_path();
894 if (!path) {
895 ret = -ENOMEM;
Filipe Manana9fecd132020-06-01 19:12:06 +0100896 goto out;
Josef Bacike3e05202019-06-20 15:37:55 -0400897 }
898
899 /*
900 * get the inode first so any iput calls done for the io_list
901 * aren't the final iput (no unlinks allowed now)
902 */
903 inode = lookup_free_space_inode(block_group, path);
904
905 mutex_lock(&trans->transaction->cache_write_mutex);
906 /*
907 * Make sure our free space cache IO is done before removing the
908 * free space inode
909 */
910 spin_lock(&trans->transaction->dirty_bgs_lock);
911 if (!list_empty(&block_group->io_list)) {
912 list_del_init(&block_group->io_list);
913
914 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
915
916 spin_unlock(&trans->transaction->dirty_bgs_lock);
917 btrfs_wait_cache_io(trans, block_group, path);
918 btrfs_put_block_group(block_group);
919 spin_lock(&trans->transaction->dirty_bgs_lock);
920 }
921
922 if (!list_empty(&block_group->dirty_list)) {
923 list_del_init(&block_group->dirty_list);
924 remove_rsv = true;
925 btrfs_put_block_group(block_group);
926 }
927 spin_unlock(&trans->transaction->dirty_bgs_lock);
928 mutex_unlock(&trans->transaction->cache_write_mutex);
929
930 if (!IS_ERR(inode)) {
931 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
932 if (ret) {
933 btrfs_add_delayed_iput(inode);
Filipe Manana9fecd132020-06-01 19:12:06 +0100934 goto out;
Josef Bacike3e05202019-06-20 15:37:55 -0400935 }
936 clear_nlink(inode);
937 /* One for the block groups ref */
938 spin_lock(&block_group->lock);
939 if (block_group->iref) {
940 block_group->iref = 0;
941 block_group->inode = NULL;
942 spin_unlock(&block_group->lock);
943 iput(inode);
944 } else {
945 spin_unlock(&block_group->lock);
946 }
947 /* One for our lookup ref */
948 btrfs_add_delayed_iput(inode);
949 }
950
951 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
Josef Bacike3e05202019-06-20 15:37:55 -0400952 key.type = 0;
David Sterbab3470b52019-10-23 18:48:22 +0200953 key.offset = block_group->start;
Josef Bacike3e05202019-06-20 15:37:55 -0400954
955 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
956 if (ret < 0)
Filipe Manana9fecd132020-06-01 19:12:06 +0100957 goto out;
Josef Bacike3e05202019-06-20 15:37:55 -0400958 if (ret > 0)
959 btrfs_release_path(path);
960 if (ret == 0) {
961 ret = btrfs_del_item(trans, tree_root, path);
962 if (ret)
Filipe Manana9fecd132020-06-01 19:12:06 +0100963 goto out;
Josef Bacike3e05202019-06-20 15:37:55 -0400964 btrfs_release_path(path);
965 }
966
967 spin_lock(&fs_info->block_group_cache_lock);
968 rb_erase(&block_group->cache_node,
969 &fs_info->block_group_cache_tree);
970 RB_CLEAR_NODE(&block_group->cache_node);
971
Filipe Manana9fecd132020-06-01 19:12:06 +0100972 /* Once for the block groups rbtree */
973 btrfs_put_block_group(block_group);
974
David Sterbab3470b52019-10-23 18:48:22 +0200975 if (fs_info->first_logical_byte == block_group->start)
Josef Bacike3e05202019-06-20 15:37:55 -0400976 fs_info->first_logical_byte = (u64)-1;
977 spin_unlock(&fs_info->block_group_cache_lock);
978
979 down_write(&block_group->space_info->groups_sem);
980 /*
981 * we must use list_del_init so people can check to see if they
982 * are still on the list after taking the semaphore
983 */
984 list_del_init(&block_group->list);
985 if (list_empty(&block_group->space_info->block_groups[index])) {
986 kobj = block_group->space_info->block_group_kobjs[index];
987 block_group->space_info->block_group_kobjs[index] = NULL;
988 clear_avail_alloc_bits(fs_info, block_group->flags);
989 }
990 up_write(&block_group->space_info->groups_sem);
991 clear_incompat_bg_bits(fs_info, block_group->flags);
992 if (kobj) {
993 kobject_del(kobj);
994 kobject_put(kobj);
995 }
996
997 if (block_group->has_caching_ctl)
998 caching_ctl = btrfs_get_caching_control(block_group);
999 if (block_group->cached == BTRFS_CACHE_STARTED)
1000 btrfs_wait_block_group_cache_done(block_group);
1001 if (block_group->has_caching_ctl) {
Josef Bacikbbb86a32020-10-23 09:58:11 -04001002 spin_lock(&fs_info->block_group_cache_lock);
Josef Bacike3e05202019-06-20 15:37:55 -04001003 if (!caching_ctl) {
1004 struct btrfs_caching_control *ctl;
1005
1006 list_for_each_entry(ctl,
1007 &fs_info->caching_block_groups, list)
1008 if (ctl->block_group == block_group) {
1009 caching_ctl = ctl;
1010 refcount_inc(&caching_ctl->count);
1011 break;
1012 }
1013 }
1014 if (caching_ctl)
1015 list_del_init(&caching_ctl->list);
Josef Bacikbbb86a32020-10-23 09:58:11 -04001016 spin_unlock(&fs_info->block_group_cache_lock);
Josef Bacike3e05202019-06-20 15:37:55 -04001017 if (caching_ctl) {
1018 /* Once for the caching bgs list and once for us. */
1019 btrfs_put_caching_control(caching_ctl);
1020 btrfs_put_caching_control(caching_ctl);
1021 }
1022 }
1023
1024 spin_lock(&trans->transaction->dirty_bgs_lock);
1025 WARN_ON(!list_empty(&block_group->dirty_list));
1026 WARN_ON(!list_empty(&block_group->io_list));
1027 spin_unlock(&trans->transaction->dirty_bgs_lock);
1028
1029 btrfs_remove_free_space_cache(block_group);
1030
1031 spin_lock(&block_group->space_info->lock);
1032 list_del_init(&block_group->ro_list);
1033
1034 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1035 WARN_ON(block_group->space_info->total_bytes
David Sterbab3470b52019-10-23 18:48:22 +02001036 < block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -04001037 WARN_ON(block_group->space_info->bytes_readonly
David Sterbab3470b52019-10-23 18:48:22 +02001038 < block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -04001039 WARN_ON(block_group->space_info->disk_total
David Sterbab3470b52019-10-23 18:48:22 +02001040 < block_group->length * factor);
Josef Bacike3e05202019-06-20 15:37:55 -04001041 }
David Sterbab3470b52019-10-23 18:48:22 +02001042 block_group->space_info->total_bytes -= block_group->length;
1043 block_group->space_info->bytes_readonly -= block_group->length;
1044 block_group->space_info->disk_total -= block_group->length * factor;
Josef Bacike3e05202019-06-20 15:37:55 -04001045
1046 spin_unlock(&block_group->space_info->lock);
1047
Filipe Mananaffcb9d42020-06-01 19:12:19 +01001048 /*
1049 * Remove the free space for the block group from the free space tree
1050 * and the block group's item from the extent tree before marking the
1051 * block group as removed. This is to prevent races with tasks that
1052 * freeze and unfreeze a block group, this task and another task
1053 * allocating a new block group - the unfreeze task ends up removing
1054 * the block group's extent map before the task calling this function
1055 * deletes the block group item from the extent tree, allowing for
1056 * another task to attempt to create another block group with the same
1057 * item key (and failing with -EEXIST and a transaction abort).
1058 */
1059 ret = remove_block_group_free_space(trans, block_group);
1060 if (ret)
1061 goto out;
1062
1063 ret = remove_block_group_item(trans, path, block_group);
1064 if (ret < 0)
1065 goto out;
1066
Josef Bacike3e05202019-06-20 15:37:55 -04001067 spin_lock(&block_group->lock);
1068 block_group->removed = 1;
1069 /*
Filipe Manana6b7304a2020-05-08 11:01:47 +01001070 * At this point trimming or scrub can't start on this block group,
1071 * because we removed the block group from the rbtree
1072 * fs_info->block_group_cache_tree so no one can't find it anymore and
1073 * even if someone already got this block group before we removed it
1074 * from the rbtree, they have already incremented block_group->frozen -
1075 * if they didn't, for the trimming case they won't find any free space
1076 * entries because we already removed them all when we called
1077 * btrfs_remove_free_space_cache().
Josef Bacike3e05202019-06-20 15:37:55 -04001078 *
1079 * And we must not remove the extent map from the fs_info->mapping_tree
1080 * to prevent the same logical address range and physical device space
Filipe Manana6b7304a2020-05-08 11:01:47 +01001081 * ranges from being reused for a new block group. This is needed to
1082 * avoid races with trimming and scrub.
1083 *
1084 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
Josef Bacike3e05202019-06-20 15:37:55 -04001085 * completely transactionless, so while it is trimming a range the
1086 * currently running transaction might finish and a new one start,
1087 * allowing for new block groups to be created that can reuse the same
1088 * physical device locations unless we take this special care.
1089 *
1090 * There may also be an implicit trim operation if the file system
1091 * is mounted with -odiscard. The same protections must remain
1092 * in place until the extents have been discarded completely when
1093 * the transaction commit has completed.
1094 */
Filipe Manana6b7304a2020-05-08 11:01:47 +01001095 remove_em = (atomic_read(&block_group->frozen) == 0);
Josef Bacike3e05202019-06-20 15:37:55 -04001096 spin_unlock(&block_group->lock);
1097
Josef Bacike3e05202019-06-20 15:37:55 -04001098 if (remove_em) {
1099 struct extent_map_tree *em_tree;
1100
1101 em_tree = &fs_info->mapping_tree;
1102 write_lock(&em_tree->lock);
1103 remove_extent_mapping(em_tree, em);
1104 write_unlock(&em_tree->lock);
1105 /* once for the tree */
1106 free_extent_map(em);
1107 }
Xiyu Yangf6033c52020-04-21 10:54:11 +08001108
Filipe Manana9fecd132020-06-01 19:12:06 +01001109out:
Xiyu Yangf6033c52020-04-21 10:54:11 +08001110 /* Once for the lookup reference */
1111 btrfs_put_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001112 if (remove_rsv)
1113 btrfs_delayed_refs_rsv_release(fs_info, 1);
1114 btrfs_free_path(path);
1115 return ret;
1116}
1117
1118struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1119 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1120{
1121 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1122 struct extent_map *em;
1123 struct map_lookup *map;
1124 unsigned int num_items;
1125
1126 read_lock(&em_tree->lock);
1127 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1128 read_unlock(&em_tree->lock);
1129 ASSERT(em && em->start == chunk_offset);
1130
1131 /*
1132 * We need to reserve 3 + N units from the metadata space info in order
1133 * to remove a block group (done at btrfs_remove_chunk() and at
1134 * btrfs_remove_block_group()), which are used for:
1135 *
1136 * 1 unit for adding the free space inode's orphan (located in the tree
1137 * of tree roots).
1138 * 1 unit for deleting the block group item (located in the extent
1139 * tree).
1140 * 1 unit for deleting the free space item (located in tree of tree
1141 * roots).
1142 * N units for deleting N device extent items corresponding to each
1143 * stripe (located in the device tree).
1144 *
1145 * In order to remove a block group we also need to reserve units in the
1146 * system space info in order to update the chunk tree (update one or
1147 * more device items and remove one chunk item), but this is done at
1148 * btrfs_remove_chunk() through a call to check_system_chunk().
1149 */
1150 map = em->map_lookup;
1151 num_items = 3 + map->num_stripes;
1152 free_extent_map(em);
1153
1154 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
Josef Bacik7f9fe612020-03-13 15:58:05 -04001155 num_items);
Josef Bacike3e05202019-06-20 15:37:55 -04001156}
1157
1158/*
Josef Bacik26ce2092019-06-20 15:37:59 -04001159 * Mark block group @cache read-only, so later write won't happen to block
1160 * group @cache.
1161 *
1162 * If @force is not set, this function will only mark the block group readonly
1163 * if we have enough free space (1M) in other metadata/system block groups.
1164 * If @force is not set, this function will mark the block group readonly
1165 * without checking free space.
1166 *
1167 * NOTE: This function doesn't care if other block groups can contain all the
1168 * data in this block group. That check should be done by relocation routine,
1169 * not this function.
1170 */
David Sterba32da53862019-10-29 19:20:18 +01001171static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
Josef Bacik26ce2092019-06-20 15:37:59 -04001172{
1173 struct btrfs_space_info *sinfo = cache->space_info;
1174 u64 num_bytes;
Josef Bacik26ce2092019-06-20 15:37:59 -04001175 int ret = -ENOSPC;
1176
Josef Bacik26ce2092019-06-20 15:37:59 -04001177 spin_lock(&sinfo->lock);
1178 spin_lock(&cache->lock);
1179
1180 if (cache->ro) {
1181 cache->ro++;
1182 ret = 0;
1183 goto out;
1184 }
1185
David Sterbab3470b52019-10-23 18:48:22 +02001186 num_bytes = cache->length - cache->reserved - cache->pinned -
David Sterbabf38be62019-10-23 18:48:11 +02001187 cache->bytes_super - cache->used;
Josef Bacik26ce2092019-06-20 15:37:59 -04001188
1189 /*
Josef Bacika30a3d22020-01-17 09:07:39 -05001190 * Data never overcommits, even in mixed mode, so do just the straight
1191 * check of left over space in how much we have allocated.
Josef Bacik26ce2092019-06-20 15:37:59 -04001192 */
Josef Bacika30a3d22020-01-17 09:07:39 -05001193 if (force) {
1194 ret = 0;
1195 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1196 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1197
1198 /*
1199 * Here we make sure if we mark this bg RO, we still have enough
1200 * free space as buffer.
1201 */
1202 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1203 ret = 0;
1204 } else {
1205 /*
1206 * We overcommit metadata, so we need to do the
1207 * btrfs_can_overcommit check here, and we need to pass in
1208 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1209 * leeway to allow us to mark this block group as read only.
1210 */
1211 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1212 BTRFS_RESERVE_NO_FLUSH))
1213 ret = 0;
1214 }
1215
1216 if (!ret) {
Josef Bacik26ce2092019-06-20 15:37:59 -04001217 sinfo->bytes_readonly += num_bytes;
1218 cache->ro++;
1219 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
Josef Bacik26ce2092019-06-20 15:37:59 -04001220 }
1221out:
1222 spin_unlock(&cache->lock);
1223 spin_unlock(&sinfo->lock);
1224 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1225 btrfs_info(cache->fs_info,
David Sterbab3470b52019-10-23 18:48:22 +02001226 "unable to make block group %llu ro", cache->start);
Josef Bacik26ce2092019-06-20 15:37:59 -04001227 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1228 }
1229 return ret;
1230}
1231
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001232static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1233 struct btrfs_block_group *bg)
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001234{
1235 struct btrfs_fs_info *fs_info = bg->fs_info;
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001236 struct btrfs_transaction *prev_trans = NULL;
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001237 const u64 start = bg->start;
1238 const u64 end = start + bg->length - 1;
1239 int ret;
1240
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001241 spin_lock(&fs_info->trans_lock);
1242 if (trans->transaction->list.prev != &fs_info->trans_list) {
1243 prev_trans = list_last_entry(&trans->transaction->list,
1244 struct btrfs_transaction, list);
1245 refcount_inc(&prev_trans->use_count);
1246 }
1247 spin_unlock(&fs_info->trans_lock);
1248
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001249 /*
1250 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1251 * btrfs_finish_extent_commit(). If we are at transaction N, another
1252 * task might be running finish_extent_commit() for the previous
1253 * transaction N - 1, and have seen a range belonging to the block
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001254 * group in pinned_extents before we were able to clear the whole block
1255 * group range from pinned_extents. This means that task can lookup for
1256 * the block group after we unpinned it from pinned_extents and removed
1257 * it, leading to a BUG_ON() at unpin_extent_range().
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001258 */
1259 mutex_lock(&fs_info->unused_bg_unpin_mutex);
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001260 if (prev_trans) {
1261 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1262 EXTENT_DIRTY);
1263 if (ret)
Filipe Manana534cf532020-04-17 16:36:50 +01001264 goto out;
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001265 }
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001266
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001267 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001268 EXTENT_DIRTY);
Filipe Manana534cf532020-04-17 16:36:50 +01001269out:
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001270 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
Filipe Manana5150bf12020-04-17 16:36:15 +01001271 if (prev_trans)
1272 btrfs_put_transaction(prev_trans);
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001273
Filipe Manana534cf532020-04-17 16:36:50 +01001274 return ret == 0;
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001275}
1276
Josef Bacik26ce2092019-06-20 15:37:59 -04001277/*
Josef Bacike3e05202019-06-20 15:37:55 -04001278 * Process the unused_bgs list and remove any that don't have any allocated
1279 * space inside of them.
1280 */
1281void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1282{
David Sterba32da53862019-10-29 19:20:18 +01001283 struct btrfs_block_group *block_group;
Josef Bacike3e05202019-06-20 15:37:55 -04001284 struct btrfs_space_info *space_info;
1285 struct btrfs_trans_handle *trans;
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001286 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
Josef Bacike3e05202019-06-20 15:37:55 -04001287 int ret = 0;
1288
1289 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1290 return;
1291
1292 spin_lock(&fs_info->unused_bgs_lock);
1293 while (!list_empty(&fs_info->unused_bgs)) {
Josef Bacike3e05202019-06-20 15:37:55 -04001294 int trimming;
1295
1296 block_group = list_first_entry(&fs_info->unused_bgs,
David Sterba32da53862019-10-29 19:20:18 +01001297 struct btrfs_block_group,
Josef Bacike3e05202019-06-20 15:37:55 -04001298 bg_list);
1299 list_del_init(&block_group->bg_list);
1300
1301 space_info = block_group->space_info;
1302
1303 if (ret || btrfs_mixed_space_info(space_info)) {
1304 btrfs_put_block_group(block_group);
1305 continue;
1306 }
1307 spin_unlock(&fs_info->unused_bgs_lock);
1308
Dennis Zhoub0643e52019-12-13 16:22:14 -08001309 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1310
Josef Bacike3e05202019-06-20 15:37:55 -04001311 mutex_lock(&fs_info->delete_unused_bgs_mutex);
1312
1313 /* Don't want to race with allocators so take the groups_sem */
1314 down_write(&space_info->groups_sem);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001315
1316 /*
1317 * Async discard moves the final block group discard to be prior
1318 * to the unused_bgs code path. Therefore, if it's not fully
1319 * trimmed, punt it back to the async discard lists.
1320 */
1321 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1322 !btrfs_is_free_space_trimmed(block_group)) {
1323 trace_btrfs_skip_unused_block_group(block_group);
1324 up_write(&space_info->groups_sem);
1325 /* Requeue if we failed because of async discard */
1326 btrfs_discard_queue_work(&fs_info->discard_ctl,
1327 block_group);
1328 goto next;
1329 }
1330
Josef Bacike3e05202019-06-20 15:37:55 -04001331 spin_lock(&block_group->lock);
1332 if (block_group->reserved || block_group->pinned ||
David Sterbabf38be62019-10-23 18:48:11 +02001333 block_group->used || block_group->ro ||
Josef Bacike3e05202019-06-20 15:37:55 -04001334 list_is_singular(&block_group->list)) {
1335 /*
1336 * We want to bail if we made new allocations or have
1337 * outstanding allocations in this block group. We do
1338 * the ro check in case balance is currently acting on
1339 * this block group.
1340 */
1341 trace_btrfs_skip_unused_block_group(block_group);
1342 spin_unlock(&block_group->lock);
1343 up_write(&space_info->groups_sem);
1344 goto next;
1345 }
1346 spin_unlock(&block_group->lock);
1347
1348 /* We don't want to force the issue, only flip if it's ok. */
Josef Bacike11c0402019-06-20 15:38:07 -04001349 ret = inc_block_group_ro(block_group, 0);
Josef Bacike3e05202019-06-20 15:37:55 -04001350 up_write(&space_info->groups_sem);
1351 if (ret < 0) {
1352 ret = 0;
1353 goto next;
1354 }
1355
1356 /*
1357 * Want to do this before we do anything else so we can recover
1358 * properly if we fail to join the transaction.
1359 */
1360 trans = btrfs_start_trans_remove_block_group(fs_info,
David Sterbab3470b52019-10-23 18:48:22 +02001361 block_group->start);
Josef Bacike3e05202019-06-20 15:37:55 -04001362 if (IS_ERR(trans)) {
1363 btrfs_dec_block_group_ro(block_group);
1364 ret = PTR_ERR(trans);
1365 goto next;
1366 }
1367
1368 /*
1369 * We could have pending pinned extents for this block group,
1370 * just delete them, we don't care about them anymore.
1371 */
Filipe Manana534cf532020-04-17 16:36:50 +01001372 if (!clean_pinned_extents(trans, block_group)) {
1373 btrfs_dec_block_group_ro(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001374 goto end_trans;
Filipe Manana534cf532020-04-17 16:36:50 +01001375 }
Josef Bacike3e05202019-06-20 15:37:55 -04001376
Dennis Zhoub0643e52019-12-13 16:22:14 -08001377 /*
1378 * At this point, the block_group is read only and should fail
1379 * new allocations. However, btrfs_finish_extent_commit() can
1380 * cause this block_group to be placed back on the discard
1381 * lists because now the block_group isn't fully discarded.
1382 * Bail here and try again later after discarding everything.
1383 */
1384 spin_lock(&fs_info->discard_ctl.lock);
1385 if (!list_empty(&block_group->discard_list)) {
1386 spin_unlock(&fs_info->discard_ctl.lock);
1387 btrfs_dec_block_group_ro(block_group);
1388 btrfs_discard_queue_work(&fs_info->discard_ctl,
1389 block_group);
1390 goto end_trans;
1391 }
1392 spin_unlock(&fs_info->discard_ctl.lock);
1393
Josef Bacike3e05202019-06-20 15:37:55 -04001394 /* Reset pinned so btrfs_put_block_group doesn't complain */
1395 spin_lock(&space_info->lock);
1396 spin_lock(&block_group->lock);
1397
1398 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1399 -block_group->pinned);
1400 space_info->bytes_readonly += block_group->pinned;
1401 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1402 -block_group->pinned,
1403 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1404 block_group->pinned = 0;
1405
1406 spin_unlock(&block_group->lock);
1407 spin_unlock(&space_info->lock);
1408
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001409 /*
1410 * The normal path here is an unused block group is passed here,
1411 * then trimming is handled in the transaction commit path.
1412 * Async discard interposes before this to do the trimming
1413 * before coming down the unused block group path as trimming
1414 * will no longer be done later in the transaction commit path.
1415 */
1416 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1417 goto flip_async;
1418
Josef Bacike3e05202019-06-20 15:37:55 -04001419 /* DISCARD can flip during remount */
Dennis Zhou46b27f52019-12-13 16:22:11 -08001420 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
Josef Bacike3e05202019-06-20 15:37:55 -04001421
1422 /* Implicit trim during transaction commit. */
1423 if (trimming)
Filipe Manana6b7304a2020-05-08 11:01:47 +01001424 btrfs_freeze_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001425
1426 /*
1427 * Btrfs_remove_chunk will abort the transaction if things go
1428 * horribly wrong.
1429 */
David Sterbab3470b52019-10-23 18:48:22 +02001430 ret = btrfs_remove_chunk(trans, block_group->start);
Josef Bacike3e05202019-06-20 15:37:55 -04001431
1432 if (ret) {
1433 if (trimming)
Filipe Manana6b7304a2020-05-08 11:01:47 +01001434 btrfs_unfreeze_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001435 goto end_trans;
1436 }
1437
1438 /*
1439 * If we're not mounted with -odiscard, we can just forget
1440 * about this block group. Otherwise we'll need to wait
1441 * until transaction commit to do the actual discard.
1442 */
1443 if (trimming) {
1444 spin_lock(&fs_info->unused_bgs_lock);
1445 /*
1446 * A concurrent scrub might have added us to the list
1447 * fs_info->unused_bgs, so use a list_move operation
1448 * to add the block group to the deleted_bgs list.
1449 */
1450 list_move(&block_group->bg_list,
1451 &trans->transaction->deleted_bgs);
1452 spin_unlock(&fs_info->unused_bgs_lock);
1453 btrfs_get_block_group(block_group);
1454 }
1455end_trans:
1456 btrfs_end_transaction(trans);
1457next:
1458 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1459 btrfs_put_block_group(block_group);
1460 spin_lock(&fs_info->unused_bgs_lock);
1461 }
1462 spin_unlock(&fs_info->unused_bgs_lock);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001463 return;
1464
1465flip_async:
1466 btrfs_end_transaction(trans);
1467 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1468 btrfs_put_block_group(block_group);
1469 btrfs_discard_punt_unused_bgs_list(fs_info);
Josef Bacike3e05202019-06-20 15:37:55 -04001470}
1471
David Sterba32da53862019-10-29 19:20:18 +01001472void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
Josef Bacike3e05202019-06-20 15:37:55 -04001473{
1474 struct btrfs_fs_info *fs_info = bg->fs_info;
1475
1476 spin_lock(&fs_info->unused_bgs_lock);
1477 if (list_empty(&bg->bg_list)) {
1478 btrfs_get_block_group(bg);
1479 trace_btrfs_add_unused_block_group(bg);
1480 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1481 }
1482 spin_unlock(&fs_info->unused_bgs_lock);
1483}
Josef Bacik4358d9632019-06-20 15:37:57 -04001484
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001485static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1486 struct btrfs_path *path)
1487{
1488 struct extent_map_tree *em_tree;
1489 struct extent_map *em;
1490 struct btrfs_block_group_item bg;
1491 struct extent_buffer *leaf;
1492 int slot;
1493 u64 flags;
1494 int ret = 0;
1495
1496 slot = path->slots[0];
1497 leaf = path->nodes[0];
1498
1499 em_tree = &fs_info->mapping_tree;
1500 read_lock(&em_tree->lock);
1501 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1502 read_unlock(&em_tree->lock);
1503 if (!em) {
1504 btrfs_err(fs_info,
1505 "logical %llu len %llu found bg but no related chunk",
1506 key->objectid, key->offset);
1507 return -ENOENT;
1508 }
1509
1510 if (em->start != key->objectid || em->len != key->offset) {
1511 btrfs_err(fs_info,
1512 "block group %llu len %llu mismatch with chunk %llu len %llu",
1513 key->objectid, key->offset, em->start, em->len);
1514 ret = -EUCLEAN;
1515 goto out_free_em;
1516 }
1517
1518 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1519 sizeof(bg));
1520 flags = btrfs_stack_block_group_flags(&bg) &
1521 BTRFS_BLOCK_GROUP_TYPE_MASK;
1522
1523 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1524 btrfs_err(fs_info,
1525"block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1526 key->objectid, key->offset, flags,
1527 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1528 ret = -EUCLEAN;
1529 }
1530
1531out_free_em:
1532 free_extent_map(em);
1533 return ret;
1534}
1535
Josef Bacik4358d9632019-06-20 15:37:57 -04001536static int find_first_block_group(struct btrfs_fs_info *fs_info,
1537 struct btrfs_path *path,
1538 struct btrfs_key *key)
1539{
1540 struct btrfs_root *root = fs_info->extent_root;
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001541 int ret;
Josef Bacik4358d9632019-06-20 15:37:57 -04001542 struct btrfs_key found_key;
1543 struct extent_buffer *leaf;
Josef Bacik4358d9632019-06-20 15:37:57 -04001544 int slot;
1545
1546 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1547 if (ret < 0)
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001548 return ret;
Josef Bacik4358d9632019-06-20 15:37:57 -04001549
1550 while (1) {
1551 slot = path->slots[0];
1552 leaf = path->nodes[0];
1553 if (slot >= btrfs_header_nritems(leaf)) {
1554 ret = btrfs_next_leaf(root, path);
1555 if (ret == 0)
1556 continue;
1557 if (ret < 0)
1558 goto out;
1559 break;
1560 }
1561 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1562
1563 if (found_key.objectid >= key->objectid &&
1564 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001565 ret = read_bg_from_eb(fs_info, &found_key, path);
1566 break;
Josef Bacik4358d9632019-06-20 15:37:57 -04001567 }
Johannes Thumshirne3ba67a2020-06-02 19:05:57 +09001568
Josef Bacik4358d9632019-06-20 15:37:57 -04001569 path->slots[0]++;
1570 }
1571out:
1572 return ret;
1573}
1574
1575static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1576{
1577 u64 extra_flags = chunk_to_extended(flags) &
1578 BTRFS_EXTENDED_PROFILE_MASK;
1579
1580 write_seqlock(&fs_info->profiles_lock);
1581 if (flags & BTRFS_BLOCK_GROUP_DATA)
1582 fs_info->avail_data_alloc_bits |= extra_flags;
1583 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1584 fs_info->avail_metadata_alloc_bits |= extra_flags;
1585 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1586 fs_info->avail_system_alloc_bits |= extra_flags;
1587 write_sequnlock(&fs_info->profiles_lock);
1588}
1589
Nikolay Borisov96a14332019-12-10 19:57:51 +02001590/**
1591 * btrfs_rmap_block - Map a physical disk address to a list of logical addresses
1592 * @chunk_start: logical address of block group
1593 * @physical: physical address to map to logical addresses
1594 * @logical: return array of logical addresses which map to @physical
1595 * @naddrs: length of @logical
1596 * @stripe_len: size of IO stripe for the given block group
1597 *
1598 * Maps a particular @physical disk address to a list of @logical addresses.
1599 * Used primarily to exclude those portions of a block group that contain super
1600 * block copies.
1601 */
1602EXPORT_FOR_TESTS
1603int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1604 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1605{
1606 struct extent_map *em;
1607 struct map_lookup *map;
1608 u64 *buf;
1609 u64 bytenr;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001610 u64 data_stripe_length;
1611 u64 io_stripe_size;
1612 int i, nr = 0;
1613 int ret = 0;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001614
1615 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1616 if (IS_ERR(em))
1617 return -EIO;
1618
1619 map = em->map_lookup;
Nikolay Borisov9e22b922020-04-03 16:40:34 +03001620 data_stripe_length = em->orig_block_len;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001621 io_stripe_size = map->stripe_len;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001622
Nikolay Borisov9e22b922020-04-03 16:40:34 +03001623 /* For RAID5/6 adjust to a full IO stripe length */
1624 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001625 io_stripe_size = map->stripe_len * nr_data_stripes(map);
Nikolay Borisov96a14332019-12-10 19:57:51 +02001626
1627 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001628 if (!buf) {
1629 ret = -ENOMEM;
1630 goto out;
1631 }
Nikolay Borisov96a14332019-12-10 19:57:51 +02001632
1633 for (i = 0; i < map->num_stripes; i++) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001634 bool already_inserted = false;
1635 u64 stripe_nr;
1636 int j;
1637
1638 if (!in_range(physical, map->stripes[i].physical,
1639 data_stripe_length))
Nikolay Borisov96a14332019-12-10 19:57:51 +02001640 continue;
1641
1642 stripe_nr = physical - map->stripes[i].physical;
1643 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1644
1645 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1646 stripe_nr = stripe_nr * map->num_stripes + i;
1647 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1648 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1649 stripe_nr = stripe_nr * map->num_stripes + i;
1650 }
1651 /*
1652 * The remaining case would be for RAID56, multiply by
1653 * nr_data_stripes(). Alternatively, just use rmap_len below
1654 * instead of map->stripe_len
1655 */
1656
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001657 bytenr = chunk_start + stripe_nr * io_stripe_size;
1658
1659 /* Ensure we don't add duplicate addresses */
Nikolay Borisov96a14332019-12-10 19:57:51 +02001660 for (j = 0; j < nr; j++) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001661 if (buf[j] == bytenr) {
1662 already_inserted = true;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001663 break;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001664 }
Nikolay Borisov96a14332019-12-10 19:57:51 +02001665 }
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001666
1667 if (!already_inserted)
Nikolay Borisov96a14332019-12-10 19:57:51 +02001668 buf[nr++] = bytenr;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001669 }
1670
1671 *logical = buf;
1672 *naddrs = nr;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001673 *stripe_len = io_stripe_size;
1674out:
Nikolay Borisov96a14332019-12-10 19:57:51 +02001675 free_extent_map(em);
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001676 return ret;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001677}
1678
David Sterba32da53862019-10-29 19:20:18 +01001679static int exclude_super_stripes(struct btrfs_block_group *cache)
Josef Bacik4358d9632019-06-20 15:37:57 -04001680{
1681 struct btrfs_fs_info *fs_info = cache->fs_info;
Naohiro Aota12659252020-11-10 20:26:14 +09001682 const bool zoned = btrfs_is_zoned(fs_info);
Josef Bacik4358d9632019-06-20 15:37:57 -04001683 u64 bytenr;
1684 u64 *logical;
1685 int stripe_len;
1686 int i, nr, ret;
1687
David Sterbab3470b52019-10-23 18:48:22 +02001688 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1689 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
Josef Bacik4358d9632019-06-20 15:37:57 -04001690 cache->bytes_super += stripe_len;
David Sterbab3470b52019-10-23 18:48:22 +02001691 ret = btrfs_add_excluded_extent(fs_info, cache->start,
Josef Bacik4358d9632019-06-20 15:37:57 -04001692 stripe_len);
1693 if (ret)
1694 return ret;
1695 }
1696
1697 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1698 bytenr = btrfs_sb_offset(i);
David Sterbab3470b52019-10-23 18:48:22 +02001699 ret = btrfs_rmap_block(fs_info, cache->start,
Josef Bacik4358d9632019-06-20 15:37:57 -04001700 bytenr, &logical, &nr, &stripe_len);
1701 if (ret)
1702 return ret;
1703
Naohiro Aota12659252020-11-10 20:26:14 +09001704 /* Shouldn't have super stripes in sequential zones */
1705 if (zoned && nr) {
1706 btrfs_err(fs_info,
1707 "zoned: block group %llu must not contain super block",
1708 cache->start);
1709 return -EUCLEAN;
1710 }
1711
Josef Bacik4358d9632019-06-20 15:37:57 -04001712 while (nr--) {
Nikolay Borisov96f9b0f2020-04-03 16:40:35 +03001713 u64 len = min_t(u64, stripe_len,
1714 cache->start + cache->length - logical[nr]);
Josef Bacik4358d9632019-06-20 15:37:57 -04001715
1716 cache->bytes_super += len;
Nikolay Borisov96f9b0f2020-04-03 16:40:35 +03001717 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
1718 len);
Josef Bacik4358d9632019-06-20 15:37:57 -04001719 if (ret) {
1720 kfree(logical);
1721 return ret;
1722 }
1723 }
1724
1725 kfree(logical);
1726 }
1727 return 0;
1728}
1729
David Sterba32da53862019-10-29 19:20:18 +01001730static void link_block_group(struct btrfs_block_group *cache)
Josef Bacik4358d9632019-06-20 15:37:57 -04001731{
1732 struct btrfs_space_info *space_info = cache->space_info;
1733 int index = btrfs_bg_flags_to_raid_index(cache->flags);
Josef Bacik4358d9632019-06-20 15:37:57 -04001734
1735 down_write(&space_info->groups_sem);
Josef Bacik4358d9632019-06-20 15:37:57 -04001736 list_add_tail(&cache->list, &space_info->block_groups[index]);
1737 up_write(&space_info->groups_sem);
Josef Bacik4358d9632019-06-20 15:37:57 -04001738}
1739
David Sterba32da53862019-10-29 19:20:18 +01001740static struct btrfs_block_group *btrfs_create_block_group_cache(
Qu Wenruo9afc6642020-05-05 07:58:20 +08001741 struct btrfs_fs_info *fs_info, u64 start)
Josef Bacik4358d9632019-06-20 15:37:57 -04001742{
David Sterba32da53862019-10-29 19:20:18 +01001743 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04001744
1745 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1746 if (!cache)
1747 return NULL;
1748
1749 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1750 GFP_NOFS);
1751 if (!cache->free_space_ctl) {
1752 kfree(cache);
1753 return NULL;
1754 }
1755
David Sterbab3470b52019-10-23 18:48:22 +02001756 cache->start = start;
Josef Bacik4358d9632019-06-20 15:37:57 -04001757
1758 cache->fs_info = fs_info;
1759 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
Josef Bacik4358d9632019-06-20 15:37:57 -04001760
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001761 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1762
Josef Bacik48aaeeb2020-07-06 09:14:11 -04001763 refcount_set(&cache->refs, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04001764 spin_lock_init(&cache->lock);
1765 init_rwsem(&cache->data_rwsem);
1766 INIT_LIST_HEAD(&cache->list);
1767 INIT_LIST_HEAD(&cache->cluster_list);
1768 INIT_LIST_HEAD(&cache->bg_list);
1769 INIT_LIST_HEAD(&cache->ro_list);
Dennis Zhoub0643e52019-12-13 16:22:14 -08001770 INIT_LIST_HEAD(&cache->discard_list);
Josef Bacik4358d9632019-06-20 15:37:57 -04001771 INIT_LIST_HEAD(&cache->dirty_list);
1772 INIT_LIST_HEAD(&cache->io_list);
Josef Bacikcd799092020-10-23 09:58:08 -04001773 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
Filipe Manana6b7304a2020-05-08 11:01:47 +01001774 atomic_set(&cache->frozen, 0);
Josef Bacik4358d9632019-06-20 15:37:57 -04001775 mutex_init(&cache->free_space_lock);
1776 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1777
1778 return cache;
1779}
1780
1781/*
1782 * Iterate all chunks and verify that each of them has the corresponding block
1783 * group
1784 */
1785static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1786{
1787 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1788 struct extent_map *em;
David Sterba32da53862019-10-29 19:20:18 +01001789 struct btrfs_block_group *bg;
Josef Bacik4358d9632019-06-20 15:37:57 -04001790 u64 start = 0;
1791 int ret = 0;
1792
1793 while (1) {
1794 read_lock(&map_tree->lock);
1795 /*
1796 * lookup_extent_mapping will return the first extent map
1797 * intersecting the range, so setting @len to 1 is enough to
1798 * get the first chunk.
1799 */
1800 em = lookup_extent_mapping(map_tree, start, 1);
1801 read_unlock(&map_tree->lock);
1802 if (!em)
1803 break;
1804
1805 bg = btrfs_lookup_block_group(fs_info, em->start);
1806 if (!bg) {
1807 btrfs_err(fs_info,
1808 "chunk start=%llu len=%llu doesn't have corresponding block group",
1809 em->start, em->len);
1810 ret = -EUCLEAN;
1811 free_extent_map(em);
1812 break;
1813 }
David Sterbab3470b52019-10-23 18:48:22 +02001814 if (bg->start != em->start || bg->length != em->len ||
Josef Bacik4358d9632019-06-20 15:37:57 -04001815 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1816 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1817 btrfs_err(fs_info,
1818"chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1819 em->start, em->len,
1820 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
David Sterbab3470b52019-10-23 18:48:22 +02001821 bg->start, bg->length,
Josef Bacik4358d9632019-06-20 15:37:57 -04001822 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1823 ret = -EUCLEAN;
1824 free_extent_map(em);
1825 btrfs_put_block_group(bg);
1826 break;
1827 }
1828 start = em->start + em->len;
1829 free_extent_map(em);
1830 btrfs_put_block_group(bg);
1831 }
1832 return ret;
1833}
1834
Marcos Paulo de Souza4c448ce2020-08-17 10:56:10 -03001835static void read_block_group_item(struct btrfs_block_group *cache,
Qu Wenruo9afc6642020-05-05 07:58:20 +08001836 struct btrfs_path *path,
1837 const struct btrfs_key *key)
1838{
1839 struct extent_buffer *leaf = path->nodes[0];
1840 struct btrfs_block_group_item bgi;
1841 int slot = path->slots[0];
1842
1843 cache->length = key->offset;
1844
1845 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1846 sizeof(bgi));
1847 cache->used = btrfs_stack_block_group_used(&bgi);
1848 cache->flags = btrfs_stack_block_group_flags(&bgi);
Qu Wenruo9afc6642020-05-05 07:58:20 +08001849}
1850
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001851static int read_one_block_group(struct btrfs_fs_info *info,
1852 struct btrfs_path *path,
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001853 const struct btrfs_key *key,
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001854 int need_clear)
1855{
David Sterba32da53862019-10-29 19:20:18 +01001856 struct btrfs_block_group *cache;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001857 struct btrfs_space_info *space_info;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001858 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001859 int ret;
1860
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001861 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001862
Qu Wenruo9afc6642020-05-05 07:58:20 +08001863 cache = btrfs_create_block_group_cache(info, key->objectid);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001864 if (!cache)
1865 return -ENOMEM;
1866
Marcos Paulo de Souza4c448ce2020-08-17 10:56:10 -03001867 read_block_group_item(cache, path, key);
Qu Wenruo9afc6642020-05-05 07:58:20 +08001868
Marcos Paulo de Souzae3e39c72020-08-21 11:54:44 -03001869 set_free_space_tree_thresholds(cache);
1870
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001871 if (need_clear) {
1872 /*
1873 * When we mount with old space cache, we need to
1874 * set BTRFS_DC_CLEAR and set dirty flag.
1875 *
1876 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1877 * truncate the old free space cache inode and
1878 * setup a new one.
1879 * b) Setting 'dirty flag' makes sure that we flush
1880 * the new space cache info onto disk.
1881 */
1882 if (btrfs_test_opt(info, SPACE_CACHE))
1883 cache->disk_cache_state = BTRFS_DC_CLEAR;
1884 }
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001885 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1886 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1887 btrfs_err(info,
1888"bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1889 cache->start);
1890 ret = -EINVAL;
1891 goto error;
1892 }
1893
1894 /*
1895 * We need to exclude the super stripes now so that the space info has
1896 * super bytes accounted for, otherwise we'll think we have more space
1897 * than we actually do.
1898 */
1899 ret = exclude_super_stripes(cache);
1900 if (ret) {
1901 /* We may have excluded something, so call this just in case. */
1902 btrfs_free_excluded_extents(cache);
1903 goto error;
1904 }
1905
1906 /*
1907 * Check for two cases, either we are full, and therefore don't need
1908 * to bother with the caching work since we won't find any space, or we
1909 * are empty, and we can just add all the space in and be done with it.
1910 * This saves us _a_lot_ of time, particularly in the full case.
1911 */
Qu Wenruo9afc6642020-05-05 07:58:20 +08001912 if (cache->length == cache->used) {
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001913 cache->last_byte_to_unpin = (u64)-1;
1914 cache->cached = BTRFS_CACHE_FINISHED;
1915 btrfs_free_excluded_extents(cache);
1916 } else if (cache->used == 0) {
1917 cache->last_byte_to_unpin = (u64)-1;
1918 cache->cached = BTRFS_CACHE_FINISHED;
Qu Wenruo9afc6642020-05-05 07:58:20 +08001919 add_new_free_space(cache, cache->start,
1920 cache->start + cache->length);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001921 btrfs_free_excluded_extents(cache);
1922 }
1923
1924 ret = btrfs_add_block_group_cache(info, cache);
1925 if (ret) {
1926 btrfs_remove_free_space_cache(cache);
1927 goto error;
1928 }
1929 trace_btrfs_add_block_group(info, cache, 0);
Qu Wenruo9afc6642020-05-05 07:58:20 +08001930 btrfs_update_space_info(info, cache->flags, cache->length,
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001931 cache->used, cache->bytes_super, &space_info);
1932
1933 cache->space_info = space_info;
1934
1935 link_block_group(cache);
1936
1937 set_avail_alloc_bits(info, cache->flags);
1938 if (btrfs_chunk_readonly(info, cache->start)) {
1939 inc_block_group_ro(cache, 1);
1940 } else if (cache->used == 0) {
1941 ASSERT(list_empty(&cache->bg_list));
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001942 if (btrfs_test_opt(info, DISCARD_ASYNC))
1943 btrfs_discard_queue_work(&info->discard_ctl, cache);
1944 else
1945 btrfs_mark_bg_unused(cache);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001946 }
1947 return 0;
1948error:
1949 btrfs_put_block_group(cache);
1950 return ret;
1951}
1952
Josef Bacik42437a62020-10-16 11:29:18 -04001953static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
1954{
1955 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1956 struct btrfs_space_info *space_info;
1957 struct rb_node *node;
1958 int ret = 0;
1959
1960 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
1961 struct extent_map *em;
1962 struct map_lookup *map;
1963 struct btrfs_block_group *bg;
1964
1965 em = rb_entry(node, struct extent_map, rb_node);
1966 map = em->map_lookup;
1967 bg = btrfs_create_block_group_cache(fs_info, em->start);
1968 if (!bg) {
1969 ret = -ENOMEM;
1970 break;
1971 }
1972
1973 /* Fill dummy cache as FULL */
1974 bg->length = em->len;
1975 bg->flags = map->type;
1976 bg->last_byte_to_unpin = (u64)-1;
1977 bg->cached = BTRFS_CACHE_FINISHED;
1978 bg->used = em->len;
1979 bg->flags = map->type;
1980 ret = btrfs_add_block_group_cache(fs_info, bg);
1981 if (ret) {
1982 btrfs_remove_free_space_cache(bg);
1983 btrfs_put_block_group(bg);
1984 break;
1985 }
1986 btrfs_update_space_info(fs_info, bg->flags, em->len, em->len,
1987 0, &space_info);
1988 bg->space_info = space_info;
1989 link_block_group(bg);
1990
1991 set_avail_alloc_bits(fs_info, bg->flags);
1992 }
1993 if (!ret)
1994 btrfs_init_global_block_rsv(fs_info);
1995 return ret;
1996}
1997
Josef Bacik4358d9632019-06-20 15:37:57 -04001998int btrfs_read_block_groups(struct btrfs_fs_info *info)
1999{
2000 struct btrfs_path *path;
2001 int ret;
David Sterba32da53862019-10-29 19:20:18 +01002002 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04002003 struct btrfs_space_info *space_info;
2004 struct btrfs_key key;
Josef Bacik4358d9632019-06-20 15:37:57 -04002005 int need_clear = 0;
2006 u64 cache_gen;
Josef Bacik4358d9632019-06-20 15:37:57 -04002007
Josef Bacik42437a62020-10-16 11:29:18 -04002008 if (!info->extent_root)
2009 return fill_dummy_bgs(info);
2010
Josef Bacik4358d9632019-06-20 15:37:57 -04002011 key.objectid = 0;
2012 key.offset = 0;
2013 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2014 path = btrfs_alloc_path();
2015 if (!path)
2016 return -ENOMEM;
Josef Bacik4358d9632019-06-20 15:37:57 -04002017
2018 cache_gen = btrfs_super_cache_generation(info->super_copy);
2019 if (btrfs_test_opt(info, SPACE_CACHE) &&
2020 btrfs_super_generation(info->super_copy) != cache_gen)
2021 need_clear = 1;
2022 if (btrfs_test_opt(info, CLEAR_CACHE))
2023 need_clear = 1;
2024
2025 while (1) {
2026 ret = find_first_block_group(info, path, &key);
2027 if (ret > 0)
2028 break;
2029 if (ret != 0)
2030 goto error;
2031
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002032 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
Qu Wenruod49a2dd2019-11-05 09:35:35 +08002033 ret = read_one_block_group(info, path, &key, need_clear);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002034 if (ret < 0)
Josef Bacik4358d9632019-06-20 15:37:57 -04002035 goto error;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002036 key.objectid += key.offset;
2037 key.offset = 0;
Josef Bacik4358d9632019-06-20 15:37:57 -04002038 btrfs_release_path(path);
Josef Bacik4358d9632019-06-20 15:37:57 -04002039 }
Josef Bacik7837fa82020-10-14 17:00:51 -04002040 btrfs_release_path(path);
Josef Bacik4358d9632019-06-20 15:37:57 -04002041
Josef Bacik72804902020-09-01 17:40:37 -04002042 list_for_each_entry(space_info, &info->space_info, list) {
Josef Bacik49ea1122020-09-01 17:40:38 -04002043 int i;
2044
2045 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2046 if (list_empty(&space_info->block_groups[i]))
2047 continue;
2048 cache = list_first_entry(&space_info->block_groups[i],
2049 struct btrfs_block_group,
2050 list);
2051 btrfs_sysfs_add_block_group_type(cache);
2052 }
2053
Josef Bacik4358d9632019-06-20 15:37:57 -04002054 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2055 (BTRFS_BLOCK_GROUP_RAID10 |
2056 BTRFS_BLOCK_GROUP_RAID1_MASK |
2057 BTRFS_BLOCK_GROUP_RAID56_MASK |
2058 BTRFS_BLOCK_GROUP_DUP)))
2059 continue;
2060 /*
2061 * Avoid allocating from un-mirrored block group if there are
2062 * mirrored block groups.
2063 */
2064 list_for_each_entry(cache,
2065 &space_info->block_groups[BTRFS_RAID_RAID0],
2066 list)
Josef Bacike11c0402019-06-20 15:38:07 -04002067 inc_block_group_ro(cache, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04002068 list_for_each_entry(cache,
2069 &space_info->block_groups[BTRFS_RAID_SINGLE],
2070 list)
Josef Bacike11c0402019-06-20 15:38:07 -04002071 inc_block_group_ro(cache, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04002072 }
2073
2074 btrfs_init_global_block_rsv(info);
2075 ret = check_chunk_block_group_mappings(info);
2076error:
2077 btrfs_free_path(path);
2078 return ret;
2079}
2080
Qu Wenruo97f47282020-05-05 07:58:22 +08002081static int insert_block_group_item(struct btrfs_trans_handle *trans,
2082 struct btrfs_block_group *block_group)
2083{
2084 struct btrfs_fs_info *fs_info = trans->fs_info;
2085 struct btrfs_block_group_item bgi;
2086 struct btrfs_root *root;
2087 struct btrfs_key key;
2088
2089 spin_lock(&block_group->lock);
2090 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2091 btrfs_set_stack_block_group_chunk_objectid(&bgi,
2092 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2093 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2094 key.objectid = block_group->start;
2095 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2096 key.offset = block_group->length;
2097 spin_unlock(&block_group->lock);
2098
2099 root = fs_info->extent_root;
2100 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2101}
2102
Josef Bacik4358d9632019-06-20 15:37:57 -04002103void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2104{
2105 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002106 struct btrfs_block_group *block_group;
Josef Bacik4358d9632019-06-20 15:37:57 -04002107 int ret = 0;
2108
2109 if (!trans->can_flush_pending_bgs)
2110 return;
2111
2112 while (!list_empty(&trans->new_bgs)) {
Josef Bacik49ea1122020-09-01 17:40:38 -04002113 int index;
2114
Josef Bacik4358d9632019-06-20 15:37:57 -04002115 block_group = list_first_entry(&trans->new_bgs,
David Sterba32da53862019-10-29 19:20:18 +01002116 struct btrfs_block_group,
Josef Bacik4358d9632019-06-20 15:37:57 -04002117 bg_list);
2118 if (ret)
2119 goto next;
2120
Josef Bacik49ea1122020-09-01 17:40:38 -04002121 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2122
Qu Wenruo97f47282020-05-05 07:58:22 +08002123 ret = insert_block_group_item(trans, block_group);
Josef Bacik4358d9632019-06-20 15:37:57 -04002124 if (ret)
2125 btrfs_abort_transaction(trans, ret);
Qu Wenruo97f47282020-05-05 07:58:22 +08002126 ret = btrfs_finish_chunk_alloc(trans, block_group->start,
2127 block_group->length);
Josef Bacik4358d9632019-06-20 15:37:57 -04002128 if (ret)
2129 btrfs_abort_transaction(trans, ret);
2130 add_block_group_free_space(trans, block_group);
Josef Bacik49ea1122020-09-01 17:40:38 -04002131
2132 /*
2133 * If we restriped during balance, we may have added a new raid
2134 * type, so now add the sysfs entries when it is safe to do so.
2135 * We don't have to worry about locking here as it's handled in
2136 * btrfs_sysfs_add_block_group_type.
2137 */
2138 if (block_group->space_info->block_group_kobjs[index] == NULL)
2139 btrfs_sysfs_add_block_group_type(block_group);
2140
Josef Bacik4358d9632019-06-20 15:37:57 -04002141 /* Already aborted the transaction if it failed. */
2142next:
2143 btrfs_delayed_refs_rsv_release(fs_info, 1);
2144 list_del_init(&block_group->bg_list);
2145 }
2146 btrfs_trans_release_chunk_metadata(trans);
2147}
2148
2149int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2150 u64 type, u64 chunk_offset, u64 size)
2151{
2152 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002153 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04002154 int ret;
2155
2156 btrfs_set_log_full_commit(trans);
2157
Qu Wenruo9afc6642020-05-05 07:58:20 +08002158 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
Josef Bacik4358d9632019-06-20 15:37:57 -04002159 if (!cache)
2160 return -ENOMEM;
2161
Qu Wenruo9afc6642020-05-05 07:58:20 +08002162 cache->length = size;
Marcos Paulo de Souzae3e39c72020-08-21 11:54:44 -03002163 set_free_space_tree_thresholds(cache);
David Sterbabf38be62019-10-23 18:48:11 +02002164 cache->used = bytes_used;
Josef Bacik4358d9632019-06-20 15:37:57 -04002165 cache->flags = type;
2166 cache->last_byte_to_unpin = (u64)-1;
2167 cache->cached = BTRFS_CACHE_FINISHED;
2168 cache->needs_free_space = 1;
2169 ret = exclude_super_stripes(cache);
2170 if (ret) {
2171 /* We may have excluded something, so call this just in case */
2172 btrfs_free_excluded_extents(cache);
2173 btrfs_put_block_group(cache);
2174 return ret;
2175 }
2176
2177 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2178
2179 btrfs_free_excluded_extents(cache);
2180
2181#ifdef CONFIG_BTRFS_DEBUG
2182 if (btrfs_should_fragment_free_space(cache)) {
2183 u64 new_bytes_used = size - bytes_used;
2184
2185 bytes_used += new_bytes_used >> 1;
Josef Bacike11c0402019-06-20 15:38:07 -04002186 fragment_free_space(cache);
Josef Bacik4358d9632019-06-20 15:37:57 -04002187 }
2188#endif
2189 /*
2190 * Ensure the corresponding space_info object is created and
2191 * assigned to our block group. We want our bg to be added to the rbtree
2192 * with its ->space_info set.
2193 */
2194 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2195 ASSERT(cache->space_info);
2196
2197 ret = btrfs_add_block_group_cache(fs_info, cache);
2198 if (ret) {
2199 btrfs_remove_free_space_cache(cache);
2200 btrfs_put_block_group(cache);
2201 return ret;
2202 }
2203
2204 /*
2205 * Now that our block group has its ->space_info set and is inserted in
2206 * the rbtree, update the space info's counters.
2207 */
2208 trace_btrfs_add_block_group(fs_info, cache, 1);
2209 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2210 cache->bytes_super, &cache->space_info);
2211 btrfs_update_global_block_rsv(fs_info);
2212
2213 link_block_group(cache);
2214
2215 list_add_tail(&cache->bg_list, &trans->new_bgs);
2216 trans->delayed_ref_updates++;
2217 btrfs_update_delayed_refs_rsv(trans);
2218
2219 set_avail_alloc_bits(fs_info, type);
2220 return 0;
2221}
Josef Bacik26ce2092019-06-20 15:37:59 -04002222
Qu Wenruob12de522019-11-15 10:09:00 +08002223/*
2224 * Mark one block group RO, can be called several times for the same block
2225 * group.
2226 *
2227 * @cache: the destination block group
2228 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2229 * ensure we still have some free space after marking this
2230 * block group RO.
2231 */
2232int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2233 bool do_chunk_alloc)
Josef Bacik26ce2092019-06-20 15:37:59 -04002234{
2235 struct btrfs_fs_info *fs_info = cache->fs_info;
2236 struct btrfs_trans_handle *trans;
2237 u64 alloc_flags;
2238 int ret;
2239
2240again:
2241 trans = btrfs_join_transaction(fs_info->extent_root);
2242 if (IS_ERR(trans))
2243 return PTR_ERR(trans);
2244
2245 /*
2246 * we're not allowed to set block groups readonly after the dirty
2247 * block groups cache has started writing. If it already started,
2248 * back off and let this transaction commit
2249 */
2250 mutex_lock(&fs_info->ro_block_group_mutex);
2251 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2252 u64 transid = trans->transid;
2253
2254 mutex_unlock(&fs_info->ro_block_group_mutex);
2255 btrfs_end_transaction(trans);
2256
2257 ret = btrfs_wait_for_commit(fs_info, transid);
2258 if (ret)
2259 return ret;
2260 goto again;
2261 }
2262
Qu Wenruob12de522019-11-15 10:09:00 +08002263 if (do_chunk_alloc) {
Josef Bacik26ce2092019-06-20 15:37:59 -04002264 /*
Qu Wenruob12de522019-11-15 10:09:00 +08002265 * If we are changing raid levels, try to allocate a
2266 * corresponding block group with the new raid level.
Josef Bacik26ce2092019-06-20 15:37:59 -04002267 */
Josef Bacik349e1202020-07-21 10:48:45 -04002268 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
Qu Wenruob12de522019-11-15 10:09:00 +08002269 if (alloc_flags != cache->flags) {
2270 ret = btrfs_chunk_alloc(trans, alloc_flags,
2271 CHUNK_ALLOC_FORCE);
2272 /*
2273 * ENOSPC is allowed here, we may have enough space
2274 * already allocated at the new raid level to carry on
2275 */
2276 if (ret == -ENOSPC)
2277 ret = 0;
2278 if (ret < 0)
2279 goto out;
2280 }
Josef Bacik26ce2092019-06-20 15:37:59 -04002281 }
2282
Josef Bacika7a63acc2020-01-17 09:07:38 -05002283 ret = inc_block_group_ro(cache, 0);
Qu Wenruob12de522019-11-15 10:09:00 +08002284 if (!do_chunk_alloc)
2285 goto unlock_out;
Josef Bacik26ce2092019-06-20 15:37:59 -04002286 if (!ret)
2287 goto out;
2288 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2289 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2290 if (ret < 0)
2291 goto out;
Josef Bacike11c0402019-06-20 15:38:07 -04002292 ret = inc_block_group_ro(cache, 0);
Josef Bacik26ce2092019-06-20 15:37:59 -04002293out:
2294 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
Josef Bacik349e1202020-07-21 10:48:45 -04002295 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
Josef Bacik26ce2092019-06-20 15:37:59 -04002296 mutex_lock(&fs_info->chunk_mutex);
2297 check_system_chunk(trans, alloc_flags);
2298 mutex_unlock(&fs_info->chunk_mutex);
2299 }
Qu Wenruob12de522019-11-15 10:09:00 +08002300unlock_out:
Josef Bacik26ce2092019-06-20 15:37:59 -04002301 mutex_unlock(&fs_info->ro_block_group_mutex);
2302
2303 btrfs_end_transaction(trans);
2304 return ret;
2305}
2306
David Sterba32da53862019-10-29 19:20:18 +01002307void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
Josef Bacik26ce2092019-06-20 15:37:59 -04002308{
2309 struct btrfs_space_info *sinfo = cache->space_info;
2310 u64 num_bytes;
2311
2312 BUG_ON(!cache->ro);
2313
2314 spin_lock(&sinfo->lock);
2315 spin_lock(&cache->lock);
2316 if (!--cache->ro) {
David Sterbab3470b52019-10-23 18:48:22 +02002317 num_bytes = cache->length - cache->reserved -
David Sterbabf38be62019-10-23 18:48:11 +02002318 cache->pinned - cache->bytes_super - cache->used;
Josef Bacik26ce2092019-06-20 15:37:59 -04002319 sinfo->bytes_readonly -= num_bytes;
2320 list_del_init(&cache->ro_list);
2321 }
2322 spin_unlock(&cache->lock);
2323 spin_unlock(&sinfo->lock);
2324}
Josef Bacik77745c02019-06-20 15:38:00 -04002325
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002326static int update_block_group_item(struct btrfs_trans_handle *trans,
2327 struct btrfs_path *path,
2328 struct btrfs_block_group *cache)
Josef Bacik77745c02019-06-20 15:38:00 -04002329{
2330 struct btrfs_fs_info *fs_info = trans->fs_info;
2331 int ret;
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002332 struct btrfs_root *root = fs_info->extent_root;
Josef Bacik77745c02019-06-20 15:38:00 -04002333 unsigned long bi;
2334 struct extent_buffer *leaf;
David Sterbabf38be62019-10-23 18:48:11 +02002335 struct btrfs_block_group_item bgi;
David Sterbab3470b52019-10-23 18:48:22 +02002336 struct btrfs_key key;
Josef Bacik77745c02019-06-20 15:38:00 -04002337
David Sterbab3470b52019-10-23 18:48:22 +02002338 key.objectid = cache->start;
2339 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2340 key.offset = cache->length;
2341
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002342 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
Josef Bacik77745c02019-06-20 15:38:00 -04002343 if (ret) {
2344 if (ret > 0)
2345 ret = -ENOENT;
2346 goto fail;
2347 }
2348
2349 leaf = path->nodes[0];
2350 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
David Sterbade0dc452019-10-23 18:48:18 +02002351 btrfs_set_stack_block_group_used(&bgi, cache->used);
2352 btrfs_set_stack_block_group_chunk_objectid(&bgi,
David Sterba3d976382019-10-23 18:48:15 +02002353 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
David Sterbade0dc452019-10-23 18:48:18 +02002354 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
David Sterbabf38be62019-10-23 18:48:11 +02002355 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
Josef Bacik77745c02019-06-20 15:38:00 -04002356 btrfs_mark_buffer_dirty(leaf);
2357fail:
2358 btrfs_release_path(path);
2359 return ret;
2360
2361}
2362
David Sterba32da53862019-10-29 19:20:18 +01002363static int cache_save_setup(struct btrfs_block_group *block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002364 struct btrfs_trans_handle *trans,
2365 struct btrfs_path *path)
2366{
2367 struct btrfs_fs_info *fs_info = block_group->fs_info;
2368 struct btrfs_root *root = fs_info->tree_root;
2369 struct inode *inode = NULL;
2370 struct extent_changeset *data_reserved = NULL;
2371 u64 alloc_hint = 0;
2372 int dcs = BTRFS_DC_ERROR;
2373 u64 num_pages = 0;
2374 int retries = 0;
2375 int ret = 0;
2376
2377 /*
2378 * If this block group is smaller than 100 megs don't bother caching the
2379 * block group.
2380 */
David Sterbab3470b52019-10-23 18:48:22 +02002381 if (block_group->length < (100 * SZ_1M)) {
Josef Bacik77745c02019-06-20 15:38:00 -04002382 spin_lock(&block_group->lock);
2383 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2384 spin_unlock(&block_group->lock);
2385 return 0;
2386 }
2387
David Sterbabf31f872020-02-05 17:34:34 +01002388 if (TRANS_ABORTED(trans))
Josef Bacik77745c02019-06-20 15:38:00 -04002389 return 0;
2390again:
2391 inode = lookup_free_space_inode(block_group, path);
2392 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2393 ret = PTR_ERR(inode);
2394 btrfs_release_path(path);
2395 goto out;
2396 }
2397
2398 if (IS_ERR(inode)) {
2399 BUG_ON(retries);
2400 retries++;
2401
2402 if (block_group->ro)
2403 goto out_free;
2404
2405 ret = create_free_space_inode(trans, block_group, path);
2406 if (ret)
2407 goto out_free;
2408 goto again;
2409 }
2410
2411 /*
2412 * We want to set the generation to 0, that way if anything goes wrong
2413 * from here on out we know not to trust this cache when we load up next
2414 * time.
2415 */
2416 BTRFS_I(inode)->generation = 0;
Nikolay Borisov9a56fcd2020-11-02 16:48:59 +02002417 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
Josef Bacik77745c02019-06-20 15:38:00 -04002418 if (ret) {
2419 /*
2420 * So theoretically we could recover from this, simply set the
2421 * super cache generation to 0 so we know to invalidate the
2422 * cache, but then we'd have to keep track of the block groups
2423 * that fail this way so we know we _have_ to reset this cache
2424 * before the next commit or risk reading stale cache. So to
2425 * limit our exposure to horrible edge cases lets just abort the
2426 * transaction, this only happens in really bad situations
2427 * anyway.
2428 */
2429 btrfs_abort_transaction(trans, ret);
2430 goto out_put;
2431 }
2432 WARN_ON(ret);
2433
2434 /* We've already setup this transaction, go ahead and exit */
2435 if (block_group->cache_generation == trans->transid &&
2436 i_size_read(inode)) {
2437 dcs = BTRFS_DC_SETUP;
2438 goto out_put;
2439 }
2440
2441 if (i_size_read(inode) > 0) {
2442 ret = btrfs_check_trunc_cache_free_space(fs_info,
2443 &fs_info->global_block_rsv);
2444 if (ret)
2445 goto out_put;
2446
2447 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2448 if (ret)
2449 goto out_put;
2450 }
2451
2452 spin_lock(&block_group->lock);
2453 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2454 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2455 /*
2456 * don't bother trying to write stuff out _if_
2457 * a) we're not cached,
2458 * b) we're with nospace_cache mount option,
2459 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2460 */
2461 dcs = BTRFS_DC_WRITTEN;
2462 spin_unlock(&block_group->lock);
2463 goto out_put;
2464 }
2465 spin_unlock(&block_group->lock);
2466
2467 /*
2468 * We hit an ENOSPC when setting up the cache in this transaction, just
2469 * skip doing the setup, we've already cleared the cache so we're safe.
2470 */
2471 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2472 ret = -ENOSPC;
2473 goto out_put;
2474 }
2475
2476 /*
2477 * Try to preallocate enough space based on how big the block group is.
2478 * Keep in mind this has to include any pinned space which could end up
2479 * taking up quite a bit since it's not folded into the other space
2480 * cache.
2481 */
David Sterbab3470b52019-10-23 18:48:22 +02002482 num_pages = div_u64(block_group->length, SZ_256M);
Josef Bacik77745c02019-06-20 15:38:00 -04002483 if (!num_pages)
2484 num_pages = 1;
2485
2486 num_pages *= 16;
2487 num_pages *= PAGE_SIZE;
2488
Nikolay Borisov36ea6f32020-06-03 08:55:41 +03002489 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
2490 num_pages);
Josef Bacik77745c02019-06-20 15:38:00 -04002491 if (ret)
2492 goto out_put;
2493
2494 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2495 num_pages, num_pages,
2496 &alloc_hint);
2497 /*
2498 * Our cache requires contiguous chunks so that we don't modify a bunch
2499 * of metadata or split extents when writing the cache out, which means
2500 * we can enospc if we are heavily fragmented in addition to just normal
2501 * out of space conditions. So if we hit this just skip setting up any
2502 * other block groups for this transaction, maybe we'll unpin enough
2503 * space the next time around.
2504 */
2505 if (!ret)
2506 dcs = BTRFS_DC_SETUP;
2507 else if (ret == -ENOSPC)
2508 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2509
2510out_put:
2511 iput(inode);
2512out_free:
2513 btrfs_release_path(path);
2514out:
2515 spin_lock(&block_group->lock);
2516 if (!ret && dcs == BTRFS_DC_SETUP)
2517 block_group->cache_generation = trans->transid;
2518 block_group->disk_cache_state = dcs;
2519 spin_unlock(&block_group->lock);
2520
2521 extent_changeset_free(data_reserved);
2522 return ret;
2523}
2524
2525int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2526{
2527 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002528 struct btrfs_block_group *cache, *tmp;
Josef Bacik77745c02019-06-20 15:38:00 -04002529 struct btrfs_transaction *cur_trans = trans->transaction;
2530 struct btrfs_path *path;
2531
2532 if (list_empty(&cur_trans->dirty_bgs) ||
2533 !btrfs_test_opt(fs_info, SPACE_CACHE))
2534 return 0;
2535
2536 path = btrfs_alloc_path();
2537 if (!path)
2538 return -ENOMEM;
2539
2540 /* Could add new block groups, use _safe just in case */
2541 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2542 dirty_list) {
2543 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2544 cache_save_setup(cache, trans, path);
2545 }
2546
2547 btrfs_free_path(path);
2548 return 0;
2549}
2550
2551/*
2552 * Transaction commit does final block group cache writeback during a critical
2553 * section where nothing is allowed to change the FS. This is required in
2554 * order for the cache to actually match the block group, but can introduce a
2555 * lot of latency into the commit.
2556 *
2557 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2558 * There's a chance we'll have to redo some of it if the block group changes
2559 * again during the commit, but it greatly reduces the commit latency by
2560 * getting rid of the easy block groups while we're still allowing others to
2561 * join the commit.
2562 */
2563int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2564{
2565 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002566 struct btrfs_block_group *cache;
Josef Bacik77745c02019-06-20 15:38:00 -04002567 struct btrfs_transaction *cur_trans = trans->transaction;
2568 int ret = 0;
2569 int should_put;
2570 struct btrfs_path *path = NULL;
2571 LIST_HEAD(dirty);
2572 struct list_head *io = &cur_trans->io_bgs;
2573 int num_started = 0;
2574 int loops = 0;
2575
2576 spin_lock(&cur_trans->dirty_bgs_lock);
2577 if (list_empty(&cur_trans->dirty_bgs)) {
2578 spin_unlock(&cur_trans->dirty_bgs_lock);
2579 return 0;
2580 }
2581 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2582 spin_unlock(&cur_trans->dirty_bgs_lock);
2583
2584again:
2585 /* Make sure all the block groups on our dirty list actually exist */
2586 btrfs_create_pending_block_groups(trans);
2587
2588 if (!path) {
2589 path = btrfs_alloc_path();
2590 if (!path)
2591 return -ENOMEM;
2592 }
2593
2594 /*
2595 * cache_write_mutex is here only to save us from balance or automatic
2596 * removal of empty block groups deleting this block group while we are
2597 * writing out the cache
2598 */
2599 mutex_lock(&trans->transaction->cache_write_mutex);
2600 while (!list_empty(&dirty)) {
2601 bool drop_reserve = true;
2602
David Sterba32da53862019-10-29 19:20:18 +01002603 cache = list_first_entry(&dirty, struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002604 dirty_list);
2605 /*
2606 * This can happen if something re-dirties a block group that
2607 * is already under IO. Just wait for it to finish and then do
2608 * it all again
2609 */
2610 if (!list_empty(&cache->io_list)) {
2611 list_del_init(&cache->io_list);
2612 btrfs_wait_cache_io(trans, cache, path);
2613 btrfs_put_block_group(cache);
2614 }
2615
2616
2617 /*
2618 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2619 * it should update the cache_state. Don't delete until after
2620 * we wait.
2621 *
2622 * Since we're not running in the commit critical section
2623 * we need the dirty_bgs_lock to protect from update_block_group
2624 */
2625 spin_lock(&cur_trans->dirty_bgs_lock);
2626 list_del_init(&cache->dirty_list);
2627 spin_unlock(&cur_trans->dirty_bgs_lock);
2628
2629 should_put = 1;
2630
2631 cache_save_setup(cache, trans, path);
2632
2633 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2634 cache->io_ctl.inode = NULL;
2635 ret = btrfs_write_out_cache(trans, cache, path);
2636 if (ret == 0 && cache->io_ctl.inode) {
2637 num_started++;
2638 should_put = 0;
2639
2640 /*
2641 * The cache_write_mutex is protecting the
2642 * io_list, also refer to the definition of
2643 * btrfs_transaction::io_bgs for more details
2644 */
2645 list_add_tail(&cache->io_list, io);
2646 } else {
2647 /*
2648 * If we failed to write the cache, the
2649 * generation will be bad and life goes on
2650 */
2651 ret = 0;
2652 }
2653 }
2654 if (!ret) {
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002655 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002656 /*
2657 * Our block group might still be attached to the list
2658 * of new block groups in the transaction handle of some
2659 * other task (struct btrfs_trans_handle->new_bgs). This
2660 * means its block group item isn't yet in the extent
2661 * tree. If this happens ignore the error, as we will
2662 * try again later in the critical section of the
2663 * transaction commit.
2664 */
2665 if (ret == -ENOENT) {
2666 ret = 0;
2667 spin_lock(&cur_trans->dirty_bgs_lock);
2668 if (list_empty(&cache->dirty_list)) {
2669 list_add_tail(&cache->dirty_list,
2670 &cur_trans->dirty_bgs);
2671 btrfs_get_block_group(cache);
2672 drop_reserve = false;
2673 }
2674 spin_unlock(&cur_trans->dirty_bgs_lock);
2675 } else if (ret) {
2676 btrfs_abort_transaction(trans, ret);
2677 }
2678 }
2679
2680 /* If it's not on the io list, we need to put the block group */
2681 if (should_put)
2682 btrfs_put_block_group(cache);
2683 if (drop_reserve)
2684 btrfs_delayed_refs_rsv_release(fs_info, 1);
2685
2686 if (ret)
2687 break;
2688
2689 /*
2690 * Avoid blocking other tasks for too long. It might even save
2691 * us from writing caches for block groups that are going to be
2692 * removed.
2693 */
2694 mutex_unlock(&trans->transaction->cache_write_mutex);
2695 mutex_lock(&trans->transaction->cache_write_mutex);
2696 }
2697 mutex_unlock(&trans->transaction->cache_write_mutex);
2698
2699 /*
2700 * Go through delayed refs for all the stuff we've just kicked off
2701 * and then loop back (just once)
2702 */
2703 ret = btrfs_run_delayed_refs(trans, 0);
2704 if (!ret && loops == 0) {
2705 loops++;
2706 spin_lock(&cur_trans->dirty_bgs_lock);
2707 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2708 /*
2709 * dirty_bgs_lock protects us from concurrent block group
2710 * deletes too (not just cache_write_mutex).
2711 */
2712 if (!list_empty(&dirty)) {
2713 spin_unlock(&cur_trans->dirty_bgs_lock);
2714 goto again;
2715 }
2716 spin_unlock(&cur_trans->dirty_bgs_lock);
2717 } else if (ret < 0) {
2718 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2719 }
2720
2721 btrfs_free_path(path);
2722 return ret;
2723}
2724
2725int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2726{
2727 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002728 struct btrfs_block_group *cache;
Josef Bacik77745c02019-06-20 15:38:00 -04002729 struct btrfs_transaction *cur_trans = trans->transaction;
2730 int ret = 0;
2731 int should_put;
2732 struct btrfs_path *path;
2733 struct list_head *io = &cur_trans->io_bgs;
2734 int num_started = 0;
2735
2736 path = btrfs_alloc_path();
2737 if (!path)
2738 return -ENOMEM;
2739
2740 /*
2741 * Even though we are in the critical section of the transaction commit,
2742 * we can still have concurrent tasks adding elements to this
2743 * transaction's list of dirty block groups. These tasks correspond to
2744 * endio free space workers started when writeback finishes for a
2745 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2746 * allocate new block groups as a result of COWing nodes of the root
2747 * tree when updating the free space inode. The writeback for the space
2748 * caches is triggered by an earlier call to
2749 * btrfs_start_dirty_block_groups() and iterations of the following
2750 * loop.
2751 * Also we want to do the cache_save_setup first and then run the
2752 * delayed refs to make sure we have the best chance at doing this all
2753 * in one shot.
2754 */
2755 spin_lock(&cur_trans->dirty_bgs_lock);
2756 while (!list_empty(&cur_trans->dirty_bgs)) {
2757 cache = list_first_entry(&cur_trans->dirty_bgs,
David Sterba32da53862019-10-29 19:20:18 +01002758 struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002759 dirty_list);
2760
2761 /*
2762 * This can happen if cache_save_setup re-dirties a block group
2763 * that is already under IO. Just wait for it to finish and
2764 * then do it all again
2765 */
2766 if (!list_empty(&cache->io_list)) {
2767 spin_unlock(&cur_trans->dirty_bgs_lock);
2768 list_del_init(&cache->io_list);
2769 btrfs_wait_cache_io(trans, cache, path);
2770 btrfs_put_block_group(cache);
2771 spin_lock(&cur_trans->dirty_bgs_lock);
2772 }
2773
2774 /*
2775 * Don't remove from the dirty list until after we've waited on
2776 * any pending IO
2777 */
2778 list_del_init(&cache->dirty_list);
2779 spin_unlock(&cur_trans->dirty_bgs_lock);
2780 should_put = 1;
2781
2782 cache_save_setup(cache, trans, path);
2783
2784 if (!ret)
2785 ret = btrfs_run_delayed_refs(trans,
2786 (unsigned long) -1);
2787
2788 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2789 cache->io_ctl.inode = NULL;
2790 ret = btrfs_write_out_cache(trans, cache, path);
2791 if (ret == 0 && cache->io_ctl.inode) {
2792 num_started++;
2793 should_put = 0;
2794 list_add_tail(&cache->io_list, io);
2795 } else {
2796 /*
2797 * If we failed to write the cache, the
2798 * generation will be bad and life goes on
2799 */
2800 ret = 0;
2801 }
2802 }
2803 if (!ret) {
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002804 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002805 /*
2806 * One of the free space endio workers might have
2807 * created a new block group while updating a free space
2808 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2809 * and hasn't released its transaction handle yet, in
2810 * which case the new block group is still attached to
2811 * its transaction handle and its creation has not
2812 * finished yet (no block group item in the extent tree
2813 * yet, etc). If this is the case, wait for all free
2814 * space endio workers to finish and retry. This is a
Randy Dunlap260db432020-08-04 19:48:34 -07002815 * very rare case so no need for a more efficient and
Josef Bacik77745c02019-06-20 15:38:00 -04002816 * complex approach.
2817 */
2818 if (ret == -ENOENT) {
2819 wait_event(cur_trans->writer_wait,
2820 atomic_read(&cur_trans->num_writers) == 1);
Qu Wenruo3be4d8e2020-05-05 07:58:23 +08002821 ret = update_block_group_item(trans, path, cache);
Josef Bacik77745c02019-06-20 15:38:00 -04002822 }
2823 if (ret)
2824 btrfs_abort_transaction(trans, ret);
2825 }
2826
2827 /* If its not on the io list, we need to put the block group */
2828 if (should_put)
2829 btrfs_put_block_group(cache);
2830 btrfs_delayed_refs_rsv_release(fs_info, 1);
2831 spin_lock(&cur_trans->dirty_bgs_lock);
2832 }
2833 spin_unlock(&cur_trans->dirty_bgs_lock);
2834
2835 /*
2836 * Refer to the definition of io_bgs member for details why it's safe
2837 * to use it without any locking
2838 */
2839 while (!list_empty(io)) {
David Sterba32da53862019-10-29 19:20:18 +01002840 cache = list_first_entry(io, struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002841 io_list);
2842 list_del_init(&cache->io_list);
2843 btrfs_wait_cache_io(trans, cache, path);
2844 btrfs_put_block_group(cache);
2845 }
2846
2847 btrfs_free_path(path);
2848 return ret;
2849}
Josef Bacik606d1bf2019-06-20 15:38:02 -04002850
2851int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2852 u64 bytenr, u64 num_bytes, int alloc)
2853{
2854 struct btrfs_fs_info *info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002855 struct btrfs_block_group *cache = NULL;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002856 u64 total = num_bytes;
2857 u64 old_val;
2858 u64 byte_in_group;
2859 int factor;
2860 int ret = 0;
2861
2862 /* Block accounting for super block */
2863 spin_lock(&info->delalloc_root_lock);
2864 old_val = btrfs_super_bytes_used(info->super_copy);
2865 if (alloc)
2866 old_val += num_bytes;
2867 else
2868 old_val -= num_bytes;
2869 btrfs_set_super_bytes_used(info->super_copy, old_val);
2870 spin_unlock(&info->delalloc_root_lock);
2871
2872 while (total) {
2873 cache = btrfs_lookup_block_group(info, bytenr);
2874 if (!cache) {
2875 ret = -ENOENT;
2876 break;
2877 }
2878 factor = btrfs_bg_type_to_factor(cache->flags);
2879
2880 /*
2881 * If this block group has free space cache written out, we
2882 * need to make sure to load it if we are removing space. This
2883 * is because we need the unpinning stage to actually add the
2884 * space back to the block group, otherwise we will leak space.
2885 */
David Sterba32da53862019-10-29 19:20:18 +01002886 if (!alloc && !btrfs_block_group_done(cache))
Josef Bacik606d1bf2019-06-20 15:38:02 -04002887 btrfs_cache_block_group(cache, 1);
2888
David Sterbab3470b52019-10-23 18:48:22 +02002889 byte_in_group = bytenr - cache->start;
2890 WARN_ON(byte_in_group > cache->length);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002891
2892 spin_lock(&cache->space_info->lock);
2893 spin_lock(&cache->lock);
2894
2895 if (btrfs_test_opt(info, SPACE_CACHE) &&
2896 cache->disk_cache_state < BTRFS_DC_CLEAR)
2897 cache->disk_cache_state = BTRFS_DC_CLEAR;
2898
David Sterbabf38be62019-10-23 18:48:11 +02002899 old_val = cache->used;
David Sterbab3470b52019-10-23 18:48:22 +02002900 num_bytes = min(total, cache->length - byte_in_group);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002901 if (alloc) {
2902 old_val += num_bytes;
David Sterbabf38be62019-10-23 18:48:11 +02002903 cache->used = old_val;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002904 cache->reserved -= num_bytes;
2905 cache->space_info->bytes_reserved -= num_bytes;
2906 cache->space_info->bytes_used += num_bytes;
2907 cache->space_info->disk_used += num_bytes * factor;
2908 spin_unlock(&cache->lock);
2909 spin_unlock(&cache->space_info->lock);
2910 } else {
2911 old_val -= num_bytes;
David Sterbabf38be62019-10-23 18:48:11 +02002912 cache->used = old_val;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002913 cache->pinned += num_bytes;
2914 btrfs_space_info_update_bytes_pinned(info,
2915 cache->space_info, num_bytes);
2916 cache->space_info->bytes_used -= num_bytes;
2917 cache->space_info->disk_used -= num_bytes * factor;
2918 spin_unlock(&cache->lock);
2919 spin_unlock(&cache->space_info->lock);
2920
Josef Bacik606d1bf2019-06-20 15:38:02 -04002921 percpu_counter_add_batch(
2922 &cache->space_info->total_bytes_pinned,
2923 num_bytes,
2924 BTRFS_TOTAL_BYTES_PINNED_BATCH);
Nikolay Borisovfe119a62020-01-20 16:09:18 +02002925 set_extent_dirty(&trans->transaction->pinned_extents,
Josef Bacik606d1bf2019-06-20 15:38:02 -04002926 bytenr, bytenr + num_bytes - 1,
2927 GFP_NOFS | __GFP_NOFAIL);
2928 }
2929
2930 spin_lock(&trans->transaction->dirty_bgs_lock);
2931 if (list_empty(&cache->dirty_list)) {
2932 list_add_tail(&cache->dirty_list,
2933 &trans->transaction->dirty_bgs);
2934 trans->delayed_ref_updates++;
2935 btrfs_get_block_group(cache);
2936 }
2937 spin_unlock(&trans->transaction->dirty_bgs_lock);
2938
2939 /*
2940 * No longer have used bytes in this block group, queue it for
2941 * deletion. We do this after adding the block group to the
2942 * dirty list to avoid races between cleaner kthread and space
2943 * cache writeout.
2944 */
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08002945 if (!alloc && old_val == 0) {
2946 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2947 btrfs_mark_bg_unused(cache);
2948 }
Josef Bacik606d1bf2019-06-20 15:38:02 -04002949
2950 btrfs_put_block_group(cache);
2951 total -= num_bytes;
2952 bytenr += num_bytes;
2953 }
2954
2955 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2956 btrfs_update_delayed_refs_rsv(trans);
2957 return ret;
2958}
2959
2960/**
2961 * btrfs_add_reserved_bytes - update the block_group and space info counters
2962 * @cache: The cache we are manipulating
2963 * @ram_bytes: The number of bytes of file content, and will be same to
2964 * @num_bytes except for the compress path.
2965 * @num_bytes: The number of bytes in question
2966 * @delalloc: The blocks are allocated for the delalloc write
2967 *
2968 * This is called by the allocator when it reserves space. If this is a
2969 * reservation and the block group has become read only we cannot make the
2970 * reservation and return -EAGAIN, otherwise this function always succeeds.
2971 */
David Sterba32da53862019-10-29 19:20:18 +01002972int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
Josef Bacik606d1bf2019-06-20 15:38:02 -04002973 u64 ram_bytes, u64 num_bytes, int delalloc)
2974{
2975 struct btrfs_space_info *space_info = cache->space_info;
2976 int ret = 0;
2977
2978 spin_lock(&space_info->lock);
2979 spin_lock(&cache->lock);
2980 if (cache->ro) {
2981 ret = -EAGAIN;
2982 } else {
2983 cache->reserved += num_bytes;
2984 space_info->bytes_reserved += num_bytes;
Josef Bacika43c3832019-08-22 15:10:56 -04002985 trace_btrfs_space_reservation(cache->fs_info, "space_info",
2986 space_info->flags, num_bytes, 1);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002987 btrfs_space_info_update_bytes_may_use(cache->fs_info,
2988 space_info, -ram_bytes);
2989 if (delalloc)
2990 cache->delalloc_bytes += num_bytes;
Josef Bacik99ffb432020-07-21 10:22:19 -04002991
2992 /*
2993 * Compression can use less space than we reserved, so wake
2994 * tickets if that happens
2995 */
2996 if (num_bytes < ram_bytes)
2997 btrfs_try_granting_tickets(cache->fs_info, space_info);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002998 }
2999 spin_unlock(&cache->lock);
3000 spin_unlock(&space_info->lock);
3001 return ret;
3002}
3003
3004/**
3005 * btrfs_free_reserved_bytes - update the block_group and space info counters
3006 * @cache: The cache we are manipulating
3007 * @num_bytes: The number of bytes in question
3008 * @delalloc: The blocks are allocated for the delalloc write
3009 *
3010 * This is called by somebody who is freeing space that was never actually used
3011 * on disk. For example if you reserve some space for a new leaf in transaction
3012 * A and before transaction A commits you free that leaf, you call this with
3013 * reserve set to 0 in order to clear the reservation.
3014 */
David Sterba32da53862019-10-29 19:20:18 +01003015void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
Josef Bacik606d1bf2019-06-20 15:38:02 -04003016 u64 num_bytes, int delalloc)
3017{
3018 struct btrfs_space_info *space_info = cache->space_info;
3019
3020 spin_lock(&space_info->lock);
3021 spin_lock(&cache->lock);
3022 if (cache->ro)
3023 space_info->bytes_readonly += num_bytes;
3024 cache->reserved -= num_bytes;
3025 space_info->bytes_reserved -= num_bytes;
3026 space_info->max_extent_size = 0;
3027
3028 if (delalloc)
3029 cache->delalloc_bytes -= num_bytes;
3030 spin_unlock(&cache->lock);
Josef Bacik33082342020-07-21 10:22:17 -04003031
3032 btrfs_try_granting_tickets(cache->fs_info, space_info);
Josef Bacik606d1bf2019-06-20 15:38:02 -04003033 spin_unlock(&space_info->lock);
3034}
Josef Bacik07730d82019-06-20 15:38:04 -04003035
3036static void force_metadata_allocation(struct btrfs_fs_info *info)
3037{
3038 struct list_head *head = &info->space_info;
3039 struct btrfs_space_info *found;
3040
Josef Bacik72804902020-09-01 17:40:37 -04003041 list_for_each_entry(found, head, list) {
Josef Bacik07730d82019-06-20 15:38:04 -04003042 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3043 found->force_alloc = CHUNK_ALLOC_FORCE;
3044 }
Josef Bacik07730d82019-06-20 15:38:04 -04003045}
3046
3047static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3048 struct btrfs_space_info *sinfo, int force)
3049{
3050 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3051 u64 thresh;
3052
3053 if (force == CHUNK_ALLOC_FORCE)
3054 return 1;
3055
3056 /*
3057 * in limited mode, we want to have some free space up to
3058 * about 1% of the FS size.
3059 */
3060 if (force == CHUNK_ALLOC_LIMITED) {
3061 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3062 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3063
3064 if (sinfo->total_bytes - bytes_used < thresh)
3065 return 1;
3066 }
3067
3068 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3069 return 0;
3070 return 1;
3071}
3072
3073int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3074{
3075 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3076
3077 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3078}
3079
3080/*
3081 * If force is CHUNK_ALLOC_FORCE:
3082 * - return 1 if it successfully allocates a chunk,
3083 * - return errors including -ENOSPC otherwise.
3084 * If force is NOT CHUNK_ALLOC_FORCE:
3085 * - return 0 if it doesn't need to allocate a new chunk,
3086 * - return 1 if it successfully allocates a chunk,
3087 * - return errors including -ENOSPC otherwise.
3088 */
3089int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3090 enum btrfs_chunk_alloc_enum force)
3091{
3092 struct btrfs_fs_info *fs_info = trans->fs_info;
3093 struct btrfs_space_info *space_info;
3094 bool wait_for_alloc = false;
3095 bool should_alloc = false;
3096 int ret = 0;
3097
3098 /* Don't re-enter if we're already allocating a chunk */
3099 if (trans->allocating_chunk)
3100 return -ENOSPC;
3101
3102 space_info = btrfs_find_space_info(fs_info, flags);
3103 ASSERT(space_info);
3104
3105 do {
3106 spin_lock(&space_info->lock);
3107 if (force < space_info->force_alloc)
3108 force = space_info->force_alloc;
3109 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3110 if (space_info->full) {
3111 /* No more free physical space */
3112 if (should_alloc)
3113 ret = -ENOSPC;
3114 else
3115 ret = 0;
3116 spin_unlock(&space_info->lock);
3117 return ret;
3118 } else if (!should_alloc) {
3119 spin_unlock(&space_info->lock);
3120 return 0;
3121 } else if (space_info->chunk_alloc) {
3122 /*
3123 * Someone is already allocating, so we need to block
3124 * until this someone is finished and then loop to
3125 * recheck if we should continue with our allocation
3126 * attempt.
3127 */
3128 wait_for_alloc = true;
3129 spin_unlock(&space_info->lock);
3130 mutex_lock(&fs_info->chunk_mutex);
3131 mutex_unlock(&fs_info->chunk_mutex);
3132 } else {
3133 /* Proceed with allocation */
3134 space_info->chunk_alloc = 1;
3135 wait_for_alloc = false;
3136 spin_unlock(&space_info->lock);
3137 }
3138
3139 cond_resched();
3140 } while (wait_for_alloc);
3141
3142 mutex_lock(&fs_info->chunk_mutex);
3143 trans->allocating_chunk = true;
3144
3145 /*
3146 * If we have mixed data/metadata chunks we want to make sure we keep
3147 * allocating mixed chunks instead of individual chunks.
3148 */
3149 if (btrfs_mixed_space_info(space_info))
3150 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3151
3152 /*
3153 * if we're doing a data chunk, go ahead and make sure that
3154 * we keep a reasonable number of metadata chunks allocated in the
3155 * FS as well.
3156 */
3157 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3158 fs_info->data_chunk_allocations++;
3159 if (!(fs_info->data_chunk_allocations %
3160 fs_info->metadata_ratio))
3161 force_metadata_allocation(fs_info);
3162 }
3163
3164 /*
3165 * Check if we have enough space in SYSTEM chunk because we may need
3166 * to update devices.
3167 */
3168 check_system_chunk(trans, flags);
3169
3170 ret = btrfs_alloc_chunk(trans, flags);
3171 trans->allocating_chunk = false;
3172
3173 spin_lock(&space_info->lock);
3174 if (ret < 0) {
3175 if (ret == -ENOSPC)
3176 space_info->full = 1;
3177 else
3178 goto out;
3179 } else {
3180 ret = 1;
3181 space_info->max_extent_size = 0;
3182 }
3183
3184 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3185out:
3186 space_info->chunk_alloc = 0;
3187 spin_unlock(&space_info->lock);
3188 mutex_unlock(&fs_info->chunk_mutex);
3189 /*
3190 * When we allocate a new chunk we reserve space in the chunk block
3191 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3192 * add new nodes/leafs to it if we end up needing to do it when
3193 * inserting the chunk item and updating device items as part of the
3194 * second phase of chunk allocation, performed by
3195 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3196 * large number of new block groups to create in our transaction
3197 * handle's new_bgs list to avoid exhausting the chunk block reserve
3198 * in extreme cases - like having a single transaction create many new
3199 * block groups when starting to write out the free space caches of all
3200 * the block groups that were made dirty during the lifetime of the
3201 * transaction.
3202 */
3203 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3204 btrfs_create_pending_block_groups(trans);
3205
3206 return ret;
3207}
3208
3209static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3210{
3211 u64 num_dev;
3212
3213 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3214 if (!num_dev)
3215 num_dev = fs_info->fs_devices->rw_devices;
3216
3217 return num_dev;
3218}
3219
3220/*
Marcos Paulo de Souzaa9143bd2019-10-07 21:50:38 -03003221 * Reserve space in the system space for allocating or removing a chunk
Josef Bacik07730d82019-06-20 15:38:04 -04003222 */
3223void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3224{
3225 struct btrfs_fs_info *fs_info = trans->fs_info;
3226 struct btrfs_space_info *info;
3227 u64 left;
3228 u64 thresh;
3229 int ret = 0;
3230 u64 num_devs;
3231
3232 /*
3233 * Needed because we can end up allocating a system chunk and for an
3234 * atomic and race free space reservation in the chunk block reserve.
3235 */
3236 lockdep_assert_held(&fs_info->chunk_mutex);
3237
3238 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3239 spin_lock(&info->lock);
3240 left = info->total_bytes - btrfs_space_info_used(info, true);
3241 spin_unlock(&info->lock);
3242
3243 num_devs = get_profile_num_devs(fs_info, type);
3244
3245 /* num_devs device items to update and 1 chunk item to add or remove */
Josef Bacik2bd36e72019-08-22 15:14:33 -04003246 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3247 btrfs_calc_insert_metadata_size(fs_info, 1);
Josef Bacik07730d82019-06-20 15:38:04 -04003248
3249 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3250 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3251 left, thresh, type);
3252 btrfs_dump_space_info(fs_info, info, 0, 0);
3253 }
3254
3255 if (left < thresh) {
3256 u64 flags = btrfs_system_alloc_profile(fs_info);
3257
3258 /*
3259 * Ignore failure to create system chunk. We might end up not
3260 * needing it, as we might not need to COW all nodes/leafs from
3261 * the paths we visit in the chunk tree (they were already COWed
3262 * or created in the current transaction for example).
3263 */
3264 ret = btrfs_alloc_chunk(trans, flags);
3265 }
3266
3267 if (!ret) {
3268 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3269 &fs_info->chunk_block_rsv,
3270 thresh, BTRFS_RESERVE_NO_FLUSH);
3271 if (!ret)
3272 trans->chunk_bytes_reserved += thresh;
3273 }
3274}
3275
Josef Bacik3e43c272019-06-20 15:38:06 -04003276void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3277{
David Sterba32da53862019-10-29 19:20:18 +01003278 struct btrfs_block_group *block_group;
Josef Bacik3e43c272019-06-20 15:38:06 -04003279 u64 last = 0;
3280
3281 while (1) {
3282 struct inode *inode;
3283
3284 block_group = btrfs_lookup_first_block_group(info, last);
3285 while (block_group) {
3286 btrfs_wait_block_group_cache_done(block_group);
3287 spin_lock(&block_group->lock);
3288 if (block_group->iref)
3289 break;
3290 spin_unlock(&block_group->lock);
3291 block_group = btrfs_next_block_group(block_group);
3292 }
3293 if (!block_group) {
3294 if (last == 0)
3295 break;
3296 last = 0;
3297 continue;
3298 }
3299
3300 inode = block_group->inode;
3301 block_group->iref = 0;
3302 block_group->inode = NULL;
3303 spin_unlock(&block_group->lock);
3304 ASSERT(block_group->io_ctl.inode == NULL);
3305 iput(inode);
David Sterbab3470b52019-10-23 18:48:22 +02003306 last = block_group->start + block_group->length;
Josef Bacik3e43c272019-06-20 15:38:06 -04003307 btrfs_put_block_group(block_group);
3308 }
3309}
3310
3311/*
3312 * Must be called only after stopping all workers, since we could have block
3313 * group caching kthreads running, and therefore they could race with us if we
3314 * freed the block groups before stopping them.
3315 */
3316int btrfs_free_block_groups(struct btrfs_fs_info *info)
3317{
David Sterba32da53862019-10-29 19:20:18 +01003318 struct btrfs_block_group *block_group;
Josef Bacik3e43c272019-06-20 15:38:06 -04003319 struct btrfs_space_info *space_info;
3320 struct btrfs_caching_control *caching_ctl;
3321 struct rb_node *n;
3322
Josef Bacikbbb86a32020-10-23 09:58:11 -04003323 spin_lock(&info->block_group_cache_lock);
Josef Bacik3e43c272019-06-20 15:38:06 -04003324 while (!list_empty(&info->caching_block_groups)) {
3325 caching_ctl = list_entry(info->caching_block_groups.next,
3326 struct btrfs_caching_control, list);
3327 list_del(&caching_ctl->list);
3328 btrfs_put_caching_control(caching_ctl);
3329 }
Josef Bacikbbb86a32020-10-23 09:58:11 -04003330 spin_unlock(&info->block_group_cache_lock);
Josef Bacik3e43c272019-06-20 15:38:06 -04003331
3332 spin_lock(&info->unused_bgs_lock);
3333 while (!list_empty(&info->unused_bgs)) {
3334 block_group = list_first_entry(&info->unused_bgs,
David Sterba32da53862019-10-29 19:20:18 +01003335 struct btrfs_block_group,
Josef Bacik3e43c272019-06-20 15:38:06 -04003336 bg_list);
3337 list_del_init(&block_group->bg_list);
3338 btrfs_put_block_group(block_group);
3339 }
3340 spin_unlock(&info->unused_bgs_lock);
3341
3342 spin_lock(&info->block_group_cache_lock);
3343 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
David Sterba32da53862019-10-29 19:20:18 +01003344 block_group = rb_entry(n, struct btrfs_block_group,
Josef Bacik3e43c272019-06-20 15:38:06 -04003345 cache_node);
3346 rb_erase(&block_group->cache_node,
3347 &info->block_group_cache_tree);
3348 RB_CLEAR_NODE(&block_group->cache_node);
3349 spin_unlock(&info->block_group_cache_lock);
3350
3351 down_write(&block_group->space_info->groups_sem);
3352 list_del(&block_group->list);
3353 up_write(&block_group->space_info->groups_sem);
3354
3355 /*
3356 * We haven't cached this block group, which means we could
3357 * possibly have excluded extents on this block group.
3358 */
3359 if (block_group->cached == BTRFS_CACHE_NO ||
3360 block_group->cached == BTRFS_CACHE_ERROR)
3361 btrfs_free_excluded_extents(block_group);
3362
3363 btrfs_remove_free_space_cache(block_group);
3364 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3365 ASSERT(list_empty(&block_group->dirty_list));
3366 ASSERT(list_empty(&block_group->io_list));
3367 ASSERT(list_empty(&block_group->bg_list));
Josef Bacik48aaeeb2020-07-06 09:14:11 -04003368 ASSERT(refcount_read(&block_group->refs) == 1);
Josef Bacik3e43c272019-06-20 15:38:06 -04003369 btrfs_put_block_group(block_group);
3370
3371 spin_lock(&info->block_group_cache_lock);
3372 }
3373 spin_unlock(&info->block_group_cache_lock);
3374
Josef Bacik3e43c272019-06-20 15:38:06 -04003375 btrfs_release_global_block_rsv(info);
3376
3377 while (!list_empty(&info->space_info)) {
3378 space_info = list_entry(info->space_info.next,
3379 struct btrfs_space_info,
3380 list);
3381
3382 /*
3383 * Do not hide this behind enospc_debug, this is actually
3384 * important and indicates a real bug if this happens.
3385 */
3386 if (WARN_ON(space_info->bytes_pinned > 0 ||
3387 space_info->bytes_reserved > 0 ||
3388 space_info->bytes_may_use > 0))
3389 btrfs_dump_space_info(info, space_info, 0, 0);
Filipe Mananad611add2020-04-07 11:38:49 +01003390 WARN_ON(space_info->reclaim_size > 0);
Josef Bacik3e43c272019-06-20 15:38:06 -04003391 list_del(&space_info->list);
3392 btrfs_sysfs_remove_space_info(space_info);
3393 }
3394 return 0;
3395}
Filipe Manana684b7522020-05-08 11:01:59 +01003396
3397void btrfs_freeze_block_group(struct btrfs_block_group *cache)
3398{
3399 atomic_inc(&cache->frozen);
3400}
3401
3402void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
3403{
3404 struct btrfs_fs_info *fs_info = block_group->fs_info;
3405 struct extent_map_tree *em_tree;
3406 struct extent_map *em;
3407 bool cleanup;
3408
3409 spin_lock(&block_group->lock);
3410 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3411 block_group->removed);
3412 spin_unlock(&block_group->lock);
3413
3414 if (cleanup) {
Filipe Manana684b7522020-05-08 11:01:59 +01003415 em_tree = &fs_info->mapping_tree;
3416 write_lock(&em_tree->lock);
3417 em = lookup_extent_mapping(em_tree, block_group->start,
3418 1);
3419 BUG_ON(!em); /* logic error, can't happen */
3420 remove_extent_mapping(em_tree, em);
3421 write_unlock(&em_tree->lock);
Filipe Manana684b7522020-05-08 11:01:59 +01003422
3423 /* once for us and once for the tree */
3424 free_extent_map(em);
3425 free_extent_map(em);
3426
3427 /*
3428 * We may have left one free space entry and other possible
3429 * tasks trimming this block group have left 1 entry each one.
3430 * Free them if any.
3431 */
3432 __btrfs_remove_free_space_cache(block_group->free_space_ctl);
3433 }
3434}