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