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