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