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