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