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