blob: 3ceaacdd4ba57d7f685c88264d1e1636340705a9 [file] [log] [blame]
Josef Bacik2e405ad2019-06-20 15:37:45 -04001// SPDX-License-Identifier: GPL-2.0
2
David Sterba784352f2019-08-21 18:54:28 +02003#include "misc.h"
Josef Bacik2e405ad2019-06-20 15:37:45 -04004#include "ctree.h"
5#include "block-group.h"
Josef Bacik3eeb3222019-06-20 15:37:47 -04006#include "space-info.h"
Josef Bacik9f212462019-08-06 16:43:19 +02007#include "disk-io.h"
8#include "free-space-cache.h"
9#include "free-space-tree.h"
Josef Bacike3e05202019-06-20 15:37:55 -040010#include "disk-io.h"
11#include "volumes.h"
12#include "transaction.h"
13#include "ref-verify.h"
Josef Bacik4358d9632019-06-20 15:37:57 -040014#include "sysfs.h"
15#include "tree-log.h"
Josef Bacik77745c02019-06-20 15:38:00 -040016#include "delalloc-space.h"
Dennis Zhoub0643e52019-12-13 16:22:14 -080017#include "discard.h"
Nikolay Borisov96a14332019-12-10 19:57:51 +020018#include "raid56.h"
Josef Bacik2e405ad2019-06-20 15:37:45 -040019
Josef Bacik878d7b62019-06-20 15:38:05 -040020/*
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 */
Josef Bacike11c0402019-06-20 15:38:07 -040026static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
Josef Bacik878d7b62019-06-20 15:38:05 -040027{
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);
Josef Bacike11c0402019-06-20 15:38:07 -040067 target = get_restripe_target(fs_info, flags);
Josef Bacik878d7b62019-06-20 15:38:05 -040068 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
Johannes Thumshirnef0a82d2020-01-02 17:14:57 +0100100u64 btrfs_get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
Josef Bacik878d7b62019-06-20 15:38:05 -0400101{
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
David Sterba32da53862019-10-29 19:20:18 +0100120void btrfs_get_block_group(struct btrfs_block_group *cache)
Josef Bacik3cad1282019-06-20 15:37:46 -0400121{
122 atomic_inc(&cache->count);
123}
124
David Sterba32da53862019-10-29 19:20:18 +0100125void btrfs_put_block_group(struct btrfs_block_group *cache)
Josef Bacik3cad1282019-06-20 15:37:46 -0400126{
127 if (atomic_dec_and_test(&cache->count)) {
128 WARN_ON(cache->pinned > 0);
129 WARN_ON(cache->reserved > 0);
130
131 /*
Dennis Zhoub0643e52019-12-13 16:22:14 -0800132 * 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
140 /*
Josef Bacik3cad1282019-06-20 15:37:46 -0400141 * 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
Josef Bacik2e405ad2019-06-20 15:37:45 -0400154/*
Josef Bacik4358d9632019-06-20 15:37:57 -0400155 * 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,
David Sterba32da53862019-10-29 19:20:18 +0100158 struct btrfs_block_group *block_group)
Josef Bacik4358d9632019-06-20 15:37:57 -0400159{
160 struct rb_node **p;
161 struct rb_node *parent = NULL;
David Sterba32da53862019-10-29 19:20:18 +0100162 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -0400163
164 spin_lock(&info->block_group_cache_lock);
165 p = &info->block_group_cache_tree.rb_node;
166
167 while (*p) {
168 parent = *p;
David Sterba32da53862019-10-29 19:20:18 +0100169 cache = rb_entry(parent, struct btrfs_block_group, cache_node);
David Sterbab3470b52019-10-23 18:48:22 +0200170 if (block_group->start < cache->start) {
Josef Bacik4358d9632019-06-20 15:37:57 -0400171 p = &(*p)->rb_left;
David Sterbab3470b52019-10-23 18:48:22 +0200172 } else if (block_group->start > cache->start) {
Josef Bacik4358d9632019-06-20 15:37:57 -0400173 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
David Sterbab3470b52019-10-23 18:48:22 +0200184 if (info->first_logical_byte > block_group->start)
185 info->first_logical_byte = block_group->start;
Josef Bacik4358d9632019-06-20 15:37:57 -0400186
187 spin_unlock(&info->block_group_cache_lock);
188
189 return 0;
190}
191
192/*
Josef Bacik2e405ad2019-06-20 15:37:45 -0400193 * 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 */
David Sterba32da53862019-10-29 19:20:18 +0100196static struct btrfs_block_group *block_group_cache_tree_search(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400197 struct btrfs_fs_info *info, u64 bytenr, int contains)
198{
David Sterba32da53862019-10-29 19:20:18 +0100199 struct btrfs_block_group *cache, *ret = NULL;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400200 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) {
David Sterba32da53862019-10-29 19:20:18 +0100207 cache = rb_entry(n, struct btrfs_block_group, cache_node);
David Sterbab3470b52019-10-23 18:48:22 +0200208 end = cache->start + cache->length - 1;
209 start = cache->start;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400210
211 if (bytenr < start) {
David Sterbab3470b52019-10-23 18:48:22 +0200212 if (!contains && (!ret || start < ret->start))
Josef Bacik2e405ad2019-06-20 15:37:45 -0400213 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);
David Sterbab3470b52019-10-23 18:48:22 +0200228 if (bytenr == 0 && info->first_logical_byte > ret->start)
229 info->first_logical_byte = ret->start;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400230 }
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 */
David Sterba32da53862019-10-29 19:20:18 +0100239struct btrfs_block_group *btrfs_lookup_first_block_group(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400240 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 */
David Sterba32da53862019-10-29 19:20:18 +0100248struct btrfs_block_group *btrfs_lookup_block_group(
Josef Bacik2e405ad2019-06-20 15:37:45 -0400249 struct btrfs_fs_info *info, u64 bytenr)
250{
251 return block_group_cache_tree_search(info, bytenr, 1);
252}
253
David Sterba32da53862019-10-29 19:20:18 +0100254struct btrfs_block_group *btrfs_next_block_group(
255 struct btrfs_block_group *cache)
Josef Bacik2e405ad2019-06-20 15:37:45 -0400256{
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)) {
David Sterbab3470b52019-10-23 18:48:22 +0200264 const u64 next_bytenr = cache->start + cache->length;
Josef Bacik2e405ad2019-06-20 15:37:45 -0400265
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) {
David Sterba32da53862019-10-29 19:20:18 +0100273 cache = rb_entry(node, struct btrfs_block_group, cache_node);
Josef Bacik2e405ad2019-06-20 15:37:45 -0400274 btrfs_get_block_group(cache);
275 } else
276 cache = NULL;
277 spin_unlock(&fs_info->block_group_cache_lock);
278 return cache;
279}
Josef Bacik3eeb3222019-06-20 15:37:47 -0400280
281bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
282{
David Sterba32da53862019-10-29 19:20:18 +0100283 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400284 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{
David Sterba32da53862019-10-29 19:20:18 +0100306 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400307
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
David Sterba32da53862019-10-29 19:20:18 +0100320void btrfs_wait_nocow_writers(struct btrfs_block_group *bg)
Josef Bacik3eeb3222019-06-20 15:37:47 -0400321{
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{
David Sterba32da53862019-10-29 19:20:18 +0100328 struct btrfs_block_group *bg;
Josef Bacik3eeb3222019-06-20 15:37:47 -0400329
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
David Sterba32da53862019-10-29 19:20:18 +0100337void btrfs_wait_block_group_reservations(struct btrfs_block_group *bg)
Josef Bacik3eeb3222019-06-20 15:37:47 -0400338{
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}
Josef Bacik9f212462019-08-06 16:43:19 +0200361
362struct btrfs_caching_control *btrfs_get_caching_control(
David Sterba32da53862019-10-29 19:20:18 +0100363 struct btrfs_block_group *cache)
Josef Bacik9f212462019-08-06 16:43:19 +0200364{
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 */
David Sterba32da53862019-10-29 19:20:18 +0100398void btrfs_wait_block_group_cache_progress(struct btrfs_block_group *cache,
Josef Bacik9f212462019-08-06 16:43:19 +0200399 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
David Sterba32da53862019-10-29 19:20:18 +0100407 wait_event(caching_ctl->wait, btrfs_block_group_done(cache) ||
Josef Bacik9f212462019-08-06 16:43:19 +0200408 (cache->free_space_ctl->free_space >= num_bytes));
409
410 btrfs_put_caching_control(caching_ctl);
411}
412
David Sterba32da53862019-10-29 19:20:18 +0100413int btrfs_wait_block_group_cache_done(struct btrfs_block_group *cache)
Josef Bacik9f212462019-08-06 16:43:19 +0200414{
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
David Sterba32da53862019-10-29 19:20:18 +0100422 wait_event(caching_ctl->wait, btrfs_block_group_done(cache));
Josef Bacik9f212462019-08-06 16:43:19 +0200423 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
David Sterba32da53862019-10-29 19:20:18 +0100430static void fragment_free_space(struct btrfs_block_group *block_group)
Josef Bacik9f212462019-08-06 16:43:19 +0200431{
432 struct btrfs_fs_info *fs_info = block_group->fs_info;
David Sterbab3470b52019-10-23 18:48:22 +0200433 u64 start = block_group->start;
434 u64 len = block_group->length;
Josef Bacik9f212462019-08-06 16:43:19 +0200435 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 */
David Sterba32da53862019-10-29 19:20:18 +0100456u64 add_new_free_space(struct btrfs_block_group *block_group, u64 start, u64 end)
Josef Bacik9f212462019-08-06 16:43:19 +0200457{
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) {
Nikolay Borisovfe119a62020-01-20 16:09:18 +0200463 ret = find_first_extent_bit(&info->excluded_extents, start,
Josef Bacik9f212462019-08-06 16:43:19 +0200464 &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;
Dennis Zhoub0643e52019-12-13 16:22:14 -0800475 ret = btrfs_add_free_space_async_trimmed(block_group,
476 start, size);
Josef Bacik9f212462019-08-06 16:43:19 +0200477 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;
Dennis Zhoub0643e52019-12-13 16:22:14 -0800487 ret = btrfs_add_free_space_async_trimmed(block_group, start,
488 size);
Josef Bacik9f212462019-08-06 16:43:19 +0200489 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{
David Sterba32da53862019-10-29 19:20:18 +0100497 struct btrfs_block_group *block_group = caching_ctl->block_group;
Josef Bacik9f212462019-08-06 16:43:19 +0200498 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
David Sterbab3470b52019-10-23 18:48:22 +0200513 last = max_t(u64, block_group->start, BTRFS_SUPER_INFO_OFFSET);
Josef Bacik9f212462019-08-06 16:43:19 +0200514
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
David Sterbab3470b52019-10-23 18:48:22 +0200593 if (key.objectid < block_group->start) {
Josef Bacik9f212462019-08-06 16:43:19 +0200594 path->slots[0]++;
595 continue;
596 }
597
David Sterbab3470b52019-10-23 18:48:22 +0200598 if (key.objectid >= block_group->start + block_group->length)
Josef Bacik9f212462019-08-06 16:43:19 +0200599 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,
David Sterbab3470b52019-10-23 18:48:22 +0200622 block_group->start + block_group->length);
Josef Bacik9f212462019-08-06 16:43:19 +0200623 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{
David Sterba32da53862019-10-29 19:20:18 +0100632 struct btrfs_block_group *block_group;
Josef Bacik9f212462019-08-06 16:43:19 +0200633 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);
David Sterbab3470b52019-10-23 18:48:22 +0200660 bytes_used = block_group->length - block_group->used;
Josef Bacik9f212462019-08-06 16:43:19 +0200661 block_group->space_info->bytes_used += bytes_used >> 1;
662 spin_unlock(&block_group->lock);
663 spin_unlock(&block_group->space_info->lock);
Josef Bacike11c0402019-06-20 15:38:07 -0400664 fragment_free_space(block_group);
Josef Bacik9f212462019-08-06 16:43:19 +0200665 }
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
David Sterba32da53862019-10-29 19:20:18 +0100680int btrfs_cache_block_group(struct btrfs_block_group *cache, int load_cache_only)
Josef Bacik9f212462019-08-06 16:43:19 +0200681{
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;
David Sterbab3470b52019-10-23 18:48:22 +0200695 caching_ctl->progress = cache->start;
Josef Bacik9f212462019-08-06 16:43:19 +0200696 refcount_set(&caching_ctl->count, 1);
Omar Sandovala0cac0e2019-09-16 11:30:57 -0700697 btrfs_init_work(&caching_ctl->work, caching_thread, NULL, NULL);
Josef Bacik9f212462019-08-06 16:43:19 +0200698
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);
David Sterbab3470b52019-10-23 18:48:22 +0200764 bytes_used = cache->length - cache->used;
Josef Bacik9f212462019-08-06 16:43:19 +0200765 cache->space_info->bytes_used += bytes_used >> 1;
766 spin_unlock(&cache->lock);
767 spin_unlock(&cache->space_info->lock);
Josef Bacike11c0402019-06-20 15:38:07 -0400768 fragment_free_space(cache);
Josef Bacik9f212462019-08-06 16:43:19 +0200769 }
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}
Josef Bacike3e05202019-06-20 15:37:55 -0400812
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
David Sterba9c907442019-10-31 15:52:01 +0100833 *
834 * - RAID1C34 - same as above for RAID1C3 and RAID1C4 block groups
Josef Bacike3e05202019-06-20 15:37:55 -0400835 */
836static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
837{
David Sterba9c907442019-10-31 15:52:01 +0100838 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)) {
Josef Bacike3e05202019-06-20 15:37:55 -0400844 struct list_head *head = &fs_info->space_info;
845 struct btrfs_space_info *sinfo;
846
847 list_for_each_entry_rcu(sinfo, head, list) {
Josef Bacike3e05202019-06-20 15:37:55 -0400848 down_read(&sinfo->groups_sem);
849 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
David Sterba9c907442019-10-31 15:52:01 +0100850 found_raid56 = true;
Josef Bacike3e05202019-06-20 15:37:55 -0400851 if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
David Sterba9c907442019-10-31 15:52:01 +0100852 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;
Josef Bacike3e05202019-06-20 15:37:55 -0400857 up_read(&sinfo->groups_sem);
Josef Bacike3e05202019-06-20 15:37:55 -0400858 }
Filipe Mananad8e6fd52020-03-20 18:43:48 +0000859 if (!found_raid56)
David Sterba9c907442019-10-31 15:52:01 +0100860 btrfs_clear_fs_incompat(fs_info, RAID56);
Filipe Mananad8e6fd52020-03-20 18:43:48 +0000861 if (!found_raid1c34)
David Sterba9c907442019-10-31 15:52:01 +0100862 btrfs_clear_fs_incompat(fs_info, RAID1C34);
Josef Bacike3e05202019-06-20 15:37:55 -0400863 }
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;
David Sterba32da53862019-10-29 19:20:18 +0100872 struct btrfs_block_group *block_group;
Josef Bacike3e05202019-06-20 15:37:55 -0400873 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);
David Sterbab3470b52019-10-23 18:48:22 +0200895 btrfs_free_ref_tree_range(fs_info, block_group->start,
896 block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -0400897
Josef Bacike3e05202019-06-20 15:37:55 -0400898 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;
Xiyu Yangf6033c52020-04-21 10:54:11 +0800919 goto out_put_group;
Josef Bacike3e05202019-06-20 15:37:55 -0400920 }
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);
Xiyu Yangf6033c52020-04-21 10:54:11 +0800957 goto out_put_group;
Josef Bacike3e05202019-06-20 15:37:55 -0400958 }
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;
Josef Bacike3e05202019-06-20 15:37:55 -0400975 key.type = 0;
David Sterbab3470b52019-10-23 18:48:22 +0200976 key.offset = block_group->start;
Josef Bacike3e05202019-06-20 15:37:55 -0400977
978 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
979 if (ret < 0)
Xiyu Yangf6033c52020-04-21 10:54:11 +0800980 goto out_put_group;
Josef Bacike3e05202019-06-20 15:37:55 -0400981 if (ret > 0)
982 btrfs_release_path(path);
983 if (ret == 0) {
984 ret = btrfs_del_item(trans, tree_root, path);
985 if (ret)
Xiyu Yangf6033c52020-04-21 10:54:11 +0800986 goto out_put_group;
Josef Bacike3e05202019-06-20 15:37:55 -0400987 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
David Sterbab3470b52019-10-23 18:48:22 +0200995 if (fs_info->first_logical_byte == block_group->start)
Josef Bacike3e05202019-06-20 15:37:55 -0400996 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
David Sterbab3470b52019-10-23 18:48:22 +02001056 < block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -04001057 WARN_ON(block_group->space_info->bytes_readonly
David Sterbab3470b52019-10-23 18:48:22 +02001058 < block_group->length);
Josef Bacike3e05202019-06-20 15:37:55 -04001059 WARN_ON(block_group->space_info->disk_total
David Sterbab3470b52019-10-23 18:48:22 +02001060 < block_group->length * factor);
Josef Bacike3e05202019-06-20 15:37:55 -04001061 }
David Sterbab3470b52019-10-23 18:48:22 +02001062 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;
Josef Bacike3e05202019-06-20 15:37:55 -04001065
1066 spin_unlock(&block_group->space_info->lock);
1067
David Sterbab3470b52019-10-23 18:48:22 +02001068 key.objectid = block_group->start;
1069 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1070 key.offset = block_group->length;
Josef Bacike3e05202019-06-20 15:37:55 -04001071
1072 mutex_lock(&fs_info->chunk_mutex);
1073 spin_lock(&block_group->lock);
1074 block_group->removed = 1;
1075 /*
Filipe Manana6b7304a2020-05-08 11:01:47 +01001076 * At this point trimming or scrub can't start on this block group,
1077 * because we removed the block group from the rbtree
1078 * fs_info->block_group_cache_tree so no one can't find it anymore and
1079 * even if someone already got this block group before we removed it
1080 * from the rbtree, they have already incremented block_group->frozen -
1081 * if they didn't, for the trimming case they won't find any free space
1082 * entries because we already removed them all when we called
1083 * btrfs_remove_free_space_cache().
Josef Bacike3e05202019-06-20 15:37:55 -04001084 *
1085 * And we must not remove the extent map from the fs_info->mapping_tree
1086 * to prevent the same logical address range and physical device space
Filipe Manana6b7304a2020-05-08 11:01:47 +01001087 * ranges from being reused for a new block group. This is needed to
1088 * avoid races with trimming and scrub.
1089 *
1090 * An fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
Josef Bacike3e05202019-06-20 15:37:55 -04001091 * completely transactionless, so while it is trimming a range the
1092 * currently running transaction might finish and a new one start,
1093 * allowing for new block groups to be created that can reuse the same
1094 * physical device locations unless we take this special care.
1095 *
1096 * There may also be an implicit trim operation if the file system
1097 * is mounted with -odiscard. The same protections must remain
1098 * in place until the extents have been discarded completely when
1099 * the transaction commit has completed.
1100 */
Filipe Manana6b7304a2020-05-08 11:01:47 +01001101 remove_em = (atomic_read(&block_group->frozen) == 0);
Josef Bacike3e05202019-06-20 15:37:55 -04001102 spin_unlock(&block_group->lock);
1103
1104 mutex_unlock(&fs_info->chunk_mutex);
1105
1106 ret = remove_block_group_free_space(trans, block_group);
1107 if (ret)
Xiyu Yangf6033c52020-04-21 10:54:11 +08001108 goto out_put_group;
Josef Bacike3e05202019-06-20 15:37:55 -04001109
Xiyu Yangf6033c52020-04-21 10:54:11 +08001110 /* Once for the block groups rbtree */
Josef Bacike3e05202019-06-20 15:37:55 -04001111 btrfs_put_block_group(block_group);
1112
1113 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1114 if (ret > 0)
1115 ret = -EIO;
1116 if (ret < 0)
1117 goto out;
1118
1119 ret = btrfs_del_item(trans, root, path);
1120 if (ret)
1121 goto out;
1122
1123 if (remove_em) {
1124 struct extent_map_tree *em_tree;
1125
1126 em_tree = &fs_info->mapping_tree;
1127 write_lock(&em_tree->lock);
1128 remove_extent_mapping(em_tree, em);
1129 write_unlock(&em_tree->lock);
1130 /* once for the tree */
1131 free_extent_map(em);
1132 }
Xiyu Yangf6033c52020-04-21 10:54:11 +08001133
1134out_put_group:
1135 /* Once for the lookup reference */
1136 btrfs_put_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001137out:
1138 if (remove_rsv)
1139 btrfs_delayed_refs_rsv_release(fs_info, 1);
1140 btrfs_free_path(path);
1141 return ret;
1142}
1143
1144struct btrfs_trans_handle *btrfs_start_trans_remove_block_group(
1145 struct btrfs_fs_info *fs_info, const u64 chunk_offset)
1146{
1147 struct extent_map_tree *em_tree = &fs_info->mapping_tree;
1148 struct extent_map *em;
1149 struct map_lookup *map;
1150 unsigned int num_items;
1151
1152 read_lock(&em_tree->lock);
1153 em = lookup_extent_mapping(em_tree, chunk_offset, 1);
1154 read_unlock(&em_tree->lock);
1155 ASSERT(em && em->start == chunk_offset);
1156
1157 /*
1158 * We need to reserve 3 + N units from the metadata space info in order
1159 * to remove a block group (done at btrfs_remove_chunk() and at
1160 * btrfs_remove_block_group()), which are used for:
1161 *
1162 * 1 unit for adding the free space inode's orphan (located in the tree
1163 * of tree roots).
1164 * 1 unit for deleting the block group item (located in the extent
1165 * tree).
1166 * 1 unit for deleting the free space item (located in tree of tree
1167 * roots).
1168 * N units for deleting N device extent items corresponding to each
1169 * stripe (located in the device tree).
1170 *
1171 * In order to remove a block group we also need to reserve units in the
1172 * system space info in order to update the chunk tree (update one or
1173 * more device items and remove one chunk item), but this is done at
1174 * btrfs_remove_chunk() through a call to check_system_chunk().
1175 */
1176 map = em->map_lookup;
1177 num_items = 3 + map->num_stripes;
1178 free_extent_map(em);
1179
1180 return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
Josef Bacik7f9fe612020-03-13 15:58:05 -04001181 num_items);
Josef Bacike3e05202019-06-20 15:37:55 -04001182}
1183
1184/*
Josef Bacik26ce2092019-06-20 15:37:59 -04001185 * Mark block group @cache read-only, so later write won't happen to block
1186 * group @cache.
1187 *
1188 * If @force is not set, this function will only mark the block group readonly
1189 * if we have enough free space (1M) in other metadata/system block groups.
1190 * If @force is not set, this function will mark the block group readonly
1191 * without checking free space.
1192 *
1193 * NOTE: This function doesn't care if other block groups can contain all the
1194 * data in this block group. That check should be done by relocation routine,
1195 * not this function.
1196 */
David Sterba32da53862019-10-29 19:20:18 +01001197static int inc_block_group_ro(struct btrfs_block_group *cache, int force)
Josef Bacik26ce2092019-06-20 15:37:59 -04001198{
1199 struct btrfs_space_info *sinfo = cache->space_info;
1200 u64 num_bytes;
Josef Bacik26ce2092019-06-20 15:37:59 -04001201 int ret = -ENOSPC;
1202
Josef Bacik26ce2092019-06-20 15:37:59 -04001203 spin_lock(&sinfo->lock);
1204 spin_lock(&cache->lock);
1205
1206 if (cache->ro) {
1207 cache->ro++;
1208 ret = 0;
1209 goto out;
1210 }
1211
David Sterbab3470b52019-10-23 18:48:22 +02001212 num_bytes = cache->length - cache->reserved - cache->pinned -
David Sterbabf38be62019-10-23 18:48:11 +02001213 cache->bytes_super - cache->used;
Josef Bacik26ce2092019-06-20 15:37:59 -04001214
1215 /*
Josef Bacika30a3d22020-01-17 09:07:39 -05001216 * Data never overcommits, even in mixed mode, so do just the straight
1217 * check of left over space in how much we have allocated.
Josef Bacik26ce2092019-06-20 15:37:59 -04001218 */
Josef Bacika30a3d22020-01-17 09:07:39 -05001219 if (force) {
1220 ret = 0;
1221 } else if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA) {
1222 u64 sinfo_used = btrfs_space_info_used(sinfo, true);
1223
1224 /*
1225 * Here we make sure if we mark this bg RO, we still have enough
1226 * free space as buffer.
1227 */
1228 if (sinfo_used + num_bytes <= sinfo->total_bytes)
1229 ret = 0;
1230 } else {
1231 /*
1232 * We overcommit metadata, so we need to do the
1233 * btrfs_can_overcommit check here, and we need to pass in
1234 * BTRFS_RESERVE_NO_FLUSH to give ourselves the most amount of
1235 * leeway to allow us to mark this block group as read only.
1236 */
1237 if (btrfs_can_overcommit(cache->fs_info, sinfo, num_bytes,
1238 BTRFS_RESERVE_NO_FLUSH))
1239 ret = 0;
1240 }
1241
1242 if (!ret) {
Josef Bacik26ce2092019-06-20 15:37:59 -04001243 sinfo->bytes_readonly += num_bytes;
1244 cache->ro++;
1245 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
Josef Bacik26ce2092019-06-20 15:37:59 -04001246 }
1247out:
1248 spin_unlock(&cache->lock);
1249 spin_unlock(&sinfo->lock);
1250 if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
1251 btrfs_info(cache->fs_info,
David Sterbab3470b52019-10-23 18:48:22 +02001252 "unable to make block group %llu ro", cache->start);
Josef Bacik26ce2092019-06-20 15:37:59 -04001253 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
1254 }
1255 return ret;
1256}
1257
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001258static bool clean_pinned_extents(struct btrfs_trans_handle *trans,
1259 struct btrfs_block_group *bg)
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001260{
1261 struct btrfs_fs_info *fs_info = bg->fs_info;
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001262 struct btrfs_transaction *prev_trans = NULL;
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001263 const u64 start = bg->start;
1264 const u64 end = start + bg->length - 1;
1265 int ret;
1266
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001267 spin_lock(&fs_info->trans_lock);
1268 if (trans->transaction->list.prev != &fs_info->trans_list) {
1269 prev_trans = list_last_entry(&trans->transaction->list,
1270 struct btrfs_transaction, list);
1271 refcount_inc(&prev_trans->use_count);
1272 }
1273 spin_unlock(&fs_info->trans_lock);
1274
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001275 /*
1276 * Hold the unused_bg_unpin_mutex lock to avoid racing with
1277 * btrfs_finish_extent_commit(). If we are at transaction N, another
1278 * task might be running finish_extent_commit() for the previous
1279 * transaction N - 1, and have seen a range belonging to the block
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001280 * group in pinned_extents before we were able to clear the whole block
1281 * group range from pinned_extents. This means that task can lookup for
1282 * the block group after we unpinned it from pinned_extents and removed
1283 * it, leading to a BUG_ON() at unpin_extent_range().
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001284 */
1285 mutex_lock(&fs_info->unused_bg_unpin_mutex);
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001286 if (prev_trans) {
1287 ret = clear_extent_bits(&prev_trans->pinned_extents, start, end,
1288 EXTENT_DIRTY);
1289 if (ret)
Filipe Manana534cf532020-04-17 16:36:50 +01001290 goto out;
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001291 }
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001292
Nikolay Borisovfe119a62020-01-20 16:09:18 +02001293 ret = clear_extent_bits(&trans->transaction->pinned_extents, start, end,
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001294 EXTENT_DIRTY);
Filipe Manana534cf532020-04-17 16:36:50 +01001295out:
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001296 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
Filipe Manana5150bf12020-04-17 16:36:15 +01001297 if (prev_trans)
1298 btrfs_put_transaction(prev_trans);
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001299
Filipe Manana534cf532020-04-17 16:36:50 +01001300 return ret == 0;
Nikolay Borisov45bb5d62020-01-20 16:09:17 +02001301}
1302
Josef Bacik26ce2092019-06-20 15:37:59 -04001303/*
Josef Bacike3e05202019-06-20 15:37:55 -04001304 * Process the unused_bgs list and remove any that don't have any allocated
1305 * space inside of them.
1306 */
1307void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
1308{
David Sterba32da53862019-10-29 19:20:18 +01001309 struct btrfs_block_group *block_group;
Josef Bacike3e05202019-06-20 15:37:55 -04001310 struct btrfs_space_info *space_info;
1311 struct btrfs_trans_handle *trans;
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001312 const bool async_trim_enabled = btrfs_test_opt(fs_info, DISCARD_ASYNC);
Josef Bacike3e05202019-06-20 15:37:55 -04001313 int ret = 0;
1314
1315 if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
1316 return;
1317
1318 spin_lock(&fs_info->unused_bgs_lock);
1319 while (!list_empty(&fs_info->unused_bgs)) {
Josef Bacike3e05202019-06-20 15:37:55 -04001320 int trimming;
1321
1322 block_group = list_first_entry(&fs_info->unused_bgs,
David Sterba32da53862019-10-29 19:20:18 +01001323 struct btrfs_block_group,
Josef Bacike3e05202019-06-20 15:37:55 -04001324 bg_list);
1325 list_del_init(&block_group->bg_list);
1326
1327 space_info = block_group->space_info;
1328
1329 if (ret || btrfs_mixed_space_info(space_info)) {
1330 btrfs_put_block_group(block_group);
1331 continue;
1332 }
1333 spin_unlock(&fs_info->unused_bgs_lock);
1334
Dennis Zhoub0643e52019-12-13 16:22:14 -08001335 btrfs_discard_cancel_work(&fs_info->discard_ctl, block_group);
1336
Josef Bacike3e05202019-06-20 15:37:55 -04001337 mutex_lock(&fs_info->delete_unused_bgs_mutex);
1338
1339 /* Don't want to race with allocators so take the groups_sem */
1340 down_write(&space_info->groups_sem);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001341
1342 /*
1343 * Async discard moves the final block group discard to be prior
1344 * to the unused_bgs code path. Therefore, if it's not fully
1345 * trimmed, punt it back to the async discard lists.
1346 */
1347 if (btrfs_test_opt(fs_info, DISCARD_ASYNC) &&
1348 !btrfs_is_free_space_trimmed(block_group)) {
1349 trace_btrfs_skip_unused_block_group(block_group);
1350 up_write(&space_info->groups_sem);
1351 /* Requeue if we failed because of async discard */
1352 btrfs_discard_queue_work(&fs_info->discard_ctl,
1353 block_group);
1354 goto next;
1355 }
1356
Josef Bacike3e05202019-06-20 15:37:55 -04001357 spin_lock(&block_group->lock);
1358 if (block_group->reserved || block_group->pinned ||
David Sterbabf38be62019-10-23 18:48:11 +02001359 block_group->used || block_group->ro ||
Josef Bacike3e05202019-06-20 15:37:55 -04001360 list_is_singular(&block_group->list)) {
1361 /*
1362 * We want to bail if we made new allocations or have
1363 * outstanding allocations in this block group. We do
1364 * the ro check in case balance is currently acting on
1365 * this block group.
1366 */
1367 trace_btrfs_skip_unused_block_group(block_group);
1368 spin_unlock(&block_group->lock);
1369 up_write(&space_info->groups_sem);
1370 goto next;
1371 }
1372 spin_unlock(&block_group->lock);
1373
1374 /* We don't want to force the issue, only flip if it's ok. */
Josef Bacike11c0402019-06-20 15:38:07 -04001375 ret = inc_block_group_ro(block_group, 0);
Josef Bacike3e05202019-06-20 15:37:55 -04001376 up_write(&space_info->groups_sem);
1377 if (ret < 0) {
1378 ret = 0;
1379 goto next;
1380 }
1381
1382 /*
1383 * Want to do this before we do anything else so we can recover
1384 * properly if we fail to join the transaction.
1385 */
1386 trans = btrfs_start_trans_remove_block_group(fs_info,
David Sterbab3470b52019-10-23 18:48:22 +02001387 block_group->start);
Josef Bacike3e05202019-06-20 15:37:55 -04001388 if (IS_ERR(trans)) {
1389 btrfs_dec_block_group_ro(block_group);
1390 ret = PTR_ERR(trans);
1391 goto next;
1392 }
1393
1394 /*
1395 * We could have pending pinned extents for this block group,
1396 * just delete them, we don't care about them anymore.
1397 */
Filipe Manana534cf532020-04-17 16:36:50 +01001398 if (!clean_pinned_extents(trans, block_group)) {
1399 btrfs_dec_block_group_ro(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001400 goto end_trans;
Filipe Manana534cf532020-04-17 16:36:50 +01001401 }
Josef Bacike3e05202019-06-20 15:37:55 -04001402
Dennis Zhoub0643e52019-12-13 16:22:14 -08001403 /*
1404 * At this point, the block_group is read only and should fail
1405 * new allocations. However, btrfs_finish_extent_commit() can
1406 * cause this block_group to be placed back on the discard
1407 * lists because now the block_group isn't fully discarded.
1408 * Bail here and try again later after discarding everything.
1409 */
1410 spin_lock(&fs_info->discard_ctl.lock);
1411 if (!list_empty(&block_group->discard_list)) {
1412 spin_unlock(&fs_info->discard_ctl.lock);
1413 btrfs_dec_block_group_ro(block_group);
1414 btrfs_discard_queue_work(&fs_info->discard_ctl,
1415 block_group);
1416 goto end_trans;
1417 }
1418 spin_unlock(&fs_info->discard_ctl.lock);
1419
Josef Bacike3e05202019-06-20 15:37:55 -04001420 /* Reset pinned so btrfs_put_block_group doesn't complain */
1421 spin_lock(&space_info->lock);
1422 spin_lock(&block_group->lock);
1423
1424 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
1425 -block_group->pinned);
1426 space_info->bytes_readonly += block_group->pinned;
1427 percpu_counter_add_batch(&space_info->total_bytes_pinned,
1428 -block_group->pinned,
1429 BTRFS_TOTAL_BYTES_PINNED_BATCH);
1430 block_group->pinned = 0;
1431
1432 spin_unlock(&block_group->lock);
1433 spin_unlock(&space_info->lock);
1434
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001435 /*
1436 * The normal path here is an unused block group is passed here,
1437 * then trimming is handled in the transaction commit path.
1438 * Async discard interposes before this to do the trimming
1439 * before coming down the unused block group path as trimming
1440 * will no longer be done later in the transaction commit path.
1441 */
1442 if (!async_trim_enabled && btrfs_test_opt(fs_info, DISCARD_ASYNC))
1443 goto flip_async;
1444
Josef Bacike3e05202019-06-20 15:37:55 -04001445 /* DISCARD can flip during remount */
Dennis Zhou46b27f52019-12-13 16:22:11 -08001446 trimming = btrfs_test_opt(fs_info, DISCARD_SYNC);
Josef Bacike3e05202019-06-20 15:37:55 -04001447
1448 /* Implicit trim during transaction commit. */
1449 if (trimming)
Filipe Manana6b7304a2020-05-08 11:01:47 +01001450 btrfs_freeze_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001451
1452 /*
1453 * Btrfs_remove_chunk will abort the transaction if things go
1454 * horribly wrong.
1455 */
David Sterbab3470b52019-10-23 18:48:22 +02001456 ret = btrfs_remove_chunk(trans, block_group->start);
Josef Bacike3e05202019-06-20 15:37:55 -04001457
1458 if (ret) {
1459 if (trimming)
Filipe Manana6b7304a2020-05-08 11:01:47 +01001460 btrfs_unfreeze_block_group(block_group);
Josef Bacike3e05202019-06-20 15:37:55 -04001461 goto end_trans;
1462 }
1463
1464 /*
1465 * If we're not mounted with -odiscard, we can just forget
1466 * about this block group. Otherwise we'll need to wait
1467 * until transaction commit to do the actual discard.
1468 */
1469 if (trimming) {
1470 spin_lock(&fs_info->unused_bgs_lock);
1471 /*
1472 * A concurrent scrub might have added us to the list
1473 * fs_info->unused_bgs, so use a list_move operation
1474 * to add the block group to the deleted_bgs list.
1475 */
1476 list_move(&block_group->bg_list,
1477 &trans->transaction->deleted_bgs);
1478 spin_unlock(&fs_info->unused_bgs_lock);
1479 btrfs_get_block_group(block_group);
1480 }
1481end_trans:
1482 btrfs_end_transaction(trans);
1483next:
1484 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1485 btrfs_put_block_group(block_group);
1486 spin_lock(&fs_info->unused_bgs_lock);
1487 }
1488 spin_unlock(&fs_info->unused_bgs_lock);
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001489 return;
1490
1491flip_async:
1492 btrfs_end_transaction(trans);
1493 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
1494 btrfs_put_block_group(block_group);
1495 btrfs_discard_punt_unused_bgs_list(fs_info);
Josef Bacike3e05202019-06-20 15:37:55 -04001496}
1497
David Sterba32da53862019-10-29 19:20:18 +01001498void btrfs_mark_bg_unused(struct btrfs_block_group *bg)
Josef Bacike3e05202019-06-20 15:37:55 -04001499{
1500 struct btrfs_fs_info *fs_info = bg->fs_info;
1501
1502 spin_lock(&fs_info->unused_bgs_lock);
1503 if (list_empty(&bg->bg_list)) {
1504 btrfs_get_block_group(bg);
1505 trace_btrfs_add_unused_block_group(bg);
1506 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
1507 }
1508 spin_unlock(&fs_info->unused_bgs_lock);
1509}
Josef Bacik4358d9632019-06-20 15:37:57 -04001510
1511static int find_first_block_group(struct btrfs_fs_info *fs_info,
1512 struct btrfs_path *path,
1513 struct btrfs_key *key)
1514{
1515 struct btrfs_root *root = fs_info->extent_root;
1516 int ret = 0;
1517 struct btrfs_key found_key;
1518 struct extent_buffer *leaf;
1519 struct btrfs_block_group_item bg;
1520 u64 flags;
1521 int slot;
1522
1523 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
1524 if (ret < 0)
1525 goto out;
1526
1527 while (1) {
1528 slot = path->slots[0];
1529 leaf = path->nodes[0];
1530 if (slot >= btrfs_header_nritems(leaf)) {
1531 ret = btrfs_next_leaf(root, path);
1532 if (ret == 0)
1533 continue;
1534 if (ret < 0)
1535 goto out;
1536 break;
1537 }
1538 btrfs_item_key_to_cpu(leaf, &found_key, slot);
1539
1540 if (found_key.objectid >= key->objectid &&
1541 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
1542 struct extent_map_tree *em_tree;
1543 struct extent_map *em;
1544
1545 em_tree = &root->fs_info->mapping_tree;
1546 read_lock(&em_tree->lock);
1547 em = lookup_extent_mapping(em_tree, found_key.objectid,
1548 found_key.offset);
1549 read_unlock(&em_tree->lock);
1550 if (!em) {
1551 btrfs_err(fs_info,
1552 "logical %llu len %llu found bg but no related chunk",
1553 found_key.objectid, found_key.offset);
1554 ret = -ENOENT;
1555 } else if (em->start != found_key.objectid ||
1556 em->len != found_key.offset) {
1557 btrfs_err(fs_info,
1558 "block group %llu len %llu mismatch with chunk %llu len %llu",
1559 found_key.objectid, found_key.offset,
1560 em->start, em->len);
1561 ret = -EUCLEAN;
1562 } else {
1563 read_extent_buffer(leaf, &bg,
1564 btrfs_item_ptr_offset(leaf, slot),
1565 sizeof(bg));
David Sterbade0dc452019-10-23 18:48:18 +02001566 flags = btrfs_stack_block_group_flags(&bg) &
Josef Bacik4358d9632019-06-20 15:37:57 -04001567 BTRFS_BLOCK_GROUP_TYPE_MASK;
1568
1569 if (flags != (em->map_lookup->type &
1570 BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1571 btrfs_err(fs_info,
1572"block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
1573 found_key.objectid,
1574 found_key.offset, flags,
1575 (BTRFS_BLOCK_GROUP_TYPE_MASK &
1576 em->map_lookup->type));
1577 ret = -EUCLEAN;
1578 } else {
1579 ret = 0;
1580 }
1581 }
1582 free_extent_map(em);
1583 goto out;
1584 }
1585 path->slots[0]++;
1586 }
1587out:
1588 return ret;
1589}
1590
1591static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
1592{
1593 u64 extra_flags = chunk_to_extended(flags) &
1594 BTRFS_EXTENDED_PROFILE_MASK;
1595
1596 write_seqlock(&fs_info->profiles_lock);
1597 if (flags & BTRFS_BLOCK_GROUP_DATA)
1598 fs_info->avail_data_alloc_bits |= extra_flags;
1599 if (flags & BTRFS_BLOCK_GROUP_METADATA)
1600 fs_info->avail_metadata_alloc_bits |= extra_flags;
1601 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
1602 fs_info->avail_system_alloc_bits |= extra_flags;
1603 write_sequnlock(&fs_info->profiles_lock);
1604}
1605
Nikolay Borisov96a14332019-12-10 19:57:51 +02001606/**
1607 * btrfs_rmap_block - Map a physical disk address to a list of logical addresses
1608 * @chunk_start: logical address of block group
1609 * @physical: physical address to map to logical addresses
1610 * @logical: return array of logical addresses which map to @physical
1611 * @naddrs: length of @logical
1612 * @stripe_len: size of IO stripe for the given block group
1613 *
1614 * Maps a particular @physical disk address to a list of @logical addresses.
1615 * Used primarily to exclude those portions of a block group that contain super
1616 * block copies.
1617 */
1618EXPORT_FOR_TESTS
1619int btrfs_rmap_block(struct btrfs_fs_info *fs_info, u64 chunk_start,
1620 u64 physical, u64 **logical, int *naddrs, int *stripe_len)
1621{
1622 struct extent_map *em;
1623 struct map_lookup *map;
1624 u64 *buf;
1625 u64 bytenr;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001626 u64 data_stripe_length;
1627 u64 io_stripe_size;
1628 int i, nr = 0;
1629 int ret = 0;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001630
1631 em = btrfs_get_chunk_map(fs_info, chunk_start, 1);
1632 if (IS_ERR(em))
1633 return -EIO;
1634
1635 map = em->map_lookup;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001636 data_stripe_length = em->len;
1637 io_stripe_size = map->stripe_len;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001638
1639 if (map->type & BTRFS_BLOCK_GROUP_RAID10)
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001640 data_stripe_length = div_u64(data_stripe_length,
1641 map->num_stripes / map->sub_stripes);
Nikolay Borisov96a14332019-12-10 19:57:51 +02001642 else if (map->type & BTRFS_BLOCK_GROUP_RAID0)
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001643 data_stripe_length = div_u64(data_stripe_length, map->num_stripes);
Nikolay Borisov96a14332019-12-10 19:57:51 +02001644 else if (map->type & BTRFS_BLOCK_GROUP_RAID56_MASK) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001645 data_stripe_length = div_u64(data_stripe_length,
1646 nr_data_stripes(map));
1647 io_stripe_size = map->stripe_len * nr_data_stripes(map);
Nikolay Borisov96a14332019-12-10 19:57:51 +02001648 }
1649
1650 buf = kcalloc(map->num_stripes, sizeof(u64), GFP_NOFS);
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001651 if (!buf) {
1652 ret = -ENOMEM;
1653 goto out;
1654 }
Nikolay Borisov96a14332019-12-10 19:57:51 +02001655
1656 for (i = 0; i < map->num_stripes; i++) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001657 bool already_inserted = false;
1658 u64 stripe_nr;
1659 int j;
1660
1661 if (!in_range(physical, map->stripes[i].physical,
1662 data_stripe_length))
Nikolay Borisov96a14332019-12-10 19:57:51 +02001663 continue;
1664
1665 stripe_nr = physical - map->stripes[i].physical;
1666 stripe_nr = div64_u64(stripe_nr, map->stripe_len);
1667
1668 if (map->type & BTRFS_BLOCK_GROUP_RAID10) {
1669 stripe_nr = stripe_nr * map->num_stripes + i;
1670 stripe_nr = div_u64(stripe_nr, map->sub_stripes);
1671 } else if (map->type & BTRFS_BLOCK_GROUP_RAID0) {
1672 stripe_nr = stripe_nr * map->num_stripes + i;
1673 }
1674 /*
1675 * The remaining case would be for RAID56, multiply by
1676 * nr_data_stripes(). Alternatively, just use rmap_len below
1677 * instead of map->stripe_len
1678 */
1679
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001680 bytenr = chunk_start + stripe_nr * io_stripe_size;
1681
1682 /* Ensure we don't add duplicate addresses */
Nikolay Borisov96a14332019-12-10 19:57:51 +02001683 for (j = 0; j < nr; j++) {
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001684 if (buf[j] == bytenr) {
1685 already_inserted = true;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001686 break;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001687 }
Nikolay Borisov96a14332019-12-10 19:57:51 +02001688 }
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001689
1690 if (!already_inserted)
Nikolay Borisov96a14332019-12-10 19:57:51 +02001691 buf[nr++] = bytenr;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001692 }
1693
1694 *logical = buf;
1695 *naddrs = nr;
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001696 *stripe_len = io_stripe_size;
1697out:
Nikolay Borisov96a14332019-12-10 19:57:51 +02001698 free_extent_map(em);
Nikolay Borisov1776ad12019-11-19 14:05:53 +02001699 return ret;
Nikolay Borisov96a14332019-12-10 19:57:51 +02001700}
1701
David Sterba32da53862019-10-29 19:20:18 +01001702static int exclude_super_stripes(struct btrfs_block_group *cache)
Josef Bacik4358d9632019-06-20 15:37:57 -04001703{
1704 struct btrfs_fs_info *fs_info = cache->fs_info;
1705 u64 bytenr;
1706 u64 *logical;
1707 int stripe_len;
1708 int i, nr, ret;
1709
David Sterbab3470b52019-10-23 18:48:22 +02001710 if (cache->start < BTRFS_SUPER_INFO_OFFSET) {
1711 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->start;
Josef Bacik4358d9632019-06-20 15:37:57 -04001712 cache->bytes_super += stripe_len;
David Sterbab3470b52019-10-23 18:48:22 +02001713 ret = btrfs_add_excluded_extent(fs_info, cache->start,
Josef Bacik4358d9632019-06-20 15:37:57 -04001714 stripe_len);
1715 if (ret)
1716 return ret;
1717 }
1718
1719 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
1720 bytenr = btrfs_sb_offset(i);
David Sterbab3470b52019-10-23 18:48:22 +02001721 ret = btrfs_rmap_block(fs_info, cache->start,
Josef Bacik4358d9632019-06-20 15:37:57 -04001722 bytenr, &logical, &nr, &stripe_len);
1723 if (ret)
1724 return ret;
1725
1726 while (nr--) {
1727 u64 start, len;
1728
David Sterbab3470b52019-10-23 18:48:22 +02001729 if (logical[nr] > cache->start + cache->length)
Josef Bacik4358d9632019-06-20 15:37:57 -04001730 continue;
1731
David Sterbab3470b52019-10-23 18:48:22 +02001732 if (logical[nr] + stripe_len <= cache->start)
Josef Bacik4358d9632019-06-20 15:37:57 -04001733 continue;
1734
1735 start = logical[nr];
David Sterbab3470b52019-10-23 18:48:22 +02001736 if (start < cache->start) {
1737 start = cache->start;
Josef Bacik4358d9632019-06-20 15:37:57 -04001738 len = (logical[nr] + stripe_len) - start;
1739 } else {
1740 len = min_t(u64, stripe_len,
David Sterbab3470b52019-10-23 18:48:22 +02001741 cache->start + cache->length - start);
Josef Bacik4358d9632019-06-20 15:37:57 -04001742 }
1743
1744 cache->bytes_super += len;
1745 ret = btrfs_add_excluded_extent(fs_info, start, len);
1746 if (ret) {
1747 kfree(logical);
1748 return ret;
1749 }
1750 }
1751
1752 kfree(logical);
1753 }
1754 return 0;
1755}
1756
David Sterba32da53862019-10-29 19:20:18 +01001757static void link_block_group(struct btrfs_block_group *cache)
Josef Bacik4358d9632019-06-20 15:37:57 -04001758{
1759 struct btrfs_space_info *space_info = cache->space_info;
1760 int index = btrfs_bg_flags_to_raid_index(cache->flags);
1761 bool first = false;
1762
1763 down_write(&space_info->groups_sem);
1764 if (list_empty(&space_info->block_groups[index]))
1765 first = true;
1766 list_add_tail(&cache->list, &space_info->block_groups[index]);
1767 up_write(&space_info->groups_sem);
1768
1769 if (first)
1770 btrfs_sysfs_add_block_group_type(cache);
1771}
1772
David Sterba32da53862019-10-29 19:20:18 +01001773static struct btrfs_block_group *btrfs_create_block_group_cache(
Josef Bacik4358d9632019-06-20 15:37:57 -04001774 struct btrfs_fs_info *fs_info, u64 start, u64 size)
1775{
David Sterba32da53862019-10-29 19:20:18 +01001776 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04001777
1778 cache = kzalloc(sizeof(*cache), GFP_NOFS);
1779 if (!cache)
1780 return NULL;
1781
1782 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
1783 GFP_NOFS);
1784 if (!cache->free_space_ctl) {
1785 kfree(cache);
1786 return NULL;
1787 }
1788
David Sterbab3470b52019-10-23 18:48:22 +02001789 cache->start = start;
1790 cache->length = size;
Josef Bacik4358d9632019-06-20 15:37:57 -04001791
1792 cache->fs_info = fs_info;
1793 cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
1794 set_free_space_tree_thresholds(cache);
1795
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001796 cache->discard_index = BTRFS_DISCARD_INDEX_UNUSED;
1797
Josef Bacik4358d9632019-06-20 15:37:57 -04001798 atomic_set(&cache->count, 1);
1799 spin_lock_init(&cache->lock);
1800 init_rwsem(&cache->data_rwsem);
1801 INIT_LIST_HEAD(&cache->list);
1802 INIT_LIST_HEAD(&cache->cluster_list);
1803 INIT_LIST_HEAD(&cache->bg_list);
1804 INIT_LIST_HEAD(&cache->ro_list);
Dennis Zhoub0643e52019-12-13 16:22:14 -08001805 INIT_LIST_HEAD(&cache->discard_list);
Josef Bacik4358d9632019-06-20 15:37:57 -04001806 INIT_LIST_HEAD(&cache->dirty_list);
1807 INIT_LIST_HEAD(&cache->io_list);
1808 btrfs_init_free_space_ctl(cache);
Filipe Manana6b7304a2020-05-08 11:01:47 +01001809 atomic_set(&cache->frozen, 0);
Josef Bacik4358d9632019-06-20 15:37:57 -04001810 mutex_init(&cache->free_space_lock);
1811 btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
1812
1813 return cache;
1814}
1815
1816/*
1817 * Iterate all chunks and verify that each of them has the corresponding block
1818 * group
1819 */
1820static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
1821{
1822 struct extent_map_tree *map_tree = &fs_info->mapping_tree;
1823 struct extent_map *em;
David Sterba32da53862019-10-29 19:20:18 +01001824 struct btrfs_block_group *bg;
Josef Bacik4358d9632019-06-20 15:37:57 -04001825 u64 start = 0;
1826 int ret = 0;
1827
1828 while (1) {
1829 read_lock(&map_tree->lock);
1830 /*
1831 * lookup_extent_mapping will return the first extent map
1832 * intersecting the range, so setting @len to 1 is enough to
1833 * get the first chunk.
1834 */
1835 em = lookup_extent_mapping(map_tree, start, 1);
1836 read_unlock(&map_tree->lock);
1837 if (!em)
1838 break;
1839
1840 bg = btrfs_lookup_block_group(fs_info, em->start);
1841 if (!bg) {
1842 btrfs_err(fs_info,
1843 "chunk start=%llu len=%llu doesn't have corresponding block group",
1844 em->start, em->len);
1845 ret = -EUCLEAN;
1846 free_extent_map(em);
1847 break;
1848 }
David Sterbab3470b52019-10-23 18:48:22 +02001849 if (bg->start != em->start || bg->length != em->len ||
Josef Bacik4358d9632019-06-20 15:37:57 -04001850 (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
1851 (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
1852 btrfs_err(fs_info,
1853"chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
1854 em->start, em->len,
1855 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
David Sterbab3470b52019-10-23 18:48:22 +02001856 bg->start, bg->length,
Josef Bacik4358d9632019-06-20 15:37:57 -04001857 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
1858 ret = -EUCLEAN;
1859 free_extent_map(em);
1860 btrfs_put_block_group(bg);
1861 break;
1862 }
1863 start = em->start + em->len;
1864 free_extent_map(em);
1865 btrfs_put_block_group(bg);
1866 }
1867 return ret;
1868}
1869
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001870static int read_one_block_group(struct btrfs_fs_info *info,
1871 struct btrfs_path *path,
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001872 const struct btrfs_key *key,
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001873 int need_clear)
1874{
1875 struct extent_buffer *leaf = path->nodes[0];
David Sterba32da53862019-10-29 19:20:18 +01001876 struct btrfs_block_group *cache;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001877 struct btrfs_space_info *space_info;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001878 struct btrfs_block_group_item bgi;
1879 const bool mixed = btrfs_fs_incompat(info, MIXED_GROUPS);
1880 int slot = path->slots[0];
1881 int ret;
1882
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001883 ASSERT(key->type == BTRFS_BLOCK_GROUP_ITEM_KEY);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001884
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001885 cache = btrfs_create_block_group_cache(info, key->objectid, key->offset);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001886 if (!cache)
1887 return -ENOMEM;
1888
1889 if (need_clear) {
1890 /*
1891 * When we mount with old space cache, we need to
1892 * set BTRFS_DC_CLEAR and set dirty flag.
1893 *
1894 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
1895 * truncate the old free space cache inode and
1896 * setup a new one.
1897 * b) Setting 'dirty flag' makes sure that we flush
1898 * the new space cache info onto disk.
1899 */
1900 if (btrfs_test_opt(info, SPACE_CACHE))
1901 cache->disk_cache_state = BTRFS_DC_CLEAR;
1902 }
1903 read_extent_buffer(leaf, &bgi, btrfs_item_ptr_offset(leaf, slot),
1904 sizeof(bgi));
1905 cache->used = btrfs_stack_block_group_used(&bgi);
1906 cache->flags = btrfs_stack_block_group_flags(&bgi);
1907 if (!mixed && ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
1908 (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
1909 btrfs_err(info,
1910"bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
1911 cache->start);
1912 ret = -EINVAL;
1913 goto error;
1914 }
1915
1916 /*
1917 * We need to exclude the super stripes now so that the space info has
1918 * super bytes accounted for, otherwise we'll think we have more space
1919 * than we actually do.
1920 */
1921 ret = exclude_super_stripes(cache);
1922 if (ret) {
1923 /* We may have excluded something, so call this just in case. */
1924 btrfs_free_excluded_extents(cache);
1925 goto error;
1926 }
1927
1928 /*
1929 * Check for two cases, either we are full, and therefore don't need
1930 * to bother with the caching work since we won't find any space, or we
1931 * are empty, and we can just add all the space in and be done with it.
1932 * This saves us _a_lot_ of time, particularly in the full case.
1933 */
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001934 if (key->offset == cache->used) {
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001935 cache->last_byte_to_unpin = (u64)-1;
1936 cache->cached = BTRFS_CACHE_FINISHED;
1937 btrfs_free_excluded_extents(cache);
1938 } else if (cache->used == 0) {
1939 cache->last_byte_to_unpin = (u64)-1;
1940 cache->cached = BTRFS_CACHE_FINISHED;
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001941 add_new_free_space(cache, key->objectid,
1942 key->objectid + key->offset);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001943 btrfs_free_excluded_extents(cache);
1944 }
1945
1946 ret = btrfs_add_block_group_cache(info, cache);
1947 if (ret) {
1948 btrfs_remove_free_space_cache(cache);
1949 goto error;
1950 }
1951 trace_btrfs_add_block_group(info, cache, 0);
Qu Wenruod49a2dd2019-11-05 09:35:35 +08001952 btrfs_update_space_info(info, cache->flags, key->offset,
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001953 cache->used, cache->bytes_super, &space_info);
1954
1955 cache->space_info = space_info;
1956
1957 link_block_group(cache);
1958
1959 set_avail_alloc_bits(info, cache->flags);
1960 if (btrfs_chunk_readonly(info, cache->start)) {
1961 inc_block_group_ro(cache, 1);
1962 } else if (cache->used == 0) {
1963 ASSERT(list_empty(&cache->bg_list));
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08001964 if (btrfs_test_opt(info, DISCARD_ASYNC))
1965 btrfs_discard_queue_work(&info->discard_ctl, cache);
1966 else
1967 btrfs_mark_bg_unused(cache);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08001968 }
1969 return 0;
1970error:
1971 btrfs_put_block_group(cache);
1972 return ret;
1973}
1974
Josef Bacik4358d9632019-06-20 15:37:57 -04001975int btrfs_read_block_groups(struct btrfs_fs_info *info)
1976{
1977 struct btrfs_path *path;
1978 int ret;
David Sterba32da53862019-10-29 19:20:18 +01001979 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04001980 struct btrfs_space_info *space_info;
1981 struct btrfs_key key;
Josef Bacik4358d9632019-06-20 15:37:57 -04001982 int need_clear = 0;
1983 u64 cache_gen;
Josef Bacik4358d9632019-06-20 15:37:57 -04001984
1985 key.objectid = 0;
1986 key.offset = 0;
1987 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
1988 path = btrfs_alloc_path();
1989 if (!path)
1990 return -ENOMEM;
1991 path->reada = READA_FORWARD;
1992
1993 cache_gen = btrfs_super_cache_generation(info->super_copy);
1994 if (btrfs_test_opt(info, SPACE_CACHE) &&
1995 btrfs_super_generation(info->super_copy) != cache_gen)
1996 need_clear = 1;
1997 if (btrfs_test_opt(info, CLEAR_CACHE))
1998 need_clear = 1;
1999
2000 while (1) {
2001 ret = find_first_block_group(info, path, &key);
2002 if (ret > 0)
2003 break;
2004 if (ret != 0)
2005 goto error;
2006
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002007 btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
Qu Wenruod49a2dd2019-11-05 09:35:35 +08002008 ret = read_one_block_group(info, path, &key, need_clear);
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002009 if (ret < 0)
Josef Bacik4358d9632019-06-20 15:37:57 -04002010 goto error;
Qu Wenruoffb9e0f2019-10-10 10:39:27 +08002011 key.objectid += key.offset;
2012 key.offset = 0;
Josef Bacik4358d9632019-06-20 15:37:57 -04002013 btrfs_release_path(path);
Josef Bacik4358d9632019-06-20 15:37:57 -04002014 }
2015
Madhuparna Bhowmik29566c92020-03-06 12:22:43 +05302016 rcu_read_lock();
Josef Bacik4358d9632019-06-20 15:37:57 -04002017 list_for_each_entry_rcu(space_info, &info->space_info, list) {
2018 if (!(btrfs_get_alloc_profile(info, space_info->flags) &
2019 (BTRFS_BLOCK_GROUP_RAID10 |
2020 BTRFS_BLOCK_GROUP_RAID1_MASK |
2021 BTRFS_BLOCK_GROUP_RAID56_MASK |
2022 BTRFS_BLOCK_GROUP_DUP)))
2023 continue;
2024 /*
2025 * Avoid allocating from un-mirrored block group if there are
2026 * mirrored block groups.
2027 */
2028 list_for_each_entry(cache,
2029 &space_info->block_groups[BTRFS_RAID_RAID0],
2030 list)
Josef Bacike11c0402019-06-20 15:38:07 -04002031 inc_block_group_ro(cache, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04002032 list_for_each_entry(cache,
2033 &space_info->block_groups[BTRFS_RAID_SINGLE],
2034 list)
Josef Bacike11c0402019-06-20 15:38:07 -04002035 inc_block_group_ro(cache, 1);
Josef Bacik4358d9632019-06-20 15:37:57 -04002036 }
Madhuparna Bhowmik29566c92020-03-06 12:22:43 +05302037 rcu_read_unlock();
Josef Bacik4358d9632019-06-20 15:37:57 -04002038
2039 btrfs_init_global_block_rsv(info);
2040 ret = check_chunk_block_group_mappings(info);
2041error:
2042 btrfs_free_path(path);
2043 return ret;
2044}
2045
2046void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
2047{
2048 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002049 struct btrfs_block_group *block_group;
Josef Bacik4358d9632019-06-20 15:37:57 -04002050 struct btrfs_root *extent_root = fs_info->extent_root;
2051 struct btrfs_block_group_item item;
2052 struct btrfs_key key;
2053 int ret = 0;
2054
2055 if (!trans->can_flush_pending_bgs)
2056 return;
2057
2058 while (!list_empty(&trans->new_bgs)) {
2059 block_group = list_first_entry(&trans->new_bgs,
David Sterba32da53862019-10-29 19:20:18 +01002060 struct btrfs_block_group,
Josef Bacik4358d9632019-06-20 15:37:57 -04002061 bg_list);
2062 if (ret)
2063 goto next;
2064
2065 spin_lock(&block_group->lock);
David Sterbade0dc452019-10-23 18:48:18 +02002066 btrfs_set_stack_block_group_used(&item, block_group->used);
2067 btrfs_set_stack_block_group_chunk_objectid(&item,
David Sterba3d976382019-10-23 18:48:15 +02002068 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
David Sterbade0dc452019-10-23 18:48:18 +02002069 btrfs_set_stack_block_group_flags(&item, block_group->flags);
David Sterbab3470b52019-10-23 18:48:22 +02002070 key.objectid = block_group->start;
2071 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2072 key.offset = block_group->length;
Josef Bacik4358d9632019-06-20 15:37:57 -04002073 spin_unlock(&block_group->lock);
2074
2075 ret = btrfs_insert_item(trans, extent_root, &key, &item,
2076 sizeof(item));
2077 if (ret)
2078 btrfs_abort_transaction(trans, ret);
2079 ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
2080 if (ret)
2081 btrfs_abort_transaction(trans, ret);
2082 add_block_group_free_space(trans, block_group);
2083 /* Already aborted the transaction if it failed. */
2084next:
2085 btrfs_delayed_refs_rsv_release(fs_info, 1);
2086 list_del_init(&block_group->bg_list);
2087 }
2088 btrfs_trans_release_chunk_metadata(trans);
2089}
2090
2091int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
2092 u64 type, u64 chunk_offset, u64 size)
2093{
2094 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002095 struct btrfs_block_group *cache;
Josef Bacik4358d9632019-06-20 15:37:57 -04002096 int ret;
2097
2098 btrfs_set_log_full_commit(trans);
2099
2100 cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
2101 if (!cache)
2102 return -ENOMEM;
2103
David Sterbabf38be62019-10-23 18:48:11 +02002104 cache->used = bytes_used;
Josef Bacik4358d9632019-06-20 15:37:57 -04002105 cache->flags = type;
2106 cache->last_byte_to_unpin = (u64)-1;
2107 cache->cached = BTRFS_CACHE_FINISHED;
2108 cache->needs_free_space = 1;
2109 ret = exclude_super_stripes(cache);
2110 if (ret) {
2111 /* We may have excluded something, so call this just in case */
2112 btrfs_free_excluded_extents(cache);
2113 btrfs_put_block_group(cache);
2114 return ret;
2115 }
2116
2117 add_new_free_space(cache, chunk_offset, chunk_offset + size);
2118
2119 btrfs_free_excluded_extents(cache);
2120
2121#ifdef CONFIG_BTRFS_DEBUG
2122 if (btrfs_should_fragment_free_space(cache)) {
2123 u64 new_bytes_used = size - bytes_used;
2124
2125 bytes_used += new_bytes_used >> 1;
Josef Bacike11c0402019-06-20 15:38:07 -04002126 fragment_free_space(cache);
Josef Bacik4358d9632019-06-20 15:37:57 -04002127 }
2128#endif
2129 /*
2130 * Ensure the corresponding space_info object is created and
2131 * assigned to our block group. We want our bg to be added to the rbtree
2132 * with its ->space_info set.
2133 */
2134 cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
2135 ASSERT(cache->space_info);
2136
2137 ret = btrfs_add_block_group_cache(fs_info, cache);
2138 if (ret) {
2139 btrfs_remove_free_space_cache(cache);
2140 btrfs_put_block_group(cache);
2141 return ret;
2142 }
2143
2144 /*
2145 * Now that our block group has its ->space_info set and is inserted in
2146 * the rbtree, update the space info's counters.
2147 */
2148 trace_btrfs_add_block_group(fs_info, cache, 1);
2149 btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
2150 cache->bytes_super, &cache->space_info);
2151 btrfs_update_global_block_rsv(fs_info);
2152
2153 link_block_group(cache);
2154
2155 list_add_tail(&cache->bg_list, &trans->new_bgs);
2156 trans->delayed_ref_updates++;
2157 btrfs_update_delayed_refs_rsv(trans);
2158
2159 set_avail_alloc_bits(fs_info, type);
2160 return 0;
2161}
Josef Bacik26ce2092019-06-20 15:37:59 -04002162
2163static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
2164{
2165 u64 num_devices;
2166 u64 stripped;
2167
2168 /*
2169 * if restripe for this chunk_type is on pick target profile and
2170 * return, otherwise do the usual balance
2171 */
Josef Bacike11c0402019-06-20 15:38:07 -04002172 stripped = get_restripe_target(fs_info, flags);
Josef Bacik26ce2092019-06-20 15:37:59 -04002173 if (stripped)
2174 return extended_to_chunk(stripped);
2175
2176 num_devices = fs_info->fs_devices->rw_devices;
2177
2178 stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
2179 BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
2180
2181 if (num_devices == 1) {
2182 stripped |= BTRFS_BLOCK_GROUP_DUP;
2183 stripped = flags & ~stripped;
2184
2185 /* turn raid0 into single device chunks */
2186 if (flags & BTRFS_BLOCK_GROUP_RAID0)
2187 return stripped;
2188
2189 /* turn mirroring into duplication */
2190 if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
2191 BTRFS_BLOCK_GROUP_RAID10))
2192 return stripped | BTRFS_BLOCK_GROUP_DUP;
2193 } else {
2194 /* they already had raid on here, just return */
2195 if (flags & stripped)
2196 return flags;
2197
2198 stripped |= BTRFS_BLOCK_GROUP_DUP;
2199 stripped = flags & ~stripped;
2200
2201 /* switch duplicated blocks with raid1 */
2202 if (flags & BTRFS_BLOCK_GROUP_DUP)
2203 return stripped | BTRFS_BLOCK_GROUP_RAID1;
2204
2205 /* this is drive concat, leave it alone */
2206 }
2207
2208 return flags;
2209}
2210
Qu Wenruob12de522019-11-15 10:09:00 +08002211/*
2212 * Mark one block group RO, can be called several times for the same block
2213 * group.
2214 *
2215 * @cache: the destination block group
2216 * @do_chunk_alloc: whether need to do chunk pre-allocation, this is to
2217 * ensure we still have some free space after marking this
2218 * block group RO.
2219 */
2220int btrfs_inc_block_group_ro(struct btrfs_block_group *cache,
2221 bool do_chunk_alloc)
Josef Bacik26ce2092019-06-20 15:37:59 -04002222{
2223 struct btrfs_fs_info *fs_info = cache->fs_info;
2224 struct btrfs_trans_handle *trans;
2225 u64 alloc_flags;
2226 int ret;
2227
2228again:
2229 trans = btrfs_join_transaction(fs_info->extent_root);
2230 if (IS_ERR(trans))
2231 return PTR_ERR(trans);
2232
2233 /*
2234 * we're not allowed to set block groups readonly after the dirty
2235 * block groups cache has started writing. If it already started,
2236 * back off and let this transaction commit
2237 */
2238 mutex_lock(&fs_info->ro_block_group_mutex);
2239 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
2240 u64 transid = trans->transid;
2241
2242 mutex_unlock(&fs_info->ro_block_group_mutex);
2243 btrfs_end_transaction(trans);
2244
2245 ret = btrfs_wait_for_commit(fs_info, transid);
2246 if (ret)
2247 return ret;
2248 goto again;
2249 }
2250
Qu Wenruob12de522019-11-15 10:09:00 +08002251 if (do_chunk_alloc) {
Josef Bacik26ce2092019-06-20 15:37:59 -04002252 /*
Qu Wenruob12de522019-11-15 10:09:00 +08002253 * If we are changing raid levels, try to allocate a
2254 * corresponding block group with the new raid level.
Josef Bacik26ce2092019-06-20 15:37:59 -04002255 */
Qu Wenruob12de522019-11-15 10:09:00 +08002256 alloc_flags = update_block_group_flags(fs_info, cache->flags);
2257 if (alloc_flags != cache->flags) {
2258 ret = btrfs_chunk_alloc(trans, alloc_flags,
2259 CHUNK_ALLOC_FORCE);
2260 /*
2261 * ENOSPC is allowed here, we may have enough space
2262 * already allocated at the new raid level to carry on
2263 */
2264 if (ret == -ENOSPC)
2265 ret = 0;
2266 if (ret < 0)
2267 goto out;
2268 }
Josef Bacik26ce2092019-06-20 15:37:59 -04002269 }
2270
Josef Bacika7a63acc2020-01-17 09:07:38 -05002271 ret = inc_block_group_ro(cache, 0);
Qu Wenruob12de522019-11-15 10:09:00 +08002272 if (!do_chunk_alloc)
2273 goto unlock_out;
Josef Bacik26ce2092019-06-20 15:37:59 -04002274 if (!ret)
2275 goto out;
2276 alloc_flags = btrfs_get_alloc_profile(fs_info, cache->space_info->flags);
2277 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
2278 if (ret < 0)
2279 goto out;
Josef Bacike11c0402019-06-20 15:38:07 -04002280 ret = inc_block_group_ro(cache, 0);
Josef Bacik26ce2092019-06-20 15:37:59 -04002281out:
2282 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
2283 alloc_flags = update_block_group_flags(fs_info, cache->flags);
2284 mutex_lock(&fs_info->chunk_mutex);
2285 check_system_chunk(trans, alloc_flags);
2286 mutex_unlock(&fs_info->chunk_mutex);
2287 }
Qu Wenruob12de522019-11-15 10:09:00 +08002288unlock_out:
Josef Bacik26ce2092019-06-20 15:37:59 -04002289 mutex_unlock(&fs_info->ro_block_group_mutex);
2290
2291 btrfs_end_transaction(trans);
2292 return ret;
2293}
2294
David Sterba32da53862019-10-29 19:20:18 +01002295void btrfs_dec_block_group_ro(struct btrfs_block_group *cache)
Josef Bacik26ce2092019-06-20 15:37:59 -04002296{
2297 struct btrfs_space_info *sinfo = cache->space_info;
2298 u64 num_bytes;
2299
2300 BUG_ON(!cache->ro);
2301
2302 spin_lock(&sinfo->lock);
2303 spin_lock(&cache->lock);
2304 if (!--cache->ro) {
David Sterbab3470b52019-10-23 18:48:22 +02002305 num_bytes = cache->length - cache->reserved -
David Sterbabf38be62019-10-23 18:48:11 +02002306 cache->pinned - cache->bytes_super - cache->used;
Josef Bacik26ce2092019-06-20 15:37:59 -04002307 sinfo->bytes_readonly -= num_bytes;
2308 list_del_init(&cache->ro_list);
2309 }
2310 spin_unlock(&cache->lock);
2311 spin_unlock(&sinfo->lock);
2312}
Josef Bacik77745c02019-06-20 15:38:00 -04002313
2314static int write_one_cache_group(struct btrfs_trans_handle *trans,
2315 struct btrfs_path *path,
David Sterba32da53862019-10-29 19:20:18 +01002316 struct btrfs_block_group *cache)
Josef Bacik77745c02019-06-20 15:38:00 -04002317{
2318 struct btrfs_fs_info *fs_info = trans->fs_info;
2319 int ret;
2320 struct btrfs_root *extent_root = fs_info->extent_root;
2321 unsigned long bi;
2322 struct extent_buffer *leaf;
David Sterbabf38be62019-10-23 18:48:11 +02002323 struct btrfs_block_group_item bgi;
David Sterbab3470b52019-10-23 18:48:22 +02002324 struct btrfs_key key;
Josef Bacik77745c02019-06-20 15:38:00 -04002325
David Sterbab3470b52019-10-23 18:48:22 +02002326 key.objectid = cache->start;
2327 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
2328 key.offset = cache->length;
2329
2330 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 1);
Josef Bacik77745c02019-06-20 15:38:00 -04002331 if (ret) {
2332 if (ret > 0)
2333 ret = -ENOENT;
2334 goto fail;
2335 }
2336
2337 leaf = path->nodes[0];
2338 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
David Sterbade0dc452019-10-23 18:48:18 +02002339 btrfs_set_stack_block_group_used(&bgi, cache->used);
2340 btrfs_set_stack_block_group_chunk_objectid(&bgi,
David Sterba3d976382019-10-23 18:48:15 +02002341 BTRFS_FIRST_CHUNK_TREE_OBJECTID);
David Sterbade0dc452019-10-23 18:48:18 +02002342 btrfs_set_stack_block_group_flags(&bgi, cache->flags);
David Sterbabf38be62019-10-23 18:48:11 +02002343 write_extent_buffer(leaf, &bgi, bi, sizeof(bgi));
Josef Bacik77745c02019-06-20 15:38:00 -04002344 btrfs_mark_buffer_dirty(leaf);
2345fail:
2346 btrfs_release_path(path);
2347 return ret;
2348
2349}
2350
David Sterba32da53862019-10-29 19:20:18 +01002351static int cache_save_setup(struct btrfs_block_group *block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002352 struct btrfs_trans_handle *trans,
2353 struct btrfs_path *path)
2354{
2355 struct btrfs_fs_info *fs_info = block_group->fs_info;
2356 struct btrfs_root *root = fs_info->tree_root;
2357 struct inode *inode = NULL;
2358 struct extent_changeset *data_reserved = NULL;
2359 u64 alloc_hint = 0;
2360 int dcs = BTRFS_DC_ERROR;
2361 u64 num_pages = 0;
2362 int retries = 0;
2363 int ret = 0;
2364
2365 /*
2366 * If this block group is smaller than 100 megs don't bother caching the
2367 * block group.
2368 */
David Sterbab3470b52019-10-23 18:48:22 +02002369 if (block_group->length < (100 * SZ_1M)) {
Josef Bacik77745c02019-06-20 15:38:00 -04002370 spin_lock(&block_group->lock);
2371 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2372 spin_unlock(&block_group->lock);
2373 return 0;
2374 }
2375
David Sterbabf31f872020-02-05 17:34:34 +01002376 if (TRANS_ABORTED(trans))
Josef Bacik77745c02019-06-20 15:38:00 -04002377 return 0;
2378again:
2379 inode = lookup_free_space_inode(block_group, path);
2380 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2381 ret = PTR_ERR(inode);
2382 btrfs_release_path(path);
2383 goto out;
2384 }
2385
2386 if (IS_ERR(inode)) {
2387 BUG_ON(retries);
2388 retries++;
2389
2390 if (block_group->ro)
2391 goto out_free;
2392
2393 ret = create_free_space_inode(trans, block_group, path);
2394 if (ret)
2395 goto out_free;
2396 goto again;
2397 }
2398
2399 /*
2400 * We want to set the generation to 0, that way if anything goes wrong
2401 * from here on out we know not to trust this cache when we load up next
2402 * time.
2403 */
2404 BTRFS_I(inode)->generation = 0;
2405 ret = btrfs_update_inode(trans, root, inode);
2406 if (ret) {
2407 /*
2408 * So theoretically we could recover from this, simply set the
2409 * super cache generation to 0 so we know to invalidate the
2410 * cache, but then we'd have to keep track of the block groups
2411 * that fail this way so we know we _have_ to reset this cache
2412 * before the next commit or risk reading stale cache. So to
2413 * limit our exposure to horrible edge cases lets just abort the
2414 * transaction, this only happens in really bad situations
2415 * anyway.
2416 */
2417 btrfs_abort_transaction(trans, ret);
2418 goto out_put;
2419 }
2420 WARN_ON(ret);
2421
2422 /* We've already setup this transaction, go ahead and exit */
2423 if (block_group->cache_generation == trans->transid &&
2424 i_size_read(inode)) {
2425 dcs = BTRFS_DC_SETUP;
2426 goto out_put;
2427 }
2428
2429 if (i_size_read(inode) > 0) {
2430 ret = btrfs_check_trunc_cache_free_space(fs_info,
2431 &fs_info->global_block_rsv);
2432 if (ret)
2433 goto out_put;
2434
2435 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
2436 if (ret)
2437 goto out_put;
2438 }
2439
2440 spin_lock(&block_group->lock);
2441 if (block_group->cached != BTRFS_CACHE_FINISHED ||
2442 !btrfs_test_opt(fs_info, SPACE_CACHE)) {
2443 /*
2444 * don't bother trying to write stuff out _if_
2445 * a) we're not cached,
2446 * b) we're with nospace_cache mount option,
2447 * c) we're with v2 space_cache (FREE_SPACE_TREE).
2448 */
2449 dcs = BTRFS_DC_WRITTEN;
2450 spin_unlock(&block_group->lock);
2451 goto out_put;
2452 }
2453 spin_unlock(&block_group->lock);
2454
2455 /*
2456 * We hit an ENOSPC when setting up the cache in this transaction, just
2457 * skip doing the setup, we've already cleared the cache so we're safe.
2458 */
2459 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
2460 ret = -ENOSPC;
2461 goto out_put;
2462 }
2463
2464 /*
2465 * Try to preallocate enough space based on how big the block group is.
2466 * Keep in mind this has to include any pinned space which could end up
2467 * taking up quite a bit since it's not folded into the other space
2468 * cache.
2469 */
David Sterbab3470b52019-10-23 18:48:22 +02002470 num_pages = div_u64(block_group->length, SZ_256M);
Josef Bacik77745c02019-06-20 15:38:00 -04002471 if (!num_pages)
2472 num_pages = 1;
2473
2474 num_pages *= 16;
2475 num_pages *= PAGE_SIZE;
2476
2477 ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
2478 if (ret)
2479 goto out_put;
2480
2481 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2482 num_pages, num_pages,
2483 &alloc_hint);
2484 /*
2485 * Our cache requires contiguous chunks so that we don't modify a bunch
2486 * of metadata or split extents when writing the cache out, which means
2487 * we can enospc if we are heavily fragmented in addition to just normal
2488 * out of space conditions. So if we hit this just skip setting up any
2489 * other block groups for this transaction, maybe we'll unpin enough
2490 * space the next time around.
2491 */
2492 if (!ret)
2493 dcs = BTRFS_DC_SETUP;
2494 else if (ret == -ENOSPC)
2495 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
2496
2497out_put:
2498 iput(inode);
2499out_free:
2500 btrfs_release_path(path);
2501out:
2502 spin_lock(&block_group->lock);
2503 if (!ret && dcs == BTRFS_DC_SETUP)
2504 block_group->cache_generation = trans->transid;
2505 block_group->disk_cache_state = dcs;
2506 spin_unlock(&block_group->lock);
2507
2508 extent_changeset_free(data_reserved);
2509 return ret;
2510}
2511
2512int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
2513{
2514 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002515 struct btrfs_block_group *cache, *tmp;
Josef Bacik77745c02019-06-20 15:38:00 -04002516 struct btrfs_transaction *cur_trans = trans->transaction;
2517 struct btrfs_path *path;
2518
2519 if (list_empty(&cur_trans->dirty_bgs) ||
2520 !btrfs_test_opt(fs_info, SPACE_CACHE))
2521 return 0;
2522
2523 path = btrfs_alloc_path();
2524 if (!path)
2525 return -ENOMEM;
2526
2527 /* Could add new block groups, use _safe just in case */
2528 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
2529 dirty_list) {
2530 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2531 cache_save_setup(cache, trans, path);
2532 }
2533
2534 btrfs_free_path(path);
2535 return 0;
2536}
2537
2538/*
2539 * Transaction commit does final block group cache writeback during a critical
2540 * section where nothing is allowed to change the FS. This is required in
2541 * order for the cache to actually match the block group, but can introduce a
2542 * lot of latency into the commit.
2543 *
2544 * So, btrfs_start_dirty_block_groups is here to kick off block group cache IO.
2545 * There's a chance we'll have to redo some of it if the block group changes
2546 * again during the commit, but it greatly reduces the commit latency by
2547 * getting rid of the easy block groups while we're still allowing others to
2548 * join the commit.
2549 */
2550int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
2551{
2552 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002553 struct btrfs_block_group *cache;
Josef Bacik77745c02019-06-20 15:38:00 -04002554 struct btrfs_transaction *cur_trans = trans->transaction;
2555 int ret = 0;
2556 int should_put;
2557 struct btrfs_path *path = NULL;
2558 LIST_HEAD(dirty);
2559 struct list_head *io = &cur_trans->io_bgs;
2560 int num_started = 0;
2561 int loops = 0;
2562
2563 spin_lock(&cur_trans->dirty_bgs_lock);
2564 if (list_empty(&cur_trans->dirty_bgs)) {
2565 spin_unlock(&cur_trans->dirty_bgs_lock);
2566 return 0;
2567 }
2568 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2569 spin_unlock(&cur_trans->dirty_bgs_lock);
2570
2571again:
2572 /* Make sure all the block groups on our dirty list actually exist */
2573 btrfs_create_pending_block_groups(trans);
2574
2575 if (!path) {
2576 path = btrfs_alloc_path();
2577 if (!path)
2578 return -ENOMEM;
2579 }
2580
2581 /*
2582 * cache_write_mutex is here only to save us from balance or automatic
2583 * removal of empty block groups deleting this block group while we are
2584 * writing out the cache
2585 */
2586 mutex_lock(&trans->transaction->cache_write_mutex);
2587 while (!list_empty(&dirty)) {
2588 bool drop_reserve = true;
2589
David Sterba32da53862019-10-29 19:20:18 +01002590 cache = list_first_entry(&dirty, struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002591 dirty_list);
2592 /*
2593 * This can happen if something re-dirties a block group that
2594 * is already under IO. Just wait for it to finish and then do
2595 * it all again
2596 */
2597 if (!list_empty(&cache->io_list)) {
2598 list_del_init(&cache->io_list);
2599 btrfs_wait_cache_io(trans, cache, path);
2600 btrfs_put_block_group(cache);
2601 }
2602
2603
2604 /*
2605 * btrfs_wait_cache_io uses the cache->dirty_list to decide if
2606 * it should update the cache_state. Don't delete until after
2607 * we wait.
2608 *
2609 * Since we're not running in the commit critical section
2610 * we need the dirty_bgs_lock to protect from update_block_group
2611 */
2612 spin_lock(&cur_trans->dirty_bgs_lock);
2613 list_del_init(&cache->dirty_list);
2614 spin_unlock(&cur_trans->dirty_bgs_lock);
2615
2616 should_put = 1;
2617
2618 cache_save_setup(cache, trans, path);
2619
2620 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
2621 cache->io_ctl.inode = NULL;
2622 ret = btrfs_write_out_cache(trans, cache, path);
2623 if (ret == 0 && cache->io_ctl.inode) {
2624 num_started++;
2625 should_put = 0;
2626
2627 /*
2628 * The cache_write_mutex is protecting the
2629 * io_list, also refer to the definition of
2630 * btrfs_transaction::io_bgs for more details
2631 */
2632 list_add_tail(&cache->io_list, io);
2633 } else {
2634 /*
2635 * If we failed to write the cache, the
2636 * generation will be bad and life goes on
2637 */
2638 ret = 0;
2639 }
2640 }
2641 if (!ret) {
2642 ret = write_one_cache_group(trans, path, cache);
2643 /*
2644 * Our block group might still be attached to the list
2645 * of new block groups in the transaction handle of some
2646 * other task (struct btrfs_trans_handle->new_bgs). This
2647 * means its block group item isn't yet in the extent
2648 * tree. If this happens ignore the error, as we will
2649 * try again later in the critical section of the
2650 * transaction commit.
2651 */
2652 if (ret == -ENOENT) {
2653 ret = 0;
2654 spin_lock(&cur_trans->dirty_bgs_lock);
2655 if (list_empty(&cache->dirty_list)) {
2656 list_add_tail(&cache->dirty_list,
2657 &cur_trans->dirty_bgs);
2658 btrfs_get_block_group(cache);
2659 drop_reserve = false;
2660 }
2661 spin_unlock(&cur_trans->dirty_bgs_lock);
2662 } else if (ret) {
2663 btrfs_abort_transaction(trans, ret);
2664 }
2665 }
2666
2667 /* If it's not on the io list, we need to put the block group */
2668 if (should_put)
2669 btrfs_put_block_group(cache);
2670 if (drop_reserve)
2671 btrfs_delayed_refs_rsv_release(fs_info, 1);
2672
2673 if (ret)
2674 break;
2675
2676 /*
2677 * Avoid blocking other tasks for too long. It might even save
2678 * us from writing caches for block groups that are going to be
2679 * removed.
2680 */
2681 mutex_unlock(&trans->transaction->cache_write_mutex);
2682 mutex_lock(&trans->transaction->cache_write_mutex);
2683 }
2684 mutex_unlock(&trans->transaction->cache_write_mutex);
2685
2686 /*
2687 * Go through delayed refs for all the stuff we've just kicked off
2688 * and then loop back (just once)
2689 */
2690 ret = btrfs_run_delayed_refs(trans, 0);
2691 if (!ret && loops == 0) {
2692 loops++;
2693 spin_lock(&cur_trans->dirty_bgs_lock);
2694 list_splice_init(&cur_trans->dirty_bgs, &dirty);
2695 /*
2696 * dirty_bgs_lock protects us from concurrent block group
2697 * deletes too (not just cache_write_mutex).
2698 */
2699 if (!list_empty(&dirty)) {
2700 spin_unlock(&cur_trans->dirty_bgs_lock);
2701 goto again;
2702 }
2703 spin_unlock(&cur_trans->dirty_bgs_lock);
2704 } else if (ret < 0) {
2705 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
2706 }
2707
2708 btrfs_free_path(path);
2709 return ret;
2710}
2711
2712int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
2713{
2714 struct btrfs_fs_info *fs_info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002715 struct btrfs_block_group *cache;
Josef Bacik77745c02019-06-20 15:38:00 -04002716 struct btrfs_transaction *cur_trans = trans->transaction;
2717 int ret = 0;
2718 int should_put;
2719 struct btrfs_path *path;
2720 struct list_head *io = &cur_trans->io_bgs;
2721 int num_started = 0;
2722
2723 path = btrfs_alloc_path();
2724 if (!path)
2725 return -ENOMEM;
2726
2727 /*
2728 * Even though we are in the critical section of the transaction commit,
2729 * we can still have concurrent tasks adding elements to this
2730 * transaction's list of dirty block groups. These tasks correspond to
2731 * endio free space workers started when writeback finishes for a
2732 * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
2733 * allocate new block groups as a result of COWing nodes of the root
2734 * tree when updating the free space inode. The writeback for the space
2735 * caches is triggered by an earlier call to
2736 * btrfs_start_dirty_block_groups() and iterations of the following
2737 * loop.
2738 * Also we want to do the cache_save_setup first and then run the
2739 * delayed refs to make sure we have the best chance at doing this all
2740 * in one shot.
2741 */
2742 spin_lock(&cur_trans->dirty_bgs_lock);
2743 while (!list_empty(&cur_trans->dirty_bgs)) {
2744 cache = list_first_entry(&cur_trans->dirty_bgs,
David Sterba32da53862019-10-29 19:20:18 +01002745 struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002746 dirty_list);
2747
2748 /*
2749 * This can happen if cache_save_setup re-dirties a block group
2750 * that is already under IO. Just wait for it to finish and
2751 * then do it all again
2752 */
2753 if (!list_empty(&cache->io_list)) {
2754 spin_unlock(&cur_trans->dirty_bgs_lock);
2755 list_del_init(&cache->io_list);
2756 btrfs_wait_cache_io(trans, cache, path);
2757 btrfs_put_block_group(cache);
2758 spin_lock(&cur_trans->dirty_bgs_lock);
2759 }
2760
2761 /*
2762 * Don't remove from the dirty list until after we've waited on
2763 * any pending IO
2764 */
2765 list_del_init(&cache->dirty_list);
2766 spin_unlock(&cur_trans->dirty_bgs_lock);
2767 should_put = 1;
2768
2769 cache_save_setup(cache, trans, path);
2770
2771 if (!ret)
2772 ret = btrfs_run_delayed_refs(trans,
2773 (unsigned long) -1);
2774
2775 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
2776 cache->io_ctl.inode = NULL;
2777 ret = btrfs_write_out_cache(trans, cache, path);
2778 if (ret == 0 && cache->io_ctl.inode) {
2779 num_started++;
2780 should_put = 0;
2781 list_add_tail(&cache->io_list, io);
2782 } else {
2783 /*
2784 * If we failed to write the cache, the
2785 * generation will be bad and life goes on
2786 */
2787 ret = 0;
2788 }
2789 }
2790 if (!ret) {
2791 ret = write_one_cache_group(trans, path, cache);
2792 /*
2793 * One of the free space endio workers might have
2794 * created a new block group while updating a free space
2795 * cache's inode (at inode.c:btrfs_finish_ordered_io())
2796 * and hasn't released its transaction handle yet, in
2797 * which case the new block group is still attached to
2798 * its transaction handle and its creation has not
2799 * finished yet (no block group item in the extent tree
2800 * yet, etc). If this is the case, wait for all free
2801 * space endio workers to finish and retry. This is a
2802 * a very rare case so no need for a more efficient and
2803 * complex approach.
2804 */
2805 if (ret == -ENOENT) {
2806 wait_event(cur_trans->writer_wait,
2807 atomic_read(&cur_trans->num_writers) == 1);
2808 ret = write_one_cache_group(trans, path, cache);
2809 }
2810 if (ret)
2811 btrfs_abort_transaction(trans, ret);
2812 }
2813
2814 /* If its not on the io list, we need to put the block group */
2815 if (should_put)
2816 btrfs_put_block_group(cache);
2817 btrfs_delayed_refs_rsv_release(fs_info, 1);
2818 spin_lock(&cur_trans->dirty_bgs_lock);
2819 }
2820 spin_unlock(&cur_trans->dirty_bgs_lock);
2821
2822 /*
2823 * Refer to the definition of io_bgs member for details why it's safe
2824 * to use it without any locking
2825 */
2826 while (!list_empty(io)) {
David Sterba32da53862019-10-29 19:20:18 +01002827 cache = list_first_entry(io, struct btrfs_block_group,
Josef Bacik77745c02019-06-20 15:38:00 -04002828 io_list);
2829 list_del_init(&cache->io_list);
2830 btrfs_wait_cache_io(trans, cache, path);
2831 btrfs_put_block_group(cache);
2832 }
2833
2834 btrfs_free_path(path);
2835 return ret;
2836}
Josef Bacik606d1bf2019-06-20 15:38:02 -04002837
2838int btrfs_update_block_group(struct btrfs_trans_handle *trans,
2839 u64 bytenr, u64 num_bytes, int alloc)
2840{
2841 struct btrfs_fs_info *info = trans->fs_info;
David Sterba32da53862019-10-29 19:20:18 +01002842 struct btrfs_block_group *cache = NULL;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002843 u64 total = num_bytes;
2844 u64 old_val;
2845 u64 byte_in_group;
2846 int factor;
2847 int ret = 0;
2848
2849 /* Block accounting for super block */
2850 spin_lock(&info->delalloc_root_lock);
2851 old_val = btrfs_super_bytes_used(info->super_copy);
2852 if (alloc)
2853 old_val += num_bytes;
2854 else
2855 old_val -= num_bytes;
2856 btrfs_set_super_bytes_used(info->super_copy, old_val);
2857 spin_unlock(&info->delalloc_root_lock);
2858
2859 while (total) {
2860 cache = btrfs_lookup_block_group(info, bytenr);
2861 if (!cache) {
2862 ret = -ENOENT;
2863 break;
2864 }
2865 factor = btrfs_bg_type_to_factor(cache->flags);
2866
2867 /*
2868 * If this block group has free space cache written out, we
2869 * need to make sure to load it if we are removing space. This
2870 * is because we need the unpinning stage to actually add the
2871 * space back to the block group, otherwise we will leak space.
2872 */
David Sterba32da53862019-10-29 19:20:18 +01002873 if (!alloc && !btrfs_block_group_done(cache))
Josef Bacik606d1bf2019-06-20 15:38:02 -04002874 btrfs_cache_block_group(cache, 1);
2875
David Sterbab3470b52019-10-23 18:48:22 +02002876 byte_in_group = bytenr - cache->start;
2877 WARN_ON(byte_in_group > cache->length);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002878
2879 spin_lock(&cache->space_info->lock);
2880 spin_lock(&cache->lock);
2881
2882 if (btrfs_test_opt(info, SPACE_CACHE) &&
2883 cache->disk_cache_state < BTRFS_DC_CLEAR)
2884 cache->disk_cache_state = BTRFS_DC_CLEAR;
2885
David Sterbabf38be62019-10-23 18:48:11 +02002886 old_val = cache->used;
David Sterbab3470b52019-10-23 18:48:22 +02002887 num_bytes = min(total, cache->length - byte_in_group);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002888 if (alloc) {
2889 old_val += num_bytes;
David Sterbabf38be62019-10-23 18:48:11 +02002890 cache->used = old_val;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002891 cache->reserved -= num_bytes;
2892 cache->space_info->bytes_reserved -= num_bytes;
2893 cache->space_info->bytes_used += num_bytes;
2894 cache->space_info->disk_used += num_bytes * factor;
2895 spin_unlock(&cache->lock);
2896 spin_unlock(&cache->space_info->lock);
2897 } else {
2898 old_val -= num_bytes;
David Sterbabf38be62019-10-23 18:48:11 +02002899 cache->used = old_val;
Josef Bacik606d1bf2019-06-20 15:38:02 -04002900 cache->pinned += num_bytes;
2901 btrfs_space_info_update_bytes_pinned(info,
2902 cache->space_info, num_bytes);
2903 cache->space_info->bytes_used -= num_bytes;
2904 cache->space_info->disk_used -= num_bytes * factor;
2905 spin_unlock(&cache->lock);
2906 spin_unlock(&cache->space_info->lock);
2907
Josef Bacik606d1bf2019-06-20 15:38:02 -04002908 percpu_counter_add_batch(
2909 &cache->space_info->total_bytes_pinned,
2910 num_bytes,
2911 BTRFS_TOTAL_BYTES_PINNED_BATCH);
Nikolay Borisovfe119a62020-01-20 16:09:18 +02002912 set_extent_dirty(&trans->transaction->pinned_extents,
Josef Bacik606d1bf2019-06-20 15:38:02 -04002913 bytenr, bytenr + num_bytes - 1,
2914 GFP_NOFS | __GFP_NOFAIL);
2915 }
2916
2917 spin_lock(&trans->transaction->dirty_bgs_lock);
2918 if (list_empty(&cache->dirty_list)) {
2919 list_add_tail(&cache->dirty_list,
2920 &trans->transaction->dirty_bgs);
2921 trans->delayed_ref_updates++;
2922 btrfs_get_block_group(cache);
2923 }
2924 spin_unlock(&trans->transaction->dirty_bgs_lock);
2925
2926 /*
2927 * No longer have used bytes in this block group, queue it for
2928 * deletion. We do this after adding the block group to the
2929 * dirty list to avoid races between cleaner kthread and space
2930 * cache writeout.
2931 */
Dennis Zhou6e80d4f2019-12-13 16:22:15 -08002932 if (!alloc && old_val == 0) {
2933 if (!btrfs_test_opt(info, DISCARD_ASYNC))
2934 btrfs_mark_bg_unused(cache);
2935 }
Josef Bacik606d1bf2019-06-20 15:38:02 -04002936
2937 btrfs_put_block_group(cache);
2938 total -= num_bytes;
2939 bytenr += num_bytes;
2940 }
2941
2942 /* Modified block groups are accounted for in the delayed_refs_rsv. */
2943 btrfs_update_delayed_refs_rsv(trans);
2944 return ret;
2945}
2946
2947/**
2948 * btrfs_add_reserved_bytes - update the block_group and space info counters
2949 * @cache: The cache we are manipulating
2950 * @ram_bytes: The number of bytes of file content, and will be same to
2951 * @num_bytes except for the compress path.
2952 * @num_bytes: The number of bytes in question
2953 * @delalloc: The blocks are allocated for the delalloc write
2954 *
2955 * This is called by the allocator when it reserves space. If this is a
2956 * reservation and the block group has become read only we cannot make the
2957 * reservation and return -EAGAIN, otherwise this function always succeeds.
2958 */
David Sterba32da53862019-10-29 19:20:18 +01002959int btrfs_add_reserved_bytes(struct btrfs_block_group *cache,
Josef Bacik606d1bf2019-06-20 15:38:02 -04002960 u64 ram_bytes, u64 num_bytes, int delalloc)
2961{
2962 struct btrfs_space_info *space_info = cache->space_info;
2963 int ret = 0;
2964
2965 spin_lock(&space_info->lock);
2966 spin_lock(&cache->lock);
2967 if (cache->ro) {
2968 ret = -EAGAIN;
2969 } else {
2970 cache->reserved += num_bytes;
2971 space_info->bytes_reserved += num_bytes;
Josef Bacika43c3832019-08-22 15:10:56 -04002972 trace_btrfs_space_reservation(cache->fs_info, "space_info",
2973 space_info->flags, num_bytes, 1);
Josef Bacik606d1bf2019-06-20 15:38:02 -04002974 btrfs_space_info_update_bytes_may_use(cache->fs_info,
2975 space_info, -ram_bytes);
2976 if (delalloc)
2977 cache->delalloc_bytes += num_bytes;
2978 }
2979 spin_unlock(&cache->lock);
2980 spin_unlock(&space_info->lock);
2981 return ret;
2982}
2983
2984/**
2985 * btrfs_free_reserved_bytes - update the block_group and space info counters
2986 * @cache: The cache we are manipulating
2987 * @num_bytes: The number of bytes in question
2988 * @delalloc: The blocks are allocated for the delalloc write
2989 *
2990 * This is called by somebody who is freeing space that was never actually used
2991 * on disk. For example if you reserve some space for a new leaf in transaction
2992 * A and before transaction A commits you free that leaf, you call this with
2993 * reserve set to 0 in order to clear the reservation.
2994 */
David Sterba32da53862019-10-29 19:20:18 +01002995void btrfs_free_reserved_bytes(struct btrfs_block_group *cache,
Josef Bacik606d1bf2019-06-20 15:38:02 -04002996 u64 num_bytes, int delalloc)
2997{
2998 struct btrfs_space_info *space_info = cache->space_info;
2999
3000 spin_lock(&space_info->lock);
3001 spin_lock(&cache->lock);
3002 if (cache->ro)
3003 space_info->bytes_readonly += num_bytes;
3004 cache->reserved -= num_bytes;
3005 space_info->bytes_reserved -= num_bytes;
3006 space_info->max_extent_size = 0;
3007
3008 if (delalloc)
3009 cache->delalloc_bytes -= num_bytes;
3010 spin_unlock(&cache->lock);
3011 spin_unlock(&space_info->lock);
3012}
Josef Bacik07730d82019-06-20 15:38:04 -04003013
3014static void force_metadata_allocation(struct btrfs_fs_info *info)
3015{
3016 struct list_head *head = &info->space_info;
3017 struct btrfs_space_info *found;
3018
3019 rcu_read_lock();
3020 list_for_each_entry_rcu(found, head, list) {
3021 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3022 found->force_alloc = CHUNK_ALLOC_FORCE;
3023 }
3024 rcu_read_unlock();
3025}
3026
3027static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
3028 struct btrfs_space_info *sinfo, int force)
3029{
3030 u64 bytes_used = btrfs_space_info_used(sinfo, false);
3031 u64 thresh;
3032
3033 if (force == CHUNK_ALLOC_FORCE)
3034 return 1;
3035
3036 /*
3037 * in limited mode, we want to have some free space up to
3038 * about 1% of the FS size.
3039 */
3040 if (force == CHUNK_ALLOC_LIMITED) {
3041 thresh = btrfs_super_total_bytes(fs_info->super_copy);
3042 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
3043
3044 if (sinfo->total_bytes - bytes_used < thresh)
3045 return 1;
3046 }
3047
3048 if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
3049 return 0;
3050 return 1;
3051}
3052
3053int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
3054{
3055 u64 alloc_flags = btrfs_get_alloc_profile(trans->fs_info, type);
3056
3057 return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
3058}
3059
3060/*
3061 * If force is CHUNK_ALLOC_FORCE:
3062 * - return 1 if it successfully allocates a chunk,
3063 * - return errors including -ENOSPC otherwise.
3064 * If force is NOT CHUNK_ALLOC_FORCE:
3065 * - return 0 if it doesn't need to allocate a new chunk,
3066 * - return 1 if it successfully allocates a chunk,
3067 * - return errors including -ENOSPC otherwise.
3068 */
3069int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
3070 enum btrfs_chunk_alloc_enum force)
3071{
3072 struct btrfs_fs_info *fs_info = trans->fs_info;
3073 struct btrfs_space_info *space_info;
3074 bool wait_for_alloc = false;
3075 bool should_alloc = false;
3076 int ret = 0;
3077
3078 /* Don't re-enter if we're already allocating a chunk */
3079 if (trans->allocating_chunk)
3080 return -ENOSPC;
3081
3082 space_info = btrfs_find_space_info(fs_info, flags);
3083 ASSERT(space_info);
3084
3085 do {
3086 spin_lock(&space_info->lock);
3087 if (force < space_info->force_alloc)
3088 force = space_info->force_alloc;
3089 should_alloc = should_alloc_chunk(fs_info, space_info, force);
3090 if (space_info->full) {
3091 /* No more free physical space */
3092 if (should_alloc)
3093 ret = -ENOSPC;
3094 else
3095 ret = 0;
3096 spin_unlock(&space_info->lock);
3097 return ret;
3098 } else if (!should_alloc) {
3099 spin_unlock(&space_info->lock);
3100 return 0;
3101 } else if (space_info->chunk_alloc) {
3102 /*
3103 * Someone is already allocating, so we need to block
3104 * until this someone is finished and then loop to
3105 * recheck if we should continue with our allocation
3106 * attempt.
3107 */
3108 wait_for_alloc = true;
3109 spin_unlock(&space_info->lock);
3110 mutex_lock(&fs_info->chunk_mutex);
3111 mutex_unlock(&fs_info->chunk_mutex);
3112 } else {
3113 /* Proceed with allocation */
3114 space_info->chunk_alloc = 1;
3115 wait_for_alloc = false;
3116 spin_unlock(&space_info->lock);
3117 }
3118
3119 cond_resched();
3120 } while (wait_for_alloc);
3121
3122 mutex_lock(&fs_info->chunk_mutex);
3123 trans->allocating_chunk = true;
3124
3125 /*
3126 * If we have mixed data/metadata chunks we want to make sure we keep
3127 * allocating mixed chunks instead of individual chunks.
3128 */
3129 if (btrfs_mixed_space_info(space_info))
3130 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3131
3132 /*
3133 * if we're doing a data chunk, go ahead and make sure that
3134 * we keep a reasonable number of metadata chunks allocated in the
3135 * FS as well.
3136 */
3137 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3138 fs_info->data_chunk_allocations++;
3139 if (!(fs_info->data_chunk_allocations %
3140 fs_info->metadata_ratio))
3141 force_metadata_allocation(fs_info);
3142 }
3143
3144 /*
3145 * Check if we have enough space in SYSTEM chunk because we may need
3146 * to update devices.
3147 */
3148 check_system_chunk(trans, flags);
3149
3150 ret = btrfs_alloc_chunk(trans, flags);
3151 trans->allocating_chunk = false;
3152
3153 spin_lock(&space_info->lock);
3154 if (ret < 0) {
3155 if (ret == -ENOSPC)
3156 space_info->full = 1;
3157 else
3158 goto out;
3159 } else {
3160 ret = 1;
3161 space_info->max_extent_size = 0;
3162 }
3163
3164 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3165out:
3166 space_info->chunk_alloc = 0;
3167 spin_unlock(&space_info->lock);
3168 mutex_unlock(&fs_info->chunk_mutex);
3169 /*
3170 * When we allocate a new chunk we reserve space in the chunk block
3171 * reserve to make sure we can COW nodes/leafs in the chunk tree or
3172 * add new nodes/leafs to it if we end up needing to do it when
3173 * inserting the chunk item and updating device items as part of the
3174 * second phase of chunk allocation, performed by
3175 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
3176 * large number of new block groups to create in our transaction
3177 * handle's new_bgs list to avoid exhausting the chunk block reserve
3178 * in extreme cases - like having a single transaction create many new
3179 * block groups when starting to write out the free space caches of all
3180 * the block groups that were made dirty during the lifetime of the
3181 * transaction.
3182 */
3183 if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
3184 btrfs_create_pending_block_groups(trans);
3185
3186 return ret;
3187}
3188
3189static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
3190{
3191 u64 num_dev;
3192
3193 num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
3194 if (!num_dev)
3195 num_dev = fs_info->fs_devices->rw_devices;
3196
3197 return num_dev;
3198}
3199
3200/*
Marcos Paulo de Souzaa9143bd2019-10-07 21:50:38 -03003201 * Reserve space in the system space for allocating or removing a chunk
Josef Bacik07730d82019-06-20 15:38:04 -04003202 */
3203void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
3204{
3205 struct btrfs_fs_info *fs_info = trans->fs_info;
3206 struct btrfs_space_info *info;
3207 u64 left;
3208 u64 thresh;
3209 int ret = 0;
3210 u64 num_devs;
3211
3212 /*
3213 * Needed because we can end up allocating a system chunk and for an
3214 * atomic and race free space reservation in the chunk block reserve.
3215 */
3216 lockdep_assert_held(&fs_info->chunk_mutex);
3217
3218 info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3219 spin_lock(&info->lock);
3220 left = info->total_bytes - btrfs_space_info_used(info, true);
3221 spin_unlock(&info->lock);
3222
3223 num_devs = get_profile_num_devs(fs_info, type);
3224
3225 /* num_devs device items to update and 1 chunk item to add or remove */
Josef Bacik2bd36e72019-08-22 15:14:33 -04003226 thresh = btrfs_calc_metadata_size(fs_info, num_devs) +
3227 btrfs_calc_insert_metadata_size(fs_info, 1);
Josef Bacik07730d82019-06-20 15:38:04 -04003228
3229 if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
3230 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
3231 left, thresh, type);
3232 btrfs_dump_space_info(fs_info, info, 0, 0);
3233 }
3234
3235 if (left < thresh) {
3236 u64 flags = btrfs_system_alloc_profile(fs_info);
3237
3238 /*
3239 * Ignore failure to create system chunk. We might end up not
3240 * needing it, as we might not need to COW all nodes/leafs from
3241 * the paths we visit in the chunk tree (they were already COWed
3242 * or created in the current transaction for example).
3243 */
3244 ret = btrfs_alloc_chunk(trans, flags);
3245 }
3246
3247 if (!ret) {
3248 ret = btrfs_block_rsv_add(fs_info->chunk_root,
3249 &fs_info->chunk_block_rsv,
3250 thresh, BTRFS_RESERVE_NO_FLUSH);
3251 if (!ret)
3252 trans->chunk_bytes_reserved += thresh;
3253 }
3254}
3255
Josef Bacik3e43c272019-06-20 15:38:06 -04003256void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
3257{
David Sterba32da53862019-10-29 19:20:18 +01003258 struct btrfs_block_group *block_group;
Josef Bacik3e43c272019-06-20 15:38:06 -04003259 u64 last = 0;
3260
3261 while (1) {
3262 struct inode *inode;
3263
3264 block_group = btrfs_lookup_first_block_group(info, last);
3265 while (block_group) {
3266 btrfs_wait_block_group_cache_done(block_group);
3267 spin_lock(&block_group->lock);
3268 if (block_group->iref)
3269 break;
3270 spin_unlock(&block_group->lock);
3271 block_group = btrfs_next_block_group(block_group);
3272 }
3273 if (!block_group) {
3274 if (last == 0)
3275 break;
3276 last = 0;
3277 continue;
3278 }
3279
3280 inode = block_group->inode;
3281 block_group->iref = 0;
3282 block_group->inode = NULL;
3283 spin_unlock(&block_group->lock);
3284 ASSERT(block_group->io_ctl.inode == NULL);
3285 iput(inode);
David Sterbab3470b52019-10-23 18:48:22 +02003286 last = block_group->start + block_group->length;
Josef Bacik3e43c272019-06-20 15:38:06 -04003287 btrfs_put_block_group(block_group);
3288 }
3289}
3290
3291/*
3292 * Must be called only after stopping all workers, since we could have block
3293 * group caching kthreads running, and therefore they could race with us if we
3294 * freed the block groups before stopping them.
3295 */
3296int btrfs_free_block_groups(struct btrfs_fs_info *info)
3297{
David Sterba32da53862019-10-29 19:20:18 +01003298 struct btrfs_block_group *block_group;
Josef Bacik3e43c272019-06-20 15:38:06 -04003299 struct btrfs_space_info *space_info;
3300 struct btrfs_caching_control *caching_ctl;
3301 struct rb_node *n;
3302
3303 down_write(&info->commit_root_sem);
3304 while (!list_empty(&info->caching_block_groups)) {
3305 caching_ctl = list_entry(info->caching_block_groups.next,
3306 struct btrfs_caching_control, list);
3307 list_del(&caching_ctl->list);
3308 btrfs_put_caching_control(caching_ctl);
3309 }
3310 up_write(&info->commit_root_sem);
3311
3312 spin_lock(&info->unused_bgs_lock);
3313 while (!list_empty(&info->unused_bgs)) {
3314 block_group = list_first_entry(&info->unused_bgs,
David Sterba32da53862019-10-29 19:20:18 +01003315 struct btrfs_block_group,
Josef Bacik3e43c272019-06-20 15:38:06 -04003316 bg_list);
3317 list_del_init(&block_group->bg_list);
3318 btrfs_put_block_group(block_group);
3319 }
3320 spin_unlock(&info->unused_bgs_lock);
3321
3322 spin_lock(&info->block_group_cache_lock);
3323 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
David Sterba32da53862019-10-29 19:20:18 +01003324 block_group = rb_entry(n, struct btrfs_block_group,
Josef Bacik3e43c272019-06-20 15:38:06 -04003325 cache_node);
3326 rb_erase(&block_group->cache_node,
3327 &info->block_group_cache_tree);
3328 RB_CLEAR_NODE(&block_group->cache_node);
3329 spin_unlock(&info->block_group_cache_lock);
3330
3331 down_write(&block_group->space_info->groups_sem);
3332 list_del(&block_group->list);
3333 up_write(&block_group->space_info->groups_sem);
3334
3335 /*
3336 * We haven't cached this block group, which means we could
3337 * possibly have excluded extents on this block group.
3338 */
3339 if (block_group->cached == BTRFS_CACHE_NO ||
3340 block_group->cached == BTRFS_CACHE_ERROR)
3341 btrfs_free_excluded_extents(block_group);
3342
3343 btrfs_remove_free_space_cache(block_group);
3344 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
3345 ASSERT(list_empty(&block_group->dirty_list));
3346 ASSERT(list_empty(&block_group->io_list));
3347 ASSERT(list_empty(&block_group->bg_list));
3348 ASSERT(atomic_read(&block_group->count) == 1);
3349 btrfs_put_block_group(block_group);
3350
3351 spin_lock(&info->block_group_cache_lock);
3352 }
3353 spin_unlock(&info->block_group_cache_lock);
3354
3355 /*
3356 * Now that all the block groups are freed, go through and free all the
3357 * space_info structs. This is only called during the final stages of
3358 * unmount, and so we know nobody is using them. We call
3359 * synchronize_rcu() once before we start, just to be on the safe side.
3360 */
3361 synchronize_rcu();
3362
3363 btrfs_release_global_block_rsv(info);
3364
3365 while (!list_empty(&info->space_info)) {
3366 space_info = list_entry(info->space_info.next,
3367 struct btrfs_space_info,
3368 list);
3369
3370 /*
3371 * Do not hide this behind enospc_debug, this is actually
3372 * important and indicates a real bug if this happens.
3373 */
3374 if (WARN_ON(space_info->bytes_pinned > 0 ||
3375 space_info->bytes_reserved > 0 ||
3376 space_info->bytes_may_use > 0))
3377 btrfs_dump_space_info(info, space_info, 0, 0);
Filipe Mananad611add2020-04-07 11:38:49 +01003378 WARN_ON(space_info->reclaim_size > 0);
Josef Bacik3e43c272019-06-20 15:38:06 -04003379 list_del(&space_info->list);
3380 btrfs_sysfs_remove_space_info(space_info);
3381 }
3382 return 0;
3383}