Btrfs: don't warn if we get ENOSPC in btrfs_block_rsv_check
[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 static int update_block_group(struct btrfs_trans_handle *trans,
37                               struct btrfs_root *root,
38                               u64 bytenr, u64 num_bytes, int alloc);
39 static int update_reserved_bytes(struct btrfs_block_group_cache *cache,
40                                  u64 num_bytes, int reserve, int sinfo);
41 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
42                                 struct btrfs_root *root,
43                                 u64 bytenr, u64 num_bytes, u64 parent,
44                                 u64 root_objectid, u64 owner_objectid,
45                                 u64 owner_offset, int refs_to_drop,
46                                 struct btrfs_delayed_extent_op *extra_op);
47 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
48                                     struct extent_buffer *leaf,
49                                     struct btrfs_extent_item *ei);
50 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
51                                       struct btrfs_root *root,
52                                       u64 parent, u64 root_objectid,
53                                       u64 flags, u64 owner, u64 offset,
54                                       struct btrfs_key *ins, int ref_mod);
55 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
56                                      struct btrfs_root *root,
57                                      u64 parent, u64 root_objectid,
58                                      u64 flags, struct btrfs_disk_key *key,
59                                      int level, struct btrfs_key *ins);
60 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
61                           struct btrfs_root *extent_root, u64 alloc_bytes,
62                           u64 flags, int force);
63 static int find_next_key(struct btrfs_path *path, int level,
64                          struct btrfs_key *key);
65 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
66                             int dump_block_groups);
67
68 static noinline int
69 block_group_cache_done(struct btrfs_block_group_cache *cache)
70 {
71         smp_mb();
72         return cache->cached == BTRFS_CACHE_FINISHED;
73 }
74
75 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
76 {
77         return (cache->flags & bits) == bits;
78 }
79
80 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
81 {
82         atomic_inc(&cache->count);
83 }
84
85 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
86 {
87         if (atomic_dec_and_test(&cache->count)) {
88                 WARN_ON(cache->pinned > 0);
89                 WARN_ON(cache->reserved > 0);
90                 WARN_ON(cache->reserved_pinned > 0);
91                 kfree(cache);
92         }
93 }
94
95 /*
96  * this adds the block group to the fs_info rb tree for the block group
97  * cache
98  */
99 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
100                                 struct btrfs_block_group_cache *block_group)
101 {
102         struct rb_node **p;
103         struct rb_node *parent = NULL;
104         struct btrfs_block_group_cache *cache;
105
106         spin_lock(&info->block_group_cache_lock);
107         p = &info->block_group_cache_tree.rb_node;
108
109         while (*p) {
110                 parent = *p;
111                 cache = rb_entry(parent, struct btrfs_block_group_cache,
112                                  cache_node);
113                 if (block_group->key.objectid < cache->key.objectid) {
114                         p = &(*p)->rb_left;
115                 } else if (block_group->key.objectid > cache->key.objectid) {
116                         p = &(*p)->rb_right;
117                 } else {
118                         spin_unlock(&info->block_group_cache_lock);
119                         return -EEXIST;
120                 }
121         }
122
123         rb_link_node(&block_group->cache_node, parent, p);
124         rb_insert_color(&block_group->cache_node,
125                         &info->block_group_cache_tree);
126         spin_unlock(&info->block_group_cache_lock);
127
128         return 0;
129 }
130
131 /*
132  * This will return the block group at or after bytenr if contains is 0, else
133  * it will return the block group that contains the bytenr
134  */
135 static struct btrfs_block_group_cache *
136 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
137                               int contains)
138 {
139         struct btrfs_block_group_cache *cache, *ret = NULL;
140         struct rb_node *n;
141         u64 end, start;
142
143         spin_lock(&info->block_group_cache_lock);
144         n = info->block_group_cache_tree.rb_node;
145
146         while (n) {
147                 cache = rb_entry(n, struct btrfs_block_group_cache,
148                                  cache_node);
149                 end = cache->key.objectid + cache->key.offset - 1;
150                 start = cache->key.objectid;
151
152                 if (bytenr < start) {
153                         if (!contains && (!ret || start < ret->key.objectid))
154                                 ret = cache;
155                         n = n->rb_left;
156                 } else if (bytenr > start) {
157                         if (contains && bytenr <= end) {
158                                 ret = cache;
159                                 break;
160                         }
161                         n = n->rb_right;
162                 } else {
163                         ret = cache;
164                         break;
165                 }
166         }
167         if (ret)
168                 btrfs_get_block_group(ret);
169         spin_unlock(&info->block_group_cache_lock);
170
171         return ret;
172 }
173
174 static int add_excluded_extent(struct btrfs_root *root,
175                                u64 start, u64 num_bytes)
176 {
177         u64 end = start + num_bytes - 1;
178         set_extent_bits(&root->fs_info->freed_extents[0],
179                         start, end, EXTENT_UPTODATE, GFP_NOFS);
180         set_extent_bits(&root->fs_info->freed_extents[1],
181                         start, end, EXTENT_UPTODATE, GFP_NOFS);
182         return 0;
183 }
184
185 static void free_excluded_extents(struct btrfs_root *root,
186                                   struct btrfs_block_group_cache *cache)
187 {
188         u64 start, end;
189
190         start = cache->key.objectid;
191         end = start + cache->key.offset - 1;
192
193         clear_extent_bits(&root->fs_info->freed_extents[0],
194                           start, end, EXTENT_UPTODATE, GFP_NOFS);
195         clear_extent_bits(&root->fs_info->freed_extents[1],
196                           start, end, EXTENT_UPTODATE, GFP_NOFS);
197 }
198
199 static int exclude_super_stripes(struct btrfs_root *root,
200                                  struct btrfs_block_group_cache *cache)
201 {
202         u64 bytenr;
203         u64 *logical;
204         int stripe_len;
205         int i, nr, ret;
206
207         if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
208                 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
209                 cache->bytes_super += stripe_len;
210                 ret = add_excluded_extent(root, cache->key.objectid,
211                                           stripe_len);
212                 BUG_ON(ret);
213         }
214
215         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
216                 bytenr = btrfs_sb_offset(i);
217                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
218                                        cache->key.objectid, bytenr,
219                                        0, &logical, &nr, &stripe_len);
220                 BUG_ON(ret);
221
222                 while (nr--) {
223                         cache->bytes_super += stripe_len;
224                         ret = add_excluded_extent(root, logical[nr],
225                                                   stripe_len);
226                         BUG_ON(ret);
227                 }
228
229                 kfree(logical);
230         }
231         return 0;
232 }
233
234 static struct btrfs_caching_control *
235 get_caching_control(struct btrfs_block_group_cache *cache)
236 {
237         struct btrfs_caching_control *ctl;
238
239         spin_lock(&cache->lock);
240         if (cache->cached != BTRFS_CACHE_STARTED) {
241                 spin_unlock(&cache->lock);
242                 return NULL;
243         }
244
245         /* We're loading it the fast way, so we don't have a caching_ctl. */
246         if (!cache->caching_ctl) {
247                 spin_unlock(&cache->lock);
248                 return NULL;
249         }
250
251         ctl = cache->caching_ctl;
252         atomic_inc(&ctl->count);
253         spin_unlock(&cache->lock);
254         return ctl;
255 }
256
257 static void put_caching_control(struct btrfs_caching_control *ctl)
258 {
259         if (atomic_dec_and_test(&ctl->count))
260                 kfree(ctl);
261 }
262
263 /*
264  * this is only called by cache_block_group, since we could have freed extents
265  * we need to check the pinned_extents for any extents that can't be used yet
266  * since their free space will be released as soon as the transaction commits.
267  */
268 static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
269                               struct btrfs_fs_info *info, u64 start, u64 end)
270 {
271         u64 extent_start, extent_end, size, total_added = 0;
272         int ret;
273
274         while (start < end) {
275                 ret = find_first_extent_bit(info->pinned_extents, start,
276                                             &extent_start, &extent_end,
277                                             EXTENT_DIRTY | EXTENT_UPTODATE);
278                 if (ret)
279                         break;
280
281                 if (extent_start <= start) {
282                         start = extent_end + 1;
283                 } else if (extent_start > start && extent_start < end) {
284                         size = extent_start - start;
285                         total_added += size;
286                         ret = btrfs_add_free_space(block_group, start,
287                                                    size);
288                         BUG_ON(ret);
289                         start = extent_end + 1;
290                 } else {
291                         break;
292                 }
293         }
294
295         if (start < end) {
296                 size = end - start;
297                 total_added += size;
298                 ret = btrfs_add_free_space(block_group, start, size);
299                 BUG_ON(ret);
300         }
301
302         return total_added;
303 }
304
305 static int caching_kthread(void *data)
306 {
307         struct btrfs_block_group_cache *block_group = data;
308         struct btrfs_fs_info *fs_info = block_group->fs_info;
309         struct btrfs_caching_control *caching_ctl = block_group->caching_ctl;
310         struct btrfs_root *extent_root = fs_info->extent_root;
311         struct btrfs_path *path;
312         struct extent_buffer *leaf;
313         struct btrfs_key key;
314         u64 total_found = 0;
315         u64 last = 0;
316         u32 nritems;
317         int ret = 0;
318
319         path = btrfs_alloc_path();
320         if (!path)
321                 return -ENOMEM;
322
323         exclude_super_stripes(extent_root, block_group);
324         spin_lock(&block_group->space_info->lock);
325         block_group->space_info->bytes_readonly += block_group->bytes_super;
326         spin_unlock(&block_group->space_info->lock);
327
328         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
329
330         /*
331          * We don't want to deadlock with somebody trying to allocate a new
332          * extent for the extent root while also trying to search the extent
333          * root to add free space.  So we skip locking and search the commit
334          * root, since its read-only
335          */
336         path->skip_locking = 1;
337         path->search_commit_root = 1;
338         path->reada = 2;
339
340         key.objectid = last;
341         key.offset = 0;
342         key.type = BTRFS_EXTENT_ITEM_KEY;
343 again:
344         mutex_lock(&caching_ctl->mutex);
345         /* need to make sure the commit_root doesn't disappear */
346         down_read(&fs_info->extent_commit_sem);
347
348         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
349         if (ret < 0)
350                 goto err;
351
352         leaf = path->nodes[0];
353         nritems = btrfs_header_nritems(leaf);
354
355         while (1) {
356                 smp_mb();
357                 if (fs_info->closing > 1) {
358                         last = (u64)-1;
359                         break;
360                 }
361
362                 if (path->slots[0] < nritems) {
363                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
364                 } else {
365                         ret = find_next_key(path, 0, &key);
366                         if (ret)
367                                 break;
368
369                         caching_ctl->progress = last;
370                         btrfs_release_path(extent_root, path);
371                         up_read(&fs_info->extent_commit_sem);
372                         mutex_unlock(&caching_ctl->mutex);
373                         if (btrfs_transaction_in_commit(fs_info))
374                                 schedule_timeout(1);
375                         else
376                                 cond_resched();
377                         goto again;
378                 }
379
380                 if (key.objectid < block_group->key.objectid) {
381                         path->slots[0]++;
382                         continue;
383                 }
384
385                 if (key.objectid >= block_group->key.objectid +
386                     block_group->key.offset)
387                         break;
388
389                 if (key.type == BTRFS_EXTENT_ITEM_KEY) {
390                         total_found += add_new_free_space(block_group,
391                                                           fs_info, last,
392                                                           key.objectid);
393                         last = key.objectid + key.offset;
394
395                         if (total_found > (1024 * 1024 * 2)) {
396                                 total_found = 0;
397                                 wake_up(&caching_ctl->wait);
398                         }
399                 }
400                 path->slots[0]++;
401         }
402         ret = 0;
403
404         total_found += add_new_free_space(block_group, fs_info, last,
405                                           block_group->key.objectid +
406                                           block_group->key.offset);
407         caching_ctl->progress = (u64)-1;
408
409         spin_lock(&block_group->lock);
410         block_group->caching_ctl = NULL;
411         block_group->cached = BTRFS_CACHE_FINISHED;
412         spin_unlock(&block_group->lock);
413
414 err:
415         btrfs_free_path(path);
416         up_read(&fs_info->extent_commit_sem);
417
418         free_excluded_extents(extent_root, block_group);
419
420         mutex_unlock(&caching_ctl->mutex);
421         wake_up(&caching_ctl->wait);
422
423         put_caching_control(caching_ctl);
424         atomic_dec(&block_group->space_info->caching_threads);
425         btrfs_put_block_group(block_group);
426
427         return 0;
428 }
429
430 static int cache_block_group(struct btrfs_block_group_cache *cache,
431                              struct btrfs_trans_handle *trans,
432                              struct btrfs_root *root,
433                              int load_cache_only)
434 {
435         struct btrfs_fs_info *fs_info = cache->fs_info;
436         struct btrfs_caching_control *caching_ctl;
437         struct task_struct *tsk;
438         int ret = 0;
439
440         smp_mb();
441         if (cache->cached != BTRFS_CACHE_NO)
442                 return 0;
443
444         /*
445          * We can't do the read from on-disk cache during a commit since we need
446          * to have the normal tree locking.  Also if we are currently trying to
447          * allocate blocks for the tree root we can't do the fast caching since
448          * we likely hold important locks.
449          */
450         if (!trans->transaction->in_commit &&
451             (root && root != root->fs_info->tree_root)) {
452                 spin_lock(&cache->lock);
453                 if (cache->cached != BTRFS_CACHE_NO) {
454                         spin_unlock(&cache->lock);
455                         return 0;
456                 }
457                 cache->cached = BTRFS_CACHE_STARTED;
458                 spin_unlock(&cache->lock);
459
460                 ret = load_free_space_cache(fs_info, cache);
461
462                 spin_lock(&cache->lock);
463                 if (ret == 1) {
464                         cache->cached = BTRFS_CACHE_FINISHED;
465                         cache->last_byte_to_unpin = (u64)-1;
466                 } else {
467                         cache->cached = BTRFS_CACHE_NO;
468                 }
469                 spin_unlock(&cache->lock);
470                 if (ret == 1)
471                         return 0;
472         }
473
474         if (load_cache_only)
475                 return 0;
476
477         caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_KERNEL);
478         BUG_ON(!caching_ctl);
479
480         INIT_LIST_HEAD(&caching_ctl->list);
481         mutex_init(&caching_ctl->mutex);
482         init_waitqueue_head(&caching_ctl->wait);
483         caching_ctl->block_group = cache;
484         caching_ctl->progress = cache->key.objectid;
485         /* one for caching kthread, one for caching block group list */
486         atomic_set(&caching_ctl->count, 2);
487
488         spin_lock(&cache->lock);
489         if (cache->cached != BTRFS_CACHE_NO) {
490                 spin_unlock(&cache->lock);
491                 kfree(caching_ctl);
492                 return 0;
493         }
494         cache->caching_ctl = caching_ctl;
495         cache->cached = BTRFS_CACHE_STARTED;
496         spin_unlock(&cache->lock);
497
498         down_write(&fs_info->extent_commit_sem);
499         list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
500         up_write(&fs_info->extent_commit_sem);
501
502         atomic_inc(&cache->space_info->caching_threads);
503         btrfs_get_block_group(cache);
504
505         tsk = kthread_run(caching_kthread, cache, "btrfs-cache-%llu\n",
506                           cache->key.objectid);
507         if (IS_ERR(tsk)) {
508                 ret = PTR_ERR(tsk);
509                 printk(KERN_ERR "error running thread %d\n", ret);
510                 BUG();
511         }
512
513         return ret;
514 }
515
516 /*
517  * return the block group that starts at or after bytenr
518  */
519 static struct btrfs_block_group_cache *
520 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
521 {
522         struct btrfs_block_group_cache *cache;
523
524         cache = block_group_cache_tree_search(info, bytenr, 0);
525
526         return cache;
527 }
528
529 /*
530  * return the block group that contains the given bytenr
531  */
532 struct btrfs_block_group_cache *btrfs_lookup_block_group(
533                                                  struct btrfs_fs_info *info,
534                                                  u64 bytenr)
535 {
536         struct btrfs_block_group_cache *cache;
537
538         cache = block_group_cache_tree_search(info, bytenr, 1);
539
540         return cache;
541 }
542
543 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
544                                                   u64 flags)
545 {
546         struct list_head *head = &info->space_info;
547         struct btrfs_space_info *found;
548
549         flags &= BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_SYSTEM |
550                  BTRFS_BLOCK_GROUP_METADATA;
551
552         rcu_read_lock();
553         list_for_each_entry_rcu(found, head, list) {
554                 if (found->flags & flags) {
555                         rcu_read_unlock();
556                         return found;
557                 }
558         }
559         rcu_read_unlock();
560         return NULL;
561 }
562
563 /*
564  * after adding space to the filesystem, we need to clear the full flags
565  * on all the space infos.
566  */
567 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
568 {
569         struct list_head *head = &info->space_info;
570         struct btrfs_space_info *found;
571
572         rcu_read_lock();
573         list_for_each_entry_rcu(found, head, list)
574                 found->full = 0;
575         rcu_read_unlock();
576 }
577
578 static u64 div_factor(u64 num, int factor)
579 {
580         if (factor == 10)
581                 return num;
582         num *= factor;
583         do_div(num, 10);
584         return num;
585 }
586
587 static u64 div_factor_fine(u64 num, int factor)
588 {
589         if (factor == 100)
590                 return num;
591         num *= factor;
592         do_div(num, 100);
593         return num;
594 }
595
596 u64 btrfs_find_block_group(struct btrfs_root *root,
597                            u64 search_start, u64 search_hint, int owner)
598 {
599         struct btrfs_block_group_cache *cache;
600         u64 used;
601         u64 last = max(search_hint, search_start);
602         u64 group_start = 0;
603         int full_search = 0;
604         int factor = 9;
605         int wrapped = 0;
606 again:
607         while (1) {
608                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
609                 if (!cache)
610                         break;
611
612                 spin_lock(&cache->lock);
613                 last = cache->key.objectid + cache->key.offset;
614                 used = btrfs_block_group_used(&cache->item);
615
616                 if ((full_search || !cache->ro) &&
617                     block_group_bits(cache, BTRFS_BLOCK_GROUP_METADATA)) {
618                         if (used + cache->pinned + cache->reserved <
619                             div_factor(cache->key.offset, factor)) {
620                                 group_start = cache->key.objectid;
621                                 spin_unlock(&cache->lock);
622                                 btrfs_put_block_group(cache);
623                                 goto found;
624                         }
625                 }
626                 spin_unlock(&cache->lock);
627                 btrfs_put_block_group(cache);
628                 cond_resched();
629         }
630         if (!wrapped) {
631                 last = search_start;
632                 wrapped = 1;
633                 goto again;
634         }
635         if (!full_search && factor < 10) {
636                 last = search_start;
637                 full_search = 1;
638                 factor = 10;
639                 goto again;
640         }
641 found:
642         return group_start;
643 }
644
645 /* simple helper to search for an existing extent at a given offset */
646 int btrfs_lookup_extent(struct btrfs_root *root, u64 start, u64 len)
647 {
648         int ret;
649         struct btrfs_key key;
650         struct btrfs_path *path;
651
652         path = btrfs_alloc_path();
653         BUG_ON(!path);
654         key.objectid = start;
655         key.offset = len;
656         btrfs_set_key_type(&key, BTRFS_EXTENT_ITEM_KEY);
657         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
658                                 0, 0);
659         btrfs_free_path(path);
660         return ret;
661 }
662
663 /*
664  * helper function to lookup reference count and flags of extent.
665  *
666  * the head node for delayed ref is used to store the sum of all the
667  * reference count modifications queued up in the rbtree. the head
668  * node may also store the extent flags to set. This way you can check
669  * to see what the reference count and extent flags would be if all of
670  * the delayed refs are not processed.
671  */
672 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
673                              struct btrfs_root *root, u64 bytenr,
674                              u64 num_bytes, u64 *refs, u64 *flags)
675 {
676         struct btrfs_delayed_ref_head *head;
677         struct btrfs_delayed_ref_root *delayed_refs;
678         struct btrfs_path *path;
679         struct btrfs_extent_item *ei;
680         struct extent_buffer *leaf;
681         struct btrfs_key key;
682         u32 item_size;
683         u64 num_refs;
684         u64 extent_flags;
685         int ret;
686
687         path = btrfs_alloc_path();
688         if (!path)
689                 return -ENOMEM;
690
691         key.objectid = bytenr;
692         key.type = BTRFS_EXTENT_ITEM_KEY;
693         key.offset = num_bytes;
694         if (!trans) {
695                 path->skip_locking = 1;
696                 path->search_commit_root = 1;
697         }
698 again:
699         ret = btrfs_search_slot(trans, root->fs_info->extent_root,
700                                 &key, path, 0, 0);
701         if (ret < 0)
702                 goto out_free;
703
704         if (ret == 0) {
705                 leaf = path->nodes[0];
706                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
707                 if (item_size >= sizeof(*ei)) {
708                         ei = btrfs_item_ptr(leaf, path->slots[0],
709                                             struct btrfs_extent_item);
710                         num_refs = btrfs_extent_refs(leaf, ei);
711                         extent_flags = btrfs_extent_flags(leaf, ei);
712                 } else {
713 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
714                         struct btrfs_extent_item_v0 *ei0;
715                         BUG_ON(item_size != sizeof(*ei0));
716                         ei0 = btrfs_item_ptr(leaf, path->slots[0],
717                                              struct btrfs_extent_item_v0);
718                         num_refs = btrfs_extent_refs_v0(leaf, ei0);
719                         /* FIXME: this isn't correct for data */
720                         extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
721 #else
722                         BUG();
723 #endif
724                 }
725                 BUG_ON(num_refs == 0);
726         } else {
727                 num_refs = 0;
728                 extent_flags = 0;
729                 ret = 0;
730         }
731
732         if (!trans)
733                 goto out;
734
735         delayed_refs = &trans->transaction->delayed_refs;
736         spin_lock(&delayed_refs->lock);
737         head = btrfs_find_delayed_ref_head(trans, bytenr);
738         if (head) {
739                 if (!mutex_trylock(&head->mutex)) {
740                         atomic_inc(&head->node.refs);
741                         spin_unlock(&delayed_refs->lock);
742
743                         btrfs_release_path(root->fs_info->extent_root, path);
744
745                         mutex_lock(&head->mutex);
746                         mutex_unlock(&head->mutex);
747                         btrfs_put_delayed_ref(&head->node);
748                         goto again;
749                 }
750                 if (head->extent_op && head->extent_op->update_flags)
751                         extent_flags |= head->extent_op->flags_to_set;
752                 else
753                         BUG_ON(num_refs == 0);
754
755                 num_refs += head->node.ref_mod;
756                 mutex_unlock(&head->mutex);
757         }
758         spin_unlock(&delayed_refs->lock);
759 out:
760         WARN_ON(num_refs == 0);
761         if (refs)
762                 *refs = num_refs;
763         if (flags)
764                 *flags = extent_flags;
765 out_free:
766         btrfs_free_path(path);
767         return ret;
768 }
769
770 /*
771  * Back reference rules.  Back refs have three main goals:
772  *
773  * 1) differentiate between all holders of references to an extent so that
774  *    when a reference is dropped we can make sure it was a valid reference
775  *    before freeing the extent.
776  *
777  * 2) Provide enough information to quickly find the holders of an extent
778  *    if we notice a given block is corrupted or bad.
779  *
780  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
781  *    maintenance.  This is actually the same as #2, but with a slightly
782  *    different use case.
783  *
784  * There are two kinds of back refs. The implicit back refs is optimized
785  * for pointers in non-shared tree blocks. For a given pointer in a block,
786  * back refs of this kind provide information about the block's owner tree
787  * and the pointer's key. These information allow us to find the block by
788  * b-tree searching. The full back refs is for pointers in tree blocks not
789  * referenced by their owner trees. The location of tree block is recorded
790  * in the back refs. Actually the full back refs is generic, and can be
791  * used in all cases the implicit back refs is used. The major shortcoming
792  * of the full back refs is its overhead. Every time a tree block gets
793  * COWed, we have to update back refs entry for all pointers in it.
794  *
795  * For a newly allocated tree block, we use implicit back refs for
796  * pointers in it. This means most tree related operations only involve
797  * implicit back refs. For a tree block created in old transaction, the
798  * only way to drop a reference to it is COW it. So we can detect the
799  * event that tree block loses its owner tree's reference and do the
800  * back refs conversion.
801  *
802  * When a tree block is COW'd through a tree, there are four cases:
803  *
804  * The reference count of the block is one and the tree is the block's
805  * owner tree. Nothing to do in this case.
806  *
807  * The reference count of the block is one and the tree is not the
808  * block's owner tree. In this case, full back refs is used for pointers
809  * in the block. Remove these full back refs, add implicit back refs for
810  * every pointers in the new block.
811  *
812  * The reference count of the block is greater than one and the tree is
813  * the block's owner tree. In this case, implicit back refs is used for
814  * pointers in the block. Add full back refs for every pointers in the
815  * block, increase lower level extents' reference counts. The original
816  * implicit back refs are entailed to the new block.
817  *
818  * The reference count of the block is greater than one and the tree is
819  * not the block's owner tree. Add implicit back refs for every pointer in
820  * the new block, increase lower level extents' reference count.
821  *
822  * Back Reference Key composing:
823  *
824  * The key objectid corresponds to the first byte in the extent,
825  * The key type is used to differentiate between types of back refs.
826  * There are different meanings of the key offset for different types
827  * of back refs.
828  *
829  * File extents can be referenced by:
830  *
831  * - multiple snapshots, subvolumes, or different generations in one subvol
832  * - different files inside a single subvolume
833  * - different offsets inside a file (bookend extents in file.c)
834  *
835  * The extent ref structure for the implicit back refs has fields for:
836  *
837  * - Objectid of the subvolume root
838  * - objectid of the file holding the reference
839  * - original offset in the file
840  * - how many bookend extents
841  *
842  * The key offset for the implicit back refs is hash of the first
843  * three fields.
844  *
845  * The extent ref structure for the full back refs has field for:
846  *
847  * - number of pointers in the tree leaf
848  *
849  * The key offset for the implicit back refs is the first byte of
850  * the tree leaf
851  *
852  * When a file extent is allocated, The implicit back refs is used.
853  * the fields are filled in:
854  *
855  *     (root_key.objectid, inode objectid, offset in file, 1)
856  *
857  * When a file extent is removed file truncation, we find the
858  * corresponding implicit back refs and check the following fields:
859  *
860  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
861  *
862  * Btree extents can be referenced by:
863  *
864  * - Different subvolumes
865  *
866  * Both the implicit back refs and the full back refs for tree blocks
867  * only consist of key. The key offset for the implicit back refs is
868  * objectid of block's owner tree. The key offset for the full back refs
869  * is the first byte of parent block.
870  *
871  * When implicit back refs is used, information about the lowest key and
872  * level of the tree block are required. These information are stored in
873  * tree block info structure.
874  */
875
876 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
877 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
878                                   struct btrfs_root *root,
879                                   struct btrfs_path *path,
880                                   u64 owner, u32 extra_size)
881 {
882         struct btrfs_extent_item *item;
883         struct btrfs_extent_item_v0 *ei0;
884         struct btrfs_extent_ref_v0 *ref0;
885         struct btrfs_tree_block_info *bi;
886         struct extent_buffer *leaf;
887         struct btrfs_key key;
888         struct btrfs_key found_key;
889         u32 new_size = sizeof(*item);
890         u64 refs;
891         int ret;
892
893         leaf = path->nodes[0];
894         BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
895
896         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
897         ei0 = btrfs_item_ptr(leaf, path->slots[0],
898                              struct btrfs_extent_item_v0);
899         refs = btrfs_extent_refs_v0(leaf, ei0);
900
901         if (owner == (u64)-1) {
902                 while (1) {
903                         if (path->slots[0] >= btrfs_header_nritems(leaf)) {
904                                 ret = btrfs_next_leaf(root, path);
905                                 if (ret < 0)
906                                         return ret;
907                                 BUG_ON(ret > 0);
908                                 leaf = path->nodes[0];
909                         }
910                         btrfs_item_key_to_cpu(leaf, &found_key,
911                                               path->slots[0]);
912                         BUG_ON(key.objectid != found_key.objectid);
913                         if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
914                                 path->slots[0]++;
915                                 continue;
916                         }
917                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
918                                               struct btrfs_extent_ref_v0);
919                         owner = btrfs_ref_objectid_v0(leaf, ref0);
920                         break;
921                 }
922         }
923         btrfs_release_path(root, path);
924
925         if (owner < BTRFS_FIRST_FREE_OBJECTID)
926                 new_size += sizeof(*bi);
927
928         new_size -= sizeof(*ei0);
929         ret = btrfs_search_slot(trans, root, &key, path,
930                                 new_size + extra_size, 1);
931         if (ret < 0)
932                 return ret;
933         BUG_ON(ret);
934
935         ret = btrfs_extend_item(trans, root, path, new_size);
936         BUG_ON(ret);
937
938         leaf = path->nodes[0];
939         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
940         btrfs_set_extent_refs(leaf, item, refs);
941         /* FIXME: get real generation */
942         btrfs_set_extent_generation(leaf, item, 0);
943         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
944                 btrfs_set_extent_flags(leaf, item,
945                                        BTRFS_EXTENT_FLAG_TREE_BLOCK |
946                                        BTRFS_BLOCK_FLAG_FULL_BACKREF);
947                 bi = (struct btrfs_tree_block_info *)(item + 1);
948                 /* FIXME: get first key of the block */
949                 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
950                 btrfs_set_tree_block_level(leaf, bi, (int)owner);
951         } else {
952                 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
953         }
954         btrfs_mark_buffer_dirty(leaf);
955         return 0;
956 }
957 #endif
958
959 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
960 {
961         u32 high_crc = ~(u32)0;
962         u32 low_crc = ~(u32)0;
963         __le64 lenum;
964
965         lenum = cpu_to_le64(root_objectid);
966         high_crc = crc32c(high_crc, &lenum, sizeof(lenum));
967         lenum = cpu_to_le64(owner);
968         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
969         lenum = cpu_to_le64(offset);
970         low_crc = crc32c(low_crc, &lenum, sizeof(lenum));
971
972         return ((u64)high_crc << 31) ^ (u64)low_crc;
973 }
974
975 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
976                                      struct btrfs_extent_data_ref *ref)
977 {
978         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
979                                     btrfs_extent_data_ref_objectid(leaf, ref),
980                                     btrfs_extent_data_ref_offset(leaf, ref));
981 }
982
983 static int match_extent_data_ref(struct extent_buffer *leaf,
984                                  struct btrfs_extent_data_ref *ref,
985                                  u64 root_objectid, u64 owner, u64 offset)
986 {
987         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
988             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
989             btrfs_extent_data_ref_offset(leaf, ref) != offset)
990                 return 0;
991         return 1;
992 }
993
994 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
995                                            struct btrfs_root *root,
996                                            struct btrfs_path *path,
997                                            u64 bytenr, u64 parent,
998                                            u64 root_objectid,
999                                            u64 owner, u64 offset)
1000 {
1001         struct btrfs_key key;
1002         struct btrfs_extent_data_ref *ref;
1003         struct extent_buffer *leaf;
1004         u32 nritems;
1005         int ret;
1006         int recow;
1007         int err = -ENOENT;
1008
1009         key.objectid = bytenr;
1010         if (parent) {
1011                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1012                 key.offset = parent;
1013         } else {
1014                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1015                 key.offset = hash_extent_data_ref(root_objectid,
1016                                                   owner, offset);
1017         }
1018 again:
1019         recow = 0;
1020         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1021         if (ret < 0) {
1022                 err = ret;
1023                 goto fail;
1024         }
1025
1026         if (parent) {
1027                 if (!ret)
1028                         return 0;
1029 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1030                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1031                 btrfs_release_path(root, path);
1032                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1033                 if (ret < 0) {
1034                         err = ret;
1035                         goto fail;
1036                 }
1037                 if (!ret)
1038                         return 0;
1039 #endif
1040                 goto fail;
1041         }
1042
1043         leaf = path->nodes[0];
1044         nritems = btrfs_header_nritems(leaf);
1045         while (1) {
1046                 if (path->slots[0] >= nritems) {
1047                         ret = btrfs_next_leaf(root, path);
1048                         if (ret < 0)
1049                                 err = ret;
1050                         if (ret)
1051                                 goto fail;
1052
1053                         leaf = path->nodes[0];
1054                         nritems = btrfs_header_nritems(leaf);
1055                         recow = 1;
1056                 }
1057
1058                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1059                 if (key.objectid != bytenr ||
1060                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1061                         goto fail;
1062
1063                 ref = btrfs_item_ptr(leaf, path->slots[0],
1064                                      struct btrfs_extent_data_ref);
1065
1066                 if (match_extent_data_ref(leaf, ref, root_objectid,
1067                                           owner, offset)) {
1068                         if (recow) {
1069                                 btrfs_release_path(root, path);
1070                                 goto again;
1071                         }
1072                         err = 0;
1073                         break;
1074                 }
1075                 path->slots[0]++;
1076         }
1077 fail:
1078         return err;
1079 }
1080
1081 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1082                                            struct btrfs_root *root,
1083                                            struct btrfs_path *path,
1084                                            u64 bytenr, u64 parent,
1085                                            u64 root_objectid, u64 owner,
1086                                            u64 offset, int refs_to_add)
1087 {
1088         struct btrfs_key key;
1089         struct extent_buffer *leaf;
1090         u32 size;
1091         u32 num_refs;
1092         int ret;
1093
1094         key.objectid = bytenr;
1095         if (parent) {
1096                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1097                 key.offset = parent;
1098                 size = sizeof(struct btrfs_shared_data_ref);
1099         } else {
1100                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1101                 key.offset = hash_extent_data_ref(root_objectid,
1102                                                   owner, offset);
1103                 size = sizeof(struct btrfs_extent_data_ref);
1104         }
1105
1106         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1107         if (ret && ret != -EEXIST)
1108                 goto fail;
1109
1110         leaf = path->nodes[0];
1111         if (parent) {
1112                 struct btrfs_shared_data_ref *ref;
1113                 ref = btrfs_item_ptr(leaf, path->slots[0],
1114                                      struct btrfs_shared_data_ref);
1115                 if (ret == 0) {
1116                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1117                 } else {
1118                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1119                         num_refs += refs_to_add;
1120                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1121                 }
1122         } else {
1123                 struct btrfs_extent_data_ref *ref;
1124                 while (ret == -EEXIST) {
1125                         ref = btrfs_item_ptr(leaf, path->slots[0],
1126                                              struct btrfs_extent_data_ref);
1127                         if (match_extent_data_ref(leaf, ref, root_objectid,
1128                                                   owner, offset))
1129                                 break;
1130                         btrfs_release_path(root, path);
1131                         key.offset++;
1132                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1133                                                       size);
1134                         if (ret && ret != -EEXIST)
1135                                 goto fail;
1136
1137                         leaf = path->nodes[0];
1138                 }
1139                 ref = btrfs_item_ptr(leaf, path->slots[0],
1140                                      struct btrfs_extent_data_ref);
1141                 if (ret == 0) {
1142                         btrfs_set_extent_data_ref_root(leaf, ref,
1143                                                        root_objectid);
1144                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1145                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1146                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1147                 } else {
1148                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1149                         num_refs += refs_to_add;
1150                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1151                 }
1152         }
1153         btrfs_mark_buffer_dirty(leaf);
1154         ret = 0;
1155 fail:
1156         btrfs_release_path(root, path);
1157         return ret;
1158 }
1159
1160 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1161                                            struct btrfs_root *root,
1162                                            struct btrfs_path *path,
1163                                            int refs_to_drop)
1164 {
1165         struct btrfs_key key;
1166         struct btrfs_extent_data_ref *ref1 = NULL;
1167         struct btrfs_shared_data_ref *ref2 = NULL;
1168         struct extent_buffer *leaf;
1169         u32 num_refs = 0;
1170         int ret = 0;
1171
1172         leaf = path->nodes[0];
1173         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1174
1175         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1176                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1177                                       struct btrfs_extent_data_ref);
1178                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1179         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1180                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1181                                       struct btrfs_shared_data_ref);
1182                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1183 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1184         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1185                 struct btrfs_extent_ref_v0 *ref0;
1186                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1187                                       struct btrfs_extent_ref_v0);
1188                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1189 #endif
1190         } else {
1191                 BUG();
1192         }
1193
1194         BUG_ON(num_refs < refs_to_drop);
1195         num_refs -= refs_to_drop;
1196
1197         if (num_refs == 0) {
1198                 ret = btrfs_del_item(trans, root, path);
1199         } else {
1200                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1201                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1202                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1203                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1204 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1205                 else {
1206                         struct btrfs_extent_ref_v0 *ref0;
1207                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1208                                         struct btrfs_extent_ref_v0);
1209                         btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1210                 }
1211 #endif
1212                 btrfs_mark_buffer_dirty(leaf);
1213         }
1214         return ret;
1215 }
1216
1217 static noinline u32 extent_data_ref_count(struct btrfs_root *root,
1218                                           struct btrfs_path *path,
1219                                           struct btrfs_extent_inline_ref *iref)
1220 {
1221         struct btrfs_key key;
1222         struct extent_buffer *leaf;
1223         struct btrfs_extent_data_ref *ref1;
1224         struct btrfs_shared_data_ref *ref2;
1225         u32 num_refs = 0;
1226
1227         leaf = path->nodes[0];
1228         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1229         if (iref) {
1230                 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1231                     BTRFS_EXTENT_DATA_REF_KEY) {
1232                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1233                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1234                 } else {
1235                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1236                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1237                 }
1238         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1239                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1240                                       struct btrfs_extent_data_ref);
1241                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1242         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1243                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1244                                       struct btrfs_shared_data_ref);
1245                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1246 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1247         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1248                 struct btrfs_extent_ref_v0 *ref0;
1249                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1250                                       struct btrfs_extent_ref_v0);
1251                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1252 #endif
1253         } else {
1254                 WARN_ON(1);
1255         }
1256         return num_refs;
1257 }
1258
1259 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1260                                           struct btrfs_root *root,
1261                                           struct btrfs_path *path,
1262                                           u64 bytenr, u64 parent,
1263                                           u64 root_objectid)
1264 {
1265         struct btrfs_key key;
1266         int ret;
1267
1268         key.objectid = bytenr;
1269         if (parent) {
1270                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1271                 key.offset = parent;
1272         } else {
1273                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1274                 key.offset = root_objectid;
1275         }
1276
1277         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1278         if (ret > 0)
1279                 ret = -ENOENT;
1280 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1281         if (ret == -ENOENT && parent) {
1282                 btrfs_release_path(root, path);
1283                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1284                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1285                 if (ret > 0)
1286                         ret = -ENOENT;
1287         }
1288 #endif
1289         return ret;
1290 }
1291
1292 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1293                                           struct btrfs_root *root,
1294                                           struct btrfs_path *path,
1295                                           u64 bytenr, u64 parent,
1296                                           u64 root_objectid)
1297 {
1298         struct btrfs_key key;
1299         int ret;
1300
1301         key.objectid = bytenr;
1302         if (parent) {
1303                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1304                 key.offset = parent;
1305         } else {
1306                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1307                 key.offset = root_objectid;
1308         }
1309
1310         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1311         btrfs_release_path(root, path);
1312         return ret;
1313 }
1314
1315 static inline int extent_ref_type(u64 parent, u64 owner)
1316 {
1317         int type;
1318         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1319                 if (parent > 0)
1320                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1321                 else
1322                         type = BTRFS_TREE_BLOCK_REF_KEY;
1323         } else {
1324                 if (parent > 0)
1325                         type = BTRFS_SHARED_DATA_REF_KEY;
1326                 else
1327                         type = BTRFS_EXTENT_DATA_REF_KEY;
1328         }
1329         return type;
1330 }
1331
1332 static int find_next_key(struct btrfs_path *path, int level,
1333                          struct btrfs_key *key)
1334
1335 {
1336         for (; level < BTRFS_MAX_LEVEL; level++) {
1337                 if (!path->nodes[level])
1338                         break;
1339                 if (path->slots[level] + 1 >=
1340                     btrfs_header_nritems(path->nodes[level]))
1341                         continue;
1342                 if (level == 0)
1343                         btrfs_item_key_to_cpu(path->nodes[level], key,
1344                                               path->slots[level] + 1);
1345                 else
1346                         btrfs_node_key_to_cpu(path->nodes[level], key,
1347                                               path->slots[level] + 1);
1348                 return 0;
1349         }
1350         return 1;
1351 }
1352
1353 /*
1354  * look for inline back ref. if back ref is found, *ref_ret is set
1355  * to the address of inline back ref, and 0 is returned.
1356  *
1357  * if back ref isn't found, *ref_ret is set to the address where it
1358  * should be inserted, and -ENOENT is returned.
1359  *
1360  * if insert is true and there are too many inline back refs, the path
1361  * points to the extent item, and -EAGAIN is returned.
1362  *
1363  * NOTE: inline back refs are ordered in the same way that back ref
1364  *       items in the tree are ordered.
1365  */
1366 static noinline_for_stack
1367 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1368                                  struct btrfs_root *root,
1369                                  struct btrfs_path *path,
1370                                  struct btrfs_extent_inline_ref **ref_ret,
1371                                  u64 bytenr, u64 num_bytes,
1372                                  u64 parent, u64 root_objectid,
1373                                  u64 owner, u64 offset, int insert)
1374 {
1375         struct btrfs_key key;
1376         struct extent_buffer *leaf;
1377         struct btrfs_extent_item *ei;
1378         struct btrfs_extent_inline_ref *iref;
1379         u64 flags;
1380         u64 item_size;
1381         unsigned long ptr;
1382         unsigned long end;
1383         int extra_size;
1384         int type;
1385         int want;
1386         int ret;
1387         int err = 0;
1388
1389         key.objectid = bytenr;
1390         key.type = BTRFS_EXTENT_ITEM_KEY;
1391         key.offset = num_bytes;
1392
1393         want = extent_ref_type(parent, owner);
1394         if (insert) {
1395                 extra_size = btrfs_extent_inline_ref_size(want);
1396                 path->keep_locks = 1;
1397         } else
1398                 extra_size = -1;
1399         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1400         if (ret < 0) {
1401                 err = ret;
1402                 goto out;
1403         }
1404         BUG_ON(ret);
1405
1406         leaf = path->nodes[0];
1407         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1408 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1409         if (item_size < sizeof(*ei)) {
1410                 if (!insert) {
1411                         err = -ENOENT;
1412                         goto out;
1413                 }
1414                 ret = convert_extent_item_v0(trans, root, path, owner,
1415                                              extra_size);
1416                 if (ret < 0) {
1417                         err = ret;
1418                         goto out;
1419                 }
1420                 leaf = path->nodes[0];
1421                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1422         }
1423 #endif
1424         BUG_ON(item_size < sizeof(*ei));
1425
1426         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1427         flags = btrfs_extent_flags(leaf, ei);
1428
1429         ptr = (unsigned long)(ei + 1);
1430         end = (unsigned long)ei + item_size;
1431
1432         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
1433                 ptr += sizeof(struct btrfs_tree_block_info);
1434                 BUG_ON(ptr > end);
1435         } else {
1436                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
1437         }
1438
1439         err = -ENOENT;
1440         while (1) {
1441                 if (ptr >= end) {
1442                         WARN_ON(ptr > end);
1443                         break;
1444                 }
1445                 iref = (struct btrfs_extent_inline_ref *)ptr;
1446                 type = btrfs_extent_inline_ref_type(leaf, iref);
1447                 if (want < type)
1448                         break;
1449                 if (want > type) {
1450                         ptr += btrfs_extent_inline_ref_size(type);
1451                         continue;
1452                 }
1453
1454                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1455                         struct btrfs_extent_data_ref *dref;
1456                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1457                         if (match_extent_data_ref(leaf, dref, root_objectid,
1458                                                   owner, offset)) {
1459                                 err = 0;
1460                                 break;
1461                         }
1462                         if (hash_extent_data_ref_item(leaf, dref) <
1463                             hash_extent_data_ref(root_objectid, owner, offset))
1464                                 break;
1465                 } else {
1466                         u64 ref_offset;
1467                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1468                         if (parent > 0) {
1469                                 if (parent == ref_offset) {
1470                                         err = 0;
1471                                         break;
1472                                 }
1473                                 if (ref_offset < parent)
1474                                         break;
1475                         } else {
1476                                 if (root_objectid == ref_offset) {
1477                                         err = 0;
1478                                         break;
1479                                 }
1480                                 if (ref_offset < root_objectid)
1481                                         break;
1482                         }
1483                 }
1484                 ptr += btrfs_extent_inline_ref_size(type);
1485         }
1486         if (err == -ENOENT && insert) {
1487                 if (item_size + extra_size >=
1488                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1489                         err = -EAGAIN;
1490                         goto out;
1491                 }
1492                 /*
1493                  * To add new inline back ref, we have to make sure
1494                  * there is no corresponding back ref item.
1495                  * For simplicity, we just do not add new inline back
1496                  * ref if there is any kind of item for this block
1497                  */
1498                 if (find_next_key(path, 0, &key) == 0 &&
1499                     key.objectid == bytenr &&
1500                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1501                         err = -EAGAIN;
1502                         goto out;
1503                 }
1504         }
1505         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1506 out:
1507         if (insert) {
1508                 path->keep_locks = 0;
1509                 btrfs_unlock_up_safe(path, 1);
1510         }
1511         return err;
1512 }
1513
1514 /*
1515  * helper to add new inline back ref
1516  */
1517 static noinline_for_stack
1518 int setup_inline_extent_backref(struct btrfs_trans_handle *trans,
1519                                 struct btrfs_root *root,
1520                                 struct btrfs_path *path,
1521                                 struct btrfs_extent_inline_ref *iref,
1522                                 u64 parent, u64 root_objectid,
1523                                 u64 owner, u64 offset, int refs_to_add,
1524                                 struct btrfs_delayed_extent_op *extent_op)
1525 {
1526         struct extent_buffer *leaf;
1527         struct btrfs_extent_item *ei;
1528         unsigned long ptr;
1529         unsigned long end;
1530         unsigned long item_offset;
1531         u64 refs;
1532         int size;
1533         int type;
1534         int ret;
1535
1536         leaf = path->nodes[0];
1537         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1538         item_offset = (unsigned long)iref - (unsigned long)ei;
1539
1540         type = extent_ref_type(parent, owner);
1541         size = btrfs_extent_inline_ref_size(type);
1542
1543         ret = btrfs_extend_item(trans, root, path, size);
1544         BUG_ON(ret);
1545
1546         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1547         refs = btrfs_extent_refs(leaf, ei);
1548         refs += refs_to_add;
1549         btrfs_set_extent_refs(leaf, ei, refs);
1550         if (extent_op)
1551                 __run_delayed_extent_op(extent_op, leaf, ei);
1552
1553         ptr = (unsigned long)ei + item_offset;
1554         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1555         if (ptr < end - size)
1556                 memmove_extent_buffer(leaf, ptr + size, ptr,
1557                                       end - size - ptr);
1558
1559         iref = (struct btrfs_extent_inline_ref *)ptr;
1560         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1561         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1562                 struct btrfs_extent_data_ref *dref;
1563                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1564                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1565                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1566                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1567                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1568         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1569                 struct btrfs_shared_data_ref *sref;
1570                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1571                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1572                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1573         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1574                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1575         } else {
1576                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1577         }
1578         btrfs_mark_buffer_dirty(leaf);
1579         return 0;
1580 }
1581
1582 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1583                                  struct btrfs_root *root,
1584                                  struct btrfs_path *path,
1585                                  struct btrfs_extent_inline_ref **ref_ret,
1586                                  u64 bytenr, u64 num_bytes, u64 parent,
1587                                  u64 root_objectid, u64 owner, u64 offset)
1588 {
1589         int ret;
1590
1591         ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1592                                            bytenr, num_bytes, parent,
1593                                            root_objectid, owner, offset, 0);
1594         if (ret != -ENOENT)
1595                 return ret;
1596
1597         btrfs_release_path(root, path);
1598         *ref_ret = NULL;
1599
1600         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1601                 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1602                                             root_objectid);
1603         } else {
1604                 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1605                                              root_objectid, owner, offset);
1606         }
1607         return ret;
1608 }
1609
1610 /*
1611  * helper to update/remove inline back ref
1612  */
1613 static noinline_for_stack
1614 int update_inline_extent_backref(struct btrfs_trans_handle *trans,
1615                                  struct btrfs_root *root,
1616                                  struct btrfs_path *path,
1617                                  struct btrfs_extent_inline_ref *iref,
1618                                  int refs_to_mod,
1619                                  struct btrfs_delayed_extent_op *extent_op)
1620 {
1621         struct extent_buffer *leaf;
1622         struct btrfs_extent_item *ei;
1623         struct btrfs_extent_data_ref *dref = NULL;
1624         struct btrfs_shared_data_ref *sref = NULL;
1625         unsigned long ptr;
1626         unsigned long end;
1627         u32 item_size;
1628         int size;
1629         int type;
1630         int ret;
1631         u64 refs;
1632
1633         leaf = path->nodes[0];
1634         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1635         refs = btrfs_extent_refs(leaf, ei);
1636         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1637         refs += refs_to_mod;
1638         btrfs_set_extent_refs(leaf, ei, refs);
1639         if (extent_op)
1640                 __run_delayed_extent_op(extent_op, leaf, ei);
1641
1642         type = btrfs_extent_inline_ref_type(leaf, iref);
1643
1644         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1645                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1646                 refs = btrfs_extent_data_ref_count(leaf, dref);
1647         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1648                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1649                 refs = btrfs_shared_data_ref_count(leaf, sref);
1650         } else {
1651                 refs = 1;
1652                 BUG_ON(refs_to_mod != -1);
1653         }
1654
1655         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1656         refs += refs_to_mod;
1657
1658         if (refs > 0) {
1659                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1660                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1661                 else
1662                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1663         } else {
1664                 size =  btrfs_extent_inline_ref_size(type);
1665                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1666                 ptr = (unsigned long)iref;
1667                 end = (unsigned long)ei + item_size;
1668                 if (ptr + size < end)
1669                         memmove_extent_buffer(leaf, ptr, ptr + size,
1670                                               end - ptr - size);
1671                 item_size -= size;
1672                 ret = btrfs_truncate_item(trans, root, path, item_size, 1);
1673                 BUG_ON(ret);
1674         }
1675         btrfs_mark_buffer_dirty(leaf);
1676         return 0;
1677 }
1678
1679 static noinline_for_stack
1680 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1681                                  struct btrfs_root *root,
1682                                  struct btrfs_path *path,
1683                                  u64 bytenr, u64 num_bytes, u64 parent,
1684                                  u64 root_objectid, u64 owner,
1685                                  u64 offset, int refs_to_add,
1686                                  struct btrfs_delayed_extent_op *extent_op)
1687 {
1688         struct btrfs_extent_inline_ref *iref;
1689         int ret;
1690
1691         ret = lookup_inline_extent_backref(trans, root, path, &iref,
1692                                            bytenr, num_bytes, parent,
1693                                            root_objectid, owner, offset, 1);
1694         if (ret == 0) {
1695                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1696                 ret = update_inline_extent_backref(trans, root, path, iref,
1697                                                    refs_to_add, extent_op);
1698         } else if (ret == -ENOENT) {
1699                 ret = setup_inline_extent_backref(trans, root, path, iref,
1700                                                   parent, root_objectid,
1701                                                   owner, offset, refs_to_add,
1702                                                   extent_op);
1703         }
1704         return ret;
1705 }
1706
1707 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1708                                  struct btrfs_root *root,
1709                                  struct btrfs_path *path,
1710                                  u64 bytenr, u64 parent, u64 root_objectid,
1711                                  u64 owner, u64 offset, int refs_to_add)
1712 {
1713         int ret;
1714         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1715                 BUG_ON(refs_to_add != 1);
1716                 ret = insert_tree_block_ref(trans, root, path, bytenr,
1717                                             parent, root_objectid);
1718         } else {
1719                 ret = insert_extent_data_ref(trans, root, path, bytenr,
1720                                              parent, root_objectid,
1721                                              owner, offset, refs_to_add);
1722         }
1723         return ret;
1724 }
1725
1726 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1727                                  struct btrfs_root *root,
1728                                  struct btrfs_path *path,
1729                                  struct btrfs_extent_inline_ref *iref,
1730                                  int refs_to_drop, int is_data)
1731 {
1732         int ret;
1733
1734         BUG_ON(!is_data && refs_to_drop != 1);
1735         if (iref) {
1736                 ret = update_inline_extent_backref(trans, root, path, iref,
1737                                                    -refs_to_drop, NULL);
1738         } else if (is_data) {
1739                 ret = remove_extent_data_ref(trans, root, path, refs_to_drop);
1740         } else {
1741                 ret = btrfs_del_item(trans, root, path);
1742         }
1743         return ret;
1744 }
1745
1746 static void btrfs_issue_discard(struct block_device *bdev,
1747                                 u64 start, u64 len)
1748 {
1749         blkdev_issue_discard(bdev, start >> 9, len >> 9, GFP_KERNEL,
1750                         BLKDEV_IFL_WAIT | BLKDEV_IFL_BARRIER);
1751 }
1752
1753 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1754                                 u64 num_bytes)
1755 {
1756         int ret;
1757         u64 map_length = num_bytes;
1758         struct btrfs_multi_bio *multi = NULL;
1759
1760         if (!btrfs_test_opt(root, DISCARD))
1761                 return 0;
1762
1763         /* Tell the block device(s) that the sectors can be discarded */
1764         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
1765                               bytenr, &map_length, &multi, 0);
1766         if (!ret) {
1767                 struct btrfs_bio_stripe *stripe = multi->stripes;
1768                 int i;
1769
1770                 if (map_length > num_bytes)
1771                         map_length = num_bytes;
1772
1773                 for (i = 0; i < multi->num_stripes; i++, stripe++) {
1774                         btrfs_issue_discard(stripe->dev->bdev,
1775                                             stripe->physical,
1776                                             map_length);
1777                 }
1778                 kfree(multi);
1779         }
1780
1781         return ret;
1782 }
1783
1784 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1785                          struct btrfs_root *root,
1786                          u64 bytenr, u64 num_bytes, u64 parent,
1787                          u64 root_objectid, u64 owner, u64 offset)
1788 {
1789         int ret;
1790         BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1791                root_objectid == BTRFS_TREE_LOG_OBJECTID);
1792
1793         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1794                 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
1795                                         parent, root_objectid, (int)owner,
1796                                         BTRFS_ADD_DELAYED_REF, NULL);
1797         } else {
1798                 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
1799                                         parent, root_objectid, owner, offset,
1800                                         BTRFS_ADD_DELAYED_REF, NULL);
1801         }
1802         return ret;
1803 }
1804
1805 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1806                                   struct btrfs_root *root,
1807                                   u64 bytenr, u64 num_bytes,
1808                                   u64 parent, u64 root_objectid,
1809                                   u64 owner, u64 offset, int refs_to_add,
1810                                   struct btrfs_delayed_extent_op *extent_op)
1811 {
1812         struct btrfs_path *path;
1813         struct extent_buffer *leaf;
1814         struct btrfs_extent_item *item;
1815         u64 refs;
1816         int ret;
1817         int err = 0;
1818
1819         path = btrfs_alloc_path();
1820         if (!path)
1821                 return -ENOMEM;
1822
1823         path->reada = 1;
1824         path->leave_spinning = 1;
1825         /* this will setup the path even if it fails to insert the back ref */
1826         ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1827                                            path, bytenr, num_bytes, parent,
1828                                            root_objectid, owner, offset,
1829                                            refs_to_add, extent_op);
1830         if (ret == 0)
1831                 goto out;
1832
1833         if (ret != -EAGAIN) {
1834                 err = ret;
1835                 goto out;
1836         }
1837
1838         leaf = path->nodes[0];
1839         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1840         refs = btrfs_extent_refs(leaf, item);
1841         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1842         if (extent_op)
1843                 __run_delayed_extent_op(extent_op, leaf, item);
1844
1845         btrfs_mark_buffer_dirty(leaf);
1846         btrfs_release_path(root->fs_info->extent_root, path);
1847
1848         path->reada = 1;
1849         path->leave_spinning = 1;
1850
1851         /* now insert the actual backref */
1852         ret = insert_extent_backref(trans, root->fs_info->extent_root,
1853                                     path, bytenr, parent, root_objectid,
1854                                     owner, offset, refs_to_add);
1855         BUG_ON(ret);
1856 out:
1857         btrfs_free_path(path);
1858         return err;
1859 }
1860
1861 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1862                                 struct btrfs_root *root,
1863                                 struct btrfs_delayed_ref_node *node,
1864                                 struct btrfs_delayed_extent_op *extent_op,
1865                                 int insert_reserved)
1866 {
1867         int ret = 0;
1868         struct btrfs_delayed_data_ref *ref;
1869         struct btrfs_key ins;
1870         u64 parent = 0;
1871         u64 ref_root = 0;
1872         u64 flags = 0;
1873
1874         ins.objectid = node->bytenr;
1875         ins.offset = node->num_bytes;
1876         ins.type = BTRFS_EXTENT_ITEM_KEY;
1877
1878         ref = btrfs_delayed_node_to_data_ref(node);
1879         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1880                 parent = ref->parent;
1881         else
1882                 ref_root = ref->root;
1883
1884         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1885                 if (extent_op) {
1886                         BUG_ON(extent_op->update_key);
1887                         flags |= extent_op->flags_to_set;
1888                 }
1889                 ret = alloc_reserved_file_extent(trans, root,
1890                                                  parent, ref_root, flags,
1891                                                  ref->objectid, ref->offset,
1892                                                  &ins, node->ref_mod);
1893         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1894                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1895                                              node->num_bytes, parent,
1896                                              ref_root, ref->objectid,
1897                                              ref->offset, node->ref_mod,
1898                                              extent_op);
1899         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1900                 ret = __btrfs_free_extent(trans, root, node->bytenr,
1901                                           node->num_bytes, parent,
1902                                           ref_root, ref->objectid,
1903                                           ref->offset, node->ref_mod,
1904                                           extent_op);
1905         } else {
1906                 BUG();
1907         }
1908         return ret;
1909 }
1910
1911 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1912                                     struct extent_buffer *leaf,
1913                                     struct btrfs_extent_item *ei)
1914 {
1915         u64 flags = btrfs_extent_flags(leaf, ei);
1916         if (extent_op->update_flags) {
1917                 flags |= extent_op->flags_to_set;
1918                 btrfs_set_extent_flags(leaf, ei, flags);
1919         }
1920
1921         if (extent_op->update_key) {
1922                 struct btrfs_tree_block_info *bi;
1923                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1924                 bi = (struct btrfs_tree_block_info *)(ei + 1);
1925                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1926         }
1927 }
1928
1929 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1930                                  struct btrfs_root *root,
1931                                  struct btrfs_delayed_ref_node *node,
1932                                  struct btrfs_delayed_extent_op *extent_op)
1933 {
1934         struct btrfs_key key;
1935         struct btrfs_path *path;
1936         struct btrfs_extent_item *ei;
1937         struct extent_buffer *leaf;
1938         u32 item_size;
1939         int ret;
1940         int err = 0;
1941
1942         path = btrfs_alloc_path();
1943         if (!path)
1944                 return -ENOMEM;
1945
1946         key.objectid = node->bytenr;
1947         key.type = BTRFS_EXTENT_ITEM_KEY;
1948         key.offset = node->num_bytes;
1949
1950         path->reada = 1;
1951         path->leave_spinning = 1;
1952         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
1953                                 path, 0, 1);
1954         if (ret < 0) {
1955                 err = ret;
1956                 goto out;
1957         }
1958         if (ret > 0) {
1959                 err = -EIO;
1960                 goto out;
1961         }
1962
1963         leaf = path->nodes[0];
1964         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1965 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1966         if (item_size < sizeof(*ei)) {
1967                 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
1968                                              path, (u64)-1, 0);
1969                 if (ret < 0) {
1970                         err = ret;
1971                         goto out;
1972                 }
1973                 leaf = path->nodes[0];
1974                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1975         }
1976 #endif
1977         BUG_ON(item_size < sizeof(*ei));
1978         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1979         __run_delayed_extent_op(extent_op, leaf, ei);
1980
1981         btrfs_mark_buffer_dirty(leaf);
1982 out:
1983         btrfs_free_path(path);
1984         return err;
1985 }
1986
1987 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1988                                 struct btrfs_root *root,
1989                                 struct btrfs_delayed_ref_node *node,
1990                                 struct btrfs_delayed_extent_op *extent_op,
1991                                 int insert_reserved)
1992 {
1993         int ret = 0;
1994         struct btrfs_delayed_tree_ref *ref;
1995         struct btrfs_key ins;
1996         u64 parent = 0;
1997         u64 ref_root = 0;
1998
1999         ins.objectid = node->bytenr;
2000         ins.offset = node->num_bytes;
2001         ins.type = BTRFS_EXTENT_ITEM_KEY;
2002
2003         ref = btrfs_delayed_node_to_tree_ref(node);
2004         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2005                 parent = ref->parent;
2006         else
2007                 ref_root = ref->root;
2008
2009         BUG_ON(node->ref_mod != 1);
2010         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2011                 BUG_ON(!extent_op || !extent_op->update_flags ||
2012                        !extent_op->update_key);
2013                 ret = alloc_reserved_tree_block(trans, root,
2014                                                 parent, ref_root,
2015                                                 extent_op->flags_to_set,
2016                                                 &extent_op->key,
2017                                                 ref->level, &ins);
2018         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2019                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
2020                                              node->num_bytes, parent, ref_root,
2021                                              ref->level, 0, 1, extent_op);
2022         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2023                 ret = __btrfs_free_extent(trans, root, node->bytenr,
2024                                           node->num_bytes, parent, ref_root,
2025                                           ref->level, 0, 1, extent_op);
2026         } else {
2027                 BUG();
2028         }
2029         return ret;
2030 }
2031
2032 /* helper function to actually process a single delayed ref entry */
2033 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2034                                struct btrfs_root *root,
2035                                struct btrfs_delayed_ref_node *node,
2036                                struct btrfs_delayed_extent_op *extent_op,
2037                                int insert_reserved)
2038 {
2039         int ret;
2040         if (btrfs_delayed_ref_is_head(node)) {
2041                 struct btrfs_delayed_ref_head *head;
2042                 /*
2043                  * we've hit the end of the chain and we were supposed
2044                  * to insert this extent into the tree.  But, it got
2045                  * deleted before we ever needed to insert it, so all
2046                  * we have to do is clean up the accounting
2047                  */
2048                 BUG_ON(extent_op);
2049                 head = btrfs_delayed_node_to_head(node);
2050                 if (insert_reserved) {
2051                         btrfs_pin_extent(root, node->bytenr,
2052                                          node->num_bytes, 1);
2053                         if (head->is_data) {
2054                                 ret = btrfs_del_csums(trans, root,
2055                                                       node->bytenr,
2056                                                       node->num_bytes);
2057                                 BUG_ON(ret);
2058                         }
2059                 }
2060                 mutex_unlock(&head->mutex);
2061                 return 0;
2062         }
2063
2064         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2065             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2066                 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2067                                            insert_reserved);
2068         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2069                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2070                 ret = run_delayed_data_ref(trans, root, node, extent_op,
2071                                            insert_reserved);
2072         else
2073                 BUG();
2074         return ret;
2075 }
2076
2077 static noinline struct btrfs_delayed_ref_node *
2078 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2079 {
2080         struct rb_node *node;
2081         struct btrfs_delayed_ref_node *ref;
2082         int action = BTRFS_ADD_DELAYED_REF;
2083 again:
2084         /*
2085          * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
2086          * this prevents ref count from going down to zero when
2087          * there still are pending delayed ref.
2088          */
2089         node = rb_prev(&head->node.rb_node);
2090         while (1) {
2091                 if (!node)
2092                         break;
2093                 ref = rb_entry(node, struct btrfs_delayed_ref_node,
2094                                 rb_node);
2095                 if (ref->bytenr != head->node.bytenr)
2096                         break;
2097                 if (ref->action == action)
2098                         return ref;
2099                 node = rb_prev(node);
2100         }
2101         if (action == BTRFS_ADD_DELAYED_REF) {
2102                 action = BTRFS_DROP_DELAYED_REF;
2103                 goto again;
2104         }
2105         return NULL;
2106 }
2107
2108 static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
2109                                        struct btrfs_root *root,
2110                                        struct list_head *cluster)
2111 {
2112         struct btrfs_delayed_ref_root *delayed_refs;
2113         struct btrfs_delayed_ref_node *ref;
2114         struct btrfs_delayed_ref_head *locked_ref = NULL;
2115         struct btrfs_delayed_extent_op *extent_op;
2116         int ret;
2117         int count = 0;
2118         int must_insert_reserved = 0;
2119
2120         delayed_refs = &trans->transaction->delayed_refs;
2121         while (1) {
2122                 if (!locked_ref) {
2123                         /* pick a new head ref from the cluster list */
2124                         if (list_empty(cluster))
2125                                 break;
2126
2127                         locked_ref = list_entry(cluster->next,
2128                                      struct btrfs_delayed_ref_head, cluster);
2129
2130                         /* grab the lock that says we are going to process
2131                          * all the refs for this head */
2132                         ret = btrfs_delayed_ref_lock(trans, locked_ref);
2133
2134                         /*
2135                          * we may have dropped the spin lock to get the head
2136                          * mutex lock, and that might have given someone else
2137                          * time to free the head.  If that's true, it has been
2138                          * removed from our list and we can move on.
2139                          */
2140                         if (ret == -EAGAIN) {
2141                                 locked_ref = NULL;
2142                                 count++;
2143                                 continue;
2144                         }
2145                 }
2146
2147                 /*
2148                  * record the must insert reserved flag before we
2149                  * drop the spin lock.
2150                  */
2151                 must_insert_reserved = locked_ref->must_insert_reserved;
2152                 locked_ref->must_insert_reserved = 0;
2153
2154                 extent_op = locked_ref->extent_op;
2155                 locked_ref->extent_op = NULL;
2156
2157                 /*
2158                  * locked_ref is the head node, so we have to go one
2159                  * node back for any delayed ref updates
2160                  */
2161                 ref = select_delayed_ref(locked_ref);
2162                 if (!ref) {
2163                         /* All delayed refs have been processed, Go ahead
2164                          * and send the head node to run_one_delayed_ref,
2165                          * so that any accounting fixes can happen
2166                          */
2167                         ref = &locked_ref->node;
2168
2169                         if (extent_op && must_insert_reserved) {
2170                                 kfree(extent_op);
2171                                 extent_op = NULL;
2172                         }
2173
2174                         if (extent_op) {
2175                                 spin_unlock(&delayed_refs->lock);
2176
2177                                 ret = run_delayed_extent_op(trans, root,
2178                                                             ref, extent_op);
2179                                 BUG_ON(ret);
2180                                 kfree(extent_op);
2181
2182                                 cond_resched();
2183                                 spin_lock(&delayed_refs->lock);
2184                                 continue;
2185                         }
2186
2187                         list_del_init(&locked_ref->cluster);
2188                         locked_ref = NULL;
2189                 }
2190
2191                 ref->in_tree = 0;
2192                 rb_erase(&ref->rb_node, &delayed_refs->root);
2193                 delayed_refs->num_entries--;
2194
2195                 spin_unlock(&delayed_refs->lock);
2196
2197                 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2198                                           must_insert_reserved);
2199                 BUG_ON(ret);
2200
2201                 btrfs_put_delayed_ref(ref);
2202                 kfree(extent_op);
2203                 count++;
2204
2205                 cond_resched();
2206                 spin_lock(&delayed_refs->lock);
2207         }
2208         return count;
2209 }
2210
2211 /*
2212  * this starts processing the delayed reference count updates and
2213  * extent insertions we have queued up so far.  count can be
2214  * 0, which means to process everything in the tree at the start
2215  * of the run (but not newly added entries), or it can be some target
2216  * number you'd like to process.
2217  */
2218 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2219                            struct btrfs_root *root, unsigned long count)
2220 {
2221         struct rb_node *node;
2222         struct btrfs_delayed_ref_root *delayed_refs;
2223         struct btrfs_delayed_ref_node *ref;
2224         struct list_head cluster;
2225         int ret;
2226         int run_all = count == (unsigned long)-1;
2227         int run_most = 0;
2228
2229         if (root == root->fs_info->extent_root)
2230                 root = root->fs_info->tree_root;
2231
2232         delayed_refs = &trans->transaction->delayed_refs;
2233         INIT_LIST_HEAD(&cluster);
2234 again:
2235         spin_lock(&delayed_refs->lock);
2236         if (count == 0) {
2237                 count = delayed_refs->num_entries * 2;
2238                 run_most = 1;
2239         }
2240         while (1) {
2241                 if (!(run_all || run_most) &&
2242                     delayed_refs->num_heads_ready < 64)
2243                         break;
2244
2245                 /*
2246                  * go find something we can process in the rbtree.  We start at
2247                  * the beginning of the tree, and then build a cluster
2248                  * of refs to process starting at the first one we are able to
2249                  * lock
2250                  */
2251                 ret = btrfs_find_ref_cluster(trans, &cluster,
2252                                              delayed_refs->run_delayed_start);
2253                 if (ret)
2254                         break;
2255
2256                 ret = run_clustered_refs(trans, root, &cluster);
2257                 BUG_ON(ret < 0);
2258
2259                 count -= min_t(unsigned long, ret, count);
2260
2261                 if (count == 0)
2262                         break;
2263         }
2264
2265         if (run_all) {
2266                 node = rb_first(&delayed_refs->root);
2267                 if (!node)
2268                         goto out;
2269                 count = (unsigned long)-1;
2270
2271                 while (node) {
2272                         ref = rb_entry(node, struct btrfs_delayed_ref_node,
2273                                        rb_node);
2274                         if (btrfs_delayed_ref_is_head(ref)) {
2275                                 struct btrfs_delayed_ref_head *head;
2276
2277                                 head = btrfs_delayed_node_to_head(ref);
2278                                 atomic_inc(&ref->refs);
2279
2280                                 spin_unlock(&delayed_refs->lock);
2281                                 mutex_lock(&head->mutex);
2282                                 mutex_unlock(&head->mutex);
2283
2284                                 btrfs_put_delayed_ref(ref);
2285                                 cond_resched();
2286                                 goto again;
2287                         }
2288                         node = rb_next(node);
2289                 }
2290                 spin_unlock(&delayed_refs->lock);
2291                 schedule_timeout(1);
2292                 goto again;
2293         }
2294 out:
2295         spin_unlock(&delayed_refs->lock);
2296         return 0;
2297 }
2298
2299 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2300                                 struct btrfs_root *root,
2301                                 u64 bytenr, u64 num_bytes, u64 flags,
2302                                 int is_data)
2303 {
2304         struct btrfs_delayed_extent_op *extent_op;
2305         int ret;
2306
2307         extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2308         if (!extent_op)
2309                 return -ENOMEM;
2310
2311         extent_op->flags_to_set = flags;
2312         extent_op->update_flags = 1;
2313         extent_op->update_key = 0;
2314         extent_op->is_data = is_data ? 1 : 0;
2315
2316         ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2317         if (ret)
2318                 kfree(extent_op);
2319         return ret;
2320 }
2321
2322 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2323                                       struct btrfs_root *root,
2324                                       struct btrfs_path *path,
2325                                       u64 objectid, u64 offset, u64 bytenr)
2326 {
2327         struct btrfs_delayed_ref_head *head;
2328         struct btrfs_delayed_ref_node *ref;
2329         struct btrfs_delayed_data_ref *data_ref;
2330         struct btrfs_delayed_ref_root *delayed_refs;
2331         struct rb_node *node;
2332         int ret = 0;
2333
2334         ret = -ENOENT;
2335         delayed_refs = &trans->transaction->delayed_refs;
2336         spin_lock(&delayed_refs->lock);
2337         head = btrfs_find_delayed_ref_head(trans, bytenr);
2338         if (!head)
2339                 goto out;
2340
2341         if (!mutex_trylock(&head->mutex)) {
2342                 atomic_inc(&head->node.refs);
2343                 spin_unlock(&delayed_refs->lock);
2344
2345                 btrfs_release_path(root->fs_info->extent_root, path);
2346
2347                 mutex_lock(&head->mutex);
2348                 mutex_unlock(&head->mutex);
2349                 btrfs_put_delayed_ref(&head->node);
2350                 return -EAGAIN;
2351         }
2352
2353         node = rb_prev(&head->node.rb_node);
2354         if (!node)
2355                 goto out_unlock;
2356
2357         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2358
2359         if (ref->bytenr != bytenr)
2360                 goto out_unlock;
2361
2362         ret = 1;
2363         if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2364                 goto out_unlock;
2365
2366         data_ref = btrfs_delayed_node_to_data_ref(ref);
2367
2368         node = rb_prev(node);
2369         if (node) {
2370                 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2371                 if (ref->bytenr == bytenr)
2372                         goto out_unlock;
2373         }
2374
2375         if (data_ref->root != root->root_key.objectid ||
2376             data_ref->objectid != objectid || data_ref->offset != offset)
2377                 goto out_unlock;
2378
2379         ret = 0;
2380 out_unlock:
2381         mutex_unlock(&head->mutex);
2382 out:
2383         spin_unlock(&delayed_refs->lock);
2384         return ret;
2385 }
2386
2387 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2388                                         struct btrfs_root *root,
2389                                         struct btrfs_path *path,
2390                                         u64 objectid, u64 offset, u64 bytenr)
2391 {
2392         struct btrfs_root *extent_root = root->fs_info->extent_root;
2393         struct extent_buffer *leaf;
2394         struct btrfs_extent_data_ref *ref;
2395         struct btrfs_extent_inline_ref *iref;
2396         struct btrfs_extent_item *ei;
2397         struct btrfs_key key;
2398         u32 item_size;
2399         int ret;
2400
2401         key.objectid = bytenr;
2402         key.offset = (u64)-1;
2403         key.type = BTRFS_EXTENT_ITEM_KEY;
2404
2405         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2406         if (ret < 0)
2407                 goto out;
2408         BUG_ON(ret == 0);
2409
2410         ret = -ENOENT;
2411         if (path->slots[0] == 0)
2412                 goto out;
2413
2414         path->slots[0]--;
2415         leaf = path->nodes[0];
2416         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2417
2418         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2419                 goto out;
2420
2421         ret = 1;
2422         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2423 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2424         if (item_size < sizeof(*ei)) {
2425                 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2426                 goto out;
2427         }
2428 #endif
2429         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2430
2431         if (item_size != sizeof(*ei) +
2432             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2433                 goto out;
2434
2435         if (btrfs_extent_generation(leaf, ei) <=
2436             btrfs_root_last_snapshot(&root->root_item))
2437                 goto out;
2438
2439         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2440         if (btrfs_extent_inline_ref_type(leaf, iref) !=
2441             BTRFS_EXTENT_DATA_REF_KEY)
2442                 goto out;
2443
2444         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2445         if (btrfs_extent_refs(leaf, ei) !=
2446             btrfs_extent_data_ref_count(leaf, ref) ||
2447             btrfs_extent_data_ref_root(leaf, ref) !=
2448             root->root_key.objectid ||
2449             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2450             btrfs_extent_data_ref_offset(leaf, ref) != offset)
2451                 goto out;
2452
2453         ret = 0;
2454 out:
2455         return ret;
2456 }
2457
2458 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2459                           struct btrfs_root *root,
2460                           u64 objectid, u64 offset, u64 bytenr)
2461 {
2462         struct btrfs_path *path;
2463         int ret;
2464         int ret2;
2465
2466         path = btrfs_alloc_path();
2467         if (!path)
2468                 return -ENOENT;
2469
2470         do {
2471                 ret = check_committed_ref(trans, root, path, objectid,
2472                                           offset, bytenr);
2473                 if (ret && ret != -ENOENT)
2474                         goto out;
2475
2476                 ret2 = check_delayed_ref(trans, root, path, objectid,
2477                                          offset, bytenr);
2478         } while (ret2 == -EAGAIN);
2479
2480         if (ret2 && ret2 != -ENOENT) {
2481                 ret = ret2;
2482                 goto out;
2483         }
2484
2485         if (ret != -ENOENT || ret2 != -ENOENT)
2486                 ret = 0;
2487 out:
2488         btrfs_free_path(path);
2489         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2490                 WARN_ON(ret > 0);
2491         return ret;
2492 }
2493
2494 #if 0
2495 int btrfs_cache_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2496                     struct extent_buffer *buf, u32 nr_extents)
2497 {
2498         struct btrfs_key key;
2499         struct btrfs_file_extent_item *fi;
2500         u64 root_gen;
2501         u32 nritems;
2502         int i;
2503         int level;
2504         int ret = 0;
2505         int shared = 0;
2506
2507         if (!root->ref_cows)
2508                 return 0;
2509
2510         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
2511                 shared = 0;
2512                 root_gen = root->root_key.offset;
2513         } else {
2514                 shared = 1;
2515                 root_gen = trans->transid - 1;
2516         }
2517
2518         level = btrfs_header_level(buf);
2519         nritems = btrfs_header_nritems(buf);
2520
2521         if (level == 0) {
2522                 struct btrfs_leaf_ref *ref;
2523                 struct btrfs_extent_info *info;
2524
2525                 ref = btrfs_alloc_leaf_ref(root, nr_extents);
2526                 if (!ref) {
2527                         ret = -ENOMEM;
2528                         goto out;
2529                 }
2530
2531                 ref->root_gen = root_gen;
2532                 ref->bytenr = buf->start;
2533                 ref->owner = btrfs_header_owner(buf);
2534                 ref->generation = btrfs_header_generation(buf);
2535                 ref->nritems = nr_extents;
2536                 info = ref->extents;
2537
2538                 for (i = 0; nr_extents > 0 && i < nritems; i++) {
2539                         u64 disk_bytenr;
2540                         btrfs_item_key_to_cpu(buf, &key, i);
2541                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2542                                 continue;
2543                         fi = btrfs_item_ptr(buf, i,
2544                                             struct btrfs_file_extent_item);
2545                         if (btrfs_file_extent_type(buf, fi) ==
2546                             BTRFS_FILE_EXTENT_INLINE)
2547                                 continue;
2548                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2549                         if (disk_bytenr == 0)
2550                                 continue;
2551
2552                         info->bytenr = disk_bytenr;
2553                         info->num_bytes =
2554                                 btrfs_file_extent_disk_num_bytes(buf, fi);
2555                         info->objectid = key.objectid;
2556                         info->offset = key.offset;
2557                         info++;
2558                 }
2559
2560                 ret = btrfs_add_leaf_ref(root, ref, shared);
2561                 if (ret == -EEXIST && shared) {
2562                         struct btrfs_leaf_ref *old;
2563                         old = btrfs_lookup_leaf_ref(root, ref->bytenr);
2564                         BUG_ON(!old);
2565                         btrfs_remove_leaf_ref(root, old);
2566                         btrfs_free_leaf_ref(root, old);
2567                         ret = btrfs_add_leaf_ref(root, ref, shared);
2568                 }
2569                 WARN_ON(ret);
2570                 btrfs_free_leaf_ref(root, ref);
2571         }
2572 out:
2573         return ret;
2574 }
2575
2576 /* when a block goes through cow, we update the reference counts of
2577  * everything that block points to.  The internal pointers of the block
2578  * can be in just about any order, and it is likely to have clusters of
2579  * things that are close together and clusters of things that are not.
2580  *
2581  * To help reduce the seeks that come with updating all of these reference
2582  * counts, sort them by byte number before actual updates are done.
2583  *
2584  * struct refsort is used to match byte number to slot in the btree block.
2585  * we sort based on the byte number and then use the slot to actually
2586  * find the item.
2587  *
2588  * struct refsort is smaller than strcut btrfs_item and smaller than
2589  * struct btrfs_key_ptr.  Since we're currently limited to the page size
2590  * for a btree block, there's no way for a kmalloc of refsorts for a
2591  * single node to be bigger than a page.
2592  */
2593 struct refsort {
2594         u64 bytenr;
2595         u32 slot;
2596 };
2597
2598 /*
2599  * for passing into sort()
2600  */
2601 static int refsort_cmp(const void *a_void, const void *b_void)
2602 {
2603         const struct refsort *a = a_void;
2604         const struct refsort *b = b_void;
2605
2606         if (a->bytenr < b->bytenr)
2607                 return -1;
2608         if (a->bytenr > b->bytenr)
2609                 return 1;
2610         return 0;
2611 }
2612 #endif
2613
2614 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2615                            struct btrfs_root *root,
2616                            struct extent_buffer *buf,
2617                            int full_backref, int inc)
2618 {
2619         u64 bytenr;
2620         u64 num_bytes;
2621         u64 parent;
2622         u64 ref_root;
2623         u32 nritems;
2624         struct btrfs_key key;
2625         struct btrfs_file_extent_item *fi;
2626         int i;
2627         int level;
2628         int ret = 0;
2629         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2630                             u64, u64, u64, u64, u64, u64);
2631
2632         ref_root = btrfs_header_owner(buf);
2633         nritems = btrfs_header_nritems(buf);
2634         level = btrfs_header_level(buf);
2635
2636         if (!root->ref_cows && level == 0)
2637                 return 0;
2638
2639         if (inc)
2640                 process_func = btrfs_inc_extent_ref;
2641         else
2642                 process_func = btrfs_free_extent;
2643
2644         if (full_backref)
2645                 parent = buf->start;
2646         else
2647                 parent = 0;
2648
2649         for (i = 0; i < nritems; i++) {
2650                 if (level == 0) {
2651                         btrfs_item_key_to_cpu(buf, &key, i);
2652                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2653                                 continue;
2654                         fi = btrfs_item_ptr(buf, i,
2655                                             struct btrfs_file_extent_item);
2656                         if (btrfs_file_extent_type(buf, fi) ==
2657                             BTRFS_FILE_EXTENT_INLINE)
2658                                 continue;
2659                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2660                         if (bytenr == 0)
2661                                 continue;
2662
2663                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2664                         key.offset -= btrfs_file_extent_offset(buf, fi);
2665                         ret = process_func(trans, root, bytenr, num_bytes,
2666                                            parent, ref_root, key.objectid,
2667                                            key.offset);
2668                         if (ret)
2669                                 goto fail;
2670                 } else {
2671                         bytenr = btrfs_node_blockptr(buf, i);
2672                         num_bytes = btrfs_level_size(root, level - 1);
2673                         ret = process_func(trans, root, bytenr, num_bytes,
2674                                            parent, ref_root, level - 1, 0);
2675                         if (ret)
2676                                 goto fail;
2677                 }
2678         }
2679         return 0;
2680 fail:
2681         BUG();
2682         return ret;
2683 }
2684
2685 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2686                   struct extent_buffer *buf, int full_backref)
2687 {
2688         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2689 }
2690
2691 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2692                   struct extent_buffer *buf, int full_backref)
2693 {
2694         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2695 }
2696
2697 static int write_one_cache_group(struct btrfs_trans_handle *trans,
2698                                  struct btrfs_root *root,
2699                                  struct btrfs_path *path,
2700                                  struct btrfs_block_group_cache *cache)
2701 {
2702         int ret;
2703         struct btrfs_root *extent_root = root->fs_info->extent_root;
2704         unsigned long bi;
2705         struct extent_buffer *leaf;
2706
2707         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
2708         if (ret < 0)
2709                 goto fail;
2710         BUG_ON(ret);
2711
2712         leaf = path->nodes[0];
2713         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2714         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2715         btrfs_mark_buffer_dirty(leaf);
2716         btrfs_release_path(extent_root, path);
2717 fail:
2718         if (ret)
2719                 return ret;
2720         return 0;
2721
2722 }
2723
2724 static struct btrfs_block_group_cache *
2725 next_block_group(struct btrfs_root *root,
2726                  struct btrfs_block_group_cache *cache)
2727 {
2728         struct rb_node *node;
2729         spin_lock(&root->fs_info->block_group_cache_lock);
2730         node = rb_next(&cache->cache_node);
2731         btrfs_put_block_group(cache);
2732         if (node) {
2733                 cache = rb_entry(node, struct btrfs_block_group_cache,
2734                                  cache_node);
2735                 btrfs_get_block_group(cache);
2736         } else
2737                 cache = NULL;
2738         spin_unlock(&root->fs_info->block_group_cache_lock);
2739         return cache;
2740 }
2741
2742 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
2743                             struct btrfs_trans_handle *trans,
2744                             struct btrfs_path *path)
2745 {
2746         struct btrfs_root *root = block_group->fs_info->tree_root;
2747         struct inode *inode = NULL;
2748         u64 alloc_hint = 0;
2749         int dcs = BTRFS_DC_ERROR;
2750         int num_pages = 0;
2751         int retries = 0;
2752         int ret = 0;
2753
2754         /*
2755          * If this block group is smaller than 100 megs don't bother caching the
2756          * block group.
2757          */
2758         if (block_group->key.offset < (100 * 1024 * 1024)) {
2759                 spin_lock(&block_group->lock);
2760                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2761                 spin_unlock(&block_group->lock);
2762                 return 0;
2763         }
2764
2765 again:
2766         inode = lookup_free_space_inode(root, block_group, path);
2767         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2768                 ret = PTR_ERR(inode);
2769                 btrfs_release_path(root, path);
2770                 goto out;
2771         }
2772
2773         if (IS_ERR(inode)) {
2774                 BUG_ON(retries);
2775                 retries++;
2776
2777                 if (block_group->ro)
2778                         goto out_free;
2779
2780                 ret = create_free_space_inode(root, trans, block_group, path);
2781                 if (ret)
2782                         goto out_free;
2783                 goto again;
2784         }
2785
2786         /*
2787          * We want to set the generation to 0, that way if anything goes wrong
2788          * from here on out we know not to trust this cache when we load up next
2789          * time.
2790          */
2791         BTRFS_I(inode)->generation = 0;
2792         ret = btrfs_update_inode(trans, root, inode);
2793         WARN_ON(ret);
2794
2795         if (i_size_read(inode) > 0) {
2796                 ret = btrfs_truncate_free_space_cache(root, trans, path,
2797                                                       inode);
2798                 if (ret)
2799                         goto out_put;
2800         }
2801
2802         spin_lock(&block_group->lock);
2803         if (block_group->cached != BTRFS_CACHE_FINISHED) {
2804                 /* We're not cached, don't bother trying to write stuff out */
2805                 dcs = BTRFS_DC_WRITTEN;
2806                 spin_unlock(&block_group->lock);
2807                 goto out_put;
2808         }
2809         spin_unlock(&block_group->lock);
2810
2811         num_pages = (int)div64_u64(block_group->key.offset, 1024 * 1024 * 1024);
2812         if (!num_pages)
2813                 num_pages = 1;
2814
2815         /*
2816          * Just to make absolutely sure we have enough space, we're going to
2817          * preallocate 12 pages worth of space for each block group.  In
2818          * practice we ought to use at most 8, but we need extra space so we can
2819          * add our header and have a terminator between the extents and the
2820          * bitmaps.
2821          */
2822         num_pages *= 16;
2823         num_pages *= PAGE_CACHE_SIZE;
2824
2825         ret = btrfs_check_data_free_space(inode, num_pages);
2826         if (ret)
2827                 goto out_put;
2828
2829         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
2830                                               num_pages, num_pages,
2831                                               &alloc_hint);
2832         if (!ret)
2833                 dcs = BTRFS_DC_SETUP;
2834         btrfs_free_reserved_data_space(inode, num_pages);
2835 out_put:
2836         iput(inode);
2837 out_free:
2838         btrfs_release_path(root, path);
2839 out:
2840         spin_lock(&block_group->lock);
2841         block_group->disk_cache_state = dcs;
2842         spin_unlock(&block_group->lock);
2843
2844         return ret;
2845 }
2846
2847 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
2848                                    struct btrfs_root *root)
2849 {
2850         struct btrfs_block_group_cache *cache;
2851         int err = 0;
2852         struct btrfs_path *path;
2853         u64 last = 0;
2854
2855         path = btrfs_alloc_path();
2856         if (!path)
2857                 return -ENOMEM;
2858
2859 again:
2860         while (1) {
2861                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2862                 while (cache) {
2863                         if (cache->disk_cache_state == BTRFS_DC_CLEAR)
2864                                 break;
2865                         cache = next_block_group(root, cache);
2866                 }
2867                 if (!cache) {
2868                         if (last == 0)
2869                                 break;
2870                         last = 0;
2871                         continue;
2872                 }
2873                 err = cache_save_setup(cache, trans, path);
2874                 last = cache->key.objectid + cache->key.offset;
2875                 btrfs_put_block_group(cache);
2876         }
2877
2878         while (1) {
2879                 if (last == 0) {
2880                         err = btrfs_run_delayed_refs(trans, root,
2881                                                      (unsigned long)-1);
2882                         BUG_ON(err);
2883                 }
2884
2885                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2886                 while (cache) {
2887                         if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
2888                                 btrfs_put_block_group(cache);
2889                                 goto again;
2890                         }
2891
2892                         if (cache->dirty)
2893                                 break;
2894                         cache = next_block_group(root, cache);
2895                 }
2896                 if (!cache) {
2897                         if (last == 0)
2898                                 break;
2899                         last = 0;
2900                         continue;
2901                 }
2902
2903                 if (cache->disk_cache_state == BTRFS_DC_SETUP)
2904                         cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
2905                 cache->dirty = 0;
2906                 last = cache->key.objectid + cache->key.offset;
2907
2908                 err = write_one_cache_group(trans, root, path, cache);
2909                 BUG_ON(err);
2910                 btrfs_put_block_group(cache);
2911         }
2912
2913         while (1) {
2914                 /*
2915                  * I don't think this is needed since we're just marking our
2916                  * preallocated extent as written, but just in case it can't
2917                  * hurt.
2918                  */
2919                 if (last == 0) {
2920                         err = btrfs_run_delayed_refs(trans, root,
2921                                                      (unsigned long)-1);
2922                         BUG_ON(err);
2923                 }
2924
2925                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2926                 while (cache) {
2927                         /*
2928                          * Really this shouldn't happen, but it could if we
2929                          * couldn't write the entire preallocated extent and
2930                          * splitting the extent resulted in a new block.
2931                          */
2932                         if (cache->dirty) {
2933                                 btrfs_put_block_group(cache);
2934                                 goto again;
2935                         }
2936                         if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2937                                 break;
2938                         cache = next_block_group(root, cache);
2939                 }
2940                 if (!cache) {
2941                         if (last == 0)
2942                                 break;
2943                         last = 0;
2944                         continue;
2945                 }
2946
2947                 btrfs_write_out_cache(root, trans, cache, path);
2948
2949                 /*
2950                  * If we didn't have an error then the cache state is still
2951                  * NEED_WRITE, so we can set it to WRITTEN.
2952                  */
2953                 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
2954                         cache->disk_cache_state = BTRFS_DC_WRITTEN;
2955                 last = cache->key.objectid + cache->key.offset;
2956                 btrfs_put_block_group(cache);
2957         }
2958
2959         btrfs_free_path(path);
2960         return 0;
2961 }
2962
2963 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
2964 {
2965         struct btrfs_block_group_cache *block_group;
2966         int readonly = 0;
2967
2968         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
2969         if (!block_group || block_group->ro)
2970                 readonly = 1;
2971         if (block_group)
2972                 btrfs_put_block_group(block_group);
2973         return readonly;
2974 }
2975
2976 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
2977                              u64 total_bytes, u64 bytes_used,
2978                              struct btrfs_space_info **space_info)
2979 {
2980         struct btrfs_space_info *found;
2981         int i;
2982         int factor;
2983
2984         if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
2985                      BTRFS_BLOCK_GROUP_RAID10))
2986                 factor = 2;
2987         else
2988                 factor = 1;
2989
2990         found = __find_space_info(info, flags);
2991         if (found) {
2992                 spin_lock(&found->lock);
2993                 found->total_bytes += total_bytes;
2994                 found->disk_total += total_bytes * factor;
2995                 found->bytes_used += bytes_used;
2996                 found->disk_used += bytes_used * factor;
2997                 found->full = 0;
2998                 spin_unlock(&found->lock);
2999                 *space_info = found;
3000                 return 0;
3001         }
3002         found = kzalloc(sizeof(*found), GFP_NOFS);
3003         if (!found)
3004                 return -ENOMEM;
3005
3006         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3007                 INIT_LIST_HEAD(&found->block_groups[i]);
3008         init_rwsem(&found->groups_sem);
3009         spin_lock_init(&found->lock);
3010         found->flags = flags & (BTRFS_BLOCK_GROUP_DATA |
3011                                 BTRFS_BLOCK_GROUP_SYSTEM |
3012                                 BTRFS_BLOCK_GROUP_METADATA);
3013         found->total_bytes = total_bytes;
3014         found->disk_total = total_bytes * factor;
3015         found->bytes_used = bytes_used;
3016         found->disk_used = bytes_used * factor;
3017         found->bytes_pinned = 0;
3018         found->bytes_reserved = 0;
3019         found->bytes_readonly = 0;
3020         found->bytes_may_use = 0;
3021         found->full = 0;
3022         found->force_alloc = 0;
3023         *space_info = found;
3024         list_add_rcu(&found->list, &info->space_info);
3025         atomic_set(&found->caching_threads, 0);
3026         return 0;
3027 }
3028
3029 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3030 {
3031         u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
3032                                    BTRFS_BLOCK_GROUP_RAID1 |
3033                                    BTRFS_BLOCK_GROUP_RAID10 |
3034                                    BTRFS_BLOCK_GROUP_DUP);
3035         if (extra_flags) {
3036                 if (flags & BTRFS_BLOCK_GROUP_DATA)
3037                         fs_info->avail_data_alloc_bits |= extra_flags;
3038                 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3039                         fs_info->avail_metadata_alloc_bits |= extra_flags;
3040                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3041                         fs_info->avail_system_alloc_bits |= extra_flags;
3042         }
3043 }
3044
3045 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
3046 {
3047         /*
3048          * we add in the count of missing devices because we want
3049          * to make sure that any RAID levels on a degraded FS
3050          * continue to be honored.
3051          */
3052         u64 num_devices = root->fs_info->fs_devices->rw_devices +
3053                 root->fs_info->fs_devices->missing_devices;
3054
3055         if (num_devices == 1)
3056                 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
3057         if (num_devices < 4)
3058                 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3059
3060         if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
3061             (flags & (BTRFS_BLOCK_GROUP_RAID1 |
3062                       BTRFS_BLOCK_GROUP_RAID10))) {
3063                 flags &= ~BTRFS_BLOCK_GROUP_DUP;
3064         }
3065
3066         if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
3067             (flags & BTRFS_BLOCK_GROUP_RAID10)) {
3068                 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
3069         }
3070
3071         if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
3072             ((flags & BTRFS_BLOCK_GROUP_RAID1) |
3073              (flags & BTRFS_BLOCK_GROUP_RAID10) |
3074              (flags & BTRFS_BLOCK_GROUP_DUP)))
3075                 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
3076         return flags;
3077 }
3078
3079 static u64 get_alloc_profile(struct btrfs_root *root, u64 flags)
3080 {
3081         if (flags & BTRFS_BLOCK_GROUP_DATA)
3082                 flags |= root->fs_info->avail_data_alloc_bits &
3083                          root->fs_info->data_alloc_profile;
3084         else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3085                 flags |= root->fs_info->avail_system_alloc_bits &
3086                          root->fs_info->system_alloc_profile;
3087         else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3088                 flags |= root->fs_info->avail_metadata_alloc_bits &
3089                          root->fs_info->metadata_alloc_profile;
3090         return btrfs_reduce_alloc_profile(root, flags);
3091 }
3092
3093 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3094 {
3095         u64 flags;
3096
3097         if (data)
3098                 flags = BTRFS_BLOCK_GROUP_DATA;
3099         else if (root == root->fs_info->chunk_root)
3100                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3101         else
3102                 flags = BTRFS_BLOCK_GROUP_METADATA;
3103
3104         return get_alloc_profile(root, flags);
3105 }
3106
3107 void btrfs_set_inode_space_info(struct btrfs_root *root, struct inode *inode)
3108 {
3109         BTRFS_I(inode)->space_info = __find_space_info(root->fs_info,
3110                                                        BTRFS_BLOCK_GROUP_DATA);
3111 }
3112
3113 /*
3114  * This will check the space that the inode allocates from to make sure we have
3115  * enough space for bytes.
3116  */
3117 int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
3118 {
3119         struct btrfs_space_info *data_sinfo;
3120         struct btrfs_root *root = BTRFS_I(inode)->root;
3121         u64 used;
3122         int ret = 0, committed = 0, alloc_chunk = 1;
3123
3124         /* make sure bytes are sectorsize aligned */
3125         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3126
3127         if (root == root->fs_info->tree_root) {
3128                 alloc_chunk = 0;
3129                 committed = 1;
3130         }
3131
3132         data_sinfo = BTRFS_I(inode)->space_info;
3133         if (!data_sinfo)
3134                 goto alloc;
3135
3136 again:
3137         /* make sure we have enough space to handle the data first */
3138         spin_lock(&data_sinfo->lock);
3139         used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3140                 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3141                 data_sinfo->bytes_may_use;
3142
3143         if (used + bytes > data_sinfo->total_bytes) {
3144                 struct btrfs_trans_handle *trans;
3145
3146                 /*
3147                  * if we don't have enough free bytes in this space then we need
3148                  * to alloc a new chunk.
3149                  */
3150                 if (!data_sinfo->full && alloc_chunk) {
3151                         u64 alloc_target;
3152
3153                         data_sinfo->force_alloc = 1;
3154                         spin_unlock(&data_sinfo->lock);
3155 alloc:
3156                         alloc_target = btrfs_get_alloc_profile(root, 1);
3157                         trans = btrfs_join_transaction(root, 1);
3158                         if (IS_ERR(trans))
3159                                 return PTR_ERR(trans);
3160
3161                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3162                                              bytes + 2 * 1024 * 1024,
3163                                              alloc_target, 0);
3164                         btrfs_end_transaction(trans, root);
3165                         if (ret < 0) {
3166                                 if (ret != -ENOSPC)
3167                                         return ret;
3168                                 else
3169                                         goto commit_trans;
3170                         }
3171
3172                         if (!data_sinfo) {
3173                                 btrfs_set_inode_space_info(root, inode);
3174                                 data_sinfo = BTRFS_I(inode)->space_info;
3175                         }
3176                         goto again;
3177                 }
3178                 spin_unlock(&data_sinfo->lock);
3179
3180                 /* commit the current transaction and try again */
3181 commit_trans:
3182                 if (!committed && !root->fs_info->open_ioctl_trans) {
3183                         committed = 1;
3184                         trans = btrfs_join_transaction(root, 1);
3185                         if (IS_ERR(trans))
3186                                 return PTR_ERR(trans);
3187                         ret = btrfs_commit_transaction(trans, root);
3188                         if (ret)
3189                                 return ret;
3190                         goto again;
3191                 }
3192
3193 #if 0 /* I hope we never need this code again, just in case */
3194                 printk(KERN_ERR "no space left, need %llu, %llu bytes_used, "
3195                        "%llu bytes_reserved, " "%llu bytes_pinned, "
3196                        "%llu bytes_readonly, %llu may use %llu total\n",
3197                        (unsigned long long)bytes,
3198                        (unsigned long long)data_sinfo->bytes_used,
3199                        (unsigned long long)data_sinfo->bytes_reserved,
3200                        (unsigned long long)data_sinfo->bytes_pinned,
3201                        (unsigned long long)data_sinfo->bytes_readonly,
3202                        (unsigned long long)data_sinfo->bytes_may_use,
3203                        (unsigned long long)data_sinfo->total_bytes);
3204 #endif
3205                 return -ENOSPC;
3206         }
3207         data_sinfo->bytes_may_use += bytes;
3208         BTRFS_I(inode)->reserved_bytes += bytes;
3209         spin_unlock(&data_sinfo->lock);
3210
3211         return 0;
3212 }
3213
3214 /*
3215  * called when we are clearing an delalloc extent from the
3216  * inode's io_tree or there was an error for whatever reason
3217  * after calling btrfs_check_data_free_space
3218  */
3219 void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
3220 {
3221         struct btrfs_root *root = BTRFS_I(inode)->root;
3222         struct btrfs_space_info *data_sinfo;
3223
3224         /* make sure bytes are sectorsize aligned */
3225         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3226
3227         data_sinfo = BTRFS_I(inode)->space_info;
3228         spin_lock(&data_sinfo->lock);
3229         data_sinfo->bytes_may_use -= bytes;
3230         BTRFS_I(inode)->reserved_bytes -= bytes;
3231         spin_unlock(&data_sinfo->lock);
3232 }
3233
3234 static void force_metadata_allocation(struct btrfs_fs_info *info)
3235 {
3236         struct list_head *head = &info->space_info;
3237         struct btrfs_space_info *found;
3238
3239         rcu_read_lock();
3240         list_for_each_entry_rcu(found, head, list) {
3241                 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3242                         found->force_alloc = 1;
3243         }
3244         rcu_read_unlock();
3245 }
3246
3247 static int should_alloc_chunk(struct btrfs_root *root,
3248                               struct btrfs_space_info *sinfo, u64 alloc_bytes)
3249 {
3250         u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
3251         u64 thresh;
3252
3253         if (sinfo->bytes_used + sinfo->bytes_reserved +
3254             alloc_bytes + 256 * 1024 * 1024 < num_bytes)
3255                 return 0;
3256
3257         if (sinfo->bytes_used + sinfo->bytes_reserved +
3258             alloc_bytes < div_factor(num_bytes, 8))
3259                 return 0;
3260
3261         thresh = btrfs_super_total_bytes(&root->fs_info->super_copy);
3262         thresh = max_t(u64, 256 * 1024 * 1024, div_factor_fine(thresh, 5));
3263
3264         if (num_bytes > thresh && sinfo->bytes_used < div_factor(num_bytes, 3))
3265                 return 0;
3266
3267         return 1;
3268 }
3269
3270 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
3271                           struct btrfs_root *extent_root, u64 alloc_bytes,
3272                           u64 flags, int force)
3273 {
3274         struct btrfs_space_info *space_info;
3275         struct btrfs_fs_info *fs_info = extent_root->fs_info;
3276         int ret = 0;
3277
3278         mutex_lock(&fs_info->chunk_mutex);
3279
3280         flags = btrfs_reduce_alloc_profile(extent_root, flags);
3281
3282         space_info = __find_space_info(extent_root->fs_info, flags);
3283         if (!space_info) {
3284                 ret = update_space_info(extent_root->fs_info, flags,
3285                                         0, 0, &space_info);
3286                 BUG_ON(ret);
3287         }
3288         BUG_ON(!space_info);
3289
3290         spin_lock(&space_info->lock);
3291         if (space_info->force_alloc)
3292                 force = 1;
3293         if (space_info->full) {
3294                 spin_unlock(&space_info->lock);
3295                 goto out;
3296         }
3297
3298         if (!force && !should_alloc_chunk(extent_root, space_info,
3299                                           alloc_bytes)) {
3300                 spin_unlock(&space_info->lock);
3301                 goto out;
3302         }
3303         spin_unlock(&space_info->lock);
3304
3305         /*
3306          * If we have mixed data/metadata chunks we want to make sure we keep
3307          * allocating mixed chunks instead of individual chunks.
3308          */
3309         if (btrfs_mixed_space_info(space_info))
3310                 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3311
3312         /*
3313          * if we're doing a data chunk, go ahead and make sure that
3314          * we keep a reasonable number of metadata chunks allocated in the
3315          * FS as well.
3316          */
3317         if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3318                 fs_info->data_chunk_allocations++;
3319                 if (!(fs_info->data_chunk_allocations %
3320                       fs_info->metadata_ratio))
3321                         force_metadata_allocation(fs_info);
3322         }
3323
3324         ret = btrfs_alloc_chunk(trans, extent_root, flags);
3325         spin_lock(&space_info->lock);
3326         if (ret)
3327                 space_info->full = 1;
3328         else
3329                 ret = 1;
3330         space_info->force_alloc = 0;
3331         spin_unlock(&space_info->lock);
3332 out:
3333         mutex_unlock(&extent_root->fs_info->chunk_mutex);
3334         return ret;
3335 }
3336
3337 /*
3338  * shrink metadata reservation for delalloc
3339  */
3340 static int shrink_delalloc(struct btrfs_trans_handle *trans,
3341                            struct btrfs_root *root, u64 to_reclaim, int sync)
3342 {
3343         struct btrfs_block_rsv *block_rsv;
3344         struct btrfs_space_info *space_info;
3345         u64 reserved;
3346         u64 max_reclaim;
3347         u64 reclaimed = 0;
3348         int pause = 1;
3349         int nr_pages = (2 * 1024 * 1024) >> PAGE_CACHE_SHIFT;
3350
3351         block_rsv = &root->fs_info->delalloc_block_rsv;
3352         space_info = block_rsv->space_info;
3353
3354         smp_mb();
3355         reserved = space_info->bytes_reserved;
3356
3357         if (reserved == 0)
3358                 return 0;
3359
3360         max_reclaim = min(reserved, to_reclaim);
3361
3362         while (1) {
3363                 /* have the flusher threads jump in and do some IO */
3364                 smp_mb();
3365                 nr_pages = min_t(unsigned long, nr_pages,
3366                        root->fs_info->delalloc_bytes >> PAGE_CACHE_SHIFT);
3367                 writeback_inodes_sb_nr_if_idle(root->fs_info->sb, nr_pages);
3368
3369                 spin_lock(&space_info->lock);
3370                 if (reserved > space_info->bytes_reserved)
3371                         reclaimed += reserved - space_info->bytes_reserved;
3372                 reserved = space_info->bytes_reserved;
3373                 spin_unlock(&space_info->lock);
3374
3375                 if (reserved == 0 || reclaimed >= max_reclaim)
3376                         break;
3377
3378                 if (trans && trans->transaction->blocked)
3379                         return -EAGAIN;
3380
3381                 __set_current_state(TASK_INTERRUPTIBLE);
3382                 schedule_timeout(pause);
3383                 pause <<= 1;
3384                 if (pause > HZ / 10)
3385                         pause = HZ / 10;
3386
3387         }
3388         return reclaimed >= to_reclaim;
3389 }
3390
3391 /*
3392  * Retries tells us how many times we've called reserve_metadata_bytes.  The
3393  * idea is if this is the first call (retries == 0) then we will add to our
3394  * reserved count if we can't make the allocation in order to hold our place
3395  * while we go and try and free up space.  That way for retries > 1 we don't try
3396  * and add space, we just check to see if the amount of unused space is >= the
3397  * total space, meaning that our reservation is valid.
3398  *
3399  * However if we don't intend to retry this reservation, pass -1 as retries so
3400  * that it short circuits this logic.
3401  */
3402 static int reserve_metadata_bytes(struct btrfs_trans_handle *trans,
3403                                   struct btrfs_root *root,
3404                                   struct btrfs_block_rsv *block_rsv,
3405                                   u64 orig_bytes, int flush)
3406 {
3407         struct btrfs_space_info *space_info = block_rsv->space_info;
3408         u64 unused;
3409         u64 num_bytes = orig_bytes;
3410         int retries = 0;
3411         int ret = 0;
3412         bool reserved = false;
3413         bool committed = false;
3414
3415 again:
3416         ret = -ENOSPC;
3417         if (reserved)
3418                 num_bytes = 0;
3419
3420         spin_lock(&space_info->lock);
3421         unused = space_info->bytes_used + space_info->bytes_reserved +
3422                  space_info->bytes_pinned + space_info->bytes_readonly +
3423                  space_info->bytes_may_use;
3424
3425         /*
3426          * The idea here is that we've not already over-reserved the block group
3427          * then we can go ahead and save our reservation first and then start
3428          * flushing if we need to.  Otherwise if we've already overcommitted
3429          * lets start flushing stuff first and then come back and try to make
3430          * our reservation.
3431          */
3432         if (unused <= space_info->total_bytes) {
3433                 unused = space_info->total_bytes - unused;
3434                 if (unused >= num_bytes) {
3435                         if (!reserved)
3436                                 space_info->bytes_reserved += orig_bytes;
3437                         ret = 0;
3438                 } else {
3439                         /*
3440                          * Ok set num_bytes to orig_bytes since we aren't
3441                          * overocmmitted, this way we only try and reclaim what
3442                          * we need.
3443                          */
3444                         num_bytes = orig_bytes;
3445                 }
3446         } else {
3447                 /*
3448                  * Ok we're over committed, set num_bytes to the overcommitted
3449                  * amount plus the amount of bytes that we need for this
3450                  * reservation.
3451                  */
3452                 num_bytes = unused - space_info->total_bytes +
3453                         (orig_bytes * (retries + 1));
3454         }
3455
3456         /*
3457          * Couldn't make our reservation, save our place so while we're trying
3458          * to reclaim space we can actually use it instead of somebody else
3459          * stealing it from us.
3460          */
3461         if (ret && !reserved) {
3462                 space_info->bytes_reserved += orig_bytes;
3463                 reserved = true;
3464         }
3465
3466         spin_unlock(&space_info->lock);
3467
3468         if (!ret)
3469                 return 0;
3470
3471         if (!flush)
3472                 goto out;
3473
3474         /*
3475          * We do synchronous shrinking since we don't actually unreserve
3476          * metadata until after the IO is completed.
3477          */
3478         ret = shrink_delalloc(trans, root, num_bytes, 1);
3479         if (ret > 0)
3480                 return 0;
3481         else if (ret < 0)
3482                 goto out;
3483
3484         /*
3485          * So if we were overcommitted it's possible that somebody else flushed
3486          * out enough space and we simply didn't have enough space to reclaim,
3487          * so go back around and try again.
3488          */
3489         if (retries < 2) {
3490                 retries++;
3491                 goto again;
3492         }
3493
3494         spin_lock(&space_info->lock);
3495         /*
3496          * Not enough space to be reclaimed, don't bother committing the
3497          * transaction.
3498          */
3499         if (space_info->bytes_pinned < orig_bytes)
3500                 ret = -ENOSPC;
3501         spin_unlock(&space_info->lock);
3502         if (ret)
3503                 goto out;
3504
3505         ret = -EAGAIN;
3506         if (trans || committed)
3507                 goto out;
3508
3509         ret = -ENOSPC;
3510         trans = btrfs_join_transaction(root, 1);
3511         if (IS_ERR(trans))
3512                 goto out;
3513         ret = btrfs_commit_transaction(trans, root);
3514         if (!ret) {
3515                 trans = NULL;
3516                 committed = true;
3517                 goto again;
3518         }
3519
3520 out:
3521         if (reserved) {
3522                 spin_lock(&space_info->lock);
3523                 space_info->bytes_reserved -= orig_bytes;
3524                 spin_unlock(&space_info->lock);
3525         }
3526
3527         return ret;
3528 }
3529
3530 static struct btrfs_block_rsv *get_block_rsv(struct btrfs_trans_handle *trans,
3531                                              struct btrfs_root *root)
3532 {
3533         struct btrfs_block_rsv *block_rsv;
3534         if (root->ref_cows)
3535                 block_rsv = trans->block_rsv;
3536         else
3537                 block_rsv = root->block_rsv;
3538
3539         if (!block_rsv)
3540                 block_rsv = &root->fs_info->empty_block_rsv;
3541
3542         return block_rsv;
3543 }
3544
3545 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
3546                                u64 num_bytes)
3547 {
3548         int ret = -ENOSPC;
3549         spin_lock(&block_rsv->lock);
3550         if (block_rsv->reserved >= num_bytes) {
3551                 block_rsv->reserved -= num_bytes;
3552                 if (block_rsv->reserved < block_rsv->size)
3553                         block_rsv->full = 0;
3554                 ret = 0;
3555         }
3556         spin_unlock(&block_rsv->lock);
3557         return ret;
3558 }
3559
3560 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
3561                                 u64 num_bytes, int update_size)
3562 {
3563         spin_lock(&block_rsv->lock);
3564         block_rsv->reserved += num_bytes;
3565         if (update_size)
3566                 block_rsv->size += num_bytes;
3567         else if (block_rsv->reserved >= block_rsv->size)
3568                 block_rsv->full = 1;
3569         spin_unlock(&block_rsv->lock);
3570 }
3571
3572 void block_rsv_release_bytes(struct btrfs_block_rsv *block_rsv,
3573                              struct btrfs_block_rsv *dest, u64 num_bytes)
3574 {
3575         struct btrfs_space_info *space_info = block_rsv->space_info;
3576
3577         spin_lock(&block_rsv->lock);
3578         if (num_bytes == (u64)-1)
3579                 num_bytes = block_rsv->size;
3580         block_rsv->size -= num_bytes;
3581         if (block_rsv->reserved >= block_rsv->size) {
3582                 num_bytes = block_rsv->reserved - block_rsv->size;
3583                 block_rsv->reserved = block_rsv->size;
3584                 block_rsv->full = 1;
3585         } else {
3586                 num_bytes = 0;
3587         }
3588         spin_unlock(&block_rsv->lock);
3589
3590         if (num_bytes > 0) {
3591                 if (dest) {
3592                         block_rsv_add_bytes(dest, num_bytes, 0);
3593                 } else {
3594                         spin_lock(&space_info->lock);
3595                         space_info->bytes_reserved -= num_bytes;
3596                         spin_unlock(&space_info->lock);
3597                 }
3598         }
3599 }
3600
3601 static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
3602                                    struct btrfs_block_rsv *dst, u64 num_bytes)
3603 {
3604         int ret;
3605
3606         ret = block_rsv_use_bytes(src, num_bytes);
3607         if (ret)
3608                 return ret;
3609
3610         block_rsv_add_bytes(dst, num_bytes, 1);
3611         return 0;
3612 }
3613
3614 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv)
3615 {
3616         memset(rsv, 0, sizeof(*rsv));
3617         spin_lock_init(&rsv->lock);
3618         atomic_set(&rsv->usage, 1);
3619         rsv->priority = 6;
3620         INIT_LIST_HEAD(&rsv->list);
3621 }
3622
3623 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root)
3624 {
3625         struct btrfs_block_rsv *block_rsv;
3626         struct btrfs_fs_info *fs_info = root->fs_info;
3627
3628         block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
3629         if (!block_rsv)
3630                 return NULL;
3631
3632         btrfs_init_block_rsv(block_rsv);
3633         block_rsv->space_info = __find_space_info(fs_info,
3634                                                   BTRFS_BLOCK_GROUP_METADATA);
3635         return block_rsv;
3636 }
3637
3638 void btrfs_free_block_rsv(struct btrfs_root *root,
3639                           struct btrfs_block_rsv *rsv)
3640 {
3641         if (rsv && atomic_dec_and_test(&rsv->usage)) {
3642                 btrfs_block_rsv_release(root, rsv, (u64)-1);
3643                 if (!rsv->durable)
3644                         kfree(rsv);
3645         }
3646 }
3647
3648 /*
3649  * make the block_rsv struct be able to capture freed space.
3650  * the captured space will re-add to the the block_rsv struct
3651  * after transaction commit
3652  */
3653 void btrfs_add_durable_block_rsv(struct btrfs_fs_info *fs_info,
3654                                  struct btrfs_block_rsv *block_rsv)
3655 {
3656         block_rsv->durable = 1;
3657         mutex_lock(&fs_info->durable_block_rsv_mutex);
3658         list_add_tail(&block_rsv->list, &fs_info->durable_block_rsv_list);
3659         mutex_unlock(&fs_info->durable_block_rsv_mutex);
3660 }
3661
3662 int btrfs_block_rsv_add(struct btrfs_trans_handle *trans,
3663                         struct btrfs_root *root,
3664                         struct btrfs_block_rsv *block_rsv,
3665                         u64 num_bytes)
3666 {
3667         int ret;
3668
3669         if (num_bytes == 0)
3670                 return 0;
3671
3672         ret = reserve_metadata_bytes(trans, root, block_rsv, num_bytes, 1);
3673         if (!ret) {
3674                 block_rsv_add_bytes(block_rsv, num_bytes, 1);
3675                 return 0;
3676         }
3677
3678         return ret;
3679 }
3680
3681 int btrfs_block_rsv_check(struct btrfs_trans_handle *trans,
3682                           struct btrfs_root *root,
3683                           struct btrfs_block_rsv *block_rsv,
3684                           u64 min_reserved, int min_factor)
3685 {
3686         u64 num_bytes = 0;
3687         int commit_trans = 0;
3688         int ret = -ENOSPC;
3689
3690         if (!block_rsv)
3691                 return 0;
3692
3693         spin_lock(&block_rsv->lock);
3694         if (min_factor > 0)
3695                 num_bytes = div_factor(block_rsv->size, min_factor);
3696         if (min_reserved > num_bytes)
3697                 num_bytes = min_reserved;
3698
3699         if (block_rsv->reserved >= num_bytes) {
3700                 ret = 0;
3701         } else {
3702                 num_bytes -= block_rsv->reserved;
3703                 if (block_rsv->durable &&
3704                     block_rsv->freed[0] + block_rsv->freed[1] >= num_bytes)
3705                         commit_trans = 1;
3706         }
3707         spin_unlock(&block_rsv->lock);
3708         if (!ret)
3709                 return 0;
3710
3711         if (block_rsv->refill_used) {
3712                 ret = reserve_metadata_bytes(trans, root, block_rsv,
3713                                              num_bytes, 0);
3714                 if (!ret) {
3715                         block_rsv_add_bytes(block_rsv, num_bytes, 0);
3716                         return 0;
3717                 }
3718         }
3719
3720         if (commit_trans) {
3721                 if (trans)
3722                         return -EAGAIN;
3723
3724                 trans = btrfs_join_transaction(root, 1);
3725                 BUG_ON(IS_ERR(trans));
3726                 ret = btrfs_commit_transaction(trans, root);
3727                 return 0;
3728         }
3729
3730         return -ENOSPC;
3731 }
3732
3733 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
3734                             struct btrfs_block_rsv *dst_rsv,
3735                             u64 num_bytes)
3736 {
3737         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
3738 }
3739
3740 void btrfs_block_rsv_release(struct btrfs_root *root,
3741                              struct btrfs_block_rsv *block_rsv,
3742                              u64 num_bytes)
3743 {
3744         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3745         if (global_rsv->full || global_rsv == block_rsv ||
3746             block_rsv->space_info != global_rsv->space_info)
3747                 global_rsv = NULL;
3748         block_rsv_release_bytes(block_rsv, global_rsv, num_bytes);
3749 }
3750
3751 /*
3752  * helper to calculate size of global block reservation.
3753  * the desired value is sum of space used by extent tree,
3754  * checksum tree and root tree
3755  */
3756 static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
3757 {
3758         struct btrfs_space_info *sinfo;
3759         u64 num_bytes;
3760         u64 meta_used;
3761         u64 data_used;
3762         int csum_size = btrfs_super_csum_size(&fs_info->super_copy);
3763 #if 0
3764         /*
3765          * per tree used space accounting can be inaccuracy, so we
3766          * can't rely on it.
3767          */
3768         spin_lock(&fs_info->extent_root->accounting_lock);
3769         num_bytes = btrfs_root_used(&fs_info->extent_root->root_item);
3770         spin_unlock(&fs_info->extent_root->accounting_lock);
3771
3772         spin_lock(&fs_info->csum_root->accounting_lock);
3773         num_bytes += btrfs_root_used(&fs_info->csum_root->root_item);
3774         spin_unlock(&fs_info->csum_root->accounting_lock);
3775
3776         spin_lock(&fs_info->tree_root->accounting_lock);
3777         num_bytes += btrfs_root_used(&fs_info->tree_root->root_item);
3778         spin_unlock(&fs_info->tree_root->accounting_lock);
3779 #endif
3780         sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
3781         spin_lock(&sinfo->lock);
3782         data_used = sinfo->bytes_used;
3783         spin_unlock(&sinfo->lock);
3784
3785         sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3786         spin_lock(&sinfo->lock);
3787         if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
3788                 data_used = 0;
3789         meta_used = sinfo->bytes_used;
3790         spin_unlock(&sinfo->lock);
3791
3792         num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
3793                     csum_size * 2;
3794         num_bytes += div64_u64(data_used + meta_used, 50);
3795
3796         if (num_bytes * 3 > meta_used)
3797                 num_bytes = div64_u64(meta_used, 3);
3798
3799         return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
3800 }
3801
3802 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
3803 {
3804         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
3805         struct btrfs_space_info *sinfo = block_rsv->space_info;
3806         u64 num_bytes;
3807
3808         num_bytes = calc_global_metadata_size(fs_info);
3809
3810         spin_lock(&block_rsv->lock);
3811         spin_lock(&sinfo->lock);
3812
3813         block_rsv->size = num_bytes;
3814
3815         num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
3816                     sinfo->bytes_reserved + sinfo->bytes_readonly +
3817                     sinfo->bytes_may_use;
3818
3819         if (sinfo->total_bytes > num_bytes) {
3820                 num_bytes = sinfo->total_bytes - num_bytes;
3821                 block_rsv->reserved += num_bytes;
3822                 sinfo->bytes_reserved += num_bytes;
3823         }
3824
3825         if (block_rsv->reserved >= block_rsv->size) {
3826                 num_bytes = block_rsv->reserved - block_rsv->size;
3827                 sinfo->bytes_reserved -= num_bytes;
3828                 block_rsv->reserved = block_rsv->size;
3829                 block_rsv->full = 1;
3830         }
3831 #if 0
3832         printk(KERN_INFO"global block rsv size %llu reserved %llu\n",
3833                 block_rsv->size, block_rsv->reserved);
3834 #endif
3835         spin_unlock(&sinfo->lock);
3836         spin_unlock(&block_rsv->lock);
3837 }
3838
3839 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
3840 {
3841         struct btrfs_space_info *space_info;
3842
3843         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3844         fs_info->chunk_block_rsv.space_info = space_info;
3845         fs_info->chunk_block_rsv.priority = 10;
3846
3847         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
3848         fs_info->global_block_rsv.space_info = space_info;
3849         fs_info->global_block_rsv.priority = 10;
3850         fs_info->global_block_rsv.refill_used = 1;
3851         fs_info->delalloc_block_rsv.space_info = space_info;
3852         fs_info->trans_block_rsv.space_info = space_info;
3853         fs_info->empty_block_rsv.space_info = space_info;
3854         fs_info->empty_block_rsv.priority = 10;
3855
3856         fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
3857         fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
3858         fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
3859         fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
3860         fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
3861
3862         btrfs_add_durable_block_rsv(fs_info, &fs_info->global_block_rsv);
3863
3864         btrfs_add_durable_block_rsv(fs_info, &fs_info->delalloc_block_rsv);
3865
3866         update_global_block_rsv(fs_info);
3867 }
3868
3869 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
3870 {
3871         block_rsv_release_bytes(&fs_info->global_block_rsv, NULL, (u64)-1);
3872         WARN_ON(fs_info->delalloc_block_rsv.size > 0);
3873         WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
3874         WARN_ON(fs_info->trans_block_rsv.size > 0);
3875         WARN_ON(fs_info->trans_block_rsv.reserved > 0);
3876         WARN_ON(fs_info->chunk_block_rsv.size > 0);
3877         WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
3878 }
3879
3880 static u64 calc_trans_metadata_size(struct btrfs_root *root, int num_items)
3881 {
3882         return (root->leafsize + root->nodesize * (BTRFS_MAX_LEVEL - 1)) *
3883                 3 * num_items;
3884 }
3885
3886 int btrfs_trans_reserve_metadata(struct btrfs_trans_handle *trans,
3887                                  struct btrfs_root *root,
3888                                  int num_items)
3889 {
3890         u64 num_bytes;
3891         int ret;
3892
3893         if (num_items == 0 || root->fs_info->chunk_root == root)
3894                 return 0;
3895
3896         num_bytes = calc_trans_metadata_size(root, num_items);
3897         ret = btrfs_block_rsv_add(trans, root, &root->fs_info->trans_block_rsv,
3898                                   num_bytes);
3899         if (!ret) {
3900                 trans->bytes_reserved += num_bytes;
3901                 trans->block_rsv = &root->fs_info->trans_block_rsv;
3902         }
3903         return ret;
3904 }
3905
3906 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
3907                                   struct btrfs_root *root)
3908 {
3909         if (!trans->bytes_reserved)
3910                 return;
3911
3912         BUG_ON(trans->block_rsv != &root->fs_info->trans_block_rsv);
3913         btrfs_block_rsv_release(root, trans->block_rsv,
3914                                 trans->bytes_reserved);
3915         trans->bytes_reserved = 0;
3916 }
3917
3918 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
3919                                   struct inode *inode)
3920 {
3921         struct btrfs_root *root = BTRFS_I(inode)->root;
3922         struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
3923         struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
3924
3925         /*
3926          * one for deleting orphan item, one for updating inode and
3927          * two for calling btrfs_truncate_inode_items.
3928          *
3929          * btrfs_truncate_inode_items is a delete operation, it frees
3930          * more space than it uses in most cases. So two units of
3931          * metadata space should be enough for calling it many times.
3932          * If all of the metadata space is used, we can commit
3933          * transaction and use space it freed.
3934          */
3935         u64 num_bytes = calc_trans_metadata_size(root, 4);
3936         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
3937 }
3938
3939 void btrfs_orphan_release_metadata(struct inode *inode)
3940 {
3941         struct btrfs_root *root = BTRFS_I(inode)->root;
3942         u64 num_bytes = calc_trans_metadata_size(root, 4);
3943         btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
3944 }
3945
3946 int btrfs_snap_reserve_metadata(struct btrfs_trans_handle *trans,
3947                                 struct btrfs_pending_snapshot *pending)
3948 {
3949         struct btrfs_root *root = pending->root;
3950         struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
3951         struct btrfs_block_rsv *dst_rsv = &pending->block_rsv;
3952         /*
3953          * two for root back/forward refs, two for directory entries
3954          * and one for root of the snapshot.
3955          */
3956         u64 num_bytes = calc_trans_metadata_size(root, 5);
3957         dst_rsv->space_info = src_rsv->space_info;
3958         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
3959 }
3960
3961 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes)
3962 {
3963         return num_bytes >>= 3;
3964 }
3965
3966 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
3967 {
3968         struct btrfs_root *root = BTRFS_I(inode)->root;
3969         struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
3970         u64 to_reserve;
3971         int nr_extents;
3972         int ret;
3973
3974         if (btrfs_transaction_in_commit(root->fs_info))
3975                 schedule_timeout(1);
3976
3977         num_bytes = ALIGN(num_bytes, root->sectorsize);
3978
3979         spin_lock(&BTRFS_I(inode)->accounting_lock);
3980         nr_extents = atomic_read(&BTRFS_I(inode)->outstanding_extents) + 1;
3981         if (nr_extents > BTRFS_I(inode)->reserved_extents) {
3982                 nr_extents -= BTRFS_I(inode)->reserved_extents;
3983                 to_reserve = calc_trans_metadata_size(root, nr_extents);
3984         } else {
3985                 nr_extents = 0;
3986                 to_reserve = 0;
3987         }
3988         spin_unlock(&BTRFS_I(inode)->accounting_lock);
3989
3990         to_reserve += calc_csum_metadata_size(inode, num_bytes);
3991         ret = reserve_metadata_bytes(NULL, root, block_rsv, to_reserve, 1);
3992         if (ret)
3993                 return ret;
3994
3995         spin_lock(&BTRFS_I(inode)->accounting_lock);
3996         BTRFS_I(inode)->reserved_extents += nr_extents;
3997         atomic_inc(&BTRFS_I(inode)->outstanding_extents);
3998         spin_unlock(&BTRFS_I(inode)->accounting_lock);
3999
4000         block_rsv_add_bytes(block_rsv, to_reserve, 1);
4001
4002         if (block_rsv->size > 512 * 1024 * 1024)
4003                 shrink_delalloc(NULL, root, to_reserve, 0);
4004
4005         return 0;
4006 }
4007
4008 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
4009 {
4010         struct btrfs_root *root = BTRFS_I(inode)->root;
4011         u64 to_free;
4012         int nr_extents;
4013
4014         num_bytes = ALIGN(num_bytes, root->sectorsize);
4015         atomic_dec(&BTRFS_I(inode)->outstanding_extents);
4016
4017         spin_lock(&BTRFS_I(inode)->accounting_lock);
4018         nr_extents = atomic_read(&BTRFS_I(inode)->outstanding_extents);
4019         if (nr_extents < BTRFS_I(inode)->reserved_extents) {
4020                 nr_extents = BTRFS_I(inode)->reserved_extents - nr_extents;
4021                 BTRFS_I(inode)->reserved_extents -= nr_extents;
4022         } else {
4023                 nr_extents = 0;
4024         }
4025         spin_unlock(&BTRFS_I(inode)->accounting_lock);
4026
4027         to_free = calc_csum_metadata_size(inode, num_bytes);
4028         if (nr_extents > 0)
4029                 to_free += calc_trans_metadata_size(root, nr_extents);
4030
4031         btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
4032                                 to_free);
4033 }
4034
4035 int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
4036 {
4037         int ret;
4038
4039         ret = btrfs_check_data_free_space(inode, num_bytes);
4040         if (ret)
4041                 return ret;
4042
4043         ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
4044         if (ret) {
4045                 btrfs_free_reserved_data_space(inode, num_bytes);
4046                 return ret;
4047         }
4048
4049         return 0;
4050 }
4051
4052 void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
4053 {
4054         btrfs_delalloc_release_metadata(inode, num_bytes);
4055         btrfs_free_reserved_data_space(inode, num_bytes);
4056 }
4057
4058 static int update_block_group(struct btrfs_trans_handle *trans,
4059                               struct btrfs_root *root,
4060                               u64 bytenr, u64 num_bytes, int alloc)
4061 {
4062         struct btrfs_block_group_cache *cache = NULL;
4063         struct btrfs_fs_info *info = root->fs_info;
4064         u64 total = num_bytes;
4065         u64 old_val;
4066         u64 byte_in_group;
4067         int factor;
4068
4069         /* block accounting for super block */
4070         spin_lock(&info->delalloc_lock);
4071         old_val = btrfs_super_bytes_used(&info->super_copy);
4072         if (alloc)
4073                 old_val += num_bytes;
4074         else
4075                 old_val -= num_bytes;
4076         btrfs_set_super_bytes_used(&info->super_copy, old_val);
4077         spin_unlock(&info->delalloc_lock);
4078
4079         while (total) {
4080                 cache = btrfs_lookup_block_group(info, bytenr);
4081                 if (!cache)
4082                         return -1;
4083                 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
4084                                     BTRFS_BLOCK_GROUP_RAID1 |
4085                                     BTRFS_BLOCK_GROUP_RAID10))
4086                         factor = 2;
4087                 else
4088                         factor = 1;
4089                 /*
4090                  * If this block group has free space cache written out, we
4091                  * need to make sure to load it if we are removing space.  This
4092                  * is because we need the unpinning stage to actually add the
4093                  * space back to the block group, otherwise we will leak space.
4094                  */
4095                 if (!alloc && cache->cached == BTRFS_CACHE_NO)
4096                         cache_block_group(cache, trans, NULL, 1);
4097
4098                 byte_in_group = bytenr - cache->key.objectid;
4099                 WARN_ON(byte_in_group > cache->key.offset);
4100
4101                 spin_lock(&cache->space_info->lock);
4102                 spin_lock(&cache->lock);
4103
4104                 if (btrfs_super_cache_generation(&info->super_copy) != 0 &&
4105                     cache->disk_cache_state < BTRFS_DC_CLEAR)
4106                         cache->disk_cache_state = BTRFS_DC_CLEAR;
4107
4108                 cache->dirty = 1;
4109                 old_val = btrfs_block_group_used(&cache->item);
4110                 num_bytes = min(total, cache->key.offset - byte_in_group);
4111                 if (alloc) {
4112                         old_val += num_bytes;
4113                         btrfs_set_block_group_used(&cache->item, old_val);
4114                         cache->reserved -= num_bytes;
4115                         cache->space_info->bytes_reserved -= num_bytes;
4116                         cache->space_info->bytes_used += num_bytes;
4117                         cache->space_info->disk_used += num_bytes * factor;
4118                         spin_unlock(&cache->lock);
4119                         spin_unlock(&cache->space_info->lock);
4120                 } else {
4121                         old_val -= num_bytes;
4122                         btrfs_set_block_group_used(&cache->item, old_val);
4123                         cache->pinned += num_bytes;
4124                         cache->space_info->bytes_pinned += num_bytes;
4125                         cache->space_info->bytes_used -= num_bytes;
4126                         cache->space_info->disk_used -= num_bytes * factor;
4127                         spin_unlock(&cache->lock);
4128                         spin_unlock(&cache->space_info->lock);
4129
4130                         set_extent_dirty(info->pinned_extents,
4131                                          bytenr, bytenr + num_bytes - 1,
4132                                          GFP_NOFS | __GFP_NOFAIL);
4133                 }
4134                 btrfs_put_block_group(cache);
4135                 total -= num_bytes;
4136                 bytenr += num_bytes;
4137         }
4138         return 0;
4139 }
4140
4141 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
4142 {
4143         struct btrfs_block_group_cache *cache;
4144         u64 bytenr;
4145
4146         cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
4147         if (!cache)
4148                 return 0;
4149
4150         bytenr = cache->key.objectid;
4151         btrfs_put_block_group(cache);
4152
4153         return bytenr;
4154 }
4155
4156 static int pin_down_extent(struct btrfs_root *root,
4157                            struct btrfs_block_group_cache *cache,
4158                            u64 bytenr, u64 num_bytes, int reserved)
4159 {
4160         spin_lock(&cache->space_info->lock);
4161         spin_lock(&cache->lock);
4162         cache->pinned += num_bytes;
4163         cache->space_info->bytes_pinned += num_bytes;
4164         if (reserved) {
4165                 cache->reserved -= num_bytes;
4166                 cache->space_info->bytes_reserved -= num_bytes;
4167         }
4168         spin_unlock(&cache->lock);
4169         spin_unlock(&cache->space_info->lock);
4170
4171         set_extent_dirty(root->fs_info->pinned_extents, bytenr,
4172                          bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
4173         return 0;
4174 }
4175
4176 /*
4177  * this function must be called within transaction
4178  */
4179 int btrfs_pin_extent(struct btrfs_root *root,
4180                      u64 bytenr, u64 num_bytes, int reserved)
4181 {
4182         struct btrfs_block_group_cache *cache;
4183
4184         cache = btrfs_lookup_block_group(root->fs_info, bytenr);
4185         BUG_ON(!cache);
4186
4187         pin_down_extent(root, cache, bytenr, num_bytes, reserved);
4188
4189         btrfs_put_block_group(cache);
4190         return 0;
4191 }
4192
4193 /*
4194  * update size of reserved extents. this function may return -EAGAIN
4195  * if 'reserve' is true or 'sinfo' is false.
4196  */
4197 static int update_reserved_bytes(struct btrfs_block_group_cache *cache,
4198                                  u64 num_bytes, int reserve, int sinfo)
4199 {
4200         int ret = 0;
4201         if (sinfo) {
4202                 struct btrfs_space_info *space_info = cache->space_info;
4203                 spin_lock(&space_info->lock);
4204                 spin_lock(&cache->lock);
4205                 if (reserve) {
4206                         if (cache->ro) {
4207                                 ret = -EAGAIN;
4208                         } else {
4209                                 cache->reserved += num_bytes;
4210                                 space_info->bytes_reserved += num_bytes;
4211                         }
4212                 } else {
4213                         if (cache->ro)
4214                                 space_info->bytes_readonly += num_bytes;
4215                         cache->reserved -= num_bytes;
4216                         space_info->bytes_reserved -= num_bytes;
4217                 }
4218                 spin_unlock(&cache->lock);
4219                 spin_unlock(&space_info->lock);
4220         } else {
4221                 spin_lock(&cache->lock);
4222                 if (cache->ro) {
4223                         ret = -EAGAIN;
4224                 } else {
4225                         if (reserve)
4226                                 cache->reserved += num_bytes;
4227                         else
4228                                 cache->reserved -= num_bytes;
4229                 }
4230                 spin_unlock(&cache->lock);
4231         }
4232         return ret;
4233 }
4234
4235 int btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
4236                                 struct btrfs_root *root)
4237 {
4238         struct btrfs_fs_info *fs_info = root->fs_info;
4239         struct btrfs_caching_control *next;
4240         struct btrfs_caching_control *caching_ctl;
4241         struct btrfs_block_group_cache *cache;
4242
4243         down_write(&fs_info->extent_commit_sem);
4244
4245         list_for_each_entry_safe(caching_ctl, next,
4246                                  &fs_info->caching_block_groups, list) {
4247                 cache = caching_ctl->block_group;
4248                 if (block_group_cache_done(cache)) {
4249                         cache->last_byte_to_unpin = (u64)-1;
4250                         list_del_init(&caching_ctl->list);
4251                         put_caching_control(caching_ctl);
4252                 } else {
4253                         cache->last_byte_to_unpin = caching_ctl->progress;
4254                 }
4255         }
4256
4257         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4258                 fs_info->pinned_extents = &fs_info->freed_extents[1];
4259         else
4260                 fs_info->pinned_extents = &fs_info->freed_extents[0];
4261
4262         up_write(&fs_info->extent_commit_sem);
4263
4264         update_global_block_rsv(fs_info);
4265         return 0;
4266 }
4267
4268 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
4269 {
4270         struct btrfs_fs_info *fs_info = root->fs_info;
4271         struct btrfs_block_group_cache *cache = NULL;
4272         u64 len;
4273
4274         while (start <= end) {
4275                 if (!cache ||
4276                     start >= cache->key.objectid + cache->key.offset) {
4277                         if (cache)
4278                                 btrfs_put_block_group(cache);
4279                         cache = btrfs_lookup_block_group(fs_info, start);
4280                         BUG_ON(!cache);
4281                 }
4282
4283                 len = cache->key.objectid + cache->key.offset - start;
4284                 len = min(len, end + 1 - start);
4285
4286                 if (start < cache->last_byte_to_unpin) {
4287                         len = min(len, cache->last_byte_to_unpin - start);
4288                         btrfs_add_free_space(cache, start, len);
4289                 }
4290
4291                 start += len;
4292
4293                 spin_lock(&cache->space_info->lock);
4294                 spin_lock(&cache->lock);
4295                 cache->pinned -= len;
4296                 cache->space_info->bytes_pinned -= len;
4297                 if (cache->ro) {
4298                         cache->space_info->bytes_readonly += len;
4299                 } else if (cache->reserved_pinned > 0) {
4300                         len = min(len, cache->reserved_pinned);
4301                         cache->reserved_pinned -= len;
4302                         cache->space_info->bytes_reserved += len;
4303                 }
4304                 spin_unlock(&cache->lock);
4305                 spin_unlock(&cache->space_info->lock);
4306         }
4307
4308         if (cache)
4309                 btrfs_put_block_group(cache);
4310         return 0;
4311 }
4312
4313 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
4314                                struct btrfs_root *root)
4315 {
4316         struct btrfs_fs_info *fs_info = root->fs_info;
4317         struct extent_io_tree *unpin;
4318         struct btrfs_block_rsv *block_rsv;
4319         struct btrfs_block_rsv *next_rsv;
4320         u64 start;
4321         u64 end;
4322         int idx;
4323         int ret;
4324
4325         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4326                 unpin = &fs_info->freed_extents[1];
4327         else
4328                 unpin = &fs_info->freed_extents[0];
4329
4330         while (1) {
4331                 ret = find_first_extent_bit(unpin, 0, &start, &end,
4332                                             EXTENT_DIRTY);
4333                 if (ret)
4334                         break;
4335
4336                 ret = btrfs_discard_extent(root, start, end + 1 - start);
4337
4338                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
4339                 unpin_extent_range(root, start, end);
4340                 cond_resched();
4341         }
4342
4343         mutex_lock(&fs_info->durable_block_rsv_mutex);
4344         list_for_each_entry_safe(block_rsv, next_rsv,
4345                                  &fs_info->durable_block_rsv_list, list) {
4346
4347                 idx = trans->transid & 0x1;
4348                 if (block_rsv->freed[idx] > 0) {
4349                         block_rsv_add_bytes(block_rsv,
4350                                             block_rsv->freed[idx], 0);
4351                         block_rsv->freed[idx] = 0;
4352                 }
4353                 if (atomic_read(&block_rsv->usage) == 0) {
4354                         btrfs_block_rsv_release(root, block_rsv, (u64)-1);
4355
4356                         if (block_rsv->freed[0] == 0 &&
4357                             block_rsv->freed[1] == 0) {
4358                                 list_del_init(&block_rsv->list);
4359                                 kfree(block_rsv);
4360                         }
4361                 } else {
4362                         btrfs_block_rsv_release(root, block_rsv, 0);
4363                 }
4364         }
4365         mutex_unlock(&fs_info->durable_block_rsv_mutex);
4366
4367         return 0;
4368 }
4369
4370 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
4371                                 struct btrfs_root *root,
4372                                 u64 bytenr, u64 num_bytes, u64 parent,
4373                                 u64 root_objectid, u64 owner_objectid,
4374                                 u64 owner_offset, int refs_to_drop,
4375                                 struct btrfs_delayed_extent_op *extent_op)
4376 {
4377         struct btrfs_key key;
4378         struct btrfs_path *path;
4379         struct btrfs_fs_info *info = root->fs_info;
4380         struct btrfs_root *extent_root = info->extent_root;
4381         struct extent_buffer *leaf;
4382         struct btrfs_extent_item *ei;
4383         struct btrfs_extent_inline_ref *iref;
4384         int ret;
4385         int is_data;
4386         int extent_slot = 0;
4387         int found_extent = 0;
4388         int num_to_del = 1;
4389         u32 item_size;
4390         u64 refs;
4391
4392         path = btrfs_alloc_path();
4393         if (!path)
4394                 return -ENOMEM;
4395
4396         path->reada = 1;
4397         path->leave_spinning = 1;
4398
4399         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
4400         BUG_ON(!is_data && refs_to_drop != 1);
4401
4402         ret = lookup_extent_backref(trans, extent_root, path, &iref,
4403                                     bytenr, num_bytes, parent,
4404                                     root_objectid, owner_objectid,
4405                                     owner_offset);
4406         if (ret == 0) {
4407                 extent_slot = path->slots[0];
4408                 while (extent_slot >= 0) {
4409                         btrfs_item_key_to_cpu(path->nodes[0], &key,
4410                                               extent_slot);
4411                         if (key.objectid != bytenr)
4412                                 break;
4413                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
4414                             key.offset == num_bytes) {
4415                                 found_extent = 1;
4416                                 break;
4417                         }
4418                         if (path->slots[0] - extent_slot > 5)
4419                                 break;
4420                         extent_slot--;
4421                 }
4422 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4423                 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
4424                 if (found_extent && item_size < sizeof(*ei))
4425                         found_extent = 0;
4426 #endif
4427                 if (!found_extent) {
4428                         BUG_ON(iref);
4429                         ret = remove_extent_backref(trans, extent_root, path,
4430                                                     NULL, refs_to_drop,
4431                                                     is_data);
4432                         BUG_ON(ret);
4433                         btrfs_release_path(extent_root, path);
4434                         path->leave_spinning = 1;
4435
4436                         key.objectid = bytenr;
4437                         key.type = BTRFS_EXTENT_ITEM_KEY;
4438                         key.offset = num_bytes;
4439
4440                         ret = btrfs_search_slot(trans, extent_root,
4441                                                 &key, path, -1, 1);
4442                         if (ret) {
4443                                 printk(KERN_ERR "umm, got %d back from search"
4444                                        ", was looking for %llu\n", ret,
4445                                        (unsigned long long)bytenr);
4446                                 btrfs_print_leaf(extent_root, path->nodes[0]);
4447                         }
4448                         BUG_ON(ret);
4449                         extent_slot = path->slots[0];
4450                 }
4451         } else {
4452                 btrfs_print_leaf(extent_root, path->nodes[0]);
4453                 WARN_ON(1);
4454                 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
4455                        "parent %llu root %llu  owner %llu offset %llu\n",
4456                        (unsigned long long)bytenr,
4457                        (unsigned long long)parent,
4458                        (unsigned long long)root_objectid,
4459                        (unsigned long long)owner_objectid,
4460                        (unsigned long long)owner_offset);
4461         }
4462
4463         leaf = path->nodes[0];
4464         item_size = btrfs_item_size_nr(leaf, extent_slot);
4465 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
4466         if (item_size < sizeof(*ei)) {
4467                 BUG_ON(found_extent || extent_slot != path->slots[0]);
4468                 ret = convert_extent_item_v0(trans, extent_root, path,
4469                                              owner_objectid, 0);
4470                 BUG_ON(ret < 0);
4471
4472                 btrfs_release_path(extent_root, path);
4473                 path->leave_spinning = 1;
4474
4475                 key.objectid = bytenr;
4476                 key.type = BTRFS_EXTENT_ITEM_KEY;
4477                 key.offset = num_bytes;
4478
4479                 ret = btrfs_search_slot(trans, extent_root, &key, path,
4480                                         -1, 1);
4481                 if (ret) {
4482                         printk(KERN_ERR "umm, got %d back from search"
4483                                ", was looking for %llu\n", ret,
4484                                (unsigned long long)bytenr);
4485                         btrfs_print_leaf(extent_root, path->nodes[0]);
4486                 }
4487                 BUG_ON(ret);
4488                 extent_slot = path->slots[0];
4489                 leaf = path->nodes[0];
4490                 item_size = btrfs_item_size_nr(leaf, extent_slot);
4491         }
4492 #endif
4493         BUG_ON(item_size < sizeof(*ei));
4494         ei = btrfs_item_ptr(leaf, extent_slot,
4495                             struct btrfs_extent_item);
4496         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
4497                 struct btrfs_tree_block_info *bi;
4498                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
4499                 bi = (struct btrfs_tree_block_info *)(ei + 1);
4500                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
4501         }
4502
4503         refs = btrfs_extent_refs(leaf, ei);
4504         BUG_ON(refs < refs_to_drop);
4505         refs -= refs_to_drop;
4506
4507         if (refs > 0) {
4508                 if (extent_op)
4509                         __run_delayed_extent_op(extent_op, leaf, ei);
4510                 /*
4511                  * In the case of inline back ref, reference count will
4512                  * be updated by remove_extent_backref
4513                  */
4514                 if (iref) {
4515                         BUG_ON(!found_extent);
4516                 } else {
4517                         btrfs_set_extent_refs(leaf, ei, refs);
4518                         btrfs_mark_buffer_dirty(leaf);
4519                 }
4520                 if (found_extent) {
4521                         ret = remove_extent_backref(trans, extent_root, path,
4522                                                     iref, refs_to_drop,
4523                                                     is_data);
4524                         BUG_ON(ret);
4525                 }
4526         } else {
4527                 if (found_extent) {
4528                         BUG_ON(is_data && refs_to_drop !=
4529                                extent_data_ref_count(root, path, iref));
4530                         if (iref) {
4531                                 BUG_ON(path->slots[0] != extent_slot);
4532                         } else {
4533                                 BUG_ON(path->slots[0] != extent_slot + 1);
4534                                 path->slots[0] = extent_slot;
4535                                 num_to_del = 2;
4536                         }
4537                 }
4538
4539                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
4540                                       num_to_del);
4541                 BUG_ON(ret);
4542                 btrfs_release_path(extent_root, path);
4543
4544                 if (is_data) {
4545                         ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
4546                         BUG_ON(ret);
4547                 } else {
4548                         invalidate_mapping_pages(info->btree_inode->i_mapping,
4549                              bytenr >> PAGE_CACHE_SHIFT,
4550                              (bytenr + num_bytes - 1) >> PAGE_CACHE_SHIFT);
4551                 }
4552
4553                 ret = update_block_group(trans, root, bytenr, num_bytes, 0);
4554                 BUG_ON(ret);
4555         }
4556         btrfs_free_path(path);
4557         return ret;
4558 }
4559
4560 /*
4561  * when we free an block, it is possible (and likely) that we free the last
4562  * delayed ref for that extent as well.  This searches the delayed ref tree for
4563  * a given extent, and if there are no other delayed refs to be processed, it
4564  * removes it from the tree.
4565  */
4566 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
4567                                       struct btrfs_root *root, u64 bytenr)
4568 {
4569         struct btrfs_delayed_ref_head *head;
4570         struct btrfs_delayed_ref_root *delayed_refs;
4571         struct btrfs_delayed_ref_node *ref;
4572         struct rb_node *node;
4573         int ret = 0;
4574
4575         delayed_refs = &trans->transaction->delayed_refs;
4576         spin_lock(&delayed_refs->lock);
4577         head = btrfs_find_delayed_ref_head(trans, bytenr);
4578         if (!head)
4579                 goto out;
4580
4581         node = rb_prev(&head->node.rb_node);
4582         if (!node)
4583                 goto out;
4584
4585         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
4586
4587         /* there are still entries for this ref, we can't drop it */
4588         if (ref->bytenr == bytenr)
4589                 goto out;
4590
4591         if (head->extent_op) {
4592                 if (!head->must_insert_reserved)
4593                         goto out;
4594                 kfree(head->extent_op);
4595                 head->extent_op = NULL;
4596         }
4597
4598         /*
4599          * waiting for the lock here would deadlock.  If someone else has it
4600          * locked they are already in the process of dropping it anyway
4601          */
4602         if (!mutex_trylock(&head->mutex))
4603                 goto out;
4604
4605         /*
4606          * at this point we have a head with no other entries.  Go
4607          * ahead and process it.
4608          */
4609         head->node.in_tree = 0;
4610         rb_erase(&head->node.rb_node, &delayed_refs->root);
4611
4612         delayed_refs->num_entries--;
4613
4614         /*
4615          * we don't take a ref on the node because we're removing it from the
4616          * tree, so we just steal the ref the tree was holding.
4617          */
4618         delayed_refs->num_heads--;
4619         if (list_empty(&head->cluster))
4620                 delayed_refs->num_heads_ready--;
4621
4622         list_del_init(&head->cluster);
4623         spin_unlock(&delayed_refs->lock);
4624
4625         BUG_ON(head->extent_op);
4626         if (head->must_insert_reserved)
4627                 ret = 1;
4628
4629         mutex_unlock(&head->mutex);
4630         btrfs_put_delayed_ref(&head->node);
4631         return ret;
4632 out:
4633         spin_unlock(&delayed_refs->lock);
4634         return 0;
4635 }
4636
4637 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
4638                            struct btrfs_root *root,
4639                            struct extent_buffer *buf,
4640                            u64 parent, int last_ref)
4641 {
4642         struct btrfs_block_rsv *block_rsv;
4643         struct btrfs_block_group_cache *cache = NULL;
4644         int ret;
4645
4646         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4647                 ret = btrfs_add_delayed_tree_ref(trans, buf->start, buf->len,
4648                                                 parent, root->root_key.objectid,
4649                                                 btrfs_header_level(buf),
4650                                                 BTRFS_DROP_DELAYED_REF, NULL);
4651                 BUG_ON(ret);
4652         }
4653
4654         if (!last_ref)
4655                 return;
4656
4657         block_rsv = get_block_rsv(trans, root);
4658         cache = btrfs_lookup_block_group(root->fs_info, buf->start);
4659         if (block_rsv->space_info != cache->space_info)
4660                 goto out;
4661
4662         if (btrfs_header_generation(buf) == trans->transid) {
4663                 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
4664                         ret = check_ref_cleanup(trans, root, buf->start);
4665                         if (!ret)
4666                                 goto pin;
4667                 }
4668
4669                 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
4670                         pin_down_extent(root, cache, buf->start, buf->len, 1);
4671                         goto pin;
4672                 }
4673
4674                 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
4675
4676                 btrfs_add_free_space(cache, buf->start, buf->len);
4677                 ret = update_reserved_bytes(cache, buf->len, 0, 0);
4678                 if (ret == -EAGAIN) {
4679                         /* block group became read-only */
4680                         update_reserved_bytes(cache, buf->len, 0, 1);
4681                         goto out;
4682                 }
4683
4684                 ret = 1;
4685                 spin_lock(&block_rsv->lock);
4686                 if (block_rsv->reserved < block_rsv->size) {
4687                         block_rsv->reserved += buf->len;
4688                         ret = 0;
4689                 }
4690                 spin_unlock(&block_rsv->lock);
4691
4692                 if (ret) {
4693                         spin_lock(&cache->space_info->lock);
4694                         cache->space_info->bytes_reserved -= buf->len;
4695                         spin_unlock(&cache->space_info->lock);
4696                 }
4697                 goto out;
4698         }
4699 pin:
4700         if (block_rsv->durable && !cache->ro) {
4701                 ret = 0;
4702                 spin_lock(&cache->lock);
4703                 if (!cache->ro) {
4704                         cache->reserved_pinned += buf->len;
4705                         ret = 1;
4706                 }
4707                 spin_unlock(&cache->lock);
4708
4709                 if (ret) {
4710                         spin_lock(&block_rsv->lock);
4711                         block_rsv->freed[trans->transid & 0x1] += buf->len;
4712                         spin_unlock(&block_rsv->lock);
4713                 }
4714         }
4715 out:
4716         btrfs_put_block_group(cache);
4717 }
4718
4719 int btrfs_free_extent(struct btrfs_trans_handle *trans,
4720                       struct btrfs_root *root,
4721                       u64 bytenr, u64 num_bytes, u64 parent,
4722                       u64 root_objectid, u64 owner, u64 offset)
4723 {
4724         int ret;
4725
4726         /*
4727          * tree log blocks never actually go into the extent allocation
4728          * tree, just update pinning info and exit early.
4729          */
4730         if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
4731                 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
4732                 /* unlocks the pinned mutex */
4733                 btrfs_pin_extent(root, bytenr, num_bytes, 1);
4734                 ret = 0;
4735         } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
4736                 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
4737                                         parent, root_objectid, (int)owner,
4738                                         BTRFS_DROP_DELAYED_REF, NULL);
4739                 BUG_ON(ret);
4740         } else {
4741                 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
4742                                         parent, root_objectid, owner,
4743                                         offset, BTRFS_DROP_DELAYED_REF, NULL);
4744                 BUG_ON(ret);
4745         }
4746         return ret;
4747 }
4748
4749 static u64 stripe_align(struct btrfs_root *root, u64 val)
4750 {
4751         u64 mask = ((u64)root->stripesize - 1);
4752         u64 ret = (val + mask) & ~mask;
4753         return ret;
4754 }
4755
4756 /*
4757  * when we wait for progress in the block group caching, its because
4758  * our allocation attempt failed at least once.  So, we must sleep
4759  * and let some progress happen before we try again.
4760  *
4761  * This function will sleep at least once waiting for new free space to
4762  * show up, and then it will check the block group free space numbers
4763  * for our min num_bytes.  Another option is to have it go ahead
4764  * and look in the rbtree for a free extent of a given size, but this
4765  * is a good start.
4766  */
4767 static noinline int
4768 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
4769                                 u64 num_bytes)
4770 {
4771         struct btrfs_caching_control *caching_ctl;
4772         DEFINE_WAIT(wait);
4773
4774         caching_ctl = get_caching_control(cache);
4775         if (!caching_ctl)
4776                 return 0;
4777
4778         wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
4779                    (cache->free_space >= num_bytes));
4780
4781         put_caching_control(caching_ctl);
4782         return 0;
4783 }
4784
4785 static noinline int
4786 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
4787 {
4788         struct btrfs_caching_control *caching_ctl;
4789         DEFINE_WAIT(wait);
4790
4791         caching_ctl = get_caching_control(cache);
4792         if (!caching_ctl)
4793                 return 0;
4794
4795         wait_event(caching_ctl->wait, block_group_cache_done(cache));
4796
4797         put_caching_control(caching_ctl);
4798         return 0;
4799 }
4800
4801 static int get_block_group_index(struct btrfs_block_group_cache *cache)
4802 {
4803         int index;
4804         if (cache->flags & BTRFS_BLOCK_GROUP_RAID10)
4805                 index = 0;
4806         else if (cache->flags & BTRFS_BLOCK_GROUP_RAID1)
4807                 index = 1;
4808         else if (cache->flags & BTRFS_BLOCK_GROUP_DUP)
4809                 index = 2;
4810         else if (cache->flags & BTRFS_BLOCK_GROUP_RAID0)
4811                 index = 3;
4812         else
4813                 index = 4;
4814         return index;
4815 }
4816
4817 enum btrfs_loop_type {
4818         LOOP_FIND_IDEAL = 0,
4819         LOOP_CACHING_NOWAIT = 1,
4820         LOOP_CACHING_WAIT = 2,
4821         LOOP_ALLOC_CHUNK = 3,
4822         LOOP_NO_EMPTY_SIZE = 4,
4823 };
4824
4825 /*
4826  * walks the btree of allocated extents and find a hole of a given size.
4827  * The key ins is changed to record the hole:
4828  * ins->objectid == block start
4829  * ins->flags = BTRFS_EXTENT_ITEM_KEY
4830  * ins->offset == number of blocks
4831  * Any available blocks before search_start are skipped.
4832  */
4833 static noinline int find_free_extent(struct btrfs_trans_handle *trans,
4834                                      struct btrfs_root *orig_root,
4835                                      u64 num_bytes, u64 empty_size,
4836                                      u64 search_start, u64 search_end,
4837                                      u64 hint_byte, struct btrfs_key *ins,
4838                                      int data)
4839 {
4840         int ret = 0;
4841         struct btrfs_root *root = orig_root->fs_info->extent_root;
4842         struct btrfs_free_cluster *last_ptr = NULL;
4843         struct btrfs_block_group_cache *block_group = NULL;
4844         int empty_cluster = 2 * 1024 * 1024;
4845         int allowed_chunk_alloc = 0;
4846         int done_chunk_alloc = 0;
4847         struct btrfs_space_info *space_info;
4848         int last_ptr_loop = 0;
4849         int loop = 0;
4850         int index = 0;
4851         bool found_uncached_bg = false;
4852         bool failed_cluster_refill = false;
4853         bool failed_alloc = false;
4854         bool use_cluster = true;
4855         u64 ideal_cache_percent = 0;
4856         u64 ideal_cache_offset = 0;
4857
4858         WARN_ON(num_bytes < root->sectorsize);
4859         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
4860         ins->objectid = 0;
4861         ins->offset = 0;
4862
4863         space_info = __find_space_info(root->fs_info, data);
4864         if (!space_info) {
4865                 printk(KERN_ERR "No space info for %d\n", data);
4866                 return -ENOSPC;
4867         }
4868
4869         /*
4870          * If the space info is for both data and metadata it means we have a
4871          * small filesystem and we can't use the clustering stuff.
4872          */
4873         if (btrfs_mixed_space_info(space_info))
4874                 use_cluster = false;
4875
4876         if (orig_root->ref_cows || empty_size)
4877                 allowed_chunk_alloc = 1;
4878
4879         if (data & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
4880                 last_ptr = &root->fs_info->meta_alloc_cluster;
4881                 if (!btrfs_test_opt(root, SSD))
4882                         empty_cluster = 64 * 1024;
4883         }
4884
4885         if ((data & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
4886             btrfs_test_opt(root, SSD)) {
4887                 last_ptr = &root->fs_info->data_alloc_cluster;
4888         }
4889
4890         if (last_ptr) {
4891                 spin_lock(&last_ptr->lock);
4892                 if (last_ptr->block_group)
4893                         hint_byte = last_ptr->window_start;
4894                 spin_unlock(&last_ptr->lock);
4895         }
4896
4897         search_start = max(search_start, first_logical_byte(root, 0));
4898         search_start = max(search_start, hint_byte);
4899
4900         if (!last_ptr)
4901                 empty_cluster = 0;
4902
4903         if (search_start == hint_byte) {
4904 ideal_cache:
4905                 block_group = btrfs_lookup_block_group(root->fs_info,
4906                                                        search_start);
4907                 /*
4908                  * we don't want to use the block group if it doesn't match our
4909                  * allocation bits, or if its not cached.
4910                  *
4911                  * However if we are re-searching with an ideal block group
4912                  * picked out then we don't care that the block group is cached.
4913                  */
4914                 if (block_group && block_group_bits(block_group, data) &&
4915                     (block_group->cached != BTRFS_CACHE_NO ||
4916                      search_start == ideal_cache_offset)) {
4917                         down_read(&space_info->groups_sem);
4918                         if (list_empty(&block_group->list) ||
4919                             block_group->ro) {
4920                                 /*
4921                                  * someone is removing this block group,
4922                                  * we can't jump into the have_block_group
4923                                  * target because our list pointers are not
4924                                  * valid
4925                                  */
4926                                 btrfs_put_block_group(block_group);
4927                                 up_read(&space_info->groups_sem);
4928                         } else {
4929                                 index = get_block_group_index(block_group);
4930                                 goto have_block_group;
4931                         }
4932                 } else if (block_group) {
4933                         btrfs_put_block_group(block_group);
4934                 }
4935         }
4936 search:
4937         down_read(&space_info->groups_sem);
4938         list_for_each_entry(block_group, &space_info->block_groups[index],
4939                             list) {
4940                 u64 offset;
4941                 int cached;
4942
4943                 btrfs_get_block_group(block_group);
4944                 search_start = block_group->key.objectid;
4945
4946                 /*
4947                  * this can happen if we end up cycling through all the
4948                  * raid types, but we want to make sure we only allocate
4949                  * for the proper type.
4950                  */
4951                 if (!block_group_bits(block_group, data)) {
4952                     u64 extra = BTRFS_BLOCK_GROUP_DUP |
4953                                 BTRFS_BLOCK_GROUP_RAID1 |
4954                                 BTRFS_BLOCK_GROUP_RAID10;
4955
4956                         /*
4957                          * if they asked for extra copies and this block group
4958                          * doesn't provide them, bail.  This does allow us to
4959                          * fill raid0 from raid1.
4960                          */
4961                         if ((data & extra) && !(block_group->flags & extra))
4962                                 goto loop;
4963                 }
4964
4965 have_block_group:
4966                 if (unlikely(block_group->cached == BTRFS_CACHE_NO)) {
4967                         u64 free_percent;
4968
4969                         ret = cache_block_group(block_group, trans,
4970                                                 orig_root, 1);
4971                         if (block_group->cached == BTRFS_CACHE_FINISHED)
4972                                 goto have_block_group;
4973
4974                         free_percent = btrfs_block_group_used(&block_group->item);
4975                         free_percent *= 100;
4976                         free_percent = div64_u64(free_percent,
4977                                                  block_group->key.offset);
4978                         free_percent = 100 - free_percent;
4979                         if (free_percent > ideal_cache_percent &&
4980                             likely(!block_group->ro)) {
4981                                 ideal_cache_offset = block_group->key.objectid;
4982                                 ideal_cache_percent = free_percent;
4983                         }
4984
4985                         /*
4986                          * We only want to start kthread caching if we are at
4987                          * the point where we will wait for caching to make
4988                          * progress, or if our ideal search is over and we've
4989                          * found somebody to start caching.
4990                          */
4991                         if (loop > LOOP_CACHING_NOWAIT ||
4992                             (loop > LOOP_FIND_IDEAL &&
4993                              atomic_read(&space_info->caching_threads) < 2)) {
4994                                 ret = cache_block_group(block_group, trans,
4995                                                         orig_root, 0);
4996                                 BUG_ON(ret);
4997                         }
4998                         found_uncached_bg = true;
4999
5000                         /*
5001                          * If loop is set for cached only, try the next block
5002                          * group.
5003                          */
5004                         if (loop == LOOP_FIND_IDEAL)
5005                                 goto loop;
5006                 }
5007
5008                 cached = block_group_cache_done(block_group);
5009                 if (unlikely(!cached))
5010                         found_uncached_bg = true;
5011
5012                 if (unlikely(block_group->ro))
5013                         goto loop;
5014
5015                 /*
5016                  * Ok we want to try and use the cluster allocator, so lets look
5017                  * there, unless we are on LOOP_NO_EMPTY_SIZE, since we will
5018                  * have tried the cluster allocator plenty of times at this
5019                  * point and not have found anything, so we are likely way too
5020                  * fragmented for the clustering stuff to find anything, so lets
5021                  * just skip it and let the allocator find whatever block it can
5022                  * find
5023                  */
5024                 if (last_ptr && loop < LOOP_NO_EMPTY_SIZE) {
5025                         /*
5026                          * the refill lock keeps out other
5027                          * people trying to start a new cluster
5028                          */
5029                         spin_lock(&last_ptr->refill_lock);
5030                         if (last_ptr->block_group &&
5031                             (last_ptr->block_group->ro ||
5032                             !block_group_bits(last_ptr->block_group, data))) {
5033                                 offset = 0;
5034                                 goto refill_cluster;
5035                         }
5036
5037                         offset = btrfs_alloc_from_cluster(block_group, last_ptr,
5038                                                  num_bytes, search_start);
5039                         if (offset) {
5040                                 /* we have a block, we're done */
5041                                 spin_unlock(&last_ptr->refill_lock);
5042                                 goto checks;
5043                         }
5044
5045                         spin_lock(&last_ptr->lock);
5046                         /*
5047                          * whoops, this cluster doesn't actually point to
5048                          * this block group.  Get a ref on the block
5049                          * group is does point to and try again
5050                          */
5051                         if (!last_ptr_loop && last_ptr->block_group &&
5052                             last_ptr->block_group != block_group) {
5053
5054                                 btrfs_put_block_group(block_group);
5055                                 block_group = last_ptr->block_group;
5056                                 btrfs_get_block_group(block_group);
5057                                 spin_unlock(&last_ptr->lock);
5058                                 spin_unlock(&last_ptr->refill_lock);
5059
5060                                 last_ptr_loop = 1;
5061                                 search_start = block_group->key.objectid;
5062                                 /*
5063                                  * we know this block group is properly
5064                                  * in the list because
5065                                  * btrfs_remove_block_group, drops the
5066                                  * cluster before it removes the block
5067                                  * group from the list
5068                                  */
5069                                 goto have_block_group;
5070                         }
5071                         spin_unlock(&last_ptr->lock);
5072 refill_cluster:
5073                         /*
5074                          * this cluster didn't work out, free it and
5075                          * start over
5076                          */
5077                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
5078
5079                         last_ptr_loop = 0;
5080
5081                         /* allocate a cluster in this block group */
5082                         ret = btrfs_find_space_cluster(trans, root,
5083                                                block_group, last_ptr,
5084                                                offset, num_bytes,
5085                                                empty_cluster + empty_size);
5086                         if (ret == 0) {
5087                                 /*
5088                                  * now pull our allocation out of this
5089                                  * cluster
5090                                  */
5091                                 offset = btrfs_alloc_from_cluster(block_group,
5092                                                   last_ptr, num_bytes,
5093                                                   search_start);
5094                                 if (offset) {
5095                                         /* we found one, proceed */
5096                                         spin_unlock(&last_ptr->refill_lock);
5097                                         goto checks;
5098                                 }
5099                         } else if (!cached && loop > LOOP_CACHING_NOWAIT
5100                                    && !failed_cluster_refill) {
5101                                 spin_unlock(&last_ptr->refill_lock);
5102
5103                                 failed_cluster_refill = true;
5104                                 wait_block_group_cache_progress(block_group,
5105                                        num_bytes + empty_cluster + empty_size);
5106                                 goto have_block_group;
5107                         }
5108
5109                         /*
5110                          * at this point we either didn't find a cluster
5111                          * or we weren't able to allocate a block from our
5112                          * cluster.  Free the cluster we've been trying
5113                          * to use, and go to the next block group
5114                          */
5115                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
5116                         spin_unlock(&last_ptr->refill_lock);
5117                         goto loop;
5118                 }
5119
5120                 offset = btrfs_find_space_for_alloc(block_group, search_start,
5121                                                     num_bytes, empty_size);
5122                 /*
5123                  * If we didn't find a chunk, and we haven't failed on this
5124                  * block group before, and this block group is in the middle of
5125                  * caching and we are ok with waiting, then go ahead and wait
5126                  * for progress to be made, and set failed_alloc to true.
5127                  *
5128                  * If failed_alloc is true then we've already waited on this
5129                  * block group once and should move on to the next block group.
5130                  */
5131                 if (!offset && !failed_alloc && !cached &&
5132                     loop > LOOP_CACHING_NOWAIT) {
5133                         wait_block_group_cache_progress(block_group,
5134                                                 num_bytes + empty_size);
5135                         failed_alloc = true;
5136                         goto have_block_group;
5137                 } else if (!offset) {
5138                         goto loop;
5139                 }
5140 checks:
5141                 search_start = stripe_align(root, offset);
5142                 /* move on to the next group */
5143                 if (search_start + num_bytes >= search_end) {
5144                         btrfs_add_free_space(block_group, offset, num_bytes);
5145                         goto loop;
5146                 }
5147
5148                 /* move on to the next group */
5149                 if (search_start + num_bytes >
5150                     block_group->key.objectid + block_group->key.offset) {
5151                         btrfs_add_free_space(block_group, offset, num_bytes);
5152                         goto loop;
5153                 }
5154
5155                 ins->objectid = search_start;
5156                 ins->offset = num_bytes;
5157
5158                 if (offset < search_start)
5159                         btrfs_add_free_space(block_group, offset,
5160                                              search_start - offset);
5161                 BUG_ON(offset > search_start);
5162
5163                 ret = update_reserved_bytes(block_group, num_bytes, 1,
5164                                             (data & BTRFS_BLOCK_GROUP_DATA));
5165                 if (ret == -EAGAIN) {
5166                         btrfs_add_free_space(block_group, offset, num_bytes);
5167                         goto loop;
5168                 }
5169
5170                 /* we are all good, lets return */
5171                 ins->objectid = search_start;
5172                 ins->offset = num_bytes;
5173
5174                 if (offset < search_start)
5175                         btrfs_add_free_space(block_group, offset,
5176                                              search_start - offset);
5177                 BUG_ON(offset > search_start);
5178                 break;
5179 loop:
5180                 failed_cluster_refill = false;
5181                 failed_alloc = false;
5182                 BUG_ON(index != get_block_group_index(block_group));
5183                 btrfs_put_block_group(block_group);
5184         }
5185         up_read(&space_info->groups_sem);
5186
5187         if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
5188                 goto search;
5189
5190         /* LOOP_FIND_IDEAL, only search caching/cached bg's, and don't wait for
5191          *                      for them to make caching progress.  Also
5192          *                      determine the best possible bg to cache
5193          * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
5194          *                      caching kthreads as we move along
5195          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
5196          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
5197          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
5198          *                      again
5199          */
5200         if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE &&
5201             (found_uncached_bg || empty_size || empty_cluster ||
5202              allowed_chunk_alloc)) {
5203                 index = 0;
5204                 if (loop == LOOP_FIND_IDEAL && found_uncached_bg) {
5205                         found_uncached_bg = false;
5206                         loop++;
5207                         if (!ideal_cache_percent &&
5208                             atomic_read(&space_info->caching_threads))
5209                                 goto search;
5210
5211                         /*
5212                          * 1 of the following 2 things have happened so far
5213                          *
5214                          * 1) We found an ideal block group for caching that
5215                          * is mostly full and will cache quickly, so we might
5216                          * as well wait for it.
5217                          *
5218                          * 2) We searched for cached only and we didn't find
5219                          * anything, and we didn't start any caching kthreads
5220                          * either, so chances are we will loop through and
5221                          * start a couple caching kthreads, and then come back
5222                          * around and just wait for them.  This will be slower
5223                          * because we will have 2 caching kthreads reading at
5224                          * the same time when we could have just started one
5225                          * and waited for it to get far enough to give us an
5226                          * allocation, so go ahead and go to the wait caching
5227                          * loop.
5228                          */
5229                         loop = LOOP_CACHING_WAIT;
5230                         search_start = ideal_cache_offset;
5231                         ideal_cache_percent = 0;
5232                         goto ideal_cache;
5233                 } else if (loop == LOOP_FIND_IDEAL) {
5234                         /*
5235                          * Didn't find a uncached bg, wait on anything we find
5236                          * next.
5237                          */
5238                         loop = LOOP_CACHING_WAIT;
5239                         goto search;
5240                 }
5241
5242                 if (loop < LOOP_CACHING_WAIT) {
5243                         loop++;
5244                         goto search;
5245                 }
5246
5247                 if (loop == LOOP_ALLOC_CHUNK) {
5248                         empty_size = 0;
5249                         empty_cluster = 0;
5250                 }
5251
5252                 if (allowed_chunk_alloc) {
5253                         ret = do_chunk_alloc(trans, root, num_bytes +
5254                                              2 * 1024 * 1024, data, 1);
5255                         allowed_chunk_alloc = 0;
5256                         done_chunk_alloc = 1;
5257                 } else if (!done_chunk_alloc) {
5258                         space_info->force_alloc = 1;
5259                 }
5260
5261                 if (loop < LOOP_NO_EMPTY_SIZE) {
5262                         loop++;
5263                         goto search;
5264                 }
5265                 ret = -ENOSPC;
5266         } else if (!ins->objectid) {
5267                 ret = -ENOSPC;
5268         }
5269
5270         /* we found what we needed */
5271         if (ins->objectid) {
5272                 if (!(data & BTRFS_BLOCK_GROUP_DATA))
5273                         trans->block_group = block_group->key.objectid;
5274
5275                 btrfs_put_block_group(block_group);
5276                 ret = 0;
5277         }
5278
5279         return ret;
5280 }
5281
5282 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
5283                             int dump_block_groups)
5284 {
5285         struct btrfs_block_group_cache *cache;
5286         int index = 0;
5287
5288         spin_lock(&info->lock);
5289         printk(KERN_INFO "space_info has %llu free, is %sfull\n",
5290                (unsigned long long)(info->total_bytes - info->bytes_used -
5291                                     info->bytes_pinned - info->bytes_reserved -
5292                                     info->bytes_readonly),
5293                (info->full) ? "" : "not ");
5294         printk(KERN_INFO "space_info total=%llu, used=%llu, pinned=%llu, "
5295                "reserved=%llu, may_use=%llu, readonly=%llu\n",
5296                (unsigned long long)info->total_bytes,
5297                (unsigned long long)info->bytes_used,
5298                (unsigned long long)info->bytes_pinned,
5299                (unsigned long long)info->bytes_reserved,
5300                (unsigned long long)info->bytes_may_use,
5301                (unsigned long long)info->bytes_readonly);
5302         spin_unlock(&info->lock);
5303
5304         if (!dump_block_groups)
5305                 return;
5306
5307         down_read(&info->groups_sem);
5308 again:
5309         list_for_each_entry(cache, &info->block_groups[index], list) {
5310                 spin_lock(&cache->lock);
5311                 printk(KERN_INFO "block group %llu has %llu bytes, %llu used "
5312                        "%llu pinned %llu reserved\n",
5313                        (unsigned long long)cache->key.objectid,
5314                        (unsigned long long)cache->key.offset,
5315                        (unsigned long long)btrfs_block_group_used(&cache->item),
5316                        (unsigned long long)cache->pinned,
5317                        (unsigned long long)cache->reserved);
5318                 btrfs_dump_free_space(cache, bytes);
5319                 spin_unlock(&cache->lock);
5320         }
5321         if (++index < BTRFS_NR_RAID_TYPES)
5322                 goto again;
5323         up_read(&info->groups_sem);
5324 }
5325
5326 int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
5327                          struct btrfs_root *root,
5328                          u64 num_bytes, u64 min_alloc_size,
5329                          u64 empty_size, u64 hint_byte,
5330                          u64 search_end, struct btrfs_key *ins,
5331                          u64 data)
5332 {
5333         int ret;
5334         u64 search_start = 0;
5335
5336         data = btrfs_get_alloc_profile(root, data);
5337 again:
5338         /*
5339          * the only place that sets empty_size is btrfs_realloc_node, which
5340          * is not called recursively on allocations
5341          */
5342         if (empty_size || root->ref_cows)
5343                 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
5344                                      num_bytes + 2 * 1024 * 1024, data, 0);
5345
5346         WARN_ON(num_bytes < root->sectorsize);
5347         ret = find_free_extent(trans, root, num_bytes, empty_size,
5348                                search_start, search_end, hint_byte,
5349                                ins, data);
5350
5351         if (ret == -ENOSPC && num_bytes > min_alloc_size) {
5352                 num_bytes = num_bytes >> 1;
5353                 num_bytes = num_bytes & ~(root->sectorsize - 1);
5354                 num_bytes = max(num_bytes, min_alloc_size);
5355                 do_chunk_alloc(trans, root->fs_info->extent_root,
5356                                num_bytes, data, 1);
5357                 goto again;
5358         }
5359         if (ret == -ENOSPC) {
5360                 struct btrfs_space_info *sinfo;
5361
5362                 sinfo = __find_space_info(root->fs_info, data);
5363                 printk(KERN_ERR "btrfs allocation failed flags %llu, "
5364                        "wanted %llu\n", (unsigned long long)data,
5365                        (unsigned long long)num_bytes);
5366                 dump_space_info(sinfo, num_bytes, 1);
5367         }
5368
5369         return ret;
5370 }
5371
5372 int btrfs_free_reserved_extent(struct btrfs_root *root, u64 start, u64 len)
5373 {
5374         struct btrfs_block_group_cache *cache;
5375         int ret = 0;
5376
5377         cache = btrfs_lookup_block_group(root->fs_info, start);
5378         if (!cache) {
5379                 printk(KERN_ERR "Unable to find block group for %llu\n",
5380                        (unsigned long long)start);
5381                 return -ENOSPC;
5382         }
5383
5384         ret = btrfs_discard_extent(root, start, len);
5385
5386         btrfs_add_free_space(cache, start, len);
5387         update_reserved_bytes(cache, len, 0, 1);
5388         btrfs_put_block_group(cache);
5389
5390         return ret;
5391 }
5392
5393 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5394                                       struct btrfs_root *root,
5395                                       u64 parent, u64 root_objectid,
5396                                       u64 flags, u64 owner, u64 offset,
5397                                       struct btrfs_key *ins, int ref_mod)
5398 {
5399         int ret;
5400         struct btrfs_fs_info *fs_info = root->fs_info;
5401         struct btrfs_extent_item *extent_item;
5402         struct btrfs_extent_inline_ref *iref;
5403         struct btrfs_path *path;
5404         struct extent_buffer *leaf;
5405         int type;
5406         u32 size;
5407
5408         if (parent > 0)
5409                 type = BTRFS_SHARED_DATA_REF_KEY;
5410         else
5411                 type = BTRFS_EXTENT_DATA_REF_KEY;
5412
5413         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
5414
5415         path = btrfs_alloc_path();
5416         BUG_ON(!path);
5417
5418         path->leave_spinning = 1;
5419         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
5420                                       ins, size);
5421         BUG_ON(ret);
5422
5423         leaf = path->nodes[0];
5424         extent_item = btrfs_item_ptr(leaf, path->slots[0],
5425                                      struct btrfs_extent_item);
5426         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
5427         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5428         btrfs_set_extent_flags(leaf, extent_item,
5429                                flags | BTRFS_EXTENT_FLAG_DATA);
5430
5431         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
5432         btrfs_set_extent_inline_ref_type(leaf, iref, type);
5433         if (parent > 0) {
5434                 struct btrfs_shared_data_ref *ref;
5435                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
5436                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
5437                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
5438         } else {
5439                 struct btrfs_extent_data_ref *ref;
5440                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
5441                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
5442                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
5443                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
5444                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
5445         }
5446
5447         btrfs_mark_buffer_dirty(path->nodes[0]);
5448         btrfs_free_path(path);
5449
5450         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
5451         if (ret) {
5452                 printk(KERN_ERR "btrfs update block group failed for %llu "
5453                        "%llu\n", (unsigned long long)ins->objectid,
5454                        (unsigned long long)ins->offset);
5455                 BUG();
5456         }
5457         return ret;
5458 }
5459
5460 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
5461                                      struct btrfs_root *root,
5462                                      u64 parent, u64 root_objectid,
5463                                      u64 flags, struct btrfs_disk_key *key,
5464                                      int level, struct btrfs_key *ins)
5465 {
5466         int ret;
5467         struct btrfs_fs_info *fs_info = root->fs_info;
5468         struct btrfs_extent_item *extent_item;
5469         struct btrfs_tree_block_info *block_info;
5470         struct btrfs_extent_inline_ref *iref;
5471         struct btrfs_path *path;
5472         struct extent_buffer *leaf;
5473         u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
5474
5475         path = btrfs_alloc_path();
5476         BUG_ON(!path);
5477
5478         path->leave_spinning = 1;
5479         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
5480                                       ins, size);
5481         BUG_ON(ret);
5482
5483         leaf = path->nodes[0];
5484         extent_item = btrfs_item_ptr(leaf, path->slots[0],
5485                                      struct btrfs_extent_item);
5486         btrfs_set_extent_refs(leaf, extent_item, 1);
5487         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
5488         btrfs_set_extent_flags(leaf, extent_item,
5489                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
5490         block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
5491
5492         btrfs_set_tree_block_key(leaf, block_info, key);
5493         btrfs_set_tree_block_level(leaf, block_info, level);
5494
5495         iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
5496         if (parent > 0) {
5497                 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
5498                 btrfs_set_extent_inline_ref_type(leaf, iref,
5499                                                  BTRFS_SHARED_BLOCK_REF_KEY);
5500                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
5501         } else {
5502                 btrfs_set_extent_inline_ref_type(leaf, iref,
5503                                                  BTRFS_TREE_BLOCK_REF_KEY);
5504                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
5505         }
5506
5507         btrfs_mark_buffer_dirty(leaf);
5508         btrfs_free_path(path);
5509
5510         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
5511         if (ret) {
5512                 printk(KERN_ERR "btrfs update block group failed for %llu "
5513                        "%llu\n", (unsigned long long)ins->objectid,
5514                        (unsigned long long)ins->offset);
5515                 BUG();
5516         }
5517         return ret;
5518 }
5519
5520 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5521                                      struct btrfs_root *root,
5522                                      u64 root_objectid, u64 owner,
5523                                      u64 offset, struct btrfs_key *ins)
5524 {
5525         int ret;
5526
5527         BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
5528
5529         ret = btrfs_add_delayed_data_ref(trans, ins->objectid, ins->offset,
5530                                          0, root_objectid, owner, offset,
5531                                          BTRFS_ADD_DELAYED_EXTENT, NULL);
5532         return ret;
5533 }
5534
5535 /*
5536  * this is used by the tree logging recovery code.  It records that
5537  * an extent has been allocated and makes sure to clear the free
5538  * space cache bits as well
5539  */
5540 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
5541                                    struct btrfs_root *root,
5542                                    u64 root_objectid, u64 owner, u64 offset,
5543                                    struct btrfs_key *ins)
5544 {
5545         int ret;
5546         struct btrfs_block_group_cache *block_group;
5547         struct btrfs_caching_control *caching_ctl;
5548         u64 start = ins->objectid;
5549         u64 num_bytes = ins->offset;
5550
5551         block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
5552         cache_block_group(block_group, trans, NULL, 0);
5553         caching_ctl = get_caching_control(block_group);
5554
5555         if (!caching_ctl) {
5556                 BUG_ON(!block_group_cache_done(block_group));
5557                 ret = btrfs_remove_free_space(block_group, start, num_bytes);
5558                 BUG_ON(ret);
5559         } else {
5560                 mutex_lock(&caching_ctl->mutex);
5561
5562                 if (start >= caching_ctl->progress) {
5563                         ret = add_excluded_extent(root, start, num_bytes);
5564                         BUG_ON(ret);
5565                 } else if (start + num_bytes <= caching_ctl->progress) {
5566                         ret = btrfs_remove_free_space(block_group,
5567                                                       start, num_bytes);
5568                         BUG_ON(ret);
5569                 } else {
5570                         num_bytes = caching_ctl->progress - start;
5571                         ret = btrfs_remove_free_space(block_group,
5572                                                       start, num_bytes);
5573                         BUG_ON(ret);
5574
5575                         start = caching_ctl->progress;
5576                         num_bytes = ins->objectid + ins->offset -
5577                                     caching_ctl->progress;
5578                         ret = add_excluded_extent(root, start, num_bytes);
5579                         BUG_ON(ret);
5580                 }
5581
5582                 mutex_unlock(&caching_ctl->mutex);
5583                 put_caching_control(caching_ctl);
5584         }
5585
5586         ret = update_reserved_bytes(block_group, ins->offset, 1, 1);
5587         BUG_ON(ret);
5588         btrfs_put_block_group(block_group);
5589         ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
5590                                          0, owner, offset, ins, 1);
5591         return ret;
5592 }
5593
5594 struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
5595                                             struct btrfs_root *root,
5596                                             u64 bytenr, u32 blocksize,
5597                                             int level)
5598 {
5599         struct extent_buffer *buf;
5600
5601         buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
5602         if (!buf)
5603                 return ERR_PTR(-ENOMEM);
5604         btrfs_set_header_generation(buf, trans->transid);
5605         btrfs_set_buffer_lockdep_class(buf, level);
5606         btrfs_tree_lock(buf);
5607         clean_tree_block(trans, root, buf);
5608
5609         btrfs_set_lock_blocking(buf);
5610         btrfs_set_buffer_uptodate(buf);
5611
5612         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
5613                 /*
5614                  * we allow two log transactions at a time, use different
5615                  * EXENT bit to differentiate dirty pages.
5616                  */
5617                 if (root->log_transid % 2 == 0)
5618                         set_extent_dirty(&root->dirty_log_pages, buf->start,
5619                                         buf->start + buf->len - 1, GFP_NOFS);
5620                 else
5621                         set_extent_new(&root->dirty_log_pages, buf->start,
5622                                         buf->start + buf->len - 1, GFP_NOFS);
5623         } else {
5624                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
5625                          buf->start + buf->len - 1, GFP_NOFS);
5626         }
5627         trans->blocks_used++;
5628         /* this returns a buffer locked for blocking */
5629         return buf;
5630 }
5631
5632 static struct btrfs_block_rsv *
5633 use_block_rsv(struct btrfs_trans_handle *trans,
5634               struct btrfs_root *root, u32 blocksize)
5635 {
5636         struct btrfs_block_rsv *block_rsv;
5637         int ret;
5638
5639         block_rsv = get_block_rsv(trans, root);
5640
5641         if (block_rsv->size == 0) {
5642                 ret = reserve_metadata_bytes(trans, root, block_rsv,
5643                                              blocksize, 0);
5644                 if (ret)
5645                         return ERR_PTR(ret);
5646                 return block_rsv;
5647         }
5648
5649         ret = block_rsv_use_bytes(block_rsv, blocksize);
5650         if (!ret)
5651                 return block_rsv;
5652
5653         return ERR_PTR(-ENOSPC);
5654 }
5655
5656 static void unuse_block_rsv(struct btrfs_block_rsv *block_rsv, u32 blocksize)
5657 {
5658         block_rsv_add_bytes(block_rsv, blocksize, 0);
5659         block_rsv_release_bytes(block_rsv, NULL, 0);
5660 }
5661
5662 /*
5663  * finds a free extent and does all the dirty work required for allocation
5664  * returns the key for the extent through ins, and a tree buffer for
5665  * the first block of the extent through buf.
5666  *
5667  * returns the tree buffer or NULL.
5668  */
5669 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
5670                                         struct btrfs_root *root, u32 blocksize,
5671                                         u64 parent, u64 root_objectid,
5672                                         struct btrfs_disk_key *key, int level,
5673                                         u64 hint, u64 empty_size)
5674 {
5675         struct btrfs_key ins;
5676         struct btrfs_block_rsv *block_rsv;
5677         struct extent_buffer *buf;
5678         u64 flags = 0;
5679         int ret;
5680
5681
5682         block_rsv = use_block_rsv(trans, root, blocksize);
5683         if (IS_ERR(block_rsv))
5684                 return ERR_CAST(block_rsv);
5685
5686         ret = btrfs_reserve_extent(trans, root, blocksize, blocksize,
5687                                    empty_size, hint, (u64)-1, &ins, 0);
5688         if (ret) {
5689                 unuse_block_rsv(block_rsv, blocksize);
5690                 return ERR_PTR(ret);
5691         }
5692
5693         buf = btrfs_init_new_buffer(trans, root, ins.objectid,
5694                                     blocksize, level);
5695         BUG_ON(IS_ERR(buf));
5696
5697         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
5698                 if (parent == 0)
5699                         parent = ins.objectid;
5700                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
5701         } else
5702                 BUG_ON(parent > 0);
5703
5704         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
5705                 struct btrfs_delayed_extent_op *extent_op;
5706                 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
5707                 BUG_ON(!extent_op);
5708                 if (key)
5709                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
5710                 else
5711                         memset(&extent_op->key, 0, sizeof(extent_op->key));
5712                 extent_op->flags_to_set = flags;
5713                 extent_op->update_key = 1;
5714                 extent_op->update_flags = 1;
5715                 extent_op->is_data = 0;
5716
5717                 ret = btrfs_add_delayed_tree_ref(trans, ins.objectid,
5718                                         ins.offset, parent, root_objectid,
5719                                         level, BTRFS_ADD_DELAYED_EXTENT,
5720                                         extent_op);
5721                 BUG_ON(ret);
5722         }
5723         return buf;
5724 }
5725
5726 struct walk_control {
5727         u64 refs[BTRFS_MAX_LEVEL];
5728         u64 flags[BTRFS_MAX_LEVEL];
5729         struct btrfs_key update_progress;
5730         int stage;
5731         int level;
5732         int shared_level;
5733         int update_ref;
5734         int keep_locks;
5735         int reada_slot;
5736         int reada_count;
5737 };
5738
5739 #define DROP_REFERENCE  1
5740 #define UPDATE_BACKREF  2
5741
5742 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
5743                                      struct btrfs_root *root,
5744                                      struct walk_control *wc,
5745                                      struct btrfs_path *path)
5746 {
5747         u64 bytenr;
5748         u64 generation;
5749         u64 refs;
5750         u64 flags;
5751         u32 nritems;
5752         u32 blocksize;
5753         struct btrfs_key key;
5754         struct extent_buffer *eb;
5755         int ret;
5756         int slot;
5757         int nread = 0;
5758
5759         if (path->slots[wc->level] < wc->reada_slot) {
5760                 wc->reada_count = wc->reada_count * 2 / 3;
5761                 wc->reada_count = max(wc->reada_count, 2);
5762         } else {
5763                 wc->reada_count = wc->reada_count * 3 / 2;
5764                 wc->reada_count = min_t(int, wc->reada_count,
5765                                         BTRFS_NODEPTRS_PER_BLOCK(root));
5766         }
5767
5768         eb = path->nodes[wc->level];
5769         nritems = btrfs_header_nritems(eb);
5770         blocksize = btrfs_level_size(root, wc->level - 1);
5771
5772         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
5773                 if (nread >= wc->reada_count)
5774                         break;
5775
5776                 cond_resched();
5777                 bytenr = btrfs_node_blockptr(eb, slot);
5778                 generation = btrfs_node_ptr_generation(eb, slot);
5779
5780                 if (slot == path->slots[wc->level])
5781                         goto reada;
5782
5783                 if (wc->stage == UPDATE_BACKREF &&
5784                     generation <= root->root_key.offset)
5785                         continue;
5786
5787                 /* We don't lock the tree block, it's OK to be racy here */
5788                 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
5789                                                &refs, &flags);
5790                 BUG_ON(ret);
5791                 BUG_ON(refs == 0);
5792
5793                 if (wc->stage == DROP_REFERENCE) {
5794                         if (refs == 1)
5795                                 goto reada;
5796
5797                         if (wc->level == 1 &&
5798                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5799                                 continue;
5800                         if (!wc->update_ref ||
5801                             generation <= root->root_key.offset)
5802                                 continue;
5803                         btrfs_node_key_to_cpu(eb, &key, slot);
5804                         ret = btrfs_comp_cpu_keys(&key,
5805                                                   &wc->update_progress);
5806                         if (ret < 0)
5807                                 continue;
5808                 } else {
5809                         if (wc->level == 1 &&
5810                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5811                                 continue;
5812                 }
5813 reada:
5814                 ret = readahead_tree_block(root, bytenr, blocksize,
5815                                            generation);
5816                 if (ret)
5817                         break;
5818                 nread++;
5819         }
5820         wc->reada_slot = slot;
5821 }
5822
5823 /*
5824  * hepler to process tree block while walking down the tree.
5825  *
5826  * when wc->stage == UPDATE_BACKREF, this function updates
5827  * back refs for pointers in the block.
5828  *
5829  * NOTE: return value 1 means we should stop walking down.
5830  */
5831 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5832                                    struct btrfs_root *root,
5833                                    struct btrfs_path *path,
5834                                    struct walk_control *wc, int lookup_info)
5835 {
5836         int level = wc->level;
5837         struct extent_buffer *eb = path->nodes[level];
5838         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5839         int ret;
5840
5841         if (wc->stage == UPDATE_BACKREF &&
5842             btrfs_header_owner(eb) != root->root_key.objectid)
5843                 return 1;
5844
5845         /*
5846          * when reference count of tree block is 1, it won't increase
5847          * again. once full backref flag is set, we never clear it.
5848          */
5849         if (lookup_info &&
5850             ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5851              (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
5852                 BUG_ON(!path->locks[level]);
5853                 ret = btrfs_lookup_extent_info(trans, root,
5854                                                eb->start, eb->len,
5855                                                &wc->refs[level],
5856                                                &wc->flags[level]);
5857                 BUG_ON(ret);
5858                 BUG_ON(wc->refs[level] == 0);
5859         }
5860
5861         if (wc->stage == DROP_REFERENCE) {
5862                 if (wc->refs[level] > 1)
5863                         return 1;
5864
5865                 if (path->locks[level] && !wc->keep_locks) {
5866                         btrfs_tree_unlock(eb);
5867                         path->locks[level] = 0;
5868                 }
5869                 return 0;
5870         }
5871
5872         /* wc->stage == UPDATE_BACKREF */
5873         if (!(wc->flags[level] & flag)) {
5874                 BUG_ON(!path->locks[level]);
5875                 ret = btrfs_inc_ref(trans, root, eb, 1);
5876                 BUG_ON(ret);
5877                 ret = btrfs_dec_ref(trans, root, eb, 0);
5878                 BUG_ON(ret);
5879                 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
5880                                                   eb->len, flag, 0);
5881                 BUG_ON(ret);
5882                 wc->flags[level] |= flag;
5883         }
5884
5885         /*
5886          * the block is shared by multiple trees, so it's not good to
5887          * keep the tree lock
5888          */
5889         if (path->locks[level] && level > 0) {
5890                 btrfs_tree_unlock(eb);
5891                 path->locks[level] = 0;
5892         }
5893         return 0;
5894 }
5895
5896 /*
5897  * hepler to process tree block pointer.
5898  *
5899  * when wc->stage == DROP_REFERENCE, this function checks
5900  * reference count of the block pointed to. if the block
5901  * is shared and we need update back refs for the subtree
5902  * rooted at the block, this function changes wc->stage to
5903  * UPDATE_BACKREF. if the block is shared and there is no
5904  * need to update back, this function drops the reference
5905  * to the block.
5906  *
5907  * NOTE: return value 1 means we should stop walking down.
5908  */
5909 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5910                                  struct btrfs_root *root,
5911                                  struct btrfs_path *path,
5912                                  struct walk_control *wc, int *lookup_info)
5913 {
5914         u64 bytenr;
5915         u64 generation;
5916         u64 parent;
5917         u32 blocksize;
5918         struct btrfs_key key;
5919         struct extent_buffer *next;
5920         int level = wc->level;
5921         int reada = 0;
5922         int ret = 0;
5923
5924         generation = btrfs_node_ptr_generation(path->nodes[level],
5925                                                path->slots[level]);
5926         /*
5927          * if the lower level block was created before the snapshot
5928          * was created, we know there is no need to update back refs
5929          * for the subtree
5930          */
5931         if (wc->stage == UPDATE_BACKREF &&
5932             generation <= root->root_key.offset) {
5933                 *lookup_info = 1;
5934                 return 1;
5935         }
5936
5937         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5938         blocksize = btrfs_level_size(root, level - 1);
5939
5940         next = btrfs_find_tree_block(root, bytenr, blocksize);
5941         if (!next) {
5942                 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
5943                 if (!next)
5944                         return -ENOMEM;
5945                 reada = 1;
5946         }
5947         btrfs_tree_lock(next);
5948         btrfs_set_lock_blocking(next);
5949
5950         ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
5951                                        &wc->refs[level - 1],
5952                                        &wc->flags[level - 1]);
5953         BUG_ON(ret);
5954         BUG_ON(wc->refs[level - 1] == 0);
5955         *lookup_info = 0;
5956
5957         if (wc->stage == DROP_REFERENCE) {
5958                 if (wc->refs[level - 1] > 1) {
5959                         if (level == 1 &&
5960                             (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5961                                 goto skip;
5962
5963                         if (!wc->update_ref ||
5964                             generation <= root->root_key.offset)
5965                                 goto skip;
5966
5967                         btrfs_node_key_to_cpu(path->nodes[level], &key,
5968                                               path->slots[level]);
5969                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
5970                         if (ret < 0)
5971                                 goto skip;
5972
5973                         wc->stage = UPDATE_BACKREF;
5974                         wc->shared_level = level - 1;
5975                 }
5976         } else {
5977                 if (level == 1 &&
5978                     (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5979                         goto skip;
5980         }
5981
5982         if (!btrfs_buffer_uptodate(next, generation)) {
5983                 btrfs_tree_unlock(next);
5984                 free_extent_buffer(next);
5985                 next = NULL;
5986                 *lookup_info = 1;
5987         }
5988
5989         if (!next) {
5990                 if (reada && level == 1)
5991                         reada_walk_down(trans, root, wc, path);
5992                 next = read_tree_block(root, bytenr, blocksize, generation);
5993                 btrfs_tree_lock(next);
5994                 btrfs_set_lock_blocking(next);
5995         }
5996
5997         level--;
5998         BUG_ON(level != btrfs_header_level(next));
5999         path->nodes[level] = next;
6000         path->slots[level] = 0;
6001         path->locks[level] = 1;
6002         wc->level = level;
6003         if (wc->level == 1)
6004                 wc->reada_slot = 0;
6005         return 0;
6006 skip:
6007         wc->refs[level - 1] = 0;
6008         wc->flags[level - 1] = 0;
6009         if (wc->stage == DROP_REFERENCE) {
6010                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6011                         parent = path->nodes[level]->start;
6012                 } else {
6013                         BUG_ON(root->root_key.objectid !=
6014                                btrfs_header_owner(path->nodes[level]));
6015                         parent = 0;
6016                 }
6017
6018                 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
6019                                         root->root_key.objectid, level - 1, 0);
6020                 BUG_ON(ret);
6021         }
6022         btrfs_tree_unlock(next);
6023         free_extent_buffer(next);
6024         *lookup_info = 1;
6025         return 1;
6026 }
6027
6028 /*
6029  * hepler to process tree block while walking up the tree.
6030  *
6031  * when wc->stage == DROP_REFERENCE, this function drops
6032  * reference count on the block.
6033  *
6034  * when wc->stage == UPDATE_BACKREF, this function changes
6035  * wc->stage back to DROP_REFERENCE if we changed wc->stage
6036  * to UPDATE_BACKREF previously while processing the block.
6037  *
6038  * NOTE: return value 1 means we should stop walking up.
6039  */
6040 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6041                                  struct btrfs_root *root,
6042                                  struct btrfs_path *path,
6043                                  struct walk_control *wc)
6044 {
6045         int ret;
6046         int level = wc->level;
6047         struct extent_buffer *eb = path->nodes[level];
6048         u64 parent = 0;
6049
6050         if (wc->stage == UPDATE_BACKREF) {
6051                 BUG_ON(wc->shared_level < level);
6052                 if (level < wc->shared_level)
6053                         goto out;
6054
6055                 ret = find_next_key(path, level + 1, &wc->update_progress);
6056                 if (ret > 0)
6057                         wc->update_ref = 0;
6058
6059                 wc->stage = DROP_REFERENCE;
6060                 wc->shared_level = -1;
6061                 path->slots[level] = 0;
6062
6063                 /*
6064                  * check reference count again if the block isn't locked.
6065                  * we should start walking down the tree again if reference
6066                  * count is one.
6067                  */
6068                 if (!path->locks[level]) {
6069                         BUG_ON(level == 0);
6070                         btrfs_tree_lock(eb);
6071                         btrfs_set_lock_blocking(eb);
6072                         path->locks[level] = 1;
6073
6074                         ret = btrfs_lookup_extent_info(trans, root,
6075                                                        eb->start, eb->len,
6076                                                        &wc->refs[level],
6077                                                        &wc->flags[level]);
6078                         BUG_ON(ret);
6079                         BUG_ON(wc->refs[level] == 0);
6080                         if (wc->refs[level] == 1) {
6081                                 btrfs_tree_unlock(eb);
6082                                 path->locks[level] = 0;
6083                                 return 1;
6084                         }
6085                 }
6086         }
6087
6088         /* wc->stage == DROP_REFERENCE */
6089         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
6090
6091         if (wc->refs[level] == 1) {
6092                 if (level == 0) {
6093                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6094                                 ret = btrfs_dec_ref(trans, root, eb, 1);
6095                         else
6096                                 ret = btrfs_dec_ref(trans, root, eb, 0);
6097                         BUG_ON(ret);
6098                 }
6099                 /* make block locked assertion in clean_tree_block happy */
6100                 if (!path->locks[level] &&
6101                     btrfs_header_generation(eb) == trans->transid) {
6102                         btrfs_tree_lock(eb);
6103                         btrfs_set_lock_blocking(eb);
6104                         path->locks[level] = 1;
6105                 }
6106                 clean_tree_block(trans, root, eb);
6107         }
6108
6109         if (eb == root->node) {
6110                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6111                         parent = eb->start;
6112                 else
6113                         BUG_ON(root->root_key.objectid !=
6114                                btrfs_header_owner(eb));
6115         } else {
6116                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6117                         parent = path->nodes[level + 1]->start;
6118                 else
6119                         BUG_ON(root->root_key.objectid !=
6120                                btrfs_header_owner(path->nodes[level + 1]));
6121         }
6122
6123         btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
6124 out:
6125         wc->refs[level] = 0;
6126         wc->flags[level] = 0;
6127         return 0;
6128 }
6129
6130 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
6131                                    struct btrfs_root *root,
6132                                    struct btrfs_path *path,
6133                                    struct walk_control *wc)
6134 {
6135         int level = wc->level;
6136         int lookup_info = 1;
6137         int ret;
6138
6139         while (level >= 0) {
6140                 ret = walk_down_proc(trans, root, path, wc, lookup_info);
6141                 if (ret > 0)
6142                         break;
6143
6144                 if (level == 0)
6145                         break;
6146
6147                 if (path->slots[level] >=
6148                     btrfs_header_nritems(path->nodes[level]))
6149                         break;
6150
6151                 ret = do_walk_down(trans, root, path, wc, &lookup_info);
6152                 if (ret > 0) {
6153                         path->slots[level]++;
6154                         continue;
6155                 } else if (ret < 0)
6156                         return ret;
6157                 level = wc->level;
6158         }
6159         return 0;
6160 }
6161
6162 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
6163                                  struct btrfs_root *root,
6164                                  struct btrfs_path *path,
6165                                  struct walk_control *wc, int max_level)
6166 {
6167         int level = wc->level;
6168         int ret;
6169
6170         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6171         while (level < max_level && path->nodes[level]) {
6172                 wc->level = level;
6173                 if (path->slots[level] + 1 <
6174                     btrfs_header_nritems(path->nodes[level])) {
6175                         path->slots[level]++;
6176                         return 0;
6177                 } else {
6178                         ret = walk_up_proc(trans, root, path, wc);
6179                         if (ret > 0)
6180                                 return 0;
6181
6182                         if (path->locks[level]) {
6183                                 btrfs_tree_unlock(path->nodes[level]);
6184                                 path->locks[level] = 0;
6185                         }
6186                         free_extent_buffer(path->nodes[level]);
6187                         path->nodes[level] = NULL;
6188                         level++;
6189                 }
6190         }
6191         return 1;
6192 }
6193
6194 /*
6195  * drop a subvolume tree.
6196  *
6197  * this function traverses the tree freeing any blocks that only
6198  * referenced by the tree.
6199  *
6200  * when a shared tree block is found. this function decreases its
6201  * reference count by one. if update_ref is true, this function
6202  * also make sure backrefs for the shared block and all lower level
6203  * blocks are properly updated.
6204  */
6205 int btrfs_drop_snapshot(struct btrfs_root *root,
6206                         struct btrfs_block_rsv *block_rsv, int update_ref)
6207 {
6208         struct btrfs_path *path;
6209         struct btrfs_trans_handle *trans;
6210         struct btrfs_root *tree_root = root->fs_info->tree_root;
6211         struct btrfs_root_item *root_item = &root->root_item;
6212         struct walk_control *wc;
6213         struct btrfs_key key;
6214         int err = 0;
6215         int ret;
6216         int level;
6217
6218         path = btrfs_alloc_path();
6219         BUG_ON(!path);
6220
6221         wc = kzalloc(sizeof(*wc), GFP_NOFS);
6222         BUG_ON(!wc);
6223
6224         trans = btrfs_start_transaction(tree_root, 0);
6225         if (block_rsv)
6226                 trans->block_rsv = block_rsv;
6227
6228         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
6229                 level = btrfs_header_level(root->node);
6230                 path->nodes[level] = btrfs_lock_root_node(root);
6231                 btrfs_set_lock_blocking(path->nodes[level]);
6232                 path->slots[level] = 0;
6233                 path->locks[level] = 1;
6234                 memset(&wc->update_progress, 0,
6235                        sizeof(wc->update_progress));
6236         } else {
6237                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
6238                 memcpy(&wc->update_progress, &key,
6239                        sizeof(wc->update_progress));
6240
6241                 level = root_item->drop_level;
6242                 BUG_ON(level == 0);
6243                 path->lowest_level = level;
6244                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6245                 path->lowest_level = 0;
6246                 if (ret < 0) {
6247                         err = ret;
6248                         goto out;
6249                 }
6250                 WARN_ON(ret > 0);
6251
6252                 /*
6253                  * unlock our path, this is safe because only this
6254                  * function is allowed to delete this snapshot
6255                  */
6256                 btrfs_unlock_up_safe(path, 0);
6257
6258                 level = btrfs_header_level(root->node);
6259                 while (1) {
6260                         btrfs_tree_lock(path->nodes[level]);
6261                         btrfs_set_lock_blocking(path->nodes[level]);
6262
6263                         ret = btrfs_lookup_extent_info(trans, root,
6264                                                 path->nodes[level]->start,
6265                                                 path->nodes[level]->len,
6266                                                 &wc->refs[level],
6267                                                 &wc->flags[level]);
6268                         BUG_ON(ret);
6269                         BUG_ON(wc->refs[level] == 0);
6270
6271                         if (level == root_item->drop_level)
6272                                 break;
6273
6274                         btrfs_tree_unlock(path->nodes[level]);
6275                         WARN_ON(wc->refs[level] != 1);
6276                         level--;
6277                 }
6278         }
6279
6280         wc->level = level;
6281         wc->shared_level = -1;
6282         wc->stage = DROP_REFERENCE;
6283         wc->update_ref = update_ref;
6284         wc->keep_locks = 0;
6285         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
6286
6287         while (1) {
6288                 ret = walk_down_tree(trans, root, path, wc);
6289                 if (ret < 0) {
6290                         err = ret;
6291                         break;
6292                 }
6293
6294                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
6295                 if (ret < 0) {
6296                         err = ret;
6297                         break;
6298                 }
6299
6300                 if (ret > 0) {
6301                         BUG_ON(wc->stage != DROP_REFERENCE);
6302                         break;
6303                 }
6304
6305                 if (wc->stage == DROP_REFERENCE) {
6306                         level = wc->level;
6307                         btrfs_node_key(path->nodes[level],
6308                                        &root_item->drop_progress,
6309                                        path->slots[level]);
6310                         root_item->drop_level = level;
6311                 }
6312
6313                 BUG_ON(wc->level == 0);
6314                 if (btrfs_should_end_transaction(trans, tree_root)) {
6315                         ret = btrfs_update_root(trans, tree_root,
6316                                                 &root->root_key,
6317                                                 root_item);
6318                         BUG_ON(ret);
6319
6320                         btrfs_end_transaction_throttle(trans, tree_root);
6321                         trans = btrfs_start_transaction(tree_root, 0);
6322                         if (block_rsv)
6323                                 trans->block_rsv = block_rsv;
6324                 }
6325         }
6326         btrfs_release_path(root, path);
6327         BUG_ON(err);
6328
6329         ret = btrfs_del_root(trans, tree_root, &root->root_key);
6330         BUG_ON(ret);
6331
6332         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
6333                 ret = btrfs_find_last_root(tree_root, root->root_key.objectid,
6334                                            NULL, NULL);
6335                 BUG_ON(ret < 0);
6336                 if (ret > 0) {
6337                         /* if we fail to delete the orphan item this time
6338                          * around, it'll get picked up the next time.
6339                          *
6340                          * The most common failure here is just -ENOENT.
6341                          */
6342                         btrfs_del_orphan_item(trans, tree_root,
6343                                               root->root_key.objectid);
6344                 }
6345         }
6346
6347         if (root->in_radix) {
6348                 btrfs_free_fs_root(tree_root->fs_info, root);
6349         } else {
6350                 free_extent_buffer(root->node);
6351                 free_extent_buffer(root->commit_root);
6352                 kfree(root);
6353         }
6354 out:
6355         btrfs_end_transaction_throttle(trans, tree_root);
6356         kfree(wc);
6357         btrfs_free_path(path);
6358         return err;
6359 }
6360
6361 /*
6362  * drop subtree rooted at tree block 'node'.
6363  *
6364  * NOTE: this function will unlock and release tree block 'node'
6365  */
6366 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
6367                         struct btrfs_root *root,
6368                         struct extent_buffer *node,
6369                         struct extent_buffer *parent)
6370 {
6371         struct btrfs_path *path;
6372         struct walk_control *wc;
6373         int level;
6374         int parent_level;
6375         int ret = 0;
6376         int wret;
6377
6378         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
6379
6380         path = btrfs_alloc_path();
6381         BUG_ON(!path);
6382
6383         wc = kzalloc(sizeof(*wc), GFP_NOFS);
6384         BUG_ON(!wc);
6385
6386         btrfs_assert_tree_locked(parent);
6387         parent_level = btrfs_header_level(parent);
6388         extent_buffer_get(parent);
6389         path->nodes[parent_level] = parent;
6390         path->slots[parent_level] = btrfs_header_nritems(parent);
6391
6392         btrfs_assert_tree_locked(node);
6393         level = btrfs_header_level(node);
6394         path->nodes[level] = node;
6395         path->slots[level] = 0;
6396         path->locks[level] = 1;
6397
6398         wc->refs[parent_level] = 1;
6399         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6400         wc->level = level;
6401         wc->shared_level = -1;
6402         wc->stage = DROP_REFERENCE;
6403         wc->update_ref = 0;
6404         wc->keep_locks = 1;
6405         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
6406
6407         while (1) {
6408                 wret = walk_down_tree(trans, root, path, wc);
6409                 if (wret < 0) {
6410                         ret = wret;
6411                         break;
6412                 }
6413
6414                 wret = walk_up_tree(trans, root, path, wc, parent_level);
6415                 if (wret < 0)
6416                         ret = wret;
6417                 if (wret != 0)
6418                         break;
6419         }
6420
6421         kfree(wc);
6422         btrfs_free_path(path);
6423         return ret;
6424 }
6425
6426 #if 0
6427 static unsigned long calc_ra(unsigned long start, unsigned long last,
6428                              unsigned long nr)
6429 {
6430         return min(last, start + nr - 1);
6431 }
6432
6433 static noinline int relocate_inode_pages(struct inode *inode, u64 start,
6434                                          u64 len)
6435 {
6436         u64 page_start;
6437         u64 page_end;
6438         unsigned long first_index;
6439         unsigned long last_index;
6440         unsigned long i;
6441         struct page *page;
6442         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
6443         struct file_ra_state *ra;
6444         struct btrfs_ordered_extent *ordered;
6445         unsigned int total_read = 0;
6446         unsigned int total_dirty = 0;
6447         int ret = 0;
6448
6449         ra = kzalloc(sizeof(*ra), GFP_NOFS);
6450
6451         mutex_lock(&inode->i_mutex);
6452         first_index = start >> PAGE_CACHE_SHIFT;
6453         last_index = (start + len - 1) >> PAGE_CACHE_SHIFT;
6454
6455         /* make sure the dirty trick played by the caller work */
6456         ret = invalidate_inode_pages2_range(inode->i_mapping,
6457                                             first_index, last_index);
6458         if (ret)
6459                 goto out_unlock;
6460
6461         file_ra_state_init(ra, inode->i_mapping);
6462
6463         for (i = first_index ; i <= last_index; i++) {
6464                 if (total_read % ra->ra_pages == 0) {
6465                         btrfs_force_ra(inode->i_mapping, ra, NULL, i,
6466                                        calc_ra(i, last_index, ra->ra_pages));
6467                 }
6468                 total_read++;
6469 again:
6470                 if (((u64)i << PAGE_CACHE_SHIFT) > i_size_read(inode))
6471                         BUG_ON(1);
6472                 page = grab_cache_page(inode->i_mapping, i);
6473                 if (!page) {
6474                         ret = -ENOMEM;
6475                         goto out_unlock;
6476                 }
6477                 if (!PageUptodate(page)) {
6478                         btrfs_readpage(NULL, page);
6479                         lock_page(page);
6480                         if (!PageUptodate(page)) {
6481                                 unlock_page(page);
6482                                 page_cache_release(page);
6483                                 ret = -EIO;
6484                                 goto out_unlock;
6485                         }
6486                 }
6487                 wait_on_page_writeback(page);
6488
6489                 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
6490                 page_end = page_start + PAGE_CACHE_SIZE - 1;
6491                 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
6492
6493                 ordered = btrfs_lookup_ordered_extent(inode, page_start);
6494                 if (ordered) {
6495                         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
6496                         unlock_page(page);
6497                         page_cache_release(page);
6498                         btrfs_start_ordered_extent(inode, ordered, 1);
6499                         btrfs_put_ordered_extent(ordered);
6500                         goto again;
6501                 }
6502                 set_page_extent_mapped(page);
6503
6504                 if (i == first_index)
6505                         set_extent_bits(io_tree, page_start, page_end,
6506                                         EXTENT_BOUNDARY, GFP_NOFS);
6507                 btrfs_set_extent_delalloc(inode, page_start, page_end);
6508
6509                 set_page_dirty(page);
6510                 total_dirty++;
6511
6512                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
6513                 unlock_page(page);
6514                 page_cache_release(page);
6515         }
6516
6517 out_unlock:
6518         kfree(ra);
6519         mutex_unlock(&inode->i_mutex);
6520         balance_dirty_pages_ratelimited_nr(inode->i_mapping, total_dirty);
6521         return ret;
6522 }
6523
6524 static noinline int relocate_data_extent(struct inode *reloc_inode,
6525                                          struct btrfs_key *extent_key,
6526                                          u64 offset)
6527 {
6528         struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
6529         struct extent_map_tree *em_tree = &BTRFS_I(reloc_inode)->extent_tree;
6530         struct extent_map *em;
6531         u64 start = extent_key->objectid - offset;
6532         u64 end = start + extent_key->offset - 1;
6533
6534         em = alloc_extent_map(GFP_NOFS);
6535         BUG_ON(!em || IS_ERR(em));
6536
6537         em->start = start;
6538         em->len = extent_key->offset;
6539         em->block_len = extent_key->offset;
6540         em->block_start = extent_key->objectid;
6541         em->bdev = root->fs_info->fs_devices->latest_bdev;
6542         set_bit(EXTENT_FLAG_PINNED, &em->flags);
6543
6544         /* setup extent map to cheat btrfs_readpage */
6545         lock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
6546         while (1) {
6547                 int ret;
6548                 write_lock(&em_tree->lock);
6549                 ret = add_extent_mapping(em_tree, em);
6550                 write_unlock(&em_tree->lock);
6551                 if (ret != -EEXIST) {
6552                         free_extent_map(em);
6553                         break;
6554                 }
6555                 btrfs_drop_extent_cache(reloc_inode, start, end, 0);
6556         }
6557         unlock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
6558
6559         return relocate_inode_pages(reloc_inode, start, extent_key->offset);
6560 }
6561
6562 struct btrfs_ref_path {
6563         u64 extent_start;
6564         u64 nodes[BTRFS_MAX_LEVEL];
6565         u64 root_objectid;
6566         u64 root_generation;
6567         u64 owner_objectid;
6568         u32 num_refs;
6569         int lowest_level;
6570         int current_level;
6571         int shared_level;
6572
6573         struct btrfs_key node_keys[BTRFS_MAX_LEVEL];
6574         u64 new_nodes[BTRFS_MAX_LEVEL];
6575 };
6576
6577 struct disk_extent {
6578         u64 ram_bytes;
6579         u64 disk_bytenr;
6580         u64 disk_num_bytes;
6581         u64 offset;
6582         u64 num_bytes;
6583         u8 compression;
6584         u8 encryption;
6585         u16 other_encoding;
6586 };
6587
6588 static int is_cowonly_root(u64 root_objectid)
6589 {
6590         if (root_objectid == BTRFS_ROOT_TREE_OBJECTID ||
6591             root_objectid == BTRFS_EXTENT_TREE_OBJECTID ||
6592             root_objectid == BTRFS_CHUNK_TREE_OBJECTID ||
6593             root_objectid == BTRFS_DEV_TREE_OBJECTID ||
6594             root_objectid == BTRFS_TREE_LOG_OBJECTID ||
6595             root_objectid == BTRFS_CSUM_TREE_OBJECTID)
6596                 return 1;
6597         return 0;
6598 }
6599
6600 static noinline int __next_ref_path(struct btrfs_trans_handle *trans,
6601                                     struct btrfs_root *extent_root,
6602                                     struct btrfs_ref_path *ref_path,
6603                                     int first_time)
6604 {
6605         struct extent_buffer *leaf;
6606         struct btrfs_path *path;
6607         struct btrfs_extent_ref *ref;
6608         struct btrfs_key key;
6609         struct btrfs_key found_key;
6610         u64 bytenr;
6611         u32 nritems;
6612         int level;
6613         int ret = 1;
6614
6615         path = btrfs_alloc_path();
6616         if (!path)
6617                 return -ENOMEM;
6618
6619         if (first_time) {
6620                 ref_path->lowest_level = -1;
6621                 ref_path->current_level = -1;
6622                 ref_path->shared_level = -1;
6623                 goto walk_up;
6624         }
6625 walk_down:
6626         level = ref_path->current_level - 1;
6627         while (level >= -1) {
6628                 u64 parent;
6629                 if (level < ref_path->lowest_level)
6630                         break;
6631
6632                 if (level >= 0)
6633                         bytenr = ref_path->nodes[level];
6634                 else
6635                         bytenr = ref_path->extent_start;
6636                 BUG_ON(bytenr == 0);
6637
6638                 parent = ref_path->nodes[level + 1];
6639                 ref_path->nodes[level + 1] = 0;
6640                 ref_path->current_level = level;
6641                 BUG_ON(parent == 0);
6642
6643                 key.objectid = bytenr;
6644                 key.offset = parent + 1;
6645                 key.type = BTRFS_EXTENT_REF_KEY;
6646
6647                 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
6648                 if (ret < 0)
6649                         goto out;
6650                 BUG_ON(ret == 0);
6651
6652                 leaf = path->nodes[0];
6653                 nritems = btrfs_header_nritems(leaf);
6654                 if (path->slots[0] >= nritems) {
6655                         ret = btrfs_next_leaf(extent_root, path);
6656                         if (ret < 0)
6657                                 goto out;
6658                         if (ret > 0)
6659                                 goto next;
6660                         leaf = path->nodes[0];
6661                 }
6662
6663                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6664                 if (found_key.objectid == bytenr &&
6665                     found_key.type == BTRFS_EXTENT_REF_KEY) {
6666                         if (level < ref_path->shared_level)
6667                                 ref_path->shared_level = level;
6668                         goto found;
6669                 }
6670 next:
6671                 level--;
6672                 btrfs_release_path(extent_root, path);
6673                 cond_resched();
6674         }
6675         /* reached lowest level */
6676         ret = 1;
6677         goto out;
6678 walk_up:
6679         level = ref_path->current_level;
6680         while (level < BTRFS_MAX_LEVEL - 1) {
6681                 u64 ref_objectid;
6682
6683                 if (level >= 0)
6684                         bytenr = ref_path->nodes[level];
6685                 else
6686                         bytenr = ref_path->extent_start;
6687
6688                 BUG_ON(bytenr == 0);
6689
6690                 key.objectid = bytenr;
6691                 key.offset = 0;
6692                 key.type = BTRFS_EXTENT_REF_KEY;
6693
6694                 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
6695                 if (ret < 0)
6696                         goto out;
6697
6698                 leaf = path->nodes[0];
6699                 nritems = btrfs_header_nritems(leaf);
6700                 if (path->slots[0] >= nritems) {
6701                         ret = btrfs_next_leaf(extent_root, path);
6702                         if (ret < 0)
6703                                 goto out;
6704                         if (ret > 0) {
6705                                 /* the extent was freed by someone */
6706                                 if (ref_path->lowest_level == level)
6707                                         goto out;
6708                                 btrfs_release_path(extent_root, path);
6709                                 goto walk_down;
6710                         }
6711                         leaf = path->nodes[0];
6712                 }
6713
6714                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6715                 if (found_key.objectid != bytenr ||
6716                                 found_key.type != BTRFS_EXTENT_REF_KEY) {
6717                         /* the extent was freed by someone */
6718                         if (ref_path->lowest_level == level) {
6719                                 ret = 1;
6720                                 goto out;
6721                         }
6722                         btrfs_release_path(extent_root, path);
6723                         goto walk_down;
6724                 }
6725 found:
6726                 ref = btrfs_item_ptr(leaf, path->slots[0],
6727                                 struct btrfs_extent_ref);
6728                 ref_objectid = btrfs_ref_objectid(leaf, ref);
6729                 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID) {
6730                         if (first_time) {
6731                                 level = (int)ref_objectid;
6732                                 BUG_ON(level >= BTRFS_MAX_LEVEL);
6733                                 ref_path->lowest_level = level;
6734                                 ref_path->current_level = level;
6735                                 ref_path->nodes[level] = bytenr;
6736                         } else {
6737                                 WARN_ON(ref_objectid != level);
6738                         }
6739                 } else {
6740                         WARN_ON(level != -1);
6741                 }
6742                 first_time = 0;
6743
6744                 if (ref_path->lowest_level == level) {
6745                         ref_path->owner_objectid = ref_objectid;
6746                         ref_path->num_refs = btrfs_ref_num_refs(leaf, ref);
6747                 }
6748
6749                 /*
6750                  * the block is tree root or the block isn't in reference
6751                  * counted tree.
6752                  */
6753                 if (found_key.objectid == found_key.offset ||
6754                     is_cowonly_root(btrfs_ref_root(leaf, ref))) {
6755                         ref_path->root_objectid = btrfs_ref_root(leaf, ref);
6756                         ref_path->root_generation =
6757                                 btrfs_ref_generation(leaf, ref);
6758                         if (level < 0) {
6759                                 /* special reference from the tree log */
6760                                 ref_path->nodes[0] = found_key.offset;
6761                                 ref_path->current_level = 0;
6762                         }
6763                         ret = 0;
6764                         goto out;
6765                 }
6766
6767                 level++;
6768                 BUG_ON(ref_path->nodes[level] != 0);
6769                 ref_path->nodes[level] = found_key.offset;
6770                 ref_path->current_level = level;
6771
6772                 /*
6773                  * the reference was created in the running transaction,
6774                  * no need to continue walking up.
6775                  */
6776                 if (btrfs_ref_generation(leaf, ref) == trans->transid) {
6777                         ref_path->root_objectid = btrfs_ref_root(leaf, ref);
6778                         ref_path->root_generation =
6779                                 btrfs_ref_generation(leaf, ref);
6780                         ret = 0;
6781                         goto out;
6782                 }
6783
6784                 btrfs_release_path(extent_root, path);
6785                 cond_resched();
6786         }
6787         /* reached max tree level, but no tree root found. */
6788         BUG();
6789 out:
6790         btrfs_free_path(path);
6791         return ret;
6792 }
6793
6794 static int btrfs_first_ref_path(struct btrfs_trans_handle *trans,
6795                                 struct btrfs_root *extent_root,
6796                                 struct btrfs_ref_path *ref_path,
6797                                 u64 extent_start)
6798 {
6799         memset(ref_path, 0, sizeof(*ref_path));
6800         ref_path->extent_start = extent_start;
6801
6802         return __next_ref_path(trans, extent_root, ref_path, 1);
6803 }
6804
6805 static int btrfs_next_ref_path(struct btrfs_trans_handle *trans,
6806                                struct btrfs_root *extent_root,
6807                                struct btrfs_ref_path *ref_path)
6808 {
6809         return __next_ref_path(trans, extent_root, ref_path, 0);
6810 }
6811
6812 static noinline int get_new_locations(struct inode *reloc_inode,
6813                                       struct btrfs_key *extent_key,
6814                                       u64 offset, int no_fragment,
6815                                       struct disk_extent **extents,
6816                                       int *nr_extents)
6817 {
6818         struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
6819         struct btrfs_path *path;
6820         struct btrfs_file_extent_item *fi;
6821         struct extent_buffer *leaf;
6822         struct disk_extent *exts = *extents;
6823         struct btrfs_key found_key;
6824         u64 cur_pos;
6825         u64 last_byte;
6826         u32 nritems;
6827         int nr = 0;
6828         int max = *nr_extents;
6829         int ret;
6830
6831         WARN_ON(!no_fragment && *extents);
6832         if (!exts) {
6833                 max = 1;
6834                 exts = kmalloc(sizeof(*exts) * max, GFP_NOFS);
6835                 if (!exts)
6836                         return -ENOMEM;
6837         }
6838
6839         path = btrfs_alloc_path();
6840         BUG_ON(!path);
6841
6842         cur_pos = extent_key->objectid - offset;
6843         last_byte = extent_key->objectid + extent_key->offset;
6844         ret = btrfs_lookup_file_extent(NULL, root, path, reloc_inode->i_ino,
6845                                        cur_pos, 0);
6846         if (ret < 0)
6847                 goto out;
6848         if (ret > 0) {
6849                 ret = -ENOENT;
6850                 goto out;
6851         }
6852
6853         while (1) {
6854                 leaf = path->nodes[0];
6855                 nritems = btrfs_header_nritems(leaf);
6856                 if (path->slots[0] >= nritems) {
6857                         ret = btrfs_next_leaf(root, path);
6858                         if (ret < 0)
6859                                 goto out;
6860                         if (ret > 0)
6861                                 break;
6862                         leaf = path->nodes[0];
6863                 }
6864
6865                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6866                 if (found_key.offset != cur_pos ||
6867                     found_key.type != BTRFS_EXTENT_DATA_KEY ||
6868                     found_key.objectid != reloc_inode->i_ino)
6869                         break;
6870
6871                 fi = btrfs_item_ptr(leaf, path->slots[0],
6872                                     struct btrfs_file_extent_item);
6873                 if (btrfs_file_extent_type(leaf, fi) !=
6874                     BTRFS_FILE_EXTENT_REG ||
6875                     btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
6876                         break;
6877
6878                 if (nr == max) {
6879                         struct disk_extent *old = exts;
6880                         max *= 2;
6881                         exts = kzalloc(sizeof(*exts) * max, GFP_NOFS);
6882                         memcpy(exts, old, sizeof(*exts) * nr);
6883                         if (old != *extents)
6884                                 kfree(old);
6885                 }
6886
6887                 exts[nr].disk_bytenr =
6888                         btrfs_file_extent_disk_bytenr(leaf, fi);
6889                 exts[nr].disk_num_bytes =
6890                         btrfs_file_extent_disk_num_bytes(leaf, fi);
6891                 exts[nr].offset = btrfs_file_extent_offset(leaf, fi);
6892                 exts[nr].num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
6893                 exts[nr].ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6894                 exts[nr].compression = btrfs_file_extent_compression(leaf, fi);
6895                 exts[nr].encryption = btrfs_file_extent_encryption(leaf, fi);
6896                 exts[nr].other_encoding = btrfs_file_extent_other_encoding(leaf,
6897                                                                            fi);
6898                 BUG_ON(exts[nr].offset > 0);
6899                 BUG_ON(exts[nr].compression || exts[nr].encryption);
6900                 BUG_ON(exts[nr].num_bytes != exts[nr].disk_num_bytes);
6901
6902                 cur_pos += exts[nr].num_bytes;
6903                 nr++;
6904
6905                 if (cur_pos + offset >= last_byte)
6906                         break;
6907
6908                 if (no_fragment) {
6909                         ret = 1;
6910                         goto out;
6911                 }
6912                 path->slots[0]++;
6913         }
6914
6915         BUG_ON(cur_pos + offset > last_byte);
6916         if (cur_pos + offset < last_byte) {
6917                 ret = -ENOENT;
6918                 goto out;
6919         }
6920         ret = 0;
6921 out:
6922         btrfs_free_path(path);
6923         if (ret) {
6924                 if (exts != *extents)
6925                         kfree(exts);
6926         } else {
6927                 *extents = exts;
6928                 *nr_extents = nr;
6929         }
6930         return ret;
6931 }
6932
6933 static noinline int replace_one_extent(struct btrfs_trans_handle *trans,
6934                                         struct btrfs_root *root,
6935                                         struct btrfs_path *path,
6936                                         struct btrfs_key *extent_key,
6937                                         struct btrfs_key *leaf_key,
6938                                         struct btrfs_ref_path *ref_path,
6939                                         struct disk_extent *new_extents,
6940                                         int nr_extents)
6941 {
6942         struct extent_buffer *leaf;
6943         struct btrfs_file_extent_item *fi;
6944         struct inode *inode = NULL;
6945         struct btrfs_key key;
6946         u64 lock_start = 0;
6947         u64 lock_end = 0;
6948         u64 num_bytes;
6949         u64 ext_offset;
6950         u64 search_end = (u64)-1;
6951         u32 nritems;
6952         int nr_scaned = 0;
6953         int extent_locked = 0;
6954         int extent_type;
6955         int ret;
6956
6957         memcpy(&key, leaf_key, sizeof(key));
6958         if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
6959                 if (key.objectid < ref_path->owner_objectid ||
6960                     (key.objectid == ref_path->owner_objectid &&
6961                      key.type < BTRFS_EXTENT_DATA_KEY)) {
6962                         key.objectid = ref_path->owner_objectid;
6963                         key.type = BTRFS_EXTENT_DATA_KEY;
6964                         key.offset = 0;
6965                 }
6966         }
6967
6968         while (1) {
6969                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6970                 if (ret < 0)
6971                         goto out;
6972
6973                 leaf = path->nodes[0];
6974                 nritems = btrfs_header_nritems(leaf);
6975 next:
6976                 if (extent_locked && ret > 0) {
6977                         /*
6978                          * the file extent item was modified by someone
6979                          * before the extent got locked.
6980                          */
6981                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6982                                       lock_end, GFP_NOFS);
6983                         extent_locked = 0;
6984                 }
6985
6986                 if (path->slots[0] >= nritems) {
6987                         if (++nr_scaned > 2)
6988                                 break;
6989
6990                         BUG_ON(extent_locked);
6991                         ret = btrfs_next_leaf(root, path);
6992                         if (ret < 0)
6993                                 goto out;
6994                         if (ret > 0)
6995                                 break;
6996                         leaf = path->nodes[0];
6997                         nritems = btrfs_header_nritems(leaf);
6998                 }
6999
7000                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7001
7002                 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
7003                         if ((key.objectid > ref_path->owner_objectid) ||
7004                             (key.objectid == ref_path->owner_objectid &&
7005                              key.type > BTRFS_EXTENT_DATA_KEY) ||
7006                             key.offset >= search_end)
7007                                 break;
7008                 }
7009
7010                 if (inode && key.objectid != inode->i_ino) {
7011                         BUG_ON(extent_locked);
7012                         btrfs_release_path(root, path);
7013                         mutex_unlock(&inode->i_mutex);
7014                         iput(inode);
7015                         inode = NULL;
7016                         continue;
7017                 }
7018
7019                 if (key.type != BTRFS_EXTENT_DATA_KEY) {
7020                         path->slots[0]++;
7021                         ret = 1;
7022                         goto next;
7023                 }
7024                 fi = btrfs_item_ptr(leaf, path->slots[0],
7025                                     struct btrfs_file_extent_item);
7026                 extent_type = btrfs_file_extent_type(leaf, fi);
7027                 if ((extent_type != BTRFS_FILE_EXTENT_REG &&
7028                      extent_type != BTRFS_FILE_EXTENT_PREALLOC) ||
7029                     (btrfs_file_extent_disk_bytenr(leaf, fi) !=
7030                      extent_key->objectid)) {
7031                         path->slots[0]++;
7032                         ret = 1;
7033                         goto next;
7034                 }
7035
7036                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
7037                 ext_offset = btrfs_file_extent_offset(leaf, fi);
7038
7039                 if (search_end == (u64)-1) {
7040                         search_end = key.offset - ext_offset +
7041                                 btrfs_file_extent_ram_bytes(leaf, fi);
7042                 }
7043
7044                 if (!extent_locked) {
7045                         lock_start = key.offset;
7046                         lock_end = lock_start + num_bytes - 1;
7047                 } else {
7048                         if (lock_start > key.offset ||
7049                             lock_end + 1 < key.offset + num_bytes) {
7050                                 unlock_extent(&BTRFS_I(inode)->io_tree,
7051                                               lock_start, lock_end, GFP_NOFS);
7052                                 extent_locked = 0;
7053                         }
7054                 }
7055
7056                 if (!inode) {
7057                         btrfs_release_path(root, path);
7058
7059                         inode = btrfs_iget_locked(root->fs_info->sb,
7060                                                   key.objectid, root);
7061                         if (inode->i_state & I_NEW) {
7062                                 BTRFS_I(inode)->root = root;
7063                                 BTRFS_I(inode)->location.objectid =
7064                                         key.objectid;
7065                                 BTRFS_I(inode)->location.type =
7066                                         BTRFS_INODE_ITEM_KEY;
7067                                 BTRFS_I(inode)->location.offset = 0;
7068                                 btrfs_read_locked_inode(inode);
7069                                 unlock_new_inode(inode);
7070                         }
7071                         /*
7072                          * some code call btrfs_commit_transaction while
7073                          * holding the i_mutex, so we can't use mutex_lock
7074                          * here.
7075                          */
7076                         if (is_bad_inode(inode) ||
7077                             !mutex_trylock(&inode->i_mutex)) {
7078                                 iput(inode);
7079                                 inode = NULL;
7080                                 key.offset = (u64)-1;
7081                                 goto skip;
7082                         }
7083                 }
7084
7085                 if (!extent_locked) {
7086                         struct btrfs_ordered_extent *ordered;
7087
7088                         btrfs_release_path(root, path);
7089
7090                         lock_extent(&BTRFS_I(inode)->io_tree, lock_start,
7091                                     lock_end, GFP_NOFS);
7092                         ordered = btrfs_lookup_first_ordered_extent(inode,
7093                                                                     lock_end);
7094                         if (ordered &&
7095                             ordered->file_offset <= lock_end &&
7096                             ordered->file_offset + ordered->len > lock_start) {
7097                                 unlock_extent(&BTRFS_I(inode)->io_tree,
7098                                               lock_start, lock_end, GFP_NOFS);
7099                                 btrfs_start_ordered_extent(inode, ordered, 1);
7100                                 btrfs_put_ordered_extent(ordered);
7101                                 key.offset += num_bytes;
7102                                 goto skip;
7103                         }
7104                         if (ordered)
7105                                 btrfs_put_ordered_extent(ordered);
7106
7107                         extent_locked = 1;
7108                         continue;
7109                 }
7110
7111                 if (nr_extents == 1) {
7112                         /* update extent pointer in place */
7113                         btrfs_set_file_extent_disk_bytenr(leaf, fi,
7114                                                 new_extents[0].disk_bytenr);
7115                         btrfs_set_file_extent_disk_num_bytes(leaf, fi,
7116                                                 new_extents[0].disk_num_bytes);
7117                         btrfs_mark_buffer_dirty(leaf);
7118
7119                         btrfs_drop_extent_cache(inode, key.offset,
7120                                                 key.offset + num_bytes - 1, 0);
7121
7122                         ret = btrfs_inc_extent_ref(trans, root,
7123                                                 new_extents[0].disk_bytenr,
7124                                                 new_extents[0].disk_num_bytes,
7125                                                 leaf->start,
7126                                                 root->root_key.objectid,
7127                                                 trans->transid,
7128                                                 key.objectid);
7129                         BUG_ON(ret);
7130
7131                         ret = btrfs_free_extent(trans, root,
7132                                                 extent_key->objectid,
7133                                                 extent_key->offset,
7134                                                 leaf->start,
7135                                                 btrfs_header_owner(leaf),
7136                                                 btrfs_header_generation(leaf),
7137                                                 key.objectid, 0);
7138                         BUG_ON(ret);
7139
7140                         btrfs_release_path(root, path);
7141                         key.offset += num_bytes;
7142                 } else {
7143                         BUG_ON(1);
7144 #if 0
7145                         u64 alloc_hint;
7146                         u64 extent_len;
7147                         int i;
7148                         /*
7149                          * drop old extent pointer at first, then insert the
7150                          * new pointers one bye one
7151                          */
7152                         btrfs_release_path(root, path);
7153                         ret = btrfs_drop_extents(trans, root, inode, key.offset,
7154                                                  key.offset + num_bytes,
7155                                                  key.offset, &alloc_hint);
7156                         BUG_ON(ret);
7157
7158                         for (i = 0; i < nr_extents; i++) {
7159                                 if (ext_offset >= new_extents[i].num_bytes) {
7160                                         ext_offset -= new_extents[i].num_bytes;
7161                                         continue;
7162                                 }
7163                                 extent_len = min(new_extents[i].num_bytes -
7164                                                  ext_offset, num_bytes);
7165
7166                                 ret = btrfs_insert_empty_item(trans, root,
7167                                                               path, &key,
7168                                                               sizeof(*fi));
7169                                 BUG_ON(ret);
7170
7171                                 leaf = path->nodes[0];
7172                                 fi = btrfs_item_ptr(leaf, path->slots[0],
7173                                                 struct btrfs_file_extent_item);
7174                                 btrfs_set_file_extent_generation(leaf, fi,
7175                                                         trans->transid);
7176                                 btrfs_set_file_extent_type(leaf, fi,
7177                                                         BTRFS_FILE_EXTENT_REG);
7178                                 btrfs_set_file_extent_disk_bytenr(leaf, fi,
7179                                                 new_extents[i].disk_bytenr);
7180                                 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
7181                                                 new_extents[i].disk_num_bytes);
7182                                 btrfs_set_file_extent_ram_bytes(leaf, fi,
7183                                                 new_extents[i].ram_bytes);
7184
7185                                 btrfs_set_file_extent_compression(leaf, fi,
7186                                                 new_extents[i].compression);
7187                                 btrfs_set_file_extent_encryption(leaf, fi,
7188                                                 new_extents[i].encryption);
7189                                 btrfs_set_file_extent_other_encoding(leaf, fi,
7190                                                 new_extents[i].other_encoding);
7191
7192                                 btrfs_set_file_extent_num_bytes(leaf, fi,
7193                                                         extent_len);
7194                                 ext_offset += new_extents[i].offset;
7195                                 btrfs_set_file_extent_offset(leaf, fi,
7196                                                         ext_offset);
7197                                 btrfs_mark_buffer_dirty(leaf);
7198
7199                                 btrfs_drop_extent_cache(inode, key.offset,
7200                                                 key.offset + extent_len - 1, 0);
7201
7202                                 ret = btrfs_inc_extent_ref(trans, root,
7203                                                 new_extents[i].disk_bytenr,
7204                                                 new_extents[i].disk_num_bytes,
7205                                                 leaf->start,
7206                                                 root->root_key.objectid,
7207                                                 trans->transid, key.objectid);
7208                                 BUG_ON(ret);
7209                                 btrfs_release_path(root, path);
7210
7211                                 inode_add_bytes(inode, extent_len);
7212
7213                                 ext_offset = 0;
7214                                 num_bytes -= extent_len;
7215                                 key.offset += extent_len;
7216
7217                                 if (num_bytes == 0)
7218                                         break;
7219                         }
7220                         BUG_ON(i >= nr_extents);
7221 #endif
7222                 }
7223
7224                 if (extent_locked) {
7225                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
7226                                       lock_end, GFP_NOFS);
7227                         extent_locked = 0;
7228                 }
7229 skip:
7230                 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS &&
7231                     key.offset >= search_end)
7232                         break;
7233
7234                 cond_resched();
7235         }
7236         ret = 0;
7237 out:
7238         btrfs_release_path(root, path);
7239         if (inode) {
7240                 mutex_unlock(&inode->i_mutex);
7241                 if (extent_locked) {
7242                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
7243                                       lock_end, GFP_NOFS);
7244                 }
7245                 iput(inode);
7246         }
7247         return ret;
7248 }
7249
7250 int btrfs_reloc_tree_cache_ref(struct btrfs_trans_handle *trans,
7251                                struct btrfs_root *root,
7252                                struct extent_buffer *buf, u64 orig_start)
7253 {
7254         int level;
7255         int ret;
7256
7257         BUG_ON(btrfs_header_generation(buf) != trans->transid);
7258         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7259
7260         level = btrfs_header_level(buf);
7261         if (level == 0) {
7262                 struct btrfs_leaf_ref *ref;
7263                 struct btrfs_leaf_ref *orig_ref;
7264
7265                 orig_ref = btrfs_lookup_leaf_ref(root, orig_start);
7266                 if (!orig_ref)
7267                         return -ENOENT;
7268
7269                 ref = btrfs_alloc_leaf_ref(root, orig_ref->nritems);
7270                 if (!ref) {
7271                         btrfs_free_leaf_ref(root, orig_ref);
7272                         return -ENOMEM;
7273                 }
7274
7275                 ref->nritems = orig_ref->nritems;
7276                 memcpy(ref->extents, orig_ref->extents,
7277                         sizeof(ref->extents[0]) * ref->nritems);
7278
7279                 btrfs_free_leaf_ref(root, orig_ref);
7280
7281                 ref->root_gen = trans->transid;
7282                 ref->bytenr = buf->start;
7283                 ref->owner = btrfs_header_owner(buf);
7284                 ref->generation = btrfs_header_generation(buf);
7285
7286                 ret = btrfs_add_leaf_ref(root, ref, 0);
7287                 WARN_ON(ret);
7288                 btrfs_free_leaf_ref(root, ref);
7289         }
7290         return 0;
7291 }
7292
7293 static noinline int invalidate_extent_cache(struct btrfs_root *root,
7294                                         struct extent_buffer *leaf,
7295                                         struct btrfs_block_group_cache *group,
7296                                         struct btrfs_root *target_root)
7297 {
7298         struct btrfs_key key;
7299         struct inode *inode = NULL;
7300         struct btrfs_file_extent_item *fi;
7301         struct extent_state *cached_state = NULL;
7302         u64 num_bytes;
7303         u64 skip_objectid = 0;
7304         u32 nritems;
7305         u32 i;
7306
7307         nritems = btrfs_header_nritems(leaf);
7308         for (i = 0; i < nritems; i++) {
7309                 btrfs_item_key_to_cpu(leaf, &key, i);
7310                 if (key.objectid == skip_objectid ||
7311                     key.type != BTRFS_EXTENT_DATA_KEY)
7312                         continue;
7313                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
7314                 if (btrfs_file_extent_type(leaf, fi) ==
7315                     BTRFS_FILE_EXTENT_INLINE)
7316                         continue;
7317                 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
7318                         continue;
7319                 if (!inode || inode->i_ino != key.objectid) {
7320                         iput(inode);
7321                         inode = btrfs_ilookup(target_root->fs_info->sb,
7322                                               key.objectid, target_root, 1);
7323                 }
7324                 if (!inode) {
7325                         skip_objectid = key.objectid;
7326                         continue;
7327                 }
7328                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
7329
7330                 lock_extent_bits(&BTRFS_I(inode)->io_tree, key.offset,
7331                                  key.offset + num_bytes - 1, 0, &cached_state,
7332                                  GFP_NOFS);
7333                 btrfs_drop_extent_cache(inode, key.offset,
7334                                         key.offset + num_bytes - 1, 1);
7335                 unlock_extent_cached(&BTRFS_I(inode)->io_tree, key.offset,
7336                                      key.offset + num_bytes - 1, &cached_state,
7337                                      GFP_NOFS);
7338                 cond_resched();
7339         }
7340         iput(inode);
7341         return 0;
7342 }
7343
7344 static noinline int replace_extents_in_leaf(struct btrfs_trans_handle *trans,
7345                                         struct btrfs_root *root,
7346                                         struct extent_buffer *leaf,
7347                                         struct btrfs_block_group_cache *group,
7348                                         struct inode *reloc_inode)
7349 {
7350         struct btrfs_key key;
7351         struct btrfs_key extent_key;
7352         struct btrfs_file_extent_item *fi;
7353         struct btrfs_leaf_ref *ref;
7354         struct disk_extent *new_extent;
7355         u64 bytenr;
7356         u64 num_bytes;
7357         u32 nritems;
7358         u32 i;
7359         int ext_index;
7360         int nr_extent;
7361         int ret;
7362
7363         new_extent = kmalloc(sizeof(*new_extent), GFP_NOFS);
7364         BUG_ON(!new_extent);
7365
7366         ref = btrfs_lookup_leaf_ref(root, leaf->start);
7367         BUG_ON(!ref);
7368
7369         ext_index = -1;
7370         nritems = btrfs_header_nritems(leaf);
7371         for (i = 0; i < nritems; i++) {
7372                 btrfs_item_key_to_cpu(leaf, &key, i);
7373                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
7374                         continue;
7375                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
7376                 if (btrfs_file_extent_type(leaf, fi) ==
7377                     BTRFS_FILE_EXTENT_INLINE)
7378                         continue;
7379                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
7380                 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
7381                 if (bytenr == 0)
7382                         continue;
7383
7384                 ext_index++;
7385                 if (bytenr >= group->key.objectid + group->key.offset ||
7386                     bytenr + num_bytes <= group->key.objectid)
7387                         continue;
7388
7389                 extent_key.objectid = bytenr;
7390                 extent_key.offset = num_bytes;
7391                 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
7392                 nr_extent = 1;
7393                 ret = get_new_locations(reloc_inode, &extent_key,
7394                                         group->key.objectid, 1,
7395                                         &new_extent, &nr_extent);
7396                 if (ret > 0)
7397                         continue;
7398                 BUG_ON(ret < 0);
7399
7400                 BUG_ON(ref->extents[ext_index].bytenr != bytenr);
7401                 BUG_ON(ref->extents[ext_index].num_bytes != num_bytes);
7402                 ref->extents[ext_index].bytenr = new_extent->disk_bytenr;
7403                 ref->extents[ext_index].num_bytes = new_extent->disk_num_bytes;
7404
7405                 btrfs_set_file_extent_disk_bytenr(leaf, fi,
7406                                                 new_extent->disk_bytenr);
7407                 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
7408                                                 new_extent->disk_num_bytes);
7409                 btrfs_mark_buffer_dirty(leaf);
7410
7411                 ret = btrfs_inc_extent_ref(trans, root,
7412                                         new_extent->disk_bytenr,
7413                                         new_extent->disk_num_bytes,
7414                                         leaf->start,
7415                                         root->root_key.objectid,
7416                                         trans->transid, key.objectid);
7417                 BUG_ON(ret);
7418
7419                 ret = btrfs_free_extent(trans, root,
7420                                         bytenr, num_bytes, leaf->start,
7421                                         btrfs_header_owner(leaf),
7422                                         btrfs_header_generation(leaf),
7423                                         key.objectid, 0);
7424                 BUG_ON(ret);
7425                 cond_resched();
7426         }
7427         kfree(new_extent);
7428         BUG_ON(ext_index + 1 != ref->nritems);
7429         btrfs_free_leaf_ref(root, ref);
7430         return 0;
7431 }
7432
7433 int btrfs_free_reloc_root(struct btrfs_trans_handle *trans,
7434                           struct btrfs_root *root)
7435 {
7436         struct btrfs_root *reloc_root;
7437         int ret;
7438
7439         if (root->reloc_root) {
7440                 reloc_root = root->reloc_root;
7441                 root->reloc_root = NULL;
7442                 list_add(&reloc_root->dead_list,
7443                          &root->fs_info->dead_reloc_roots);
7444
7445                 btrfs_set_root_bytenr(&reloc_root->root_item,
7446                                       reloc_root->node->start);
7447                 btrfs_set_root_level(&root->root_item,
7448                                      btrfs_header_level(reloc_root->node));
7449                 memset(&reloc_root->root_item.drop_progress, 0,
7450                         sizeof(struct btrfs_disk_key));
7451                 reloc_root->root_item.drop_level = 0;
7452
7453                 ret = btrfs_update_root(trans, root->fs_info->tree_root,
7454                                         &reloc_root->root_key,
7455                                         &reloc_root->root_item);
7456                 BUG_ON(ret);
7457         }
7458         return 0;
7459 }
7460
7461 int btrfs_drop_dead_reloc_roots(struct btrfs_root *root)
7462 {
7463         struct btrfs_trans_handle *trans;
7464         struct btrfs_root *reloc_root;
7465         struct btrfs_root *prev_root = NULL;
7466         struct list_head dead_roots;
7467         int ret;
7468         unsigned long nr;
7469
7470         INIT_LIST_HEAD(&dead_roots);
7471         list_splice_init(&root->fs_info->dead_reloc_roots, &dead_roots);
7472
7473         while (!list_empty(&dead_roots)) {
7474                 reloc_root = list_entry(dead_roots.prev,
7475                                         struct btrfs_root, dead_list);
7476                 list_del_init(&reloc_root->dead_list);
7477
7478                 BUG_ON(reloc_root->commit_root != NULL);
7479                 while (1) {
7480                         trans = btrfs_join_transaction(root, 1);
7481                         BUG_ON(!trans);
7482
7483                         mutex_lock(&root->fs_info->drop_mutex);
7484                         ret = btrfs_drop_snapshot(trans, reloc_root);
7485                         if (ret != -EAGAIN)
7486                                 break;
7487                         mutex_unlock(&root->fs_info->drop_mutex);
7488
7489                         nr = trans->blocks_used;
7490                         ret = btrfs_end_transaction(trans, root);
7491                         BUG_ON(ret);
7492                         btrfs_btree_balance_dirty(root, nr);
7493                 }
7494
7495                 free_extent_buffer(reloc_root->node);
7496
7497                 ret = btrfs_del_root(trans, root->fs_info->tree_root,
7498                                      &reloc_root->root_key);
7499                 BUG_ON(ret);
7500                 mutex_unlock(&root->fs_info->drop_mutex);
7501
7502                 nr = trans->blocks_used;
7503                 ret = btrfs_end_transaction(trans, root);
7504                 BUG_ON(ret);
7505                 btrfs_btree_balance_dirty(root, nr);
7506
7507                 kfree(prev_root);
7508                 prev_root = reloc_root;
7509         }
7510         if (prev_root) {
7511                 btrfs_remove_leaf_refs(prev_root, (u64)-1, 0);
7512                 kfree(prev_root);
7513         }
7514         return 0;
7515 }
7516
7517 int btrfs_add_dead_reloc_root(struct btrfs_root *root)
7518 {
7519         list_add(&root->dead_list, &root->fs_info->dead_reloc_roots);
7520         return 0;
7521 }
7522
7523 int btrfs_cleanup_reloc_trees(struct btrfs_root *root)
7524 {
7525         struct btrfs_root *reloc_root;
7526         struct btrfs_trans_handle *trans;
7527         struct btrfs_key location;
7528         int found;
7529         int ret;
7530
7531         mutex_lock(&root->fs_info->tree_reloc_mutex);
7532         ret = btrfs_find_dead_roots(root, BTRFS_TREE_RELOC_OBJECTID, NULL);
7533         BUG_ON(ret);
7534         found = !list_empty(&root->fs_info->dead_reloc_roots);
7535         mutex_unlock(&root->fs_info->tree_reloc_mutex);
7536
7537         if (found) {
7538                 trans = btrfs_start_transaction(root, 1);
7539                 BUG_ON(!trans);
7540                 ret = btrfs_commit_transaction(trans, root);
7541                 BUG_ON(ret);
7542         }
7543
7544         location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
7545         location.offset = (u64)-1;
7546         location.type = BTRFS_ROOT_ITEM_KEY;
7547
7548         reloc_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
7549         BUG_ON(!reloc_root);
7550         btrfs_orphan_cleanup(reloc_root);
7551         return 0;
7552 }
7553
7554 static noinline int init_reloc_tree(struct btrfs_trans_handle *trans,
7555                                     struct btrfs_root *root)
7556 {
7557         struct btrfs_root *reloc_root;
7558         struct extent_buffer *eb;
7559         struct btrfs_root_item *root_item;
7560         struct btrfs_key root_key;
7561         int ret;
7562
7563         BUG_ON(!root->ref_cows);
7564         if (root->reloc_root)
7565                 return 0;
7566
7567         root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
7568         BUG_ON(!root_item);
7569
7570         ret = btrfs_copy_root(trans, root, root->commit_root,
7571                               &eb, BTRFS_TREE_RELOC_OBJECTID);
7572         BUG_ON(ret);
7573
7574         root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
7575         root_key.offset = root->root_key.objectid;
7576         root_key.type = BTRFS_ROOT_ITEM_KEY;
7577
7578         memcpy(root_item, &root->root_item, sizeof(root_item));
7579         btrfs_set_root_refs(root_item, 0);
7580         btrfs_set_root_bytenr(root_item, eb->start);
7581         btrfs_set_root_level(root_item, btrfs_header_level(eb));
7582         btrfs_set_root_generation(root_item, trans->transid);
7583
7584         btrfs_tree_unlock(eb);
7585         free_extent_buffer(eb);
7586
7587         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
7588                                 &root_key, root_item);
7589         BUG_ON(ret);
7590         kfree(root_item);
7591
7592         reloc_root = btrfs_read_fs_root_no_radix(root->fs_info->tree_root,
7593                                                  &root_key);
7594         BUG_ON(!reloc_root);
7595         reloc_root->last_trans = trans->transid;
7596         reloc_root->commit_root = NULL;
7597         reloc_root->ref_tree = &root->fs_info->reloc_ref_tree;
7598
7599         root->reloc_root = reloc_root;
7600         return 0;
7601 }
7602
7603 /*
7604  * Core function of space balance.
7605  *
7606  * The idea is using reloc trees to relocate tree blocks in reference
7607  * counted roots. There is one reloc tree for each subvol, and all
7608  * reloc trees share same root key objectid. Reloc trees are snapshots
7609  * of the latest committed roots of subvols (root->commit_root).
7610  *
7611  * To relocate a tree block referenced by a subvol, there are two steps.
7612  * COW the block through subvol's reloc tree, then update block pointer
7613  * in the subvol to point to the new block. Since all reloc trees share
7614  * same root key objectid, doing special handing for tree blocks owned
7615  * by them is easy. Once a tree block has been COWed in one reloc tree,
7616  * we can use the resulting new block directly when the same block is
7617  * required to COW again through other reloc trees. By this way, relocated
7618  * tree blocks are shared between reloc trees, so they are also shared
7619  * between subvols.
7620  */
7621 static noinline int relocate_one_path(struct btrfs_trans_handle *trans,
7622                                       struct btrfs_root *root,
7623                                       struct btrfs_path *path,
7624                                       struct btrfs_key *first_key,
7625                                       struct btrfs_ref_path *ref_path,
7626                                       struct btrfs_block_group_cache *group,
7627                                       struct inode *reloc_inode)
7628 {
7629         struct btrfs_root *reloc_root;
7630         struct extent_buffer *eb = NULL;
7631         struct btrfs_key *keys;
7632         u64 *nodes;
7633         int level;
7634         int shared_level;
7635         int lowest_level = 0;
7636         int ret;
7637
7638         if (ref_path->owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
7639                 lowest_level = ref_path->owner_objectid;
7640
7641         if (!root->ref_cows) {
7642                 path->lowest_level = lowest_level;
7643                 ret = btrfs_search_slot(trans, root, first_key, path, 0, 1);
7644                 BUG_ON(ret < 0);
7645                 path->lowest_level = 0;
7646                 btrfs_release_path(root, path);
7647                 return 0;
7648         }
7649
7650         mutex_lock(&root->fs_info->tree_reloc_mutex);
7651         ret = init_reloc_tree(trans, root);
7652         BUG_ON(ret);
7653         reloc_root = root->reloc_root;
7654
7655         shared_level = ref_path->shared_level;
7656         ref_path->shared_level = BTRFS_MAX_LEVEL - 1;
7657
7658         keys = ref_path->node_keys;
7659         nodes = ref_path->new_nodes;
7660         memset(&keys[shared_level + 1], 0,
7661                sizeof(*keys) * (BTRFS_MAX_LEVEL - shared_level - 1));
7662         memset(&nodes[shared_level + 1], 0,
7663                sizeof(*nodes) * (BTRFS_MAX_LEVEL - shared_level - 1));
7664
7665         if (nodes[lowest_level] == 0) {
7666                 path->lowest_level = lowest_level;
7667                 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
7668                                         0, 1);
7669                 BUG_ON(ret);
7670                 for (level = lowest_level; level < BTRFS_MAX_LEVEL; level++) {
7671                         eb = path->nodes[level];
7672                         if (!eb || eb == reloc_root->node)
7673                                 break;
7674                         nodes[level] = eb->start;
7675                         if (level == 0)
7676                                 btrfs_item_key_to_cpu(eb, &keys[level], 0);
7677                         else
7678                                 btrfs_node_key_to_cpu(eb, &keys[level], 0);
7679                 }
7680                 if (nodes[0] &&
7681                     ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
7682                         eb = path->nodes[0];
7683                         ret = replace_extents_in_leaf(trans, reloc_root, eb,
7684                                                       group, reloc_inode);
7685                         BUG_ON(ret);
7686                 }
7687                 btrfs_release_path(reloc_root, path);
7688         } else {
7689                 ret = btrfs_merge_path(trans, reloc_root, keys, nodes,
7690                                        lowest_level);
7691                 BUG_ON(ret);
7692         }
7693
7694         /*
7695          * replace tree blocks in the fs tree with tree blocks in
7696          * the reloc tree.
7697          */
7698         ret = btrfs_merge_path(trans, root, keys, nodes, lowest_level);
7699         BUG_ON(ret < 0);
7700
7701         if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
7702                 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
7703                                         0, 0);
7704                 BUG_ON(ret);
7705                 extent_buffer_get(path->nodes[0]);
7706                 eb = path->nodes[0];
7707                 btrfs_release_path(reloc_root, path);
7708                 ret = invalidate_extent_cache(reloc_root, eb, group, root);
7709                 BUG_ON(ret);
7710                 free_extent_buffer(eb);
7711         }
7712
7713         mutex_unlock(&root->fs_info->tree_reloc_mutex);
7714         path->lowest_level = 0;
7715         return 0;
7716 }
7717
7718 static noinline int relocate_tree_block(struct btrfs_trans_handle *trans,
7719                                         struct btrfs_root *root,
7720                                         struct btrfs_path *path,
7721                                         struct btrfs_key *first_key,
7722                                         struct btrfs_ref_path *ref_path)
7723 {
7724         int ret;
7725
7726         ret = relocate_one_path(trans, root, path, first_key,
7727                                 ref_path, NULL, NULL);
7728         BUG_ON(ret);
7729
7730         return 0;
7731 }
7732
7733 static noinline int del_extent_zero(struct btrfs_trans_handle *trans,
7734                                     struct btrfs_root *extent_root,
7735                                     struct btrfs_path *path,
7736                                     struct btrfs_key *extent_key)
7737 {
7738         int ret;
7739
7740         ret = btrfs_search_slot(trans, extent_root, extent_key, path, -1, 1);
7741         if (ret)
7742                 goto out;
7743         ret = btrfs_del_item(trans, extent_root, path);
7744 out:
7745         btrfs_release_path(extent_root, path);
7746         return ret;
7747 }
7748
7749 static noinline struct btrfs_root *read_ref_root(struct btrfs_fs_info *fs_info,
7750                                                 struct btrfs_ref_path *ref_path)
7751 {
7752         struct btrfs_key root_key;
7753
7754         root_key.objectid = ref_path->root_objectid;
7755         root_key.type = BTRFS_ROOT_ITEM_KEY;
7756         if (is_cowonly_root(ref_path->root_objectid))
7757                 root_key.offset = 0;
7758         else
7759                 root_key.offset = (u64)-1;
7760
7761         return btrfs_read_fs_root_no_name(fs_info, &root_key);
7762 }
7763
7764 static noinline int relocate_one_extent(struct btrfs_root *extent_root,
7765                                         struct btrfs_path *path,
7766                                         struct btrfs_key *extent_key,
7767                                         struct btrfs_block_group_cache *group,
7768                                         struct inode *reloc_inode, int pass)
7769 {
7770         struct btrfs_trans_handle *trans;
7771         struct btrfs_root *found_root;
7772         struct btrfs_ref_path *ref_path = NULL;
7773         struct disk_extent *new_extents = NULL;
7774         int nr_extents = 0;
7775         int loops;
7776         int ret;
7777         int level;
7778         struct btrfs_key first_key;
7779         u64 prev_block = 0;
7780
7781
7782         trans = btrfs_start_transaction(extent_root, 1);
7783         BUG_ON(!trans);
7784
7785         if (extent_key->objectid == 0) {
7786                 ret = del_extent_zero(trans, extent_root, path, extent_key);
7787                 goto out;
7788         }
7789
7790         ref_path = kmalloc(sizeof(*ref_path), GFP_NOFS);
7791         if (!ref_path) {
7792                 ret = -ENOMEM;
7793                 goto out;
7794         }
7795
7796         for (loops = 0; ; loops++) {
7797                 if (loops == 0) {
7798                         ret = btrfs_first_ref_path(trans, extent_root, ref_path,
7799                                                    extent_key->objectid);
7800                 } else {
7801                         ret = btrfs_next_ref_path(trans, extent_root, ref_path);
7802                 }
7803                 if (ret < 0)
7804                         goto out;
7805                 if (ret > 0)
7806                         break;
7807
7808                 if (ref_path->root_objectid == BTRFS_TREE_LOG_OBJECTID ||
7809                     ref_path->root_objectid == BTRFS_TREE_RELOC_OBJECTID)
7810                         continue;
7811
7812                 found_root = read_ref_root(extent_root->fs_info, ref_path);
7813                 BUG_ON(!found_root);
7814                 /*
7815                  * for reference counted tree, only process reference paths
7816                  * rooted at the latest committed root.
7817                  */
7818                 if (found_root->ref_cows &&
7819                     ref_path->root_generation != found_root->root_key.offset)
7820                         continue;
7821
7822                 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
7823                         if (pass == 0) {
7824                                 /*
7825                                  * copy data extents to new locations
7826                                  */
7827                                 u64 group_start = group->key.objectid;
7828                                 ret = relocate_data_extent(reloc_inode,
7829                                                            extent_key,
7830                                                            group_start);
7831                                 if (ret < 0)
7832                                         goto out;
7833                                 break;
7834                         }
7835                         level = 0;
7836                 } else {
7837                         level = ref_path->owner_objectid;
7838                 }
7839
7840                 if (prev_block != ref_path->nodes[level]) {
7841                         struct extent_buffer *eb;
7842                         u64 block_start = ref_path->nodes[level];
7843                         u64 block_size = btrfs_level_size(found_root, level);
7844
7845                         eb = read_tree_block(found_root, block_start,
7846                                              block_size, 0);
7847                         btrfs_tree_lock(eb);
7848                         BUG_ON(level != btrfs_header_level(eb));
7849
7850                         if (level == 0)
7851                                 btrfs_item_key_to_cpu(eb, &first_key, 0);
7852                         else
7853                                 btrfs_node_key_to_cpu(eb, &first_key, 0);
7854
7855                         btrfs_tree_unlock(eb);
7856                         free_extent_buffer(eb);
7857                         prev_block = block_start;
7858                 }
7859
7860                 mutex_lock(&extent_root->fs_info->trans_mutex);
7861                 btrfs_record_root_in_trans(found_root);
7862                 mutex_unlock(&extent_root->fs_info->trans_mutex);
7863                 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
7864                         /*
7865                          * try to update data extent references while
7866                          * keeping metadata shared between snapshots.
7867                          */
7868                         if (pass == 1) {
7869                                 ret = relocate_one_path(trans, found_root,
7870                                                 path, &first_key, ref_path,
7871                                                 group, reloc_inode);
7872                                 if (ret < 0)
7873                                         goto out;
7874                                 continue;
7875                         }
7876                         /*
7877                          * use fallback method to process the remaining
7878                          * references.
7879                          */
7880                         if (!new_extents) {
7881                                 u64 group_start = group->key.objectid;
7882                                 new_extents = kmalloc(sizeof(*new_extents),
7883                                                       GFP_NOFS);
7884                                 nr_extents = 1;
7885                                 ret = get_new_locations(reloc_inode,
7886                                                         extent_key,
7887                                                         group_start, 1,
7888                                                         &new_extents,
7889                                                         &nr_extents);
7890                                 if (ret)
7891                                         goto out;
7892                         }
7893                         ret = replace_one_extent(trans, found_root,
7894                                                 path, extent_key,
7895                                                 &first_key, ref_path,
7896                                                 new_extents, nr_extents);
7897                 } else {
7898                         ret = relocate_tree_block(trans, found_root, path,
7899                                                   &first_key, ref_path);
7900                 }
7901                 if (ret < 0)
7902                         goto out;
7903         }
7904         ret = 0;
7905 out:
7906         btrfs_end_transaction(trans, extent_root);
7907         kfree(new_extents);
7908         kfree(ref_path);
7909         return ret;
7910 }
7911 #endif
7912
7913 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
7914 {
7915         u64 num_devices;
7916         u64 stripped = BTRFS_BLOCK_GROUP_RAID0 |
7917                 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
7918
7919         /*
7920          * we add in the count of missing devices because we want
7921          * to make sure that any RAID levels on a degraded FS
7922          * continue to be honored.
7923          */
7924         num_devices = root->fs_info->fs_devices->rw_devices +
7925                 root->fs_info->fs_devices->missing_devices;
7926
7927         if (num_devices == 1) {
7928                 stripped |= BTRFS_BLOCK_GROUP_DUP;
7929                 stripped = flags & ~stripped;
7930
7931                 /* turn raid0 into single device chunks */
7932                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
7933                         return stripped;
7934
7935                 /* turn mirroring into duplication */
7936                 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
7937                              BTRFS_BLOCK_GROUP_RAID10))
7938                         return stripped | BTRFS_BLOCK_GROUP_DUP;
7939                 return flags;
7940         } else {
7941                 /* they already had raid on here, just return */
7942                 if (flags & stripped)
7943                         return flags;
7944
7945                 stripped |= BTRFS_BLOCK_GROUP_DUP;
7946                 stripped = flags & ~stripped;
7947
7948                 /* switch duplicated blocks with raid1 */
7949                 if (flags & BTRFS_BLOCK_GROUP_DUP)
7950                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
7951
7952                 /* turn single device chunks into raid0 */
7953                 return stripped | BTRFS_BLOCK_GROUP_RAID0;
7954         }
7955         return flags;
7956 }
7957
7958 static int set_block_group_ro(struct btrfs_block_group_cache *cache)
7959 {
7960         struct btrfs_space_info *sinfo = cache->space_info;
7961         u64 num_bytes;
7962         int ret = -ENOSPC;
7963
7964         if (cache->ro)
7965                 return 0;
7966
7967         spin_lock(&sinfo->lock);
7968         spin_lock(&cache->lock);
7969         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7970                     cache->bytes_super - btrfs_block_group_used(&cache->item);
7971
7972         if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
7973             sinfo->bytes_may_use + sinfo->bytes_readonly +
7974             cache->reserved_pinned + num_bytes <= sinfo->total_bytes) {
7975                 sinfo->bytes_readonly += num_bytes;
7976                 sinfo->bytes_reserved += cache->reserved_pinned;
7977                 cache->reserved_pinned = 0;
7978                 cache->ro = 1;
7979                 ret = 0;
7980         }
7981
7982         spin_unlock(&cache->lock);
7983         spin_unlock(&sinfo->lock);
7984         return ret;
7985 }
7986
7987 int btrfs_set_block_group_ro(struct btrfs_root *root,
7988                              struct btrfs_block_group_cache *cache)
7989
7990 {
7991         struct btrfs_trans_handle *trans;
7992         u64 alloc_flags;
7993         int ret;
7994
7995         BUG_ON(cache->ro);
7996
7997         trans = btrfs_join_transaction(root, 1);
7998         BUG_ON(IS_ERR(trans));
7999
8000         alloc_flags = update_block_group_flags(root, cache->flags);
8001         if (alloc_flags != cache->flags)
8002                 do_chunk_alloc(trans, root, 2 * 1024 * 1024, alloc_flags, 1);
8003
8004         ret = set_block_group_ro(cache);
8005         if (!ret)
8006                 goto out;
8007         alloc_flags = get_alloc_profile(root, cache->space_info->flags);
8008         ret = do_chunk_alloc(trans, root, 2 * 1024 * 1024, alloc_flags, 1);
8009         if (ret < 0)
8010                 goto out;
8011         ret = set_block_group_ro(cache);
8012 out:
8013         btrfs_end_transaction(trans, root);
8014         return ret;
8015 }
8016
8017 /*
8018  * helper to account the unused space of all the readonly block group in the
8019  * list. takes mirrors into account.
8020  */
8021 static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
8022 {
8023         struct btrfs_block_group_cache *block_group;
8024         u64 free_bytes = 0;
8025         int factor;
8026
8027         list_for_each_entry(block_group, groups_list, list) {
8028                 spin_lock(&block_group->lock);
8029
8030                 if (!block_group->ro) {
8031                         spin_unlock(&block_group->lock);
8032                         continue;
8033                 }
8034
8035                 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
8036                                           BTRFS_BLOCK_GROUP_RAID10 |
8037                                           BTRFS_BLOCK_GROUP_DUP))
8038                         factor = 2;
8039                 else
8040                         factor = 1;
8041
8042                 free_bytes += (block_group->key.offset -
8043                                btrfs_block_group_used(&block_group->item)) *
8044                                factor;
8045
8046                 spin_unlock(&block_group->lock);
8047         }
8048
8049         return free_bytes;
8050 }
8051
8052 /*
8053  * helper to account the unused space of all the readonly block group in the
8054  * space_info. takes mirrors into account.
8055  */
8056 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
8057 {
8058         int i;
8059         u64 free_bytes = 0;
8060
8061         spin_lock(&sinfo->lock);
8062
8063         for(i = 0; i < BTRFS_NR_RAID_TYPES; i++)
8064                 if (!list_empty(&sinfo->block_groups[i]))
8065                         free_bytes += __btrfs_get_ro_block_group_free_space(
8066                                                 &sinfo->block_groups[i]);
8067
8068         spin_unlock(&sinfo->lock);
8069
8070         return free_bytes;
8071 }
8072
8073 int btrfs_set_block_group_rw(struct btrfs_root *root,
8074                               struct btrfs_block_group_cache *cache)
8075 {
8076         struct btrfs_space_info *sinfo = cache->space_info;
8077         u64 num_bytes;
8078
8079         BUG_ON(!cache->ro);
8080
8081         spin_lock(&sinfo->lock);
8082         spin_lock(&cache->lock);
8083         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8084                     cache->bytes_super - btrfs_block_group_used(&cache->item);
8085         sinfo->bytes_readonly -= num_bytes;
8086         cache->ro = 0;
8087         spin_unlock(&cache->lock);
8088         spin_unlock(&sinfo->lock);
8089         return 0;
8090 }
8091
8092 /*
8093  * checks to see if its even possible to relocate this block group.
8094  *
8095  * @return - -1 if it's not a good idea to relocate this block group, 0 if its
8096  * ok to go ahead and try.
8097  */
8098 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
8099 {
8100         struct btrfs_block_group_cache *block_group;
8101         struct btrfs_space_info *space_info;
8102         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
8103         struct btrfs_device *device;
8104         int full = 0;
8105         int ret = 0;
8106
8107         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
8108
8109         /* odd, couldn't find the block group, leave it alone */
8110         if (!block_group)
8111                 return -1;
8112
8113         /* no bytes used, we're good */
8114         if (!btrfs_block_group_used(&block_group->item))
8115                 goto out;
8116
8117         space_info = block_group->space_info;
8118         spin_lock(&space_info->lock);
8119
8120         full = space_info->full;
8121
8122         /*
8123          * if this is the last block group we have in this space, we can't
8124          * relocate it unless we're able to allocate a new chunk below.
8125          *
8126          * Otherwise, we need to make sure we have room in the space to handle
8127          * all of the extents from this block group.  If we can, we're good
8128          */
8129         if ((space_info->total_bytes != block_group->key.offset) &&
8130            (space_info->bytes_used + space_info->bytes_reserved +
8131             space_info->bytes_pinned + space_info->bytes_readonly +
8132             btrfs_block_group_used(&block_group->item) <
8133             space_info->total_bytes)) {
8134                 spin_unlock(&space_info->lock);
8135                 goto out;
8136         }
8137         spin_unlock(&space_info->lock);
8138
8139         /*
8140          * ok we don't have enough space, but maybe we have free space on our
8141          * devices to allocate new chunks for relocation, so loop through our
8142          * alloc devices and guess if we have enough space.  However, if we
8143          * were marked as full, then we know there aren't enough chunks, and we
8144          * can just return.
8145          */
8146         ret = -1;
8147         if (full)
8148                 goto out;
8149
8150         mutex_lock(&root->fs_info->chunk_mutex);
8151         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
8152                 u64 min_free = btrfs_block_group_used(&block_group->item);
8153                 u64 dev_offset;
8154
8155                 /*
8156                  * check to make sure we can actually find a chunk with enough
8157                  * space to fit our block group in.
8158                  */
8159                 if (device->total_bytes > device->bytes_used + min_free) {
8160                         ret = find_free_dev_extent(NULL, device, min_free,
8161                                                    &dev_offset, NULL);
8162                         if (!ret)
8163                                 break;
8164                         ret = -1;
8165                 }
8166         }
8167         mutex_unlock(&root->fs_info->chunk_mutex);
8168 out:
8169         btrfs_put_block_group(block_group);
8170         return ret;
8171 }
8172
8173 static int find_first_block_group(struct btrfs_root *root,
8174                 struct btrfs_path *path, struct btrfs_key *key)
8175 {
8176         int ret = 0;
8177         struct btrfs_key found_key;
8178         struct extent_buffer *leaf;
8179         int slot;
8180
8181         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
8182         if (ret < 0)
8183                 goto out;
8184
8185         while (1) {
8186                 slot = path->slots[0];
8187                 leaf = path->nodes[0];
8188                 if (slot >= btrfs_header_nritems(leaf)) {
8189                         ret = btrfs_next_leaf(root, path);
8190                         if (ret == 0)
8191                                 continue;
8192                         if (ret < 0)
8193                                 goto out;
8194                         break;
8195                 }
8196                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
8197
8198                 if (found_key.objectid >= key->objectid &&
8199                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
8200                         ret = 0;
8201                         goto out;
8202                 }
8203                 path->slots[0]++;
8204         }
8205 out:
8206         return ret;
8207 }
8208
8209 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
8210 {
8211         struct btrfs_block_group_cache *block_group;
8212         u64 last = 0;
8213
8214         while (1) {
8215                 struct inode *inode;
8216
8217                 block_group = btrfs_lookup_first_block_group(info, last);
8218                 while (block_group) {
8219                         spin_lock(&block_group->lock);
8220                         if (block_group->iref)
8221                                 break;
8222                         spin_unlock(&block_group->lock);
8223                         block_group = next_block_group(info->tree_root,
8224                                                        block_group);
8225                 }
8226                 if (!block_group) {
8227                         if (last == 0)
8228                                 break;
8229                         last = 0;
8230                         continue;
8231                 }
8232
8233                 inode = block_group->inode;
8234                 block_group->iref = 0;
8235                 block_group->inode = NULL;
8236                 spin_unlock(&block_group->lock);
8237                 iput(inode);
8238                 last = block_group->key.objectid + block_group->key.offset;
8239                 btrfs_put_block_group(block_group);
8240         }
8241 }
8242
8243 int btrfs_free_block_groups(struct btrfs_fs_info *info)
8244 {
8245         struct btrfs_block_group_cache *block_group;
8246         struct btrfs_space_info *space_info;
8247         struct btrfs_caching_control *caching_ctl;
8248         struct rb_node *n;
8249
8250         down_write(&info->extent_commit_sem);
8251         while (!list_empty(&info->caching_block_groups)) {
8252                 caching_ctl = list_entry(info->caching_block_groups.next,
8253                                          struct btrfs_caching_control, list);
8254                 list_del(&caching_ctl->list);
8255                 put_caching_control(caching_ctl);
8256         }
8257         up_write(&info->extent_commit_sem);
8258
8259         spin_lock(&info->block_group_cache_lock);
8260         while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
8261                 block_group = rb_entry(n, struct btrfs_block_group_cache,
8262                                        cache_node);
8263                 rb_erase(&block_group->cache_node,
8264                          &info->block_group_cache_tree);
8265                 spin_unlock(&info->block_group_cache_lock);
8266
8267                 down_write(&block_group->space_info->groups_sem);
8268                 list_del(&block_group->list);
8269                 up_write(&block_group->space_info->groups_sem);
8270
8271                 if (block_group->cached == BTRFS_CACHE_STARTED)
8272                         wait_block_group_cache_done(block_group);
8273
8274                 btrfs_remove_free_space_cache(block_group);
8275                 btrfs_put_block_group(block_group);
8276
8277                 spin_lock(&info->block_group_cache_lock);
8278         }
8279         spin_unlock(&info->block_group_cache_lock);
8280
8281         /* now that all the block groups are freed, go through and
8282          * free all the space_info structs.  This is only called during
8283          * the final stages of unmount, and so we know nobody is
8284          * using them.  We call synchronize_rcu() once before we start,
8285          * just to be on the safe side.
8286          */
8287         synchronize_rcu();
8288
8289         release_global_block_rsv(info);
8290
8291         while(!list_empty(&info->space_info)) {
8292                 space_info = list_entry(info->space_info.next,
8293                                         struct btrfs_space_info,
8294                                         list);
8295                 if (space_info->bytes_pinned > 0 ||
8296                     space_info->bytes_reserved > 0) {
8297                         WARN_ON(1);
8298                         dump_space_info(space_info, 0, 0);
8299                 }
8300                 list_del(&space_info->list);
8301                 kfree(space_info);
8302         }
8303         return 0;
8304 }
8305
8306 static void __link_block_group(struct btrfs_space_info *space_info,
8307                                struct btrfs_block_group_cache *cache)
8308 {
8309         int index = get_block_group_index(cache);
8310
8311         down_write(&space_info->groups_sem);
8312         list_add_tail(&cache->list, &space_info->block_groups[index]);
8313         up_write(&space_info->groups_sem);
8314 }
8315
8316 int btrfs_read_block_groups(struct btrfs_root *root)
8317 {
8318         struct btrfs_path *path;
8319         int ret;
8320         struct btrfs_block_group_cache *cache;
8321         struct btrfs_fs_info *info = root->fs_info;
8322         struct btrfs_space_info *space_info;
8323         struct btrfs_key key;
8324         struct btrfs_key found_key;
8325         struct extent_buffer *leaf;
8326         int need_clear = 0;
8327         u64 cache_gen;
8328
8329         root = info->extent_root;
8330         key.objectid = 0;
8331         key.offset = 0;
8332         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
8333         path = btrfs_alloc_path();
8334         if (!path)
8335                 return -ENOMEM;
8336
8337         cache_gen = btrfs_super_cache_generation(&root->fs_info->super_copy);
8338         if (cache_gen != 0 &&
8339             btrfs_super_generation(&root->fs_info->super_copy) != cache_gen)
8340                 need_clear = 1;
8341         if (btrfs_test_opt(root, CLEAR_CACHE))
8342                 need_clear = 1;
8343         if (!btrfs_test_opt(root, SPACE_CACHE) && cache_gen)
8344                 printk(KERN_INFO "btrfs: disk space caching is enabled\n");
8345
8346         while (1) {
8347                 ret = find_first_block_group(root, path, &key);
8348                 if (ret > 0)
8349                         break;
8350                 if (ret != 0)
8351                         goto error;
8352                 leaf = path->nodes[0];
8353                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8354                 cache = kzalloc(sizeof(*cache), GFP_NOFS);
8355                 if (!cache) {
8356                         ret = -ENOMEM;
8357                         goto error;
8358                 }
8359
8360                 atomic_set(&cache->count, 1);
8361                 spin_lock_init(&cache->lock);
8362                 spin_lock_init(&cache->tree_lock);
8363                 cache->fs_info = info;
8364                 INIT_LIST_HEAD(&cache->list);
8365                 INIT_LIST_HEAD(&cache->cluster_list);
8366
8367                 if (need_clear)
8368                         cache->disk_cache_state = BTRFS_DC_CLEAR;
8369
8370                 /*
8371                  * we only want to have 32k of ram per block group for keeping
8372                  * track of free space, and if we pass 1/2 of that we want to
8373                  * start converting things over to using bitmaps
8374                  */
8375                 cache->extents_thresh = ((1024 * 32) / 2) /
8376                         sizeof(struct btrfs_free_space);
8377
8378                 read_extent_buffer(leaf, &cache->item,
8379                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
8380                                    sizeof(cache->item));
8381                 memcpy(&cache->key, &found_key, sizeof(found_key));
8382
8383                 key.objectid = found_key.objectid + found_key.offset;
8384                 btrfs_release_path(root, path);
8385                 cache->flags = btrfs_block_group_flags(&cache->item);
8386                 cache->sectorsize = root->sectorsize;
8387
8388                 /*
8389                  * check for two cases, either we are full, and therefore
8390                  * don't need to bother with the caching work since we won't
8391                  * find any space, or we are empty, and we can just add all
8392                  * the space in and be done with it.  This saves us _alot_ of
8393                  * time, particularly in the full case.
8394                  */
8395                 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
8396                         exclude_super_stripes(root, cache);
8397                         cache->last_byte_to_unpin = (u64)-1;
8398                         cache->cached = BTRFS_CACHE_FINISHED;
8399                         free_excluded_extents(root, cache);
8400                 } else if (btrfs_block_group_used(&cache->item) == 0) {
8401                         exclude_super_stripes(root, cache);
8402                         cache->last_byte_to_unpin = (u64)-1;
8403                         cache->cached = BTRFS_CACHE_FINISHED;
8404                         add_new_free_space(cache, root->fs_info,
8405                                            found_key.objectid,
8406                                            found_key.objectid +
8407                                            found_key.offset);
8408                         free_excluded_extents(root, cache);
8409                 }
8410
8411                 ret = update_space_info(info, cache->flags, found_key.offset,
8412                                         btrfs_block_group_used(&cache->item),
8413                                         &space_info);
8414                 BUG_ON(ret);
8415                 cache->space_info = space_info;
8416                 spin_lock(&cache->space_info->lock);
8417                 cache->space_info->bytes_readonly += cache->bytes_super;
8418                 spin_unlock(&cache->space_info->lock);
8419
8420                 __link_block_group(space_info, cache);
8421
8422                 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8423                 BUG_ON(ret);
8424
8425                 set_avail_alloc_bits(root->fs_info, cache->flags);
8426                 if (btrfs_chunk_readonly(root, cache->key.objectid))
8427                         set_block_group_ro(cache);
8428         }
8429
8430         list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
8431                 if (!(get_alloc_profile(root, space_info->flags) &
8432                       (BTRFS_BLOCK_GROUP_RAID10 |
8433                        BTRFS_BLOCK_GROUP_RAID1 |
8434                        BTRFS_BLOCK_GROUP_DUP)))
8435                         continue;
8436                 /*
8437                  * avoid allocating from un-mirrored block group if there are
8438                  * mirrored block groups.
8439                  */
8440                 list_for_each_entry(cache, &space_info->block_groups[3], list)
8441                         set_block_group_ro(cache);
8442                 list_for_each_entry(cache, &space_info->block_groups[4], list)
8443                         set_block_group_ro(cache);
8444         }
8445
8446         init_global_block_rsv(info);
8447         ret = 0;
8448 error:
8449         btrfs_free_path(path);
8450         return ret;
8451 }
8452
8453 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
8454                            struct btrfs_root *root, u64 bytes_used,
8455                            u64 type, u64 chunk_objectid, u64 chunk_offset,
8456                            u64 size)
8457 {
8458         int ret;
8459         struct btrfs_root *extent_root;
8460         struct btrfs_block_group_cache *cache;
8461
8462         extent_root = root->fs_info->extent_root;
8463
8464         root->fs_info->last_trans_log_full_commit = trans->transid;
8465
8466         cache = kzalloc(sizeof(*cache), GFP_NOFS);
8467         if (!cache)
8468                 return -ENOMEM;
8469
8470         cache->key.objectid = chunk_offset;
8471         cache->key.offset = size;
8472         cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8473         cache->sectorsize = root->sectorsize;
8474         cache->fs_info = root->fs_info;
8475
8476         /*
8477          * we only want to have 32k of ram per block group for keeping track
8478          * of free space, and if we pass 1/2 of that we want to start
8479          * converting things over to using bitmaps
8480          */
8481         cache->extents_thresh = ((1024 * 32) / 2) /
8482                 sizeof(struct btrfs_free_space);
8483         atomic_set(&cache->count, 1);
8484         spin_lock_init(&cache->lock);
8485         spin_lock_init(&cache->tree_lock);
8486         INIT_LIST_HEAD(&cache->list);
8487         INIT_LIST_HEAD(&cache->cluster_list);
8488
8489         btrfs_set_block_group_used(&cache->item, bytes_used);
8490         btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
8491         cache->flags = type;
8492         btrfs_set_block_group_flags(&cache->item, type);
8493
8494         cache->last_byte_to_unpin = (u64)-1;
8495         cache->cached = BTRFS_CACHE_FINISHED;
8496         exclude_super_stripes(root, cache);
8497
8498         add_new_free_space(cache, root->fs_info, chunk_offset,
8499                            chunk_offset + size);
8500
8501         free_excluded_extents(root, cache);
8502
8503         ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
8504                                 &cache->space_info);
8505         BUG_ON(ret);
8506
8507         spin_lock(&cache->space_info->lock);
8508         cache->space_info->bytes_readonly += cache->bytes_super;
8509         spin_unlock(&cache->space_info->lock);
8510
8511         __link_block_group(cache->space_info, cache);
8512
8513         ret = btrfs_add_block_group_cache(root->fs_info, cache);
8514         BUG_ON(ret);
8515
8516         ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
8517                                 sizeof(cache->item));
8518         BUG_ON(ret);
8519
8520         set_avail_alloc_bits(extent_root->fs_info, type);
8521
8522         return 0;
8523 }
8524
8525 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8526                              struct btrfs_root *root, u64 group_start)
8527 {
8528         struct btrfs_path *path;
8529         struct btrfs_block_group_cache *block_group;
8530         struct btrfs_free_cluster *cluster;
8531         struct btrfs_root *tree_root = root->fs_info->tree_root;
8532         struct btrfs_key key;
8533         struct inode *inode;
8534         int ret;
8535         int factor;
8536
8537         root = root->fs_info->extent_root;
8538
8539         block_group = btrfs_lookup_block_group(root->fs_info, group_start);
8540         BUG_ON(!block_group);
8541         BUG_ON(!block_group->ro);
8542
8543         memcpy(&key, &block_group->key, sizeof(key));
8544         if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
8545                                   BTRFS_BLOCK_GROUP_RAID1 |
8546                                   BTRFS_BLOCK_GROUP_RAID10))
8547                 factor = 2;
8548         else
8549                 factor = 1;
8550
8551         /* make sure this block group isn't part of an allocation cluster */
8552         cluster = &root->fs_info->data_alloc_cluster;
8553         spin_lock(&cluster->refill_lock);
8554         btrfs_return_cluster_to_free_space(block_group, cluster);
8555         spin_unlock(&cluster->refill_lock);
8556
8557         /*
8558          * make sure this block group isn't part of a metadata
8559          * allocation cluster
8560          */
8561         cluster = &root->fs_info->meta_alloc_cluster;
8562         spin_lock(&cluster->refill_lock);
8563         btrfs_return_cluster_to_free_space(block_group, cluster);
8564         spin_unlock(&cluster->refill_lock);
8565
8566         path = btrfs_alloc_path();
8567         BUG_ON(!path);
8568
8569         inode = lookup_free_space_inode(root, block_group, path);
8570         if (!IS_ERR(inode)) {
8571                 btrfs_orphan_add(trans, inode);
8572                 clear_nlink(inode);
8573                 /* One for the block groups ref */
8574                 spin_lock(&block_group->lock);
8575                 if (block_group->iref) {
8576                         block_group->iref = 0;
8577                         block_group->inode = NULL;
8578                         spin_unlock(&block_group->lock);
8579                         iput(inode);
8580                 } else {
8581                         spin_unlock(&block_group->lock);
8582                 }
8583                 /* One for our lookup ref */
8584                 iput(inode);
8585         }
8586
8587         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8588         key.offset = block_group->key.objectid;
8589         key.type = 0;
8590
8591         ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8592         if (ret < 0)
8593                 goto out;
8594         if (ret > 0)
8595                 btrfs_release_path(tree_root, path);
8596         if (ret == 0) {
8597                 ret = btrfs_del_item(trans, tree_root, path);
8598                 if (ret)
8599                         goto out;
8600                 btrfs_release_path(tree_root, path);
8601         }
8602
8603         spin_lock(&root->fs_info->block_group_cache_lock);
8604         rb_erase(&block_group->cache_node,
8605                  &root->fs_info->block_group_cache_tree);
8606         spin_unlock(&root->fs_info->block_group_cache_lock);
8607
8608         down_write(&block_group->space_info->groups_sem);
8609         /*
8610          * we must use list_del_init so people can check to see if they
8611          * are still on the list after taking the semaphore
8612          */
8613         list_del_init(&block_group->list);
8614         up_write(&block_group->space_info->groups_sem);
8615
8616         if (block_group->cached == BTRFS_CACHE_STARTED)
8617                 wait_block_group_cache_done(block_group);
8618
8619         btrfs_remove_free_space_cache(block_group);
8620
8621         spin_lock(&block_group->space_info->lock);
8622         block_group->space_info->total_bytes -= block_group->key.offset;
8623         block_group->space_info->bytes_readonly -= block_group->key.offset;
8624         block_group->space_info->disk_total -= block_group->key.offset * factor;
8625         spin_unlock(&block_group->space_info->lock);
8626
8627         memcpy(&key, &block_group->key, sizeof(key));
8628
8629         btrfs_clear_space_info_full(root->fs_info);
8630
8631         btrfs_put_block_group(block_group);
8632         btrfs_put_block_group(block_group);
8633
8634         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8635         if (ret > 0)
8636                 ret = -EIO;
8637         if (ret < 0)
8638                 goto out;
8639
8640         ret = btrfs_del_item(trans, root, path);
8641 out:
8642         btrfs_free_path(path);
8643         return ret;
8644 }