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