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