btrfs: move reserve_metadata_bytes and supporting code to space-info.c
[sfrench/cifs-2.6.git] / fs / btrfs / extent-tree.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5
6 #include <linux/sched.h>
7 #include <linux/sched/signal.h>
8 #include <linux/pagemap.h>
9 #include <linux/writeback.h>
10 #include <linux/blkdev.h>
11 #include <linux/sort.h>
12 #include <linux/rcupdate.h>
13 #include <linux/kthread.h>
14 #include <linux/slab.h>
15 #include <linux/ratelimit.h>
16 #include <linux/percpu_counter.h>
17 #include <linux/lockdep.h>
18 #include <linux/crc32c.h>
19 #include "tree-log.h"
20 #include "disk-io.h"
21 #include "print-tree.h"
22 #include "volumes.h"
23 #include "raid56.h"
24 #include "locking.h"
25 #include "free-space-cache.h"
26 #include "free-space-tree.h"
27 #include "math.h"
28 #include "sysfs.h"
29 #include "qgroup.h"
30 #include "ref-verify.h"
31 #include "space-info.h"
32
33 #undef SCRAMBLE_DELAYED_REFS
34
35
36 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
37                                struct btrfs_delayed_ref_node *node, u64 parent,
38                                u64 root_objectid, u64 owner_objectid,
39                                u64 owner_offset, int refs_to_drop,
40                                struct btrfs_delayed_extent_op *extra_op);
41 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
42                                     struct extent_buffer *leaf,
43                                     struct btrfs_extent_item *ei);
44 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
45                                       u64 parent, u64 root_objectid,
46                                       u64 flags, u64 owner, u64 offset,
47                                       struct btrfs_key *ins, int ref_mod);
48 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
49                                      struct btrfs_delayed_ref_node *node,
50                                      struct btrfs_delayed_extent_op *extent_op);
51 static int find_next_key(struct btrfs_path *path, int level,
52                          struct btrfs_key *key);
53
54 static noinline int
55 block_group_cache_done(struct btrfs_block_group_cache *cache)
56 {
57         smp_mb();
58         return cache->cached == BTRFS_CACHE_FINISHED ||
59                 cache->cached == BTRFS_CACHE_ERROR;
60 }
61
62 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
63 {
64         return (cache->flags & bits) == bits;
65 }
66
67 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
68 {
69         atomic_inc(&cache->count);
70 }
71
72 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
73 {
74         if (atomic_dec_and_test(&cache->count)) {
75                 WARN_ON(cache->pinned > 0);
76                 WARN_ON(cache->reserved > 0);
77
78                 /*
79                  * If not empty, someone is still holding mutex of
80                  * full_stripe_lock, which can only be released by caller.
81                  * And it will definitely cause use-after-free when caller
82                  * tries to release full stripe lock.
83                  *
84                  * No better way to resolve, but only to warn.
85                  */
86                 WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
87                 kfree(cache->free_space_ctl);
88                 kfree(cache);
89         }
90 }
91
92 /*
93  * this adds the block group to the fs_info rb tree for the block group
94  * cache
95  */
96 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
97                                 struct btrfs_block_group_cache *block_group)
98 {
99         struct rb_node **p;
100         struct rb_node *parent = NULL;
101         struct btrfs_block_group_cache *cache;
102
103         spin_lock(&info->block_group_cache_lock);
104         p = &info->block_group_cache_tree.rb_node;
105
106         while (*p) {
107                 parent = *p;
108                 cache = rb_entry(parent, struct btrfs_block_group_cache,
109                                  cache_node);
110                 if (block_group->key.objectid < cache->key.objectid) {
111                         p = &(*p)->rb_left;
112                 } else if (block_group->key.objectid > cache->key.objectid) {
113                         p = &(*p)->rb_right;
114                 } else {
115                         spin_unlock(&info->block_group_cache_lock);
116                         return -EEXIST;
117                 }
118         }
119
120         rb_link_node(&block_group->cache_node, parent, p);
121         rb_insert_color(&block_group->cache_node,
122                         &info->block_group_cache_tree);
123
124         if (info->first_logical_byte > block_group->key.objectid)
125                 info->first_logical_byte = block_group->key.objectid;
126
127         spin_unlock(&info->block_group_cache_lock);
128
129         return 0;
130 }
131
132 /*
133  * This will return the block group at or after bytenr if contains is 0, else
134  * it will return the block group that contains the bytenr
135  */
136 static struct btrfs_block_group_cache *
137 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
138                               int contains)
139 {
140         struct btrfs_block_group_cache *cache, *ret = NULL;
141         struct rb_node *n;
142         u64 end, start;
143
144         spin_lock(&info->block_group_cache_lock);
145         n = info->block_group_cache_tree.rb_node;
146
147         while (n) {
148                 cache = rb_entry(n, struct btrfs_block_group_cache,
149                                  cache_node);
150                 end = cache->key.objectid + cache->key.offset - 1;
151                 start = cache->key.objectid;
152
153                 if (bytenr < start) {
154                         if (!contains && (!ret || start < ret->key.objectid))
155                                 ret = cache;
156                         n = n->rb_left;
157                 } else if (bytenr > start) {
158                         if (contains && bytenr <= end) {
159                                 ret = cache;
160                                 break;
161                         }
162                         n = n->rb_right;
163                 } else {
164                         ret = cache;
165                         break;
166                 }
167         }
168         if (ret) {
169                 btrfs_get_block_group(ret);
170                 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
171                         info->first_logical_byte = ret->key.objectid;
172         }
173         spin_unlock(&info->block_group_cache_lock);
174
175         return ret;
176 }
177
178 static int add_excluded_extent(struct btrfs_fs_info *fs_info,
179                                u64 start, u64 num_bytes)
180 {
181         u64 end = start + num_bytes - 1;
182         set_extent_bits(&fs_info->freed_extents[0],
183                         start, end, EXTENT_UPTODATE);
184         set_extent_bits(&fs_info->freed_extents[1],
185                         start, end, EXTENT_UPTODATE);
186         return 0;
187 }
188
189 static void free_excluded_extents(struct btrfs_block_group_cache *cache)
190 {
191         struct btrfs_fs_info *fs_info = cache->fs_info;
192         u64 start, end;
193
194         start = cache->key.objectid;
195         end = start + cache->key.offset - 1;
196
197         clear_extent_bits(&fs_info->freed_extents[0],
198                           start, end, EXTENT_UPTODATE);
199         clear_extent_bits(&fs_info->freed_extents[1],
200                           start, end, EXTENT_UPTODATE);
201 }
202
203 static int exclude_super_stripes(struct btrfs_block_group_cache *cache)
204 {
205         struct btrfs_fs_info *fs_info = cache->fs_info;
206         u64 bytenr;
207         u64 *logical;
208         int stripe_len;
209         int i, nr, ret;
210
211         if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
212                 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
213                 cache->bytes_super += stripe_len;
214                 ret = add_excluded_extent(fs_info, cache->key.objectid,
215                                           stripe_len);
216                 if (ret)
217                         return ret;
218         }
219
220         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
221                 bytenr = btrfs_sb_offset(i);
222                 ret = btrfs_rmap_block(fs_info, cache->key.objectid,
223                                        bytenr, &logical, &nr, &stripe_len);
224                 if (ret)
225                         return ret;
226
227                 while (nr--) {
228                         u64 start, len;
229
230                         if (logical[nr] > cache->key.objectid +
231                             cache->key.offset)
232                                 continue;
233
234                         if (logical[nr] + stripe_len <= cache->key.objectid)
235                                 continue;
236
237                         start = logical[nr];
238                         if (start < cache->key.objectid) {
239                                 start = cache->key.objectid;
240                                 len = (logical[nr] + stripe_len) - start;
241                         } else {
242                                 len = min_t(u64, stripe_len,
243                                             cache->key.objectid +
244                                             cache->key.offset - start);
245                         }
246
247                         cache->bytes_super += len;
248                         ret = add_excluded_extent(fs_info, start, len);
249                         if (ret) {
250                                 kfree(logical);
251                                 return ret;
252                         }
253                 }
254
255                 kfree(logical);
256         }
257         return 0;
258 }
259
260 static struct btrfs_caching_control *
261 get_caching_control(struct btrfs_block_group_cache *cache)
262 {
263         struct btrfs_caching_control *ctl;
264
265         spin_lock(&cache->lock);
266         if (!cache->caching_ctl) {
267                 spin_unlock(&cache->lock);
268                 return NULL;
269         }
270
271         ctl = cache->caching_ctl;
272         refcount_inc(&ctl->count);
273         spin_unlock(&cache->lock);
274         return ctl;
275 }
276
277 static void put_caching_control(struct btrfs_caching_control *ctl)
278 {
279         if (refcount_dec_and_test(&ctl->count))
280                 kfree(ctl);
281 }
282
283 #ifdef CONFIG_BTRFS_DEBUG
284 static void fragment_free_space(struct btrfs_block_group_cache *block_group)
285 {
286         struct btrfs_fs_info *fs_info = block_group->fs_info;
287         u64 start = block_group->key.objectid;
288         u64 len = block_group->key.offset;
289         u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
290                 fs_info->nodesize : fs_info->sectorsize;
291         u64 step = chunk << 1;
292
293         while (len > chunk) {
294                 btrfs_remove_free_space(block_group, start, chunk);
295                 start += step;
296                 if (len < step)
297                         len = 0;
298                 else
299                         len -= step;
300         }
301 }
302 #endif
303
304 /*
305  * this is only called by cache_block_group, since we could have freed extents
306  * we need to check the pinned_extents for any extents that can't be used yet
307  * since their free space will be released as soon as the transaction commits.
308  */
309 u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
310                        u64 start, u64 end)
311 {
312         struct btrfs_fs_info *info = block_group->fs_info;
313         u64 extent_start, extent_end, size, total_added = 0;
314         int ret;
315
316         while (start < end) {
317                 ret = find_first_extent_bit(info->pinned_extents, start,
318                                             &extent_start, &extent_end,
319                                             EXTENT_DIRTY | EXTENT_UPTODATE,
320                                             NULL);
321                 if (ret)
322                         break;
323
324                 if (extent_start <= start) {
325                         start = extent_end + 1;
326                 } else if (extent_start > start && extent_start < end) {
327                         size = extent_start - start;
328                         total_added += size;
329                         ret = btrfs_add_free_space(block_group, start,
330                                                    size);
331                         BUG_ON(ret); /* -ENOMEM or logic error */
332                         start = extent_end + 1;
333                 } else {
334                         break;
335                 }
336         }
337
338         if (start < end) {
339                 size = end - start;
340                 total_added += size;
341                 ret = btrfs_add_free_space(block_group, start, size);
342                 BUG_ON(ret); /* -ENOMEM or logic error */
343         }
344
345         return total_added;
346 }
347
348 static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
349 {
350         struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
351         struct btrfs_fs_info *fs_info = block_group->fs_info;
352         struct btrfs_root *extent_root = fs_info->extent_root;
353         struct btrfs_path *path;
354         struct extent_buffer *leaf;
355         struct btrfs_key key;
356         u64 total_found = 0;
357         u64 last = 0;
358         u32 nritems;
359         int ret;
360         bool wakeup = true;
361
362         path = btrfs_alloc_path();
363         if (!path)
364                 return -ENOMEM;
365
366         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
367
368 #ifdef CONFIG_BTRFS_DEBUG
369         /*
370          * If we're fragmenting we don't want to make anybody think we can
371          * allocate from this block group until we've had a chance to fragment
372          * the free space.
373          */
374         if (btrfs_should_fragment_free_space(block_group))
375                 wakeup = false;
376 #endif
377         /*
378          * We don't want to deadlock with somebody trying to allocate a new
379          * extent for the extent root while also trying to search the extent
380          * root to add free space.  So we skip locking and search the commit
381          * root, since its read-only
382          */
383         path->skip_locking = 1;
384         path->search_commit_root = 1;
385         path->reada = READA_FORWARD;
386
387         key.objectid = last;
388         key.offset = 0;
389         key.type = BTRFS_EXTENT_ITEM_KEY;
390
391 next:
392         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
393         if (ret < 0)
394                 goto out;
395
396         leaf = path->nodes[0];
397         nritems = btrfs_header_nritems(leaf);
398
399         while (1) {
400                 if (btrfs_fs_closing(fs_info) > 1) {
401                         last = (u64)-1;
402                         break;
403                 }
404
405                 if (path->slots[0] < nritems) {
406                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
407                 } else {
408                         ret = find_next_key(path, 0, &key);
409                         if (ret)
410                                 break;
411
412                         if (need_resched() ||
413                             rwsem_is_contended(&fs_info->commit_root_sem)) {
414                                 if (wakeup)
415                                         caching_ctl->progress = last;
416                                 btrfs_release_path(path);
417                                 up_read(&fs_info->commit_root_sem);
418                                 mutex_unlock(&caching_ctl->mutex);
419                                 cond_resched();
420                                 mutex_lock(&caching_ctl->mutex);
421                                 down_read(&fs_info->commit_root_sem);
422                                 goto next;
423                         }
424
425                         ret = btrfs_next_leaf(extent_root, path);
426                         if (ret < 0)
427                                 goto out;
428                         if (ret)
429                                 break;
430                         leaf = path->nodes[0];
431                         nritems = btrfs_header_nritems(leaf);
432                         continue;
433                 }
434
435                 if (key.objectid < last) {
436                         key.objectid = last;
437                         key.offset = 0;
438                         key.type = BTRFS_EXTENT_ITEM_KEY;
439
440                         if (wakeup)
441                                 caching_ctl->progress = last;
442                         btrfs_release_path(path);
443                         goto next;
444                 }
445
446                 if (key.objectid < block_group->key.objectid) {
447                         path->slots[0]++;
448                         continue;
449                 }
450
451                 if (key.objectid >= block_group->key.objectid +
452                     block_group->key.offset)
453                         break;
454
455                 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
456                     key.type == BTRFS_METADATA_ITEM_KEY) {
457                         total_found += add_new_free_space(block_group, last,
458                                                           key.objectid);
459                         if (key.type == BTRFS_METADATA_ITEM_KEY)
460                                 last = key.objectid +
461                                         fs_info->nodesize;
462                         else
463                                 last = key.objectid + key.offset;
464
465                         if (total_found > CACHING_CTL_WAKE_UP) {
466                                 total_found = 0;
467                                 if (wakeup)
468                                         wake_up(&caching_ctl->wait);
469                         }
470                 }
471                 path->slots[0]++;
472         }
473         ret = 0;
474
475         total_found += add_new_free_space(block_group, last,
476                                           block_group->key.objectid +
477                                           block_group->key.offset);
478         caching_ctl->progress = (u64)-1;
479
480 out:
481         btrfs_free_path(path);
482         return ret;
483 }
484
485 static noinline void caching_thread(struct btrfs_work *work)
486 {
487         struct btrfs_block_group_cache *block_group;
488         struct btrfs_fs_info *fs_info;
489         struct btrfs_caching_control *caching_ctl;
490         int ret;
491
492         caching_ctl = container_of(work, struct btrfs_caching_control, work);
493         block_group = caching_ctl->block_group;
494         fs_info = block_group->fs_info;
495
496         mutex_lock(&caching_ctl->mutex);
497         down_read(&fs_info->commit_root_sem);
498
499         if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
500                 ret = load_free_space_tree(caching_ctl);
501         else
502                 ret = load_extent_tree_free(caching_ctl);
503
504         spin_lock(&block_group->lock);
505         block_group->caching_ctl = NULL;
506         block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
507         spin_unlock(&block_group->lock);
508
509 #ifdef CONFIG_BTRFS_DEBUG
510         if (btrfs_should_fragment_free_space(block_group)) {
511                 u64 bytes_used;
512
513                 spin_lock(&block_group->space_info->lock);
514                 spin_lock(&block_group->lock);
515                 bytes_used = block_group->key.offset -
516                         btrfs_block_group_used(&block_group->item);
517                 block_group->space_info->bytes_used += bytes_used >> 1;
518                 spin_unlock(&block_group->lock);
519                 spin_unlock(&block_group->space_info->lock);
520                 fragment_free_space(block_group);
521         }
522 #endif
523
524         caching_ctl->progress = (u64)-1;
525
526         up_read(&fs_info->commit_root_sem);
527         free_excluded_extents(block_group);
528         mutex_unlock(&caching_ctl->mutex);
529
530         wake_up(&caching_ctl->wait);
531
532         put_caching_control(caching_ctl);
533         btrfs_put_block_group(block_group);
534 }
535
536 static int cache_block_group(struct btrfs_block_group_cache *cache,
537                              int load_cache_only)
538 {
539         DEFINE_WAIT(wait);
540         struct btrfs_fs_info *fs_info = cache->fs_info;
541         struct btrfs_caching_control *caching_ctl;
542         int ret = 0;
543
544         caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
545         if (!caching_ctl)
546                 return -ENOMEM;
547
548         INIT_LIST_HEAD(&caching_ctl->list);
549         mutex_init(&caching_ctl->mutex);
550         init_waitqueue_head(&caching_ctl->wait);
551         caching_ctl->block_group = cache;
552         caching_ctl->progress = cache->key.objectid;
553         refcount_set(&caching_ctl->count, 1);
554         btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
555                         caching_thread, NULL, NULL);
556
557         spin_lock(&cache->lock);
558         /*
559          * This should be a rare occasion, but this could happen I think in the
560          * case where one thread starts to load the space cache info, and then
561          * some other thread starts a transaction commit which tries to do an
562          * allocation while the other thread is still loading the space cache
563          * info.  The previous loop should have kept us from choosing this block
564          * group, but if we've moved to the state where we will wait on caching
565          * block groups we need to first check if we're doing a fast load here,
566          * so we can wait for it to finish, otherwise we could end up allocating
567          * from a block group who's cache gets evicted for one reason or
568          * another.
569          */
570         while (cache->cached == BTRFS_CACHE_FAST) {
571                 struct btrfs_caching_control *ctl;
572
573                 ctl = cache->caching_ctl;
574                 refcount_inc(&ctl->count);
575                 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
576                 spin_unlock(&cache->lock);
577
578                 schedule();
579
580                 finish_wait(&ctl->wait, &wait);
581                 put_caching_control(ctl);
582                 spin_lock(&cache->lock);
583         }
584
585         if (cache->cached != BTRFS_CACHE_NO) {
586                 spin_unlock(&cache->lock);
587                 kfree(caching_ctl);
588                 return 0;
589         }
590         WARN_ON(cache->caching_ctl);
591         cache->caching_ctl = caching_ctl;
592         cache->cached = BTRFS_CACHE_FAST;
593         spin_unlock(&cache->lock);
594
595         if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
596                 mutex_lock(&caching_ctl->mutex);
597                 ret = load_free_space_cache(cache);
598
599                 spin_lock(&cache->lock);
600                 if (ret == 1) {
601                         cache->caching_ctl = NULL;
602                         cache->cached = BTRFS_CACHE_FINISHED;
603                         cache->last_byte_to_unpin = (u64)-1;
604                         caching_ctl->progress = (u64)-1;
605                 } else {
606                         if (load_cache_only) {
607                                 cache->caching_ctl = NULL;
608                                 cache->cached = BTRFS_CACHE_NO;
609                         } else {
610                                 cache->cached = BTRFS_CACHE_STARTED;
611                                 cache->has_caching_ctl = 1;
612                         }
613                 }
614                 spin_unlock(&cache->lock);
615 #ifdef CONFIG_BTRFS_DEBUG
616                 if (ret == 1 &&
617                     btrfs_should_fragment_free_space(cache)) {
618                         u64 bytes_used;
619
620                         spin_lock(&cache->space_info->lock);
621                         spin_lock(&cache->lock);
622                         bytes_used = cache->key.offset -
623                                 btrfs_block_group_used(&cache->item);
624                         cache->space_info->bytes_used += bytes_used >> 1;
625                         spin_unlock(&cache->lock);
626                         spin_unlock(&cache->space_info->lock);
627                         fragment_free_space(cache);
628                 }
629 #endif
630                 mutex_unlock(&caching_ctl->mutex);
631
632                 wake_up(&caching_ctl->wait);
633                 if (ret == 1) {
634                         put_caching_control(caching_ctl);
635                         free_excluded_extents(cache);
636                         return 0;
637                 }
638         } else {
639                 /*
640                  * We're either using the free space tree or no caching at all.
641                  * Set cached to the appropriate value and wakeup any waiters.
642                  */
643                 spin_lock(&cache->lock);
644                 if (load_cache_only) {
645                         cache->caching_ctl = NULL;
646                         cache->cached = BTRFS_CACHE_NO;
647                 } else {
648                         cache->cached = BTRFS_CACHE_STARTED;
649                         cache->has_caching_ctl = 1;
650                 }
651                 spin_unlock(&cache->lock);
652                 wake_up(&caching_ctl->wait);
653         }
654
655         if (load_cache_only) {
656                 put_caching_control(caching_ctl);
657                 return 0;
658         }
659
660         down_write(&fs_info->commit_root_sem);
661         refcount_inc(&caching_ctl->count);
662         list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
663         up_write(&fs_info->commit_root_sem);
664
665         btrfs_get_block_group(cache);
666
667         btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
668
669         return ret;
670 }
671
672 /*
673  * return the block group that starts at or after bytenr
674  */
675 static struct btrfs_block_group_cache *
676 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
677 {
678         return block_group_cache_tree_search(info, bytenr, 0);
679 }
680
681 /*
682  * return the block group that contains the given bytenr
683  */
684 struct btrfs_block_group_cache *btrfs_lookup_block_group(
685                                                  struct btrfs_fs_info *info,
686                                                  u64 bytenr)
687 {
688         return block_group_cache_tree_search(info, bytenr, 1);
689 }
690
691 static u64 generic_ref_to_space_flags(struct btrfs_ref *ref)
692 {
693         if (ref->type == BTRFS_REF_METADATA) {
694                 if (ref->tree_ref.root == BTRFS_CHUNK_TREE_OBJECTID)
695                         return BTRFS_BLOCK_GROUP_SYSTEM;
696                 else
697                         return BTRFS_BLOCK_GROUP_METADATA;
698         }
699         return BTRFS_BLOCK_GROUP_DATA;
700 }
701
702 static void add_pinned_bytes(struct btrfs_fs_info *fs_info,
703                              struct btrfs_ref *ref)
704 {
705         struct btrfs_space_info *space_info;
706         u64 flags = generic_ref_to_space_flags(ref);
707
708         space_info = btrfs_find_space_info(fs_info, flags);
709         ASSERT(space_info);
710         percpu_counter_add_batch(&space_info->total_bytes_pinned, ref->len,
711                     BTRFS_TOTAL_BYTES_PINNED_BATCH);
712 }
713
714 static void sub_pinned_bytes(struct btrfs_fs_info *fs_info,
715                              struct btrfs_ref *ref)
716 {
717         struct btrfs_space_info *space_info;
718         u64 flags = generic_ref_to_space_flags(ref);
719
720         space_info = btrfs_find_space_info(fs_info, flags);
721         ASSERT(space_info);
722         percpu_counter_add_batch(&space_info->total_bytes_pinned, -ref->len,
723                     BTRFS_TOTAL_BYTES_PINNED_BATCH);
724 }
725
726 /* simple helper to search for an existing data extent at a given offset */
727 int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
728 {
729         int ret;
730         struct btrfs_key key;
731         struct btrfs_path *path;
732
733         path = btrfs_alloc_path();
734         if (!path)
735                 return -ENOMEM;
736
737         key.objectid = start;
738         key.offset = len;
739         key.type = BTRFS_EXTENT_ITEM_KEY;
740         ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
741         btrfs_free_path(path);
742         return ret;
743 }
744
745 /*
746  * helper function to lookup reference count and flags of a tree block.
747  *
748  * the head node for delayed ref is used to store the sum of all the
749  * reference count modifications queued up in the rbtree. the head
750  * node may also store the extent flags to set. This way you can check
751  * to see what the reference count and extent flags would be if all of
752  * the delayed refs are not processed.
753  */
754 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
755                              struct btrfs_fs_info *fs_info, u64 bytenr,
756                              u64 offset, int metadata, u64 *refs, u64 *flags)
757 {
758         struct btrfs_delayed_ref_head *head;
759         struct btrfs_delayed_ref_root *delayed_refs;
760         struct btrfs_path *path;
761         struct btrfs_extent_item *ei;
762         struct extent_buffer *leaf;
763         struct btrfs_key key;
764         u32 item_size;
765         u64 num_refs;
766         u64 extent_flags;
767         int ret;
768
769         /*
770          * If we don't have skinny metadata, don't bother doing anything
771          * different
772          */
773         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
774                 offset = fs_info->nodesize;
775                 metadata = 0;
776         }
777
778         path = btrfs_alloc_path();
779         if (!path)
780                 return -ENOMEM;
781
782         if (!trans) {
783                 path->skip_locking = 1;
784                 path->search_commit_root = 1;
785         }
786
787 search_again:
788         key.objectid = bytenr;
789         key.offset = offset;
790         if (metadata)
791                 key.type = BTRFS_METADATA_ITEM_KEY;
792         else
793                 key.type = BTRFS_EXTENT_ITEM_KEY;
794
795         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
796         if (ret < 0)
797                 goto out_free;
798
799         if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
800                 if (path->slots[0]) {
801                         path->slots[0]--;
802                         btrfs_item_key_to_cpu(path->nodes[0], &key,
803                                               path->slots[0]);
804                         if (key.objectid == bytenr &&
805                             key.type == BTRFS_EXTENT_ITEM_KEY &&
806                             key.offset == fs_info->nodesize)
807                                 ret = 0;
808                 }
809         }
810
811         if (ret == 0) {
812                 leaf = path->nodes[0];
813                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
814                 if (item_size >= sizeof(*ei)) {
815                         ei = btrfs_item_ptr(leaf, path->slots[0],
816                                             struct btrfs_extent_item);
817                         num_refs = btrfs_extent_refs(leaf, ei);
818                         extent_flags = btrfs_extent_flags(leaf, ei);
819                 } else {
820                         ret = -EINVAL;
821                         btrfs_print_v0_err(fs_info);
822                         if (trans)
823                                 btrfs_abort_transaction(trans, ret);
824                         else
825                                 btrfs_handle_fs_error(fs_info, ret, NULL);
826
827                         goto out_free;
828                 }
829
830                 BUG_ON(num_refs == 0);
831         } else {
832                 num_refs = 0;
833                 extent_flags = 0;
834                 ret = 0;
835         }
836
837         if (!trans)
838                 goto out;
839
840         delayed_refs = &trans->transaction->delayed_refs;
841         spin_lock(&delayed_refs->lock);
842         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
843         if (head) {
844                 if (!mutex_trylock(&head->mutex)) {
845                         refcount_inc(&head->refs);
846                         spin_unlock(&delayed_refs->lock);
847
848                         btrfs_release_path(path);
849
850                         /*
851                          * Mutex was contended, block until it's released and try
852                          * again
853                          */
854                         mutex_lock(&head->mutex);
855                         mutex_unlock(&head->mutex);
856                         btrfs_put_delayed_ref_head(head);
857                         goto search_again;
858                 }
859                 spin_lock(&head->lock);
860                 if (head->extent_op && head->extent_op->update_flags)
861                         extent_flags |= head->extent_op->flags_to_set;
862                 else
863                         BUG_ON(num_refs == 0);
864
865                 num_refs += head->ref_mod;
866                 spin_unlock(&head->lock);
867                 mutex_unlock(&head->mutex);
868         }
869         spin_unlock(&delayed_refs->lock);
870 out:
871         WARN_ON(num_refs == 0);
872         if (refs)
873                 *refs = num_refs;
874         if (flags)
875                 *flags = extent_flags;
876 out_free:
877         btrfs_free_path(path);
878         return ret;
879 }
880
881 /*
882  * Back reference rules.  Back refs have three main goals:
883  *
884  * 1) differentiate between all holders of references to an extent so that
885  *    when a reference is dropped we can make sure it was a valid reference
886  *    before freeing the extent.
887  *
888  * 2) Provide enough information to quickly find the holders of an extent
889  *    if we notice a given block is corrupted or bad.
890  *
891  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
892  *    maintenance.  This is actually the same as #2, but with a slightly
893  *    different use case.
894  *
895  * There are two kinds of back refs. The implicit back refs is optimized
896  * for pointers in non-shared tree blocks. For a given pointer in a block,
897  * back refs of this kind provide information about the block's owner tree
898  * and the pointer's key. These information allow us to find the block by
899  * b-tree searching. The full back refs is for pointers in tree blocks not
900  * referenced by their owner trees. The location of tree block is recorded
901  * in the back refs. Actually the full back refs is generic, and can be
902  * used in all cases the implicit back refs is used. The major shortcoming
903  * of the full back refs is its overhead. Every time a tree block gets
904  * COWed, we have to update back refs entry for all pointers in it.
905  *
906  * For a newly allocated tree block, we use implicit back refs for
907  * pointers in it. This means most tree related operations only involve
908  * implicit back refs. For a tree block created in old transaction, the
909  * only way to drop a reference to it is COW it. So we can detect the
910  * event that tree block loses its owner tree's reference and do the
911  * back refs conversion.
912  *
913  * When a tree block is COWed through a tree, there are four cases:
914  *
915  * The reference count of the block is one and the tree is the block's
916  * owner tree. Nothing to do in this case.
917  *
918  * The reference count of the block is one and the tree is not the
919  * block's owner tree. In this case, full back refs is used for pointers
920  * in the block. Remove these full back refs, add implicit back refs for
921  * every pointers in the new block.
922  *
923  * The reference count of the block is greater than one and the tree is
924  * the block's owner tree. In this case, implicit back refs is used for
925  * pointers in the block. Add full back refs for every pointers in the
926  * block, increase lower level extents' reference counts. The original
927  * implicit back refs are entailed to the new block.
928  *
929  * The reference count of the block is greater than one and the tree is
930  * not the block's owner tree. Add implicit back refs for every pointer in
931  * the new block, increase lower level extents' reference count.
932  *
933  * Back Reference Key composing:
934  *
935  * The key objectid corresponds to the first byte in the extent,
936  * The key type is used to differentiate between types of back refs.
937  * There are different meanings of the key offset for different types
938  * of back refs.
939  *
940  * File extents can be referenced by:
941  *
942  * - multiple snapshots, subvolumes, or different generations in one subvol
943  * - different files inside a single subvolume
944  * - different offsets inside a file (bookend extents in file.c)
945  *
946  * The extent ref structure for the implicit back refs has fields for:
947  *
948  * - Objectid of the subvolume root
949  * - objectid of the file holding the reference
950  * - original offset in the file
951  * - how many bookend extents
952  *
953  * The key offset for the implicit back refs is hash of the first
954  * three fields.
955  *
956  * The extent ref structure for the full back refs has field for:
957  *
958  * - number of pointers in the tree leaf
959  *
960  * The key offset for the implicit back refs is the first byte of
961  * the tree leaf
962  *
963  * When a file extent is allocated, The implicit back refs is used.
964  * the fields are filled in:
965  *
966  *     (root_key.objectid, inode objectid, offset in file, 1)
967  *
968  * When a file extent is removed file truncation, we find the
969  * corresponding implicit back refs and check the following fields:
970  *
971  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
972  *
973  * Btree extents can be referenced by:
974  *
975  * - Different subvolumes
976  *
977  * Both the implicit back refs and the full back refs for tree blocks
978  * only consist of key. The key offset for the implicit back refs is
979  * objectid of block's owner tree. The key offset for the full back refs
980  * is the first byte of parent block.
981  *
982  * When implicit back refs is used, information about the lowest key and
983  * level of the tree block are required. These information are stored in
984  * tree block info structure.
985  */
986
987 /*
988  * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
989  * is_data == BTRFS_REF_TYPE_DATA, data type is requiried,
990  * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
991  */
992 int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
993                                      struct btrfs_extent_inline_ref *iref,
994                                      enum btrfs_inline_ref_type is_data)
995 {
996         int type = btrfs_extent_inline_ref_type(eb, iref);
997         u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
998
999         if (type == BTRFS_TREE_BLOCK_REF_KEY ||
1000             type == BTRFS_SHARED_BLOCK_REF_KEY ||
1001             type == BTRFS_SHARED_DATA_REF_KEY ||
1002             type == BTRFS_EXTENT_DATA_REF_KEY) {
1003                 if (is_data == BTRFS_REF_TYPE_BLOCK) {
1004                         if (type == BTRFS_TREE_BLOCK_REF_KEY)
1005                                 return type;
1006                         if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1007                                 ASSERT(eb->fs_info);
1008                                 /*
1009                                  * Every shared one has parent tree
1010                                  * block, which must be aligned to
1011                                  * nodesize.
1012                                  */
1013                                 if (offset &&
1014                                     IS_ALIGNED(offset, eb->fs_info->nodesize))
1015                                         return type;
1016                         }
1017                 } else if (is_data == BTRFS_REF_TYPE_DATA) {
1018                         if (type == BTRFS_EXTENT_DATA_REF_KEY)
1019                                 return type;
1020                         if (type == BTRFS_SHARED_DATA_REF_KEY) {
1021                                 ASSERT(eb->fs_info);
1022                                 /*
1023                                  * Every shared one has parent tree
1024                                  * block, which must be aligned to
1025                                  * nodesize.
1026                                  */
1027                                 if (offset &&
1028                                     IS_ALIGNED(offset, eb->fs_info->nodesize))
1029                                         return type;
1030                         }
1031                 } else {
1032                         ASSERT(is_data == BTRFS_REF_TYPE_ANY);
1033                         return type;
1034                 }
1035         }
1036
1037         btrfs_print_leaf((struct extent_buffer *)eb);
1038         btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
1039                   eb->start, type);
1040         WARN_ON(1);
1041
1042         return BTRFS_REF_TYPE_INVALID;
1043 }
1044
1045 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1046 {
1047         u32 high_crc = ~(u32)0;
1048         u32 low_crc = ~(u32)0;
1049         __le64 lenum;
1050
1051         lenum = cpu_to_le64(root_objectid);
1052         high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1053         lenum = cpu_to_le64(owner);
1054         low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1055         lenum = cpu_to_le64(offset);
1056         low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1057
1058         return ((u64)high_crc << 31) ^ (u64)low_crc;
1059 }
1060
1061 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1062                                      struct btrfs_extent_data_ref *ref)
1063 {
1064         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1065                                     btrfs_extent_data_ref_objectid(leaf, ref),
1066                                     btrfs_extent_data_ref_offset(leaf, ref));
1067 }
1068
1069 static int match_extent_data_ref(struct extent_buffer *leaf,
1070                                  struct btrfs_extent_data_ref *ref,
1071                                  u64 root_objectid, u64 owner, u64 offset)
1072 {
1073         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1074             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1075             btrfs_extent_data_ref_offset(leaf, ref) != offset)
1076                 return 0;
1077         return 1;
1078 }
1079
1080 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1081                                            struct btrfs_path *path,
1082                                            u64 bytenr, u64 parent,
1083                                            u64 root_objectid,
1084                                            u64 owner, u64 offset)
1085 {
1086         struct btrfs_root *root = trans->fs_info->extent_root;
1087         struct btrfs_key key;
1088         struct btrfs_extent_data_ref *ref;
1089         struct extent_buffer *leaf;
1090         u32 nritems;
1091         int ret;
1092         int recow;
1093         int err = -ENOENT;
1094
1095         key.objectid = bytenr;
1096         if (parent) {
1097                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1098                 key.offset = parent;
1099         } else {
1100                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1101                 key.offset = hash_extent_data_ref(root_objectid,
1102                                                   owner, offset);
1103         }
1104 again:
1105         recow = 0;
1106         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1107         if (ret < 0) {
1108                 err = ret;
1109                 goto fail;
1110         }
1111
1112         if (parent) {
1113                 if (!ret)
1114                         return 0;
1115                 goto fail;
1116         }
1117
1118         leaf = path->nodes[0];
1119         nritems = btrfs_header_nritems(leaf);
1120         while (1) {
1121                 if (path->slots[0] >= nritems) {
1122                         ret = btrfs_next_leaf(root, path);
1123                         if (ret < 0)
1124                                 err = ret;
1125                         if (ret)
1126                                 goto fail;
1127
1128                         leaf = path->nodes[0];
1129                         nritems = btrfs_header_nritems(leaf);
1130                         recow = 1;
1131                 }
1132
1133                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1134                 if (key.objectid != bytenr ||
1135                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1136                         goto fail;
1137
1138                 ref = btrfs_item_ptr(leaf, path->slots[0],
1139                                      struct btrfs_extent_data_ref);
1140
1141                 if (match_extent_data_ref(leaf, ref, root_objectid,
1142                                           owner, offset)) {
1143                         if (recow) {
1144                                 btrfs_release_path(path);
1145                                 goto again;
1146                         }
1147                         err = 0;
1148                         break;
1149                 }
1150                 path->slots[0]++;
1151         }
1152 fail:
1153         return err;
1154 }
1155
1156 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1157                                            struct btrfs_path *path,
1158                                            u64 bytenr, u64 parent,
1159                                            u64 root_objectid, u64 owner,
1160                                            u64 offset, int refs_to_add)
1161 {
1162         struct btrfs_root *root = trans->fs_info->extent_root;
1163         struct btrfs_key key;
1164         struct extent_buffer *leaf;
1165         u32 size;
1166         u32 num_refs;
1167         int ret;
1168
1169         key.objectid = bytenr;
1170         if (parent) {
1171                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1172                 key.offset = parent;
1173                 size = sizeof(struct btrfs_shared_data_ref);
1174         } else {
1175                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1176                 key.offset = hash_extent_data_ref(root_objectid,
1177                                                   owner, offset);
1178                 size = sizeof(struct btrfs_extent_data_ref);
1179         }
1180
1181         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1182         if (ret && ret != -EEXIST)
1183                 goto fail;
1184
1185         leaf = path->nodes[0];
1186         if (parent) {
1187                 struct btrfs_shared_data_ref *ref;
1188                 ref = btrfs_item_ptr(leaf, path->slots[0],
1189                                      struct btrfs_shared_data_ref);
1190                 if (ret == 0) {
1191                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1192                 } else {
1193                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1194                         num_refs += refs_to_add;
1195                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1196                 }
1197         } else {
1198                 struct btrfs_extent_data_ref *ref;
1199                 while (ret == -EEXIST) {
1200                         ref = btrfs_item_ptr(leaf, path->slots[0],
1201                                              struct btrfs_extent_data_ref);
1202                         if (match_extent_data_ref(leaf, ref, root_objectid,
1203                                                   owner, offset))
1204                                 break;
1205                         btrfs_release_path(path);
1206                         key.offset++;
1207                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1208                                                       size);
1209                         if (ret && ret != -EEXIST)
1210                                 goto fail;
1211
1212                         leaf = path->nodes[0];
1213                 }
1214                 ref = btrfs_item_ptr(leaf, path->slots[0],
1215                                      struct btrfs_extent_data_ref);
1216                 if (ret == 0) {
1217                         btrfs_set_extent_data_ref_root(leaf, ref,
1218                                                        root_objectid);
1219                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1220                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1221                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1222                 } else {
1223                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1224                         num_refs += refs_to_add;
1225                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1226                 }
1227         }
1228         btrfs_mark_buffer_dirty(leaf);
1229         ret = 0;
1230 fail:
1231         btrfs_release_path(path);
1232         return ret;
1233 }
1234
1235 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1236                                            struct btrfs_path *path,
1237                                            int refs_to_drop, int *last_ref)
1238 {
1239         struct btrfs_key key;
1240         struct btrfs_extent_data_ref *ref1 = NULL;
1241         struct btrfs_shared_data_ref *ref2 = NULL;
1242         struct extent_buffer *leaf;
1243         u32 num_refs = 0;
1244         int ret = 0;
1245
1246         leaf = path->nodes[0];
1247         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1248
1249         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1250                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1251                                       struct btrfs_extent_data_ref);
1252                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1253         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1254                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1255                                       struct btrfs_shared_data_ref);
1256                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1257         } else if (unlikely(key.type == BTRFS_EXTENT_REF_V0_KEY)) {
1258                 btrfs_print_v0_err(trans->fs_info);
1259                 btrfs_abort_transaction(trans, -EINVAL);
1260                 return -EINVAL;
1261         } else {
1262                 BUG();
1263         }
1264
1265         BUG_ON(num_refs < refs_to_drop);
1266         num_refs -= refs_to_drop;
1267
1268         if (num_refs == 0) {
1269                 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1270                 *last_ref = 1;
1271         } else {
1272                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1273                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1274                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1275                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1276                 btrfs_mark_buffer_dirty(leaf);
1277         }
1278         return ret;
1279 }
1280
1281 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1282                                           struct btrfs_extent_inline_ref *iref)
1283 {
1284         struct btrfs_key key;
1285         struct extent_buffer *leaf;
1286         struct btrfs_extent_data_ref *ref1;
1287         struct btrfs_shared_data_ref *ref2;
1288         u32 num_refs = 0;
1289         int type;
1290
1291         leaf = path->nodes[0];
1292         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1293
1294         BUG_ON(key.type == BTRFS_EXTENT_REF_V0_KEY);
1295         if (iref) {
1296                 /*
1297                  * If type is invalid, we should have bailed out earlier than
1298                  * this call.
1299                  */
1300                 type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
1301                 ASSERT(type != BTRFS_REF_TYPE_INVALID);
1302                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1303                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1304                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1305                 } else {
1306                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1307                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1308                 }
1309         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1310                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1311                                       struct btrfs_extent_data_ref);
1312                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1313         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1314                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1315                                       struct btrfs_shared_data_ref);
1316                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1317         } else {
1318                 WARN_ON(1);
1319         }
1320         return num_refs;
1321 }
1322
1323 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1324                                           struct btrfs_path *path,
1325                                           u64 bytenr, u64 parent,
1326                                           u64 root_objectid)
1327 {
1328         struct btrfs_root *root = trans->fs_info->extent_root;
1329         struct btrfs_key key;
1330         int ret;
1331
1332         key.objectid = bytenr;
1333         if (parent) {
1334                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1335                 key.offset = parent;
1336         } else {
1337                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1338                 key.offset = root_objectid;
1339         }
1340
1341         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1342         if (ret > 0)
1343                 ret = -ENOENT;
1344         return ret;
1345 }
1346
1347 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1348                                           struct btrfs_path *path,
1349                                           u64 bytenr, u64 parent,
1350                                           u64 root_objectid)
1351 {
1352         struct btrfs_key key;
1353         int ret;
1354
1355         key.objectid = bytenr;
1356         if (parent) {
1357                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1358                 key.offset = parent;
1359         } else {
1360                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1361                 key.offset = root_objectid;
1362         }
1363
1364         ret = btrfs_insert_empty_item(trans, trans->fs_info->extent_root,
1365                                       path, &key, 0);
1366         btrfs_release_path(path);
1367         return ret;
1368 }
1369
1370 static inline int extent_ref_type(u64 parent, u64 owner)
1371 {
1372         int type;
1373         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1374                 if (parent > 0)
1375                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1376                 else
1377                         type = BTRFS_TREE_BLOCK_REF_KEY;
1378         } else {
1379                 if (parent > 0)
1380                         type = BTRFS_SHARED_DATA_REF_KEY;
1381                 else
1382                         type = BTRFS_EXTENT_DATA_REF_KEY;
1383         }
1384         return type;
1385 }
1386
1387 static int find_next_key(struct btrfs_path *path, int level,
1388                          struct btrfs_key *key)
1389
1390 {
1391         for (; level < BTRFS_MAX_LEVEL; level++) {
1392                 if (!path->nodes[level])
1393                         break;
1394                 if (path->slots[level] + 1 >=
1395                     btrfs_header_nritems(path->nodes[level]))
1396                         continue;
1397                 if (level == 0)
1398                         btrfs_item_key_to_cpu(path->nodes[level], key,
1399                                               path->slots[level] + 1);
1400                 else
1401                         btrfs_node_key_to_cpu(path->nodes[level], key,
1402                                               path->slots[level] + 1);
1403                 return 0;
1404         }
1405         return 1;
1406 }
1407
1408 /*
1409  * look for inline back ref. if back ref is found, *ref_ret is set
1410  * to the address of inline back ref, and 0 is returned.
1411  *
1412  * if back ref isn't found, *ref_ret is set to the address where it
1413  * should be inserted, and -ENOENT is returned.
1414  *
1415  * if insert is true and there are too many inline back refs, the path
1416  * points to the extent item, and -EAGAIN is returned.
1417  *
1418  * NOTE: inline back refs are ordered in the same way that back ref
1419  *       items in the tree are ordered.
1420  */
1421 static noinline_for_stack
1422 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1423                                  struct btrfs_path *path,
1424                                  struct btrfs_extent_inline_ref **ref_ret,
1425                                  u64 bytenr, u64 num_bytes,
1426                                  u64 parent, u64 root_objectid,
1427                                  u64 owner, u64 offset, int insert)
1428 {
1429         struct btrfs_fs_info *fs_info = trans->fs_info;
1430         struct btrfs_root *root = fs_info->extent_root;
1431         struct btrfs_key key;
1432         struct extent_buffer *leaf;
1433         struct btrfs_extent_item *ei;
1434         struct btrfs_extent_inline_ref *iref;
1435         u64 flags;
1436         u64 item_size;
1437         unsigned long ptr;
1438         unsigned long end;
1439         int extra_size;
1440         int type;
1441         int want;
1442         int ret;
1443         int err = 0;
1444         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1445         int needed;
1446
1447         key.objectid = bytenr;
1448         key.type = BTRFS_EXTENT_ITEM_KEY;
1449         key.offset = num_bytes;
1450
1451         want = extent_ref_type(parent, owner);
1452         if (insert) {
1453                 extra_size = btrfs_extent_inline_ref_size(want);
1454                 path->keep_locks = 1;
1455         } else
1456                 extra_size = -1;
1457
1458         /*
1459          * Owner is our level, so we can just add one to get the level for the
1460          * block we are interested in.
1461          */
1462         if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1463                 key.type = BTRFS_METADATA_ITEM_KEY;
1464                 key.offset = owner;
1465         }
1466
1467 again:
1468         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1469         if (ret < 0) {
1470                 err = ret;
1471                 goto out;
1472         }
1473
1474         /*
1475          * We may be a newly converted file system which still has the old fat
1476          * extent entries for metadata, so try and see if we have one of those.
1477          */
1478         if (ret > 0 && skinny_metadata) {
1479                 skinny_metadata = false;
1480                 if (path->slots[0]) {
1481                         path->slots[0]--;
1482                         btrfs_item_key_to_cpu(path->nodes[0], &key,
1483                                               path->slots[0]);
1484                         if (key.objectid == bytenr &&
1485                             key.type == BTRFS_EXTENT_ITEM_KEY &&
1486                             key.offset == num_bytes)
1487                                 ret = 0;
1488                 }
1489                 if (ret) {
1490                         key.objectid = bytenr;
1491                         key.type = BTRFS_EXTENT_ITEM_KEY;
1492                         key.offset = num_bytes;
1493                         btrfs_release_path(path);
1494                         goto again;
1495                 }
1496         }
1497
1498         if (ret && !insert) {
1499                 err = -ENOENT;
1500                 goto out;
1501         } else if (WARN_ON(ret)) {
1502                 err = -EIO;
1503                 goto out;
1504         }
1505
1506         leaf = path->nodes[0];
1507         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1508         if (unlikely(item_size < sizeof(*ei))) {
1509                 err = -EINVAL;
1510                 btrfs_print_v0_err(fs_info);
1511                 btrfs_abort_transaction(trans, err);
1512                 goto out;
1513         }
1514
1515         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1516         flags = btrfs_extent_flags(leaf, ei);
1517
1518         ptr = (unsigned long)(ei + 1);
1519         end = (unsigned long)ei + item_size;
1520
1521         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1522                 ptr += sizeof(struct btrfs_tree_block_info);
1523                 BUG_ON(ptr > end);
1524         }
1525
1526         if (owner >= BTRFS_FIRST_FREE_OBJECTID)
1527                 needed = BTRFS_REF_TYPE_DATA;
1528         else
1529                 needed = BTRFS_REF_TYPE_BLOCK;
1530
1531         err = -ENOENT;
1532         while (1) {
1533                 if (ptr >= end) {
1534                         WARN_ON(ptr > end);
1535                         break;
1536                 }
1537                 iref = (struct btrfs_extent_inline_ref *)ptr;
1538                 type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
1539                 if (type == BTRFS_REF_TYPE_INVALID) {
1540                         err = -EUCLEAN;
1541                         goto out;
1542                 }
1543
1544                 if (want < type)
1545                         break;
1546                 if (want > type) {
1547                         ptr += btrfs_extent_inline_ref_size(type);
1548                         continue;
1549                 }
1550
1551                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1552                         struct btrfs_extent_data_ref *dref;
1553                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1554                         if (match_extent_data_ref(leaf, dref, root_objectid,
1555                                                   owner, offset)) {
1556                                 err = 0;
1557                                 break;
1558                         }
1559                         if (hash_extent_data_ref_item(leaf, dref) <
1560                             hash_extent_data_ref(root_objectid, owner, offset))
1561                                 break;
1562                 } else {
1563                         u64 ref_offset;
1564                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1565                         if (parent > 0) {
1566                                 if (parent == ref_offset) {
1567                                         err = 0;
1568                                         break;
1569                                 }
1570                                 if (ref_offset < parent)
1571                                         break;
1572                         } else {
1573                                 if (root_objectid == ref_offset) {
1574                                         err = 0;
1575                                         break;
1576                                 }
1577                                 if (ref_offset < root_objectid)
1578                                         break;
1579                         }
1580                 }
1581                 ptr += btrfs_extent_inline_ref_size(type);
1582         }
1583         if (err == -ENOENT && insert) {
1584                 if (item_size + extra_size >=
1585                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1586                         err = -EAGAIN;
1587                         goto out;
1588                 }
1589                 /*
1590                  * To add new inline back ref, we have to make sure
1591                  * there is no corresponding back ref item.
1592                  * For simplicity, we just do not add new inline back
1593                  * ref if there is any kind of item for this block
1594                  */
1595                 if (find_next_key(path, 0, &key) == 0 &&
1596                     key.objectid == bytenr &&
1597                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1598                         err = -EAGAIN;
1599                         goto out;
1600                 }
1601         }
1602         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1603 out:
1604         if (insert) {
1605                 path->keep_locks = 0;
1606                 btrfs_unlock_up_safe(path, 1);
1607         }
1608         return err;
1609 }
1610
1611 /*
1612  * helper to add new inline back ref
1613  */
1614 static noinline_for_stack
1615 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1616                                  struct btrfs_path *path,
1617                                  struct btrfs_extent_inline_ref *iref,
1618                                  u64 parent, u64 root_objectid,
1619                                  u64 owner, u64 offset, int refs_to_add,
1620                                  struct btrfs_delayed_extent_op *extent_op)
1621 {
1622         struct extent_buffer *leaf;
1623         struct btrfs_extent_item *ei;
1624         unsigned long ptr;
1625         unsigned long end;
1626         unsigned long item_offset;
1627         u64 refs;
1628         int size;
1629         int type;
1630
1631         leaf = path->nodes[0];
1632         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1633         item_offset = (unsigned long)iref - (unsigned long)ei;
1634
1635         type = extent_ref_type(parent, owner);
1636         size = btrfs_extent_inline_ref_size(type);
1637
1638         btrfs_extend_item(path, size);
1639
1640         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1641         refs = btrfs_extent_refs(leaf, ei);
1642         refs += refs_to_add;
1643         btrfs_set_extent_refs(leaf, ei, refs);
1644         if (extent_op)
1645                 __run_delayed_extent_op(extent_op, leaf, ei);
1646
1647         ptr = (unsigned long)ei + item_offset;
1648         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1649         if (ptr < end - size)
1650                 memmove_extent_buffer(leaf, ptr + size, ptr,
1651                                       end - size - ptr);
1652
1653         iref = (struct btrfs_extent_inline_ref *)ptr;
1654         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1655         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1656                 struct btrfs_extent_data_ref *dref;
1657                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1658                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1659                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1660                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1661                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1662         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1663                 struct btrfs_shared_data_ref *sref;
1664                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1665                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1666                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1667         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1668                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1669         } else {
1670                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1671         }
1672         btrfs_mark_buffer_dirty(leaf);
1673 }
1674
1675 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1676                                  struct btrfs_path *path,
1677                                  struct btrfs_extent_inline_ref **ref_ret,
1678                                  u64 bytenr, u64 num_bytes, u64 parent,
1679                                  u64 root_objectid, u64 owner, u64 offset)
1680 {
1681         int ret;
1682
1683         ret = lookup_inline_extent_backref(trans, path, ref_ret, bytenr,
1684                                            num_bytes, parent, root_objectid,
1685                                            owner, offset, 0);
1686         if (ret != -ENOENT)
1687                 return ret;
1688
1689         btrfs_release_path(path);
1690         *ref_ret = NULL;
1691
1692         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1693                 ret = lookup_tree_block_ref(trans, path, bytenr, parent,
1694                                             root_objectid);
1695         } else {
1696                 ret = lookup_extent_data_ref(trans, path, bytenr, parent,
1697                                              root_objectid, owner, offset);
1698         }
1699         return ret;
1700 }
1701
1702 /*
1703  * helper to update/remove inline back ref
1704  */
1705 static noinline_for_stack
1706 void update_inline_extent_backref(struct btrfs_path *path,
1707                                   struct btrfs_extent_inline_ref *iref,
1708                                   int refs_to_mod,
1709                                   struct btrfs_delayed_extent_op *extent_op,
1710                                   int *last_ref)
1711 {
1712         struct extent_buffer *leaf = path->nodes[0];
1713         struct btrfs_extent_item *ei;
1714         struct btrfs_extent_data_ref *dref = NULL;
1715         struct btrfs_shared_data_ref *sref = NULL;
1716         unsigned long ptr;
1717         unsigned long end;
1718         u32 item_size;
1719         int size;
1720         int type;
1721         u64 refs;
1722
1723         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1724         refs = btrfs_extent_refs(leaf, ei);
1725         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1726         refs += refs_to_mod;
1727         btrfs_set_extent_refs(leaf, ei, refs);
1728         if (extent_op)
1729                 __run_delayed_extent_op(extent_op, leaf, ei);
1730
1731         /*
1732          * If type is invalid, we should have bailed out after
1733          * lookup_inline_extent_backref().
1734          */
1735         type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
1736         ASSERT(type != BTRFS_REF_TYPE_INVALID);
1737
1738         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1739                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1740                 refs = btrfs_extent_data_ref_count(leaf, dref);
1741         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1742                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1743                 refs = btrfs_shared_data_ref_count(leaf, sref);
1744         } else {
1745                 refs = 1;
1746                 BUG_ON(refs_to_mod != -1);
1747         }
1748
1749         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1750         refs += refs_to_mod;
1751
1752         if (refs > 0) {
1753                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1754                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1755                 else
1756                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1757         } else {
1758                 *last_ref = 1;
1759                 size =  btrfs_extent_inline_ref_size(type);
1760                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1761                 ptr = (unsigned long)iref;
1762                 end = (unsigned long)ei + item_size;
1763                 if (ptr + size < end)
1764                         memmove_extent_buffer(leaf, ptr, ptr + size,
1765                                               end - ptr - size);
1766                 item_size -= size;
1767                 btrfs_truncate_item(path, item_size, 1);
1768         }
1769         btrfs_mark_buffer_dirty(leaf);
1770 }
1771
1772 static noinline_for_stack
1773 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1774                                  struct btrfs_path *path,
1775                                  u64 bytenr, u64 num_bytes, u64 parent,
1776                                  u64 root_objectid, u64 owner,
1777                                  u64 offset, int refs_to_add,
1778                                  struct btrfs_delayed_extent_op *extent_op)
1779 {
1780         struct btrfs_extent_inline_ref *iref;
1781         int ret;
1782
1783         ret = lookup_inline_extent_backref(trans, path, &iref, bytenr,
1784                                            num_bytes, parent, root_objectid,
1785                                            owner, offset, 1);
1786         if (ret == 0) {
1787                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1788                 update_inline_extent_backref(path, iref, refs_to_add,
1789                                              extent_op, NULL);
1790         } else if (ret == -ENOENT) {
1791                 setup_inline_extent_backref(trans->fs_info, path, iref, parent,
1792                                             root_objectid, owner, offset,
1793                                             refs_to_add, extent_op);
1794                 ret = 0;
1795         }
1796         return ret;
1797 }
1798
1799 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1800                                  struct btrfs_path *path,
1801                                  u64 bytenr, u64 parent, u64 root_objectid,
1802                                  u64 owner, u64 offset, int refs_to_add)
1803 {
1804         int ret;
1805         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1806                 BUG_ON(refs_to_add != 1);
1807                 ret = insert_tree_block_ref(trans, path, bytenr, parent,
1808                                             root_objectid);
1809         } else {
1810                 ret = insert_extent_data_ref(trans, path, bytenr, parent,
1811                                              root_objectid, owner, offset,
1812                                              refs_to_add);
1813         }
1814         return ret;
1815 }
1816
1817 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1818                                  struct btrfs_path *path,
1819                                  struct btrfs_extent_inline_ref *iref,
1820                                  int refs_to_drop, int is_data, int *last_ref)
1821 {
1822         int ret = 0;
1823
1824         BUG_ON(!is_data && refs_to_drop != 1);
1825         if (iref) {
1826                 update_inline_extent_backref(path, iref, -refs_to_drop, NULL,
1827                                              last_ref);
1828         } else if (is_data) {
1829                 ret = remove_extent_data_ref(trans, path, refs_to_drop,
1830                                              last_ref);
1831         } else {
1832                 *last_ref = 1;
1833                 ret = btrfs_del_item(trans, trans->fs_info->extent_root, path);
1834         }
1835         return ret;
1836 }
1837
1838 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1839                                u64 *discarded_bytes)
1840 {
1841         int j, ret = 0;
1842         u64 bytes_left, end;
1843         u64 aligned_start = ALIGN(start, 1 << 9);
1844
1845         if (WARN_ON(start != aligned_start)) {
1846                 len -= aligned_start - start;
1847                 len = round_down(len, 1 << 9);
1848                 start = aligned_start;
1849         }
1850
1851         *discarded_bytes = 0;
1852
1853         if (!len)
1854                 return 0;
1855
1856         end = start + len;
1857         bytes_left = len;
1858
1859         /* Skip any superblocks on this device. */
1860         for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1861                 u64 sb_start = btrfs_sb_offset(j);
1862                 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1863                 u64 size = sb_start - start;
1864
1865                 if (!in_range(sb_start, start, bytes_left) &&
1866                     !in_range(sb_end, start, bytes_left) &&
1867                     !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1868                         continue;
1869
1870                 /*
1871                  * Superblock spans beginning of range.  Adjust start and
1872                  * try again.
1873                  */
1874                 if (sb_start <= start) {
1875                         start += sb_end - start;
1876                         if (start > end) {
1877                                 bytes_left = 0;
1878                                 break;
1879                         }
1880                         bytes_left = end - start;
1881                         continue;
1882                 }
1883
1884                 if (size) {
1885                         ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1886                                                    GFP_NOFS, 0);
1887                         if (!ret)
1888                                 *discarded_bytes += size;
1889                         else if (ret != -EOPNOTSUPP)
1890                                 return ret;
1891                 }
1892
1893                 start = sb_end;
1894                 if (start > end) {
1895                         bytes_left = 0;
1896                         break;
1897                 }
1898                 bytes_left = end - start;
1899         }
1900
1901         if (bytes_left) {
1902                 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
1903                                            GFP_NOFS, 0);
1904                 if (!ret)
1905                         *discarded_bytes += bytes_left;
1906         }
1907         return ret;
1908 }
1909
1910 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
1911                          u64 num_bytes, u64 *actual_bytes)
1912 {
1913         int ret;
1914         u64 discarded_bytes = 0;
1915         struct btrfs_bio *bbio = NULL;
1916
1917
1918         /*
1919          * Avoid races with device replace and make sure our bbio has devices
1920          * associated to its stripes that don't go away while we are discarding.
1921          */
1922         btrfs_bio_counter_inc_blocked(fs_info);
1923         /* Tell the block device(s) that the sectors can be discarded */
1924         ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
1925                               &bbio, 0);
1926         /* Error condition is -ENOMEM */
1927         if (!ret) {
1928                 struct btrfs_bio_stripe *stripe = bbio->stripes;
1929                 int i;
1930
1931
1932                 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
1933                         u64 bytes;
1934                         struct request_queue *req_q;
1935
1936                         if (!stripe->dev->bdev) {
1937                                 ASSERT(btrfs_test_opt(fs_info, DEGRADED));
1938                                 continue;
1939                         }
1940                         req_q = bdev_get_queue(stripe->dev->bdev);
1941                         if (!blk_queue_discard(req_q))
1942                                 continue;
1943
1944                         ret = btrfs_issue_discard(stripe->dev->bdev,
1945                                                   stripe->physical,
1946                                                   stripe->length,
1947                                                   &bytes);
1948                         if (!ret)
1949                                 discarded_bytes += bytes;
1950                         else if (ret != -EOPNOTSUPP)
1951                                 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
1952
1953                         /*
1954                          * Just in case we get back EOPNOTSUPP for some reason,
1955                          * just ignore the return value so we don't screw up
1956                          * people calling discard_extent.
1957                          */
1958                         ret = 0;
1959                 }
1960                 btrfs_put_bbio(bbio);
1961         }
1962         btrfs_bio_counter_dec(fs_info);
1963
1964         if (actual_bytes)
1965                 *actual_bytes = discarded_bytes;
1966
1967
1968         if (ret == -EOPNOTSUPP)
1969                 ret = 0;
1970         return ret;
1971 }
1972
1973 /* Can return -ENOMEM */
1974 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1975                          struct btrfs_ref *generic_ref)
1976 {
1977         struct btrfs_fs_info *fs_info = trans->fs_info;
1978         int old_ref_mod, new_ref_mod;
1979         int ret;
1980
1981         ASSERT(generic_ref->type != BTRFS_REF_NOT_SET &&
1982                generic_ref->action);
1983         BUG_ON(generic_ref->type == BTRFS_REF_METADATA &&
1984                generic_ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID);
1985
1986         if (generic_ref->type == BTRFS_REF_METADATA)
1987                 ret = btrfs_add_delayed_tree_ref(trans, generic_ref,
1988                                 NULL, &old_ref_mod, &new_ref_mod);
1989         else
1990                 ret = btrfs_add_delayed_data_ref(trans, generic_ref, 0,
1991                                                  &old_ref_mod, &new_ref_mod);
1992
1993         btrfs_ref_tree_mod(fs_info, generic_ref);
1994
1995         if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
1996                 sub_pinned_bytes(fs_info, generic_ref);
1997
1998         return ret;
1999 }
2000
2001 /*
2002  * __btrfs_inc_extent_ref - insert backreference for a given extent
2003  *
2004  * @trans:          Handle of transaction
2005  *
2006  * @node:           The delayed ref node used to get the bytenr/length for
2007  *                  extent whose references are incremented.
2008  *
2009  * @parent:         If this is a shared extent (BTRFS_SHARED_DATA_REF_KEY/
2010  *                  BTRFS_SHARED_BLOCK_REF_KEY) then it holds the logical
2011  *                  bytenr of the parent block. Since new extents are always
2012  *                  created with indirect references, this will only be the case
2013  *                  when relocating a shared extent. In that case, root_objectid
2014  *                  will be BTRFS_TREE_RELOC_OBJECTID. Otheriwse, parent must
2015  *                  be 0
2016  *
2017  * @root_objectid:  The id of the root where this modification has originated,
2018  *                  this can be either one of the well-known metadata trees or
2019  *                  the subvolume id which references this extent.
2020  *
2021  * @owner:          For data extents it is the inode number of the owning file.
2022  *                  For metadata extents this parameter holds the level in the
2023  *                  tree of the extent.
2024  *
2025  * @offset:         For metadata extents the offset is ignored and is currently
2026  *                  always passed as 0. For data extents it is the fileoffset
2027  *                  this extent belongs to.
2028  *
2029  * @refs_to_add     Number of references to add
2030  *
2031  * @extent_op       Pointer to a structure, holding information necessary when
2032  *                  updating a tree block's flags
2033  *
2034  */
2035 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2036                                   struct btrfs_delayed_ref_node *node,
2037                                   u64 parent, u64 root_objectid,
2038                                   u64 owner, u64 offset, int refs_to_add,
2039                                   struct btrfs_delayed_extent_op *extent_op)
2040 {
2041         struct btrfs_path *path;
2042         struct extent_buffer *leaf;
2043         struct btrfs_extent_item *item;
2044         struct btrfs_key key;
2045         u64 bytenr = node->bytenr;
2046         u64 num_bytes = node->num_bytes;
2047         u64 refs;
2048         int ret;
2049
2050         path = btrfs_alloc_path();
2051         if (!path)
2052                 return -ENOMEM;
2053
2054         path->reada = READA_FORWARD;
2055         path->leave_spinning = 1;
2056         /* this will setup the path even if it fails to insert the back ref */
2057         ret = insert_inline_extent_backref(trans, path, bytenr, num_bytes,
2058                                            parent, root_objectid, owner,
2059                                            offset, refs_to_add, extent_op);
2060         if ((ret < 0 && ret != -EAGAIN) || !ret)
2061                 goto out;
2062
2063         /*
2064          * Ok we had -EAGAIN which means we didn't have space to insert and
2065          * inline extent ref, so just update the reference count and add a
2066          * normal backref.
2067          */
2068         leaf = path->nodes[0];
2069         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2070         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2071         refs = btrfs_extent_refs(leaf, item);
2072         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2073         if (extent_op)
2074                 __run_delayed_extent_op(extent_op, leaf, item);
2075
2076         btrfs_mark_buffer_dirty(leaf);
2077         btrfs_release_path(path);
2078
2079         path->reada = READA_FORWARD;
2080         path->leave_spinning = 1;
2081         /* now insert the actual backref */
2082         ret = insert_extent_backref(trans, path, bytenr, parent, root_objectid,
2083                                     owner, offset, refs_to_add);
2084         if (ret)
2085                 btrfs_abort_transaction(trans, ret);
2086 out:
2087         btrfs_free_path(path);
2088         return ret;
2089 }
2090
2091 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2092                                 struct btrfs_delayed_ref_node *node,
2093                                 struct btrfs_delayed_extent_op *extent_op,
2094                                 int insert_reserved)
2095 {
2096         int ret = 0;
2097         struct btrfs_delayed_data_ref *ref;
2098         struct btrfs_key ins;
2099         u64 parent = 0;
2100         u64 ref_root = 0;
2101         u64 flags = 0;
2102
2103         ins.objectid = node->bytenr;
2104         ins.offset = node->num_bytes;
2105         ins.type = BTRFS_EXTENT_ITEM_KEY;
2106
2107         ref = btrfs_delayed_node_to_data_ref(node);
2108         trace_run_delayed_data_ref(trans->fs_info, node, ref, node->action);
2109
2110         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2111                 parent = ref->parent;
2112         ref_root = ref->root;
2113
2114         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2115                 if (extent_op)
2116                         flags |= extent_op->flags_to_set;
2117                 ret = alloc_reserved_file_extent(trans, parent, ref_root,
2118                                                  flags, ref->objectid,
2119                                                  ref->offset, &ins,
2120                                                  node->ref_mod);
2121         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2122                 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2123                                              ref->objectid, ref->offset,
2124                                              node->ref_mod, extent_op);
2125         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2126                 ret = __btrfs_free_extent(trans, node, parent,
2127                                           ref_root, ref->objectid,
2128                                           ref->offset, node->ref_mod,
2129                                           extent_op);
2130         } else {
2131                 BUG();
2132         }
2133         return ret;
2134 }
2135
2136 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2137                                     struct extent_buffer *leaf,
2138                                     struct btrfs_extent_item *ei)
2139 {
2140         u64 flags = btrfs_extent_flags(leaf, ei);
2141         if (extent_op->update_flags) {
2142                 flags |= extent_op->flags_to_set;
2143                 btrfs_set_extent_flags(leaf, ei, flags);
2144         }
2145
2146         if (extent_op->update_key) {
2147                 struct btrfs_tree_block_info *bi;
2148                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2149                 bi = (struct btrfs_tree_block_info *)(ei + 1);
2150                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2151         }
2152 }
2153
2154 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2155                                  struct btrfs_delayed_ref_head *head,
2156                                  struct btrfs_delayed_extent_op *extent_op)
2157 {
2158         struct btrfs_fs_info *fs_info = trans->fs_info;
2159         struct btrfs_key key;
2160         struct btrfs_path *path;
2161         struct btrfs_extent_item *ei;
2162         struct extent_buffer *leaf;
2163         u32 item_size;
2164         int ret;
2165         int err = 0;
2166         int metadata = !extent_op->is_data;
2167
2168         if (trans->aborted)
2169                 return 0;
2170
2171         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2172                 metadata = 0;
2173
2174         path = btrfs_alloc_path();
2175         if (!path)
2176                 return -ENOMEM;
2177
2178         key.objectid = head->bytenr;
2179
2180         if (metadata) {
2181                 key.type = BTRFS_METADATA_ITEM_KEY;
2182                 key.offset = extent_op->level;
2183         } else {
2184                 key.type = BTRFS_EXTENT_ITEM_KEY;
2185                 key.offset = head->num_bytes;
2186         }
2187
2188 again:
2189         path->reada = READA_FORWARD;
2190         path->leave_spinning = 1;
2191         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2192         if (ret < 0) {
2193                 err = ret;
2194                 goto out;
2195         }
2196         if (ret > 0) {
2197                 if (metadata) {
2198                         if (path->slots[0] > 0) {
2199                                 path->slots[0]--;
2200                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
2201                                                       path->slots[0]);
2202                                 if (key.objectid == head->bytenr &&
2203                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
2204                                     key.offset == head->num_bytes)
2205                                         ret = 0;
2206                         }
2207                         if (ret > 0) {
2208                                 btrfs_release_path(path);
2209                                 metadata = 0;
2210
2211                                 key.objectid = head->bytenr;
2212                                 key.offset = head->num_bytes;
2213                                 key.type = BTRFS_EXTENT_ITEM_KEY;
2214                                 goto again;
2215                         }
2216                 } else {
2217                         err = -EIO;
2218                         goto out;
2219                 }
2220         }
2221
2222         leaf = path->nodes[0];
2223         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2224
2225         if (unlikely(item_size < sizeof(*ei))) {
2226                 err = -EINVAL;
2227                 btrfs_print_v0_err(fs_info);
2228                 btrfs_abort_transaction(trans, err);
2229                 goto out;
2230         }
2231
2232         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2233         __run_delayed_extent_op(extent_op, leaf, ei);
2234
2235         btrfs_mark_buffer_dirty(leaf);
2236 out:
2237         btrfs_free_path(path);
2238         return err;
2239 }
2240
2241 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2242                                 struct btrfs_delayed_ref_node *node,
2243                                 struct btrfs_delayed_extent_op *extent_op,
2244                                 int insert_reserved)
2245 {
2246         int ret = 0;
2247         struct btrfs_delayed_tree_ref *ref;
2248         u64 parent = 0;
2249         u64 ref_root = 0;
2250
2251         ref = btrfs_delayed_node_to_tree_ref(node);
2252         trace_run_delayed_tree_ref(trans->fs_info, node, ref, node->action);
2253
2254         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2255                 parent = ref->parent;
2256         ref_root = ref->root;
2257
2258         if (node->ref_mod != 1) {
2259                 btrfs_err(trans->fs_info,
2260         "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2261                           node->bytenr, node->ref_mod, node->action, ref_root,
2262                           parent);
2263                 return -EIO;
2264         }
2265         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2266                 BUG_ON(!extent_op || !extent_op->update_flags);
2267                 ret = alloc_reserved_tree_block(trans, node, extent_op);
2268         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2269                 ret = __btrfs_inc_extent_ref(trans, node, parent, ref_root,
2270                                              ref->level, 0, 1, extent_op);
2271         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2272                 ret = __btrfs_free_extent(trans, node, parent, ref_root,
2273                                           ref->level, 0, 1, extent_op);
2274         } else {
2275                 BUG();
2276         }
2277         return ret;
2278 }
2279
2280 /* helper function to actually process a single delayed ref entry */
2281 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2282                                struct btrfs_delayed_ref_node *node,
2283                                struct btrfs_delayed_extent_op *extent_op,
2284                                int insert_reserved)
2285 {
2286         int ret = 0;
2287
2288         if (trans->aborted) {
2289                 if (insert_reserved)
2290                         btrfs_pin_extent(trans->fs_info, node->bytenr,
2291                                          node->num_bytes, 1);
2292                 return 0;
2293         }
2294
2295         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2296             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2297                 ret = run_delayed_tree_ref(trans, node, extent_op,
2298                                            insert_reserved);
2299         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2300                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2301                 ret = run_delayed_data_ref(trans, node, extent_op,
2302                                            insert_reserved);
2303         else
2304                 BUG();
2305         if (ret && insert_reserved)
2306                 btrfs_pin_extent(trans->fs_info, node->bytenr,
2307                                  node->num_bytes, 1);
2308         return ret;
2309 }
2310
2311 static inline struct btrfs_delayed_ref_node *
2312 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2313 {
2314         struct btrfs_delayed_ref_node *ref;
2315
2316         if (RB_EMPTY_ROOT(&head->ref_tree.rb_root))
2317                 return NULL;
2318
2319         /*
2320          * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2321          * This is to prevent a ref count from going down to zero, which deletes
2322          * the extent item from the extent tree, when there still are references
2323          * to add, which would fail because they would not find the extent item.
2324          */
2325         if (!list_empty(&head->ref_add_list))
2326                 return list_first_entry(&head->ref_add_list,
2327                                 struct btrfs_delayed_ref_node, add_list);
2328
2329         ref = rb_entry(rb_first_cached(&head->ref_tree),
2330                        struct btrfs_delayed_ref_node, ref_node);
2331         ASSERT(list_empty(&ref->add_list));
2332         return ref;
2333 }
2334
2335 static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
2336                                       struct btrfs_delayed_ref_head *head)
2337 {
2338         spin_lock(&delayed_refs->lock);
2339         head->processing = 0;
2340         delayed_refs->num_heads_ready++;
2341         spin_unlock(&delayed_refs->lock);
2342         btrfs_delayed_ref_unlock(head);
2343 }
2344
2345 static struct btrfs_delayed_extent_op *cleanup_extent_op(
2346                                 struct btrfs_delayed_ref_head *head)
2347 {
2348         struct btrfs_delayed_extent_op *extent_op = head->extent_op;
2349
2350         if (!extent_op)
2351                 return NULL;
2352
2353         if (head->must_insert_reserved) {
2354                 head->extent_op = NULL;
2355                 btrfs_free_delayed_extent_op(extent_op);
2356                 return NULL;
2357         }
2358         return extent_op;
2359 }
2360
2361 static int run_and_cleanup_extent_op(struct btrfs_trans_handle *trans,
2362                                      struct btrfs_delayed_ref_head *head)
2363 {
2364         struct btrfs_delayed_extent_op *extent_op;
2365         int ret;
2366
2367         extent_op = cleanup_extent_op(head);
2368         if (!extent_op)
2369                 return 0;
2370         head->extent_op = NULL;
2371         spin_unlock(&head->lock);
2372         ret = run_delayed_extent_op(trans, head, extent_op);
2373         btrfs_free_delayed_extent_op(extent_op);
2374         return ret ? ret : 1;
2375 }
2376
2377 void btrfs_cleanup_ref_head_accounting(struct btrfs_fs_info *fs_info,
2378                                   struct btrfs_delayed_ref_root *delayed_refs,
2379                                   struct btrfs_delayed_ref_head *head)
2380 {
2381         int nr_items = 1;       /* Dropping this ref head update. */
2382
2383         if (head->total_ref_mod < 0) {
2384                 struct btrfs_space_info *space_info;
2385                 u64 flags;
2386
2387                 if (head->is_data)
2388                         flags = BTRFS_BLOCK_GROUP_DATA;
2389                 else if (head->is_system)
2390                         flags = BTRFS_BLOCK_GROUP_SYSTEM;
2391                 else
2392                         flags = BTRFS_BLOCK_GROUP_METADATA;
2393                 space_info = btrfs_find_space_info(fs_info, flags);
2394                 ASSERT(space_info);
2395                 percpu_counter_add_batch(&space_info->total_bytes_pinned,
2396                                    -head->num_bytes,
2397                                    BTRFS_TOTAL_BYTES_PINNED_BATCH);
2398
2399                 /*
2400                  * We had csum deletions accounted for in our delayed refs rsv,
2401                  * we need to drop the csum leaves for this update from our
2402                  * delayed_refs_rsv.
2403                  */
2404                 if (head->is_data) {
2405                         spin_lock(&delayed_refs->lock);
2406                         delayed_refs->pending_csums -= head->num_bytes;
2407                         spin_unlock(&delayed_refs->lock);
2408                         nr_items += btrfs_csum_bytes_to_leaves(fs_info,
2409                                 head->num_bytes);
2410                 }
2411         }
2412
2413         btrfs_delayed_refs_rsv_release(fs_info, nr_items);
2414 }
2415
2416 static int cleanup_ref_head(struct btrfs_trans_handle *trans,
2417                             struct btrfs_delayed_ref_head *head)
2418 {
2419
2420         struct btrfs_fs_info *fs_info = trans->fs_info;
2421         struct btrfs_delayed_ref_root *delayed_refs;
2422         int ret;
2423
2424         delayed_refs = &trans->transaction->delayed_refs;
2425
2426         ret = run_and_cleanup_extent_op(trans, head);
2427         if (ret < 0) {
2428                 unselect_delayed_ref_head(delayed_refs, head);
2429                 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2430                 return ret;
2431         } else if (ret) {
2432                 return ret;
2433         }
2434
2435         /*
2436          * Need to drop our head ref lock and re-acquire the delayed ref lock
2437          * and then re-check to make sure nobody got added.
2438          */
2439         spin_unlock(&head->lock);
2440         spin_lock(&delayed_refs->lock);
2441         spin_lock(&head->lock);
2442         if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root) || head->extent_op) {
2443                 spin_unlock(&head->lock);
2444                 spin_unlock(&delayed_refs->lock);
2445                 return 1;
2446         }
2447         btrfs_delete_ref_head(delayed_refs, head);
2448         spin_unlock(&head->lock);
2449         spin_unlock(&delayed_refs->lock);
2450
2451         if (head->must_insert_reserved) {
2452                 btrfs_pin_extent(fs_info, head->bytenr,
2453                                  head->num_bytes, 1);
2454                 if (head->is_data) {
2455                         ret = btrfs_del_csums(trans, fs_info, head->bytenr,
2456                                               head->num_bytes);
2457                 }
2458         }
2459
2460         btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
2461
2462         trace_run_delayed_ref_head(fs_info, head, 0);
2463         btrfs_delayed_ref_unlock(head);
2464         btrfs_put_delayed_ref_head(head);
2465         return 0;
2466 }
2467
2468 static struct btrfs_delayed_ref_head *btrfs_obtain_ref_head(
2469                                         struct btrfs_trans_handle *trans)
2470 {
2471         struct btrfs_delayed_ref_root *delayed_refs =
2472                 &trans->transaction->delayed_refs;
2473         struct btrfs_delayed_ref_head *head = NULL;
2474         int ret;
2475
2476         spin_lock(&delayed_refs->lock);
2477         head = btrfs_select_ref_head(delayed_refs);
2478         if (!head) {
2479                 spin_unlock(&delayed_refs->lock);
2480                 return head;
2481         }
2482
2483         /*
2484          * Grab the lock that says we are going to process all the refs for
2485          * this head
2486          */
2487         ret = btrfs_delayed_ref_lock(delayed_refs, head);
2488         spin_unlock(&delayed_refs->lock);
2489
2490         /*
2491          * We may have dropped the spin lock to get the head mutex lock, and
2492          * that might have given someone else time to free the head.  If that's
2493          * true, it has been removed from our list and we can move on.
2494          */
2495         if (ret == -EAGAIN)
2496                 head = ERR_PTR(-EAGAIN);
2497
2498         return head;
2499 }
2500
2501 static int btrfs_run_delayed_refs_for_head(struct btrfs_trans_handle *trans,
2502                                     struct btrfs_delayed_ref_head *locked_ref,
2503                                     unsigned long *run_refs)
2504 {
2505         struct btrfs_fs_info *fs_info = trans->fs_info;
2506         struct btrfs_delayed_ref_root *delayed_refs;
2507         struct btrfs_delayed_extent_op *extent_op;
2508         struct btrfs_delayed_ref_node *ref;
2509         int must_insert_reserved = 0;
2510         int ret;
2511
2512         delayed_refs = &trans->transaction->delayed_refs;
2513
2514         lockdep_assert_held(&locked_ref->mutex);
2515         lockdep_assert_held(&locked_ref->lock);
2516
2517         while ((ref = select_delayed_ref(locked_ref))) {
2518                 if (ref->seq &&
2519                     btrfs_check_delayed_seq(fs_info, ref->seq)) {
2520                         spin_unlock(&locked_ref->lock);
2521                         unselect_delayed_ref_head(delayed_refs, locked_ref);
2522                         return -EAGAIN;
2523                 }
2524
2525                 (*run_refs)++;
2526                 ref->in_tree = 0;
2527                 rb_erase_cached(&ref->ref_node, &locked_ref->ref_tree);
2528                 RB_CLEAR_NODE(&ref->ref_node);
2529                 if (!list_empty(&ref->add_list))
2530                         list_del(&ref->add_list);
2531                 /*
2532                  * When we play the delayed ref, also correct the ref_mod on
2533                  * head
2534                  */
2535                 switch (ref->action) {
2536                 case BTRFS_ADD_DELAYED_REF:
2537                 case BTRFS_ADD_DELAYED_EXTENT:
2538                         locked_ref->ref_mod -= ref->ref_mod;
2539                         break;
2540                 case BTRFS_DROP_DELAYED_REF:
2541                         locked_ref->ref_mod += ref->ref_mod;
2542                         break;
2543                 default:
2544                         WARN_ON(1);
2545                 }
2546                 atomic_dec(&delayed_refs->num_entries);
2547
2548                 /*
2549                  * Record the must_insert_reserved flag before we drop the
2550                  * spin lock.
2551                  */
2552                 must_insert_reserved = locked_ref->must_insert_reserved;
2553                 locked_ref->must_insert_reserved = 0;
2554
2555                 extent_op = locked_ref->extent_op;
2556                 locked_ref->extent_op = NULL;
2557                 spin_unlock(&locked_ref->lock);
2558
2559                 ret = run_one_delayed_ref(trans, ref, extent_op,
2560                                           must_insert_reserved);
2561
2562                 btrfs_free_delayed_extent_op(extent_op);
2563                 if (ret) {
2564                         unselect_delayed_ref_head(delayed_refs, locked_ref);
2565                         btrfs_put_delayed_ref(ref);
2566                         btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2567                                     ret);
2568                         return ret;
2569                 }
2570
2571                 btrfs_put_delayed_ref(ref);
2572                 cond_resched();
2573
2574                 spin_lock(&locked_ref->lock);
2575                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2576         }
2577
2578         return 0;
2579 }
2580
2581 /*
2582  * Returns 0 on success or if called with an already aborted transaction.
2583  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2584  */
2585 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2586                                              unsigned long nr)
2587 {
2588         struct btrfs_fs_info *fs_info = trans->fs_info;
2589         struct btrfs_delayed_ref_root *delayed_refs;
2590         struct btrfs_delayed_ref_head *locked_ref = NULL;
2591         ktime_t start = ktime_get();
2592         int ret;
2593         unsigned long count = 0;
2594         unsigned long actual_count = 0;
2595
2596         delayed_refs = &trans->transaction->delayed_refs;
2597         do {
2598                 if (!locked_ref) {
2599                         locked_ref = btrfs_obtain_ref_head(trans);
2600                         if (IS_ERR_OR_NULL(locked_ref)) {
2601                                 if (PTR_ERR(locked_ref) == -EAGAIN) {
2602                                         continue;
2603                                 } else {
2604                                         break;
2605                                 }
2606                         }
2607                         count++;
2608                 }
2609                 /*
2610                  * We need to try and merge add/drops of the same ref since we
2611                  * can run into issues with relocate dropping the implicit ref
2612                  * and then it being added back again before the drop can
2613                  * finish.  If we merged anything we need to re-loop so we can
2614                  * get a good ref.
2615                  * Or we can get node references of the same type that weren't
2616                  * merged when created due to bumps in the tree mod seq, and
2617                  * we need to merge them to prevent adding an inline extent
2618                  * backref before dropping it (triggering a BUG_ON at
2619                  * insert_inline_extent_backref()).
2620                  */
2621                 spin_lock(&locked_ref->lock);
2622                 btrfs_merge_delayed_refs(trans, delayed_refs, locked_ref);
2623
2624                 ret = btrfs_run_delayed_refs_for_head(trans, locked_ref,
2625                                                       &actual_count);
2626                 if (ret < 0 && ret != -EAGAIN) {
2627                         /*
2628                          * Error, btrfs_run_delayed_refs_for_head already
2629                          * unlocked everything so just bail out
2630                          */
2631                         return ret;
2632                 } else if (!ret) {
2633                         /*
2634                          * Success, perform the usual cleanup of a processed
2635                          * head
2636                          */
2637                         ret = cleanup_ref_head(trans, locked_ref);
2638                         if (ret > 0 ) {
2639                                 /* We dropped our lock, we need to loop. */
2640                                 ret = 0;
2641                                 continue;
2642                         } else if (ret) {
2643                                 return ret;
2644                         }
2645                 }
2646
2647                 /*
2648                  * Either success case or btrfs_run_delayed_refs_for_head
2649                  * returned -EAGAIN, meaning we need to select another head
2650                  */
2651
2652                 locked_ref = NULL;
2653                 cond_resched();
2654         } while ((nr != -1 && count < nr) || locked_ref);
2655
2656         /*
2657          * We don't want to include ref heads since we can have empty ref heads
2658          * and those will drastically skew our runtime down since we just do
2659          * accounting, no actual extent tree updates.
2660          */
2661         if (actual_count > 0) {
2662                 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2663                 u64 avg;
2664
2665                 /*
2666                  * We weigh the current average higher than our current runtime
2667                  * to avoid large swings in the average.
2668                  */
2669                 spin_lock(&delayed_refs->lock);
2670                 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2671                 fs_info->avg_delayed_ref_runtime = avg >> 2;    /* div by 4 */
2672                 spin_unlock(&delayed_refs->lock);
2673         }
2674         return 0;
2675 }
2676
2677 #ifdef SCRAMBLE_DELAYED_REFS
2678 /*
2679  * Normally delayed refs get processed in ascending bytenr order. This
2680  * correlates in most cases to the order added. To expose dependencies on this
2681  * order, we start to process the tree in the middle instead of the beginning
2682  */
2683 static u64 find_middle(struct rb_root *root)
2684 {
2685         struct rb_node *n = root->rb_node;
2686         struct btrfs_delayed_ref_node *entry;
2687         int alt = 1;
2688         u64 middle;
2689         u64 first = 0, last = 0;
2690
2691         n = rb_first(root);
2692         if (n) {
2693                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2694                 first = entry->bytenr;
2695         }
2696         n = rb_last(root);
2697         if (n) {
2698                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2699                 last = entry->bytenr;
2700         }
2701         n = root->rb_node;
2702
2703         while (n) {
2704                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2705                 WARN_ON(!entry->in_tree);
2706
2707                 middle = entry->bytenr;
2708
2709                 if (alt)
2710                         n = n->rb_left;
2711                 else
2712                         n = n->rb_right;
2713
2714                 alt = 1 - alt;
2715         }
2716         return middle;
2717 }
2718 #endif
2719
2720 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2721 {
2722         u64 num_bytes;
2723
2724         num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2725                              sizeof(struct btrfs_extent_inline_ref));
2726         if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2727                 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2728
2729         /*
2730          * We don't ever fill up leaves all the way so multiply by 2 just to be
2731          * closer to what we're really going to want to use.
2732          */
2733         return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2734 }
2735
2736 /*
2737  * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2738  * would require to store the csums for that many bytes.
2739  */
2740 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2741 {
2742         u64 csum_size;
2743         u64 num_csums_per_leaf;
2744         u64 num_csums;
2745
2746         csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2747         num_csums_per_leaf = div64_u64(csum_size,
2748                         (u64)btrfs_super_csum_size(fs_info->super_copy));
2749         num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2750         num_csums += num_csums_per_leaf - 1;
2751         num_csums = div64_u64(num_csums, num_csums_per_leaf);
2752         return num_csums;
2753 }
2754
2755 bool btrfs_check_space_for_delayed_refs(struct btrfs_fs_info *fs_info)
2756 {
2757         struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
2758         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
2759         bool ret = false;
2760         u64 reserved;
2761
2762         spin_lock(&global_rsv->lock);
2763         reserved = global_rsv->reserved;
2764         spin_unlock(&global_rsv->lock);
2765
2766         /*
2767          * Since the global reserve is just kind of magic we don't really want
2768          * to rely on it to save our bacon, so if our size is more than the
2769          * delayed_refs_rsv and the global rsv then it's time to think about
2770          * bailing.
2771          */
2772         spin_lock(&delayed_refs_rsv->lock);
2773         reserved += delayed_refs_rsv->reserved;
2774         if (delayed_refs_rsv->size >= reserved)
2775                 ret = true;
2776         spin_unlock(&delayed_refs_rsv->lock);
2777         return ret;
2778 }
2779
2780 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans)
2781 {
2782         u64 num_entries =
2783                 atomic_read(&trans->transaction->delayed_refs.num_entries);
2784         u64 avg_runtime;
2785         u64 val;
2786
2787         smp_mb();
2788         avg_runtime = trans->fs_info->avg_delayed_ref_runtime;
2789         val = num_entries * avg_runtime;
2790         if (val >= NSEC_PER_SEC)
2791                 return 1;
2792         if (val >= NSEC_PER_SEC / 2)
2793                 return 2;
2794
2795         return btrfs_check_space_for_delayed_refs(trans->fs_info);
2796 }
2797
2798 /*
2799  * this starts processing the delayed reference count updates and
2800  * extent insertions we have queued up so far.  count can be
2801  * 0, which means to process everything in the tree at the start
2802  * of the run (but not newly added entries), or it can be some target
2803  * number you'd like to process.
2804  *
2805  * Returns 0 on success or if called with an aborted transaction
2806  * Returns <0 on error and aborts the transaction
2807  */
2808 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2809                            unsigned long count)
2810 {
2811         struct btrfs_fs_info *fs_info = trans->fs_info;
2812         struct rb_node *node;
2813         struct btrfs_delayed_ref_root *delayed_refs;
2814         struct btrfs_delayed_ref_head *head;
2815         int ret;
2816         int run_all = count == (unsigned long)-1;
2817
2818         /* We'll clean this up in btrfs_cleanup_transaction */
2819         if (trans->aborted)
2820                 return 0;
2821
2822         if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2823                 return 0;
2824
2825         delayed_refs = &trans->transaction->delayed_refs;
2826         if (count == 0)
2827                 count = atomic_read(&delayed_refs->num_entries) * 2;
2828
2829 again:
2830 #ifdef SCRAMBLE_DELAYED_REFS
2831         delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2832 #endif
2833         ret = __btrfs_run_delayed_refs(trans, count);
2834         if (ret < 0) {
2835                 btrfs_abort_transaction(trans, ret);
2836                 return ret;
2837         }
2838
2839         if (run_all) {
2840                 btrfs_create_pending_block_groups(trans);
2841
2842                 spin_lock(&delayed_refs->lock);
2843                 node = rb_first_cached(&delayed_refs->href_root);
2844                 if (!node) {
2845                         spin_unlock(&delayed_refs->lock);
2846                         goto out;
2847                 }
2848                 head = rb_entry(node, struct btrfs_delayed_ref_head,
2849                                 href_node);
2850                 refcount_inc(&head->refs);
2851                 spin_unlock(&delayed_refs->lock);
2852
2853                 /* Mutex was contended, block until it's released and retry. */
2854                 mutex_lock(&head->mutex);
2855                 mutex_unlock(&head->mutex);
2856
2857                 btrfs_put_delayed_ref_head(head);
2858                 cond_resched();
2859                 goto again;
2860         }
2861 out:
2862         return 0;
2863 }
2864
2865 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2866                                 u64 bytenr, u64 num_bytes, u64 flags,
2867                                 int level, int is_data)
2868 {
2869         struct btrfs_delayed_extent_op *extent_op;
2870         int ret;
2871
2872         extent_op = btrfs_alloc_delayed_extent_op();
2873         if (!extent_op)
2874                 return -ENOMEM;
2875
2876         extent_op->flags_to_set = flags;
2877         extent_op->update_flags = true;
2878         extent_op->update_key = false;
2879         extent_op->is_data = is_data ? true : false;
2880         extent_op->level = level;
2881
2882         ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2883         if (ret)
2884                 btrfs_free_delayed_extent_op(extent_op);
2885         return ret;
2886 }
2887
2888 static noinline int check_delayed_ref(struct btrfs_root *root,
2889                                       struct btrfs_path *path,
2890                                       u64 objectid, u64 offset, u64 bytenr)
2891 {
2892         struct btrfs_delayed_ref_head *head;
2893         struct btrfs_delayed_ref_node *ref;
2894         struct btrfs_delayed_data_ref *data_ref;
2895         struct btrfs_delayed_ref_root *delayed_refs;
2896         struct btrfs_transaction *cur_trans;
2897         struct rb_node *node;
2898         int ret = 0;
2899
2900         spin_lock(&root->fs_info->trans_lock);
2901         cur_trans = root->fs_info->running_transaction;
2902         if (cur_trans)
2903                 refcount_inc(&cur_trans->use_count);
2904         spin_unlock(&root->fs_info->trans_lock);
2905         if (!cur_trans)
2906                 return 0;
2907
2908         delayed_refs = &cur_trans->delayed_refs;
2909         spin_lock(&delayed_refs->lock);
2910         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
2911         if (!head) {
2912                 spin_unlock(&delayed_refs->lock);
2913                 btrfs_put_transaction(cur_trans);
2914                 return 0;
2915         }
2916
2917         if (!mutex_trylock(&head->mutex)) {
2918                 refcount_inc(&head->refs);
2919                 spin_unlock(&delayed_refs->lock);
2920
2921                 btrfs_release_path(path);
2922
2923                 /*
2924                  * Mutex was contended, block until it's released and let
2925                  * caller try again
2926                  */
2927                 mutex_lock(&head->mutex);
2928                 mutex_unlock(&head->mutex);
2929                 btrfs_put_delayed_ref_head(head);
2930                 btrfs_put_transaction(cur_trans);
2931                 return -EAGAIN;
2932         }
2933         spin_unlock(&delayed_refs->lock);
2934
2935         spin_lock(&head->lock);
2936         /*
2937          * XXX: We should replace this with a proper search function in the
2938          * future.
2939          */
2940         for (node = rb_first_cached(&head->ref_tree); node;
2941              node = rb_next(node)) {
2942                 ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
2943                 /* If it's a shared ref we know a cross reference exists */
2944                 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
2945                         ret = 1;
2946                         break;
2947                 }
2948
2949                 data_ref = btrfs_delayed_node_to_data_ref(ref);
2950
2951                 /*
2952                  * If our ref doesn't match the one we're currently looking at
2953                  * then we have a cross reference.
2954                  */
2955                 if (data_ref->root != root->root_key.objectid ||
2956                     data_ref->objectid != objectid ||
2957                     data_ref->offset != offset) {
2958                         ret = 1;
2959                         break;
2960                 }
2961         }
2962         spin_unlock(&head->lock);
2963         mutex_unlock(&head->mutex);
2964         btrfs_put_transaction(cur_trans);
2965         return ret;
2966 }
2967
2968 static noinline int check_committed_ref(struct btrfs_root *root,
2969                                         struct btrfs_path *path,
2970                                         u64 objectid, u64 offset, u64 bytenr)
2971 {
2972         struct btrfs_fs_info *fs_info = root->fs_info;
2973         struct btrfs_root *extent_root = fs_info->extent_root;
2974         struct extent_buffer *leaf;
2975         struct btrfs_extent_data_ref *ref;
2976         struct btrfs_extent_inline_ref *iref;
2977         struct btrfs_extent_item *ei;
2978         struct btrfs_key key;
2979         u32 item_size;
2980         int type;
2981         int ret;
2982
2983         key.objectid = bytenr;
2984         key.offset = (u64)-1;
2985         key.type = BTRFS_EXTENT_ITEM_KEY;
2986
2987         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2988         if (ret < 0)
2989                 goto out;
2990         BUG_ON(ret == 0); /* Corruption */
2991
2992         ret = -ENOENT;
2993         if (path->slots[0] == 0)
2994                 goto out;
2995
2996         path->slots[0]--;
2997         leaf = path->nodes[0];
2998         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2999
3000         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3001                 goto out;
3002
3003         ret = 1;
3004         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3005         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3006
3007         if (item_size != sizeof(*ei) +
3008             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3009                 goto out;
3010
3011         if (btrfs_extent_generation(leaf, ei) <=
3012             btrfs_root_last_snapshot(&root->root_item))
3013                 goto out;
3014
3015         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3016
3017         type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
3018         if (type != BTRFS_EXTENT_DATA_REF_KEY)
3019                 goto out;
3020
3021         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3022         if (btrfs_extent_refs(leaf, ei) !=
3023             btrfs_extent_data_ref_count(leaf, ref) ||
3024             btrfs_extent_data_ref_root(leaf, ref) !=
3025             root->root_key.objectid ||
3026             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3027             btrfs_extent_data_ref_offset(leaf, ref) != offset)
3028                 goto out;
3029
3030         ret = 0;
3031 out:
3032         return ret;
3033 }
3034
3035 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3036                           u64 bytenr)
3037 {
3038         struct btrfs_path *path;
3039         int ret;
3040
3041         path = btrfs_alloc_path();
3042         if (!path)
3043                 return -ENOMEM;
3044
3045         do {
3046                 ret = check_committed_ref(root, path, objectid,
3047                                           offset, bytenr);
3048                 if (ret && ret != -ENOENT)
3049                         goto out;
3050
3051                 ret = check_delayed_ref(root, path, objectid, offset, bytenr);
3052         } while (ret == -EAGAIN);
3053
3054 out:
3055         btrfs_free_path(path);
3056         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3057                 WARN_ON(ret > 0);
3058         return ret;
3059 }
3060
3061 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3062                            struct btrfs_root *root,
3063                            struct extent_buffer *buf,
3064                            int full_backref, int inc)
3065 {
3066         struct btrfs_fs_info *fs_info = root->fs_info;
3067         u64 bytenr;
3068         u64 num_bytes;
3069         u64 parent;
3070         u64 ref_root;
3071         u32 nritems;
3072         struct btrfs_key key;
3073         struct btrfs_file_extent_item *fi;
3074         struct btrfs_ref generic_ref = { 0 };
3075         bool for_reloc = btrfs_header_flag(buf, BTRFS_HEADER_FLAG_RELOC);
3076         int i;
3077         int action;
3078         int level;
3079         int ret = 0;
3080
3081         if (btrfs_is_testing(fs_info))
3082                 return 0;
3083
3084         ref_root = btrfs_header_owner(buf);
3085         nritems = btrfs_header_nritems(buf);
3086         level = btrfs_header_level(buf);
3087
3088         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3089                 return 0;
3090
3091         if (full_backref)
3092                 parent = buf->start;
3093         else
3094                 parent = 0;
3095         if (inc)
3096                 action = BTRFS_ADD_DELAYED_REF;
3097         else
3098                 action = BTRFS_DROP_DELAYED_REF;
3099
3100         for (i = 0; i < nritems; i++) {
3101                 if (level == 0) {
3102                         btrfs_item_key_to_cpu(buf, &key, i);
3103                         if (key.type != BTRFS_EXTENT_DATA_KEY)
3104                                 continue;
3105                         fi = btrfs_item_ptr(buf, i,
3106                                             struct btrfs_file_extent_item);
3107                         if (btrfs_file_extent_type(buf, fi) ==
3108                             BTRFS_FILE_EXTENT_INLINE)
3109                                 continue;
3110                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3111                         if (bytenr == 0)
3112                                 continue;
3113
3114                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3115                         key.offset -= btrfs_file_extent_offset(buf, fi);
3116                         btrfs_init_generic_ref(&generic_ref, action, bytenr,
3117                                                num_bytes, parent);
3118                         generic_ref.real_root = root->root_key.objectid;
3119                         btrfs_init_data_ref(&generic_ref, ref_root, key.objectid,
3120                                             key.offset);
3121                         generic_ref.skip_qgroup = for_reloc;
3122                         if (inc)
3123                                 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3124                         else
3125                                 ret = btrfs_free_extent(trans, &generic_ref);
3126                         if (ret)
3127                                 goto fail;
3128                 } else {
3129                         bytenr = btrfs_node_blockptr(buf, i);
3130                         num_bytes = fs_info->nodesize;
3131                         btrfs_init_generic_ref(&generic_ref, action, bytenr,
3132                                                num_bytes, parent);
3133                         generic_ref.real_root = root->root_key.objectid;
3134                         btrfs_init_tree_ref(&generic_ref, level - 1, ref_root);
3135                         generic_ref.skip_qgroup = for_reloc;
3136                         if (inc)
3137                                 ret = btrfs_inc_extent_ref(trans, &generic_ref);
3138                         else
3139                                 ret = btrfs_free_extent(trans, &generic_ref);
3140                         if (ret)
3141                                 goto fail;
3142                 }
3143         }
3144         return 0;
3145 fail:
3146         return ret;
3147 }
3148
3149 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3150                   struct extent_buffer *buf, int full_backref)
3151 {
3152         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3153 }
3154
3155 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3156                   struct extent_buffer *buf, int full_backref)
3157 {
3158         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3159 }
3160
3161 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3162                                  struct btrfs_path *path,
3163                                  struct btrfs_block_group_cache *cache)
3164 {
3165         struct btrfs_fs_info *fs_info = trans->fs_info;
3166         int ret;
3167         struct btrfs_root *extent_root = fs_info->extent_root;
3168         unsigned long bi;
3169         struct extent_buffer *leaf;
3170
3171         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3172         if (ret) {
3173                 if (ret > 0)
3174                         ret = -ENOENT;
3175                 goto fail;
3176         }
3177
3178         leaf = path->nodes[0];
3179         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3180         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3181         btrfs_mark_buffer_dirty(leaf);
3182 fail:
3183         btrfs_release_path(path);
3184         return ret;
3185
3186 }
3187
3188 static struct btrfs_block_group_cache *next_block_group(
3189                 struct btrfs_block_group_cache *cache)
3190 {
3191         struct btrfs_fs_info *fs_info = cache->fs_info;
3192         struct rb_node *node;
3193
3194         spin_lock(&fs_info->block_group_cache_lock);
3195
3196         /* If our block group was removed, we need a full search. */
3197         if (RB_EMPTY_NODE(&cache->cache_node)) {
3198                 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3199
3200                 spin_unlock(&fs_info->block_group_cache_lock);
3201                 btrfs_put_block_group(cache);
3202                 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3203         }
3204         node = rb_next(&cache->cache_node);
3205         btrfs_put_block_group(cache);
3206         if (node) {
3207                 cache = rb_entry(node, struct btrfs_block_group_cache,
3208                                  cache_node);
3209                 btrfs_get_block_group(cache);
3210         } else
3211                 cache = NULL;
3212         spin_unlock(&fs_info->block_group_cache_lock);
3213         return cache;
3214 }
3215
3216 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3217                             struct btrfs_trans_handle *trans,
3218                             struct btrfs_path *path)
3219 {
3220         struct btrfs_fs_info *fs_info = block_group->fs_info;
3221         struct btrfs_root *root = fs_info->tree_root;
3222         struct inode *inode = NULL;
3223         struct extent_changeset *data_reserved = NULL;
3224         u64 alloc_hint = 0;
3225         int dcs = BTRFS_DC_ERROR;
3226         u64 num_pages = 0;
3227         int retries = 0;
3228         int ret = 0;
3229
3230         /*
3231          * If this block group is smaller than 100 megs don't bother caching the
3232          * block group.
3233          */
3234         if (block_group->key.offset < (100 * SZ_1M)) {
3235                 spin_lock(&block_group->lock);
3236                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3237                 spin_unlock(&block_group->lock);
3238                 return 0;
3239         }
3240
3241         if (trans->aborted)
3242                 return 0;
3243 again:
3244         inode = lookup_free_space_inode(block_group, path);
3245         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3246                 ret = PTR_ERR(inode);
3247                 btrfs_release_path(path);
3248                 goto out;
3249         }
3250
3251         if (IS_ERR(inode)) {
3252                 BUG_ON(retries);
3253                 retries++;
3254
3255                 if (block_group->ro)
3256                         goto out_free;
3257
3258                 ret = create_free_space_inode(trans, block_group, path);
3259                 if (ret)
3260                         goto out_free;
3261                 goto again;
3262         }
3263
3264         /*
3265          * We want to set the generation to 0, that way if anything goes wrong
3266          * from here on out we know not to trust this cache when we load up next
3267          * time.
3268          */
3269         BTRFS_I(inode)->generation = 0;
3270         ret = btrfs_update_inode(trans, root, inode);
3271         if (ret) {
3272                 /*
3273                  * So theoretically we could recover from this, simply set the
3274                  * super cache generation to 0 so we know to invalidate the
3275                  * cache, but then we'd have to keep track of the block groups
3276                  * that fail this way so we know we _have_ to reset this cache
3277                  * before the next commit or risk reading stale cache.  So to
3278                  * limit our exposure to horrible edge cases lets just abort the
3279                  * transaction, this only happens in really bad situations
3280                  * anyway.
3281                  */
3282                 btrfs_abort_transaction(trans, ret);
3283                 goto out_put;
3284         }
3285         WARN_ON(ret);
3286
3287         /* We've already setup this transaction, go ahead and exit */
3288         if (block_group->cache_generation == trans->transid &&
3289             i_size_read(inode)) {
3290                 dcs = BTRFS_DC_SETUP;
3291                 goto out_put;
3292         }
3293
3294         if (i_size_read(inode) > 0) {
3295                 ret = btrfs_check_trunc_cache_free_space(fs_info,
3296                                         &fs_info->global_block_rsv);
3297                 if (ret)
3298                         goto out_put;
3299
3300                 ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
3301                 if (ret)
3302                         goto out_put;
3303         }
3304
3305         spin_lock(&block_group->lock);
3306         if (block_group->cached != BTRFS_CACHE_FINISHED ||
3307             !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3308                 /*
3309                  * don't bother trying to write stuff out _if_
3310                  * a) we're not cached,
3311                  * b) we're with nospace_cache mount option,
3312                  * c) we're with v2 space_cache (FREE_SPACE_TREE).
3313                  */
3314                 dcs = BTRFS_DC_WRITTEN;
3315                 spin_unlock(&block_group->lock);
3316                 goto out_put;
3317         }
3318         spin_unlock(&block_group->lock);
3319
3320         /*
3321          * We hit an ENOSPC when setting up the cache in this transaction, just
3322          * skip doing the setup, we've already cleared the cache so we're safe.
3323          */
3324         if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3325                 ret = -ENOSPC;
3326                 goto out_put;
3327         }
3328
3329         /*
3330          * Try to preallocate enough space based on how big the block group is.
3331          * Keep in mind this has to include any pinned space which could end up
3332          * taking up quite a bit since it's not folded into the other space
3333          * cache.
3334          */
3335         num_pages = div_u64(block_group->key.offset, SZ_256M);
3336         if (!num_pages)
3337                 num_pages = 1;
3338
3339         num_pages *= 16;
3340         num_pages *= PAGE_SIZE;
3341
3342         ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
3343         if (ret)
3344                 goto out_put;
3345
3346         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3347                                               num_pages, num_pages,
3348                                               &alloc_hint);
3349         /*
3350          * Our cache requires contiguous chunks so that we don't modify a bunch
3351          * of metadata or split extents when writing the cache out, which means
3352          * we can enospc if we are heavily fragmented in addition to just normal
3353          * out of space conditions.  So if we hit this just skip setting up any
3354          * other block groups for this transaction, maybe we'll unpin enough
3355          * space the next time around.
3356          */
3357         if (!ret)
3358                 dcs = BTRFS_DC_SETUP;
3359         else if (ret == -ENOSPC)
3360                 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3361
3362 out_put:
3363         iput(inode);
3364 out_free:
3365         btrfs_release_path(path);
3366 out:
3367         spin_lock(&block_group->lock);
3368         if (!ret && dcs == BTRFS_DC_SETUP)
3369                 block_group->cache_generation = trans->transid;
3370         block_group->disk_cache_state = dcs;
3371         spin_unlock(&block_group->lock);
3372
3373         extent_changeset_free(data_reserved);
3374         return ret;
3375 }
3376
3377 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans)
3378 {
3379         struct btrfs_fs_info *fs_info = trans->fs_info;
3380         struct btrfs_block_group_cache *cache, *tmp;
3381         struct btrfs_transaction *cur_trans = trans->transaction;
3382         struct btrfs_path *path;
3383
3384         if (list_empty(&cur_trans->dirty_bgs) ||
3385             !btrfs_test_opt(fs_info, SPACE_CACHE))
3386                 return 0;
3387
3388         path = btrfs_alloc_path();
3389         if (!path)
3390                 return -ENOMEM;
3391
3392         /* Could add new block groups, use _safe just in case */
3393         list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3394                                  dirty_list) {
3395                 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3396                         cache_save_setup(cache, trans, path);
3397         }
3398
3399         btrfs_free_path(path);
3400         return 0;
3401 }
3402
3403 /*
3404  * transaction commit does final block group cache writeback during a
3405  * critical section where nothing is allowed to change the FS.  This is
3406  * required in order for the cache to actually match the block group,
3407  * but can introduce a lot of latency into the commit.
3408  *
3409  * So, btrfs_start_dirty_block_groups is here to kick off block group
3410  * cache IO.  There's a chance we'll have to redo some of it if the
3411  * block group changes again during the commit, but it greatly reduces
3412  * the commit latency by getting rid of the easy block groups while
3413  * we're still allowing others to join the commit.
3414  */
3415 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans)
3416 {
3417         struct btrfs_fs_info *fs_info = trans->fs_info;
3418         struct btrfs_block_group_cache *cache;
3419         struct btrfs_transaction *cur_trans = trans->transaction;
3420         int ret = 0;
3421         int should_put;
3422         struct btrfs_path *path = NULL;
3423         LIST_HEAD(dirty);
3424         struct list_head *io = &cur_trans->io_bgs;
3425         int num_started = 0;
3426         int loops = 0;
3427
3428         spin_lock(&cur_trans->dirty_bgs_lock);
3429         if (list_empty(&cur_trans->dirty_bgs)) {
3430                 spin_unlock(&cur_trans->dirty_bgs_lock);
3431                 return 0;
3432         }
3433         list_splice_init(&cur_trans->dirty_bgs, &dirty);
3434         spin_unlock(&cur_trans->dirty_bgs_lock);
3435
3436 again:
3437         /*
3438          * make sure all the block groups on our dirty list actually
3439          * exist
3440          */
3441         btrfs_create_pending_block_groups(trans);
3442
3443         if (!path) {
3444                 path = btrfs_alloc_path();
3445                 if (!path)
3446                         return -ENOMEM;
3447         }
3448
3449         /*
3450          * cache_write_mutex is here only to save us from balance or automatic
3451          * removal of empty block groups deleting this block group while we are
3452          * writing out the cache
3453          */
3454         mutex_lock(&trans->transaction->cache_write_mutex);
3455         while (!list_empty(&dirty)) {
3456                 bool drop_reserve = true;
3457
3458                 cache = list_first_entry(&dirty,
3459                                          struct btrfs_block_group_cache,
3460                                          dirty_list);
3461                 /*
3462                  * this can happen if something re-dirties a block
3463                  * group that is already under IO.  Just wait for it to
3464                  * finish and then do it all again
3465                  */
3466                 if (!list_empty(&cache->io_list)) {
3467                         list_del_init(&cache->io_list);
3468                         btrfs_wait_cache_io(trans, cache, path);
3469                         btrfs_put_block_group(cache);
3470                 }
3471
3472
3473                 /*
3474                  * btrfs_wait_cache_io uses the cache->dirty_list to decide
3475                  * if it should update the cache_state.  Don't delete
3476                  * until after we wait.
3477                  *
3478                  * Since we're not running in the commit critical section
3479                  * we need the dirty_bgs_lock to protect from update_block_group
3480                  */
3481                 spin_lock(&cur_trans->dirty_bgs_lock);
3482                 list_del_init(&cache->dirty_list);
3483                 spin_unlock(&cur_trans->dirty_bgs_lock);
3484
3485                 should_put = 1;
3486
3487                 cache_save_setup(cache, trans, path);
3488
3489                 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3490                         cache->io_ctl.inode = NULL;
3491                         ret = btrfs_write_out_cache(trans, cache, path);
3492                         if (ret == 0 && cache->io_ctl.inode) {
3493                                 num_started++;
3494                                 should_put = 0;
3495
3496                                 /*
3497                                  * The cache_write_mutex is protecting the
3498                                  * io_list, also refer to the definition of
3499                                  * btrfs_transaction::io_bgs for more details
3500                                  */
3501                                 list_add_tail(&cache->io_list, io);
3502                         } else {
3503                                 /*
3504                                  * if we failed to write the cache, the
3505                                  * generation will be bad and life goes on
3506                                  */
3507                                 ret = 0;
3508                         }
3509                 }
3510                 if (!ret) {
3511                         ret = write_one_cache_group(trans, path, cache);
3512                         /*
3513                          * Our block group might still be attached to the list
3514                          * of new block groups in the transaction handle of some
3515                          * other task (struct btrfs_trans_handle->new_bgs). This
3516                          * means its block group item isn't yet in the extent
3517                          * tree. If this happens ignore the error, as we will
3518                          * try again later in the critical section of the
3519                          * transaction commit.
3520                          */
3521                         if (ret == -ENOENT) {
3522                                 ret = 0;
3523                                 spin_lock(&cur_trans->dirty_bgs_lock);
3524                                 if (list_empty(&cache->dirty_list)) {
3525                                         list_add_tail(&cache->dirty_list,
3526                                                       &cur_trans->dirty_bgs);
3527                                         btrfs_get_block_group(cache);
3528                                         drop_reserve = false;
3529                                 }
3530                                 spin_unlock(&cur_trans->dirty_bgs_lock);
3531                         } else if (ret) {
3532                                 btrfs_abort_transaction(trans, ret);
3533                         }
3534                 }
3535
3536                 /* if it's not on the io list, we need to put the block group */
3537                 if (should_put)
3538                         btrfs_put_block_group(cache);
3539                 if (drop_reserve)
3540                         btrfs_delayed_refs_rsv_release(fs_info, 1);
3541
3542                 if (ret)
3543                         break;
3544
3545                 /*
3546                  * Avoid blocking other tasks for too long. It might even save
3547                  * us from writing caches for block groups that are going to be
3548                  * removed.
3549                  */
3550                 mutex_unlock(&trans->transaction->cache_write_mutex);
3551                 mutex_lock(&trans->transaction->cache_write_mutex);
3552         }
3553         mutex_unlock(&trans->transaction->cache_write_mutex);
3554
3555         /*
3556          * go through delayed refs for all the stuff we've just kicked off
3557          * and then loop back (just once)
3558          */
3559         ret = btrfs_run_delayed_refs(trans, 0);
3560         if (!ret && loops == 0) {
3561                 loops++;
3562                 spin_lock(&cur_trans->dirty_bgs_lock);
3563                 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3564                 /*
3565                  * dirty_bgs_lock protects us from concurrent block group
3566                  * deletes too (not just cache_write_mutex).
3567                  */
3568                 if (!list_empty(&dirty)) {
3569                         spin_unlock(&cur_trans->dirty_bgs_lock);
3570                         goto again;
3571                 }
3572                 spin_unlock(&cur_trans->dirty_bgs_lock);
3573         } else if (ret < 0) {
3574                 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3575         }
3576
3577         btrfs_free_path(path);
3578         return ret;
3579 }
3580
3581 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans)
3582 {
3583         struct btrfs_fs_info *fs_info = trans->fs_info;
3584         struct btrfs_block_group_cache *cache;
3585         struct btrfs_transaction *cur_trans = trans->transaction;
3586         int ret = 0;
3587         int should_put;
3588         struct btrfs_path *path;
3589         struct list_head *io = &cur_trans->io_bgs;
3590         int num_started = 0;
3591
3592         path = btrfs_alloc_path();
3593         if (!path)
3594                 return -ENOMEM;
3595
3596         /*
3597          * Even though we are in the critical section of the transaction commit,
3598          * we can still have concurrent tasks adding elements to this
3599          * transaction's list of dirty block groups. These tasks correspond to
3600          * endio free space workers started when writeback finishes for a
3601          * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3602          * allocate new block groups as a result of COWing nodes of the root
3603          * tree when updating the free space inode. The writeback for the space
3604          * caches is triggered by an earlier call to
3605          * btrfs_start_dirty_block_groups() and iterations of the following
3606          * loop.
3607          * Also we want to do the cache_save_setup first and then run the
3608          * delayed refs to make sure we have the best chance at doing this all
3609          * in one shot.
3610          */
3611         spin_lock(&cur_trans->dirty_bgs_lock);
3612         while (!list_empty(&cur_trans->dirty_bgs)) {
3613                 cache = list_first_entry(&cur_trans->dirty_bgs,
3614                                          struct btrfs_block_group_cache,
3615                                          dirty_list);
3616
3617                 /*
3618                  * this can happen if cache_save_setup re-dirties a block
3619                  * group that is already under IO.  Just wait for it to
3620                  * finish and then do it all again
3621                  */
3622                 if (!list_empty(&cache->io_list)) {
3623                         spin_unlock(&cur_trans->dirty_bgs_lock);
3624                         list_del_init(&cache->io_list);
3625                         btrfs_wait_cache_io(trans, cache, path);
3626                         btrfs_put_block_group(cache);
3627                         spin_lock(&cur_trans->dirty_bgs_lock);
3628                 }
3629
3630                 /*
3631                  * don't remove from the dirty list until after we've waited
3632                  * on any pending IO
3633                  */
3634                 list_del_init(&cache->dirty_list);
3635                 spin_unlock(&cur_trans->dirty_bgs_lock);
3636                 should_put = 1;
3637
3638                 cache_save_setup(cache, trans, path);
3639
3640                 if (!ret)
3641                         ret = btrfs_run_delayed_refs(trans,
3642                                                      (unsigned long) -1);
3643
3644                 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3645                         cache->io_ctl.inode = NULL;
3646                         ret = btrfs_write_out_cache(trans, cache, path);
3647                         if (ret == 0 && cache->io_ctl.inode) {
3648                                 num_started++;
3649                                 should_put = 0;
3650                                 list_add_tail(&cache->io_list, io);
3651                         } else {
3652                                 /*
3653                                  * if we failed to write the cache, the
3654                                  * generation will be bad and life goes on
3655                                  */
3656                                 ret = 0;
3657                         }
3658                 }
3659                 if (!ret) {
3660                         ret = write_one_cache_group(trans, path, cache);
3661                         /*
3662                          * One of the free space endio workers might have
3663                          * created a new block group while updating a free space
3664                          * cache's inode (at inode.c:btrfs_finish_ordered_io())
3665                          * and hasn't released its transaction handle yet, in
3666                          * which case the new block group is still attached to
3667                          * its transaction handle and its creation has not
3668                          * finished yet (no block group item in the extent tree
3669                          * yet, etc). If this is the case, wait for all free
3670                          * space endio workers to finish and retry. This is a
3671                          * a very rare case so no need for a more efficient and
3672                          * complex approach.
3673                          */
3674                         if (ret == -ENOENT) {
3675                                 wait_event(cur_trans->writer_wait,
3676                                    atomic_read(&cur_trans->num_writers) == 1);
3677                                 ret = write_one_cache_group(trans, path, cache);
3678                         }
3679                         if (ret)
3680                                 btrfs_abort_transaction(trans, ret);
3681                 }
3682
3683                 /* if its not on the io list, we need to put the block group */
3684                 if (should_put)
3685                         btrfs_put_block_group(cache);
3686                 btrfs_delayed_refs_rsv_release(fs_info, 1);
3687                 spin_lock(&cur_trans->dirty_bgs_lock);
3688         }
3689         spin_unlock(&cur_trans->dirty_bgs_lock);
3690
3691         /*
3692          * Refer to the definition of io_bgs member for details why it's safe
3693          * to use it without any locking
3694          */
3695         while (!list_empty(io)) {
3696                 cache = list_first_entry(io, struct btrfs_block_group_cache,
3697                                          io_list);
3698                 list_del_init(&cache->io_list);
3699                 btrfs_wait_cache_io(trans, cache, path);
3700                 btrfs_put_block_group(cache);
3701         }
3702
3703         btrfs_free_path(path);
3704         return ret;
3705 }
3706
3707 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3708 {
3709         struct btrfs_block_group_cache *block_group;
3710         int readonly = 0;
3711
3712         block_group = btrfs_lookup_block_group(fs_info, bytenr);
3713         if (!block_group || block_group->ro)
3714                 readonly = 1;
3715         if (block_group)
3716                 btrfs_put_block_group(block_group);
3717         return readonly;
3718 }
3719
3720 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3721 {
3722         struct btrfs_block_group_cache *bg;
3723         bool ret = true;
3724
3725         bg = btrfs_lookup_block_group(fs_info, bytenr);
3726         if (!bg)
3727                 return false;
3728
3729         spin_lock(&bg->lock);
3730         if (bg->ro)
3731                 ret = false;
3732         else
3733                 atomic_inc(&bg->nocow_writers);
3734         spin_unlock(&bg->lock);
3735
3736         /* no put on block group, done by btrfs_dec_nocow_writers */
3737         if (!ret)
3738                 btrfs_put_block_group(bg);
3739
3740         return ret;
3741
3742 }
3743
3744 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3745 {
3746         struct btrfs_block_group_cache *bg;
3747
3748         bg = btrfs_lookup_block_group(fs_info, bytenr);
3749         ASSERT(bg);
3750         if (atomic_dec_and_test(&bg->nocow_writers))
3751                 wake_up_var(&bg->nocow_writers);
3752         /*
3753          * Once for our lookup and once for the lookup done by a previous call
3754          * to btrfs_inc_nocow_writers()
3755          */
3756         btrfs_put_block_group(bg);
3757         btrfs_put_block_group(bg);
3758 }
3759
3760 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3761 {
3762         wait_var_event(&bg->nocow_writers, !atomic_read(&bg->nocow_writers));
3763 }
3764
3765 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3766 {
3767         u64 extra_flags = chunk_to_extended(flags) &
3768                                 BTRFS_EXTENDED_PROFILE_MASK;
3769
3770         write_seqlock(&fs_info->profiles_lock);
3771         if (flags & BTRFS_BLOCK_GROUP_DATA)
3772                 fs_info->avail_data_alloc_bits |= extra_flags;
3773         if (flags & BTRFS_BLOCK_GROUP_METADATA)
3774                 fs_info->avail_metadata_alloc_bits |= extra_flags;
3775         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3776                 fs_info->avail_system_alloc_bits |= extra_flags;
3777         write_sequnlock(&fs_info->profiles_lock);
3778 }
3779
3780 /*
3781  * returns target flags in extended format or 0 if restripe for this
3782  * chunk_type is not in progress
3783  *
3784  * should be called with balance_lock held
3785  */
3786 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3787 {
3788         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3789         u64 target = 0;
3790
3791         if (!bctl)
3792                 return 0;
3793
3794         if (flags & BTRFS_BLOCK_GROUP_DATA &&
3795             bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3796                 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3797         } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3798                    bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3799                 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3800         } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3801                    bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3802                 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3803         }
3804
3805         return target;
3806 }
3807
3808 /*
3809  * @flags: available profiles in extended format (see ctree.h)
3810  *
3811  * Returns reduced profile in chunk format.  If profile changing is in
3812  * progress (either running or paused) picks the target profile (if it's
3813  * already available), otherwise falls back to plain reducing.
3814  */
3815 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
3816 {
3817         u64 num_devices = fs_info->fs_devices->rw_devices;
3818         u64 target;
3819         u64 raid_type;
3820         u64 allowed = 0;
3821
3822         /*
3823          * see if restripe for this chunk_type is in progress, if so
3824          * try to reduce to the target profile
3825          */
3826         spin_lock(&fs_info->balance_lock);
3827         target = get_restripe_target(fs_info, flags);
3828         if (target) {
3829                 /* pick target profile only if it's already available */
3830                 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3831                         spin_unlock(&fs_info->balance_lock);
3832                         return extended_to_chunk(target);
3833                 }
3834         }
3835         spin_unlock(&fs_info->balance_lock);
3836
3837         /* First, mask out the RAID levels which aren't possible */
3838         for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3839                 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
3840                         allowed |= btrfs_raid_array[raid_type].bg_flag;
3841         }
3842         allowed &= flags;
3843
3844         if (allowed & BTRFS_BLOCK_GROUP_RAID6)
3845                 allowed = BTRFS_BLOCK_GROUP_RAID6;
3846         else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
3847                 allowed = BTRFS_BLOCK_GROUP_RAID5;
3848         else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
3849                 allowed = BTRFS_BLOCK_GROUP_RAID10;
3850         else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
3851                 allowed = BTRFS_BLOCK_GROUP_RAID1;
3852         else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
3853                 allowed = BTRFS_BLOCK_GROUP_RAID0;
3854
3855         flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
3856
3857         return extended_to_chunk(flags | allowed);
3858 }
3859
3860 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
3861 {
3862         unsigned seq;
3863         u64 flags;
3864
3865         do {
3866                 flags = orig_flags;
3867                 seq = read_seqbegin(&fs_info->profiles_lock);
3868
3869                 if (flags & BTRFS_BLOCK_GROUP_DATA)
3870                         flags |= fs_info->avail_data_alloc_bits;
3871                 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3872                         flags |= fs_info->avail_system_alloc_bits;
3873                 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3874                         flags |= fs_info->avail_metadata_alloc_bits;
3875         } while (read_seqretry(&fs_info->profiles_lock, seq));
3876
3877         return btrfs_reduce_alloc_profile(fs_info, flags);
3878 }
3879
3880 static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
3881 {
3882         struct btrfs_fs_info *fs_info = root->fs_info;
3883         u64 flags;
3884         u64 ret;
3885
3886         if (data)
3887                 flags = BTRFS_BLOCK_GROUP_DATA;
3888         else if (root == fs_info->chunk_root)
3889                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3890         else
3891                 flags = BTRFS_BLOCK_GROUP_METADATA;
3892
3893         ret = get_alloc_profile(fs_info, flags);
3894         return ret;
3895 }
3896
3897 u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
3898 {
3899         return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
3900 }
3901
3902 u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
3903 {
3904         return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3905 }
3906
3907 u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
3908 {
3909         return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3910 }
3911
3912 int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
3913 {
3914         struct btrfs_root *root = inode->root;
3915         struct btrfs_fs_info *fs_info = root->fs_info;
3916         struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
3917         u64 used;
3918         int ret = 0;
3919         int need_commit = 2;
3920         int have_pinned_space;
3921
3922         /* make sure bytes are sectorsize aligned */
3923         bytes = ALIGN(bytes, fs_info->sectorsize);
3924
3925         if (btrfs_is_free_space_inode(inode)) {
3926                 need_commit = 0;
3927                 ASSERT(current->journal_info);
3928         }
3929
3930 again:
3931         /* make sure we have enough space to handle the data first */
3932         spin_lock(&data_sinfo->lock);
3933         used = btrfs_space_info_used(data_sinfo, true);
3934
3935         if (used + bytes > data_sinfo->total_bytes) {
3936                 struct btrfs_trans_handle *trans;
3937
3938                 /*
3939                  * if we don't have enough free bytes in this space then we need
3940                  * to alloc a new chunk.
3941                  */
3942                 if (!data_sinfo->full) {
3943                         u64 alloc_target;
3944
3945                         data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
3946                         spin_unlock(&data_sinfo->lock);
3947
3948                         alloc_target = btrfs_data_alloc_profile(fs_info);
3949                         /*
3950                          * It is ugly that we don't call nolock join
3951                          * transaction for the free space inode case here.
3952                          * But it is safe because we only do the data space
3953                          * reservation for the free space cache in the
3954                          * transaction context, the common join transaction
3955                          * just increase the counter of the current transaction
3956                          * handler, doesn't try to acquire the trans_lock of
3957                          * the fs.
3958                          */
3959                         trans = btrfs_join_transaction(root);
3960                         if (IS_ERR(trans))
3961                                 return PTR_ERR(trans);
3962
3963                         ret = btrfs_chunk_alloc(trans, alloc_target,
3964                                                 CHUNK_ALLOC_NO_FORCE);
3965                         btrfs_end_transaction(trans);
3966                         if (ret < 0) {
3967                                 if (ret != -ENOSPC)
3968                                         return ret;
3969                                 else {
3970                                         have_pinned_space = 1;
3971                                         goto commit_trans;
3972                                 }
3973                         }
3974
3975                         goto again;
3976                 }
3977
3978                 /*
3979                  * If we don't have enough pinned space to deal with this
3980                  * allocation, and no removed chunk in current transaction,
3981                  * don't bother committing the transaction.
3982                  */
3983                 have_pinned_space = __percpu_counter_compare(
3984                         &data_sinfo->total_bytes_pinned,
3985                         used + bytes - data_sinfo->total_bytes,
3986                         BTRFS_TOTAL_BYTES_PINNED_BATCH);
3987                 spin_unlock(&data_sinfo->lock);
3988
3989                 /* commit the current transaction and try again */
3990 commit_trans:
3991                 if (need_commit) {
3992                         need_commit--;
3993
3994                         if (need_commit > 0) {
3995                                 btrfs_start_delalloc_roots(fs_info, -1);
3996                                 btrfs_wait_ordered_roots(fs_info, U64_MAX, 0,
3997                                                          (u64)-1);
3998                         }
3999
4000                         trans = btrfs_join_transaction(root);
4001                         if (IS_ERR(trans))
4002                                 return PTR_ERR(trans);
4003                         if (have_pinned_space >= 0 ||
4004                             test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4005                                      &trans->transaction->flags) ||
4006                             need_commit > 0) {
4007                                 ret = btrfs_commit_transaction(trans);
4008                                 if (ret)
4009                                         return ret;
4010                                 /*
4011                                  * The cleaner kthread might still be doing iput
4012                                  * operations. Wait for it to finish so that
4013                                  * more space is released.  We don't need to
4014                                  * explicitly run the delayed iputs here because
4015                                  * the commit_transaction would have woken up
4016                                  * the cleaner.
4017                                  */
4018                                 ret = btrfs_wait_on_delayed_iputs(fs_info);
4019                                 if (ret)
4020                                         return ret;
4021                                 goto again;
4022                         } else {
4023                                 btrfs_end_transaction(trans);
4024                         }
4025                 }
4026
4027                 trace_btrfs_space_reservation(fs_info,
4028                                               "space_info:enospc",
4029                                               data_sinfo->flags, bytes, 1);
4030                 return -ENOSPC;
4031         }
4032         btrfs_space_info_update_bytes_may_use(fs_info, data_sinfo, bytes);
4033         trace_btrfs_space_reservation(fs_info, "space_info",
4034                                       data_sinfo->flags, bytes, 1);
4035         spin_unlock(&data_sinfo->lock);
4036
4037         return 0;
4038 }
4039
4040 int btrfs_check_data_free_space(struct inode *inode,
4041                         struct extent_changeset **reserved, u64 start, u64 len)
4042 {
4043         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4044         int ret;
4045
4046         /* align the range */
4047         len = round_up(start + len, fs_info->sectorsize) -
4048               round_down(start, fs_info->sectorsize);
4049         start = round_down(start, fs_info->sectorsize);
4050
4051         ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
4052         if (ret < 0)
4053                 return ret;
4054
4055         /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4056         ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
4057         if (ret < 0)
4058                 btrfs_free_reserved_data_space_noquota(inode, start, len);
4059         else
4060                 ret = 0;
4061         return ret;
4062 }
4063
4064 /*
4065  * Called if we need to clear a data reservation for this inode
4066  * Normally in a error case.
4067  *
4068  * This one will *NOT* use accurate qgroup reserved space API, just for case
4069  * which we can't sleep and is sure it won't affect qgroup reserved space.
4070  * Like clear_bit_hook().
4071  */
4072 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4073                                             u64 len)
4074 {
4075         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4076         struct btrfs_space_info *data_sinfo;
4077
4078         /* Make sure the range is aligned to sectorsize */
4079         len = round_up(start + len, fs_info->sectorsize) -
4080               round_down(start, fs_info->sectorsize);
4081         start = round_down(start, fs_info->sectorsize);
4082
4083         data_sinfo = fs_info->data_sinfo;
4084         spin_lock(&data_sinfo->lock);
4085         btrfs_space_info_update_bytes_may_use(fs_info, data_sinfo, -len);
4086         trace_btrfs_space_reservation(fs_info, "space_info",
4087                                       data_sinfo->flags, len, 0);
4088         spin_unlock(&data_sinfo->lock);
4089 }
4090
4091 /*
4092  * Called if we need to clear a data reservation for this inode
4093  * Normally in a error case.
4094  *
4095  * This one will handle the per-inode data rsv map for accurate reserved
4096  * space framework.
4097  */
4098 void btrfs_free_reserved_data_space(struct inode *inode,
4099                         struct extent_changeset *reserved, u64 start, u64 len)
4100 {
4101         struct btrfs_root *root = BTRFS_I(inode)->root;
4102
4103         /* Make sure the range is aligned to sectorsize */
4104         len = round_up(start + len, root->fs_info->sectorsize) -
4105               round_down(start, root->fs_info->sectorsize);
4106         start = round_down(start, root->fs_info->sectorsize);
4107
4108         btrfs_free_reserved_data_space_noquota(inode, start, len);
4109         btrfs_qgroup_free_data(inode, reserved, start, len);
4110 }
4111
4112 static void force_metadata_allocation(struct btrfs_fs_info *info)
4113 {
4114         struct list_head *head = &info->space_info;
4115         struct btrfs_space_info *found;
4116
4117         rcu_read_lock();
4118         list_for_each_entry_rcu(found, head, list) {
4119                 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4120                         found->force_alloc = CHUNK_ALLOC_FORCE;
4121         }
4122         rcu_read_unlock();
4123 }
4124
4125 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4126                               struct btrfs_space_info *sinfo, int force)
4127 {
4128         u64 bytes_used = btrfs_space_info_used(sinfo, false);
4129         u64 thresh;
4130
4131         if (force == CHUNK_ALLOC_FORCE)
4132                 return 1;
4133
4134         /*
4135          * in limited mode, we want to have some free space up to
4136          * about 1% of the FS size.
4137          */
4138         if (force == CHUNK_ALLOC_LIMITED) {
4139                 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4140                 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4141
4142                 if (sinfo->total_bytes - bytes_used < thresh)
4143                         return 1;
4144         }
4145
4146         if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
4147                 return 0;
4148         return 1;
4149 }
4150
4151 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4152 {
4153         u64 num_dev;
4154
4155         num_dev = btrfs_raid_array[btrfs_bg_flags_to_raid_index(type)].devs_max;
4156         if (!num_dev)
4157                 num_dev = fs_info->fs_devices->rw_devices;
4158
4159         return num_dev;
4160 }
4161
4162 /*
4163  * If @is_allocation is true, reserve space in the system space info necessary
4164  * for allocating a chunk, otherwise if it's false, reserve space necessary for
4165  * removing a chunk.
4166  */
4167 void check_system_chunk(struct btrfs_trans_handle *trans, u64 type)
4168 {
4169         struct btrfs_fs_info *fs_info = trans->fs_info;
4170         struct btrfs_space_info *info;
4171         u64 left;
4172         u64 thresh;
4173         int ret = 0;
4174         u64 num_devs;
4175
4176         /*
4177          * Needed because we can end up allocating a system chunk and for an
4178          * atomic and race free space reservation in the chunk block reserve.
4179          */
4180         lockdep_assert_held(&fs_info->chunk_mutex);
4181
4182         info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4183         spin_lock(&info->lock);
4184         left = info->total_bytes - btrfs_space_info_used(info, true);
4185         spin_unlock(&info->lock);
4186
4187         num_devs = get_profile_num_devs(fs_info, type);
4188
4189         /* num_devs device items to update and 1 chunk item to add or remove */
4190         thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4191                 btrfs_calc_trans_metadata_size(fs_info, 1);
4192
4193         if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4194                 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4195                            left, thresh, type);
4196                 btrfs_dump_space_info(fs_info, info, 0, 0);
4197         }
4198
4199         if (left < thresh) {
4200                 u64 flags = btrfs_system_alloc_profile(fs_info);
4201
4202                 /*
4203                  * Ignore failure to create system chunk. We might end up not
4204                  * needing it, as we might not need to COW all nodes/leafs from
4205                  * the paths we visit in the chunk tree (they were already COWed
4206                  * or created in the current transaction for example).
4207                  */
4208                 ret = btrfs_alloc_chunk(trans, flags);
4209         }
4210
4211         if (!ret) {
4212                 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4213                                           &fs_info->chunk_block_rsv,
4214                                           thresh, BTRFS_RESERVE_NO_FLUSH);
4215                 if (!ret)
4216                         trans->chunk_bytes_reserved += thresh;
4217         }
4218 }
4219
4220 /*
4221  * If force is CHUNK_ALLOC_FORCE:
4222  *    - return 1 if it successfully allocates a chunk,
4223  *    - return errors including -ENOSPC otherwise.
4224  * If force is NOT CHUNK_ALLOC_FORCE:
4225  *    - return 0 if it doesn't need to allocate a new chunk,
4226  *    - return 1 if it successfully allocates a chunk,
4227  *    - return errors including -ENOSPC otherwise.
4228  */
4229 int btrfs_chunk_alloc(struct btrfs_trans_handle *trans, u64 flags,
4230                       enum btrfs_chunk_alloc_enum force)
4231 {
4232         struct btrfs_fs_info *fs_info = trans->fs_info;
4233         struct btrfs_space_info *space_info;
4234         bool wait_for_alloc = false;
4235         bool should_alloc = false;
4236         int ret = 0;
4237
4238         /* Don't re-enter if we're already allocating a chunk */
4239         if (trans->allocating_chunk)
4240                 return -ENOSPC;
4241
4242         space_info = btrfs_find_space_info(fs_info, flags);
4243         ASSERT(space_info);
4244
4245         do {
4246                 spin_lock(&space_info->lock);
4247                 if (force < space_info->force_alloc)
4248                         force = space_info->force_alloc;
4249                 should_alloc = should_alloc_chunk(fs_info, space_info, force);
4250                 if (space_info->full) {
4251                         /* No more free physical space */
4252                         if (should_alloc)
4253                                 ret = -ENOSPC;
4254                         else
4255                                 ret = 0;
4256                         spin_unlock(&space_info->lock);
4257                         return ret;
4258                 } else if (!should_alloc) {
4259                         spin_unlock(&space_info->lock);
4260                         return 0;
4261                 } else if (space_info->chunk_alloc) {
4262                         /*
4263                          * Someone is already allocating, so we need to block
4264                          * until this someone is finished and then loop to
4265                          * recheck if we should continue with our allocation
4266                          * attempt.
4267                          */
4268                         wait_for_alloc = true;
4269                         spin_unlock(&space_info->lock);
4270                         mutex_lock(&fs_info->chunk_mutex);
4271                         mutex_unlock(&fs_info->chunk_mutex);
4272                 } else {
4273                         /* Proceed with allocation */
4274                         space_info->chunk_alloc = 1;
4275                         wait_for_alloc = false;
4276                         spin_unlock(&space_info->lock);
4277                 }
4278
4279                 cond_resched();
4280         } while (wait_for_alloc);
4281
4282         mutex_lock(&fs_info->chunk_mutex);
4283         trans->allocating_chunk = true;
4284
4285         /*
4286          * If we have mixed data/metadata chunks we want to make sure we keep
4287          * allocating mixed chunks instead of individual chunks.
4288          */
4289         if (btrfs_mixed_space_info(space_info))
4290                 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4291
4292         /*
4293          * if we're doing a data chunk, go ahead and make sure that
4294          * we keep a reasonable number of metadata chunks allocated in the
4295          * FS as well.
4296          */
4297         if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4298                 fs_info->data_chunk_allocations++;
4299                 if (!(fs_info->data_chunk_allocations %
4300                       fs_info->metadata_ratio))
4301                         force_metadata_allocation(fs_info);
4302         }
4303
4304         /*
4305          * Check if we have enough space in SYSTEM chunk because we may need
4306          * to update devices.
4307          */
4308         check_system_chunk(trans, flags);
4309
4310         ret = btrfs_alloc_chunk(trans, flags);
4311         trans->allocating_chunk = false;
4312
4313         spin_lock(&space_info->lock);
4314         if (ret < 0) {
4315                 if (ret == -ENOSPC)
4316                         space_info->full = 1;
4317                 else
4318                         goto out;
4319         } else {
4320                 ret = 1;
4321                 space_info->max_extent_size = 0;
4322         }
4323
4324         space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4325 out:
4326         space_info->chunk_alloc = 0;
4327         spin_unlock(&space_info->lock);
4328         mutex_unlock(&fs_info->chunk_mutex);
4329         /*
4330          * When we allocate a new chunk we reserve space in the chunk block
4331          * reserve to make sure we can COW nodes/leafs in the chunk tree or
4332          * add new nodes/leafs to it if we end up needing to do it when
4333          * inserting the chunk item and updating device items as part of the
4334          * second phase of chunk allocation, performed by
4335          * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4336          * large number of new block groups to create in our transaction
4337          * handle's new_bgs list to avoid exhausting the chunk block reserve
4338          * in extreme cases - like having a single transaction create many new
4339          * block groups when starting to write out the free space caches of all
4340          * the block groups that were made dirty during the lifetime of the
4341          * transaction.
4342          */
4343         if (trans->chunk_bytes_reserved >= (u64)SZ_2M)
4344                 btrfs_create_pending_block_groups(trans);
4345
4346         return ret;
4347 }
4348
4349 static struct btrfs_block_rsv *get_block_rsv(
4350                                         const struct btrfs_trans_handle *trans,
4351                                         const struct btrfs_root *root)
4352 {
4353         struct btrfs_fs_info *fs_info = root->fs_info;
4354         struct btrfs_block_rsv *block_rsv = NULL;
4355
4356         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
4357             (root == fs_info->csum_root && trans->adding_csums) ||
4358             (root == fs_info->uuid_root))
4359                 block_rsv = trans->block_rsv;
4360
4361         if (!block_rsv)
4362                 block_rsv = root->block_rsv;
4363
4364         if (!block_rsv)
4365                 block_rsv = &fs_info->empty_block_rsv;
4366
4367         return block_rsv;
4368 }
4369
4370 int btrfs_block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv, u64 num_bytes)
4371 {
4372         int ret = -ENOSPC;
4373         spin_lock(&block_rsv->lock);
4374         if (block_rsv->reserved >= num_bytes) {
4375                 block_rsv->reserved -= num_bytes;
4376                 if (block_rsv->reserved < block_rsv->size)
4377                         block_rsv->full = 0;
4378                 ret = 0;
4379         }
4380         spin_unlock(&block_rsv->lock);
4381         return ret;
4382 }
4383
4384 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
4385                                 u64 num_bytes, bool update_size)
4386 {
4387         spin_lock(&block_rsv->lock);
4388         block_rsv->reserved += num_bytes;
4389         if (update_size)
4390                 block_rsv->size += num_bytes;
4391         else if (block_rsv->reserved >= block_rsv->size)
4392                 block_rsv->full = 1;
4393         spin_unlock(&block_rsv->lock);
4394 }
4395
4396 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
4397                              struct btrfs_block_rsv *dest, u64 num_bytes,
4398                              int min_factor)
4399 {
4400         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4401         u64 min_bytes;
4402
4403         if (global_rsv->space_info != dest->space_info)
4404                 return -ENOSPC;
4405
4406         spin_lock(&global_rsv->lock);
4407         min_bytes = div_factor(global_rsv->size, min_factor);
4408         if (global_rsv->reserved < min_bytes + num_bytes) {
4409                 spin_unlock(&global_rsv->lock);
4410                 return -ENOSPC;
4411         }
4412         global_rsv->reserved -= num_bytes;
4413         if (global_rsv->reserved < global_rsv->size)
4414                 global_rsv->full = 0;
4415         spin_unlock(&global_rsv->lock);
4416
4417         block_rsv_add_bytes(dest, num_bytes, true);
4418         return 0;
4419 }
4420
4421 /**
4422  * btrfs_migrate_to_delayed_refs_rsv - transfer bytes to our delayed refs rsv.
4423  * @fs_info - the fs info for our fs.
4424  * @src - the source block rsv to transfer from.
4425  * @num_bytes - the number of bytes to transfer.
4426  *
4427  * This transfers up to the num_bytes amount from the src rsv to the
4428  * delayed_refs_rsv.  Any extra bytes are returned to the space info.
4429  */
4430 void btrfs_migrate_to_delayed_refs_rsv(struct btrfs_fs_info *fs_info,
4431                                        struct btrfs_block_rsv *src,
4432                                        u64 num_bytes)
4433 {
4434         struct btrfs_block_rsv *delayed_refs_rsv = &fs_info->delayed_refs_rsv;
4435         u64 to_free = 0;
4436
4437         spin_lock(&src->lock);
4438         src->reserved -= num_bytes;
4439         src->size -= num_bytes;
4440         spin_unlock(&src->lock);
4441
4442         spin_lock(&delayed_refs_rsv->lock);
4443         if (delayed_refs_rsv->size > delayed_refs_rsv->reserved) {
4444                 u64 delta = delayed_refs_rsv->size -
4445                         delayed_refs_rsv->reserved;
4446                 if (num_bytes > delta) {
4447                         to_free = num_bytes - delta;
4448                         num_bytes = delta;
4449                 }
4450         } else {
4451                 to_free = num_bytes;
4452                 num_bytes = 0;
4453         }
4454
4455         if (num_bytes)
4456                 delayed_refs_rsv->reserved += num_bytes;
4457         if (delayed_refs_rsv->reserved >= delayed_refs_rsv->size)
4458                 delayed_refs_rsv->full = 1;
4459         spin_unlock(&delayed_refs_rsv->lock);
4460
4461         if (num_bytes)
4462                 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
4463                                               0, num_bytes, 1);
4464         if (to_free)
4465                 btrfs_space_info_add_old_bytes(fs_info,
4466                                 delayed_refs_rsv->space_info, to_free);
4467 }
4468
4469 /**
4470  * btrfs_delayed_refs_rsv_refill - refill based on our delayed refs usage.
4471  * @fs_info - the fs_info for our fs.
4472  * @flush - control how we can flush for this reservation.
4473  *
4474  * This will refill the delayed block_rsv up to 1 items size worth of space and
4475  * will return -ENOSPC if we can't make the reservation.
4476  */
4477 int btrfs_delayed_refs_rsv_refill(struct btrfs_fs_info *fs_info,
4478                                   enum btrfs_reserve_flush_enum flush)
4479 {
4480         struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
4481         u64 limit = btrfs_calc_trans_metadata_size(fs_info, 1);
4482         u64 num_bytes = 0;
4483         int ret = -ENOSPC;
4484
4485         spin_lock(&block_rsv->lock);
4486         if (block_rsv->reserved < block_rsv->size) {
4487                 num_bytes = block_rsv->size - block_rsv->reserved;
4488                 num_bytes = min(num_bytes, limit);
4489         }
4490         spin_unlock(&block_rsv->lock);
4491
4492         if (!num_bytes)
4493                 return 0;
4494
4495         ret = btrfs_reserve_metadata_bytes(fs_info->extent_root, block_rsv,
4496                                            num_bytes, flush);
4497         if (ret)
4498                 return ret;
4499         block_rsv_add_bytes(block_rsv, num_bytes, 0);
4500         trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
4501                                       0, num_bytes, 1);
4502         return 0;
4503 }
4504
4505 static u64 block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
4506                                     struct btrfs_block_rsv *block_rsv,
4507                                     struct btrfs_block_rsv *dest, u64 num_bytes,
4508                                     u64 *qgroup_to_release_ret)
4509 {
4510         struct btrfs_space_info *space_info = block_rsv->space_info;
4511         u64 qgroup_to_release = 0;
4512         u64 ret;
4513
4514         spin_lock(&block_rsv->lock);
4515         if (num_bytes == (u64)-1) {
4516                 num_bytes = block_rsv->size;
4517                 qgroup_to_release = block_rsv->qgroup_rsv_size;
4518         }
4519         block_rsv->size -= num_bytes;
4520         if (block_rsv->reserved >= block_rsv->size) {
4521                 num_bytes = block_rsv->reserved - block_rsv->size;
4522                 block_rsv->reserved = block_rsv->size;
4523                 block_rsv->full = 1;
4524         } else {
4525                 num_bytes = 0;
4526         }
4527         if (block_rsv->qgroup_rsv_reserved >= block_rsv->qgroup_rsv_size) {
4528                 qgroup_to_release = block_rsv->qgroup_rsv_reserved -
4529                                     block_rsv->qgroup_rsv_size;
4530                 block_rsv->qgroup_rsv_reserved = block_rsv->qgroup_rsv_size;
4531         } else {
4532                 qgroup_to_release = 0;
4533         }
4534         spin_unlock(&block_rsv->lock);
4535
4536         ret = num_bytes;
4537         if (num_bytes > 0) {
4538                 if (dest) {
4539                         spin_lock(&dest->lock);
4540                         if (!dest->full) {
4541                                 u64 bytes_to_add;
4542
4543                                 bytes_to_add = dest->size - dest->reserved;
4544                                 bytes_to_add = min(num_bytes, bytes_to_add);
4545                                 dest->reserved += bytes_to_add;
4546                                 if (dest->reserved >= dest->size)
4547                                         dest->full = 1;
4548                                 num_bytes -= bytes_to_add;
4549                         }
4550                         spin_unlock(&dest->lock);
4551                 }
4552                 if (num_bytes)
4553                         btrfs_space_info_add_old_bytes(fs_info, space_info,
4554                                                        num_bytes);
4555         }
4556         if (qgroup_to_release_ret)
4557                 *qgroup_to_release_ret = qgroup_to_release;
4558         return ret;
4559 }
4560
4561 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
4562                             struct btrfs_block_rsv *dst, u64 num_bytes,
4563                             bool update_size)
4564 {
4565         int ret;
4566
4567         ret = btrfs_block_rsv_use_bytes(src, num_bytes);
4568         if (ret)
4569                 return ret;
4570
4571         block_rsv_add_bytes(dst, num_bytes, update_size);
4572         return 0;
4573 }
4574
4575 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
4576 {
4577         memset(rsv, 0, sizeof(*rsv));
4578         spin_lock_init(&rsv->lock);
4579         rsv->type = type;
4580 }
4581
4582 void btrfs_init_metadata_block_rsv(struct btrfs_fs_info *fs_info,
4583                                    struct btrfs_block_rsv *rsv,
4584                                    unsigned short type)
4585 {
4586         btrfs_init_block_rsv(rsv, type);
4587         rsv->space_info = btrfs_find_space_info(fs_info,
4588                                             BTRFS_BLOCK_GROUP_METADATA);
4589 }
4590
4591 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
4592                                               unsigned short type)
4593 {
4594         struct btrfs_block_rsv *block_rsv;
4595
4596         block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
4597         if (!block_rsv)
4598                 return NULL;
4599
4600         btrfs_init_metadata_block_rsv(fs_info, block_rsv, type);
4601         return block_rsv;
4602 }
4603
4604 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
4605                           struct btrfs_block_rsv *rsv)
4606 {
4607         if (!rsv)
4608                 return;
4609         btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
4610         kfree(rsv);
4611 }
4612
4613 int btrfs_block_rsv_add(struct btrfs_root *root,
4614                         struct btrfs_block_rsv *block_rsv, u64 num_bytes,
4615                         enum btrfs_reserve_flush_enum flush)
4616 {
4617         int ret;
4618
4619         if (num_bytes == 0)
4620                 return 0;
4621
4622         ret = btrfs_reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4623         if (!ret)
4624                 block_rsv_add_bytes(block_rsv, num_bytes, true);
4625
4626         return ret;
4627 }
4628
4629 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
4630 {
4631         u64 num_bytes = 0;
4632         int ret = -ENOSPC;
4633
4634         if (!block_rsv)
4635                 return 0;
4636
4637         spin_lock(&block_rsv->lock);
4638         num_bytes = div_factor(block_rsv->size, min_factor);
4639         if (block_rsv->reserved >= num_bytes)
4640                 ret = 0;
4641         spin_unlock(&block_rsv->lock);
4642
4643         return ret;
4644 }
4645
4646 int btrfs_block_rsv_refill(struct btrfs_root *root,
4647                            struct btrfs_block_rsv *block_rsv, u64 min_reserved,
4648                            enum btrfs_reserve_flush_enum flush)
4649 {
4650         u64 num_bytes = 0;
4651         int ret = -ENOSPC;
4652
4653         if (!block_rsv)
4654                 return 0;
4655
4656         spin_lock(&block_rsv->lock);
4657         num_bytes = min_reserved;
4658         if (block_rsv->reserved >= num_bytes)
4659                 ret = 0;
4660         else
4661                 num_bytes -= block_rsv->reserved;
4662         spin_unlock(&block_rsv->lock);
4663
4664         if (!ret)
4665                 return 0;
4666
4667         ret = btrfs_reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4668         if (!ret) {
4669                 block_rsv_add_bytes(block_rsv, num_bytes, false);
4670                 return 0;
4671         }
4672
4673         return ret;
4674 }
4675
4676 static u64 __btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
4677                                      struct btrfs_block_rsv *block_rsv,
4678                                      u64 num_bytes, u64 *qgroup_to_release)
4679 {
4680         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4681         struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
4682         struct btrfs_block_rsv *target = delayed_rsv;
4683
4684         if (target->full || target == block_rsv)
4685                 target = global_rsv;
4686
4687         if (block_rsv->space_info != target->space_info)
4688                 target = NULL;
4689
4690         return block_rsv_release_bytes(fs_info, block_rsv, target, num_bytes,
4691                                        qgroup_to_release);
4692 }
4693
4694 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
4695                              struct btrfs_block_rsv *block_rsv,
4696                              u64 num_bytes)
4697 {
4698         __btrfs_block_rsv_release(fs_info, block_rsv, num_bytes, NULL);
4699 }
4700
4701 /**
4702  * btrfs_inode_rsv_release - release any excessive reservation.
4703  * @inode - the inode we need to release from.
4704  * @qgroup_free - free or convert qgroup meta.
4705  *   Unlike normal operation, qgroup meta reservation needs to know if we are
4706  *   freeing qgroup reservation or just converting it into per-trans.  Normally
4707  *   @qgroup_free is true for error handling, and false for normal release.
4708  *
4709  * This is the same as btrfs_block_rsv_release, except that it handles the
4710  * tracepoint for the reservation.
4711  */
4712 static void btrfs_inode_rsv_release(struct btrfs_inode *inode, bool qgroup_free)
4713 {
4714         struct btrfs_fs_info *fs_info = inode->root->fs_info;
4715         struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
4716         u64 released = 0;
4717         u64 qgroup_to_release = 0;
4718
4719         /*
4720          * Since we statically set the block_rsv->size we just want to say we
4721          * are releasing 0 bytes, and then we'll just get the reservation over
4722          * the size free'd.
4723          */
4724         released = __btrfs_block_rsv_release(fs_info, block_rsv, 0,
4725                                              &qgroup_to_release);
4726         if (released > 0)
4727                 trace_btrfs_space_reservation(fs_info, "delalloc",
4728                                               btrfs_ino(inode), released, 0);
4729         if (qgroup_free)
4730                 btrfs_qgroup_free_meta_prealloc(inode->root, qgroup_to_release);
4731         else
4732                 btrfs_qgroup_convert_reserved_meta(inode->root,
4733                                                    qgroup_to_release);
4734 }
4735
4736 /**
4737  * btrfs_delayed_refs_rsv_release - release a ref head's reservation.
4738  * @fs_info - the fs_info for our fs.
4739  * @nr - the number of items to drop.
4740  *
4741  * This drops the delayed ref head's count from the delayed refs rsv and frees
4742  * any excess reservation we had.
4743  */
4744 void btrfs_delayed_refs_rsv_release(struct btrfs_fs_info *fs_info, int nr)
4745 {
4746         struct btrfs_block_rsv *block_rsv = &fs_info->delayed_refs_rsv;
4747         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4748         u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, nr);
4749         u64 released = 0;
4750
4751         released = block_rsv_release_bytes(fs_info, block_rsv, global_rsv,
4752                                            num_bytes, NULL);
4753         if (released)
4754                 trace_btrfs_space_reservation(fs_info, "delayed_refs_rsv",
4755                                               0, released, 0);
4756 }
4757
4758 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
4759 {
4760         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4761         struct btrfs_space_info *sinfo = block_rsv->space_info;
4762         u64 num_bytes;
4763
4764         /*
4765          * The global block rsv is based on the size of the extent tree, the
4766          * checksum tree and the root tree.  If the fs is empty we want to set
4767          * it to a minimal amount for safety.
4768          */
4769         num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
4770                 btrfs_root_used(&fs_info->csum_root->root_item) +
4771                 btrfs_root_used(&fs_info->tree_root->root_item);
4772         num_bytes = max_t(u64, num_bytes, SZ_16M);
4773
4774         spin_lock(&sinfo->lock);
4775         spin_lock(&block_rsv->lock);
4776
4777         block_rsv->size = min_t(u64, num_bytes, SZ_512M);
4778
4779         if (block_rsv->reserved < block_rsv->size) {
4780                 num_bytes = btrfs_space_info_used(sinfo, true);
4781                 if (sinfo->total_bytes > num_bytes) {
4782                         num_bytes = sinfo->total_bytes - num_bytes;
4783                         num_bytes = min(num_bytes,
4784                                         block_rsv->size - block_rsv->reserved);
4785                         block_rsv->reserved += num_bytes;
4786                         btrfs_space_info_update_bytes_may_use(fs_info, sinfo,
4787                                                               num_bytes);
4788                         trace_btrfs_space_reservation(fs_info, "space_info",
4789                                                       sinfo->flags, num_bytes,
4790                                                       1);
4791                 }
4792         } else if (block_rsv->reserved > block_rsv->size) {
4793                 num_bytes = block_rsv->reserved - block_rsv->size;
4794                 btrfs_space_info_update_bytes_may_use(fs_info, sinfo,
4795                                                       -num_bytes);
4796                 trace_btrfs_space_reservation(fs_info, "space_info",
4797                                       sinfo->flags, num_bytes, 0);
4798                 block_rsv->reserved = block_rsv->size;
4799         }
4800
4801         if (block_rsv->reserved == block_rsv->size)
4802                 block_rsv->full = 1;
4803         else
4804                 block_rsv->full = 0;
4805
4806         spin_unlock(&block_rsv->lock);
4807         spin_unlock(&sinfo->lock);
4808 }
4809
4810 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
4811 {
4812         struct btrfs_space_info *space_info;
4813
4814         space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4815         fs_info->chunk_block_rsv.space_info = space_info;
4816
4817         space_info = btrfs_find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4818         fs_info->global_block_rsv.space_info = space_info;
4819         fs_info->trans_block_rsv.space_info = space_info;
4820         fs_info->empty_block_rsv.space_info = space_info;
4821         fs_info->delayed_block_rsv.space_info = space_info;
4822         fs_info->delayed_refs_rsv.space_info = space_info;
4823
4824         fs_info->extent_root->block_rsv = &fs_info->delayed_refs_rsv;
4825         fs_info->csum_root->block_rsv = &fs_info->delayed_refs_rsv;
4826         fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
4827         fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
4828         if (fs_info->quota_root)
4829                 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
4830         fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
4831
4832         update_global_block_rsv(fs_info);
4833 }
4834
4835 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
4836 {
4837         block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
4838                                 (u64)-1, NULL);
4839         WARN_ON(fs_info->trans_block_rsv.size > 0);
4840         WARN_ON(fs_info->trans_block_rsv.reserved > 0);
4841         WARN_ON(fs_info->chunk_block_rsv.size > 0);
4842         WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
4843         WARN_ON(fs_info->delayed_block_rsv.size > 0);
4844         WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
4845         WARN_ON(fs_info->delayed_refs_rsv.reserved > 0);
4846         WARN_ON(fs_info->delayed_refs_rsv.size > 0);
4847 }
4848
4849 /*
4850  * btrfs_update_delayed_refs_rsv - adjust the size of the delayed refs rsv
4851  * @trans - the trans that may have generated delayed refs
4852  *
4853  * This is to be called anytime we may have adjusted trans->delayed_ref_updates,
4854  * it'll calculate the additional size and add it to the delayed_refs_rsv.
4855  */
4856 void btrfs_update_delayed_refs_rsv(struct btrfs_trans_handle *trans)
4857 {
4858         struct btrfs_fs_info *fs_info = trans->fs_info;
4859         struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_refs_rsv;
4860         u64 num_bytes;
4861
4862         if (!trans->delayed_ref_updates)
4863                 return;
4864
4865         num_bytes = btrfs_calc_trans_metadata_size(fs_info,
4866                                                    trans->delayed_ref_updates);
4867         spin_lock(&delayed_rsv->lock);
4868         delayed_rsv->size += num_bytes;
4869         delayed_rsv->full = 0;
4870         spin_unlock(&delayed_rsv->lock);
4871         trans->delayed_ref_updates = 0;
4872 }
4873
4874 /*
4875  * To be called after all the new block groups attached to the transaction
4876  * handle have been created (btrfs_create_pending_block_groups()).
4877  */
4878 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
4879 {
4880         struct btrfs_fs_info *fs_info = trans->fs_info;
4881
4882         if (!trans->chunk_bytes_reserved)
4883                 return;
4884
4885         WARN_ON_ONCE(!list_empty(&trans->new_bgs));
4886
4887         block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
4888                                 trans->chunk_bytes_reserved, NULL);
4889         trans->chunk_bytes_reserved = 0;
4890 }
4891
4892 /*
4893  * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
4894  * root: the root of the parent directory
4895  * rsv: block reservation
4896  * items: the number of items that we need do reservation
4897  * use_global_rsv: allow fallback to the global block reservation
4898  *
4899  * This function is used to reserve the space for snapshot/subvolume
4900  * creation and deletion. Those operations are different with the
4901  * common file/directory operations, they change two fs/file trees
4902  * and root tree, the number of items that the qgroup reserves is
4903  * different with the free space reservation. So we can not use
4904  * the space reservation mechanism in start_transaction().
4905  */
4906 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
4907                                      struct btrfs_block_rsv *rsv, int items,
4908                                      bool use_global_rsv)
4909 {
4910         u64 qgroup_num_bytes = 0;
4911         u64 num_bytes;
4912         int ret;
4913         struct btrfs_fs_info *fs_info = root->fs_info;
4914         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4915
4916         if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
4917                 /* One for parent inode, two for dir entries */
4918                 qgroup_num_bytes = 3 * fs_info->nodesize;
4919                 ret = btrfs_qgroup_reserve_meta_prealloc(root,
4920                                 qgroup_num_bytes, true);
4921                 if (ret)
4922                         return ret;
4923         }
4924
4925         num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
4926         rsv->space_info = btrfs_find_space_info(fs_info,
4927                                             BTRFS_BLOCK_GROUP_METADATA);
4928         ret = btrfs_block_rsv_add(root, rsv, num_bytes,
4929                                   BTRFS_RESERVE_FLUSH_ALL);
4930
4931         if (ret == -ENOSPC && use_global_rsv)
4932                 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, true);
4933
4934         if (ret && qgroup_num_bytes)
4935                 btrfs_qgroup_free_meta_prealloc(root, qgroup_num_bytes);
4936
4937         return ret;
4938 }
4939
4940 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
4941                                       struct btrfs_block_rsv *rsv)
4942 {
4943         btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
4944 }
4945
4946 static void btrfs_calculate_inode_block_rsv_size(struct btrfs_fs_info *fs_info,
4947                                                  struct btrfs_inode *inode)
4948 {
4949         struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
4950         u64 reserve_size = 0;
4951         u64 qgroup_rsv_size = 0;
4952         u64 csum_leaves;
4953         unsigned outstanding_extents;
4954
4955         lockdep_assert_held(&inode->lock);
4956         outstanding_extents = inode->outstanding_extents;
4957         if (outstanding_extents)
4958                 reserve_size = btrfs_calc_trans_metadata_size(fs_info,
4959                                                 outstanding_extents + 1);
4960         csum_leaves = btrfs_csum_bytes_to_leaves(fs_info,
4961                                                  inode->csum_bytes);
4962         reserve_size += btrfs_calc_trans_metadata_size(fs_info,
4963                                                        csum_leaves);
4964         /*
4965          * For qgroup rsv, the calculation is very simple:
4966          * account one nodesize for each outstanding extent
4967          *
4968          * This is overestimating in most cases.
4969          */
4970         qgroup_rsv_size = (u64)outstanding_extents * fs_info->nodesize;
4971
4972         spin_lock(&block_rsv->lock);
4973         block_rsv->size = reserve_size;
4974         block_rsv->qgroup_rsv_size = qgroup_rsv_size;
4975         spin_unlock(&block_rsv->lock);
4976 }
4977
4978 static void calc_inode_reservations(struct btrfs_fs_info *fs_info,
4979                                     u64 num_bytes, u64 *meta_reserve,
4980                                     u64 *qgroup_reserve)
4981 {
4982         u64 nr_extents = count_max_extents(num_bytes);
4983         u64 csum_leaves = btrfs_csum_bytes_to_leaves(fs_info, num_bytes);
4984
4985         /* We add one for the inode update at finish ordered time */
4986         *meta_reserve = btrfs_calc_trans_metadata_size(fs_info,
4987                                                 nr_extents + csum_leaves + 1);
4988         *qgroup_reserve = nr_extents * fs_info->nodesize;
4989 }
4990
4991 int btrfs_delalloc_reserve_metadata(struct btrfs_inode *inode, u64 num_bytes)
4992 {
4993         struct btrfs_root *root = inode->root;
4994         struct btrfs_fs_info *fs_info = root->fs_info;
4995         struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
4996         u64 meta_reserve, qgroup_reserve;
4997         unsigned nr_extents;
4998         enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
4999         int ret = 0;
5000         bool delalloc_lock = true;
5001
5002         /* If we are a free space inode we need to not flush since we will be in
5003          * the middle of a transaction commit.  We also don't need the delalloc
5004          * mutex since we won't race with anybody.  We need this mostly to make
5005          * lockdep shut its filthy mouth.
5006          *
5007          * If we have a transaction open (can happen if we call truncate_block
5008          * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
5009          */
5010         if (btrfs_is_free_space_inode(inode)) {
5011                 flush = BTRFS_RESERVE_NO_FLUSH;
5012                 delalloc_lock = false;
5013         } else {
5014                 if (current->journal_info)
5015                         flush = BTRFS_RESERVE_FLUSH_LIMIT;
5016
5017                 if (btrfs_transaction_in_commit(fs_info))
5018                         schedule_timeout(1);
5019         }
5020
5021         if (delalloc_lock)
5022                 mutex_lock(&inode->delalloc_mutex);
5023
5024         num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5025
5026         /*
5027          * We always want to do it this way, every other way is wrong and ends
5028          * in tears.  Pre-reserving the amount we are going to add will always
5029          * be the right way, because otherwise if we have enough parallelism we
5030          * could end up with thousands of inodes all holding little bits of
5031          * reservations they were able to make previously and the only way to
5032          * reclaim that space is to ENOSPC out the operations and clear
5033          * everything out and try again, which is bad.  This way we just
5034          * over-reserve slightly, and clean up the mess when we are done.
5035          */
5036         calc_inode_reservations(fs_info, num_bytes, &meta_reserve,
5037                                 &qgroup_reserve);
5038         ret = btrfs_qgroup_reserve_meta_prealloc(root, qgroup_reserve, true);
5039         if (ret)
5040                 goto out_fail;
5041         ret = btrfs_reserve_metadata_bytes(root, block_rsv, meta_reserve, flush);
5042         if (ret)
5043                 goto out_qgroup;
5044
5045         /*
5046          * Now we need to update our outstanding extents and csum bytes _first_
5047          * and then add the reservation to the block_rsv.  This keeps us from
5048          * racing with an ordered completion or some such that would think it
5049          * needs to free the reservation we just made.
5050          */
5051         spin_lock(&inode->lock);
5052         nr_extents = count_max_extents(num_bytes);
5053         btrfs_mod_outstanding_extents(inode, nr_extents);
5054         inode->csum_bytes += num_bytes;
5055         btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5056         spin_unlock(&inode->lock);
5057
5058         /* Now we can safely add our space to our block rsv */
5059         block_rsv_add_bytes(block_rsv, meta_reserve, false);
5060         trace_btrfs_space_reservation(root->fs_info, "delalloc",
5061                                       btrfs_ino(inode), meta_reserve, 1);
5062
5063         spin_lock(&block_rsv->lock);
5064         block_rsv->qgroup_rsv_reserved += qgroup_reserve;
5065         spin_unlock(&block_rsv->lock);
5066
5067         if (delalloc_lock)
5068                 mutex_unlock(&inode->delalloc_mutex);
5069         return 0;
5070 out_qgroup:
5071         btrfs_qgroup_free_meta_prealloc(root, qgroup_reserve);
5072 out_fail:
5073         btrfs_inode_rsv_release(inode, true);
5074         if (delalloc_lock)
5075                 mutex_unlock(&inode->delalloc_mutex);
5076         return ret;
5077 }
5078
5079 /**
5080  * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
5081  * @inode: the inode to release the reservation for.
5082  * @num_bytes: the number of bytes we are releasing.
5083  * @qgroup_free: free qgroup reservation or convert it to per-trans reservation
5084  *
5085  * This will release the metadata reservation for an inode.  This can be called
5086  * once we complete IO for a given set of bytes to release their metadata
5087  * reservations, or on error for the same reason.
5088  */
5089 void btrfs_delalloc_release_metadata(struct btrfs_inode *inode, u64 num_bytes,
5090                                      bool qgroup_free)
5091 {
5092         struct btrfs_fs_info *fs_info = inode->root->fs_info;
5093
5094         num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5095         spin_lock(&inode->lock);
5096         inode->csum_bytes -= num_bytes;
5097         btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5098         spin_unlock(&inode->lock);
5099
5100         if (btrfs_is_testing(fs_info))
5101                 return;
5102
5103         btrfs_inode_rsv_release(inode, qgroup_free);
5104 }
5105
5106 /**
5107  * btrfs_delalloc_release_extents - release our outstanding_extents
5108  * @inode: the inode to balance the reservation for.
5109  * @num_bytes: the number of bytes we originally reserved with
5110  * @qgroup_free: do we need to free qgroup meta reservation or convert them.
5111  *
5112  * When we reserve space we increase outstanding_extents for the extents we may
5113  * add.  Once we've set the range as delalloc or created our ordered extents we
5114  * have outstanding_extents to track the real usage, so we use this to free our
5115  * temporarily tracked outstanding_extents.  This _must_ be used in conjunction
5116  * with btrfs_delalloc_reserve_metadata.
5117  */
5118 void btrfs_delalloc_release_extents(struct btrfs_inode *inode, u64 num_bytes,
5119                                     bool qgroup_free)
5120 {
5121         struct btrfs_fs_info *fs_info = inode->root->fs_info;
5122         unsigned num_extents;
5123
5124         spin_lock(&inode->lock);
5125         num_extents = count_max_extents(num_bytes);
5126         btrfs_mod_outstanding_extents(inode, -num_extents);
5127         btrfs_calculate_inode_block_rsv_size(fs_info, inode);
5128         spin_unlock(&inode->lock);
5129
5130         if (btrfs_is_testing(fs_info))
5131                 return;
5132
5133         btrfs_inode_rsv_release(inode, qgroup_free);
5134 }
5135
5136 /**
5137  * btrfs_delalloc_reserve_space - reserve data and metadata space for
5138  * delalloc
5139  * @inode: inode we're writing to
5140  * @start: start range we are writing to
5141  * @len: how long the range we are writing to
5142  * @reserved: mandatory parameter, record actually reserved qgroup ranges of
5143  *            current reservation.
5144  *
5145  * This will do the following things
5146  *
5147  * o reserve space in data space info for num bytes
5148  *   and reserve precious corresponding qgroup space
5149  *   (Done in check_data_free_space)
5150  *
5151  * o reserve space for metadata space, based on the number of outstanding
5152  *   extents and how much csums will be needed
5153  *   also reserve metadata space in a per root over-reserve method.
5154  * o add to the inodes->delalloc_bytes
5155  * o add it to the fs_info's delalloc inodes list.
5156  *   (Above 3 all done in delalloc_reserve_metadata)
5157  *
5158  * Return 0 for success
5159  * Return <0 for error(-ENOSPC or -EQUOT)
5160  */
5161 int btrfs_delalloc_reserve_space(struct inode *inode,
5162                         struct extent_changeset **reserved, u64 start, u64 len)
5163 {
5164         int ret;
5165
5166         ret = btrfs_check_data_free_space(inode, reserved, start, len);
5167         if (ret < 0)
5168                 return ret;
5169         ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
5170         if (ret < 0)
5171                 btrfs_free_reserved_data_space(inode, *reserved, start, len);
5172         return ret;
5173 }
5174
5175 /**
5176  * btrfs_delalloc_release_space - release data and metadata space for delalloc
5177  * @inode: inode we're releasing space for
5178  * @start: start position of the space already reserved
5179  * @len: the len of the space already reserved
5180  * @release_bytes: the len of the space we consumed or didn't use
5181  *
5182  * This function will release the metadata space that was not used and will
5183  * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
5184  * list if there are no delalloc bytes left.
5185  * Also it will handle the qgroup reserved space.
5186  */
5187 void btrfs_delalloc_release_space(struct inode *inode,
5188                                   struct extent_changeset *reserved,
5189                                   u64 start, u64 len, bool qgroup_free)
5190 {
5191         btrfs_delalloc_release_metadata(BTRFS_I(inode), len, qgroup_free);
5192         btrfs_free_reserved_data_space(inode, reserved, start, len);
5193 }
5194
5195 static int update_block_group(struct btrfs_trans_handle *trans,
5196                               u64 bytenr, u64 num_bytes, int alloc)
5197 {
5198         struct btrfs_fs_info *info = trans->fs_info;
5199         struct btrfs_block_group_cache *cache = NULL;
5200         u64 total = num_bytes;
5201         u64 old_val;
5202         u64 byte_in_group;
5203         int factor;
5204         int ret = 0;
5205
5206         /* block accounting for super block */
5207         spin_lock(&info->delalloc_root_lock);
5208         old_val = btrfs_super_bytes_used(info->super_copy);
5209         if (alloc)
5210                 old_val += num_bytes;
5211         else
5212                 old_val -= num_bytes;
5213         btrfs_set_super_bytes_used(info->super_copy, old_val);
5214         spin_unlock(&info->delalloc_root_lock);
5215
5216         while (total) {
5217                 cache = btrfs_lookup_block_group(info, bytenr);
5218                 if (!cache) {
5219                         ret = -ENOENT;
5220                         break;
5221                 }
5222                 factor = btrfs_bg_type_to_factor(cache->flags);
5223
5224                 /*
5225                  * If this block group has free space cache written out, we
5226                  * need to make sure to load it if we are removing space.  This
5227                  * is because we need the unpinning stage to actually add the
5228                  * space back to the block group, otherwise we will leak space.
5229                  */
5230                 if (!alloc && cache->cached == BTRFS_CACHE_NO)
5231                         cache_block_group(cache, 1);
5232
5233                 byte_in_group = bytenr - cache->key.objectid;
5234                 WARN_ON(byte_in_group > cache->key.offset);
5235
5236                 spin_lock(&cache->space_info->lock);
5237                 spin_lock(&cache->lock);
5238
5239                 if (btrfs_test_opt(info, SPACE_CACHE) &&
5240                     cache->disk_cache_state < BTRFS_DC_CLEAR)
5241                         cache->disk_cache_state = BTRFS_DC_CLEAR;
5242
5243                 old_val = btrfs_block_group_used(&cache->item);
5244                 num_bytes = min(total, cache->key.offset - byte_in_group);
5245                 if (alloc) {
5246                         old_val += num_bytes;
5247                         btrfs_set_block_group_used(&cache->item, old_val);
5248                         cache->reserved -= num_bytes;
5249                         cache->space_info->bytes_reserved -= num_bytes;
5250                         cache->space_info->bytes_used += num_bytes;
5251                         cache->space_info->disk_used += num_bytes * factor;
5252                         spin_unlock(&cache->lock);
5253                         spin_unlock(&cache->space_info->lock);
5254                 } else {
5255                         old_val -= num_bytes;
5256                         btrfs_set_block_group_used(&cache->item, old_val);
5257                         cache->pinned += num_bytes;
5258                         btrfs_space_info_update_bytes_pinned(info,
5259                                         cache->space_info, num_bytes);
5260                         cache->space_info->bytes_used -= num_bytes;
5261                         cache->space_info->disk_used -= num_bytes * factor;
5262                         spin_unlock(&cache->lock);
5263                         spin_unlock(&cache->space_info->lock);
5264
5265                         trace_btrfs_space_reservation(info, "pinned",
5266                                                       cache->space_info->flags,
5267                                                       num_bytes, 1);
5268                         percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
5269                                            num_bytes,
5270                                            BTRFS_TOTAL_BYTES_PINNED_BATCH);
5271                         set_extent_dirty(info->pinned_extents,
5272                                          bytenr, bytenr + num_bytes - 1,
5273                                          GFP_NOFS | __GFP_NOFAIL);
5274                 }
5275
5276                 spin_lock(&trans->transaction->dirty_bgs_lock);
5277                 if (list_empty(&cache->dirty_list)) {
5278                         list_add_tail(&cache->dirty_list,
5279                                       &trans->transaction->dirty_bgs);
5280                         trans->delayed_ref_updates++;
5281                         btrfs_get_block_group(cache);
5282                 }
5283                 spin_unlock(&trans->transaction->dirty_bgs_lock);
5284
5285                 /*
5286                  * No longer have used bytes in this block group, queue it for
5287                  * deletion. We do this after adding the block group to the
5288                  * dirty list to avoid races between cleaner kthread and space
5289                  * cache writeout.
5290                  */
5291                 if (!alloc && old_val == 0)
5292                         btrfs_mark_bg_unused(cache);
5293
5294                 btrfs_put_block_group(cache);
5295                 total -= num_bytes;
5296                 bytenr += num_bytes;
5297         }
5298
5299         /* Modified block groups are accounted for in the delayed_refs_rsv. */
5300         btrfs_update_delayed_refs_rsv(trans);
5301         return ret;
5302 }
5303
5304 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
5305 {
5306         struct btrfs_block_group_cache *cache;
5307         u64 bytenr;
5308
5309         spin_lock(&fs_info->block_group_cache_lock);
5310         bytenr = fs_info->first_logical_byte;
5311         spin_unlock(&fs_info->block_group_cache_lock);
5312
5313         if (bytenr < (u64)-1)
5314                 return bytenr;
5315
5316         cache = btrfs_lookup_first_block_group(fs_info, search_start);
5317         if (!cache)
5318                 return 0;
5319
5320         bytenr = cache->key.objectid;
5321         btrfs_put_block_group(cache);
5322
5323         return bytenr;
5324 }
5325
5326 static int pin_down_extent(struct btrfs_block_group_cache *cache,
5327                            u64 bytenr, u64 num_bytes, int reserved)
5328 {
5329         struct btrfs_fs_info *fs_info = cache->fs_info;
5330
5331         spin_lock(&cache->space_info->lock);
5332         spin_lock(&cache->lock);
5333         cache->pinned += num_bytes;
5334         btrfs_space_info_update_bytes_pinned(fs_info, cache->space_info,
5335                                              num_bytes);
5336         if (reserved) {
5337                 cache->reserved -= num_bytes;
5338                 cache->space_info->bytes_reserved -= num_bytes;
5339         }
5340         spin_unlock(&cache->lock);
5341         spin_unlock(&cache->space_info->lock);
5342
5343         trace_btrfs_space_reservation(fs_info, "pinned",
5344                                       cache->space_info->flags, num_bytes, 1);
5345         percpu_counter_add_batch(&cache->space_info->total_bytes_pinned,
5346                     num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
5347         set_extent_dirty(fs_info->pinned_extents, bytenr,
5348                          bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
5349         return 0;
5350 }
5351
5352 /*
5353  * this function must be called within transaction
5354  */
5355 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
5356                      u64 bytenr, u64 num_bytes, int reserved)
5357 {
5358         struct btrfs_block_group_cache *cache;
5359
5360         cache = btrfs_lookup_block_group(fs_info, bytenr);
5361         BUG_ON(!cache); /* Logic error */
5362
5363         pin_down_extent(cache, bytenr, num_bytes, reserved);
5364
5365         btrfs_put_block_group(cache);
5366         return 0;
5367 }
5368
5369 /*
5370  * this function must be called within transaction
5371  */
5372 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
5373                                     u64 bytenr, u64 num_bytes)
5374 {
5375         struct btrfs_block_group_cache *cache;
5376         int ret;
5377
5378         cache = btrfs_lookup_block_group(fs_info, bytenr);
5379         if (!cache)
5380                 return -EINVAL;
5381
5382         /*
5383          * pull in the free space cache (if any) so that our pin
5384          * removes the free space from the cache.  We have load_only set
5385          * to one because the slow code to read in the free extents does check
5386          * the pinned extents.
5387          */
5388         cache_block_group(cache, 1);
5389
5390         pin_down_extent(cache, bytenr, num_bytes, 0);
5391
5392         /* remove us from the free space cache (if we're there at all) */
5393         ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
5394         btrfs_put_block_group(cache);
5395         return ret;
5396 }
5397
5398 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
5399                                    u64 start, u64 num_bytes)
5400 {
5401         int ret;
5402         struct btrfs_block_group_cache *block_group;
5403         struct btrfs_caching_control *caching_ctl;
5404
5405         block_group = btrfs_lookup_block_group(fs_info, start);
5406         if (!block_group)
5407                 return -EINVAL;
5408
5409         cache_block_group(block_group, 0);
5410         caching_ctl = get_caching_control(block_group);
5411
5412         if (!caching_ctl) {
5413                 /* Logic error */
5414                 BUG_ON(!block_group_cache_done(block_group));
5415                 ret = btrfs_remove_free_space(block_group, start, num_bytes);
5416         } else {
5417                 mutex_lock(&caching_ctl->mutex);
5418
5419                 if (start >= caching_ctl->progress) {
5420                         ret = add_excluded_extent(fs_info, start, num_bytes);
5421                 } else if (start + num_bytes <= caching_ctl->progress) {
5422                         ret = btrfs_remove_free_space(block_group,
5423                                                       start, num_bytes);
5424                 } else {
5425                         num_bytes = caching_ctl->progress - start;
5426                         ret = btrfs_remove_free_space(block_group,
5427                                                       start, num_bytes);
5428                         if (ret)
5429                                 goto out_lock;
5430
5431                         num_bytes = (start + num_bytes) -
5432                                 caching_ctl->progress;
5433                         start = caching_ctl->progress;
5434                         ret = add_excluded_extent(fs_info, start, num_bytes);
5435                 }
5436 out_lock:
5437                 mutex_unlock(&caching_ctl->mutex);
5438                 put_caching_control(caching_ctl);
5439         }
5440         btrfs_put_block_group(block_group);
5441         return ret;
5442 }
5443
5444 int btrfs_exclude_logged_extents(struct extent_buffer *eb)
5445 {
5446         struct btrfs_fs_info *fs_info = eb->fs_info;
5447         struct btrfs_file_extent_item *item;
5448         struct btrfs_key key;
5449         int found_type;
5450         int i;
5451         int ret = 0;
5452
5453         if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
5454                 return 0;
5455
5456         for (i = 0; i < btrfs_header_nritems(eb); i++) {
5457                 btrfs_item_key_to_cpu(eb, &key, i);
5458                 if (key.type != BTRFS_EXTENT_DATA_KEY)
5459                         continue;
5460                 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
5461                 found_type = btrfs_file_extent_type(eb, item);
5462                 if (found_type == BTRFS_FILE_EXTENT_INLINE)
5463                         continue;
5464                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
5465                         continue;
5466                 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
5467                 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
5468                 ret = __exclude_logged_extent(fs_info, key.objectid, key.offset);
5469                 if (ret)
5470                         break;
5471         }
5472
5473         return ret;
5474 }
5475
5476 static void
5477 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
5478 {
5479         atomic_inc(&bg->reservations);
5480 }
5481
5482 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
5483                                         const u64 start)
5484 {
5485         struct btrfs_block_group_cache *bg;
5486
5487         bg = btrfs_lookup_block_group(fs_info, start);
5488         ASSERT(bg);
5489         if (atomic_dec_and_test(&bg->reservations))
5490                 wake_up_var(&bg->reservations);
5491         btrfs_put_block_group(bg);
5492 }
5493
5494 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
5495 {
5496         struct btrfs_space_info *space_info = bg->space_info;
5497
5498         ASSERT(bg->ro);
5499
5500         if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
5501                 return;
5502
5503         /*
5504          * Our block group is read only but before we set it to read only,
5505          * some task might have had allocated an extent from it already, but it
5506          * has not yet created a respective ordered extent (and added it to a
5507          * root's list of ordered extents).
5508          * Therefore wait for any task currently allocating extents, since the
5509          * block group's reservations counter is incremented while a read lock
5510          * on the groups' semaphore is held and decremented after releasing
5511          * the read access on that semaphore and creating the ordered extent.
5512          */
5513         down_write(&space_info->groups_sem);
5514         up_write(&space_info->groups_sem);
5515
5516         wait_var_event(&bg->reservations, !atomic_read(&bg->reservations));
5517 }
5518
5519 /**
5520  * btrfs_add_reserved_bytes - update the block_group and space info counters
5521  * @cache:      The cache we are manipulating
5522  * @ram_bytes:  The number of bytes of file content, and will be same to
5523  *              @num_bytes except for the compress path.
5524  * @num_bytes:  The number of bytes in question
5525  * @delalloc:   The blocks are allocated for the delalloc write
5526  *
5527  * This is called by the allocator when it reserves space. If this is a
5528  * reservation and the block group has become read only we cannot make the
5529  * reservation and return -EAGAIN, otherwise this function always succeeds.
5530  */
5531 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
5532                                     u64 ram_bytes, u64 num_bytes, int delalloc)
5533 {
5534         struct btrfs_space_info *space_info = cache->space_info;
5535         int ret = 0;
5536
5537         spin_lock(&space_info->lock);
5538         spin_lock(&cache->lock);
5539         if (cache->ro) {
5540                 ret = -EAGAIN;
5541         } else {
5542                 cache->reserved += num_bytes;
5543                 space_info->bytes_reserved += num_bytes;
5544                 btrfs_space_info_update_bytes_may_use(cache->fs_info,
5545                                                       space_info, -ram_bytes);
5546                 if (delalloc)
5547                         cache->delalloc_bytes += num_bytes;
5548         }
5549         spin_unlock(&cache->lock);
5550         spin_unlock(&space_info->lock);
5551         return ret;
5552 }
5553
5554 /**
5555  * btrfs_free_reserved_bytes - update the block_group and space info counters
5556  * @cache:      The cache we are manipulating
5557  * @num_bytes:  The number of bytes in question
5558  * @delalloc:   The blocks are allocated for the delalloc write
5559  *
5560  * This is called by somebody who is freeing space that was never actually used
5561  * on disk.  For example if you reserve some space for a new leaf in transaction
5562  * A and before transaction A commits you free that leaf, you call this with
5563  * reserve set to 0 in order to clear the reservation.
5564  */
5565
5566 static void btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
5567                                       u64 num_bytes, int delalloc)
5568 {
5569         struct btrfs_space_info *space_info = cache->space_info;
5570
5571         spin_lock(&space_info->lock);
5572         spin_lock(&cache->lock);
5573         if (cache->ro)
5574                 space_info->bytes_readonly += num_bytes;
5575         cache->reserved -= num_bytes;
5576         space_info->bytes_reserved -= num_bytes;
5577         space_info->max_extent_size = 0;
5578
5579         if (delalloc)
5580                 cache->delalloc_bytes -= num_bytes;
5581         spin_unlock(&cache->lock);
5582         spin_unlock(&space_info->lock);
5583 }
5584 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
5585 {
5586         struct btrfs_caching_control *next;
5587         struct btrfs_caching_control *caching_ctl;
5588         struct btrfs_block_group_cache *cache;
5589
5590         down_write(&fs_info->commit_root_sem);
5591
5592         list_for_each_entry_safe(caching_ctl, next,
5593                                  &fs_info->caching_block_groups, list) {
5594                 cache = caching_ctl->block_group;
5595                 if (block_group_cache_done(cache)) {
5596                         cache->last_byte_to_unpin = (u64)-1;
5597                         list_del_init(&caching_ctl->list);
5598                         put_caching_control(caching_ctl);
5599                 } else {
5600                         cache->last_byte_to_unpin = caching_ctl->progress;
5601                 }
5602         }
5603
5604         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5605                 fs_info->pinned_extents = &fs_info->freed_extents[1];
5606         else
5607                 fs_info->pinned_extents = &fs_info->freed_extents[0];
5608
5609         up_write(&fs_info->commit_root_sem);
5610
5611         update_global_block_rsv(fs_info);
5612 }
5613
5614 /*
5615  * Returns the free cluster for the given space info and sets empty_cluster to
5616  * what it should be based on the mount options.
5617  */
5618 static struct btrfs_free_cluster *
5619 fetch_cluster_info(struct btrfs_fs_info *fs_info,
5620                    struct btrfs_space_info *space_info, u64 *empty_cluster)
5621 {
5622         struct btrfs_free_cluster *ret = NULL;
5623
5624         *empty_cluster = 0;
5625         if (btrfs_mixed_space_info(space_info))
5626                 return ret;
5627
5628         if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5629                 ret = &fs_info->meta_alloc_cluster;
5630                 if (btrfs_test_opt(fs_info, SSD))
5631                         *empty_cluster = SZ_2M;
5632                 else
5633                         *empty_cluster = SZ_64K;
5634         } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
5635                    btrfs_test_opt(fs_info, SSD_SPREAD)) {
5636                 *empty_cluster = SZ_2M;
5637                 ret = &fs_info->data_alloc_cluster;
5638         }
5639
5640         return ret;
5641 }
5642
5643 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
5644                               u64 start, u64 end,
5645                               const bool return_free_space)
5646 {
5647         struct btrfs_block_group_cache *cache = NULL;
5648         struct btrfs_space_info *space_info;
5649         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5650         struct btrfs_free_cluster *cluster = NULL;
5651         u64 len;
5652         u64 total_unpinned = 0;
5653         u64 empty_cluster = 0;
5654         bool readonly;
5655
5656         while (start <= end) {
5657                 readonly = false;
5658                 if (!cache ||
5659                     start >= cache->key.objectid + cache->key.offset) {
5660                         if (cache)
5661                                 btrfs_put_block_group(cache);
5662                         total_unpinned = 0;
5663                         cache = btrfs_lookup_block_group(fs_info, start);
5664                         BUG_ON(!cache); /* Logic error */
5665
5666                         cluster = fetch_cluster_info(fs_info,
5667                                                      cache->space_info,
5668                                                      &empty_cluster);
5669                         empty_cluster <<= 1;
5670                 }
5671
5672                 len = cache->key.objectid + cache->key.offset - start;
5673                 len = min(len, end + 1 - start);
5674
5675                 if (start < cache->last_byte_to_unpin) {
5676                         len = min(len, cache->last_byte_to_unpin - start);
5677                         if (return_free_space)
5678                                 btrfs_add_free_space(cache, start, len);
5679                 }
5680
5681                 start += len;
5682                 total_unpinned += len;
5683                 space_info = cache->space_info;
5684
5685                 /*
5686                  * If this space cluster has been marked as fragmented and we've
5687                  * unpinned enough in this block group to potentially allow a
5688                  * cluster to be created inside of it go ahead and clear the
5689                  * fragmented check.
5690                  */
5691                 if (cluster && cluster->fragmented &&
5692                     total_unpinned > empty_cluster) {
5693                         spin_lock(&cluster->lock);
5694                         cluster->fragmented = 0;
5695                         spin_unlock(&cluster->lock);
5696                 }
5697
5698                 spin_lock(&space_info->lock);
5699                 spin_lock(&cache->lock);
5700                 cache->pinned -= len;
5701                 btrfs_space_info_update_bytes_pinned(fs_info, space_info, -len);
5702
5703                 trace_btrfs_space_reservation(fs_info, "pinned",
5704                                               space_info->flags, len, 0);
5705                 space_info->max_extent_size = 0;
5706                 percpu_counter_add_batch(&space_info->total_bytes_pinned,
5707                             -len, BTRFS_TOTAL_BYTES_PINNED_BATCH);
5708                 if (cache->ro) {
5709                         space_info->bytes_readonly += len;
5710                         readonly = true;
5711                 }
5712                 spin_unlock(&cache->lock);
5713                 if (!readonly && return_free_space &&
5714                     global_rsv->space_info == space_info) {
5715                         u64 to_add = len;
5716
5717                         spin_lock(&global_rsv->lock);
5718                         if (!global_rsv->full) {
5719                                 to_add = min(len, global_rsv->size -
5720                                              global_rsv->reserved);
5721                                 global_rsv->reserved += to_add;
5722                                 btrfs_space_info_update_bytes_may_use(fs_info,
5723                                                 space_info, to_add);
5724                                 if (global_rsv->reserved >= global_rsv->size)
5725                                         global_rsv->full = 1;
5726                                 trace_btrfs_space_reservation(fs_info,
5727                                                               "space_info",
5728                                                               space_info->flags,
5729                                                               to_add, 1);
5730                                 len -= to_add;
5731                         }
5732                         spin_unlock(&global_rsv->lock);
5733                         /* Add to any tickets we may have */
5734                         if (len)
5735                                 btrfs_space_info_add_new_bytes(fs_info,
5736                                                 space_info, len);
5737                 }
5738                 spin_unlock(&space_info->lock);
5739         }
5740
5741         if (cache)
5742                 btrfs_put_block_group(cache);
5743         return 0;
5744 }
5745
5746 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans)
5747 {
5748         struct btrfs_fs_info *fs_info = trans->fs_info;
5749         struct btrfs_block_group_cache *block_group, *tmp;
5750         struct list_head *deleted_bgs;
5751         struct extent_io_tree *unpin;
5752         u64 start;
5753         u64 end;
5754         int ret;
5755
5756         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5757                 unpin = &fs_info->freed_extents[1];
5758         else
5759                 unpin = &fs_info->freed_extents[0];
5760
5761         while (!trans->aborted) {
5762                 struct extent_state *cached_state = NULL;
5763
5764                 mutex_lock(&fs_info->unused_bg_unpin_mutex);
5765                 ret = find_first_extent_bit(unpin, 0, &start, &end,
5766                                             EXTENT_DIRTY, &cached_state);
5767                 if (ret) {
5768                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5769                         break;
5770                 }
5771
5772                 if (btrfs_test_opt(fs_info, DISCARD))
5773                         ret = btrfs_discard_extent(fs_info, start,
5774                                                    end + 1 - start, NULL);
5775
5776                 clear_extent_dirty(unpin, start, end, &cached_state);
5777                 unpin_extent_range(fs_info, start, end, true);
5778                 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
5779                 free_extent_state(cached_state);
5780                 cond_resched();
5781         }
5782
5783         /*
5784          * Transaction is finished.  We don't need the lock anymore.  We
5785          * do need to clean up the block groups in case of a transaction
5786          * abort.
5787          */
5788         deleted_bgs = &trans->transaction->deleted_bgs;
5789         list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
5790                 u64 trimmed = 0;
5791
5792                 ret = -EROFS;
5793                 if (!trans->aborted)
5794                         ret = btrfs_discard_extent(fs_info,
5795                                                    block_group->key.objectid,
5796                                                    block_group->key.offset,
5797                                                    &trimmed);
5798
5799                 list_del_init(&block_group->bg_list);
5800                 btrfs_put_block_group_trimming(block_group);
5801                 btrfs_put_block_group(block_group);
5802
5803                 if (ret) {
5804                         const char *errstr = btrfs_decode_error(ret);
5805                         btrfs_warn(fs_info,
5806                            "discard failed while removing blockgroup: errno=%d %s",
5807                                    ret, errstr);
5808                 }
5809         }
5810
5811         return 0;
5812 }
5813
5814 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
5815                                struct btrfs_delayed_ref_node *node, u64 parent,
5816                                u64 root_objectid, u64 owner_objectid,
5817                                u64 owner_offset, int refs_to_drop,
5818                                struct btrfs_delayed_extent_op *extent_op)
5819 {
5820         struct btrfs_fs_info *info = trans->fs_info;
5821         struct btrfs_key key;
5822         struct btrfs_path *path;
5823         struct btrfs_root *extent_root = info->extent_root;
5824         struct extent_buffer *leaf;
5825         struct btrfs_extent_item *ei;
5826         struct btrfs_extent_inline_ref *iref;
5827         int ret;
5828         int is_data;
5829         int extent_slot = 0;
5830         int found_extent = 0;
5831         int num_to_del = 1;
5832         u32 item_size;
5833         u64 refs;
5834         u64 bytenr = node->bytenr;
5835         u64 num_bytes = node->num_bytes;
5836         int last_ref = 0;
5837         bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
5838
5839         path = btrfs_alloc_path();
5840         if (!path)
5841                 return -ENOMEM;
5842
5843         path->reada = READA_FORWARD;
5844         path->leave_spinning = 1;
5845
5846         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
5847         BUG_ON(!is_data && refs_to_drop != 1);
5848
5849         if (is_data)
5850                 skinny_metadata = false;
5851
5852         ret = lookup_extent_backref(trans, path, &iref, bytenr, num_bytes,
5853                                     parent, root_objectid, owner_objectid,
5854                                     owner_offset);
5855         if (ret == 0) {
5856                 extent_slot = path->slots[0];
5857                 while (extent_slot >= 0) {
5858                         btrfs_item_key_to_cpu(path->nodes[0], &key,
5859                                               extent_slot);
5860                         if (key.objectid != bytenr)
5861                                 break;
5862                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5863                             key.offset == num_bytes) {
5864                                 found_extent = 1;
5865                                 break;
5866                         }
5867                         if (key.type == BTRFS_METADATA_ITEM_KEY &&
5868                             key.offset == owner_objectid) {
5869                                 found_extent = 1;
5870                                 break;
5871                         }
5872                         if (path->slots[0] - extent_slot > 5)
5873                                 break;
5874                         extent_slot--;
5875                 }
5876
5877                 if (!found_extent) {
5878                         BUG_ON(iref);
5879                         ret = remove_extent_backref(trans, path, NULL,
5880                                                     refs_to_drop,
5881                                                     is_data, &last_ref);
5882                         if (ret) {
5883                                 btrfs_abort_transaction(trans, ret);
5884                                 goto out;
5885                         }
5886                         btrfs_release_path(path);
5887                         path->leave_spinning = 1;
5888
5889                         key.objectid = bytenr;
5890                         key.type = BTRFS_EXTENT_ITEM_KEY;
5891                         key.offset = num_bytes;
5892
5893                         if (!is_data && skinny_metadata) {
5894                                 key.type = BTRFS_METADATA_ITEM_KEY;
5895                                 key.offset = owner_objectid;
5896                         }
5897
5898                         ret = btrfs_search_slot(trans, extent_root,
5899                                                 &key, path, -1, 1);
5900                         if (ret > 0 && skinny_metadata && path->slots[0]) {
5901                                 /*
5902                                  * Couldn't find our skinny metadata item,
5903                                  * see if we have ye olde extent item.
5904                                  */
5905                                 path->slots[0]--;
5906                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
5907                                                       path->slots[0]);
5908                                 if (key.objectid == bytenr &&
5909                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
5910                                     key.offset == num_bytes)
5911                                         ret = 0;
5912                         }
5913
5914                         if (ret > 0 && skinny_metadata) {
5915                                 skinny_metadata = false;
5916                                 key.objectid = bytenr;
5917                                 key.type = BTRFS_EXTENT_ITEM_KEY;
5918                                 key.offset = num_bytes;
5919                                 btrfs_release_path(path);
5920                                 ret = btrfs_search_slot(trans, extent_root,
5921                                                         &key, path, -1, 1);
5922                         }
5923
5924                         if (ret) {
5925                                 btrfs_err(info,
5926                                           "umm, got %d back from search, was looking for %llu",
5927                                           ret, bytenr);
5928                                 if (ret > 0)
5929                                         btrfs_print_leaf(path->nodes[0]);
5930                         }
5931                         if (ret < 0) {
5932                                 btrfs_abort_transaction(trans, ret);
5933                                 goto out;
5934                         }
5935                         extent_slot = path->slots[0];
5936                 }
5937         } else if (WARN_ON(ret == -ENOENT)) {
5938                 btrfs_print_leaf(path->nodes[0]);
5939                 btrfs_err(info,
5940                         "unable to find ref byte nr %llu parent %llu root %llu  owner %llu offset %llu",
5941                         bytenr, parent, root_objectid, owner_objectid,
5942                         owner_offset);
5943                 btrfs_abort_transaction(trans, ret);
5944                 goto out;
5945         } else {
5946                 btrfs_abort_transaction(trans, ret);
5947                 goto out;
5948         }
5949
5950         leaf = path->nodes[0];
5951         item_size = btrfs_item_size_nr(leaf, extent_slot);
5952         if (unlikely(item_size < sizeof(*ei))) {
5953                 ret = -EINVAL;
5954                 btrfs_print_v0_err(info);
5955                 btrfs_abort_transaction(trans, ret);
5956                 goto out;
5957         }
5958         ei = btrfs_item_ptr(leaf, extent_slot,
5959                             struct btrfs_extent_item);
5960         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
5961             key.type == BTRFS_EXTENT_ITEM_KEY) {
5962                 struct btrfs_tree_block_info *bi;
5963                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
5964                 bi = (struct btrfs_tree_block_info *)(ei + 1);
5965                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
5966         }
5967
5968         refs = btrfs_extent_refs(leaf, ei);
5969         if (refs < refs_to_drop) {
5970                 btrfs_err(info,
5971                           "trying to drop %d refs but we only have %Lu for bytenr %Lu",
5972                           refs_to_drop, refs, bytenr);
5973                 ret = -EINVAL;
5974                 btrfs_abort_transaction(trans, ret);
5975                 goto out;
5976         }
5977         refs -= refs_to_drop;
5978
5979         if (refs > 0) {
5980                 if (extent_op)
5981                         __run_delayed_extent_op(extent_op, leaf, ei);
5982                 /*
5983                  * In the case of inline back ref, reference count will
5984                  * be updated by remove_extent_backref
5985                  */
5986                 if (iref) {
5987                         BUG_ON(!found_extent);
5988                 } else {
5989                         btrfs_set_extent_refs(leaf, ei, refs);
5990                         btrfs_mark_buffer_dirty(leaf);
5991                 }
5992                 if (found_extent) {
5993                         ret = remove_extent_backref(trans, path, iref,
5994                                                     refs_to_drop, is_data,
5995                                                     &last_ref);
5996                         if (ret) {
5997                                 btrfs_abort_transaction(trans, ret);
5998                                 goto out;
5999                         }
6000                 }
6001         } else {
6002                 if (found_extent) {
6003                         BUG_ON(is_data && refs_to_drop !=
6004                                extent_data_ref_count(path, iref));
6005                         if (iref) {
6006                                 BUG_ON(path->slots[0] != extent_slot);
6007                         } else {
6008                                 BUG_ON(path->slots[0] != extent_slot + 1);
6009                                 path->slots[0] = extent_slot;
6010                                 num_to_del = 2;
6011                         }
6012                 }
6013
6014                 last_ref = 1;
6015                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
6016                                       num_to_del);
6017                 if (ret) {
6018                         btrfs_abort_transaction(trans, ret);
6019                         goto out;
6020                 }
6021                 btrfs_release_path(path);
6022
6023                 if (is_data) {
6024                         ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
6025                         if (ret) {
6026                                 btrfs_abort_transaction(trans, ret);
6027                                 goto out;
6028                         }
6029                 }
6030
6031                 ret = add_to_free_space_tree(trans, bytenr, num_bytes);
6032                 if (ret) {
6033                         btrfs_abort_transaction(trans, ret);
6034                         goto out;
6035                 }
6036
6037                 ret = update_block_group(trans, bytenr, num_bytes, 0);
6038                 if (ret) {
6039                         btrfs_abort_transaction(trans, ret);
6040                         goto out;
6041                 }
6042         }
6043         btrfs_release_path(path);
6044
6045 out:
6046         btrfs_free_path(path);
6047         return ret;
6048 }
6049
6050 /*
6051  * when we free an block, it is possible (and likely) that we free the last
6052  * delayed ref for that extent as well.  This searches the delayed ref tree for
6053  * a given extent, and if there are no other delayed refs to be processed, it
6054  * removes it from the tree.
6055  */
6056 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
6057                                       u64 bytenr)
6058 {
6059         struct btrfs_delayed_ref_head *head;
6060         struct btrfs_delayed_ref_root *delayed_refs;
6061         int ret = 0;
6062
6063         delayed_refs = &trans->transaction->delayed_refs;
6064         spin_lock(&delayed_refs->lock);
6065         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
6066         if (!head)
6067                 goto out_delayed_unlock;
6068
6069         spin_lock(&head->lock);
6070         if (!RB_EMPTY_ROOT(&head->ref_tree.rb_root))
6071                 goto out;
6072
6073         if (cleanup_extent_op(head) != NULL)
6074                 goto out;
6075
6076         /*
6077          * waiting for the lock here would deadlock.  If someone else has it
6078          * locked they are already in the process of dropping it anyway
6079          */
6080         if (!mutex_trylock(&head->mutex))
6081                 goto out;
6082
6083         btrfs_delete_ref_head(delayed_refs, head);
6084         head->processing = 0;
6085
6086         spin_unlock(&head->lock);
6087         spin_unlock(&delayed_refs->lock);
6088
6089         BUG_ON(head->extent_op);
6090         if (head->must_insert_reserved)
6091                 ret = 1;
6092
6093         btrfs_cleanup_ref_head_accounting(trans->fs_info, delayed_refs, head);
6094         mutex_unlock(&head->mutex);
6095         btrfs_put_delayed_ref_head(head);
6096         return ret;
6097 out:
6098         spin_unlock(&head->lock);
6099
6100 out_delayed_unlock:
6101         spin_unlock(&delayed_refs->lock);
6102         return 0;
6103 }
6104
6105 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
6106                            struct btrfs_root *root,
6107                            struct extent_buffer *buf,
6108                            u64 parent, int last_ref)
6109 {
6110         struct btrfs_fs_info *fs_info = root->fs_info;
6111         struct btrfs_ref generic_ref = { 0 };
6112         int pin = 1;
6113         int ret;
6114
6115         btrfs_init_generic_ref(&generic_ref, BTRFS_DROP_DELAYED_REF,
6116                                buf->start, buf->len, parent);
6117         btrfs_init_tree_ref(&generic_ref, btrfs_header_level(buf),
6118                             root->root_key.objectid);
6119
6120         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6121                 int old_ref_mod, new_ref_mod;
6122
6123                 btrfs_ref_tree_mod(fs_info, &generic_ref);
6124                 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref, NULL,
6125                                                  &old_ref_mod, &new_ref_mod);
6126                 BUG_ON(ret); /* -ENOMEM */
6127                 pin = old_ref_mod >= 0 && new_ref_mod < 0;
6128         }
6129
6130         if (last_ref && btrfs_header_generation(buf) == trans->transid) {
6131                 struct btrfs_block_group_cache *cache;
6132
6133                 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6134                         ret = check_ref_cleanup(trans, buf->start);
6135                         if (!ret)
6136                                 goto out;
6137                 }
6138
6139                 pin = 0;
6140                 cache = btrfs_lookup_block_group(fs_info, buf->start);
6141
6142                 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
6143                         pin_down_extent(cache, buf->start, buf->len, 1);
6144                         btrfs_put_block_group(cache);
6145                         goto out;
6146                 }
6147
6148                 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
6149
6150                 btrfs_add_free_space(cache, buf->start, buf->len);
6151                 btrfs_free_reserved_bytes(cache, buf->len, 0);
6152                 btrfs_put_block_group(cache);
6153                 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
6154         }
6155 out:
6156         if (pin)
6157                 add_pinned_bytes(fs_info, &generic_ref);
6158
6159         if (last_ref) {
6160                 /*
6161                  * Deleting the buffer, clear the corrupt flag since it doesn't
6162                  * matter anymore.
6163                  */
6164                 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
6165         }
6166 }
6167
6168 /* Can return -ENOMEM */
6169 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_ref *ref)
6170 {
6171         struct btrfs_fs_info *fs_info = trans->fs_info;
6172         int old_ref_mod, new_ref_mod;
6173         int ret;
6174
6175         if (btrfs_is_testing(fs_info))
6176                 return 0;
6177
6178         /*
6179          * tree log blocks never actually go into the extent allocation
6180          * tree, just update pinning info and exit early.
6181          */
6182         if ((ref->type == BTRFS_REF_METADATA &&
6183              ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
6184             (ref->type == BTRFS_REF_DATA &&
6185              ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)) {
6186                 /* unlocks the pinned mutex */
6187                 btrfs_pin_extent(fs_info, ref->bytenr, ref->len, 1);
6188                 old_ref_mod = new_ref_mod = 0;
6189                 ret = 0;
6190         } else if (ref->type == BTRFS_REF_METADATA) {
6191                 ret = btrfs_add_delayed_tree_ref(trans, ref, NULL,
6192                                                  &old_ref_mod, &new_ref_mod);
6193         } else {
6194                 ret = btrfs_add_delayed_data_ref(trans, ref, 0,
6195                                                  &old_ref_mod, &new_ref_mod);
6196         }
6197
6198         if (!((ref->type == BTRFS_REF_METADATA &&
6199                ref->tree_ref.root == BTRFS_TREE_LOG_OBJECTID) ||
6200               (ref->type == BTRFS_REF_DATA &&
6201                ref->data_ref.ref_root == BTRFS_TREE_LOG_OBJECTID)))
6202                 btrfs_ref_tree_mod(fs_info, ref);
6203
6204         if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
6205                 add_pinned_bytes(fs_info, ref);
6206
6207         return ret;
6208 }
6209
6210 /*
6211  * when we wait for progress in the block group caching, its because
6212  * our allocation attempt failed at least once.  So, we must sleep
6213  * and let some progress happen before we try again.
6214  *
6215  * This function will sleep at least once waiting for new free space to
6216  * show up, and then it will check the block group free space numbers
6217  * for our min num_bytes.  Another option is to have it go ahead
6218  * and look in the rbtree for a free extent of a given size, but this
6219  * is a good start.
6220  *
6221  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
6222  * any of the information in this block group.
6223  */
6224 static noinline void
6225 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
6226                                 u64 num_bytes)
6227 {
6228         struct btrfs_caching_control *caching_ctl;
6229
6230         caching_ctl = get_caching_control(cache);
6231         if (!caching_ctl)
6232                 return;
6233
6234         wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
6235                    (cache->free_space_ctl->free_space >= num_bytes));
6236
6237         put_caching_control(caching_ctl);
6238 }
6239
6240 static noinline int
6241 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
6242 {
6243         struct btrfs_caching_control *caching_ctl;
6244         int ret = 0;
6245
6246         caching_ctl = get_caching_control(cache);
6247         if (!caching_ctl)
6248                 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
6249
6250         wait_event(caching_ctl->wait, block_group_cache_done(cache));
6251         if (cache->cached == BTRFS_CACHE_ERROR)
6252                 ret = -EIO;
6253         put_caching_control(caching_ctl);
6254         return ret;
6255 }
6256
6257 enum btrfs_loop_type {
6258         LOOP_CACHING_NOWAIT,
6259         LOOP_CACHING_WAIT,
6260         LOOP_ALLOC_CHUNK,
6261         LOOP_NO_EMPTY_SIZE,
6262 };
6263
6264 static inline void
6265 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
6266                        int delalloc)
6267 {
6268         if (delalloc)
6269                 down_read(&cache->data_rwsem);
6270 }
6271
6272 static inline void
6273 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
6274                        int delalloc)
6275 {
6276         btrfs_get_block_group(cache);
6277         if (delalloc)
6278                 down_read(&cache->data_rwsem);
6279 }
6280
6281 static struct btrfs_block_group_cache *
6282 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
6283                    struct btrfs_free_cluster *cluster,
6284                    int delalloc)
6285 {
6286         struct btrfs_block_group_cache *used_bg = NULL;
6287
6288         spin_lock(&cluster->refill_lock);
6289         while (1) {
6290                 used_bg = cluster->block_group;
6291                 if (!used_bg)
6292                         return NULL;
6293
6294                 if (used_bg == block_group)
6295                         return used_bg;
6296
6297                 btrfs_get_block_group(used_bg);
6298
6299                 if (!delalloc)
6300                         return used_bg;
6301
6302                 if (down_read_trylock(&used_bg->data_rwsem))
6303                         return used_bg;
6304
6305                 spin_unlock(&cluster->refill_lock);
6306
6307                 /* We should only have one-level nested. */
6308                 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
6309
6310                 spin_lock(&cluster->refill_lock);
6311                 if (used_bg == cluster->block_group)
6312                         return used_bg;
6313
6314                 up_read(&used_bg->data_rwsem);
6315                 btrfs_put_block_group(used_bg);
6316         }
6317 }
6318
6319 static inline void
6320 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
6321                          int delalloc)
6322 {
6323         if (delalloc)
6324                 up_read(&cache->data_rwsem);
6325         btrfs_put_block_group(cache);
6326 }
6327
6328 /*
6329  * Structure used internally for find_free_extent() function.  Wraps needed
6330  * parameters.
6331  */
6332 struct find_free_extent_ctl {
6333         /* Basic allocation info */
6334         u64 ram_bytes;
6335         u64 num_bytes;
6336         u64 empty_size;
6337         u64 flags;
6338         int delalloc;
6339
6340         /* Where to start the search inside the bg */
6341         u64 search_start;
6342
6343         /* For clustered allocation */
6344         u64 empty_cluster;
6345
6346         bool have_caching_bg;
6347         bool orig_have_caching_bg;
6348
6349         /* RAID index, converted from flags */
6350         int index;
6351
6352         /*
6353          * Current loop number, check find_free_extent_update_loop() for details
6354          */
6355         int loop;
6356
6357         /*
6358          * Whether we're refilling a cluster, if true we need to re-search
6359          * current block group but don't try to refill the cluster again.
6360          */
6361         bool retry_clustered;
6362
6363         /*
6364          * Whether we're updating free space cache, if true we need to re-search
6365          * current block group but don't try updating free space cache again.
6366          */
6367         bool retry_unclustered;
6368
6369         /* If current block group is cached */
6370         int cached;
6371
6372         /* Max contiguous hole found */
6373         u64 max_extent_size;
6374
6375         /* Total free space from free space cache, not always contiguous */
6376         u64 total_free_space;
6377
6378         /* Found result */
6379         u64 found_offset;
6380 };
6381
6382
6383 /*
6384  * Helper function for find_free_extent().
6385  *
6386  * Return -ENOENT to inform caller that we need fallback to unclustered mode.
6387  * Return -EAGAIN to inform caller that we need to re-search this block group
6388  * Return >0 to inform caller that we find nothing
6389  * Return 0 means we have found a location and set ffe_ctl->found_offset.
6390  */
6391 static int find_free_extent_clustered(struct btrfs_block_group_cache *bg,
6392                 struct btrfs_free_cluster *last_ptr,
6393                 struct find_free_extent_ctl *ffe_ctl,
6394                 struct btrfs_block_group_cache **cluster_bg_ret)
6395 {
6396         struct btrfs_block_group_cache *cluster_bg;
6397         u64 aligned_cluster;
6398         u64 offset;
6399         int ret;
6400
6401         cluster_bg = btrfs_lock_cluster(bg, last_ptr, ffe_ctl->delalloc);
6402         if (!cluster_bg)
6403                 goto refill_cluster;
6404         if (cluster_bg != bg && (cluster_bg->ro ||
6405             !block_group_bits(cluster_bg, ffe_ctl->flags)))
6406                 goto release_cluster;
6407
6408         offset = btrfs_alloc_from_cluster(cluster_bg, last_ptr,
6409                         ffe_ctl->num_bytes, cluster_bg->key.objectid,
6410                         &ffe_ctl->max_extent_size);
6411         if (offset) {
6412                 /* We have a block, we're done */
6413                 spin_unlock(&last_ptr->refill_lock);
6414                 trace_btrfs_reserve_extent_cluster(cluster_bg,
6415                                 ffe_ctl->search_start, ffe_ctl->num_bytes);
6416                 *cluster_bg_ret = cluster_bg;
6417                 ffe_ctl->found_offset = offset;
6418                 return 0;
6419         }
6420         WARN_ON(last_ptr->block_group != cluster_bg);
6421
6422 release_cluster:
6423         /*
6424          * If we are on LOOP_NO_EMPTY_SIZE, we can't set up a new clusters, so
6425          * lets just skip it and let the allocator find whatever block it can
6426          * find. If we reach this point, we will have tried the cluster
6427          * allocator plenty of times and not have found anything, so we are
6428          * likely way too fragmented for the clustering stuff to find anything.
6429          *
6430          * However, if the cluster is taken from the current block group,
6431          * release the cluster first, so that we stand a better chance of
6432          * succeeding in the unclustered allocation.
6433          */
6434         if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE && cluster_bg != bg) {
6435                 spin_unlock(&last_ptr->refill_lock);
6436                 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
6437                 return -ENOENT;
6438         }
6439
6440         /* This cluster didn't work out, free it and start over */
6441         btrfs_return_cluster_to_free_space(NULL, last_ptr);
6442
6443         if (cluster_bg != bg)
6444                 btrfs_release_block_group(cluster_bg, ffe_ctl->delalloc);
6445
6446 refill_cluster:
6447         if (ffe_ctl->loop >= LOOP_NO_EMPTY_SIZE) {
6448                 spin_unlock(&last_ptr->refill_lock);
6449                 return -ENOENT;
6450         }
6451
6452         aligned_cluster = max_t(u64,
6453                         ffe_ctl->empty_cluster + ffe_ctl->empty_size,
6454                         bg->full_stripe_len);
6455         ret = btrfs_find_space_cluster(bg, last_ptr, ffe_ctl->search_start,
6456                         ffe_ctl->num_bytes, aligned_cluster);
6457         if (ret == 0) {
6458                 /* Now pull our allocation out of this cluster */
6459                 offset = btrfs_alloc_from_cluster(bg, last_ptr,
6460                                 ffe_ctl->num_bytes, ffe_ctl->search_start,
6461                                 &ffe_ctl->max_extent_size);
6462                 if (offset) {
6463                         /* We found one, proceed */
6464                         spin_unlock(&last_ptr->refill_lock);
6465                         trace_btrfs_reserve_extent_cluster(bg,
6466                                         ffe_ctl->search_start,
6467                                         ffe_ctl->num_bytes);
6468                         ffe_ctl->found_offset = offset;
6469                         return 0;
6470                 }
6471         } else if (!ffe_ctl->cached && ffe_ctl->loop > LOOP_CACHING_NOWAIT &&
6472                    !ffe_ctl->retry_clustered) {
6473                 spin_unlock(&last_ptr->refill_lock);
6474
6475                 ffe_ctl->retry_clustered = true;
6476                 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
6477                                 ffe_ctl->empty_cluster + ffe_ctl->empty_size);
6478                 return -EAGAIN;
6479         }
6480         /*
6481          * At this point we either didn't find a cluster or we weren't able to
6482          * allocate a block from our cluster.  Free the cluster we've been
6483          * trying to use, and go to the next block group.
6484          */
6485         btrfs_return_cluster_to_free_space(NULL, last_ptr);
6486         spin_unlock(&last_ptr->refill_lock);
6487         return 1;
6488 }
6489
6490 /*
6491  * Return >0 to inform caller that we find nothing
6492  * Return 0 when we found an free extent and set ffe_ctrl->found_offset
6493  * Return -EAGAIN to inform caller that we need to re-search this block group
6494  */
6495 static int find_free_extent_unclustered(struct btrfs_block_group_cache *bg,
6496                 struct btrfs_free_cluster *last_ptr,
6497                 struct find_free_extent_ctl *ffe_ctl)
6498 {
6499         u64 offset;
6500
6501         /*
6502          * We are doing an unclustered allocation, set the fragmented flag so
6503          * we don't bother trying to setup a cluster again until we get more
6504          * space.
6505          */
6506         if (unlikely(last_ptr)) {
6507                 spin_lock(&last_ptr->lock);
6508                 last_ptr->fragmented = 1;
6509                 spin_unlock(&last_ptr->lock);
6510         }
6511         if (ffe_ctl->cached) {
6512                 struct btrfs_free_space_ctl *free_space_ctl;
6513
6514                 free_space_ctl = bg->free_space_ctl;
6515                 spin_lock(&free_space_ctl->tree_lock);
6516                 if (free_space_ctl->free_space <
6517                     ffe_ctl->num_bytes + ffe_ctl->empty_cluster +
6518                     ffe_ctl->empty_size) {
6519                         ffe_ctl->total_free_space = max_t(u64,
6520                                         ffe_ctl->total_free_space,
6521                                         free_space_ctl->free_space);
6522                         spin_unlock(&free_space_ctl->tree_lock);
6523                         return 1;
6524                 }
6525                 spin_unlock(&free_space_ctl->tree_lock);
6526         }
6527
6528         offset = btrfs_find_space_for_alloc(bg, ffe_ctl->search_start,
6529                         ffe_ctl->num_bytes, ffe_ctl->empty_size,
6530                         &ffe_ctl->max_extent_size);
6531
6532         /*
6533          * If we didn't find a chunk, and we haven't failed on this block group
6534          * before, and this block group is in the middle of caching and we are
6535          * ok with waiting, then go ahead and wait for progress to be made, and
6536          * set @retry_unclustered to true.
6537          *
6538          * If @retry_unclustered is true then we've already waited on this
6539          * block group once and should move on to the next block group.
6540          */
6541         if (!offset && !ffe_ctl->retry_unclustered && !ffe_ctl->cached &&
6542             ffe_ctl->loop > LOOP_CACHING_NOWAIT) {
6543                 wait_block_group_cache_progress(bg, ffe_ctl->num_bytes +
6544                                                 ffe_ctl->empty_size);
6545                 ffe_ctl->retry_unclustered = true;
6546                 return -EAGAIN;
6547         } else if (!offset) {
6548                 return 1;
6549         }
6550         ffe_ctl->found_offset = offset;
6551         return 0;
6552 }
6553
6554 /*
6555  * Return >0 means caller needs to re-search for free extent
6556  * Return 0 means we have the needed free extent.
6557  * Return <0 means we failed to locate any free extent.
6558  */
6559 static int find_free_extent_update_loop(struct btrfs_fs_info *fs_info,
6560                                         struct btrfs_free_cluster *last_ptr,
6561                                         struct btrfs_key *ins,
6562                                         struct find_free_extent_ctl *ffe_ctl,
6563                                         int full_search, bool use_cluster)
6564 {
6565         struct btrfs_root *root = fs_info->extent_root;
6566         int ret;
6567
6568         if ((ffe_ctl->loop == LOOP_CACHING_NOWAIT) &&
6569             ffe_ctl->have_caching_bg && !ffe_ctl->orig_have_caching_bg)
6570                 ffe_ctl->orig_have_caching_bg = true;
6571
6572         if (!ins->objectid && ffe_ctl->loop >= LOOP_CACHING_WAIT &&
6573             ffe_ctl->have_caching_bg)
6574                 return 1;
6575
6576         if (!ins->objectid && ++(ffe_ctl->index) < BTRFS_NR_RAID_TYPES)
6577                 return 1;
6578
6579         if (ins->objectid) {
6580                 if (!use_cluster && last_ptr) {
6581                         spin_lock(&last_ptr->lock);
6582                         last_ptr->window_start = ins->objectid;
6583                         spin_unlock(&last_ptr->lock);
6584                 }
6585                 return 0;
6586         }
6587
6588         /*
6589          * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
6590          *                      caching kthreads as we move along
6591          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
6592          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
6593          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
6594          *                     again
6595          */
6596         if (ffe_ctl->loop < LOOP_NO_EMPTY_SIZE) {
6597                 ffe_ctl->index = 0;
6598                 if (ffe_ctl->loop == LOOP_CACHING_NOWAIT) {
6599                         /*
6600                          * We want to skip the LOOP_CACHING_WAIT step if we
6601                          * don't have any uncached bgs and we've already done a
6602                          * full search through.
6603                          */
6604                         if (ffe_ctl->orig_have_caching_bg || !full_search)
6605                                 ffe_ctl->loop = LOOP_CACHING_WAIT;
6606                         else
6607                                 ffe_ctl->loop = LOOP_ALLOC_CHUNK;
6608                 } else {
6609                         ffe_ctl->loop++;
6610                 }
6611
6612                 if (ffe_ctl->loop == LOOP_ALLOC_CHUNK) {
6613                         struct btrfs_trans_handle *trans;
6614                         int exist = 0;
6615
6616                         trans = current->journal_info;
6617                         if (trans)
6618                                 exist = 1;
6619                         else
6620                                 trans = btrfs_join_transaction(root);
6621
6622                         if (IS_ERR(trans)) {
6623                                 ret = PTR_ERR(trans);
6624                                 return ret;
6625                         }
6626
6627                         ret = btrfs_chunk_alloc(trans, ffe_ctl->flags,
6628                                                 CHUNK_ALLOC_FORCE);
6629
6630                         /*
6631                          * If we can't allocate a new chunk we've already looped
6632                          * through at least once, move on to the NO_EMPTY_SIZE
6633                          * case.
6634                          */
6635                         if (ret == -ENOSPC)
6636                                 ffe_ctl->loop = LOOP_NO_EMPTY_SIZE;
6637
6638                         /* Do not bail out on ENOSPC since we can do more. */
6639                         if (ret < 0 && ret != -ENOSPC)
6640                                 btrfs_abort_transaction(trans, ret);
6641                         else
6642                                 ret = 0;
6643                         if (!exist)
6644                                 btrfs_end_transaction(trans);
6645                         if (ret)
6646                                 return ret;
6647                 }
6648
6649                 if (ffe_ctl->loop == LOOP_NO_EMPTY_SIZE) {
6650                         /*
6651                          * Don't loop again if we already have no empty_size and
6652                          * no empty_cluster.
6653                          */
6654                         if (ffe_ctl->empty_size == 0 &&
6655                             ffe_ctl->empty_cluster == 0)
6656                                 return -ENOSPC;
6657                         ffe_ctl->empty_size = 0;
6658                         ffe_ctl->empty_cluster = 0;
6659                 }
6660                 return 1;
6661         }
6662         return -ENOSPC;
6663 }
6664
6665 /*
6666  * walks the btree of allocated extents and find a hole of a given size.
6667  * The key ins is changed to record the hole:
6668  * ins->objectid == start position
6669  * ins->flags = BTRFS_EXTENT_ITEM_KEY
6670  * ins->offset == the size of the hole.
6671  * Any available blocks before search_start are skipped.
6672  *
6673  * If there is no suitable free space, we will record the max size of
6674  * the free space extent currently.
6675  *
6676  * The overall logic and call chain:
6677  *
6678  * find_free_extent()
6679  * |- Iterate through all block groups
6680  * |  |- Get a valid block group
6681  * |  |- Try to do clustered allocation in that block group
6682  * |  |- Try to do unclustered allocation in that block group
6683  * |  |- Check if the result is valid
6684  * |  |  |- If valid, then exit
6685  * |  |- Jump to next block group
6686  * |
6687  * |- Push harder to find free extents
6688  *    |- If not found, re-iterate all block groups
6689  */
6690 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
6691                                 u64 ram_bytes, u64 num_bytes, u64 empty_size,
6692                                 u64 hint_byte, struct btrfs_key *ins,
6693                                 u64 flags, int delalloc)
6694 {
6695         int ret = 0;
6696         struct btrfs_free_cluster *last_ptr = NULL;
6697         struct btrfs_block_group_cache *block_group = NULL;
6698         struct find_free_extent_ctl ffe_ctl = {0};
6699         struct btrfs_space_info *space_info;
6700         bool use_cluster = true;
6701         bool full_search = false;
6702
6703         WARN_ON(num_bytes < fs_info->sectorsize);
6704
6705         ffe_ctl.ram_bytes = ram_bytes;
6706         ffe_ctl.num_bytes = num_bytes;
6707         ffe_ctl.empty_size = empty_size;
6708         ffe_ctl.flags = flags;
6709         ffe_ctl.search_start = 0;
6710         ffe_ctl.retry_clustered = false;
6711         ffe_ctl.retry_unclustered = false;
6712         ffe_ctl.delalloc = delalloc;
6713         ffe_ctl.index = btrfs_bg_flags_to_raid_index(flags);
6714         ffe_ctl.have_caching_bg = false;
6715         ffe_ctl.orig_have_caching_bg = false;
6716         ffe_ctl.found_offset = 0;
6717
6718         ins->type = BTRFS_EXTENT_ITEM_KEY;
6719         ins->objectid = 0;
6720         ins->offset = 0;
6721
6722         trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
6723
6724         space_info = btrfs_find_space_info(fs_info, flags);
6725         if (!space_info) {
6726                 btrfs_err(fs_info, "No space info for %llu", flags);
6727                 return -ENOSPC;
6728         }
6729
6730         /*
6731          * If our free space is heavily fragmented we may not be able to make
6732          * big contiguous allocations, so instead of doing the expensive search
6733          * for free space, simply return ENOSPC with our max_extent_size so we
6734          * can go ahead and search for a more manageable chunk.
6735          *
6736          * If our max_extent_size is large enough for our allocation simply
6737          * disable clustering since we will likely not be able to find enough
6738          * space to create a cluster and induce latency trying.
6739          */
6740         if (unlikely(space_info->max_extent_size)) {
6741                 spin_lock(&space_info->lock);
6742                 if (space_info->max_extent_size &&
6743                     num_bytes > space_info->max_extent_size) {
6744                         ins->offset = space_info->max_extent_size;
6745                         spin_unlock(&space_info->lock);
6746                         return -ENOSPC;
6747                 } else if (space_info->max_extent_size) {
6748                         use_cluster = false;
6749                 }
6750                 spin_unlock(&space_info->lock);
6751         }
6752
6753         last_ptr = fetch_cluster_info(fs_info, space_info,
6754                                       &ffe_ctl.empty_cluster);
6755         if (last_ptr) {
6756                 spin_lock(&last_ptr->lock);
6757                 if (last_ptr->block_group)
6758                         hint_byte = last_ptr->window_start;
6759                 if (last_ptr->fragmented) {
6760                         /*
6761                          * We still set window_start so we can keep track of the
6762                          * last place we found an allocation to try and save
6763                          * some time.
6764                          */
6765                         hint_byte = last_ptr->window_start;
6766                         use_cluster = false;
6767                 }
6768                 spin_unlock(&last_ptr->lock);
6769         }
6770
6771         ffe_ctl.search_start = max(ffe_ctl.search_start,
6772                                    first_logical_byte(fs_info, 0));
6773         ffe_ctl.search_start = max(ffe_ctl.search_start, hint_byte);
6774         if (ffe_ctl.search_start == hint_byte) {
6775                 block_group = btrfs_lookup_block_group(fs_info,
6776                                                        ffe_ctl.search_start);
6777                 /*
6778                  * we don't want to use the block group if it doesn't match our
6779                  * allocation bits, or if its not cached.
6780                  *
6781                  * However if we are re-searching with an ideal block group
6782                  * picked out then we don't care that the block group is cached.
6783                  */
6784                 if (block_group && block_group_bits(block_group, flags) &&
6785                     block_group->cached != BTRFS_CACHE_NO) {
6786                         down_read(&space_info->groups_sem);
6787                         if (list_empty(&block_group->list) ||
6788                             block_group->ro) {
6789                                 /*
6790                                  * someone is removing this block group,
6791                                  * we can't jump into the have_block_group
6792                                  * target because our list pointers are not
6793                                  * valid
6794                                  */
6795                                 btrfs_put_block_group(block_group);
6796                                 up_read(&space_info->groups_sem);
6797                         } else {
6798                                 ffe_ctl.index = btrfs_bg_flags_to_raid_index(
6799                                                 block_group->flags);
6800                                 btrfs_lock_block_group(block_group, delalloc);
6801                                 goto have_block_group;
6802                         }
6803                 } else if (block_group) {
6804                         btrfs_put_block_group(block_group);
6805                 }
6806         }
6807 search:
6808         ffe_ctl.have_caching_bg = false;
6809         if (ffe_ctl.index == btrfs_bg_flags_to_raid_index(flags) ||
6810             ffe_ctl.index == 0)
6811                 full_search = true;
6812         down_read(&space_info->groups_sem);
6813         list_for_each_entry(block_group,
6814                             &space_info->block_groups[ffe_ctl.index], list) {
6815                 /* If the block group is read-only, we can skip it entirely. */
6816                 if (unlikely(block_group->ro))
6817                         continue;
6818
6819                 btrfs_grab_block_group(block_group, delalloc);
6820                 ffe_ctl.search_start = block_group->key.objectid;
6821
6822                 /*
6823                  * this can happen if we end up cycling through all the
6824                  * raid types, but we want to make sure we only allocate
6825                  * for the proper type.
6826                  */
6827                 if (!block_group_bits(block_group, flags)) {
6828                         u64 extra = BTRFS_BLOCK_GROUP_DUP |
6829                                 BTRFS_BLOCK_GROUP_RAID1_MASK |
6830                                 BTRFS_BLOCK_GROUP_RAID56_MASK |
6831                                 BTRFS_BLOCK_GROUP_RAID10;
6832
6833                         /*
6834                          * if they asked for extra copies and this block group
6835                          * doesn't provide them, bail.  This does allow us to
6836                          * fill raid0 from raid1.
6837                          */
6838                         if ((flags & extra) && !(block_group->flags & extra))
6839                                 goto loop;
6840                 }
6841
6842 have_block_group:
6843                 ffe_ctl.cached = block_group_cache_done(block_group);
6844                 if (unlikely(!ffe_ctl.cached)) {
6845                         ffe_ctl.have_caching_bg = true;
6846                         ret = cache_block_group(block_group, 0);
6847                         BUG_ON(ret < 0);
6848                         ret = 0;
6849                 }
6850
6851                 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
6852                         goto loop;
6853
6854                 /*
6855                  * Ok we want to try and use the cluster allocator, so
6856                  * lets look there
6857                  */
6858                 if (last_ptr && use_cluster) {
6859                         struct btrfs_block_group_cache *cluster_bg = NULL;
6860
6861                         ret = find_free_extent_clustered(block_group, last_ptr,
6862                                                          &ffe_ctl, &cluster_bg);
6863
6864                         if (ret == 0) {
6865                                 if (cluster_bg && cluster_bg != block_group) {
6866                                         btrfs_release_block_group(block_group,
6867                                                                   delalloc);
6868                                         block_group = cluster_bg;
6869                                 }
6870                                 goto checks;
6871                         } else if (ret == -EAGAIN) {
6872                                 goto have_block_group;
6873                         } else if (ret > 0) {
6874                                 goto loop;
6875                         }
6876                         /* ret == -ENOENT case falls through */
6877                 }
6878
6879                 ret = find_free_extent_unclustered(block_group, last_ptr,
6880                                                    &ffe_ctl);
6881                 if (ret == -EAGAIN)
6882                         goto have_block_group;
6883                 else if (ret > 0)
6884                         goto loop;
6885                 /* ret == 0 case falls through */
6886 checks:
6887                 ffe_ctl.search_start = round_up(ffe_ctl.found_offset,
6888                                              fs_info->stripesize);
6889
6890                 /* move on to the next group */
6891                 if (ffe_ctl.search_start + num_bytes >
6892                     block_group->key.objectid + block_group->key.offset) {
6893                         btrfs_add_free_space(block_group, ffe_ctl.found_offset,
6894                                              num_bytes);
6895                         goto loop;
6896                 }
6897
6898                 if (ffe_ctl.found_offset < ffe_ctl.search_start)
6899                         btrfs_add_free_space(block_group, ffe_ctl.found_offset,
6900                                 ffe_ctl.search_start - ffe_ctl.found_offset);
6901
6902                 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
6903                                 num_bytes, delalloc);
6904                 if (ret == -EAGAIN) {
6905                         btrfs_add_free_space(block_group, ffe_ctl.found_offset,
6906                                              num_bytes);
6907                         goto loop;
6908                 }
6909                 btrfs_inc_block_group_reservations(block_group);
6910
6911                 /* we are all good, lets return */
6912                 ins->objectid = ffe_ctl.search_start;
6913                 ins->offset = num_bytes;
6914
6915                 trace_btrfs_reserve_extent(block_group, ffe_ctl.search_start,
6916                                            num_bytes);
6917                 btrfs_release_block_group(block_group, delalloc);
6918                 break;
6919 loop:
6920                 ffe_ctl.retry_clustered = false;
6921                 ffe_ctl.retry_unclustered = false;
6922                 BUG_ON(btrfs_bg_flags_to_raid_index(block_group->flags) !=
6923                        ffe_ctl.index);
6924                 btrfs_release_block_group(block_group, delalloc);
6925                 cond_resched();
6926         }
6927         up_read(&space_info->groups_sem);
6928
6929         ret = find_free_extent_update_loop(fs_info, last_ptr, ins, &ffe_ctl,
6930                                            full_search, use_cluster);
6931         if (ret > 0)
6932                 goto search;
6933
6934         if (ret == -ENOSPC) {
6935                 /*
6936                  * Use ffe_ctl->total_free_space as fallback if we can't find
6937                  * any contiguous hole.
6938                  */
6939                 if (!ffe_ctl.max_extent_size)
6940                         ffe_ctl.max_extent_size = ffe_ctl.total_free_space;
6941                 spin_lock(&space_info->lock);
6942                 space_info->max_extent_size = ffe_ctl.max_extent_size;
6943                 spin_unlock(&space_info->lock);
6944                 ins->offset = ffe_ctl.max_extent_size;
6945         }
6946         return ret;
6947 }
6948
6949 /*
6950  * btrfs_reserve_extent - entry point to the extent allocator. Tries to find a
6951  *                        hole that is at least as big as @num_bytes.
6952  *
6953  * @root           -    The root that will contain this extent
6954  *
6955  * @ram_bytes      -    The amount of space in ram that @num_bytes take. This
6956  *                      is used for accounting purposes. This value differs
6957  *                      from @num_bytes only in the case of compressed extents.
6958  *
6959  * @num_bytes      -    Number of bytes to allocate on-disk.
6960  *
6961  * @min_alloc_size -    Indicates the minimum amount of space that the
6962  *                      allocator should try to satisfy. In some cases
6963  *                      @num_bytes may be larger than what is required and if
6964  *                      the filesystem is fragmented then allocation fails.
6965  *                      However, the presence of @min_alloc_size gives a
6966  *                      chance to try and satisfy the smaller allocation.
6967  *
6968  * @empty_size     -    A hint that you plan on doing more COW. This is the
6969  *                      size in bytes the allocator should try to find free
6970  *                      next to the block it returns.  This is just a hint and
6971  *                      may be ignored by the allocator.
6972  *
6973  * @hint_byte      -    Hint to the allocator to start searching above the byte
6974  *                      address passed. It might be ignored.
6975  *
6976  * @ins            -    This key is modified to record the found hole. It will
6977  *                      have the following values:
6978  *                      ins->objectid == start position
6979  *                      ins->flags = BTRFS_EXTENT_ITEM_KEY
6980  *                      ins->offset == the size of the hole.
6981  *
6982  * @is_data        -    Boolean flag indicating whether an extent is
6983  *                      allocated for data (true) or metadata (false)
6984  *
6985  * @delalloc       -    Boolean flag indicating whether this allocation is for
6986  *                      delalloc or not. If 'true' data_rwsem of block groups
6987  *                      is going to be acquired.
6988  *
6989  *
6990  * Returns 0 when an allocation succeeded or < 0 when an error occurred. In
6991  * case -ENOSPC is returned then @ins->offset will contain the size of the
6992  * largest available hole the allocator managed to find.
6993  */
6994 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
6995                          u64 num_bytes, u64 min_alloc_size,
6996                          u64 empty_size, u64 hint_byte,
6997                          struct btrfs_key *ins, int is_data, int delalloc)
6998 {
6999         struct btrfs_fs_info *fs_info = root->fs_info;
7000         bool final_tried = num_bytes == min_alloc_size;
7001         u64 flags;
7002         int ret;
7003
7004         flags = get_alloc_profile_by_root(root, is_data);
7005 again:
7006         WARN_ON(num_bytes < fs_info->sectorsize);
7007         ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
7008                                hint_byte, ins, flags, delalloc);
7009         if (!ret && !is_data) {
7010                 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
7011         } else if (ret == -ENOSPC) {
7012                 if (!final_tried && ins->offset) {
7013                         num_bytes = min(num_bytes >> 1, ins->offset);
7014                         num_bytes = round_down(num_bytes,
7015                                                fs_info->sectorsize);
7016                         num_bytes = max(num_bytes, min_alloc_size);
7017                         ram_bytes = num_bytes;
7018                         if (num_bytes == min_alloc_size)
7019                                 final_tried = true;
7020                         goto again;
7021                 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
7022                         struct btrfs_space_info *sinfo;
7023
7024                         sinfo = btrfs_find_space_info(fs_info, flags);
7025                         btrfs_err(fs_info,
7026                                   "allocation failed flags %llu, wanted %llu",
7027                                   flags, num_bytes);
7028                         if (sinfo)
7029                                 btrfs_dump_space_info(fs_info, sinfo,
7030                                                       num_bytes, 1);
7031                 }
7032         }
7033
7034         return ret;
7035 }
7036
7037 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7038                                         u64 start, u64 len,
7039                                         int pin, int delalloc)
7040 {
7041         struct btrfs_block_group_cache *cache;
7042         int ret = 0;
7043
7044         cache = btrfs_lookup_block_group(fs_info, start);
7045         if (!cache) {
7046                 btrfs_err(fs_info, "Unable to find block group for %llu",
7047                           start);
7048                 return -ENOSPC;
7049         }
7050
7051         if (pin)
7052                 pin_down_extent(cache, start, len, 1);
7053         else {
7054                 if (btrfs_test_opt(fs_info, DISCARD))
7055                         ret = btrfs_discard_extent(fs_info, start, len, NULL);
7056                 btrfs_add_free_space(cache, start, len);
7057                 btrfs_free_reserved_bytes(cache, len, delalloc);
7058                 trace_btrfs_reserved_extent_free(fs_info, start, len);
7059         }
7060
7061         btrfs_put_block_group(cache);
7062         return ret;
7063 }
7064
7065 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7066                                u64 start, u64 len, int delalloc)
7067 {
7068         return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
7069 }
7070
7071 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
7072                                        u64 start, u64 len)
7073 {
7074         return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
7075 }
7076
7077 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7078                                       u64 parent, u64 root_objectid,
7079                                       u64 flags, u64 owner, u64 offset,
7080                                       struct btrfs_key *ins, int ref_mod)
7081 {
7082         struct btrfs_fs_info *fs_info = trans->fs_info;
7083         int ret;
7084         struct btrfs_extent_item *extent_item;
7085         struct btrfs_extent_inline_ref *iref;
7086         struct btrfs_path *path;
7087         struct extent_buffer *leaf;
7088         int type;
7089         u32 size;
7090
7091         if (parent > 0)
7092                 type = BTRFS_SHARED_DATA_REF_KEY;
7093         else
7094                 type = BTRFS_EXTENT_DATA_REF_KEY;
7095
7096         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7097
7098         path = btrfs_alloc_path();
7099         if (!path)
7100                 return -ENOMEM;
7101
7102         path->leave_spinning = 1;
7103         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7104                                       ins, size);
7105         if (ret) {
7106                 btrfs_free_path(path);
7107                 return ret;
7108         }
7109
7110         leaf = path->nodes[0];
7111         extent_item = btrfs_item_ptr(leaf, path->slots[0],
7112                                      struct btrfs_extent_item);
7113         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
7114         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7115         btrfs_set_extent_flags(leaf, extent_item,
7116                                flags | BTRFS_EXTENT_FLAG_DATA);
7117
7118         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
7119         btrfs_set_extent_inline_ref_type(leaf, iref, type);
7120         if (parent > 0) {
7121                 struct btrfs_shared_data_ref *ref;
7122                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
7123                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
7124                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
7125         } else {
7126                 struct btrfs_extent_data_ref *ref;
7127                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
7128                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
7129                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
7130                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
7131                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
7132         }
7133
7134         btrfs_mark_buffer_dirty(path->nodes[0]);
7135         btrfs_free_path(path);
7136
7137         ret = remove_from_free_space_tree(trans, ins->objectid, ins->offset);
7138         if (ret)
7139                 return ret;
7140
7141         ret = update_block_group(trans, ins->objectid, ins->offset, 1);
7142         if (ret) { /* -ENOENT, logic error */
7143                 btrfs_err(fs_info, "update block group failed for %llu %llu",
7144                         ins->objectid, ins->offset);
7145                 BUG();
7146         }
7147         trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
7148         return ret;
7149 }
7150
7151 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
7152                                      struct btrfs_delayed_ref_node *node,
7153                                      struct btrfs_delayed_extent_op *extent_op)
7154 {
7155         struct btrfs_fs_info *fs_info = trans->fs_info;
7156         int ret;
7157         struct btrfs_extent_item *extent_item;
7158         struct btrfs_key extent_key;
7159         struct btrfs_tree_block_info *block_info;
7160         struct btrfs_extent_inline_ref *iref;
7161         struct btrfs_path *path;
7162         struct extent_buffer *leaf;
7163         struct btrfs_delayed_tree_ref *ref;
7164         u32 size = sizeof(*extent_item) + sizeof(*iref);
7165         u64 num_bytes;
7166         u64 flags = extent_op->flags_to_set;
7167         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
7168
7169         ref = btrfs_delayed_node_to_tree_ref(node);
7170
7171         extent_key.objectid = node->bytenr;
7172         if (skinny_metadata) {
7173                 extent_key.offset = ref->level;
7174                 extent_key.type = BTRFS_METADATA_ITEM_KEY;
7175                 num_bytes = fs_info->nodesize;
7176         } else {
7177                 extent_key.offset = node->num_bytes;
7178                 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
7179                 size += sizeof(*block_info);
7180                 num_bytes = node->num_bytes;
7181         }
7182
7183         path = btrfs_alloc_path();
7184         if (!path)
7185                 return -ENOMEM;
7186
7187         path->leave_spinning = 1;
7188         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7189                                       &extent_key, size);
7190         if (ret) {
7191                 btrfs_free_path(path);
7192                 return ret;
7193         }
7194
7195         leaf = path->nodes[0];
7196         extent_item = btrfs_item_ptr(leaf, path->slots[0],
7197                                      struct btrfs_extent_item);
7198         btrfs_set_extent_refs(leaf, extent_item, 1);
7199         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7200         btrfs_set_extent_flags(leaf, extent_item,
7201                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
7202
7203         if (skinny_metadata) {
7204                 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
7205         } else {
7206                 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
7207                 btrfs_set_tree_block_key(leaf, block_info, &extent_op->key);
7208                 btrfs_set_tree_block_level(leaf, block_info, ref->level);
7209                 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
7210         }
7211
7212         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY) {
7213                 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
7214                 btrfs_set_extent_inline_ref_type(leaf, iref,
7215                                                  BTRFS_SHARED_BLOCK_REF_KEY);
7216                 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->parent);
7217         } else {
7218                 btrfs_set_extent_inline_ref_type(leaf, iref,
7219                                                  BTRFS_TREE_BLOCK_REF_KEY);
7220                 btrfs_set_extent_inline_ref_offset(leaf, iref, ref->root);
7221         }
7222
7223         btrfs_mark_buffer_dirty(leaf);
7224         btrfs_free_path(path);
7225
7226         ret = remove_from_free_space_tree(trans, extent_key.objectid,
7227                                           num_bytes);
7228         if (ret)
7229                 return ret;
7230
7231         ret = update_block_group(trans, extent_key.objectid,
7232                                  fs_info->nodesize, 1);
7233         if (ret) { /* -ENOENT, logic error */
7234                 btrfs_err(fs_info, "update block group failed for %llu %llu",
7235                         extent_key.objectid, extent_key.offset);
7236                 BUG();
7237         }
7238
7239         trace_btrfs_reserved_extent_alloc(fs_info, extent_key.objectid,
7240                                           fs_info->nodesize);
7241         return ret;
7242 }
7243
7244 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7245                                      struct btrfs_root *root, u64 owner,
7246                                      u64 offset, u64 ram_bytes,
7247                                      struct btrfs_key *ins)
7248 {
7249         struct btrfs_ref generic_ref = { 0 };
7250         int ret;
7251
7252         BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
7253
7254         btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
7255                                ins->objectid, ins->offset, 0);
7256         btrfs_init_data_ref(&generic_ref, root->root_key.objectid, owner, offset);
7257         btrfs_ref_tree_mod(root->fs_info, &generic_ref);
7258         ret = btrfs_add_delayed_data_ref(trans, &generic_ref,
7259                                          ram_bytes, NULL, NULL);
7260         return ret;
7261 }
7262
7263 /*
7264  * this is used by the tree logging recovery code.  It records that
7265  * an extent has been allocated and makes sure to clear the free
7266  * space cache bits as well
7267  */
7268 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
7269                                    u64 root_objectid, u64 owner, u64 offset,
7270                                    struct btrfs_key *ins)
7271 {
7272         struct btrfs_fs_info *fs_info = trans->fs_info;
7273         int ret;
7274         struct btrfs_block_group_cache *block_group;
7275         struct btrfs_space_info *space_info;
7276
7277         /*
7278          * Mixed block groups will exclude before processing the log so we only
7279          * need to do the exclude dance if this fs isn't mixed.
7280          */
7281         if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
7282                 ret = __exclude_logged_extent(fs_info, ins->objectid,
7283                                               ins->offset);
7284                 if (ret)
7285                         return ret;
7286         }
7287
7288         block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
7289         if (!block_group)
7290                 return -EINVAL;
7291
7292         space_info = block_group->space_info;
7293         spin_lock(&space_info->lock);
7294         spin_lock(&block_group->lock);
7295         space_info->bytes_reserved += ins->offset;
7296         block_group->reserved += ins->offset;
7297         spin_unlock(&block_group->lock);
7298         spin_unlock(&space_info->lock);
7299
7300         ret = alloc_reserved_file_extent(trans, 0, root_objectid, 0, owner,
7301                                          offset, ins, 1);
7302         btrfs_put_block_group(block_group);
7303         return ret;
7304 }
7305
7306 static struct extent_buffer *
7307 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
7308                       u64 bytenr, int level, u64 owner)
7309 {
7310         struct btrfs_fs_info *fs_info = root->fs_info;
7311         struct extent_buffer *buf;
7312
7313         buf = btrfs_find_create_tree_block(fs_info, bytenr);
7314         if (IS_ERR(buf))
7315                 return buf;
7316
7317         /*
7318          * Extra safety check in case the extent tree is corrupted and extent
7319          * allocator chooses to use a tree block which is already used and
7320          * locked.
7321          */
7322         if (buf->lock_owner == current->pid) {
7323                 btrfs_err_rl(fs_info,
7324 "tree block %llu owner %llu already locked by pid=%d, extent tree corruption detected",
7325                         buf->start, btrfs_header_owner(buf), current->pid);
7326                 free_extent_buffer(buf);
7327                 return ERR_PTR(-EUCLEAN);
7328         }
7329
7330         btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
7331         btrfs_tree_lock(buf);
7332         btrfs_clean_tree_block(buf);
7333         clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
7334
7335         btrfs_set_lock_blocking_write(buf);
7336         set_extent_buffer_uptodate(buf);
7337
7338         memzero_extent_buffer(buf, 0, sizeof(struct btrfs_header));
7339         btrfs_set_header_level(buf, level);
7340         btrfs_set_header_bytenr(buf, buf->start);
7341         btrfs_set_header_generation(buf, trans->transid);
7342         btrfs_set_header_backref_rev(buf, BTRFS_MIXED_BACKREF_REV);
7343         btrfs_set_header_owner(buf, owner);
7344         write_extent_buffer_fsid(buf, fs_info->fs_devices->metadata_uuid);
7345         write_extent_buffer_chunk_tree_uuid(buf, fs_info->chunk_tree_uuid);
7346         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
7347                 buf->log_index = root->log_transid % 2;
7348                 /*
7349                  * we allow two log transactions at a time, use different
7350                  * EXTENT bit to differentiate dirty pages.
7351                  */
7352                 if (buf->log_index == 0)
7353                         set_extent_dirty(&root->dirty_log_pages, buf->start,
7354                                         buf->start + buf->len - 1, GFP_NOFS);
7355                 else
7356                         set_extent_new(&root->dirty_log_pages, buf->start,
7357                                         buf->start + buf->len - 1);
7358         } else {
7359                 buf->log_index = -1;
7360                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
7361                          buf->start + buf->len - 1, GFP_NOFS);
7362         }
7363         trans->dirty = true;
7364         /* this returns a buffer locked for blocking */
7365         return buf;
7366 }
7367
7368 static struct btrfs_block_rsv *
7369 use_block_rsv(struct btrfs_trans_handle *trans,
7370               struct btrfs_root *root, u32 blocksize)
7371 {
7372         struct btrfs_fs_info *fs_info = root->fs_info;
7373         struct btrfs_block_rsv *block_rsv;
7374         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
7375         int ret;
7376         bool global_updated = false;
7377
7378         block_rsv = get_block_rsv(trans, root);
7379
7380         if (unlikely(block_rsv->size == 0))
7381                 goto try_reserve;
7382 again:
7383         ret = btrfs_block_rsv_use_bytes(block_rsv, blocksize);
7384         if (!ret)
7385                 return block_rsv;
7386
7387         if (block_rsv->failfast)
7388                 return ERR_PTR(ret);
7389
7390         if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
7391                 global_updated = true;
7392                 update_global_block_rsv(fs_info);
7393                 goto again;
7394         }
7395
7396         /*
7397          * The global reserve still exists to save us from ourselves, so don't
7398          * warn_on if we are short on our delayed refs reserve.
7399          */
7400         if (block_rsv->type != BTRFS_BLOCK_RSV_DELREFS &&
7401             btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
7402                 static DEFINE_RATELIMIT_STATE(_rs,
7403                                 DEFAULT_RATELIMIT_INTERVAL * 10,
7404                                 /*DEFAULT_RATELIMIT_BURST*/ 1);
7405                 if (__ratelimit(&_rs))
7406                         WARN(1, KERN_DEBUG
7407                                 "BTRFS: block rsv returned %d\n", ret);
7408         }
7409 try_reserve:
7410         ret = btrfs_reserve_metadata_bytes(root, block_rsv, blocksize,
7411                                            BTRFS_RESERVE_NO_FLUSH);
7412         if (!ret)
7413                 return block_rsv;
7414         /*
7415          * If we couldn't reserve metadata bytes try and use some from
7416          * the global reserve if its space type is the same as the global
7417          * reservation.
7418          */
7419         if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
7420             block_rsv->space_info == global_rsv->space_info) {
7421                 ret = btrfs_block_rsv_use_bytes(global_rsv, blocksize);
7422                 if (!ret)
7423                         return global_rsv;
7424         }
7425         return ERR_PTR(ret);
7426 }
7427
7428 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
7429                             struct btrfs_block_rsv *block_rsv, u32 blocksize)
7430 {
7431         block_rsv_add_bytes(block_rsv, blocksize, false);
7432         block_rsv_release_bytes(fs_info, block_rsv, NULL, 0, NULL);
7433 }
7434
7435 /*
7436  * finds a free extent and does all the dirty work required for allocation
7437  * returns the tree buffer or an ERR_PTR on error.
7438  */
7439 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
7440                                              struct btrfs_root *root,
7441                                              u64 parent, u64 root_objectid,
7442                                              const struct btrfs_disk_key *key,
7443                                              int level, u64 hint,
7444                                              u64 empty_size)
7445 {
7446         struct btrfs_fs_info *fs_info = root->fs_info;
7447         struct btrfs_key ins;
7448         struct btrfs_block_rsv *block_rsv;
7449         struct extent_buffer *buf;
7450         struct btrfs_delayed_extent_op *extent_op;
7451         struct btrfs_ref generic_ref = { 0 };
7452         u64 flags = 0;
7453         int ret;
7454         u32 blocksize = fs_info->nodesize;
7455         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
7456
7457 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
7458         if (btrfs_is_testing(fs_info)) {
7459                 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
7460                                             level, root_objectid);
7461                 if (!IS_ERR(buf))
7462                         root->alloc_bytenr += blocksize;
7463                 return buf;
7464         }
7465 #endif
7466
7467         block_rsv = use_block_rsv(trans, root, blocksize);
7468         if (IS_ERR(block_rsv))
7469                 return ERR_CAST(block_rsv);
7470
7471         ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
7472                                    empty_size, hint, &ins, 0, 0);
7473         if (ret)
7474                 goto out_unuse;
7475
7476         buf = btrfs_init_new_buffer(trans, root, ins.objectid, level,
7477                                     root_objectid);
7478         if (IS_ERR(buf)) {
7479                 ret = PTR_ERR(buf);
7480                 goto out_free_reserved;
7481         }
7482
7483         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
7484                 if (parent == 0)
7485                         parent = ins.objectid;
7486                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7487         } else
7488                 BUG_ON(parent > 0);
7489
7490         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
7491                 extent_op = btrfs_alloc_delayed_extent_op();
7492                 if (!extent_op) {
7493                         ret = -ENOMEM;
7494                         goto out_free_buf;
7495                 }
7496                 if (key)
7497                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
7498                 else
7499                         memset(&extent_op->key, 0, sizeof(extent_op->key));
7500                 extent_op->flags_to_set = flags;
7501                 extent_op->update_key = skinny_metadata ? false : true;
7502                 extent_op->update_flags = true;
7503                 extent_op->is_data = false;
7504                 extent_op->level = level;
7505
7506                 btrfs_init_generic_ref(&generic_ref, BTRFS_ADD_DELAYED_EXTENT,
7507                                        ins.objectid, ins.offset, parent);
7508                 generic_ref.real_root = root->root_key.objectid;
7509                 btrfs_init_tree_ref(&generic_ref, level, root_objectid);
7510                 btrfs_ref_tree_mod(fs_info, &generic_ref);
7511                 ret = btrfs_add_delayed_tree_ref(trans, &generic_ref,
7512                                                  extent_op, NULL, NULL);
7513                 if (ret)
7514                         goto out_free_delayed;
7515         }
7516         return buf;
7517
7518 out_free_delayed:
7519         btrfs_free_delayed_extent_op(extent_op);
7520 out_free_buf:
7521         free_extent_buffer(buf);
7522 out_free_reserved:
7523         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
7524 out_unuse:
7525         unuse_block_rsv(fs_info, block_rsv, blocksize);
7526         return ERR_PTR(ret);
7527 }
7528
7529 struct walk_control {
7530         u64 refs[BTRFS_MAX_LEVEL];
7531         u64 flags[BTRFS_MAX_LEVEL];
7532         struct btrfs_key update_progress;
7533         struct btrfs_key drop_progress;
7534         int drop_level;
7535         int stage;
7536         int level;
7537         int shared_level;
7538         int update_ref;
7539         int keep_locks;
7540         int reada_slot;
7541         int reada_count;
7542         int restarted;
7543 };
7544
7545 #define DROP_REFERENCE  1
7546 #define UPDATE_BACKREF  2
7547
7548 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
7549                                      struct btrfs_root *root,
7550                                      struct walk_control *wc,
7551                                      struct btrfs_path *path)
7552 {
7553         struct btrfs_fs_info *fs_info = root->fs_info;
7554         u64 bytenr;
7555         u64 generation;
7556         u64 refs;
7557         u64 flags;
7558         u32 nritems;
7559         struct btrfs_key key;
7560         struct extent_buffer *eb;
7561         int ret;
7562         int slot;
7563         int nread = 0;
7564
7565         if (path->slots[wc->level] < wc->reada_slot) {
7566                 wc->reada_count = wc->reada_count * 2 / 3;
7567                 wc->reada_count = max(wc->reada_count, 2);
7568         } else {
7569                 wc->reada_count = wc->reada_count * 3 / 2;
7570                 wc->reada_count = min_t(int, wc->reada_count,
7571                                         BTRFS_NODEPTRS_PER_BLOCK(fs_info));
7572         }
7573
7574         eb = path->nodes[wc->level];
7575         nritems = btrfs_header_nritems(eb);
7576
7577         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
7578                 if (nread >= wc->reada_count)
7579                         break;
7580
7581                 cond_resched();
7582                 bytenr = btrfs_node_blockptr(eb, slot);
7583                 generation = btrfs_node_ptr_generation(eb, slot);
7584
7585                 if (slot == path->slots[wc->level])
7586                         goto reada;
7587
7588                 if (wc->stage == UPDATE_BACKREF &&
7589                     generation <= root->root_key.offset)
7590                         continue;
7591
7592                 /* We don't lock the tree block, it's OK to be racy here */
7593                 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
7594                                                wc->level - 1, 1, &refs,
7595                                                &flags);
7596                 /* We don't care about errors in readahead. */
7597                 if (ret < 0)
7598                         continue;
7599                 BUG_ON(refs == 0);
7600
7601                 if (wc->stage == DROP_REFERENCE) {
7602                         if (refs == 1)
7603                                 goto reada;
7604
7605                         if (wc->level == 1 &&
7606                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7607                                 continue;
7608                         if (!wc->update_ref ||
7609                             generation <= root->root_key.offset)
7610                                 continue;
7611                         btrfs_node_key_to_cpu(eb, &key, slot);
7612                         ret = btrfs_comp_cpu_keys(&key,
7613                                                   &wc->update_progress);
7614                         if (ret < 0)
7615                                 continue;
7616                 } else {
7617                         if (wc->level == 1 &&
7618                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7619                                 continue;
7620                 }
7621 reada:
7622                 readahead_tree_block(fs_info, bytenr);
7623                 nread++;
7624         }
7625         wc->reada_slot = slot;
7626 }
7627
7628 /*
7629  * helper to process tree block while walking down the tree.
7630  *
7631  * when wc->stage == UPDATE_BACKREF, this function updates
7632  * back refs for pointers in the block.
7633  *
7634  * NOTE: return value 1 means we should stop walking down.
7635  */
7636 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
7637                                    struct btrfs_root *root,
7638                                    struct btrfs_path *path,
7639                                    struct walk_control *wc, int lookup_info)
7640 {
7641         struct btrfs_fs_info *fs_info = root->fs_info;
7642         int level = wc->level;
7643         struct extent_buffer *eb = path->nodes[level];
7644         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7645         int ret;
7646
7647         if (wc->stage == UPDATE_BACKREF &&
7648             btrfs_header_owner(eb) != root->root_key.objectid)
7649                 return 1;
7650
7651         /*
7652          * when reference count of tree block is 1, it won't increase
7653          * again. once full backref flag is set, we never clear it.
7654          */
7655         if (lookup_info &&
7656             ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
7657              (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
7658                 BUG_ON(!path->locks[level]);
7659                 ret = btrfs_lookup_extent_info(trans, fs_info,
7660                                                eb->start, level, 1,
7661                                                &wc->refs[level],
7662                                                &wc->flags[level]);
7663                 BUG_ON(ret == -ENOMEM);
7664                 if (ret)
7665                         return ret;
7666                 BUG_ON(wc->refs[level] == 0);
7667         }
7668
7669         if (wc->stage == DROP_REFERENCE) {
7670                 if (wc->refs[level] > 1)
7671                         return 1;
7672
7673                 if (path->locks[level] && !wc->keep_locks) {
7674                         btrfs_tree_unlock_rw(eb, path->locks[level]);
7675                         path->locks[level] = 0;
7676                 }
7677                 return 0;
7678         }
7679
7680         /* wc->stage == UPDATE_BACKREF */
7681         if (!(wc->flags[level] & flag)) {
7682                 BUG_ON(!path->locks[level]);
7683                 ret = btrfs_inc_ref(trans, root, eb, 1);
7684                 BUG_ON(ret); /* -ENOMEM */
7685                 ret = btrfs_dec_ref(trans, root, eb, 0);
7686                 BUG_ON(ret); /* -ENOMEM */
7687                 ret = btrfs_set_disk_extent_flags(trans, eb->start,
7688                                                   eb->len, flag,
7689                                                   btrfs_header_level(eb), 0);
7690                 BUG_ON(ret); /* -ENOMEM */
7691                 wc->flags[level] |= flag;
7692         }
7693
7694         /*
7695          * the block is shared by multiple trees, so it's not good to
7696          * keep the tree lock
7697          */
7698         if (path->locks[level] && level > 0) {
7699                 btrfs_tree_unlock_rw(eb, path->locks[level]);
7700                 path->locks[level] = 0;
7701         }
7702         return 0;
7703 }
7704
7705 /*
7706  * This is used to verify a ref exists for this root to deal with a bug where we
7707  * would have a drop_progress key that hadn't been updated properly.
7708  */
7709 static int check_ref_exists(struct btrfs_trans_handle *trans,
7710                             struct btrfs_root *root, u64 bytenr, u64 parent,
7711                             int level)
7712 {
7713         struct btrfs_path *path;
7714         struct btrfs_extent_inline_ref *iref;
7715         int ret;
7716
7717         path = btrfs_alloc_path();
7718         if (!path)
7719                 return -ENOMEM;
7720
7721         ret = lookup_extent_backref(trans, path, &iref, bytenr,
7722                                     root->fs_info->nodesize, parent,
7723                                     root->root_key.objectid, level, 0);
7724         btrfs_free_path(path);
7725         if (ret == -ENOENT)
7726                 return 0;
7727         if (ret < 0)
7728                 return ret;
7729         return 1;
7730 }
7731
7732 /*
7733  * helper to process tree block pointer.
7734  *
7735  * when wc->stage == DROP_REFERENCE, this function checks
7736  * reference count of the block pointed to. if the block
7737  * is shared and we need update back refs for the subtree
7738  * rooted at the block, this function changes wc->stage to
7739  * UPDATE_BACKREF. if the block is shared and there is no
7740  * need to update back, this function drops the reference
7741  * to the block.
7742  *
7743  * NOTE: return value 1 means we should stop walking down.
7744  */
7745 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
7746                                  struct btrfs_root *root,
7747                                  struct btrfs_path *path,
7748                                  struct walk_control *wc, int *lookup_info)
7749 {
7750         struct btrfs_fs_info *fs_info = root->fs_info;
7751         u64 bytenr;
7752         u64 generation;
7753         u64 parent;
7754         struct btrfs_key key;
7755         struct btrfs_key first_key;
7756         struct btrfs_ref ref = { 0 };
7757         struct extent_buffer *next;
7758         int level = wc->level;
7759         int reada = 0;
7760         int ret = 0;
7761         bool need_account = false;
7762
7763         generation = btrfs_node_ptr_generation(path->nodes[level],
7764                                                path->slots[level]);
7765         /*
7766          * if the lower level block was created before the snapshot
7767          * was created, we know there is no need to update back refs
7768          * for the subtree
7769          */
7770         if (wc->stage == UPDATE_BACKREF &&
7771             generation <= root->root_key.offset) {
7772                 *lookup_info = 1;
7773                 return 1;
7774         }
7775
7776         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
7777         btrfs_node_key_to_cpu(path->nodes[level], &first_key,
7778                               path->slots[level]);
7779
7780         next = find_extent_buffer(fs_info, bytenr);
7781         if (!next) {
7782                 next = btrfs_find_create_tree_block(fs_info, bytenr);
7783                 if (IS_ERR(next))
7784                         return PTR_ERR(next);
7785
7786                 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
7787                                                level - 1);
7788                 reada = 1;
7789         }
7790         btrfs_tree_lock(next);
7791         btrfs_set_lock_blocking_write(next);
7792
7793         ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
7794                                        &wc->refs[level - 1],
7795                                        &wc->flags[level - 1]);
7796         if (ret < 0)
7797                 goto out_unlock;
7798
7799         if (unlikely(wc->refs[level - 1] == 0)) {
7800                 btrfs_err(fs_info, "Missing references.");
7801                 ret = -EIO;
7802                 goto out_unlock;
7803         }
7804         *lookup_info = 0;
7805
7806         if (wc->stage == DROP_REFERENCE) {
7807                 if (wc->refs[level - 1] > 1) {
7808                         need_account = true;
7809                         if (level == 1 &&
7810                             (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7811                                 goto skip;
7812
7813                         if (!wc->update_ref ||
7814                             generation <= root->root_key.offset)
7815                                 goto skip;
7816
7817                         btrfs_node_key_to_cpu(path->nodes[level], &key,
7818                                               path->slots[level]);
7819                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
7820                         if (ret < 0)
7821                                 goto skip;
7822
7823                         wc->stage = UPDATE_BACKREF;
7824                         wc->shared_level = level - 1;
7825                 }
7826         } else {
7827                 if (level == 1 &&
7828                     (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7829                         goto skip;
7830         }
7831
7832         if (!btrfs_buffer_uptodate(next, generation, 0)) {
7833                 btrfs_tree_unlock(next);
7834                 free_extent_buffer(next);
7835                 next = NULL;
7836                 *lookup_info = 1;
7837         }
7838
7839         if (!next) {
7840                 if (reada && level == 1)
7841                         reada_walk_down(trans, root, wc, path);
7842                 next = read_tree_block(fs_info, bytenr, generation, level - 1,
7843                                        &first_key);
7844                 if (IS_ERR(next)) {
7845                         return PTR_ERR(next);
7846                 } else if (!extent_buffer_uptodate(next)) {
7847                         free_extent_buffer(next);
7848                         return -EIO;
7849                 }
7850                 btrfs_tree_lock(next);
7851                 btrfs_set_lock_blocking_write(next);
7852         }
7853
7854         level--;
7855         ASSERT(level == btrfs_header_level(next));
7856         if (level != btrfs_header_level(next)) {
7857                 btrfs_err(root->fs_info, "mismatched level");
7858                 ret = -EIO;
7859                 goto out_unlock;
7860         }
7861         path->nodes[level] = next;
7862         path->slots[level] = 0;
7863         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7864         wc->level = level;
7865         if (wc->level == 1)
7866                 wc->reada_slot = 0;
7867         return 0;
7868 skip:
7869         wc->refs[level - 1] = 0;
7870         wc->flags[level - 1] = 0;
7871         if (wc->stage == DROP_REFERENCE) {
7872                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
7873                         parent = path->nodes[level]->start;
7874                 } else {
7875                         ASSERT(root->root_key.objectid ==
7876                                btrfs_header_owner(path->nodes[level]));
7877                         if (root->root_key.objectid !=
7878                             btrfs_header_owner(path->nodes[level])) {
7879                                 btrfs_err(root->fs_info,
7880                                                 "mismatched block owner");
7881                                 ret = -EIO;
7882                                 goto out_unlock;
7883                         }
7884                         parent = 0;
7885                 }
7886
7887                 /*
7888                  * If we had a drop_progress we need to verify the refs are set
7889                  * as expected.  If we find our ref then we know that from here
7890                  * on out everything should be correct, and we can clear the
7891                  * ->restarted flag.
7892                  */
7893                 if (wc->restarted) {
7894                         ret = check_ref_exists(trans, root, bytenr, parent,
7895                                                level - 1);
7896                         if (ret < 0)
7897                                 goto out_unlock;
7898                         if (ret == 0)
7899                                 goto no_delete;
7900                         ret = 0;
7901                         wc->restarted = 0;
7902                 }
7903
7904                 /*
7905                  * Reloc tree doesn't contribute to qgroup numbers, and we have
7906                  * already accounted them at merge time (replace_path),
7907                  * thus we could skip expensive subtree trace here.
7908                  */
7909                 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID &&
7910                     need_account) {
7911                         ret = btrfs_qgroup_trace_subtree(trans, next,
7912                                                          generation, level - 1);
7913                         if (ret) {
7914                                 btrfs_err_rl(fs_info,
7915                                              "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
7916                                              ret);
7917                         }
7918                 }
7919
7920                 /*
7921                  * We need to update the next key in our walk control so we can
7922                  * update the drop_progress key accordingly.  We don't care if
7923                  * find_next_key doesn't find a key because that means we're at
7924                  * the end and are going to clean up now.
7925                  */
7926                 wc->drop_level = level;
7927                 find_next_key(path, level, &wc->drop_progress);
7928
7929                 btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
7930                                        fs_info->nodesize, parent);
7931                 btrfs_init_tree_ref(&ref, level - 1, root->root_key.objectid);
7932                 ret = btrfs_free_extent(trans, &ref);
7933                 if (ret)
7934                         goto out_unlock;
7935         }
7936 no_delete:
7937         *lookup_info = 1;
7938         ret = 1;
7939
7940 out_unlock:
7941         btrfs_tree_unlock(next);
7942         free_extent_buffer(next);
7943
7944         return ret;
7945 }
7946
7947 /*
7948  * helper to process tree block while walking up the tree.
7949  *
7950  * when wc->stage == DROP_REFERENCE, this function drops
7951  * reference count on the block.
7952  *
7953  * when wc->stage == UPDATE_BACKREF, this function changes
7954  * wc->stage back to DROP_REFERENCE if we changed wc->stage
7955  * to UPDATE_BACKREF previously while processing the block.
7956  *
7957  * NOTE: return value 1 means we should stop walking up.
7958  */
7959 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
7960                                  struct btrfs_root *root,
7961                                  struct btrfs_path *path,
7962                                  struct walk_control *wc)
7963 {
7964         struct btrfs_fs_info *fs_info = root->fs_info;
7965         int ret;
7966         int level = wc->level;
7967         struct extent_buffer *eb = path->nodes[level];
7968         u64 parent = 0;
7969
7970         if (wc->stage == UPDATE_BACKREF) {
7971                 BUG_ON(wc->shared_level < level);
7972                 if (level < wc->shared_level)
7973                         goto out;
7974
7975                 ret = find_next_key(path, level + 1, &wc->update_progress);
7976                 if (ret > 0)
7977                         wc->update_ref = 0;
7978
7979                 wc->stage = DROP_REFERENCE;
7980                 wc->shared_level = -1;
7981                 path->slots[level] = 0;
7982
7983                 /*
7984                  * check reference count again if the block isn't locked.
7985                  * we should start walking down the tree again if reference
7986                  * count is one.
7987                  */
7988                 if (!path->locks[level]) {
7989                         BUG_ON(level == 0);
7990                         btrfs_tree_lock(eb);
7991                         btrfs_set_lock_blocking_write(eb);
7992                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7993
7994                         ret = btrfs_lookup_extent_info(trans, fs_info,
7995                                                        eb->start, level, 1,
7996                                                        &wc->refs[level],
7997                                                        &wc->flags[level]);
7998                         if (ret < 0) {
7999                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8000                                 path->locks[level] = 0;
8001                                 return ret;
8002                         }
8003                         BUG_ON(wc->refs[level] == 0);
8004                         if (wc->refs[level] == 1) {
8005                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8006                                 path->locks[level] = 0;
8007                                 return 1;
8008                         }
8009                 }
8010         }
8011
8012         /* wc->stage == DROP_REFERENCE */
8013         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
8014
8015         if (wc->refs[level] == 1) {
8016                 if (level == 0) {
8017                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8018                                 ret = btrfs_dec_ref(trans, root, eb, 1);
8019                         else
8020                                 ret = btrfs_dec_ref(trans, root, eb, 0);
8021                         BUG_ON(ret); /* -ENOMEM */
8022                         if (is_fstree(root->root_key.objectid)) {
8023                                 ret = btrfs_qgroup_trace_leaf_items(trans, eb);
8024                                 if (ret) {
8025                                         btrfs_err_rl(fs_info,
8026         "error %d accounting leaf items, quota is out of sync, rescan required",
8027                                              ret);
8028                                 }
8029                         }
8030                 }
8031                 /* make block locked assertion in btrfs_clean_tree_block happy */
8032                 if (!path->locks[level] &&
8033                     btrfs_header_generation(eb) == trans->transid) {
8034                         btrfs_tree_lock(eb);
8035                         btrfs_set_lock_blocking_write(eb);
8036                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8037                 }
8038                 btrfs_clean_tree_block(eb);
8039         }
8040
8041         if (eb == root->node) {
8042                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8043                         parent = eb->start;
8044                 else if (root->root_key.objectid != btrfs_header_owner(eb))
8045                         goto owner_mismatch;
8046         } else {
8047                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8048                         parent = path->nodes[level + 1]->start;
8049                 else if (root->root_key.objectid !=
8050                          btrfs_header_owner(path->nodes[level + 1]))
8051                         goto owner_mismatch;
8052         }
8053
8054         btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
8055 out:
8056         wc->refs[level] = 0;
8057         wc->flags[level] = 0;
8058         return 0;
8059
8060 owner_mismatch:
8061         btrfs_err_rl(fs_info, "unexpected tree owner, have %llu expect %llu",
8062                      btrfs_header_owner(eb), root->root_key.objectid);
8063         return -EUCLEAN;
8064 }
8065
8066 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8067                                    struct btrfs_root *root,
8068                                    struct btrfs_path *path,
8069                                    struct walk_control *wc)
8070 {
8071         int level = wc->level;
8072         int lookup_info = 1;
8073         int ret;
8074
8075         while (level >= 0) {
8076                 ret = walk_down_proc(trans, root, path, wc, lookup_info);
8077                 if (ret > 0)
8078                         break;
8079
8080                 if (level == 0)
8081                         break;
8082
8083                 if (path->slots[level] >=
8084                     btrfs_header_nritems(path->nodes[level]))
8085                         break;
8086
8087                 ret = do_walk_down(trans, root, path, wc, &lookup_info);
8088                 if (ret > 0) {
8089                         path->slots[level]++;
8090                         continue;
8091                 } else if (ret < 0)
8092                         return ret;
8093                 level = wc->level;
8094         }
8095         return 0;
8096 }
8097
8098 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
8099                                  struct btrfs_root *root,
8100                                  struct btrfs_path *path,
8101                                  struct walk_control *wc, int max_level)
8102 {
8103         int level = wc->level;
8104         int ret;
8105
8106         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8107         while (level < max_level && path->nodes[level]) {
8108                 wc->level = level;
8109                 if (path->slots[level] + 1 <
8110                     btrfs_header_nritems(path->nodes[level])) {
8111                         path->slots[level]++;
8112                         return 0;
8113                 } else {
8114                         ret = walk_up_proc(trans, root, path, wc);
8115                         if (ret > 0)
8116                                 return 0;
8117                         if (ret < 0)
8118                                 return ret;
8119
8120                         if (path->locks[level]) {
8121                                 btrfs_tree_unlock_rw(path->nodes[level],
8122                                                      path->locks[level]);
8123                                 path->locks[level] = 0;
8124                         }
8125                         free_extent_buffer(path->nodes[level]);
8126                         path->nodes[level] = NULL;
8127                         level++;
8128                 }
8129         }
8130         return 1;
8131 }
8132
8133 /*
8134  * drop a subvolume tree.
8135  *
8136  * this function traverses the tree freeing any blocks that only
8137  * referenced by the tree.
8138  *
8139  * when a shared tree block is found. this function decreases its
8140  * reference count by one. if update_ref is true, this function
8141  * also make sure backrefs for the shared block and all lower level
8142  * blocks are properly updated.
8143  *
8144  * If called with for_reloc == 0, may exit early with -EAGAIN
8145  */
8146 int btrfs_drop_snapshot(struct btrfs_root *root,
8147                          struct btrfs_block_rsv *block_rsv, int update_ref,
8148                          int for_reloc)
8149 {
8150         struct btrfs_fs_info *fs_info = root->fs_info;
8151         struct btrfs_path *path;
8152         struct btrfs_trans_handle *trans;
8153         struct btrfs_root *tree_root = fs_info->tree_root;
8154         struct btrfs_root_item *root_item = &root->root_item;
8155         struct walk_control *wc;
8156         struct btrfs_key key;
8157         int err = 0;
8158         int ret;
8159         int level;
8160         bool root_dropped = false;
8161
8162         btrfs_debug(fs_info, "Drop subvolume %llu", root->root_key.objectid);
8163
8164         path = btrfs_alloc_path();
8165         if (!path) {
8166                 err = -ENOMEM;
8167                 goto out;
8168         }
8169
8170         wc = kzalloc(sizeof(*wc), GFP_NOFS);
8171         if (!wc) {
8172                 btrfs_free_path(path);
8173                 err = -ENOMEM;
8174                 goto out;
8175         }
8176
8177         trans = btrfs_start_transaction(tree_root, 0);
8178         if (IS_ERR(trans)) {
8179                 err = PTR_ERR(trans);
8180                 goto out_free;
8181         }
8182
8183         err = btrfs_run_delayed_items(trans);
8184         if (err)
8185                 goto out_end_trans;
8186
8187         if (block_rsv)
8188                 trans->block_rsv = block_rsv;
8189
8190         /*
8191          * This will help us catch people modifying the fs tree while we're
8192          * dropping it.  It is unsafe to mess with the fs tree while it's being
8193          * dropped as we unlock the root node and parent nodes as we walk down
8194          * the tree, assuming nothing will change.  If something does change
8195          * then we'll have stale information and drop references to blocks we've
8196          * already dropped.
8197          */
8198         set_bit(BTRFS_ROOT_DELETING, &root->state);
8199         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
8200                 level = btrfs_header_level(root->node);
8201                 path->nodes[level] = btrfs_lock_root_node(root);
8202                 btrfs_set_lock_blocking_write(path->nodes[level]);
8203                 path->slots[level] = 0;
8204                 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8205                 memset(&wc->update_progress, 0,
8206                        sizeof(wc->update_progress));
8207         } else {
8208                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
8209                 memcpy(&wc->update_progress, &key,
8210                        sizeof(wc->update_progress));
8211
8212                 level = root_item->drop_level;
8213                 BUG_ON(level == 0);
8214                 path->lowest_level = level;
8215                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8216                 path->lowest_level = 0;
8217                 if (ret < 0) {
8218                         err = ret;
8219                         goto out_end_trans;
8220                 }
8221                 WARN_ON(ret > 0);
8222
8223                 /*
8224                  * unlock our path, this is safe because only this
8225                  * function is allowed to delete this snapshot
8226                  */
8227                 btrfs_unlock_up_safe(path, 0);
8228
8229                 level = btrfs_header_level(root->node);
8230                 while (1) {
8231                         btrfs_tree_lock(path->nodes[level]);
8232                         btrfs_set_lock_blocking_write(path->nodes[level]);
8233                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8234
8235                         ret = btrfs_lookup_extent_info(trans, fs_info,
8236                                                 path->nodes[level]->start,
8237                                                 level, 1, &wc->refs[level],
8238                                                 &wc->flags[level]);
8239                         if (ret < 0) {
8240                                 err = ret;
8241                                 goto out_end_trans;
8242                         }
8243                         BUG_ON(wc->refs[level] == 0);
8244
8245                         if (level == root_item->drop_level)
8246                                 break;
8247
8248                         btrfs_tree_unlock(path->nodes[level]);
8249                         path->locks[level] = 0;
8250                         WARN_ON(wc->refs[level] != 1);
8251                         level--;
8252                 }
8253         }
8254
8255         wc->restarted = test_bit(BTRFS_ROOT_DEAD_TREE, &root->state);
8256         wc->level = level;
8257         wc->shared_level = -1;
8258         wc->stage = DROP_REFERENCE;
8259         wc->update_ref = update_ref;
8260         wc->keep_locks = 0;
8261         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
8262
8263         while (1) {
8264
8265                 ret = walk_down_tree(trans, root, path, wc);
8266                 if (ret < 0) {
8267                         err = ret;
8268                         break;
8269                 }
8270
8271                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
8272                 if (ret < 0) {
8273                         err = ret;
8274                         break;
8275                 }
8276
8277                 if (ret > 0) {
8278                         BUG_ON(wc->stage != DROP_REFERENCE);
8279                         break;
8280                 }
8281
8282                 if (wc->stage == DROP_REFERENCE) {
8283                         wc->drop_level = wc->level;
8284                         btrfs_node_key_to_cpu(path->nodes[wc->drop_level],
8285                                               &wc->drop_progress,
8286                                               path->slots[wc->drop_level]);
8287                 }
8288                 btrfs_cpu_key_to_disk(&root_item->drop_progress,
8289                                       &wc->drop_progress);
8290                 root_item->drop_level = wc->drop_level;
8291
8292                 BUG_ON(wc->level == 0);
8293                 if (btrfs_should_end_transaction(trans) ||
8294                     (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
8295                         ret = btrfs_update_root(trans, tree_root,
8296                                                 &root->root_key,
8297                                                 root_item);
8298                         if (ret) {
8299                                 btrfs_abort_transaction(trans, ret);
8300                                 err = ret;
8301                                 goto out_end_trans;
8302                         }
8303
8304                         btrfs_end_transaction_throttle(trans);
8305                         if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
8306                                 btrfs_debug(fs_info,
8307                                             "drop snapshot early exit");
8308                                 err = -EAGAIN;
8309                                 goto out_free;
8310                         }
8311
8312                         trans = btrfs_start_transaction(tree_root, 0);
8313                         if (IS_ERR(trans)) {
8314                                 err = PTR_ERR(trans);
8315                                 goto out_free;
8316                         }
8317                         if (block_rsv)
8318                                 trans->block_rsv = block_rsv;
8319                 }
8320         }
8321         btrfs_release_path(path);
8322         if (err)
8323                 goto out_end_trans;
8324
8325         ret = btrfs_del_root(trans, &root->root_key);
8326         if (ret) {
8327                 btrfs_abort_transaction(trans, ret);
8328                 err = ret;
8329                 goto out_end_trans;
8330         }
8331
8332         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8333                 ret = btrfs_find_root(tree_root, &root->root_key, path,
8334                                       NULL, NULL);
8335                 if (ret < 0) {
8336                         btrfs_abort_transaction(trans, ret);
8337                         err = ret;
8338                         goto out_end_trans;
8339                 } else if (ret > 0) {
8340                         /* if we fail to delete the orphan item this time
8341                          * around, it'll get picked up the next time.
8342                          *
8343                          * The most common failure here is just -ENOENT.
8344                          */
8345                         btrfs_del_orphan_item(trans, tree_root,
8346                                               root->root_key.objectid);
8347                 }
8348         }
8349
8350         if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
8351                 btrfs_add_dropped_root(trans, root);
8352         } else {
8353                 free_extent_buffer(root->node);
8354                 free_extent_buffer(root->commit_root);
8355                 btrfs_put_fs_root(root);
8356         }
8357         root_dropped = true;
8358 out_end_trans:
8359         btrfs_end_transaction_throttle(trans);
8360 out_free:
8361         kfree(wc);
8362         btrfs_free_path(path);
8363 out:
8364         /*
8365          * So if we need to stop dropping the snapshot for whatever reason we
8366          * need to make sure to add it back to the dead root list so that we
8367          * keep trying to do the work later.  This also cleans up roots if we
8368          * don't have it in the radix (like when we recover after a power fail
8369          * or unmount) so we don't leak memory.
8370          */
8371         if (!for_reloc && !root_dropped)
8372                 btrfs_add_dead_root(root);
8373         if (err && err != -EAGAIN)
8374                 btrfs_handle_fs_error(fs_info, err, NULL);
8375         return err;
8376 }
8377
8378 /*
8379  * drop subtree rooted at tree block 'node'.
8380  *
8381  * NOTE: this function will unlock and release tree block 'node'
8382  * only used by relocation code
8383  */
8384 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
8385                         struct btrfs_root *root,
8386                         struct extent_buffer *node,
8387                         struct extent_buffer *parent)
8388 {
8389         struct btrfs_fs_info *fs_info = root->fs_info;
8390         struct btrfs_path *path;
8391         struct walk_control *wc;
8392         int level;
8393         int parent_level;
8394         int ret = 0;
8395         int wret;
8396
8397         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
8398
8399         path = btrfs_alloc_path();
8400         if (!path)
8401                 return -ENOMEM;
8402
8403         wc = kzalloc(sizeof(*wc), GFP_NOFS);
8404         if (!wc) {
8405                 btrfs_free_path(path);
8406                 return -ENOMEM;
8407         }
8408
8409         btrfs_assert_tree_locked(parent);
8410         parent_level = btrfs_header_level(parent);
8411         extent_buffer_get(parent);
8412         path->nodes[parent_level] = parent;
8413         path->slots[parent_level] = btrfs_header_nritems(parent);
8414
8415         btrfs_assert_tree_locked(node);
8416         level = btrfs_header_level(node);
8417         path->nodes[level] = node;
8418         path->slots[level] = 0;
8419         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8420
8421         wc->refs[parent_level] = 1;
8422         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8423         wc->level = level;
8424         wc->shared_level = -1;
8425         wc->stage = DROP_REFERENCE;
8426         wc->update_ref = 0;
8427         wc->keep_locks = 1;
8428         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
8429
8430         while (1) {
8431                 wret = walk_down_tree(trans, root, path, wc);
8432                 if (wret < 0) {
8433                         ret = wret;
8434                         break;
8435                 }
8436
8437                 wret = walk_up_tree(trans, root, path, wc, parent_level);
8438                 if (wret < 0)
8439                         ret = wret;
8440                 if (wret != 0)
8441                         break;
8442         }
8443
8444         kfree(wc);
8445         btrfs_free_path(path);
8446         return ret;
8447 }
8448
8449 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
8450 {
8451         u64 num_devices;
8452         u64 stripped;
8453
8454         /*
8455          * if restripe for this chunk_type is on pick target profile and
8456          * return, otherwise do the usual balance
8457          */
8458         stripped = get_restripe_target(fs_info, flags);
8459         if (stripped)
8460                 return extended_to_chunk(stripped);
8461
8462         num_devices = fs_info->fs_devices->rw_devices;
8463
8464         stripped = BTRFS_BLOCK_GROUP_RAID0 | BTRFS_BLOCK_GROUP_RAID56_MASK |
8465                 BTRFS_BLOCK_GROUP_RAID1_MASK | BTRFS_BLOCK_GROUP_RAID10;
8466
8467         if (num_devices == 1) {
8468                 stripped |= BTRFS_BLOCK_GROUP_DUP;
8469                 stripped = flags & ~stripped;
8470
8471                 /* turn raid0 into single device chunks */
8472                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
8473                         return stripped;
8474
8475                 /* turn mirroring into duplication */
8476                 if (flags & (BTRFS_BLOCK_GROUP_RAID1_MASK |
8477                              BTRFS_BLOCK_GROUP_RAID10))
8478                         return stripped | BTRFS_BLOCK_GROUP_DUP;
8479         } else {
8480                 /* they already had raid on here, just return */
8481                 if (flags & stripped)
8482                         return flags;
8483
8484                 stripped |= BTRFS_BLOCK_GROUP_DUP;
8485                 stripped = flags & ~stripped;
8486
8487                 /* switch duplicated blocks with raid1 */
8488                 if (flags & BTRFS_BLOCK_GROUP_DUP)
8489                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
8490
8491                 /* this is drive concat, leave it alone */
8492         }
8493
8494         return flags;
8495 }
8496
8497 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
8498 {
8499         struct btrfs_space_info *sinfo = cache->space_info;
8500         u64 num_bytes;
8501         u64 sinfo_used;
8502         u64 min_allocable_bytes;
8503         int ret = -ENOSPC;
8504
8505         /*
8506          * We need some metadata space and system metadata space for
8507          * allocating chunks in some corner cases until we force to set
8508          * it to be readonly.
8509          */
8510         if ((sinfo->flags &
8511              (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
8512             !force)
8513                 min_allocable_bytes = SZ_1M;
8514         else
8515                 min_allocable_bytes = 0;
8516
8517         spin_lock(&sinfo->lock);
8518         spin_lock(&cache->lock);
8519
8520         if (cache->ro) {
8521                 cache->ro++;
8522                 ret = 0;
8523                 goto out;
8524         }
8525
8526         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8527                     cache->bytes_super - btrfs_block_group_used(&cache->item);
8528         sinfo_used = btrfs_space_info_used(sinfo, true);
8529
8530         if (sinfo_used + num_bytes + min_allocable_bytes <=
8531             sinfo->total_bytes) {
8532                 sinfo->bytes_readonly += num_bytes;
8533                 cache->ro++;
8534                 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
8535                 ret = 0;
8536         }
8537 out:
8538         spin_unlock(&cache->lock);
8539         spin_unlock(&sinfo->lock);
8540         if (ret == -ENOSPC && btrfs_test_opt(cache->fs_info, ENOSPC_DEBUG)) {
8541                 btrfs_info(cache->fs_info,
8542                         "unable to make block group %llu ro",
8543                         cache->key.objectid);
8544                 btrfs_info(cache->fs_info,
8545                         "sinfo_used=%llu bg_num_bytes=%llu min_allocable=%llu",
8546                         sinfo_used, num_bytes, min_allocable_bytes);
8547                 btrfs_dump_space_info(cache->fs_info, cache->space_info, 0, 0);
8548         }
8549         return ret;
8550 }
8551
8552 int btrfs_inc_block_group_ro(struct btrfs_block_group_cache *cache)
8553
8554 {
8555         struct btrfs_fs_info *fs_info = cache->fs_info;
8556         struct btrfs_trans_handle *trans;
8557         u64 alloc_flags;
8558         int ret;
8559
8560 again:
8561         trans = btrfs_join_transaction(fs_info->extent_root);
8562         if (IS_ERR(trans))
8563                 return PTR_ERR(trans);
8564
8565         /*
8566          * we're not allowed to set block groups readonly after the dirty
8567          * block groups cache has started writing.  If it already started,
8568          * back off and let this transaction commit
8569          */
8570         mutex_lock(&fs_info->ro_block_group_mutex);
8571         if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
8572                 u64 transid = trans->transid;
8573
8574                 mutex_unlock(&fs_info->ro_block_group_mutex);
8575                 btrfs_end_transaction(trans);
8576
8577                 ret = btrfs_wait_for_commit(fs_info, transid);
8578                 if (ret)
8579                         return ret;
8580                 goto again;
8581         }
8582
8583         /*
8584          * if we are changing raid levels, try to allocate a corresponding
8585          * block group with the new raid level.
8586          */
8587         alloc_flags = update_block_group_flags(fs_info, cache->flags);
8588         if (alloc_flags != cache->flags) {
8589                 ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
8590                 /*
8591                  * ENOSPC is allowed here, we may have enough space
8592                  * already allocated at the new raid level to
8593                  * carry on
8594                  */
8595                 if (ret == -ENOSPC)
8596                         ret = 0;
8597                 if (ret < 0)
8598                         goto out;
8599         }
8600
8601         ret = inc_block_group_ro(cache, 0);
8602         if (!ret)
8603                 goto out;
8604         alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
8605         ret = btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
8606         if (ret < 0)
8607                 goto out;
8608         ret = inc_block_group_ro(cache, 0);
8609 out:
8610         if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
8611                 alloc_flags = update_block_group_flags(fs_info, cache->flags);
8612                 mutex_lock(&fs_info->chunk_mutex);
8613                 check_system_chunk(trans, alloc_flags);
8614                 mutex_unlock(&fs_info->chunk_mutex);
8615         }
8616         mutex_unlock(&fs_info->ro_block_group_mutex);
8617
8618         btrfs_end_transaction(trans);
8619         return ret;
8620 }
8621
8622 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans, u64 type)
8623 {
8624         u64 alloc_flags = get_alloc_profile(trans->fs_info, type);
8625
8626         return btrfs_chunk_alloc(trans, alloc_flags, CHUNK_ALLOC_FORCE);
8627 }
8628
8629 /*
8630  * helper to account the unused space of all the readonly block group in the
8631  * space_info. takes mirrors into account.
8632  */
8633 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
8634 {
8635         struct btrfs_block_group_cache *block_group;
8636         u64 free_bytes = 0;
8637         int factor;
8638
8639         /* It's df, we don't care if it's racy */
8640         if (list_empty(&sinfo->ro_bgs))
8641                 return 0;
8642
8643         spin_lock(&sinfo->lock);
8644         list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
8645                 spin_lock(&block_group->lock);
8646
8647                 if (!block_group->ro) {
8648                         spin_unlock(&block_group->lock);
8649                         continue;
8650                 }
8651
8652                 factor = btrfs_bg_type_to_factor(block_group->flags);
8653                 free_bytes += (block_group->key.offset -
8654                                btrfs_block_group_used(&block_group->item)) *
8655                                factor;
8656
8657                 spin_unlock(&block_group->lock);
8658         }
8659         spin_unlock(&sinfo->lock);
8660
8661         return free_bytes;
8662 }
8663
8664 void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
8665 {
8666         struct btrfs_space_info *sinfo = cache->space_info;
8667         u64 num_bytes;
8668
8669         BUG_ON(!cache->ro);
8670
8671         spin_lock(&sinfo->lock);
8672         spin_lock(&cache->lock);
8673         if (!--cache->ro) {
8674                 num_bytes = cache->key.offset - cache->reserved -
8675                             cache->pinned - cache->bytes_super -
8676                             btrfs_block_group_used(&cache->item);
8677                 sinfo->bytes_readonly -= num_bytes;
8678                 list_del_init(&cache->ro_list);
8679         }
8680         spin_unlock(&cache->lock);
8681         spin_unlock(&sinfo->lock);
8682 }
8683
8684 /*
8685  * Checks to see if it's even possible to relocate this block group.
8686  *
8687  * @return - -1 if it's not a good idea to relocate this block group, 0 if its
8688  * ok to go ahead and try.
8689  */
8690 int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
8691 {
8692         struct btrfs_block_group_cache *block_group;
8693         struct btrfs_space_info *space_info;
8694         struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
8695         struct btrfs_device *device;
8696         u64 min_free;
8697         u64 dev_min = 1;
8698         u64 dev_nr = 0;
8699         u64 target;
8700         int debug;
8701         int index;
8702         int full = 0;
8703         int ret = 0;
8704
8705         debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
8706
8707         block_group = btrfs_lookup_block_group(fs_info, bytenr);
8708
8709         /* odd, couldn't find the block group, leave it alone */
8710         if (!block_group) {
8711                 if (debug)
8712                         btrfs_warn(fs_info,
8713                                    "can't find block group for bytenr %llu",
8714                                    bytenr);
8715                 return -1;
8716         }
8717
8718         min_free = btrfs_block_group_used(&block_group->item);
8719
8720         /* no bytes used, we're good */
8721         if (!min_free)
8722                 goto out;
8723
8724         space_info = block_group->space_info;
8725         spin_lock(&space_info->lock);
8726
8727         full = space_info->full;
8728
8729         /*
8730          * if this is the last block group we have in this space, we can't
8731          * relocate it unless we're able to allocate a new chunk below.
8732          *
8733          * Otherwise, we need to make sure we have room in the space to handle
8734          * all of the extents from this block group.  If we can, we're good
8735          */
8736         if ((space_info->total_bytes != block_group->key.offset) &&
8737             (btrfs_space_info_used(space_info, false) + min_free <
8738              space_info->total_bytes)) {
8739                 spin_unlock(&space_info->lock);
8740                 goto out;
8741         }
8742         spin_unlock(&space_info->lock);
8743
8744         /*
8745          * ok we don't have enough space, but maybe we have free space on our
8746          * devices to allocate new chunks for relocation, so loop through our
8747          * alloc devices and guess if we have enough space.  if this block
8748          * group is going to be restriped, run checks against the target
8749          * profile instead of the current one.
8750          */
8751         ret = -1;
8752
8753         /*
8754          * index:
8755          *      0: raid10
8756          *      1: raid1
8757          *      2: dup
8758          *      3: raid0
8759          *      4: single
8760          */
8761         target = get_restripe_target(fs_info, block_group->flags);
8762         if (target) {
8763                 index = btrfs_bg_flags_to_raid_index(extended_to_chunk(target));
8764         } else {
8765                 /*
8766                  * this is just a balance, so if we were marked as full
8767                  * we know there is no space for a new chunk
8768                  */
8769                 if (full) {
8770                         if (debug)
8771                                 btrfs_warn(fs_info,
8772                                            "no space to alloc new chunk for block group %llu",
8773                                            block_group->key.objectid);
8774                         goto out;
8775                 }
8776
8777                 index = btrfs_bg_flags_to_raid_index(block_group->flags);
8778         }
8779
8780         if (index == BTRFS_RAID_RAID10) {
8781                 dev_min = 4;
8782                 /* Divide by 2 */
8783                 min_free >>= 1;
8784         } else if (index == BTRFS_RAID_RAID1) {
8785                 dev_min = 2;
8786         } else if (index == BTRFS_RAID_DUP) {
8787                 /* Multiply by 2 */
8788                 min_free <<= 1;
8789         } else if (index == BTRFS_RAID_RAID0) {
8790                 dev_min = fs_devices->rw_devices;
8791                 min_free = div64_u64(min_free, dev_min);
8792         }
8793
8794         mutex_lock(&fs_info->chunk_mutex);
8795         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
8796                 u64 dev_offset;
8797
8798                 /*
8799                  * check to make sure we can actually find a chunk with enough
8800                  * space to fit our block group in.
8801                  */
8802                 if (device->total_bytes > device->bytes_used + min_free &&
8803                     !test_bit(BTRFS_DEV_STATE_REPLACE_TGT, &device->dev_state)) {
8804                         ret = find_free_dev_extent(device, min_free,
8805                                                    &dev_offset, NULL);
8806                         if (!ret)
8807                                 dev_nr++;
8808
8809                         if (dev_nr >= dev_min)
8810                                 break;
8811
8812                         ret = -1;
8813                 }
8814         }
8815         if (debug && ret == -1)
8816                 btrfs_warn(fs_info,
8817                            "no space to allocate a new chunk for block group %llu",
8818                            block_group->key.objectid);
8819         mutex_unlock(&fs_info->chunk_mutex);
8820 out:
8821         btrfs_put_block_group(block_group);
8822         return ret;
8823 }
8824
8825 static int find_first_block_group(struct btrfs_fs_info *fs_info,
8826                                   struct btrfs_path *path,
8827                                   struct btrfs_key *key)
8828 {
8829         struct btrfs_root *root = fs_info->extent_root;
8830         int ret = 0;
8831         struct btrfs_key found_key;
8832         struct extent_buffer *leaf;
8833         struct btrfs_block_group_item bg;
8834         u64 flags;
8835         int slot;
8836
8837         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
8838         if (ret < 0)
8839                 goto out;
8840
8841         while (1) {
8842                 slot = path->slots[0];
8843                 leaf = path->nodes[0];
8844                 if (slot >= btrfs_header_nritems(leaf)) {
8845                         ret = btrfs_next_leaf(root, path);
8846                         if (ret == 0)
8847                                 continue;
8848                         if (ret < 0)
8849                                 goto out;
8850                         break;
8851                 }
8852                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
8853
8854                 if (found_key.objectid >= key->objectid &&
8855                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
8856                         struct extent_map_tree *em_tree;
8857                         struct extent_map *em;
8858
8859                         em_tree = &root->fs_info->mapping_tree;
8860                         read_lock(&em_tree->lock);
8861                         em = lookup_extent_mapping(em_tree, found_key.objectid,
8862                                                    found_key.offset);
8863                         read_unlock(&em_tree->lock);
8864                         if (!em) {
8865                                 btrfs_err(fs_info,
8866                         "logical %llu len %llu found bg but no related chunk",
8867                                           found_key.objectid, found_key.offset);
8868                                 ret = -ENOENT;
8869                         } else if (em->start != found_key.objectid ||
8870                                    em->len != found_key.offset) {
8871                                 btrfs_err(fs_info,
8872                 "block group %llu len %llu mismatch with chunk %llu len %llu",
8873                                           found_key.objectid, found_key.offset,
8874                                           em->start, em->len);
8875                                 ret = -EUCLEAN;
8876                         } else {
8877                                 read_extent_buffer(leaf, &bg,
8878                                         btrfs_item_ptr_offset(leaf, slot),
8879                                         sizeof(bg));
8880                                 flags = btrfs_block_group_flags(&bg) &
8881                                         BTRFS_BLOCK_GROUP_TYPE_MASK;
8882
8883                                 if (flags != (em->map_lookup->type &
8884                                               BTRFS_BLOCK_GROUP_TYPE_MASK)) {
8885                                         btrfs_err(fs_info,
8886 "block group %llu len %llu type flags 0x%llx mismatch with chunk type flags 0x%llx",
8887                                                 found_key.objectid,
8888                                                 found_key.offset, flags,
8889                                                 (BTRFS_BLOCK_GROUP_TYPE_MASK &
8890                                                  em->map_lookup->type));
8891                                         ret = -EUCLEAN;
8892                                 } else {
8893                                         ret = 0;
8894                                 }
8895                         }
8896                         free_extent_map(em);
8897                         goto out;
8898                 }
8899                 path->slots[0]++;
8900         }
8901 out:
8902         return ret;
8903 }
8904
8905 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
8906 {
8907         struct btrfs_block_group_cache *block_group;
8908         u64 last = 0;
8909
8910         while (1) {
8911                 struct inode *inode;
8912
8913                 block_group = btrfs_lookup_first_block_group(info, last);
8914                 while (block_group) {
8915                         wait_block_group_cache_done(block_group);
8916                         spin_lock(&block_group->lock);
8917                         if (block_group->iref)
8918                                 break;
8919                         spin_unlock(&block_group->lock);
8920                         block_group = next_block_group(block_group);
8921                 }
8922                 if (!block_group) {
8923                         if (last == 0)
8924                                 break;
8925                         last = 0;
8926                         continue;
8927                 }
8928
8929                 inode = block_group->inode;
8930                 block_group->iref = 0;
8931                 block_group->inode = NULL;
8932                 spin_unlock(&block_group->lock);
8933                 ASSERT(block_group->io_ctl.inode == NULL);
8934                 iput(inode);
8935                 last = block_group->key.objectid + block_group->key.offset;
8936                 btrfs_put_block_group(block_group);
8937         }
8938 }
8939
8940 /*
8941  * Must be called only after stopping all workers, since we could have block
8942  * group caching kthreads running, and therefore they could race with us if we
8943  * freed the block groups before stopping them.
8944  */
8945 int btrfs_free_block_groups(struct btrfs_fs_info *info)
8946 {
8947         struct btrfs_block_group_cache *block_group;
8948         struct btrfs_space_info *space_info;
8949         struct btrfs_caching_control *caching_ctl;
8950         struct rb_node *n;
8951
8952         down_write(&info->commit_root_sem);
8953         while (!list_empty(&info->caching_block_groups)) {
8954                 caching_ctl = list_entry(info->caching_block_groups.next,
8955                                          struct btrfs_caching_control, list);
8956                 list_del(&caching_ctl->list);
8957                 put_caching_control(caching_ctl);
8958         }
8959         up_write(&info->commit_root_sem);
8960
8961         spin_lock(&info->unused_bgs_lock);
8962         while (!list_empty(&info->unused_bgs)) {
8963                 block_group = list_first_entry(&info->unused_bgs,
8964                                                struct btrfs_block_group_cache,
8965                                                bg_list);
8966                 list_del_init(&block_group->bg_list);
8967                 btrfs_put_block_group(block_group);
8968         }
8969         spin_unlock(&info->unused_bgs_lock);
8970
8971         spin_lock(&info->block_group_cache_lock);
8972         while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
8973                 block_group = rb_entry(n, struct btrfs_block_group_cache,
8974                                        cache_node);
8975                 rb_erase(&block_group->cache_node,
8976                          &info->block_group_cache_tree);
8977                 RB_CLEAR_NODE(&block_group->cache_node);
8978                 spin_unlock(&info->block_group_cache_lock);
8979
8980                 down_write(&block_group->space_info->groups_sem);
8981                 list_del(&block_group->list);
8982                 up_write(&block_group->space_info->groups_sem);
8983
8984                 /*
8985                  * We haven't cached this block group, which means we could
8986                  * possibly have excluded extents on this block group.
8987                  */
8988                 if (block_group->cached == BTRFS_CACHE_NO ||
8989                     block_group->cached == BTRFS_CACHE_ERROR)
8990                         free_excluded_extents(block_group);
8991
8992                 btrfs_remove_free_space_cache(block_group);
8993                 ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
8994                 ASSERT(list_empty(&block_group->dirty_list));
8995                 ASSERT(list_empty(&block_group->io_list));
8996                 ASSERT(list_empty(&block_group->bg_list));
8997                 ASSERT(atomic_read(&block_group->count) == 1);
8998                 btrfs_put_block_group(block_group);
8999
9000                 spin_lock(&info->block_group_cache_lock);
9001         }
9002         spin_unlock(&info->block_group_cache_lock);
9003
9004         /* now that all the block groups are freed, go through and
9005          * free all the space_info structs.  This is only called during
9006          * the final stages of unmount, and so we know nobody is
9007          * using them.  We call synchronize_rcu() once before we start,
9008          * just to be on the safe side.
9009          */
9010         synchronize_rcu();
9011
9012         release_global_block_rsv(info);
9013
9014         while (!list_empty(&info->space_info)) {
9015                 int i;
9016
9017                 space_info = list_entry(info->space_info.next,
9018                                         struct btrfs_space_info,
9019                                         list);
9020
9021                 /*
9022                  * Do not hide this behind enospc_debug, this is actually
9023                  * important and indicates a real bug if this happens.
9024                  */
9025                 if (WARN_ON(space_info->bytes_pinned > 0 ||
9026                             space_info->bytes_reserved > 0 ||
9027                             space_info->bytes_may_use > 0))
9028                         btrfs_dump_space_info(info, space_info, 0, 0);
9029                 list_del(&space_info->list);
9030                 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
9031                         struct kobject *kobj;
9032                         kobj = space_info->block_group_kobjs[i];
9033                         space_info->block_group_kobjs[i] = NULL;
9034                         if (kobj) {
9035                                 kobject_del(kobj);
9036                                 kobject_put(kobj);
9037                         }
9038                 }
9039                 kobject_del(&space_info->kobj);
9040                 kobject_put(&space_info->kobj);
9041         }
9042         return 0;
9043 }
9044
9045 /* link_block_group will queue up kobjects to add when we're reclaim-safe */
9046 void btrfs_add_raid_kobjects(struct btrfs_fs_info *fs_info)
9047 {
9048         struct btrfs_space_info *space_info;
9049         struct raid_kobject *rkobj;
9050         LIST_HEAD(list);
9051         int ret = 0;
9052
9053         spin_lock(&fs_info->pending_raid_kobjs_lock);
9054         list_splice_init(&fs_info->pending_raid_kobjs, &list);
9055         spin_unlock(&fs_info->pending_raid_kobjs_lock);
9056
9057         list_for_each_entry(rkobj, &list, list) {
9058                 space_info = btrfs_find_space_info(fs_info, rkobj->flags);
9059
9060                 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
9061                                 "%s", btrfs_bg_type_to_raid_name(rkobj->flags));
9062                 if (ret) {
9063                         kobject_put(&rkobj->kobj);
9064                         break;
9065                 }
9066         }
9067         if (ret)
9068                 btrfs_warn(fs_info,
9069                            "failed to add kobject for block cache, ignoring");
9070 }
9071
9072 static void link_block_group(struct btrfs_block_group_cache *cache)
9073 {
9074         struct btrfs_space_info *space_info = cache->space_info;
9075         struct btrfs_fs_info *fs_info = cache->fs_info;
9076         int index = btrfs_bg_flags_to_raid_index(cache->flags);
9077         bool first = false;
9078
9079         down_write(&space_info->groups_sem);
9080         if (list_empty(&space_info->block_groups[index]))
9081                 first = true;
9082         list_add_tail(&cache->list, &space_info->block_groups[index]);
9083         up_write(&space_info->groups_sem);
9084
9085         if (first) {
9086                 struct raid_kobject *rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
9087                 if (!rkobj) {
9088                         btrfs_warn(cache->fs_info,
9089                                 "couldn't alloc memory for raid level kobject");
9090                         return;
9091                 }
9092                 rkobj->flags = cache->flags;
9093                 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
9094
9095                 spin_lock(&fs_info->pending_raid_kobjs_lock);
9096                 list_add_tail(&rkobj->list, &fs_info->pending_raid_kobjs);
9097                 spin_unlock(&fs_info->pending_raid_kobjs_lock);
9098                 space_info->block_group_kobjs[index] = &rkobj->kobj;
9099         }
9100 }
9101
9102 static struct btrfs_block_group_cache *
9103 btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
9104                                u64 start, u64 size)
9105 {
9106         struct btrfs_block_group_cache *cache;
9107
9108         cache = kzalloc(sizeof(*cache), GFP_NOFS);
9109         if (!cache)
9110                 return NULL;
9111
9112         cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
9113                                         GFP_NOFS);
9114         if (!cache->free_space_ctl) {
9115                 kfree(cache);
9116                 return NULL;
9117         }
9118
9119         cache->key.objectid = start;
9120         cache->key.offset = size;
9121         cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9122
9123         cache->fs_info = fs_info;
9124         cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
9125         set_free_space_tree_thresholds(cache);
9126
9127         atomic_set(&cache->count, 1);
9128         spin_lock_init(&cache->lock);
9129         init_rwsem(&cache->data_rwsem);
9130         INIT_LIST_HEAD(&cache->list);
9131         INIT_LIST_HEAD(&cache->cluster_list);
9132         INIT_LIST_HEAD(&cache->bg_list);
9133         INIT_LIST_HEAD(&cache->ro_list);
9134         INIT_LIST_HEAD(&cache->dirty_list);
9135         INIT_LIST_HEAD(&cache->io_list);
9136         btrfs_init_free_space_ctl(cache);
9137         atomic_set(&cache->trimming, 0);
9138         mutex_init(&cache->free_space_lock);
9139         btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
9140
9141         return cache;
9142 }
9143
9144
9145 /*
9146  * Iterate all chunks and verify that each of them has the corresponding block
9147  * group
9148  */
9149 static int check_chunk_block_group_mappings(struct btrfs_fs_info *fs_info)
9150 {
9151         struct extent_map_tree *map_tree = &fs_info->mapping_tree;
9152         struct extent_map *em;
9153         struct btrfs_block_group_cache *bg;
9154         u64 start = 0;
9155         int ret = 0;
9156
9157         while (1) {
9158                 read_lock(&map_tree->lock);
9159                 /*
9160                  * lookup_extent_mapping will return the first extent map
9161                  * intersecting the range, so setting @len to 1 is enough to
9162                  * get the first chunk.
9163                  */
9164                 em = lookup_extent_mapping(map_tree, start, 1);
9165                 read_unlock(&map_tree->lock);
9166                 if (!em)
9167                         break;
9168
9169                 bg = btrfs_lookup_block_group(fs_info, em->start);
9170                 if (!bg) {
9171                         btrfs_err(fs_info,
9172         "chunk start=%llu len=%llu doesn't have corresponding block group",
9173                                      em->start, em->len);
9174                         ret = -EUCLEAN;
9175                         free_extent_map(em);
9176                         break;
9177                 }
9178                 if (bg->key.objectid != em->start ||
9179                     bg->key.offset != em->len ||
9180                     (bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK) !=
9181                     (em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK)) {
9182                         btrfs_err(fs_info,
9183 "chunk start=%llu len=%llu flags=0x%llx doesn't match block group start=%llu len=%llu flags=0x%llx",
9184                                 em->start, em->len,
9185                                 em->map_lookup->type & BTRFS_BLOCK_GROUP_TYPE_MASK,
9186                                 bg->key.objectid, bg->key.offset,
9187                                 bg->flags & BTRFS_BLOCK_GROUP_TYPE_MASK);
9188                         ret = -EUCLEAN;
9189                         free_extent_map(em);
9190                         btrfs_put_block_group(bg);
9191                         break;
9192                 }
9193                 start = em->start + em->len;
9194                 free_extent_map(em);
9195                 btrfs_put_block_group(bg);
9196         }
9197         return ret;
9198 }
9199
9200 int btrfs_read_block_groups(struct btrfs_fs_info *info)
9201 {
9202         struct btrfs_path *path;
9203         int ret;
9204         struct btrfs_block_group_cache *cache;
9205         struct btrfs_space_info *space_info;
9206         struct btrfs_key key;
9207         struct btrfs_key found_key;
9208         struct extent_buffer *leaf;
9209         int need_clear = 0;
9210         u64 cache_gen;
9211         u64 feature;
9212         int mixed;
9213
9214         feature = btrfs_super_incompat_flags(info->super_copy);
9215         mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
9216
9217         key.objectid = 0;
9218         key.offset = 0;
9219         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9220         path = btrfs_alloc_path();
9221         if (!path)
9222                 return -ENOMEM;
9223         path->reada = READA_FORWARD;
9224
9225         cache_gen = btrfs_super_cache_generation(info->super_copy);
9226         if (btrfs_test_opt(info, SPACE_CACHE) &&
9227             btrfs_super_generation(info->super_copy) != cache_gen)
9228                 need_clear = 1;
9229         if (btrfs_test_opt(info, CLEAR_CACHE))
9230                 need_clear = 1;
9231
9232         while (1) {
9233                 ret = find_first_block_group(info, path, &key);
9234                 if (ret > 0)
9235                         break;
9236                 if (ret != 0)
9237                         goto error;
9238
9239                 leaf = path->nodes[0];
9240                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9241
9242                 cache = btrfs_create_block_group_cache(info, found_key.objectid,
9243                                                        found_key.offset);
9244                 if (!cache) {
9245                         ret = -ENOMEM;
9246                         goto error;
9247                 }
9248
9249                 if (need_clear) {
9250                         /*
9251                          * When we mount with old space cache, we need to
9252                          * set BTRFS_DC_CLEAR and set dirty flag.
9253                          *
9254                          * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
9255                          *    truncate the old free space cache inode and
9256                          *    setup a new one.
9257                          * b) Setting 'dirty flag' makes sure that we flush
9258                          *    the new space cache info onto disk.
9259                          */
9260                         if (btrfs_test_opt(info, SPACE_CACHE))
9261                                 cache->disk_cache_state = BTRFS_DC_CLEAR;
9262                 }
9263
9264                 read_extent_buffer(leaf, &cache->item,
9265                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
9266                                    sizeof(cache->item));
9267                 cache->flags = btrfs_block_group_flags(&cache->item);
9268                 if (!mixed &&
9269                     ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
9270                     (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
9271                         btrfs_err(info,
9272 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
9273                                   cache->key.objectid);
9274                         ret = -EINVAL;
9275                         goto error;
9276                 }
9277
9278                 key.objectid = found_key.objectid + found_key.offset;
9279                 btrfs_release_path(path);
9280
9281                 /*
9282                  * We need to exclude the super stripes now so that the space
9283                  * info has super bytes accounted for, otherwise we'll think
9284                  * we have more space than we actually do.
9285                  */
9286                 ret = exclude_super_stripes(cache);
9287                 if (ret) {
9288                         /*
9289                          * We may have excluded something, so call this just in
9290                          * case.
9291                          */
9292                         free_excluded_extents(cache);
9293                         btrfs_put_block_group(cache);
9294                         goto error;
9295                 }
9296
9297                 /*
9298                  * check for two cases, either we are full, and therefore
9299                  * don't need to bother with the caching work since we won't
9300                  * find any space, or we are empty, and we can just add all
9301                  * the space in and be done with it.  This saves us _a_lot_ of
9302                  * time, particularly in the full case.
9303                  */
9304                 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
9305                         cache->last_byte_to_unpin = (u64)-1;
9306                         cache->cached = BTRFS_CACHE_FINISHED;
9307                         free_excluded_extents(cache);
9308                 } else if (btrfs_block_group_used(&cache->item) == 0) {
9309                         cache->last_byte_to_unpin = (u64)-1;
9310                         cache->cached = BTRFS_CACHE_FINISHED;
9311                         add_new_free_space(cache, found_key.objectid,
9312                                            found_key.objectid +
9313                                            found_key.offset);
9314                         free_excluded_extents(cache);
9315                 }
9316
9317                 ret = btrfs_add_block_group_cache(info, cache);
9318                 if (ret) {
9319                         btrfs_remove_free_space_cache(cache);
9320                         btrfs_put_block_group(cache);
9321                         goto error;
9322                 }
9323
9324                 trace_btrfs_add_block_group(info, cache, 0);
9325                 btrfs_update_space_info(info, cache->flags, found_key.offset,
9326                                         btrfs_block_group_used(&cache->item),
9327                                         cache->bytes_super, &space_info);
9328
9329                 cache->space_info = space_info;
9330
9331                 link_block_group(cache);
9332
9333                 set_avail_alloc_bits(info, cache->flags);
9334                 if (btrfs_chunk_readonly(info, cache->key.objectid)) {
9335                         inc_block_group_ro(cache, 1);
9336                 } else if (btrfs_block_group_used(&cache->item) == 0) {
9337                         ASSERT(list_empty(&cache->bg_list));
9338                         btrfs_mark_bg_unused(cache);
9339                 }
9340         }
9341
9342         list_for_each_entry_rcu(space_info, &info->space_info, list) {
9343                 if (!(get_alloc_profile(info, space_info->flags) &
9344                       (BTRFS_BLOCK_GROUP_RAID10 |
9345                        BTRFS_BLOCK_GROUP_RAID1_MASK |
9346                        BTRFS_BLOCK_GROUP_RAID56_MASK |
9347                        BTRFS_BLOCK_GROUP_DUP)))
9348                         continue;
9349                 /*
9350                  * avoid allocating from un-mirrored block group if there are
9351                  * mirrored block groups.
9352                  */
9353                 list_for_each_entry(cache,
9354                                 &space_info->block_groups[BTRFS_RAID_RAID0],
9355                                 list)
9356                         inc_block_group_ro(cache, 1);
9357                 list_for_each_entry(cache,
9358                                 &space_info->block_groups[BTRFS_RAID_SINGLE],
9359                                 list)
9360                         inc_block_group_ro(cache, 1);
9361         }
9362
9363         btrfs_add_raid_kobjects(info);
9364         init_global_block_rsv(info);
9365         ret = check_chunk_block_group_mappings(info);
9366 error:
9367         btrfs_free_path(path);
9368         return ret;
9369 }
9370
9371 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans)
9372 {
9373         struct btrfs_fs_info *fs_info = trans->fs_info;
9374         struct btrfs_block_group_cache *block_group;
9375         struct btrfs_root *extent_root = fs_info->extent_root;
9376         struct btrfs_block_group_item item;
9377         struct btrfs_key key;
9378         int ret = 0;
9379
9380         if (!trans->can_flush_pending_bgs)
9381                 return;
9382
9383         while (!list_empty(&trans->new_bgs)) {
9384                 block_group = list_first_entry(&trans->new_bgs,
9385                                                struct btrfs_block_group_cache,
9386                                                bg_list);
9387                 if (ret)
9388                         goto next;
9389
9390                 spin_lock(&block_group->lock);
9391                 memcpy(&item, &block_group->item, sizeof(item));
9392                 memcpy(&key, &block_group->key, sizeof(key));
9393                 spin_unlock(&block_group->lock);
9394
9395                 ret = btrfs_insert_item(trans, extent_root, &key, &item,
9396                                         sizeof(item));
9397                 if (ret)
9398                         btrfs_abort_transaction(trans, ret);
9399                 ret = btrfs_finish_chunk_alloc(trans, key.objectid, key.offset);
9400                 if (ret)
9401                         btrfs_abort_transaction(trans, ret);
9402                 add_block_group_free_space(trans, block_group);
9403                 /* already aborted the transaction if it failed. */
9404 next:
9405                 btrfs_delayed_refs_rsv_release(fs_info, 1);
9406                 list_del_init(&block_group->bg_list);
9407         }
9408         btrfs_trans_release_chunk_metadata(trans);
9409 }
9410
9411 int btrfs_make_block_group(struct btrfs_trans_handle *trans, u64 bytes_used,
9412                            u64 type, u64 chunk_offset, u64 size)
9413 {
9414         struct btrfs_fs_info *fs_info = trans->fs_info;
9415         struct btrfs_block_group_cache *cache;
9416         int ret;
9417
9418         btrfs_set_log_full_commit(trans);
9419
9420         cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
9421         if (!cache)
9422                 return -ENOMEM;
9423
9424         btrfs_set_block_group_used(&cache->item, bytes_used);
9425         btrfs_set_block_group_chunk_objectid(&cache->item,
9426                                              BTRFS_FIRST_CHUNK_TREE_OBJECTID);
9427         btrfs_set_block_group_flags(&cache->item, type);
9428
9429         cache->flags = type;
9430         cache->last_byte_to_unpin = (u64)-1;
9431         cache->cached = BTRFS_CACHE_FINISHED;
9432         cache->needs_free_space = 1;
9433         ret = exclude_super_stripes(cache);
9434         if (ret) {
9435                 /*
9436                  * We may have excluded something, so call this just in
9437                  * case.
9438                  */
9439                 free_excluded_extents(cache);
9440                 btrfs_put_block_group(cache);
9441                 return ret;
9442         }
9443
9444         add_new_free_space(cache, chunk_offset, chunk_offset + size);
9445
9446         free_excluded_extents(cache);
9447
9448 #ifdef CONFIG_BTRFS_DEBUG
9449         if (btrfs_should_fragment_free_space(cache)) {
9450                 u64 new_bytes_used = size - bytes_used;
9451
9452                 bytes_used += new_bytes_used >> 1;
9453                 fragment_free_space(cache);
9454         }
9455 #endif
9456         /*
9457          * Ensure the corresponding space_info object is created and
9458          * assigned to our block group. We want our bg to be added to the rbtree
9459          * with its ->space_info set.
9460          */
9461         cache->space_info = btrfs_find_space_info(fs_info, cache->flags);
9462         ASSERT(cache->space_info);
9463
9464         ret = btrfs_add_block_group_cache(fs_info, cache);
9465         if (ret) {
9466                 btrfs_remove_free_space_cache(cache);
9467                 btrfs_put_block_group(cache);
9468                 return ret;
9469         }
9470
9471         /*
9472          * Now that our block group has its ->space_info set and is inserted in
9473          * the rbtree, update the space info's counters.
9474          */
9475         trace_btrfs_add_block_group(fs_info, cache, 1);
9476         btrfs_update_space_info(fs_info, cache->flags, size, bytes_used,
9477                                 cache->bytes_super, &cache->space_info);
9478         update_global_block_rsv(fs_info);
9479
9480         link_block_group(cache);
9481
9482         list_add_tail(&cache->bg_list, &trans->new_bgs);
9483         trans->delayed_ref_updates++;
9484         btrfs_update_delayed_refs_rsv(trans);
9485
9486         set_avail_alloc_bits(fs_info, type);
9487         return 0;
9488 }
9489
9490 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
9491 {
9492         u64 extra_flags = chunk_to_extended(flags) &
9493                                 BTRFS_EXTENDED_PROFILE_MASK;
9494
9495         write_seqlock(&fs_info->profiles_lock);
9496         if (flags & BTRFS_BLOCK_GROUP_DATA)
9497                 fs_info->avail_data_alloc_bits &= ~extra_flags;
9498         if (flags & BTRFS_BLOCK_GROUP_METADATA)
9499                 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
9500         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
9501                 fs_info->avail_system_alloc_bits &= ~extra_flags;
9502         write_sequnlock(&fs_info->profiles_lock);
9503 }
9504
9505 /*
9506  * Clear incompat bits for the following feature(s):
9507  *
9508  * - RAID56 - in case there's neither RAID5 nor RAID6 profile block group
9509  *            in the whole filesystem
9510  */
9511 static void clear_incompat_bg_bits(struct btrfs_fs_info *fs_info, u64 flags)
9512 {
9513         if (flags & BTRFS_BLOCK_GROUP_RAID56_MASK) {
9514                 struct list_head *head = &fs_info->space_info;
9515                 struct btrfs_space_info *sinfo;
9516
9517                 list_for_each_entry_rcu(sinfo, head, list) {
9518                         bool found = false;
9519
9520                         down_read(&sinfo->groups_sem);
9521                         if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID5]))
9522                                 found = true;
9523                         if (!list_empty(&sinfo->block_groups[BTRFS_RAID_RAID6]))
9524                                 found = true;
9525                         up_read(&sinfo->groups_sem);
9526
9527                         if (found)
9528                                 return;
9529                 }
9530                 btrfs_clear_fs_incompat(fs_info, RAID56);
9531         }
9532 }
9533
9534 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
9535                              u64 group_start, struct extent_map *em)
9536 {
9537         struct btrfs_fs_info *fs_info = trans->fs_info;
9538         struct btrfs_root *root = fs_info->extent_root;
9539         struct btrfs_path *path;
9540         struct btrfs_block_group_cache *block_group;
9541         struct btrfs_free_cluster *cluster;
9542         struct btrfs_root *tree_root = fs_info->tree_root;
9543         struct btrfs_key key;
9544         struct inode *inode;
9545         struct kobject *kobj = NULL;
9546         int ret;
9547         int index;
9548         int factor;
9549         struct btrfs_caching_control *caching_ctl = NULL;
9550         bool remove_em;
9551         bool remove_rsv = false;
9552
9553         block_group = btrfs_lookup_block_group(fs_info, group_start);
9554         BUG_ON(!block_group);
9555         BUG_ON(!block_group->ro);
9556
9557         trace_btrfs_remove_block_group(block_group);
9558         /*
9559          * Free the reserved super bytes from this block group before
9560          * remove it.
9561          */
9562         free_excluded_extents(block_group);
9563         btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
9564                                   block_group->key.offset);
9565
9566         memcpy(&key, &block_group->key, sizeof(key));
9567         index = btrfs_bg_flags_to_raid_index(block_group->flags);
9568         factor = btrfs_bg_type_to_factor(block_group->flags);
9569
9570         /* make sure this block group isn't part of an allocation cluster */
9571         cluster = &fs_info->data_alloc_cluster;
9572         spin_lock(&cluster->refill_lock);
9573         btrfs_return_cluster_to_free_space(block_group, cluster);
9574         spin_unlock(&cluster->refill_lock);
9575
9576         /*
9577          * make sure this block group isn't part of a metadata
9578          * allocation cluster
9579          */
9580         cluster = &fs_info->meta_alloc_cluster;
9581         spin_lock(&cluster->refill_lock);
9582         btrfs_return_cluster_to_free_space(block_group, cluster);
9583         spin_unlock(&cluster->refill_lock);
9584
9585         path = btrfs_alloc_path();
9586         if (!path) {
9587                 ret = -ENOMEM;
9588                 goto out;
9589         }
9590
9591         /*
9592          * get the inode first so any iput calls done for the io_list
9593          * aren't the final iput (no unlinks allowed now)
9594          */
9595         inode = lookup_free_space_inode(block_group, path);
9596
9597         mutex_lock(&trans->transaction->cache_write_mutex);
9598         /*
9599          * Make sure our free space cache IO is done before removing the
9600          * free space inode
9601          */
9602         spin_lock(&trans->transaction->dirty_bgs_lock);
9603         if (!list_empty(&block_group->io_list)) {
9604                 list_del_init(&block_group->io_list);
9605
9606                 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
9607
9608                 spin_unlock(&trans->transaction->dirty_bgs_lock);
9609                 btrfs_wait_cache_io(trans, block_group, path);
9610                 btrfs_put_block_group(block_group);
9611                 spin_lock(&trans->transaction->dirty_bgs_lock);
9612         }
9613
9614         if (!list_empty(&block_group->dirty_list)) {
9615                 list_del_init(&block_group->dirty_list);
9616                 remove_rsv = true;
9617                 btrfs_put_block_group(block_group);
9618         }
9619         spin_unlock(&trans->transaction->dirty_bgs_lock);
9620         mutex_unlock(&trans->transaction->cache_write_mutex);
9621
9622         if (!IS_ERR(inode)) {
9623                 ret = btrfs_orphan_add(trans, BTRFS_I(inode));
9624                 if (ret) {
9625                         btrfs_add_delayed_iput(inode);
9626                         goto out;
9627                 }
9628                 clear_nlink(inode);
9629                 /* One for the block groups ref */
9630                 spin_lock(&block_group->lock);
9631                 if (block_group->iref) {
9632                         block_group->iref = 0;
9633                         block_group->inode = NULL;
9634                         spin_unlock(&block_group->lock);
9635                         iput(inode);
9636                 } else {
9637                         spin_unlock(&block_group->lock);
9638                 }
9639                 /* One for our lookup ref */
9640                 btrfs_add_delayed_iput(inode);
9641         }
9642
9643         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
9644         key.offset = block_group->key.objectid;
9645         key.type = 0;
9646
9647         ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
9648         if (ret < 0)
9649                 goto out;
9650         if (ret > 0)
9651                 btrfs_release_path(path);
9652         if (ret == 0) {
9653                 ret = btrfs_del_item(trans, tree_root, path);
9654                 if (ret)
9655                         goto out;
9656                 btrfs_release_path(path);
9657         }
9658
9659         spin_lock(&fs_info->block_group_cache_lock);
9660         rb_erase(&block_group->cache_node,
9661                  &fs_info->block_group_cache_tree);
9662         RB_CLEAR_NODE(&block_group->cache_node);
9663
9664         if (fs_info->first_logical_byte == block_group->key.objectid)
9665                 fs_info->first_logical_byte = (u64)-1;
9666         spin_unlock(&fs_info->block_group_cache_lock);
9667
9668         down_write(&block_group->space_info->groups_sem);
9669         /*
9670          * we must use list_del_init so people can check to see if they
9671          * are still on the list after taking the semaphore
9672          */
9673         list_del_init(&block_group->list);
9674         if (list_empty(&block_group->space_info->block_groups[index])) {
9675                 kobj = block_group->space_info->block_group_kobjs[index];
9676                 block_group->space_info->block_group_kobjs[index] = NULL;
9677                 clear_avail_alloc_bits(fs_info, block_group->flags);
9678         }
9679         up_write(&block_group->space_info->groups_sem);
9680         clear_incompat_bg_bits(fs_info, block_group->flags);
9681         if (kobj) {
9682                 kobject_del(kobj);
9683                 kobject_put(kobj);
9684         }
9685
9686         if (block_group->has_caching_ctl)
9687                 caching_ctl = get_caching_control(block_group);
9688         if (block_group->cached == BTRFS_CACHE_STARTED)
9689                 wait_block_group_cache_done(block_group);
9690         if (block_group->has_caching_ctl) {
9691                 down_write(&fs_info->commit_root_sem);
9692                 if (!caching_ctl) {
9693                         struct btrfs_caching_control *ctl;
9694
9695                         list_for_each_entry(ctl,
9696                                     &fs_info->caching_block_groups, list)
9697                                 if (ctl->block_group == block_group) {
9698                                         caching_ctl = ctl;
9699                                         refcount_inc(&caching_ctl->count);
9700                                         break;
9701                                 }
9702                 }
9703                 if (caching_ctl)
9704                         list_del_init(&caching_ctl->list);
9705                 up_write(&fs_info->commit_root_sem);
9706                 if (caching_ctl) {
9707                         /* Once for the caching bgs list and once for us. */
9708                         put_caching_control(caching_ctl);
9709                         put_caching_control(caching_ctl);
9710                 }
9711         }
9712
9713         spin_lock(&trans->transaction->dirty_bgs_lock);
9714         WARN_ON(!list_empty(&block_group->dirty_list));
9715         WARN_ON(!list_empty(&block_group->io_list));
9716         spin_unlock(&trans->transaction->dirty_bgs_lock);
9717
9718         btrfs_remove_free_space_cache(block_group);
9719
9720         spin_lock(&block_group->space_info->lock);
9721         list_del_init(&block_group->ro_list);
9722
9723         if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
9724                 WARN_ON(block_group->space_info->total_bytes
9725                         < block_group->key.offset);
9726                 WARN_ON(block_group->space_info->bytes_readonly
9727                         < block_group->key.offset);
9728                 WARN_ON(block_group->space_info->disk_total
9729                         < block_group->key.offset * factor);
9730         }
9731         block_group->space_info->total_bytes -= block_group->key.offset;
9732         block_group->space_info->bytes_readonly -= block_group->key.offset;
9733         block_group->space_info->disk_total -= block_group->key.offset * factor;
9734
9735         spin_unlock(&block_group->space_info->lock);
9736
9737         memcpy(&key, &block_group->key, sizeof(key));
9738
9739         mutex_lock(&fs_info->chunk_mutex);
9740         spin_lock(&block_group->lock);
9741         block_group->removed = 1;
9742         /*
9743          * At this point trimming can't start on this block group, because we
9744          * removed the block group from the tree fs_info->block_group_cache_tree
9745          * so no one can't find it anymore and even if someone already got this
9746          * block group before we removed it from the rbtree, they have already
9747          * incremented block_group->trimming - if they didn't, they won't find
9748          * any free space entries because we already removed them all when we
9749          * called btrfs_remove_free_space_cache().
9750          *
9751          * And we must not remove the extent map from the fs_info->mapping_tree
9752          * to prevent the same logical address range and physical device space
9753          * ranges from being reused for a new block group. This is because our
9754          * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
9755          * completely transactionless, so while it is trimming a range the
9756          * currently running transaction might finish and a new one start,
9757          * allowing for new block groups to be created that can reuse the same
9758          * physical device locations unless we take this special care.
9759          *
9760          * There may also be an implicit trim operation if the file system
9761          * is mounted with -odiscard. The same protections must remain
9762          * in place until the extents have been discarded completely when
9763          * the transaction commit has completed.
9764          */
9765         remove_em = (atomic_read(&block_group->trimming) == 0);
9766         spin_unlock(&block_group->lock);
9767
9768         mutex_unlock(&fs_info->chunk_mutex);
9769
9770         ret = remove_block_group_free_space(trans, block_group);
9771         if (ret)
9772                 goto out;
9773
9774         btrfs_put_block_group(block_group);
9775         btrfs_put_block_group(block_group);
9776
9777         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
9778         if (ret > 0)
9779                 ret = -EIO;
9780         if (ret < 0)
9781                 goto out;
9782
9783         ret = btrfs_del_item(trans, root, path);
9784         if (ret)
9785                 goto out;
9786
9787         if (remove_em) {
9788                 struct extent_map_tree *em_tree;
9789
9790                 em_tree = &fs_info->mapping_tree;
9791                 write_lock(&em_tree->lock);
9792                 remove_extent_mapping(em_tree, em);
9793                 write_unlock(&em_tree->lock);
9794                 /* once for the tree */
9795                 free_extent_map(em);
9796         }
9797 out:
9798         if (remove_rsv)
9799                 btrfs_delayed_refs_rsv_release(fs_info, 1);
9800         btrfs_free_path(path);
9801         return ret;
9802 }
9803
9804 struct btrfs_trans_handle *
9805 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
9806                                      const u64 chunk_offset)
9807 {
9808         struct extent_map_tree *em_tree = &fs_info->mapping_tree;
9809         struct extent_map *em;
9810         struct map_lookup *map;
9811         unsigned int num_items;
9812
9813         read_lock(&em_tree->lock);
9814         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
9815         read_unlock(&em_tree->lock);
9816         ASSERT(em && em->start == chunk_offset);
9817
9818         /*
9819          * We need to reserve 3 + N units from the metadata space info in order
9820          * to remove a block group (done at btrfs_remove_chunk() and at
9821          * btrfs_remove_block_group()), which are used for:
9822          *
9823          * 1 unit for adding the free space inode's orphan (located in the tree
9824          * of tree roots).
9825          * 1 unit for deleting the block group item (located in the extent
9826          * tree).
9827          * 1 unit for deleting the free space item (located in tree of tree
9828          * roots).
9829          * N units for deleting N device extent items corresponding to each
9830          * stripe (located in the device tree).
9831          *
9832          * In order to remove a block group we also need to reserve units in the
9833          * system space info in order to update the chunk tree (update one or
9834          * more device items and remove one chunk item), but this is done at
9835          * btrfs_remove_chunk() through a call to check_system_chunk().
9836          */
9837         map = em->map_lookup;
9838         num_items = 3 + map->num_stripes;
9839         free_extent_map(em);
9840
9841         return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
9842                                                            num_items, 1);
9843 }
9844
9845 /*
9846  * Process the unused_bgs list and remove any that don't have any allocated
9847  * space inside of them.
9848  */
9849 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
9850 {
9851         struct btrfs_block_group_cache *block_group;
9852         struct btrfs_space_info *space_info;
9853         struct btrfs_trans_handle *trans;
9854         int ret = 0;
9855
9856         if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
9857                 return;
9858
9859         spin_lock(&fs_info->unused_bgs_lock);
9860         while (!list_empty(&fs_info->unused_bgs)) {
9861                 u64 start, end;
9862                 int trimming;
9863
9864                 block_group = list_first_entry(&fs_info->unused_bgs,
9865                                                struct btrfs_block_group_cache,
9866                                                bg_list);
9867                 list_del_init(&block_group->bg_list);
9868
9869                 space_info = block_group->space_info;
9870
9871                 if (ret || btrfs_mixed_space_info(space_info)) {
9872                         btrfs_put_block_group(block_group);
9873                         continue;
9874                 }
9875                 spin_unlock(&fs_info->unused_bgs_lock);
9876
9877                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
9878
9879                 /* Don't want to race with allocators so take the groups_sem */
9880                 down_write(&space_info->groups_sem);
9881                 spin_lock(&block_group->lock);
9882                 if (block_group->reserved || block_group->pinned ||
9883                     btrfs_block_group_used(&block_group->item) ||
9884                     block_group->ro ||
9885                     list_is_singular(&block_group->list)) {
9886                         /*
9887                          * We want to bail if we made new allocations or have
9888                          * outstanding allocations in this block group.  We do
9889                          * the ro check in case balance is currently acting on
9890                          * this block group.
9891                          */
9892                         trace_btrfs_skip_unused_block_group(block_group);
9893                         spin_unlock(&block_group->lock);
9894                         up_write(&space_info->groups_sem);
9895                         goto next;
9896                 }
9897                 spin_unlock(&block_group->lock);
9898
9899                 /* We don't want to force the issue, only flip if it's ok. */
9900                 ret = inc_block_group_ro(block_group, 0);
9901                 up_write(&space_info->groups_sem);
9902                 if (ret < 0) {
9903                         ret = 0;
9904                         goto next;
9905                 }
9906
9907                 /*
9908                  * Want to do this before we do anything else so we can recover
9909                  * properly if we fail to join the transaction.
9910                  */
9911                 trans = btrfs_start_trans_remove_block_group(fs_info,
9912                                                      block_group->key.objectid);
9913                 if (IS_ERR(trans)) {
9914                         btrfs_dec_block_group_ro(block_group);
9915                         ret = PTR_ERR(trans);
9916                         goto next;
9917                 }
9918
9919                 /*
9920                  * We could have pending pinned extents for this block group,
9921                  * just delete them, we don't care about them anymore.
9922                  */
9923                 start = block_group->key.objectid;
9924                 end = start + block_group->key.offset - 1;
9925                 /*
9926                  * Hold the unused_bg_unpin_mutex lock to avoid racing with
9927                  * btrfs_finish_extent_commit(). If we are at transaction N,
9928                  * another task might be running finish_extent_commit() for the
9929                  * previous transaction N - 1, and have seen a range belonging
9930                  * to the block group in freed_extents[] before we were able to
9931                  * clear the whole block group range from freed_extents[]. This
9932                  * means that task can lookup for the block group after we
9933                  * unpinned it from freed_extents[] and removed it, leading to
9934                  * a BUG_ON() at btrfs_unpin_extent_range().
9935                  */
9936                 mutex_lock(&fs_info->unused_bg_unpin_mutex);
9937                 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
9938                                   EXTENT_DIRTY);
9939                 if (ret) {
9940                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
9941                         btrfs_dec_block_group_ro(block_group);
9942                         goto end_trans;
9943                 }
9944                 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
9945                                   EXTENT_DIRTY);
9946                 if (ret) {
9947                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
9948                         btrfs_dec_block_group_ro(block_group);
9949                         goto end_trans;
9950                 }
9951                 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
9952
9953                 /* Reset pinned so btrfs_put_block_group doesn't complain */
9954                 spin_lock(&space_info->lock);
9955                 spin_lock(&block_group->lock);
9956
9957                 btrfs_space_info_update_bytes_pinned(fs_info, space_info,
9958                                                      -block_group->pinned);
9959                 space_info->bytes_readonly += block_group->pinned;
9960                 percpu_counter_add_batch(&space_info->total_bytes_pinned,
9961                                    -block_group->pinned,
9962                                    BTRFS_TOTAL_BYTES_PINNED_BATCH);
9963                 block_group->pinned = 0;
9964
9965                 spin_unlock(&block_group->lock);
9966                 spin_unlock(&space_info->lock);
9967
9968                 /* DISCARD can flip during remount */
9969                 trimming = btrfs_test_opt(fs_info, DISCARD);
9970
9971                 /* Implicit trim during transaction commit. */
9972                 if (trimming)
9973                         btrfs_get_block_group_trimming(block_group);
9974
9975                 /*
9976                  * Btrfs_remove_chunk will abort the transaction if things go
9977                  * horribly wrong.
9978                  */
9979                 ret = btrfs_remove_chunk(trans, block_group->key.objectid);
9980
9981                 if (ret) {
9982                         if (trimming)
9983                                 btrfs_put_block_group_trimming(block_group);
9984                         goto end_trans;
9985                 }
9986
9987                 /*
9988                  * If we're not mounted with -odiscard, we can just forget
9989                  * about this block group. Otherwise we'll need to wait
9990                  * until transaction commit to do the actual discard.
9991                  */
9992                 if (trimming) {
9993                         spin_lock(&fs_info->unused_bgs_lock);
9994                         /*
9995                          * A concurrent scrub might have added us to the list
9996                          * fs_info->unused_bgs, so use a list_move operation
9997                          * to add the block group to the deleted_bgs list.
9998                          */
9999                         list_move(&block_group->bg_list,
10000                                   &trans->transaction->deleted_bgs);
10001                         spin_unlock(&fs_info->unused_bgs_lock);
10002                         btrfs_get_block_group(block_group);
10003                 }
10004 end_trans:
10005                 btrfs_end_transaction(trans);
10006 next:
10007                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
10008                 btrfs_put_block_group(block_group);
10009                 spin_lock(&fs_info->unused_bgs_lock);
10010         }
10011         spin_unlock(&fs_info->unused_bgs_lock);
10012 }
10013
10014 int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
10015                                    u64 start, u64 end)
10016 {
10017         return unpin_extent_range(fs_info, start, end, false);
10018 }
10019
10020 /*
10021  * It used to be that old block groups would be left around forever.
10022  * Iterating over them would be enough to trim unused space.  Since we
10023  * now automatically remove them, we also need to iterate over unallocated
10024  * space.
10025  *
10026  * We don't want a transaction for this since the discard may take a
10027  * substantial amount of time.  We don't require that a transaction be
10028  * running, but we do need to take a running transaction into account
10029  * to ensure that we're not discarding chunks that were released or
10030  * allocated in the current transaction.
10031  *
10032  * Holding the chunks lock will prevent other threads from allocating
10033  * or releasing chunks, but it won't prevent a running transaction
10034  * from committing and releasing the memory that the pending chunks
10035  * list head uses.  For that, we need to take a reference to the
10036  * transaction and hold the commit root sem.  We only need to hold
10037  * it while performing the free space search since we have already
10038  * held back allocations.
10039  */
10040 static int btrfs_trim_free_extents(struct btrfs_device *device, u64 *trimmed)
10041 {
10042         u64 start = SZ_1M, len = 0, end = 0;
10043         int ret;
10044
10045         *trimmed = 0;
10046
10047         /* Discard not supported = nothing to do. */
10048         if (!blk_queue_discard(bdev_get_queue(device->bdev)))
10049                 return 0;
10050
10051         /* Not writable = nothing to do. */
10052         if (!test_bit(BTRFS_DEV_STATE_WRITEABLE, &device->dev_state))
10053                 return 0;
10054
10055         /* No free space = nothing to do. */
10056         if (device->total_bytes <= device->bytes_used)
10057                 return 0;
10058
10059         ret = 0;
10060
10061         while (1) {
10062                 struct btrfs_fs_info *fs_info = device->fs_info;
10063                 u64 bytes;
10064
10065                 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
10066                 if (ret)
10067                         break;
10068
10069                 find_first_clear_extent_bit(&device->alloc_state, start,
10070                                             &start, &end,
10071                                             CHUNK_TRIMMED | CHUNK_ALLOCATED);
10072
10073                 /* Ensure we skip the reserved area in the first 1M */
10074                 start = max_t(u64, start, SZ_1M);
10075
10076                 /*
10077                  * If find_first_clear_extent_bit find a range that spans the
10078                  * end of the device it will set end to -1, in this case it's up
10079                  * to the caller to trim the value to the size of the device.
10080                  */
10081                 end = min(end, device->total_bytes - 1);
10082
10083                 len = end - start + 1;
10084
10085                 /* We didn't find any extents */
10086                 if (!len) {
10087                         mutex_unlock(&fs_info->chunk_mutex);
10088                         ret = 0;
10089                         break;
10090                 }
10091
10092                 ret = btrfs_issue_discard(device->bdev, start, len,
10093                                           &bytes);
10094                 if (!ret)
10095                         set_extent_bits(&device->alloc_state, start,
10096                                         start + bytes - 1,
10097                                         CHUNK_TRIMMED);
10098                 mutex_unlock(&fs_info->chunk_mutex);
10099
10100                 if (ret)
10101                         break;
10102
10103                 start += len;
10104                 *trimmed += bytes;
10105
10106                 if (fatal_signal_pending(current)) {
10107                         ret = -ERESTARTSYS;
10108                         break;
10109                 }
10110
10111                 cond_resched();
10112         }
10113
10114         return ret;
10115 }
10116
10117 /*
10118  * Trim the whole filesystem by:
10119  * 1) trimming the free space in each block group
10120  * 2) trimming the unallocated space on each device
10121  *
10122  * This will also continue trimming even if a block group or device encounters
10123  * an error.  The return value will be the last error, or 0 if nothing bad
10124  * happens.
10125  */
10126 int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
10127 {
10128         struct btrfs_block_group_cache *cache = NULL;
10129         struct btrfs_device *device;
10130         struct list_head *devices;
10131         u64 group_trimmed;
10132         u64 start;
10133         u64 end;
10134         u64 trimmed = 0;
10135         u64 bg_failed = 0;
10136         u64 dev_failed = 0;
10137         int bg_ret = 0;
10138         int dev_ret = 0;
10139         int ret = 0;
10140
10141         cache = btrfs_lookup_first_block_group(fs_info, range->start);
10142         for (; cache; cache = next_block_group(cache)) {
10143                 if (cache->key.objectid >= (range->start + range->len)) {
10144                         btrfs_put_block_group(cache);
10145                         break;
10146                 }
10147
10148                 start = max(range->start, cache->key.objectid);
10149                 end = min(range->start + range->len,
10150                                 cache->key.objectid + cache->key.offset);
10151
10152                 if (end - start >= range->minlen) {
10153                         if (!block_group_cache_done(cache)) {
10154                                 ret = cache_block_group(cache, 0);
10155                                 if (ret) {
10156                                         bg_failed++;
10157                                         bg_ret = ret;
10158                                         continue;
10159                                 }
10160                                 ret = wait_block_group_cache_done(cache);
10161                                 if (ret) {
10162                                         bg_failed++;
10163                                         bg_ret = ret;
10164                                         continue;
10165                                 }
10166                         }
10167                         ret = btrfs_trim_block_group(cache,
10168                                                      &group_trimmed,
10169                                                      start,
10170                                                      end,
10171                                                      range->minlen);
10172
10173                         trimmed += group_trimmed;
10174                         if (ret) {
10175                                 bg_failed++;
10176                                 bg_ret = ret;
10177                                 continue;
10178                         }
10179                 }
10180         }
10181
10182         if (bg_failed)
10183                 btrfs_warn(fs_info,
10184                         "failed to trim %llu block group(s), last error %d",
10185                         bg_failed, bg_ret);
10186         mutex_lock(&fs_info->fs_devices->device_list_mutex);
10187         devices = &fs_info->fs_devices->devices;
10188         list_for_each_entry(device, devices, dev_list) {
10189                 ret = btrfs_trim_free_extents(device, &group_trimmed);
10190                 if (ret) {
10191                         dev_failed++;
10192                         dev_ret = ret;
10193                         break;
10194                 }
10195
10196                 trimmed += group_trimmed;
10197         }
10198         mutex_unlock(&fs_info->fs_devices->device_list_mutex);
10199
10200         if (dev_failed)
10201                 btrfs_warn(fs_info,
10202                         "failed to trim %llu device(s), last error %d",
10203                         dev_failed, dev_ret);
10204         range->len = trimmed;
10205         if (bg_ret)
10206                 return bg_ret;
10207         return dev_ret;
10208 }
10209
10210 /*
10211  * btrfs_{start,end}_write_no_snapshotting() are similar to
10212  * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
10213  * data into the page cache through nocow before the subvolume is snapshoted,
10214  * but flush the data into disk after the snapshot creation, or to prevent
10215  * operations while snapshotting is ongoing and that cause the snapshot to be
10216  * inconsistent (writes followed by expanding truncates for example).
10217  */
10218 void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
10219 {
10220         percpu_counter_dec(&root->subv_writers->counter);
10221         cond_wake_up(&root->subv_writers->wait);
10222 }
10223
10224 int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
10225 {
10226         if (atomic_read(&root->will_be_snapshotted))
10227                 return 0;
10228
10229         percpu_counter_inc(&root->subv_writers->counter);
10230         /*
10231          * Make sure counter is updated before we check for snapshot creation.
10232          */
10233         smp_mb();
10234         if (atomic_read(&root->will_be_snapshotted)) {
10235                 btrfs_end_write_no_snapshotting(root);
10236                 return 0;
10237         }
10238         return 1;
10239 }
10240
10241 void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
10242 {
10243         while (true) {
10244                 int ret;
10245
10246                 ret = btrfs_start_write_no_snapshotting(root);
10247                 if (ret)
10248                         break;
10249                 wait_var_event(&root->will_be_snapshotted,
10250                                !atomic_read(&root->will_be_snapshotted));
10251         }
10252 }
10253
10254 void btrfs_mark_bg_unused(struct btrfs_block_group_cache *bg)
10255 {
10256         struct btrfs_fs_info *fs_info = bg->fs_info;
10257
10258         spin_lock(&fs_info->unused_bgs_lock);
10259         if (list_empty(&bg->bg_list)) {
10260                 btrfs_get_block_group(bg);
10261                 trace_btrfs_add_unused_block_group(bg);
10262                 list_add_tail(&bg->bg_list, &fs_info->unused_bgs);
10263         }
10264         spin_unlock(&fs_info->unused_bgs_lock);
10265 }