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