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