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