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