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