Merge branch 'cleanups' of git://repo.or.cz/linux-2.6/btrfs-unstable into inode_numbers
[pandora-kernel.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 "compat.h"
27 #include "hash.h"
28 #include "ctree.h"
29 #include "disk-io.h"
30 #include "print-tree.h"
31 #include "transaction.h"
32 #include "volumes.h"
33 #include "locking.h"
34 #include "free-space-cache.h"
35
36 /* control flags for do_chunk_alloc's force field
37  * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
38  * if we really need one.
39  *
40  * CHUNK_ALLOC_FORCE means it must try to allocate one
41  *
42  * CHUNK_ALLOC_LIMITED means to only try and allocate one
43  * if we have very few chunks already allocated.  This is
44  * used as part of the clustering code to help make sure
45  * we have a good pool of storage to cluster in, without
46  * filling the FS with empty chunks
47  *
48  */
49 enum {
50         CHUNK_ALLOC_NO_FORCE = 0,
51         CHUNK_ALLOC_FORCE = 1,
52         CHUNK_ALLOC_LIMITED = 2,
53 };
54
55 static int update_block_group(struct btrfs_trans_handle *trans,
56                               struct btrfs_root *root,
57                               u64 bytenr, u64 num_bytes, int alloc);
58 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
59                                 struct btrfs_root *root,
60                                 u64 bytenr, u64 num_bytes, u64 parent,
61                                 u64 root_objectid, u64 owner_objectid,
62                                 u64 owner_offset, int refs_to_drop,
63                                 struct btrfs_delayed_extent_op *extra_op);
64 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
65                                     struct extent_buffer *leaf,
66                                     struct btrfs_extent_item *ei);
67 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
68                                       struct btrfs_root *root,
69                                       u64 parent, u64 root_objectid,
70                                       u64 flags, u64 owner, u64 offset,
71                                       struct btrfs_key *ins, int ref_mod);
72 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
73                                      struct btrfs_root *root,
74                                      u64 parent, u64 root_objectid,
75                                      u64 flags, struct btrfs_disk_key *key,
76                                      int level, struct btrfs_key *ins);
77 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
78                           struct btrfs_root *extent_root, u64 alloc_bytes,
79                           u64 flags, int force);
80 static int find_next_key(struct btrfs_path *path, int level,
81                          struct btrfs_key *key);
82 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
83                             int dump_block_groups);
84
85 static noinline int
86 block_group_cache_done(struct btrfs_block_group_cache *cache)
87 {
88         smp_mb();
89         return cache->cached == BTRFS_CACHE_FINISHED;
90 }
91
92 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
93 {
94         return (cache->flags & bits) == bits;
95 }
96
97 static void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
98 {
99         atomic_inc(&cache->count);
100 }
101
102 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
103 {
104         if (atomic_dec_and_test(&cache->count)) {
105                 WARN_ON(cache->pinned > 0);
106                 WARN_ON(cache->reserved > 0);
107                 WARN_ON(cache->reserved_pinned > 0);
108                 kfree(cache->free_space_ctl);
109                 kfree(cache);
110         }
111 }
112
113 /*
114  * this adds the block group to the fs_info rb tree for the block group
115  * cache
116  */
117 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
118                                 struct btrfs_block_group_cache *block_group)
119 {
120         struct rb_node **p;
121         struct rb_node *parent = NULL;
122         struct btrfs_block_group_cache *cache;
123
124         spin_lock(&info->block_group_cache_lock);
125         p = &info->block_group_cache_tree.rb_node;
126
127         while (*p) {
128                 parent = *p;
129                 cache = rb_entry(parent, struct btrfs_block_group_cache,
130                                  cache_node);
131                 if (block_group->key.objectid < cache->key.objectid) {
132                         p = &(*p)->rb_left;
133                 } else if (block_group->key.objectid > cache->key.objectid) {
134                         p = &(*p)->rb_right;
135                 } else {
136                         spin_unlock(&info->block_group_cache_lock);
137                         return -EEXIST;
138                 }
139         }
140
141         rb_link_node(&block_group->cache_node, parent, p);
142         rb_insert_color(&block_group->cache_node,
143                         &info->block_group_cache_tree);
144         spin_unlock(&info->block_group_cache_lock);
145
146         return 0;
147 }
148
149 /*
150  * This will return the block group at or after bytenr if contains is 0, else
151  * it will return the block group that contains the bytenr
152  */
153 static struct btrfs_block_group_cache *
154 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
155                               int contains)
156 {
157         struct btrfs_block_group_cache *cache, *ret = NULL;
158         struct rb_node *n;
159         u64 end, start;
160
161         spin_lock(&info->block_group_cache_lock);
162         n = info->block_group_cache_tree.rb_node;
163
164         while (n) {
165                 cache = rb_entry(n, struct btrfs_block_group_cache,
166                                  cache_node);
167                 end = cache->key.objectid + cache->key.offset - 1;
168                 start = cache->key.objectid;
169
170                 if (bytenr < start) {
171                         if (!contains && (!ret || start < ret->key.objectid))
172                                 ret = cache;
173                         n = n->rb_left;
174                 } else if (bytenr > start) {
175                         if (contains && bytenr <= end) {
176                                 ret = cache;
177                                 break;
178                         }
179                         n = n->rb_right;
180                 } else {
181                         ret = cache;
182                         break;
183                 }
184         }
185         if (ret)
186                 btrfs_get_block_group(ret);
187         spin_unlock(&info->block_group_cache_lock);
188
189         return ret;
190 }
191
192 static int add_excluded_extent(struct btrfs_root *root,
193                                u64 start, u64 num_bytes)
194 {
195         u64 end = start + num_bytes - 1;
196         set_extent_bits(&root->fs_info->freed_extents[0],
197                         start, end, EXTENT_UPTODATE, GFP_NOFS);
198         set_extent_bits(&root->fs_info->freed_extents[1],
199                         start, end, EXTENT_UPTODATE, GFP_NOFS);
200         return 0;
201 }
202
203 static void free_excluded_extents(struct btrfs_root *root,
204                                   struct btrfs_block_group_cache *cache)
205 {
206         u64 start, end;
207
208         start = cache->key.objectid;
209         end = start + cache->key.offset - 1;
210
211         clear_extent_bits(&root->fs_info->freed_extents[0],
212                           start, end, EXTENT_UPTODATE, GFP_NOFS);
213         clear_extent_bits(&root->fs_info->freed_extents[1],
214                           start, end, EXTENT_UPTODATE, GFP_NOFS);
215 }
216
217 static int exclude_super_stripes(struct btrfs_root *root,
218                                  struct btrfs_block_group_cache *cache)
219 {
220         u64 bytenr;
221         u64 *logical;
222         int stripe_len;
223         int i, nr, ret;
224
225         if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
226                 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
227                 cache->bytes_super += stripe_len;
228                 ret = add_excluded_extent(root, cache->key.objectid,
229                                           stripe_len);
230                 BUG_ON(ret);
231         }
232
233         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
234                 bytenr = btrfs_sb_offset(i);
235                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
236                                        cache->key.objectid, bytenr,
237                                        0, &logical, &nr, &stripe_len);
238                 BUG_ON(ret);
239
240                 while (nr--) {
241                         cache->bytes_super += stripe_len;
242                         ret = add_excluded_extent(root, logical[nr],
243                                                   stripe_len);
244                         BUG_ON(ret);
245                 }
246
247                 kfree(logical);
248         }
249         return 0;
250 }
251
252 static struct btrfs_caching_control *
253 get_caching_control(struct btrfs_block_group_cache *cache)
254 {
255         struct btrfs_caching_control *ctl;
256
257         spin_lock(&cache->lock);
258         if (cache->cached != BTRFS_CACHE_STARTED) {
259                 spin_unlock(&cache->lock);
260                 return NULL;
261         }
262
263         /* We're loading it the fast way, so we don't have a caching_ctl. */
264         if (!cache->caching_ctl) {
265                 spin_unlock(&cache->lock);
266                 return NULL;
267         }
268
269         ctl = cache->caching_ctl;
270         atomic_inc(&ctl->count);
271         spin_unlock(&cache->lock);
272         return ctl;
273 }
274
275 static void put_caching_control(struct btrfs_caching_control *ctl)
276 {
277         if (atomic_dec_and_test(&ctl->count))
278                 kfree(ctl);
279 }
280
281 /*
282  * this is only called by cache_block_group, since we could have freed extents
283  * we need to check the pinned_extents for any extents that can't be used yet
284  * since their free space will be released as soon as the transaction commits.
285  */
286 static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
287                               struct btrfs_fs_info *info, u64 start, u64 end)
288 {
289         u64 extent_start, extent_end, size, total_added = 0;
290         int ret;
291
292         while (start < end) {
293                 ret = find_first_extent_bit(info->pinned_extents, start,
294                                             &extent_start, &extent_end,
295                                             EXTENT_DIRTY | EXTENT_UPTODATE);
296                 if (ret)
297                         break;
298
299                 if (extent_start <= start) {
300                         start = extent_end + 1;
301                 } else if (extent_start > start && extent_start < end) {
302                         size = extent_start - start;
303                         total_added += size;
304                         ret = btrfs_add_free_space(block_group, start,
305                                                    size);
306                         BUG_ON(ret);
307                         start = extent_end + 1;
308                 } else {
309                         break;
310                 }
311         }
312
313         if (start < end) {
314                 size = end - start;
315                 total_added += size;
316                 ret = btrfs_add_free_space(block_group, start, size);
317                 BUG_ON(ret);
318         }
319
320         return total_added;
321 }
322
323 static int caching_kthread(void *data)
324 {
325         struct btrfs_block_group_cache *block_group = data;
326         struct btrfs_fs_info *fs_info = block_group->fs_info;
327         struct btrfs_caching_control *caching_ctl = block_group->caching_ctl;
328         struct btrfs_root *extent_root = fs_info->extent_root;
329         struct btrfs_path *path;
330         struct extent_buffer *leaf;
331         struct btrfs_key key;
332         u64 total_found = 0;
333         u64 last = 0;
334         u32 nritems;
335         int ret = 0;
336
337         path = btrfs_alloc_path();
338         if (!path)
339                 return -ENOMEM;
340
341         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
342
343         /*
344          * We don't want to deadlock with somebody trying to allocate a new
345          * extent for the extent root while also trying to search the extent
346          * root to add free space.  So we skip locking and search the commit
347          * root, since its read-only
348          */
349         path->skip_locking = 1;
350         path->search_commit_root = 1;
351         path->reada = 2;
352
353         key.objectid = last;
354         key.offset = 0;
355         key.type = BTRFS_EXTENT_ITEM_KEY;
356 again:
357         mutex_lock(&caching_ctl->mutex);
358         /* need to make sure the commit_root doesn't disappear */
359         down_read(&fs_info->extent_commit_sem);
360
361         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
362         if (ret < 0)
363                 goto err;
364
365         leaf = path->nodes[0];
366         nritems = btrfs_header_nritems(leaf);
367
368         while (1) {
369                 smp_mb();
370                 if (fs_info->closing > 1) {
371                         last = (u64)-1;
372                         break;
373                 }
374
375                 if (path->slots[0] < nritems) {
376                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
377                 } else {
378                         ret = find_next_key(path, 0, &key);
379                         if (ret)
380                                 break;
381
382                         caching_ctl->progress = last;
383                         btrfs_release_path(path);
384                         up_read(&fs_info->extent_commit_sem);
385                         mutex_unlock(&caching_ctl->mutex);
386                         if (btrfs_transaction_in_commit(fs_info))
387                                 schedule_timeout(1);
388                         else
389                                 cond_resched();
390                         goto again;
391                 }
392
393                 if (key.objectid < block_group->key.objectid) {
394                         path->slots[0]++;
395                         continue;
396                 }
397
398                 if (key.objectid >= block_group->key.objectid +
399                     block_group->key.offset)
400                         break;
401
402                 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
403                         total_found += add_new_free_space(block_group,
404                                                           fs_info, last,
405                                                           key.objectid);
406                         last = key.objectid + key.offset;
407
408                         if (total_found > (1024 * 1024 * 2)) {
409                                 total_found = 0;
410                                 wake_up(&caching_ctl->wait);
411                         }
412                 }
413                 path->slots[0]++;
414         }
415         ret = 0;
416
417         total_found += add_new_free_space(block_group, fs_info, last,
418                                           block_group->key.objectid +
419                                           block_group->key.offset);
420         caching_ctl->progress = (u64)-1;
421
422         spin_lock(&block_group->lock);
423         block_group->caching_ctl = NULL;
424         block_group->cached = BTRFS_CACHE_FINISHED;
425         spin_unlock(&block_group->lock);
426
427 err:
428         btrfs_free_path(path);
429         up_read(&fs_info->extent_commit_sem);
430
431         free_excluded_extents(extent_root, block_group);
432
433         mutex_unlock(&caching_ctl->mutex);
434         wake_up(&caching_ctl->wait);
435
436         put_caching_control(caching_ctl);
437         atomic_dec(&block_group->space_info->caching_threads);
438         btrfs_put_block_group(block_group);
439
440         return 0;
441 }
442
443 static int cache_block_group(struct btrfs_block_group_cache *cache,
444                              struct btrfs_trans_handle *trans,
445                              struct btrfs_root *root,
446                              int load_cache_only)
447 {
448         struct btrfs_fs_info *fs_info = cache->fs_info;
449         struct btrfs_caching_control *caching_ctl;
450         struct task_struct *tsk;
451         int ret = 0;
452
453         smp_mb();
454         if (cache->cached != BTRFS_CACHE_NO)
455                 return 0;
456
457         /*
458          * We can't do the read from on-disk cache during a commit since we need
459          * to have the normal tree locking.  Also if we are currently trying to
460          * allocate blocks for the tree root we can't do the fast caching since
461          * we likely hold important locks.
462          */
463         if (trans && (!trans->transaction->in_commit) &&
464             (root && root != root->fs_info->tree_root)) {
465                 spin_lock(&cache->lock);
466                 if (cache->cached != BTRFS_CACHE_NO) {
467                         spin_unlock(&cache->lock);
468                         return 0;
469                 }
470                 cache->cached = BTRFS_CACHE_STARTED;
471                 spin_unlock(&cache->lock);
472
473                 ret = load_free_space_cache(fs_info, cache);
474
475                 spin_lock(&cache->lock);
476                 if (ret == 1) {
477                         cache->cached = BTRFS_CACHE_FINISHED;
478                         cache->last_byte_to_unpin = (u64)-1;
479                 } else {
480                         cache->cached = BTRFS_CACHE_NO;
481                 }
482                 spin_unlock(&cache->lock);
483                 if (ret == 1) {
484                         free_excluded_extents(fs_info->extent_root, cache);
485                         return 0;
486                 }
487         }
488
489         if (load_cache_only)
490                 return 0;
491
492         caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
493         BUG_ON(!caching_ctl);
494
495         INIT_LIST_HEAD(&caching_ctl->list);
496         mutex_init(&caching_ctl->mutex);
497         init_waitqueue_head(&caching_ctl->wait);
498         caching_ctl->block_group = cache;
499         caching_ctl->progress = cache->key.objectid;
500         /* one for caching kthread, one for caching block group list */
501         atomic_set(&caching_ctl->count, 2);
502
503         spin_lock(&cache->lock);
504         if (cache->cached != BTRFS_CACHE_NO) {
505                 spin_unlock(&cache->lock);
506                 kfree(caching_ctl);
507                 return 0;
508         }
509         cache->caching_ctl = caching_ctl;
510         cache->cached = BTRFS_CACHE_STARTED;
511         spin_unlock(&cache->lock);
512
513         down_write(&fs_info->extent_commit_sem);
514         list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
515         up_write(&fs_info->extent_commit_sem);
516
517         atomic_inc(&cache->space_info->caching_threads);
518         btrfs_get_block_group(cache);
519
520         tsk = kthread_run(caching_kthread, cache, "btrfs-cache-%llu\n",
521                           cache->key.objectid);
522         if (IS_ERR(tsk)) {
523                 ret = PTR_ERR(tsk);
524                 printk(KERN_ERR "error running thread %d\n", ret);
525                 BUG();
526         }
527
528         return ret;
529 }
530
531 /*
532  * return the block group that starts at or after bytenr
533  */
534 static struct btrfs_block_group_cache *
535 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
536 {
537         struct btrfs_block_group_cache *cache;
538
539         cache = block_group_cache_tree_search(info, bytenr, 0);
540
541         return cache;
542 }
543
544 /*
545  * return the block group that contains the given bytenr
546  */
547 struct btrfs_block_group_cache *btrfs_lookup_block_group(
548                                                  struct btrfs_fs_info *info,
549                                                  u64 bytenr)
550 {
551         struct btrfs_block_group_cache *cache;
552
553         cache = block_group_cache_tree_search(info, bytenr, 1);
554
555         return cache;
556 }
557
558 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
559                                                   u64 flags)
560 {
561         struct list_head *head = &info->space_info;
562         struct btrfs_space_info *found;
563
564         flags &= BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_SYSTEM |
565                  BTRFS_BLOCK_GROUP_METADATA;
566
567         rcu_read_lock();
568         list_for_each_entry_rcu(found, head, list) {
569                 if (found->flags & flags) {
570                         rcu_read_unlock();
571                         return found;
572                 }
573         }
574         rcu_read_unlock();
575         return NULL;
576 }
577
578 /*
579  * after adding space to the filesystem, we need to clear the full flags
580  * on all the space infos.
581  */
582 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
583 {
584         struct list_head *head = &info->space_info;
585         struct btrfs_space_info *found;
586
587         rcu_read_lock();
588         list_for_each_entry_rcu(found, head, list)
589                 found->full = 0;
590         rcu_read_unlock();
591 }
592
593 static u64 div_factor(u64 num, int factor)
594 {
595         if (factor == 10)
596                 return num;
597         num *= factor;
598         do_div(num, 10);
599         return num;
600 }
601
602 static u64 div_factor_fine(u64 num, int factor)
603 {
604         if (factor == 100)
605                 return num;
606         num *= factor;
607         do_div(num, 100);
608         return num;
609 }
610
611 u64 btrfs_find_block_group(struct btrfs_root *root,
612                            u64 search_start, u64 search_hint, int owner)
613 {
614         struct btrfs_block_group_cache *cache;
615         u64 used;
616         u64 last = max(search_hint, search_start);
617         u64 group_start = 0;
618         int full_search = 0;
619         int factor = 9;
620         int wrapped = 0;
621 again:
622         while (1) {
623                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
624                 if (!cache)
625                         break;
626
627                 spin_lock(&cache->lock);
628                 last = cache->key.objectid + cache->key.offset;
629                 used = btrfs_block_group_used(&cache->item);
630
631                 if ((full_search || !cache->ro) &&
632                     block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
633                         if (used + cache->pinned + cache->reserved <
634                             div_factor(cache->key.offset, factor)) {
635                                 group_start = cache->key.objectid;
636                                 spin_unlock(&cache->lock);
637                                 btrfs_put_block_group(cache);
638                                 goto found;
639                         }
640                 }
641                 spin_unlock(&cache->lock);
642                 btrfs_put_block_group(cache);
643                 cond_resched();
644         }
645         if (!wrapped) {
646                 last = search_start;
647                 wrapped = 1;
648                 goto again;
649         }
650         if (!full_search && factor < 10) {
651                 last = search_start;
652                 full_search = 1;
653                 factor = 10;
654                 goto again;
655         }
656 found:
657         return group_start;
658 }
659
660 /* simple helper to search for an existing extent at a given offset */
661 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
662 {
663         int ret;
664         struct btrfs_key key;
665         struct btrfs_path *path;
666
667         path = btrfs_alloc_path();
668         BUG_ON(!path);
669         key.objectid = start;
670         key.offset = len;
671         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
672         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
673                                 0, 0);
674         btrfs_free_path(path);
675         return ret;
676 }
677
678 /*
679  * helper function to lookup reference count and flags of extent.
680  *
681  * the head node for delayed ref is used to store the sum of all the
682  * reference count modifications queued up in the rbtree. the head
683  * node may also store the extent flags to set. This way you can check
684  * to see what the reference count and extent flags would be if all of
685  * the delayed refs are not processed.
686  */
687 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
688                              struct btrfs_root *root, u64 bytenr,
689                              u64 num_bytes, u64 *refs, u64 *flags)
690 {
691         struct btrfs_delayed_ref_head *head;
692         struct btrfs_delayed_ref_root *delayed_refs;
693         struct btrfs_path *path;
694         struct btrfs_extent_item *ei;
695         struct extent_buffer *leaf;
696         struct btrfs_key key;
697         u32 item_size;
698         u64 num_refs;
699         u64 extent_flags;
700         int ret;
701
702         path = btrfs_alloc_path();
703         if (!path)
704                 return -ENOMEM;
705
706         key.objectid = bytenr;
707         key.type = BTRFS_EXTENT_ITEM_KEY;
708         key.offset = num_bytes;
709         if (!trans) {
710                 path->skip_locking = 1;
711                 path->search_commit_root = 1;
712         }
713 again:
714         ret = btrfs_search_slot(trans, root->fs_info->extent_root,
715                                 &key, path, 0, 0);
716         if (ret < 0)
717                 goto out_free;
718
719         if (ret == 0) {
720                 leaf = path->nodes[0];
721                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
722                 if (item_size >= sizeof(*ei)) {
723                         ei = btrfs_item_ptr(leaf, path->slots[0],
724                                             struct btrfs_extent_item);
725                         num_refs = btrfs_extent_refs(leaf, ei);
726                         extent_flags = btrfs_extent_flags(leaf, ei);
727                 } else {
728 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
729                         struct btrfs_extent_item_v0 *ei0;
730                         BUG_ON(item_size != sizeof(*ei0));
731                         ei0 = btrfs_item_ptr(leaf, path->slots[0],
732                                              struct btrfs_extent_item_v0);
733                         num_refs = btrfs_extent_refs_v0(leaf, ei0);
734                         /* FIXME: this isn't correct for data */
735                         extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
736 #else
737                         BUG();
738 #endif
739                 }
740                 BUG_ON(num_refs == 0);
741         } else {
742                 num_refs = 0;
743                 extent_flags = 0;
744                 ret = 0;
745         }
746
747         if (!trans)
748                 goto out;
749
750         delayed_refs = &trans->transaction->delayed_refs;
751         spin_lock(&delayed_refs->lock);
752         head = btrfs_find_delayed_ref_head(trans, bytenr);
753         if (head) {
754                 if (!mutex_trylock(&head->mutex)) {
755                         atomic_inc(&head->node.refs);
756                         spin_unlock(&delayed_refs->lock);
757
758                         btrfs_release_path(path);
759
760                         /*
761                          * Mutex was contended, block until it's released and try
762                          * again
763                          */
764                         mutex_lock(&head->mutex);
765                         mutex_unlock(&head->mutex);
766                         btrfs_put_delayed_ref(&head->node);
767                         goto again;
768                 }
769                 if (head->extent_op && head->extent_op->update_flags)
770                         extent_flags |= head->extent_op->flags_to_set;
771                 else
772                         BUG_ON(num_refs == 0);
773
774                 num_refs += head->node.ref_mod;
775                 mutex_unlock(&head->mutex);
776         }
777         spin_unlock(&delayed_refs->lock);
778 out:
779         WARN_ON(num_refs == 0);
780         if (refs)
781                 *refs = num_refs;
782         if (flags)
783                 *flags = extent_flags;
784 out_free:
785         btrfs_free_path(path);
786         return ret;
787 }
788
789 /*
790  * Back reference rules.  Back refs have three main goals:
791  *
792  * 1) differentiate between all holders of references to an extent so that
793  *    when a reference is dropped we can make sure it was a valid reference
794  *    before freeing the extent.
795  *
796  * 2) Provide enough information to quickly find the holders of an extent
797  *    if we notice a given block is corrupted or bad.
798  *
799  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
800  *    maintenance.  This is actually the same as #2, but with a slightly
801  *    different use case.
802  *
803  * There are two kinds of back refs. The implicit back refs is optimized
804  * for pointers in non-shared tree blocks. For a given pointer in a block,
805  * back refs of this kind provide information about the block's owner tree
806  * and the pointer's key. These information allow us to find the block by
807  * b-tree searching. The full back refs is for pointers in tree blocks not
808  * referenced by their owner trees. The location of tree block is recorded
809  * in the back refs. Actually the full back refs is generic, and can be
810  * used in all cases the implicit back refs is used. The major shortcoming
811  * of the full back refs is its overhead. Every time a tree block gets
812  * COWed, we have to update back refs entry for all pointers in it.
813  *
814  * For a newly allocated tree block, we use implicit back refs for
815  * pointers in it. This means most tree related operations only involve
816  * implicit back refs. For a tree block created in old transaction, the
817  * only way to drop a reference to it is COW it. So we can detect the
818  * event that tree block loses its owner tree's reference and do the
819  * back refs conversion.
820  *
821  * When a tree block is COW'd through a tree, there are four cases:
822  *
823  * The reference count of the block is one and the tree is the block's
824  * owner tree. Nothing to do in this case.
825  *
826  * The reference count of the block is one and the tree is not the
827  * block's owner tree. In this case, full back refs is used for pointers
828  * in the block. Remove these full back refs, add implicit back refs for
829  * every pointers in the new block.
830  *
831  * The reference count of the block is greater than one and the tree is
832  * the block's owner tree. In this case, implicit back refs is used for
833  * pointers in the block. Add full back refs for every pointers in the
834  * block, increase lower level extents' reference counts. The original
835  * implicit back refs are entailed to the new block.
836  *
837  * The reference count of the block is greater than one and the tree is
838  * not the block's owner tree. Add implicit back refs for every pointer in
839  * the new block, increase lower level extents' reference count.
840  *
841  * Back Reference Key composing:
842  *
843  * The key objectid corresponds to the first byte in the extent,
844  * The key type is used to differentiate between types of back refs.
845  * There are different meanings of the key offset for different types
846  * of back refs.
847  *
848  * File extents can be referenced by:
849  *
850  * - multiple snapshots, subvolumes, or different generations in one subvol
851  * - different files inside a single subvolume
852  * - different offsets inside a file (bookend extents in file.c)
853  *
854  * The extent ref structure for the implicit back refs has fields for:
855  *
856  * - Objectid of the subvolume root
857  * - objectid of the file holding the reference
858  * - original offset in the file
859  * - how many bookend extents
860  *
861  * The key offset for the implicit back refs is hash of the first
862  * three fields.
863  *
864  * The extent ref structure for the full back refs has field for:
865  *
866  * - number of pointers in the tree leaf
867  *
868  * The key offset for the implicit back refs is the first byte of
869  * the tree leaf
870  *
871  * When a file extent is allocated, The implicit back refs is used.
872  * the fields are filled in:
873  *
874  *     (root_key.objectid, inode objectid, offset in file, 1)
875  *
876  * When a file extent is removed file truncation, we find the
877  * corresponding implicit back refs and check the following fields:
878  *
879  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
880  *
881  * Btree extents can be referenced by:
882  *
883  * - Different subvolumes
884  *
885  * Both the implicit back refs and the full back refs for tree blocks
886  * only consist of key. The key offset for the implicit back refs is
887  * objectid of block's owner tree. The key offset for the full back refs
888  * is the first byte of parent block.
889  *
890  * When implicit back refs is used, information about the lowest key and
891  * level of the tree block are required. These information are stored in
892  * tree block info structure.
893  */
894
895 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
896 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
897                                   struct btrfs_root *root,
898                                   struct btrfs_path *path,
899                                   u64 owner, u32 extra_size)
900 {
901         struct btrfs_extent_item *item;
902         struct btrfs_extent_item_v0 *ei0;
903         struct btrfs_extent_ref_v0 *ref0;
904         struct btrfs_tree_block_info *bi;
905         struct extent_buffer *leaf;
906         struct btrfs_key key;
907         struct btrfs_key found_key;
908         u32 new_size = sizeof(*item);
909         u64 refs;
910         int ret;
911
912         leaf = path->nodes[0];
913         BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
914
915         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
916         ei0 = btrfs_item_ptr(leaf, path->slots[0],
917                              struct btrfs_extent_item_v0);
918         refs = btrfs_extent_refs_v0(leaf, ei0);
919
920         if (owner == (u64)-1) {
921                 while (1) {
922                         if (path->slots[0] >= btrfs_header_nritems(leaf)) {
923                                 ret = btrfs_next_leaf(root, path);
924                                 if (ret < 0)
925                                         return ret;
926                                 BUG_ON(ret > 0);
927                                 leaf = path->nodes[0];
928                         }
929                         btrfs_item_key_to_cpu(leaf, &found_key,
930                                               path->slots[0]);
931                         BUG_ON(key.objectid != found_key.objectid);
932                         if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
933                                 path->slots[0]++;
934                                 continue;
935                         }
936                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
937                                               struct btrfs_extent_ref_v0);
938                         owner = btrfs_ref_objectid_v0(leaf, ref0);
939                         break;
940                 }
941         }
942         btrfs_release_path(path);
943
944         if (owner < BTRFS_FIRST_FREE_OBJECTID)
945                 new_size += sizeof(*bi);
946
947         new_size -= sizeof(*ei0);
948         ret = btrfs_search_slot(trans, root, &key, path,
949                                 new_size + extra_size, 1);
950         if (ret < 0)
951                 return ret;
952         BUG_ON(ret);
953
954         ret = btrfs_extend_item(trans, root, path, new_size);
955         BUG_ON(ret);
956
957         leaf = path->nodes[0];
958         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
959         btrfs_set_extent_refs(leaf, item, refs);
960         /* FIXME: get real generation */
961         btrfs_set_extent_generation(leaf, item, 0);
962         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
963                 btrfs_set_extent_flags(leaf, item,
964                                        BTRFS_EXTENT_FLAG_TREE_BLOCK |
965                                        BTRFS_BLOCK_FLAG_FULL_BACKREF);
966                 bi = (struct btrfs_tree_block_info *)(item + 1);
967                 /* FIXME: get first key of the block */
968                 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
969                 btrfs_set_tree_block_level(leaf, bi, (int)owner);
970         } else {
971                 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
972         }
973         btrfs_mark_buffer_dirty(leaf);
974         return 0;
975 }
976 #endif
977
978 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
979 {
980         u32 high_crc = ~(u32)0;
981         u32 low_crc = ~(u32)0;
982         __le64 lenum;
983
984         lenum = cpu_to_le64(root_objectid);
985         high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
986         lenum = cpu_to_le64(owner);
987         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
988         lenum = cpu_to_le64(offset);
989         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
990
991         return ((u64)high_crc << 31) ^ (u64)low_crc;
992 }
993
994 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
995                                      struct btrfs_extent_data_ref *ref)
996 {
997         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
998                                     btrfs_extent_data_ref_objectid(leaf, ref),
999                                     btrfs_extent_data_ref_offset(leaf, ref));
1000 }
1001
1002 static int match_extent_data_ref(struct extent_buffer *leaf,
1003                                  struct btrfs_extent_data_ref *ref,
1004                                  u64 root_objectid, u64 owner, u64 offset)
1005 {
1006         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1007             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1008             btrfs_extent_data_ref_offset(leaf, ref) != offset)
1009                 return 0;
1010         return 1;
1011 }
1012
1013 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1014                                            struct btrfs_root *root,
1015                                            struct btrfs_path *path,
1016                                            u64 bytenr, u64 parent,
1017                                            u64 root_objectid,
1018                                            u64 owner, u64 offset)
1019 {
1020         struct btrfs_key key;
1021         struct btrfs_extent_data_ref *ref;
1022         struct extent_buffer *leaf;
1023         u32 nritems;
1024         int ret;
1025         int recow;
1026         int err = -ENOENT;
1027
1028         key.objectid = bytenr;
1029         if (parent) {
1030                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1031                 key.offset = parent;
1032         } else {
1033                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1034                 key.offset = hash_extent_data_ref(root_objectid,
1035                                                   owner, offset);
1036         }
1037 again:
1038         recow = 0;
1039         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1040         if (ret < 0) {
1041                 err = ret;
1042                 goto fail;
1043         }
1044
1045         if (parent) {
1046                 if (!ret)
1047                         return 0;
1048 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1049                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1050                 btrfs_release_path(path);
1051                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1052                 if (ret < 0) {
1053                         err = ret;
1054                         goto fail;
1055                 }
1056                 if (!ret)
1057                         return 0;
1058 #endif
1059                 goto fail;
1060         }
1061
1062         leaf = path->nodes[0];
1063         nritems = btrfs_header_nritems(leaf);
1064         while (1) {
1065                 if (path->slots[0] >= nritems) {
1066                         ret = btrfs_next_leaf(root, path);
1067                         if (ret < 0)
1068                                 err = ret;
1069                         if (ret)
1070                                 goto fail;
1071
1072                         leaf = path->nodes[0];
1073                         nritems = btrfs_header_nritems(leaf);
1074                         recow = 1;
1075                 }
1076
1077                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1078                 if (key.objectid != bytenr ||
1079                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1080                         goto fail;
1081
1082                 ref = btrfs_item_ptr(leaf, path->slots[0],
1083                                      struct btrfs_extent_data_ref);
1084
1085                 if (match_extent_data_ref(leaf, ref, root_objectid,
1086                                           owner, offset)) {
1087                         if (recow) {
1088                                 btrfs_release_path(path);
1089                                 goto again;
1090                         }
1091                         err = 0;
1092                         break;
1093                 }
1094                 path->slots[0]++;
1095         }
1096 fail:
1097         return err;
1098 }
1099
1100 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1101                                            struct btrfs_root *root,
1102                                            struct btrfs_path *path,
1103                                            u64 bytenr, u64 parent,
1104                                            u64 root_objectid, u64 owner,
1105                                            u64 offset, int refs_to_add)
1106 {
1107         struct btrfs_key key;
1108         struct extent_buffer *leaf;
1109         u32 size;
1110         u32 num_refs;
1111         int ret;
1112
1113         key.objectid = bytenr;
1114         if (parent) {
1115                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1116                 key.offset = parent;
1117                 size = sizeof(struct btrfs_shared_data_ref);
1118         } else {
1119                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1120                 key.offset = hash_extent_data_ref(root_objectid,
1121                                                   owner, offset);
1122                 size = sizeof(struct btrfs_extent_data_ref);
1123         }
1124
1125         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1126         if (ret && ret != -EEXIST)
1127                 goto fail;
1128
1129         leaf = path->nodes[0];
1130         if (parent) {
1131                 struct btrfs_shared_data_ref *ref;
1132                 ref = btrfs_item_ptr(leaf, path->slots[0],
1133                                      struct btrfs_shared_data_ref);
1134                 if (ret == 0) {
1135                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1136                 } else {
1137                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1138                         num_refs += refs_to_add;
1139                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1140                 }
1141         } else {
1142                 struct btrfs_extent_data_ref *ref;
1143                 while (ret == -EEXIST) {
1144                         ref = btrfs_item_ptr(leaf, path->slots[0],
1145                                              struct btrfs_extent_data_ref);
1146                         if (match_extent_data_ref(leaf, ref, root_objectid,
1147                                                   owner, offset))
1148                                 break;
1149                         btrfs_release_path(path);
1150                         key.offset++;
1151                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1152                                                       size);
1153                         if (ret && ret != -EEXIST)
1154                                 goto fail;
1155
1156                         leaf = path->nodes[0];
1157                 }
1158                 ref = btrfs_item_ptr(leaf, path->slots[0],
1159                                      struct btrfs_extent_data_ref);
1160                 if (ret == 0) {
1161                         btrfs_set_extent_data_ref_root(leaf, ref,
1162                                                        root_objectid);
1163                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1164                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1165                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1166                 } else {
1167                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1168                         num_refs += refs_to_add;
1169                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1170                 }
1171         }
1172         btrfs_mark_buffer_dirty(leaf);
1173         ret = 0;
1174 fail:
1175         btrfs_release_path(path);
1176         return ret;
1177 }
1178
1179 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1180                                            struct btrfs_root *root,
1181                                            struct btrfs_path *path,
1182                                            int refs_to_drop)
1183 {
1184         struct btrfs_key key;
1185         struct btrfs_extent_data_ref *ref1 = NULL;
1186         struct btrfs_shared_data_ref *ref2 = NULL;
1187         struct extent_buffer *leaf;
1188         u32 num_refs = 0;
1189         int ret = 0;
1190
1191         leaf = path->nodes[0];
1192         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1193
1194         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1195                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1196                                       struct btrfs_extent_data_ref);
1197                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1198         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1199                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1200                                       struct btrfs_shared_data_ref);
1201                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1202 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1203         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1204                 struct btrfs_extent_ref_v0 *ref0;
1205                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1206                                       struct btrfs_extent_ref_v0);
1207                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1208 #endif
1209         } else {
1210                 BUG();
1211         }
1212
1213         BUG_ON(num_refs < refs_to_drop);
1214         num_refs -= refs_to_drop;
1215
1216         if (num_refs == 0) {
1217                 ret = btrfs_del_item(trans, root, path);
1218         } else {
1219                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1220                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1221                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1222                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1223 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1224                 else {
1225                         struct btrfs_extent_ref_v0 *ref0;
1226                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1227                                         struct btrfs_extent_ref_v0);
1228                         btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1229                 }
1230 #endif
1231                 btrfs_mark_buffer_dirty(leaf);
1232         }
1233         return ret;
1234 }
1235
1236 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1237                                           struct btrfs_path *path,
1238                                           struct btrfs_extent_inline_ref *iref)
1239 {
1240         struct btrfs_key key;
1241         struct extent_buffer *leaf;
1242         struct btrfs_extent_data_ref *ref1;
1243         struct btrfs_shared_data_ref *ref2;
1244         u32 num_refs = 0;
1245
1246         leaf = path->nodes[0];
1247         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1248         if (iref) {
1249                 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1250                     BTRFS_EXTENT_DATA_REF_KEY) {
1251                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1252                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1253                 } else {
1254                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1255                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1256                 }
1257         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1258                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1259                                       struct btrfs_extent_data_ref);
1260                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1261         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1262                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1263                                       struct btrfs_shared_data_ref);
1264                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1265 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1266         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1267                 struct btrfs_extent_ref_v0 *ref0;
1268                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1269                                       struct btrfs_extent_ref_v0);
1270                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1271 #endif
1272         } else {
1273                 WARN_ON(1);
1274         }
1275         return num_refs;
1276 }
1277
1278 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1279                                           struct btrfs_root *root,
1280                                           struct btrfs_path *path,
1281                                           u64 bytenr, u64 parent,
1282                                           u64 root_objectid)
1283 {
1284         struct btrfs_key key;
1285         int ret;
1286
1287         key.objectid = bytenr;
1288         if (parent) {
1289                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1290                 key.offset = parent;
1291         } else {
1292                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1293                 key.offset = root_objectid;
1294         }
1295
1296         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1297         if (ret > 0)
1298                 ret = -ENOENT;
1299 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1300         if (ret == -ENOENT && parent) {
1301                 btrfs_release_path(path);
1302                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1303                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1304                 if (ret > 0)
1305                         ret = -ENOENT;
1306         }
1307 #endif
1308         return ret;
1309 }
1310
1311 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1312                                           struct btrfs_root *root,
1313                                           struct btrfs_path *path,
1314                                           u64 bytenr, u64 parent,
1315                                           u64 root_objectid)
1316 {
1317         struct btrfs_key key;
1318         int ret;
1319
1320         key.objectid = bytenr;
1321         if (parent) {
1322                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1323                 key.offset = parent;
1324         } else {
1325                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1326                 key.offset = root_objectid;
1327         }
1328
1329         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1330         btrfs_release_path(path);
1331         return ret;
1332 }
1333
1334 static inline int extent_ref_type(u64 parent, u64 owner)
1335 {
1336         int type;
1337         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1338                 if (parent > 0)
1339                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1340                 else
1341                         type = BTRFS_TREE_BLOCK_REF_KEY;
1342         } else {
1343                 if (parent > 0)
1344                         type = BTRFS_SHARED_DATA_REF_KEY;
1345                 else
1346                         type = BTRFS_EXTENT_DATA_REF_KEY;
1347         }
1348         return type;
1349 }
1350
1351 static int find_next_key(struct btrfs_path *path, int level,
1352                          struct btrfs_key *key)
1353
1354 {
1355         for (; level < BTRFS_MAX_LEVEL; level++) {
1356                 if (!path->nodes[level])
1357                         break;
1358                 if (path->slots[level] + 1 >=
1359                     btrfs_header_nritems(path->nodes[level]))
1360                         continue;
1361                 if (level == 0)
1362                         btrfs_item_key_to_cpu(path->nodes[level], key,
1363                                               path->slots[level] + 1);
1364                 else
1365                         btrfs_node_key_to_cpu(path->nodes[level], key,
1366                                               path->slots[level] + 1);
1367                 return 0;
1368         }
1369         return 1;
1370 }
1371
1372 /*
1373  * look for inline back ref. if back ref is found, *ref_ret is set
1374  * to the address of inline back ref, and 0 is returned.
1375  *
1376  * if back ref isn't found, *ref_ret is set to the address where it
1377  * should be inserted, and -ENOENT is returned.
1378  *
1379  * if insert is true and there are too many inline back refs, the path
1380  * points to the extent item, and -EAGAIN is returned.
1381  *
1382  * NOTE: inline back refs are ordered in the same way that back ref
1383  *       items in the tree are ordered.
1384  */
1385 static noinline_for_stack
1386 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1387                                  struct btrfs_root *root,
1388                                  struct btrfs_path *path,
1389                                  struct btrfs_extent_inline_ref **ref_ret,
1390                                  u64 bytenr, u64 num_bytes,
1391                                  u64 parent, u64 root_objectid,
1392                                  u64 owner, u64 offset, int insert)
1393 {
1394         struct btrfs_key key;
1395         struct extent_buffer *leaf;
1396         struct btrfs_extent_item *ei;
1397         struct btrfs_extent_inline_ref *iref;
1398         u64 flags;
1399         u64 item_size;
1400         unsigned long ptr;
1401         unsigned long end;
1402         int extra_size;
1403         int type;
1404         int want;
1405         int ret;
1406         int err = 0;
1407
1408         key.objectid = bytenr;
1409         key.type = BTRFS_EXTENT_ITEM_KEY;
1410         key.offset = num_bytes;
1411
1412         want = extent_ref_type(parent, owner);
1413         if (insert) {
1414                 extra_size = btrfs_extent_inline_ref_size(want);
1415                 path->keep_locks = 1;
1416         } else
1417                 extra_size = -1;
1418         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1419         if (ret < 0) {
1420                 err = ret;
1421                 goto out;
1422         }
1423         BUG_ON(ret);
1424
1425         leaf = path->nodes[0];
1426         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1427 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1428         if (item_size < sizeof(*ei)) {
1429                 if (!insert) {
1430                         err = -ENOENT;
1431                         goto out;
1432                 }
1433                 ret = convert_extent_item_v0(trans, root, path, owner,
1434                                              extra_size);
1435                 if (ret < 0) {
1436                         err = ret;
1437                         goto out;
1438                 }
1439                 leaf = path->nodes[0];
1440                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1441         }
1442 #endif
1443         BUG_ON(item_size < sizeof(*ei));
1444
1445         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1446         flags = btrfs_extent_flags(leaf, ei);
1447
1448         ptr = (unsigned long)(ei + 1);
1449         end = (unsigned long)ei + item_size;
1450
1451         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1452                 ptr += sizeof(struct btrfs_tree_block_info);
1453                 BUG_ON(ptr > end);
1454         } else {
1455                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1456         }
1457
1458         err = -ENOENT;
1459         while (1) {
1460                 if (ptr >= end) {
1461                         WARN_ON(ptr > end);
1462                         break;
1463                 }
1464                 iref = (struct btrfs_extent_inline_ref *)ptr;
1465                 type = btrfs_extent_inline_ref_type(leaf, iref);
1466                 if (want < type)
1467                         break;
1468                 if (want > type) {
1469                         ptr += btrfs_extent_inline_ref_size(type);
1470                         continue;
1471                 }
1472
1473                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1474                         struct btrfs_extent_data_ref *dref;
1475                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1476                         if (match_extent_data_ref(leaf, dref, root_objectid,
1477                                                   owner, offset)) {
1478                                 err = 0;
1479                                 break;
1480                         }
1481                         if (hash_extent_data_ref_item(leaf, dref) <
1482                             hash_extent_data_ref(root_objectid, owner, offset))
1483                                 break;
1484                 } else {
1485                         u64 ref_offset;
1486                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1487                         if (parent > 0) {
1488                                 if (parent == ref_offset) {
1489                                         err = 0;
1490                                         break;
1491                                 }
1492                                 if (ref_offset < parent)
1493                                         break;
1494                         } else {
1495                                 if (root_objectid == ref_offset) {
1496                                         err = 0;
1497                                         break;
1498                                 }
1499                                 if (ref_offset < root_objectid)
1500                                         break;
1501                         }
1502                 }
1503                 ptr += btrfs_extent_inline_ref_size(type);
1504         }
1505         if (err == -ENOENT && insert) {
1506                 if (item_size + extra_size >=
1507                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1508                         err = -EAGAIN;
1509                         goto out;
1510                 }
1511                 /*
1512                  * To add new inline back ref, we have to make sure
1513                  * there is no corresponding back ref item.
1514                  * For simplicity, we just do not add new inline back
1515                  * ref if there is any kind of item for this block
1516                  */
1517                 if (find_next_key(path, 0, &key) == 0 &&
1518                     key.objectid == bytenr &&
1519                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1520                         err = -EAGAIN;
1521                         goto out;
1522                 }
1523         }
1524         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1525 out:
1526         if (insert) {
1527                 path->keep_locks = 0;
1528                 btrfs_unlock_up_safe(path, 1);
1529         }
1530         return err;
1531 }
1532
1533 /*
1534  * helper to add new inline back ref
1535  */
1536 static noinline_for_stack
1537 int setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1538                                 struct btrfs_root *root,
1539                                 struct btrfs_path *path,
1540                                 struct btrfs_extent_inline_ref *iref,
1541                                 u64 parent, u64 root_objectid,
1542                                 u64 owner, u64 offset, int refs_to_add,
1543                                 struct btrfs_delayed_extent_op *extent_op)
1544 {
1545         struct extent_buffer *leaf;
1546         struct btrfs_extent_item *ei;
1547         unsigned long ptr;
1548         unsigned long end;
1549         unsigned long item_offset;
1550         u64 refs;
1551         int size;
1552         int type;
1553         int ret;
1554
1555         leaf = path->nodes[0];
1556         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1557         item_offset = (unsigned long)iref - (unsigned long)ei;
1558
1559         type = extent_ref_type(parent, owner);
1560         size = btrfs_extent_inline_ref_size(type);
1561
1562         ret = btrfs_extend_item(trans, root, path, size);
1563         BUG_ON(ret);
1564
1565         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1566         refs = btrfs_extent_refs(leaf, ei);
1567         refs += refs_to_add;
1568         btrfs_set_extent_refs(leaf, ei, refs);
1569         if (extent_op)
1570                 __run_delayed_extent_op(extent_op, leaf, ei);
1571
1572         ptr = (unsigned long)ei + item_offset;
1573         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1574         if (ptr < end - size)
1575                 memmove_extent_buffer(leaf, ptr + size, ptr,
1576                                       end - size - ptr);
1577
1578         iref = (struct btrfs_extent_inline_ref *)ptr;
1579         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1580         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1581                 struct btrfs_extent_data_ref *dref;
1582                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1583                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1584                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1585                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1586                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1587         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1588                 struct btrfs_shared_data_ref *sref;
1589                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1590                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1591                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1592         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1593                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1594         } else {
1595                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1596         }
1597         btrfs_mark_buffer_dirty(leaf);
1598         return 0;
1599 }
1600
1601 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1602                                  struct btrfs_root *root,
1603                                  struct btrfs_path *path,
1604                                  struct btrfs_extent_inline_ref **ref_ret,
1605                                  u64 bytenr, u64 num_bytes, u64 parent,
1606                                  u64 root_objectid, u64 owner, u64 offset)
1607 {
1608         int ret;
1609
1610         ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1611                                            bytenr, num_bytes, parent,
1612                                            root_objectid, owner, offset, 0);
1613         if (ret != -ENOENT)
1614                 return ret;
1615
1616         btrfs_release_path(path);
1617         *ref_ret = NULL;
1618
1619         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1620                 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1621                                             root_objectid);
1622         } else {
1623                 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1624                                              root_objectid, owner, offset);
1625         }
1626         return ret;
1627 }
1628
1629 /*
1630  * helper to update/remove inline back ref
1631  */
1632 static noinline_for_stack
1633 int update_inline_extent_backref(struct btrfs_trans_handle *trans,
1634                                  struct btrfs_root *root,
1635                                  struct btrfs_path *path,
1636                                  struct btrfs_extent_inline_ref *iref,
1637                                  int refs_to_mod,
1638                                  struct btrfs_delayed_extent_op *extent_op)
1639 {
1640         struct extent_buffer *leaf;
1641         struct btrfs_extent_item *ei;
1642         struct btrfs_extent_data_ref *dref = NULL;
1643         struct btrfs_shared_data_ref *sref = NULL;
1644         unsigned long ptr;
1645         unsigned long end;
1646         u32 item_size;
1647         int size;
1648         int type;
1649         int ret;
1650         u64 refs;
1651
1652         leaf = path->nodes[0];
1653         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1654         refs = btrfs_extent_refs(leaf, ei);
1655         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1656         refs += refs_to_mod;
1657         btrfs_set_extent_refs(leaf, ei, refs);
1658         if (extent_op)
1659                 __run_delayed_extent_op(extent_op, leaf, ei);
1660
1661         type = btrfs_extent_inline_ref_type(leaf, iref);
1662
1663         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1664                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1665                 refs = btrfs_extent_data_ref_count(leaf, dref);
1666         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1667                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1668                 refs = btrfs_shared_data_ref_count(leaf, sref);
1669         } else {
1670                 refs = 1;
1671                 BUG_ON(refs_to_mod != -1);
1672         }
1673
1674         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1675         refs += refs_to_mod;
1676
1677         if (refs > 0) {
1678                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1679                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1680                 else
1681                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1682         } else {
1683                 size =  btrfs_extent_inline_ref_size(type);
1684                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1685                 ptr = (unsigned long)iref;
1686                 end = (unsigned long)ei + item_size;
1687                 if (ptr + size < end)
1688                         memmove_extent_buffer(leaf, ptr, ptr + size,
1689                                               end - ptr - size);
1690                 item_size -= size;
1691                 ret = btrfs_truncate_item(trans, root, path, item_size, 1);
1692                 BUG_ON(ret);
1693         }
1694         btrfs_mark_buffer_dirty(leaf);
1695         return 0;
1696 }
1697
1698 static noinline_for_stack
1699 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1700                                  struct btrfs_root *root,
1701                                  struct btrfs_path *path,
1702                                  u64 bytenr, u64 num_bytes, u64 parent,
1703                                  u64 root_objectid, u64 owner,
1704                                  u64 offset, int refs_to_add,
1705                                  struct btrfs_delayed_extent_op *extent_op)
1706 {
1707         struct btrfs_extent_inline_ref *iref;
1708         int ret;
1709
1710         ret = lookup_inline_extent_backref(trans, root, path, &iref,
1711                                            bytenr, num_bytes, parent,
1712                                            root_objectid, owner, offset, 1);
1713         if (ret == 0) {
1714                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1715                 ret = update_inline_extent_backref(trans, root, path, iref,
1716                                                    refs_to_add, extent_op);
1717         } else if (ret == -ENOENT) {
1718                 ret = setup_inline_extent_backref(trans, root, path, iref,
1719                                                   parent, root_objectid,
1720                                                   owner, offset, refs_to_add,
1721                                                   extent_op);
1722         }
1723         return ret;
1724 }
1725
1726 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1727                                  struct btrfs_root *root,
1728                                  struct btrfs_path *path,
1729                                  u64 bytenr, u64 parent, u64 root_objectid,
1730                                  u64 owner, u64 offset, int refs_to_add)
1731 {
1732         int ret;
1733         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1734                 BUG_ON(refs_to_add != 1);
1735                 ret = insert_tree_block_ref(trans, root, path, bytenr,
1736                                             parent, root_objectid);
1737         } else {
1738                 ret = insert_extent_data_ref(trans, root, path, bytenr,
1739                                              parent, root_objectid,
1740                                              owner, offset, refs_to_add);
1741         }
1742         return ret;
1743 }
1744
1745 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1746                                  struct btrfs_root *root,
1747                                  struct btrfs_path *path,
1748                                  struct btrfs_extent_inline_ref *iref,
1749                                  int refs_to_drop, int is_data)
1750 {
1751         int ret;
1752
1753         BUG_ON(!is_data && refs_to_drop != 1);
1754         if (iref) {
1755                 ret = update_inline_extent_backref(trans, root, path, iref,
1756                                                    -refs_to_drop, NULL);
1757         } else if (is_data) {
1758                 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1759         } else {
1760                 ret = btrfs_del_item(trans, root, path);
1761         }
1762         return ret;
1763 }
1764
1765 static int btrfs_issue_discard(struct block_device *bdev,
1766                                 u64 start, u64 len)
1767 {
1768         return blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_NOFS, 0);
1769 }
1770
1771 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1772                                 u64 num_bytes, u64 *actual_bytes)
1773 {
1774         int ret;
1775         u64 discarded_bytes = 0;
1776         struct btrfs_multi_bio *multi = NULL;
1777
1778
1779         /* Tell the block device(s) that the sectors can be discarded */
1780         ret = btrfs_map_block(&root->fs_info->mapping_tree, REQ_DISCARD,
1781                               bytenr, &num_bytes, &multi, 0);
1782         if (!ret) {
1783                 struct btrfs_bio_stripe *stripe = multi->stripes;
1784                 int i;
1785
1786
1787                 for (i = 0; i < multi->num_stripes; i++, stripe++) {
1788                         ret = btrfs_issue_discard(stripe->dev->bdev,
1789                                                   stripe->physical,
1790                                                   stripe->length);
1791                         if (!ret)
1792                                 discarded_bytes += stripe->length;
1793                         else if (ret != -EOPNOTSUPP)
1794                                 break;
1795                 }
1796                 kfree(multi);
1797         }
1798         if (discarded_bytes && ret == -EOPNOTSUPP)
1799                 ret = 0;
1800
1801         if (actual_bytes)
1802                 *actual_bytes = discarded_bytes;
1803
1804
1805         return ret;
1806 }
1807
1808 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1809                          struct btrfs_root *root,
1810                          u64 bytenr, u64 num_bytes, u64 parent,
1811                          u64 root_objectid, u64 owner, u64 offset)
1812 {
1813         int ret;
1814         BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1815                root_objectid == BTRFS_TREE_LOG_OBJECTID);
1816
1817         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1818                 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
1819                                         parent, root_objectid, (int)owner,
1820                                         BTRFS_ADD_DELAYED_REF, NULL);
1821         } else {
1822                 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
1823                                         parent, root_objectid, owner, offset,
1824                                         BTRFS_ADD_DELAYED_REF, NULL);
1825         }
1826         return ret;
1827 }
1828
1829 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1830                                   struct btrfs_root *root,
1831                                   u64 bytenr, u64 num_bytes,
1832                                   u64 parent, u64 root_objectid,
1833                                   u64 owner, u64 offset, int refs_to_add,
1834                                   struct btrfs_delayed_extent_op *extent_op)
1835 {
1836         struct btrfs_path *path;
1837         struct extent_buffer *leaf;
1838         struct btrfs_extent_item *item;
1839         u64 refs;
1840         int ret;
1841         int err = 0;
1842
1843         path = btrfs_alloc_path();
1844         if (!path)
1845                 return -ENOMEM;
1846
1847         path->reada = 1;
1848         path->leave_spinning = 1;
1849         /* this will setup the path even if it fails to insert the back ref */
1850         ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1851                                            path, bytenr, num_bytes, parent,
1852                                            root_objectid, owner, offset,
1853                                            refs_to_add, extent_op);
1854         if (ret == 0)
1855                 goto out;
1856
1857         if (ret != -EAGAIN) {
1858                 err = ret;
1859                 goto out;
1860         }
1861
1862         leaf = path->nodes[0];
1863         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1864         refs = btrfs_extent_refs(leaf, item);
1865         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1866         if (extent_op)
1867                 __run_delayed_extent_op(extent_op, leaf, item);
1868
1869         btrfs_mark_buffer_dirty(leaf);
1870         btrfs_release_path(path);
1871
1872         path->reada = 1;
1873         path->leave_spinning = 1;
1874
1875         /* now insert the actual backref */
1876         ret = insert_extent_backref(trans, root->fs_info->extent_root,
1877                                     path, bytenr, parent, root_objectid,
1878                                     owner, offset, refs_to_add);
1879         BUG_ON(ret);
1880 out:
1881         btrfs_free_path(path);
1882         return err;
1883 }
1884
1885 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1886                                 struct btrfs_root *root,
1887                                 struct btrfs_delayed_ref_node *node,
1888                                 struct btrfs_delayed_extent_op *extent_op,
1889                                 int insert_reserved)
1890 {
1891         int ret = 0;
1892         struct btrfs_delayed_data_ref *ref;
1893         struct btrfs_key ins;
1894         u64 parent = 0;
1895         u64 ref_root = 0;
1896         u64 flags = 0;
1897
1898         ins.objectid = node->bytenr;
1899         ins.offset = node->num_bytes;
1900         ins.type = BTRFS_EXTENT_ITEM_KEY;
1901
1902         ref = btrfs_delayed_node_to_data_ref(node);
1903         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1904                 parent = ref->parent;
1905         else
1906                 ref_root = ref->root;
1907
1908         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1909                 if (extent_op) {
1910                         BUG_ON(extent_op->update_key);
1911                         flags |= extent_op->flags_to_set;
1912                 }
1913                 ret = alloc_reserved_file_extent(trans, root,
1914                                                  parent, ref_root, flags,
1915                                                  ref->objectid, ref->offset,
1916                                                  &ins, node->ref_mod);
1917         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1918                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1919                                              node->num_bytes, parent,
1920                                              ref_root, ref->objectid,
1921                                              ref->offset, node->ref_mod,
1922                                              extent_op);
1923         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1924                 ret = __btrfs_free_extent(trans, root, node->bytenr,
1925                                           node->num_bytes, parent,
1926                                           ref_root, ref->objectid,
1927                                           ref->offset, node->ref_mod,
1928                                           extent_op);
1929         } else {
1930                 BUG();
1931         }
1932         return ret;
1933 }
1934
1935 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1936                                     struct extent_buffer *leaf,
1937                                     struct btrfs_extent_item *ei)
1938 {
1939         u64 flags = btrfs_extent_flags(leaf, ei);
1940         if (extent_op->update_flags) {
1941                 flags |= extent_op->flags_to_set;
1942                 btrfs_set_extent_flags(leaf, ei, flags);
1943         }
1944
1945         if (extent_op->update_key) {
1946                 struct btrfs_tree_block_info *bi;
1947                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1948                 bi = (struct btrfs_tree_block_info *)(ei + 1);
1949                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1950         }
1951 }
1952
1953 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1954                                  struct btrfs_root *root,
1955                                  struct btrfs_delayed_ref_node *node,
1956                                  struct btrfs_delayed_extent_op *extent_op)
1957 {
1958         struct btrfs_key key;
1959         struct btrfs_path *path;
1960         struct btrfs_extent_item *ei;
1961         struct extent_buffer *leaf;
1962         u32 item_size;
1963         int ret;
1964         int err = 0;
1965
1966         path = btrfs_alloc_path();
1967         if (!path)
1968                 return -ENOMEM;
1969
1970         key.objectid = node->bytenr;
1971         key.type = BTRFS_EXTENT_ITEM_KEY;
1972         key.offset = node->num_bytes;
1973
1974         path->reada = 1;
1975         path->leave_spinning = 1;
1976         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
1977                                 path, 0, 1);
1978         if (ret < 0) {
1979                 err = ret;
1980                 goto out;
1981         }
1982         if (ret > 0) {
1983                 err = -EIO;
1984                 goto out;
1985         }
1986
1987         leaf = path->nodes[0];
1988         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1989 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1990         if (item_size < sizeof(*ei)) {
1991                 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
1992                                              path, (u64)-1, 0);
1993                 if (ret < 0) {
1994                         err = ret;
1995                         goto out;
1996                 }
1997                 leaf = path->nodes[0];
1998                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1999         }
2000 #endif
2001         BUG_ON(item_size < sizeof(*ei));
2002         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2003         __run_delayed_extent_op(extent_op, leaf, ei);
2004
2005         btrfs_mark_buffer_dirty(leaf);
2006 out:
2007         btrfs_free_path(path);
2008         return err;
2009 }
2010
2011 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2012                                 struct btrfs_root *root,
2013                                 struct btrfs_delayed_ref_node *node,
2014                                 struct btrfs_delayed_extent_op *extent_op,
2015                                 int insert_reserved)
2016 {
2017         int ret = 0;
2018         struct btrfs_delayed_tree_ref *ref;
2019         struct btrfs_key ins;
2020         u64 parent = 0;
2021         u64 ref_root = 0;
2022
2023         ins.objectid = node->bytenr;
2024         ins.offset = node->num_bytes;
2025         ins.type = BTRFS_EXTENT_ITEM_KEY;
2026
2027         ref = btrfs_delayed_node_to_tree_ref(node);
2028         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2029                 parent = ref->parent;
2030         else
2031                 ref_root = ref->root;
2032
2033         BUG_ON(node->ref_mod != 1);
2034         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2035                 BUG_ON(!extent_op || !extent_op->update_flags ||
2036                        !extent_op->update_key);
2037                 ret = alloc_reserved_tree_block(trans, root,
2038                                                 parent, ref_root,
2039                                                 extent_op->flags_to_set,
2040                                                 &extent_op->key,
2041                                                 ref->level, &ins);
2042         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2043                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2044                                              node->num_bytes, parent, ref_root,
2045                                              ref->level, 0, 1, extent_op);
2046         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2047                 ret = __btrfs_free_extent(trans, root, node->bytenr,
2048                                           node->num_bytes, parent, ref_root,
2049                                           ref->level, 0, 1, extent_op);
2050         } else {
2051                 BUG();
2052         }
2053         return ret;
2054 }
2055
2056 /* helper function to actually process a single delayed ref entry */
2057 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2058                                struct btrfs_root *root,
2059                                struct btrfs_delayed_ref_node *node,
2060                                struct btrfs_delayed_extent_op *extent_op,
2061                                int insert_reserved)
2062 {
2063         int ret;
2064         if (btrfs_delayed_ref_is_head(node)) {
2065                 struct btrfs_delayed_ref_head *head;
2066                 /*
2067                  * we've hit the end of the chain and we were supposed
2068                  * to insert this extent into the tree.  But, it got
2069                  * deleted before we ever needed to insert it, so all
2070                  * we have to do is clean up the accounting
2071                  */
2072                 BUG_ON(extent_op);
2073                 head = btrfs_delayed_node_to_head(node);
2074                 if (insert_reserved) {
2075                         btrfs_pin_extent(root, node->bytenr,
2076                                          node->num_bytes, 1);
2077                         if (head->is_data) {
2078                                 ret = btrfs_del_csums(trans, root,
2079                                                       node->bytenr,
2080                                                       node->num_bytes);
2081                                 BUG_ON(ret);
2082                         }
2083                 }
2084                 mutex_unlock(&head->mutex);
2085                 return 0;
2086         }
2087
2088         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2089             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2090                 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2091                                            insert_reserved);
2092         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2093                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2094                 ret = run_delayed_data_ref(trans, root, node, extent_op,
2095                                            insert_reserved);
2096         else
2097                 BUG();
2098         return ret;
2099 }
2100
2101 static noinline struct btrfs_delayed_ref_node *
2102 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2103 {
2104         struct rb_node *node;
2105         struct btrfs_delayed_ref_node *ref;
2106         int action = BTRFS_ADD_DELAYED_REF;
2107 again:
2108         /*
2109          * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2110          * this prevents ref count from going down to zero when
2111          * there still are pending delayed ref.
2112          */
2113         node = rb_prev(&head->node.rb_node);
2114         while (1) {
2115                 if (!node)
2116                         break;
2117                 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2118                                 rb_node);
2119                 if (ref->bytenr != head->node.bytenr)
2120                         break;
2121                 if (ref->action == action)
2122                         return ref;
2123                 node = rb_prev(node);
2124         }
2125         if (action == BTRFS_ADD_DELAYED_REF) {
2126                 action = BTRFS_DROP_DELAYED_REF;
2127                 goto again;
2128         }
2129         return NULL;
2130 }
2131
2132 static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
2133                                        struct btrfs_root *root,
2134                                        struct list_head *cluster)
2135 {
2136         struct btrfs_delayed_ref_root *delayed_refs;
2137         struct btrfs_delayed_ref_node *ref;
2138         struct btrfs_delayed_ref_head *locked_ref = NULL;
2139         struct btrfs_delayed_extent_op *extent_op;
2140         int ret;
2141         int count = 0;
2142         int must_insert_reserved = 0;
2143
2144         delayed_refs = &trans->transaction->delayed_refs;
2145         while (1) {
2146                 if (!locked_ref) {
2147                         /* pick a new head ref from the cluster list */
2148                         if (list_empty(cluster))
2149                                 break;
2150
2151                         locked_ref = list_entry(cluster->next,
2152                                      struct btrfs_delayed_ref_head, cluster);
2153
2154                         /* grab the lock that says we are going to process
2155                          * all the refs for this head */
2156                         ret = btrfs_delayed_ref_lock(trans, locked_ref);
2157
2158                         /*
2159                          * we may have dropped the spin lock to get the head
2160                          * mutex lock, and that might have given someone else
2161                          * time to free the head.  If that's true, it has been
2162                          * removed from our list and we can move on.
2163                          */
2164                         if (ret == -EAGAIN) {
2165                                 locked_ref = NULL;
2166                                 count++;
2167                                 continue;
2168                         }
2169                 }
2170
2171                 /*
2172                  * record the must insert reserved flag before we
2173                  * drop the spin lock.
2174                  */
2175                 must_insert_reserved = locked_ref->must_insert_reserved;
2176                 locked_ref->must_insert_reserved = 0;
2177
2178                 extent_op = locked_ref->extent_op;
2179                 locked_ref->extent_op = NULL;
2180
2181                 /*
2182                  * locked_ref is the head node, so we have to go one
2183                  * node back for any delayed ref updates
2184                  */
2185                 ref = select_delayed_ref(locked_ref);
2186                 if (!ref) {
2187                         /* All delayed refs have been processed, Go ahead
2188                          * and send the head node to run_one_delayed_ref,
2189                          * so that any accounting fixes can happen
2190                          */
2191                         ref = &locked_ref->node;
2192
2193                         if (extent_op && must_insert_reserved) {
2194                                 kfree(extent_op);
2195                                 extent_op = NULL;
2196                         }
2197
2198                         if (extent_op) {
2199                                 spin_unlock(&delayed_refs->lock);
2200
2201                                 ret = run_delayed_extent_op(trans, root,
2202                                                             ref, extent_op);
2203                                 BUG_ON(ret);
2204                                 kfree(extent_op);
2205
2206                                 cond_resched();
2207                                 spin_lock(&delayed_refs->lock);
2208                                 continue;
2209                         }
2210
2211                         list_del_init(&locked_ref->cluster);
2212                         locked_ref = NULL;
2213                 }
2214
2215                 ref->in_tree = 0;
2216                 rb_erase(&ref->rb_node, &delayed_refs->root);
2217                 delayed_refs->num_entries--;
2218
2219                 spin_unlock(&delayed_refs->lock);
2220
2221                 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2222                                           must_insert_reserved);
2223                 BUG_ON(ret);
2224
2225                 btrfs_put_delayed_ref(ref);
2226                 kfree(extent_op);
2227                 count++;
2228
2229                 cond_resched();
2230                 spin_lock(&delayed_refs->lock);
2231         }
2232         return count;
2233 }
2234
2235 /*
2236  * this starts processing the delayed reference count updates and
2237  * extent insertions we have queued up so far.  count can be
2238  * 0, which means to process everything in the tree at the start
2239  * of the run (but not newly added entries), or it can be some target
2240  * number you'd like to process.
2241  */
2242 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2243                            struct btrfs_root *root, unsigned long count)
2244 {
2245         struct rb_node *node;
2246         struct btrfs_delayed_ref_root *delayed_refs;
2247         struct btrfs_delayed_ref_node *ref;
2248         struct list_head cluster;
2249         int ret;
2250         int run_all = count == (unsigned long)-1;
2251         int run_most = 0;
2252
2253         if (root == root->fs_info->extent_root)
2254                 root = root->fs_info->tree_root;
2255
2256         delayed_refs = &trans->transaction->delayed_refs;
2257         INIT_LIST_HEAD(&cluster);
2258 again:
2259         spin_lock(&delayed_refs->lock);
2260         if (count == 0) {
2261                 count = delayed_refs->num_entries * 2;
2262                 run_most = 1;
2263         }
2264         while (1) {
2265                 if (!(run_all || run_most) &&
2266                     delayed_refs->num_heads_ready < 64)
2267                         break;
2268
2269                 /*
2270                  * go find something we can process in the rbtree.  We start at
2271                  * the beginning of the tree, and then build a cluster
2272                  * of refs to process starting at the first one we are able to
2273                  * lock
2274                  */
2275                 ret = btrfs_find_ref_cluster(trans, &cluster,
2276                                              delayed_refs->run_delayed_start);
2277                 if (ret)
2278                         break;
2279
2280                 ret = run_clustered_refs(trans, root, &cluster);
2281                 BUG_ON(ret < 0);
2282
2283                 count -= min_t(unsigned long, ret, count);
2284
2285                 if (count == 0)
2286                         break;
2287         }
2288
2289         if (run_all) {
2290                 node = rb_first(&delayed_refs->root);
2291                 if (!node)
2292                         goto out;
2293                 count = (unsigned long)-1;
2294
2295                 while (node) {
2296                         ref = rb_entry(node, struct btrfs_delayed_ref_node,
2297                                        rb_node);
2298                         if (btrfs_delayed_ref_is_head(ref)) {
2299                                 struct btrfs_delayed_ref_head *head;
2300
2301                                 head = btrfs_delayed_node_to_head(ref);
2302                                 atomic_inc(&ref->refs);
2303
2304                                 spin_unlock(&delayed_refs->lock);
2305                                 /*
2306                                  * Mutex was contended, block until it's
2307                                  * released and try again
2308                                  */
2309                                 mutex_lock(&head->mutex);
2310                                 mutex_unlock(&head->mutex);
2311
2312                                 btrfs_put_delayed_ref(ref);
2313                                 cond_resched();
2314                                 goto again;
2315                         }
2316                         node = rb_next(node);
2317                 }
2318                 spin_unlock(&delayed_refs->lock);
2319                 schedule_timeout(1);
2320                 goto again;
2321         }
2322 out:
2323         spin_unlock(&delayed_refs->lock);
2324         return 0;
2325 }
2326
2327 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2328                                 struct btrfs_root *root,
2329                                 u64 bytenr, u64 num_bytes, u64 flags,
2330                                 int is_data)
2331 {
2332         struct btrfs_delayed_extent_op *extent_op;
2333         int ret;
2334
2335         extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2336         if (!extent_op)
2337                 return -ENOMEM;
2338
2339         extent_op->flags_to_set = flags;
2340         extent_op->update_flags = 1;
2341         extent_op->update_key = 0;
2342         extent_op->is_data = is_data ? 1 : 0;
2343
2344         ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2345         if (ret)
2346                 kfree(extent_op);
2347         return ret;
2348 }
2349
2350 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2351                                       struct btrfs_root *root,
2352                                       struct btrfs_path *path,
2353                                       u64 objectid, u64 offset, u64 bytenr)
2354 {
2355         struct btrfs_delayed_ref_head *head;
2356         struct btrfs_delayed_ref_node *ref;
2357         struct btrfs_delayed_data_ref *data_ref;
2358         struct btrfs_delayed_ref_root *delayed_refs;
2359         struct rb_node *node;
2360         int ret = 0;
2361
2362         ret = -ENOENT;
2363         delayed_refs = &trans->transaction->delayed_refs;
2364         spin_lock(&delayed_refs->lock);
2365         head = btrfs_find_delayed_ref_head(trans, bytenr);
2366         if (!head)
2367                 goto out;
2368
2369         if (!mutex_trylock(&head->mutex)) {
2370                 atomic_inc(&head->node.refs);
2371                 spin_unlock(&delayed_refs->lock);
2372
2373                 btrfs_release_path(path);
2374
2375                 /*
2376                  * Mutex was contended, block until it's released and let
2377                  * caller try again
2378                  */
2379                 mutex_lock(&head->mutex);
2380                 mutex_unlock(&head->mutex);
2381                 btrfs_put_delayed_ref(&head->node);
2382                 return -EAGAIN;
2383         }
2384
2385         node = rb_prev(&head->node.rb_node);
2386         if (!node)
2387                 goto out_unlock;
2388
2389         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2390
2391         if (ref->bytenr != bytenr)
2392                 goto out_unlock;
2393
2394         ret = 1;
2395         if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2396                 goto out_unlock;
2397
2398         data_ref = btrfs_delayed_node_to_data_ref(ref);
2399
2400         node = rb_prev(node);
2401         if (node) {
2402                 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2403                 if (ref->bytenr == bytenr)
2404                         goto out_unlock;
2405         }
2406
2407         if (data_ref->root != root->root_key.objectid ||
2408             data_ref->objectid != objectid || data_ref->offset != offset)
2409                 goto out_unlock;
2410
2411         ret = 0;
2412 out_unlock:
2413         mutex_unlock(&head->mutex);
2414 out:
2415         spin_unlock(&delayed_refs->lock);
2416         return ret;
2417 }
2418
2419 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2420                                         struct btrfs_root *root,
2421                                         struct btrfs_path *path,
2422                                         u64 objectid, u64 offset, u64 bytenr)
2423 {
2424         struct btrfs_root *extent_root = root->fs_info->extent_root;
2425         struct extent_buffer *leaf;
2426         struct btrfs_extent_data_ref *ref;
2427         struct btrfs_extent_inline_ref *iref;
2428         struct btrfs_extent_item *ei;
2429         struct btrfs_key key;
2430         u32 item_size;
2431         int ret;
2432
2433         key.objectid = bytenr;
2434         key.offset = (u64)-1;
2435         key.type = BTRFS_EXTENT_ITEM_KEY;
2436
2437         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2438         if (ret < 0)
2439                 goto out;
2440         BUG_ON(ret == 0);
2441
2442         ret = -ENOENT;
2443         if (path->slots[0] == 0)
2444                 goto out;
2445
2446         path->slots[0]--;
2447         leaf = path->nodes[0];
2448         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2449
2450         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2451                 goto out;
2452
2453         ret = 1;
2454         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2455 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2456         if (item_size < sizeof(*ei)) {
2457                 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2458                 goto out;
2459         }
2460 #endif
2461         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2462
2463         if (item_size != sizeof(*ei) +
2464             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2465                 goto out;
2466
2467         if (btrfs_extent_generation(leaf, ei) <=
2468             btrfs_root_last_snapshot(&root->root_item))
2469                 goto out;
2470
2471         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2472         if (btrfs_extent_inline_ref_type(leaf, iref) !=
2473             BTRFS_EXTENT_DATA_REF_KEY)
2474                 goto out;
2475
2476         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2477         if (btrfs_extent_refs(leaf, ei) !=
2478             btrfs_extent_data_ref_count(leaf, ref) ||
2479             btrfs_extent_data_ref_root(leaf, ref) !=
2480             root->root_key.objectid ||
2481             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2482             btrfs_extent_data_ref_offset(leaf, ref) != offset)
2483                 goto out;
2484
2485         ret = 0;
2486 out:
2487         return ret;
2488 }
2489
2490 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2491                           struct btrfs_root *root,
2492                           u64 objectid, u64 offset, u64 bytenr)
2493 {
2494         struct btrfs_path *path;
2495         int ret;
2496         int ret2;
2497
2498         path = btrfs_alloc_path();
2499         if (!path)
2500                 return -ENOENT;
2501
2502         do {
2503                 ret = check_committed_ref(trans, root, path, objectid,
2504                                           offset, bytenr);
2505                 if (ret && ret != -ENOENT)
2506                         goto out;
2507
2508                 ret2 = check_delayed_ref(trans, root, path, objectid,
2509                                          offset, bytenr);
2510         } while (ret2 == -EAGAIN);
2511
2512         if (ret2 && ret2 != -ENOENT) {
2513                 ret = ret2;
2514                 goto out;
2515         }
2516
2517         if (ret != -ENOENT || ret2 != -ENOENT)
2518                 ret = 0;
2519 out:
2520         btrfs_free_path(path);
2521         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2522                 WARN_ON(ret > 0);
2523         return ret;
2524 }
2525
2526 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2527                            struct btrfs_root *root,
2528                            struct extent_buffer *buf,
2529                            int full_backref, int inc)
2530 {
2531         u64 bytenr;
2532         u64 num_bytes;
2533         u64 parent;
2534         u64 ref_root;
2535         u32 nritems;
2536         struct btrfs_key key;
2537         struct btrfs_file_extent_item *fi;
2538         int i;
2539         int level;
2540         int ret = 0;
2541         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2542                             u64, u64, u64, u64, u64, u64);
2543
2544         ref_root = btrfs_header_owner(buf);
2545         nritems = btrfs_header_nritems(buf);
2546         level = btrfs_header_level(buf);
2547
2548         if (!root->ref_cows && level == 0)
2549                 return 0;
2550
2551         if (inc)
2552                 process_func = btrfs_inc_extent_ref;
2553         else
2554                 process_func = btrfs_free_extent;
2555
2556         if (full_backref)
2557                 parent = buf->start;
2558         else
2559                 parent = 0;
2560
2561         for (i = 0; i < nritems; i++) {
2562                 if (level == 0) {
2563                         btrfs_item_key_to_cpu(buf, &key, i);
2564                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2565                                 continue;
2566                         fi = btrfs_item_ptr(buf, i,
2567                                             struct btrfs_file_extent_item);
2568                         if (btrfs_file_extent_type(buf, fi) ==
2569                             BTRFS_FILE_EXTENT_INLINE)
2570                                 continue;
2571                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2572                         if (bytenr == 0)
2573                                 continue;
2574
2575                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2576                         key.offset -= btrfs_file_extent_offset(buf, fi);
2577                         ret = process_func(trans, root, bytenr, num_bytes,
2578                                            parent, ref_root, key.objectid,
2579                                            key.offset);
2580                         if (ret)
2581                                 goto fail;
2582                 } else {
2583                         bytenr = btrfs_node_blockptr(buf, i);
2584                         num_bytes = btrfs_level_size(root, level - 1);
2585                         ret = process_func(trans, root, bytenr, num_bytes,
2586                                            parent, ref_root, level - 1, 0);
2587                         if (ret)
2588                                 goto fail;
2589                 }
2590         }
2591         return 0;
2592 fail:
2593         BUG();
2594         return ret;
2595 }
2596
2597 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2598                   struct extent_buffer *buf, int full_backref)
2599 {
2600         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2601 }
2602
2603 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2604                   struct extent_buffer *buf, int full_backref)
2605 {
2606         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2607 }
2608
2609 static int write_one_cache_group(struct btrfs_trans_handle *trans,
2610                                  struct btrfs_root *root,
2611                                  struct btrfs_path *path,
2612                                  struct btrfs_block_group_cache *cache)
2613 {
2614         int ret;
2615         struct btrfs_root *extent_root = root->fs_info->extent_root;
2616         unsigned long bi;
2617         struct extent_buffer *leaf;
2618
2619         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
2620         if (ret < 0)
2621                 goto fail;
2622         BUG_ON(ret);
2623
2624         leaf = path->nodes[0];
2625         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2626         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2627         btrfs_mark_buffer_dirty(leaf);
2628         btrfs_release_path(path);
2629 fail:
2630         if (ret)
2631                 return ret;
2632         return 0;
2633
2634 }
2635
2636 static struct btrfs_block_group_cache *
2637 next_block_group(struct btrfs_root *root,
2638                  struct btrfs_block_group_cache *cache)
2639 {
2640         struct rb_node *node;
2641         spin_lock(&root->fs_info->block_group_cache_lock);
2642         node = rb_next(&cache->cache_node);
2643         btrfs_put_block_group(cache);
2644         if (node) {
2645                 cache = rb_entry(node, struct btrfs_block_group_cache,
2646                                  cache_node);
2647                 btrfs_get_block_group(cache);
2648         } else
2649                 cache = NULL;
2650         spin_unlock(&root->fs_info->block_group_cache_lock);
2651         return cache;
2652 }
2653
2654 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
2655                             struct btrfs_trans_handle *trans,
2656                             struct btrfs_path *path)
2657 {
2658         struct btrfs_root *root = block_group->fs_info->tree_root;
2659         struct inode *inode = NULL;
2660         u64 alloc_hint = 0;
2661         int dcs = BTRFS_DC_ERROR;
2662         int num_pages = 0;
2663         int retries = 0;
2664         int ret = 0;
2665
2666         /*
2667          * If this block group is smaller than 100 megs don't bother caching the
2668          * block group.
2669          */
2670         if (block_group->key.offset < (100 * 1024 * 1024)) {
2671                 spin_lock(&block_group->lock);
2672                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2673                 spin_unlock(&block_group->lock);
2674                 return 0;
2675         }
2676
2677 again:
2678         inode = lookup_free_space_inode(root, block_group, path);
2679         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2680                 ret = PTR_ERR(inode);
2681                 btrfs_release_path(path);
2682                 goto out;
2683         }
2684
2685         if (IS_ERR(inode)) {
2686                 BUG_ON(retries);
2687                 retries++;
2688
2689                 if (block_group->ro)
2690                         goto out_free;
2691
2692                 ret = create_free_space_inode(root, trans, block_group, path);
2693                 if (ret)
2694                         goto out_free;
2695                 goto again;
2696         }
2697
2698         /*
2699          * We want to set the generation to 0, that way if anything goes wrong
2700          * from here on out we know not to trust this cache when we load up next
2701          * time.
2702          */
2703         BTRFS_I(inode)->generation = 0;
2704         ret = btrfs_update_inode(trans, root, inode);
2705         WARN_ON(ret);
2706
2707         if (i_size_read(inode) > 0) {
2708                 ret = btrfs_truncate_free_space_cache(root, trans, path,
2709                                                       inode);
2710                 if (ret)
2711                         goto out_put;
2712         }
2713
2714         spin_lock(&block_group->lock);
2715         if (block_group->cached != BTRFS_CACHE_FINISHED) {
2716                 /* We're not cached, don't bother trying to write stuff out */
2717                 dcs = BTRFS_DC_WRITTEN;
2718                 spin_unlock(&block_group->lock);
2719                 goto out_put;
2720         }
2721         spin_unlock(&block_group->lock);
2722
2723         num_pages = (int)div64_u64(block_group->key.offset, 1024 * 1024 * 1024);
2724         if (!num_pages)
2725                 num_pages = 1;
2726
2727         /*
2728          * Just to make absolutely sure we have enough space, we're going to
2729          * preallocate 12 pages worth of space for each block group.  In
2730          * practice we ought to use at most 8, but we need extra space so we can
2731          * add our header and have a terminator between the extents and the
2732          * bitmaps.
2733          */
2734         num_pages *= 16;
2735         num_pages *= PAGE_CACHE_SIZE;
2736
2737         ret = btrfs_check_data_free_space(inode, num_pages);
2738         if (ret)
2739                 goto out_put;
2740
2741         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2742                                               num_pages, num_pages,
2743                                               &alloc_hint);
2744         if (!ret)
2745                 dcs = BTRFS_DC_SETUP;
2746         btrfs_free_reserved_data_space(inode, num_pages);
2747 out_put:
2748         iput(inode);
2749 out_free:
2750         btrfs_release_path(path);
2751 out:
2752         spin_lock(&block_group->lock);
2753         block_group->disk_cache_state = dcs;
2754         spin_unlock(&block_group->lock);
2755
2756         return ret;
2757 }
2758
2759 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
2760                                    struct btrfs_root *root)
2761 {
2762         struct btrfs_block_group_cache *cache;
2763         int err = 0;
2764         struct btrfs_path *path;
2765         u64 last = 0;
2766
2767         path = btrfs_alloc_path();
2768         if (!path)
2769                 return -ENOMEM;
2770
2771 again:
2772         while (1) {
2773                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2774                 while (cache) {
2775                         if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2776                                 break;
2777                         cache = next_block_group(root, cache);
2778                 }
2779                 if (!cache) {
2780                         if (last == 0)
2781                                 break;
2782                         last = 0;
2783                         continue;
2784                 }
2785                 err = cache_save_setup(cache, trans, path);
2786                 last = cache->key.objectid + cache->key.offset;
2787                 btrfs_put_block_group(cache);
2788         }
2789
2790         while (1) {
2791                 if (last == 0) {
2792                         err = btrfs_run_delayed_refs(trans, root,
2793                                                      (unsigned long)-1);
2794                         BUG_ON(err);
2795                 }
2796
2797                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2798                 while (cache) {
2799                         if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
2800                                 btrfs_put_block_group(cache);
2801                                 goto again;
2802                         }
2803
2804                         if (cache->dirty)
2805                                 break;
2806                         cache = next_block_group(root, cache);
2807                 }
2808                 if (!cache) {
2809                         if (last == 0)
2810                                 break;
2811                         last = 0;
2812                         continue;
2813                 }
2814
2815                 if (cache->disk_cache_state == BTRFS_DC_SETUP)
2816                         cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
2817                 cache->dirty = 0;
2818                 last = cache->key.objectid + cache->key.offset;
2819
2820                 err = write_one_cache_group(trans, root, path, cache);
2821                 BUG_ON(err);
2822                 btrfs_put_block_group(cache);
2823         }
2824
2825         while (1) {
2826                 /*
2827                  * I don't think this is needed since we're just marking our
2828                  * preallocated extent as written, but just in case it can't
2829                  * hurt.
2830                  */
2831                 if (last == 0) {
2832                         err = btrfs_run_delayed_refs(trans, root,
2833                                                      (unsigned long)-1);
2834                         BUG_ON(err);
2835                 }
2836
2837                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2838                 while (cache) {
2839                         /*
2840                          * Really this shouldn't happen, but it could if we
2841                          * couldn't write the entire preallocated extent and
2842                          * splitting the extent resulted in a new block.
2843                          */
2844                         if (cache->dirty) {
2845                                 btrfs_put_block_group(cache);
2846                                 goto again;
2847                         }
2848                         if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2849                                 break;
2850                         cache = next_block_group(root, cache);
2851                 }
2852                 if (!cache) {
2853                         if (last == 0)
2854                                 break;
2855                         last = 0;
2856                         continue;
2857                 }
2858
2859                 btrfs_write_out_cache(root, trans, cache, path);
2860
2861                 /*
2862                  * If we didn't have an error then the cache state is still
2863                  * NEED_WRITE, so we can set it to WRITTEN.
2864                  */
2865                 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2866                         cache->disk_cache_state = BTRFS_DC_WRITTEN;
2867                 last = cache->key.objectid + cache->key.offset;
2868                 btrfs_put_block_group(cache);
2869         }
2870
2871         btrfs_free_path(path);
2872         return 0;
2873 }
2874
2875 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
2876 {
2877         struct btrfs_block_group_cache *block_group;
2878         int readonly = 0;
2879
2880         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
2881         if (!block_group || block_group->ro)
2882                 readonly = 1;
2883         if (block_group)
2884                 btrfs_put_block_group(block_group);
2885         return readonly;
2886 }
2887
2888 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
2889                              u64 total_bytes, u64 bytes_used,
2890                              struct btrfs_space_info **space_info)
2891 {
2892         struct btrfs_space_info *found;
2893         int i;
2894         int factor;
2895
2896         if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
2897                      BTRFS_BLOCK_GROUP_RAID10))
2898                 factor = 2;
2899         else
2900                 factor = 1;
2901
2902         found = __find_space_info(info, flags);
2903         if (found) {
2904                 spin_lock(&found->lock);
2905                 found->total_bytes += total_bytes;
2906                 found->disk_total += total_bytes * factor;
2907                 found->bytes_used += bytes_used;
2908                 found->disk_used += bytes_used * factor;
2909                 found->full = 0;
2910                 spin_unlock(&found->lock);
2911                 *space_info = found;
2912                 return 0;
2913         }
2914         found = kzalloc(sizeof(*found), GFP_NOFS);
2915         if (!found)
2916                 return -ENOMEM;
2917
2918         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
2919                 INIT_LIST_HEAD(&found->block_groups[i]);
2920         init_rwsem(&found->groups_sem);
2921         spin_lock_init(&found->lock);
2922         found->flags = flags & (BTRFS_BLOCK_GROUP_DATA |
2923                                 BTRFS_BLOCK_GROUP_SYSTEM |
2924                                 BTRFS_BLOCK_GROUP_METADATA);
2925         found->total_bytes = total_bytes;
2926         found->disk_total = total_bytes * factor;
2927         found->bytes_used = bytes_used;
2928         found->disk_used = bytes_used * factor;
2929         found->bytes_pinned = 0;
2930         found->bytes_reserved = 0;
2931         found->bytes_readonly = 0;
2932         found->bytes_may_use = 0;
2933         found->full = 0;
2934         found->force_alloc = CHUNK_ALLOC_NO_FORCE;
2935         found->chunk_alloc = 0;
2936         *space_info = found;
2937         list_add_rcu(&found->list, &info->space_info);
2938         atomic_set(&found->caching_threads, 0);
2939         return 0;
2940 }
2941
2942 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
2943 {
2944         u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
2945                                    BTRFS_BLOCK_GROUP_RAID1 |
2946                                    BTRFS_BLOCK_GROUP_RAID10 |
2947                                    BTRFS_BLOCK_GROUP_DUP);
2948         if (extra_flags) {
2949                 if (flags & BTRFS_BLOCK_GROUP_DATA)
2950                         fs_info->avail_data_alloc_bits |= extra_flags;
2951                 if (flags & BTRFS_BLOCK_GROUP_METADATA)
2952                         fs_info->avail_metadata_alloc_bits |= extra_flags;
2953                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
2954                         fs_info->avail_system_alloc_bits |= extra_flags;
2955         }
2956 }
2957
2958 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
2959 {
2960         /*
2961          * we add in the count of missing devices because we want
2962          * to make sure that any RAID levels on a degraded FS
2963          * continue to be honored.
2964          */
2965         u64 num_devices = root->fs_info->fs_devices->rw_devices +
2966                 root->fs_info->fs_devices->missing_devices;
2967
2968         if (num_devices == 1)
2969                 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
2970         if (num_devices < 4)
2971                 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
2972
2973         if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
2974             (flags & (BTRFS_BLOCK_GROUP_RAID1 |
2975                       BTRFS_BLOCK_GROUP_RAID10))) {
2976                 flags &= ~BTRFS_BLOCK_GROUP_DUP;
2977         }
2978
2979         if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
2980             (flags & BTRFS_BLOCK_GROUP_RAID10)) {
2981                 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
2982         }
2983
2984         if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
2985             ((flags & BTRFS_BLOCK_GROUP_RAID1) |
2986              (flags & BTRFS_BLOCK_GROUP_RAID10) |
2987              (flags & BTRFS_BLOCK_GROUP_DUP)))
2988                 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
2989         return flags;
2990 }
2991
2992 static u64 get_alloc_profile(struct btrfs_root *root, u64 flags)
2993 {
2994         if (flags & BTRFS_BLOCK_GROUP_DATA)
2995                 flags |= root->fs_info->avail_data_alloc_bits &
2996                          root->fs_info->data_alloc_profile;
2997         else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
2998                 flags |= root->fs_info->avail_system_alloc_bits &
2999                          root->fs_info->system_alloc_profile;
3000         else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3001                 flags |= root->fs_info->avail_metadata_alloc_bits &
3002                          root->fs_info->metadata_alloc_profile;
3003         return btrfs_reduce_alloc_profile(root, flags);
3004 }
3005
3006 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3007 {
3008         u64 flags;
3009
3010         if (data)
3011                 flags = BTRFS_BLOCK_GROUP_DATA;
3012         else if (root == root->fs_info->chunk_root)
3013                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3014         else
3015                 flags = BTRFS_BLOCK_GROUP_METADATA;
3016
3017         return get_alloc_profile(root, flags);
3018 }
3019
3020 void btrfs_set_inode_space_info(struct btrfs_root *root, struct inode *inode)
3021 {
3022         BTRFS_I(inode)->space_info = __find_space_info(root->fs_info,
3023                                                        BTRFS_BLOCK_GROUP_DATA);
3024 }
3025
3026 /*
3027  * This will check the space that the inode allocates from to make sure we have
3028  * enough space for bytes.
3029  */
3030 int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
3031 {
3032         struct btrfs_space_info *data_sinfo;
3033         struct btrfs_root *root = BTRFS_I(inode)->root;
3034         u64 used;
3035         int ret = 0, committed = 0, alloc_chunk = 1;
3036
3037         /* make sure bytes are sectorsize aligned */
3038         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3039
3040         if (root == root->fs_info->tree_root ||
3041             BTRFS_I(inode)->location.objectid == BTRFS_FREE_INO_OBJECTID) {
3042                 alloc_chunk = 0;
3043                 committed = 1;
3044         }
3045
3046         data_sinfo = BTRFS_I(inode)->space_info;
3047         if (!data_sinfo)
3048                 goto alloc;
3049
3050 again:
3051         /* make sure we have enough space to handle the data first */
3052         spin_lock(&data_sinfo->lock);
3053         used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3054                 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3055                 data_sinfo->bytes_may_use;
3056
3057         if (used + bytes > data_sinfo->total_bytes) {
3058                 struct btrfs_trans_handle *trans;
3059
3060                 /*
3061                  * if we don't have enough free bytes in this space then we need
3062                  * to alloc a new chunk.
3063                  */
3064                 if (!data_sinfo->full && alloc_chunk) {
3065                         u64 alloc_target;
3066
3067                         data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
3068                         spin_unlock(&data_sinfo->lock);
3069 alloc:
3070                         alloc_target = btrfs_get_alloc_profile(root, 1);
3071                         trans = btrfs_join_transaction(root, 1);
3072                         if (IS_ERR(trans))
3073                                 return PTR_ERR(trans);
3074
3075                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3076                                              bytes + 2 * 1024 * 1024,
3077                                              alloc_target,
3078                                              CHUNK_ALLOC_NO_FORCE);
3079                         btrfs_end_transaction(trans, root);
3080                         if (ret < 0) {
3081                                 if (ret != -ENOSPC)
3082                                         return ret;
3083                                 else
3084                                         goto commit_trans;
3085                         }
3086
3087                         if (!data_sinfo) {
3088                                 btrfs_set_inode_space_info(root, inode);
3089                                 data_sinfo = BTRFS_I(inode)->space_info;
3090                         }
3091                         goto again;
3092                 }
3093                 spin_unlock(&data_sinfo->lock);
3094
3095                 /* commit the current transaction and try again */
3096 commit_trans:
3097                 if (!committed && !root->fs_info->open_ioctl_trans) {
3098                         committed = 1;
3099                         trans = btrfs_join_transaction(root, 1);
3100                         if (IS_ERR(trans))
3101                                 return PTR_ERR(trans);
3102                         ret = btrfs_commit_transaction(trans, root);
3103                         if (ret)
3104                                 return ret;
3105                         goto again;
3106                 }
3107
3108                 return -ENOSPC;
3109         }
3110         data_sinfo->bytes_may_use += bytes;
3111         BTRFS_I(inode)->reserved_bytes += bytes;
3112         spin_unlock(&data_sinfo->lock);
3113
3114         return 0;
3115 }
3116
3117 /*
3118  * called when we are clearing an delalloc extent from the
3119  * inode's io_tree or there was an error for whatever reason
3120  * after calling btrfs_check_data_free_space
3121  */
3122 void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
3123 {
3124         struct btrfs_root *root = BTRFS_I(inode)->root;
3125         struct btrfs_space_info *data_sinfo;
3126
3127         /* make sure bytes are sectorsize aligned */
3128         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3129
3130         data_sinfo = BTRFS_I(inode)->space_info;
3131         spin_lock(&data_sinfo->lock);
3132         data_sinfo->bytes_may_use -= bytes;
3133         BTRFS_I(inode)->reserved_bytes -= bytes;
3134         spin_unlock(&data_sinfo->lock);
3135 }
3136
3137 static void force_metadata_allocation(struct btrfs_fs_info *info)
3138 {
3139         struct list_head *head = &info->space_info;
3140         struct btrfs_space_info *found;
3141
3142         rcu_read_lock();
3143         list_for_each_entry_rcu(found, head, list) {
3144                 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3145                         found->force_alloc = CHUNK_ALLOC_FORCE;
3146         }
3147         rcu_read_unlock();
3148 }
3149
3150 static int should_alloc_chunk(struct btrfs_root *root,
3151                               struct btrfs_space_info *sinfo, u64 alloc_bytes,
3152                               int force)
3153 {
3154         u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
3155         u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
3156         u64 thresh;
3157
3158         if (force == CHUNK_ALLOC_FORCE)
3159                 return 1;
3160
3161         /*
3162          * in limited mode, we want to have some free space up to
3163          * about 1% of the FS size.
3164          */
3165         if (force == CHUNK_ALLOC_LIMITED) {
3166                 thresh = btrfs_super_total_bytes(&root->fs_info->super_copy);
3167                 thresh = max_t(u64, 64 * 1024 * 1024,
3168                                div_factor_fine(thresh, 1));
3169
3170                 if (num_bytes - num_allocated < thresh)
3171                         return 1;
3172         }
3173
3174         /*
3175          * we have two similar checks here, one based on percentage
3176          * and once based on a hard number of 256MB.  The idea
3177          * is that if we have a good amount of free
3178          * room, don't allocate a chunk.  A good mount is
3179          * less than 80% utilized of the chunks we have allocated,
3180          * or more than 256MB free
3181          */
3182         if (num_allocated + alloc_bytes + 256 * 1024 * 1024 < num_bytes)
3183                 return 0;
3184
3185         if (num_allocated + alloc_bytes < div_factor(num_bytes, 8))
3186                 return 0;
3187
3188         thresh = btrfs_super_total_bytes(&root->fs_info->super_copy);
3189
3190         /* 256MB or 5% of the FS */
3191         thresh = max_t(u64, 256 * 1024 * 1024, div_factor_fine(thresh, 5));
3192
3193         if (num_bytes > thresh && sinfo->bytes_used < div_factor(num_bytes, 3))
3194                 return 0;
3195         return 1;
3196 }
3197
3198 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
3199                           struct btrfs_root *extent_root, u64 alloc_bytes,
3200                           u64 flags, int force)
3201 {
3202         struct btrfs_space_info *space_info;
3203         struct btrfs_fs_info *fs_info = extent_root->fs_info;
3204         int wait_for_alloc = 0;
3205         int ret = 0;
3206
3207         flags = btrfs_reduce_alloc_profile(extent_root, flags);
3208
3209         space_info = __find_space_info(extent_root->fs_info, flags);
3210         if (!space_info) {
3211                 ret = update_space_info(extent_root->fs_info, flags,
3212                                         0, 0, &space_info);
3213                 BUG_ON(ret);
3214         }
3215         BUG_ON(!space_info);
3216
3217 again:
3218         spin_lock(&space_info->lock);
3219         if (space_info->force_alloc)
3220                 force = space_info->force_alloc;
3221         if (space_info->full) {
3222                 spin_unlock(&space_info->lock);
3223                 return 0;
3224         }
3225
3226         if (!should_alloc_chunk(extent_root, space_info, alloc_bytes, force)) {
3227                 spin_unlock(&space_info->lock);
3228                 return 0;
3229         } else if (space_info->chunk_alloc) {
3230                 wait_for_alloc = 1;
3231         } else {
3232                 space_info->chunk_alloc = 1;
3233         }
3234
3235         spin_unlock(&space_info->lock);
3236
3237         mutex_lock(&fs_info->chunk_mutex);
3238
3239         /*
3240          * The chunk_mutex is held throughout the entirety of a chunk
3241          * allocation, so once we've acquired the chunk_mutex we know that the
3242          * other guy is done and we need to recheck and see if we should
3243          * allocate.
3244          */
3245         if (wait_for_alloc) {
3246                 mutex_unlock(&fs_info->chunk_mutex);
3247                 wait_for_alloc = 0;
3248                 goto again;
3249         }
3250
3251         /*
3252          * If we have mixed data/metadata chunks we want to make sure we keep
3253          * allocating mixed chunks instead of individual chunks.
3254          */
3255         if (btrfs_mixed_space_info(space_info))
3256                 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3257
3258         /*
3259          * if we're doing a data chunk, go ahead and make sure that
3260          * we keep a reasonable number of metadata chunks allocated in the
3261          * FS as well.
3262          */
3263         if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3264                 fs_info->data_chunk_allocations++;
3265                 if (!(fs_info->data_chunk_allocations %
3266                       fs_info->metadata_ratio))
3267                         force_metadata_allocation(fs_info);
3268         }
3269
3270         ret = btrfs_alloc_chunk(trans, extent_root, flags);
3271         spin_lock(&space_info->lock);
3272         if (ret)
3273                 space_info->full = 1;
3274         else
3275                 ret = 1;
3276
3277         space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3278         space_info->chunk_alloc = 0;
3279         spin_unlock(&space_info->lock);
3280         mutex_unlock(&extent_root->fs_info->chunk_mutex);
3281         return ret;
3282 }
3283
3284 /*
3285  * shrink metadata reservation for delalloc
3286  */
3287 static int shrink_delalloc(struct btrfs_trans_handle *trans,
3288                            struct btrfs_root *root, u64 to_reclaim, int sync)
3289 {
3290         struct btrfs_block_rsv *block_rsv;
3291         struct btrfs_space_info *space_info;
3292         u64 reserved;
3293         u64 max_reclaim;
3294         u64 reclaimed = 0;
3295         long time_left;
3296         int nr_pages = (2 * 1024 * 1024) >> PAGE_CACHE_SHIFT;
3297         int loops = 0;
3298         unsigned long progress;
3299
3300         block_rsv = &root->fs_info->delalloc_block_rsv;
3301         space_info = block_rsv->space_info;
3302
3303         smp_mb();
3304         reserved = space_info->bytes_reserved;
3305         progress = space_info->reservation_progress;
3306
3307         if (reserved == 0)
3308                 return 0;
3309
3310         max_reclaim = min(reserved, to_reclaim);
3311
3312         while (loops < 1024) {
3313                 /* have the flusher threads jump in and do some IO */
3314                 smp_mb();
3315                 nr_pages = min_t(unsigned long, nr_pages,
3316                        root->fs_info->delalloc_bytes >> PAGE_CACHE_SHIFT);
3317                 writeback_inodes_sb_nr_if_idle(root->fs_info->sb, nr_pages);
3318
3319                 spin_lock(&space_info->lock);
3320                 if (reserved > space_info->bytes_reserved)
3321                         reclaimed += reserved - space_info->bytes_reserved;
3322                 reserved = space_info->bytes_reserved;
3323                 spin_unlock(&space_info->lock);
3324
3325                 loops++;
3326
3327                 if (reserved == 0 || reclaimed >= max_reclaim)
3328                         break;
3329
3330                 if (trans && trans->transaction->blocked)
3331                         return -EAGAIN;
3332
3333                 time_left = schedule_timeout_interruptible(1);
3334
3335                 /* We were interrupted, exit */
3336                 if (time_left)
3337                         break;
3338
3339                 /* we've kicked the IO a few times, if anything has been freed,
3340                  * exit.  There is no sense in looping here for a long time
3341                  * when we really need to commit the transaction, or there are
3342                  * just too many writers without enough free space
3343                  */
3344
3345                 if (loops > 3) {
3346                         smp_mb();
3347                         if (progress != space_info->reservation_progress)
3348                                 break;
3349                 }
3350
3351         }
3352         return reclaimed >= to_reclaim;
3353 }
3354
3355 /*
3356  * Retries tells us how many times we've called reserve_metadata_bytes.  The
3357  * idea is if this is the first call (retries == 0) then we will add to our
3358  * reserved count if we can't make the allocation in order to hold our place
3359  * while we go and try and free up space.  That way for retries > 1 we don't try
3360  * and add space, we just check to see if the amount of unused space is >= the
3361  * total space, meaning that our reservation is valid.
3362  *
3363  * However if we don't intend to retry this reservation, pass -1 as retries so
3364  * that it short circuits this logic.
3365  */
3366 static int reserve_metadata_bytes(struct btrfs_trans_handle *trans,
3367                                   struct btrfs_root *root,
3368                                   struct btrfs_block_rsv *block_rsv,
3369                                   u64 orig_bytes, int flush)
3370 {
3371         struct btrfs_space_info *space_info = block_rsv->space_info;
3372         u64 unused;
3373         u64 num_bytes = orig_bytes;
3374         int retries = 0;
3375         int ret = 0;
3376         bool reserved = false;
3377         bool committed = false;
3378
3379 again:
3380         ret = -ENOSPC;
3381         if (reserved)
3382                 num_bytes = 0;
3383
3384         spin_lock(&space_info->lock);
3385         unused = space_info->bytes_used + space_info->bytes_reserved +
3386                  space_info->bytes_pinned + space_info->bytes_readonly +
3387                  space_info->bytes_may_use;
3388
3389         /*
3390          * The idea here is that we've not already over-reserved the block group
3391          * then we can go ahead and save our reservation first and then start
3392          * flushing if we need to.  Otherwise if we've already overcommitted
3393          * lets start flushing stuff first and then come back and try to make
3394          * our reservation.
3395          */
3396         if (unused <= space_info->total_bytes) {
3397                 unused = space_info->total_bytes - unused;
3398                 if (unused >= num_bytes) {
3399                         if (!reserved)
3400                                 space_info->bytes_reserved += orig_bytes;
3401                         ret = 0;
3402                 } else {
3403                         /*
3404                          * Ok set num_bytes to orig_bytes since we aren't
3405                          * overocmmitted, this way we only try and reclaim what
3406                          * we need.
3407                          */
3408                         num_bytes = orig_bytes;
3409                 }
3410         } else {
3411                 /*
3412                  * Ok we're over committed, set num_bytes to the overcommitted
3413                  * amount plus the amount of bytes that we need for this
3414                  * reservation.
3415                  */
3416                 num_bytes = unused - space_info->total_bytes +
3417                         (orig_bytes * (retries + 1));
3418         }
3419
3420         /*
3421          * Couldn't make our reservation, save our place so while we're trying
3422          * to reclaim space we can actually use it instead of somebody else
3423          * stealing it from us.
3424          */
3425         if (ret && !reserved) {
3426                 space_info->bytes_reserved += orig_bytes;
3427                 reserved = true;
3428         }
3429
3430         spin_unlock(&space_info->lock);
3431
3432         if (!ret)
3433                 return 0;
3434
3435         if (!flush)
3436                 goto out;
3437
3438         /*
3439          * We do synchronous shrinking since we don't actually unreserve
3440          * metadata until after the IO is completed.
3441          */
3442         ret = shrink_delalloc(trans, root, num_bytes, 1);
3443         if (ret > 0)
3444                 return 0;
3445         else if (ret < 0)
3446                 goto out;
3447
3448         /*
3449          * So if we were overcommitted it's possible that somebody else flushed
3450          * out enough space and we simply didn't have enough space to reclaim,
3451          * so go back around and try again.
3452          */
3453         if (retries < 2) {
3454                 retries++;
3455                 goto again;
3456         }
3457
3458         spin_lock(&space_info->lock);
3459         /*
3460          * Not enough space to be reclaimed, don't bother committing the
3461          * transaction.
3462          */
3463         if (space_info->bytes_pinned < orig_bytes)
3464                 ret = -ENOSPC;
3465         spin_unlock(&space_info->lock);
3466         if (ret)
3467                 goto out;
3468
3469         ret = -EAGAIN;
3470         if (trans || committed)
3471                 goto out;
3472
3473         ret = -ENOSPC;
3474         trans = btrfs_join_transaction(root, 1);
3475         if (IS_ERR(trans))
3476                 goto out;
3477         ret = btrfs_commit_transaction(trans, root);
3478         if (!ret) {
3479                 trans = NULL;
3480                 committed = true;
3481                 goto again;
3482         }
3483
3484 out:
3485         if (reserved) {
3486                 spin_lock(&space_info->lock);
3487                 space_info->bytes_reserved -= orig_bytes;
3488                 spin_unlock(&space_info->lock);
3489         }
3490
3491         return ret;
3492 }
3493
3494 static struct btrfs_block_rsv *get_block_rsv(struct btrfs_trans_handle *trans,
3495                                              struct btrfs_root *root)
3496 {
3497         struct btrfs_block_rsv *block_rsv;
3498         if (root->ref_cows)
3499                 block_rsv = trans->block_rsv;
3500         else
3501                 block_rsv = root->block_rsv;
3502
3503         if (!block_rsv)
3504                 block_rsv = &root->fs_info->empty_block_rsv;
3505
3506         return block_rsv;
3507 }
3508
3509 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
3510                                u64 num_bytes)
3511 {
3512         int ret = -ENOSPC;
3513         spin_lock(&block_rsv->lock);
3514         if (block_rsv->reserved >= num_bytes) {
3515                 block_rsv->reserved -= num_bytes;
3516                 if (block_rsv->reserved < block_rsv->size)
3517                         block_rsv->full = 0;
3518                 ret = 0;
3519         }
3520         spin_unlock(&block_rsv->lock);
3521         return ret;
3522 }
3523
3524 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
3525                                 u64 num_bytes, int update_size)
3526 {
3527         spin_lock(&block_rsv->lock);
3528         block_rsv->reserved += num_bytes;
3529         if (update_size)
3530                 block_rsv->size += num_bytes;
3531         else if (block_rsv->reserved >= block_rsv->size)
3532                 block_rsv->full = 1;
3533         spin_unlock(&block_rsv->lock);
3534 }
3535
3536 static void block_rsv_release_bytes(struct btrfs_block_rsv *block_rsv,
3537                                     struct btrfs_block_rsv *dest, u64 num_bytes)
3538 {
3539         struct btrfs_space_info *space_info = block_rsv->space_info;
3540
3541         spin_lock(&block_rsv->lock);
3542         if (num_bytes == (u64)-1)
3543                 num_bytes = block_rsv->size;
3544         block_rsv->size -= num_bytes;
3545         if (block_rsv->reserved >= block_rsv->size) {
3546                 num_bytes = block_rsv->reserved - block_rsv->size;
3547                 block_rsv->reserved = block_rsv->size;
3548                 block_rsv->full = 1;
3549         } else {
3550                 num_bytes = 0;
3551         }
3552         spin_unlock(&block_rsv->lock);
3553
3554         if (num_bytes > 0) {
3555                 if (dest) {
3556                         spin_lock(&dest->lock);
3557                         if (!dest->full) {
3558                                 u64 bytes_to_add;
3559
3560                                 bytes_to_add = dest->size - dest->reserved;
3561                                 bytes_to_add = min(num_bytes, bytes_to_add);
3562                                 dest->reserved += bytes_to_add;
3563                                 if (dest->reserved >= dest->size)
3564                                         dest->full = 1;
3565                                 num_bytes -= bytes_to_add;
3566                         }
3567                         spin_unlock(&dest->lock);
3568                 }
3569                 if (num_bytes) {
3570                         spin_lock(&space_info->lock);
3571                         space_info->bytes_reserved -= num_bytes;
3572                         space_info->reservation_progress++;
3573                         spin_unlock(&space_info->lock);
3574                 }
3575         }
3576 }
3577
3578 static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
3579                                    struct btrfs_block_rsv *dst, u64 num_bytes)
3580 {
3581         int ret;
3582
3583         ret = block_rsv_use_bytes(src, num_bytes);
3584         if (ret)
3585                 return ret;
3586
3587         block_rsv_add_bytes(dst, num_bytes, 1);
3588         return 0;
3589 }
3590
3591 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv)
3592 {
3593         memset(rsv, 0, sizeof(*rsv));
3594         spin_lock_init(&rsv->lock);
3595         atomic_set(&rsv->usage, 1);
3596         rsv->priority = 6;
3597         INIT_LIST_HEAD(&rsv->list);
3598 }
3599
3600 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root)
3601 {
3602         struct btrfs_block_rsv *block_rsv;
3603         struct btrfs_fs_info *fs_info = root->fs_info;
3604
3605         block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
3606         if (!block_rsv)
3607                 return NULL;
3608
3609         btrfs_init_block_rsv(block_rsv);
3610         block_rsv->space_info = __find_space_info(fs_info,
3611                                                   BTRFS_BLOCK_GROUP_METADATA);
3612         return block_rsv;
3613 }
3614
3615 void btrfs_free_block_rsv(struct btrfs_root *root,
3616                           struct btrfs_block_rsv *rsv)
3617 {
3618         if (rsv && atomic_dec_and_test(&rsv->usage)) {
3619                 btrfs_block_rsv_release(root, rsv, (u64)-1);
3620                 if (!rsv->durable)
3621                         kfree(rsv);
3622         }
3623 }
3624
3625 /*
3626  * make the block_rsv struct be able to capture freed space.
3627  * the captured space will re-add to the the block_rsv struct
3628  * after transaction commit
3629  */
3630 void btrfs_add_durable_block_rsv(struct btrfs_fs_info *fs_info,
3631                                  struct btrfs_block_rsv *block_rsv)
3632 {
3633         block_rsv->durable = 1;
3634         mutex_lock(&fs_info->durable_block_rsv_mutex);
3635         list_add_tail(&block_rsv->list, &fs_info->durable_block_rsv_list);
3636         mutex_unlock(&fs_info->durable_block_rsv_mutex);
3637 }
3638
3639 int btrfs_block_rsv_add(struct btrfs_trans_handle *trans,
3640                         struct btrfs_root *root,
3641                         struct btrfs_block_rsv *block_rsv,
3642                         u64 num_bytes)
3643 {
3644         int ret;
3645
3646         if (num_bytes == 0)
3647                 return 0;
3648
3649         ret = reserve_metadata_bytes(trans, root, block_rsv, num_bytes, 1);
3650         if (!ret) {
3651                 block_rsv_add_bytes(block_rsv, num_bytes, 1);
3652                 return 0;
3653         }
3654
3655         return ret;
3656 }
3657
3658 int btrfs_block_rsv_check(struct btrfs_trans_handle *trans,
3659                           struct btrfs_root *root,
3660                           struct btrfs_block_rsv *block_rsv,
3661                           u64 min_reserved, int min_factor)
3662 {
3663         u64 num_bytes = 0;
3664         int commit_trans = 0;
3665         int ret = -ENOSPC;
3666
3667         if (!block_rsv)
3668                 return 0;
3669
3670         spin_lock(&block_rsv->lock);
3671         if (min_factor > 0)
3672                 num_bytes = div_factor(block_rsv->size, min_factor);
3673         if (min_reserved > num_bytes)
3674                 num_bytes = min_reserved;
3675
3676         if (block_rsv->reserved >= num_bytes) {
3677                 ret = 0;
3678         } else {
3679                 num_bytes -= block_rsv->reserved;
3680                 if (block_rsv->durable &&
3681                     block_rsv->freed[0] + block_rsv->freed[1] >= num_bytes)
3682                         commit_trans = 1;
3683         }
3684         spin_unlock(&block_rsv->lock);
3685         if (!ret)
3686                 return 0;
3687
3688         if (block_rsv->refill_used) {
3689                 ret = reserve_metadata_bytes(trans, root, block_rsv,
3690                                              num_bytes, 0);
3691                 if (!ret) {
3692                         block_rsv_add_bytes(block_rsv, num_bytes, 0);
3693                         return 0;
3694                 }
3695         }
3696
3697         if (commit_trans) {
3698                 if (trans)
3699                         return -EAGAIN;
3700
3701                 trans = btrfs_join_transaction(root, 1);
3702                 BUG_ON(IS_ERR(trans));
3703                 ret = btrfs_commit_transaction(trans, root);
3704                 return 0;
3705         }
3706
3707         return -ENOSPC;
3708 }
3709
3710 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
3711                             struct btrfs_block_rsv *dst_rsv,
3712                             u64 num_bytes)
3713 {
3714         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
3715 }
3716
3717 void btrfs_block_rsv_release(struct btrfs_root *root,
3718                              struct btrfs_block_rsv *block_rsv,
3719                              u64 num_bytes)
3720 {
3721         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3722         if (global_rsv->full || global_rsv == block_rsv ||
3723             block_rsv->space_info != global_rsv->space_info)
3724                 global_rsv = NULL;
3725         block_rsv_release_bytes(block_rsv, global_rsv, num_bytes);
3726 }
3727
3728 /*
3729  * helper to calculate size of global block reservation.
3730  * the desired value is sum of space used by extent tree,
3731  * checksum tree and root tree
3732  */
3733 static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
3734 {
3735         struct btrfs_space_info *sinfo;
3736         u64 num_bytes;
3737         u64 meta_used;
3738         u64 data_used;
3739         int csum_size = btrfs_super_csum_size(&fs_info->super_copy);
3740
3741         sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
3742         spin_lock(&sinfo->lock);
3743         data_used = sinfo->bytes_used;
3744         spin_unlock(&sinfo->lock);
3745
3746         sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3747         spin_lock(&sinfo->lock);
3748         if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
3749                 data_used = 0;
3750         meta_used = sinfo->bytes_used;
3751         spin_unlock(&sinfo->lock);
3752
3753         num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
3754                     csum_size * 2;
3755         num_bytes += div64_u64(data_used + meta_used, 50);
3756
3757         if (num_bytes * 3 > meta_used)
3758                 num_bytes = div64_u64(meta_used, 3);
3759
3760         return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
3761 }
3762
3763 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
3764 {
3765         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3766         struct btrfs_space_info *sinfo = block_rsv->space_info;
3767         u64 num_bytes;
3768
3769         num_bytes = calc_global_metadata_size(fs_info);
3770
3771         spin_lock(&block_rsv->lock);
3772         spin_lock(&sinfo->lock);
3773
3774         block_rsv->size = num_bytes;
3775
3776         num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
3777                     sinfo->bytes_reserved + sinfo->bytes_readonly +
3778                     sinfo->bytes_may_use;
3779
3780         if (sinfo->total_bytes > num_bytes) {
3781                 num_bytes = sinfo->total_bytes - num_bytes;
3782                 block_rsv->reserved += num_bytes;
3783                 sinfo->bytes_reserved += num_bytes;
3784         }
3785
3786         if (block_rsv->reserved >= block_rsv->size) {
3787                 num_bytes = block_rsv->reserved - block_rsv->size;
3788                 sinfo->bytes_reserved -= num_bytes;
3789                 sinfo->reservation_progress++;
3790                 block_rsv->reserved = block_rsv->size;
3791                 block_rsv->full = 1;
3792         }
3793
3794         spin_unlock(&sinfo->lock);
3795         spin_unlock(&block_rsv->lock);
3796 }
3797
3798 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
3799 {
3800         struct btrfs_space_info *space_info;
3801
3802         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3803         fs_info->chunk_block_rsv.space_info = space_info;
3804         fs_info->chunk_block_rsv.priority = 10;
3805
3806         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3807         fs_info->global_block_rsv.space_info = space_info;
3808         fs_info->global_block_rsv.priority = 10;
3809         fs_info->global_block_rsv.refill_used = 1;
3810         fs_info->delalloc_block_rsv.space_info = space_info;
3811         fs_info->trans_block_rsv.space_info = space_info;
3812         fs_info->empty_block_rsv.space_info = space_info;
3813         fs_info->empty_block_rsv.priority = 10;
3814
3815         fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
3816         fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
3817         fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
3818         fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
3819         fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
3820
3821         btrfs_add_durable_block_rsv(fs_info, &fs_info->global_block_rsv);
3822
3823         btrfs_add_durable_block_rsv(fs_info, &fs_info->delalloc_block_rsv);
3824
3825         update_global_block_rsv(fs_info);
3826 }
3827
3828 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
3829 {
3830         block_rsv_release_bytes(&fs_info->global_block_rsv, NULL, (u64)-1);
3831         WARN_ON(fs_info->delalloc_block_rsv.size > 0);
3832         WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
3833         WARN_ON(fs_info->trans_block_rsv.size > 0);
3834         WARN_ON(fs_info->trans_block_rsv.reserved > 0);
3835         WARN_ON(fs_info->chunk_block_rsv.size > 0);
3836         WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
3837 }
3838
3839 int btrfs_trans_reserve_metadata(struct btrfs_trans_handle *trans,
3840                                  struct btrfs_root *root,
3841                                  int num_items)
3842 {
3843         u64 num_bytes;
3844         int ret;
3845
3846         if (num_items == 0 || root->fs_info->chunk_root == root)
3847                 return 0;
3848
3849         num_bytes = btrfs_calc_trans_metadata_size(root, num_items);
3850         ret = btrfs_block_rsv_add(trans, root, &root->fs_info->trans_block_rsv,
3851                                   num_bytes);
3852         if (!ret) {
3853                 trans->bytes_reserved += num_bytes;
3854                 trans->block_rsv = &root->fs_info->trans_block_rsv;
3855         }
3856         return ret;
3857 }
3858
3859 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
3860                                   struct btrfs_root *root)
3861 {
3862         if (!trans->bytes_reserved)
3863                 return;
3864
3865         BUG_ON(trans->block_rsv != &root->fs_info->trans_block_rsv);
3866         btrfs_block_rsv_release(root, trans->block_rsv,
3867                                 trans->bytes_reserved);
3868         trans->bytes_reserved = 0;
3869 }
3870
3871 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
3872                                   struct inode *inode)
3873 {
3874         struct btrfs_root *root = BTRFS_I(inode)->root;
3875         struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
3876         struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
3877
3878         /*
3879          * one for deleting orphan item, one for updating inode and
3880          * two for calling btrfs_truncate_inode_items.
3881          *
3882          * btrfs_truncate_inode_items is a delete operation, it frees
3883          * more space than it uses in most cases. So two units of
3884          * metadata space should be enough for calling it many times.
3885          * If all of the metadata space is used, we can commit
3886          * transaction and use space it freed.
3887          */
3888         u64 num_bytes = btrfs_calc_trans_metadata_size(root, 4);
3889         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
3890 }
3891
3892 void btrfs_orphan_release_metadata(struct inode *inode)
3893 {
3894         struct btrfs_root *root = BTRFS_I(inode)->root;
3895         u64 num_bytes = btrfs_calc_trans_metadata_size(root, 4);
3896         btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
3897 }
3898
3899 int btrfs_snap_reserve_metadata(struct btrfs_trans_handle *trans,
3900                                 struct btrfs_pending_snapshot *pending)
3901 {
3902         struct btrfs_root *root = pending->root;
3903         struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
3904         struct btrfs_block_rsv *dst_rsv = &pending->block_rsv;
3905         /*
3906          * two for root back/forward refs, two for directory entries
3907          * and one for root of the snapshot.
3908          */
3909         u64 num_bytes = btrfs_calc_trans_metadata_size(root, 5);
3910         dst_rsv->space_info = src_rsv->space_info;
3911         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
3912 }
3913
3914 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes)
3915 {
3916         return num_bytes >>= 3;
3917 }
3918
3919 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
3920 {
3921         struct btrfs_root *root = BTRFS_I(inode)->root;
3922         struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
3923         u64 to_reserve;
3924         int nr_extents;
3925         int reserved_extents;
3926         int ret;
3927
3928         if (btrfs_transaction_in_commit(root->fs_info))
3929                 schedule_timeout(1);
3930
3931         num_bytes = ALIGN(num_bytes, root->sectorsize);
3932
3933         nr_extents = atomic_read(&BTRFS_I(inode)->outstanding_extents) + 1;
3934         reserved_extents = atomic_read(&BTRFS_I(inode)->reserved_extents);
3935
3936         if (nr_extents > reserved_extents) {
3937                 nr_extents -= reserved_extents;
3938                 to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
3939         } else {
3940                 nr_extents = 0;
3941                 to_reserve = 0;
3942         }
3943
3944         to_reserve += calc_csum_metadata_size(inode, num_bytes);
3945         ret = reserve_metadata_bytes(NULL, root, block_rsv, to_reserve, 1);
3946         if (ret)
3947                 return ret;
3948
3949         atomic_add(nr_extents, &BTRFS_I(inode)->reserved_extents);
3950         atomic_inc(&BTRFS_I(inode)->outstanding_extents);
3951
3952         block_rsv_add_bytes(block_rsv, to_reserve, 1);
3953
3954         if (block_rsv->size > 512 * 1024 * 1024)
3955                 shrink_delalloc(NULL, root, to_reserve, 0);
3956
3957         return 0;
3958 }
3959
3960 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
3961 {
3962         struct btrfs_root *root = BTRFS_I(inode)->root;
3963         u64 to_free;
3964         int nr_extents;
3965         int reserved_extents;
3966
3967         num_bytes = ALIGN(num_bytes, root->sectorsize);
3968         atomic_dec(&BTRFS_I(inode)->outstanding_extents);
3969         WARN_ON(atomic_read(&BTRFS_I(inode)->outstanding_extents) < 0);
3970
3971         reserved_extents = atomic_read(&BTRFS_I(inode)->reserved_extents);
3972         do {
3973                 int old, new;
3974
3975                 nr_extents = atomic_read(&BTRFS_I(inode)->outstanding_extents);
3976                 if (nr_extents >= reserved_extents) {
3977                         nr_extents = 0;
3978                         break;
3979                 }
3980                 old = reserved_extents;
3981                 nr_extents = reserved_extents - nr_extents;
3982                 new = reserved_extents - nr_extents;
3983                 old = atomic_cmpxchg(&BTRFS_I(inode)->reserved_extents,
3984                                      reserved_extents, new);
3985                 if (likely(old == reserved_extents))
3986                         break;
3987                 reserved_extents = old;
3988         } while (1);
3989
3990         to_free = calc_csum_metadata_size(inode, num_bytes);
3991         if (nr_extents > 0)
3992                 to_free += btrfs_calc_trans_metadata_size(root, nr_extents);
3993
3994         btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
3995                                 to_free);
3996 }
3997
3998 int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
3999 {
4000         int ret;
4001
4002         ret = btrfs_check_data_free_space(inode, num_bytes);
4003         if (ret)
4004                 return ret;
4005
4006         ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
4007         if (ret) {
4008                 btrfs_free_reserved_data_space(inode, num_bytes);
4009                 return ret;
4010         }
4011
4012         return 0;
4013 }
4014
4015 void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
4016 {
4017         btrfs_delalloc_release_metadata(inode, num_bytes);
4018         btrfs_free_reserved_data_space(inode, num_bytes);
4019 }
4020
4021 static int update_block_group(struct btrfs_trans_handle *trans,
4022                               struct btrfs_root *root,
4023                               u64 bytenr, u64 num_bytes, int alloc)
4024 {
4025         struct btrfs_block_group_cache *cache = NULL;
4026         struct btrfs_fs_info *info = root->fs_info;
4027         u64 total = num_bytes;
4028         u64 old_val;
4029         u64 byte_in_group;
4030         int factor;
4031
4032         /* block accounting for super block */
4033         spin_lock(&info->delalloc_lock);
4034         old_val = btrfs_super_bytes_used(&info->super_copy);
4035         if (alloc)
4036                 old_val += num_bytes;
4037         else
4038                 old_val -= num_bytes;
4039         btrfs_set_super_bytes_used(&info->super_copy, old_val);
4040         spin_unlock(&info->delalloc_lock);
4041
4042         while (total) {
4043                 cache = btrfs_lookup_block_group(info, bytenr);
4044                 if (!cache)
4045                         return -1;
4046                 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
4047                                     BTRFS_BLOCK_GROUP_RAID1 |
4048                                     BTRFS_BLOCK_GROUP_RAID10))
4049                         factor = 2;
4050                 else
4051                         factor = 1;
4052                 /*
4053                  * If this block group has free space cache written out, we
4054                  * need to make sure to load it if we are removing space.  This
4055                  * is because we need the unpinning stage to actually add the
4056                  * space back to the block group, otherwise we will leak space.
4057                  */
4058                 if (!alloc && cache->cached == BTRFS_CACHE_NO)
4059                         cache_block_group(cache, trans, NULL, 1);
4060
4061                 byte_in_group = bytenr - cache->key.objectid;
4062                 WARN_ON(byte_in_group > cache->key.offset);
4063
4064                 spin_lock(&cache->space_info->lock);
4065                 spin_lock(&cache->lock);
4066
4067                 if (btrfs_super_cache_generation(&info->super_copy) != 0 &&
4068                     cache->disk_cache_state < BTRFS_DC_CLEAR)
4069                         cache->disk_cache_state = BTRFS_DC_CLEAR;
4070
4071                 cache->dirty = 1;
4072                 old_val = btrfs_block_group_used(&cache->item);
4073                 num_bytes = min(total, cache->key.offset - byte_in_group);
4074                 if (alloc) {
4075                         old_val += num_bytes;
4076                         btrfs_set_block_group_used(&cache->item, old_val);
4077                         cache->reserved -= num_bytes;
4078                         cache->space_info->bytes_reserved -= num_bytes;
4079                         cache->space_info->reservation_progress++;
4080                         cache->space_info->bytes_used += num_bytes;
4081                         cache->space_info->disk_used += num_bytes * factor;
4082                         spin_unlock(&cache->lock);
4083                         spin_unlock(&cache->space_info->lock);
4084                 } else {
4085                         old_val -= num_bytes;
4086                         btrfs_set_block_group_used(&cache->item, old_val);
4087                         cache->pinned += num_bytes;
4088                         cache->space_info->bytes_pinned += num_bytes;
4089                         cache->space_info->bytes_used -= num_bytes;
4090                         cache->space_info->disk_used -= num_bytes * factor;
4091                         spin_unlock(&cache->lock);
4092                         spin_unlock(&cache->space_info->lock);
4093
4094                         set_extent_dirty(info->pinned_extents,
4095                                          bytenr, bytenr + num_bytes - 1,
4096                                          GFP_NOFS | __GFP_NOFAIL);
4097                 }
4098                 btrfs_put_block_group(cache);
4099                 total -= num_bytes;
4100                 bytenr += num_bytes;
4101         }
4102         return 0;
4103 }
4104
4105 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
4106 {
4107         struct btrfs_block_group_cache *cache;
4108         u64 bytenr;
4109
4110         cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
4111         if (!cache)
4112                 return 0;
4113
4114         bytenr = cache->key.objectid;
4115         btrfs_put_block_group(cache);
4116
4117         return bytenr;
4118 }
4119
4120 static int pin_down_extent(struct btrfs_root *root,
4121                            struct btrfs_block_group_cache *cache,
4122                            u64 bytenr, u64 num_bytes, int reserved)
4123 {
4124         spin_lock(&cache->space_info->lock);
4125         spin_lock(&cache->lock);
4126         cache->pinned += num_bytes;
4127         cache->space_info->bytes_pinned += num_bytes;
4128         if (reserved) {
4129                 cache->reserved -= num_bytes;
4130                 cache->space_info->bytes_reserved -= num_bytes;
4131                 cache->space_info->reservation_progress++;
4132         }
4133         spin_unlock(&cache->lock);
4134         spin_unlock(&cache->space_info->lock);
4135
4136         set_extent_dirty(root->fs_info->pinned_extents, bytenr,
4137                          bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
4138         return 0;
4139 }
4140
4141 /*
4142  * this function must be called within transaction
4143  */
4144 int btrfs_pin_extent(struct btrfs_root *root,
4145                      u64 bytenr, u64 num_bytes, int reserved)
4146 {
4147         struct btrfs_block_group_cache *cache;
4148
4149         cache = btrfs_lookup_block_group(root->fs_info, bytenr);
4150         BUG_ON(!cache);
4151
4152         pin_down_extent(root, cache, bytenr, num_bytes, reserved);
4153
4154         btrfs_put_block_group(cache);
4155         return 0;
4156 }
4157
4158 /*
4159  * update size of reserved extents. this function may return -EAGAIN
4160  * if 'reserve' is true or 'sinfo' is false.
4161  */
4162 int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
4163                                 u64 num_bytes, int reserve, int sinfo)
4164 {
4165         int ret = 0;
4166         if (sinfo) {
4167                 struct btrfs_space_info *space_info = cache->space_info;
4168                 spin_lock(&space_info->lock);
4169                 spin_lock(&cache->lock);
4170                 if (reserve) {
4171                         if (cache->ro) {
4172                                 ret = -EAGAIN;
4173                         } else {
4174                                 cache->reserved += num_bytes;
4175                                 space_info->bytes_reserved += num_bytes;
4176                         }
4177                 } else {
4178                         if (cache->ro)
4179                                 space_info->bytes_readonly += num_bytes;
4180                         cache->reserved -= num_bytes;
4181                         space_info->bytes_reserved -= num_bytes;
4182                         space_info->reservation_progress++;
4183                 }
4184                 spin_unlock(&cache->lock);
4185                 spin_unlock(&space_info->lock);
4186         } else {
4187                 spin_lock(&cache->lock);
4188                 if (cache->ro) {
4189                         ret = -EAGAIN;
4190                 } else {
4191                         if (reserve)
4192                                 cache->reserved += num_bytes;
4193                         else
4194                                 cache->reserved -= num_bytes;
4195                 }
4196                 spin_unlock(&cache->lock);
4197         }
4198         return ret;
4199 }
4200
4201 int btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
4202                                 struct btrfs_root *root)
4203 {
4204         struct btrfs_fs_info *fs_info = root->fs_info;
4205         struct btrfs_caching_control *next;
4206         struct btrfs_caching_control *caching_ctl;
4207         struct btrfs_block_group_cache *cache;
4208
4209         down_write(&fs_info->extent_commit_sem);
4210
4211         list_for_each_entry_safe(caching_ctl, next,
4212                                  &fs_info->caching_block_groups, list) {
4213                 cache = caching_ctl->block_group;
4214                 if (block_group_cache_done(cache)) {
4215                         cache->last_byte_to_unpin = (u64)-1;
4216                         list_del_init(&caching_ctl->list);
4217                         put_caching_control(caching_ctl);
4218                 } else {
4219                         cache->last_byte_to_unpin = caching_ctl->progress;
4220                 }
4221         }
4222
4223         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4224                 fs_info->pinned_extents = &fs_info->freed_extents[1];
4225         else
4226                 fs_info->pinned_extents = &fs_info->freed_extents[0];
4227
4228         up_write(&fs_info->extent_commit_sem);
4229
4230         update_global_block_rsv(fs_info);
4231         return 0;
4232 }
4233
4234 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
4235 {
4236         struct btrfs_fs_info *fs_info = root->fs_info;
4237         struct btrfs_block_group_cache *cache = NULL;
4238         u64 len;
4239
4240         while (start <= end) {
4241                 if (!cache ||
4242                     start >= cache->key.objectid + cache->key.offset) {
4243                         if (cache)
4244                                 btrfs_put_block_group(cache);
4245                         cache = btrfs_lookup_block_group(fs_info, start);
4246                         BUG_ON(!cache);
4247                 }
4248
4249                 len = cache->key.objectid + cache->key.offset - start;
4250                 len = min(len, end + 1 - start);
4251
4252                 if (start < cache->last_byte_to_unpin) {
4253                         len = min(len, cache->last_byte_to_unpin - start);
4254                         btrfs_add_free_space(cache, start, len);
4255                 }
4256
4257                 start += len;
4258
4259                 spin_lock(&cache->space_info->lock);
4260                 spin_lock(&cache->lock);
4261                 cache->pinned -= len;
4262                 cache->space_info->bytes_pinned -= len;
4263                 if (cache->ro) {
4264                         cache->space_info->bytes_readonly += len;
4265                 } else if (cache->reserved_pinned > 0) {
4266                         len = min(len, cache->reserved_pinned);
4267                         cache->reserved_pinned -= len;
4268                         cache->space_info->bytes_reserved += len;
4269                 }
4270                 spin_unlock(&cache->lock);
4271                 spin_unlock(&cache->space_info->lock);
4272         }
4273
4274         if (cache)
4275                 btrfs_put_block_group(cache);
4276         return 0;
4277 }
4278
4279 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
4280                                struct btrfs_root *root)
4281 {
4282         struct btrfs_fs_info *fs_info = root->fs_info;
4283         struct extent_io_tree *unpin;
4284         struct btrfs_block_rsv *block_rsv;
4285         struct btrfs_block_rsv *next_rsv;
4286         u64 start;
4287         u64 end;
4288         int idx;
4289         int ret;
4290
4291         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4292                 unpin = &fs_info->freed_extents[1];
4293         else
4294                 unpin = &fs_info->freed_extents[0];
4295
4296         while (1) {
4297                 ret = find_first_extent_bit(unpin, 0, &start, &end,
4298                                             EXTENT_DIRTY);
4299                 if (ret)
4300                         break;
4301
4302                 if (btrfs_test_opt(root, DISCARD))
4303                         ret = btrfs_discard_extent(root, start,
4304                                                    end + 1 - start, NULL);
4305
4306                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
4307                 unpin_extent_range(root, start, end);
4308                 cond_resched();
4309         }
4310
4311         mutex_lock(&fs_info->durable_block_rsv_mutex);
4312         list_for_each_entry_safe(block_rsv, next_rsv,
4313                                  &fs_info->durable_block_rsv_list, list) {
4314
4315                 idx = trans->transid & 0x1;
4316                 if (block_rsv->freed[idx] > 0) {
4317                         block_rsv_add_bytes(block_rsv,
4318                                             block_rsv->freed[idx], 0);
4319                         block_rsv->freed[idx] = 0;
4320                 }
4321                 if (atomic_read(&block_rsv->usage) == 0) {
4322                         btrfs_block_rsv_release(root, block_rsv, (u64)-1);
4323
4324                         if (block_rsv->freed[0] == 0 &&
4325                             block_rsv->freed[1] == 0) {
4326                                 list_del_init(&block_rsv->list);
4327                                 kfree(block_rsv);
4328                         }
4329                 } else {
4330                         btrfs_block_rsv_release(root, block_rsv, 0);
4331                 }
4332         }
4333         mutex_unlock(&fs_info->durable_block_rsv_mutex);
4334
4335         return 0;
4336 }
4337
4338 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
4339                                 struct btrfs_root *root,
4340                                 u64 bytenr, u64 num_bytes, u64 parent,
4341                                 u64 root_objectid, u64 owner_objectid,
4342                                 u64 owner_offset, int refs_to_drop,
4343                                 struct btrfs_delayed_extent_op *extent_op)
4344 {
4345         struct btrfs_key key;
4346         struct btrfs_path *path;
4347         struct btrfs_fs_info *info = root->fs_info;
4348         struct btrfs_root *extent_root = info->extent_root;
4349         struct extent_buffer *leaf;
4350         struct btrfs_extent_item *ei;
4351         struct btrfs_extent_inline_ref *iref;
4352         int ret;
4353         int is_data;
4354         int extent_slot = 0;
4355         int found_extent = 0;
4356         int num_to_del = 1;
4357         u32 item_size;
4358         u64 refs;
4359
4360         path = btrfs_alloc_path();
4361         if (!path)
4362                 return -ENOMEM;
4363
4364         path->reada = 1;
4365         path->leave_spinning = 1;
4366
4367         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
4368         BUG_ON(!is_data && refs_to_drop != 1);
4369
4370         ret = lookup_extent_backref(trans, extent_root, path, &iref,
4371                                     bytenr, num_bytes, parent,
4372                                     root_objectid, owner_objectid,
4373                                     owner_offset);
4374         if (ret == 0) {
4375                 extent_slot = path->slots[0];
4376                 while (extent_slot >= 0) {
4377                         btrfs_item_key_to_cpu(path->nodes[0], &key,
4378                                               extent_slot);
4379                         if (key.objectid != bytenr)
4380                                 break;
4381                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
4382                             key.offset == num_bytes) {
4383                                 found_extent = 1;
4384                                 break;
4385                         }
4386                         if (path->slots[0] - extent_slot > 5)
4387                                 break;
4388                         extent_slot--;
4389                 }
4390 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4391                 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
4392                 if (found_extent && item_size < sizeof(*ei))
4393                         found_extent = 0;
4394 #endif
4395                 if (!found_extent) {
4396                         BUG_ON(iref);
4397                         ret = remove_extent_backref(trans, extent_root, path,
4398                                                     NULL, refs_to_drop,
4399                                                     is_data);
4400                         BUG_ON(ret);
4401                         btrfs_release_path(path);
4402                         path->leave_spinning = 1;
4403
4404                         key.objectid = bytenr;
4405                         key.type = BTRFS_EXTENT_ITEM_KEY;
4406                         key.offset = num_bytes;
4407
4408                         ret = btrfs_search_slot(trans, extent_root,
4409                                                 &key, path, -1, 1);
4410                         if (ret) {
4411                                 printk(KERN_ERR "umm, got %d back from search"
4412                                        ", was looking for %llu\n", ret,
4413                                        (unsigned long long)bytenr);
4414                                 btrfs_print_leaf(extent_root, path->nodes[0]);
4415                         }
4416                         BUG_ON(ret);
4417                         extent_slot = path->slots[0];
4418                 }
4419         } else {
4420                 btrfs_print_leaf(extent_root, path->nodes[0]);
4421                 WARN_ON(1);
4422                 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
4423                        "parent %llu root %llu  owner %llu offset %llu\n",
4424                        (unsigned long long)bytenr,
4425                        (unsigned long long)parent,
4426                        (unsigned long long)root_objectid,
4427                        (unsigned long long)owner_objectid,
4428                        (unsigned long long)owner_offset);
4429         }
4430
4431         leaf = path->nodes[0];
4432         item_size = btrfs_item_size_nr(leaf, extent_slot);
4433 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4434         if (item_size < sizeof(*ei)) {
4435                 BUG_ON(found_extent || extent_slot != path->slots[0]);
4436                 ret = convert_extent_item_v0(trans, extent_root, path,
4437                                              owner_objectid, 0);
4438                 BUG_ON(ret < 0);
4439
4440                 btrfs_release_path(path);
4441                 path->leave_spinning = 1;
4442
4443                 key.objectid = bytenr;
4444                 key.type = BTRFS_EXTENT_ITEM_KEY;
4445                 key.offset = num_bytes;
4446
4447                 ret = btrfs_search_slot(trans, extent_root, &key, path,
4448                                         -1, 1);
4449                 if (ret) {
4450                         printk(KERN_ERR "umm, got %d back from search"
4451                                ", was looking for %llu\n", ret,
4452                                (unsigned long long)bytenr);
4453                         btrfs_print_leaf(extent_root, path->nodes[0]);
4454                 }
4455                 BUG_ON(ret);
4456                 extent_slot = path->slots[0];
4457                 leaf = path->nodes[0];
4458                 item_size = btrfs_item_size_nr(leaf, extent_slot);
4459         }
4460 #endif
4461         BUG_ON(item_size < sizeof(*ei));
4462         ei = btrfs_item_ptr(leaf, extent_slot,
4463                             struct btrfs_extent_item);
4464         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
4465                 struct btrfs_tree_block_info *bi;
4466                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
4467                 bi = (struct btrfs_tree_block_info *)(ei + 1);
4468                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
4469         }
4470
4471         refs = btrfs_extent_refs(leaf, ei);
4472         BUG_ON(refs < refs_to_drop);
4473         refs -= refs_to_drop;
4474
4475         if (refs > 0) {
4476                 if (extent_op)
4477                         __run_delayed_extent_op(extent_op, leaf, ei);
4478                 /*
4479                  * In the case of inline back ref, reference count will
4480                  * be updated by remove_extent_backref
4481                  */
4482                 if (iref) {
4483                         BUG_ON(!found_extent);
4484                 } else {
4485                         btrfs_set_extent_refs(leaf, ei, refs);
4486                         btrfs_mark_buffer_dirty(leaf);
4487                 }
4488                 if (found_extent) {
4489                         ret = remove_extent_backref(trans, extent_root, path,
4490                                                     iref, refs_to_drop,
4491                                                     is_data);
4492                         BUG_ON(ret);
4493                 }
4494         } else {
4495                 if (found_extent) {
4496                         BUG_ON(is_data && refs_to_drop !=
4497                                extent_data_ref_count(root, path, iref));
4498                         if (iref) {
4499                                 BUG_ON(path->slots[0] != extent_slot);
4500                         } else {
4501                                 BUG_ON(path->slots[0] != extent_slot + 1);
4502                                 path->slots[0] = extent_slot;
4503                                 num_to_del = 2;
4504                         }
4505                 }
4506
4507                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
4508                                       num_to_del);
4509                 BUG_ON(ret);
4510                 btrfs_release_path(path);
4511
4512                 if (is_data) {
4513                         ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
4514                         BUG_ON(ret);
4515                 } else {
4516                         invalidate_mapping_pages(info->btree_inode->i_mapping,
4517                              bytenr >> PAGE_CACHE_SHIFT,
4518                              (bytenr + num_bytes - 1) >> PAGE_CACHE_SHIFT);
4519                 }
4520
4521                 ret = update_block_group(trans, root, bytenr, num_bytes, 0);
4522                 BUG_ON(ret);
4523         }
4524         btrfs_free_path(path);
4525         return ret;
4526 }
4527
4528 /*
4529  * when we free an block, it is possible (and likely) that we free the last
4530  * delayed ref for that extent as well.  This searches the delayed ref tree for
4531  * a given extent, and if there are no other delayed refs to be processed, it
4532  * removes it from the tree.
4533  */
4534 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
4535                                       struct btrfs_root *root, u64 bytenr)
4536 {
4537         struct btrfs_delayed_ref_head *head;
4538         struct btrfs_delayed_ref_root *delayed_refs;
4539         struct btrfs_delayed_ref_node *ref;
4540         struct rb_node *node;
4541         int ret = 0;
4542
4543         delayed_refs = &trans->transaction->delayed_refs;
4544         spin_lock(&delayed_refs->lock);
4545         head = btrfs_find_delayed_ref_head(trans, bytenr);
4546         if (!head)
4547                 goto out;
4548
4549         node = rb_prev(&head->node.rb_node);
4550         if (!node)
4551                 goto out;
4552
4553         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
4554
4555         /* there are still entries for this ref, we can't drop it */
4556         if (ref->bytenr == bytenr)
4557                 goto out;
4558
4559         if (head->extent_op) {
4560                 if (!head->must_insert_reserved)
4561                         goto out;
4562                 kfree(head->extent_op);
4563                 head->extent_op = NULL;
4564         }
4565
4566         /*
4567          * waiting for the lock here would deadlock.  If someone else has it
4568          * locked they are already in the process of dropping it anyway
4569          */
4570         if (!mutex_trylock(&head->mutex))
4571                 goto out;
4572
4573         /*
4574          * at this point we have a head with no other entries.  Go
4575          * ahead and process it.
4576          */
4577         head->node.in_tree = 0;
4578         rb_erase(&head->node.rb_node, &delayed_refs->root);
4579
4580         delayed_refs->num_entries--;
4581
4582         /*
4583          * we don't take a ref on the node because we're removing it from the
4584          * tree, so we just steal the ref the tree was holding.
4585          */
4586         delayed_refs->num_heads--;
4587         if (list_empty(&head->cluster))
4588                 delayed_refs->num_heads_ready--;
4589
4590         list_del_init(&head->cluster);
4591         spin_unlock(&delayed_refs->lock);
4592
4593         BUG_ON(head->extent_op);
4594         if (head->must_insert_reserved)
4595                 ret = 1;
4596
4597         mutex_unlock(&head->mutex);
4598         btrfs_put_delayed_ref(&head->node);
4599         return ret;
4600 out:
4601         spin_unlock(&delayed_refs->lock);
4602         return 0;
4603 }
4604
4605 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
4606                            struct btrfs_root *root,
4607                            struct extent_buffer *buf,
4608                            u64 parent, int last_ref)
4609 {
4610         struct btrfs_block_rsv *block_rsv;
4611         struct btrfs_block_group_cache *cache = NULL;
4612         int ret;
4613
4614         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4615                 ret = btrfs_add_delayed_tree_ref(trans, buf->start, buf->len,
4616                                                 parent, root->root_key.objectid,
4617                                                 btrfs_header_level(buf),
4618                                                 BTRFS_DROP_DELAYED_REF, NULL);
4619                 BUG_ON(ret);
4620         }
4621
4622         if (!last_ref)
4623                 return;
4624
4625         block_rsv = get_block_rsv(trans, root);
4626         cache = btrfs_lookup_block_group(root->fs_info, buf->start);
4627         if (block_rsv->space_info != cache->space_info)
4628                 goto out;
4629
4630         if (btrfs_header_generation(buf) == trans->transid) {
4631                 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4632                         ret = check_ref_cleanup(trans, root, buf->start);
4633                         if (!ret)
4634                                 goto pin;
4635                 }
4636
4637                 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
4638                         pin_down_extent(root, cache, buf->start, buf->len, 1);
4639                         goto pin;
4640                 }
4641
4642                 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
4643
4644                 btrfs_add_free_space(cache, buf->start, buf->len);
4645                 ret = btrfs_update_reserved_bytes(cache, buf->len, 0, 0);
4646                 if (ret == -EAGAIN) {
4647                         /* block group became read-only */
4648                         btrfs_update_reserved_bytes(cache, buf->len, 0, 1);
4649                         goto out;
4650                 }
4651
4652                 ret = 1;
4653                 spin_lock(&block_rsv->lock);
4654                 if (block_rsv->reserved < block_rsv->size) {
4655                         block_rsv->reserved += buf->len;
4656                         ret = 0;
4657                 }
4658                 spin_unlock(&block_rsv->lock);
4659
4660                 if (ret) {
4661                         spin_lock(&cache->space_info->lock);
4662                         cache->space_info->bytes_reserved -= buf->len;
4663                         cache->space_info->reservation_progress++;
4664                         spin_unlock(&cache->space_info->lock);
4665                 }
4666                 goto out;
4667         }
4668 pin:
4669         if (block_rsv->durable && !cache->ro) {
4670                 ret = 0;
4671                 spin_lock(&cache->lock);
4672                 if (!cache->ro) {
4673                         cache->reserved_pinned += buf->len;
4674                         ret = 1;
4675                 }
4676                 spin_unlock(&cache->lock);
4677
4678                 if (ret) {
4679                         spin_lock(&block_rsv->lock);
4680                         block_rsv->freed[trans->transid & 0x1] += buf->len;
4681                         spin_unlock(&block_rsv->lock);
4682                 }
4683         }
4684 out:
4685         /*
4686          * Deleting the buffer, clear the corrupt flag since it doesn't matter
4687          * anymore.
4688          */
4689         clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
4690         btrfs_put_block_group(cache);
4691 }
4692
4693 int btrfs_free_extent(struct btrfs_trans_handle *trans,
4694                       struct btrfs_root *root,
4695                       u64 bytenr, u64 num_bytes, u64 parent,
4696                       u64 root_objectid, u64 owner, u64 offset)
4697 {
4698         int ret;
4699
4700         /*
4701          * tree log blocks never actually go into the extent allocation
4702          * tree, just update pinning info and exit early.
4703          */
4704         if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
4705                 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
4706                 /* unlocks the pinned mutex */
4707                 btrfs_pin_extent(root, bytenr, num_bytes, 1);
4708                 ret = 0;
4709         } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
4710                 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
4711                                         parent, root_objectid, (int)owner,
4712                                         BTRFS_DROP_DELAYED_REF, NULL);
4713                 BUG_ON(ret);
4714         } else {
4715                 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
4716                                         parent, root_objectid, owner,
4717                                         offset, BTRFS_DROP_DELAYED_REF, NULL);
4718                 BUG_ON(ret);
4719         }
4720         return ret;
4721 }
4722
4723 static u64 stripe_align(struct btrfs_root *root, u64 val)
4724 {
4725         u64 mask = ((u64)root->stripesize - 1);
4726         u64 ret = (val + mask) & ~mask;
4727         return ret;
4728 }
4729
4730 /*
4731  * when we wait for progress in the block group caching, its because
4732  * our allocation attempt failed at least once.  So, we must sleep
4733  * and let some progress happen before we try again.
4734  *
4735  * This function will sleep at least once waiting for new free space to
4736  * show up, and then it will check the block group free space numbers
4737  * for our min num_bytes.  Another option is to have it go ahead
4738  * and look in the rbtree for a free extent of a given size, but this
4739  * is a good start.
4740  */
4741 static noinline int
4742 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
4743                                 u64 num_bytes)
4744 {
4745         struct btrfs_caching_control *caching_ctl;
4746         DEFINE_WAIT(wait);
4747
4748         caching_ctl = get_caching_control(cache);
4749         if (!caching_ctl)
4750                 return 0;
4751
4752         wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
4753                    (cache->free_space_ctl->free_space >= num_bytes));
4754
4755         put_caching_control(caching_ctl);
4756         return 0;
4757 }
4758
4759 static noinline int
4760 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
4761 {
4762         struct btrfs_caching_control *caching_ctl;
4763         DEFINE_WAIT(wait);
4764
4765         caching_ctl = get_caching_control(cache);
4766         if (!caching_ctl)
4767                 return 0;
4768
4769         wait_event(caching_ctl->wait, block_group_cache_done(cache));
4770
4771         put_caching_control(caching_ctl);
4772         return 0;
4773 }
4774
4775 static int get_block_group_index(struct btrfs_block_group_cache *cache)
4776 {
4777         int index;
4778         if (cache->flags & BTRFS_BLOCK_GROUP_RAID10)
4779                 index = 0;
4780         else if (cache->flags & BTRFS_BLOCK_GROUP_RAID1)
4781                 index = 1;
4782         else if (cache->flags & BTRFS_BLOCK_GROUP_DUP)
4783                 index = 2;
4784         else if (cache->flags & BTRFS_BLOCK_GROUP_RAID0)
4785                 index = 3;
4786         else
4787                 index = 4;
4788         return index;
4789 }
4790
4791 enum btrfs_loop_type {
4792         LOOP_FIND_IDEAL = 0,
4793         LOOP_CACHING_NOWAIT = 1,
4794         LOOP_CACHING_WAIT = 2,
4795         LOOP_ALLOC_CHUNK = 3,
4796         LOOP_NO_EMPTY_SIZE = 4,
4797 };
4798
4799 /*
4800  * walks the btree of allocated extents and find a hole of a given size.
4801  * The key ins is changed to record the hole:
4802  * ins->objectid == block start
4803  * ins->flags = BTRFS_EXTENT_ITEM_KEY
4804  * ins->offset == number of blocks
4805  * Any available blocks before search_start are skipped.
4806  */
4807 static noinline int find_free_extent(struct btrfs_trans_handle *trans,
4808                                      struct btrfs_root *orig_root,
4809                                      u64 num_bytes, u64 empty_size,
4810                                      u64 search_start, u64 search_end,
4811                                      u64 hint_byte, struct btrfs_key *ins,
4812                                      int data)
4813 {
4814         int ret = 0;
4815         struct btrfs_root *root = orig_root->fs_info->extent_root;
4816         struct btrfs_free_cluster *last_ptr = NULL;
4817         struct btrfs_block_group_cache *block_group = NULL;
4818         int empty_cluster = 2 * 1024 * 1024;
4819         int allowed_chunk_alloc = 0;
4820         int done_chunk_alloc = 0;
4821         struct btrfs_space_info *space_info;
4822         int last_ptr_loop = 0;
4823         int loop = 0;
4824         int index = 0;
4825         bool found_uncached_bg = false;
4826         bool failed_cluster_refill = false;
4827         bool failed_alloc = false;
4828         bool use_cluster = true;
4829         u64 ideal_cache_percent = 0;
4830         u64 ideal_cache_offset = 0;
4831
4832         WARN_ON(num_bytes < root->sectorsize);
4833         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
4834         ins->objectid = 0;
4835         ins->offset = 0;
4836
4837         space_info = __find_space_info(root->fs_info, data);
4838         if (!space_info) {
4839                 printk(KERN_ERR "No space info for %d\n", data);
4840                 return -ENOSPC;
4841         }
4842
4843         /*
4844          * If the space info is for both data and metadata it means we have a
4845          * small filesystem and we can't use the clustering stuff.
4846          */
4847         if (btrfs_mixed_space_info(space_info))
4848                 use_cluster = false;
4849
4850         if (orig_root->ref_cows || empty_size)
4851                 allowed_chunk_alloc = 1;
4852
4853         if (data & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
4854                 last_ptr = &root->fs_info->meta_alloc_cluster;
4855                 if (!btrfs_test_opt(root, SSD))
4856                         empty_cluster = 64 * 1024;
4857         }
4858
4859         if ((data & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
4860             btrfs_test_opt(root, SSD)) {
4861                 last_ptr = &root->fs_info->data_alloc_cluster;
4862         }
4863
4864         if (last_ptr) {
4865                 spin_lock(&last_ptr->lock);
4866                 if (last_ptr->block_group)
4867                         hint_byte = last_ptr->window_start;
4868                 spin_unlock(&last_ptr->lock);
4869         }
4870
4871         search_start = max(search_start, first_logical_byte(root, 0));
4872         search_start = max(search_start, hint_byte);
4873
4874         if (!last_ptr)
4875                 empty_cluster = 0;
4876
4877         if (search_start == hint_byte) {
4878 ideal_cache:
4879                 block_group = btrfs_lookup_block_group(root->fs_info,
4880                                                        search_start);
4881                 /*
4882                  * we don't want to use the block group if it doesn't match our
4883                  * allocation bits, or if its not cached.
4884                  *
4885                  * However if we are re-searching with an ideal block group
4886                  * picked out then we don't care that the block group is cached.
4887                  */
4888                 if (block_group && block_group_bits(block_group, data) &&
4889                     (block_group->cached != BTRFS_CACHE_NO ||
4890                      search_start == ideal_cache_offset)) {
4891                         down_read(&space_info->groups_sem);
4892                         if (list_empty(&block_group->list) ||
4893                             block_group->ro) {
4894                                 /*
4895                                  * someone is removing this block group,
4896                                  * we can't jump into the have_block_group
4897                                  * target because our list pointers are not
4898                                  * valid
4899                                  */
4900                                 btrfs_put_block_group(block_group);
4901                                 up_read(&space_info->groups_sem);
4902                         } else {
4903                                 index = get_block_group_index(block_group);
4904                                 goto have_block_group;
4905                         }
4906                 } else if (block_group) {
4907                         btrfs_put_block_group(block_group);
4908                 }
4909         }
4910 search:
4911         down_read(&space_info->groups_sem);
4912         list_for_each_entry(block_group, &space_info->block_groups[index],
4913                             list) {
4914                 u64 offset;
4915                 int cached;
4916
4917                 btrfs_get_block_group(block_group);
4918                 search_start = block_group->key.objectid;
4919
4920                 /*
4921                  * this can happen if we end up cycling through all the
4922                  * raid types, but we want to make sure we only allocate
4923                  * for the proper type.
4924                  */
4925                 if (!block_group_bits(block_group, data)) {
4926                     u64 extra = BTRFS_BLOCK_GROUP_DUP |
4927                                 BTRFS_BLOCK_GROUP_RAID1 |
4928                                 BTRFS_BLOCK_GROUP_RAID10;
4929
4930                         /*
4931                          * if they asked for extra copies and this block group
4932                          * doesn't provide them, bail.  This does allow us to
4933                          * fill raid0 from raid1.
4934                          */
4935                         if ((data & extra) && !(block_group->flags & extra))
4936                                 goto loop;
4937                 }
4938
4939 have_block_group:
4940                 if (unlikely(block_group->cached == BTRFS_CACHE_NO)) {
4941                         u64 free_percent;
4942
4943                         ret = cache_block_group(block_group, trans,
4944                                                 orig_root, 1);
4945                         if (block_group->cached == BTRFS_CACHE_FINISHED)
4946                                 goto have_block_group;
4947
4948                         free_percent = btrfs_block_group_used(&block_group->item);
4949                         free_percent *= 100;
4950                         free_percent = div64_u64(free_percent,
4951                                                  block_group->key.offset);
4952                         free_percent = 100 - free_percent;
4953                         if (free_percent > ideal_cache_percent &&
4954                             likely(!block_group->ro)) {
4955                                 ideal_cache_offset = block_group->key.objectid;
4956                                 ideal_cache_percent = free_percent;
4957                         }
4958
4959                         /*
4960                          * We only want to start kthread caching if we are at
4961                          * the point where we will wait for caching to make
4962                          * progress, or if our ideal search is over and we've
4963                          * found somebody to start caching.
4964                          */
4965                         if (loop > LOOP_CACHING_NOWAIT ||
4966                             (loop > LOOP_FIND_IDEAL &&
4967                              atomic_read(&space_info->caching_threads) < 2)) {
4968                                 ret = cache_block_group(block_group, trans,
4969                                                         orig_root, 0);
4970                                 BUG_ON(ret);
4971                         }
4972                         found_uncached_bg = true;
4973
4974                         /*
4975                          * If loop is set for cached only, try the next block
4976                          * group.
4977                          */
4978                         if (loop == LOOP_FIND_IDEAL)
4979                                 goto loop;
4980                 }
4981
4982                 cached = block_group_cache_done(block_group);
4983                 if (unlikely(!cached))
4984                         found_uncached_bg = true;
4985
4986                 if (unlikely(block_group->ro))
4987                         goto loop;
4988
4989                 /*
4990                  * Ok we want to try and use the cluster allocator, so lets look
4991                  * there, unless we are on LOOP_NO_EMPTY_SIZE, since we will
4992                  * have tried the cluster allocator plenty of times at this
4993                  * point and not have found anything, so we are likely way too
4994                  * fragmented for the clustering stuff to find anything, so lets
4995                  * just skip it and let the allocator find whatever block it can
4996                  * find
4997                  */
4998                 if (last_ptr && loop < LOOP_NO_EMPTY_SIZE) {
4999                         /*
5000                          * the refill lock keeps out other
5001                          * people trying to start a new cluster
5002                          */
5003                         spin_lock(&last_ptr->refill_lock);
5004                         if (last_ptr->block_group &&
5005                             (last_ptr->block_group->ro ||
5006                             !block_group_bits(last_ptr->block_group, data))) {
5007                                 offset = 0;
5008                                 goto refill_cluster;
5009                         }
5010
5011                         offset = btrfs_alloc_from_cluster(block_group, last_ptr,
5012                                                  num_bytes, search_start);
5013                         if (offset) {
5014                                 /* we have a block, we're done */
5015                                 spin_unlock(&last_ptr->refill_lock);
5016                                 goto checks;
5017                         }
5018
5019                         spin_lock(&last_ptr->lock);
5020                         /*
5021                          * whoops, this cluster doesn't actually point to
5022                          * this block group.  Get a ref on the block
5023                          * group is does point to and try again
5024                          */
5025                         if (!last_ptr_loop && last_ptr->block_group &&
5026                             last_ptr->block_group != block_group) {
5027
5028                                 btrfs_put_block_group(block_group);
5029                                 block_group = last_ptr->block_group;
5030                                 btrfs_get_block_group(block_group);
5031                                 spin_unlock(&last_ptr->lock);
5032                                 spin_unlock(&last_ptr->refill_lock);
5033
5034                                 last_ptr_loop = 1;
5035                                 search_start = block_group->key.objectid;
5036                                 /*
5037                                  * we know this block group is properly
5038                                  * in the list because
5039                                  * btrfs_remove_block_group, drops the
5040                                  * cluster before it removes the block
5041                                  * group from the list
5042                                  */
5043                                 goto have_block_group;
5044                         }
5045                         spin_unlock(&last_ptr->lock);
5046 refill_cluster:
5047                         /*
5048                          * this cluster didn't work out, free it and
5049                          * start over
5050                          */
5051                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
5052
5053                         last_ptr_loop = 0;
5054
5055                         /* allocate a cluster in this block group */
5056                         ret = btrfs_find_space_cluster(trans, root,
5057                                                block_group, last_ptr,
5058                                                offset, num_bytes,
5059                                                empty_cluster + empty_size);
5060                         if (ret == 0) {
5061                                 /*
5062                                  * now pull our allocation out of this
5063                                  * cluster
5064                                  */
5065                                 offset = btrfs_alloc_from_cluster(block_group,
5066                                                   last_ptr, num_bytes,
5067                                                   search_start);
5068                                 if (offset) {
5069                                         /* we found one, proceed */
5070                                         spin_unlock(&last_ptr->refill_lock);
5071                                         goto checks;
5072                                 }
5073                         } else if (!cached && loop > LOOP_CACHING_NOWAIT
5074                                    && !failed_cluster_refill) {
5075                                 spin_unlock(&last_ptr->refill_lock);
5076
5077                                 failed_cluster_refill = true;
5078                                 wait_block_group_cache_progress(block_group,
5079                                        num_bytes + empty_cluster + empty_size);
5080                                 goto have_block_group;
5081                         }
5082
5083                         /*
5084                          * at this point we either didn't find a cluster
5085                          * or we weren't able to allocate a block from our
5086                          * cluster.  Free the cluster we've been trying
5087                          * to use, and go to the next block group
5088                          */
5089                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
5090                         spin_unlock(&last_ptr->refill_lock);
5091                         goto loop;
5092                 }
5093
5094                 offset = btrfs_find_space_for_alloc(block_group, search_start,
5095                                                     num_bytes, empty_size);
5096                 /*
5097                  * If we didn't find a chunk, and we haven't failed on this
5098                  * block group before, and this block group is in the middle of
5099                  * caching and we are ok with waiting, then go ahead and wait
5100                  * for progress to be made, and set failed_alloc to true.
5101                  *
5102                  * If failed_alloc is true then we've already waited on this
5103                  * block group once and should move on to the next block group.
5104                  */
5105                 if (!offset && !failed_alloc && !cached &&
5106                     loop > LOOP_CACHING_NOWAIT) {
5107                         wait_block_group_cache_progress(block_group,
5108                                                 num_bytes + empty_size);
5109                         failed_alloc = true;
5110                         goto have_block_group;
5111                 } else if (!offset) {
5112                         goto loop;
5113                 }
5114 checks:
5115                 search_start = stripe_align(root, offset);
5116                 /* move on to the next group */
5117                 if (search_start + num_bytes >= search_end) {
5118                         btrfs_add_free_space(block_group, offset, num_bytes);
5119                         goto loop;
5120                 }
5121
5122                 /* move on to the next group */
5123                 if (search_start + num_bytes >
5124                     block_group->key.objectid + block_group->key.offset) {
5125                         btrfs_add_free_space(block_group, offset, num_bytes);
5126                         goto loop;
5127                 }
5128
5129                 ins->objectid = search_start;
5130                 ins->offset = num_bytes;
5131
5132                 if (offset < search_start)
5133                         btrfs_add_free_space(block_group, offset,
5134                                              search_start - offset);
5135                 BUG_ON(offset > search_start);
5136
5137                 ret = btrfs_update_reserved_bytes(block_group, num_bytes, 1,
5138                                             (data & BTRFS_BLOCK_GROUP_DATA));
5139                 if (ret == -EAGAIN) {
5140                         btrfs_add_free_space(block_group, offset, num_bytes);
5141                         goto loop;
5142                 }
5143
5144                 /* we are all good, lets return */
5145                 ins->objectid = search_start;
5146                 ins->offset = num_bytes;
5147
5148                 if (offset < search_start)
5149                         btrfs_add_free_space(block_group, offset,
5150                                              search_start - offset);
5151                 BUG_ON(offset > search_start);
5152                 break;
5153 loop:
5154                 failed_cluster_refill = false;
5155                 failed_alloc = false;
5156                 BUG_ON(index != get_block_group_index(block_group));
5157                 btrfs_put_block_group(block_group);
5158         }
5159         up_read(&space_info->groups_sem);
5160
5161         if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
5162                 goto search;
5163
5164         /* LOOP_FIND_IDEAL, only search caching/cached bg's, and don't wait for
5165          *                      for them to make caching progress.  Also
5166          *                      determine the best possible bg to cache
5167          * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
5168          *                      caching kthreads as we move along
5169          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
5170          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
5171          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
5172          *                      again
5173          */
5174         if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE &&
5175             (found_uncached_bg || empty_size || empty_cluster ||
5176              allowed_chunk_alloc)) {
5177                 index = 0;
5178                 if (loop == LOOP_FIND_IDEAL && found_uncached_bg) {
5179                         found_uncached_bg = false;
5180                         loop++;
5181                         if (!ideal_cache_percent &&
5182                             atomic_read(&space_info->caching_threads))
5183                                 goto search;
5184
5185                         /*
5186                          * 1 of the following 2 things have happened so far
5187                          *
5188                          * 1) We found an ideal block group for caching that
5189                          * is mostly full and will cache quickly, so we might
5190                          * as well wait for it.
5191                          *
5192                          * 2) We searched for cached only and we didn't find
5193                          * anything, and we didn't start any caching kthreads
5194                          * either, so chances are we will loop through and
5195                          * start a couple caching kthreads, and then come back
5196                          * around and just wait for them.  This will be slower
5197                          * because we will have 2 caching kthreads reading at
5198                          * the same time when we could have just started one
5199                          * and waited for it to get far enough to give us an
5200                          * allocation, so go ahead and go to the wait caching
5201                          * loop.
5202                          */
5203                         loop = LOOP_CACHING_WAIT;
5204                         search_start = ideal_cache_offset;
5205                         ideal_cache_percent = 0;
5206                         goto ideal_cache;
5207                 } else if (loop == LOOP_FIND_IDEAL) {
5208                         /*
5209                          * Didn't find a uncached bg, wait on anything we find
5210                          * next.
5211                          */
5212                         loop = LOOP_CACHING_WAIT;
5213                         goto search;
5214                 }
5215
5216                 if (loop < LOOP_CACHING_WAIT) {
5217                         loop++;
5218                         goto search;
5219                 }
5220
5221                 if (loop == LOOP_ALLOC_CHUNK) {
5222                         empty_size = 0;
5223                         empty_cluster = 0;
5224                 }
5225
5226                 if (allowed_chunk_alloc) {
5227                         ret = do_chunk_alloc(trans, root, num_bytes +
5228                                              2 * 1024 * 1024, data,
5229                                              CHUNK_ALLOC_LIMITED);
5230                         allowed_chunk_alloc = 0;
5231                         done_chunk_alloc = 1;
5232                 } else if (!done_chunk_alloc &&
5233                            space_info->force_alloc == CHUNK_ALLOC_NO_FORCE) {
5234                         space_info->force_alloc = CHUNK_ALLOC_LIMITED;
5235                 }
5236
5237                 if (loop < LOOP_NO_EMPTY_SIZE) {
5238                         loop++;
5239                         goto search;
5240                 }
5241                 ret = -ENOSPC;
5242         } else if (!ins->objectid) {
5243                 ret = -ENOSPC;
5244         }
5245
5246         /* we found what we needed */
5247         if (ins->objectid) {
5248                 if (!(data & BTRFS_BLOCK_GROUP_DATA))
5249                         trans->block_group = block_group->key.objectid;
5250
5251                 btrfs_put_block_group(block_group);
5252                 ret = 0;
5253         }
5254
5255         return ret;
5256 }
5257
5258 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
5259                             int dump_block_groups)
5260 {
5261         struct btrfs_block_group_cache *cache;
5262         int index = 0;
5263
5264         spin_lock(&info->lock);
5265         printk(KERN_INFO "space_info has %llu free, is %sfull\n",
5266                (unsigned long long)(info->total_bytes - info->bytes_used -
5267                                     info->bytes_pinned - info->bytes_reserved -
5268                                     info->bytes_readonly),
5269                (info->full) ? "" : "not ");
5270         printk(KERN_INFO "space_info total=%llu, used=%llu, pinned=%llu, "
5271                "reserved=%llu, may_use=%llu, readonly=%llu\n",
5272                (unsigned long long)info->total_bytes,
5273                (unsigned long long)info->bytes_used,
5274                (unsigned long long)info->bytes_pinned,
5275                (unsigned long long)info->bytes_reserved,
5276                (unsigned long long)info->bytes_may_use,
5277                (unsigned long long)info->bytes_readonly);
5278         spin_unlock(&info->lock);
5279
5280         if (!dump_block_groups)
5281                 return;
5282
5283         down_read(&info->groups_sem);
5284 again:
5285         list_for_each_entry(cache, &info->block_groups[index], list) {
5286                 spin_lock(&cache->lock);
5287                 printk(KERN_INFO "block group %llu has %llu bytes, %llu used "
5288                        "%llu pinned %llu reserved\n",
5289                        (unsigned long long)cache->key.objectid,
5290                        (unsigned long long)cache->key.offset,
5291                        (unsigned long long)btrfs_block_group_used(&cache->item),
5292                        (unsigned long long)cache->pinned,
5293                        (unsigned long long)cache->reserved);
5294                 btrfs_dump_free_space(cache, bytes);
5295                 spin_unlock(&cache->lock);
5296         }
5297         if (++index < BTRFS_NR_RAID_TYPES)
5298                 goto again;
5299         up_read(&info->groups_sem);
5300 }
5301
5302 int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
5303                          struct btrfs_root *root,
5304                          u64 num_bytes, u64 min_alloc_size,
5305                          u64 empty_size, u64 hint_byte,
5306                          u64 search_end, struct btrfs_key *ins,
5307                          u64 data)
5308 {
5309         int ret;
5310         u64 search_start = 0;
5311
5312         data = btrfs_get_alloc_profile(root, data);
5313 again:
5314         /*
5315          * the only place that sets empty_size is btrfs_realloc_node, which
5316          * is not called recursively on allocations
5317          */
5318         if (empty_size || root->ref_cows)
5319                 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
5320                                      num_bytes + 2 * 1024 * 1024, data,
5321                                      CHUNK_ALLOC_NO_FORCE);
5322
5323         WARN_ON(num_bytes < root->sectorsize);
5324         ret = find_free_extent(trans, root, num_bytes, empty_size,
5325                                search_start, search_end, hint_byte,
5326                                ins, data);
5327
5328         if (ret == -ENOSPC && num_bytes > min_alloc_size) {
5329                 num_bytes = num_bytes >> 1;
5330                 num_bytes = num_bytes & ~(root->sectorsize - 1);
5331                 num_bytes = max(num_bytes, min_alloc_size);
5332                 do_chunk_alloc(trans, root->fs_info->extent_root,
5333                                num_bytes, data, CHUNK_ALLOC_FORCE);
5334                 goto again;
5335         }
5336         if (ret == -ENOSPC && btrfs_test_opt(root, ENOSPC_DEBUG)) {
5337                 struct btrfs_space_info *sinfo;
5338
5339                 sinfo = __find_space_info(root->fs_info, data);
5340                 printk(KERN_ERR "btrfs allocation failed flags %llu, "
5341                        "wanted %llu\n", (unsigned long long)data,
5342                        (unsigned long long)num_bytes);
5343                 dump_space_info(sinfo, num_bytes, 1);
5344         }
5345
5346         trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
5347
5348         return ret;
5349 }
5350
5351 int btrfs_free_reserved_extent(struct btrfs_root *root, u64 start, u64 len)
5352 {
5353         struct btrfs_block_group_cache *cache;
5354         int ret = 0;
5355
5356         cache = btrfs_lookup_block_group(root->fs_info, start);
5357         if (!cache) {
5358                 printk(KERN_ERR "Unable to find block group for %llu\n",
5359                        (unsigned long long)start);
5360                 return -ENOSPC;
5361         }
5362
5363         if (btrfs_test_opt(root, DISCARD))
5364                 ret = btrfs_discard_extent(root, start, len, NULL);
5365
5366         btrfs_add_free_space(cache, start, len);
5367         btrfs_update_reserved_bytes(cache, len, 0, 1);
5368         btrfs_put_block_group(cache);
5369
5370         trace_btrfs_reserved_extent_free(root, start, len);
5371
5372         return ret;
5373 }
5374
5375 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5376                                       struct btrfs_root *root,
5377                                       u64 parent, u64 root_objectid,
5378                                       u64 flags, u64 owner, u64 offset,
5379                                       struct btrfs_key *ins, int ref_mod)
5380 {
5381         int ret;
5382         struct btrfs_fs_info *fs_info = root->fs_info;
5383         struct btrfs_extent_item *extent_item;
5384         struct btrfs_extent_inline_ref *iref;
5385         struct btrfs_path *path;
5386         struct extent_buffer *leaf;
5387         int type;
5388         u32 size;
5389
5390         if (parent > 0)
5391                 type = BTRFS_SHARED_DATA_REF_KEY;
5392         else
5393                 type = BTRFS_EXTENT_DATA_REF_KEY;
5394
5395         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
5396
5397         path = btrfs_alloc_path();
5398         if (!path)
5399                 return -ENOMEM;
5400
5401         path->leave_spinning = 1;
5402         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
5403                                       ins, size);
5404         BUG_ON(ret);
5405
5406         leaf = path->nodes[0];
5407         extent_item = btrfs_item_ptr(leaf, path->slots[0],
5408                                      struct btrfs_extent_item);
5409         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
5410         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5411         btrfs_set_extent_flags(leaf, extent_item,
5412                                flags | BTRFS_EXTENT_FLAG_DATA);
5413
5414         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
5415         btrfs_set_extent_inline_ref_type(leaf, iref, type);
5416         if (parent > 0) {
5417                 struct btrfs_shared_data_ref *ref;
5418                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
5419                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
5420                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
5421         } else {
5422                 struct btrfs_extent_data_ref *ref;
5423                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
5424                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
5425                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
5426                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
5427                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
5428         }
5429
5430         btrfs_mark_buffer_dirty(path->nodes[0]);
5431         btrfs_free_path(path);
5432
5433         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
5434         if (ret) {
5435                 printk(KERN_ERR "btrfs update block group failed for %llu "
5436                        "%llu\n", (unsigned long long)ins->objectid,
5437                        (unsigned long long)ins->offset);
5438                 BUG();
5439         }
5440         return ret;
5441 }
5442
5443 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
5444                                      struct btrfs_root *root,
5445                                      u64 parent, u64 root_objectid,
5446                                      u64 flags, struct btrfs_disk_key *key,
5447                                      int level, struct btrfs_key *ins)
5448 {
5449         int ret;
5450         struct btrfs_fs_info *fs_info = root->fs_info;
5451         struct btrfs_extent_item *extent_item;
5452         struct btrfs_tree_block_info *block_info;
5453         struct btrfs_extent_inline_ref *iref;
5454         struct btrfs_path *path;
5455         struct extent_buffer *leaf;
5456         u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
5457
5458         path = btrfs_alloc_path();
5459         BUG_ON(!path);
5460
5461         path->leave_spinning = 1;
5462         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
5463                                       ins, size);
5464         BUG_ON(ret);
5465
5466         leaf = path->nodes[0];
5467         extent_item = btrfs_item_ptr(leaf, path->slots[0],
5468                                      struct btrfs_extent_item);
5469         btrfs_set_extent_refs(leaf, extent_item, 1);
5470         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5471         btrfs_set_extent_flags(leaf, extent_item,
5472                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
5473         block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
5474
5475         btrfs_set_tree_block_key(leaf, block_info, key);
5476         btrfs_set_tree_block_level(leaf, block_info, level);
5477
5478         iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
5479         if (parent > 0) {
5480                 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
5481                 btrfs_set_extent_inline_ref_type(leaf, iref,
5482                                                  BTRFS_SHARED_BLOCK_REF_KEY);
5483                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
5484         } else {
5485                 btrfs_set_extent_inline_ref_type(leaf, iref,
5486                                                  BTRFS_TREE_BLOCK_REF_KEY);
5487                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
5488         }
5489
5490         btrfs_mark_buffer_dirty(leaf);
5491         btrfs_free_path(path);
5492
5493         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
5494         if (ret) {
5495                 printk(KERN_ERR "btrfs update block group failed for %llu "
5496                        "%llu\n", (unsigned long long)ins->objectid,
5497                        (unsigned long long)ins->offset);
5498                 BUG();
5499         }
5500         return ret;
5501 }
5502
5503 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5504                                      struct btrfs_root *root,
5505                                      u64 root_objectid, u64 owner,
5506                                      u64 offset, struct btrfs_key *ins)
5507 {
5508         int ret;
5509
5510         BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
5511
5512         ret = btrfs_add_delayed_data_ref(trans, ins->objectid, ins->offset,
5513                                          0, root_objectid, owner, offset,
5514                                          BTRFS_ADD_DELAYED_EXTENT, NULL);
5515         return ret;
5516 }
5517
5518 /*
5519  * this is used by the tree logging recovery code.  It records that
5520  * an extent has been allocated and makes sure to clear the free
5521  * space cache bits as well
5522  */
5523 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
5524                                    struct btrfs_root *root,
5525                                    u64 root_objectid, u64 owner, u64 offset,
5526                                    struct btrfs_key *ins)
5527 {
5528         int ret;
5529         struct btrfs_block_group_cache *block_group;
5530         struct btrfs_caching_control *caching_ctl;
5531         u64 start = ins->objectid;
5532         u64 num_bytes = ins->offset;
5533
5534         block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
5535         cache_block_group(block_group, trans, NULL, 0);
5536         caching_ctl = get_caching_control(block_group);
5537
5538         if (!caching_ctl) {
5539                 BUG_ON(!block_group_cache_done(block_group));
5540                 ret = btrfs_remove_free_space(block_group, start, num_bytes);
5541                 BUG_ON(ret);
5542         } else {
5543                 mutex_lock(&caching_ctl->mutex);
5544
5545                 if (start >= caching_ctl->progress) {
5546                         ret = add_excluded_extent(root, start, num_bytes);
5547                         BUG_ON(ret);
5548                 } else if (start + num_bytes <= caching_ctl->progress) {
5549                         ret = btrfs_remove_free_space(block_group,
5550                                                       start, num_bytes);
5551                         BUG_ON(ret);
5552                 } else {
5553                         num_bytes = caching_ctl->progress - start;
5554                         ret = btrfs_remove_free_space(block_group,
5555                                                       start, num_bytes);
5556                         BUG_ON(ret);
5557
5558                         start = caching_ctl->progress;
5559                         num_bytes = ins->objectid + ins->offset -
5560                                     caching_ctl->progress;
5561                         ret = add_excluded_extent(root, start, num_bytes);
5562                         BUG_ON(ret);
5563                 }
5564
5565                 mutex_unlock(&caching_ctl->mutex);
5566                 put_caching_control(caching_ctl);
5567         }
5568
5569         ret = btrfs_update_reserved_bytes(block_group, ins->offset, 1, 1);
5570         BUG_ON(ret);
5571         btrfs_put_block_group(block_group);
5572         ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
5573                                          0, owner, offset, ins, 1);
5574         return ret;
5575 }
5576
5577 struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
5578                                             struct btrfs_root *root,
5579                                             u64 bytenr, u32 blocksize,
5580                                             int level)
5581 {
5582         struct extent_buffer *buf;
5583
5584         buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
5585         if (!buf)
5586                 return ERR_PTR(-ENOMEM);
5587         btrfs_set_header_generation(buf, trans->transid);
5588         btrfs_set_buffer_lockdep_class(buf, level);
5589         btrfs_tree_lock(buf);
5590         clean_tree_block(trans, root, buf);
5591
5592         btrfs_set_lock_blocking(buf);
5593         btrfs_set_buffer_uptodate(buf);
5594
5595         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
5596                 /*
5597                  * we allow two log transactions at a time, use different
5598                  * EXENT bit to differentiate dirty pages.
5599                  */
5600                 if (root->log_transid % 2 == 0)
5601                         set_extent_dirty(&root->dirty_log_pages, buf->start,
5602                                         buf->start + buf->len - 1, GFP_NOFS);
5603                 else
5604                         set_extent_new(&root->dirty_log_pages, buf->start,
5605                                         buf->start + buf->len - 1, GFP_NOFS);
5606         } else {
5607                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
5608                          buf->start + buf->len - 1, GFP_NOFS);
5609         }
5610         trans->blocks_used++;
5611         /* this returns a buffer locked for blocking */
5612         return buf;
5613 }
5614
5615 static struct btrfs_block_rsv *
5616 use_block_rsv(struct btrfs_trans_handle *trans,
5617               struct btrfs_root *root, u32 blocksize)
5618 {
5619         struct btrfs_block_rsv *block_rsv;
5620         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
5621         int ret;
5622
5623         block_rsv = get_block_rsv(trans, root);
5624
5625         if (block_rsv->size == 0) {
5626                 ret = reserve_metadata_bytes(trans, root, block_rsv,
5627                                              blocksize, 0);
5628                 /*
5629                  * If we couldn't reserve metadata bytes try and use some from
5630                  * the global reserve.
5631                  */
5632                 if (ret && block_rsv != global_rsv) {
5633                         ret = block_rsv_use_bytes(global_rsv, blocksize);
5634                         if (!ret)
5635                                 return global_rsv;
5636                         return ERR_PTR(ret);
5637                 } else if (ret) {
5638                         return ERR_PTR(ret);
5639                 }
5640                 return block_rsv;
5641         }
5642
5643         ret = block_rsv_use_bytes(block_rsv, blocksize);
5644         if (!ret)
5645                 return block_rsv;
5646         if (ret) {
5647                 WARN_ON(1);
5648                 ret = reserve_metadata_bytes(trans, root, block_rsv, blocksize,
5649                                              0);
5650                 if (!ret) {
5651                         spin_lock(&block_rsv->lock);
5652                         block_rsv->size += blocksize;
5653                         spin_unlock(&block_rsv->lock);
5654                         return block_rsv;
5655                 } else if (ret && block_rsv != global_rsv) {
5656                         ret = block_rsv_use_bytes(global_rsv, blocksize);
5657                         if (!ret)
5658                                 return global_rsv;
5659                 }
5660         }
5661
5662         return ERR_PTR(-ENOSPC);
5663 }
5664
5665 static void unuse_block_rsv(struct btrfs_block_rsv *block_rsv, u32 blocksize)
5666 {
5667         block_rsv_add_bytes(block_rsv, blocksize, 0);
5668         block_rsv_release_bytes(block_rsv, NULL, 0);
5669 }
5670
5671 /*
5672  * finds a free extent and does all the dirty work required for allocation
5673  * returns the key for the extent through ins, and a tree buffer for
5674  * the first block of the extent through buf.
5675  *
5676  * returns the tree buffer or NULL.
5677  */
5678 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
5679                                         struct btrfs_root *root, u32 blocksize,
5680                                         u64 parent, u64 root_objectid,
5681                                         struct btrfs_disk_key *key, int level,
5682                                         u64 hint, u64 empty_size)
5683 {
5684         struct btrfs_key ins;
5685         struct btrfs_block_rsv *block_rsv;
5686         struct extent_buffer *buf;
5687         u64 flags = 0;
5688         int ret;
5689
5690
5691         block_rsv = use_block_rsv(trans, root, blocksize);
5692         if (IS_ERR(block_rsv))
5693                 return ERR_CAST(block_rsv);
5694
5695         ret = btrfs_reserve_extent(trans, root, blocksize, blocksize,
5696                                    empty_size, hint, (u64)-1, &ins, 0);
5697         if (ret) {
5698                 unuse_block_rsv(block_rsv, blocksize);
5699                 return ERR_PTR(ret);
5700         }
5701
5702         buf = btrfs_init_new_buffer(trans, root, ins.objectid,
5703                                     blocksize, level);
5704         BUG_ON(IS_ERR(buf));
5705
5706         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
5707                 if (parent == 0)
5708                         parent = ins.objectid;
5709                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5710         } else
5711                 BUG_ON(parent > 0);
5712
5713         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
5714                 struct btrfs_delayed_extent_op *extent_op;
5715                 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
5716                 BUG_ON(!extent_op);
5717                 if (key)
5718                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
5719                 else
5720                         memset(&extent_op->key, 0, sizeof(extent_op->key));
5721                 extent_op->flags_to_set = flags;
5722                 extent_op->update_key = 1;
5723                 extent_op->update_flags = 1;
5724                 extent_op->is_data = 0;
5725
5726                 ret = btrfs_add_delayed_tree_ref(trans, ins.objectid,
5727                                         ins.offset, parent, root_objectid,
5728                                         level, BTRFS_ADD_DELAYED_EXTENT,
5729                                         extent_op);
5730                 BUG_ON(ret);
5731         }
5732         return buf;
5733 }
5734
5735 struct walk_control {
5736         u64 refs[BTRFS_MAX_LEVEL];
5737         u64 flags[BTRFS_MAX_LEVEL];
5738         struct btrfs_key update_progress;
5739         int stage;
5740         int level;
5741         int shared_level;
5742         int update_ref;
5743         int keep_locks;
5744         int reada_slot;
5745         int reada_count;
5746 };
5747
5748 #define DROP_REFERENCE  1
5749 #define UPDATE_BACKREF  2
5750
5751 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5752                                      struct btrfs_root *root,
5753                                      struct walk_control *wc,
5754                                      struct btrfs_path *path)
5755 {
5756         u64 bytenr;
5757         u64 generation;
5758         u64 refs;
5759         u64 flags;
5760         u32 nritems;
5761         u32 blocksize;
5762         struct btrfs_key key;
5763         struct extent_buffer *eb;
5764         int ret;
5765         int slot;
5766         int nread = 0;
5767
5768         if (path->slots[wc->level] < wc->reada_slot) {
5769                 wc->reada_count = wc->reada_count * 2 / 3;
5770                 wc->reada_count = max(wc->reada_count, 2);
5771         } else {
5772                 wc->reada_count = wc->reada_count * 3 / 2;
5773                 wc->reada_count = min_t(int, wc->reada_count,
5774                                         BTRFS_NODEPTRS_PER_BLOCK(root));
5775         }
5776
5777         eb = path->nodes[wc->level];
5778         nritems = btrfs_header_nritems(eb);
5779         blocksize = btrfs_level_size(root, wc->level - 1);
5780
5781         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5782                 if (nread >= wc->reada_count)
5783                         break;
5784
5785                 cond_resched();
5786                 bytenr = btrfs_node_blockptr(eb, slot);
5787                 generation = btrfs_node_ptr_generation(eb, slot);
5788
5789                 if (slot == path->slots[wc->level])
5790                         goto reada;
5791
5792                 if (wc->stage == UPDATE_BACKREF &&
5793                     generation <= root->root_key.offset)
5794                         continue;
5795
5796                 /* We don't lock the tree block, it's OK to be racy here */
5797                 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
5798                                                &refs, &flags);
5799                 BUG_ON(ret);
5800                 BUG_ON(refs == 0);
5801
5802                 if (wc->stage == DROP_REFERENCE) {
5803                         if (refs == 1)
5804                                 goto reada;
5805
5806                         if (wc->level == 1 &&
5807                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5808                                 continue;
5809                         if (!wc->update_ref ||
5810                             generation <= root->root_key.offset)
5811                                 continue;
5812                         btrfs_node_key_to_cpu(eb, &key, slot);
5813                         ret = btrfs_comp_cpu_keys(&key,
5814                                                   &wc->update_progress);
5815                         if (ret < 0)
5816                                 continue;
5817                 } else {
5818                         if (wc->level == 1 &&
5819                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5820                                 continue;
5821                 }
5822 reada:
5823                 ret = readahead_tree_block(root, bytenr, blocksize,
5824                                            generation);
5825                 if (ret)
5826                         break;
5827                 nread++;
5828         }
5829         wc->reada_slot = slot;
5830 }
5831
5832 /*
5833  * hepler to process tree block while walking down the tree.
5834  *
5835  * when wc->stage == UPDATE_BACKREF, this function updates
5836  * back refs for pointers in the block.
5837  *
5838  * NOTE: return value 1 means we should stop walking down.
5839  */
5840 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5841                                    struct btrfs_root *root,
5842                                    struct btrfs_path *path,
5843                                    struct walk_control *wc, int lookup_info)
5844 {
5845         int level = wc->level;
5846         struct extent_buffer *eb = path->nodes[level];
5847         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5848         int ret;
5849
5850         if (wc->stage == UPDATE_BACKREF &&
5851             btrfs_header_owner(eb) != root->root_key.objectid)
5852                 return 1;
5853
5854         /*
5855          * when reference count of tree block is 1, it won't increase
5856          * again. once full backref flag is set, we never clear it.
5857          */
5858         if (lookup_info &&
5859             ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5860              (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5861                 BUG_ON(!path->locks[level]);
5862                 ret = btrfs_lookup_extent_info(trans, root,
5863                                                eb->start, eb->len,
5864                                                &wc->refs[level],
5865                                                &wc->flags[level]);
5866                 BUG_ON(ret);
5867                 BUG_ON(wc->refs[level] == 0);
5868         }
5869
5870         if (wc->stage == DROP_REFERENCE) {
5871                 if (wc->refs[level] > 1)
5872                         return 1;
5873
5874                 if (path->locks[level] && !wc->keep_locks) {
5875                         btrfs_tree_unlock(eb);
5876                         path->locks[level] = 0;
5877                 }
5878                 return 0;
5879         }
5880
5881         /* wc->stage == UPDATE_BACKREF */
5882         if (!(wc->flags[level] & flag)) {
5883                 BUG_ON(!path->locks[level]);
5884                 ret = btrfs_inc_ref(trans, root, eb, 1);
5885                 BUG_ON(ret);
5886                 ret = btrfs_dec_ref(trans, root, eb, 0);
5887                 BUG_ON(ret);
5888                 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
5889                                                   eb->len, flag, 0);
5890                 BUG_ON(ret);
5891                 wc->flags[level] |= flag;
5892         }
5893
5894         /*
5895          * the block is shared by multiple trees, so it's not good to
5896          * keep the tree lock
5897          */
5898         if (path->locks[level] && level > 0) {
5899                 btrfs_tree_unlock(eb);
5900                 path->locks[level] = 0;
5901         }
5902         return 0;
5903 }
5904
5905 /*
5906  * hepler to process tree block pointer.
5907  *
5908  * when wc->stage == DROP_REFERENCE, this function checks
5909  * reference count of the block pointed to. if the block
5910  * is shared and we need update back refs for the subtree
5911  * rooted at the block, this function changes wc->stage to
5912  * UPDATE_BACKREF. if the block is shared and there is no
5913  * need to update back, this function drops the reference
5914  * to the block.
5915  *
5916  * NOTE: return value 1 means we should stop walking down.
5917  */
5918 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5919                                  struct btrfs_root *root,
5920                                  struct btrfs_path *path,
5921                                  struct walk_control *wc, int *lookup_info)
5922 {
5923         u64 bytenr;
5924         u64 generation;
5925         u64 parent;
5926         u32 blocksize;
5927         struct btrfs_key key;
5928         struct extent_buffer *next;
5929         int level = wc->level;
5930         int reada = 0;
5931         int ret = 0;
5932
5933         generation = btrfs_node_ptr_generation(path->nodes[level],
5934                                                path->slots[level]);
5935         /*
5936          * if the lower level block was created before the snapshot
5937          * was created, we know there is no need to update back refs
5938          * for the subtree
5939          */
5940         if (wc->stage == UPDATE_BACKREF &&
5941             generation <= root->root_key.offset) {
5942                 *lookup_info = 1;
5943                 return 1;
5944         }
5945
5946         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5947         blocksize = btrfs_level_size(root, level - 1);
5948
5949         next = btrfs_find_tree_block(root, bytenr, blocksize);
5950         if (!next) {
5951                 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
5952                 if (!next)
5953                         return -ENOMEM;
5954                 reada = 1;
5955         }
5956         btrfs_tree_lock(next);
5957         btrfs_set_lock_blocking(next);
5958
5959         ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
5960                                        &wc->refs[level - 1],
5961                                        &wc->flags[level - 1]);
5962         BUG_ON(ret);
5963         BUG_ON(wc->refs[level - 1] == 0);
5964         *lookup_info = 0;
5965
5966         if (wc->stage == DROP_REFERENCE) {
5967                 if (wc->refs[level - 1] > 1) {
5968                         if (level == 1 &&
5969                             (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5970                                 goto skip;
5971
5972                         if (!wc->update_ref ||
5973                             generation <= root->root_key.offset)
5974                                 goto skip;
5975
5976                         btrfs_node_key_to_cpu(path->nodes[level], &key,
5977                                               path->slots[level]);
5978                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
5979                         if (ret < 0)
5980                                 goto skip;
5981
5982                         wc->stage = UPDATE_BACKREF;
5983                         wc->shared_level = level - 1;
5984                 }
5985         } else {
5986                 if (level == 1 &&
5987                     (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5988                         goto skip;
5989         }
5990
5991         if (!btrfs_buffer_uptodate(next, generation)) {
5992                 btrfs_tree_unlock(next);
5993                 free_extent_buffer(next);
5994                 next = NULL;
5995                 *lookup_info = 1;
5996         }
5997
5998         if (!next) {
5999                 if (reada && level == 1)
6000                         reada_walk_down(trans, root, wc, path);
6001                 next = read_tree_block(root, bytenr, blocksize, generation);
6002                 if (!next)
6003                         return -EIO;
6004                 btrfs_tree_lock(next);
6005                 btrfs_set_lock_blocking(next);
6006         }
6007
6008         level--;
6009         BUG_ON(level != btrfs_header_level(next));
6010         path->nodes[level] = next;
6011         path->slots[level] = 0;
6012         path->locks[level] = 1;
6013         wc->level = level;
6014         if (wc->level == 1)
6015                 wc->reada_slot = 0;
6016         return 0;
6017 skip:
6018         wc->refs[level - 1] = 0;
6019         wc->flags[level - 1] = 0;
6020         if (wc->stage == DROP_REFERENCE) {
6021                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6022                         parent = path->nodes[level]->start;
6023                 } else {
6024                         BUG_ON(root->root_key.objectid !=
6025                                btrfs_header_owner(path->nodes[level]));
6026                         parent = 0;
6027                 }
6028
6029                 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
6030                                         root->root_key.objectid, level - 1, 0);
6031                 BUG_ON(ret);
6032         }
6033         btrfs_tree_unlock(next);
6034         free_extent_buffer(next);
6035         *lookup_info = 1;
6036         return 1;
6037 }
6038
6039 /*
6040  * hepler to process tree block while walking up the tree.
6041  *
6042  * when wc->stage == DROP_REFERENCE, this function drops
6043  * reference count on the block.
6044  *
6045  * when wc->stage == UPDATE_BACKREF, this function changes
6046  * wc->stage back to DROP_REFERENCE if we changed wc->stage
6047  * to UPDATE_BACKREF previously while processing the block.
6048  *
6049  * NOTE: return value 1 means we should stop walking up.
6050  */
6051 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6052                                  struct btrfs_root *root,
6053                                  struct btrfs_path *path,
6054                                  struct walk_control *wc)
6055 {
6056         int ret;
6057         int level = wc->level;
6058         struct extent_buffer *eb = path->nodes[level];
6059         u64 parent = 0;
6060
6061         if (wc->stage == UPDATE_BACKREF) {
6062                 BUG_ON(wc->shared_level < level);
6063                 if (level < wc->shared_level)
6064                         goto out;
6065
6066                 ret = find_next_key(path, level + 1, &wc->update_progress);
6067                 if (ret > 0)
6068                         wc->update_ref = 0;
6069
6070                 wc->stage = DROP_REFERENCE;
6071                 wc->shared_level = -1;
6072                 path->slots[level] = 0;
6073
6074                 /*
6075                  * check reference count again if the block isn't locked.
6076                  * we should start walking down the tree again if reference
6077                  * count is one.
6078                  */
6079                 if (!path->locks[level]) {
6080                         BUG_ON(level == 0);
6081                         btrfs_tree_lock(eb);
6082                         btrfs_set_lock_blocking(eb);
6083                         path->locks[level] = 1;
6084
6085                         ret = btrfs_lookup_extent_info(trans, root,
6086                                                        eb->start, eb->len,
6087                                                        &wc->refs[level],
6088                                                        &wc->flags[level]);
6089                         BUG_ON(ret);
6090                         BUG_ON(wc->refs[level] == 0);
6091                         if (wc->refs[level] == 1) {
6092                                 btrfs_tree_unlock(eb);
6093                                 path->locks[level] = 0;
6094                                 return 1;
6095                         }
6096                 }
6097         }
6098
6099         /* wc->stage == DROP_REFERENCE */
6100         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
6101
6102         if (wc->refs[level] == 1) {
6103                 if (level == 0) {
6104                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6105                                 ret = btrfs_dec_ref(trans, root, eb, 1);
6106                         else
6107                                 ret = btrfs_dec_ref(trans, root, eb, 0);
6108                         BUG_ON(ret);
6109                 }
6110                 /* make block locked assertion in clean_tree_block happy */
6111                 if (!path->locks[level] &&
6112                     btrfs_header_generation(eb) == trans->transid) {
6113                         btrfs_tree_lock(eb);
6114                         btrfs_set_lock_blocking(eb);
6115                         path->locks[level] = 1;
6116                 }
6117                 clean_tree_block(trans, root, eb);
6118         }
6119
6120         if (eb == root->node) {
6121                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6122                         parent = eb->start;
6123                 else
6124                         BUG_ON(root->root_key.objectid !=
6125                                btrfs_header_owner(eb));
6126         } else {
6127                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6128                         parent = path->nodes[level + 1]->start;
6129                 else
6130                         BUG_ON(root->root_key.objectid !=
6131                                btrfs_header_owner(path->nodes[level + 1]));
6132         }
6133
6134         btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
6135 out:
6136         wc->refs[level] = 0;
6137         wc->flags[level] = 0;
6138         return 0;
6139 }
6140
6141 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
6142                                    struct btrfs_root *root,
6143                                    struct btrfs_path *path,
6144                                    struct walk_control *wc)
6145 {
6146         int level = wc->level;
6147         int lookup_info = 1;
6148         int ret;
6149
6150         while (level >= 0) {
6151                 ret = walk_down_proc(trans, root, path, wc, lookup_info);
6152                 if (ret > 0)
6153                         break;
6154
6155                 if (level == 0)
6156                         break;
6157
6158                 if (path->slots[level] >=
6159                     btrfs_header_nritems(path->nodes[level]))
6160                         break;
6161
6162                 ret = do_walk_down(trans, root, path, wc, &lookup_info);
6163                 if (ret > 0) {
6164                         path->slots[level]++;
6165                         continue;
6166                 } else if (ret < 0)
6167                         return ret;
6168                 level = wc->level;
6169         }
6170         return 0;
6171 }
6172
6173 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
6174                                  struct btrfs_root *root,
6175                                  struct btrfs_path *path,
6176                                  struct walk_control *wc, int max_level)
6177 {
6178         int level = wc->level;
6179         int ret;
6180
6181         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6182         while (level < max_level && path->nodes[level]) {
6183                 wc->level = level;
6184                 if (path->slots[level] + 1 <
6185                     btrfs_header_nritems(path->nodes[level])) {
6186                         path->slots[level]++;
6187                         return 0;
6188                 } else {
6189                         ret = walk_up_proc(trans, root, path, wc);
6190                         if (ret > 0)
6191                                 return 0;
6192
6193                         if (path->locks[level]) {
6194                                 btrfs_tree_unlock(path->nodes[level]);
6195                                 path->locks[level] = 0;
6196                         }
6197                         free_extent_buffer(path->nodes[level]);
6198                         path->nodes[level] = NULL;
6199                         level++;
6200                 }
6201         }
6202         return 1;
6203 }
6204
6205 /*
6206  * drop a subvolume tree.
6207  *
6208  * this function traverses the tree freeing any blocks that only
6209  * referenced by the tree.
6210  *
6211  * when a shared tree block is found. this function decreases its
6212  * reference count by one. if update_ref is true, this function
6213  * also make sure backrefs for the shared block and all lower level
6214  * blocks are properly updated.
6215  */
6216 int btrfs_drop_snapshot(struct btrfs_root *root,
6217                         struct btrfs_block_rsv *block_rsv, int update_ref)
6218 {
6219         struct btrfs_path *path;
6220         struct btrfs_trans_handle *trans;
6221         struct btrfs_root *tree_root = root->fs_info->tree_root;
6222         struct btrfs_root_item *root_item = &root->root_item;
6223         struct walk_control *wc;
6224         struct btrfs_key key;
6225         int err = 0;
6226         int ret;
6227         int level;
6228
6229         path = btrfs_alloc_path();
6230         BUG_ON(!path);
6231
6232         wc = kzalloc(sizeof(*wc), GFP_NOFS);
6233         BUG_ON(!wc);
6234
6235         trans = btrfs_start_transaction(tree_root, 0);
6236         BUG_ON(IS_ERR(trans));
6237
6238         if (block_rsv)
6239                 trans->block_rsv = block_rsv;
6240
6241         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
6242                 level = btrfs_header_level(root->node);
6243                 path->nodes[level] = btrfs_lock_root_node(root);
6244                 btrfs_set_lock_blocking(path->nodes[level]);
6245                 path->slots[level] = 0;
6246                 path->locks[level] = 1;
6247                 memset(&wc->update_progress, 0,
6248                        sizeof(wc->update_progress));
6249         } else {
6250                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
6251                 memcpy(&wc->update_progress, &key,
6252                        sizeof(wc->update_progress));
6253
6254                 level = root_item->drop_level;
6255                 BUG_ON(level == 0);
6256                 path->lowest_level = level;
6257                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6258                 path->lowest_level = 0;
6259                 if (ret < 0) {
6260                         err = ret;
6261                         goto out;
6262                 }
6263                 WARN_ON(ret > 0);
6264
6265                 /*
6266                  * unlock our path, this is safe because only this
6267                  * function is allowed to delete this snapshot
6268                  */
6269                 btrfs_unlock_up_safe(path, 0);
6270
6271                 level = btrfs_header_level(root->node);
6272                 while (1) {
6273                         btrfs_tree_lock(path->nodes[level]);
6274                         btrfs_set_lock_blocking(path->nodes[level]);
6275
6276                         ret = btrfs_lookup_extent_info(trans, root,
6277                                                 path->nodes[level]->start,
6278                                                 path->nodes[level]->len,
6279                                                 &wc->refs[level],
6280                                                 &wc->flags[level]);
6281                         BUG_ON(ret);
6282                         BUG_ON(wc->refs[level] == 0);
6283
6284                         if (level == root_item->drop_level)
6285                                 break;
6286
6287                         btrfs_tree_unlock(path->nodes[level]);
6288                         WARN_ON(wc->refs[level] != 1);
6289                         level--;
6290                 }
6291         }
6292
6293         wc->level = level;
6294         wc->shared_level = -1;
6295         wc->stage = DROP_REFERENCE;
6296         wc->update_ref = update_ref;
6297         wc->keep_locks = 0;
6298         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
6299
6300         while (1) {
6301                 ret = walk_down_tree(trans, root, path, wc);
6302                 if (ret < 0) {
6303                         err = ret;
6304                         break;
6305                 }
6306
6307                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
6308                 if (ret < 0) {
6309                         err = ret;
6310                         break;
6311                 }
6312
6313                 if (ret > 0) {
6314                         BUG_ON(wc->stage != DROP_REFERENCE);
6315                         break;
6316                 }
6317
6318                 if (wc->stage == DROP_REFERENCE) {
6319                         level = wc->level;
6320                         btrfs_node_key(path->nodes[level],
6321                                        &root_item->drop_progress,
6322                                        path->slots[level]);
6323                         root_item->drop_level = level;
6324                 }
6325
6326                 BUG_ON(wc->level == 0);
6327                 if (btrfs_should_end_transaction(trans, tree_root)) {
6328                         ret = btrfs_update_root(trans, tree_root,
6329                                                 &root->root_key,
6330                                                 root_item);
6331                         BUG_ON(ret);
6332
6333                         btrfs_end_transaction_throttle(trans, tree_root);
6334                         trans = btrfs_start_transaction(tree_root, 0);
6335                         BUG_ON(IS_ERR(trans));
6336                         if (block_rsv)
6337                                 trans->block_rsv = block_rsv;
6338                 }
6339         }
6340         btrfs_release_path(path);
6341         BUG_ON(err);
6342
6343         ret = btrfs_del_root(trans, tree_root, &root->root_key);
6344         BUG_ON(ret);
6345
6346         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
6347                 ret = btrfs_find_last_root(tree_root, root->root_key.objectid,
6348                                            NULL, NULL);
6349                 BUG_ON(ret < 0);
6350                 if (ret > 0) {
6351                         /* if we fail to delete the orphan item this time
6352                          * around, it'll get picked up the next time.
6353                          *
6354                          * The most common failure here is just -ENOENT.
6355                          */
6356                         btrfs_del_orphan_item(trans, tree_root,
6357                                               root->root_key.objectid);
6358                 }
6359         }
6360
6361         if (root->in_radix) {
6362                 btrfs_free_fs_root(tree_root->fs_info, root);
6363         } else {
6364                 free_extent_buffer(root->node);
6365                 free_extent_buffer(root->commit_root);
6366                 kfree(root);
6367         }
6368 out:
6369         btrfs_end_transaction_throttle(trans, tree_root);
6370         kfree(wc);
6371         btrfs_free_path(path);
6372         return err;
6373 }
6374
6375 /*
6376  * drop subtree rooted at tree block 'node'.
6377  *
6378  * NOTE: this function will unlock and release tree block 'node'
6379  */
6380 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
6381                         struct btrfs_root *root,
6382                         struct extent_buffer *node,
6383                         struct extent_buffer *parent)
6384 {
6385         struct btrfs_path *path;
6386         struct walk_control *wc;
6387         int level;
6388         int parent_level;
6389         int ret = 0;
6390         int wret;
6391
6392         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
6393
6394         path = btrfs_alloc_path();
6395         if (!path)
6396                 return -ENOMEM;
6397
6398         wc = kzalloc(sizeof(*wc), GFP_NOFS);
6399         if (!wc) {
6400                 btrfs_free_path(path);
6401                 return -ENOMEM;
6402         }
6403
6404         btrfs_assert_tree_locked(parent);
6405         parent_level = btrfs_header_level(parent);
6406         extent_buffer_get(parent);
6407         path->nodes[parent_level] = parent;
6408         path->slots[parent_level] = btrfs_header_nritems(parent);
6409
6410         btrfs_assert_tree_locked(node);
6411         level = btrfs_header_level(node);
6412         path->nodes[level] = node;
6413         path->slots[level] = 0;
6414         path->locks[level] = 1;
6415
6416         wc->refs[parent_level] = 1;
6417         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6418         wc->level = level;
6419         wc->shared_level = -1;
6420         wc->stage = DROP_REFERENCE;
6421         wc->update_ref = 0;
6422         wc->keep_locks = 1;
6423         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
6424
6425         while (1) {
6426                 wret = walk_down_tree(trans, root, path, wc);
6427                 if (wret < 0) {
6428                         ret = wret;
6429                         break;
6430                 }
6431
6432                 wret = walk_up_tree(trans, root, path, wc, parent_level);
6433                 if (wret < 0)
6434                         ret = wret;
6435                 if (wret != 0)
6436                         break;
6437         }
6438
6439         kfree(wc);
6440         btrfs_free_path(path);
6441         return ret;
6442 }
6443
6444 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
6445 {
6446         u64 num_devices;
6447         u64 stripped = BTRFS_BLOCK_GROUP_RAID0 |
6448                 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
6449
6450         /*
6451          * we add in the count of missing devices because we want
6452          * to make sure that any RAID levels on a degraded FS
6453          * continue to be honored.
6454          */
6455         num_devices = root->fs_info->fs_devices->rw_devices +
6456                 root->fs_info->fs_devices->missing_devices;
6457
6458         if (num_devices == 1) {
6459                 stripped |= BTRFS_BLOCK_GROUP_DUP;
6460                 stripped = flags & ~stripped;
6461
6462                 /* turn raid0 into single device chunks */
6463                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
6464                         return stripped;
6465
6466                 /* turn mirroring into duplication */
6467                 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
6468                              BTRFS_BLOCK_GROUP_RAID10))
6469                         return stripped | BTRFS_BLOCK_GROUP_DUP;
6470                 return flags;
6471         } else {
6472                 /* they already had raid on here, just return */
6473                 if (flags & stripped)
6474                         return flags;
6475
6476                 stripped |= BTRFS_BLOCK_GROUP_DUP;
6477                 stripped = flags & ~stripped;
6478
6479                 /* switch duplicated blocks with raid1 */
6480                 if (flags & BTRFS_BLOCK_GROUP_DUP)
6481                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
6482
6483                 /* turn single device chunks into raid0 */
6484                 return stripped | BTRFS_BLOCK_GROUP_RAID0;
6485         }
6486         return flags;
6487 }
6488
6489 static int set_block_group_ro(struct btrfs_block_group_cache *cache)
6490 {
6491         struct btrfs_space_info *sinfo = cache->space_info;
6492         u64 num_bytes;
6493         int ret = -ENOSPC;
6494
6495         if (cache->ro)
6496                 return 0;
6497
6498         spin_lock(&sinfo->lock);
6499         spin_lock(&cache->lock);
6500         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
6501                     cache->bytes_super - btrfs_block_group_used(&cache->item);
6502
6503         if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
6504             sinfo->bytes_may_use + sinfo->bytes_readonly +
6505             cache->reserved_pinned + num_bytes <= sinfo->total_bytes) {
6506                 sinfo->bytes_readonly += num_bytes;
6507                 sinfo->bytes_reserved += cache->reserved_pinned;
6508                 cache->reserved_pinned = 0;
6509                 cache->ro = 1;
6510                 ret = 0;
6511         }
6512
6513         spin_unlock(&cache->lock);
6514         spin_unlock(&sinfo->lock);
6515         return ret;
6516 }
6517
6518 int btrfs_set_block_group_ro(struct btrfs_root *root,
6519                              struct btrfs_block_group_cache *cache)
6520
6521 {
6522         struct btrfs_trans_handle *trans;
6523         u64 alloc_flags;
6524         int ret;
6525
6526         BUG_ON(cache->ro);
6527
6528         trans = btrfs_join_transaction(root, 1);
6529         BUG_ON(IS_ERR(trans));
6530
6531         alloc_flags = update_block_group_flags(root, cache->flags);
6532         if (alloc_flags != cache->flags)
6533                 do_chunk_alloc(trans, root, 2 * 1024 * 1024, alloc_flags,
6534                                CHUNK_ALLOC_FORCE);
6535
6536         ret = set_block_group_ro(cache);
6537         if (!ret)
6538                 goto out;
6539         alloc_flags = get_alloc_profile(root, cache->space_info->flags);
6540         ret = do_chunk_alloc(trans, root, 2 * 1024 * 1024, alloc_flags,
6541                              CHUNK_ALLOC_FORCE);
6542         if (ret < 0)
6543                 goto out;
6544         ret = set_block_group_ro(cache);
6545 out:
6546         btrfs_end_transaction(trans, root);
6547         return ret;
6548 }
6549
6550 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
6551                             struct btrfs_root *root, u64 type)
6552 {
6553         u64 alloc_flags = get_alloc_profile(root, type);
6554         return do_chunk_alloc(trans, root, 2 * 1024 * 1024, alloc_flags,
6555                               CHUNK_ALLOC_FORCE);
6556 }
6557
6558 /*
6559  * helper to account the unused space of all the readonly block group in the
6560  * list. takes mirrors into account.
6561  */
6562 static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
6563 {
6564         struct btrfs_block_group_cache *block_group;
6565         u64 free_bytes = 0;
6566         int factor;
6567
6568         list_for_each_entry(block_group, groups_list, list) {
6569                 spin_lock(&block_group->lock);
6570
6571                 if (!block_group->ro) {
6572                         spin_unlock(&block_group->lock);
6573                         continue;
6574                 }
6575
6576                 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
6577                                           BTRFS_BLOCK_GROUP_RAID10 |
6578                                           BTRFS_BLOCK_GROUP_DUP))
6579                         factor = 2;
6580                 else
6581                         factor = 1;
6582
6583                 free_bytes += (block_group->key.offset -
6584                                btrfs_block_group_used(&block_group->item)) *
6585                                factor;
6586
6587                 spin_unlock(&block_group->lock);
6588         }
6589
6590         return free_bytes;
6591 }
6592
6593 /*
6594  * helper to account the unused space of all the readonly block group in the
6595  * space_info. takes mirrors into account.
6596  */
6597 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
6598 {
6599         int i;
6600         u64 free_bytes = 0;
6601
6602         spin_lock(&sinfo->lock);
6603
6604         for(i = 0; i < BTRFS_NR_RAID_TYPES; i++)
6605                 if (!list_empty(&sinfo->block_groups[i]))
6606                         free_bytes += __btrfs_get_ro_block_group_free_space(
6607                                                 &sinfo->block_groups[i]);
6608
6609         spin_unlock(&sinfo->lock);
6610
6611         return free_bytes;
6612 }
6613
6614 int btrfs_set_block_group_rw(struct btrfs_root *root,
6615                               struct btrfs_block_group_cache *cache)
6616 {
6617         struct btrfs_space_info *sinfo = cache->space_info;
6618         u64 num_bytes;
6619
6620         BUG_ON(!cache->ro);
6621
6622         spin_lock(&sinfo->lock);
6623         spin_lock(&cache->lock);
6624         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
6625                     cache->bytes_super - btrfs_block_group_used(&cache->item);
6626         sinfo->bytes_readonly -= num_bytes;
6627         cache->ro = 0;
6628         spin_unlock(&cache->lock);
6629         spin_unlock(&sinfo->lock);
6630         return 0;
6631 }
6632
6633 /*
6634  * checks to see if its even possible to relocate this block group.
6635  *
6636  * @return - -1 if it's not a good idea to relocate this block group, 0 if its
6637  * ok to go ahead and try.
6638  */
6639 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
6640 {
6641         struct btrfs_block_group_cache *block_group;
6642         struct btrfs_space_info *space_info;
6643         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
6644         struct btrfs_device *device;
6645         int full = 0;
6646         int ret = 0;
6647
6648         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
6649
6650         /* odd, couldn't find the block group, leave it alone */
6651         if (!block_group)
6652                 return -1;
6653
6654         /* no bytes used, we're good */
6655         if (!btrfs_block_group_used(&block_group->item))
6656                 goto out;
6657
6658         space_info = block_group->space_info;
6659         spin_lock(&space_info->lock);
6660
6661         full = space_info->full;
6662
6663         /*
6664          * if this is the last block group we have in this space, we can't
6665          * relocate it unless we're able to allocate a new chunk below.
6666          *
6667          * Otherwise, we need to make sure we have room in the space to handle
6668          * all of the extents from this block group.  If we can, we're good
6669          */
6670         if ((space_info->total_bytes != block_group->key.offset) &&
6671            (space_info->bytes_used + space_info->bytes_reserved +
6672             space_info->bytes_pinned + space_info->bytes_readonly +
6673             btrfs_block_group_used(&block_group->item) <
6674             space_info->total_bytes)) {
6675                 spin_unlock(&space_info->lock);
6676                 goto out;
6677         }
6678         spin_unlock(&space_info->lock);
6679
6680         /*
6681          * ok we don't have enough space, but maybe we have free space on our
6682          * devices to allocate new chunks for relocation, so loop through our
6683          * alloc devices and guess if we have enough space.  However, if we
6684          * were marked as full, then we know there aren't enough chunks, and we
6685          * can just return.
6686          */
6687         ret = -1;
6688         if (full)
6689                 goto out;
6690
6691         mutex_lock(&root->fs_info->chunk_mutex);
6692         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
6693                 u64 min_free = btrfs_block_group_used(&block_group->item);
6694                 u64 dev_offset;
6695
6696                 /*
6697                  * check to make sure we can actually find a chunk with enough
6698                  * space to fit our block group in.
6699                  */
6700                 if (device->total_bytes > device->bytes_used + min_free) {
6701                         ret = find_free_dev_extent(NULL, device, min_free,
6702                                                    &dev_offset, NULL);
6703                         if (!ret)
6704                                 break;
6705                         ret = -1;
6706                 }
6707         }
6708         mutex_unlock(&root->fs_info->chunk_mutex);
6709 out:
6710         btrfs_put_block_group(block_group);
6711         return ret;
6712 }
6713
6714 static int find_first_block_group(struct btrfs_root *root,
6715                 struct btrfs_path *path, struct btrfs_key *key)
6716 {
6717         int ret = 0;
6718         struct btrfs_key found_key;
6719         struct extent_buffer *leaf;
6720         int slot;
6721
6722         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
6723         if (ret < 0)
6724                 goto out;
6725
6726         while (1) {
6727                 slot = path->slots[0];
6728                 leaf = path->nodes[0];
6729                 if (slot >= btrfs_header_nritems(leaf)) {
6730                         ret = btrfs_next_leaf(root, path);
6731                         if (ret == 0)
6732                                 continue;
6733                         if (ret < 0)
6734                                 goto out;
6735                         break;
6736                 }
6737                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
6738
6739                 if (found_key.objectid >= key->objectid &&
6740                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
6741                         ret = 0;
6742                         goto out;
6743                 }
6744                 path->slots[0]++;
6745         }
6746 out:
6747         return ret;
6748 }
6749
6750 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
6751 {
6752         struct btrfs_block_group_cache *block_group;
6753         u64 last = 0;
6754
6755         while (1) {
6756                 struct inode *inode;
6757
6758                 block_group = btrfs_lookup_first_block_group(info, last);
6759                 while (block_group) {
6760                         spin_lock(&block_group->lock);
6761                         if (block_group->iref)
6762                                 break;
6763                         spin_unlock(&block_group->lock);
6764                         block_group = next_block_group(info->tree_root,
6765                                                        block_group);
6766                 }
6767                 if (!block_group) {
6768                         if (last == 0)
6769                                 break;
6770                         last = 0;
6771                         continue;
6772                 }
6773
6774                 inode = block_group->inode;
6775                 block_group->iref = 0;
6776                 block_group->inode = NULL;
6777                 spin_unlock(&block_group->lock);
6778                 iput(inode);
6779                 last = block_group->key.objectid + block_group->key.offset;
6780                 btrfs_put_block_group(block_group);
6781         }
6782 }
6783
6784 int btrfs_free_block_groups(struct btrfs_fs_info *info)
6785 {
6786         struct btrfs_block_group_cache *block_group;
6787         struct btrfs_space_info *space_info;
6788         struct btrfs_caching_control *caching_ctl;
6789         struct rb_node *n;
6790
6791         down_write(&info->extent_commit_sem);
6792         while (!list_empty(&info->caching_block_groups)) {
6793                 caching_ctl = list_entry(info->caching_block_groups.next,
6794                                          struct btrfs_caching_control, list);
6795                 list_del(&caching_ctl->list);
6796                 put_caching_control(caching_ctl);
6797         }
6798         up_write(&info->extent_commit_sem);
6799
6800         spin_lock(&info->block_group_cache_lock);
6801         while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
6802                 block_group = rb_entry(n, struct btrfs_block_group_cache,
6803                                        cache_node);
6804                 rb_erase(&block_group->cache_node,
6805                          &info->block_group_cache_tree);
6806                 spin_unlock(&info->block_group_cache_lock);
6807
6808                 down_write(&block_group->space_info->groups_sem);
6809                 list_del(&block_group->list);
6810                 up_write(&block_group->space_info->groups_sem);
6811
6812                 if (block_group->cached == BTRFS_CACHE_STARTED)
6813                         wait_block_group_cache_done(block_group);
6814
6815                 /*
6816                  * We haven't cached this block group, which means we could
6817                  * possibly have excluded extents on this block group.
6818                  */
6819                 if (block_group->cached == BTRFS_CACHE_NO)
6820                         free_excluded_extents(info->extent_root, block_group);
6821
6822                 btrfs_remove_free_space_cache(block_group);
6823                 btrfs_put_block_group(block_group);
6824
6825                 spin_lock(&info->block_group_cache_lock);
6826         }
6827         spin_unlock(&info->block_group_cache_lock);
6828
6829         /* now that all the block groups are freed, go through and
6830          * free all the space_info structs.  This is only called during
6831          * the final stages of unmount, and so we know nobody is
6832          * using them.  We call synchronize_rcu() once before we start,
6833          * just to be on the safe side.
6834          */
6835         synchronize_rcu();
6836
6837         release_global_block_rsv(info);
6838
6839         while(!list_empty(&info->space_info)) {
6840                 space_info = list_entry(info->space_info.next,
6841                                         struct btrfs_space_info,
6842                                         list);
6843                 if (space_info->bytes_pinned > 0 ||
6844                     space_info->bytes_reserved > 0) {
6845                         WARN_ON(1);
6846                         dump_space_info(space_info, 0, 0);
6847                 }
6848                 list_del(&space_info->list);
6849                 kfree(space_info);
6850         }
6851         return 0;
6852 }
6853
6854 static void __link_block_group(struct btrfs_space_info *space_info,
6855                                struct btrfs_block_group_cache *cache)
6856 {
6857         int index = get_block_group_index(cache);
6858
6859         down_write(&space_info->groups_sem);
6860         list_add_tail(&cache->list, &space_info->block_groups[index]);
6861         up_write(&space_info->groups_sem);
6862 }
6863
6864 int btrfs_read_block_groups(struct btrfs_root *root)
6865 {
6866         struct btrfs_path *path;
6867         int ret;
6868         struct btrfs_block_group_cache *cache;
6869         struct btrfs_fs_info *info = root->fs_info;
6870         struct btrfs_space_info *space_info;
6871         struct btrfs_key key;
6872         struct btrfs_key found_key;
6873         struct extent_buffer *leaf;
6874         int need_clear = 0;
6875         u64 cache_gen;
6876
6877         root = info->extent_root;
6878         key.objectid = 0;
6879         key.offset = 0;
6880         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
6881         path = btrfs_alloc_path();
6882         if (!path)
6883                 return -ENOMEM;
6884
6885         cache_gen = btrfs_super_cache_generation(&root->fs_info->super_copy);
6886         if (cache_gen != 0 &&
6887             btrfs_super_generation(&root->fs_info->super_copy) != cache_gen)
6888                 need_clear = 1;
6889         if (btrfs_test_opt(root, CLEAR_CACHE))
6890                 need_clear = 1;
6891         if (!btrfs_test_opt(root, SPACE_CACHE) && cache_gen)
6892                 printk(KERN_INFO "btrfs: disk space caching is enabled\n");
6893
6894         while (1) {
6895                 ret = find_first_block_group(root, path, &key);
6896                 if (ret > 0)
6897                         break;
6898                 if (ret != 0)
6899                         goto error;
6900                 leaf = path->nodes[0];
6901                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6902                 cache = kzalloc(sizeof(*cache), GFP_NOFS);
6903                 if (!cache) {
6904                         ret = -ENOMEM;
6905                         goto error;
6906                 }
6907                 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
6908                                                 GFP_NOFS);
6909                 if (!cache->free_space_ctl) {
6910                         kfree(cache);
6911                         ret = -ENOMEM;
6912                         goto error;
6913                 }
6914
6915                 atomic_set(&cache->count, 1);
6916                 spin_lock_init(&cache->lock);
6917                 cache->fs_info = info;
6918                 INIT_LIST_HEAD(&cache->list);
6919                 INIT_LIST_HEAD(&cache->cluster_list);
6920
6921                 if (need_clear)
6922                         cache->disk_cache_state = BTRFS_DC_CLEAR;
6923
6924                 read_extent_buffer(leaf, &cache->item,
6925                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
6926                                    sizeof(cache->item));
6927                 memcpy(&cache->key, &found_key, sizeof(found_key));
6928
6929                 key.objectid = found_key.objectid + found_key.offset;
6930                 btrfs_release_path(path);
6931                 cache->flags = btrfs_block_group_flags(&cache->item);
6932                 cache->sectorsize = root->sectorsize;
6933
6934                 btrfs_init_free_space_ctl(cache);
6935
6936                 /*
6937                  * We need to exclude the super stripes now so that the space
6938                  * info has super bytes accounted for, otherwise we'll think
6939                  * we have more space than we actually do.
6940                  */
6941                 exclude_super_stripes(root, cache);
6942
6943                 /*
6944                  * check for two cases, either we are full, and therefore
6945                  * don't need to bother with the caching work since we won't
6946                  * find any space, or we are empty, and we can just add all
6947                  * the space in and be done with it.  This saves us _alot_ of
6948                  * time, particularly in the full case.
6949                  */
6950                 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
6951                         cache->last_byte_to_unpin = (u64)-1;
6952                         cache->cached = BTRFS_CACHE_FINISHED;
6953                         free_excluded_extents(root, cache);
6954                 } else if (btrfs_block_group_used(&cache->item) == 0) {
6955                         cache->last_byte_to_unpin = (u64)-1;
6956                         cache->cached = BTRFS_CACHE_FINISHED;
6957                         add_new_free_space(cache, root->fs_info,
6958                                            found_key.objectid,
6959                                            found_key.objectid +
6960                                            found_key.offset);
6961                         free_excluded_extents(root, cache);
6962                 }
6963
6964                 ret = update_space_info(info, cache->flags, found_key.offset,
6965                                         btrfs_block_group_used(&cache->item),
6966                                         &space_info);
6967                 BUG_ON(ret);
6968                 cache->space_info = space_info;
6969                 spin_lock(&cache->space_info->lock);
6970                 cache->space_info->bytes_readonly += cache->bytes_super;
6971                 spin_unlock(&cache->space_info->lock);
6972
6973                 __link_block_group(space_info, cache);
6974
6975                 ret = btrfs_add_block_group_cache(root->fs_info, cache);
6976                 BUG_ON(ret);
6977
6978                 set_avail_alloc_bits(root->fs_info, cache->flags);
6979                 if (btrfs_chunk_readonly(root, cache->key.objectid))
6980                         set_block_group_ro(cache);
6981         }
6982
6983         list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
6984                 if (!(get_alloc_profile(root, space_info->flags) &
6985                       (BTRFS_BLOCK_GROUP_RAID10 |
6986                        BTRFS_BLOCK_GROUP_RAID1 |
6987                        BTRFS_BLOCK_GROUP_DUP)))
6988                         continue;
6989                 /*
6990                  * avoid allocating from un-mirrored block group if there are
6991                  * mirrored block groups.
6992                  */
6993                 list_for_each_entry(cache, &space_info->block_groups[3], list)
6994                         set_block_group_ro(cache);
6995                 list_for_each_entry(cache, &space_info->block_groups[4], list)
6996                         set_block_group_ro(cache);
6997         }
6998
6999         init_global_block_rsv(info);
7000         ret = 0;
7001 error:
7002         btrfs_free_path(path);
7003         return ret;
7004 }
7005
7006 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
7007                            struct btrfs_root *root, u64 bytes_used,
7008                            u64 type, u64 chunk_objectid, u64 chunk_offset,
7009                            u64 size)
7010 {
7011         int ret;
7012         struct btrfs_root *extent_root;
7013         struct btrfs_block_group_cache *cache;
7014
7015         extent_root = root->fs_info->extent_root;
7016
7017         root->fs_info->last_trans_log_full_commit = trans->transid;
7018
7019         cache = kzalloc(sizeof(*cache), GFP_NOFS);
7020         if (!cache)
7021                 return -ENOMEM;
7022         cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
7023                                         GFP_NOFS);
7024         if (!cache->free_space_ctl) {
7025                 kfree(cache);
7026                 return -ENOMEM;
7027         }
7028
7029         cache->key.objectid = chunk_offset;
7030         cache->key.offset = size;
7031         cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
7032         cache->sectorsize = root->sectorsize;
7033         cache->fs_info = root->fs_info;
7034
7035         atomic_set(&cache->count, 1);
7036         spin_lock_init(&cache->lock);
7037         INIT_LIST_HEAD(&cache->list);
7038         INIT_LIST_HEAD(&cache->cluster_list);
7039
7040         btrfs_init_free_space_ctl(cache);
7041
7042         btrfs_set_block_group_used(&cache->item, bytes_used);
7043         btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
7044         cache->flags = type;
7045         btrfs_set_block_group_flags(&cache->item, type);
7046
7047         cache->last_byte_to_unpin = (u64)-1;
7048         cache->cached = BTRFS_CACHE_FINISHED;
7049         exclude_super_stripes(root, cache);
7050
7051         add_new_free_space(cache, root->fs_info, chunk_offset,
7052                            chunk_offset + size);
7053
7054         free_excluded_extents(root, cache);
7055
7056         ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
7057                                 &cache->space_info);
7058         BUG_ON(ret);
7059
7060         spin_lock(&cache->space_info->lock);
7061         cache->space_info->bytes_readonly += cache->bytes_super;
7062         spin_unlock(&cache->space_info->lock);
7063
7064         __link_block_group(cache->space_info, cache);
7065
7066         ret = btrfs_add_block_group_cache(root->fs_info, cache);
7067         BUG_ON(ret);
7068
7069         ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
7070                                 sizeof(cache->item));
7071         BUG_ON(ret);
7072
7073         set_avail_alloc_bits(extent_root->fs_info, type);
7074
7075         return 0;
7076 }
7077
7078 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
7079                              struct btrfs_root *root, u64 group_start)
7080 {
7081         struct btrfs_path *path;
7082         struct btrfs_block_group_cache *block_group;
7083         struct btrfs_free_cluster *cluster;
7084         struct btrfs_root *tree_root = root->fs_info->tree_root;
7085         struct btrfs_key key;
7086         struct inode *inode;
7087         int ret;
7088         int factor;
7089
7090         root = root->fs_info->extent_root;
7091
7092         block_group = btrfs_lookup_block_group(root->fs_info, group_start);
7093         BUG_ON(!block_group);
7094         BUG_ON(!block_group->ro);
7095
7096         /*
7097          * Free the reserved super bytes from this block group before
7098          * remove it.
7099          */
7100         free_excluded_extents(root, block_group);
7101
7102         memcpy(&key, &block_group->key, sizeof(key));
7103         if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
7104                                   BTRFS_BLOCK_GROUP_RAID1 |
7105                                   BTRFS_BLOCK_GROUP_RAID10))
7106                 factor = 2;
7107         else
7108                 factor = 1;
7109
7110         /* make sure this block group isn't part of an allocation cluster */
7111         cluster = &root->fs_info->data_alloc_cluster;
7112         spin_lock(&cluster->refill_lock);
7113         btrfs_return_cluster_to_free_space(block_group, cluster);
7114         spin_unlock(&cluster->refill_lock);
7115
7116         /*
7117          * make sure this block group isn't part of a metadata
7118          * allocation cluster
7119          */
7120         cluster = &root->fs_info->meta_alloc_cluster;
7121         spin_lock(&cluster->refill_lock);
7122         btrfs_return_cluster_to_free_space(block_group, cluster);
7123         spin_unlock(&cluster->refill_lock);
7124
7125         path = btrfs_alloc_path();
7126         BUG_ON(!path);
7127
7128         inode = lookup_free_space_inode(root, block_group, path);
7129         if (!IS_ERR(inode)) {
7130                 btrfs_orphan_add(trans, inode);
7131                 clear_nlink(inode);
7132                 /* One for the block groups ref */
7133                 spin_lock(&block_group->lock);
7134                 if (block_group->iref) {
7135                         block_group->iref = 0;
7136                         block_group->inode = NULL;
7137                         spin_unlock(&block_group->lock);
7138                         iput(inode);
7139                 } else {
7140                         spin_unlock(&block_group->lock);
7141                 }
7142                 /* One for our lookup ref */
7143                 iput(inode);
7144         }
7145
7146         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
7147         key.offset = block_group->key.objectid;
7148         key.type = 0;
7149
7150         ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
7151         if (ret < 0)
7152                 goto out;
7153         if (ret > 0)
7154                 btrfs_release_path(path);
7155         if (ret == 0) {
7156                 ret = btrfs_del_item(trans, tree_root, path);
7157                 if (ret)
7158                         goto out;
7159                 btrfs_release_path(path);
7160         }
7161
7162         spin_lock(&root->fs_info->block_group_cache_lock);
7163         rb_erase(&block_group->cache_node,
7164                  &root->fs_info->block_group_cache_tree);
7165         spin_unlock(&root->fs_info->block_group_cache_lock);
7166
7167         down_write(&block_group->space_info->groups_sem);
7168         /*
7169          * we must use list_del_init so people can check to see if they
7170          * are still on the list after taking the semaphore
7171          */
7172         list_del_init(&block_group->list);
7173         up_write(&block_group->space_info->groups_sem);
7174
7175         if (block_group->cached == BTRFS_CACHE_STARTED)
7176                 wait_block_group_cache_done(block_group);
7177
7178         btrfs_remove_free_space_cache(block_group);
7179
7180         spin_lock(&block_group->space_info->lock);
7181         block_group->space_info->total_bytes -= block_group->key.offset;
7182         block_group->space_info->bytes_readonly -= block_group->key.offset;
7183         block_group->space_info->disk_total -= block_group->key.offset * factor;
7184         spin_unlock(&block_group->space_info->lock);
7185
7186         memcpy(&key, &block_group->key, sizeof(key));
7187
7188         btrfs_clear_space_info_full(root->fs_info);
7189
7190         btrfs_put_block_group(block_group);
7191         btrfs_put_block_group(block_group);
7192
7193         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
7194         if (ret > 0)
7195                 ret = -EIO;
7196         if (ret < 0)
7197                 goto out;
7198
7199         ret = btrfs_del_item(trans, root, path);
7200 out:
7201         btrfs_free_path(path);
7202         return ret;
7203 }
7204
7205 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
7206 {
7207         struct btrfs_space_info *space_info;
7208         struct btrfs_super_block *disk_super;
7209         u64 features;
7210         u64 flags;
7211         int mixed = 0;
7212         int ret;
7213
7214         disk_super = &fs_info->super_copy;
7215         if (!btrfs_super_root(disk_super))
7216                 return 1;
7217
7218         features = btrfs_super_incompat_flags(disk_super);
7219         if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
7220                 mixed = 1;
7221
7222         flags = BTRFS_BLOCK_GROUP_SYSTEM;
7223         ret = update_space_info(fs_info, flags, 0, 0, &space_info);
7224         if (ret)
7225                 goto out;
7226
7227         if (mixed) {
7228                 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
7229                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
7230         } else {
7231                 flags = BTRFS_BLOCK_GROUP_METADATA;
7232                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
7233                 if (ret)
7234                         goto out;
7235
7236                 flags = BTRFS_BLOCK_GROUP_DATA;
7237                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
7238         }
7239 out:
7240         return ret;
7241 }
7242
7243 int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
7244 {
7245         return unpin_extent_range(root, start, end);
7246 }
7247
7248 int btrfs_error_discard_extent(struct btrfs_root *root, u64 bytenr,
7249                                u64 num_bytes, u64 *actual_bytes)
7250 {
7251         return btrfs_discard_extent(root, bytenr, num_bytes, actual_bytes);
7252 }
7253
7254 int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
7255 {
7256         struct btrfs_fs_info *fs_info = root->fs_info;
7257         struct btrfs_block_group_cache *cache = NULL;
7258         u64 group_trimmed;
7259         u64 start;
7260         u64 end;
7261         u64 trimmed = 0;
7262         int ret = 0;
7263
7264         cache = btrfs_lookup_block_group(fs_info, range->start);
7265
7266         while (cache) {
7267                 if (cache->key.objectid >= (range->start + range->len)) {
7268                         btrfs_put_block_group(cache);
7269                         break;
7270                 }
7271
7272                 start = max(range->start, cache->key.objectid);
7273                 end = min(range->start + range->len,
7274                                 cache->key.objectid + cache->key.offset);
7275
7276                 if (end - start >= range->minlen) {
7277                         if (!block_group_cache_done(cache)) {
7278                                 ret = cache_block_group(cache, NULL, root, 0);
7279                                 if (!ret)
7280                                         wait_block_group_cache_done(cache);
7281                         }
7282                         ret = btrfs_trim_block_group(cache,
7283                                                      &group_trimmed,
7284                                                      start,
7285                                                      end,
7286                                                      range->minlen);
7287
7288                         trimmed += group_trimmed;
7289                         if (ret) {
7290                                 btrfs_put_block_group(cache);
7291                                 break;
7292                         }
7293                 }
7294
7295                 cache = next_block_group(fs_info->tree_root, cache);
7296         }
7297
7298         range->len = trimmed;
7299         return ret;
7300 }