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