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