]> git.ipfire.org Git - thirdparty/linux.git/blame - fs/btrfs/block-group.c
btrfs: don't rely on unchanging ->bi_bdev for zone append remaps
[thirdparty/linux.git] / fs / btrfs / block-group.c
CommitLineData
2e405ad8
JB
1// SPDX-License-Identifier: GPL-2.0
2
52bb7a21 3#include <linux/sizes.h>
2ca0ec77 4#include <linux/list_sort.h>
784352fe 5#include "misc.h"
2e405ad8
JB
6#include "ctree.h"
7#include "block-group.h"
3eeb3226 8#include "space-info.h"
9f21246d
JB
9#include "disk-io.h"
10#include "free-space-cache.h"
11#include "free-space-tree.h"
e3e0520b
JB
12#include "volumes.h"
13#include "transaction.h"
14#include "ref-verify.h"
4358d963
JB
15#include "sysfs.h"
16#include "tree-log.h"
77745c05 17#include "delalloc-space.h"
b0643e59 18#include "discard.h"
96a14336 19#include "raid56.h"
08e11a3d 20#include "zoned.h"
c7f13d42 21#include "fs.h"
07e81dc9 22#include "accessors.h"
a0231804 23#include "extent-tree.h"
2e405ad8 24
06d61cb1
JB
25#ifdef CONFIG_BTRFS_DEBUG
26int btrfs_should_fragment_free_space(struct btrfs_block_group *block_group)
27{
28 struct btrfs_fs_info *fs_info = block_group->fs_info;
29
30 return (btrfs_test_opt(fs_info, FRAGMENT_METADATA) &&
31 block_group->flags & BTRFS_BLOCK_GROUP_METADATA) ||
32 (btrfs_test_opt(fs_info, FRAGMENT_DATA) &&
33 block_group->flags & BTRFS_BLOCK_GROUP_DATA);
34}
35#endif
36
878d7b67
JB
37/*
38 * Return target flags in extended format or 0 if restripe for this chunk_type
39 * is not in progress
40 *
41 * Should be called with balance_lock held
42 */
e11c0406 43static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
878d7b67
JB
44{
45 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
46 u64 target = 0;
47
48 if (!bctl)
49 return 0;
50
51 if (flags & BTRFS_BLOCK_GROUP_DATA &&
52 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
53 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
54 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
55 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
56 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
57 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
58 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
59 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
60 }
61
62 return target;
63}
64
65/*
66 * @flags: available profiles in extended format (see ctree.h)
67 *
68 * Return reduced profile in chunk format. If profile changing is in progress
69 * (either running or paused) picks the target profile (if it's already
70 * available), otherwise falls back to plain reducing.
71 */
72static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
73{
74 u64 num_devices = fs_info->fs_devices->rw_devices;
75 u64 target;
76 u64 raid_type;
77 u64 allowed = 0;
78
79 /*
80 * See if restripe for this chunk_type is in progress, if so try to
81 * reduce to the target profile
82 */
83 spin_lock(&fs_info->balance_lock);
e11c0406 84 target = get_restripe_target(fs_info, flags);
878d7b67 85 if (target) {
162e0a16
JB
86 spin_unlock(&fs_info->balance_lock);
87 return extended_to_chunk(target);
878d7b67
JB
88 }
89 spin_unlock(&fs_info->balance_lock);
90
91 /* First, mask out the RAID levels which aren't possible */
92 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
93 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
94 allowed |= btrfs_raid_array[raid_type].bg_flag;
95 }
96 allowed &= flags;
97
98 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
99 allowed = BTRFS_BLOCK_GROUP_RAID6;
100 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
101 allowed = BTRFS_BLOCK_GROUP_RAID5;
102 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
103 allowed = BTRFS_BLOCK_GROUP_RAID10;
104 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
105 allowed = BTRFS_BLOCK_GROUP_RAID1;
106 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
107 allowed = BTRFS_BLOCK_GROUP_RAID0;
108
109 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
110
111 return extended_to_chunk(flags | allowed);
112}
113
ef0a82da 114u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
878d7b67
JB
115{
116 unsigned seq;
117 u64 flags;
118
119 do {
120 flags = orig_flags;
121 seq = read_seqbegin(&fs_info->profiles_lock);
122
123 if (flags & BTRFS_BLOCK_GROUP_DATA)
124 flags |= fs_info->avail_data_alloc_bits;
125 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
126 flags |= fs_info->avail_system_alloc_bits;
127 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
128 flags |= fs_info->avail_metadata_alloc_bits;
129 } while (read_seqretry(&fs_info->profiles_lock, seq));
130
131 return btrfs_reduce_alloc_profile(fs_info, flags);
132}
133
32da5386 134void btrfs_get_block_group(struct btrfs_block_group *cache)
3cad1284 135{
48aaeebe 136 refcount_inc(&cache->refs);
3cad1284
JB
137}
138
32da5386 139void btrfs_put_block_group(struct btrfs_block_group *cache)
3cad1284 140{
48aaeebe 141 if (refcount_dec_and_test(&cache->refs)) {
3cad1284 142 WARN_ON(cache->pinned > 0);
40cdc509
FM
143 /*
144 * If there was a failure to cleanup a log tree, very likely due
145 * to an IO failure on a writeback attempt of one or more of its
146 * extent buffers, we could not do proper (and cheap) unaccounting
147 * of their reserved space, so don't warn on reserved > 0 in that
148 * case.
149 */
150 if (!(cache->flags & BTRFS_BLOCK_GROUP_METADATA) ||
151 !BTRFS_FS_LOG_CLEANUP_ERROR(cache->fs_info))
152 WARN_ON(cache->reserved > 0);
3cad1284 153
b0643e59
DZ
154 /*
155 * A block_group shouldn't be on the discard_list anymore.
156 * Remove the block_group from the discard_list to prevent us
157 * from causing a panic due to NULL pointer dereference.
158 */
159 if (WARN_ON(!list_empty(&cache->discard_list)))
160 btrfs_discard_cancel_work(&cache->fs_info->discard_ctl,
161 cache);
162
3cad1284
JB
163 /*
164 * If not empty, someone is still holding mutex of
165 * full_stripe_lock, which can only be released by caller.
166 * And it will definitely cause use-after-free when caller
167 * tries to release full stripe lock.
168 *
169 * No better way to resolve, but only to warn.
170 */
171 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
172 kfree(cache->free_space_ctl);
dafc340d 173 kfree(cache->physical_map);
3cad1284
JB
174 kfree(cache);
175 }
176}
177
4358d963
JB
178/*
179 * This adds the block group to the fs_info rb tree for the block group cache
180 */
181static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
32da5386 182 struct btrfs_block_group *block_group)
4358d963
JB
183{
184 struct rb_node **p;
185 struct rb_node *parent = NULL;
32da5386 186 struct btrfs_block_group *cache;
08dddb29 187 bool leftmost = true;
4358d963 188
9afc6649
QW
189 ASSERT(block_group->length != 0);
190
16b0c258 191 write_lock(&info->block_group_cache_lock);
08dddb29 192 p = &info->block_group_cache_tree.rb_root.rb_node;
4358d963
JB
193
194 while (*p) {
195 parent = *p;
32da5386 196 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
b3470b5d 197 if (block_group->start < cache->start) {
4358d963 198 p = &(*p)->rb_left;
b3470b5d 199 } else if (block_group->start > cache->start) {
4358d963 200 p = &(*p)->rb_right;
08dddb29 201 leftmost = false;
4358d963 202 } else {
16b0c258 203 write_unlock(&info->block_group_cache_lock);
4358d963
JB
204 return -EEXIST;
205 }
206 }
207
208 rb_link_node(&block_group->cache_node, parent, p);
08dddb29
FM
209 rb_insert_color_cached(&block_group->cache_node,
210 &info->block_group_cache_tree, leftmost);
4358d963 211
16b0c258 212 write_unlock(&info->block_group_cache_lock);
4358d963
JB
213
214 return 0;
215}
216
2e405ad8
JB
217/*
218 * This will return the block group at or after bytenr if contains is 0, else
219 * it will return the block group that contains the bytenr
220 */
32da5386 221static struct btrfs_block_group *block_group_cache_tree_search(
2e405ad8
JB
222 struct btrfs_fs_info *info, u64 bytenr, int contains)
223{
32da5386 224 struct btrfs_block_group *cache, *ret = NULL;
2e405ad8
JB
225 struct rb_node *n;
226 u64 end, start;
227
16b0c258 228 read_lock(&info->block_group_cache_lock);
08dddb29 229 n = info->block_group_cache_tree.rb_root.rb_node;
2e405ad8
JB
230
231 while (n) {
32da5386 232 cache = rb_entry(n, struct btrfs_block_group, cache_node);
b3470b5d
DS
233 end = cache->start + cache->length - 1;
234 start = cache->start;
2e405ad8
JB
235
236 if (bytenr < start) {
b3470b5d 237 if (!contains && (!ret || start < ret->start))
2e405ad8
JB
238 ret = cache;
239 n = n->rb_left;
240 } else if (bytenr > start) {
241 if (contains && bytenr <= end) {
242 ret = cache;
243 break;
244 }
245 n = n->rb_right;
246 } else {
247 ret = cache;
248 break;
249 }
250 }
08dddb29 251 if (ret)
2e405ad8 252 btrfs_get_block_group(ret);
16b0c258 253 read_unlock(&info->block_group_cache_lock);
2e405ad8
JB
254
255 return ret;
256}
257
258/*
259 * Return the block group that starts at or after bytenr
260 */
32da5386 261struct btrfs_block_group *btrfs_lookup_first_block_group(
2e405ad8
JB
262 struct btrfs_fs_info *info, u64 bytenr)
263{
264 return block_group_cache_tree_search(info, bytenr, 0);
265}
266
267/*
268 * Return the block group that contains the given bytenr
269 */
32da5386 270struct btrfs_block_group *btrfs_lookup_block_group(
2e405ad8
JB
271 struct btrfs_fs_info *info, u64 bytenr)
272{
273 return block_group_cache_tree_search(info, bytenr, 1);
274}
275
32da5386
DS
276struct btrfs_block_group *btrfs_next_block_group(
277 struct btrfs_block_group *cache)
2e405ad8
JB
278{
279 struct btrfs_fs_info *fs_info = cache->fs_info;
280 struct rb_node *node;
281
16b0c258 282 read_lock(&fs_info->block_group_cache_lock);
2e405ad8
JB
283
284 /* If our block group was removed, we need a full search. */
285 if (RB_EMPTY_NODE(&cache->cache_node)) {
b3470b5d 286 const u64 next_bytenr = cache->start + cache->length;
2e405ad8 287
16b0c258 288 read_unlock(&fs_info->block_group_cache_lock);
2e405ad8 289 btrfs_put_block_group(cache);
8b01f931 290 return btrfs_lookup_first_block_group(fs_info, next_bytenr);
2e405ad8
JB
291 }
292 node = rb_next(&cache->cache_node);
293 btrfs_put_block_group(cache);
294 if (node) {
32da5386 295 cache = rb_entry(node, struct btrfs_block_group, cache_node);
2e405ad8
JB
296 btrfs_get_block_group(cache);
297 } else
298 cache = NULL;
16b0c258 299 read_unlock(&fs_info->block_group_cache_lock);
2e405ad8
JB
300 return cache;
301}
3eeb3226 302
43dd529a 303/*
2306e83e
FM
304 * Check if we can do a NOCOW write for a given extent.
305 *
306 * @fs_info: The filesystem information object.
307 * @bytenr: Logical start address of the extent.
308 *
309 * Check if we can do a NOCOW write for the given extent, and increments the
310 * number of NOCOW writers in the block group that contains the extent, as long
311 * as the block group exists and it's currently not in read-only mode.
312 *
313 * Returns: A non-NULL block group pointer if we can do a NOCOW write, the caller
314 * is responsible for calling btrfs_dec_nocow_writers() later.
315 *
316 * Or NULL if we can not do a NOCOW write
317 */
318struct btrfs_block_group *btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info,
319 u64 bytenr)
3eeb3226 320{
32da5386 321 struct btrfs_block_group *bg;
2306e83e 322 bool can_nocow = true;
3eeb3226
JB
323
324 bg = btrfs_lookup_block_group(fs_info, bytenr);
325 if (!bg)
2306e83e 326 return NULL;
3eeb3226
JB
327
328 spin_lock(&bg->lock);
329 if (bg->ro)
2306e83e 330 can_nocow = false;
3eeb3226
JB
331 else
332 atomic_inc(&bg->nocow_writers);
333 spin_unlock(&bg->lock);
334
2306e83e 335 if (!can_nocow) {
3eeb3226 336 btrfs_put_block_group(bg);
2306e83e
FM
337 return NULL;
338 }
3eeb3226 339
2306e83e
FM
340 /* No put on block group, done by btrfs_dec_nocow_writers(). */
341 return bg;
3eeb3226
JB
342}
343
43dd529a 344/*
2306e83e
FM
345 * Decrement the number of NOCOW writers in a block group.
346 *
2306e83e
FM
347 * This is meant to be called after a previous call to btrfs_inc_nocow_writers(),
348 * and on the block group returned by that call. Typically this is called after
349 * creating an ordered extent for a NOCOW write, to prevent races with scrub and
350 * relocation.
351 *
352 * After this call, the caller should not use the block group anymore. It it wants
353 * to use it, then it should get a reference on it before calling this function.
354 */
355void btrfs_dec_nocow_writers(struct btrfs_block_group *bg)
3eeb3226 356{
3eeb3226
JB
357 if (atomic_dec_and_test(&bg->nocow_writers))
358 wake_up_var(&bg->nocow_writers);
2306e83e
FM
359
360 /* For the lookup done by a previous call to btrfs_inc_nocow_writers(). */
3eeb3226
JB
361 btrfs_put_block_group(bg);
362}
363
32da5386 364void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
3eeb3226
JB
365{
366 wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
367}
368
369void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
370 const u64 start)
371{
32da5386 372 struct btrfs_block_group *bg;
3eeb3226
JB
373
374 bg = btrfs_lookup_block_group(fs_info, start);
375 ASSERT(bg);
376 if (atomic_dec_and_test(&bg->reservations))
377 wake_up_var(&bg->reservations);
378 btrfs_put_block_group(bg);
379}
380
32da5386 381void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
3eeb3226
JB
382{
383 struct btrfs_space_info *space_info = bg->space_info;
384
385 ASSERT(bg->ro);
386
387 if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
388 return;
389
390 /*
391 * Our block group is read only but before we set it to read only,
392 * some task might have had allocated an extent from it already, but it
393 * has not yet created a respective ordered extent (and added it to a
394 * root's list of ordered extents).
395 * Therefore wait for any task currently allocating extents, since the
396 * block group's reservations counter is incremented while a read lock
397 * on the groups' semaphore is held and decremented after releasing
398 * the read access on that semaphore and creating the ordered extent.
399 */
400 down_write(&space_info->groups_sem);
401 up_write(&space_info->groups_sem);
402
403 wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
404}
9f21246d
JB
405
406struct btrfs_caching_control *btrfs_get_caching_control(
32da5386 407 struct btrfs_block_group *cache)
9f21246d
JB
408{
409 struct btrfs_caching_control *ctl;
410
411 spin_lock(&cache->lock);
412 if (!cache->caching_ctl) {
413 spin_unlock(&cache->lock);
414 return NULL;
415 }
416
417 ctl = cache->caching_ctl;
418 refcount_inc(&ctl->count);
419 spin_unlock(&cache->lock);
420 return ctl;
421}
422
423void btrfs_put_caching_control(struct btrfs_caching_control *ctl)
424{
425 if (refcount_dec_and_test(&ctl->count))
426 kfree(ctl);
427}
428
429/*
430 * When we wait for progress in the block group caching, its because our
431 * allocation attempt failed at least once. So, we must sleep and let some
432 * progress happen before we try again.
433 *
434 * This function will sleep at least once waiting for new free space to show
435 * up, and then it will check the block group free space numbers for our min
436 * num_bytes. Another option is to have it go ahead and look in the rbtree for
437 * a free extent of a given size, but this is a good start.
438 *
439 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
440 * any of the information in this block group.
441 */
32da5386 442void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
9f21246d
JB
443 u64 num_bytes)
444{
445 struct btrfs_caching_control *caching_ctl;
446
447 caching_ctl = btrfs_get_caching_control(cache);
448 if (!caching_ctl)
449 return;
450
32da5386 451 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
9f21246d
JB
452 (cache->free_space_ctl->free_space >= num_bytes));
453
454 btrfs_put_caching_control(caching_ctl);
455}
456
ced8ecf0
OS
457static int btrfs_caching_ctl_wait_done(struct btrfs_block_group *cache,
458 struct btrfs_caching_control *caching_ctl)
459{
460 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
461 return cache->cached == BTRFS_CACHE_ERROR ? -EIO : 0;
462}
463
464static int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
9f21246d
JB
465{
466 struct btrfs_caching_control *caching_ctl;
ced8ecf0 467 int ret;
9f21246d
JB
468
469 caching_ctl = btrfs_get_caching_control(cache);
470 if (!caching_ctl)
471 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
ced8ecf0 472 ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
9f21246d
JB
473 btrfs_put_caching_control(caching_ctl);
474 return ret;
475}
476
477#ifdef CONFIG_BTRFS_DEBUG
32da5386 478static void fragment_free_space(struct btrfs_block_group *block_group)
9f21246d
JB
479{
480 struct btrfs_fs_info *fs_info = block_group->fs_info;
b3470b5d
DS
481 u64 start = block_group->start;
482 u64 len = block_group->length;
9f21246d
JB
483 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
484 fs_info->nodesize : fs_info->sectorsize;
485 u64 step = chunk << 1;
486
487 while (len > chunk) {
488 btrfs_remove_free_space(block_group, start, chunk);
489 start += step;
490 if (len < step)
491 len = 0;
492 else
493 len -= step;
494 }
495}
496#endif
497
498/*
499 * This is only called by btrfs_cache_block_group, since we could have freed
500 * extents we need to check the pinned_extents for any extents that can't be
501 * used yet since their free space will be released as soon as the transaction
502 * commits.
503 */
32da5386 504u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
9f21246d
JB
505{
506 struct btrfs_fs_info *info = block_group->fs_info;
507 u64 extent_start, extent_end, size, total_added = 0;
508 int ret;
509
510 while (start < end) {
fe119a6e 511 ret = find_first_extent_bit(&info->excluded_extents, start,
9f21246d
JB
512 &extent_start, &extent_end,
513 EXTENT_DIRTY | EXTENT_UPTODATE,
514 NULL);
515 if (ret)
516 break;
517
518 if (extent_start <= start) {
519 start = extent_end + 1;
520 } else if (extent_start > start && extent_start < end) {
521 size = extent_start - start;
522 total_added += size;
b0643e59
DZ
523 ret = btrfs_add_free_space_async_trimmed(block_group,
524 start, size);
9f21246d
JB
525 BUG_ON(ret); /* -ENOMEM or logic error */
526 start = extent_end + 1;
527 } else {
528 break;
529 }
530 }
531
532 if (start < end) {
533 size = end - start;
534 total_added += size;
b0643e59
DZ
535 ret = btrfs_add_free_space_async_trimmed(block_group, start,
536 size);
9f21246d
JB
537 BUG_ON(ret); /* -ENOMEM or logic error */
538 }
539
540 return total_added;
541}
542
c7eec3d9
BB
543/*
544 * Get an arbitrary extent item index / max_index through the block group
545 *
546 * @block_group the block group to sample from
547 * @index: the integral step through the block group to grab from
548 * @max_index: the granularity of the sampling
549 * @key: return value parameter for the item we find
550 *
551 * Pre-conditions on indices:
552 * 0 <= index <= max_index
553 * 0 < max_index
554 *
555 * Returns: 0 on success, 1 if the search didn't yield a useful item, negative
556 * error code on error.
557 */
558static int sample_block_group_extent_item(struct btrfs_caching_control *caching_ctl,
559 struct btrfs_block_group *block_group,
560 int index, int max_index,
561 struct btrfs_key *key)
562{
563 struct btrfs_fs_info *fs_info = block_group->fs_info;
564 struct btrfs_root *extent_root;
565 int ret = 0;
566 u64 search_offset;
567 u64 search_end = block_group->start + block_group->length;
568 struct btrfs_path *path;
569
570 ASSERT(index >= 0);
571 ASSERT(index <= max_index);
572 ASSERT(max_index > 0);
573 lockdep_assert_held(&caching_ctl->mutex);
574 lockdep_assert_held_read(&fs_info->commit_root_sem);
575
576 path = btrfs_alloc_path();
577 if (!path)
578 return -ENOMEM;
579
580 extent_root = btrfs_extent_root(fs_info, max_t(u64, block_group->start,
581 BTRFS_SUPER_INFO_OFFSET));
582
583 path->skip_locking = 1;
584 path->search_commit_root = 1;
585 path->reada = READA_FORWARD;
586
587 search_offset = index * div_u64(block_group->length, max_index);
588 key->objectid = block_group->start + search_offset;
589 key->type = BTRFS_EXTENT_ITEM_KEY;
590 key->offset = 0;
591
592 while (1) {
593 ret = btrfs_search_forward(extent_root, key, path, 0);
594 if (ret != 0)
595 goto out;
596 /* Success; sampled an extent item in the block group */
597 if (key->type == BTRFS_EXTENT_ITEM_KEY &&
598 key->objectid >= block_group->start &&
599 key->objectid + key->offset <= search_end)
600 goto out;
601
602 /* We can't possibly find a valid extent item anymore */
603 if (key->objectid >= search_end) {
604 ret = 1;
605 break;
606 }
607 if (key->type < BTRFS_EXTENT_ITEM_KEY)
608 key->type = BTRFS_EXTENT_ITEM_KEY;
609 else
610 key->objectid++;
611 btrfs_release_path(path);
612 up_read(&fs_info->commit_root_sem);
613 mutex_unlock(&caching_ctl->mutex);
614 cond_resched();
615 mutex_lock(&caching_ctl->mutex);
616 down_read(&fs_info->commit_root_sem);
617 }
618out:
619 lockdep_assert_held(&caching_ctl->mutex);
620 lockdep_assert_held_read(&fs_info->commit_root_sem);
621 btrfs_free_path(path);
622 return ret;
623}
624
625/*
626 * Best effort attempt to compute a block group's size class while caching it.
627 *
628 * @block_group: the block group we are caching
629 *
630 * We cannot infer the size class while adding free space extents, because that
631 * logic doesn't care about contiguous file extents (it doesn't differentiate
632 * between a 100M extent and 100 contiguous 1M extents). So we need to read the
633 * file extent items. Reading all of them is quite wasteful, because usually
634 * only a handful are enough to give a good answer. Therefore, we just grab 5 of
635 * them at even steps through the block group and pick the smallest size class
636 * we see. Since size class is best effort, and not guaranteed in general,
637 * inaccuracy is acceptable.
638 *
639 * To be more explicit about why this algorithm makes sense:
640 *
641 * If we are caching in a block group from disk, then there are three major cases
642 * to consider:
643 * 1. the block group is well behaved and all extents in it are the same size
644 * class.
645 * 2. the block group is mostly one size class with rare exceptions for last
646 * ditch allocations
647 * 3. the block group was populated before size classes and can have a totally
648 * arbitrary mix of size classes.
649 *
650 * In case 1, looking at any extent in the block group will yield the correct
651 * result. For the mixed cases, taking the minimum size class seems like a good
652 * approximation, since gaps from frees will be usable to the size class. For
653 * 2., a small handful of file extents is likely to yield the right answer. For
654 * 3, we can either read every file extent, or admit that this is best effort
655 * anyway and try to stay fast.
656 *
657 * Returns: 0 on success, negative error code on error.
658 */
659static int load_block_group_size_class(struct btrfs_caching_control *caching_ctl,
660 struct btrfs_block_group *block_group)
661{
662 struct btrfs_key key;
663 int i;
664 u64 min_size = block_group->length;
665 enum btrfs_block_group_size_class size_class = BTRFS_BG_SZ_NONE;
666 int ret;
667
cb0922f2 668 if (!btrfs_block_group_should_use_size_class(block_group))
c7eec3d9
BB
669 return 0;
670
671 for (i = 0; i < 5; ++i) {
672 ret = sample_block_group_extent_item(caching_ctl, block_group, i, 5, &key);
673 if (ret < 0)
674 goto out;
675 if (ret > 0)
676 continue;
677 min_size = min_t(u64, min_size, key.offset);
678 size_class = btrfs_calc_block_group_size_class(min_size);
679 }
680 if (size_class != BTRFS_BG_SZ_NONE) {
681 spin_lock(&block_group->lock);
682 block_group->size_class = size_class;
683 spin_unlock(&block_group->lock);
684 }
685
686out:
687 return ret;
688}
689
9f21246d
JB
690static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
691{
32da5386 692 struct btrfs_block_group *block_group = caching_ctl->block_group;
9f21246d 693 struct btrfs_fs_info *fs_info = block_group->fs_info;
29cbcf40 694 struct btrfs_root *extent_root;
9f21246d
JB
695 struct btrfs_path *path;
696 struct extent_buffer *leaf;
697 struct btrfs_key key;
698 u64 total_found = 0;
699 u64 last = 0;
700 u32 nritems;
701 int ret;
702 bool wakeup = true;
703
704 path = btrfs_alloc_path();
705 if (!path)
706 return -ENOMEM;
707
b3470b5d 708 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
29cbcf40 709 extent_root = btrfs_extent_root(fs_info, last);
9f21246d
JB
710
711#ifdef CONFIG_BTRFS_DEBUG
712 /*
713 * If we're fragmenting we don't want to make anybody think we can
714 * allocate from this block group until we've had a chance to fragment
715 * the free space.
716 */
717 if (btrfs_should_fragment_free_space(block_group))
718 wakeup = false;
719#endif
720 /*
721 * We don't want to deadlock with somebody trying to allocate a new
722 * extent for the extent root while also trying to search the extent
723 * root to add free space. So we skip locking and search the commit
724 * root, since its read-only
725 */
726 path->skip_locking = 1;
727 path->search_commit_root = 1;
728 path->reada = READA_FORWARD;
729
730 key.objectid = last;
731 key.offset = 0;
732 key.type = BTRFS_EXTENT_ITEM_KEY;
733
734next:
735 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
736 if (ret < 0)
737 goto out;
738
739 leaf = path->nodes[0];
740 nritems = btrfs_header_nritems(leaf);
741
742 while (1) {
743 if (btrfs_fs_closing(fs_info) > 1) {
744 last = (u64)-1;
745 break;
746 }
747
748 if (path->slots[0] < nritems) {
749 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
750 } else {
751 ret = btrfs_find_next_key(extent_root, path, &key, 0, 0);
752 if (ret)
753 break;
754
755 if (need_resched() ||
756 rwsem_is_contended(&fs_info->commit_root_sem)) {
9f21246d
JB
757 btrfs_release_path(path);
758 up_read(&fs_info->commit_root_sem);
759 mutex_unlock(&caching_ctl->mutex);
760 cond_resched();
761 mutex_lock(&caching_ctl->mutex);
762 down_read(&fs_info->commit_root_sem);
763 goto next;
764 }
765
766 ret = btrfs_next_leaf(extent_root, path);
767 if (ret < 0)
768 goto out;
769 if (ret)
770 break;
771 leaf = path->nodes[0];
772 nritems = btrfs_header_nritems(leaf);
773 continue;
774 }
775
776 if (key.objectid < last) {
777 key.objectid = last;
778 key.offset = 0;
779 key.type = BTRFS_EXTENT_ITEM_KEY;
9f21246d
JB
780 btrfs_release_path(path);
781 goto next;
782 }
783
b3470b5d 784 if (key.objectid < block_group->start) {
9f21246d
JB
785 path->slots[0]++;
786 continue;
787 }
788
b3470b5d 789 if (key.objectid >= block_group->start + block_group->length)
9f21246d
JB
790 break;
791
792 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
793 key.type == BTRFS_METADATA_ITEM_KEY) {
794 total_found += add_new_free_space(block_group, last,
795 key.objectid);
796 if (key.type == BTRFS_METADATA_ITEM_KEY)
797 last = key.objectid +
798 fs_info->nodesize;
799 else
800 last = key.objectid + key.offset;
801
802 if (total_found > CACHING_CTL_WAKE_UP) {
803 total_found = 0;
804 if (wakeup)
805 wake_up(&caching_ctl->wait);
806 }
807 }
808 path->slots[0]++;
809 }
810 ret = 0;
811
812 total_found += add_new_free_space(block_group, last,
b3470b5d 813 block_group->start + block_group->length);
9f21246d
JB
814
815out:
816 btrfs_free_path(path);
817 return ret;
818}
819
820static noinline void caching_thread(struct btrfs_work *work)
821{
32da5386 822 struct btrfs_block_group *block_group;
9f21246d
JB
823 struct btrfs_fs_info *fs_info;
824 struct btrfs_caching_control *caching_ctl;
825 int ret;
826
827 caching_ctl = container_of(work, struct btrfs_caching_control, work);
828 block_group = caching_ctl->block_group;
829 fs_info = block_group->fs_info;
830
831 mutex_lock(&caching_ctl->mutex);
832 down_read(&fs_info->commit_root_sem);
833
c7eec3d9 834 load_block_group_size_class(caching_ctl, block_group);
e747853c
JB
835 if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
836 ret = load_free_space_cache(block_group);
837 if (ret == 1) {
838 ret = 0;
839 goto done;
840 }
841
842 /*
843 * We failed to load the space cache, set ourselves to
844 * CACHE_STARTED and carry on.
845 */
846 spin_lock(&block_group->lock);
847 block_group->cached = BTRFS_CACHE_STARTED;
848 spin_unlock(&block_group->lock);
849 wake_up(&caching_ctl->wait);
850 }
851
2f96e402
JB
852 /*
853 * If we are in the transaction that populated the free space tree we
854 * can't actually cache from the free space tree as our commit root and
855 * real root are the same, so we could change the contents of the blocks
856 * while caching. Instead do the slow caching in this case, and after
857 * the transaction has committed we will be safe.
858 */
859 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
860 !(test_bit(BTRFS_FS_FREE_SPACE_TREE_UNTRUSTED, &fs_info->flags)))
9f21246d
JB
861 ret = load_free_space_tree(caching_ctl);
862 else
863 ret = load_extent_tree_free(caching_ctl);
e747853c 864done:
9f21246d
JB
865 spin_lock(&block_group->lock);
866 block_group->caching_ctl = NULL;
867 block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
868 spin_unlock(&block_group->lock);
869
870#ifdef CONFIG_BTRFS_DEBUG
871 if (btrfs_should_fragment_free_space(block_group)) {
872 u64 bytes_used;
873
874 spin_lock(&block_group->space_info->lock);
875 spin_lock(&block_group->lock);
b3470b5d 876 bytes_used = block_group->length - block_group->used;
9f21246d
JB
877 block_group->space_info->bytes_used += bytes_used >> 1;
878 spin_unlock(&block_group->lock);
879 spin_unlock(&block_group->space_info->lock);
e11c0406 880 fragment_free_space(block_group);
9f21246d
JB
881 }
882#endif
883
9f21246d
JB
884 up_read(&fs_info->commit_root_sem);
885 btrfs_free_excluded_extents(block_group);
886 mutex_unlock(&caching_ctl->mutex);
887
888 wake_up(&caching_ctl->wait);
889
890 btrfs_put_caching_control(caching_ctl);
891 btrfs_put_block_group(block_group);
892}
893
ced8ecf0 894int btrfs_cache_block_group(struct btrfs_block_group *cache, bool wait)
9f21246d 895{
9f21246d 896 struct btrfs_fs_info *fs_info = cache->fs_info;
e747853c 897 struct btrfs_caching_control *caching_ctl = NULL;
9f21246d
JB
898 int ret = 0;
899
2eda5708
NA
900 /* Allocator for zoned filesystems does not use the cache at all */
901 if (btrfs_is_zoned(fs_info))
902 return 0;
903
9f21246d
JB
904 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
905 if (!caching_ctl)
906 return -ENOMEM;
907
908 INIT_LIST_HEAD(&caching_ctl->list);
909 mutex_init(&caching_ctl->mutex);
910 init_waitqueue_head(&caching_ctl->wait);
911 caching_ctl->block_group = cache;
e747853c 912 refcount_set(&caching_ctl->count, 2);
a0cac0ec 913 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
9f21246d
JB
914
915 spin_lock(&cache->lock);
9f21246d 916 if (cache->cached != BTRFS_CACHE_NO) {
9f21246d 917 kfree(caching_ctl);
e747853c
JB
918
919 caching_ctl = cache->caching_ctl;
920 if (caching_ctl)
921 refcount_inc(&caching_ctl->count);
922 spin_unlock(&cache->lock);
923 goto out;
9f21246d
JB
924 }
925 WARN_ON(cache->caching_ctl);
926 cache->caching_ctl = caching_ctl;
ced8ecf0 927 cache->cached = BTRFS_CACHE_STARTED;
9f21246d
JB
928 spin_unlock(&cache->lock);
929
16b0c258 930 write_lock(&fs_info->block_group_cache_lock);
9f21246d
JB
931 refcount_inc(&caching_ctl->count);
932 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
16b0c258 933 write_unlock(&fs_info->block_group_cache_lock);
9f21246d
JB
934
935 btrfs_get_block_group(cache);
936
937 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
e747853c 938out:
ced8ecf0
OS
939 if (wait && caching_ctl)
940 ret = btrfs_caching_ctl_wait_done(cache, caching_ctl);
e747853c
JB
941 if (caching_ctl)
942 btrfs_put_caching_control(caching_ctl);
9f21246d
JB
943
944 return ret;
945}
e3e0520b
JB
946
947static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
948{
949 u64 extra_flags = chunk_to_extended(flags) &
950 BTRFS_EXTENDED_PROFILE_MASK;
951
952 write_seqlock(&fs_info->profiles_lock);
953 if (flags & BTRFS_BLOCK_GROUP_DATA)
954 fs_info->avail_data_alloc_bits &= ~extra_flags;
955 if (flags & BTRFS_BLOCK_GROUP_METADATA)
956 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
957 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
958 fs_info->avail_system_alloc_bits &= ~extra_flags;
959 write_sequnlock(&fs_info->profiles_lock);
960}
961
962/*
963 * Clear incompat bits for the following feature(s):
964 *
965 * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
966 * in the whole filesystem
9c907446
DS
967 *
968 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
e3e0520b
JB
969 */
970static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
971{
9c907446
DS
972 bool found_raid56 = false;
973 bool found_raid1c34 = false;
974
975 if ((flags & BTRFS_BLOCK_GROUP_RAID56_MASK) ||
976 (flags & BTRFS_BLOCK_GROUP_RAID1C3) ||
977 (flags & BTRFS_BLOCK_GROUP_RAID1C4)) {
e3e0520b
JB
978 struct list_head *head = &fs_info->space_info;
979 struct btrfs_space_info *sinfo;
980
981 list_for_each_entry_rcu(sinfo, head, list) {
e3e0520b
JB
982 down_read(&sinfo->groups_sem);
983 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
9c907446 984 found_raid56 = true;
e3e0520b 985 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
9c907446
DS
986 found_raid56 = true;
987 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C3]))
988 found_raid1c34 = true;
989 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID1C4]))
990 found_raid1c34 = true;
e3e0520b 991 up_read(&sinfo->groups_sem);
e3e0520b 992 }
d8e6fd5c 993 if (!found_raid56)
9c907446 994 btrfs_clear_fs_incompat(fs_info, RAID56);
d8e6fd5c 995 if (!found_raid1c34)
9c907446 996 btrfs_clear_fs_incompat(fs_info, RAID1C34);
e3e0520b
JB
997 }
998}
999
7357623a
QW
1000static int remove_block_group_item(struct btrfs_trans_handle *trans,
1001 struct btrfs_path *path,
1002 struct btrfs_block_group *block_group)
1003{
1004 struct btrfs_fs_info *fs_info = trans->fs_info;
1005 struct btrfs_root *root;
1006 struct btrfs_key key;
1007 int ret;
1008
dfe8aec4 1009 root = btrfs_block_group_root(fs_info);
7357623a
QW
1010 key.objectid = block_group->start;
1011 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1012 key.offset = block_group->length;
1013
1014 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1015 if (ret > 0)
1016 ret = -ENOENT;
1017 if (ret < 0)
1018 return ret;
1019
1020 ret = btrfs_del_item(trans, root, path);
1021 return ret;
1022}
1023
e3e0520b
JB
1024int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
1025 u64 group_start, struct extent_map *em)
1026{
1027 struct btrfs_fs_info *fs_info = trans->fs_info;
e3e0520b 1028 struct btrfs_path *path;
32da5386 1029 struct btrfs_block_group *block_group;
e3e0520b 1030 struct btrfs_free_cluster *cluster;
e3e0520b
JB
1031 struct inode *inode;
1032 struct kobject *kobj = NULL;
1033 int ret;
1034 int index;
1035 int factor;
1036 struct btrfs_caching_control *caching_ctl = NULL;
1037 bool remove_em;
1038 bool remove_rsv = false;
1039
1040 block_group = btrfs_lookup_block_group(fs_info, group_start);
1041 BUG_ON(!block_group);
1042 BUG_ON(!block_group->ro);
1043
1044 trace_btrfs_remove_block_group(block_group);
1045 /*
1046 * Free the reserved super bytes from this block group before
1047 * remove it.
1048 */
1049 btrfs_free_excluded_extents(block_group);
b3470b5d
DS
1050 btrfs_free_ref_tree_range(fs_info, block_group->start,
1051 block_group->length);
e3e0520b 1052
e3e0520b
JB
1053 index = btrfs_bg_flags_to_raid_index(block_group->flags);
1054 factor = btrfs_bg_type_to_factor(block_group->flags);
1055
1056 /* make sure this block group isn't part of an allocation cluster */
1057 cluster = &fs_info->data_alloc_cluster;
1058 spin_lock(&cluster->refill_lock);
1059 btrfs_return_cluster_to_free_space(block_group, cluster);
1060 spin_unlock(&cluster->refill_lock);
1061
1062 /*
1063 * make sure this block group isn't part of a metadata
1064 * allocation cluster
1065 */
1066 cluster = &fs_info->meta_alloc_cluster;
1067 spin_lock(&cluster->refill_lock);
1068 btrfs_return_cluster_to_free_space(block_group, cluster);
1069 spin_unlock(&cluster->refill_lock);
1070
40ab3be1 1071 btrfs_clear_treelog_bg(block_group);
c2707a25 1072 btrfs_clear_data_reloc_bg(block_group);
40ab3be1 1073
e3e0520b
JB
1074 path = btrfs_alloc_path();
1075 if (!path) {
1076 ret = -ENOMEM;
9fecd132 1077 goto out;
e3e0520b
JB
1078 }
1079
1080 /*
1081 * get the inode first so any iput calls done for the io_list
1082 * aren't the final iput (no unlinks allowed now)
1083 */
1084 inode = lookup_free_space_inode(block_group, path);
1085
1086 mutex_lock(&trans->transaction->cache_write_mutex);
1087 /*
1088 * Make sure our free space cache IO is done before removing the
1089 * free space inode
1090 */
1091 spin_lock(&trans->transaction->dirty_bgs_lock);
1092 if (!list_empty(&block_group->io_list)) {
1093 list_del_init(&block_group->io_list);
1094
1095 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
1096
1097 spin_unlock(&trans->transaction->dirty_bgs_lock);
1098 btrfs_wait_cache_io(trans, block_group, path);
1099 btrfs_put_block_group(block_group);
1100 spin_lock(&trans->transaction->dirty_bgs_lock);
1101 }
1102
1103 if (!list_empty(&block_group->dirty_list)) {
1104 list_del_init(&block_group->dirty_list);
1105 remove_rsv = true;
1106 btrfs_put_block_group(block_group);
1107 }
1108 spin_unlock(&trans->transaction->dirty_bgs_lock);
1109 mutex_unlock(&trans->transaction->cache_write_mutex);
1110
36b216c8
BB
1111 ret = btrfs_remove_free_space_inode(trans, inode, block_group);
1112 if (ret)
9fecd132 1113 goto out;
e3e0520b 1114
16b0c258 1115 write_lock(&fs_info->block_group_cache_lock);
08dddb29
FM
1116 rb_erase_cached(&block_group->cache_node,
1117 &fs_info->block_group_cache_tree);
e3e0520b
JB
1118 RB_CLEAR_NODE(&block_group->cache_node);
1119
9fecd132
FM
1120 /* Once for the block groups rbtree */
1121 btrfs_put_block_group(block_group);
1122
16b0c258 1123 write_unlock(&fs_info->block_group_cache_lock);
e3e0520b
JB
1124
1125 down_write(&block_group->space_info->groups_sem);
1126 /*
1127 * we must use list_del_init so people can check to see if they
1128 * are still on the list after taking the semaphore
1129 */
1130 list_del_init(&block_group->list);
1131 if (list_empty(&block_group->space_info->block_groups[index])) {
1132 kobj = block_group->space_info->block_group_kobjs[index];
1133 block_group->space_info->block_group_kobjs[index] = NULL;
1134 clear_avail_alloc_bits(fs_info, block_group->flags);
1135 }
1136 up_write(&block_group->space_info->groups_sem);
1137 clear_incompat_bg_bits(fs_info, block_group->flags);
1138 if (kobj) {
1139 kobject_del(kobj);
1140 kobject_put(kobj);
1141 }
1142
e3e0520b
JB
1143 if (block_group->cached == BTRFS_CACHE_STARTED)
1144 btrfs_wait_block_group_cache_done(block_group);
7b9c293b
JB
1145
1146 write_lock(&fs_info->block_group_cache_lock);
1147 caching_ctl = btrfs_get_caching_control(block_group);
1148 if (!caching_ctl) {
1149 struct btrfs_caching_control *ctl;
1150
1151 list_for_each_entry(ctl, &fs_info->caching_block_groups, list) {
1152 if (ctl->block_group == block_group) {
1153 caching_ctl = ctl;
1154 refcount_inc(&caching_ctl->count);
1155 break;
1156 }
e3e0520b
JB
1157 }
1158 }
7b9c293b
JB
1159 if (caching_ctl)
1160 list_del_init(&caching_ctl->list);
1161 write_unlock(&fs_info->block_group_cache_lock);
1162
1163 if (caching_ctl) {
1164 /* Once for the caching bgs list and once for us. */
1165 btrfs_put_caching_control(caching_ctl);
1166 btrfs_put_caching_control(caching_ctl);
1167 }
e3e0520b
JB
1168
1169 spin_lock(&trans->transaction->dirty_bgs_lock);
1170 WARN_ON(!list_empty(&block_group->dirty_list));
1171 WARN_ON(!list_empty(&block_group->io_list));
1172 spin_unlock(&trans->transaction->dirty_bgs_lock);
1173
1174 btrfs_remove_free_space_cache(block_group);
1175
1176 spin_lock(&block_group->space_info->lock);
1177 list_del_init(&block_group->ro_list);
1178
1179 if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
1180 WARN_ON(block_group->space_info->total_bytes
b3470b5d 1181 < block_group->length);
e3e0520b 1182 WARN_ON(block_group->space_info->bytes_readonly
169e0da9
NA
1183 < block_group->length - block_group->zone_unusable);
1184 WARN_ON(block_group->space_info->bytes_zone_unusable
1185 < block_group->zone_unusable);
e3e0520b 1186 WARN_ON(block_group->space_info->disk_total
b3470b5d 1187 < block_group->length * factor);
3349b57f
JB
1188 WARN_ON(test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE,
1189 &block_group->runtime_flags) &&
6a921de5
NA
1190 block_group->space_info->active_total_bytes
1191 < block_group->length);
e3e0520b 1192 }
b3470b5d 1193 block_group->space_info->total_bytes -= block_group->length;
3349b57f 1194 if (test_bit(BLOCK_GROUP_FLAG_ZONE_IS_ACTIVE, &block_group->runtime_flags))
6a921de5 1195 block_group->space_info->active_total_bytes -= block_group->length;
169e0da9
NA
1196 block_group->space_info->bytes_readonly -=
1197 (block_group->length - block_group->zone_unusable);
1198 block_group->space_info->bytes_zone_unusable -=
1199 block_group->zone_unusable;
b3470b5d 1200 block_group->space_info->disk_total -= block_group->length * factor;
e3e0520b
JB
1201
1202 spin_unlock(&block_group->space_info->lock);
1203
ffcb9d44
FM
1204 /*
1205 * Remove the free space for the block group from the free space tree
1206 * and the block group's item from the extent tree before marking the
1207 * block group as removed. This is to prevent races with tasks that
1208 * freeze and unfreeze a block group, this task and another task
1209 * allocating a new block group - the unfreeze task ends up removing
1210 * the block group's extent map before the task calling this function
1211 * deletes the block group item from the extent tree, allowing for
1212 * another task to attempt to create another block group with the same
1213 * item key (and failing with -EEXIST and a transaction abort).
1214 */
1215 ret = remove_block_group_free_space(trans, block_group);
1216 if (ret)
1217 goto out;
1218
1219 ret = remove_block_group_item(trans, path, block_group);
1220 if (ret < 0)
1221 goto out;
1222
e3e0520b 1223 spin_lock(&block_group->lock);
3349b57f
JB
1224 set_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags);
1225
e3e0520b 1226 /*
6b7304af
FM
1227 * At this point trimming or scrub can't start on this block group,
1228 * because we removed the block group from the rbtree
1229 * fs_info->block_group_cache_tree so no one can't find it anymore and
1230 * even if someone already got this block group before we removed it
1231 * from the rbtree, they have already incremented block_group->frozen -
1232 * if they didn't, for the trimming case they won't find any free space
1233 * entries because we already removed them all when we called
1234 * btrfs_remove_free_space_cache().
e3e0520b
JB
1235 *
1236 * And we must not remove the extent map from the fs_info->mapping_tree
1237 * to prevent the same logical address range and physical device space
6b7304af
FM
1238 * ranges from being reused for a new block group. This is needed to
1239 * avoid races with trimming and scrub.
1240 *
1241 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
e3e0520b
JB
1242 * completely transactionless, so while it is trimming a range the
1243 * currently running transaction might finish and a new one start,
1244 * allowing for new block groups to be created that can reuse the same
1245 * physical device locations unless we take this special care.
1246 *
1247 * There may also be an implicit trim operation if the file system
1248 * is mounted with -odiscard. The same protections must remain
1249 * in place until the extents have been discarded completely when
1250 * the transaction commit has completed.
1251 */
6b7304af 1252 remove_em = (atomic_read(&block_group->frozen) == 0);
e3e0520b
JB
1253 spin_unlock(&block_group->lock);
1254
e3e0520b
JB
1255 if (remove_em) {
1256 struct extent_map_tree *em_tree;
1257
1258 em_tree = &fs_info->mapping_tree;
1259 write_lock(&em_tree->lock);
1260 remove_extent_mapping(em_tree, em);
1261 write_unlock(&em_tree->lock);
1262 /* once for the tree */
1263 free_extent_map(em);
1264 }
f6033c5e 1265
9fecd132 1266out:
f6033c5e
XY
1267 /* Once for the lookup reference */
1268 btrfs_put_block_group(block_group);
e3e0520b
JB
1269 if (remove_rsv)
1270 btrfs_delayed_refs_rsv_release(fs_info, 1);
1271 btrfs_free_path(path);
1272 return ret;
1273}
1274
1275struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1276 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1277{
dfe8aec4 1278 struct btrfs_root *root = btrfs_block_group_root(fs_info);
e3e0520b
JB
1279 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1280 struct extent_map *em;
1281 struct map_lookup *map;
1282 unsigned int num_items;
1283
1284 read_lock(&em_tree->lock);
1285 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1286 read_unlock(&em_tree->lock);
1287 ASSERT(em && em->start == chunk_offset);
1288
1289 /*
1290 * We need to reserve 3 + N units from the metadata space info in order
1291 * to remove a block group (done at btrfs_remove_chunk() and at
1292 * btrfs_remove_block_group()), which are used for:
1293 *
1294 * 1 unit for adding the free space inode's orphan (located in the tree
1295 * of tree roots).
1296 * 1 unit for deleting the block group item (located in the extent
1297 * tree).
1298 * 1 unit for deleting the free space item (located in tree of tree
1299 * roots).
1300 * N units for deleting N device extent items corresponding to each
1301 * stripe (located in the device tree).
1302 *
1303 * In order to remove a block group we also need to reserve units in the
1304 * system space info in order to update the chunk tree (update one or
1305 * more device items and remove one chunk item), but this is done at
1306 * btrfs_remove_chunk() through a call to check_system_chunk().
1307 */
1308 map = em->map_lookup;
1309 num_items = 3 + map->num_stripes;
1310 free_extent_map(em);
1311
dfe8aec4 1312 return btrfs_start_transaction_fallback_global_rsv(root, num_items);
e3e0520b
JB
1313}
1314
26ce2095
JB
1315/*
1316 * Mark block group @cache read-only, so later write won't happen to block
1317 * group @cache.
1318 *
1319 * If @force is not set, this function will only mark the block group readonly
1320 * if we have enough free space (1M) in other metadata/system block groups.
1321 * If @force is not set, this function will mark the block group readonly
1322 * without checking free space.
1323 *
1324 * NOTE: This function doesn't care if other block groups can contain all the
1325 * data in this block group. That check should be done by relocation routine,
1326 * not this function.
1327 */
32da5386 1328static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
26ce2095
JB
1329{
1330 struct btrfs_space_info *sinfo = cache->space_info;
1331 u64 num_bytes;
26ce2095
JB
1332 int ret = -ENOSPC;
1333
26ce2095
JB
1334 spin_lock(&sinfo->lock);
1335 spin_lock(&cache->lock);
1336
195a49ea
FM
1337 if (cache->swap_extents) {
1338 ret = -ETXTBSY;
1339 goto out;
1340 }
1341
26ce2095
JB
1342 if (cache->ro) {
1343 cache->ro++;
1344 ret = 0;
1345 goto out;
1346 }
1347
b3470b5d 1348 num_bytes = cache->length - cache->reserved - cache->pinned -
169e0da9 1349 cache->bytes_super - cache->zone_unusable - cache->used;
26ce2095
JB
1350
1351 /*
a30a3d20
JB
1352 * Data never overcommits, even in mixed mode, so do just the straight
1353 * check of left over space in how much we have allocated.
26ce2095 1354 */
a30a3d20
JB
1355 if (force) {
1356 ret = 0;
1357 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1358 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1359
1360 /*
1361 * Here we make sure if we mark this bg RO, we still have enough
1362 * free space as buffer.
1363 */
1364 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1365 ret = 0;
1366 } else {
1367 /*
1368 * We overcommit metadata, so we need to do the
1369 * btrfs_can_overcommit check here, and we need to pass in
1370 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1371 * leeway to allow us to mark this block group as read only.
1372 */
1373 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1374 BTRFS_RESERVE_NO_FLUSH))
1375 ret = 0;
1376 }
1377
1378 if (!ret) {
26ce2095 1379 sinfo->bytes_readonly += num_bytes;
169e0da9
NA
1380 if (btrfs_is_zoned(cache->fs_info)) {
1381 /* Migrate zone_unusable bytes to readonly */
1382 sinfo->bytes_readonly += cache->zone_unusable;
1383 sinfo->bytes_zone_unusable -= cache->zone_unusable;
1384 cache->zone_unusable = 0;
1385 }
26ce2095
JB
1386 cache->ro++;
1387 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
26ce2095
JB
1388 }
1389out:
1390 spin_unlock(&cache->lock);
1391 spin_unlock(&sinfo->lock);
1392 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1393 btrfs_info(cache->fs_info,
b3470b5d 1394 "unable to make block group %llu ro", cache->start);
26ce2095
JB
1395 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1396 }
1397 return ret;
1398}
1399
fe119a6e
NB
1400static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1401 struct btrfs_block_group *bg)
45bb5d6a
NB
1402{
1403 struct btrfs_fs_info *fs_info = bg->fs_info;
fe119a6e 1404 struct btrfs_transaction *prev_trans = NULL;
45bb5d6a
NB
1405 const u64 start = bg->start;
1406 const u64 end = start + bg->length - 1;
1407 int ret;
1408
fe119a6e
NB
1409 spin_lock(&fs_info->trans_lock);
1410 if (trans->transaction->list.prev != &fs_info->trans_list) {
1411 prev_trans = list_last_entry(&trans->transaction->list,
1412 struct btrfs_transaction, list);
1413 refcount_inc(&prev_trans->use_count);
1414 }
1415 spin_unlock(&fs_info->trans_lock);
1416
45bb5d6a
NB
1417 /*
1418 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1419 * btrfs_finish_extent_commit(). If we are at transaction N, another
1420 * task might be running finish_extent_commit() for the previous
1421 * transaction N - 1, and have seen a range belonging to the block
fe119a6e
NB
1422 * group in pinned_extents before we were able to clear the whole block
1423 * group range from pinned_extents. This means that task can lookup for
1424 * the block group after we unpinned it from pinned_extents and removed
1425 * it, leading to a BUG_ON() at unpin_extent_range().
45bb5d6a
NB
1426 */
1427 mutex_lock(&fs_info->unused_bg_unpin_mutex);
fe119a6e
NB
1428 if (prev_trans) {
1429 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1430 EXTENT_DIRTY);
1431 if (ret)
534cf531 1432 goto out;
fe119a6e 1433 }
45bb5d6a 1434
fe119a6e 1435 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
45bb5d6a 1436 EXTENT_DIRTY);
534cf531 1437out:
45bb5d6a 1438 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5150bf19
FM
1439 if (prev_trans)
1440 btrfs_put_transaction(prev_trans);
45bb5d6a 1441
534cf531 1442 return ret == 0;
45bb5d6a
NB
1443}
1444
e3e0520b
JB
1445/*
1446 * Process the unused_bgs list and remove any that don't have any allocated
1447 * space inside of them.
1448 */
1449void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1450{
32da5386 1451 struct btrfs_block_group *block_group;
e3e0520b
JB
1452 struct btrfs_space_info *space_info;
1453 struct btrfs_trans_handle *trans;
6e80d4f8 1454 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
e3e0520b
JB
1455 int ret = 0;
1456
1457 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1458 return;
1459
2f12741f
JB
1460 if (btrfs_fs_closing(fs_info))
1461 return;
1462
ddfd08cb
JB
1463 /*
1464 * Long running balances can keep us blocked here for eternity, so
1465 * simply skip deletion if we're unable to get the mutex.
1466 */
f3372065 1467 if (!mutex_trylock(&fs_info->reclaim_bgs_lock))
ddfd08cb
JB
1468 return;
1469
e3e0520b
JB
1470 spin_lock(&fs_info->unused_bgs_lock);
1471 while (!list_empty(&fs_info->unused_bgs)) {
e3e0520b
JB
1472 int trimming;
1473
1474 block_group = list_first_entry(&fs_info->unused_bgs,
32da5386 1475 struct btrfs_block_group,
e3e0520b
JB
1476 bg_list);
1477 list_del_init(&block_group->bg_list);
1478
1479 space_info = block_group->space_info;
1480
1481 if (ret || btrfs_mixed_space_info(space_info)) {
1482 btrfs_put_block_group(block_group);
1483 continue;
1484 }
1485 spin_unlock(&fs_info->unused_bgs_lock);
1486
b0643e59
DZ
1487 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1488
e3e0520b
JB
1489 /* Don't want to race with allocators so take the groups_sem */
1490 down_write(&space_info->groups_sem);
6e80d4f8
DZ
1491
1492 /*
1493 * Async discard moves the final block group discard to be prior
1494 * to the unused_bgs code path. Therefore, if it's not fully
1495 * trimmed, punt it back to the async discard lists.
1496 */
1497 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1498 !btrfs_is_free_space_trimmed(block_group)) {
1499 trace_btrfs_skip_unused_block_group(block_group);
1500 up_write(&space_info->groups_sem);
1501 /* Requeue if we failed because of async discard */
1502 btrfs_discard_queue_work(&fs_info->discard_ctl,
1503 block_group);
1504 goto next;
1505 }
1506
e3e0520b
JB
1507 spin_lock(&block_group->lock);
1508 if (block_group->reserved || block_group->pinned ||
bf38be65 1509 block_group->used || block_group->ro ||
e3e0520b
JB
1510 list_is_singular(&block_group->list)) {
1511 /*
1512 * We want to bail if we made new allocations or have
1513 * outstanding allocations in this block group. We do
1514 * the ro check in case balance is currently acting on
1515 * this block group.
1516 */
1517 trace_btrfs_skip_unused_block_group(block_group);
1518 spin_unlock(&block_group->lock);
1519 up_write(&space_info->groups_sem);
1520 goto next;
1521 }
1522 spin_unlock(&block_group->lock);
1523
1524 /* We don't want to force the issue, only flip if it's ok. */
e11c0406 1525 ret = inc_block_group_ro(block_group, 0);
e3e0520b
JB
1526 up_write(&space_info->groups_sem);
1527 if (ret < 0) {
1528 ret = 0;
1529 goto next;
1530 }
1531
74e91b12
NA
1532 ret = btrfs_zone_finish(block_group);
1533 if (ret < 0) {
1534 btrfs_dec_block_group_ro(block_group);
1535 if (ret == -EAGAIN)
1536 ret = 0;
1537 goto next;
1538 }
1539
e3e0520b
JB
1540 /*
1541 * Want to do this before we do anything else so we can recover
1542 * properly if we fail to join the transaction.
1543 */
1544 trans = btrfs_start_trans_remove_block_group(fs_info,
b3470b5d 1545 block_group->start);
e3e0520b
JB
1546 if (IS_ERR(trans)) {
1547 btrfs_dec_block_group_ro(block_group);
1548 ret = PTR_ERR(trans);
1549 goto next;
1550 }
1551
1552 /*
1553 * We could have pending pinned extents for this block group,
1554 * just delete them, we don't care about them anymore.
1555 */
534cf531
FM
1556 if (!clean_pinned_extents(trans, block_group)) {
1557 btrfs_dec_block_group_ro(block_group);
e3e0520b 1558 goto end_trans;
534cf531 1559 }
e3e0520b 1560
b0643e59
DZ
1561 /*
1562 * At this point, the block_group is read only and should fail
1563 * new allocations. However, btrfs_finish_extent_commit() can
1564 * cause this block_group to be placed back on the discard
1565 * lists because now the block_group isn't fully discarded.
1566 * Bail here and try again later after discarding everything.
1567 */
1568 spin_lock(&fs_info->discard_ctl.lock);
1569 if (!list_empty(&block_group->discard_list)) {
1570 spin_unlock(&fs_info->discard_ctl.lock);
1571 btrfs_dec_block_group_ro(block_group);
1572 btrfs_discard_queue_work(&fs_info->discard_ctl,
1573 block_group);
1574 goto end_trans;
1575 }
1576 spin_unlock(&fs_info->discard_ctl.lock);
1577
e3e0520b
JB
1578 /* Reset pinned so btrfs_put_block_group doesn't complain */
1579 spin_lock(&space_info->lock);
1580 spin_lock(&block_group->lock);
1581
1582 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1583 -block_group->pinned);
1584 space_info->bytes_readonly += block_group->pinned;
e3e0520b
JB
1585 block_group->pinned = 0;
1586
1587 spin_unlock(&block_group->lock);
1588 spin_unlock(&space_info->lock);
1589
6e80d4f8
DZ
1590 /*
1591 * The normal path here is an unused block group is passed here,
1592 * then trimming is handled in the transaction commit path.
1593 * Async discard interposes before this to do the trimming
1594 * before coming down the unused block group path as trimming
1595 * will no longer be done later in the transaction commit path.
1596 */
1597 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1598 goto flip_async;
1599
dcba6e48
NA
1600 /*
1601 * DISCARD can flip during remount. On zoned filesystems, we
1602 * need to reset sequential-required zones.
1603 */
1604 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC) ||
1605 btrfs_is_zoned(fs_info);
e3e0520b
JB
1606
1607 /* Implicit trim during transaction commit. */
1608 if (trimming)
6b7304af 1609 btrfs_freeze_block_group(block_group);
e3e0520b
JB
1610
1611 /*
1612 * Btrfs_remove_chunk will abort the transaction if things go
1613 * horribly wrong.
1614 */
b3470b5d 1615 ret = btrfs_remove_chunk(trans, block_group->start);
e3e0520b
JB
1616
1617 if (ret) {
1618 if (trimming)
6b7304af 1619 btrfs_unfreeze_block_group(block_group);
e3e0520b
JB
1620 goto end_trans;
1621 }
1622
1623 /*
1624 * If we're not mounted with -odiscard, we can just forget
1625 * about this block group. Otherwise we'll need to wait
1626 * until transaction commit to do the actual discard.
1627 */
1628 if (trimming) {
1629 spin_lock(&fs_info->unused_bgs_lock);
1630 /*
1631 * A concurrent scrub might have added us to the list
1632 * fs_info->unused_bgs, so use a list_move operation
1633 * to add the block group to the deleted_bgs list.
1634 */
1635 list_move(&block_group->bg_list,
1636 &trans->transaction->deleted_bgs);
1637 spin_unlock(&fs_info->unused_bgs_lock);
1638 btrfs_get_block_group(block_group);
1639 }
1640end_trans:
1641 btrfs_end_transaction(trans);
1642next:
e3e0520b
JB
1643 btrfs_put_block_group(block_group);
1644 spin_lock(&fs_info->unused_bgs_lock);
1645 }
1646 spin_unlock(&fs_info->unused_bgs_lock);
f3372065 1647 mutex_unlock(&fs_info->reclaim_bgs_lock);
6e80d4f8
DZ
1648 return;
1649
1650flip_async:
1651 btrfs_end_transaction(trans);
f3372065 1652 mutex_unlock(&fs_info->reclaim_bgs_lock);
6e80d4f8
DZ
1653 btrfs_put_block_group(block_group);
1654 btrfs_discard_punt_unused_bgs_list(fs_info);
e3e0520b
JB
1655}
1656
32da5386 1657void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
e3e0520b
JB
1658{
1659 struct btrfs_fs_info *fs_info = bg->fs_info;
1660
1661 spin_lock(&fs_info->unused_bgs_lock);
1662 if (list_empty(&bg->bg_list)) {
1663 btrfs_get_block_group(bg);
1664 trace_btrfs_add_unused_block_group(bg);
1665 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1666 }
1667 spin_unlock(&fs_info->unused_bgs_lock);
1668}
4358d963 1669
2ca0ec77
JT
1670/*
1671 * We want block groups with a low number of used bytes to be in the beginning
1672 * of the list, so they will get reclaimed first.
1673 */
1674static int reclaim_bgs_cmp(void *unused, const struct list_head *a,
1675 const struct list_head *b)
1676{
1677 const struct btrfs_block_group *bg1, *bg2;
1678
1679 bg1 = list_entry(a, struct btrfs_block_group, bg_list);
1680 bg2 = list_entry(b, struct btrfs_block_group, bg_list);
1681
1682 return bg1->used > bg2->used;
1683}
1684
3687fcb0
JT
1685static inline bool btrfs_should_reclaim(struct btrfs_fs_info *fs_info)
1686{
1687 if (btrfs_is_zoned(fs_info))
1688 return btrfs_zoned_should_reclaim(fs_info);
1689 return true;
1690}
1691
81531225
BB
1692static bool should_reclaim_block_group(struct btrfs_block_group *bg, u64 bytes_freed)
1693{
1694 const struct btrfs_space_info *space_info = bg->space_info;
1695 const int reclaim_thresh = READ_ONCE(space_info->bg_reclaim_threshold);
1696 const u64 new_val = bg->used;
1697 const u64 old_val = new_val + bytes_freed;
1698 u64 thresh;
1699
1700 if (reclaim_thresh == 0)
1701 return false;
1702
428c8e03 1703 thresh = mult_perc(bg->length, reclaim_thresh);
81531225
BB
1704
1705 /*
1706 * If we were below the threshold before don't reclaim, we are likely a
1707 * brand new block group and we don't want to relocate new block groups.
1708 */
1709 if (old_val < thresh)
1710 return false;
1711 if (new_val >= thresh)
1712 return false;
1713 return true;
1714}
1715
18bb8bbf
JT
1716void btrfs_reclaim_bgs_work(struct work_struct *work)
1717{
1718 struct btrfs_fs_info *fs_info =
1719 container_of(work, struct btrfs_fs_info, reclaim_bgs_work);
1720 struct btrfs_block_group *bg;
1721 struct btrfs_space_info *space_info;
18bb8bbf
JT
1722
1723 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1724 return;
1725
2f12741f
JB
1726 if (btrfs_fs_closing(fs_info))
1727 return;
1728
3687fcb0
JT
1729 if (!btrfs_should_reclaim(fs_info))
1730 return;
1731
ca5e4ea0
NA
1732 sb_start_write(fs_info->sb);
1733
1734 if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_BALANCE)) {
1735 sb_end_write(fs_info->sb);
18bb8bbf 1736 return;
ca5e4ea0 1737 }
18bb8bbf 1738
9cc0b837
JT
1739 /*
1740 * Long running balances can keep us blocked here for eternity, so
1741 * simply skip reclaim if we're unable to get the mutex.
1742 */
1743 if (!mutex_trylock(&fs_info->reclaim_bgs_lock)) {
1744 btrfs_exclop_finish(fs_info);
ca5e4ea0 1745 sb_end_write(fs_info->sb);
9cc0b837
JT
1746 return;
1747 }
1748
18bb8bbf 1749 spin_lock(&fs_info->unused_bgs_lock);
2ca0ec77
JT
1750 /*
1751 * Sort happens under lock because we can't simply splice it and sort.
1752 * The block groups might still be in use and reachable via bg_list,
1753 * and their presence in the reclaim_bgs list must be preserved.
1754 */
1755 list_sort(NULL, &fs_info->reclaim_bgs, reclaim_bgs_cmp);
18bb8bbf 1756 while (!list_empty(&fs_info->reclaim_bgs)) {
5f93e776 1757 u64 zone_unusable;
1cea5cf0
FM
1758 int ret = 0;
1759
18bb8bbf
JT
1760 bg = list_first_entry(&fs_info->reclaim_bgs,
1761 struct btrfs_block_group,
1762 bg_list);
1763 list_del_init(&bg->bg_list);
1764
1765 space_info = bg->space_info;
1766 spin_unlock(&fs_info->unused_bgs_lock);
1767
1768 /* Don't race with allocators so take the groups_sem */
1769 down_write(&space_info->groups_sem);
1770
1771 spin_lock(&bg->lock);
1772 if (bg->reserved || bg->pinned || bg->ro) {
1773 /*
1774 * We want to bail if we made new allocations or have
1775 * outstanding allocations in this block group. We do
1776 * the ro check in case balance is currently acting on
1777 * this block group.
1778 */
1779 spin_unlock(&bg->lock);
1780 up_write(&space_info->groups_sem);
1781 goto next;
1782 }
cc4804bf
BB
1783 if (bg->used == 0) {
1784 /*
1785 * It is possible that we trigger relocation on a block
1786 * group as its extents are deleted and it first goes
1787 * below the threshold, then shortly after goes empty.
1788 *
1789 * In this case, relocating it does delete it, but has
1790 * some overhead in relocation specific metadata, looking
1791 * for the non-existent extents and running some extra
1792 * transactions, which we can avoid by using one of the
1793 * other mechanisms for dealing with empty block groups.
1794 */
1795 if (!btrfs_test_opt(fs_info, DISCARD_ASYNC))
1796 btrfs_mark_bg_unused(bg);
1797 spin_unlock(&bg->lock);
1798 up_write(&space_info->groups_sem);
1799 goto next;
81531225
BB
1800
1801 }
1802 /*
1803 * The block group might no longer meet the reclaim condition by
1804 * the time we get around to reclaiming it, so to avoid
1805 * reclaiming overly full block_groups, skip reclaiming them.
1806 *
1807 * Since the decision making process also depends on the amount
1808 * being freed, pass in a fake giant value to skip that extra
1809 * check, which is more meaningful when adding to the list in
1810 * the first place.
1811 */
1812 if (!should_reclaim_block_group(bg, bg->length)) {
1813 spin_unlock(&bg->lock);
1814 up_write(&space_info->groups_sem);
1815 goto next;
cc4804bf 1816 }
18bb8bbf
JT
1817 spin_unlock(&bg->lock);
1818
1819 /* Get out fast, in case we're unmounting the filesystem */
1820 if (btrfs_fs_closing(fs_info)) {
1821 up_write(&space_info->groups_sem);
1822 goto next;
1823 }
1824
5f93e776
JT
1825 /*
1826 * Cache the zone_unusable value before turning the block group
1827 * to read only. As soon as the blog group is read only it's
1828 * zone_unusable value gets moved to the block group's read-only
1829 * bytes and isn't available for calculations anymore.
1830 */
1831 zone_unusable = bg->zone_unusable;
18bb8bbf
JT
1832 ret = inc_block_group_ro(bg, 0);
1833 up_write(&space_info->groups_sem);
1834 if (ret < 0)
1835 goto next;
1836
5f93e776
JT
1837 btrfs_info(fs_info,
1838 "reclaiming chunk %llu with %llu%% used %llu%% unusable",
1839 bg->start, div_u64(bg->used * 100, bg->length),
1840 div64_u64(zone_unusable * 100, bg->length));
18bb8bbf
JT
1841 trace_btrfs_reclaim_block_group(bg);
1842 ret = btrfs_relocate_chunk(fs_info, bg->start);
74944c87
JB
1843 if (ret) {
1844 btrfs_dec_block_group_ro(bg);
18bb8bbf
JT
1845 btrfs_err(fs_info, "error relocating chunk %llu",
1846 bg->start);
74944c87 1847 }
18bb8bbf
JT
1848
1849next:
d96b3424 1850 btrfs_put_block_group(bg);
18bb8bbf
JT
1851 spin_lock(&fs_info->unused_bgs_lock);
1852 }
1853 spin_unlock(&fs_info->unused_bgs_lock);
1854 mutex_unlock(&fs_info->reclaim_bgs_lock);
1855 btrfs_exclop_finish(fs_info);
ca5e4ea0 1856 sb_end_write(fs_info->sb);
18bb8bbf
JT
1857}
1858
1859void btrfs_reclaim_bgs(struct btrfs_fs_info *fs_info)
1860{
1861 spin_lock(&fs_info->unused_bgs_lock);
1862 if (!list_empty(&fs_info->reclaim_bgs))
1863 queue_work(system_unbound_wq, &fs_info->reclaim_bgs_work);
1864 spin_unlock(&fs_info->unused_bgs_lock);
1865}
1866
1867void btrfs_mark_bg_to_reclaim(struct btrfs_block_group *bg)
1868{
1869 struct btrfs_fs_info *fs_info = bg->fs_info;
1870
1871 spin_lock(&fs_info->unused_bgs_lock);
1872 if (list_empty(&bg->bg_list)) {
1873 btrfs_get_block_group(bg);
1874 trace_btrfs_add_reclaim_block_group(bg);
1875 list_add_tail(&bg->bg_list, &fs_info->reclaim_bgs);
1876 }
1877 spin_unlock(&fs_info->unused_bgs_lock);
1878}
1879
e3ba67a1
JT
1880static int read_bg_from_eb(struct btrfs_fs_info *fs_info, struct btrfs_key *key,
1881 struct btrfs_path *path)
1882{
1883 struct extent_map_tree *em_tree;
1884 struct extent_map *em;
1885 struct btrfs_block_group_item bg;
1886 struct extent_buffer *leaf;
1887 int slot;
1888 u64 flags;
1889 int ret = 0;
1890
1891 slot = path->slots[0];
1892 leaf = path->nodes[0];
1893
1894 em_tree = &fs_info->mapping_tree;
1895 read_lock(&em_tree->lock);
1896 em = lookup_extent_mapping(em_tree, key->objectid, key->offset);
1897 read_unlock(&em_tree->lock);
1898 if (!em) {
1899 btrfs_err(fs_info,
1900 "logical %llu len %llu found bg but no related chunk",
1901 key->objectid, key->offset);
1902 return -ENOENT;
1903 }
1904
1905 if (em->start != key->objectid || em->len != key->offset) {
1906 btrfs_err(fs_info,
1907 "block group %llu len %llu mismatch with chunk %llu len %llu",
1908 key->objectid, key->offset, em->start, em->len);
1909 ret = -EUCLEAN;
1910 goto out_free_em;
1911 }
1912
1913 read_extent_buffer(leaf, &bg, btrfs_item_ptr_offset(leaf, slot),
1914 sizeof(bg));
1915 flags = btrfs_stack_block_group_flags(&bg) &
1916 BTRFS_BLOCK_GROUP_TYPE_MASK;
1917
1918 if (flags != (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1919 btrfs_err(fs_info,
1920"block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1921 key->objectid, key->offset, flags,
1922 (BTRFS_BLOCK_GROUP_TYPE_MASK & em->map_lookup->type));
1923 ret = -EUCLEAN;
1924 }
1925
1926out_free_em:
1927 free_extent_map(em);
1928 return ret;
1929}
1930
4358d963
JB
1931static int find_first_block_group(struct btrfs_fs_info *fs_info,
1932 struct btrfs_path *path,
1933 struct btrfs_key *key)
1934{
dfe8aec4 1935 struct btrfs_root *root = btrfs_block_group_root(fs_info);
e3ba67a1 1936 int ret;
4358d963 1937 struct btrfs_key found_key;
4358d963 1938
36dfbbe2 1939 btrfs_for_each_slot(root, key, &found_key, path, ret) {
4358d963
JB
1940 if (found_key.objectid >= key->objectid &&
1941 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
36dfbbe2 1942 return read_bg_from_eb(fs_info, &found_key, path);
4358d963 1943 }
4358d963 1944 }
4358d963
JB
1945 return ret;
1946}
1947
1948static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1949{
1950 u64 extra_flags = chunk_to_extended(flags) &
1951 BTRFS_EXTENDED_PROFILE_MASK;
1952
1953 write_seqlock(&fs_info->profiles_lock);
1954 if (flags & BTRFS_BLOCK_GROUP_DATA)
1955 fs_info->avail_data_alloc_bits |= extra_flags;
1956 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1957 fs_info->avail_metadata_alloc_bits |= extra_flags;
1958 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1959 fs_info->avail_system_alloc_bits |= extra_flags;
1960 write_sequnlock(&fs_info->profiles_lock);
1961}
1962
43dd529a
DS
1963/*
1964 * Map a physical disk address to a list of logical addresses.
9ee9b979
NB
1965 *
1966 * @fs_info: the filesystem
96a14336 1967 * @chunk_start: logical address of block group
138082f3 1968 * @bdev: physical device to resolve, can be NULL to indicate any device
96a14336
NB
1969 * @physical: physical address to map to logical addresses
1970 * @logical: return array of logical addresses which map to @physical
1971 * @naddrs: length of @logical
1972 * @stripe_len: size of IO stripe for the given block group
1973 *
1974 * Maps a particular @physical disk address to a list of @logical addresses.
1975 * Used primarily to exclude those portions of a block group that contain super
1976 * block copies.
1977 */
96a14336 1978int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
138082f3
NA
1979 struct block_device *bdev, u64 physical, u64 **logical,
1980 int *naddrs, int *stripe_len)
96a14336
NB
1981{
1982 struct extent_map *em;
1983 struct map_lookup *map;
1984 u64 *buf;
1985 u64 bytenr;
1776ad17
NB
1986 u64 data_stripe_length;
1987 u64 io_stripe_size;
1988 int i, nr = 0;
1989 int ret = 0;
96a14336
NB
1990
1991 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1992 if (IS_ERR(em))
1993 return -EIO;
1994
1995 map = em->map_lookup;
9e22b925 1996 data_stripe_length = em->orig_block_len;
1776ad17 1997 io_stripe_size = map->stripe_len;
138082f3 1998 chunk_start = em->start;
96a14336 1999
9e22b925
NB
2000 /* For RAID5/6 adjust to a full IO stripe length */
2001 if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK)
1776ad17 2002 io_stripe_size = map->stripe_len * nr_data_stripes(map);
96a14336
NB
2003
2004 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
1776ad17
NB
2005 if (!buf) {
2006 ret = -ENOMEM;
2007 goto out;
2008 }
96a14336
NB
2009
2010 for (i = 0; i < map->num_stripes; i++) {
1776ad17
NB
2011 bool already_inserted = false;
2012 u64 stripe_nr;
138082f3 2013 u64 offset;
1776ad17
NB
2014 int j;
2015
2016 if (!in_range(physical, map->stripes[i].physical,
2017 data_stripe_length))
96a14336
NB
2018 continue;
2019
138082f3
NA
2020 if (bdev && map->stripes[i].dev->bdev != bdev)
2021 continue;
2022
96a14336 2023 stripe_nr = physical - map->stripes[i].physical;
138082f3 2024 stripe_nr = div64_u64_rem(stripe_nr, map->stripe_len, &offset);
96a14336 2025
ac067734
DS
2026 if (map->type & (BTRFS_BLOCK_GROUP_RAID0 |
2027 BTRFS_BLOCK_GROUP_RAID10)) {
96a14336
NB
2028 stripe_nr = stripe_nr * map->num_stripes + i;
2029 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
96a14336
NB
2030 }
2031 /*
2032 * The remaining case would be for RAID56, multiply by
2033 * nr_data_stripes(). Alternatively, just use rmap_len below
2034 * instead of map->stripe_len
2035 */
2036
138082f3 2037 bytenr = chunk_start + stripe_nr * io_stripe_size + offset;
1776ad17
NB
2038
2039 /* Ensure we don't add duplicate addresses */
96a14336 2040 for (j = 0; j < nr; j++) {
1776ad17
NB
2041 if (buf[j] == bytenr) {
2042 already_inserted = true;
96a14336 2043 break;
1776ad17 2044 }
96a14336 2045 }
1776ad17
NB
2046
2047 if (!already_inserted)
96a14336 2048 buf[nr++] = bytenr;
96a14336
NB
2049 }
2050
2051 *logical = buf;
2052 *naddrs = nr;
1776ad17
NB
2053 *stripe_len = io_stripe_size;
2054out:
96a14336 2055 free_extent_map(em);
1776ad17 2056 return ret;
96a14336
NB
2057}
2058
32da5386 2059static int exclude_super_stripes(struct btrfs_block_group *cache)
4358d963
JB
2060{
2061 struct btrfs_fs_info *fs_info = cache->fs_info;
12659251 2062 const bool zoned = btrfs_is_zoned(fs_info);
4358d963
JB
2063 u64 bytenr;
2064 u64 *logical;
2065 int stripe_len;
2066 int i, nr, ret;
2067
b3470b5d
DS
2068 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
2069 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
4358d963 2070 cache->bytes_super += stripe_len;
b3470b5d 2071 ret = btrfs_add_excluded_extent(fs_info, cache->start,
4358d963
JB
2072 stripe_len);
2073 if (ret)
2074 return ret;
2075 }
2076
2077 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
2078 bytenr = btrfs_sb_offset(i);
138082f3 2079 ret = btrfs_rmap_block(fs_info, cache->start, NULL,
4358d963
JB
2080 bytenr, &logical, &nr, &stripe_len);
2081 if (ret)
2082 return ret;
2083
12659251
NA
2084 /* Shouldn't have super stripes in sequential zones */
2085 if (zoned && nr) {
2086 btrfs_err(fs_info,
2087 "zoned: block group %llu must not contain super block",
2088 cache->start);
2089 return -EUCLEAN;
2090 }
2091
4358d963 2092 while (nr--) {
96f9b0f2
NB
2093 u64 len = min_t(u64, stripe_len,
2094 cache->start + cache->length - logical[nr]);
4358d963
JB
2095
2096 cache->bytes_super += len;
96f9b0f2
NB
2097 ret = btrfs_add_excluded_extent(fs_info, logical[nr],
2098 len);
4358d963
JB
2099 if (ret) {
2100 kfree(logical);
2101 return ret;
2102 }
2103 }
2104
2105 kfree(logical);
2106 }
2107 return 0;
2108}
2109
32da5386 2110static struct btrfs_block_group *btrfs_create_block_group_cache(
9afc6649 2111 struct btrfs_fs_info *fs_info, u64 start)
4358d963 2112{
32da5386 2113 struct btrfs_block_group *cache;
4358d963
JB
2114
2115 cache = kzalloc(sizeof(*cache), GFP_NOFS);
2116 if (!cache)
2117 return NULL;
2118
2119 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
2120 GFP_NOFS);
2121 if (!cache->free_space_ctl) {
2122 kfree(cache);
2123 return NULL;
2124 }
2125
b3470b5d 2126 cache->start = start;
4358d963
JB
2127
2128 cache->fs_info = fs_info;
2129 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
4358d963 2130
6e80d4f8
DZ
2131 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
2132
48aaeebe 2133 refcount_set(&cache->refs, 1);
4358d963
JB
2134 spin_lock_init(&cache->lock);
2135 init_rwsem(&cache->data_rwsem);
2136 INIT_LIST_HEAD(&cache->list);
2137 INIT_LIST_HEAD(&cache->cluster_list);
2138 INIT_LIST_HEAD(&cache->bg_list);
2139 INIT_LIST_HEAD(&cache->ro_list);
b0643e59 2140 INIT_LIST_HEAD(&cache->discard_list);
4358d963
JB
2141 INIT_LIST_HEAD(&cache->dirty_list);
2142 INIT_LIST_HEAD(&cache->io_list);
afba2bc0 2143 INIT_LIST_HEAD(&cache->active_bg_list);
cd79909b 2144 btrfs_init_free_space_ctl(cache, cache->free_space_ctl);
6b7304af 2145 atomic_set(&cache->frozen, 0);
4358d963 2146 mutex_init(&cache->free_space_lock);
c29abab4
JB
2147 cache->full_stripe_locks_root.root = RB_ROOT;
2148 mutex_init(&cache->full_stripe_locks_root.lock);
4358d963
JB
2149
2150 return cache;
2151}
2152
2153/*
2154 * Iterate all chunks and verify that each of them has the corresponding block
2155 * group
2156 */
2157static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
2158{
2159 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
2160 struct extent_map *em;
32da5386 2161 struct btrfs_block_group *bg;
4358d963
JB
2162 u64 start = 0;
2163 int ret = 0;
2164
2165 while (1) {
2166 read_lock(&map_tree->lock);
2167 /*
2168 * lookup_extent_mapping will return the first extent map
2169 * intersecting the range, so setting @len to 1 is enough to
2170 * get the first chunk.
2171 */
2172 em = lookup_extent_mapping(map_tree, start, 1);
2173 read_unlock(&map_tree->lock);
2174 if (!em)
2175 break;
2176
2177 bg = btrfs_lookup_block_group(fs_info, em->start);
2178 if (!bg) {
2179 btrfs_err(fs_info,
2180 "chunk start=%llu len=%llu doesn't have corresponding block group",
2181 em->start, em->len);
2182 ret = -EUCLEAN;
2183 free_extent_map(em);
2184 break;
2185 }
b3470b5d 2186 if (bg->start != em->start || bg->length != em->len ||
4358d963
JB
2187 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
2188 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
2189 btrfs_err(fs_info,
2190"chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
2191 em->start, em->len,
2192 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
b3470b5d 2193 bg->start, bg->length,
4358d963
JB
2194 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
2195 ret = -EUCLEAN;
2196 free_extent_map(em);
2197 btrfs_put_block_group(bg);
2198 break;
2199 }
2200 start = em->start + em->len;
2201 free_extent_map(em);
2202 btrfs_put_block_group(bg);
2203 }
2204 return ret;
2205}
2206
ffb9e0f0 2207static int read_one_block_group(struct btrfs_fs_info *info,
4afd2fe8 2208 struct btrfs_block_group_item *bgi,
d49a2ddb 2209 const struct btrfs_key *key,
ffb9e0f0
QW
2210 int need_clear)
2211{
32da5386 2212 struct btrfs_block_group *cache;
ffb9e0f0 2213 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
ffb9e0f0
QW
2214 int ret;
2215
d49a2ddb 2216 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
ffb9e0f0 2217
9afc6649 2218 cache = btrfs_create_block_group_cache(info, key->objectid);
ffb9e0f0
QW
2219 if (!cache)
2220 return -ENOMEM;
2221
4afd2fe8
JT
2222 cache->length = key->offset;
2223 cache->used = btrfs_stack_block_group_used(bgi);
7248e0ce 2224 cache->commit_used = cache->used;
4afd2fe8 2225 cache->flags = btrfs_stack_block_group_flags(bgi);
f7238e50 2226 cache->global_root_id = btrfs_stack_block_group_chunk_objectid(bgi);
9afc6649 2227
e3e39c72
MPS
2228 set_free_space_tree_thresholds(cache);
2229
ffb9e0f0
QW
2230 if (need_clear) {
2231 /*
2232 * When we mount with old space cache, we need to
2233 * set BTRFS_DC_CLEAR and set dirty flag.
2234 *
2235 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
2236 * truncate the old free space cache inode and
2237 * setup a new one.
2238 * b) Setting 'dirty flag' makes sure that we flush
2239 * the new space cache info onto disk.
2240 */
2241 if (btrfs_test_opt(info, SPACE_CACHE))
2242 cache->disk_cache_state = BTRFS_DC_CLEAR;
2243 }
ffb9e0f0
QW
2244 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
2245 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
2246 btrfs_err(info,
2247"bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
2248 cache->start);
2249 ret = -EINVAL;
2250 goto error;
2251 }
2252
a94794d5 2253 ret = btrfs_load_block_group_zone_info(cache, false);
08e11a3d
NA
2254 if (ret) {
2255 btrfs_err(info, "zoned: failed to load zone info of bg %llu",
2256 cache->start);
2257 goto error;
2258 }
2259
ffb9e0f0
QW
2260 /*
2261 * We need to exclude the super stripes now so that the space info has
2262 * super bytes accounted for, otherwise we'll think we have more space
2263 * than we actually do.
2264 */
2265 ret = exclude_super_stripes(cache);
2266 if (ret) {
2267 /* We may have excluded something, so call this just in case. */
2268 btrfs_free_excluded_extents(cache);
2269 goto error;
2270 }
2271
2272 /*
169e0da9
NA
2273 * For zoned filesystem, space after the allocation offset is the only
2274 * free space for a block group. So, we don't need any caching work.
2275 * btrfs_calc_zone_unusable() will set the amount of free space and
2276 * zone_unusable space.
2277 *
2278 * For regular filesystem, check for two cases, either we are full, and
2279 * therefore don't need to bother with the caching work since we won't
2280 * find any space, or we are empty, and we can just add all the space
2281 * in and be done with it. This saves us _a_lot_ of time, particularly
2282 * in the full case.
ffb9e0f0 2283 */
169e0da9
NA
2284 if (btrfs_is_zoned(info)) {
2285 btrfs_calc_zone_unusable(cache);
c46c4247
NA
2286 /* Should not have any excluded extents. Just in case, though. */
2287 btrfs_free_excluded_extents(cache);
169e0da9 2288 } else if (cache->length == cache->used) {
ffb9e0f0
QW
2289 cache->cached = BTRFS_CACHE_FINISHED;
2290 btrfs_free_excluded_extents(cache);
2291 } else if (cache->used == 0) {
ffb9e0f0 2292 cache->cached = BTRFS_CACHE_FINISHED;
9afc6649
QW
2293 add_new_free_space(cache, cache->start,
2294 cache->start + cache->length);
ffb9e0f0
QW
2295 btrfs_free_excluded_extents(cache);
2296 }
2297
2298 ret = btrfs_add_block_group_cache(info, cache);
2299 if (ret) {
2300 btrfs_remove_free_space_cache(cache);
2301 goto error;
2302 }
2303 trace_btrfs_add_block_group(info, cache, 0);
723de71d 2304 btrfs_add_bg_to_space_info(info, cache);
ffb9e0f0
QW
2305
2306 set_avail_alloc_bits(info, cache->flags);
a09f23c3
AJ
2307 if (btrfs_chunk_writeable(info, cache->start)) {
2308 if (cache->used == 0) {
2309 ASSERT(list_empty(&cache->bg_list));
2310 if (btrfs_test_opt(info, DISCARD_ASYNC))
2311 btrfs_discard_queue_work(&info->discard_ctl, cache);
2312 else
2313 btrfs_mark_bg_unused(cache);
2314 }
2315 } else {
ffb9e0f0 2316 inc_block_group_ro(cache, 1);
ffb9e0f0 2317 }
a09f23c3 2318
ffb9e0f0
QW
2319 return 0;
2320error:
2321 btrfs_put_block_group(cache);
2322 return ret;
2323}
2324
42437a63
JB
2325static int fill_dummy_bgs(struct btrfs_fs_info *fs_info)
2326{
2327 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
42437a63
JB
2328 struct rb_node *node;
2329 int ret = 0;
2330
2331 for (node = rb_first_cached(&em_tree->map); node; node = rb_next(node)) {
2332 struct extent_map *em;
2333 struct map_lookup *map;
2334 struct btrfs_block_group *bg;
2335
2336 em = rb_entry(node, struct extent_map, rb_node);
2337 map = em->map_lookup;
2338 bg = btrfs_create_block_group_cache(fs_info, em->start);
2339 if (!bg) {
2340 ret = -ENOMEM;
2341 break;
2342 }
2343
2344 /* Fill dummy cache as FULL */
2345 bg->length = em->len;
2346 bg->flags = map->type;
42437a63
JB
2347 bg->cached = BTRFS_CACHE_FINISHED;
2348 bg->used = em->len;
2349 bg->flags = map->type;
2350 ret = btrfs_add_block_group_cache(fs_info, bg);
2b29726c
QW
2351 /*
2352 * We may have some valid block group cache added already, in
2353 * that case we skip to the next one.
2354 */
2355 if (ret == -EEXIST) {
2356 ret = 0;
2357 btrfs_put_block_group(bg);
2358 continue;
2359 }
2360
42437a63
JB
2361 if (ret) {
2362 btrfs_remove_free_space_cache(bg);
2363 btrfs_put_block_group(bg);
2364 break;
2365 }
2b29726c 2366
723de71d 2367 btrfs_add_bg_to_space_info(fs_info, bg);
42437a63
JB
2368
2369 set_avail_alloc_bits(fs_info, bg->flags);
2370 }
2371 if (!ret)
2372 btrfs_init_global_block_rsv(fs_info);
2373 return ret;
2374}
2375
4358d963
JB
2376int btrfs_read_block_groups(struct btrfs_fs_info *info)
2377{
dfe8aec4 2378 struct btrfs_root *root = btrfs_block_group_root(info);
4358d963
JB
2379 struct btrfs_path *path;
2380 int ret;
32da5386 2381 struct btrfs_block_group *cache;
4358d963
JB
2382 struct btrfs_space_info *space_info;
2383 struct btrfs_key key;
4358d963
JB
2384 int need_clear = 0;
2385 u64 cache_gen;
4358d963 2386
81d5d614
QW
2387 /*
2388 * Either no extent root (with ibadroots rescue option) or we have
2389 * unsupported RO options. The fs can never be mounted read-write, so no
2390 * need to waste time searching block group items.
2391 *
2392 * This also allows new extent tree related changes to be RO compat,
2393 * no need for a full incompat flag.
2394 */
2395 if (!root || (btrfs_super_compat_ro_flags(info->super_copy) &
2396 ~BTRFS_FEATURE_COMPAT_RO_SUPP))
42437a63
JB
2397 return fill_dummy_bgs(info);
2398
4358d963
JB
2399 key.objectid = 0;
2400 key.offset = 0;
2401 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2402 path = btrfs_alloc_path();
2403 if (!path)
2404 return -ENOMEM;
4358d963
JB
2405
2406 cache_gen = btrfs_super_cache_generation(info->super_copy);
2407 if (btrfs_test_opt(info, SPACE_CACHE) &&
2408 btrfs_super_generation(info->super_copy) != cache_gen)
2409 need_clear = 1;
2410 if (btrfs_test_opt(info, CLEAR_CACHE))
2411 need_clear = 1;
2412
2413 while (1) {
4afd2fe8
JT
2414 struct btrfs_block_group_item bgi;
2415 struct extent_buffer *leaf;
2416 int slot;
2417
4358d963
JB
2418 ret = find_first_block_group(info, path, &key);
2419 if (ret > 0)
2420 break;
2421 if (ret != 0)
2422 goto error;
2423
4afd2fe8
JT
2424 leaf = path->nodes[0];
2425 slot = path->slots[0];
2426
2427 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
2428 sizeof(bgi));
2429
2430 btrfs_item_key_to_cpu(leaf, &key, slot);
2431 btrfs_release_path(path);
2432 ret = read_one_block_group(info, &bgi, &key, need_clear);
ffb9e0f0 2433 if (ret < 0)
4358d963 2434 goto error;
ffb9e0f0
QW
2435 key.objectid += key.offset;
2436 key.offset = 0;
4358d963 2437 }
7837fa88 2438 btrfs_release_path(path);
4358d963 2439
72804905 2440 list_for_each_entry(space_info, &info->space_info, list) {
49ea112d
JB
2441 int i;
2442
2443 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
2444 if (list_empty(&space_info->block_groups[i]))
2445 continue;
2446 cache = list_first_entry(&space_info->block_groups[i],
2447 struct btrfs_block_group,
2448 list);
2449 btrfs_sysfs_add_block_group_type(cache);
2450 }
2451
4358d963
JB
2452 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2453 (BTRFS_BLOCK_GROUP_RAID10 |
2454 BTRFS_BLOCK_GROUP_RAID1_MASK |
2455 BTRFS_BLOCK_GROUP_RAID56_MASK |
2456 BTRFS_BLOCK_GROUP_DUP)))
2457 continue;
2458 /*
2459 * Avoid allocating from un-mirrored block group if there are
2460 * mirrored block groups.
2461 */
2462 list_for_each_entry(cache,
2463 &space_info->block_groups[BTRFS_RAID_RAID0],
2464 list)
e11c0406 2465 inc_block_group_ro(cache, 1);
4358d963
JB
2466 list_for_each_entry(cache,
2467 &space_info->block_groups[BTRFS_RAID_SINGLE],
2468 list)
e11c0406 2469 inc_block_group_ro(cache, 1);
4358d963
JB
2470 }
2471
2472 btrfs_init_global_block_rsv(info);
2473 ret = check_chunk_block_group_mappings(info);
2474error:
2475 btrfs_free_path(path);
2b29726c
QW
2476 /*
2477 * We've hit some error while reading the extent tree, and have
2478 * rescue=ibadroots mount option.
2479 * Try to fill the tree using dummy block groups so that the user can
2480 * continue to mount and grab their data.
2481 */
2482 if (ret && btrfs_test_opt(info, IGNOREBADROOTS))
2483 ret = fill_dummy_bgs(info);
4358d963
JB
2484 return ret;
2485}
2486
79bd3712
FM
2487/*
2488 * This function, insert_block_group_item(), belongs to the phase 2 of chunk
2489 * allocation.
2490 *
2491 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2492 * phases.
2493 */
97f4728a
QW
2494static int insert_block_group_item(struct btrfs_trans_handle *trans,
2495 struct btrfs_block_group *block_group)
2496{
2497 struct btrfs_fs_info *fs_info = trans->fs_info;
2498 struct btrfs_block_group_item bgi;
dfe8aec4 2499 struct btrfs_root *root = btrfs_block_group_root(fs_info);
97f4728a
QW
2500 struct btrfs_key key;
2501
2502 spin_lock(&block_group->lock);
2503 btrfs_set_stack_block_group_used(&bgi, block_group->used);
2504 btrfs_set_stack_block_group_chunk_objectid(&bgi,
f7238e50 2505 block_group->global_root_id);
97f4728a
QW
2506 btrfs_set_stack_block_group_flags(&bgi, block_group->flags);
2507 key.objectid = block_group->start;
2508 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2509 key.offset = block_group->length;
2510 spin_unlock(&block_group->lock);
2511
97f4728a
QW
2512 return btrfs_insert_item(trans, root, &key, &bgi, sizeof(bgi));
2513}
2514
2eadb9e7
NB
2515static int insert_dev_extent(struct btrfs_trans_handle *trans,
2516 struct btrfs_device *device, u64 chunk_offset,
2517 u64 start, u64 num_bytes)
2518{
2519 struct btrfs_fs_info *fs_info = device->fs_info;
2520 struct btrfs_root *root = fs_info->dev_root;
2521 struct btrfs_path *path;
2522 struct btrfs_dev_extent *extent;
2523 struct extent_buffer *leaf;
2524 struct btrfs_key key;
2525 int ret;
2526
2527 WARN_ON(!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &device->dev_state));
2528 WARN_ON(test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state));
2529 path = btrfs_alloc_path();
2530 if (!path)
2531 return -ENOMEM;
2532
2533 key.objectid = device->devid;
2534 key.type = BTRFS_DEV_EXTENT_KEY;
2535 key.offset = start;
2536 ret = btrfs_insert_empty_item(trans, root, path, &key, sizeof(*extent));
2537 if (ret)
2538 goto out;
2539
2540 leaf = path->nodes[0];
2541 extent = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dev_extent);
2542 btrfs_set_dev_extent_chunk_tree(leaf, extent, BTRFS_CHUNK_TREE_OBJECTID);
2543 btrfs_set_dev_extent_chunk_objectid(leaf, extent,
2544 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
2545 btrfs_set_dev_extent_chunk_offset(leaf, extent, chunk_offset);
2546
2547 btrfs_set_dev_extent_length(leaf, extent, num_bytes);
2548 btrfs_mark_buffer_dirty(leaf);
2549out:
2550 btrfs_free_path(path);
2551 return ret;
2552}
2553
2554/*
2555 * This function belongs to phase 2.
2556 *
2557 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2558 * phases.
2559 */
2560static int insert_dev_extents(struct btrfs_trans_handle *trans,
2561 u64 chunk_offset, u64 chunk_size)
2562{
2563 struct btrfs_fs_info *fs_info = trans->fs_info;
2564 struct btrfs_device *device;
2565 struct extent_map *em;
2566 struct map_lookup *map;
2567 u64 dev_offset;
2568 u64 stripe_size;
2569 int i;
2570 int ret = 0;
2571
2572 em = btrfs_get_chunk_map(fs_info, chunk_offset, chunk_size);
2573 if (IS_ERR(em))
2574 return PTR_ERR(em);
2575
2576 map = em->map_lookup;
2577 stripe_size = em->orig_block_len;
2578
2579 /*
2580 * Take the device list mutex to prevent races with the final phase of
2581 * a device replace operation that replaces the device object associated
2582 * with the map's stripes, because the device object's id can change
2583 * at any time during that final phase of the device replace operation
2584 * (dev-replace.c:btrfs_dev_replace_finishing()), so we could grab the
2585 * replaced device and then see it with an ID of BTRFS_DEV_REPLACE_DEVID,
2586 * resulting in persisting a device extent item with such ID.
2587 */
2588 mutex_lock(&fs_info->fs_devices->device_list_mutex);
2589 for (i = 0; i < map->num_stripes; i++) {
2590 device = map->stripes[i].dev;
2591 dev_offset = map->stripes[i].physical;
2592
2593 ret = insert_dev_extent(trans, device, chunk_offset, dev_offset,
2594 stripe_size);
2595 if (ret)
2596 break;
2597 }
2598 mutex_unlock(&fs_info->fs_devices->device_list_mutex);
2599
2600 free_extent_map(em);
2601 return ret;
2602}
2603
79bd3712
FM
2604/*
2605 * This function, btrfs_create_pending_block_groups(), belongs to the phase 2 of
2606 * chunk allocation.
2607 *
2608 * See the comment at btrfs_chunk_alloc() for details about the chunk allocation
2609 * phases.
2610 */
4358d963
JB
2611void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2612{
2613 struct btrfs_fs_info *fs_info = trans->fs_info;
32da5386 2614 struct btrfs_block_group *block_group;
4358d963
JB
2615 int ret = 0;
2616
4358d963 2617 while (!list_empty(&trans->new_bgs)) {
49ea112d
JB
2618 int index;
2619
4358d963 2620 block_group = list_first_entry(&trans->new_bgs,
32da5386 2621 struct btrfs_block_group,
4358d963
JB
2622 bg_list);
2623 if (ret)
2624 goto next;
2625
49ea112d
JB
2626 index = btrfs_bg_flags_to_raid_index(block_group->flags);
2627
97f4728a 2628 ret = insert_block_group_item(trans, block_group);
4358d963
JB
2629 if (ret)
2630 btrfs_abort_transaction(trans, ret);
3349b57f
JB
2631 if (!test_bit(BLOCK_GROUP_FLAG_CHUNK_ITEM_INSERTED,
2632 &block_group->runtime_flags)) {
79bd3712
FM
2633 mutex_lock(&fs_info->chunk_mutex);
2634 ret = btrfs_chunk_alloc_add_chunk_item(trans, block_group);
2635 mutex_unlock(&fs_info->chunk_mutex);
2636 if (ret)
2637 btrfs_abort_transaction(trans, ret);
2638 }
2eadb9e7
NB
2639 ret = insert_dev_extents(trans, block_group->start,
2640 block_group->length);
4358d963
JB
2641 if (ret)
2642 btrfs_abort_transaction(trans, ret);
2643 add_block_group_free_space(trans, block_group);
49ea112d
JB
2644
2645 /*
2646 * If we restriped during balance, we may have added a new raid
2647 * type, so now add the sysfs entries when it is safe to do so.
2648 * We don't have to worry about locking here as it's handled in
2649 * btrfs_sysfs_add_block_group_type.
2650 */
2651 if (block_group->space_info->block_group_kobjs[index] == NULL)
2652 btrfs_sysfs_add_block_group_type(block_group);
2653
4358d963
JB
2654 /* Already aborted the transaction if it failed. */
2655next:
2656 btrfs_delayed_refs_rsv_release(fs_info, 1);
2657 list_del_init(&block_group->bg_list);
2658 }
2659 btrfs_trans_release_chunk_metadata(trans);
2660}
2661
f7238e50
JB
2662/*
2663 * For extent tree v2 we use the block_group_item->chunk_offset to point at our
2664 * global root id. For v1 it's always set to BTRFS_FIRST_CHUNK_TREE_OBJECTID.
2665 */
2666static u64 calculate_global_root_id(struct btrfs_fs_info *fs_info, u64 offset)
2667{
2668 u64 div = SZ_1G;
2669 u64 index;
2670
2671 if (!btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))
2672 return BTRFS_FIRST_CHUNK_TREE_OBJECTID;
2673
2674 /* If we have a smaller fs index based on 128MiB. */
2675 if (btrfs_super_total_bytes(fs_info->super_copy) <= (SZ_1G * 10ULL))
2676 div = SZ_128M;
2677
2678 offset = div64_u64(offset, div);
2679 div64_u64_rem(offset, fs_info->nr_global_roots, &index);
2680 return index;
2681}
2682
79bd3712
FM
2683struct btrfs_block_group *btrfs_make_block_group(struct btrfs_trans_handle *trans,
2684 u64 bytes_used, u64 type,
2685 u64 chunk_offset, u64 size)
4358d963
JB
2686{
2687 struct btrfs_fs_info *fs_info = trans->fs_info;
32da5386 2688 struct btrfs_block_group *cache;
4358d963
JB
2689 int ret;
2690
2691 btrfs_set_log_full_commit(trans);
2692
9afc6649 2693 cache = btrfs_create_block_group_cache(fs_info, chunk_offset);
4358d963 2694 if (!cache)
79bd3712 2695 return ERR_PTR(-ENOMEM);
4358d963 2696
9afc6649 2697 cache->length = size;
e3e39c72 2698 set_free_space_tree_thresholds(cache);
bf38be65 2699 cache->used = bytes_used;
4358d963 2700 cache->flags = type;
4358d963 2701 cache->cached = BTRFS_CACHE_FINISHED;
f7238e50
JB
2702 cache->global_root_id = calculate_global_root_id(fs_info, cache->start);
2703
997e3e2e 2704 if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
0d7764ff 2705 set_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &cache->runtime_flags);
08e11a3d 2706
a94794d5 2707 ret = btrfs_load_block_group_zone_info(cache, true);
08e11a3d
NA
2708 if (ret) {
2709 btrfs_put_block_group(cache);
79bd3712 2710 return ERR_PTR(ret);
08e11a3d
NA
2711 }
2712
4358d963
JB
2713 ret = exclude_super_stripes(cache);
2714 if (ret) {
2715 /* We may have excluded something, so call this just in case */
2716 btrfs_free_excluded_extents(cache);
2717 btrfs_put_block_group(cache);
79bd3712 2718 return ERR_PTR(ret);
4358d963
JB
2719 }
2720
2721 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2722
2723 btrfs_free_excluded_extents(cache);
2724
4358d963
JB
2725 /*
2726 * Ensure the corresponding space_info object is created and
2727 * assigned to our block group. We want our bg to be added to the rbtree
2728 * with its ->space_info set.
2729 */
2730 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2731 ASSERT(cache->space_info);
2732
2733 ret = btrfs_add_block_group_cache(fs_info, cache);
2734 if (ret) {
2735 btrfs_remove_free_space_cache(cache);
2736 btrfs_put_block_group(cache);
79bd3712 2737 return ERR_PTR(ret);
4358d963
JB
2738 }
2739
2740 /*
2741 * Now that our block group has its ->space_info set and is inserted in
2742 * the rbtree, update the space info's counters.
2743 */
2744 trace_btrfs_add_block_group(fs_info, cache, 1);
723de71d 2745 btrfs_add_bg_to_space_info(fs_info, cache);
4358d963
JB
2746 btrfs_update_global_block_rsv(fs_info);
2747
9d4b0a12
JB
2748#ifdef CONFIG_BTRFS_DEBUG
2749 if (btrfs_should_fragment_free_space(cache)) {
2750 u64 new_bytes_used = size - bytes_used;
2751
2752 cache->space_info->bytes_used += new_bytes_used >> 1;
2753 fragment_free_space(cache);
2754 }
2755#endif
4358d963
JB
2756
2757 list_add_tail(&cache->bg_list, &trans->new_bgs);
2758 trans->delayed_ref_updates++;
2759 btrfs_update_delayed_refs_rsv(trans);
2760
2761 set_avail_alloc_bits(fs_info, type);
79bd3712 2762 return cache;
4358d963 2763}
26ce2095 2764
b12de528
QW
2765/*
2766 * Mark one block group RO, can be called several times for the same block
2767 * group.
2768 *
2769 * @cache: the destination block group
2770 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2771 * ensure we still have some free space after marking this
2772 * block group RO.
2773 */
2774int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2775 bool do_chunk_alloc)
26ce2095
JB
2776{
2777 struct btrfs_fs_info *fs_info = cache->fs_info;
2778 struct btrfs_trans_handle *trans;
dfe8aec4 2779 struct btrfs_root *root = btrfs_block_group_root(fs_info);
26ce2095
JB
2780 u64 alloc_flags;
2781 int ret;
b6e9f16c 2782 bool dirty_bg_running;
26ce2095 2783
2d192fc4
QW
2784 /*
2785 * This can only happen when we are doing read-only scrub on read-only
2786 * mount.
2787 * In that case we should not start a new transaction on read-only fs.
2788 * Thus here we skip all chunk allocations.
2789 */
2790 if (sb_rdonly(fs_info->sb)) {
2791 mutex_lock(&fs_info->ro_block_group_mutex);
2792 ret = inc_block_group_ro(cache, 0);
2793 mutex_unlock(&fs_info->ro_block_group_mutex);
2794 return ret;
2795 }
2796
b6e9f16c 2797 do {
dfe8aec4 2798 trans = btrfs_join_transaction(root);
b6e9f16c
NB
2799 if (IS_ERR(trans))
2800 return PTR_ERR(trans);
26ce2095 2801
b6e9f16c 2802 dirty_bg_running = false;
26ce2095 2803
b6e9f16c
NB
2804 /*
2805 * We're not allowed to set block groups readonly after the dirty
2806 * block group cache has started writing. If it already started,
2807 * back off and let this transaction commit.
2808 */
2809 mutex_lock(&fs_info->ro_block_group_mutex);
2810 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2811 u64 transid = trans->transid;
26ce2095 2812
b6e9f16c
NB
2813 mutex_unlock(&fs_info->ro_block_group_mutex);
2814 btrfs_end_transaction(trans);
2815
2816 ret = btrfs_wait_for_commit(fs_info, transid);
2817 if (ret)
2818 return ret;
2819 dirty_bg_running = true;
2820 }
2821 } while (dirty_bg_running);
26ce2095 2822
b12de528 2823 if (do_chunk_alloc) {
26ce2095 2824 /*
b12de528
QW
2825 * If we are changing raid levels, try to allocate a
2826 * corresponding block group with the new raid level.
26ce2095 2827 */
349e120e 2828 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
b12de528
QW
2829 if (alloc_flags != cache->flags) {
2830 ret = btrfs_chunk_alloc(trans, alloc_flags,
2831 CHUNK_ALLOC_FORCE);
2832 /*
2833 * ENOSPC is allowed here, we may have enough space
2834 * already allocated at the new raid level to carry on
2835 */
2836 if (ret == -ENOSPC)
2837 ret = 0;
2838 if (ret < 0)
2839 goto out;
2840 }
26ce2095
JB
2841 }
2842
a7a63acc 2843 ret = inc_block_group_ro(cache, 0);
195a49ea 2844 if (!do_chunk_alloc || ret == -ETXTBSY)
b12de528 2845 goto unlock_out;
26ce2095
JB
2846 if (!ret)
2847 goto out;
2848 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2849 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2850 if (ret < 0)
2851 goto out;
b6a98021
NA
2852 /*
2853 * We have allocated a new chunk. We also need to activate that chunk to
2854 * grant metadata tickets for zoned filesystem.
2855 */
2856 ret = btrfs_zoned_activate_one_bg(fs_info, cache->space_info, true);
2857 if (ret < 0)
2858 goto out;
2859
e11c0406 2860 ret = inc_block_group_ro(cache, 0);
195a49ea
FM
2861 if (ret == -ETXTBSY)
2862 goto unlock_out;
26ce2095
JB
2863out:
2864 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
349e120e 2865 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->flags);
26ce2095
JB
2866 mutex_lock(&fs_info->chunk_mutex);
2867 check_system_chunk(trans, alloc_flags);
2868 mutex_unlock(&fs_info->chunk_mutex);
2869 }
b12de528 2870unlock_out:
26ce2095
JB
2871 mutex_unlock(&fs_info->ro_block_group_mutex);
2872
2873 btrfs_end_transaction(trans);
2874 return ret;
2875}
2876
32da5386 2877void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
26ce2095
JB
2878{
2879 struct btrfs_space_info *sinfo = cache->space_info;
2880 u64 num_bytes;
2881
2882 BUG_ON(!cache->ro);
2883
2884 spin_lock(&sinfo->lock);
2885 spin_lock(&cache->lock);
2886 if (!--cache->ro) {
169e0da9
NA
2887 if (btrfs_is_zoned(cache->fs_info)) {
2888 /* Migrate zone_unusable bytes back */
98173255
NA
2889 cache->zone_unusable =
2890 (cache->alloc_offset - cache->used) +
2891 (cache->length - cache->zone_capacity);
169e0da9
NA
2892 sinfo->bytes_zone_unusable += cache->zone_unusable;
2893 sinfo->bytes_readonly -= cache->zone_unusable;
2894 }
f9f28e5b
NA
2895 num_bytes = cache->length - cache->reserved -
2896 cache->pinned - cache->bytes_super -
2897 cache->zone_unusable - cache->used;
2898 sinfo->bytes_readonly -= num_bytes;
26ce2095
JB
2899 list_del_init(&cache->ro_list);
2900 }
2901 spin_unlock(&cache->lock);
2902 spin_unlock(&sinfo->lock);
2903}
77745c05 2904
3be4d8ef
QW
2905static int update_block_group_item(struct btrfs_trans_handle *trans,
2906 struct btrfs_path *path,
2907 struct btrfs_block_group *cache)
77745c05
JB
2908{
2909 struct btrfs_fs_info *fs_info = trans->fs_info;
2910 int ret;
dfe8aec4 2911 struct btrfs_root *root = btrfs_block_group_root(fs_info);
77745c05
JB
2912 unsigned long bi;
2913 struct extent_buffer *leaf;
bf38be65 2914 struct btrfs_block_group_item bgi;
b3470b5d 2915 struct btrfs_key key;
7248e0ce
QW
2916 u64 old_commit_used;
2917 u64 used;
2918
2919 /*
2920 * Block group items update can be triggered out of commit transaction
2921 * critical section, thus we need a consistent view of used bytes.
2922 * We cannot use cache->used directly outside of the spin lock, as it
2923 * may be changed.
2924 */
2925 spin_lock(&cache->lock);
2926 old_commit_used = cache->commit_used;
2927 used = cache->used;
2928 /* No change in used bytes, can safely skip it. */
2929 if (cache->commit_used == used) {
2930 spin_unlock(&cache->lock);
2931 return 0;
2932 }
2933 cache->commit_used = used;
2934 spin_unlock(&cache->lock);
b3470b5d
DS
2935
2936 key.objectid = cache->start;
2937 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2938 key.offset = cache->length;
77745c05 2939
3be4d8ef 2940 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
77745c05
JB
2941 if (ret) {
2942 if (ret > 0)
2943 ret = -ENOENT;
2944 goto fail;
2945 }
2946
2947 leaf = path->nodes[0];
2948 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
7248e0ce 2949 btrfs_set_stack_block_group_used(&bgi, used);
de0dc456 2950 btrfs_set_stack_block_group_chunk_objectid(&bgi,
f7238e50 2951 cache->global_root_id);
de0dc456 2952 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
bf38be65 2953 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
77745c05
JB
2954 btrfs_mark_buffer_dirty(leaf);
2955fail:
2956 btrfs_release_path(path);
7248e0ce
QW
2957 /* We didn't update the block group item, need to revert @commit_used. */
2958 if (ret < 0) {
2959 spin_lock(&cache->lock);
2960 cache->commit_used = old_commit_used;
2961 spin_unlock(&cache->lock);
2962 }
77745c05
JB
2963 return ret;
2964
2965}
2966
32da5386 2967static int cache_save_setup(struct btrfs_block_group *block_group,
77745c05
JB
2968 struct btrfs_trans_handle *trans,
2969 struct btrfs_path *path)
2970{
2971 struct btrfs_fs_info *fs_info = block_group->fs_info;
2972 struct btrfs_root *root = fs_info->tree_root;
2973 struct inode *inode = NULL;
2974 struct extent_changeset *data_reserved = NULL;
2975 u64 alloc_hint = 0;
2976 int dcs = BTRFS_DC_ERROR;
0044ae11 2977 u64 cache_size = 0;
77745c05
JB
2978 int retries = 0;
2979 int ret = 0;
2980
af456a2c
BB
2981 if (!btrfs_test_opt(fs_info, SPACE_CACHE))
2982 return 0;
2983
77745c05
JB
2984 /*
2985 * If this block group is smaller than 100 megs don't bother caching the
2986 * block group.
2987 */
b3470b5d 2988 if (block_group->length < (100 * SZ_1M)) {
77745c05
JB
2989 spin_lock(&block_group->lock);
2990 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2991 spin_unlock(&block_group->lock);
2992 return 0;
2993 }
2994
bf31f87f 2995 if (TRANS_ABORTED(trans))
77745c05
JB
2996 return 0;
2997again:
2998 inode = lookup_free_space_inode(block_group, path);
2999 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3000 ret = PTR_ERR(inode);
3001 btrfs_release_path(path);
3002 goto out;
3003 }
3004
3005 if (IS_ERR(inode)) {
3006 BUG_ON(retries);
3007 retries++;
3008
3009 if (block_group->ro)
3010 goto out_free;
3011
3012 ret = create_free_space_inode(trans, block_group, path);
3013 if (ret)
3014 goto out_free;
3015 goto again;
3016 }
3017
3018 /*
3019 * We want to set the generation to 0, that way if anything goes wrong
3020 * from here on out we know not to trust this cache when we load up next
3021 * time.
3022 */
3023 BTRFS_I(inode)->generation = 0;
9a56fcd1 3024 ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
77745c05
JB
3025 if (ret) {
3026 /*
3027 * So theoretically we could recover from this, simply set the
3028 * super cache generation to 0 so we know to invalidate the
3029 * cache, but then we'd have to keep track of the block groups
3030 * that fail this way so we know we _have_ to reset this cache
3031 * before the next commit or risk reading stale cache. So to
3032 * limit our exposure to horrible edge cases lets just abort the
3033 * transaction, this only happens in really bad situations
3034 * anyway.
3035 */
3036 btrfs_abort_transaction(trans, ret);
3037 goto out_put;
3038 }
3039 WARN_ON(ret);
3040
3041 /* We've already setup this transaction, go ahead and exit */
3042 if (block_group->cache_generation == trans->transid &&
3043 i_size_read(inode)) {
3044 dcs = BTRFS_DC_SETUP;
3045 goto out_put;
3046 }
3047
3048 if (i_size_read(inode) > 0) {
3049 ret = btrfs_check_trunc_cache_free_space(fs_info,
3050 &fs_info->global_block_rsv);
3051 if (ret)
3052 goto out_put;
3053
3054 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3055 if (ret)
3056 goto out_put;
3057 }
3058
3059 spin_lock(&block_group->lock);
3060 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3061 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3062 /*
3063 * don't bother trying to write stuff out _if_
3064 * a) we're not cached,
3065 * b) we're with nospace_cache mount option,
3066 * c) we're with v2 space_cache (FREE_SPACE_TREE).
3067 */
3068 dcs = BTRFS_DC_WRITTEN;
3069 spin_unlock(&block_group->lock);
3070 goto out_put;
3071 }
3072 spin_unlock(&block_group->lock);
3073
3074 /*
3075 * We hit an ENOSPC when setting up the cache in this transaction, just
3076 * skip doing the setup, we've already cleared the cache so we're safe.
3077 */
3078 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3079 ret = -ENOSPC;
3080 goto out_put;
3081 }
3082
3083 /*
3084 * Try to preallocate enough space based on how big the block group is.
3085 * Keep in mind this has to include any pinned space which could end up
3086 * taking up quite a bit since it's not folded into the other space
3087 * cache.
3088 */
0044ae11
QW
3089 cache_size = div_u64(block_group->length, SZ_256M);
3090 if (!cache_size)
3091 cache_size = 1;
77745c05 3092
0044ae11
QW
3093 cache_size *= 16;
3094 cache_size *= fs_info->sectorsize;
77745c05 3095
36ea6f3e 3096 ret = btrfs_check_data_free_space(BTRFS_I(inode), &data_reserved, 0,
1daedb1d 3097 cache_size, false);
77745c05
JB
3098 if (ret)
3099 goto out_put;
3100
0044ae11
QW
3101 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, cache_size,
3102 cache_size, cache_size,
77745c05
JB
3103 &alloc_hint);
3104 /*
3105 * Our cache requires contiguous chunks so that we don't modify a bunch
3106 * of metadata or split extents when writing the cache out, which means
3107 * we can enospc if we are heavily fragmented in addition to just normal
3108 * out of space conditions. So if we hit this just skip setting up any
3109 * other block groups for this transaction, maybe we'll unpin enough
3110 * space the next time around.
3111 */
3112 if (!ret)
3113 dcs = BTRFS_DC_SETUP;
3114 else if (ret == -ENOSPC)
3115 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3116
3117out_put:
3118 iput(inode);
3119out_free:
3120 btrfs_release_path(path);
3121out:
3122 spin_lock(&block_group->lock);
3123 if (!ret && dcs == BTRFS_DC_SETUP)
3124 block_group->cache_generation = trans->transid;
3125 block_group->disk_cache_state = dcs;
3126 spin_unlock(&block_group->lock);
3127
3128 extent_changeset_free(data_reserved);
3129 return ret;
3130}
3131
3132int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3133{
3134 struct btrfs_fs_info *fs_info = trans->fs_info;
32da5386 3135 struct btrfs_block_group *cache, *tmp;
77745c05
JB
3136 struct btrfs_transaction *cur_trans = trans->transaction;
3137 struct btrfs_path *path;
3138
3139 if (list_empty(&cur_trans->dirty_bgs) ||
3140 !btrfs_test_opt(fs_info, SPACE_CACHE))
3141 return 0;
3142
3143 path = btrfs_alloc_path();
3144 if (!path)
3145 return -ENOMEM;
3146
3147 /* Could add new block groups, use _safe just in case */
3148 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3149 dirty_list) {
3150 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3151 cache_save_setup(cache, trans, path);
3152 }
3153
3154 btrfs_free_path(path);
3155 return 0;
3156}
3157
3158/*
3159 * Transaction commit does final block group cache writeback during a critical
3160 * section where nothing is allowed to change the FS. This is required in
3161 * order for the cache to actually match the block group, but can introduce a
3162 * lot of latency into the commit.
3163 *
3164 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
3165 * There's a chance we'll have to redo some of it if the block group changes
3166 * again during the commit, but it greatly reduces the commit latency by
3167 * getting rid of the easy block groups while we're still allowing others to
3168 * join the commit.
3169 */
3170int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3171{
3172 struct btrfs_fs_info *fs_info = trans->fs_info;
32da5386 3173 struct btrfs_block_group *cache;
77745c05
JB
3174 struct btrfs_transaction *cur_trans = trans->transaction;
3175 int ret = 0;
3176 int should_put;
3177 struct btrfs_path *path = NULL;
3178 LIST_HEAD(dirty);
3179 struct list_head *io = &cur_trans->io_bgs;
77745c05
JB
3180 int loops = 0;
3181
3182 spin_lock(&cur_trans->dirty_bgs_lock);
3183 if (list_empty(&cur_trans->dirty_bgs)) {
3184 spin_unlock(&cur_trans->dirty_bgs_lock);
3185 return 0;
3186 }
3187 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3188 spin_unlock(&cur_trans->dirty_bgs_lock);
3189
3190again:
3191 /* Make sure all the block groups on our dirty list actually exist */
3192 btrfs_create_pending_block_groups(trans);
3193
3194 if (!path) {
3195 path = btrfs_alloc_path();
938fcbfb
JB
3196 if (!path) {
3197 ret = -ENOMEM;
3198 goto out;
3199 }
77745c05
JB
3200 }
3201
3202 /*
3203 * cache_write_mutex is here only to save us from balance or automatic
3204 * removal of empty block groups deleting this block group while we are
3205 * writing out the cache
3206 */
3207 mutex_lock(&trans->transaction->cache_write_mutex);
3208 while (!list_empty(&dirty)) {
3209 bool drop_reserve = true;
3210
32da5386 3211 cache = list_first_entry(&dirty, struct btrfs_block_group,
77745c05
JB
3212 dirty_list);
3213 /*
3214 * This can happen if something re-dirties a block group that
3215 * is already under IO. Just wait for it to finish and then do
3216 * it all again
3217 */
3218 if (!list_empty(&cache->io_list)) {
3219 list_del_init(&cache->io_list);
3220 btrfs_wait_cache_io(trans, cache, path);
3221 btrfs_put_block_group(cache);
3222 }
3223
3224
3225 /*
3226 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
3227 * it should update the cache_state. Don't delete until after
3228 * we wait.
3229 *
3230 * Since we're not running in the commit critical section
3231 * we need the dirty_bgs_lock to protect from update_block_group
3232 */
3233 spin_lock(&cur_trans->dirty_bgs_lock);
3234 list_del_init(&cache->dirty_list);
3235 spin_unlock(&cur_trans->dirty_bgs_lock);
3236
3237 should_put = 1;
3238
3239 cache_save_setup(cache, trans, path);
3240
3241 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3242 cache->io_ctl.inode = NULL;
3243 ret = btrfs_write_out_cache(trans, cache, path);
3244 if (ret == 0 && cache->io_ctl.inode) {
77745c05
JB
3245 should_put = 0;
3246
3247 /*
3248 * The cache_write_mutex is protecting the
3249 * io_list, also refer to the definition of
3250 * btrfs_transaction::io_bgs for more details
3251 */
3252 list_add_tail(&cache->io_list, io);
3253 } else {
3254 /*
3255 * If we failed to write the cache, the
3256 * generation will be bad and life goes on
3257 */
3258 ret = 0;
3259 }
3260 }
3261 if (!ret) {
3be4d8ef 3262 ret = update_block_group_item(trans, path, cache);
77745c05
JB
3263 /*
3264 * Our block group might still be attached to the list
3265 * of new block groups in the transaction handle of some
3266 * other task (struct btrfs_trans_handle->new_bgs). This
3267 * means its block group item isn't yet in the extent
3268 * tree. If this happens ignore the error, as we will
3269 * try again later in the critical section of the
3270 * transaction commit.
3271 */
3272 if (ret == -ENOENT) {
3273 ret = 0;
3274 spin_lock(&cur_trans->dirty_bgs_lock);
3275 if (list_empty(&cache->dirty_list)) {
3276 list_add_tail(&cache->dirty_list,
3277 &cur_trans->dirty_bgs);
3278 btrfs_get_block_group(cache);
3279 drop_reserve = false;
3280 }
3281 spin_unlock(&cur_trans->dirty_bgs_lock);
3282 } else if (ret) {
3283 btrfs_abort_transaction(trans, ret);
3284 }
3285 }
3286
3287 /* If it's not on the io list, we need to put the block group */
3288 if (should_put)
3289 btrfs_put_block_group(cache);
3290 if (drop_reserve)
3291 btrfs_delayed_refs_rsv_release(fs_info, 1);
77745c05
JB
3292 /*
3293 * Avoid blocking other tasks for too long. It might even save
3294 * us from writing caches for block groups that are going to be
3295 * removed.
3296 */
3297 mutex_unlock(&trans->transaction->cache_write_mutex);
938fcbfb
JB
3298 if (ret)
3299 goto out;
77745c05
JB
3300 mutex_lock(&trans->transaction->cache_write_mutex);
3301 }
3302 mutex_unlock(&trans->transaction->cache_write_mutex);
3303
3304 /*
3305 * Go through delayed refs for all the stuff we've just kicked off
3306 * and then loop back (just once)
3307 */
34d1eb0e
JB
3308 if (!ret)
3309 ret = btrfs_run_delayed_refs(trans, 0);
77745c05
JB
3310 if (!ret && loops == 0) {
3311 loops++;
3312 spin_lock(&cur_trans->dirty_bgs_lock);
3313 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3314 /*
3315 * dirty_bgs_lock protects us from concurrent block group
3316 * deletes too (not just cache_write_mutex).
3317 */
3318 if (!list_empty(&dirty)) {
3319 spin_unlock(&cur_trans->dirty_bgs_lock);
3320 goto again;
3321 }
3322 spin_unlock(&cur_trans->dirty_bgs_lock);
938fcbfb
JB
3323 }
3324out:
3325 if (ret < 0) {
3326 spin_lock(&cur_trans->dirty_bgs_lock);
3327 list_splice_init(&dirty, &cur_trans->dirty_bgs);
3328 spin_unlock(&cur_trans->dirty_bgs_lock);
77745c05
JB
3329 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3330 }
3331
3332 btrfs_free_path(path);
3333 return ret;
3334}
3335
3336int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3337{
3338 struct btrfs_fs_info *fs_info = trans->fs_info;
32da5386 3339 struct btrfs_block_group *cache;
77745c05
JB
3340 struct btrfs_transaction *cur_trans = trans->transaction;
3341 int ret = 0;
3342 int should_put;
3343 struct btrfs_path *path;
3344 struct list_head *io = &cur_trans->io_bgs;
77745c05
JB
3345
3346 path = btrfs_alloc_path();
3347 if (!path)
3348 return -ENOMEM;
3349
3350 /*
3351 * Even though we are in the critical section of the transaction commit,
3352 * we can still have concurrent tasks adding elements to this
3353 * transaction's list of dirty block groups. These tasks correspond to
3354 * endio free space workers started when writeback finishes for a
3355 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3356 * allocate new block groups as a result of COWing nodes of the root
3357 * tree when updating the free space inode. The writeback for the space
3358 * caches is triggered by an earlier call to
3359 * btrfs_start_dirty_block_groups() and iterations of the following
3360 * loop.
3361 * Also we want to do the cache_save_setup first and then run the
3362 * delayed refs to make sure we have the best chance at doing this all
3363 * in one shot.
3364 */
3365 spin_lock(&cur_trans->dirty_bgs_lock);
3366 while (!list_empty(&cur_trans->dirty_bgs)) {
3367 cache = list_first_entry(&cur_trans->dirty_bgs,
32da5386 3368 struct btrfs_block_group,
77745c05
JB
3369 dirty_list);
3370
3371 /*
3372 * This can happen if cache_save_setup re-dirties a block group
3373 * that is already under IO. Just wait for it to finish and
3374 * then do it all again
3375 */
3376 if (!list_empty(&cache->io_list)) {
3377 spin_unlock(&cur_trans->dirty_bgs_lock);
3378 list_del_init(&cache->io_list);
3379 btrfs_wait_cache_io(trans, cache, path);
3380 btrfs_put_block_group(cache);
3381 spin_lock(&cur_trans->dirty_bgs_lock);
3382 }
3383
3384 /*
3385 * Don't remove from the dirty list until after we've waited on
3386 * any pending IO
3387 */
3388 list_del_init(&cache->dirty_list);
3389 spin_unlock(&cur_trans->dirty_bgs_lock);
3390 should_put = 1;
3391
3392 cache_save_setup(cache, trans, path);
3393
3394 if (!ret)
3395 ret = btrfs_run_delayed_refs(trans,
3396 (unsigned long) -1);
3397
3398 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3399 cache->io_ctl.inode = NULL;
3400 ret = btrfs_write_out_cache(trans, cache, path);
3401 if (ret == 0 && cache->io_ctl.inode) {
77745c05
JB
3402 should_put = 0;
3403 list_add_tail(&cache->io_list, io);
3404 } else {
3405 /*
3406 * If we failed to write the cache, the
3407 * generation will be bad and life goes on
3408 */
3409 ret = 0;
3410 }
3411 }
3412 if (!ret) {
3be4d8ef 3413 ret = update_block_group_item(trans, path, cache);
77745c05
JB
3414 /*
3415 * One of the free space endio workers might have
3416 * created a new block group while updating a free space
3417 * cache's inode (at inode.c:btrfs_finish_ordered_io())
3418 * and hasn't released its transaction handle yet, in
3419 * which case the new block group is still attached to
3420 * its transaction handle and its creation has not
3421 * finished yet (no block group item in the extent tree
3422 * yet, etc). If this is the case, wait for all free
3423 * space endio workers to finish and retry. This is a
260db43c 3424 * very rare case so no need for a more efficient and
77745c05
JB
3425 * complex approach.
3426 */
3427 if (ret == -ENOENT) {
3428 wait_event(cur_trans->writer_wait,
3429 atomic_read(&cur_trans->num_writers) == 1);
3be4d8ef 3430 ret = update_block_group_item(trans, path, cache);
77745c05
JB
3431 }
3432 if (ret)
3433 btrfs_abort_transaction(trans, ret);
3434 }
3435
3436 /* If its not on the io list, we need to put the block group */
3437 if (should_put)
3438 btrfs_put_block_group(cache);
3439 btrfs_delayed_refs_rsv_release(fs_info, 1);
3440 spin_lock(&cur_trans->dirty_bgs_lock);
3441 }
3442 spin_unlock(&cur_trans->dirty_bgs_lock);
3443
3444 /*
3445 * Refer to the definition of io_bgs member for details why it's safe
3446 * to use it without any locking
3447 */
3448 while (!list_empty(io)) {
32da5386 3449 cache = list_first_entry(io, struct btrfs_block_group,
77745c05
JB
3450 io_list);
3451 list_del_init(&cache->io_list);
3452 btrfs_wait_cache_io(trans, cache, path);
3453 btrfs_put_block_group(cache);
3454 }
3455
3456 btrfs_free_path(path);
3457 return ret;
3458}
606d1bf1
JB
3459
3460int btrfs_update_block_group(struct btrfs_trans_handle *trans,
11b66fa6 3461 u64 bytenr, u64 num_bytes, bool alloc)
606d1bf1
JB
3462{
3463 struct btrfs_fs_info *info = trans->fs_info;
32da5386 3464 struct btrfs_block_group *cache = NULL;
606d1bf1
JB
3465 u64 total = num_bytes;
3466 u64 old_val;
3467 u64 byte_in_group;
3468 int factor;
3469 int ret = 0;
3470
3471 /* Block accounting for super block */
3472 spin_lock(&info->delalloc_root_lock);
3473 old_val = btrfs_super_bytes_used(info->super_copy);
3474 if (alloc)
3475 old_val += num_bytes;
3476 else
3477 old_val -= num_bytes;
3478 btrfs_set_super_bytes_used(info->super_copy, old_val);
3479 spin_unlock(&info->delalloc_root_lock);
3480
3481 while (total) {
efbf35a1 3482 bool reclaim = false;
ac2f1e63 3483
606d1bf1
JB
3484 cache = btrfs_lookup_block_group(info, bytenr);
3485 if (!cache) {
3486 ret = -ENOENT;
3487 break;
3488 }
3489 factor = btrfs_bg_type_to_factor(cache->flags);
3490
3491 /*
3492 * If this block group has free space cache written out, we
3493 * need to make sure to load it if we are removing space. This
3494 * is because we need the unpinning stage to actually add the
3495 * space back to the block group, otherwise we will leak space.
3496 */
32da5386 3497 if (!alloc && !btrfs_block_group_done(cache))
ced8ecf0 3498 btrfs_cache_block_group(cache, true);
606d1bf1 3499
b3470b5d
DS
3500 byte_in_group = bytenr - cache->start;
3501 WARN_ON(byte_in_group > cache->length);
606d1bf1
JB
3502
3503 spin_lock(&cache->space_info->lock);
3504 spin_lock(&cache->lock);
3505
3506 if (btrfs_test_opt(info, SPACE_CACHE) &&
3507 cache->disk_cache_state < BTRFS_DC_CLEAR)
3508 cache->disk_cache_state = BTRFS_DC_CLEAR;
3509
bf38be65 3510 old_val = cache->used;
b3470b5d 3511 num_bytes = min(total, cache->length - byte_in_group);
606d1bf1
JB
3512 if (alloc) {
3513 old_val += num_bytes;
bf38be65 3514 cache->used = old_val;
606d1bf1
JB
3515 cache->reserved -= num_bytes;
3516 cache->space_info->bytes_reserved -= num_bytes;
3517 cache->space_info->bytes_used += num_bytes;
3518 cache->space_info->disk_used += num_bytes * factor;
3519 spin_unlock(&cache->lock);
3520 spin_unlock(&cache->space_info->lock);
3521 } else {
3522 old_val -= num_bytes;
bf38be65 3523 cache->used = old_val;
606d1bf1
JB
3524 cache->pinned += num_bytes;
3525 btrfs_space_info_update_bytes_pinned(info,
3526 cache->space_info, num_bytes);
3527 cache->space_info->bytes_used -= num_bytes;
3528 cache->space_info->disk_used -= num_bytes * factor;
ac2f1e63
JB
3529
3530 reclaim = should_reclaim_block_group(cache, num_bytes);
52bb7a21 3531
606d1bf1
JB
3532 spin_unlock(&cache->lock);
3533 spin_unlock(&cache->space_info->lock);
3534
fe119a6e 3535 set_extent_dirty(&trans->transaction->pinned_extents,
606d1bf1
JB
3536 bytenr, bytenr + num_bytes - 1,
3537 GFP_NOFS | __GFP_NOFAIL);
3538 }
3539
3540 spin_lock(&trans->transaction->dirty_bgs_lock);
3541 if (list_empty(&cache->dirty_list)) {
3542 list_add_tail(&cache->dirty_list,
3543 &trans->transaction->dirty_bgs);
3544 trans->delayed_ref_updates++;
3545 btrfs_get_block_group(cache);
3546 }
3547 spin_unlock(&trans->transaction->dirty_bgs_lock);
3548
3549 /*
3550 * No longer have used bytes in this block group, queue it for
3551 * deletion. We do this after adding the block group to the
3552 * dirty list to avoid races between cleaner kthread and space
3553 * cache writeout.
3554 */
6e80d4f8
DZ
3555 if (!alloc && old_val == 0) {
3556 if (!btrfs_test_opt(info, DISCARD_ASYNC))
3557 btrfs_mark_bg_unused(cache);
ac2f1e63
JB
3558 } else if (!alloc && reclaim) {
3559 btrfs_mark_bg_to_reclaim(cache);
6e80d4f8 3560 }
606d1bf1
JB
3561
3562 btrfs_put_block_group(cache);
3563 total -= num_bytes;
3564 bytenr += num_bytes;
3565 }
3566
3567 /* Modified block groups are accounted for in the delayed_refs_rsv. */
3568 btrfs_update_delayed_refs_rsv(trans);
3569 return ret;
3570}
3571
43dd529a
DS
3572/*
3573 * Update the block_group and space info counters.
3574 *
606d1bf1
JB
3575 * @cache: The cache we are manipulating
3576 * @ram_bytes: The number of bytes of file content, and will be same to
3577 * @num_bytes except for the compress path.
3578 * @num_bytes: The number of bytes in question
3579 * @delalloc: The blocks are allocated for the delalloc write
3580 *
3581 * This is called by the allocator when it reserves space. If this is a
3582 * reservation and the block group has become read only we cannot make the
3583 * reservation and return -EAGAIN, otherwise this function always succeeds.
3584 */
32da5386 3585int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
52bb7a21
BB
3586 u64 ram_bytes, u64 num_bytes, int delalloc,
3587 bool force_wrong_size_class)
606d1bf1
JB
3588{
3589 struct btrfs_space_info *space_info = cache->space_info;
52bb7a21 3590 enum btrfs_block_group_size_class size_class;
606d1bf1
JB
3591 int ret = 0;
3592
3593 spin_lock(&space_info->lock);
3594 spin_lock(&cache->lock);
3595 if (cache->ro) {
3596 ret = -EAGAIN;
52bb7a21
BB
3597 goto out;
3598 }
99ffb43e 3599
cb0922f2 3600 if (btrfs_block_group_should_use_size_class(cache)) {
52bb7a21
BB
3601 size_class = btrfs_calc_block_group_size_class(num_bytes);
3602 ret = btrfs_use_block_group_size_class(cache, size_class, force_wrong_size_class);
3603 if (ret)
3604 goto out;
606d1bf1 3605 }
52bb7a21
BB
3606 cache->reserved += num_bytes;
3607 space_info->bytes_reserved += num_bytes;
3608 trace_btrfs_space_reservation(cache->fs_info, "space_info",
3609 space_info->flags, num_bytes, 1);
3610 btrfs_space_info_update_bytes_may_use(cache->fs_info,
3611 space_info, -ram_bytes);
3612 if (delalloc)
3613 cache->delalloc_bytes += num_bytes;
3614
3615 /*
3616 * Compression can use less space than we reserved, so wake tickets if
3617 * that happens.
3618 */
3619 if (num_bytes < ram_bytes)
3620 btrfs_try_granting_tickets(cache->fs_info, space_info);
3621out:
606d1bf1
JB
3622 spin_unlock(&cache->lock);
3623 spin_unlock(&space_info->lock);
3624 return ret;
3625}
3626
43dd529a
DS
3627/*
3628 * Update the block_group and space info counters.
3629 *
606d1bf1
JB
3630 * @cache: The cache we are manipulating
3631 * @num_bytes: The number of bytes in question
3632 * @delalloc: The blocks are allocated for the delalloc write
3633 *
3634 * This is called by somebody who is freeing space that was never actually used
3635 * on disk. For example if you reserve some space for a new leaf in transaction
3636 * A and before transaction A commits you free that leaf, you call this with
3637 * reserve set to 0 in order to clear the reservation.
3638 */
32da5386 3639void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
606d1bf1
JB
3640 u64 num_bytes, int delalloc)
3641{
3642 struct btrfs_space_info *space_info = cache->space_info;
3643
3644 spin_lock(&space_info->lock);
3645 spin_lock(&cache->lock);
3646 if (cache->ro)
3647 space_info->bytes_readonly += num_bytes;
3648 cache->reserved -= num_bytes;
3649 space_info->bytes_reserved -= num_bytes;
3650 space_info->max_extent_size = 0;
3651
3652 if (delalloc)
3653 cache->delalloc_bytes -= num_bytes;
3654 spin_unlock(&cache->lock);
3308234a
JB
3655
3656 btrfs_try_granting_tickets(cache->fs_info, space_info);
606d1bf1
JB
3657 spin_unlock(&space_info->lock);
3658}
07730d87
JB
3659
3660static void force_metadata_allocation(struct btrfs_fs_info *info)
3661{
3662 struct list_head *head = &info->space_info;
3663 struct btrfs_space_info *found;
3664
72804905 3665 list_for_each_entry(found, head, list) {
07730d87
JB
3666 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3667 found->force_alloc = CHUNK_ALLOC_FORCE;
3668 }
07730d87
JB
3669}
3670
3671static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3672 struct btrfs_space_info *sinfo, int force)
3673{
3674 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3675 u64 thresh;
3676
3677 if (force == CHUNK_ALLOC_FORCE)
3678 return 1;
3679
3680 /*
3681 * in limited mode, we want to have some free space up to
3682 * about 1% of the FS size.
3683 */
3684 if (force == CHUNK_ALLOC_LIMITED) {
3685 thresh = btrfs_super_total_bytes(fs_info->super_copy);
428c8e03 3686 thresh = max_t(u64, SZ_64M, mult_perc(thresh, 1));
07730d87
JB
3687
3688 if (sinfo->total_bytes - bytes_used < thresh)
3689 return 1;
3690 }
3691
428c8e03 3692 if (bytes_used + SZ_2M < mult_perc(sinfo->total_bytes, 80))
07730d87
JB
3693 return 0;
3694 return 1;
3695}
3696
3697int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3698{
3699 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3700
3701 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3702}
3703
820c363b 3704static struct btrfs_block_group *do_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags)
79bd3712
FM
3705{
3706 struct btrfs_block_group *bg;
3707 int ret;
3708
3709 /*
3710 * Check if we have enough space in the system space info because we
3711 * will need to update device items in the chunk btree and insert a new
3712 * chunk item in the chunk btree as well. This will allocate a new
3713 * system block group if needed.
3714 */
3715 check_system_chunk(trans, flags);
3716
f6f39f7a 3717 bg = btrfs_create_chunk(trans, flags);
79bd3712
FM
3718 if (IS_ERR(bg)) {
3719 ret = PTR_ERR(bg);
3720 goto out;
3721 }
3722
79bd3712
FM
3723 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3724 /*
3725 * Normally we are not expected to fail with -ENOSPC here, since we have
3726 * previously reserved space in the system space_info and allocated one
ecd84d54 3727 * new system chunk if necessary. However there are three exceptions:
79bd3712
FM
3728 *
3729 * 1) We may have enough free space in the system space_info but all the
3730 * existing system block groups have a profile which can not be used
3731 * for extent allocation.
3732 *
3733 * This happens when mounting in degraded mode. For example we have a
3734 * RAID1 filesystem with 2 devices, lose one device and mount the fs
3735 * using the other device in degraded mode. If we then allocate a chunk,
3736 * we may have enough free space in the existing system space_info, but
3737 * none of the block groups can be used for extent allocation since they
3738 * have a RAID1 profile, and because we are in degraded mode with a
3739 * single device, we are forced to allocate a new system chunk with a
3740 * SINGLE profile. Making check_system_chunk() iterate over all system
3741 * block groups and check if they have a usable profile and enough space
3742 * can be slow on very large filesystems, so we tolerate the -ENOSPC and
3743 * try again after forcing allocation of a new system chunk. Like this
3744 * we avoid paying the cost of that search in normal circumstances, when
3745 * we were not mounted in degraded mode;
3746 *
3747 * 2) We had enough free space info the system space_info, and one suitable
3748 * block group to allocate from when we called check_system_chunk()
3749 * above. However right after we called it, the only system block group
3750 * with enough free space got turned into RO mode by a running scrub,
3751 * and in this case we have to allocate a new one and retry. We only
3752 * need do this allocate and retry once, since we have a transaction
ecd84d54
FM
3753 * handle and scrub uses the commit root to search for block groups;
3754 *
3755 * 3) We had one system block group with enough free space when we called
3756 * check_system_chunk(), but after that, right before we tried to
3757 * allocate the last extent buffer we needed, a discard operation came
3758 * in and it temporarily removed the last free space entry from the
3759 * block group (discard removes a free space entry, discards it, and
3760 * then adds back the entry to the block group cache).
79bd3712
FM
3761 */
3762 if (ret == -ENOSPC) {
3763 const u64 sys_flags = btrfs_system_alloc_profile(trans->fs_info);
3764 struct btrfs_block_group *sys_bg;
3765
f6f39f7a 3766 sys_bg = btrfs_create_chunk(trans, sys_flags);
79bd3712
FM
3767 if (IS_ERR(sys_bg)) {
3768 ret = PTR_ERR(sys_bg);
3769 btrfs_abort_transaction(trans, ret);
3770 goto out;
3771 }
3772
3773 ret = btrfs_chunk_alloc_add_chunk_item(trans, sys_bg);
3774 if (ret) {
3775 btrfs_abort_transaction(trans, ret);
3776 goto out;
3777 }
3778
3779 ret = btrfs_chunk_alloc_add_chunk_item(trans, bg);
3780 if (ret) {
3781 btrfs_abort_transaction(trans, ret);
3782 goto out;
3783 }
3784 } else if (ret) {
3785 btrfs_abort_transaction(trans, ret);
3786 goto out;
3787 }
3788out:
3789 btrfs_trans_release_chunk_metadata(trans);
3790
820c363b
NA
3791 if (ret)
3792 return ERR_PTR(ret);
3793
3794 btrfs_get_block_group(bg);
3795 return bg;
79bd3712
FM
3796}
3797
07730d87 3798/*
79bd3712
FM
3799 * Chunk allocation is done in 2 phases:
3800 *
3801 * 1) Phase 1 - through btrfs_chunk_alloc() we allocate device extents for
3802 * the chunk, the chunk mapping, create its block group and add the items
3803 * that belong in the chunk btree to it - more specifically, we need to
3804 * update device items in the chunk btree and add a new chunk item to it.
3805 *
3806 * 2) Phase 2 - through btrfs_create_pending_block_groups(), we add the block
3807 * group item to the extent btree and the device extent items to the devices
3808 * btree.
3809 *
3810 * This is done to prevent deadlocks. For example when COWing a node from the
3811 * extent btree we are holding a write lock on the node's parent and if we
3812 * trigger chunk allocation and attempted to insert the new block group item
3813 * in the extent btree right way, we could deadlock because the path for the
3814 * insertion can include that parent node. At first glance it seems impossible
3815 * to trigger chunk allocation after starting a transaction since tasks should
3816 * reserve enough transaction units (metadata space), however while that is true
3817 * most of the time, chunk allocation may still be triggered for several reasons:
3818 *
3819 * 1) When reserving metadata, we check if there is enough free space in the
3820 * metadata space_info and therefore don't trigger allocation of a new chunk.
3821 * However later when the task actually tries to COW an extent buffer from
3822 * the extent btree or from the device btree for example, it is forced to
3823 * allocate a new block group (chunk) because the only one that had enough
3824 * free space was just turned to RO mode by a running scrub for example (or
3825 * device replace, block group reclaim thread, etc), so we can not use it
3826 * for allocating an extent and end up being forced to allocate a new one;
3827 *
3828 * 2) Because we only check that the metadata space_info has enough free bytes,
3829 * we end up not allocating a new metadata chunk in that case. However if
3830 * the filesystem was mounted in degraded mode, none of the existing block
3831 * groups might be suitable for extent allocation due to their incompatible
3832 * profile (for e.g. mounting a 2 devices filesystem, where all block groups
3833 * use a RAID1 profile, in degraded mode using a single device). In this case
3834 * when the task attempts to COW some extent buffer of the extent btree for
3835 * example, it will trigger allocation of a new metadata block group with a
3836 * suitable profile (SINGLE profile in the example of the degraded mount of
3837 * the RAID1 filesystem);
3838 *
3839 * 3) The task has reserved enough transaction units / metadata space, but when
3840 * it attempts to COW an extent buffer from the extent or device btree for
3841 * example, it does not find any free extent in any metadata block group,
3842 * therefore forced to try to allocate a new metadata block group.
3843 * This is because some other task allocated all available extents in the
3844 * meanwhile - this typically happens with tasks that don't reserve space
3845 * properly, either intentionally or as a bug. One example where this is
3846 * done intentionally is fsync, as it does not reserve any transaction units
3847 * and ends up allocating a variable number of metadata extents for log
ecd84d54
FM
3848 * tree extent buffers;
3849 *
3850 * 4) The task has reserved enough transaction units / metadata space, but right
3851 * before it tries to allocate the last extent buffer it needs, a discard
3852 * operation comes in and, temporarily, removes the last free space entry from
3853 * the only metadata block group that had free space (discard starts by
3854 * removing a free space entry from a block group, then does the discard
3855 * operation and, once it's done, it adds back the free space entry to the
3856 * block group).
79bd3712
FM
3857 *
3858 * We also need this 2 phases setup when adding a device to a filesystem with
3859 * a seed device - we must create new metadata and system chunks without adding
3860 * any of the block group items to the chunk, extent and device btrees. If we
3861 * did not do it this way, we would get ENOSPC when attempting to update those
3862 * btrees, since all the chunks from the seed device are read-only.
3863 *
3864 * Phase 1 does the updates and insertions to the chunk btree because if we had
3865 * it done in phase 2 and have a thundering herd of tasks allocating chunks in
3866 * parallel, we risk having too many system chunks allocated by many tasks if
3867 * many tasks reach phase 1 without the previous ones completing phase 2. In the
3868 * extreme case this leads to exhaustion of the system chunk array in the
3869 * superblock. This is easier to trigger if using a btree node/leaf size of 64K
3870 * and with RAID filesystems (so we have more device items in the chunk btree).
3871 * This has happened before and commit eafa4fd0ad0607 ("btrfs: fix exhaustion of
3872 * the system chunk array due to concurrent allocations") provides more details.
3873 *
2bb2e00e
FM
3874 * Allocation of system chunks does not happen through this function. A task that
3875 * needs to update the chunk btree (the only btree that uses system chunks), must
3876 * preallocate chunk space by calling either check_system_chunk() or
3877 * btrfs_reserve_chunk_metadata() - the former is used when allocating a data or
3878 * metadata chunk or when removing a chunk, while the later is used before doing
3879 * a modification to the chunk btree - use cases for the later are adding,
3880 * removing and resizing a device as well as relocation of a system chunk.
3881 * See the comment below for more details.
79bd3712
FM
3882 *
3883 * The reservation of system space, done through check_system_chunk(), as well
3884 * as all the updates and insertions into the chunk btree must be done while
3885 * holding fs_info->chunk_mutex. This is important to guarantee that while COWing
3886 * an extent buffer from the chunks btree we never trigger allocation of a new
3887 * system chunk, which would result in a deadlock (trying to lock twice an
3888 * extent buffer of the chunk btree, first time before triggering the chunk
3889 * allocation and the second time during chunk allocation while attempting to
3890 * update the chunks btree). The system chunk array is also updated while holding
3891 * that mutex. The same logic applies to removing chunks - we must reserve system
3892 * space, update the chunk btree and the system chunk array in the superblock
3893 * while holding fs_info->chunk_mutex.
3894 *
3895 * This function, btrfs_chunk_alloc(), belongs to phase 1.
3896 *
3897 * If @force is CHUNK_ALLOC_FORCE:
07730d87
JB
3898 * - return 1 if it successfully allocates a chunk,
3899 * - return errors including -ENOSPC otherwise.
79bd3712 3900 * If @force is NOT CHUNK_ALLOC_FORCE:
07730d87
JB
3901 * - return 0 if it doesn't need to allocate a new chunk,
3902 * - return 1 if it successfully allocates a chunk,
3903 * - return errors including -ENOSPC otherwise.
3904 */
3905int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3906 enum btrfs_chunk_alloc_enum force)
3907{
3908 struct btrfs_fs_info *fs_info = trans->fs_info;
3909 struct btrfs_space_info *space_info;
820c363b 3910 struct btrfs_block_group *ret_bg;
07730d87
JB
3911 bool wait_for_alloc = false;
3912 bool should_alloc = false;
760e69c4 3913 bool from_extent_allocation = false;
07730d87
JB
3914 int ret = 0;
3915
760e69c4
NA
3916 if (force == CHUNK_ALLOC_FORCE_FOR_EXTENT) {
3917 from_extent_allocation = true;
3918 force = CHUNK_ALLOC_FORCE;
3919 }
3920
07730d87
JB
3921 /* Don't re-enter if we're already allocating a chunk */
3922 if (trans->allocating_chunk)
3923 return -ENOSPC;
79bd3712 3924 /*
2bb2e00e
FM
3925 * Allocation of system chunks can not happen through this path, as we
3926 * could end up in a deadlock if we are allocating a data or metadata
3927 * chunk and there is another task modifying the chunk btree.
3928 *
3929 * This is because while we are holding the chunk mutex, we will attempt
3930 * to add the new chunk item to the chunk btree or update an existing
3931 * device item in the chunk btree, while the other task that is modifying
3932 * the chunk btree is attempting to COW an extent buffer while holding a
3933 * lock on it and on its parent - if the COW operation triggers a system
3934 * chunk allocation, then we can deadlock because we are holding the
3935 * chunk mutex and we may need to access that extent buffer or its parent
3936 * in order to add the chunk item or update a device item.
3937 *
3938 * Tasks that want to modify the chunk tree should reserve system space
3939 * before updating the chunk btree, by calling either
3940 * btrfs_reserve_chunk_metadata() or check_system_chunk().
3941 * It's possible that after a task reserves the space, it still ends up
3942 * here - this happens in the cases described above at do_chunk_alloc().
3943 * The task will have to either retry or fail.
79bd3712 3944 */
2bb2e00e 3945 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
79bd3712 3946 return -ENOSPC;
07730d87
JB
3947
3948 space_info = btrfs_find_space_info(fs_info, flags);
3949 ASSERT(space_info);
3950
3951 do {
3952 spin_lock(&space_info->lock);
3953 if (force < space_info->force_alloc)
3954 force = space_info->force_alloc;
3955 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3956 if (space_info->full) {
3957 /* No more free physical space */
3958 if (should_alloc)
3959 ret = -ENOSPC;
3960 else
3961 ret = 0;
3962 spin_unlock(&space_info->lock);
3963 return ret;
3964 } else if (!should_alloc) {
3965 spin_unlock(&space_info->lock);
3966 return 0;
3967 } else if (space_info->chunk_alloc) {
3968 /*
3969 * Someone is already allocating, so we need to block
3970 * until this someone is finished and then loop to
3971 * recheck if we should continue with our allocation
3972 * attempt.
3973 */
3974 wait_for_alloc = true;
1314ca78 3975 force = CHUNK_ALLOC_NO_FORCE;
07730d87
JB
3976 spin_unlock(&space_info->lock);
3977 mutex_lock(&fs_info->chunk_mutex);
3978 mutex_unlock(&fs_info->chunk_mutex);
3979 } else {
3980 /* Proceed with allocation */
3981 space_info->chunk_alloc = 1;
3982 wait_for_alloc = false;
3983 spin_unlock(&space_info->lock);
3984 }
3985
3986 cond_resched();
3987 } while (wait_for_alloc);
3988
3989 mutex_lock(&fs_info->chunk_mutex);
3990 trans->allocating_chunk = true;
3991
3992 /*
3993 * If we have mixed data/metadata chunks we want to make sure we keep
3994 * allocating mixed chunks instead of individual chunks.
3995 */
3996 if (btrfs_mixed_space_info(space_info))
3997 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3998
3999 /*
4000 * if we're doing a data chunk, go ahead and make sure that
4001 * we keep a reasonable number of metadata chunks allocated in the
4002 * FS as well.
4003 */
4004 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4005 fs_info->data_chunk_allocations++;
4006 if (!(fs_info->data_chunk_allocations %
4007 fs_info->metadata_ratio))
4008 force_metadata_allocation(fs_info);
4009 }
4010
820c363b 4011 ret_bg = do_chunk_alloc(trans, flags);
07730d87
JB
4012 trans->allocating_chunk = false;
4013
760e69c4 4014 if (IS_ERR(ret_bg)) {
820c363b 4015 ret = PTR_ERR(ret_bg);
760e69c4
NA
4016 } else if (from_extent_allocation) {
4017 /*
4018 * New block group is likely to be used soon. Try to activate
4019 * it now. Failure is OK for now.
4020 */
4021 btrfs_zone_activate(ret_bg);
4022 }
4023
4024 if (!ret)
820c363b
NA
4025 btrfs_put_block_group(ret_bg);
4026
07730d87
JB
4027 spin_lock(&space_info->lock);
4028 if (ret < 0) {
4029 if (ret == -ENOSPC)
4030 space_info->full = 1;
4031 else
4032 goto out;
4033 } else {
4034 ret = 1;
4035 space_info->max_extent_size = 0;
4036 }
4037
4038 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4039out:
4040 space_info->chunk_alloc = 0;
4041 spin_unlock(&space_info->lock);
4042 mutex_unlock(&fs_info->chunk_mutex);
07730d87
JB
4043
4044 return ret;
4045}
4046
4047static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4048{
4049 u64 num_dev;
4050
4051 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
4052 if (!num_dev)
4053 num_dev = fs_info->fs_devices->rw_devices;
4054
4055 return num_dev;
4056}
4057
2bb2e00e
FM
4058static void reserve_chunk_space(struct btrfs_trans_handle *trans,
4059 u64 bytes,
4060 u64 type)
07730d87
JB
4061{
4062 struct btrfs_fs_info *fs_info = trans->fs_info;
4063 struct btrfs_space_info *info;
4064 u64 left;
07730d87 4065 int ret = 0;
07730d87
JB
4066
4067 /*
4068 * Needed because we can end up allocating a system chunk and for an
4069 * atomic and race free space reservation in the chunk block reserve.
4070 */
4071 lockdep_assert_held(&fs_info->chunk_mutex);
4072
4073 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4074 spin_lock(&info->lock);
4075 left = info->total_bytes - btrfs_space_info_used(info, true);
4076 spin_unlock(&info->lock);
4077
2bb2e00e 4078 if (left < bytes && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
07730d87 4079 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
2bb2e00e 4080 left, bytes, type);
07730d87
JB
4081 btrfs_dump_space_info(fs_info, info, 0, 0);
4082 }
4083
2bb2e00e 4084 if (left < bytes) {
07730d87 4085 u64 flags = btrfs_system_alloc_profile(fs_info);
79bd3712 4086 struct btrfs_block_group *bg;
07730d87
JB
4087
4088 /*
4089 * Ignore failure to create system chunk. We might end up not
4090 * needing it, as we might not need to COW all nodes/leafs from
4091 * the paths we visit in the chunk tree (they were already COWed
4092 * or created in the current transaction for example).
4093 */
f6f39f7a 4094 bg = btrfs_create_chunk(trans, flags);
79bd3712
FM
4095 if (IS_ERR(bg)) {
4096 ret = PTR_ERR(bg);
2bb2e00e 4097 } else {
b6a98021
NA
4098 /*
4099 * We have a new chunk. We also need to activate it for
4100 * zoned filesystem.
4101 */
4102 ret = btrfs_zoned_activate_one_bg(fs_info, info, true);
4103 if (ret < 0)
4104 return;
4105
79bd3712
FM
4106 /*
4107 * If we fail to add the chunk item here, we end up
4108 * trying again at phase 2 of chunk allocation, at
4109 * btrfs_create_pending_block_groups(). So ignore
2bb2e00e
FM
4110 * any error here. An ENOSPC here could happen, due to
4111 * the cases described at do_chunk_alloc() - the system
4112 * block group we just created was just turned into RO
4113 * mode by a scrub for example, or a running discard
4114 * temporarily removed its free space entries, etc.
79bd3712
FM
4115 */
4116 btrfs_chunk_alloc_add_chunk_item(trans, bg);
4117 }
07730d87
JB
4118 }
4119
4120 if (!ret) {
9270501c 4121 ret = btrfs_block_rsv_add(fs_info,
07730d87 4122 &fs_info->chunk_block_rsv,
2bb2e00e 4123 bytes, BTRFS_RESERVE_NO_FLUSH);
1cb3db1c 4124 if (!ret)
2bb2e00e 4125 trans->chunk_bytes_reserved += bytes;
07730d87
JB
4126 }
4127}
4128
2bb2e00e
FM
4129/*
4130 * Reserve space in the system space for allocating or removing a chunk.
4131 * The caller must be holding fs_info->chunk_mutex.
4132 */
4133void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4134{
4135 struct btrfs_fs_info *fs_info = trans->fs_info;
4136 const u64 num_devs = get_profile_num_devs(fs_info, type);
4137 u64 bytes;
4138
4139 /* num_devs device items to update and 1 chunk item to add or remove. */
4140 bytes = btrfs_calc_metadata_size(fs_info, num_devs) +
4141 btrfs_calc_insert_metadata_size(fs_info, 1);
4142
4143 reserve_chunk_space(trans, bytes, type);
4144}
4145
4146/*
4147 * Reserve space in the system space, if needed, for doing a modification to the
4148 * chunk btree.
4149 *
4150 * @trans: A transaction handle.
4151 * @is_item_insertion: Indicate if the modification is for inserting a new item
4152 * in the chunk btree or if it's for the deletion or update
4153 * of an existing item.
4154 *
4155 * This is used in a context where we need to update the chunk btree outside
4156 * block group allocation and removal, to avoid a deadlock with a concurrent
4157 * task that is allocating a metadata or data block group and therefore needs to
4158 * update the chunk btree while holding the chunk mutex. After the update to the
4159 * chunk btree is done, btrfs_trans_release_chunk_metadata() should be called.
4160 *
4161 */
4162void btrfs_reserve_chunk_metadata(struct btrfs_trans_handle *trans,
4163 bool is_item_insertion)
4164{
4165 struct btrfs_fs_info *fs_info = trans->fs_info;
4166 u64 bytes;
4167
4168 if (is_item_insertion)
4169 bytes = btrfs_calc_insert_metadata_size(fs_info, 1);
4170 else
4171 bytes = btrfs_calc_metadata_size(fs_info, 1);
4172
4173 mutex_lock(&fs_info->chunk_mutex);
4174 reserve_chunk_space(trans, bytes, BTRFS_BLOCK_GROUP_SYSTEM);
4175 mutex_unlock(&fs_info->chunk_mutex);
4176}
4177
3e43c279
JB
4178void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
4179{
32da5386 4180 struct btrfs_block_group *block_group;
3e43c279 4181
50c31eaa
JB
4182 block_group = btrfs_lookup_first_block_group(info, 0);
4183 while (block_group) {
4184 btrfs_wait_block_group_cache_done(block_group);
4185 spin_lock(&block_group->lock);
4186 if (test_and_clear_bit(BLOCK_GROUP_FLAG_IREF,
4187 &block_group->runtime_flags)) {
4188 struct inode *inode = block_group->inode;
4189
4190 block_group->inode = NULL;
3e43c279 4191 spin_unlock(&block_group->lock);
3e43c279 4192
50c31eaa
JB
4193 ASSERT(block_group->io_ctl.inode == NULL);
4194 iput(inode);
4195 } else {
4196 spin_unlock(&block_group->lock);
4197 }
4198 block_group = btrfs_next_block_group(block_group);
3e43c279
JB
4199 }
4200}
4201
4202/*
4203 * Must be called only after stopping all workers, since we could have block
4204 * group caching kthreads running, and therefore they could race with us if we
4205 * freed the block groups before stopping them.
4206 */
4207int btrfs_free_block_groups(struct btrfs_fs_info *info)
4208{
32da5386 4209 struct btrfs_block_group *block_group;
3e43c279
JB
4210 struct btrfs_space_info *space_info;
4211 struct btrfs_caching_control *caching_ctl;
4212 struct rb_node *n;
4213
16b0c258 4214 write_lock(&info->block_group_cache_lock);
3e43c279
JB
4215 while (!list_empty(&info->caching_block_groups)) {
4216 caching_ctl = list_entry(info->caching_block_groups.next,
4217 struct btrfs_caching_control, list);
4218 list_del(&caching_ctl->list);
4219 btrfs_put_caching_control(caching_ctl);
4220 }
16b0c258 4221 write_unlock(&info->block_group_cache_lock);
3e43c279
JB
4222
4223 spin_lock(&info->unused_bgs_lock);
4224 while (!list_empty(&info->unused_bgs)) {
4225 block_group = list_first_entry(&info->unused_bgs,
32da5386 4226 struct btrfs_block_group,
3e43c279
JB
4227 bg_list);
4228 list_del_init(&block_group->bg_list);
4229 btrfs_put_block_group(block_group);
4230 }
3e43c279 4231
18bb8bbf
JT
4232 while (!list_empty(&info->reclaim_bgs)) {
4233 block_group = list_first_entry(&info->reclaim_bgs,
4234 struct btrfs_block_group,
4235 bg_list);
4236 list_del_init(&block_group->bg_list);
4237 btrfs_put_block_group(block_group);
4238 }
4239 spin_unlock(&info->unused_bgs_lock);
4240
afba2bc0
NA
4241 spin_lock(&info->zone_active_bgs_lock);
4242 while (!list_empty(&info->zone_active_bgs)) {
4243 block_group = list_first_entry(&info->zone_active_bgs,
4244 struct btrfs_block_group,
4245 active_bg_list);
4246 list_del_init(&block_group->active_bg_list);
4247 btrfs_put_block_group(block_group);
4248 }
4249 spin_unlock(&info->zone_active_bgs_lock);
4250
16b0c258 4251 write_lock(&info->block_group_cache_lock);
08dddb29 4252 while ((n = rb_last(&info->block_group_cache_tree.rb_root)) != NULL) {
32da5386 4253 block_group = rb_entry(n, struct btrfs_block_group,
3e43c279 4254 cache_node);
08dddb29
FM
4255 rb_erase_cached(&block_group->cache_node,
4256 &info->block_group_cache_tree);
3e43c279 4257 RB_CLEAR_NODE(&block_group->cache_node);
16b0c258 4258 write_unlock(&info->block_group_cache_lock);
3e43c279
JB
4259
4260 down_write(&block_group->space_info->groups_sem);
4261 list_del(&block_group->list);
4262 up_write(&block_group->space_info->groups_sem);
4263
4264 /*
4265 * We haven't cached this block group, which means we could
4266 * possibly have excluded extents on this block group.
4267 */
4268 if (block_group->cached == BTRFS_CACHE_NO ||
4269 block_group->cached == BTRFS_CACHE_ERROR)
4270 btrfs_free_excluded_extents(block_group);
4271
4272 btrfs_remove_free_space_cache(block_group);
4273 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
4274 ASSERT(list_empty(&block_group->dirty_list));
4275 ASSERT(list_empty(&block_group->io_list));
4276 ASSERT(list_empty(&block_group->bg_list));
48aaeebe 4277 ASSERT(refcount_read(&block_group->refs) == 1);
195a49ea 4278 ASSERT(block_group->swap_extents == 0);
3e43c279
JB
4279 btrfs_put_block_group(block_group);
4280
16b0c258 4281 write_lock(&info->block_group_cache_lock);
3e43c279 4282 }
16b0c258 4283 write_unlock(&info->block_group_cache_lock);
3e43c279 4284
3e43c279
JB
4285 btrfs_release_global_block_rsv(info);
4286
4287 while (!list_empty(&info->space_info)) {
4288 space_info = list_entry(info->space_info.next,
4289 struct btrfs_space_info,
4290 list);
4291
4292 /*
4293 * Do not hide this behind enospc_debug, this is actually
4294 * important and indicates a real bug if this happens.
4295 */
4296 if (WARN_ON(space_info->bytes_pinned > 0 ||
3e43c279
JB
4297 space_info->bytes_may_use > 0))
4298 btrfs_dump_space_info(info, space_info, 0, 0);
40cdc509
FM
4299
4300 /*
4301 * If there was a failure to cleanup a log tree, very likely due
4302 * to an IO failure on a writeback attempt of one or more of its
4303 * extent buffers, we could not do proper (and cheap) unaccounting
4304 * of their reserved space, so don't warn on bytes_reserved > 0 in
4305 * that case.
4306 */
4307 if (!(space_info->flags & BTRFS_BLOCK_GROUP_METADATA) ||
4308 !BTRFS_FS_LOG_CLEANUP_ERROR(info)) {
4309 if (WARN_ON(space_info->bytes_reserved > 0))
4310 btrfs_dump_space_info(info, space_info, 0, 0);
4311 }
4312
d611add4 4313 WARN_ON(space_info->reclaim_size > 0);
3e43c279
JB
4314 list_del(&space_info->list);
4315 btrfs_sysfs_remove_space_info(space_info);
4316 }
4317 return 0;
4318}
684b752b
FM
4319
4320void btrfs_freeze_block_group(struct btrfs_block_group *cache)
4321{
4322 atomic_inc(&cache->frozen);
4323}
4324
4325void btrfs_unfreeze_block_group(struct btrfs_block_group *block_group)
4326{
4327 struct btrfs_fs_info *fs_info = block_group->fs_info;
4328 struct extent_map_tree *em_tree;
4329 struct extent_map *em;
4330 bool cleanup;
4331
4332 spin_lock(&block_group->lock);
4333 cleanup = (atomic_dec_and_test(&block_group->frozen) &&
3349b57f 4334 test_bit(BLOCK_GROUP_FLAG_REMOVED, &block_group->runtime_flags));
684b752b
FM
4335 spin_unlock(&block_group->lock);
4336
4337 if (cleanup) {
684b752b
FM
4338 em_tree = &fs_info->mapping_tree;
4339 write_lock(&em_tree->lock);
4340 em = lookup_extent_mapping(em_tree, block_group->start,
4341 1);
4342 BUG_ON(!em); /* logic error, can't happen */
4343 remove_extent_mapping(em_tree, em);
4344 write_unlock(&em_tree->lock);
684b752b
FM
4345
4346 /* once for us and once for the tree */
4347 free_extent_map(em);
4348 free_extent_map(em);
4349
4350 /*
4351 * We may have left one free space entry and other possible
4352 * tasks trimming this block group have left 1 entry each one.
4353 * Free them if any.
4354 */
fc80f7ac 4355 btrfs_remove_free_space_cache(block_group);
684b752b
FM
4356 }
4357}
195a49ea
FM
4358
4359bool btrfs_inc_block_group_swap_extents(struct btrfs_block_group *bg)
4360{
4361 bool ret = true;
4362
4363 spin_lock(&bg->lock);
4364 if (bg->ro)
4365 ret = false;
4366 else
4367 bg->swap_extents++;
4368 spin_unlock(&bg->lock);
4369
4370 return ret;
4371}
4372
4373void btrfs_dec_block_group_swap_extents(struct btrfs_block_group *bg, int amount)
4374{
4375 spin_lock(&bg->lock);
4376 ASSERT(!bg->ro);
4377 ASSERT(bg->swap_extents >= amount);
4378 bg->swap_extents -= amount;
4379 spin_unlock(&bg->lock);
4380}
52bb7a21
BB
4381
4382enum btrfs_block_group_size_class btrfs_calc_block_group_size_class(u64 size)
4383{
4384 if (size <= SZ_128K)
4385 return BTRFS_BG_SZ_SMALL;
4386 if (size <= SZ_8M)
4387 return BTRFS_BG_SZ_MEDIUM;
4388 return BTRFS_BG_SZ_LARGE;
4389}
4390
4391/*
4392 * Handle a block group allocating an extent in a size class
4393 *
4394 * @bg: The block group we allocated in.
4395 * @size_class: The size class of the allocation.
4396 * @force_wrong_size_class: Whether we are desperate enough to allow
4397 * mismatched size classes.
4398 *
4399 * Returns: 0 if the size class was valid for this block_group, -EAGAIN in the
4400 * case of a race that leads to the wrong size class without
4401 * force_wrong_size_class set.
4402 *
4403 * find_free_extent will skip block groups with a mismatched size class until
4404 * it really needs to avoid ENOSPC. In that case it will set
4405 * force_wrong_size_class. However, if a block group is newly allocated and
4406 * doesn't yet have a size class, then it is possible for two allocations of
4407 * different sizes to race and both try to use it. The loser is caught here and
4408 * has to retry.
4409 */
4410int btrfs_use_block_group_size_class(struct btrfs_block_group *bg,
4411 enum btrfs_block_group_size_class size_class,
4412 bool force_wrong_size_class)
4413{
4414 ASSERT(size_class != BTRFS_BG_SZ_NONE);
4415
4416 /* The new allocation is in the right size class, do nothing */
4417 if (bg->size_class == size_class)
4418 return 0;
4419 /*
4420 * The new allocation is in a mismatched size class.
4421 * This means one of two things:
4422 *
4423 * 1. Two tasks in find_free_extent for different size_classes raced
4424 * and hit the same empty block_group. Make the loser try again.
4425 * 2. A call to find_free_extent got desperate enough to set
4426 * 'force_wrong_slab'. Don't change the size_class, but allow the
4427 * allocation.
4428 */
4429 if (bg->size_class != BTRFS_BG_SZ_NONE) {
4430 if (force_wrong_size_class)
4431 return 0;
4432 return -EAGAIN;
4433 }
4434 /*
4435 * The happy new block group case: the new allocation is the first
4436 * one in the block_group so we set size_class.
4437 */
4438 bg->size_class = size_class;
4439
4440 return 0;
4441}
cb0922f2
BB
4442
4443bool btrfs_block_group_should_use_size_class(struct btrfs_block_group *bg)
4444{
4445 if (btrfs_is_zoned(bg->fs_info))
4446 return false;
4447 if (!btrfs_is_block_group_data_only(bg))
4448 return false;
4449 return true;
4450}