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