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