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