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 static int update_reserved_bytes(struct btrfs_block_group_cache *cache,
40                                  u64 num_bytes, int reserve, int sinfo);
41 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
42                                 struct btrfs_root *root,
43                                 u64 bytenr, u64 num_bytes, u64 parent,
44                                 u64 root_objectid, u64 owner_objectid,
45                                 u64 owner_offset, int refs_to_drop,
46                                 struct btrfs_delayed_extent_op *extra_op);
47 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
48                                     struct extent_buffer *leaf,
49                                     struct btrfs_extent_item *ei);
50 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
51                                       struct btrfs_root *root,
52                                       u64 parent, u64 root_objectid,
53                                       u64 flags, u64 owner, u64 offset,
54                                       struct btrfs_key *ins, int ref_mod);
55 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
56                                      struct btrfs_root *root,
57                                      u64 parent, u64 root_objectid,
58                                      u64 flags, struct btrfs_disk_key *key,
59                                      int level, struct btrfs_key *ins);
60 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
61                           struct btrfs_root *extent_root, u64 alloc_bytes,
62                           u64 flags, int force);
63 static int find_next_key(struct btrfs_path *path, int level,
64                          struct btrfs_key *key);
65 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
66                             int dump_block_groups);
67
68 static noinline int
69 block_group_cache_done(struct btrfs_block_group_cache *cache)
70 {
71         smp_mb();
72         return cache->cached == BTRFS_CACHE_FINISHED;
73 }
74
75 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
76 {
77         return (cache->flags & bits) == bits;
78 }
79
80 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
81 {
82         atomic_inc(&cache->count);
83 }
84
85 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
86 {
87         if (atomic_dec_and_test(&cache->count)) {
88                 WARN_ON(cache->pinned > 0);
89                 WARN_ON(cache->reserved > 0);
90                 WARN_ON(cache->reserved_pinned > 0);
91                 kfree(cache);
92         }
93 }
94
95 /*
96  * this adds the block group to the fs_info rb tree for the block group
97  * cache
98  */
99 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
100                                 struct btrfs_block_group_cache *block_group)
101 {
102         struct rb_node **p;
103         struct rb_node *parent = NULL;
104         struct btrfs_block_group_cache *cache;
105
106         spin_lock(&info->block_group_cache_lock);
107         p = &info->block_group_cache_tree.rb_node;
108
109         while (*p) {
110                 parent = *p;
111                 cache = rb_entry(parent, struct btrfs_block_group_cache,
112                                  cache_node);
113                 if (block_group->key.objectid < cache->key.objectid) {
114                         p = &(*p)->rb_left;
115                 } else if (block_group->key.objectid > cache->key.objectid) {
116                         p = &(*p)->rb_right;
117                 } else {
118                         spin_unlock(&info->block_group_cache_lock);
119                         return -EEXIST;
120                 }
121         }
122
123         rb_link_node(&block_group->cache_node, parent, p);
124         rb_insert_color(&block_group->cache_node,
125                         &info->block_group_cache_tree);
126         spin_unlock(&info->block_group_cache_lock);
127
128         return 0;
129 }
130
131 /*
132  * This will return the block group at or after bytenr if contains is 0, else
133  * it will return the block group that contains the bytenr
134  */
135 static struct btrfs_block_group_cache *
136 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
137                               int contains)
138 {
139         struct btrfs_block_group_cache *cache, *ret = NULL;
140         struct rb_node *n;
141         u64 end, start;
142
143         spin_lock(&info->block_group_cache_lock);
144         n = info->block_group_cache_tree.rb_node;
145
146         while (n) {
147                 cache = rb_entry(n, struct btrfs_block_group_cache,
148                                  cache_node);
149                 end = cache->key.objectid + cache->key.offset - 1;
150                 start = cache->key.objectid;
151
152                 if (bytenr < start) {
153                         if (!contains && (!ret || start < ret->key.objectid))
154                                 ret = cache;
155                         n = n->rb_left;
156                 } else if (bytenr > start) {
157                         if (contains && bytenr <= end) {
158                                 ret = cache;
159                                 break;
160                         }
161                         n = n->rb_right;
162                 } else {
163                         ret = cache;
164                         break;
165                 }
166         }
167         if (ret)
168                 btrfs_get_block_group(ret);
169         spin_unlock(&info->block_group_cache_lock);
170
171         return ret;
172 }
173
174 static int add_excluded_extent(struct btrfs_root *root,
175                                u64 start, u64 num_bytes)
176 {
177         u64 end = start + num_bytes - 1;
178         set_extent_bits(&root->fs_info->freed_extents[0],
179                         start, end, EXTENT_UPTODATE, GFP_NOFS);
180         set_extent_bits(&root->fs_info->freed_extents[1],
181                         start, end, EXTENT_UPTODATE, GFP_NOFS);
182         return 0;
183 }
184
185 static void free_excluded_extents(struct btrfs_root *root,
186                                   struct btrfs_block_group_cache *cache)
187 {
188         u64 start, end;
189
190         start = cache->key.objectid;
191         end = start + cache->key.offset - 1;
192
193         clear_extent_bits(&root->fs_info->freed_extents[0],
194                           start, end, EXTENT_UPTODATE, GFP_NOFS);
195         clear_extent_bits(&root->fs_info->freed_extents[1],
196                           start, end, EXTENT_UPTODATE, GFP_NOFS);
197 }
198
199 static int exclude_super_stripes(struct btrfs_root *root,
200                                  struct btrfs_block_group_cache *cache)
201 {
202         u64 bytenr;
203         u64 *logical;
204         int stripe_len;
205         int i, nr, ret;
206
207         if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
208                 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
209                 cache->bytes_super += stripe_len;
210                 ret = add_excluded_extent(root, cache->key.objectid,
211                                           stripe_len);
212                 BUG_ON(ret);
213         }
214
215         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
216                 bytenr = btrfs_sb_offset(i);
217                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
218                                        cache->key.objectid, bytenr,
219                                        0, &logical, &nr, &stripe_len);
220                 BUG_ON(ret);
221
222                 while (nr--) {
223                         cache->bytes_super += stripe_len;
224                         ret = add_excluded_extent(root, logical[nr],
225                                                   stripe_len);
226                         BUG_ON(ret);
227                 }
228
229                 kfree(logical);
230         }
231         return 0;
232 }
233
234 static struct btrfs_caching_control *
235 get_caching_control(struct btrfs_block_group_cache *cache)
236 {
237         struct btrfs_caching_control *ctl;
238
239         spin_lock(&cache->lock);
240         if (cache->cached != BTRFS_CACHE_STARTED) {
241                 spin_unlock(&cache->lock);
242                 return NULL;
243         }
244
245         /* We're loading it the fast way, so we don't have a caching_ctl. */
246         if (!cache->caching_ctl) {
247                 spin_unlock(&cache->lock);
248                 return NULL;
249         }
250
251         ctl = cache->caching_ctl;
252         atomic_inc(&ctl->count);
253         spin_unlock(&cache->lock);
254         return ctl;
255 }
256
257 static void put_caching_control(struct btrfs_caching_control *ctl)
258 {
259         if (atomic_dec_and_test(&ctl->count))
260                 kfree(ctl);
261 }
262
263 /*
264  * this is only called by cache_block_group, since we could have freed extents
265  * we need to check the pinned_extents for any extents that can't be used yet
266  * since their free space will be released as soon as the transaction commits.
267  */
268 static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
269                               struct btrfs_fs_info *info, u64 start, u64 end)
270 {
271         u64 extent_start, extent_end, size, total_added = 0;
272         int ret;
273
274         while (start < end) {
275                 ret = find_first_extent_bit(info->pinned_extents, start,
276                                             &extent_start, &extent_end,
277                                             EXTENT_DIRTY | EXTENT_UPTODATE);
278                 if (ret)
279                         break;
280
281                 if (extent_start <= start) {
282                         start = extent_end + 1;
283                 } else if (extent_start > start && extent_start < end) {
284                         size = extent_start - start;
285                         total_added += size;
286                         ret = btrfs_add_free_space(block_group, start,
287                                                    size);
288                         BUG_ON(ret);
289                         start = extent_end + 1;
290                 } else {
291                         break;
292                 }
293         }
294
295         if (start < end) {
296                 size = end - start;
297                 total_added += size;
298                 ret = btrfs_add_free_space(block_group, start, size);
299                 BUG_ON(ret);
300         }
301
302         return total_added;
303 }
304
305 static int caching_kthread(void *data)
306 {
307         struct btrfs_block_group_cache *block_group = data;
308         struct btrfs_fs_info *fs_info = block_group->fs_info;
309         struct btrfs_caching_control *caching_ctl = block_group->caching_ctl;
310         struct btrfs_root *extent_root = fs_info->extent_root;
311         struct btrfs_path *path;
312         struct extent_buffer *leaf;
313         struct btrfs_key key;
314         u64 total_found = 0;
315         u64 last = 0;
316         u32 nritems;
317         int ret = 0;
318
319         path = btrfs_alloc_path();
320         if (!path)
321                 return -ENOMEM;
322
323         exclude_super_stripes(extent_root, block_group);
324         spin_lock(&block_group->space_info->lock);
325         block_group->space_info->bytes_readonly += block_group->bytes_super;
326         spin_unlock(&block_group->space_info->lock);
327
328         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
329
330         /*
331          * We don't want to deadlock with somebody trying to allocate a new
332          * extent for the extent root while also trying to search the extent
333          * root to add free space.  So we skip locking and search the commit
334          * root, since its read-only
335          */
336         path->skip_locking = 1;
337         path->search_commit_root = 1;
338         path->reada = 2;
339
340         key.objectid = last;
341         key.offset = 0;
342         key.type = BTRFS_EXTENT_ITEM_KEY;
343 again:
344         mutex_lock(&caching_ctl->mutex);
345         /* need to make sure the commit_root doesn't disappear */
346         down_read(&fs_info->extent_commit_sem);
347
348         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
349         if (ret < 0)
350                 goto err;
351
352         leaf = path->nodes[0];
353         nritems = btrfs_header_nritems(leaf);
354
355         while (1) {
356                 smp_mb();
357                 if (fs_info->closing > 1) {
358                         last = (u64)-1;
359                         break;
360                 }
361
362                 if (path->slots[0] < nritems) {
363                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
364                 } else {
365                         ret = find_next_key(path, 0, &key);
366                         if (ret)
367                                 break;
368
369                         caching_ctl->progress = last;
370                         btrfs_release_path(extent_root, path);
371                         up_read(&fs_info->extent_commit_sem);
372                         mutex_unlock(&caching_ctl->mutex);
373                         if (btrfs_transaction_in_commit(fs_info))
374                                 schedule_timeout(1);
375                         else
376                                 cond_resched();
377                         goto again;
378                 }
379
380                 if (key.objectid < block_group->key.objectid) {
381                         path->slots[0]++;
382                         continue;
383                 }
384
385                 if (key.objectid >= block_group->key.objectid +
386                     block_group->key.offset)
387                         break;
388
389                 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
390                         total_found += add_new_free_space(block_group,
391                                                           fs_info, last,
392                                                           key.objectid);
393                         last = key.objectid + key.offset;
394
395                         if (total_found > (1024 * 1024 * 2)) {
396                                 total_found = 0;
397                                 wake_up(&caching_ctl->wait);
398                         }
399                 }
400                 path->slots[0]++;
401         }
402         ret = 0;
403
404         total_found += add_new_free_space(block_group, fs_info, last,
405                                           block_group->key.objectid +
406                                           block_group->key.offset);
407         caching_ctl->progress = (u64)-1;
408
409         spin_lock(&block_group->lock);
410         block_group->caching_ctl = NULL;
411         block_group->cached = BTRFS_CACHE_FINISHED;
412         spin_unlock(&block_group->lock);
413
414 err:
415         btrfs_free_path(path);
416         up_read(&fs_info->extent_commit_sem);
417
418         free_excluded_extents(extent_root, block_group);
419
420         mutex_unlock(&caching_ctl->mutex);
421         wake_up(&caching_ctl->wait);
422
423         put_caching_control(caching_ctl);
424         atomic_dec(&block_group->space_info->caching_threads);
425         btrfs_put_block_group(block_group);
426
427         return 0;
428 }
429
430 static int cache_block_group(struct btrfs_block_group_cache *cache,
431                              struct btrfs_trans_handle *trans,
432                              int load_cache_only)
433 {
434         struct btrfs_fs_info *fs_info = cache->fs_info;
435         struct btrfs_caching_control *caching_ctl;
436         struct task_struct *tsk;
437         int ret = 0;
438
439         smp_mb();
440         if (cache->cached != BTRFS_CACHE_NO)
441                 return 0;
442
443         /*
444          * We can't do the read from on-disk cache during a commit since we need
445          * to have the normal tree locking.
446          */
447         if (!trans->transaction->in_commit) {
448                 spin_lock(&cache->lock);
449                 if (cache->cached != BTRFS_CACHE_NO) {
450                         spin_unlock(&cache->lock);
451                         return 0;
452                 }
453                 cache->cached = BTRFS_CACHE_STARTED;
454                 spin_unlock(&cache->lock);
455
456                 ret = load_free_space_cache(fs_info, cache);
457
458                 spin_lock(&cache->lock);
459                 if (ret == 1) {
460                         cache->cached = BTRFS_CACHE_FINISHED;
461                         cache->last_byte_to_unpin = (u64)-1;
462                 } else {
463                         cache->cached = BTRFS_CACHE_NO;
464                 }
465                 spin_unlock(&cache->lock);
466                 if (ret == 1)
467                         return 0;
468         }
469
470         if (load_cache_only)
471                 return 0;
472
473         caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_KERNEL);
474         BUG_ON(!caching_ctl);
475
476         INIT_LIST_HEAD(&caching_ctl->list);
477         mutex_init(&caching_ctl->mutex);
478         init_waitqueue_head(&caching_ctl->wait);
479         caching_ctl->block_group = cache;
480         caching_ctl->progress = cache->key.objectid;
481         /* one for caching kthread, one for caching block group list */
482         atomic_set(&caching_ctl->count, 2);
483
484         spin_lock(&cache->lock);
485         if (cache->cached != BTRFS_CACHE_NO) {
486                 spin_unlock(&cache->lock);
487                 kfree(caching_ctl);
488                 return 0;
489         }
490         cache->caching_ctl = caching_ctl;
491         cache->cached = BTRFS_CACHE_STARTED;
492         spin_unlock(&cache->lock);
493
494         down_write(&fs_info->extent_commit_sem);
495         list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
496         up_write(&fs_info->extent_commit_sem);
497
498         atomic_inc(&cache->space_info->caching_threads);
499         btrfs_get_block_group(cache);
500
501         tsk = kthread_run(caching_kthread, cache, "btrfs-cache-%llu\n",
502                           cache->key.objectid);
503         if (IS_ERR(tsk)) {
504                 ret = PTR_ERR(tsk);
505                 printk(KERN_ERR "error running thread %d\n", ret);
506                 BUG();
507         }
508
509         return ret;
510 }
511
512 /*
513  * return the block group that starts at or after bytenr
514  */
515 static struct btrfs_block_group_cache *
516 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
517 {
518         struct btrfs_block_group_cache *cache;
519
520         cache = block_group_cache_tree_search(info, bytenr, 0);
521
522         return cache;
523 }
524
525 /*
526  * return the block group that contains the given bytenr
527  */
528 struct btrfs_block_group_cache *btrfs_lookup_block_group(
529                                                  struct btrfs_fs_info *info,
530                                                  u64 bytenr)
531 {
532         struct btrfs_block_group_cache *cache;
533
534         cache = block_group_cache_tree_search(info, bytenr, 1);
535
536         return cache;
537 }
538
539 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
540                                                   u64 flags)
541 {
542         struct list_head *head = &info->space_info;
543         struct btrfs_space_info *found;
544
545         flags &= BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_SYSTEM |
546                  BTRFS_BLOCK_GROUP_METADATA;
547
548         rcu_read_lock();
549         list_for_each_entry_rcu(found, head, list) {
550                 if (found->flags & flags) {
551                         rcu_read_unlock();
552                         return found;
553                 }
554         }
555         rcu_read_unlock();
556         return NULL;
557 }
558
559 /*
560  * after adding space to the filesystem, we need to clear the full flags
561  * on all the space infos.
562  */
563 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
564 {
565         struct list_head *head = &info->space_info;
566         struct btrfs_space_info *found;
567
568         rcu_read_lock();
569         list_for_each_entry_rcu(found, head, list)
570                 found->full = 0;
571         rcu_read_unlock();
572 }
573
574 static u64 div_factor(u64 num, int factor)
575 {
576         if (factor == 10)
577                 return num;
578         num *= factor;
579         do_div(num, 10);
580         return num;
581 }
582
583 static u64 div_factor_fine(u64 num, int factor)
584 {
585         if (factor == 100)
586                 return num;
587         num *= factor;
588         do_div(num, 100);
589         return num;
590 }
591
592 u64 btrfs_find_block_group(struct btrfs_root *root,
593                            u64 search_start, u64 search_hint, int owner)
594 {
595         struct btrfs_block_group_cache *cache;
596         u64 used;
597         u64 last = max(search_hint, search_start);
598         u64 group_start = 0;
599         int full_search = 0;
600         int factor = 9;
601         int wrapped = 0;
602 again:
603         while (1) {
604                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
605                 if (!cache)
606                         break;
607
608                 spin_lock(&cache->lock);
609                 last = cache->key.objectid + cache->key.offset;
610                 used = btrfs_block_group_used(&cache->item);
611
612                 if ((full_search || !cache->ro) &&
613                     block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
614                         if (used + cache->pinned + cache->reserved <
615                             div_factor(cache->key.offset, factor)) {
616                                 group_start = cache->key.objectid;
617                                 spin_unlock(&cache->lock);
618                                 btrfs_put_block_group(cache);
619                                 goto found;
620                         }
621                 }
622                 spin_unlock(&cache->lock);
623                 btrfs_put_block_group(cache);
624                 cond_resched();
625         }
626         if (!wrapped) {
627                 last = search_start;
628                 wrapped = 1;
629                 goto again;
630         }
631         if (!full_search && factor < 10) {
632                 last = search_start;
633                 full_search = 1;
634                 factor = 10;
635                 goto again;
636         }
637 found:
638         return group_start;
639 }
640
641 /* simple helper to search for an existing extent at a given offset */
642 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
643 {
644         int ret;
645         struct btrfs_key key;
646         struct btrfs_path *path;
647
648         path = btrfs_alloc_path();
649         BUG_ON(!path);
650         key.objectid = start;
651         key.offset = len;
652         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
653         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
654                                 0, 0);
655         btrfs_free_path(path);
656         return ret;
657 }
658
659 /*
660  * helper function to lookup reference count and flags of extent.
661  *
662  * the head node for delayed ref is used to store the sum of all the
663  * reference count modifications queued up in the rbtree. the head
664  * node may also store the extent flags to set. This way you can check
665  * to see what the reference count and extent flags would be if all of
666  * the delayed refs are not processed.
667  */
668 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
669                              struct btrfs_root *root, u64 bytenr,
670                              u64 num_bytes, u64 *refs, u64 *flags)
671 {
672         struct btrfs_delayed_ref_head *head;
673         struct btrfs_delayed_ref_root *delayed_refs;
674         struct btrfs_path *path;
675         struct btrfs_extent_item *ei;
676         struct extent_buffer *leaf;
677         struct btrfs_key key;
678         u32 item_size;
679         u64 num_refs;
680         u64 extent_flags;
681         int ret;
682
683         path = btrfs_alloc_path();
684         if (!path)
685                 return -ENOMEM;
686
687         key.objectid = bytenr;
688         key.type = BTRFS_EXTENT_ITEM_KEY;
689         key.offset = num_bytes;
690         if (!trans) {
691                 path->skip_locking = 1;
692                 path->search_commit_root = 1;
693         }
694 again:
695         ret = btrfs_search_slot(trans, root->fs_info->extent_root,
696                                 &key, path, 0, 0);
697         if (ret < 0)
698                 goto out_free;
699
700         if (ret == 0) {
701                 leaf = path->nodes[0];
702                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
703                 if (item_size >= sizeof(*ei)) {
704                         ei = btrfs_item_ptr(leaf, path->slots[0],
705                                             struct btrfs_extent_item);
706                         num_refs = btrfs_extent_refs(leaf, ei);
707                         extent_flags = btrfs_extent_flags(leaf, ei);
708                 } else {
709 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
710                         struct btrfs_extent_item_v0 *ei0;
711                         BUG_ON(item_size != sizeof(*ei0));
712                         ei0 = btrfs_item_ptr(leaf, path->slots[0],
713                                              struct btrfs_extent_item_v0);
714                         num_refs = btrfs_extent_refs_v0(leaf, ei0);
715                         /* FIXME: this isn't correct for data */
716                         extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
717 #else
718                         BUG();
719 #endif
720                 }
721                 BUG_ON(num_refs == 0);
722         } else {
723                 num_refs = 0;
724                 extent_flags = 0;
725                 ret = 0;
726         }
727
728         if (!trans)
729                 goto out;
730
731         delayed_refs = &trans->transaction->delayed_refs;
732         spin_lock(&delayed_refs->lock);
733         head = btrfs_find_delayed_ref_head(trans, bytenr);
734         if (head) {
735                 if (!mutex_trylock(&head->mutex)) {
736                         atomic_inc(&head->node.refs);
737                         spin_unlock(&delayed_refs->lock);
738
739                         btrfs_release_path(root->fs_info->extent_root, path);
740
741                         mutex_lock(&head->mutex);
742                         mutex_unlock(&head->mutex);
743                         btrfs_put_delayed_ref(&head->node);
744                         goto again;
745                 }
746                 if (head->extent_op && head->extent_op->update_flags)
747                         extent_flags |= head->extent_op->flags_to_set;
748                 else
749                         BUG_ON(num_refs == 0);
750
751                 num_refs += head->node.ref_mod;
752                 mutex_unlock(&head->mutex);
753         }
754         spin_unlock(&delayed_refs->lock);
755 out:
756         WARN_ON(num_refs == 0);
757         if (refs)
758                 *refs = num_refs;
759         if (flags)
760                 *flags = extent_flags;
761 out_free:
762         btrfs_free_path(path);
763         return ret;
764 }
765
766 /*
767  * Back reference rules.  Back refs have three main goals:
768  *
769  * 1) differentiate between all holders of references to an extent so that
770  *    when a reference is dropped we can make sure it was a valid reference
771  *    before freeing the extent.
772  *
773  * 2) Provide enough information to quickly find the holders of an extent
774  *    if we notice a given block is corrupted or bad.
775  *
776  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
777  *    maintenance.  This is actually the same as #2, but with a slightly
778  *    different use case.
779  *
780  * There are two kinds of back refs. The implicit back refs is optimized
781  * for pointers in non-shared tree blocks. For a given pointer in a block,
782  * back refs of this kind provide information about the block's owner tree
783  * and the pointer's key. These information allow us to find the block by
784  * b-tree searching. The full back refs is for pointers in tree blocks not
785  * referenced by their owner trees. The location of tree block is recorded
786  * in the back refs. Actually the full back refs is generic, and can be
787  * used in all cases the implicit back refs is used. The major shortcoming
788  * of the full back refs is its overhead. Every time a tree block gets
789  * COWed, we have to update back refs entry for all pointers in it.
790  *
791  * For a newly allocated tree block, we use implicit back refs for
792  * pointers in it. This means most tree related operations only involve
793  * implicit back refs. For a tree block created in old transaction, the
794  * only way to drop a reference to it is COW it. So we can detect the
795  * event that tree block loses its owner tree's reference and do the
796  * back refs conversion.
797  *
798  * When a tree block is COW'd through a tree, there are four cases:
799  *
800  * The reference count of the block is one and the tree is the block's
801  * owner tree. Nothing to do in this case.
802  *
803  * The reference count of the block is one and the tree is not the
804  * block's owner tree. In this case, full back refs is used for pointers
805  * in the block. Remove these full back refs, add implicit back refs for
806  * every pointers in the new block.
807  *
808  * The reference count of the block is greater than one and the tree is
809  * the block's owner tree. In this case, implicit back refs is used for
810  * pointers in the block. Add full back refs for every pointers in the
811  * block, increase lower level extents' reference counts. The original
812  * implicit back refs are entailed to the new block.
813  *
814  * The reference count of the block is greater than one and the tree is
815  * not the block's owner tree. Add implicit back refs for every pointer in
816  * the new block, increase lower level extents' reference count.
817  *
818  * Back Reference Key composing:
819  *
820  * The key objectid corresponds to the first byte in the extent,
821  * The key type is used to differentiate between types of back refs.
822  * There are different meanings of the key offset for different types
823  * of back refs.
824  *
825  * File extents can be referenced by:
826  *
827  * - multiple snapshots, subvolumes, or different generations in one subvol
828  * - different files inside a single subvolume
829  * - different offsets inside a file (bookend extents in file.c)
830  *
831  * The extent ref structure for the implicit back refs has fields for:
832  *
833  * - Objectid of the subvolume root
834  * - objectid of the file holding the reference
835  * - original offset in the file
836  * - how many bookend extents
837  *
838  * The key offset for the implicit back refs is hash of the first
839  * three fields.
840  *
841  * The extent ref structure for the full back refs has field for:
842  *
843  * - number of pointers in the tree leaf
844  *
845  * The key offset for the implicit back refs is the first byte of
846  * the tree leaf
847  *
848  * When a file extent is allocated, The implicit back refs is used.
849  * the fields are filled in:
850  *
851  *     (root_key.objectid, inode objectid, offset in file, 1)
852  *
853  * When a file extent is removed file truncation, we find the
854  * corresponding implicit back refs and check the following fields:
855  *
856  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
857  *
858  * Btree extents can be referenced by:
859  *
860  * - Different subvolumes
861  *
862  * Both the implicit back refs and the full back refs for tree blocks
863  * only consist of key. The key offset for the implicit back refs is
864  * objectid of block's owner tree. The key offset for the full back refs
865  * is the first byte of parent block.
866  *
867  * When implicit back refs is used, information about the lowest key and
868  * level of the tree block are required. These information are stored in
869  * tree block info structure.
870  */
871
872 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
873 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
874                                   struct btrfs_root *root,
875                                   struct btrfs_path *path,
876                                   u64 owner, u32 extra_size)
877 {
878         struct btrfs_extent_item *item;
879         struct btrfs_extent_item_v0 *ei0;
880         struct btrfs_extent_ref_v0 *ref0;
881         struct btrfs_tree_block_info *bi;
882         struct extent_buffer *leaf;
883         struct btrfs_key key;
884         struct btrfs_key found_key;
885         u32 new_size = sizeof(*item);
886         u64 refs;
887         int ret;
888
889         leaf = path->nodes[0];
890         BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
891
892         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
893         ei0 = btrfs_item_ptr(leaf, path->slots[0],
894                              struct btrfs_extent_item_v0);
895         refs = btrfs_extent_refs_v0(leaf, ei0);
896
897         if (owner == (u64)-1) {
898                 while (1) {
899                         if (path->slots[0] >= btrfs_header_nritems(leaf)) {
900                                 ret = btrfs_next_leaf(root, path);
901                                 if (ret < 0)
902                                         return ret;
903                                 BUG_ON(ret > 0);
904                                 leaf = path->nodes[0];
905                         }
906                         btrfs_item_key_to_cpu(leaf, &found_key,
907                                               path->slots[0]);
908                         BUG_ON(key.objectid != found_key.objectid);
909                         if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
910                                 path->slots[0]++;
911                                 continue;
912                         }
913                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
914                                               struct btrfs_extent_ref_v0);
915                         owner = btrfs_ref_objectid_v0(leaf, ref0);
916                         break;
917                 }
918         }
919         btrfs_release_path(root, path);
920
921         if (owner < BTRFS_FIRST_FREE_OBJECTID)
922                 new_size += sizeof(*bi);
923
924         new_size -= sizeof(*ei0);
925         ret = btrfs_search_slot(trans, root, &key, path,
926                                 new_size + extra_size, 1);
927         if (ret < 0)
928                 return ret;
929         BUG_ON(ret);
930
931         ret = btrfs_extend_item(trans, root, path, new_size);
932         BUG_ON(ret);
933
934         leaf = path->nodes[0];
935         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
936         btrfs_set_extent_refs(leaf, item, refs);
937         /* FIXME: get real generation */
938         btrfs_set_extent_generation(leaf, item, 0);
939         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
940                 btrfs_set_extent_flags(leaf, item,
941                                        BTRFS_EXTENT_FLAG_TREE_BLOCK |
942                                        BTRFS_BLOCK_FLAG_FULL_BACKREF);
943                 bi = (struct btrfs_tree_block_info *)(item + 1);
944                 /* FIXME: get first key of the block */
945                 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
946                 btrfs_set_tree_block_level(leaf, bi, (int)owner);
947         } else {
948                 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
949         }
950         btrfs_mark_buffer_dirty(leaf);
951         return 0;
952 }
953 #endif
954
955 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
956 {
957         u32 high_crc = ~(u32)0;
958         u32 low_crc = ~(u32)0;
959         __le64 lenum;
960
961         lenum = cpu_to_le64(root_objectid);
962         high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
963         lenum = cpu_to_le64(owner);
964         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
965         lenum = cpu_to_le64(offset);
966         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
967
968         return ((u64)high_crc << 31) ^ (u64)low_crc;
969 }
970
971 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
972                                      struct btrfs_extent_data_ref *ref)
973 {
974         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
975                                     btrfs_extent_data_ref_objectid(leaf, ref),
976                                     btrfs_extent_data_ref_offset(leaf, ref));
977 }
978
979 static int match_extent_data_ref(struct extent_buffer *leaf,
980                                  struct btrfs_extent_data_ref *ref,
981                                  u64 root_objectid, u64 owner, u64 offset)
982 {
983         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
984             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
985             btrfs_extent_data_ref_offset(leaf, ref) != offset)
986                 return 0;
987         return 1;
988 }
989
990 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
991                                            struct btrfs_root *root,
992                                            struct btrfs_path *path,
993                                            u64 bytenr, u64 parent,
994                                            u64 root_objectid,
995                                            u64 owner, u64 offset)
996 {
997         struct btrfs_key key;
998         struct btrfs_extent_data_ref *ref;
999         struct extent_buffer *leaf;
1000         u32 nritems;
1001         int ret;
1002         int recow;
1003         int err = -ENOENT;
1004
1005         key.objectid = bytenr;
1006         if (parent) {
1007                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1008                 key.offset = parent;
1009         } else {
1010                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1011                 key.offset = hash_extent_data_ref(root_objectid,
1012                                                   owner, offset);
1013         }
1014 again:
1015         recow = 0;
1016         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1017         if (ret < 0) {
1018                 err = ret;
1019                 goto fail;
1020         }
1021
1022         if (parent) {
1023                 if (!ret)
1024                         return 0;
1025 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1026                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1027                 btrfs_release_path(root, path);
1028                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1029                 if (ret < 0) {
1030                         err = ret;
1031                         goto fail;
1032                 }
1033                 if (!ret)
1034                         return 0;
1035 #endif
1036                 goto fail;
1037         }
1038
1039         leaf = path->nodes[0];
1040         nritems = btrfs_header_nritems(leaf);
1041         while (1) {
1042                 if (path->slots[0] >= nritems) {
1043                         ret = btrfs_next_leaf(root, path);
1044                         if (ret < 0)
1045                                 err = ret;
1046                         if (ret)
1047                                 goto fail;
1048
1049                         leaf = path->nodes[0];
1050                         nritems = btrfs_header_nritems(leaf);
1051                         recow = 1;
1052                 }
1053
1054                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1055                 if (key.objectid != bytenr ||
1056                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1057                         goto fail;
1058
1059                 ref = btrfs_item_ptr(leaf, path->slots[0],
1060                                      struct btrfs_extent_data_ref);
1061
1062                 if (match_extent_data_ref(leaf, ref, root_objectid,
1063                                           owner, offset)) {
1064                         if (recow) {
1065                                 btrfs_release_path(root, path);
1066                                 goto again;
1067                         }
1068                         err = 0;
1069                         break;
1070                 }
1071                 path->slots[0]++;
1072         }
1073 fail:
1074         return err;
1075 }
1076
1077 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1078                                            struct btrfs_root *root,
1079                                            struct btrfs_path *path,
1080                                            u64 bytenr, u64 parent,
1081                                            u64 root_objectid, u64 owner,
1082                                            u64 offset, int refs_to_add)
1083 {
1084         struct btrfs_key key;
1085         struct extent_buffer *leaf;
1086         u32 size;
1087         u32 num_refs;
1088         int ret;
1089
1090         key.objectid = bytenr;
1091         if (parent) {
1092                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1093                 key.offset = parent;
1094                 size = sizeof(struct btrfs_shared_data_ref);
1095         } else {
1096                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1097                 key.offset = hash_extent_data_ref(root_objectid,
1098                                                   owner, offset);
1099                 size = sizeof(struct btrfs_extent_data_ref);
1100         }
1101
1102         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1103         if (ret && ret != -EEXIST)
1104                 goto fail;
1105
1106         leaf = path->nodes[0];
1107         if (parent) {
1108                 struct btrfs_shared_data_ref *ref;
1109                 ref = btrfs_item_ptr(leaf, path->slots[0],
1110                                      struct btrfs_shared_data_ref);
1111                 if (ret == 0) {
1112                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1113                 } else {
1114                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1115                         num_refs += refs_to_add;
1116                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1117                 }
1118         } else {
1119                 struct btrfs_extent_data_ref *ref;
1120                 while (ret == -EEXIST) {
1121                         ref = btrfs_item_ptr(leaf, path->slots[0],
1122                                              struct btrfs_extent_data_ref);
1123                         if (match_extent_data_ref(leaf, ref, root_objectid,
1124                                                   owner, offset))
1125                                 break;
1126                         btrfs_release_path(root, path);
1127                         key.offset++;
1128                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1129                                                       size);
1130                         if (ret && ret != -EEXIST)
1131                                 goto fail;
1132
1133                         leaf = path->nodes[0];
1134                 }
1135                 ref = btrfs_item_ptr(leaf, path->slots[0],
1136                                      struct btrfs_extent_data_ref);
1137                 if (ret == 0) {
1138                         btrfs_set_extent_data_ref_root(leaf, ref,
1139                                                        root_objectid);
1140                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1141                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1142                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1143                 } else {
1144                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1145                         num_refs += refs_to_add;
1146                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1147                 }
1148         }
1149         btrfs_mark_buffer_dirty(leaf);
1150         ret = 0;
1151 fail:
1152         btrfs_release_path(root, path);
1153         return ret;
1154 }
1155
1156 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1157                                            struct btrfs_root *root,
1158                                            struct btrfs_path *path,
1159                                            int refs_to_drop)
1160 {
1161         struct btrfs_key key;
1162         struct btrfs_extent_data_ref *ref1 = NULL;
1163         struct btrfs_shared_data_ref *ref2 = NULL;
1164         struct extent_buffer *leaf;
1165         u32 num_refs = 0;
1166         int ret = 0;
1167
1168         leaf = path->nodes[0];
1169         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1170
1171         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1172                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1173                                       struct btrfs_extent_data_ref);
1174                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1175         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1176                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1177                                       struct btrfs_shared_data_ref);
1178                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1179 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1180         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1181                 struct btrfs_extent_ref_v0 *ref0;
1182                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1183                                       struct btrfs_extent_ref_v0);
1184                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1185 #endif
1186         } else {
1187                 BUG();
1188         }
1189
1190         BUG_ON(num_refs < refs_to_drop);
1191         num_refs -= refs_to_drop;
1192
1193         if (num_refs == 0) {
1194                 ret = btrfs_del_item(trans, root, path);
1195         } else {
1196                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1197                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1198                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1199                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1200 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1201                 else {
1202                         struct btrfs_extent_ref_v0 *ref0;
1203                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1204                                         struct btrfs_extent_ref_v0);
1205                         btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1206                 }
1207 #endif
1208                 btrfs_mark_buffer_dirty(leaf);
1209         }
1210         return ret;
1211 }
1212
1213 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1214                                           struct btrfs_path *path,
1215                                           struct btrfs_extent_inline_ref *iref)
1216 {
1217         struct btrfs_key key;
1218         struct extent_buffer *leaf;
1219         struct btrfs_extent_data_ref *ref1;
1220         struct btrfs_shared_data_ref *ref2;
1221         u32 num_refs = 0;
1222
1223         leaf = path->nodes[0];
1224         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1225         if (iref) {
1226                 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1227                     BTRFS_EXTENT_DATA_REF_KEY) {
1228                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1229                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1230                 } else {
1231                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1232                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1233                 }
1234         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1235                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1236                                       struct btrfs_extent_data_ref);
1237                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1238         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1239                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1240                                       struct btrfs_shared_data_ref);
1241                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1242 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1243         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1244                 struct btrfs_extent_ref_v0 *ref0;
1245                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1246                                       struct btrfs_extent_ref_v0);
1247                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1248 #endif
1249         } else {
1250                 WARN_ON(1);
1251         }
1252         return num_refs;
1253 }
1254
1255 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1256                                           struct btrfs_root *root,
1257                                           struct btrfs_path *path,
1258                                           u64 bytenr, u64 parent,
1259                                           u64 root_objectid)
1260 {
1261         struct btrfs_key key;
1262         int ret;
1263
1264         key.objectid = bytenr;
1265         if (parent) {
1266                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1267                 key.offset = parent;
1268         } else {
1269                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1270                 key.offset = root_objectid;
1271         }
1272
1273         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1274         if (ret > 0)
1275                 ret = -ENOENT;
1276 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1277         if (ret == -ENOENT && parent) {
1278                 btrfs_release_path(root, path);
1279                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1280                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1281                 if (ret > 0)
1282                         ret = -ENOENT;
1283         }
1284 #endif
1285         return ret;
1286 }
1287
1288 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1289                                           struct btrfs_root *root,
1290                                           struct btrfs_path *path,
1291                                           u64 bytenr, u64 parent,
1292                                           u64 root_objectid)
1293 {
1294         struct btrfs_key key;
1295         int ret;
1296
1297         key.objectid = bytenr;
1298         if (parent) {
1299                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1300                 key.offset = parent;
1301         } else {
1302                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1303                 key.offset = root_objectid;
1304         }
1305
1306         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1307         btrfs_release_path(root, path);
1308         return ret;
1309 }
1310
1311 static inline int extent_ref_type(u64 parent, u64 owner)
1312 {
1313         int type;
1314         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1315                 if (parent > 0)
1316                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1317                 else
1318                         type = BTRFS_TREE_BLOCK_REF_KEY;
1319         } else {
1320                 if (parent > 0)
1321                         type = BTRFS_SHARED_DATA_REF_KEY;
1322                 else
1323                         type = BTRFS_EXTENT_DATA_REF_KEY;
1324         }
1325         return type;
1326 }
1327
1328 static int find_next_key(struct btrfs_path *path, int level,
1329                          struct btrfs_key *key)
1330
1331 {
1332         for (; level < BTRFS_MAX_LEVEL; level++) {
1333                 if (!path->nodes[level])
1334                         break;
1335                 if (path->slots[level] + 1 >=
1336                     btrfs_header_nritems(path->nodes[level]))
1337                         continue;
1338                 if (level == 0)
1339                         btrfs_item_key_to_cpu(path->nodes[level], key,
1340                                               path->slots[level] + 1);
1341                 else
1342                         btrfs_node_key_to_cpu(path->nodes[level], key,
1343                                               path->slots[level] + 1);
1344                 return 0;
1345         }
1346         return 1;
1347 }
1348
1349 /*
1350  * look for inline back ref. if back ref is found, *ref_ret is set
1351  * to the address of inline back ref, and 0 is returned.
1352  *
1353  * if back ref isn't found, *ref_ret is set to the address where it
1354  * should be inserted, and -ENOENT is returned.
1355  *
1356  * if insert is true and there are too many inline back refs, the path
1357  * points to the extent item, and -EAGAIN is returned.
1358  *
1359  * NOTE: inline back refs are ordered in the same way that back ref
1360  *       items in the tree are ordered.
1361  */
1362 static noinline_for_stack
1363 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1364                                  struct btrfs_root *root,
1365                                  struct btrfs_path *path,
1366                                  struct btrfs_extent_inline_ref **ref_ret,
1367                                  u64 bytenr, u64 num_bytes,
1368                                  u64 parent, u64 root_objectid,
1369                                  u64 owner, u64 offset, int insert)
1370 {
1371         struct btrfs_key key;
1372         struct extent_buffer *leaf;
1373         struct btrfs_extent_item *ei;
1374         struct btrfs_extent_inline_ref *iref;
1375         u64 flags;
1376         u64 item_size;
1377         unsigned long ptr;
1378         unsigned long end;
1379         int extra_size;
1380         int type;
1381         int want;
1382         int ret;
1383         int err = 0;
1384
1385         key.objectid = bytenr;
1386         key.type = BTRFS_EXTENT_ITEM_KEY;
1387         key.offset = num_bytes;
1388
1389         want = extent_ref_type(parent, owner);
1390         if (insert) {
1391                 extra_size = btrfs_extent_inline_ref_size(want);
1392                 path->keep_locks = 1;
1393         } else
1394                 extra_size = -1;
1395         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1396         if (ret < 0) {
1397                 err = ret;
1398                 goto out;
1399         }
1400         BUG_ON(ret);
1401
1402         leaf = path->nodes[0];
1403         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1404 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1405         if (item_size < sizeof(*ei)) {
1406                 if (!insert) {
1407                         err = -ENOENT;
1408                         goto out;
1409                 }
1410                 ret = convert_extent_item_v0(trans, root, path, owner,
1411                                              extra_size);
1412                 if (ret < 0) {
1413                         err = ret;
1414                         goto out;
1415                 }
1416                 leaf = path->nodes[0];
1417                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1418         }
1419 #endif
1420         BUG_ON(item_size < sizeof(*ei));
1421
1422         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1423         flags = btrfs_extent_flags(leaf, ei);
1424
1425         ptr = (unsigned long)(ei + 1);
1426         end = (unsigned long)ei + item_size;
1427
1428         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1429                 ptr += sizeof(struct btrfs_tree_block_info);
1430                 BUG_ON(ptr > end);
1431         } else {
1432                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1433         }
1434
1435         err = -ENOENT;
1436         while (1) {
1437                 if (ptr >= end) {
1438                         WARN_ON(ptr > end);
1439                         break;
1440                 }
1441                 iref = (struct btrfs_extent_inline_ref *)ptr;
1442                 type = btrfs_extent_inline_ref_type(leaf, iref);
1443                 if (want < type)
1444                         break;
1445                 if (want > type) {
1446                         ptr += btrfs_extent_inline_ref_size(type);
1447                         continue;
1448                 }
1449
1450                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1451                         struct btrfs_extent_data_ref *dref;
1452                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1453                         if (match_extent_data_ref(leaf, dref, root_objectid,
1454                                                   owner, offset)) {
1455                                 err = 0;
1456                                 break;
1457                         }
1458                         if (hash_extent_data_ref_item(leaf, dref) <
1459                             hash_extent_data_ref(root_objectid, owner, offset))
1460                                 break;
1461                 } else {
1462                         u64 ref_offset;
1463                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1464                         if (parent > 0) {
1465                                 if (parent == ref_offset) {
1466                                         err = 0;
1467                                         break;
1468                                 }
1469                                 if (ref_offset < parent)
1470                                         break;
1471                         } else {
1472                                 if (root_objectid == ref_offset) {
1473                                         err = 0;
1474                                         break;
1475                                 }
1476                                 if (ref_offset < root_objectid)
1477                                         break;
1478                         }
1479                 }
1480                 ptr += btrfs_extent_inline_ref_size(type);
1481         }
1482         if (err == -ENOENT && insert) {
1483                 if (item_size + extra_size >=
1484                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1485                         err = -EAGAIN;
1486                         goto out;
1487                 }
1488                 /*
1489                  * To add new inline back ref, we have to make sure
1490                  * there is no corresponding back ref item.
1491                  * For simplicity, we just do not add new inline back
1492                  * ref if there is any kind of item for this block
1493                  */
1494                 if (find_next_key(path, 0, &key) == 0 &&
1495                     key.objectid == bytenr &&
1496                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1497                         err = -EAGAIN;
1498                         goto out;
1499                 }
1500         }
1501         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1502 out:
1503         if (insert) {
1504                 path->keep_locks = 0;
1505                 btrfs_unlock_up_safe(path, 1);
1506         }
1507         return err;
1508 }
1509
1510 /*
1511  * helper to add new inline back ref
1512  */
1513 static noinline_for_stack
1514 int setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1515                                 struct btrfs_root *root,
1516                                 struct btrfs_path *path,
1517                                 struct btrfs_extent_inline_ref *iref,
1518                                 u64 parent, u64 root_objectid,
1519                                 u64 owner, u64 offset, int refs_to_add,
1520                                 struct btrfs_delayed_extent_op *extent_op)
1521 {
1522         struct extent_buffer *leaf;
1523         struct btrfs_extent_item *ei;
1524         unsigned long ptr;
1525         unsigned long end;
1526         unsigned long item_offset;
1527         u64 refs;
1528         int size;
1529         int type;
1530         int ret;
1531
1532         leaf = path->nodes[0];
1533         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1534         item_offset = (unsigned long)iref - (unsigned long)ei;
1535
1536         type = extent_ref_type(parent, owner);
1537         size = btrfs_extent_inline_ref_size(type);
1538
1539         ret = btrfs_extend_item(trans, root, path, size);
1540         BUG_ON(ret);
1541
1542         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1543         refs = btrfs_extent_refs(leaf, ei);
1544         refs += refs_to_add;
1545         btrfs_set_extent_refs(leaf, ei, refs);
1546         if (extent_op)
1547                 __run_delayed_extent_op(extent_op, leaf, ei);
1548
1549         ptr = (unsigned long)ei + item_offset;
1550         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1551         if (ptr < end - size)
1552                 memmove_extent_buffer(leaf, ptr + size, ptr,
1553                                       end - size - ptr);
1554
1555         iref = (struct btrfs_extent_inline_ref *)ptr;
1556         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1557         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1558                 struct btrfs_extent_data_ref *dref;
1559                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1560                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1561                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1562                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1563                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1564         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1565                 struct btrfs_shared_data_ref *sref;
1566                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1567                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1568                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1569         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1570                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1571         } else {
1572                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1573         }
1574         btrfs_mark_buffer_dirty(leaf);
1575         return 0;
1576 }
1577
1578 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1579                                  struct btrfs_root *root,
1580                                  struct btrfs_path *path,
1581                                  struct btrfs_extent_inline_ref **ref_ret,
1582                                  u64 bytenr, u64 num_bytes, u64 parent,
1583                                  u64 root_objectid, u64 owner, u64 offset)
1584 {
1585         int ret;
1586
1587         ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1588                                            bytenr, num_bytes, parent,
1589                                            root_objectid, owner, offset, 0);
1590         if (ret != -ENOENT)
1591                 return ret;
1592
1593         btrfs_release_path(root, path);
1594         *ref_ret = NULL;
1595
1596         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1597                 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1598                                             root_objectid);
1599         } else {
1600                 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1601                                              root_objectid, owner, offset);
1602         }
1603         return ret;
1604 }
1605
1606 /*
1607  * helper to update/remove inline back ref
1608  */
1609 static noinline_for_stack
1610 int update_inline_extent_backref(struct btrfs_trans_handle *trans,
1611                                  struct btrfs_root *root,
1612                                  struct btrfs_path *path,
1613                                  struct btrfs_extent_inline_ref *iref,
1614                                  int refs_to_mod,
1615                                  struct btrfs_delayed_extent_op *extent_op)
1616 {
1617         struct extent_buffer *leaf;
1618         struct btrfs_extent_item *ei;
1619         struct btrfs_extent_data_ref *dref = NULL;
1620         struct btrfs_shared_data_ref *sref = NULL;
1621         unsigned long ptr;
1622         unsigned long end;
1623         u32 item_size;
1624         int size;
1625         int type;
1626         int ret;
1627         u64 refs;
1628
1629         leaf = path->nodes[0];
1630         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1631         refs = btrfs_extent_refs(leaf, ei);
1632         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1633         refs += refs_to_mod;
1634         btrfs_set_extent_refs(leaf, ei, refs);
1635         if (extent_op)
1636                 __run_delayed_extent_op(extent_op, leaf, ei);
1637
1638         type = btrfs_extent_inline_ref_type(leaf, iref);
1639
1640         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1641                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1642                 refs = btrfs_extent_data_ref_count(leaf, dref);
1643         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1644                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1645                 refs = btrfs_shared_data_ref_count(leaf, sref);
1646         } else {
1647                 refs = 1;
1648                 BUG_ON(refs_to_mod != -1);
1649         }
1650
1651         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1652         refs += refs_to_mod;
1653
1654         if (refs > 0) {
1655                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1656                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1657                 else
1658                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1659         } else {
1660                 size =  btrfs_extent_inline_ref_size(type);
1661                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1662                 ptr = (unsigned long)iref;
1663                 end = (unsigned long)ei + item_size;
1664                 if (ptr + size < end)
1665                         memmove_extent_buffer(leaf, ptr, ptr + size,
1666                                               end - ptr - size);
1667                 item_size -= size;
1668                 ret = btrfs_truncate_item(trans, root, path, item_size, 1);
1669                 BUG_ON(ret);
1670         }
1671         btrfs_mark_buffer_dirty(leaf);
1672         return 0;
1673 }
1674
1675 static noinline_for_stack
1676 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1677                                  struct btrfs_root *root,
1678                                  struct btrfs_path *path,
1679                                  u64 bytenr, u64 num_bytes, u64 parent,
1680                                  u64 root_objectid, u64 owner,
1681                                  u64 offset, int refs_to_add,
1682                                  struct btrfs_delayed_extent_op *extent_op)
1683 {
1684         struct btrfs_extent_inline_ref *iref;
1685         int ret;
1686
1687         ret = lookup_inline_extent_backref(trans, root, path, &iref,
1688                                            bytenr, num_bytes, parent,
1689                                            root_objectid, owner, offset, 1);
1690         if (ret == 0) {
1691                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1692                 ret = update_inline_extent_backref(trans, root, path, iref,
1693                                                    refs_to_add, extent_op);
1694         } else if (ret == -ENOENT) {
1695                 ret = setup_inline_extent_backref(trans, root, path, iref,
1696                                                   parent, root_objectid,
1697                                                   owner, offset, refs_to_add,
1698                                                   extent_op);
1699         }
1700         return ret;
1701 }
1702
1703 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1704                                  struct btrfs_root *root,
1705                                  struct btrfs_path *path,
1706                                  u64 bytenr, u64 parent, u64 root_objectid,
1707                                  u64 owner, u64 offset, int refs_to_add)
1708 {
1709         int ret;
1710         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1711                 BUG_ON(refs_to_add != 1);
1712                 ret = insert_tree_block_ref(trans, root, path, bytenr,
1713                                             parent, root_objectid);
1714         } else {
1715                 ret = insert_extent_data_ref(trans, root, path, bytenr,
1716                                              parent, root_objectid,
1717                                              owner, offset, refs_to_add);
1718         }
1719         return ret;
1720 }
1721
1722 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1723                                  struct btrfs_root *root,
1724                                  struct btrfs_path *path,
1725                                  struct btrfs_extent_inline_ref *iref,
1726                                  int refs_to_drop, int is_data)
1727 {
1728         int ret;
1729
1730         BUG_ON(!is_data && refs_to_drop != 1);
1731         if (iref) {
1732                 ret = update_inline_extent_backref(trans, root, path, iref,
1733                                                    -refs_to_drop, NULL);
1734         } else if (is_data) {
1735                 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1736         } else {
1737                 ret = btrfs_del_item(trans, root, path);
1738         }
1739         return ret;
1740 }
1741
1742 static void btrfs_issue_discard(struct block_device *bdev,
1743                                 u64 start, u64 len)
1744 {
1745         blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_KERNEL, 0);
1746 }
1747
1748 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1749                                 u64 num_bytes)
1750 {
1751         int ret;
1752         u64 map_length = num_bytes;
1753         struct btrfs_multi_bio *multi = NULL;
1754
1755         if (!btrfs_test_opt(root, DISCARD))
1756                 return 0;
1757
1758         /* Tell the block device(s) that the sectors can be discarded */
1759         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
1760                               bytenr, &map_length, &multi, 0);
1761         if (!ret) {
1762                 struct btrfs_bio_stripe *stripe = multi->stripes;
1763                 int i;
1764
1765                 if (map_length > num_bytes)
1766                         map_length = num_bytes;
1767
1768                 for (i = 0; i < multi->num_stripes; i++, stripe++) {
1769                         btrfs_issue_discard(stripe->dev->bdev,
1770                                             stripe->physical,
1771                                             map_length);
1772                 }
1773                 kfree(multi);
1774         }
1775
1776         return ret;
1777 }
1778
1779 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1780                          struct btrfs_root *root,
1781                          u64 bytenr, u64 num_bytes, u64 parent,
1782                          u64 root_objectid, u64 owner, u64 offset)
1783 {
1784         int ret;
1785         BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1786                root_objectid == BTRFS_TREE_LOG_OBJECTID);
1787
1788         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1789                 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
1790                                         parent, root_objectid, (int)owner,
1791                                         BTRFS_ADD_DELAYED_REF, NULL);
1792         } else {
1793                 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
1794                                         parent, root_objectid, owner, offset,
1795                                         BTRFS_ADD_DELAYED_REF, NULL);
1796         }
1797         return ret;
1798 }
1799
1800 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1801                                   struct btrfs_root *root,
1802                                   u64 bytenr, u64 num_bytes,
1803                                   u64 parent, u64 root_objectid,
1804                                   u64 owner, u64 offset, int refs_to_add,
1805                                   struct btrfs_delayed_extent_op *extent_op)
1806 {
1807         struct btrfs_path *path;
1808         struct extent_buffer *leaf;
1809         struct btrfs_extent_item *item;
1810         u64 refs;
1811         int ret;
1812         int err = 0;
1813
1814         path = btrfs_alloc_path();
1815         if (!path)
1816                 return -ENOMEM;
1817
1818         path->reada = 1;
1819         path->leave_spinning = 1;
1820         /* this will setup the path even if it fails to insert the back ref */
1821         ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1822                                            path, bytenr, num_bytes, parent,
1823                                            root_objectid, owner, offset,
1824                                            refs_to_add, extent_op);
1825         if (ret == 0)
1826                 goto out;
1827
1828         if (ret != -EAGAIN) {
1829                 err = ret;
1830                 goto out;
1831         }
1832
1833         leaf = path->nodes[0];
1834         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1835         refs = btrfs_extent_refs(leaf, item);
1836         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1837         if (extent_op)
1838                 __run_delayed_extent_op(extent_op, leaf, item);
1839
1840         btrfs_mark_buffer_dirty(leaf);
1841         btrfs_release_path(root->fs_info->extent_root, path);
1842
1843         path->reada = 1;
1844         path->leave_spinning = 1;
1845
1846         /* now insert the actual backref */
1847         ret = insert_extent_backref(trans, root->fs_info->extent_root,
1848                                     path, bytenr, parent, root_objectid,
1849                                     owner, offset, refs_to_add);
1850         BUG_ON(ret);
1851 out:
1852         btrfs_free_path(path);
1853         return err;
1854 }
1855
1856 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1857                                 struct btrfs_root *root,
1858                                 struct btrfs_delayed_ref_node *node,
1859                                 struct btrfs_delayed_extent_op *extent_op,
1860                                 int insert_reserved)
1861 {
1862         int ret = 0;
1863         struct btrfs_delayed_data_ref *ref;
1864         struct btrfs_key ins;
1865         u64 parent = 0;
1866         u64 ref_root = 0;
1867         u64 flags = 0;
1868
1869         ins.objectid = node->bytenr;
1870         ins.offset = node->num_bytes;
1871         ins.type = BTRFS_EXTENT_ITEM_KEY;
1872
1873         ref = btrfs_delayed_node_to_data_ref(node);
1874         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1875                 parent = ref->parent;
1876         else
1877                 ref_root = ref->root;
1878
1879         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1880                 if (extent_op) {
1881                         BUG_ON(extent_op->update_key);
1882                         flags |= extent_op->flags_to_set;
1883                 }
1884                 ret = alloc_reserved_file_extent(trans, root,
1885                                                  parent, ref_root, flags,
1886                                                  ref->objectid, ref->offset,
1887                                                  &ins, node->ref_mod);
1888         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1889                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1890                                              node->num_bytes, parent,
1891                                              ref_root, ref->objectid,
1892                                              ref->offset, node->ref_mod,
1893                                              extent_op);
1894         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1895                 ret = __btrfs_free_extent(trans, root, node->bytenr,
1896                                           node->num_bytes, parent,
1897                                           ref_root, ref->objectid,
1898                                           ref->offset, node->ref_mod,
1899                                           extent_op);
1900         } else {
1901                 BUG();
1902         }
1903         return ret;
1904 }
1905
1906 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1907                                     struct extent_buffer *leaf,
1908                                     struct btrfs_extent_item *ei)
1909 {
1910         u64 flags = btrfs_extent_flags(leaf, ei);
1911         if (extent_op->update_flags) {
1912                 flags |= extent_op->flags_to_set;
1913                 btrfs_set_extent_flags(leaf, ei, flags);
1914         }
1915
1916         if (extent_op->update_key) {
1917                 struct btrfs_tree_block_info *bi;
1918                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1919                 bi = (struct btrfs_tree_block_info *)(ei + 1);
1920                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1921         }
1922 }
1923
1924 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1925                                  struct btrfs_root *root,
1926                                  struct btrfs_delayed_ref_node *node,
1927                                  struct btrfs_delayed_extent_op *extent_op)
1928 {
1929         struct btrfs_key key;
1930         struct btrfs_path *path;
1931         struct btrfs_extent_item *ei;
1932         struct extent_buffer *leaf;
1933         u32 item_size;
1934         int ret;
1935         int err = 0;
1936
1937         path = btrfs_alloc_path();
1938         if (!path)
1939                 return -ENOMEM;
1940
1941         key.objectid = node->bytenr;
1942         key.type = BTRFS_EXTENT_ITEM_KEY;
1943         key.offset = node->num_bytes;
1944
1945         path->reada = 1;
1946         path->leave_spinning = 1;
1947         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
1948                                 path, 0, 1);
1949         if (ret < 0) {
1950                 err = ret;
1951                 goto out;
1952         }
1953         if (ret > 0) {
1954                 err = -EIO;
1955                 goto out;
1956         }
1957
1958         leaf = path->nodes[0];
1959         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1960 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1961         if (item_size < sizeof(*ei)) {
1962                 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
1963                                              path, (u64)-1, 0);
1964                 if (ret < 0) {
1965                         err = ret;
1966                         goto out;
1967                 }
1968                 leaf = path->nodes[0];
1969                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1970         }
1971 #endif
1972         BUG_ON(item_size < sizeof(*ei));
1973         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1974         __run_delayed_extent_op(extent_op, leaf, ei);
1975
1976         btrfs_mark_buffer_dirty(leaf);
1977 out:
1978         btrfs_free_path(path);
1979         return err;
1980 }
1981
1982 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1983                                 struct btrfs_root *root,
1984                                 struct btrfs_delayed_ref_node *node,
1985                                 struct btrfs_delayed_extent_op *extent_op,
1986                                 int insert_reserved)
1987 {
1988         int ret = 0;
1989         struct btrfs_delayed_tree_ref *ref;
1990         struct btrfs_key ins;
1991         u64 parent = 0;
1992         u64 ref_root = 0;
1993
1994         ins.objectid = node->bytenr;
1995         ins.offset = node->num_bytes;
1996         ins.type = BTRFS_EXTENT_ITEM_KEY;
1997
1998         ref = btrfs_delayed_node_to_tree_ref(node);
1999         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2000                 parent = ref->parent;
2001         else
2002                 ref_root = ref->root;
2003
2004         BUG_ON(node->ref_mod != 1);
2005         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2006                 BUG_ON(!extent_op || !extent_op->update_flags ||
2007                        !extent_op->update_key);
2008                 ret = alloc_reserved_tree_block(trans, root,
2009                                                 parent, ref_root,
2010                                                 extent_op->flags_to_set,
2011                                                 &extent_op->key,
2012                                                 ref->level, &ins);
2013         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2014                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2015                                              node->num_bytes, parent, ref_root,
2016                                              ref->level, 0, 1, extent_op);
2017         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2018                 ret = __btrfs_free_extent(trans, root, node->bytenr,
2019                                           node->num_bytes, parent, ref_root,
2020                                           ref->level, 0, 1, extent_op);
2021         } else {
2022                 BUG();
2023         }
2024         return ret;
2025 }
2026
2027 /* helper function to actually process a single delayed ref entry */
2028 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2029                                struct btrfs_root *root,
2030                                struct btrfs_delayed_ref_node *node,
2031                                struct btrfs_delayed_extent_op *extent_op,
2032                                int insert_reserved)
2033 {
2034         int ret;
2035         if (btrfs_delayed_ref_is_head(node)) {
2036                 struct btrfs_delayed_ref_head *head;
2037                 /*
2038                  * we've hit the end of the chain and we were supposed
2039                  * to insert this extent into the tree.  But, it got
2040                  * deleted before we ever needed to insert it, so all
2041                  * we have to do is clean up the accounting
2042                  */
2043                 BUG_ON(extent_op);
2044                 head = btrfs_delayed_node_to_head(node);
2045                 if (insert_reserved) {
2046                         btrfs_pin_extent(root, node->bytenr,
2047                                          node->num_bytes, 1);
2048                         if (head->is_data) {
2049                                 ret = btrfs_del_csums(trans, root,
2050                                                       node->bytenr,
2051                                                       node->num_bytes);
2052                                 BUG_ON(ret);
2053                         }
2054                 }
2055                 mutex_unlock(&head->mutex);
2056                 return 0;
2057         }
2058
2059         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2060             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2061                 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2062                                            insert_reserved);
2063         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2064                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2065                 ret = run_delayed_data_ref(trans, root, node, extent_op,
2066                                            insert_reserved);
2067         else
2068                 BUG();
2069         return ret;
2070 }
2071
2072 static noinline struct btrfs_delayed_ref_node *
2073 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2074 {
2075         struct rb_node *node;
2076         struct btrfs_delayed_ref_node *ref;
2077         int action = BTRFS_ADD_DELAYED_REF;
2078 again:
2079         /*
2080          * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2081          * this prevents ref count from going down to zero when
2082          * there still are pending delayed ref.
2083          */
2084         node = rb_prev(&head->node.rb_node);
2085         while (1) {
2086                 if (!node)
2087                         break;
2088                 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2089                                 rb_node);
2090                 if (ref->bytenr != head->node.bytenr)
2091                         break;
2092                 if (ref->action == action)
2093                         return ref;
2094                 node = rb_prev(node);
2095         }
2096         if (action == BTRFS_ADD_DELAYED_REF) {
2097                 action = BTRFS_DROP_DELAYED_REF;
2098                 goto again;
2099         }
2100         return NULL;
2101 }
2102
2103 static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
2104                                        struct btrfs_root *root,
2105                                        struct list_head *cluster)
2106 {
2107         struct btrfs_delayed_ref_root *delayed_refs;
2108         struct btrfs_delayed_ref_node *ref;
2109         struct btrfs_delayed_ref_head *locked_ref = NULL;
2110         struct btrfs_delayed_extent_op *extent_op;
2111         int ret;
2112         int count = 0;
2113         int must_insert_reserved = 0;
2114
2115         delayed_refs = &trans->transaction->delayed_refs;
2116         while (1) {
2117                 if (!locked_ref) {
2118                         /* pick a new head ref from the cluster list */
2119                         if (list_empty(cluster))
2120                                 break;
2121
2122                         locked_ref = list_entry(cluster->next,
2123                                      struct btrfs_delayed_ref_head, cluster);
2124
2125                         /* grab the lock that says we are going to process
2126                          * all the refs for this head */
2127                         ret = btrfs_delayed_ref_lock(trans, locked_ref);
2128
2129                         /*
2130                          * we may have dropped the spin lock to get the head
2131                          * mutex lock, and that might have given someone else
2132                          * time to free the head.  If that's true, it has been
2133                          * removed from our list and we can move on.
2134                          */
2135                         if (ret == -EAGAIN) {
2136                                 locked_ref = NULL;
2137                                 count++;
2138                                 continue;
2139                         }
2140                 }
2141
2142                 /*
2143                  * record the must insert reserved flag before we
2144                  * drop the spin lock.
2145                  */
2146                 must_insert_reserved = locked_ref->must_insert_reserved;
2147                 locked_ref->must_insert_reserved = 0;
2148
2149                 extent_op = locked_ref->extent_op;
2150                 locked_ref->extent_op = NULL;
2151
2152                 /*
2153                  * locked_ref is the head node, so we have to go one
2154                  * node back for any delayed ref updates
2155                  */
2156                 ref = select_delayed_ref(locked_ref);
2157                 if (!ref) {
2158                         /* All delayed refs have been processed, Go ahead
2159                          * and send the head node to run_one_delayed_ref,
2160                          * so that any accounting fixes can happen
2161                          */
2162                         ref = &locked_ref->node;
2163
2164                         if (extent_op && must_insert_reserved) {
2165                                 kfree(extent_op);
2166                                 extent_op = NULL;
2167                         }
2168
2169                         if (extent_op) {
2170                                 spin_unlock(&delayed_refs->lock);
2171
2172                                 ret = run_delayed_extent_op(trans, root,
2173                                                             ref, extent_op);
2174                                 BUG_ON(ret);
2175                                 kfree(extent_op);
2176
2177                                 cond_resched();
2178                                 spin_lock(&delayed_refs->lock);
2179                                 continue;
2180                         }
2181
2182                         list_del_init(&locked_ref->cluster);
2183                         locked_ref = NULL;
2184                 }
2185
2186                 ref->in_tree = 0;
2187                 rb_erase(&ref->rb_node, &delayed_refs->root);
2188                 delayed_refs->num_entries--;
2189
2190                 spin_unlock(&delayed_refs->lock);
2191
2192                 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2193                                           must_insert_reserved);
2194                 BUG_ON(ret);
2195
2196                 btrfs_put_delayed_ref(ref);
2197                 kfree(extent_op);
2198                 count++;
2199
2200                 cond_resched();
2201                 spin_lock(&delayed_refs->lock);
2202         }
2203         return count;
2204 }
2205
2206 /*
2207  * this starts processing the delayed reference count updates and
2208  * extent insertions we have queued up so far.  count can be
2209  * 0, which means to process everything in the tree at the start
2210  * of the run (but not newly added entries), or it can be some target
2211  * number you'd like to process.
2212  */
2213 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2214                            struct btrfs_root *root, unsigned long count)
2215 {
2216         struct rb_node *node;
2217         struct btrfs_delayed_ref_root *delayed_refs;
2218         struct btrfs_delayed_ref_node *ref;
2219         struct list_head cluster;
2220         int ret;
2221         int run_all = count == (unsigned long)-1;
2222         int run_most = 0;
2223
2224         if (root == root->fs_info->extent_root)
2225                 root = root->fs_info->tree_root;
2226
2227         delayed_refs = &trans->transaction->delayed_refs;
2228         INIT_LIST_HEAD(&cluster);
2229 again:
2230         spin_lock(&delayed_refs->lock);
2231         if (count == 0) {
2232                 count = delayed_refs->num_entries * 2;
2233                 run_most = 1;
2234         }
2235         while (1) {
2236                 if (!(run_all || run_most) &&
2237                     delayed_refs->num_heads_ready < 64)
2238                         break;
2239
2240                 /*
2241                  * go find something we can process in the rbtree.  We start at
2242                  * the beginning of the tree, and then build a cluster
2243                  * of refs to process starting at the first one we are able to
2244                  * lock
2245                  */
2246                 ret = btrfs_find_ref_cluster(trans, &cluster,
2247                                              delayed_refs->run_delayed_start);
2248                 if (ret)
2249                         break;
2250
2251                 ret = run_clustered_refs(trans, root, &cluster);
2252                 BUG_ON(ret < 0);
2253
2254                 count -= min_t(unsigned long, ret, count);
2255
2256                 if (count == 0)
2257                         break;
2258         }
2259
2260         if (run_all) {
2261                 node = rb_first(&delayed_refs->root);
2262                 if (!node)
2263                         goto out;
2264                 count = (unsigned long)-1;
2265
2266                 while (node) {
2267                         ref = rb_entry(node, struct btrfs_delayed_ref_node,
2268                                        rb_node);
2269                         if (btrfs_delayed_ref_is_head(ref)) {
2270                                 struct btrfs_delayed_ref_head *head;
2271
2272                                 head = btrfs_delayed_node_to_head(ref);
2273                                 atomic_inc(&ref->refs);
2274
2275                                 spin_unlock(&delayed_refs->lock);
2276                                 mutex_lock(&head->mutex);
2277                                 mutex_unlock(&head->mutex);
2278
2279                                 btrfs_put_delayed_ref(ref);
2280                                 cond_resched();
2281                                 goto again;
2282                         }
2283                         node = rb_next(node);
2284                 }
2285                 spin_unlock(&delayed_refs->lock);
2286                 schedule_timeout(1);
2287                 goto again;
2288         }
2289 out:
2290         spin_unlock(&delayed_refs->lock);
2291         return 0;
2292 }
2293
2294 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2295                                 struct btrfs_root *root,
2296                                 u64 bytenr, u64 num_bytes, u64 flags,
2297                                 int is_data)
2298 {
2299         struct btrfs_delayed_extent_op *extent_op;
2300         int ret;
2301
2302         extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2303         if (!extent_op)
2304                 return -ENOMEM;
2305
2306         extent_op->flags_to_set = flags;
2307         extent_op->update_flags = 1;
2308         extent_op->update_key = 0;
2309         extent_op->is_data = is_data ? 1 : 0;
2310
2311         ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2312         if (ret)
2313                 kfree(extent_op);
2314         return ret;
2315 }
2316
2317 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2318                                       struct btrfs_root *root,
2319                                       struct btrfs_path *path,
2320                                       u64 objectid, u64 offset, u64 bytenr)
2321 {
2322         struct btrfs_delayed_ref_head *head;
2323         struct btrfs_delayed_ref_node *ref;
2324         struct btrfs_delayed_data_ref *data_ref;
2325         struct btrfs_delayed_ref_root *delayed_refs;
2326         struct rb_node *node;
2327         int ret = 0;
2328
2329         ret = -ENOENT;
2330         delayed_refs = &trans->transaction->delayed_refs;
2331         spin_lock(&delayed_refs->lock);
2332         head = btrfs_find_delayed_ref_head(trans, bytenr);
2333         if (!head)
2334                 goto out;
2335
2336         if (!mutex_trylock(&head->mutex)) {
2337                 atomic_inc(&head->node.refs);
2338                 spin_unlock(&delayed_refs->lock);
2339
2340                 btrfs_release_path(root->fs_info->extent_root, path);
2341
2342                 mutex_lock(&head->mutex);
2343                 mutex_unlock(&head->mutex);
2344                 btrfs_put_delayed_ref(&head->node);
2345                 return -EAGAIN;
2346         }
2347
2348         node = rb_prev(&head->node.rb_node);
2349         if (!node)
2350                 goto out_unlock;
2351
2352         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2353
2354         if (ref->bytenr != bytenr)
2355                 goto out_unlock;
2356
2357         ret = 1;
2358         if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2359                 goto out_unlock;
2360
2361         data_ref = btrfs_delayed_node_to_data_ref(ref);
2362
2363         node = rb_prev(node);
2364         if (node) {
2365                 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2366                 if (ref->bytenr == bytenr)
2367                         goto out_unlock;
2368         }
2369
2370         if (data_ref->root != root->root_key.objectid ||
2371             data_ref->objectid != objectid || data_ref->offset != offset)
2372                 goto out_unlock;
2373
2374         ret = 0;
2375 out_unlock:
2376         mutex_unlock(&head->mutex);
2377 out:
2378         spin_unlock(&delayed_refs->lock);
2379         return ret;
2380 }
2381
2382 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2383                                         struct btrfs_root *root,
2384                                         struct btrfs_path *path,
2385                                         u64 objectid, u64 offset, u64 bytenr)
2386 {
2387         struct btrfs_root *extent_root = root->fs_info->extent_root;
2388         struct extent_buffer *leaf;
2389         struct btrfs_extent_data_ref *ref;
2390         struct btrfs_extent_inline_ref *iref;
2391         struct btrfs_extent_item *ei;
2392         struct btrfs_key key;
2393         u32 item_size;
2394         int ret;
2395
2396         key.objectid = bytenr;
2397         key.offset = (u64)-1;
2398         key.type = BTRFS_EXTENT_ITEM_KEY;
2399
2400         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2401         if (ret < 0)
2402                 goto out;
2403         BUG_ON(ret == 0);
2404
2405         ret = -ENOENT;
2406         if (path->slots[0] == 0)
2407                 goto out;
2408
2409         path->slots[0]--;
2410         leaf = path->nodes[0];
2411         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2412
2413         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2414                 goto out;
2415
2416         ret = 1;
2417         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2418 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2419         if (item_size < sizeof(*ei)) {
2420                 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2421                 goto out;
2422         }
2423 #endif
2424         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2425
2426         if (item_size != sizeof(*ei) +
2427             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2428                 goto out;
2429
2430         if (btrfs_extent_generation(leaf, ei) <=
2431             btrfs_root_last_snapshot(&root->root_item))
2432                 goto out;
2433
2434         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2435         if (btrfs_extent_inline_ref_type(leaf, iref) !=
2436             BTRFS_EXTENT_DATA_REF_KEY)
2437                 goto out;
2438
2439         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2440         if (btrfs_extent_refs(leaf, ei) !=
2441             btrfs_extent_data_ref_count(leaf, ref) ||
2442             btrfs_extent_data_ref_root(leaf, ref) !=
2443             root->root_key.objectid ||
2444             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2445             btrfs_extent_data_ref_offset(leaf, ref) != offset)
2446                 goto out;
2447
2448         ret = 0;
2449 out:
2450         return ret;
2451 }
2452
2453 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2454                           struct btrfs_root *root,
2455                           u64 objectid, u64 offset, u64 bytenr)
2456 {
2457         struct btrfs_path *path;
2458         int ret;
2459         int ret2;
2460
2461         path = btrfs_alloc_path();
2462         if (!path)
2463                 return -ENOENT;
2464
2465         do {
2466                 ret = check_committed_ref(trans, root, path, objectid,
2467                                           offset, bytenr);
2468                 if (ret && ret != -ENOENT)
2469                         goto out;
2470
2471                 ret2 = check_delayed_ref(trans, root, path, objectid,
2472                                          offset, bytenr);
2473         } while (ret2 == -EAGAIN);
2474
2475         if (ret2 && ret2 != -ENOENT) {
2476                 ret = ret2;
2477                 goto out;
2478         }
2479
2480         if (ret != -ENOENT || ret2 != -ENOENT)
2481                 ret = 0;
2482 out:
2483         btrfs_free_path(path);
2484         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2485                 WARN_ON(ret > 0);
2486         return ret;
2487 }
2488
2489 #if 0
2490 int btrfs_cache_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2491                     struct extent_buffer *buf, u32 nr_extents)
2492 {
2493         struct btrfs_key key;
2494         struct btrfs_file_extent_item *fi;
2495         u64 root_gen;
2496         u32 nritems;
2497         int i;
2498         int level;
2499         int ret = 0;
2500         int shared = 0;
2501
2502         if (!root->ref_cows)
2503                 return 0;
2504
2505         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
2506                 shared = 0;
2507                 root_gen = root->root_key.offset;
2508         } else {
2509                 shared = 1;
2510                 root_gen = trans->transid - 1;
2511         }
2512
2513         level = btrfs_header_level(buf);
2514         nritems = btrfs_header_nritems(buf);
2515
2516         if (level == 0) {
2517                 struct btrfs_leaf_ref *ref;
2518                 struct btrfs_extent_info *info;
2519
2520                 ref = btrfs_alloc_leaf_ref(root, nr_extents);
2521                 if (!ref) {
2522                         ret = -ENOMEM;
2523                         goto out;
2524                 }
2525
2526                 ref->root_gen = root_gen;
2527                 ref->bytenr = buf->start;
2528                 ref->owner = btrfs_header_owner(buf);
2529                 ref->generation = btrfs_header_generation(buf);
2530                 ref->nritems = nr_extents;
2531                 info = ref->extents;
2532
2533                 for (i = 0; nr_extents > 0 && i < nritems; i++) {
2534                         u64 disk_bytenr;
2535                         btrfs_item_key_to_cpu(buf, &key, i);
2536                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2537                                 continue;
2538                         fi = btrfs_item_ptr(buf, i,
2539                                             struct btrfs_file_extent_item);
2540                         if (btrfs_file_extent_type(buf, fi) ==
2541                             BTRFS_FILE_EXTENT_INLINE)
2542                                 continue;
2543                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2544                         if (disk_bytenr == 0)
2545                                 continue;
2546
2547                         info->bytenr = disk_bytenr;
2548                         info->num_bytes =
2549                                 btrfs_file_extent_disk_num_bytes(buf, fi);
2550                         info->objectid = key.objectid;
2551                         info->offset = key.offset;
2552                         info++;
2553                 }
2554
2555                 ret = btrfs_add_leaf_ref(root, ref, shared);
2556                 if (ret == -EEXIST && shared) {
2557                         struct btrfs_leaf_ref *old;
2558                         old = btrfs_lookup_leaf_ref(root, ref->bytenr);
2559                         BUG_ON(!old);
2560                         btrfs_remove_leaf_ref(root, old);
2561                         btrfs_free_leaf_ref(root, old);
2562                         ret = btrfs_add_leaf_ref(root, ref, shared);
2563                 }
2564                 WARN_ON(ret);
2565                 btrfs_free_leaf_ref(root, ref);
2566         }
2567 out:
2568         return ret;
2569 }
2570
2571 /* when a block goes through cow, we update the reference counts of
2572  * everything that block points to.  The internal pointers of the block
2573  * can be in just about any order, and it is likely to have clusters of
2574  * things that are close together and clusters of things that are not.
2575  *
2576  * To help reduce the seeks that come with updating all of these reference
2577  * counts, sort them by byte number before actual updates are done.
2578  *
2579  * struct refsort is used to match byte number to slot in the btree block.
2580  * we sort based on the byte number and then use the slot to actually
2581  * find the item.
2582  *
2583  * struct refsort is smaller than strcut btrfs_item and smaller than
2584  * struct btrfs_key_ptr.  Since we're currently limited to the page size
2585  * for a btree block, there's no way for a kmalloc of refsorts for a
2586  * single node to be bigger than a page.
2587  */
2588 struct refsort {
2589         u64 bytenr;
2590         u32 slot;
2591 };
2592
2593 /*
2594  * for passing into sort()
2595  */
2596 static int refsort_cmp(const void *a_void, const void *b_void)
2597 {
2598         const struct refsort *a = a_void;
2599         const struct refsort *b = b_void;
2600
2601         if (a->bytenr < b->bytenr)
2602                 return -1;
2603         if (a->bytenr > b->bytenr)
2604                 return 1;
2605         return 0;
2606 }
2607 #endif
2608
2609 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2610                            struct btrfs_root *root,
2611                            struct extent_buffer *buf,
2612                            int full_backref, int inc)
2613 {
2614         u64 bytenr;
2615         u64 num_bytes;
2616         u64 parent;
2617         u64 ref_root;
2618         u32 nritems;
2619         struct btrfs_key key;
2620         struct btrfs_file_extent_item *fi;
2621         int i;
2622         int level;
2623         int ret = 0;
2624         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2625                             u64, u64, u64, u64, u64, u64);
2626
2627         ref_root = btrfs_header_owner(buf);
2628         nritems = btrfs_header_nritems(buf);
2629         level = btrfs_header_level(buf);
2630
2631         if (!root->ref_cows && level == 0)
2632                 return 0;
2633
2634         if (inc)
2635                 process_func = btrfs_inc_extent_ref;
2636         else
2637                 process_func = btrfs_free_extent;
2638
2639         if (full_backref)
2640                 parent = buf->start;
2641         else
2642                 parent = 0;
2643
2644         for (i = 0; i < nritems; i++) {
2645                 if (level == 0) {
2646                         btrfs_item_key_to_cpu(buf, &key, i);
2647                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2648                                 continue;
2649                         fi = btrfs_item_ptr(buf, i,
2650                                             struct btrfs_file_extent_item);
2651                         if (btrfs_file_extent_type(buf, fi) ==
2652                             BTRFS_FILE_EXTENT_INLINE)
2653                                 continue;
2654                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2655                         if (bytenr == 0)
2656                                 continue;
2657
2658                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2659                         key.offset -= btrfs_file_extent_offset(buf, fi);
2660                         ret = process_func(trans, root, bytenr, num_bytes,
2661                                            parent, ref_root, key.objectid,
2662                                            key.offset);
2663                         if (ret)
2664                                 goto fail;
2665                 } else {
2666                         bytenr = btrfs_node_blockptr(buf, i);
2667                         num_bytes = btrfs_level_size(root, level - 1);
2668                         ret = process_func(trans, root, bytenr, num_bytes,
2669                                            parent, ref_root, level - 1, 0);
2670                         if (ret)
2671                                 goto fail;
2672                 }
2673         }
2674         return 0;
2675 fail:
2676         BUG();
2677         return ret;
2678 }
2679
2680 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2681                   struct extent_buffer *buf, int full_backref)
2682 {
2683         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2684 }
2685
2686 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2687                   struct extent_buffer *buf, int full_backref)
2688 {
2689         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2690 }
2691
2692 static int write_one_cache_group(struct btrfs_trans_handle *trans,
2693                                  struct btrfs_root *root,
2694                                  struct btrfs_path *path,
2695                                  struct btrfs_block_group_cache *cache)
2696 {
2697         int ret;
2698         struct btrfs_root *extent_root = root->fs_info->extent_root;
2699         unsigned long bi;
2700         struct extent_buffer *leaf;
2701
2702         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
2703         if (ret < 0)
2704                 goto fail;
2705         BUG_ON(ret);
2706
2707         leaf = path->nodes[0];
2708         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2709         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2710         btrfs_mark_buffer_dirty(leaf);
2711         btrfs_release_path(extent_root, path);
2712 fail:
2713         if (ret)
2714                 return ret;
2715         return 0;
2716
2717 }
2718
2719 static struct btrfs_block_group_cache *
2720 next_block_group(struct btrfs_root *root,
2721                  struct btrfs_block_group_cache *cache)
2722 {
2723         struct rb_node *node;
2724         spin_lock(&root->fs_info->block_group_cache_lock);
2725         node = rb_next(&cache->cache_node);
2726         btrfs_put_block_group(cache);
2727         if (node) {
2728                 cache = rb_entry(node, struct btrfs_block_group_cache,
2729                                  cache_node);
2730                 btrfs_get_block_group(cache);
2731         } else
2732                 cache = NULL;
2733         spin_unlock(&root->fs_info->block_group_cache_lock);
2734         return cache;
2735 }
2736
2737 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
2738                             struct btrfs_trans_handle *trans,
2739                             struct btrfs_path *path)
2740 {
2741         struct btrfs_root *root = block_group->fs_info->tree_root;
2742         struct inode *inode = NULL;
2743         u64 alloc_hint = 0;
2744         int num_pages = 0;
2745         int retries = 0;
2746         int ret = 0;
2747
2748         /*
2749          * If this block group is smaller than 100 megs don't bother caching the
2750          * block group.
2751          */
2752         if (block_group->key.offset < (100 * 1024 * 1024)) {
2753                 spin_lock(&block_group->lock);
2754                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2755                 spin_unlock(&block_group->lock);
2756                 return 0;
2757         }
2758
2759 again:
2760         inode = lookup_free_space_inode(root, block_group, path);
2761         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2762                 ret = PTR_ERR(inode);
2763                 btrfs_release_path(root, path);
2764                 goto out;
2765         }
2766
2767         if (IS_ERR(inode)) {
2768                 BUG_ON(retries);
2769                 retries++;
2770
2771                 if (block_group->ro)
2772                         goto out_free;
2773
2774                 ret = create_free_space_inode(root, trans, block_group, path);
2775                 if (ret)
2776                         goto out_free;
2777                 goto again;
2778         }
2779
2780         /*
2781          * We want to set the generation to 0, that way if anything goes wrong
2782          * from here on out we know not to trust this cache when we load up next
2783          * time.
2784          */
2785         BTRFS_I(inode)->generation = 0;
2786         ret = btrfs_update_inode(trans, root, inode);
2787         WARN_ON(ret);
2788
2789         if (i_size_read(inode) > 0) {
2790                 ret = btrfs_truncate_free_space_cache(root, trans, path,
2791                                                       inode);
2792                 if (ret)
2793                         goto out_put;
2794         }
2795
2796         spin_lock(&block_group->lock);
2797         if (block_group->cached != BTRFS_CACHE_FINISHED) {
2798                 spin_unlock(&block_group->lock);
2799                 goto out_put;
2800         }
2801         spin_unlock(&block_group->lock);
2802
2803         num_pages = (int)div64_u64(block_group->key.offset, 1024 * 1024 * 1024);
2804         if (!num_pages)
2805                 num_pages = 1;
2806
2807         /*
2808          * Just to make absolutely sure we have enough space, we're going to
2809          * preallocate 12 pages worth of space for each block group.  In
2810          * practice we ought to use at most 8, but we need extra space so we can
2811          * add our header and have a terminator between the extents and the
2812          * bitmaps.
2813          */
2814         num_pages *= 16;
2815         num_pages *= PAGE_CACHE_SIZE;
2816
2817         ret = btrfs_check_data_free_space(inode, num_pages);
2818         if (ret)
2819                 goto out_put;
2820
2821         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2822                                               num_pages, num_pages,
2823                                               &alloc_hint);
2824         btrfs_free_reserved_data_space(inode, num_pages);
2825 out_put:
2826         iput(inode);
2827 out_free:
2828         btrfs_release_path(root, path);
2829 out:
2830         spin_lock(&block_group->lock);
2831         if (ret)
2832                 block_group->disk_cache_state = BTRFS_DC_ERROR;
2833         else
2834                 block_group->disk_cache_state = BTRFS_DC_SETUP;
2835         spin_unlock(&block_group->lock);
2836
2837         return ret;
2838 }
2839
2840 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
2841                                    struct btrfs_root *root)
2842 {
2843         struct btrfs_block_group_cache *cache;
2844         int err = 0;
2845         struct btrfs_path *path;
2846         u64 last = 0;
2847
2848         path = btrfs_alloc_path();
2849         if (!path)
2850                 return -ENOMEM;
2851
2852 again:
2853         while (1) {
2854                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2855                 while (cache) {
2856                         if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2857                                 break;
2858                         cache = next_block_group(root, cache);
2859                 }
2860                 if (!cache) {
2861                         if (last == 0)
2862                                 break;
2863                         last = 0;
2864                         continue;
2865                 }
2866                 err = cache_save_setup(cache, trans, path);
2867                 last = cache->key.objectid + cache->key.offset;
2868                 btrfs_put_block_group(cache);
2869         }
2870
2871         while (1) {
2872                 if (last == 0) {
2873                         err = btrfs_run_delayed_refs(trans, root,
2874                                                      (unsigned long)-1);
2875                         BUG_ON(err);
2876                 }
2877
2878                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2879                 while (cache) {
2880                         if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
2881                                 btrfs_put_block_group(cache);
2882                                 goto again;
2883                         }
2884
2885                         if (cache->dirty)
2886                                 break;
2887                         cache = next_block_group(root, cache);
2888                 }
2889                 if (!cache) {
2890                         if (last == 0)
2891                                 break;
2892                         last = 0;
2893                         continue;
2894                 }
2895
2896                 if (cache->disk_cache_state == BTRFS_DC_SETUP)
2897                         cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
2898                 cache->dirty = 0;
2899                 last = cache->key.objectid + cache->key.offset;
2900
2901                 err = write_one_cache_group(trans, root, path, cache);
2902                 BUG_ON(err);
2903                 btrfs_put_block_group(cache);
2904         }
2905
2906         while (1) {
2907                 /*
2908                  * I don't think this is needed since we're just marking our
2909                  * preallocated extent as written, but just in case it can't
2910                  * hurt.
2911                  */
2912                 if (last == 0) {
2913                         err = btrfs_run_delayed_refs(trans, root,
2914                                                      (unsigned long)-1);
2915                         BUG_ON(err);
2916                 }
2917
2918                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2919                 while (cache) {
2920                         /*
2921                          * Really this shouldn't happen, but it could if we
2922                          * couldn't write the entire preallocated extent and
2923                          * splitting the extent resulted in a new block.
2924                          */
2925                         if (cache->dirty) {
2926                                 btrfs_put_block_group(cache);
2927                                 goto again;
2928                         }
2929                         if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2930                                 break;
2931                         cache = next_block_group(root, cache);
2932                 }
2933                 if (!cache) {
2934                         if (last == 0)
2935                                 break;
2936                         last = 0;
2937                         continue;
2938                 }
2939
2940                 btrfs_write_out_cache(root, trans, cache, path);
2941
2942                 /*
2943                  * If we didn't have an error then the cache state is still
2944                  * NEED_WRITE, so we can set it to WRITTEN.
2945                  */
2946                 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2947                         cache->disk_cache_state = BTRFS_DC_WRITTEN;
2948                 last = cache->key.objectid + cache->key.offset;
2949                 btrfs_put_block_group(cache);
2950         }
2951
2952         btrfs_free_path(path);
2953         return 0;
2954 }
2955
2956 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
2957 {
2958         struct btrfs_block_group_cache *block_group;
2959         int readonly = 0;
2960
2961         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
2962         if (!block_group || block_group->ro)
2963                 readonly = 1;
2964         if (block_group)
2965                 btrfs_put_block_group(block_group);
2966         return readonly;
2967 }
2968
2969 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
2970                              u64 total_bytes, u64 bytes_used,
2971                              struct btrfs_space_info **space_info)
2972 {
2973         struct btrfs_space_info *found;
2974         int i;
2975         int factor;
2976
2977         if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
2978                      BTRFS_BLOCK_GROUP_RAID10))
2979                 factor = 2;
2980         else
2981                 factor = 1;
2982
2983         found = __find_space_info(info, flags);
2984         if (found) {
2985                 spin_lock(&found->lock);
2986                 found->total_bytes += total_bytes;
2987                 found->disk_total += total_bytes * factor;
2988                 found->bytes_used += bytes_used;
2989                 found->disk_used += bytes_used * factor;
2990                 found->full = 0;
2991                 spin_unlock(&found->lock);
2992                 *space_info = found;
2993                 return 0;
2994         }
2995         found = kzalloc(sizeof(*found), GFP_NOFS);
2996         if (!found)
2997                 return -ENOMEM;
2998
2999         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3000                 INIT_LIST_HEAD(&found->block_groups[i]);
3001         init_rwsem(&found->groups_sem);
3002         spin_lock_init(&found->lock);
3003         found->flags = flags & (BTRFS_BLOCK_GROUP_DATA |
3004                                 BTRFS_BLOCK_GROUP_SYSTEM |
3005                                 BTRFS_BLOCK_GROUP_METADATA);
3006         found->total_bytes = total_bytes;
3007         found->disk_total = total_bytes * factor;
3008         found->bytes_used = bytes_used;
3009         found->disk_used = bytes_used * factor;
3010         found->bytes_pinned = 0;
3011         found->bytes_reserved = 0;
3012         found->bytes_readonly = 0;
3013         found->bytes_may_use = 0;
3014         found->full = 0;
3015         found->force_alloc = 0;
3016         *space_info = found;
3017         list_add_rcu(&found->list, &info->space_info);
3018         atomic_set(&found->caching_threads, 0);
3019         return 0;
3020 }
3021
3022 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3023 {
3024         u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
3025                                    BTRFS_BLOCK_GROUP_RAID1 |
3026                                    BTRFS_BLOCK_GROUP_RAID10 |
3027                                    BTRFS_BLOCK_GROUP_DUP);
3028         if (extra_flags) {
3029                 if (flags & BTRFS_BLOCK_GROUP_DATA)
3030                         fs_info->avail_data_alloc_bits |= extra_flags;
3031                 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3032                         fs_info->avail_metadata_alloc_bits |= extra_flags;
3033          &