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