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