Btrfs: let the user know space caching is enabled
[~shefty/rdma-dev.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 u64 btrfs_find_block_group(struct btrfs_root *root,
584                            u64 search_start, u64 search_hint, int owner)
585 {
586         struct btrfs_block_group_cache *cache;
587         u64 used;
588         u64 last = max(search_hint, search_start);
589         u64 group_start = 0;
590         int full_search = 0;
591         int factor = 9;
592         int wrapped = 0;
593 again:
594         while (1) {
595                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
596                 if (!cache)
597                         break;
598
599                 spin_lock(&cache->lock);
600                 last = cache->key.objectid + cache->key.offset;
601                 used = btrfs_block_group_used(&cache->item);
602
603                 if ((full_search || !cache->ro) &&
604                     block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
605                         if (used + cache->pinned + cache->reserved <
606                             div_factor(cache->key.offset, factor)) {
607                                 group_start = cache->key.objectid;
608                                 spin_unlock(&cache->lock);
609                                 btrfs_put_block_group(cache);
610                                 goto found;
611                         }
612                 }
613                 spin_unlock(&cache->lock);
614                 btrfs_put_block_group(cache);
615                 cond_resched();
616         }
617         if (!wrapped) {
618                 last = search_start;
619                 wrapped = 1;
620                 goto again;
621         }
622         if (!full_search && factor < 10) {
623                 last = search_start;
624                 full_search = 1;
625                 factor = 10;
626                 goto again;
627         }
628 found:
629         return group_start;
630 }
631
632 /* simple helper to search for an existing extent at a given offset */
633 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
634 {
635         int ret;
636         struct btrfs_key key;
637         struct btrfs_path *path;
638
639         path = btrfs_alloc_path();
640         BUG_ON(!path);
641         key.objectid = start;
642         key.offset = len;
643         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
644         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
645                                 0, 0);
646         btrfs_free_path(path);
647         return ret;
648 }
649
650 /*
651  * helper function to lookup reference count and flags of extent.
652  *
653  * the head node for delayed ref is used to store the sum of all the
654  * reference count modifications queued up in the rbtree. the head
655  * node may also store the extent flags to set. This way you can check
656  * to see what the reference count and extent flags would be if all of
657  * the delayed refs are not processed.
658  */
659 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
660                              struct btrfs_root *root, u64 bytenr,
661                              u64 num_bytes, u64 *refs, u64 *flags)
662 {
663         struct btrfs_delayed_ref_head *head;
664         struct btrfs_delayed_ref_root *delayed_refs;
665         struct btrfs_path *path;
666         struct btrfs_extent_item *ei;
667         struct extent_buffer *leaf;
668         struct btrfs_key key;
669         u32 item_size;
670         u64 num_refs;
671         u64 extent_flags;
672         int ret;
673
674         path = btrfs_alloc_path();
675         if (!path)
676                 return -ENOMEM;
677
678         key.objectid = bytenr;
679         key.type = BTRFS_EXTENT_ITEM_KEY;
680         key.offset = num_bytes;
681         if (!trans) {
682                 path->skip_locking = 1;
683                 path->search_commit_root = 1;
684         }
685 again:
686         ret = btrfs_search_slot(trans, root->fs_info->extent_root,
687                                 &key, path, 0, 0);
688         if (ret < 0)
689                 goto out_free;
690
691         if (ret == 0) {
692                 leaf = path->nodes[0];
693                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
694                 if (item_size >= sizeof(*ei)) {
695                         ei = btrfs_item_ptr(leaf, path->slots[0],
696                                             struct btrfs_extent_item);
697                         num_refs = btrfs_extent_refs(leaf, ei);
698                         extent_flags = btrfs_extent_flags(leaf, ei);
699                 } else {
700 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
701                         struct btrfs_extent_item_v0 *ei0;
702                         BUG_ON(item_size != sizeof(*ei0));
703                         ei0 = btrfs_item_ptr(leaf, path->slots[0],
704                                              struct btrfs_extent_item_v0);
705                         num_refs = btrfs_extent_refs_v0(leaf, ei0);
706                         /* FIXME: this isn't correct for data */
707                         extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
708 #else
709                         BUG();
710 #endif
711                 }
712                 BUG_ON(num_refs == 0);
713         } else {
714                 num_refs = 0;
715                 extent_flags = 0;
716                 ret = 0;
717         }
718
719         if (!trans)
720                 goto out;
721
722         delayed_refs = &trans->transaction->delayed_refs;
723         spin_lock(&delayed_refs->lock);
724         head = btrfs_find_delayed_ref_head(trans, bytenr);
725         if (head) {
726                 if (!mutex_trylock(&head->mutex)) {
727                         atomic_inc(&head->node.refs);
728                         spin_unlock(&delayed_refs->lock);
729
730                         btrfs_release_path(root->fs_info->extent_root, path);
731
732                         mutex_lock(&head->mutex);
733                         mutex_unlock(&head->mutex);
734                         btrfs_put_delayed_ref(&head->node);
735                         goto again;
736                 }
737                 if (head->extent_op && head->extent_op->update_flags)
738                         extent_flags |= head->extent_op->flags_to_set;
739                 else
740                         BUG_ON(num_refs == 0);
741
742                 num_refs += head->node.ref_mod;
743                 mutex_unlock(&head->mutex);
744         }
745         spin_unlock(&delayed_refs->lock);
746 out:
747         WARN_ON(num_refs == 0);
748         if (refs)
749                 *refs = num_refs;
750         if (flags)
751                 *flags = extent_flags;
752 out_free:
753         btrfs_free_path(path);
754         return ret;
755 }
756
757 /*
758  * Back reference rules.  Back refs have three main goals:
759  *
760  * 1) differentiate between all holders of references to an extent so that
761  *    when a reference is dropped we can make sure it was a valid reference
762  *    before freeing the extent.
763  *
764  * 2) Provide enough information to quickly find the holders of an extent
765  *    if we notice a given block is corrupted or bad.
766  *
767  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
768  *    maintenance.  This is actually the same as #2, but with a slightly
769  *    different use case.
770  *
771  * There are two kinds of back refs. The implicit back refs is optimized
772  * for pointers in non-shared tree blocks. For a given pointer in a block,
773  * back refs of this kind provide information about the block's owner tree
774  * and the pointer's key. These information allow us to find the block by
775  * b-tree searching. The full back refs is for pointers in tree blocks not
776  * referenced by their owner trees. The location of tree block is recorded
777  * in the back refs. Actually the full back refs is generic, and can be
778  * used in all cases the implicit back refs is used. The major shortcoming
779  * of the full back refs is its overhead. Every time a tree block gets
780  * COWed, we have to update back refs entry for all pointers in it.
781  *
782  * For a newly allocated tree block, we use implicit back refs for
783  * pointers in it. This means most tree related operations only involve
784  * implicit back refs. For a tree block created in old transaction, the
785  * only way to drop a reference to it is COW it. So we can detect the
786  * event that tree block loses its owner tree's reference and do the
787  * back refs conversion.
788  *
789  * When a tree block is COW'd through a tree, there are four cases:
790  *
791  * The reference count of the block is one and the tree is the block's
792  * owner tree. Nothing to do in this case.
793  *
794  * The reference count of the block is one and the tree is not the
795  * block's owner tree. In this case, full back refs is used for pointers
796  * in the block. Remove these full back refs, add implicit back refs for
797  * every pointers in the new block.
798  *
799  * The reference count of the block is greater than one and the tree is
800  * the block's owner tree. In this case, implicit back refs is used for
801  * pointers in the block. Add full back refs for every pointers in the
802  * block, increase lower level extents' reference counts. The original
803  * implicit back refs are entailed to the new block.
804  *
805  * The reference count of the block is greater than one and the tree is
806  * not the block's owner tree. Add implicit back refs for every pointer in
807  * the new block, increase lower level extents' reference count.
808  *
809  * Back Reference Key composing:
810  *
811  * The key objectid corresponds to the first byte in the extent,
812  * The key type is used to differentiate between types of back refs.
813  * There are different meanings of the key offset for different types
814  * of back refs.
815  *
816  * File extents can be referenced by:
817  *
818  * - multiple snapshots, subvolumes, or different generations in one subvol
819  * - different files inside a single subvolume
820  * - different offsets inside a file (bookend extents in file.c)
821  *
822  * The extent ref structure for the implicit back refs has fields for:
823  *
824  * - Objectid of the subvolume root
825  * - objectid of the file holding the reference
826  * - original offset in the file
827  * - how many bookend extents
828  *
829  * The key offset for the implicit back refs is hash of the first
830  * three fields.
831  *
832  * The extent ref structure for the full back refs has field for:
833  *
834  * - number of pointers in the tree leaf
835  *
836  * The key offset for the implicit back refs is the first byte of
837  * the tree leaf
838  *
839  * When a file extent is allocated, The implicit back refs is used.
840  * the fields are filled in:
841  *
842  *     (root_key.objectid, inode objectid, offset in file, 1)
843  *
844  * When a file extent is removed file truncation, we find the
845  * corresponding implicit back refs and check the following fields:
846  *
847  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
848  *
849  * Btree extents can be referenced by:
850  *
851  * - Different subvolumes
852  *
853  * Both the implicit back refs and the full back refs for tree blocks
854  * only consist of key. The key offset for the implicit back refs is
855  * objectid of block's owner tree. The key offset for the full back refs
856  * is the first byte of parent block.
857  *
858  * When implicit back refs is used, information about the lowest key and
859  * level of the tree block are required. These information are stored in
860  * tree block info structure.
861  */
862
863 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
864 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
865                                   struct btrfs_root *root,
866                                   struct btrfs_path *path,
867                                   u64 owner, u32 extra_size)
868 {
869         struct btrfs_extent_item *item;
870         struct btrfs_extent_item_v0 *ei0;
871         struct btrfs_extent_ref_v0 *ref0;
872         struct btrfs_tree_block_info *bi;
873         struct extent_buffer *leaf;
874         struct btrfs_key key;
875         struct btrfs_key found_key;
876         u32 new_size = sizeof(*item);
877         u64 refs;
878         int ret;
879
880         leaf = path->nodes[0];
881         BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
882
883         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
884         ei0 = btrfs_item_ptr(leaf, path->slots[0],
885                              struct btrfs_extent_item_v0);
886         refs = btrfs_extent_refs_v0(leaf, ei0);
887
888         if (owner == (u64)-1) {
889                 while (1) {
890                         if (path->slots[0] >= btrfs_header_nritems(leaf)) {
891                                 ret = btrfs_next_leaf(root, path);
892                                 if (ret < 0)
893                                         return ret;
894                                 BUG_ON(ret > 0);
895                                 leaf = path->nodes[0];
896                         }
897                         btrfs_item_key_to_cpu(leaf, &found_key,
898                                               path->slots[0]);
899                         BUG_ON(key.objectid != found_key.objectid);
900                         if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
901                                 path->slots[0]++;
902                                 continue;
903                         }
904                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
905                                               struct btrfs_extent_ref_v0);
906                         owner = btrfs_ref_objectid_v0(leaf, ref0);
907                         break;
908                 }
909         }
910         btrfs_release_path(root, path);
911
912         if (owner < BTRFS_FIRST_FREE_OBJECTID)
913                 new_size += sizeof(*bi);
914
915         new_size -= sizeof(*ei0);
916         ret = btrfs_search_slot(trans, root, &key, path,
917                                 new_size + extra_size, 1);
918         if (ret < 0)
919                 return ret;
920         BUG_ON(ret);
921
922         ret = btrfs_extend_item(trans, root, path, new_size);
923         BUG_ON(ret);
924
925         leaf = path->nodes[0];
926         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
927         btrfs_set_extent_refs(leaf, item, refs);
928         /* FIXME: get real generation */
929         btrfs_set_extent_generation(leaf, item, 0);
930         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
931                 btrfs_set_extent_flags(leaf, item,
932                                        BTRFS_EXTENT_FLAG_TREE_BLOCK |
933                                        BTRFS_BLOCK_FLAG_FULL_BACKREF);
934                 bi = (struct btrfs_tree_block_info *)(item + 1);
935                 /* FIXME: get first key of the block */
936                 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
937                 btrfs_set_tree_block_level(leaf, bi, (int)owner);
938         } else {
939                 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
940         }
941         btrfs_mark_buffer_dirty(leaf);
942         return 0;
943 }
944 #endif
945
946 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
947 {
948         u32 high_crc = ~(u32)0;
949         u32 low_crc = ~(u32)0;
950         __le64 lenum;
951
952         lenum = cpu_to_le64(root_objectid);
953         high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
954         lenum = cpu_to_le64(owner);
955         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
956         lenum = cpu_to_le64(offset);
957         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
958
959         return ((u64)high_crc << 31) ^ (u64)low_crc;
960 }
961
962 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
963                                      struct btrfs_extent_data_ref *ref)
964 {
965         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
966                                     btrfs_extent_data_ref_objectid(leaf, ref),
967                                     btrfs_extent_data_ref_offset(leaf, ref));
968 }
969
970 static int match_extent_data_ref(struct extent_buffer *leaf,
971                                  struct btrfs_extent_data_ref *ref,
972                                  u64 root_objectid, u64 owner, u64 offset)
973 {
974         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
975             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
976             btrfs_extent_data_ref_offset(leaf, ref) != offset)
977                 return 0;
978         return 1;
979 }
980
981 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
982                                            struct btrfs_root *root,
983                                            struct btrfs_path *path,
984                                            u64 bytenr, u64 parent,
985                                            u64 root_objectid,
986                                            u64 owner, u64 offset)
987 {
988         struct btrfs_key key;
989         struct btrfs_extent_data_ref *ref;
990         struct extent_buffer *leaf;
991         u32 nritems;
992         int ret;
993         int recow;
994         int err = -ENOENT;
995
996         key.objectid = bytenr;
997         if (parent) {
998                 key.type = BTRFS_SHARED_DATA_REF_KEY;
999                 key.offset = parent;
1000         } else {
1001                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1002                 key.offset = hash_extent_data_ref(root_objectid,
1003                                                   owner, offset);
1004         }
1005 again:
1006         recow = 0;
1007         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1008         if (ret < 0) {
1009                 err = ret;
1010                 goto fail;
1011         }
1012
1013         if (parent) {
1014                 if (!ret)
1015                         return 0;
1016 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1017                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1018                 btrfs_release_path(root, path);
1019                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1020                 if (ret < 0) {
1021                         err = ret;
1022                         goto fail;
1023                 }
1024                 if (!ret)
1025                         return 0;
1026 #endif
1027                 goto fail;
1028         }
1029
1030         leaf = path->nodes[0];
1031         nritems = btrfs_header_nritems(leaf);
1032         while (1) {
1033                 if (path->slots[0] >= nritems) {
1034                         ret = btrfs_next_leaf(root, path);
1035                         if (ret < 0)
1036                                 err = ret;
1037                         if (ret)
1038                                 goto fail;
1039
1040                         leaf = path->nodes[0];
1041                         nritems = btrfs_header_nritems(leaf);
1042                         recow = 1;
1043                 }
1044
1045                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1046                 if (key.objectid != bytenr ||
1047                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1048                         goto fail;
1049
1050                 ref = btrfs_item_ptr(leaf, path->slots[0],
1051                                      struct btrfs_extent_data_ref);
1052
1053                 if (match_extent_data_ref(leaf, ref, root_objectid,
1054                                           owner, offset)) {
1055                         if (recow) {
1056                                 btrfs_release_path(root, path);
1057                                 goto again;
1058                         }
1059                         err = 0;
1060                         break;
1061                 }
1062                 path->slots[0]++;
1063         }
1064 fail:
1065         return err;
1066 }
1067
1068 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1069                                            struct btrfs_root *root,
1070                                            struct btrfs_path *path,
1071                                            u64 bytenr, u64 parent,
1072                                            u64 root_objectid, u64 owner,
1073                                            u64 offset, int refs_to_add)
1074 {
1075         struct btrfs_key key;
1076         struct extent_buffer *leaf;
1077         u32 size;
1078         u32 num_refs;
1079         int ret;
1080
1081         key.objectid = bytenr;
1082         if (parent) {
1083                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1084                 key.offset = parent;
1085                 size = sizeof(struct btrfs_shared_data_ref);
1086         } else {
1087                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1088                 key.offset = hash_extent_data_ref(root_objectid,
1089                                                   owner, offset);
1090                 size = sizeof(struct btrfs_extent_data_ref);
1091         }
1092
1093         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1094         if (ret && ret != -EEXIST)
1095                 goto fail;
1096
1097         leaf = path->nodes[0];
1098         if (parent) {
1099                 struct btrfs_shared_data_ref *ref;
1100                 ref = btrfs_item_ptr(leaf, path->slots[0],
1101                                      struct btrfs_shared_data_ref);
1102                 if (ret == 0) {
1103                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1104                 } else {
1105                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1106                         num_refs += refs_to_add;
1107                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1108                 }
1109         } else {
1110                 struct btrfs_extent_data_ref *ref;
1111                 while (ret == -EEXIST) {
1112                         ref = btrfs_item_ptr(leaf, path->slots[0],
1113                                              struct btrfs_extent_data_ref);
1114                         if (match_extent_data_ref(leaf, ref, root_objectid,
1115                                                   owner, offset))
1116                                 break;
1117                         btrfs_release_path(root, path);
1118                         key.offset++;
1119                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1120                                                       size);
1121                         if (ret && ret != -EEXIST)
1122                                 goto fail;
1123
1124                         leaf = path->nodes[0];
1125                 }
1126                 ref = btrfs_item_ptr(leaf, path->slots[0],
1127                                      struct btrfs_extent_data_ref);
1128                 if (ret == 0) {
1129                         btrfs_set_extent_data_ref_root(leaf, ref,
1130                                                        root_objectid);
1131                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1132                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1133                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1134                 } else {
1135                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1136                         num_refs += refs_to_add;
1137                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1138                 }
1139         }
1140         btrfs_mark_buffer_dirty(leaf);
1141         ret = 0;
1142 fail:
1143         btrfs_release_path(root, path);
1144         return ret;
1145 }
1146
1147 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1148                                            struct btrfs_root *root,
1149                                            struct btrfs_path *path,
1150                                            int refs_to_drop)
1151 {
1152         struct btrfs_key key;
1153         struct btrfs_extent_data_ref *ref1 = NULL;
1154         struct btrfs_shared_data_ref *ref2 = NULL;
1155         struct extent_buffer *leaf;
1156         u32 num_refs = 0;
1157         int ret = 0;
1158
1159         leaf = path->nodes[0];
1160         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1161
1162         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1163                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1164                                       struct btrfs_extent_data_ref);
1165                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1166         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1167                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1168                                       struct btrfs_shared_data_ref);
1169                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1170 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1171         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1172                 struct btrfs_extent_ref_v0 *ref0;
1173                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1174                                       struct btrfs_extent_ref_v0);
1175                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1176 #endif
1177         } else {
1178                 BUG();
1179         }
1180
1181         BUG_ON(num_refs < refs_to_drop);
1182         num_refs -= refs_to_drop;
1183
1184         if (num_refs == 0) {
1185                 ret = btrfs_del_item(trans, root, path);
1186         } else {
1187                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1188                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1189                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1190                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1191 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1192                 else {
1193                         struct btrfs_extent_ref_v0 *ref0;
1194                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1195                                         struct btrfs_extent_ref_v0);
1196                         btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1197                 }
1198 #endif
1199                 btrfs_mark_buffer_dirty(leaf);
1200         }
1201         return ret;
1202 }
1203
1204 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1205                                           struct btrfs_path *path,
1206                                           struct btrfs_extent_inline_ref *iref)
1207 {
1208         struct btrfs_key key;
1209         struct extent_buffer *leaf;
1210         struct btrfs_extent_data_ref *ref1;
1211         struct btrfs_shared_data_ref *ref2;
1212         u32 num_refs = 0;
1213
1214         leaf = path->nodes[0];
1215         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1216         if (iref) {
1217                 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1218                     BTRFS_EXTENT_DATA_REF_KEY) {
1219                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1220                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1221                 } else {
1222                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1223                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1224                 }
1225         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1226                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1227                                       struct btrfs_extent_data_ref);
1228                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1229         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1230                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1231                                       struct btrfs_shared_data_ref);
1232                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1233 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1234         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1235                 struct btrfs_extent_ref_v0 *ref0;
1236                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1237                                       struct btrfs_extent_ref_v0);
1238                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1239 #endif
1240         } else {
1241                 WARN_ON(1);
1242         }
1243         return num_refs;
1244 }
1245
1246 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1247                                           struct btrfs_root *root,
1248                                           struct btrfs_path *path,
1249                                           u64 bytenr, u64 parent,
1250                                           u64 root_objectid)
1251 {
1252         struct btrfs_key key;
1253         int ret;
1254
1255         key.objectid = bytenr;
1256         if (parent) {
1257                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1258                 key.offset = parent;
1259         } else {
1260                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1261                 key.offset = root_objectid;
1262         }
1263
1264         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1265         if (ret > 0)
1266                 ret = -ENOENT;
1267 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1268         if (ret == -ENOENT && parent) {
1269                 btrfs_release_path(root, path);
1270                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1271                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1272                 if (ret > 0)
1273                         ret = -ENOENT;
1274         }
1275 #endif
1276         return ret;
1277 }
1278
1279 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1280                                           struct btrfs_root *root,
1281                                           struct btrfs_path *path,
1282                                           u64 bytenr, u64 parent,
1283                                           u64 root_objectid)
1284 {
1285         struct btrfs_key key;
1286         int ret;
1287
1288         key.objectid = bytenr;
1289         if (parent) {
1290                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1291                 key.offset = parent;
1292         } else {
1293                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1294                 key.offset = root_objectid;
1295         }
1296
1297         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1298         btrfs_release_path(root, path);
1299         return ret;
1300 }
1301
1302 static inline int extent_ref_type(u64 parent, u64 owner)
1303 {
1304         int type;
1305         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1306                 if (parent > 0)
1307                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1308                 else
1309                         type = BTRFS_TREE_BLOCK_REF_KEY;
1310         } else {
1311                 if (parent > 0)
1312                         type = BTRFS_SHARED_DATA_REF_KEY;
1313                 else
1314                         type = BTRFS_EXTENT_DATA_REF_KEY;
1315         }
1316         return type;
1317 }
1318
1319 static int find_next_key(struct btrfs_path *path, int level,
1320                          struct btrfs_key *key)
1321
1322 {
1323         for (; level < BTRFS_MAX_LEVEL; level++) {
1324                 if (!path->nodes[level])
1325                         break;
1326                 if (path->slots[level] + 1 >=
1327                     btrfs_header_nritems(path->nodes[level]))
1328                         continue;
1329                 if (level == 0)
1330                         btrfs_item_key_to_cpu(path->nodes[level], key,
1331                                               path->slots[level] + 1);
1332                 else
1333                         btrfs_node_key_to_cpu(path->nodes[level], key,
1334                                               path->slots[level] + 1);
1335                 return 0;
1336         }
1337         return 1;
1338 }
1339
1340 /*
1341  * look for inline back ref. if back ref is found, *ref_ret is set
1342  * to the address of inline back ref, and 0 is returned.
1343  *
1344  * if back ref isn't found, *ref_ret is set to the address where it
1345  * should be inserted, and -ENOENT is returned.
1346  *
1347  * if insert is true and there are too many inline back refs, the path
1348  * points to the extent item, and -EAGAIN is returned.
1349  *
1350  * NOTE: inline back refs are ordered in the same way that back ref
1351  *       items in the tree are ordered.
1352  */
1353 static noinline_for_stack
1354 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1355                                  struct btrfs_root *root,
1356                                  struct btrfs_path *path,
1357                                  struct btrfs_extent_inline_ref **ref_ret,
1358                                  u64 bytenr, u64 num_bytes,
1359                                  u64 parent, u64 root_objectid,
1360                                  u64 owner, u64 offset, int insert)
1361 {
1362         struct btrfs_key key;
1363         struct extent_buffer *leaf;
1364         struct btrfs_extent_item *ei;
1365         struct btrfs_extent_inline_ref *iref;
1366         u64 flags;
1367         u64 item_size;
1368         unsigned long ptr;
1369         unsigned long end;
1370         int extra_size;
1371         int type;
1372         int want;
1373         int ret;
1374         int err = 0;
1375
1376         key.objectid = bytenr;
1377         key.type = BTRFS_EXTENT_ITEM_KEY;
1378         key.offset = num_bytes;
1379
1380         want = extent_ref_type(parent, owner);
1381         if (insert) {
1382                 extra_size = btrfs_extent_inline_ref_size(want);
1383                 path->keep_locks = 1;
1384         } else
1385                 extra_size = -1;
1386         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1387         if (ret < 0) {
1388                 err = ret;
1389                 goto out;
1390         }
1391         BUG_ON(ret);
1392
1393         leaf = path->nodes[0];
1394         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1395 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1396         if (item_size < sizeof(*ei)) {
1397                 if (!insert) {
1398                         err = -ENOENT;
1399                         goto out;
1400                 }
1401                 ret = convert_extent_item_v0(trans, root, path, owner,
1402                                              extra_size);
1403                 if (ret < 0) {
1404                         err = ret;
1405                         goto out;
1406                 }
1407                 leaf = path->nodes[0];
1408                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1409         }
1410 #endif
1411         BUG_ON(item_size < sizeof(*ei));
1412
1413         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1414         flags = btrfs_extent_flags(leaf, ei);
1415
1416         ptr = (unsigned long)(ei + 1);
1417         end = (unsigned long)ei + item_size;
1418
1419         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1420                 ptr += sizeof(struct btrfs_tree_block_info);
1421                 BUG_ON(ptr > end);
1422         } else {
1423                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1424         }
1425
1426         err = -ENOENT;
1427         while (1) {
1428                 if (ptr >= end) {
1429                         WARN_ON(ptr > end);
1430                         break;
1431                 }
1432                 iref = (struct btrfs_extent_inline_ref *)ptr;
1433                 type = btrfs_extent_inline_ref_type(leaf, iref);
1434                 if (want < type)
1435                         break;
1436                 if (want > type) {
1437                         ptr += btrfs_extent_inline_ref_size(type);
1438                         continue;
1439                 }
1440
1441                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1442                         struct btrfs_extent_data_ref *dref;
1443                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1444                         if (match_extent_data_ref(leaf, dref, root_objectid,
1445                                                   owner, offset)) {
1446                                 err = 0;
1447                                 break;
1448                         }
1449                         if (hash_extent_data_ref_item(leaf, dref) <
1450                             hash_extent_data_ref(root_objectid, owner, offset))
1451                                 break;
1452                 } else {
1453                         u64 ref_offset;
1454                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1455                         if (parent > 0) {
1456                                 if (parent == ref_offset) {
1457                                         err = 0;
1458                                         break;
1459                                 }
1460                                 if (ref_offset < parent)
1461                                         break;
1462                         } else {
1463                                 if (root_objectid == ref_offset) {
1464                                         err = 0;
1465                                         break;
1466                                 }
1467                                 if (ref_offset < root_objectid)
1468                                         break;
1469                         }
1470                 }
1471                 ptr += btrfs_extent_inline_ref_size(type);
1472         }
1473         if (err == -ENOENT && insert) {
1474                 if (item_size + extra_size >=
1475                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1476                         err = -EAGAIN;
1477                         goto out;
1478                 }
1479                 /*
1480                  * To add new inline back ref, we have to make sure
1481                  * there is no corresponding back ref item.
1482                  * For simplicity, we just do not add new inline back
1483                  * ref if there is any kind of item for this block
1484                  */
1485                 if (find_next_key(path, 0, &key) == 0 &&
1486                     key.objectid == bytenr &&
1487                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1488                         err = -EAGAIN;
1489                         goto out;
1490                 }
1491         }
1492         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1493 out:
1494         if (insert) {
1495                 path->keep_locks = 0;
1496                 btrfs_unlock_up_safe(path, 1);
1497         }
1498         return err;
1499 }
1500
1501 /*
1502  * helper to add new inline back ref
1503  */
1504 static noinline_for_stack
1505 int setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1506                                 struct btrfs_root *root,
1507                                 struct btrfs_path *path,
1508                                 struct btrfs_extent_inline_ref *iref,
1509                                 u64 parent, u64 root_objectid,
1510                                 u64 owner, u64 offset, int refs_to_add,
1511                                 struct btrfs_delayed_extent_op *extent_op)
1512 {
1513         struct extent_buffer *leaf;
1514         struct btrfs_extent_item *ei;
1515         unsigned long ptr;
1516         unsigned long end;
1517         unsigned long item_offset;
1518         u64 refs;
1519         int size;
1520         int type;
1521         int ret;
1522
1523         leaf = path->nodes[0];
1524         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1525         item_offset = (unsigned long)iref - (unsigned long)ei;
1526
1527         type = extent_ref_type(parent, owner);
1528         size = btrfs_extent_inline_ref_size(type);
1529
1530         ret = btrfs_extend_item(trans, root, path, size);
1531         BUG_ON(ret);
1532
1533         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1534         refs = btrfs_extent_refs(leaf, ei);
1535         refs += refs_to_add;
1536         btrfs_set_extent_refs(leaf, ei, refs);
1537         if (extent_op)
1538                 __run_delayed_extent_op(extent_op, leaf, ei);
1539
1540         ptr = (unsigned long)ei + item_offset;
1541         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1542         if (ptr < end - size)
1543                 memmove_extent_buffer(leaf, ptr + size, ptr,
1544                                       end - size - ptr);
1545
1546         iref = (struct btrfs_extent_inline_ref *)ptr;
1547         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1548         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1549                 struct btrfs_extent_data_ref *dref;
1550                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1551                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1552                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1553                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1554                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1555         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1556                 struct btrfs_shared_data_ref *sref;
1557                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1558                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1559                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1560         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1561                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1562         } else {
1563                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1564         }
1565         btrfs_mark_buffer_dirty(leaf);
1566         return 0;
1567 }
1568
1569 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1570                                  struct btrfs_root *root,
1571                                  struct btrfs_path *path,
1572                                  struct btrfs_extent_inline_ref **ref_ret,
1573                                  u64 bytenr, u64 num_bytes, u64 parent,
1574                                  u64 root_objectid, u64 owner, u64 offset)
1575 {
1576         int ret;
1577
1578         ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1579                                            bytenr, num_bytes, parent,
1580                                            root_objectid, owner, offset, 0);
1581         if (ret != -ENOENT)
1582                 return ret;
1583
1584         btrfs_release_path(root, path);
1585         *ref_ret = NULL;
1586
1587         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1588                 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1589                                             root_objectid);
1590         } else {
1591                 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1592                                              root_objectid, owner, offset);
1593         }
1594         return ret;
1595 }
1596
1597 /*
1598  * helper to update/remove inline back ref
1599  */
1600 static noinline_for_stack
1601 int update_inline_extent_backref(struct btrfs_trans_handle *trans,
1602                                  struct btrfs_root *root,
1603                                  struct btrfs_path *path,
1604                                  struct btrfs_extent_inline_ref *iref,
1605                                  int refs_to_mod,
1606                                  struct btrfs_delayed_extent_op *extent_op)
1607 {
1608         struct extent_buffer *leaf;
1609         struct btrfs_extent_item *ei;
1610         struct btrfs_extent_data_ref *dref = NULL;
1611         struct btrfs_shared_data_ref *sref = NULL;
1612         unsigned long ptr;
1613         unsigned long end;
1614         u32 item_size;
1615         int size;
1616         int type;
1617         int ret;
1618         u64 refs;
1619
1620         leaf = path->nodes[0];
1621         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1622         refs = btrfs_extent_refs(leaf, ei);
1623         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1624         refs += refs_to_mod;
1625         btrfs_set_extent_refs(leaf, ei, refs);
1626         if (extent_op)
1627                 __run_delayed_extent_op(extent_op, leaf, ei);
1628
1629         type = btrfs_extent_inline_ref_type(leaf, iref);
1630
1631         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1632                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1633                 refs = btrfs_extent_data_ref_count(leaf, dref);
1634         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1635                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1636                 refs = btrfs_shared_data_ref_count(leaf, sref);
1637         } else {
1638                 refs = 1;
1639                 BUG_ON(refs_to_mod != -1);
1640         }
1641
1642         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1643         refs += refs_to_mod;
1644
1645         if (refs > 0) {
1646                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1647                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1648                 else
1649                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1650         } else {
1651                 size =  btrfs_extent_inline_ref_size(type);
1652                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1653                 ptr = (unsigned long)iref;
1654                 end = (unsigned long)ei + item_size;
1655                 if (ptr + size < end)
1656                         memmove_extent_buffer(leaf, ptr, ptr + size,
1657                                               end - ptr - size);
1658                 item_size -= size;
1659                 ret = btrfs_truncate_item(trans, root, path, item_size, 1);
1660                 BUG_ON(ret);
1661         }
1662         btrfs_mark_buffer_dirty(leaf);
1663         return 0;
1664 }
1665
1666 static noinline_for_stack
1667 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1668                                  struct btrfs_root *root,
1669                                  struct btrfs_path *path,
1670                                  u64 bytenr, u64 num_bytes, u64 parent,
1671                                  u64 root_objectid, u64 owner,
1672                                  u64 offset, int refs_to_add,
1673                                  struct btrfs_delayed_extent_op *extent_op)
1674 {
1675         struct btrfs_extent_inline_ref *iref;
1676         int ret;
1677
1678         ret = lookup_inline_extent_backref(trans, root, path, &iref,
1679                                            bytenr, num_bytes, parent,
1680                                            root_objectid, owner, offset, 1);
1681         if (ret == 0) {
1682                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1683                 ret = update_inline_extent_backref(trans, root, path, iref,
1684                                                    refs_to_add, extent_op);
1685         } else if (ret == -ENOENT) {
1686                 ret = setup_inline_extent_backref(trans, root, path, iref,
1687                                                   parent, root_objectid,
1688                                                   owner, offset, refs_to_add,
1689                                                   extent_op);
1690         }
1691         return ret;
1692 }
1693
1694 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1695                                  struct btrfs_root *root,
1696                                  struct btrfs_path *path,
1697                                  u64 bytenr, u64 parent, u64 root_objectid,
1698                                  u64 owner, u64 offset, int refs_to_add)
1699 {
1700         int ret;
1701         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1702                 BUG_ON(refs_to_add != 1);
1703                 ret = insert_tree_block_ref(trans, root, path, bytenr,
1704                                             parent, root_objectid);
1705         } else {
1706                 ret = insert_extent_data_ref(trans, root, path, bytenr,
1707                                              parent, root_objectid,
1708                                              owner, offset, refs_to_add);
1709         }
1710         return ret;
1711 }
1712
1713 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1714                                  struct btrfs_root *root,
1715                                  struct btrfs_path *path,
1716                                  struct btrfs_extent_inline_ref *iref,
1717                                  int refs_to_drop, int is_data)
1718 {
1719         int ret;
1720
1721         BUG_ON(!is_data && refs_to_drop != 1);
1722         if (iref) {
1723                 ret = update_inline_extent_backref(trans, root, path, iref,
1724                                                    -refs_to_drop, NULL);
1725         } else if (is_data) {
1726                 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1727         } else {
1728                 ret = btrfs_del_item(trans, root, path);
1729         }
1730         return ret;
1731 }
1732
1733 static void btrfs_issue_discard(struct block_device *bdev,
1734                                 u64 start, u64 len)
1735 {
1736         blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_KERNEL,
1737                         BLKDEV_IFL_WAIT | BLKDEV_IFL_BARRIER);
1738 }
1739
1740 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1741                                 u64 num_bytes)
1742 {
1743         int ret;
1744         u64 map_length = num_bytes;
1745         struct btrfs_multi_bio *multi = NULL;
1746
1747         if (!btrfs_test_opt(root, DISCARD))
1748                 return 0;
1749
1750         /* Tell the block device(s) that the sectors can be discarded */
1751         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
1752                               bytenr, &map_length, &multi, 0);
1753         if (!ret) {
1754                 struct btrfs_bio_stripe *stripe = multi->stripes;
1755                 int i;
1756
1757                 if (map_length > num_bytes)
1758                         map_length = num_bytes;
1759
1760                 for (i = 0; i < multi->num_stripes; i++, stripe++) {
1761                         btrfs_issue_discard(stripe->dev->bdev,
1762                                             stripe->physical,
1763                                             map_length);
1764                 }
1765                 kfree(multi);
1766         }
1767
1768         return ret;
1769 }
1770
1771 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1772                          struct btrfs_root *root,
1773                          u64 bytenr, u64 num_bytes, u64 parent,
1774                          u64 root_objectid, u64 owner, u64 offset)
1775 {
1776         int ret;
1777         BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1778                root_objectid == BTRFS_TREE_LOG_OBJECTID);
1779
1780         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1781                 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
1782                                         parent, root_objectid, (int)owner,
1783                                         BTRFS_ADD_DELAYED_REF, NULL);
1784         } else {
1785                 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
1786                                         parent, root_objectid, owner, offset,
1787                                         BTRFS_ADD_DELAYED_REF, NULL);
1788         }
1789         return ret;
1790 }
1791
1792 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1793                                   struct btrfs_root *root,
1794                                   u64 bytenr, u64 num_bytes,
1795                                   u64 parent, u64 root_objectid,
1796                                   u64 owner, u64 offset, int refs_to_add,
1797                                   struct btrfs_delayed_extent_op *extent_op)
1798 {
1799         struct btrfs_path *path;
1800         struct extent_buffer *leaf;
1801         struct btrfs_extent_item *item;
1802         u64 refs;
1803         int ret;
1804         int err = 0;
1805
1806         path = btrfs_alloc_path();
1807         if (!path)
1808                 return -ENOMEM;
1809
1810         path->reada = 1;
1811         path->leave_spinning = 1;
1812         /* this will setup the path even if it fails to insert the back ref */
1813         ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1814                                            path, bytenr, num_bytes, parent,
1815                                            root_objectid, owner, offset,
1816                                            refs_to_add, extent_op);
1817         if (ret == 0)
1818                 goto out;
1819
1820         if (ret != -EAGAIN) {
1821                 err = ret;
1822                 goto out;
1823         }
1824
1825         leaf = path->nodes[0];
1826         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1827         refs = btrfs_extent_refs(leaf, item);
1828         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1829         if (extent_op)
1830                 __run_delayed_extent_op(extent_op, leaf, item);
1831
1832         btrfs_mark_buffer_dirty(leaf);
1833         btrfs_release_path(root->fs_info->extent_root, path);
1834
1835         path->reada = 1;
1836         path->leave_spinning = 1;
1837
1838         /* now insert the actual backref */
1839         ret = insert_extent_backref(trans, root->fs_info->extent_root,
1840                                     path, bytenr, parent, root_objectid,
1841                                     owner, offset, refs_to_add);
1842         BUG_ON(ret);
1843 out:
1844         btrfs_free_path(path);
1845         return err;
1846 }
1847
1848 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1849                                 struct btrfs_root *root,
1850                                 struct btrfs_delayed_ref_node *node,
1851                                 struct btrfs_delayed_extent_op *extent_op,
1852                                 int insert_reserved)
1853 {
1854         int ret = 0;
1855         struct btrfs_delayed_data_ref *ref;
1856         struct btrfs_key ins;
1857         u64 parent = 0;
1858         u64 ref_root = 0;
1859         u64 flags = 0;
1860
1861         ins.objectid = node->bytenr;
1862         ins.offset = node->num_bytes;
1863         ins.type = BTRFS_EXTENT_ITEM_KEY;
1864
1865         ref = btrfs_delayed_node_to_data_ref(node);
1866         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1867                 parent = ref->parent;
1868         else
1869                 ref_root = ref->root;
1870
1871         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1872                 if (extent_op) {
1873                         BUG_ON(extent_op->update_key);
1874                         flags |= extent_op->flags_to_set;
1875                 }
1876                 ret = alloc_reserved_file_extent(trans, root,
1877                                                  parent, ref_root, flags,
1878                                                  ref->objectid, ref->offset,
1879                                                  &ins, node->ref_mod);
1880         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1881                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1882                                              node->num_bytes, parent,
1883                                              ref_root, ref->objectid,
1884                                              ref->offset, node->ref_mod,
1885                                              extent_op);
1886         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1887                 ret = __btrfs_free_extent(trans, root, node->bytenr,
1888                                           node->num_bytes, parent,
1889                                           ref_root, ref->objectid,
1890                                           ref->offset, node->ref_mod,
1891                                           extent_op);
1892         } else {
1893                 BUG();
1894         }
1895         return ret;
1896 }
1897
1898 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1899                                     struct extent_buffer *leaf,
1900                                     struct btrfs_extent_item *ei)
1901 {
1902         u64 flags = btrfs_extent_flags(leaf, ei);
1903         if (extent_op->update_flags) {
1904                 flags |= extent_op->flags_to_set;
1905                 btrfs_set_extent_flags(leaf, ei, flags);
1906         }
1907
1908         if (extent_op->update_key) {
1909                 struct btrfs_tree_block_info *bi;
1910                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1911                 bi = (struct btrfs_tree_block_info *)(ei + 1);
1912                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1913         }
1914 }
1915
1916 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1917                                  struct btrfs_root *root,
1918                                  struct btrfs_delayed_ref_node *node,
1919                                  struct btrfs_delayed_extent_op *extent_op)
1920 {
1921         struct btrfs_key key;
1922         struct btrfs_path *path;
1923         struct btrfs_extent_item *ei;
1924         struct extent_buffer *leaf;
1925         u32 item_size;
1926         int ret;
1927         int err = 0;
1928
1929         path = btrfs_alloc_path();
1930         if (!path)
1931                 return -ENOMEM;
1932
1933         key.objectid = node->bytenr;
1934         key.type = BTRFS_EXTENT_ITEM_KEY;
1935         key.offset = node->num_bytes;
1936
1937         path->reada = 1;
1938         path->leave_spinning = 1;
1939         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
1940                                 path, 0, 1);
1941         if (ret < 0) {
1942                 err = ret;
1943                 goto out;
1944         }
1945         if (ret > 0) {
1946                 err = -EIO;
1947                 goto out;
1948         }
1949
1950         leaf = path->nodes[0];
1951         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1952 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1953         if (item_size < sizeof(*ei)) {
1954                 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
1955                                              path, (u64)-1, 0);
1956                 if (ret < 0) {
1957                         err = ret;
1958                         goto out;
1959                 }
1960                 leaf = path->nodes[0];
1961                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1962         }
1963 #endif
1964         BUG_ON(item_size < sizeof(*ei));
1965         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1966         __run_delayed_extent_op(extent_op, leaf, ei);
1967
1968         btrfs_mark_buffer_dirty(leaf);
1969 out:
1970         btrfs_free_path(path);
1971         return err;
1972 }
1973
1974 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1975                                 struct btrfs_root *root,
1976                                 struct btrfs_delayed_ref_node *node,
1977                                 struct btrfs_delayed_extent_op *extent_op,
1978                                 int insert_reserved)
1979 {
1980         int ret = 0;
1981         struct btrfs_delayed_tree_ref *ref;
1982         struct btrfs_key ins;
1983         u64 parent = 0;
1984         u64 ref_root = 0;
1985
1986         ins.objectid = node->bytenr;
1987         ins.offset = node->num_bytes;
1988         ins.type = BTRFS_EXTENT_ITEM_KEY;
1989
1990         ref = btrfs_delayed_node_to_tree_ref(node);
1991         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1992                 parent = ref->parent;
1993         else
1994                 ref_root = ref->root;
1995
1996         BUG_ON(node->ref_mod != 1);
1997         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1998                 BUG_ON(!extent_op || !extent_op->update_flags ||
1999                        !extent_op->update_key);
2000                 ret = alloc_reserved_tree_block(trans, root,
2001                                                 parent, ref_root,
2002                                                 extent_op->flags_to_set,
2003                                                 &extent_op->key,
2004                                                 ref->level, &ins);
2005         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2006                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2007                                              node->num_bytes, parent, ref_root,
2008                                              ref->level, 0, 1, extent_op);
2009         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2010                 ret = __btrfs_free_extent(trans, root, node->bytenr,
2011                                           node->num_bytes, parent, ref_root,
2012                                           ref->level, 0, 1, extent_op);
2013         } else {
2014                 BUG();
2015         }
2016         return ret;
2017 }
2018
2019 /* helper function to actually process a single delayed ref entry */
2020 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2021                                struct btrfs_root *root,
2022                                struct btrfs_delayed_ref_node *node,
2023                                struct btrfs_delayed_extent_op *extent_op,
2024                                int insert_reserved)
2025 {
2026         int ret;
2027         if (btrfs_delayed_ref_is_head(node)) {
2028                 struct btrfs_delayed_ref_head *head;
2029                 /*
2030                  * we've hit the end of the chain and we were supposed
2031                  * to insert this extent into the tree.  But, it got
2032                  * deleted before we ever needed to insert it, so all
2033                  * we have to do is clean up the accounting
2034                  */
2035                 BUG_ON(extent_op);
2036                 head = btrfs_delayed_node_to_head(node);
2037                 if (insert_reserved) {
2038                         btrfs_pin_extent(root, node->bytenr,
2039                                          node->num_bytes, 1);
2040                         if (head->is_data) {
2041                                 ret = btrfs_del_csums(trans, root,
2042                                                       node->bytenr,
2043                                                       node->num_bytes);
2044                                 BUG_ON(ret);
2045                         }
2046                 }
2047                 mutex_unlock(&head->mutex);
2048                 return 0;
2049         }
2050
2051         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2052             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2053                 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2054                                            insert_reserved);
2055         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2056                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2057                 ret = run_delayed_data_ref(trans, root, node, extent_op,
2058                                            insert_reserved);
2059         else
2060                 BUG();
2061         return ret;
2062 }
2063
2064 static noinline struct btrfs_delayed_ref_node *
2065 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2066 {
2067         struct rb_node *node;
2068         struct btrfs_delayed_ref_node *ref;
2069         int action = BTRFS_ADD_DELAYED_REF;
2070 again:
2071         /*
2072          * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2073          * this prevents ref count from going down to zero when
2074          * there still are pending delayed ref.
2075          */
2076         node = rb_prev(&head->node.rb_node);
2077         while (1) {
2078                 if (!node)
2079                         break;
2080                 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2081                                 rb_node);
2082                 if (ref->bytenr != head->node.bytenr)
2083                         break;
2084                 if (ref->action == action)
2085                         return ref;
2086                 node = rb_prev(node);
2087         }
2088         if (action == BTRFS_ADD_DELAYED_REF) {
2089                 action = BTRFS_DROP_DELAYED_REF;
2090                 goto again;
2091         }
2092         return NULL;
2093 }
2094
2095 static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
2096                                        struct btrfs_root *root,
2097                                        struct list_head *cluster)
2098 {
2099         struct btrfs_delayed_ref_root *delayed_refs;
2100         struct btrfs_delayed_ref_node *ref;
2101         struct btrfs_delayed_ref_head *locked_ref = NULL;
2102         struct btrfs_delayed_extent_op *extent_op;
2103         int ret;
2104         int count = 0;
2105         int must_insert_reserved = 0;
2106
2107         delayed_refs = &trans->transaction->delayed_refs;
2108         while (1) {
2109                 if (!locked_ref) {
2110                         /* pick a new head ref from the cluster list */
2111                         if (list_empty(cluster))
2112                                 break;
2113
2114                         locked_ref = list_entry(cluster->next,
2115                                      struct btrfs_delayed_ref_head, cluster);
2116
2117                         /* grab the lock that says we are going to process
2118                          * all the refs for this head */
2119                         ret = btrfs_delayed_ref_lock(trans, locked_ref);
2120
2121                         /*
2122                          * we may have dropped the spin lock to get the head
2123                          * mutex lock, and that might have given someone else
2124                          * time to free the head.  If that's true, it has been
2125                          * removed from our list and we can move on.
2126                          */
2127                         if (ret == -EAGAIN) {
2128                                 locked_ref = NULL;
2129                                 count++;
2130                                 continue;
2131                         }
2132                 }
2133
2134                 /*
2135                  * record the must insert reserved flag before we
2136                  * drop the spin lock.
2137                  */
2138                 must_insert_reserved = locked_ref->must_insert_reserved;
2139                 locked_ref->must_insert_reserved = 0;
2140
2141                 extent_op = locked_ref->extent_op;
2142                 locked_ref->extent_op = NULL;
2143
2144                 /*
2145                  * locked_ref is the head node, so we have to go one
2146                  * node back for any delayed ref updates
2147                  */
2148                 ref = select_delayed_ref(locked_ref);
2149                 if (!ref) {
2150                         /* All delayed refs have been processed, Go ahead
2151                          * and send the head node to run_one_delayed_ref,
2152                          * so that any accounting fixes can happen
2153                          */
2154                         ref = &locked_ref->node;
2155
2156                         if (extent_op && must_insert_reserved) {
2157                                 kfree(extent_op);
2158                                 extent_op = NULL;
2159                         }
2160
2161                         if (extent_op) {
2162                                 spin_unlock(&delayed_refs->lock);
2163
2164                                 ret = run_delayed_extent_op(trans, root,
2165                                                             ref, extent_op);
2166                                 BUG_ON(ret);
2167                                 kfree(extent_op);
2168
2169                                 cond_resched();
2170                                 spin_lock(&delayed_refs->lock);
2171                                 continue;
2172                         }
2173
2174                         list_del_init(&locked_ref->cluster);
2175                         locked_ref = NULL;
2176                 }
2177
2178                 ref->in_tree = 0;
2179                 rb_erase(&ref->rb_node, &delayed_refs->root);
2180                 delayed_refs->num_entries--;
2181
2182                 spin_unlock(&delayed_refs->lock);
2183
2184                 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2185                                           must_insert_reserved);
2186                 BUG_ON(ret);
2187
2188                 btrfs_put_delayed_ref(ref);
2189                 kfree(extent_op);
2190                 count++;
2191
2192                 cond_resched();
2193                 spin_lock(&delayed_refs->lock);
2194         }
2195         return count;
2196 }
2197
2198 /*
2199  * this starts processing the delayed reference count updates and
2200  * extent insertions we have queued up so far.  count can be
2201  * 0, which means to process everything in the tree at the start
2202  * of the run (but not newly added entries), or it can be some target
2203  * number you'd like to process.
2204  */
2205 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2206                            struct btrfs_root *root, unsigned long count)
2207 {
2208         struct rb_node *node;
2209         struct btrfs_delayed_ref_root *delayed_refs;
2210         struct btrfs_delayed_ref_node *ref;
2211         struct list_head cluster;
2212         int ret;
2213         int run_all = count == (unsigned long)-1;
2214         int run_most = 0;
2215
2216         if (root == root->fs_info->extent_root)
2217                 root = root->fs_info->tree_root;
2218
2219         delayed_refs = &trans->transaction->delayed_refs;
2220         INIT_LIST_HEAD(&cluster);
2221 again:
2222         spin_lock(&delayed_refs->lock);
2223         if (count == 0) {
2224                 count = delayed_refs->num_entries * 2;
2225                 run_most = 1;
2226         }
2227         while (1) {
2228                 if (!(run_all || run_most) &&
2229                     delayed_refs->num_heads_ready < 64)
2230                         break;
2231
2232                 /*
2233                  * go find something we can process in the rbtree.  We start at
2234                  * the beginning of the tree, and then build a cluster
2235                  * of refs to process starting at the first one we are able to
2236                  * lock
2237                  */
2238                 ret = btrfs_find_ref_cluster(trans, &cluster,
2239                                              delayed_refs->run_delayed_start);
2240                 if (ret)
2241                         break;
2242
2243                 ret = run_clustered_refs(trans, root, &cluster);
2244                 BUG_ON(ret < 0);
2245
2246                 count -= min_t(unsigned long, ret, count);
2247
2248                 if (count == 0)
2249                         break;
2250         }
2251
2252         if (run_all) {
2253                 node = rb_first(&delayed_refs->root);
2254                 if (!node)
2255                         goto out;
2256                 count = (unsigned long)-1;
2257
2258                 while (node) {
2259                         ref = rb_entry(node, struct btrfs_delayed_ref_node,
2260                                        rb_node);
2261                         if (btrfs_delayed_ref_is_head(ref)) {
2262                                 struct btrfs_delayed_ref_head *head;
2263
2264                                 head = btrfs_delayed_node_to_head(ref);
2265                                 atomic_inc(&ref->refs);
2266
2267                                 spin_unlock(&delayed_refs->lock);
2268                                 mutex_lock(&head->mutex);
2269                                 mutex_unlock(&head->mutex);
2270
2271                                 btrfs_put_delayed_ref(ref);
2272                                 cond_resched();
2273                                 goto again;
2274                         }
2275                         node = rb_next(node);
2276                 }
2277                 spin_unlock(&delayed_refs->lock);
2278                 schedule_timeout(1);
2279                 goto again;
2280         }
2281 out:
2282         spin_unlock(&delayed_refs->lock);
2283         return 0;
2284 }
2285
2286 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2287                                 struct btrfs_root *root,
2288                                 u64 bytenr, u64 num_bytes, u64 flags,
2289                                 int is_data)
2290 {
2291         struct btrfs_delayed_extent_op *extent_op;
2292         int ret;
2293
2294         extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2295         if (!extent_op)
2296                 return -ENOMEM;
2297
2298         extent_op->flags_to_set = flags;
2299         extent_op->update_flags = 1;
2300         extent_op->update_key = 0;
2301         extent_op->is_data = is_data ? 1 : 0;
2302
2303         ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2304         if (ret)
2305                 kfree(extent_op);
2306         return ret;
2307 }
2308
2309 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2310                                       struct btrfs_root *root,
2311                                       struct btrfs_path *path,
2312                                       u64 objectid, u64 offset, u64 bytenr)
2313 {
2314         struct btrfs_delayed_ref_head *head;
2315         struct btrfs_delayed_ref_node *ref;
2316         struct btrfs_delayed_data_ref *data_ref;
2317         struct btrfs_delayed_ref_root *delayed_refs;
2318         struct rb_node *node;
2319         int ret = 0;
2320
2321         ret = -ENOENT;
2322         delayed_refs = &trans->transaction->delayed_refs;
2323         spin_lock(&delayed_refs->lock);
2324         head = btrfs_find_delayed_ref_head(trans, bytenr);
2325         if (!head)
2326                 goto out;
2327
2328         if (!mutex_trylock(&head->mutex)) {
2329                 atomic_inc(&head->node.refs);
2330                 spin_unlock(&delayed_refs->lock);
2331
2332                 btrfs_release_path(root->fs_info->extent_root, path);
2333
2334                 mutex_lock(&head->mutex);
2335                 mutex_unlock(&head->mutex);
2336                 btrfs_put_delayed_ref(&head->node);
2337                 return -EAGAIN;
2338         }
2339
2340         node = rb_prev(&head->node.rb_node);
2341         if (!node)
2342                 goto out_unlock;
2343
2344         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2345
2346         if (ref->bytenr != bytenr)
2347                 goto out_unlock;
2348
2349         ret = 1;
2350         if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2351                 goto out_unlock;
2352
2353         data_ref = btrfs_delayed_node_to_data_ref(ref);
2354
2355         node = rb_prev(node);
2356         if (node) {
2357                 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2358                 if (ref->bytenr == bytenr)
2359                         goto out_unlock;
2360         }
2361
2362         if (data_ref->root != root->root_key.objectid ||
2363             data_ref->objectid != objectid || data_ref->offset != offset)
2364                 goto out_unlock;
2365
2366         ret = 0;
2367 out_unlock:
2368         mutex_unlock(&head->mutex);
2369 out:
2370         spin_unlock(&delayed_refs->lock);
2371         return ret;
2372 }
2373
2374 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2375                                         struct btrfs_root *root,
2376                                         struct btrfs_path *path,
2377                                         u64 objectid, u64 offset, u64 bytenr)
2378 {
2379         struct btrfs_root *extent_root = root->fs_info->extent_root;
2380         struct extent_buffer *leaf;
2381         struct btrfs_extent_data_ref *ref;
2382         struct btrfs_extent_inline_ref *iref;
2383         struct btrfs_extent_item *ei;
2384         struct btrfs_key key;
2385         u32 item_size;
2386         int ret;
2387
2388         key.objectid = bytenr;
2389         key.offset = (u64)-1;
2390         key.type = BTRFS_EXTENT_ITEM_KEY;
2391
2392         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2393         if (ret < 0)
2394                 goto out;
2395         BUG_ON(ret == 0);
2396
2397         ret = -ENOENT;
2398         if (path->slots[0] == 0)
2399                 goto out;
2400
2401         path->slots[0]--;
2402         leaf = path->nodes[0];
2403         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2404
2405         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2406                 goto out;
2407
2408         ret = 1;
2409         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2410 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2411         if (item_size < sizeof(*ei)) {
2412                 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2413                 goto out;
2414         }
2415 #endif
2416         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2417
2418         if (item_size != sizeof(*ei) +
2419             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2420                 goto out;
2421
2422         if (btrfs_extent_generation(leaf, ei) <=
2423             btrfs_root_last_snapshot(&root->root_item))
2424                 goto out;
2425
2426         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2427         if (btrfs_extent_inline_ref_type(leaf, iref) !=
2428             BTRFS_EXTENT_DATA_REF_KEY)
2429                 goto out;
2430
2431         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2432         if (btrfs_extent_refs(leaf, ei) !=
2433             btrfs_extent_data_ref_count(leaf, ref) ||
2434             btrfs_extent_data_ref_root(leaf, ref) !=
2435             root->root_key.objectid ||
2436             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2437             btrfs_extent_data_ref_offset(leaf, ref) != offset)
2438                 goto out;
2439
2440         ret = 0;
2441 out:
2442         return ret;
2443 }
2444
2445 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2446                           struct btrfs_root *root,
2447                           u64 objectid, u64 offset, u64 bytenr)
2448 {
2449         struct btrfs_path *path;
2450         int ret;
2451         int ret2;
2452
2453         path = btrfs_alloc_path();
2454         if (!path)
2455                 return -ENOENT;
2456
2457         do {
2458                 ret = check_committed_ref(trans, root, path, objectid,
2459                                           offset, bytenr);
2460                 if (ret && ret != -ENOENT)
2461                         goto out;
2462
2463                 ret2 = check_delayed_ref(trans, root, path, objectid,
2464                                          offset, bytenr);
2465         } while (ret2 == -EAGAIN);
2466
2467         if (ret2 && ret2 != -ENOENT) {
2468                 ret = ret2;
2469                 goto out;
2470         }
2471
2472         if (ret != -ENOENT || ret2 != -ENOENT)
2473                 ret = 0;
2474 out:
2475         btrfs_free_path(path);
2476         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2477                 WARN_ON(ret > 0);
2478         return ret;
2479 }
2480
2481 #if 0
2482 int btrfs_cache_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2483                     struct extent_buffer *buf, u32 nr_extents)
2484 {
2485         struct btrfs_key key;
2486         struct btrfs_file_extent_item *fi;
2487         u64 root_gen;
2488         u32 nritems;
2489         int i;
2490         int level;
2491         int ret = 0;
2492         int shared = 0;
2493
2494         if (!root->ref_cows)
2495                 return 0;
2496
2497         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
2498                 shared = 0;
2499                 root_gen = root->root_key.offset;
2500         } else {
2501                 shared = 1;
2502                 root_gen = trans->transid - 1;
2503         }
2504
2505         level = btrfs_header_level(buf);
2506         nritems = btrfs_header_nritems(buf);
2507
2508         if (level == 0) {
2509                 struct btrfs_leaf_ref *ref;
2510                 struct btrfs_extent_info *info;
2511
2512                 ref = btrfs_alloc_leaf_ref(root, nr_extents);
2513                 if (!ref) {
2514                         ret = -ENOMEM;
2515                         goto out;
2516                 }
2517
2518                 ref->root_gen = root_gen;
2519                 ref->bytenr = buf->start;
2520                 ref->owner = btrfs_header_owner(buf);
2521                 ref->generation = btrfs_header_generation(buf);
2522                 ref->nritems = nr_extents;
2523                 info = ref->extents;
2524
2525                 for (i = 0; nr_extents > 0 && i < nritems; i++) {
2526                         u64 disk_bytenr;
2527                         btrfs_item_key_to_cpu(buf, &key, i);
2528                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2529                                 continue;
2530                         fi = btrfs_item_ptr(buf, i,
2531                                             struct btrfs_file_extent_item);
2532                         if (btrfs_file_extent_type(buf, fi) ==
2533                             BTRFS_FILE_EXTENT_INLINE)
2534                                 continue;
2535                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2536                         if (disk_bytenr == 0)
2537                                 continue;
2538
2539                         info->bytenr = disk_bytenr;
2540                         info->num_bytes =
2541                                 btrfs_file_extent_disk_num_bytes(buf, fi);
2542                         info->objectid = key.objectid;
2543                         info->offset = key.offset;
2544                         info++;
2545                 }
2546
2547                 ret = btrfs_add_leaf_ref(root, ref, shared);
2548                 if (ret == -EEXIST && shared) {
2549                         struct btrfs_leaf_ref *old;
2550                         old = btrfs_lookup_leaf_ref(root, ref->bytenr);
2551                         BUG_ON(!old);
2552                         btrfs_remove_leaf_ref(root, old);
2553                         btrfs_free_leaf_ref(root, old);
2554                         ret = btrfs_add_leaf_ref(root, ref, shared);
2555                 }
2556                 WARN_ON(ret);
2557                 btrfs_free_leaf_ref(root, ref);
2558         }
2559 out:
2560         return ret;
2561 }
2562
2563 /* when a block goes through cow, we update the reference counts of
2564  * everything that block points to.  The internal pointers of the block
2565  * can be in just about any order, and it is likely to have clusters of
2566  * things that are close together and clusters of things that are not.
2567  *
2568  * To help reduce the seeks that come with updating all of these reference
2569  * counts, sort them by byte number before actual updates are done.
2570  *
2571  * struct refsort is used to match byte number to slot in the btree block.
2572  * we sort based on the byte number and then use the slot to actually
2573  * find the item.
2574  *
2575  * struct refsort is smaller than strcut btrfs_item and smaller than
2576  * struct btrfs_key_ptr.  Since we're currently limited to the page size
2577  * for a btree block, there's no way for a kmalloc of refsorts for a
2578  * single node to be bigger than a page.
2579  */
2580 struct refsort {
2581         u64 bytenr;
2582         u32 slot;
2583 };
2584
2585 /*
2586  * for passing into sort()
2587  */
2588 static int refsort_cmp(const void *a_void, const void *b_void)
2589 {
2590         const struct refsort *a = a_void;
2591         const struct refsort *b = b_void;
2592
2593         if (a->bytenr < b->bytenr)
2594                 return -1;
2595         if (a->bytenr > b->bytenr)
2596                 return 1;
2597         return 0;
2598 }
2599 #endif
2600
2601 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2602                            struct btrfs_root *root,
2603                            struct extent_buffer *buf,
2604                            int full_backref, int inc)
2605 {
2606         u64 bytenr;
2607         u64 num_bytes;
2608         u64 parent;
2609         u64 ref_root;
2610         u32 nritems;
2611         struct btrfs_key key;
2612         struct btrfs_file_extent_item *fi;
2613         int i;
2614         int level;
2615         int ret = 0;
2616         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2617                             u64, u64, u64, u64, u64, u64);
2618
2619         ref_root = btrfs_header_owner(buf);
2620         nritems = btrfs_header_nritems(buf);
2621         level = btrfs_header_level(buf);
2622
2623         if (!root->ref_cows && level == 0)
2624                 return 0;
2625
2626         if (inc)
2627                 process_func = btrfs_inc_extent_ref;
2628         else
2629                 process_func = btrfs_free_extent;
2630
2631         if (full_backref)
2632                 parent = buf->start;
2633         else
2634                 parent = 0;
2635
2636         for (i = 0; i < nritems; i++) {
2637                 if (level == 0) {
2638                         btrfs_item_key_to_cpu(buf, &key, i);
2639                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2640                                 continue;
2641                         fi = btrfs_item_ptr(buf, i,
2642                                             struct btrfs_file_extent_item);
2643                         if (btrfs_file_extent_type(buf, fi) ==
2644                             BTRFS_FILE_EXTENT_INLINE)
2645                                 continue;
2646                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2647                         if (bytenr == 0)
2648                                 continue;
2649
2650                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2651                         key.offset -= btrfs_file_extent_offset(buf, fi);
2652                         ret = process_func(trans, root, bytenr, num_bytes,
2653                                            parent, ref_root, key.objectid,
2654                                            key.offset);
2655                         if (ret)
2656                                 goto fail;
2657                 } else {
2658                         bytenr = btrfs_node_blockptr(buf, i);
2659                         num_bytes = btrfs_level_size(root, level - 1);
2660                         ret = process_func(trans, root, bytenr, num_bytes,
2661                                            parent, ref_root, level - 1, 0);
2662                         if (ret)
2663                                 goto fail;
2664                 }
2665         }
2666         return 0;
2667 fail:
2668         BUG();
2669         return ret;
2670 }
2671
2672 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2673                   struct extent_buffer *buf, int full_backref)
2674 {
2675         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2676 }
2677
2678 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2679                   struct extent_buffer *buf, int full_backref)
2680 {
2681         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2682 }
2683
2684 static int write_one_cache_group(struct btrfs_trans_handle *trans,
2685                                  struct btrfs_root *root,
2686                                  struct btrfs_path *path,
2687                                  struct btrfs_block_group_cache *cache)
2688 {
2689         int ret;
2690         struct btrfs_root *extent_root = root->fs_info->extent_root;
2691         unsigned long bi;
2692         struct extent_buffer *leaf;
2693
2694         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
2695         if (ret < 0)
2696                 goto fail;
2697         BUG_ON(ret);
2698
2699         leaf = path->nodes[0];
2700         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2701         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2702         btrfs_mark_buffer_dirty(leaf);
2703         btrfs_release_path(extent_root, path);
2704 fail:
2705         if (ret)
2706                 return ret;
2707         return 0;
2708
2709 }
2710
2711 static struct btrfs_block_group_cache *
2712 next_block_group(struct btrfs_root *root,
2713                  struct btrfs_block_group_cache *cache)
2714 {
2715         struct rb_node *node;
2716         spin_lock(&root->fs_info->block_group_cache_lock);
2717         node = rb_next(&cache->cache_node);
2718         btrfs_put_block_group(cache);
2719         if (node) {
2720                 cache = rb_entry(node, struct btrfs_block_group_cache,
2721                                  cache_node);
2722                 btrfs_get_block_group(cache);
2723         } else
2724                 cache = NULL;
2725         spin_unlock(&root->fs_info->block_group_cache_lock);
2726         return cache;
2727 }
2728
2729 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
2730                             struct btrfs_trans_handle *trans,
2731                             struct btrfs_path *path)
2732 {
2733         struct btrfs_root *root = block_group->fs_info->tree_root;
2734         struct inode *inode = NULL;
2735         u64 alloc_hint = 0;
2736         int num_pages = 0;
2737         int retries = 0;
2738         int ret = 0;
2739
2740         /*
2741          * If this block group is smaller than 100 megs don't bother caching the
2742          * block group.
2743          */
2744         if (block_group->key.offset < (100 * 1024 * 1024)) {
2745                 spin_lock(&block_group->lock);
2746                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2747                 spin_unlock(&block_group->lock);
2748                 return 0;
2749         }
2750
2751 again:
2752         inode = lookup_free_space_inode(root, block_group, path);
2753         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2754                 ret = PTR_ERR(inode);
2755                 btrfs_release_path(root, path);
2756                 goto out;
2757         }
2758
2759         if (IS_ERR(inode)) {
2760                 BUG_ON(retries);
2761                 retries++;
2762
2763                 if (block_group->ro)
2764                         goto out_free;
2765
2766                 ret = create_free_space_inode(root, trans, block_group, path);
2767                 if (ret)
2768                         goto out_free;
2769                 goto again;
2770         }
2771
2772         /*
2773          * We want to set the generation to 0, that way if anything goes wrong
2774          * from here on out we know not to trust this cache when we load up next
2775          * time.
2776          */
2777         BTRFS_I(inode)->generation = 0;
2778         ret = btrfs_update_inode(trans, root, inode);
2779         WARN_ON(ret);
2780
2781         if (i_size_read(inode) > 0) {
2782                 ret = btrfs_truncate_free_space_cache(root, trans, path,
2783                                                       inode);
2784                 if (ret)
2785                         goto out_put;
2786         }
2787
2788         spin_lock(&block_group->lock);
2789         if (block_group->cached != BTRFS_CACHE_FINISHED) {
2790                 spin_unlock(&block_group->lock);
2791                 goto out_put;
2792         }
2793         spin_unlock(&block_group->lock);
2794
2795         num_pages = (int)div64_u64(block_group->key.offset, 1024 * 1024 * 1024);
2796         if (!num_pages)
2797                 num_pages = 1;
2798
2799         /*
2800          * Just to make absolutely sure we have enough space, we're going to
2801          * preallocate 12 pages worth of space for each block group.  In
2802          * practice we ought to use at most 8, but we need extra space so we can
2803          * add our header and have a terminator between the extents and the
2804          * bitmaps.
2805          */
2806         num_pages *= 16;
2807         num_pages *= PAGE_CACHE_SIZE;
2808
2809         ret = btrfs_check_data_free_space(inode, num_pages);
2810         if (ret)
2811                 goto out_put;
2812
2813         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2814                                               num_pages, num_pages,
2815                                               &alloc_hint);
2816         btrfs_free_reserved_data_space(inode, num_pages);
2817 out_put:
2818         iput(inode);
2819 out_free:
2820         btrfs_release_path(root, path);
2821 out:
2822         spin_lock(&block_group->lock);
2823         if (ret)
2824                 block_group->disk_cache_state = BTRFS_DC_ERROR;
2825         else
2826                 block_group->disk_cache_state = BTRFS_DC_SETUP;
2827         spin_unlock(&block_group->lock);
2828
2829         return ret;
2830 }
2831
2832 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
2833                                    struct btrfs_root *root)
2834 {
2835         struct btrfs_block_group_cache *cache;
2836         int err = 0;
2837         struct btrfs_path *path;
2838         u64 last = 0;
2839
2840         path = btrfs_alloc_path();
2841         if (!path)
2842                 return -ENOMEM;
2843
2844 again:
2845         while (1) {
2846                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2847                 while (cache) {
2848                         if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2849                                 break;
2850                         cache = next_block_group(root, cache);
2851                 }
2852                 if (!cache) {
2853                         if (last == 0)
2854                                 break;
2855                         last = 0;
2856                         continue;
2857                 }
2858                 err = cache_save_setup(cache, trans, path);
2859                 last = cache->key.objectid + cache->key.offset;
2860                 btrfs_put_block_group(cache);
2861         }
2862
2863         while (1) {
2864                 if (last == 0) {
2865                         err = btrfs_run_delayed_refs(trans, root,
2866                                                      (unsigned long)-1);
2867                         BUG_ON(err);
2868                 }
2869
2870                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2871                 while (cache) {
2872                         if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
2873                                 btrfs_put_block_group(cache);
2874                                 goto again;
2875                         }
2876
2877                         if (cache->dirty)
2878                                 break;
2879                         cache = next_block_group(root, cache);
2880                 }
2881                 if (!cache) {
2882                         if (last == 0)
2883                                 break;
2884                         last = 0;
2885                         continue;
2886                 }
2887
2888                 if (cache->disk_cache_state == BTRFS_DC_SETUP)
2889                         cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
2890                 cache->dirty = 0;
2891                 last = cache->key.objectid + cache->key.offset;
2892
2893                 err = write_one_cache_group(trans, root, path, cache);
2894                 BUG_ON(err);
2895                 btrfs_put_block_group(cache);
2896         }
2897
2898         while (1) {
2899                 /*
2900                  * I don't think this is needed since we're just marking our
2901                  * preallocated extent as written, but just in case it can't
2902                  * hurt.
2903                  */
2904                 if (last == 0) {
2905                         err = btrfs_run_delayed_refs(trans, root,
2906                                                      (unsigned long)-1);
2907                         BUG_ON(err);
2908                 }
2909
2910                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2911                 while (cache) {
2912                         /*
2913                          * Really this shouldn't happen, but it could if we
2914                          * couldn't write the entire preallocated extent and
2915                          * splitting the extent resulted in a new block.
2916                          */
2917                         if (cache->dirty) {
2918                                 btrfs_put_block_group(cache);
2919                                 goto again;
2920                         }
2921                         if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2922                                 break;
2923                         cache = next_block_group(root, cache);
2924                 }
2925                 if (!cache) {
2926                         if (last == 0)
2927                                 break;
2928                         last = 0;
2929                         continue;
2930                 }
2931
2932                 btrfs_write_out_cache(root, trans, cache, path);
2933
2934                 /*
2935                  * If we didn't have an error then the cache state is still
2936                  * NEED_WRITE, so we can set it to WRITTEN.
2937                  */
2938                 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2939                         cache->disk_cache_state = BTRFS_DC_WRITTEN;
2940                 last = cache->key.objectid + cache->key.offset;
2941                 btrfs_put_block_group(cache);
2942         }
2943
2944         btrfs_free_path(path);
2945         return 0;
2946 }
2947
2948 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
2949 {
2950         struct btrfs_block_group_cache *block_group;
2951         int readonly = 0;
2952
2953         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
2954         if (!block_group || block_group->ro)
2955                 readonly = 1;
2956         if (block_group)
2957                 btrfs_put_block_group(block_group);
2958         return readonly;
2959 }
2960
2961 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
2962                              u64 total_bytes, u64 bytes_used,
2963                              struct btrfs_space_info **space_info)
2964 {
2965         struct btrfs_space_info *found;
2966         int i;
2967         int factor;
2968
2969         if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
2970                      BTRFS_BLOCK_GROUP_RAID10))
2971                 factor = 2;
2972         else
2973                 factor = 1;
2974
2975         found = __find_space_info(info, flags);
2976         if (found) {
2977                 spin_lock(&found->lock);
2978                 found->total_bytes += total_bytes;
2979                 found->bytes_used += bytes_used;
2980                 found->disk_used += bytes_used * factor;
2981                 found->full = 0;
2982                 spin_unlock(&found->lock);
2983                 *space_info = found;
2984                 return 0;
2985         }
2986         found = kzalloc(sizeof(*found), GFP_NOFS);
2987         if (!found)
2988                 return -ENOMEM;
2989
2990         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
2991                 INIT_LIST_HEAD(&found->block_groups[i]);
2992         init_rwsem(&found->groups_sem);
2993         spin_lock_init(&found->lock);
2994         found->flags = flags & (BTRFS_BLOCK_GROUP_DATA |
2995                                 BTRFS_BLOCK_GROUP_SYSTEM |
2996                                 BTRFS_BLOCK_GROUP_METADATA);
2997         found->total_bytes = total_bytes;
2998         found->bytes_used = bytes_used;
2999         found->disk_used = bytes_used * factor;
3000         found->bytes_pinned = 0;
3001         found->bytes_reserved = 0;
3002         found->bytes_readonly = 0;
3003         found->bytes_may_use = 0;
3004         found->full = 0;
3005         found->force_alloc = 0;
3006         *space_info = found;
3007         list_add_rcu(&found->list, &info->space_info);
3008         atomic_set(&found->caching_threads, 0);
3009         return 0;
3010 }
3011
3012 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3013 {
3014         u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
3015                                    BTRFS_BLOCK_GROUP_RAID1 |
3016                                    BTRFS_BLOCK_GROUP_RAID10 |
3017                                    BTRFS_BLOCK_GROUP_DUP);
3018         if (extra_flags) {
3019                 if (flags & BTRFS_BLOCK_GROUP_DATA)
3020                         fs_info->avail_data_alloc_bits |= extra_flags;
3021                 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3022                         fs_info->avail_metadata_alloc_bits |= extra_flags;
3023                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3024                         fs_info->avail_system_alloc_bits |= extra_flags;
3025         }
3026 }
3027
3028 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
3029 {
3030         u64 num_devices = root->fs_info->fs_devices->rw_devices;
3031
3032         if (num_devices == 1)
3033                 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
3034         if (num_devices < 4)
3035                 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3036
3037         if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
3038             (flags & (BTRFS_BLOCK_GROUP_RAID1 |
3039                       BTRFS_BLOCK_GROUP_RAID10))) {
3040                 flags &= ~BTRFS_BLOCK_GROUP_DUP;
3041         }
3042
3043         if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
3044             (flags & BTRFS_BLOCK_GROUP_RAID10)) {
3045                 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
3046         }
3047
3048         if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
3049             ((flags & BTRFS_BLOCK_GROUP_RAID1) |
3050              (flags & BTRFS_BLOCK_GROUP_RAID10) |
3051              (flags & BTRFS_BLOCK_GROUP_DUP)))
3052                 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
3053         return flags;
3054 }
3055
3056 static u64 get_alloc_profile(struct btrfs_root *root, u64 flags)
3057 {
3058         if (flags & BTRFS_BLOCK_GROUP_DATA)
3059                 flags |= root->fs_info->avail_data_alloc_bits &
3060                          root->fs_info->data_alloc_profile;
3061         else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3062                 flags |= root->fs_info->avail_system_alloc_bits &
3063                          root->fs_info->system_alloc_profile;
3064         else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3065                 flags |= root->fs_info->avail_metadata_alloc_bits &
3066                          root->fs_info->metadata_alloc_profile;
3067         return btrfs_reduce_alloc_profile(root, flags);
3068 }
3069
3070 static u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3071 {
3072         u64 flags;
3073
3074         if (data)
3075                 flags = BTRFS_BLOCK_GROUP_DATA;
3076         else if (root == root->fs_info->chunk_root)
3077                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3078         else
3079                 flags = BTRFS_BLOCK_GROUP_METADATA;
3080
3081         return get_alloc_profile(root, flags);
3082 }
3083
3084 void btrfs_set_inode_space_info(struct btrfs_root *root, struct inode *inode)
3085 {
3086         BTRFS_I(inode)->space_info = __find_space_info(root->fs_info,
3087                                                        BTRFS_BLOCK_GROUP_DATA);
3088 }
3089
3090 /*
3091  * This will check the space that the inode allocates from to make sure we have
3092  * enough space for bytes.
3093  */
3094 int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
3095 {
3096         struct btrfs_space_info *data_sinfo;
3097         struct btrfs_root *root = BTRFS_I(inode)->root;
3098         u64 used;
3099         int ret = 0, committed = 0, alloc_chunk = 1;
3100
3101         /* make sure bytes are sectorsize aligned */
3102         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3103
3104         if (root == root->fs_info->tree_root) {
3105                 alloc_chunk = 0;
3106                 committed = 1;
3107         }
3108
3109         data_sinfo = BTRFS_I(inode)->space_info;
3110         if (!data_sinfo)
3111                 goto alloc;
3112
3113 again:
3114         /* make sure we have enough space to handle the data first */
3115         spin_lock(&data_sinfo->lock);
3116         used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3117                 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3118                 data_sinfo->bytes_may_use;
3119
3120         if (used + bytes > data_sinfo->total_bytes) {
3121                 struct btrfs_trans_handle *trans;
3122
3123                 /*
3124                  * if we don't have enough free bytes in this space then we need
3125                  * to alloc a new chunk.
3126                  */
3127                 if (!data_sinfo->full && alloc_chunk) {
3128                         u64 alloc_target;
3129
3130                         data_sinfo->force_alloc = 1;
3131                         spin_unlock(&data_sinfo->lock);
3132 alloc:
3133                         alloc_target = btrfs_get_alloc_profile(root, 1);
3134                         trans = btrfs_join_transaction(root, 1);
3135                         if (IS_ERR(trans))
3136                                 return PTR_ERR(trans);
3137
3138                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3139                                              bytes + 2 * 1024 * 1024,
3140                                              alloc_target, 0);
3141                         btrfs_end_transaction(trans, root);
3142                         if (ret < 0)
3143                                 return ret;
3144
3145                         if (!data_sinfo) {
3146                                 btrfs_set_inode_space_info(root, inode);
3147                                 data_sinfo = BTRFS_I(inode)->space_info;
3148                         }
3149                         goto again;
3150                 }
3151                 spin_unlock(&data_sinfo->lock);
3152
3153                 /* commit the current transaction and try again */
3154                 if (!committed && !root->fs_info->open_ioctl_trans) {
3155                         committed = 1;
3156                         trans = btrfs_join_transaction(root, 1);
3157                         if (IS_ERR(trans))
3158                                 return PTR_ERR(trans);
3159                         ret = btrfs_commit_transaction(trans, root);
3160                         if (ret)
3161                                 return ret;
3162                         goto again;
3163                 }
3164
3165 #if 0 /* I hope we never need this code again, just in case */
3166                 printk(KERN_ERR "no space left, need %llu, %llu bytes_used, "
3167                        "%llu bytes_reserved, " "%llu bytes_pinned, "
3168                        "%llu bytes_readonly, %llu may use %llu total\n",
3169                        (unsigned long long)bytes,
3170                        (unsigned long long)data_sinfo->bytes_used,
3171                        (unsigned long long)data_sinfo->bytes_reserved,
3172                        (unsigned long long)data_sinfo->bytes_pinned,
3173                        (unsigned long long)data_sinfo->bytes_readonly,
3174                        (unsigned long long)data_sinfo->bytes_may_use,
3175                        (unsigned long long)data_sinfo->total_bytes);
3176 #endif
3177                 return -ENOSPC;
3178         }