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