]> Pileus Git - ~andy/linux/blob - fs/btrfs/extent-tree.c
Btrfs: fix possible softlockup in the allocator
[~andy/linux] / 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 }
1577 #endif
1578
1579 static int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
1580                                 u64 num_bytes)
1581 {
1582 #ifdef BIO_RW_DISCARD
1583         int ret;
1584         u64 map_length = num_bytes;
1585         struct btrfs_multi_bio *multi = NULL;
1586
1587         /* Tell the block device(s) that the sectors can be discarded */
1588         ret = btrfs_map_block(&root->fs_info->mapping_tree, READ,
1589                               bytenr, &map_length, &multi, 0);
1590         if (!ret) {
1591                 struct btrfs_bio_stripe *stripe = multi->stripes;
1592                 int i;
1593
1594                 if (map_length > num_bytes)
1595                         map_length = num_bytes;
1596
1597                 for (i = 0; i < multi->num_stripes; i++, stripe++) {
1598                         btrfs_issue_discard(stripe->dev->bdev,
1599                                             stripe->physical,
1600                                             map_length);
1601                 }
1602                 kfree(multi);
1603         }
1604
1605         return ret;
1606 #else
1607         return 0;
1608 #endif
1609 }
1610
1611 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1612                          struct btrfs_root *root,
1613                          u64 bytenr, u64 num_bytes, u64 parent,
1614                          u64 root_objectid, u64 owner, u64 offset)
1615 {
1616         int ret;
1617         BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
1618                root_objectid == BTRFS_TREE_LOG_OBJECTID);
1619
1620         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1621                 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
1622                                         parent, root_objectid, (int)owner,
1623                                         BTRFS_ADD_DELAYED_REF, NULL);
1624         } else {
1625                 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
1626                                         parent, root_objectid, owner, offset,
1627                                         BTRFS_ADD_DELAYED_REF, NULL);
1628         }
1629         return ret;
1630 }
1631
1632 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
1633                                   struct btrfs_root *root,
1634                                   u64 bytenr, u64 num_bytes,
1635                                   u64 parent, u64 root_objectid,
1636                                   u64 owner, u64 offset, int refs_to_add,
1637                                   struct btrfs_delayed_extent_op *extent_op)
1638 {
1639         struct btrfs_path *path;
1640         struct extent_buffer *leaf;
1641         struct btrfs_extent_item *item;
1642         u64 refs;
1643         int ret;
1644         int err = 0;
1645
1646         path = btrfs_alloc_path();
1647         if (!path)
1648                 return -ENOMEM;
1649
1650         path->reada = 1;
1651         path->leave_spinning = 1;
1652         /* this will setup the path even if it fails to insert the back ref */
1653         ret = insert_inline_extent_backref(trans, root->fs_info->extent_root,
1654                                            path, bytenr, num_bytes, parent,
1655                                            root_objectid, owner, offset,
1656                                            refs_to_add, extent_op);
1657         if (ret == 0)
1658                 goto out;
1659
1660         if (ret != -EAGAIN) {
1661                 err = ret;
1662                 goto out;
1663         }
1664
1665         leaf = path->nodes[0];
1666         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1667         refs = btrfs_extent_refs(leaf, item);
1668         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
1669         if (extent_op)
1670                 __run_delayed_extent_op(extent_op, leaf, item);
1671
1672         btrfs_mark_buffer_dirty(leaf);
1673         btrfs_release_path(root->fs_info->extent_root, path);
1674
1675         path->reada = 1;
1676         path->leave_spinning = 1;
1677
1678         /* now insert the actual backref */
1679         ret = insert_extent_backref(trans, root->fs_info->extent_root,
1680                                     path, bytenr, parent, root_objectid,
1681                                     owner, offset, refs_to_add);
1682         BUG_ON(ret);
1683 out:
1684         btrfs_free_path(path);
1685         return err;
1686 }
1687
1688 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
1689                                 struct btrfs_root *root,
1690                                 struct btrfs_delayed_ref_node *node,
1691                                 struct btrfs_delayed_extent_op *extent_op,
1692                                 int insert_reserved)
1693 {
1694         int ret = 0;
1695         struct btrfs_delayed_data_ref *ref;
1696         struct btrfs_key ins;
1697         u64 parent = 0;
1698         u64 ref_root = 0;
1699         u64 flags = 0;
1700
1701         ins.objectid = node->bytenr;
1702         ins.offset = node->num_bytes;
1703         ins.type = BTRFS_EXTENT_ITEM_KEY;
1704
1705         ref = btrfs_delayed_node_to_data_ref(node);
1706         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
1707                 parent = ref->parent;
1708         else
1709                 ref_root = ref->root;
1710
1711         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1712                 if (extent_op) {
1713                         BUG_ON(extent_op->update_key);
1714                         flags |= extent_op->flags_to_set;
1715                 }
1716                 ret = alloc_reserved_file_extent(trans, root,
1717                                                  parent, ref_root, flags,
1718                                                  ref->objectid, ref->offset,
1719                                                  &ins, node->ref_mod);
1720         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1721                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1722                                              node->num_bytes, parent,
1723                                              ref_root, ref->objectid,
1724                                              ref->offset, node->ref_mod,
1725                                              extent_op);
1726         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1727                 ret = __btrfs_free_extent(trans, root, node->bytenr,
1728                                           node->num_bytes, parent,
1729                                           ref_root, ref->objectid,
1730                                           ref->offset, node->ref_mod,
1731                                           extent_op);
1732         } else {
1733                 BUG();
1734         }
1735         return ret;
1736 }
1737
1738 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
1739                                     struct extent_buffer *leaf,
1740                                     struct btrfs_extent_item *ei)
1741 {
1742         u64 flags = btrfs_extent_flags(leaf, ei);
1743         if (extent_op->update_flags) {
1744                 flags |= extent_op->flags_to_set;
1745                 btrfs_set_extent_flags(leaf, ei, flags);
1746         }
1747
1748         if (extent_op->update_key) {
1749                 struct btrfs_tree_block_info *bi;
1750                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
1751                 bi = (struct btrfs_tree_block_info *)(ei + 1);
1752                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
1753         }
1754 }
1755
1756 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
1757                                  struct btrfs_root *root,
1758                                  struct btrfs_delayed_ref_node *node,
1759                                  struct btrfs_delayed_extent_op *extent_op)
1760 {
1761         struct btrfs_key key;
1762         struct btrfs_path *path;
1763         struct btrfs_extent_item *ei;
1764         struct extent_buffer *leaf;
1765         u32 item_size;
1766         int ret;
1767         int err = 0;
1768
1769         path = btrfs_alloc_path();
1770         if (!path)
1771                 return -ENOMEM;
1772
1773         key.objectid = node->bytenr;
1774         key.type = BTRFS_EXTENT_ITEM_KEY;
1775         key.offset = node->num_bytes;
1776
1777         path->reada = 1;
1778         path->leave_spinning = 1;
1779         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
1780                                 path, 0, 1);
1781         if (ret < 0) {
1782                 err = ret;
1783                 goto out;
1784         }
1785         if (ret > 0) {
1786                 err = -EIO;
1787                 goto out;
1788         }
1789
1790         leaf = path->nodes[0];
1791         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1792 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1793         if (item_size < sizeof(*ei)) {
1794                 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
1795                                              path, (u64)-1, 0);
1796                 if (ret < 0) {
1797                         err = ret;
1798                         goto out;
1799                 }
1800                 leaf = path->nodes[0];
1801                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1802         }
1803 #endif
1804         BUG_ON(item_size < sizeof(*ei));
1805         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1806         __run_delayed_extent_op(extent_op, leaf, ei);
1807
1808         btrfs_mark_buffer_dirty(leaf);
1809 out:
1810         btrfs_free_path(path);
1811         return err;
1812 }
1813
1814 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
1815                                 struct btrfs_root *root,
1816                                 struct btrfs_delayed_ref_node *node,
1817                                 struct btrfs_delayed_extent_op *extent_op,
1818                                 int insert_reserved)
1819 {
1820         int ret = 0;
1821         struct btrfs_delayed_tree_ref *ref;
1822         struct btrfs_key ins;
1823         u64 parent = 0;
1824         u64 ref_root = 0;
1825
1826         ins.objectid = node->bytenr;
1827         ins.offset = node->num_bytes;
1828         ins.type = BTRFS_EXTENT_ITEM_KEY;
1829
1830         ref = btrfs_delayed_node_to_tree_ref(node);
1831         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1832                 parent = ref->parent;
1833         else
1834                 ref_root = ref->root;
1835
1836         BUG_ON(node->ref_mod != 1);
1837         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
1838                 BUG_ON(!extent_op || !extent_op->update_flags ||
1839                        !extent_op->update_key);
1840                 ret = alloc_reserved_tree_block(trans, root,
1841                                                 parent, ref_root,
1842                                                 extent_op->flags_to_set,
1843                                                 &extent_op->key,
1844                                                 ref->level, &ins);
1845         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
1846                 ret = __btrfs_inc_extent_ref(trans, root, node->bytenr,
1847                                              node->num_bytes, parent, ref_root,
1848                                              ref->level, 0, 1, extent_op);
1849         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
1850                 ret = __btrfs_free_extent(trans, root, node->bytenr,
1851                                           node->num_bytes, parent, ref_root,
1852                                           ref->level, 0, 1, extent_op);
1853         } else {
1854                 BUG();
1855         }
1856         return ret;
1857 }
1858
1859
1860 /* helper function to actually process a single delayed ref entry */
1861 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
1862                                struct btrfs_root *root,
1863                                struct btrfs_delayed_ref_node *node,
1864                                struct btrfs_delayed_extent_op *extent_op,
1865                                int insert_reserved)
1866 {
1867         int ret;
1868         if (btrfs_delayed_ref_is_head(node)) {
1869                 struct btrfs_delayed_ref_head *head;
1870                 /*
1871                  * we've hit the end of the chain and we were supposed
1872                  * to insert this extent into the tree.  But, it got
1873                  * deleted before we ever needed to insert it, so all
1874                  * we have to do is clean up the accounting
1875                  */
1876                 BUG_ON(extent_op);
1877                 head = btrfs_delayed_node_to_head(node);
1878                 if (insert_reserved) {
1879                         int mark_free = 0;
1880                         struct extent_buffer *must_clean = NULL;
1881
1882                         ret = pin_down_bytes(trans, root, NULL,
1883                                              node->bytenr, node->num_bytes,
1884                                              head->is_data, 1, &must_clean);
1885                         if (ret > 0)
1886                                 mark_free = 1;
1887
1888                         if (must_clean) {
1889                                 clean_tree_block(NULL, root, must_clean);
1890                                 btrfs_tree_unlock(must_clean);
1891                                 free_extent_buffer(must_clean);
1892                         }
1893                         if (head->is_data) {
1894                                 ret = btrfs_del_csums(trans, root,
1895                                                       node->bytenr,
1896                                                       node->num_bytes);
1897                                 BUG_ON(ret);
1898                         }
1899                         if (mark_free) {
1900                                 ret = btrfs_free_reserved_extent(root,
1901                                                         node->bytenr,
1902                                                         node->num_bytes);
1903                                 BUG_ON(ret);
1904                         }
1905                 }
1906                 mutex_unlock(&head->mutex);
1907                 return 0;
1908         }
1909
1910         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
1911             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
1912                 ret = run_delayed_tree_ref(trans, root, node, extent_op,
1913                                            insert_reserved);
1914         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
1915                  node->type == BTRFS_SHARED_DATA_REF_KEY)
1916                 ret = run_delayed_data_ref(trans, root, node, extent_op,
1917                                            insert_reserved);
1918         else
1919                 BUG();
1920         return ret;
1921 }
1922
1923 static noinline struct btrfs_delayed_ref_node *
1924 select_delayed_ref(struct btrfs_delayed_ref_head *head)
1925 {
1926         struct rb_node *node;
1927         struct btrfs_delayed_ref_node *ref;
1928         int action = BTRFS_ADD_DELAYED_REF;
1929 again:
1930         /*
1931          * select delayed ref of type BTRFS_ADD_DELAYED_REF first.
1932          * this prevents ref count from going down to zero when
1933          * there still are pending delayed ref.
1934          */
1935         node = rb_prev(&head->node.rb_node);
1936         while (1) {
1937                 if (!node)
1938                         break;
1939                 ref = rb_entry(node, struct btrfs_delayed_ref_node,
1940                                 rb_node);
1941                 if (ref->bytenr != head->node.bytenr)
1942                         break;
1943                 if (ref->action == action)
1944                         return ref;
1945                 node = rb_prev(node);
1946         }
1947         if (action == BTRFS_ADD_DELAYED_REF) {
1948                 action = BTRFS_DROP_DELAYED_REF;
1949                 goto again;
1950         }
1951         return NULL;
1952 }
1953
1954 static noinline int run_clustered_refs(struct btrfs_trans_handle *trans,
1955                                        struct btrfs_root *root,
1956                                        struct list_head *cluster)
1957 {
1958         struct btrfs_delayed_ref_root *delayed_refs;
1959         struct btrfs_delayed_ref_node *ref;
1960         struct btrfs_delayed_ref_head *locked_ref = NULL;
1961         struct btrfs_delayed_extent_op *extent_op;
1962         int ret;
1963         int count = 0;
1964         int must_insert_reserved = 0;
1965
1966         delayed_refs = &trans->transaction->delayed_refs;
1967         while (1) {
1968                 if (!locked_ref) {
1969                         /* pick a new head ref from the cluster list */
1970                         if (list_empty(cluster))
1971                                 break;
1972
1973                         locked_ref = list_entry(cluster->next,
1974                                      struct btrfs_delayed_ref_head, cluster);
1975
1976                         /* grab the lock that says we are going to process
1977                          * all the refs for this head */
1978                         ret = btrfs_delayed_ref_lock(trans, locked_ref);
1979
1980                         /*
1981                          * we may have dropped the spin lock to get the head
1982                          * mutex lock, and that might have given someone else
1983                          * time to free the head.  If that's true, it has been
1984                          * removed from our list and we can move on.
1985                          */
1986                         if (ret == -EAGAIN) {
1987                                 locked_ref = NULL;
1988                                 count++;
1989                                 continue;
1990                         }
1991                 }
1992
1993                 /*
1994                  * record the must insert reserved flag before we
1995                  * drop the spin lock.
1996                  */
1997                 must_insert_reserved = locked_ref->must_insert_reserved;
1998                 locked_ref->must_insert_reserved = 0;
1999
2000                 extent_op = locked_ref->extent_op;
2001                 locked_ref->extent_op = NULL;
2002
2003                 /*
2004                  * locked_ref is the head node, so we have to go one
2005                  * node back for any delayed ref updates
2006                  */
2007                 ref = select_delayed_ref(locked_ref);
2008                 if (!ref) {
2009                         /* All delayed refs have been processed, Go ahead
2010                          * and send the head node to run_one_delayed_ref,
2011                          * so that any accounting fixes can happen
2012                          */
2013                         ref = &locked_ref->node;
2014
2015                         if (extent_op && must_insert_reserved) {
2016                                 kfree(extent_op);
2017                                 extent_op = NULL;
2018                         }
2019
2020                         if (extent_op) {
2021                                 spin_unlock(&delayed_refs->lock);
2022
2023                                 ret = run_delayed_extent_op(trans, root,
2024                                                             ref, extent_op);
2025                                 BUG_ON(ret);
2026                                 kfree(extent_op);
2027
2028                                 cond_resched();
2029                                 spin_lock(&delayed_refs->lock);
2030                                 continue;
2031                         }
2032
2033                         list_del_init(&locked_ref->cluster);
2034                         locked_ref = NULL;
2035                 }
2036
2037                 ref->in_tree = 0;
2038                 rb_erase(&ref->rb_node, &delayed_refs->root);
2039                 delayed_refs->num_entries--;
2040
2041                 spin_unlock(&delayed_refs->lock);
2042
2043                 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2044                                           must_insert_reserved);
2045                 BUG_ON(ret);
2046
2047                 btrfs_put_delayed_ref(ref);
2048                 kfree(extent_op);
2049                 count++;
2050
2051                 cond_resched();
2052                 spin_lock(&delayed_refs->lock);
2053         }
2054         return count;
2055 }
2056
2057 /*
2058  * this starts processing the delayed reference count updates and
2059  * extent insertions we have queued up so far.  count can be
2060  * 0, which means to process everything in the tree at the start
2061  * of the run (but not newly added entries), or it can be some target
2062  * number you'd like to process.
2063  */
2064 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2065                            struct btrfs_root *root, unsigned long count)
2066 {
2067         struct rb_node *node;
2068         struct btrfs_delayed_ref_root *delayed_refs;
2069         struct btrfs_delayed_ref_node *ref;
2070         struct list_head cluster;
2071         int ret;
2072         int run_all = count == (unsigned long)-1;
2073         int run_most = 0;
2074
2075         if (root == root->fs_info->extent_root)
2076                 root = root->fs_info->tree_root;
2077
2078         delayed_refs = &trans->transaction->delayed_refs;
2079         INIT_LIST_HEAD(&cluster);
2080 again:
2081         spin_lock(&delayed_refs->lock);
2082         if (count == 0) {
2083                 count = delayed_refs->num_entries * 2;
2084                 run_most = 1;
2085         }
2086         while (1) {
2087                 if (!(run_all || run_most) &&
2088                     delayed_refs->num_heads_ready < 64)
2089                         break;
2090
2091                 /*
2092                  * go find something we can process in the rbtree.  We start at
2093                  * the beginning of the tree, and then build a cluster
2094                  * of refs to process starting at the first one we are able to
2095                  * lock
2096                  */
2097                 ret = btrfs_find_ref_cluster(trans, &cluster,
2098                                              delayed_refs->run_delayed_start);
2099                 if (ret)
2100                         break;
2101
2102                 ret = run_clustered_refs(trans, root, &cluster);
2103                 BUG_ON(ret < 0);
2104
2105                 count -= min_t(unsigned long, ret, count);
2106
2107                 if (count == 0)
2108                         break;
2109         }
2110
2111         if (run_all) {
2112                 node = rb_first(&delayed_refs->root);
2113                 if (!node)
2114                         goto out;
2115                 count = (unsigned long)-1;
2116
2117                 while (node) {
2118                         ref = rb_entry(node, struct btrfs_delayed_ref_node,
2119                                        rb_node);
2120                         if (btrfs_delayed_ref_is_head(ref)) {
2121                                 struct btrfs_delayed_ref_head *head;
2122
2123                                 head = btrfs_delayed_node_to_head(ref);
2124                                 atomic_inc(&ref->refs);
2125
2126                                 spin_unlock(&delayed_refs->lock);
2127                                 mutex_lock(&head->mutex);
2128                                 mutex_unlock(&head->mutex);
2129
2130                                 btrfs_put_delayed_ref(ref);
2131                                 cond_resched();
2132                                 goto again;
2133                         }
2134                         node = rb_next(node);
2135                 }
2136                 spin_unlock(&delayed_refs->lock);
2137                 schedule_timeout(1);
2138                 goto again;
2139         }
2140 out:
2141         spin_unlock(&delayed_refs->lock);
2142         return 0;
2143 }
2144
2145 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2146                                 struct btrfs_root *root,
2147                                 u64 bytenr, u64 num_bytes, u64 flags,
2148                                 int is_data)
2149 {
2150         struct btrfs_delayed_extent_op *extent_op;
2151         int ret;
2152
2153         extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2154         if (!extent_op)
2155                 return -ENOMEM;
2156
2157         extent_op->flags_to_set = flags;
2158         extent_op->update_flags = 1;
2159         extent_op->update_key = 0;
2160         extent_op->is_data = is_data ? 1 : 0;
2161
2162         ret = btrfs_add_delayed_extent_op(trans, bytenr, num_bytes, extent_op);
2163         if (ret)
2164                 kfree(extent_op);
2165         return ret;
2166 }
2167
2168 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2169                                       struct btrfs_root *root,
2170                                       struct btrfs_path *path,
2171                                       u64 objectid, u64 offset, u64 bytenr)
2172 {
2173         struct btrfs_delayed_ref_head *head;
2174         struct btrfs_delayed_ref_node *ref;
2175         struct btrfs_delayed_data_ref *data_ref;
2176         struct btrfs_delayed_ref_root *delayed_refs;
2177         struct rb_node *node;
2178         int ret = 0;
2179
2180         ret = -ENOENT;
2181         delayed_refs = &trans->transaction->delayed_refs;
2182         spin_lock(&delayed_refs->lock);
2183         head = btrfs_find_delayed_ref_head(trans, bytenr);
2184         if (!head)
2185                 goto out;
2186
2187         if (!mutex_trylock(&head->mutex)) {
2188                 atomic_inc(&head->node.refs);
2189                 spin_unlock(&delayed_refs->lock);
2190
2191                 btrfs_release_path(root->fs_info->extent_root, path);
2192
2193                 mutex_lock(&head->mutex);
2194                 mutex_unlock(&head->mutex);
2195                 btrfs_put_delayed_ref(&head->node);
2196                 return -EAGAIN;
2197         }
2198
2199         node = rb_prev(&head->node.rb_node);
2200         if (!node)
2201                 goto out_unlock;
2202
2203         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2204
2205         if (ref->bytenr != bytenr)
2206                 goto out_unlock;
2207
2208         ret = 1;
2209         if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2210                 goto out_unlock;
2211
2212         data_ref = btrfs_delayed_node_to_data_ref(ref);
2213
2214         node = rb_prev(node);
2215         if (node) {
2216                 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2217                 if (ref->bytenr == bytenr)
2218                         goto out_unlock;
2219         }
2220
2221         if (data_ref->root != root->root_key.objectid ||
2222             data_ref->objectid != objectid || data_ref->offset != offset)
2223                 goto out_unlock;
2224
2225         ret = 0;
2226 out_unlock:
2227         mutex_unlock(&head->mutex);
2228 out:
2229         spin_unlock(&delayed_refs->lock);
2230         return ret;
2231 }
2232
2233 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2234                                         struct btrfs_root *root,
2235                                         struct btrfs_path *path,
2236                                         u64 objectid, u64 offset, u64 bytenr)
2237 {
2238         struct btrfs_root *extent_root = root->fs_info->extent_root;
2239         struct extent_buffer *leaf;
2240         struct btrfs_extent_data_ref *ref;
2241         struct btrfs_extent_inline_ref *iref;
2242         struct btrfs_extent_item *ei;
2243         struct btrfs_key key;
2244         u32 item_size;
2245         int ret;
2246
2247         key.objectid = bytenr;
2248         key.offset = (u64)-1;
2249         key.type = BTRFS_EXTENT_ITEM_KEY;
2250
2251         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2252         if (ret < 0)
2253                 goto out;
2254         BUG_ON(ret == 0);
2255
2256         ret = -ENOENT;
2257         if (path->slots[0] == 0)
2258                 goto out;
2259
2260         path->slots[0]--;
2261         leaf = path->nodes[0];
2262         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2263
2264         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2265                 goto out;
2266
2267         ret = 1;
2268         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2269 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2270         if (item_size < sizeof(*ei)) {
2271                 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2272                 goto out;
2273         }
2274 #endif
2275         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2276
2277         if (item_size != sizeof(*ei) +
2278             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2279                 goto out;
2280
2281         if (btrfs_extent_generation(leaf, ei) <=
2282             btrfs_root_last_snapshot(&root->root_item))
2283                 goto out;
2284
2285         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2286         if (btrfs_extent_inline_ref_type(leaf, iref) !=
2287             BTRFS_EXTENT_DATA_REF_KEY)
2288                 goto out;
2289
2290         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2291         if (btrfs_extent_refs(leaf, ei) !=
2292             btrfs_extent_data_ref_count(leaf, ref) ||
2293             btrfs_extent_data_ref_root(leaf, ref) !=
2294             root->root_key.objectid ||
2295             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2296             btrfs_extent_data_ref_offset(leaf, ref) != offset)
2297                 goto out;
2298
2299         ret = 0;
2300 out:
2301         return ret;
2302 }
2303
2304 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2305                           struct btrfs_root *root,
2306                           u64 objectid, u64 offset, u64 bytenr)
2307 {
2308         struct btrfs_path *path;
2309         int ret;
2310         int ret2;
2311
2312         path = btrfs_alloc_path();
2313         if (!path)
2314                 return -ENOENT;
2315
2316         do {
2317                 ret = check_committed_ref(trans, root, path, objectid,
2318                                           offset, bytenr);
2319                 if (ret && ret != -ENOENT)
2320                         goto out;
2321
2322                 ret2 = check_delayed_ref(trans, root, path, objectid,
2323                                          offset, bytenr);
2324         } while (ret2 == -EAGAIN);
2325
2326         if (ret2 && ret2 != -ENOENT) {
2327                 ret = ret2;
2328                 goto out;
2329         }
2330
2331         if (ret != -ENOENT || ret2 != -ENOENT)
2332                 ret = 0;
2333 out:
2334         btrfs_free_path(path);
2335         return ret;
2336 }
2337
2338 #if 0
2339 int btrfs_cache_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2340                     struct extent_buffer *buf, u32 nr_extents)
2341 {
2342         struct btrfs_key key;
2343         struct btrfs_file_extent_item *fi;
2344         u64 root_gen;
2345         u32 nritems;
2346         int i;
2347         int level;
2348         int ret = 0;
2349         int shared = 0;
2350
2351         if (!root->ref_cows)
2352                 return 0;
2353
2354         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
2355                 shared = 0;
2356                 root_gen = root->root_key.offset;
2357         } else {
2358                 shared = 1;
2359                 root_gen = trans->transid - 1;
2360         }
2361
2362         level = btrfs_header_level(buf);
2363         nritems = btrfs_header_nritems(buf);
2364
2365         if (level == 0) {
2366                 struct btrfs_leaf_ref *ref;
2367                 struct btrfs_extent_info *info;
2368
2369                 ref = btrfs_alloc_leaf_ref(root, nr_extents);
2370                 if (!ref) {
2371                         ret = -ENOMEM;
2372                         goto out;
2373                 }
2374
2375                 ref->root_gen = root_gen;
2376                 ref->bytenr = buf->start;
2377                 ref->owner = btrfs_header_owner(buf);
2378                 ref->generation = btrfs_header_generation(buf);
2379                 ref->nritems = nr_extents;
2380                 info = ref->extents;
2381
2382                 for (i = 0; nr_extents > 0 && i < nritems; i++) {
2383                         u64 disk_bytenr;
2384                         btrfs_item_key_to_cpu(buf, &key, i);
2385                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2386                                 continue;
2387                         fi = btrfs_item_ptr(buf, i,
2388                                             struct btrfs_file_extent_item);
2389                         if (btrfs_file_extent_type(buf, fi) ==
2390                             BTRFS_FILE_EXTENT_INLINE)
2391                                 continue;
2392                         disk_bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2393                         if (disk_bytenr == 0)
2394                                 continue;
2395
2396                         info->bytenr = disk_bytenr;
2397                         info->num_bytes =
2398                                 btrfs_file_extent_disk_num_bytes(buf, fi);
2399                         info->objectid = key.objectid;
2400                         info->offset = key.offset;
2401                         info++;
2402                 }
2403
2404                 ret = btrfs_add_leaf_ref(root, ref, shared);
2405                 if (ret == -EEXIST && shared) {
2406                         struct btrfs_leaf_ref *old;
2407                         old = btrfs_lookup_leaf_ref(root, ref->bytenr);
2408                         BUG_ON(!old);
2409                         btrfs_remove_leaf_ref(root, old);
2410                         btrfs_free_leaf_ref(root, old);
2411                         ret = btrfs_add_leaf_ref(root, ref, shared);
2412                 }
2413                 WARN_ON(ret);
2414                 btrfs_free_leaf_ref(root, ref);
2415         }
2416 out:
2417         return ret;
2418 }
2419
2420 /* when a block goes through cow, we update the reference counts of
2421  * everything that block points to.  The internal pointers of the block
2422  * can be in just about any order, and it is likely to have clusters of
2423  * things that are close together and clusters of things that are not.
2424  *
2425  * To help reduce the seeks that come with updating all of these reference
2426  * counts, sort them by byte number before actual updates are done.
2427  *
2428  * struct refsort is used to match byte number to slot in the btree block.
2429  * we sort based on the byte number and then use the slot to actually
2430  * find the item.
2431  *
2432  * struct refsort is smaller than strcut btrfs_item and smaller than
2433  * struct btrfs_key_ptr.  Since we're currently limited to the page size
2434  * for a btree block, there's no way for a kmalloc of refsorts for a
2435  * single node to be bigger than a page.
2436  */
2437 struct refsort {
2438         u64 bytenr;
2439         u32 slot;
2440 };
2441
2442 /*
2443  * for passing into sort()
2444  */
2445 static int refsort_cmp(const void *a_void, const void *b_void)
2446 {
2447         const struct refsort *a = a_void;
2448         const struct refsort *b = b_void;
2449
2450         if (a->bytenr < b->bytenr)
2451                 return -1;
2452         if (a->bytenr > b->bytenr)
2453                 return 1;
2454         return 0;
2455 }
2456 #endif
2457
2458 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2459                            struct btrfs_root *root,
2460                            struct extent_buffer *buf,
2461                            int full_backref, int inc)
2462 {
2463         u64 bytenr;
2464         u64 num_bytes;
2465         u64 parent;
2466         u64 ref_root;
2467         u32 nritems;
2468         struct btrfs_key key;
2469         struct btrfs_file_extent_item *fi;
2470         int i;
2471         int level;
2472         int ret = 0;
2473         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2474                             u64, u64, u64, u64, u64, u64);
2475
2476         ref_root = btrfs_header_owner(buf);
2477         nritems = btrfs_header_nritems(buf);
2478         level = btrfs_header_level(buf);
2479
2480         if (!root->ref_cows && level == 0)
2481                 return 0;
2482
2483         if (inc)
2484                 process_func = btrfs_inc_extent_ref;
2485         else
2486                 process_func = btrfs_free_extent;
2487
2488         if (full_backref)
2489                 parent = buf->start;
2490         else
2491                 parent = 0;
2492
2493         for (i = 0; i < nritems; i++) {
2494                 if (level == 0) {
2495                         btrfs_item_key_to_cpu(buf, &key, i);
2496                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2497                                 continue;
2498                         fi = btrfs_item_ptr(buf, i,
2499                                             struct btrfs_file_extent_item);
2500                         if (btrfs_file_extent_type(buf, fi) ==
2501                             BTRFS_FILE_EXTENT_INLINE)
2502                                 continue;
2503                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2504                         if (bytenr == 0)
2505                                 continue;
2506
2507                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2508                         key.offset -= btrfs_file_extent_offset(buf, fi);
2509                         ret = process_func(trans, root, bytenr, num_bytes,
2510                                            parent, ref_root, key.objectid,
2511                                            key.offset);
2512                         if (ret)
2513                                 goto fail;
2514                 } else {
2515                         bytenr = btrfs_node_blockptr(buf, i);
2516                         num_bytes = btrfs_level_size(root, level - 1);
2517                         ret = process_func(trans, root, bytenr, num_bytes,
2518                                            parent, ref_root, level - 1, 0);
2519                         if (ret)
2520                                 goto fail;
2521                 }
2522         }
2523         return 0;
2524 fail:
2525         BUG();
2526         return ret;
2527 }
2528
2529 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2530                   struct extent_buffer *buf, int full_backref)
2531 {
2532         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
2533 }
2534
2535 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2536                   struct extent_buffer *buf, int full_backref)
2537 {
2538         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
2539 }
2540
2541 static int write_one_cache_group(struct btrfs_trans_handle *trans,
2542                                  struct btrfs_root *root,
2543                                  struct btrfs_path *path,
2544                                  struct btrfs_block_group_cache *cache)
2545 {
2546         int ret;
2547         struct btrfs_root *extent_root = root->fs_info->extent_root;
2548         unsigned long bi;
2549         struct extent_buffer *leaf;
2550
2551         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
2552         if (ret < 0)
2553                 goto fail;
2554         BUG_ON(ret);
2555
2556         leaf = path->nodes[0];
2557         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2558         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2559         btrfs_mark_buffer_dirty(leaf);
2560         btrfs_release_path(extent_root, path);
2561 fail:
2562         if (ret)
2563                 return ret;
2564         return 0;
2565
2566 }
2567
2568 static struct btrfs_block_group_cache *
2569 next_block_group(struct btrfs_root *root,
2570                  struct btrfs_block_group_cache *cache)
2571 {
2572         struct rb_node *node;
2573         spin_lock(&root->fs_info->block_group_cache_lock);
2574         node = rb_next(&cache->cache_node);
2575         btrfs_put_block_group(cache);
2576         if (node) {
2577                 cache = rb_entry(node, struct btrfs_block_group_cache,
2578                                  cache_node);
2579                 atomic_inc(&cache->count);
2580         } else
2581                 cache = NULL;
2582         spin_unlock(&root->fs_info->block_group_cache_lock);
2583         return cache;
2584 }
2585
2586 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
2587                                    struct btrfs_root *root)
2588 {
2589         struct btrfs_block_group_cache *cache;
2590         int err = 0;
2591         struct btrfs_path *path;
2592         u64 last = 0;
2593
2594         path = btrfs_alloc_path();
2595         if (!path)
2596                 return -ENOMEM;
2597
2598         while (1) {
2599                 if (last == 0) {
2600                         err = btrfs_run_delayed_refs(trans, root,
2601                                                      (unsigned long)-1);
2602                         BUG_ON(err);
2603                 }
2604
2605                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
2606                 while (cache) {
2607                         if (cache->dirty)
2608                                 break;
2609                         cache = next_block_group(root, cache);
2610                 }
2611                 if (!cache) {
2612                         if (last == 0)
2613                                 break;
2614                         last = 0;
2615                         continue;
2616                 }
2617
2618                 cache->dirty = 0;
2619                 last = cache->key.objectid + cache->key.offset;
2620
2621                 err = write_one_cache_group(trans, root, path, cache);
2622                 BUG_ON(err);
2623                 btrfs_put_block_group(cache);
2624         }
2625
2626         btrfs_free_path(path);
2627         return 0;
2628 }
2629
2630 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
2631 {
2632         struct btrfs_block_group_cache *block_group;
2633         int readonly = 0;
2634
2635         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
2636         if (!block_group || block_group->ro)
2637                 readonly = 1;
2638         if (block_group)
2639                 btrfs_put_block_group(block_group);
2640         return readonly;
2641 }
2642
2643 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
2644                              u64 total_bytes, u64 bytes_used,
2645                              struct btrfs_space_info **space_info)
2646 {
2647         struct btrfs_space_info *found;
2648
2649         found = __find_space_info(info, flags);
2650         if (found) {
2651                 spin_lock(&found->lock);
2652                 found->total_bytes += total_bytes;
2653                 found->bytes_used += bytes_used;
2654                 found->full = 0;
2655                 spin_unlock(&found->lock);
2656                 *space_info = found;
2657                 return 0;
2658         }
2659         found = kzalloc(sizeof(*found), GFP_NOFS);
2660         if (!found)
2661                 return -ENOMEM;
2662
2663         INIT_LIST_HEAD(&found->block_groups);
2664         init_rwsem(&found->groups_sem);
2665         spin_lock_init(&found->lock);
2666         found->flags = flags;
2667         found->total_bytes = total_bytes;
2668         found->bytes_used = bytes_used;
2669         found->bytes_pinned = 0;
2670         found->bytes_reserved = 0;
2671         found->bytes_readonly = 0;
2672         found->bytes_delalloc = 0;
2673         found->full = 0;
2674         found->force_alloc = 0;
2675         *space_info = found;
2676         list_add_rcu(&found->list, &info->space_info);
2677         atomic_set(&found->caching_threads, 0);
2678         return 0;
2679 }
2680
2681 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
2682 {
2683         u64 extra_flags = flags & (BTRFS_BLOCK_GROUP_RAID0 |
2684                                    BTRFS_BLOCK_GROUP_RAID1 |
2685                                    BTRFS_BLOCK_GROUP_RAID10 |
2686                                    BTRFS_BLOCK_GROUP_DUP);
2687         if (extra_flags) {
2688                 if (flags & BTRFS_BLOCK_GROUP_DATA)
2689                         fs_info->avail_data_alloc_bits |= extra_flags;
2690                 if (flags & BTRFS_BLOCK_GROUP_METADATA)
2691                         fs_info->avail_metadata_alloc_bits |= extra_flags;
2692                 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
2693                         fs_info->avail_system_alloc_bits |= extra_flags;
2694         }
2695 }
2696
2697 static void set_block_group_readonly(struct btrfs_block_group_cache *cache)
2698 {
2699         spin_lock(&cache->space_info->lock);
2700         spin_lock(&cache->lock);
2701         if (!cache->ro) {
2702                 cache->space_info->bytes_readonly += cache->key.offset -
2703                                         btrfs_block_group_used(&cache->item);
2704                 cache->ro = 1;
2705         }
2706         spin_unlock(&cache->lock);
2707         spin_unlock(&cache->space_info->lock);
2708 }
2709
2710 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
2711 {
2712         u64 num_devices = root->fs_info->fs_devices->rw_devices;
2713
2714         if (num_devices == 1)
2715                 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
2716         if (num_devices < 4)
2717                 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
2718
2719         if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
2720             (flags & (BTRFS_BLOCK_GROUP_RAID1 |
2721                       BTRFS_BLOCK_GROUP_RAID10))) {
2722                 flags &= ~BTRFS_BLOCK_GROUP_DUP;
2723         }
2724
2725         if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
2726             (flags & BTRFS_BLOCK_GROUP_RAID10)) {
2727                 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
2728         }
2729
2730         if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
2731             ((flags & BTRFS_BLOCK_GROUP_RAID1) |
2732              (flags & BTRFS_BLOCK_GROUP_RAID10) |
2733              (flags & BTRFS_BLOCK_GROUP_DUP)))
2734                 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
2735         return flags;
2736 }
2737
2738 static u64 btrfs_get_alloc_profile(struct btrfs_root *root, u64 data)
2739 {
2740         struct btrfs_fs_info *info = root->fs_info;
2741         u64 alloc_profile;
2742
2743         if (data) {
2744                 alloc_profile = info->avail_data_alloc_bits &
2745                         info->data_alloc_profile;
2746                 data = BTRFS_BLOCK_GROUP_DATA | alloc_profile;
2747         } else if (root == root->fs_info->chunk_root) {
2748                 alloc_profile = info->avail_system_alloc_bits &
2749                         info->system_alloc_profile;
2750                 data = BTRFS_BLOCK_GROUP_SYSTEM | alloc_profile;
2751         } else {
2752                 alloc_profile = info->avail_metadata_alloc_bits &
2753                         info->metadata_alloc_profile;
2754                 data = BTRFS_BLOCK_GROUP_METADATA | alloc_profile;
2755         }
2756
2757         return btrfs_reduce_alloc_profile(root, data);
2758 }
2759
2760 void btrfs_set_inode_space_info(struct btrfs_root *root, struct inode *inode)
2761 {
2762         u64 alloc_target;
2763
2764         alloc_target = btrfs_get_alloc_profile(root, 1);
2765         BTRFS_I(inode)->space_info = __find_space_info(root->fs_info,
2766                                                        alloc_target);
2767 }
2768
2769 static u64 calculate_bytes_needed(struct btrfs_root *root, int num_items)
2770 {
2771         u64 num_bytes;
2772         int level;
2773
2774         level = BTRFS_MAX_LEVEL - 2;
2775         /*
2776          * NOTE: these calculations are absolutely the worst possible case.
2777          * This assumes that _every_ item we insert will require a new leaf, and
2778          * that the tree has grown to its maximum level size.
2779          */
2780
2781         /*
2782          * for every item we insert we could insert both an extent item and a
2783          * extent ref item.  Then for ever item we insert, we will need to cow
2784          * both the original leaf, plus the leaf to the left and right of it.
2785          *
2786          * Unless we are talking about the extent root, then we just want the
2787          * number of items * 2, since we just need the extent item plus its ref.
2788          */
2789         if (root == root->fs_info->extent_root)
2790                 num_bytes = num_items * 2;
2791         else
2792                 num_bytes = (num_items + (2 * num_items)) * 3;
2793
2794         /*
2795          * num_bytes is total number of leaves we could need times the leaf
2796          * size, and then for every leaf we could end up cow'ing 2 nodes per
2797          * level, down to the leaf level.
2798          */
2799         num_bytes = (num_bytes * root->leafsize) +
2800                 (num_bytes * (level * 2)) * root->nodesize;
2801
2802         return num_bytes;
2803 }
2804
2805 /*
2806  * Unreserve metadata space for delalloc.  If we have less reserved credits than
2807  * we have extents, this function does nothing.
2808  */
2809 int btrfs_unreserve_metadata_for_delalloc(struct btrfs_root *root,
2810                                           struct inode *inode, int num_items)
2811 {
2812         struct btrfs_fs_info *info = root->fs_info;
2813         struct btrfs_space_info *meta_sinfo;
2814         u64 num_bytes;
2815         u64 alloc_target;
2816         bool bug = false;
2817
2818         /* get the space info for where the metadata will live */
2819         alloc_target = btrfs_get_alloc_profile(root, 0);
2820         meta_sinfo = __find_space_info(info, alloc_target);
2821
2822         num_bytes = calculate_bytes_needed(root->fs_info->extent_root,
2823                                            num_items);
2824
2825         spin_lock(&meta_sinfo->lock);
2826         if (BTRFS_I(inode)->delalloc_reserved_extents <=
2827             BTRFS_I(inode)->delalloc_extents) {
2828                 spin_unlock(&meta_sinfo->lock);
2829                 return 0;
2830         }
2831
2832         BTRFS_I(inode)->delalloc_reserved_extents--;
2833         BUG_ON(BTRFS_I(inode)->delalloc_reserved_extents < 0);
2834
2835         if (meta_sinfo->bytes_delalloc < num_bytes) {
2836                 bug = true;
2837                 meta_sinfo->bytes_delalloc = 0;
2838         } else {
2839                 meta_sinfo->bytes_delalloc -= num_bytes;
2840         }
2841         spin_unlock(&meta_sinfo->lock);
2842
2843         BUG_ON(bug);
2844
2845         return 0;
2846 }
2847
2848 static void check_force_delalloc(struct btrfs_space_info *meta_sinfo)
2849 {
2850         u64 thresh;
2851
2852         thresh = meta_sinfo->bytes_used + meta_sinfo->bytes_reserved +
2853                 meta_sinfo->bytes_pinned + meta_sinfo->bytes_readonly +
2854                 meta_sinfo->bytes_super + meta_sinfo->bytes_root +
2855                 meta_sinfo->bytes_may_use;
2856
2857         thresh = meta_sinfo->total_bytes - thresh;
2858         thresh *= 80;
2859         do_div(thresh, 100);
2860         if (thresh <= meta_sinfo->bytes_delalloc)
2861                 meta_sinfo->force_delalloc = 1;
2862         else
2863                 meta_sinfo->force_delalloc = 0;
2864 }
2865
2866 static int maybe_allocate_chunk(struct btrfs_root *root,
2867                                  struct btrfs_space_info *info)
2868 {
2869         struct btrfs_super_block *disk_super = &root->fs_info->super_copy;
2870         struct btrfs_trans_handle *trans;
2871         bool wait = false;
2872         int ret = 0;
2873         u64 min_metadata;
2874         u64 free_space;
2875
2876         free_space = btrfs_super_total_bytes(disk_super);
2877         /*
2878          * we allow the metadata to grow to a max of either 5gb or 5% of the
2879          * space in the volume.
2880          */
2881         min_metadata = min((u64)5 * 1024 * 1024 * 1024,
2882                              div64_u64(free_space * 5, 100));
2883         if (info->total_bytes >= min_metadata) {
2884                 spin_unlock(&info->lock);
2885                 return 0;
2886         }
2887
2888         if (info->full) {
2889                 spin_unlock(&info->lock);
2890                 return 0;
2891         }
2892
2893         if (!info->allocating_chunk) {
2894                 info->force_alloc = 1;
2895                 info->allocating_chunk = 1;
2896                 init_waitqueue_head(&info->wait);
2897         } else {
2898                 wait = true;
2899         }
2900
2901         spin_unlock(&info->lock);
2902
2903         if (wait) {
2904                 wait_event(info->wait,
2905                            !info->allocating_chunk);
2906                 return 1;
2907         }
2908
2909         trans = btrfs_start_transaction(root, 1);
2910         if (!trans) {
2911                 ret = -ENOMEM;
2912                 goto out;
2913         }
2914
2915         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
2916                              4096 + 2 * 1024 * 1024,
2917                              info->flags, 0);
2918         btrfs_end_transaction(trans, root);
2919         if (ret)
2920                 goto out;
2921 out:
2922         spin_lock(&info->lock);
2923         info->allocating_chunk = 0;
2924         spin_unlock(&info->lock);
2925         wake_up(&info->wait);
2926
2927         if (ret)
2928                 return 0;
2929         return 1;
2930 }
2931
2932 /*
2933  * Reserve metadata space for delalloc.
2934  */
2935 int btrfs_reserve_metadata_for_delalloc(struct btrfs_root *root,
2936                                         struct inode *inode, int num_items)
2937 {
2938         struct btrfs_fs_info *info = root->fs_info;
2939         struct btrfs_space_info *meta_sinfo;
2940         u64 num_bytes;
2941         u64 used;
2942         u64 alloc_target;
2943         int flushed = 0;
2944         int force_delalloc;
2945
2946         /* get the space info for where the metadata will live */
2947         alloc_target = btrfs_get_alloc_profile(root, 0);
2948         meta_sinfo = __find_space_info(info, alloc_target);
2949
2950         num_bytes = calculate_bytes_needed(root->fs_info->extent_root,
2951                                            num_items);
2952 again:
2953         spin_lock(&meta_sinfo->lock);
2954
2955         force_delalloc = meta_sinfo->force_delalloc;
2956
2957         if (unlikely(!meta_sinfo->bytes_root))
2958                 meta_sinfo->bytes_root = calculate_bytes_needed(root, 6);
2959
2960         if (!flushed)
2961                 meta_sinfo->bytes_delalloc += num_bytes;
2962
2963         used = meta_sinfo->bytes_used + meta_sinfo->bytes_reserved +
2964                 meta_sinfo->bytes_pinned + meta_sinfo->bytes_readonly +
2965                 meta_sinfo->bytes_super + meta_sinfo->bytes_root +
2966                 meta_sinfo->bytes_may_use + meta_sinfo->bytes_delalloc;
2967
2968         if (used > meta_sinfo->total_bytes) {
2969                 flushed++;
2970
2971                 if (flushed == 1) {
2972                         if (maybe_allocate_chunk(root, meta_sinfo))
2973                                 goto again;
2974                         flushed++;
2975                 } else {
2976                         spin_unlock(&meta_sinfo->lock);
2977                 }
2978
2979                 if (flushed == 2) {
2980                         filemap_flush(inode->i_mapping);
2981                         goto again;
2982                 } else if (flushed == 3) {
2983                         btrfs_start_delalloc_inodes(root);
2984                         btrfs_wait_ordered_extents(root, 0);
2985                         goto again;
2986                 }
2987                 spin_lock(&meta_sinfo->lock);
2988                 meta_sinfo->bytes_delalloc -= num_bytes;
2989                 spin_unlock(&meta_sinfo->lock);
2990                 printk(KERN_ERR "enospc, has %d, reserved %d\n",
2991                        BTRFS_I(inode)->delalloc_extents,
2992                        BTRFS_I(inode)->delalloc_reserved_extents);
2993                 dump_space_info(meta_sinfo, 0, 0);
2994                 return -ENOSPC;
2995         }
2996
2997         BTRFS_I(inode)->delalloc_reserved_extents++;
2998         check_force_delalloc(meta_sinfo);
2999         spin_unlock(&meta_sinfo->lock);
3000
3001         if (!flushed && force_delalloc)
3002                 filemap_flush(inode->i_mapping);
3003
3004         return 0;
3005 }
3006
3007 /*
3008  * unreserve num_items number of items worth of metadata space.  This needs to
3009  * be paired with btrfs_reserve_metadata_space.
3010  *
3011  * NOTE: if you have the option, run this _AFTER_ you do a
3012  * btrfs_end_transaction, since btrfs_end_transaction will run delayed ref
3013  * oprations which will result in more used metadata, so we want to make sure we
3014  * can do that without issue.
3015  */
3016 int btrfs_unreserve_metadata_space(struct btrfs_root *root, int num_items)
3017 {
3018         struct btrfs_fs_info *info = root->fs_info;
3019         struct btrfs_space_info *meta_sinfo;
3020         u64 num_bytes;
3021         u64 alloc_target;
3022         bool bug = false;
3023
3024         /* get the space info for where the metadata will live */
3025         alloc_target = btrfs_get_alloc_profile(root, 0);
3026         meta_sinfo = __find_space_info(info, alloc_target);
3027
3028         num_bytes = calculate_bytes_needed(root, num_items);
3029
3030         spin_lock(&meta_sinfo->lock);
3031         if (meta_sinfo->bytes_may_use < num_bytes) {
3032                 bug = true;
3033                 meta_sinfo->bytes_may_use = 0;
3034         } else {
3035                 meta_sinfo->bytes_may_use -= num_bytes;
3036         }
3037         spin_unlock(&meta_sinfo->lock);
3038
3039         BUG_ON(bug);
3040
3041         return 0;
3042 }
3043
3044 /*
3045  * Reserve some metadata space for use.  We'll calculate the worste case number
3046  * of bytes that would be needed to modify num_items number of items.  If we
3047  * have space, fantastic, if not, you get -ENOSPC.  Please call
3048  * btrfs_unreserve_metadata_space when you are done for the _SAME_ number of
3049  * items you reserved, since whatever metadata you needed should have already
3050  * been allocated.
3051  *
3052  * This will commit the transaction to make more space if we don't have enough
3053  * metadata space.  THe only time we don't do this is if we're reserving space
3054  * inside of a transaction, then we will just return -ENOSPC and it is the
3055  * callers responsibility to handle it properly.
3056  */
3057 int btrfs_reserve_metadata_space(struct btrfs_root *root, int num_items)
3058 {
3059         struct btrfs_fs_info *info = root->fs_info;
3060         struct btrfs_space_info *meta_sinfo;
3061         u64 num_bytes;
3062         u64 used;
3063         u64 alloc_target;
3064         int retries = 0;
3065
3066         /* get the space info for where the metadata will live */
3067         alloc_target = btrfs_get_alloc_profile(root, 0);
3068         meta_sinfo = __find_space_info(info, alloc_target);
3069
3070         num_bytes = calculate_bytes_needed(root, num_items);
3071 again:
3072         spin_lock(&meta_sinfo->lock);
3073
3074         if (unlikely(!meta_sinfo->bytes_root))
3075                 meta_sinfo->bytes_root = calculate_bytes_needed(root, 6);
3076
3077         if (!retries)
3078                 meta_sinfo->bytes_may_use += num_bytes;
3079
3080         used = meta_sinfo->bytes_used + meta_sinfo->bytes_reserved +
3081                 meta_sinfo->bytes_pinned + meta_sinfo->bytes_readonly +
3082                 meta_sinfo->bytes_super + meta_sinfo->bytes_root +
3083                 meta_sinfo->bytes_may_use + meta_sinfo->bytes_delalloc;
3084
3085         if (used > meta_sinfo->total_bytes) {
3086                 retries++;
3087                 if (retries == 1) {
3088                         if (maybe_allocate_chunk(root, meta_sinfo))
3089                                 goto again;
3090                         retries++;
3091                 } else {
3092                         spin_unlock(&meta_sinfo->lock);
3093                 }
3094
3095                 if (retries == 2) {
3096                         btrfs_start_delalloc_inodes(root);
3097                         btrfs_wait_ordered_extents(root, 0);
3098                         goto again;
3099                 }
3100                 spin_lock(&meta_sinfo->lock);
3101                 meta_sinfo->bytes_may_use -= num_bytes;
3102                 spin_unlock(&meta_sinfo->lock);
3103
3104                 dump_space_info(meta_sinfo, 0, 0);
3105                 return -ENOSPC;
3106         }
3107
3108         check_force_delalloc(meta_sinfo);
3109         spin_unlock(&meta_sinfo->lock);
3110
3111         return 0;
3112 }
3113
3114 /*
3115  * This will check the space that the inode allocates from to make sure we have
3116  * enough space for bytes.
3117  */
3118 int btrfs_check_data_free_space(struct btrfs_root *root, struct inode *inode,
3119                                 u64 bytes)
3120 {
3121         struct btrfs_space_info *data_sinfo;
3122         int ret = 0, committed = 0;
3123
3124         /* make sure bytes are sectorsize aligned */
3125         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3126
3127         data_sinfo = BTRFS_I(inode)->space_info;
3128         if (!data_sinfo)
3129                 goto alloc;
3130
3131 again:
3132         /* make sure we have enough space to handle the data first */
3133         spin_lock(&data_sinfo->lock);
3134         if (data_sinfo->total_bytes - data_sinfo->bytes_used -
3135             data_sinfo->bytes_delalloc - data_sinfo->bytes_reserved -
3136             data_sinfo->bytes_pinned - data_sinfo->bytes_readonly -
3137             data_sinfo->bytes_may_use - data_sinfo->bytes_super < bytes) {
3138                 struct btrfs_trans_handle *trans;
3139
3140                 /*
3141                  * if we don't have enough free bytes in this space then we need
3142                  * to alloc a new chunk.
3143                  */
3144                 if (!data_sinfo->full) {
3145                         u64 alloc_target;
3146
3147                         data_sinfo->force_alloc = 1;
3148                         spin_unlock(&data_sinfo->lock);
3149 alloc:
3150                         alloc_target = btrfs_get_alloc_profile(root, 1);
3151                         trans = btrfs_start_transaction(root, 1);
3152                         if (!trans)
3153                                 return -ENOMEM;
3154
3155                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3156                                              bytes + 2 * 1024 * 1024,
3157                                              alloc_target, 0);
3158                         btrfs_end_transaction(trans, root);
3159                         if (ret)
3160                                 return ret;
3161
3162                         if (!data_sinfo) {
3163                                 btrfs_set_inode_space_info(root, inode);
3164                                 data_sinfo = BTRFS_I(inode)->space_info;
3165                         }
3166                         goto again;
3167                 }
3168                 spin_unlock(&data_sinfo->lock);
3169
3170                 /* commit the current transaction and try again */
3171                 if (!committed && !root->fs_info->open_ioctl_trans) {
3172                         committed = 1;
3173                         trans = btrfs_join_transaction(root, 1);
3174                         if (!trans)
3175                                 return -ENOMEM;
3176                         ret = btrfs_commit_transaction(trans, root);
3177                         if (ret)
3178                                 return ret;
3179                         goto again;
3180                 }
3181
3182                 printk(KERN_ERR "no space left, need %llu, %llu delalloc bytes"
3183                        ", %llu bytes_used, %llu bytes_reserved, "
3184                        "%llu bytes_pinned, %llu bytes_readonly, %llu may use "
3185                        "%llu total\n", (unsigned long long)bytes,
3186                        (unsigned long long)data_sinfo->bytes_delalloc,
3187                        (unsigned long long)data_sinfo->bytes_used,
3188                        (unsigned long long)data_sinfo->bytes_reserved,
3189                        (unsigned long long)data_sinfo->bytes_pinned,
3190                        (unsigned long long)data_sinfo->bytes_readonly,
3191                        (unsigned long long)data_sinfo->bytes_may_use,
3192                        (unsigned long long)data_sinfo->total_bytes);
3193                 return -ENOSPC;
3194         }
3195         data_sinfo->bytes_may_use += bytes;
3196         BTRFS_I(inode)->reserved_bytes += bytes;
3197         spin_unlock(&data_sinfo->lock);
3198
3199         return 0;
3200 }
3201
3202 /*
3203  * if there was an error for whatever reason after calling
3204  * btrfs_check_data_free_space, call this so we can cleanup the counters.
3205  */
3206 void btrfs_free_reserved_data_space(struct btrfs_root *root,
3207                                     struct inode *inode, u64 bytes)
3208 {
3209         struct btrfs_space_info *data_sinfo;
3210
3211         /* make sure bytes are sectorsize aligned */
3212         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3213
3214         data_sinfo = BTRFS_I(inode)->space_info;
3215         spin_lock(&data_sinfo->lock);
3216         data_sinfo->bytes_may_use -= bytes;
3217         BTRFS_I(inode)->reserved_bytes -= bytes;
3218         spin_unlock(&data_sinfo->lock);
3219 }
3220
3221 /* called when we are adding a delalloc extent to the inode's io_tree */
3222 void btrfs_delalloc_reserve_space(struct btrfs_root *root, struct inode *inode,
3223                                   u64 bytes)
3224 {
3225         struct btrfs_space_info *data_sinfo;
3226
3227         /* get the space info for where this inode will be storing its data */
3228         data_sinfo = BTRFS_I(inode)->space_info;
3229
3230         /* make sure we have enough space to handle the data first */
3231         spin_lock(&data_sinfo->lock);
3232         data_sinfo->bytes_delalloc += bytes;
3233
3234         /*
3235          * we are adding a delalloc extent without calling
3236          * btrfs_check_data_free_space first.  This happens on a weird
3237          * writepage condition, but shouldn't hurt our accounting
3238          */
3239         if (unlikely(bytes > BTRFS_I(inode)->reserved_bytes)) {
3240                 data_sinfo->bytes_may_use -= BTRFS_I(inode)->reserved_bytes;
3241                 BTRFS_I(inode)->reserved_bytes = 0;
3242         } else {
3243                 data_sinfo->bytes_may_use -= bytes;
3244                 BTRFS_I(inode)->reserved_bytes -= bytes;
3245         }
3246
3247         spin_unlock(&data_sinfo->lock);
3248 }
3249
3250 /* called when we are clearing an delalloc extent from the inode's io_tree */
3251 void btrfs_delalloc_free_space(struct btrfs_root *root, struct inode *inode,
3252                               u64 bytes)
3253 {
3254         struct btrfs_space_info *info;
3255
3256         info = BTRFS_I(inode)->space_info;
3257
3258         spin_lock(&info->lock);
3259         info->bytes_delalloc -= bytes;
3260         spin_unlock(&info->lock);
3261 }
3262
3263 static void force_metadata_allocation(struct btrfs_fs_info *info)
3264 {
3265         struct list_head *head = &info->space_info;
3266         struct btrfs_space_info *found;
3267
3268         rcu_read_lock();
3269         list_for_each_entry_rcu(found, head, list) {
3270                 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3271                         found->force_alloc = 1;
3272         }
3273         rcu_read_unlock();
3274 }
3275
3276 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
3277                           struct btrfs_root *extent_root, u64 alloc_bytes,
3278                           u64 flags, int force)
3279 {
3280         struct btrfs_space_info *space_info;
3281         struct btrfs_fs_info *fs_info = extent_root->fs_info;
3282         u64 thresh;
3283         int ret = 0;
3284
3285         mutex_lock(&fs_info->chunk_mutex);
3286
3287         flags = btrfs_reduce_alloc_profile(extent_root, flags);
3288
3289         space_info = __find_space_info(extent_root->fs_info, flags);
3290         if (!space_info) {
3291                 ret = update_space_info(extent_root->fs_info, flags,
3292                                         0, 0, &space_info);
3293                 BUG_ON(ret);
3294         }
3295         BUG_ON(!space_info);
3296
3297         spin_lock(&space_info->lock);
3298         if (space_info->force_alloc)
3299                 force = 1;
3300         if (space_info->full) {
3301                 spin_unlock(&space_info->lock);
3302                 goto out;
3303         }
3304
3305         thresh = space_info->total_bytes - space_info->bytes_readonly;
3306         thresh = div_factor(thresh, 8);
3307         if (!force &&
3308            (space_info->bytes_used + space_info->bytes_pinned +
3309             space_info->bytes_reserved + alloc_bytes) < thresh) {
3310                 spin_unlock(&space_info->lock);
3311                 goto out;
3312         }
3313         spin_unlock(&space_info->lock);
3314
3315         /*
3316          * if we're doing a data chunk, go ahead and make sure that
3317          * we keep a reasonable number of metadata chunks allocated in the
3318          * FS as well.
3319          */
3320         if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3321                 fs_info->data_chunk_allocations++;
3322                 if (!(fs_info->data_chunk_allocations %
3323                       fs_info->metadata_ratio))
3324                         force_metadata_allocation(fs_info);
3325         }
3326
3327         ret = btrfs_alloc_chunk(trans, extent_root, flags);
3328         spin_lock(&space_info->lock);
3329         if (ret)
3330                 space_info->full = 1;
3331         space_info->force_alloc = 0;
3332         spin_unlock(&space_info->lock);
3333 out:
3334         mutex_unlock(&extent_root->fs_info->chunk_mutex);
3335         return ret;
3336 }
3337
3338 static int update_block_group(struct btrfs_trans_handle *trans,
3339                               struct btrfs_root *root,
3340                               u64 bytenr, u64 num_bytes, int alloc,
3341                               int mark_free)
3342 {
3343         struct btrfs_block_group_cache *cache;
3344         struct btrfs_fs_info *info = root->fs_info;
3345         u64 total = num_bytes;
3346         u64 old_val;
3347         u64 byte_in_group;
3348
3349         /* block accounting for super block */
3350         spin_lock(&info->delalloc_lock);
3351         old_val = btrfs_super_bytes_used(&info->super_copy);
3352         if (alloc)
3353                 old_val += num_bytes;
3354         else
3355                 old_val -= num_bytes;
3356         btrfs_set_super_bytes_used(&info->super_copy, old_val);
3357
3358         /* block accounting for root item */
3359         old_val = btrfs_root_used(&root->root_item);
3360         if (alloc)
3361                 old_val += num_bytes;
3362         else
3363                 old_val -= num_bytes;
3364         btrfs_set_root_used(&root->root_item, old_val);
3365         spin_unlock(&info->delalloc_lock);
3366
3367         while (total) {
3368                 cache = btrfs_lookup_block_group(info, bytenr);
3369                 if (!cache)
3370                         return -1;
3371                 byte_in_group = bytenr - cache->key.objectid;
3372                 WARN_ON(byte_in_group > cache->key.offset);
3373
3374                 spin_lock(&cache->space_info->lock);
3375                 spin_lock(&cache->lock);
3376                 cache->dirty = 1;
3377                 old_val = btrfs_block_group_used(&cache->item);
3378                 num_bytes = min(total, cache->key.offset - byte_in_group);
3379                 if (alloc) {
3380                         old_val += num_bytes;
3381                         btrfs_set_block_group_used(&cache->item, old_val);
3382                         cache->reserved -= num_bytes;
3383                         cache->space_info->bytes_used += num_bytes;
3384                         cache->space_info->bytes_reserved -= num_bytes;
3385                         if (cache->ro)
3386                                 cache->space_info->bytes_readonly -= num_bytes;
3387                         spin_unlock(&cache->lock);
3388                         spin_unlock(&cache->space_info->lock);
3389                 } else {
3390                         old_val -= num_bytes;
3391                         cache->space_info->bytes_used -= num_bytes;
3392                         if (cache->ro)
3393                                 cache->space_info->bytes_readonly += num_bytes;
3394                         btrfs_set_block_group_used(&cache->item, old_val);
3395                         spin_unlock(&cache->lock);
3396                         spin_unlock(&cache->space_info->lock);
3397                         if (mark_free) {
3398                                 int ret;
3399
3400                                 ret = btrfs_discard_extent(root, bytenr,
3401                                                            num_bytes);
3402                                 WARN_ON(ret);
3403
3404                                 ret = btrfs_add_free_space(cache, bytenr,
3405                                                            num_bytes);
3406                                 WARN_ON(ret);
3407                         }
3408                 }
3409                 btrfs_put_block_group(cache);
3410                 total -= num_bytes;
3411                 bytenr += num_bytes;
3412         }
3413         return 0;
3414 }
3415
3416 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
3417 {
3418         struct btrfs_block_group_cache *cache;
3419         u64 bytenr;
3420
3421         cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
3422         if (!cache)
3423                 return 0;
3424
3425         bytenr = cache->key.objectid;
3426         btrfs_put_block_group(cache);
3427
3428         return bytenr;
3429 }
3430
3431 /*
3432  * this function must be called within transaction
3433  */
3434 int btrfs_pin_extent(struct btrfs_root *root,
3435                      u64 bytenr, u64 num_bytes, int reserved)
3436 {
3437         struct btrfs_fs_info *fs_info = root->fs_info;
3438         struct btrfs_block_group_cache *cache;
3439
3440         cache = btrfs_lookup_block_group(fs_info, bytenr);
3441         BUG_ON(!cache);
3442
3443         spin_lock(&cache->space_info->lock);
3444         spin_lock(&cache->lock);
3445         cache->pinned += num_bytes;
3446         cache->space_info->bytes_pinned += num_bytes;
3447         if (reserved) {
3448                 cache->reserved -= num_bytes;
3449                 cache->space_info->bytes_reserved -= num_bytes;
3450         }
3451         spin_unlock(&cache->lock);
3452         spin_unlock(&cache->space_info->lock);
3453
3454         btrfs_put_block_group(cache);
3455
3456         set_extent_dirty(fs_info->pinned_extents,
3457                          bytenr, bytenr + num_bytes - 1, GFP_NOFS);
3458         return 0;
3459 }
3460
3461 static int update_reserved_extents(struct btrfs_block_group_cache *cache,
3462                                    u64 num_bytes, int reserve)
3463 {
3464         spin_lock(&cache->space_info->lock);
3465         spin_lock(&cache->lock);
3466         if (reserve) {
3467                 cache->reserved += num_bytes;
3468                 cache->space_info->bytes_reserved += num_bytes;
3469         } else {
3470                 cache->reserved -= num_bytes;
3471                 cache->space_info->bytes_reserved -= num_bytes;
3472         }
3473         spin_unlock(&cache->lock);
3474         spin_unlock(&cache->space_info->lock);
3475         return 0;
3476 }
3477
3478 int btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
3479                                 struct btrfs_root *root)
3480 {
3481         struct btrfs_fs_info *fs_info = root->fs_info;
3482         struct btrfs_caching_control *next;
3483         struct btrfs_caching_control *caching_ctl;
3484         struct btrfs_block_group_cache *cache;
3485
3486         down_write(&fs_info->extent_commit_sem);
3487
3488         list_for_each_entry_safe(caching_ctl, next,
3489                                  &fs_info->caching_block_groups, list) {
3490                 cache = caching_ctl->block_group;
3491                 if (block_group_cache_done(cache)) {
3492                         cache->last_byte_to_unpin = (u64)-1;
3493                         list_del_init(&caching_ctl->list);
3494                         put_caching_control(caching_ctl);
3495                 } else {
3496                         cache->last_byte_to_unpin = caching_ctl->progress;
3497                 }
3498         }
3499
3500         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
3501                 fs_info->pinned_extents = &fs_info->freed_extents[1];
3502         else
3503                 fs_info->pinned_extents = &fs_info->freed_extents[0];
3504
3505         up_write(&fs_info->extent_commit_sem);
3506         return 0;
3507 }
3508
3509 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
3510 {
3511         struct btrfs_fs_info *fs_info = root->fs_info;
3512         struct btrfs_block_group_cache *cache = NULL;
3513         u64 len;
3514
3515         while (start <= end) {
3516                 if (!cache ||
3517                     start >= cache->key.objectid + cache->key.offset) {
3518                         if (cache)
3519                                 btrfs_put_block_group(cache);
3520                         cache = btrfs_lookup_block_group(fs_info, start);
3521                         BUG_ON(!cache);
3522                 }
3523
3524                 len = cache->key.objectid + cache->key.offset - start;
3525                 len = min(len, end + 1 - start);
3526
3527                 if (start < cache->last_byte_to_unpin) {
3528                         len = min(len, cache->last_byte_to_unpin - start);
3529                         btrfs_add_free_space(cache, start, len);
3530                 }
3531
3532                 spin_lock(&cache->space_info->lock);
3533                 spin_lock(&cache->lock);
3534                 cache->pinned -= len;
3535                 cache->space_info->bytes_pinned -= len;
3536                 spin_unlock(&cache->lock);
3537                 spin_unlock(&cache->space_info->lock);
3538
3539                 start += len;
3540         }
3541
3542         if (cache)
3543                 btrfs_put_block_group(cache);
3544         return 0;
3545 }
3546
3547 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
3548                                struct btrfs_root *root)
3549 {
3550         struct btrfs_fs_info *fs_info = root->fs_info;
3551         struct extent_io_tree *unpin;
3552         u64 start;
3553         u64 end;
3554         int ret;
3555
3556         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
3557                 unpin = &fs_info->freed_extents[1];
3558         else
3559                 unpin = &fs_info->freed_extents[0];
3560
3561         while (1) {
3562                 ret = find_first_extent_bit(unpin, 0, &start, &end,
3563                                             EXTENT_DIRTY);
3564                 if (ret)
3565                         break;
3566
3567                 ret = btrfs_discard_extent(root, start, end + 1 - start);
3568
3569                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
3570                 unpin_extent_range(root, start, end);
3571                 cond_resched();
3572         }
3573
3574         return ret;
3575 }
3576
3577 static int pin_down_bytes(struct btrfs_trans_handle *trans,
3578                           struct btrfs_root *root,
3579                           struct btrfs_path *path,
3580                           u64 bytenr, u64 num_bytes,
3581                           int is_data, int reserved,
3582                           struct extent_buffer **must_clean)
3583 {
3584         int err = 0;
3585         struct extent_buffer *buf;
3586
3587         if (is_data)
3588                 goto pinit;
3589
3590         buf = btrfs_find_tree_block(root, bytenr, num_bytes);
3591         if (!buf)
3592                 goto pinit;
3593
3594         /* we can reuse a block if it hasn't been written
3595          * and it is from this transaction.  We can't
3596          * reuse anything from the tree log root because
3597          * it has tiny sub-transactions.
3598          */
3599         if (btrfs_buffer_uptodate(buf, 0) &&
3600             btrfs_try_tree_lock(buf)) {
3601                 u64 header_owner = btrfs_header_owner(buf);
3602                 u64 header_transid = btrfs_header_generation(buf);
3603                 if (header_owner != BTRFS_TREE_LOG_OBJECTID &&
3604                     header_transid == trans->transid &&
3605                     !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
3606                         *must_clean = buf;
3607                         return 1;
3608                 }
3609                 btrfs_tree_unlock(buf);
3610         }
3611         free_extent_buffer(buf);
3612 pinit:
3613         if (path)
3614                 btrfs_set_path_blocking(path);
3615         /* unlocks the pinned mutex */
3616         btrfs_pin_extent(root, bytenr, num_bytes, reserved);
3617
3618         BUG_ON(err < 0);
3619         return 0;
3620 }
3621
3622 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
3623                                 struct btrfs_root *root,
3624                                 u64 bytenr, u64 num_bytes, u64 parent,
3625                                 u64 root_objectid, u64 owner_objectid,
3626                                 u64 owner_offset, int refs_to_drop,
3627                                 struct btrfs_delayed_extent_op *extent_op)
3628 {
3629         struct btrfs_key key;
3630         struct btrfs_path *path;
3631         struct btrfs_fs_info *info = root->fs_info;
3632         struct btrfs_root *extent_root = info->extent_root;
3633         struct extent_buffer *leaf;
3634         struct btrfs_extent_item *ei;
3635         struct btrfs_extent_inline_ref *iref;
3636         int ret;
3637         int is_data;
3638         int extent_slot = 0;
3639         int found_extent = 0;
3640         int num_to_del = 1;
3641         u32 item_size;
3642         u64 refs;
3643
3644         path = btrfs_alloc_path();
3645         if (!path)
3646                 return -ENOMEM;
3647
3648         path->reada = 1;
3649         path->leave_spinning = 1;
3650
3651         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
3652         BUG_ON(!is_data && refs_to_drop != 1);
3653
3654         ret = lookup_extent_backref(trans, extent_root, path, &iref,
3655                                     bytenr, num_bytes, parent,
3656                                     root_objectid, owner_objectid,
3657                                     owner_offset);
3658         if (ret == 0) {
3659                 extent_slot = path->slots[0];
3660                 while (extent_slot >= 0) {
3661                         btrfs_item_key_to_cpu(path->nodes[0], &key,
3662                                               extent_slot);
3663                         if (key.objectid != bytenr)
3664                                 break;
3665                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3666                             key.offset == num_bytes) {
3667                                 found_extent = 1;
3668                                 break;
3669                         }
3670                         if (path->slots[0] - extent_slot > 5)
3671                                 break;
3672                         extent_slot--;
3673                 }
3674 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3675                 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
3676                 if (found_extent && item_size < sizeof(*ei))
3677                         found_extent = 0;
3678 #endif
3679                 if (!found_extent) {
3680                         BUG_ON(iref);
3681                         ret = remove_extent_backref(trans, extent_root, path,
3682                                                     NULL, refs_to_drop,
3683                                                     is_data);
3684                         BUG_ON(ret);
3685                         btrfs_release_path(extent_root, path);
3686                         path->leave_spinning = 1;
3687
3688                         key.objectid = bytenr;
3689                         key.type = BTRFS_EXTENT_ITEM_KEY;
3690                         key.offset = num_bytes;
3691
3692                         ret = btrfs_search_slot(trans, extent_root,
3693                                                 &key, path, -1, 1);
3694                         if (ret) {
3695                                 printk(KERN_ERR "umm, got %d back from search"
3696                                        ", was looking for %llu\n", ret,
3697                                        (unsigned long long)bytenr);
3698                                 btrfs_print_leaf(extent_root, path->nodes[0]);
3699                         }
3700                         BUG_ON(ret);
3701                         extent_slot = path->slots[0];
3702                 }
3703         } else {
3704                 btrfs_print_leaf(extent_root, path->nodes[0]);
3705                 WARN_ON(1);
3706                 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
3707                        "parent %llu root %llu  owner %llu offset %llu\n",
3708                        (unsigned long long)bytenr,
3709                        (unsigned long long)parent,
3710                        (unsigned long long)root_objectid,
3711                        (unsigned long long)owner_objectid,
3712                        (unsigned long long)owner_offset);
3713         }
3714
3715         leaf = path->nodes[0];
3716         item_size = btrfs_item_size_nr(leaf, extent_slot);
3717 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3718         if (item_size < sizeof(*ei)) {
3719                 BUG_ON(found_extent || extent_slot != path->slots[0]);
3720                 ret = convert_extent_item_v0(trans, extent_root, path,
3721                                              owner_objectid, 0);
3722                 BUG_ON(ret < 0);
3723
3724                 btrfs_release_path(extent_root, path);
3725                 path->leave_spinning = 1;
3726
3727                 key.objectid = bytenr;
3728                 key.type = BTRFS_EXTENT_ITEM_KEY;
3729                 key.offset = num_bytes;
3730
3731                 ret = btrfs_search_slot(trans, extent_root, &key, path,
3732                                         -1, 1);
3733                 if (ret) {
3734                         printk(KERN_ERR "umm, got %d back from search"
3735                                ", was looking for %llu\n", ret,
3736                                (unsigned long long)bytenr);
3737                         btrfs_print_leaf(extent_root, path->nodes[0]);
3738                 }
3739                 BUG_ON(ret);
3740                 extent_slot = path->slots[0];
3741                 leaf = path->nodes[0];
3742                 item_size = btrfs_item_size_nr(leaf, extent_slot);
3743         }
3744 #endif
3745         BUG_ON(item_size < sizeof(*ei));
3746         ei = btrfs_item_ptr(leaf, extent_slot,
3747                             struct btrfs_extent_item);
3748         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
3749                 struct btrfs_tree_block_info *bi;
3750                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
3751                 bi = (struct btrfs_tree_block_info *)(ei + 1);
3752                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3753         }
3754
3755         refs = btrfs_extent_refs(leaf, ei);
3756         BUG_ON(refs < refs_to_drop);
3757         refs -= refs_to_drop;
3758
3759         if (refs > 0) {
3760                 if (extent_op)
3761                         __run_delayed_extent_op(extent_op, leaf, ei);
3762                 /*
3763                  * In the case of inline back ref, reference count will
3764                  * be updated by remove_extent_backref
3765                  */
3766                 if (iref) {
3767                         BUG_ON(!found_extent);
3768                 } else {
3769                         btrfs_set_extent_refs(leaf, ei, refs);
3770                         btrfs_mark_buffer_dirty(leaf);
3771                 }
3772                 if (found_extent) {
3773                         ret = remove_extent_backref(trans, extent_root, path,
3774                                                     iref, refs_to_drop,
3775                                                     is_data);
3776                         BUG_ON(ret);
3777                 }
3778         } else {
3779                 int mark_free = 0;
3780                 struct extent_buffer *must_clean = NULL;
3781
3782                 if (found_extent) {
3783                         BUG_ON(is_data && refs_to_drop !=
3784                                extent_data_ref_count(root, path, iref));
3785                         if (iref) {
3786                                 BUG_ON(path->slots[0] != extent_slot);
3787                         } else {
3788                                 BUG_ON(path->slots[0] != extent_slot + 1);
3789                                 path->slots[0] = extent_slot;
3790                                 num_to_del = 2;
3791                         }
3792                 }
3793
3794                 ret = pin_down_bytes(trans, root, path, bytenr,
3795                                      num_bytes, is_data, 0, &must_clean);
3796                 if (ret > 0)
3797                         mark_free = 1;
3798                 BUG_ON(ret < 0);
3799                 /*
3800                  * it is going to be very rare for someone to be waiting
3801                  * on the block we're freeing.  del_items might need to
3802                  * schedule, so rather than get fancy, just force it
3803                  * to blocking here
3804                  */
3805                 if (must_clean)
3806                         btrfs_set_lock_blocking(must_clean);
3807
3808                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3809                                       num_to_del);
3810                 BUG_ON(ret);
3811                 btrfs_release_path(extent_root, path);
3812
3813                 if (must_clean) {
3814                         clean_tree_block(NULL, root, must_clean);
3815                         btrfs_tree_unlock(must_clean);
3816                         free_extent_buffer(must_clean);
3817                 }
3818
3819                 if (is_data) {
3820                         ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
3821                         BUG_ON(ret);
3822                 } else {
3823                         invalidate_mapping_pages(info->btree_inode->i_mapping,
3824                              bytenr >> PAGE_CACHE_SHIFT,
3825                              (bytenr + num_bytes - 1) >> PAGE_CACHE_SHIFT);
3826                 }
3827
3828                 ret = update_block_group(trans, root, bytenr, num_bytes, 0,
3829                                          mark_free);
3830                 BUG_ON(ret);
3831         }
3832         btrfs_free_path(path);
3833         return ret;
3834 }
3835
3836 /*
3837  * when we free an extent, it is possible (and likely) that we free the last
3838  * delayed ref for that extent as well.  This searches the delayed ref tree for
3839  * a given extent, and if there are no other delayed refs to be processed, it
3840  * removes it from the tree.
3841  */
3842 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3843                                       struct btrfs_root *root, u64 bytenr)
3844 {
3845         struct btrfs_delayed_ref_head *head;
3846         struct btrfs_delayed_ref_root *delayed_refs;
3847         struct btrfs_delayed_ref_node *ref;
3848         struct rb_node *node;
3849         int ret;
3850
3851         delayed_refs = &trans->transaction->delayed_refs;
3852         spin_lock(&delayed_refs->lock);
3853         head = btrfs_find_delayed_ref_head(trans, bytenr);
3854         if (!head)
3855                 goto out;
3856
3857         node = rb_prev(&head->node.rb_node);
3858         if (!node)
3859                 goto out;
3860
3861         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
3862
3863         /* there are still entries for this ref, we can't drop it */
3864         if (ref->bytenr == bytenr)
3865                 goto out;
3866
3867         if (head->extent_op) {
3868                 if (!head->must_insert_reserved)
3869                         goto out;
3870                 kfree(head->extent_op);
3871                 head->extent_op = NULL;
3872         }
3873
3874         /*
3875          * waiting for the lock here would deadlock.  If someone else has it
3876          * locked they are already in the process of dropping it anyway
3877          */
3878         if (!mutex_trylock(&head->mutex))
3879                 goto out;
3880
3881         /*
3882          * at this point we have a head with no other entries.  Go
3883          * ahead and process it.
3884          */
3885         head->node.in_tree = 0;
3886         rb_erase(&head->node.rb_node, &delayed_refs->root);
3887
3888         delayed_refs->num_entries--;
3889
3890         /*
3891          * we don't take a ref on the node because we're removing it from the
3892          * tree, so we just steal the ref the tree was holding.
3893          */
3894         delayed_refs->num_heads--;
3895         if (list_empty(&head->cluster))
3896                 delayed_refs->num_heads_ready--;
3897
3898         list_del_init(&head->cluster);
3899         spin_unlock(&delayed_refs->lock);
3900
3901         ret = run_one_delayed_ref(trans, root->fs_info->tree_root,
3902                                   &head->node, head->extent_op,
3903                                   head->must_insert_reserved);
3904         BUG_ON(ret);
3905         btrfs_put_delayed_ref(&head->node);
3906         return 0;
3907 out:
3908         spin_unlock(&delayed_refs->lock);
3909         return 0;
3910 }
3911
3912 int btrfs_free_extent(struct btrfs_trans_handle *trans,
3913                       struct btrfs_root *root,
3914                       u64 bytenr, u64 num_bytes, u64 parent,
3915                       u64 root_objectid, u64 owner, u64 offset)
3916 {
3917         int ret;
3918
3919         /*
3920          * tree log blocks never actually go into the extent allocation
3921          * tree, just update pinning info and exit early.
3922          */
3923         if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
3924                 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
3925                 /* unlocks the pinned mutex */
3926                 btrfs_pin_extent(root, bytenr, num_bytes, 1);
3927                 ret = 0;
3928         } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
3929                 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
3930                                         parent, root_objectid, (int)owner,
3931                                         BTRFS_DROP_DELAYED_REF, NULL);
3932                 BUG_ON(ret);
3933                 ret = check_ref_cleanup(trans, root, bytenr);
3934                 BUG_ON(ret);
3935         } else {
3936                 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
3937                                         parent, root_objectid, owner,
3938                                         offset, BTRFS_DROP_DELAYED_REF, NULL);
3939                 BUG_ON(ret);
3940         }
3941         return ret;
3942 }
3943
3944 static u64 stripe_align(struct btrfs_root *root, u64 val)
3945 {
3946         u64 mask = ((u64)root->stripesize - 1);
3947         u64 ret = (val + mask) & ~mask;
3948         return ret;
3949 }
3950
3951 /*
3952  * when we wait for progress in the block group caching, its because
3953  * our allocation attempt failed at least once.  So, we must sleep
3954  * and let some progress happen before we try again.
3955  *
3956  * This function will sleep at least once waiting for new free space to
3957  * show up, and then it will check the block group free space numbers
3958  * for our min num_bytes.  Another option is to have it go ahead
3959  * and look in the rbtree for a free extent of a given size, but this
3960  * is a good start.
3961  */
3962 static noinline int
3963 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
3964                                 u64 num_bytes)
3965 {
3966         struct btrfs_caching_control *caching_ctl;
3967         DEFINE_WAIT(wait);
3968
3969         caching_ctl = get_caching_control(cache);
3970         if (!caching_ctl)
3971                 return 0;
3972
3973         wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
3974                    (cache->free_space >= num_bytes));
3975
3976         put_caching_control(caching_ctl);
3977         return 0;
3978 }
3979
3980 static noinline int
3981 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
3982 {
3983         struct btrfs_caching_control *caching_ctl;
3984         DEFINE_WAIT(wait);
3985
3986         caching_ctl = get_caching_control(cache);
3987         if (!caching_ctl)
3988                 return 0;
3989
3990         wait_event(caching_ctl->wait, block_group_cache_done(cache));
3991
3992         put_caching_control(caching_ctl);
3993         return 0;
3994 }
3995
3996 enum btrfs_loop_type {
3997         LOOP_CACHED_ONLY = 0,
3998         LOOP_CACHING_NOWAIT = 1,
3999         LOOP_CACHING_WAIT = 2,
4000         LOOP_ALLOC_CHUNK = 3,
4001         LOOP_NO_EMPTY_SIZE = 4,
4002 };
4003
4004 /*
4005  * walks the btree of allocated extents and find a hole of a given size.
4006  * The key ins is changed to record the hole:
4007  * ins->objectid == block start
4008  * ins->flags = BTRFS_EXTENT_ITEM_KEY
4009  * ins->offset == number of blocks
4010  * Any available blocks before search_start are skipped.
4011  */
4012 static noinline int find_free_extent(struct btrfs_trans_handle *trans,
4013                                      struct btrfs_root *orig_root,
4014                                      u64 num_bytes, u64 empty_size,
4015                                      u64 search_start, u64 search_end,
4016                                      u64 hint_byte, struct btrfs_key *ins,
4017                                      u64 exclude_start, u64 exclude_nr,
4018                                      int data)
4019 {
4020         int ret = 0;
4021         struct btrfs_root *root = orig_root->fs_info->extent_root;
4022         struct btrfs_free_cluster *last_ptr = NULL;
4023         struct btrfs_block_group_cache *block_group = NULL;
4024         int empty_cluster = 2 * 1024 * 1024;
4025         int allowed_chunk_alloc = 0;
4026         struct btrfs_space_info *space_info;
4027         int last_ptr_loop = 0;
4028         int loop = 0;
4029         bool found_uncached_bg = false;
4030         bool failed_cluster_refill = false;
4031         bool failed_alloc = false;
4032
4033         WARN_ON(num_bytes < root->sectorsize);
4034         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
4035         ins->objectid = 0;
4036         ins->offset = 0;
4037
4038         space_info = __find_space_info(root->fs_info, data);
4039
4040         if (orig_root->ref_cows || empty_size)
4041                 allowed_chunk_alloc = 1;
4042
4043         if (data & BTRFS_BLOCK_GROUP_METADATA) {
4044                 last_ptr = &root->fs_info->meta_alloc_cluster;
4045                 if (!btrfs_test_opt(root, SSD))
4046                         empty_cluster = 64 * 1024;
4047         }
4048
4049         if ((data & BTRFS_BLOCK_GROUP_DATA) && btrfs_test_opt(root, SSD)) {
4050                 last_ptr = &root->fs_info->data_alloc_cluster;
4051         }
4052
4053         if (last_ptr) {
4054                 spin_lock(&last_ptr->lock);
4055                 if (last_ptr->block_group)
4056                         hint_byte = last_ptr->window_start;
4057                 spin_unlock(&last_ptr->lock);
4058         }
4059
4060         search_start = max(search_start, first_logical_byte(root, 0));
4061         search_start = max(search_start, hint_byte);
4062
4063         if (!last_ptr)
4064                 empty_cluster = 0;
4065
4066         if (search_start == hint_byte) {
4067                 block_group = btrfs_lookup_block_group(root->fs_info,
4068                                                        search_start);
4069                 /*
4070                  * we don't want to use the block group if it doesn't match our
4071                  * allocation bits, or if its not cached.
4072                  */
4073                 if (block_group && block_group_bits(block_group, data) &&
4074                     block_group_cache_done(block_group)) {
4075                         down_read(&space_info->groups_sem);
4076                         if (list_empty(&block_group->list) ||
4077                             block_group->ro) {
4078                                 /*
4079                                  * someone is removing this block group,
4080                                  * we can't jump into the have_block_group
4081                                  * target because our list pointers are not
4082                                  * valid
4083                                  */
4084                                 btrfs_put_block_group(block_group);
4085                                 up_read(&space_info->groups_sem);
4086                         } else
4087                                 goto have_block_group;
4088                 } else if (block_group) {
4089                         btrfs_put_block_group(block_group);
4090                 }
4091         }
4092
4093 search:
4094         down_read(&space_info->groups_sem);
4095         list_for_each_entry(block_group, &space_info->block_groups, list) {
4096                 u64 offset;
4097                 int cached;
4098
4099                 atomic_inc(&block_group->count);
4100                 search_start = block_group->key.objectid;
4101
4102 have_block_group:
4103                 if (unlikely(block_group->cached == BTRFS_CACHE_NO)) {
4104                         /*
4105                          * we want to start caching kthreads, but not too many
4106                          * right off the bat so we don't overwhelm the system,
4107                          * so only start them if there are less than 2 and we're
4108                          * in the initial allocation phase.
4109                          */
4110                         if (loop > LOOP_CACHING_NOWAIT ||
4111                             atomic_read(&space_info->caching_threads) < 2) {
4112                                 ret = cache_block_group(block_group);
4113                                 BUG_ON(ret);
4114                         }
4115                 }
4116
4117                 cached = block_group_cache_done(block_group);
4118                 if (unlikely(!cached)) {
4119                         found_uncached_bg = true;
4120
4121                         /* if we only want cached bgs, loop */
4122                         if (loop == LOOP_CACHED_ONLY)
4123                                 goto loop;
4124                 }
4125
4126                 if (unlikely(block_group->ro))
4127                         goto loop;
4128
4129                 /*
4130                  * Ok we want to try and use the cluster allocator, so lets look
4131                  * there, unless we are on LOOP_NO_EMPTY_SIZE, since we will
4132                  * have tried the cluster allocator plenty of times at this
4133                  * point and not have found anything, so we are likely way too
4134                  * fragmented for the clustering stuff to find anything, so lets
4135                  * just skip it and let the allocator find whatever block it can
4136                  * find
4137                  */
4138                 if (last_ptr && loop < LOOP_NO_EMPTY_SIZE) {
4139                         /*
4140                          * the refill lock keeps out other
4141                          * people trying to start a new cluster
4142                          */
4143                         spin_lock(&last_ptr->refill_lock);
4144                         if (last_ptr->block_group &&
4145                             (last_ptr->block_group->ro ||
4146                             !block_group_bits(last_ptr->block_group, data))) {
4147                                 offset = 0;
4148                                 goto refill_cluster;
4149                         }
4150
4151                         offset = btrfs_alloc_from_cluster(block_group, last_ptr,
4152                                                  num_bytes, search_start);
4153                         if (offset) {
4154                                 /* we have a block, we're done */
4155                                 spin_unlock(&last_ptr->refill_lock);
4156                                 goto checks;
4157                         }
4158
4159                         spin_lock(&last_ptr->lock);
4160                         /*
4161                          * whoops, this cluster doesn't actually point to
4162                          * this block group.  Get a ref on the block
4163                          * group is does point to and try again
4164                          */
4165                         if (!last_ptr_loop && last_ptr->block_group &&
4166                             last_ptr->block_group != block_group) {
4167
4168                                 btrfs_put_block_group(block_group);
4169                                 block_group = last_ptr->block_group;
4170                                 atomic_inc(&block_group->count);
4171                                 spin_unlock(&last_ptr->lock);
4172                                 spin_unlock(&last_ptr->refill_lock);
4173
4174                                 last_ptr_loop = 1;
4175                                 search_start = block_group->key.objectid;
4176                                 /*
4177                                  * we know this block group is properly
4178                                  * in the list because
4179                                  * btrfs_remove_block_group, drops the
4180                                  * cluster before it removes the block
4181                                  * group from the list
4182                                  */
4183                                 goto have_block_group;
4184                         }
4185                         spin_unlock(&last_ptr->lock);
4186 refill_cluster:
4187                         /*
4188                          * this cluster didn't work out, free it and
4189                          * start over
4190                          */
4191                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
4192
4193                         last_ptr_loop = 0;
4194
4195                         /* allocate a cluster in this block group */
4196                         ret = btrfs_find_space_cluster(trans, root,
4197                                                block_group, last_ptr,
4198                                                offset, num_bytes,
4199                                                empty_cluster + empty_size);
4200                         if (ret == 0) {
4201                                 /*
4202                                  * now pull our allocation out of this
4203                                  * cluster
4204                                  */
4205                                 offset = btrfs_alloc_from_cluster(block_group,
4206                                                   last_ptr, num_bytes,
4207                                                   search_start);
4208                                 if (offset) {
4209                                         /* we found one, proceed */
4210                                         spin_unlock(&last_ptr->refill_lock);
4211                                         goto checks;
4212                                 }
4213                         } else if (!cached && loop > LOOP_CACHING_NOWAIT
4214                                    && !failed_cluster_refill) {
4215                                 spin_unlock(&last_ptr->refill_lock);
4216
4217                                 failed_cluster_refill = true;
4218                                 wait_block_group_cache_progress(block_group,
4219                                        num_bytes + empty_cluster + empty_size);
4220                                 goto have_block_group;
4221                         }
4222
4223                         /*
4224                          * at this point we either didn't find a cluster
4225                          * or we weren't able to allocate a block from our
4226                          * cluster.  Free the cluster we've been trying
4227                          * to use, and go to the next block group
4228                          */
4229                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
4230                         spin_unlock(&last_ptr->refill_lock);
4231                         goto loop;
4232                 }
4233
4234                 offset = btrfs_find_space_for_alloc(block_group, search_start,
4235                                                     num_bytes, empty_size);
4236                 /*
4237                  * If we didn't find a chunk, and we haven't failed on this
4238                  * block group before, and this block group is in the middle of
4239                  * caching and we are ok with waiting, then go ahead and wait
4240                  * for progress to be made, and set failed_alloc to true.
4241                  *
4242                  * If failed_alloc is true then we've already waited on this
4243                  * block group once and should move on to the next block group.
4244                  */
4245                 if (!offset && !failed_alloc && !cached &&
4246                     loop > LOOP_CACHING_NOWAIT) {
4247                         wait_block_group_cache_progress(block_group,
4248                                                 num_bytes + empty_size);
4249                         failed_alloc = true;
4250                         goto have_block_group;
4251                 } else if (!offset) {
4252                         goto loop;
4253                 }
4254 checks:
4255                 search_start = stripe_align(root, offset);
4256                 /* move on to the next group */
4257                 if (search_start + num_bytes >= search_end) {
4258                         btrfs_add_free_space(block_group, offset, num_bytes);
4259                         goto loop;
4260                 }
4261
4262                 /* move on to the next group */
4263                 if (search_start + num_bytes >
4264                     block_group->key.objectid + block_group->key.offset) {
4265                         btrfs_add_free_space(block_group, offset, num_bytes);
4266                         goto loop;
4267                 }
4268
4269                 if (exclude_nr > 0 &&
4270                     (search_start + num_bytes > exclude_start &&
4271                      search_start < exclude_start + exclude_nr)) {
4272                         search_start = exclude_start + exclude_nr;
4273
4274                         btrfs_add_free_space(block_group, offset, num_bytes);
4275                         /*
4276                          * if search_start is still in this block group
4277                          * then we just re-search this block group
4278                          */
4279                         if (search_start >= block_group->key.objectid &&
4280                             search_start < (block_group->key.objectid +
4281                                             block_group->key.offset))
4282                                 goto have_block_group;
4283                         goto loop;
4284                 }
4285
4286                 ins->objectid = search_start;
4287                 ins->offset = num_bytes;
4288
4289                 if (offset < search_start)
4290                         btrfs_add_free_space(block_group, offset,
4291                                              search_start - offset);
4292                 BUG_ON(offset > search_start);
4293
4294                 update_reserved_extents(block_group, num_bytes, 1);
4295
4296                 /* we are all good, lets return */
4297                 break;
4298 loop:
4299                 failed_cluster_refill = false;
4300                 failed_alloc = false;
4301                 btrfs_put_block_group(block_group);
4302         }
4303         up_read(&space_info->groups_sem);
4304
4305         /* LOOP_CACHED_ONLY, only search fully cached block groups
4306          * LOOP_CACHING_NOWAIT, search partially cached block groups, but
4307          *                      dont wait foR them to finish caching
4308          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
4309          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
4310          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
4311          *                      again
4312          */
4313         if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE &&
4314             (found_uncached_bg || empty_size || empty_cluster ||
4315              allowed_chunk_alloc)) {
4316                 if (found_uncached_bg) {
4317                         found_uncached_bg = false;
4318                         if (loop < LOOP_CACHING_WAIT) {
4319                                 loop++;
4320                                 goto search;
4321                         }
4322                 }
4323
4324                 if (loop == LOOP_ALLOC_CHUNK) {
4325                         empty_size = 0;
4326                         empty_cluster = 0;
4327                 }
4328
4329                 if (allowed_chunk_alloc) {
4330                         ret = do_chunk_alloc(trans, root, num_bytes +
4331                                              2 * 1024 * 1024, data, 1);
4332                         allowed_chunk_alloc = 0;
4333                 } else {
4334                         space_info->force_alloc = 1;
4335                 }
4336
4337                 if (loop < LOOP_NO_EMPTY_SIZE) {
4338                         loop++;
4339                         goto search;
4340                 }
4341                 ret = -ENOSPC;
4342         } else if (!ins->objectid) {
4343                 ret = -ENOSPC;
4344         }
4345
4346         /* we found what we needed */
4347         if (ins->objectid) {
4348                 if (!(data & BTRFS_BLOCK_GROUP_DATA))
4349                         trans->block_group = block_group->key.objectid;
4350
4351                 btrfs_put_block_group(block_group);
4352                 ret = 0;
4353         }
4354
4355         return ret;
4356 }
4357
4358 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
4359                             int dump_block_groups)
4360 {
4361         struct btrfs_block_group_cache *cache;
4362
4363         spin_lock(&info->lock);
4364         printk(KERN_INFO "space_info has %llu free, is %sfull\n",
4365                (unsigned long long)(info->total_bytes - info->bytes_used -
4366                                     info->bytes_pinned - info->bytes_reserved -
4367                                     info->bytes_super),
4368                (info->full) ? "" : "not ");
4369         printk(KERN_INFO "space_info total=%llu, pinned=%llu, delalloc=%llu,"
4370                " may_use=%llu, used=%llu, root=%llu, super=%llu, reserved=%llu"
4371                "\n",
4372                (unsigned long long)info->total_bytes,
4373                (unsigned long long)info->bytes_pinned,
4374                (unsigned long long)info->bytes_delalloc,
4375                (unsigned long long)info->bytes_may_use,
4376                (unsigned long long)info->bytes_used,
4377                (unsigned long long)info->bytes_root,
4378                (unsigned long long)info->bytes_super,
4379                (unsigned long long)info->bytes_reserved);
4380         spin_unlock(&info->lock);
4381
4382         if (!dump_block_groups)
4383                 return;
4384
4385         down_read(&info->groups_sem);
4386         list_for_each_entry(cache, &info->block_groups, list) {
4387                 spin_lock(&cache->lock);
4388                 printk(KERN_INFO "block group %llu has %llu bytes, %llu used "
4389                        "%llu pinned %llu reserved\n",
4390                        (unsigned long long)cache->key.objectid,
4391                        (unsigned long long)cache->key.offset,
4392                        (unsigned long long)btrfs_block_group_used(&cache->item),
4393                        (unsigned long long)cache->pinned,
4394                        (unsigned long long)cache->reserved);
4395                 btrfs_dump_free_space(cache, bytes);
4396                 spin_unlock(&cache->lock);
4397         }
4398         up_read(&info->groups_sem);
4399 }
4400
4401 int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
4402                          struct btrfs_root *root,
4403                          u64 num_bytes, u64 min_alloc_size,
4404                          u64 empty_size, u64 hint_byte,
4405                          u64 search_end, struct btrfs_key *ins,
4406                          u64 data)
4407 {
4408         int ret;
4409         u64 search_start = 0;
4410         struct btrfs_fs_info *info = root->fs_info;
4411
4412         data = btrfs_get_alloc_profile(root, data);
4413 again:
4414         /*
4415          * the only place that sets empty_size is btrfs_realloc_node, which
4416          * is not called recursively on allocations
4417          */
4418         if (empty_size || root->ref_cows) {
4419                 if (!(data & BTRFS_BLOCK_GROUP_METADATA)) {
4420                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
4421                                      2 * 1024 * 1024,
4422                                      BTRFS_BLOCK_GROUP_METADATA |
4423                                      (info->metadata_alloc_profile &
4424                                       info->avail_metadata_alloc_bits), 0);
4425                 }
4426                 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
4427                                      num_bytes + 2 * 1024 * 1024, data, 0);
4428         }
4429
4430         WARN_ON(num_bytes < root->sectorsize);
4431         ret = find_free_extent(trans, root, num_bytes, empty_size,
4432                                search_start, search_end, hint_byte, ins,
4433                                trans->alloc_exclude_start,
4434                                trans->alloc_exclude_nr, data);
4435
4436         if (ret == -ENOSPC && num_bytes > min_alloc_size) {
4437                 num_bytes = num_bytes >> 1;
4438                 num_bytes = num_bytes & ~(root->sectorsize - 1);
4439                 num_bytes = max(num_bytes, min_alloc_size);
4440                 do_chunk_alloc(trans, root->fs_info->extent_root,
4441                                num_bytes, data, 1);
4442                 goto again;
4443         }
4444         if (ret == -ENOSPC) {
4445                 struct btrfs_space_info *sinfo;
4446
4447                 sinfo = __find_space_info(root->fs_info, data);
4448                 printk(KERN_ERR "btrfs allocation failed flags %llu, "
4449                        "wanted %llu\n", (unsigned long long)data,
4450                        (unsigned long long)num_bytes);
4451                 dump_space_info(sinfo, num_bytes, 1);
4452         }
4453
4454         return ret;
4455 }
4456
4457 int btrfs_free_reserved_extent(struct btrfs_root *root, u64 start, u64 len)
4458 {
4459         struct btrfs_block_group_cache *cache;
4460         int ret = 0;
4461
4462         cache = btrfs_lookup_block_group(root->fs_info, start);
4463         if (!cache) {
4464                 printk(KERN_ERR "Unable to find block group for %llu\n",
4465                        (unsigned long long)start);
4466                 return -ENOSPC;
4467         }
4468
4469         ret = btrfs_discard_extent(root, start, len);
4470
4471         btrfs_add_free_space(cache, start, len);
4472         update_reserved_extents(cache, len, 0);
4473         btrfs_put_block_group(cache);
4474
4475         return ret;
4476 }
4477
4478 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4479                                       struct btrfs_root *root,
4480                                       u64 parent, u64 root_objectid,
4481                                       u64 flags, u64 owner, u64 offset,
4482                                       struct btrfs_key *ins, int ref_mod)
4483 {
4484         int ret;
4485         struct btrfs_fs_info *fs_info = root->fs_info;
4486         struct btrfs_extent_item *extent_item;
4487         struct btrfs_extent_inline_ref *iref;
4488         struct btrfs_path *path;
4489         struct extent_buffer *leaf;
4490         int type;
4491         u32 size;
4492
4493         if (parent > 0)
4494                 type = BTRFS_SHARED_DATA_REF_KEY;
4495         else
4496                 type = BTRFS_EXTENT_DATA_REF_KEY;
4497
4498         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
4499
4500         path = btrfs_alloc_path();
4501         BUG_ON(!path);
4502
4503         path->leave_spinning = 1;
4504         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4505                                       ins, size);
4506         BUG_ON(ret);
4507
4508         leaf = path->nodes[0];
4509         extent_item = btrfs_item_ptr(leaf, path->slots[0],
4510                                      struct btrfs_extent_item);
4511         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4512         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4513         btrfs_set_extent_flags(leaf, extent_item,
4514                                flags | BTRFS_EXTENT_FLAG_DATA);
4515
4516         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4517         btrfs_set_extent_inline_ref_type(leaf, iref, type);
4518         if (parent > 0) {
4519                 struct btrfs_shared_data_ref *ref;
4520                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4521                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4522                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4523         } else {
4524                 struct btrfs_extent_data_ref *ref;
4525                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4526                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4527                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4528                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4529                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4530         }
4531
4532         btrfs_mark_buffer_dirty(path->nodes[0]);
4533         btrfs_free_path(path);
4534
4535         ret = update_block_group(trans, root, ins->objectid, ins->offset,
4536                                  1, 0);
4537         if (ret) {
4538                 printk(KERN_ERR "btrfs update block group failed for %llu "
4539                        "%llu\n", (unsigned long long)ins->objectid,
4540                        (unsigned long long)ins->offset);
4541                 BUG();
4542         }
4543         return ret;
4544 }
4545
4546 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4547                                      struct btrfs_root *root,
4548                                      u64 parent, u64 root_objectid,
4549                                      u64 flags, struct btrfs_disk_key *key,
4550                                      int level, struct btrfs_key *ins)
4551 {
4552         int ret;
4553         struct btrfs_fs_info *fs_info = root->fs_info;
4554         struct btrfs_extent_item *extent_item;
4555         struct btrfs_tree_block_info *block_info;
4556         struct btrfs_extent_inline_ref *iref;
4557         struct btrfs_path *path;
4558         struct extent_buffer *leaf;
4559         u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
4560
4561         path = btrfs_alloc_path();
4562         BUG_ON(!path);
4563
4564         path->leave_spinning = 1;
4565         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4566                                       ins, size);
4567         BUG_ON(ret);
4568
4569         leaf = path->nodes[0];
4570         extent_item = btrfs_item_ptr(leaf, path->slots[0],
4571                                      struct btrfs_extent_item);
4572         btrfs_set_extent_refs(leaf, extent_item, 1);
4573         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4574         btrfs_set_extent_flags(leaf, extent_item,
4575                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4576         block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4577
4578         btrfs_set_tree_block_key(leaf, block_info, key);
4579         btrfs_set_tree_block_level(leaf, block_info, level);
4580
4581         iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4582         if (parent > 0) {
4583                 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4584                 btrfs_set_extent_inline_ref_type(leaf, iref,
4585                                                  BTRFS_SHARED_BLOCK_REF_KEY);
4586                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4587         } else {
4588                 btrfs_set_extent_inline_ref_type(leaf, iref,
4589                                                  BTRFS_TREE_BLOCK_REF_KEY);
4590                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
4591         }
4592
4593         btrfs_mark_buffer_dirty(leaf);
4594         btrfs_free_path(path);
4595
4596         ret = update_block_group(trans, root, ins->objectid, ins->offset,
4597                                  1, 0);
4598         if (ret) {
4599                 printk(KERN_ERR "btrfs update block group failed for %llu "
4600                        "%llu\n", (unsigned long long)ins->objectid,
4601                        (unsigned long long)ins->offset);
4602                 BUG();
4603         }
4604         return ret;
4605 }
4606
4607 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4608                                      struct btrfs_root *root,
4609                                      u64 root_objectid, u64 owner,
4610                                      u64 offset, struct btrfs_key *ins)
4611 {
4612         int ret;
4613
4614         BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
4615
4616         ret = btrfs_add_delayed_data_ref(trans, ins->objectid, ins->offset,
4617                                          0, root_objectid, owner, offset,
4618                                          BTRFS_ADD_DELAYED_EXTENT, NULL);
4619         return ret;
4620 }
4621
4622 /*
4623  * this is used by the tree logging recovery code.  It records that
4624  * an extent has been allocated and makes sure to clear the free
4625  * space cache bits as well
4626  */
4627 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4628                                    struct btrfs_root *root,
4629                                    u64 root_objectid, u64 owner, u64 offset,
4630                                    struct btrfs_key *ins)
4631 {
4632         int ret;
4633         struct btrfs_block_group_cache *block_group;
4634         struct btrfs_caching_control *caching_ctl;
4635         u64 start = ins->objectid;
4636         u64 num_bytes = ins->offset;
4637
4638         block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
4639         cache_block_group(block_group);
4640         caching_ctl = get_caching_control(block_group);
4641
4642         if (!caching_ctl) {
4643                 BUG_ON(!block_group_cache_done(block_group));
4644                 ret = btrfs_remove_free_space(block_group, start, num_bytes);
4645                 BUG_ON(ret);
4646         } else {
4647                 mutex_lock(&caching_ctl->mutex);
4648
4649                 if (start >= caching_ctl->progress) {
4650                         ret = add_excluded_extent(root, start, num_bytes);
4651                         BUG_ON(ret);
4652                 } else if (start + num_bytes <= caching_ctl->progress) {
4653                         ret = btrfs_remove_free_space(block_group,
4654                                                       start, num_bytes);
4655                         BUG_ON(ret);
4656                 } else {
4657                         num_bytes = caching_ctl->progress - start;
4658                         ret = btrfs_remove_free_space(block_group,
4659                                                       start, num_bytes);
4660                         BUG_ON(ret);
4661
4662                         start = caching_ctl->progress;
4663                         num_bytes = ins->objectid + ins->offset -
4664                                     caching_ctl->progress;
4665                         ret = add_excluded_extent(root, start, num_bytes);
4666                         BUG_ON(ret);
4667                 }
4668
4669                 mutex_unlock(&caching_ctl->mutex);
4670                 put_caching_control(caching_ctl);
4671         }
4672
4673         update_reserved_extents(block_group, ins->offset, 1);
4674         btrfs_put_block_group(block_group);
4675         ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
4676                                          0, owner, offset, ins, 1);
4677         return ret;
4678 }
4679
4680 /*
4681  * finds a free extent and does all the dirty work required for allocation
4682  * returns the key for the extent through ins, and a tree buffer for
4683  * the first block of the extent through buf.
4684  *
4685  * returns 0 if everything worked, non-zero otherwise.
4686  */
4687 static int alloc_tree_block(struct btrfs_trans_handle *trans,
4688                             struct btrfs_root *root,
4689                             u64 num_bytes, u64 parent, u64 root_objectid,
4690                             struct btrfs_disk_key *key, int level,
4691                             u64 empty_size, u64 hint_byte, u64 search_end,
4692                             struct btrfs_key *ins)
4693 {
4694         int ret;
4695         u64 flags = 0;
4696
4697         ret = btrfs_reserve_extent(trans, root, num_bytes, num_bytes,
4698                                    empty_size, hint_byte, search_end,
4699                                    ins, 0);
4700         if (ret)
4701                 return ret;
4702
4703         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4704                 if (parent == 0)
4705                         parent = ins->objectid;
4706                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4707         } else
4708                 BUG_ON(parent > 0);
4709
4710         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
4711                 struct btrfs_delayed_extent_op *extent_op;
4712                 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
4713                 BUG_ON(!extent_op);
4714                 if (key)
4715                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
4716                 else
4717                         memset(&extent_op->key, 0, sizeof(extent_op->key));
4718                 extent_op->flags_to_set = flags;
4719                 extent_op->update_key = 1;
4720                 extent_op->update_flags = 1;
4721                 extent_op->is_data = 0;
4722
4723                 ret = btrfs_add_delayed_tree_ref(trans, ins->objectid,
4724                                         ins->offset, parent, root_objectid,
4725                                         level, BTRFS_ADD_DELAYED_EXTENT,
4726                                         extent_op);
4727                 BUG_ON(ret);
4728         }
4729         return ret;
4730 }
4731
4732 struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
4733                                             struct btrfs_root *root,
4734                                             u64 bytenr, u32 blocksize,
4735                                             int level)
4736 {
4737         struct extent_buffer *buf;
4738
4739         buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
4740         if (!buf)
4741                 return ERR_PTR(-ENOMEM);
4742         btrfs_set_header_generation(buf, trans->transid);
4743         btrfs_set_buffer_lockdep_class(buf, level);
4744         btrfs_tree_lock(buf);
4745         clean_tree_block(trans, root, buf);
4746
4747         btrfs_set_lock_blocking(buf);
4748         btrfs_set_buffer_uptodate(buf);
4749
4750         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4751                 set_extent_dirty(&root->dirty_log_pages, buf->start,
4752                          buf->start + buf->len - 1, GFP_NOFS);
4753         } else {
4754                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
4755                          buf->start + buf->len - 1, GFP_NOFS);
4756         }
4757         trans->blocks_used++;
4758         /* this returns a buffer locked for blocking */
4759         return buf;
4760 }
4761
4762 /*
4763  * helper function to allocate a block for a given tree
4764  * returns the tree buffer or NULL.
4765  */
4766 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
4767                                         struct btrfs_root *root, u32 blocksize,
4768                                         u64 parent, u64 root_objectid,
4769                                         struct btrfs_disk_key *key, int level,
4770                                         u64 hint, u64 empty_size)
4771 {
4772         struct btrfs_key ins;
4773         int ret;
4774         struct extent_buffer *buf;
4775
4776         ret = alloc_tree_block(trans, root, blocksize, parent, root_objectid,
4777                                key, level, empty_size, hint, (u64)-1, &ins);
4778         if (ret) {
4779                 BUG_ON(ret > 0);
4780                 return ERR_PTR(ret);
4781         }
4782
4783         buf = btrfs_init_new_buffer(trans, root, ins.objectid,
4784                                     blocksize, level);
4785         return buf;
4786 }
4787
4788 struct walk_control {
4789         u64 refs[BTRFS_MAX_LEVEL];
4790         u64 flags[BTRFS_MAX_LEVEL];
4791         struct btrfs_key update_progress;
4792         int stage;
4793         int level;
4794         int shared_level;
4795         int update_ref;
4796         int keep_locks;
4797         int reada_slot;
4798         int reada_count;
4799 };
4800
4801 #define DROP_REFERENCE  1
4802 #define UPDATE_BACKREF  2
4803
4804 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
4805                                      struct btrfs_root *root,
4806                                      struct walk_control *wc,
4807                                      struct btrfs_path *path)
4808 {
4809         u64 bytenr;
4810         u64 generation;
4811         u64 refs;
4812         u64 last = 0;
4813         u32 nritems;
4814         u32 blocksize;
4815         struct btrfs_key key;
4816         struct extent_buffer *eb;
4817         int ret;
4818         int slot;
4819         int nread = 0;
4820
4821         if (path->slots[wc->level] < wc->reada_slot) {
4822                 wc->reada_count = wc->reada_count * 2 / 3;
4823                 wc->reada_count = max(wc->reada_count, 2);
4824         } else {
4825                 wc->reada_count = wc->reada_count * 3 / 2;
4826                 wc->reada_count = min_t(int, wc->reada_count,
4827                                         BTRFS_NODEPTRS_PER_BLOCK(root));
4828         }
4829
4830         eb = path->nodes[wc->level];
4831         nritems = btrfs_header_nritems(eb);
4832         blocksize = btrfs_level_size(root, wc->level - 1);
4833
4834         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
4835                 if (nread >= wc->reada_count)
4836                         break;
4837
4838                 cond_resched();
4839                 bytenr = btrfs_node_blockptr(eb, slot);
4840                 generation = btrfs_node_ptr_generation(eb, slot);
4841
4842                 if (slot == path->slots[wc->level])
4843                         goto reada;
4844
4845                 if (wc->stage == UPDATE_BACKREF &&
4846                     generation <= root->root_key.offset)
4847                         continue;
4848
4849                 if (wc->stage == DROP_REFERENCE) {
4850                         ret = btrfs_lookup_extent_info(trans, root,
4851                                                 bytenr, blocksize,
4852                                                 &refs, NULL);
4853                         BUG_ON(ret);
4854                         BUG_ON(refs == 0);
4855                         if (refs == 1)
4856                                 goto reada;
4857
4858                         if (!wc->update_ref ||
4859                             generation <= root->root_key.offset)
4860                                 continue;
4861                         btrfs_node_key_to_cpu(eb, &key, slot);
4862                         ret = btrfs_comp_cpu_keys(&key,
4863                                                   &wc->update_progress);
4864                         if (ret < 0)
4865                                 continue;
4866                 }
4867 reada:
4868                 ret = readahead_tree_block(root, bytenr, blocksize,
4869                                            generation);
4870                 if (ret)
4871                         break;
4872                 last = bytenr + blocksize;
4873                 nread++;
4874         }
4875         wc->reada_slot = slot;
4876 }
4877
4878 /*
4879  * hepler to process tree block while walking down the tree.
4880  *
4881  * when wc->stage == UPDATE_BACKREF, this function updates
4882  * back refs for pointers in the block.
4883  *
4884  * NOTE: return value 1 means we should stop walking down.
4885  */
4886 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
4887                                    struct btrfs_root *root,
4888                                    struct btrfs_path *path,
4889                                    struct walk_control *wc)
4890 {
4891         int level = wc->level;
4892         struct extent_buffer *eb = path->nodes[level];
4893         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
4894         int ret;
4895
4896         if (wc->stage == UPDATE_BACKREF &&
4897             btrfs_header_owner(eb) != root->root_key.objectid)
4898                 return 1;
4899
4900         /*
4901          * when reference count of tree block is 1, it won't increase
4902          * again. once full backref flag is set, we never clear it.
4903          */
4904         if ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
4905             (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag))) {
4906                 BUG_ON(!path->locks[level]);
4907                 ret = btrfs_lookup_extent_info(trans, root,
4908                                                eb->start, eb->len,
4909                                                &wc->refs[level],
4910                                                &wc->flags[level]);
4911                 BUG_ON(ret);
4912                 BUG_ON(wc->refs[level] == 0);
4913         }
4914
4915         if (wc->stage == DROP_REFERENCE) {
4916                 if (wc->refs[level] > 1)
4917                         return 1;
4918
4919                 if (path->locks[level] && !wc->keep_locks) {
4920                         btrfs_tree_unlock(eb);
4921                         path->locks[level] = 0;
4922                 }
4923                 return 0;
4924         }
4925
4926         /* wc->stage == UPDATE_BACKREF */
4927         if (!(wc->flags[level] & flag)) {
4928                 BUG_ON(!path->locks[level]);
4929                 ret = btrfs_inc_ref(trans, root, eb, 1);
4930                 BUG_ON(ret);
4931                 ret = btrfs_dec_ref(trans, root, eb, 0);
4932                 BUG_ON(ret);
4933                 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
4934                                                   eb->len, flag, 0);
4935                 BUG_ON(ret);
4936                 wc->flags[level] |= flag;
4937         }
4938
4939         /*
4940          * the block is shared by multiple trees, so it's not good to
4941          * keep the tree lock
4942          */
4943         if (path->locks[level] && level > 0) {
4944                 btrfs_tree_unlock(eb);
4945                 path->locks[level] = 0;
4946         }
4947         return 0;
4948 }
4949
4950 /*
4951  * hepler to process tree block pointer.
4952  *
4953  * when wc->stage == DROP_REFERENCE, this function checks
4954  * reference count of the block pointed to. if the block
4955  * is shared and we need update back refs for the subtree
4956  * rooted at the block, this function changes wc->stage to
4957  * UPDATE_BACKREF. if the block is shared and there is no
4958  * need to update back, this function drops the reference
4959  * to the block.
4960  *
4961  * NOTE: return value 1 means we should stop walking down.
4962  */
4963 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
4964                                  struct btrfs_root *root,
4965                                  struct btrfs_path *path,
4966                                  struct walk_control *wc)
4967 {
4968         u64 bytenr;
4969         u64 generation;
4970         u64 parent;
4971         u32 blocksize;
4972         struct btrfs_key key;
4973         struct extent_buffer *next;
4974         int level = wc->level;
4975         int reada = 0;
4976         int ret = 0;
4977
4978         generation = btrfs_node_ptr_generation(path->nodes[level],
4979                                                path->slots[level]);
4980         /*
4981          * if the lower level block was created before the snapshot
4982          * was created, we know there is no need to update back refs
4983          * for the subtree
4984          */
4985         if (wc->stage == UPDATE_BACKREF &&
4986             generation <= root->root_key.offset)
4987                 return 1;
4988
4989         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
4990         blocksize = btrfs_level_size(root, level - 1);
4991
4992         next = btrfs_find_tree_block(root, bytenr, blocksize);
4993         if (!next) {
4994                 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
4995                 reada = 1;
4996         }
4997         btrfs_tree_lock(next);
4998         btrfs_set_lock_blocking(next);
4999
5000         if (wc->stage == DROP_REFERENCE) {
5001                 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
5002                                                &wc->refs[level - 1],
5003                                                &wc->flags[level - 1]);
5004                 BUG_ON(ret);
5005                 BUG_ON(wc->refs[level - 1] == 0);
5006
5007                 if (wc->refs[level - 1] > 1) {
5008                         if (!wc->update_ref ||
5009                             generation <= root->root_key.offset)
5010                                 goto skip;
5011
5012                         btrfs_node_key_to_cpu(path->nodes[level], &key,
5013                                               path->slots[level]);
5014                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
5015                         if (ret < 0)
5016                                 goto skip;
5017
5018                         wc->stage = UPDATE_BACKREF;
5019                         wc->shared_level = level - 1;
5020                 }
5021         }
5022
5023         if (!btrfs_buffer_uptodate(next, generation)) {
5024                 btrfs_tree_unlock(next);
5025                 free_extent_buffer(next);
5026                 next = NULL;
5027         }
5028
5029         if (!next) {
5030                 if (reada && level == 1)
5031                         reada_walk_down(trans, root, wc, path);
5032                 next = read_tree_block(root, bytenr, blocksize, generation);
5033                 btrfs_tree_lock(next);
5034                 btrfs_set_lock_blocking(next);
5035         }
5036
5037         level--;
5038         BUG_ON(level != btrfs_header_level(next));
5039         path->nodes[level] = next;
5040         path->slots[level] = 0;
5041         path->locks[level] = 1;
5042         wc->level = level;
5043         if (wc->level == 1)
5044                 wc->reada_slot = 0;
5045         return 0;
5046 skip:
5047         wc->refs[level - 1] = 0;
5048         wc->flags[level - 1] = 0;
5049
5050         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5051                 parent = path->nodes[level]->start;
5052         } else {
5053                 BUG_ON(root->root_key.objectid !=
5054                        btrfs_header_owner(path->nodes[level]));
5055                 parent = 0;
5056         }
5057
5058         ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
5059                                 root->root_key.objectid, level - 1, 0);
5060         BUG_ON(ret);
5061
5062         btrfs_tree_unlock(next);
5063         free_extent_buffer(next);
5064         return 1;
5065 }
5066
5067 /*
5068  * hepler to process tree block while walking up the tree.
5069  *
5070  * when wc->stage == DROP_REFERENCE, this function drops
5071  * reference count on the block.
5072  *
5073  * when wc->stage == UPDATE_BACKREF, this function changes
5074  * wc->stage back to DROP_REFERENCE if we changed wc->stage
5075  * to UPDATE_BACKREF previously while processing the block.
5076  *
5077  * NOTE: return value 1 means we should stop walking up.
5078  */
5079 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5080                                  struct btrfs_root *root,
5081                                  struct btrfs_path *path,
5082                                  struct walk_control *wc)
5083 {
5084         int ret = 0;
5085         int level = wc->level;
5086         struct extent_buffer *eb = path->nodes[level];
5087         u64 parent = 0;
5088
5089         if (wc->stage == UPDATE_BACKREF) {
5090                 BUG_ON(wc->shared_level < level);
5091                 if (level < wc->shared_level)
5092                         goto out;
5093
5094                 ret = find_next_key(path, level + 1, &wc->update_progress);
5095                 if (ret > 0)
5096                         wc->update_ref = 0;
5097
5098                 wc->stage = DROP_REFERENCE;
5099                 wc->shared_level = -1;
5100                 path->slots[level] = 0;
5101
5102                 /*
5103                  * check reference count again if the block isn't locked.
5104                  * we should start walking down the tree again if reference
5105                  * count is one.
5106                  */
5107                 if (!path->locks[level]) {
5108                         BUG_ON(level == 0);
5109                         btrfs_tree_lock(eb);
5110                         btrfs_set_lock_blocking(eb);
5111                         path->locks[level] = 1;
5112
5113                         ret = btrfs_lookup_extent_info(trans, root,
5114                                                        eb->start, eb->len,
5115                                                        &wc->refs[level],
5116                                                        &wc->flags[level]);
5117                         BUG_ON(ret);
5118                         BUG_ON(wc->refs[level] == 0);
5119                         if (wc->refs[level] == 1) {
5120                                 btrfs_tree_unlock(eb);
5121                                 path->locks[level] = 0;
5122                                 return 1;
5123                         }
5124                 }
5125         }
5126
5127         /* wc->stage == DROP_REFERENCE */
5128         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5129
5130         if (wc->refs[level] == 1) {
5131                 if (level == 0) {
5132                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5133                                 ret = btrfs_dec_ref(trans, root, eb, 1);
5134                         else
5135                                 ret = btrfs_dec_ref(trans, root, eb, 0);
5136                         BUG_ON(ret);
5137                 }
5138                 /* make block locked assertion in clean_tree_block happy */
5139                 if (!path->locks[level] &&
5140                     btrfs_header_generation(eb) == trans->transid) {
5141                         btrfs_tree_lock(eb);
5142                         btrfs_set_lock_blocking(eb);
5143                         path->locks[level] = 1;
5144                 }
5145                 clean_tree_block(trans, root, eb);
5146         }
5147
5148         if (eb == root->node) {
5149                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5150                         parent = eb->start;
5151                 else
5152                         BUG_ON(root->root_key.objectid !=
5153                                btrfs_header_owner(eb));
5154         } else {
5155                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5156                         parent = path->nodes[level + 1]->start;
5157                 else
5158                         BUG_ON(root->root_key.objectid !=
5159                                btrfs_header_owner(path->nodes[level + 1]));
5160         }
5161
5162         ret = btrfs_free_extent(trans, root, eb->start, eb->len, parent,
5163                                 root->root_key.objectid, level, 0);
5164         BUG_ON(ret);
5165 out:
5166         wc->refs[level] = 0;
5167         wc->flags[level] = 0;
5168         return ret;
5169 }
5170
5171 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5172                                    struct btrfs_root *root,
5173                                    struct btrfs_path *path,
5174                                    struct walk_control *wc)
5175 {
5176         int level = wc->level;
5177         int ret;
5178
5179         while (level >= 0) {
5180                 if (path->slots[level] >=
5181                     btrfs_header_nritems(path->nodes[level]))
5182                         break;
5183
5184                 ret = walk_down_proc(trans, root, path, wc);
5185                 if (ret > 0)
5186                         break;
5187
5188                 if (level == 0)
5189                         break;
5190
5191                 ret = do_walk_down(trans, root, path, wc);
5192                 if (ret > 0) {
5193                         path->slots[level]++;
5194                         continue;
5195                 }
5196                 level = wc->level;
5197         }
5198         return 0;
5199 }
5200
5201 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
5202                                  struct btrfs_root *root,
5203                                  struct btrfs_path *path,
5204                                  struct walk_control *wc, int max_level)
5205 {
5206         int level = wc->level;
5207         int ret;
5208
5209         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5210         while (level < max_level && path->nodes[level]) {
5211                 wc->level = level;
5212                 if (path->slots[level] + 1 <
5213                     btrfs_header_nritems(path->nodes[level])) {
5214                         path->slots[level]++;
5215                         return 0;
5216                 } else {
5217                         ret = walk_up_proc(trans, root, path, wc);
5218                         if (ret > 0)
5219                                 return 0;
5220
5221                         if (path->locks[level]) {
5222                                 btrfs_tree_unlock(path->nodes[level]);
5223                                 path->locks[level] = 0;
5224                         }
5225                         free_extent_buffer(path->nodes[level]);
5226                         path->nodes[level] = NULL;
5227                         level++;
5228                 }
5229         }
5230         return 1;
5231 }
5232
5233 /*
5234  * drop a subvolume tree.
5235  *
5236  * this function traverses the tree freeing any blocks that only
5237  * referenced by the tree.
5238  *
5239  * when a shared tree block is found. this function decreases its
5240  * reference count by one. if update_ref is true, this function
5241  * also make sure backrefs for the shared block and all lower level
5242  * blocks are properly updated.
5243  */
5244 int btrfs_drop_snapshot(struct btrfs_root *root, int update_ref)
5245 {
5246         struct btrfs_path *path;
5247         struct btrfs_trans_handle *trans;
5248         struct btrfs_root *tree_root = root->fs_info->tree_root;
5249         struct btrfs_root_item *root_item = &root->root_item;
5250         struct walk_control *wc;
5251         struct btrfs_key key;
5252         int err = 0;
5253         int ret;
5254         int level;
5255
5256         path = btrfs_alloc_path();
5257         BUG_ON(!path);
5258
5259         wc = kzalloc(sizeof(*wc), GFP_NOFS);
5260         BUG_ON(!wc);
5261
5262         trans = btrfs_start_transaction(tree_root, 1);
5263
5264         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
5265                 level = btrfs_header_level(root->node);
5266                 path->nodes[level] = btrfs_lock_root_node(root);
5267                 btrfs_set_lock_blocking(path->nodes[level]);
5268                 path->slots[level] = 0;
5269                 path->locks[level] = 1;
5270                 memset(&wc->update_progress, 0,
5271                        sizeof(wc->update_progress));
5272         } else {
5273                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
5274                 memcpy(&wc->update_progress, &key,
5275                        sizeof(wc->update_progress));
5276
5277                 level = root_item->drop_level;
5278                 BUG_ON(level == 0);
5279                 path->lowest_level = level;
5280                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5281                 path->lowest_level = 0;
5282                 if (ret < 0) {
5283                         err = ret;
5284                         goto out;
5285                 }
5286                 WARN_ON(ret > 0);
5287
5288                 /*
5289                  * unlock our path, this is safe because only this
5290                  * function is allowed to delete this snapshot
5291                  */
5292                 btrfs_unlock_up_safe(path, 0);
5293
5294                 level = btrfs_header_level(root->node);
5295                 while (1) {
5296                         btrfs_tree_lock(path->nodes[level]);
5297                         btrfs_set_lock_blocking(path->nodes[level]);
5298
5299                         ret = btrfs_lookup_extent_info(trans, root,
5300                                                 path->nodes[level]->start,
5301                                                 path->nodes[level]->len,
5302                                                 &wc->refs[level],
5303                                                 &wc->flags[level]);
5304                         BUG_ON(ret);
5305                         BUG_ON(wc->refs[level] == 0);
5306
5307                         if (level == root_item->drop_level)
5308                                 break;
5309
5310                         btrfs_tree_unlock(path->nodes[level]);
5311                         WARN_ON(wc->refs[level] != 1);
5312                         level--;
5313                 }
5314         }
5315
5316         wc->level = level;
5317         wc->shared_level = -1;
5318         wc->stage = DROP_REFERENCE;
5319         wc->update_ref = update_ref;
5320         wc->keep_locks = 0;
5321         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
5322
5323         while (1) {
5324                 ret = walk_down_tree(trans, root, path, wc);
5325                 if (ret < 0) {
5326                         err = ret;
5327                         break;
5328                 }
5329
5330                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5331                 if (ret < 0) {
5332                         err = ret;
5333                         break;
5334                 }
5335
5336                 if (ret > 0) {
5337                         BUG_ON(wc->stage != DROP_REFERENCE);
5338                         break;
5339                 }
5340
5341                 if (wc->stage == DROP_REFERENCE) {
5342                         level = wc->level;
5343                         btrfs_node_key(path->nodes[level],
5344                                        &root_item->drop_progress,
5345                                        path->slots[level]);
5346                         root_item->drop_level = level;
5347                 }
5348
5349                 BUG_ON(wc->level == 0);
5350                 if (trans->transaction->in_commit ||
5351                     trans->transaction->delayed_refs.flushing) {
5352                         ret = btrfs_update_root(trans, tree_root,
5353                                                 &root->root_key,
5354                                                 root_item);
5355                         BUG_ON(ret);
5356
5357                         btrfs_end_transaction(trans, tree_root);
5358                         trans = btrfs_start_transaction(tree_root, 1);
5359                 } else {
5360                         unsigned long update;
5361                         update = trans->delayed_ref_updates;
5362                         trans->delayed_ref_updates = 0;
5363                         if (update)
5364                                 btrfs_run_delayed_refs(trans, tree_root,
5365                                                        update);
5366                 }
5367         }
5368         btrfs_release_path(root, path);
5369         BUG_ON(err);
5370
5371         ret = btrfs_del_root(trans, tree_root, &root->root_key);
5372         BUG_ON(ret);
5373
5374         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5375                 ret = btrfs_find_last_root(tree_root, root->root_key.objectid,
5376                                            NULL, NULL);
5377                 BUG_ON(ret < 0);
5378                 if (ret > 0) {
5379                         ret = btrfs_del_orphan_item(trans, tree_root,
5380                                                     root->root_key.objectid);
5381                         BUG_ON(ret);
5382                 }
5383         }
5384
5385         if (root->in_radix) {
5386                 btrfs_free_fs_root(tree_root->fs_info, root);
5387         } else {
5388                 free_extent_buffer(root->node);
5389                 free_extent_buffer(root->commit_root);
5390                 kfree(root);
5391         }
5392 out:
5393         btrfs_end_transaction(trans, tree_root);
5394         kfree(wc);
5395         btrfs_free_path(path);
5396         return err;
5397 }
5398
5399 /*
5400  * drop subtree rooted at tree block 'node'.
5401  *
5402  * NOTE: this function will unlock and release tree block 'node'
5403  */
5404 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5405                         struct btrfs_root *root,
5406                         struct extent_buffer *node,
5407                         struct extent_buffer *parent)
5408 {
5409         struct btrfs_path *path;
5410         struct walk_control *wc;
5411         int level;
5412         int parent_level;
5413         int ret = 0;
5414         int wret;
5415
5416         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5417
5418         path = btrfs_alloc_path();
5419         BUG_ON(!path);
5420
5421         wc = kzalloc(sizeof(*wc), GFP_NOFS);
5422         BUG_ON(!wc);
5423
5424         btrfs_assert_tree_locked(parent);
5425         parent_level = btrfs_header_level(parent);
5426         extent_buffer_get(parent);
5427         path->nodes[parent_level] = parent;
5428         path->slots[parent_level] = btrfs_header_nritems(parent);
5429
5430         btrfs_assert_tree_locked(node);
5431         level = btrfs_header_level(node);
5432         path->nodes[level] = node;
5433         path->slots[level] = 0;
5434         path->locks[level] = 1;
5435
5436         wc->refs[parent_level] = 1;
5437         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5438         wc->level = level;
5439         wc->shared_level = -1;
5440         wc->stage = DROP_REFERENCE;
5441         wc->update_ref = 0;
5442         wc->keep_locks = 1;
5443         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
5444
5445         while (1) {
5446                 wret = walk_down_tree(trans, root, path, wc);
5447                 if (wret < 0) {
5448                         ret = wret;
5449                         break;
5450                 }
5451
5452                 wret = walk_up_tree(trans, root, path, wc, parent_level);
5453                 if (wret < 0)
5454                         ret = wret;
5455                 if (wret != 0)
5456                         break;
5457         }
5458
5459         kfree(wc);
5460         btrfs_free_path(path);
5461         return ret;
5462 }
5463
5464 #if 0
5465 static unsigned long calc_ra(unsigned long start, unsigned long last,
5466                              unsigned long nr)
5467 {
5468         return min(last, start + nr - 1);
5469 }
5470
5471 static noinline int relocate_inode_pages(struct inode *inode, u64 start,
5472                                          u64 len)
5473 {
5474         u64 page_start;
5475         u64 page_end;
5476         unsigned long first_index;
5477         unsigned long last_index;
5478         unsigned long i;
5479         struct page *page;
5480         struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5481         struct file_ra_state *ra;
5482         struct btrfs_ordered_extent *ordered;
5483         unsigned int total_read = 0;
5484         unsigned int total_dirty = 0;
5485         int ret = 0;
5486
5487         ra = kzalloc(sizeof(*ra), GFP_NOFS);
5488
5489         mutex_lock(&inode->i_mutex);
5490         first_index = start >> PAGE_CACHE_SHIFT;
5491         last_index = (start + len - 1) >> PAGE_CACHE_SHIFT;
5492
5493         /* make sure the dirty trick played by the caller work */
5494         ret = invalidate_inode_pages2_range(inode->i_mapping,
5495                                             first_index, last_index);
5496         if (ret)
5497                 goto out_unlock;
5498
5499         file_ra_state_init(ra, inode->i_mapping);
5500
5501         for (i = first_index ; i <= last_index; i++) {
5502                 if (total_read % ra->ra_pages == 0) {
5503                         btrfs_force_ra(inode->i_mapping, ra, NULL, i,
5504                                        calc_ra(i, last_index, ra->ra_pages));
5505                 }
5506                 total_read++;
5507 again:
5508                 if (((u64)i << PAGE_CACHE_SHIFT) > i_size_read(inode))
5509                         BUG_ON(1);
5510                 page = grab_cache_page(inode->i_mapping, i);
5511                 if (!page) {
5512                         ret = -ENOMEM;
5513                         goto out_unlock;
5514                 }
5515                 if (!PageUptodate(page)) {
5516                         btrfs_readpage(NULL, page);
5517                         lock_page(page);
5518                         if (!PageUptodate(page)) {
5519                                 unlock_page(page);
5520                                 page_cache_release(page);
5521                                 ret = -EIO;
5522                                 goto out_unlock;
5523                         }
5524                 }
5525                 wait_on_page_writeback(page);
5526
5527                 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
5528                 page_end = page_start + PAGE_CACHE_SIZE - 1;
5529                 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
5530
5531                 ordered = btrfs_lookup_ordered_extent(inode, page_start);
5532                 if (ordered) {
5533                         unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
5534                         unlock_page(page);
5535                         page_cache_release(page);
5536                         btrfs_start_ordered_extent(inode, ordered, 1);
5537                         btrfs_put_ordered_extent(ordered);
5538                         goto again;
5539                 }
5540                 set_page_extent_mapped(page);
5541
5542                 if (i == first_index)
5543                         set_extent_bits(io_tree, page_start, page_end,
5544                                         EXTENT_BOUNDARY, GFP_NOFS);
5545                 btrfs_set_extent_delalloc(inode, page_start, page_end);
5546
5547                 set_page_dirty(page);
5548                 total_dirty++;
5549
5550                 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
5551                 unlock_page(page);
5552                 page_cache_release(page);
5553         }
5554
5555 out_unlock:
5556         kfree(ra);
5557         mutex_unlock(&inode->i_mutex);
5558         balance_dirty_pages_ratelimited_nr(inode->i_mapping, total_dirty);
5559         return ret;
5560 }
5561
5562 static noinline int relocate_data_extent(struct inode *reloc_inode,
5563                                          struct btrfs_key *extent_key,
5564                                          u64 offset)
5565 {
5566         struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
5567         struct extent_map_tree *em_tree = &BTRFS_I(reloc_inode)->extent_tree;
5568         struct extent_map *em;
5569         u64 start = extent_key->objectid - offset;
5570         u64 end = start + extent_key->offset - 1;
5571
5572         em = alloc_extent_map(GFP_NOFS);
5573         BUG_ON(!em || IS_ERR(em));
5574
5575         em->start = start;
5576         em->len = extent_key->offset;
5577         em->block_len = extent_key->offset;
5578         em->block_start = extent_key->objectid;
5579         em->bdev = root->fs_info->fs_devices->latest_bdev;
5580         set_bit(EXTENT_FLAG_PINNED, &em->flags);
5581
5582         /* setup extent map to cheat btrfs_readpage */
5583         lock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
5584         while (1) {
5585                 int ret;
5586                 write_lock(&em_tree->lock);
5587                 ret = add_extent_mapping(em_tree, em);
5588                 write_unlock(&em_tree->lock);
5589                 if (ret != -EEXIST) {
5590                         free_extent_map(em);
5591                         break;
5592                 }
5593                 btrfs_drop_extent_cache(reloc_inode, start, end, 0);
5594         }
5595         unlock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
5596
5597         return relocate_inode_pages(reloc_inode, start, extent_key->offset);
5598 }
5599
5600 struct btrfs_ref_path {
5601         u64 extent_start;
5602         u64 nodes[BTRFS_MAX_LEVEL];
5603         u64 root_objectid;
5604         u64 root_generation;
5605         u64 owner_objectid;
5606         u32 num_refs;
5607         int lowest_level;
5608         int current_level;
5609         int shared_level;
5610
5611         struct btrfs_key node_keys[BTRFS_MAX_LEVEL];
5612         u64 new_nodes[BTRFS_MAX_LEVEL];
5613 };
5614
5615 struct disk_extent {
5616         u64 ram_bytes;
5617         u64 disk_bytenr;
5618         u64 disk_num_bytes;
5619         u64 offset;
5620         u64 num_bytes;
5621         u8 compression;
5622         u8 encryption;
5623         u16 other_encoding;
5624 };
5625
5626 static int is_cowonly_root(u64 root_objectid)
5627 {
5628         if (root_objectid == BTRFS_ROOT_TREE_OBJECTID ||
5629             root_objectid == BTRFS_EXTENT_TREE_OBJECTID ||
5630             root_objectid == BTRFS_CHUNK_TREE_OBJECTID ||
5631             root_objectid == BTRFS_DEV_TREE_OBJECTID ||
5632             root_objectid == BTRFS_TREE_LOG_OBJECTID ||
5633             root_objectid == BTRFS_CSUM_TREE_OBJECTID)
5634                 return 1;
5635         return 0;
5636 }
5637
5638 static noinline int __next_ref_path(struct btrfs_trans_handle *trans,
5639                                     struct btrfs_root *extent_root,
5640                                     struct btrfs_ref_path *ref_path,
5641                                     int first_time)
5642 {
5643         struct extent_buffer *leaf;
5644         struct btrfs_path *path;
5645         struct btrfs_extent_ref *ref;
5646         struct btrfs_key key;
5647         struct btrfs_key found_key;
5648         u64 bytenr;
5649         u32 nritems;
5650         int level;
5651         int ret = 1;
5652
5653         path = btrfs_alloc_path();
5654         if (!path)
5655                 return -ENOMEM;
5656
5657         if (first_time) {
5658                 ref_path->lowest_level = -1;
5659                 ref_path->current_level = -1;
5660                 ref_path->shared_level = -1;
5661                 goto walk_up;
5662         }
5663 walk_down:
5664         level = ref_path->current_level - 1;
5665         while (level >= -1) {
5666                 u64 parent;
5667                 if (level < ref_path->lowest_level)
5668                         break;
5669
5670                 if (level >= 0)
5671                         bytenr = ref_path->nodes[level];
5672                 else
5673                         bytenr = ref_path->extent_start;
5674                 BUG_ON(bytenr == 0);
5675
5676                 parent = ref_path->nodes[level + 1];
5677                 ref_path->nodes[level + 1] = 0;
5678                 ref_path->current_level = level;
5679                 BUG_ON(parent == 0);
5680
5681                 key.objectid = bytenr;
5682                 key.offset = parent + 1;
5683                 key.type = BTRFS_EXTENT_REF_KEY;
5684
5685                 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
5686                 if (ret < 0)
5687                         goto out;
5688                 BUG_ON(ret == 0);
5689
5690                 leaf = path->nodes[0];
5691                 nritems = btrfs_header_nritems(leaf);
5692                 if (path->slots[0] >= nritems) {
5693                         ret = btrfs_next_leaf(extent_root, path);
5694                         if (ret < 0)
5695                                 goto out;
5696                         if (ret > 0)
5697                                 goto next;
5698                         leaf = path->nodes[0];
5699                 }
5700
5701                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5702                 if (found_key.objectid == bytenr &&
5703                     found_key.type == BTRFS_EXTENT_REF_KEY) {
5704                         if (level < ref_path->shared_level)
5705                                 ref_path->shared_level = level;
5706                         goto found;
5707                 }
5708 next:
5709                 level--;
5710                 btrfs_release_path(extent_root, path);
5711                 cond_resched();
5712         }
5713         /* reached lowest level */
5714         ret = 1;
5715         goto out;
5716 walk_up:
5717         level = ref_path->current_level;
5718         while (level < BTRFS_MAX_LEVEL - 1) {
5719                 u64 ref_objectid;
5720
5721                 if (level >= 0)
5722                         bytenr = ref_path->nodes[level];
5723                 else
5724                         bytenr = ref_path->extent_start;
5725
5726                 BUG_ON(bytenr == 0);
5727
5728                 key.objectid = bytenr;
5729                 key.offset = 0;
5730                 key.type = BTRFS_EXTENT_REF_KEY;
5731
5732                 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
5733                 if (ret < 0)
5734                         goto out;
5735
5736                 leaf = path->nodes[0];
5737                 nritems = btrfs_header_nritems(leaf);
5738                 if (path->slots[0] >= nritems) {
5739                         ret = btrfs_next_leaf(extent_root, path);
5740                         if (ret < 0)
5741                                 goto out;
5742                         if (ret > 0) {
5743                                 /* the extent was freed by someone */
5744                                 if (ref_path->lowest_level == level)
5745                                         goto out;
5746                                 btrfs_release_path(extent_root, path);
5747                                 goto walk_down;
5748                         }
5749                         leaf = path->nodes[0];
5750                 }
5751
5752                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5753                 if (found_key.objectid != bytenr ||
5754                                 found_key.type != BTRFS_EXTENT_REF_KEY) {
5755                         /* the extent was freed by someone */
5756                         if (ref_path->lowest_level == level) {
5757                                 ret = 1;
5758                                 goto out;
5759                         }
5760                         btrfs_release_path(extent_root, path);
5761                         goto walk_down;
5762                 }
5763 found:
5764                 ref = btrfs_item_ptr(leaf, path->slots[0],
5765                                 struct btrfs_extent_ref);
5766                 ref_objectid = btrfs_ref_objectid(leaf, ref);
5767                 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID) {
5768                         if (first_time) {
5769                                 level = (int)ref_objectid;
5770                                 BUG_ON(level >= BTRFS_MAX_LEVEL);
5771                                 ref_path->lowest_level = level;
5772                                 ref_path->current_level = level;
5773                                 ref_path->nodes[level] = bytenr;
5774                         } else {
5775                                 WARN_ON(ref_objectid != level);
5776                         }
5777                 } else {
5778                         WARN_ON(level != -1);
5779                 }
5780                 first_time = 0;
5781
5782                 if (ref_path->lowest_level == level) {
5783                         ref_path->owner_objectid = ref_objectid;
5784                         ref_path->num_refs = btrfs_ref_num_refs(leaf, ref);
5785                 }
5786
5787                 /*
5788                  * the block is tree root or the block isn't in reference
5789                  * counted tree.
5790                  */
5791                 if (found_key.objectid == found_key.offset ||
5792                     is_cowonly_root(btrfs_ref_root(leaf, ref))) {
5793                         ref_path->root_objectid = btrfs_ref_root(leaf, ref);
5794                         ref_path->root_generation =
5795                                 btrfs_ref_generation(leaf, ref);
5796                         if (level < 0) {
5797                                 /* special reference from the tree log */
5798                                 ref_path->nodes[0] = found_key.offset;
5799                                 ref_path->current_level = 0;
5800                         }
5801                         ret = 0;
5802                         goto out;
5803                 }
5804
5805                 level++;
5806                 BUG_ON(ref_path->nodes[level] != 0);
5807                 ref_path->nodes[level] = found_key.offset;
5808                 ref_path->current_level = level;
5809
5810                 /*
5811                  * the reference was created in the running transaction,
5812                  * no need to continue walking up.
5813                  */
5814                 if (btrfs_ref_generation(leaf, ref) == trans->transid) {
5815                         ref_path->root_objectid = btrfs_ref_root(leaf, ref);
5816                         ref_path->root_generation =
5817                                 btrfs_ref_generation(leaf, ref);
5818                         ret = 0;
5819                         goto out;
5820                 }
5821
5822                 btrfs_release_path(extent_root, path);
5823                 cond_resched();
5824         }
5825         /* reached max tree level, but no tree root found. */
5826         BUG();
5827 out:
5828         btrfs_free_path(path);
5829         return ret;
5830 }
5831
5832 static int btrfs_first_ref_path(struct btrfs_trans_handle *trans,
5833                                 struct btrfs_root *extent_root,
5834                                 struct btrfs_ref_path *ref_path,
5835                                 u64 extent_start)
5836 {
5837         memset(ref_path, 0, sizeof(*ref_path));
5838         ref_path->extent_start = extent_start;
5839
5840         return __next_ref_path(trans, extent_root, ref_path, 1);
5841 }
5842
5843 static int btrfs_next_ref_path(struct btrfs_trans_handle *trans,
5844                                struct btrfs_root *extent_root,
5845                                struct btrfs_ref_path *ref_path)
5846 {
5847         return __next_ref_path(trans, extent_root, ref_path, 0);
5848 }
5849
5850 static noinline int get_new_locations(struct inode *reloc_inode,
5851                                       struct btrfs_key *extent_key,
5852                                       u64 offset, int no_fragment,
5853                                       struct disk_extent **extents,
5854                                       int *nr_extents)
5855 {
5856         struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
5857         struct btrfs_path *path;
5858         struct btrfs_file_extent_item *fi;
5859         struct extent_buffer *leaf;
5860         struct disk_extent *exts = *extents;
5861         struct btrfs_key found_key;
5862         u64 cur_pos;
5863         u64 last_byte;
5864         u32 nritems;
5865         int nr = 0;
5866         int max = *nr_extents;
5867         int ret;
5868
5869         WARN_ON(!no_fragment && *extents);
5870         if (!exts) {
5871                 max = 1;
5872                 exts = kmalloc(sizeof(*exts) * max, GFP_NOFS);
5873                 if (!exts)
5874                         return -ENOMEM;
5875         }
5876
5877         path = btrfs_alloc_path();
5878         BUG_ON(!path);
5879
5880         cur_pos = extent_key->objectid - offset;
5881         last_byte = extent_key->objectid + extent_key->offset;
5882         ret = btrfs_lookup_file_extent(NULL, root, path, reloc_inode->i_ino,
5883                                        cur_pos, 0);
5884         if (ret < 0)
5885                 goto out;
5886         if (ret > 0) {
5887                 ret = -ENOENT;
5888                 goto out;
5889         }
5890
5891         while (1) {
5892                 leaf = path->nodes[0];
5893                 nritems = btrfs_header_nritems(leaf);
5894                 if (path->slots[0] >= nritems) {
5895                         ret = btrfs_next_leaf(root, path);
5896                         if (ret < 0)
5897                                 goto out;
5898                         if (ret > 0)
5899                                 break;
5900                         leaf = path->nodes[0];
5901                 }
5902
5903                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5904                 if (found_key.offset != cur_pos ||
5905                     found_key.type != BTRFS_EXTENT_DATA_KEY ||
5906                     found_key.objectid != reloc_inode->i_ino)
5907                         break;
5908
5909                 fi = btrfs_item_ptr(leaf, path->slots[0],
5910                                     struct btrfs_file_extent_item);
5911                 if (btrfs_file_extent_type(leaf, fi) !=
5912                     BTRFS_FILE_EXTENT_REG ||
5913                     btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
5914                         break;
5915
5916                 if (nr == max) {
5917                         struct disk_extent *old = exts;
5918                         max *= 2;
5919                         exts = kzalloc(sizeof(*exts) * max, GFP_NOFS);
5920                         memcpy(exts, old, sizeof(*exts) * nr);
5921                         if (old != *extents)
5922                                 kfree(old);
5923                 }
5924
5925                 exts[nr].disk_bytenr =
5926                         btrfs_file_extent_disk_bytenr(leaf, fi);
5927                 exts[nr].disk_num_bytes =
5928                         btrfs_file_extent_disk_num_bytes(leaf, fi);
5929                 exts[nr].offset = btrfs_file_extent_offset(leaf, fi);
5930                 exts[nr].num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
5931                 exts[nr].ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
5932                 exts[nr].compression = btrfs_file_extent_compression(leaf, fi);
5933                 exts[nr].encryption = btrfs_file_extent_encryption(leaf, fi);
5934                 exts[nr].other_encoding = btrfs_file_extent_other_encoding(leaf,
5935                                                                            fi);
5936                 BUG_ON(exts[nr].offset > 0);
5937                 BUG_ON(exts[nr].compression || exts[nr].encryption);
5938                 BUG_ON(exts[nr].num_bytes != exts[nr].disk_num_bytes);
5939
5940                 cur_pos += exts[nr].num_bytes;
5941                 nr++;
5942
5943                 if (cur_pos + offset >= last_byte)
5944                         break;
5945
5946                 if (no_fragment) {
5947                         ret = 1;
5948                         goto out;
5949                 }
5950                 path->slots[0]++;
5951         }
5952
5953         BUG_ON(cur_pos + offset > last_byte);
5954         if (cur_pos + offset < last_byte) {
5955                 ret = -ENOENT;
5956                 goto out;
5957         }
5958         ret = 0;
5959 out:
5960         btrfs_free_path(path);
5961         if (ret) {
5962                 if (exts != *extents)
5963                         kfree(exts);
5964         } else {
5965                 *extents = exts;
5966                 *nr_extents = nr;
5967         }
5968         return ret;
5969 }
5970
5971 static noinline int replace_one_extent(struct btrfs_trans_handle *trans,
5972                                         struct btrfs_root *root,
5973                                         struct btrfs_path *path,
5974                                         struct btrfs_key *extent_key,
5975                                         struct btrfs_key *leaf_key,
5976                                         struct btrfs_ref_path *ref_path,
5977                                         struct disk_extent *new_extents,
5978                                         int nr_extents)
5979 {
5980         struct extent_buffer *leaf;
5981         struct btrfs_file_extent_item *fi;
5982         struct inode *inode = NULL;
5983         struct btrfs_key key;
5984         u64 lock_start = 0;
5985         u64 lock_end = 0;
5986         u64 num_bytes;
5987         u64 ext_offset;
5988         u64 search_end = (u64)-1;
5989         u32 nritems;
5990         int nr_scaned = 0;
5991         int extent_locked = 0;
5992         int extent_type;
5993         int ret;
5994
5995         memcpy(&key, leaf_key, sizeof(key));
5996         if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
5997                 if (key.objectid < ref_path->owner_objectid ||
5998                     (key.objectid == ref_path->owner_objectid &&
5999                      key.type < BTRFS_EXTENT_DATA_KEY)) {
6000                         key.objectid = ref_path->owner_objectid;
6001                         key.type = BTRFS_EXTENT_DATA_KEY;
6002                         key.offset = 0;
6003                 }
6004         }
6005
6006         while (1) {
6007                 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6008                 if (ret < 0)
6009                         goto out;
6010
6011                 leaf = path->nodes[0];
6012                 nritems = btrfs_header_nritems(leaf);
6013 next:
6014                 if (extent_locked && ret > 0) {
6015                         /*
6016                          * the file extent item was modified by someone
6017                          * before the extent got locked.
6018                          */
6019                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6020                                       lock_end, GFP_NOFS);
6021                         extent_locked = 0;
6022                 }
6023
6024                 if (path->slots[0] >= nritems) {
6025                         if (++nr_scaned > 2)
6026                                 break;
6027
6028                         BUG_ON(extent_locked);
6029                         ret = btrfs_next_leaf(root, path);
6030                         if (ret < 0)
6031                                 goto out;
6032                         if (ret > 0)
6033                                 break;
6034                         leaf = path->nodes[0];
6035                         nritems = btrfs_header_nritems(leaf);
6036                 }
6037
6038                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6039
6040                 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
6041                         if ((key.objectid > ref_path->owner_objectid) ||
6042                             (key.objectid == ref_path->owner_objectid &&
6043                              key.type > BTRFS_EXTENT_DATA_KEY) ||
6044                             key.offset >= search_end)
6045                                 break;
6046                 }
6047
6048                 if (inode && key.objectid != inode->i_ino) {
6049                         BUG_ON(extent_locked);
6050                         btrfs_release_path(root, path);
6051                         mutex_unlock(&inode->i_mutex);
6052                         iput(inode);
6053                         inode = NULL;
6054                         continue;
6055                 }
6056
6057                 if (key.type != BTRFS_EXTENT_DATA_KEY) {
6058                         path->slots[0]++;
6059                         ret = 1;
6060                         goto next;
6061                 }
6062                 fi = btrfs_item_ptr(leaf, path->slots[0],
6063                                     struct btrfs_file_extent_item);
6064                 extent_type = btrfs_file_extent_type(leaf, fi);
6065                 if ((extent_type != BTRFS_FILE_EXTENT_REG &&
6066                      extent_type != BTRFS_FILE_EXTENT_PREALLOC) ||
6067                     (btrfs_file_extent_disk_bytenr(leaf, fi) !=
6068                      extent_key->objectid)) {
6069                         path->slots[0]++;
6070                         ret = 1;
6071                         goto next;
6072                 }
6073
6074                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
6075                 ext_offset = btrfs_file_extent_offset(leaf, fi);
6076
6077                 if (search_end == (u64)-1) {
6078                         search_end = key.offset - ext_offset +
6079                                 btrfs_file_extent_ram_bytes(leaf, fi);
6080                 }
6081
6082                 if (!extent_locked) {
6083                         lock_start = key.offset;
6084                         lock_end = lock_start + num_bytes - 1;
6085                 } else {
6086                         if (lock_start > key.offset ||
6087                             lock_end + 1 < key.offset + num_bytes) {
6088                                 unlock_extent(&BTRFS_I(inode)->io_tree,
6089                                               lock_start, lock_end, GFP_NOFS);
6090                                 extent_locked = 0;
6091                         }
6092                 }
6093
6094                 if (!inode) {
6095                         btrfs_release_path(root, path);
6096
6097                         inode = btrfs_iget_locked(root->fs_info->sb,
6098                                                   key.objectid, root);
6099                         if (inode->i_state & I_NEW) {
6100                                 BTRFS_I(inode)->root = root;
6101                                 BTRFS_I(inode)->location.objectid =
6102                                         key.objectid;
6103                                 BTRFS_I(inode)->location.type =
6104                                         BTRFS_INODE_ITEM_KEY;
6105                                 BTRFS_I(inode)->location.offset = 0;
6106                                 btrfs_read_locked_inode(inode);
6107                                 unlock_new_inode(inode);
6108                         }
6109                         /*
6110                          * some code call btrfs_commit_transaction while
6111                          * holding the i_mutex, so we can't use mutex_lock
6112                          * here.
6113                          */
6114                         if (is_bad_inode(inode) ||
6115                             !mutex_trylock(&inode->i_mutex)) {
6116                                 iput(inode);
6117                                 inode = NULL;
6118                                 key.offset = (u64)-1;
6119                                 goto skip;
6120                         }
6121                 }
6122
6123                 if (!extent_locked) {
6124                         struct btrfs_ordered_extent *ordered;
6125
6126                         btrfs_release_path(root, path);
6127
6128                         lock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6129                                     lock_end, GFP_NOFS);
6130                         ordered = btrfs_lookup_first_ordered_extent(inode,
6131                                                                     lock_end);
6132                         if (ordered &&
6133                             ordered->file_offset <= lock_end &&
6134                             ordered->file_offset + ordered->len > lock_start) {
6135                                 unlock_extent(&BTRFS_I(inode)->io_tree,
6136                                               lock_start, lock_end, GFP_NOFS);
6137                                 btrfs_start_ordered_extent(inode, ordered, 1);
6138                                 btrfs_put_ordered_extent(ordered);
6139                                 key.offset += num_bytes;
6140                                 goto skip;
6141                         }
6142                         if (ordered)
6143                                 btrfs_put_ordered_extent(ordered);
6144
6145                         extent_locked = 1;
6146                         continue;
6147                 }
6148
6149                 if (nr_extents == 1) {
6150                         /* update extent pointer in place */
6151                         btrfs_set_file_extent_disk_bytenr(leaf, fi,
6152                                                 new_extents[0].disk_bytenr);
6153                         btrfs_set_file_extent_disk_num_bytes(leaf, fi,
6154                                                 new_extents[0].disk_num_bytes);
6155                         btrfs_mark_buffer_dirty(leaf);
6156
6157                         btrfs_drop_extent_cache(inode, key.offset,
6158                                                 key.offset + num_bytes - 1, 0);
6159
6160                         ret = btrfs_inc_extent_ref(trans, root,
6161                                                 new_extents[0].disk_bytenr,
6162                                                 new_extents[0].disk_num_bytes,
6163                                                 leaf->start,
6164                                                 root->root_key.objectid,
6165                                                 trans->transid,
6166                                                 key.objectid);
6167                         BUG_ON(ret);
6168
6169                         ret = btrfs_free_extent(trans, root,
6170                                                 extent_key->objectid,
6171                                                 extent_key->offset,
6172                                                 leaf->start,
6173                                                 btrfs_header_owner(leaf),
6174                                                 btrfs_header_generation(leaf),
6175                                                 key.objectid, 0);
6176                         BUG_ON(ret);
6177
6178                         btrfs_release_path(root, path);
6179                         key.offset += num_bytes;
6180                 } else {
6181                         BUG_ON(1);
6182 #if 0
6183                         u64 alloc_hint;
6184                         u64 extent_len;
6185                         int i;
6186                         /*
6187                          * drop old extent pointer at first, then insert the
6188                          * new pointers one bye one
6189                          */
6190                         btrfs_release_path(root, path);
6191                         ret = btrfs_drop_extents(trans, root, inode, key.offset,
6192                                                  key.offset + num_bytes,
6193                                                  key.offset, &alloc_hint);
6194                         BUG_ON(ret);
6195
6196                         for (i = 0; i < nr_extents; i++) {
6197                                 if (ext_offset >= new_extents[i].num_bytes) {
6198                                         ext_offset -= new_extents[i].num_bytes;
6199                                         continue;
6200                                 }
6201                                 extent_len = min(new_extents[i].num_bytes -
6202                                                  ext_offset, num_bytes);
6203
6204                                 ret = btrfs_insert_empty_item(trans, root,
6205                                                               path, &key,
6206                                                               sizeof(*fi));
6207                                 BUG_ON(ret);
6208
6209                                 leaf = path->nodes[0];
6210                                 fi = btrfs_item_ptr(leaf, path->slots[0],
6211                                                 struct btrfs_file_extent_item);
6212                                 btrfs_set_file_extent_generation(leaf, fi,
6213                                                         trans->transid);
6214                                 btrfs_set_file_extent_type(leaf, fi,
6215                                                         BTRFS_FILE_EXTENT_REG);
6216                                 btrfs_set_file_extent_disk_bytenr(leaf, fi,
6217                                                 new_extents[i].disk_bytenr);
6218                                 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
6219                                                 new_extents[i].disk_num_bytes);
6220                                 btrfs_set_file_extent_ram_bytes(leaf, fi,
6221                                                 new_extents[i].ram_bytes);
6222
6223                                 btrfs_set_file_extent_compression(leaf, fi,
6224                                                 new_extents[i].compression);
6225                                 btrfs_set_file_extent_encryption(leaf, fi,
6226                                                 new_extents[i].encryption);
6227                                 btrfs_set_file_extent_other_encoding(leaf, fi,
6228                                                 new_extents[i].other_encoding);
6229
6230                                 btrfs_set_file_extent_num_bytes(leaf, fi,
6231                                                         extent_len);
6232                                 ext_offset += new_extents[i].offset;
6233                                 btrfs_set_file_extent_offset(leaf, fi,
6234                                                         ext_offset);
6235                                 btrfs_mark_buffer_dirty(leaf);
6236
6237                                 btrfs_drop_extent_cache(inode, key.offset,
6238                                                 key.offset + extent_len - 1, 0);
6239
6240                                 ret = btrfs_inc_extent_ref(trans, root,
6241                                                 new_extents[i].disk_bytenr,
6242                                                 new_extents[i].disk_num_bytes,
6243                                                 leaf->start,
6244                                                 root->root_key.objectid,
6245                                                 trans->transid, key.objectid);
6246                                 BUG_ON(ret);
6247                                 btrfs_release_path(root, path);
6248
6249                                 inode_add_bytes(inode, extent_len);
6250
6251                                 ext_offset = 0;
6252                                 num_bytes -= extent_len;
6253                                 key.offset += extent_len;
6254
6255                                 if (num_bytes == 0)
6256                                         break;
6257                         }
6258                         BUG_ON(i >= nr_extents);
6259 #endif
6260                 }
6261
6262                 if (extent_locked) {
6263                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6264                                       lock_end, GFP_NOFS);
6265                         extent_locked = 0;
6266                 }
6267 skip:
6268                 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS &&
6269                     key.offset >= search_end)
6270                         break;
6271
6272                 cond_resched();
6273         }
6274         ret = 0;
6275 out:
6276         btrfs_release_path(root, path);
6277         if (inode) {
6278                 mutex_unlock(&inode->i_mutex);
6279                 if (extent_locked) {
6280                         unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6281                                       lock_end, GFP_NOFS);
6282                 }
6283                 iput(inode);
6284         }
6285         return ret;
6286 }
6287
6288 int btrfs_reloc_tree_cache_ref(struct btrfs_trans_handle *trans,
6289                                struct btrfs_root *root,
6290                                struct extent_buffer *buf, u64 orig_start)
6291 {
6292         int level;
6293         int ret;
6294
6295         BUG_ON(btrfs_header_generation(buf) != trans->transid);
6296         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
6297
6298         level = btrfs_header_level(buf);
6299         if (level == 0) {
6300                 struct btrfs_leaf_ref *ref;
6301                 struct btrfs_leaf_ref *orig_ref;
6302
6303                 orig_ref = btrfs_lookup_leaf_ref(root, orig_start);
6304                 if (!orig_ref)
6305                         return -ENOENT;
6306
6307                 ref = btrfs_alloc_leaf_ref(root, orig_ref->nritems);
6308                 if (!ref) {
6309                         btrfs_free_leaf_ref(root, orig_ref);
6310                         return -ENOMEM;
6311                 }
6312
6313                 ref->nritems = orig_ref->nritems;
6314                 memcpy(ref->extents, orig_ref->extents,
6315                         sizeof(ref->extents[0]) * ref->nritems);
6316
6317                 btrfs_free_leaf_ref(root, orig_ref);
6318
6319                 ref->root_gen = trans->transid;
6320                 ref->bytenr = buf->start;
6321                 ref->owner = btrfs_header_owner(buf);
6322                 ref->generation = btrfs_header_generation(buf);
6323
6324                 ret = btrfs_add_leaf_ref(root, ref, 0);
6325                 WARN_ON(ret);
6326                 btrfs_free_leaf_ref(root, ref);
6327         }
6328         return 0;
6329 }
6330
6331 static noinline int invalidate_extent_cache(struct btrfs_root *root,
6332                                         struct extent_buffer *leaf,
6333                                         struct btrfs_block_group_cache *group,
6334                                         struct btrfs_root *target_root)
6335 {
6336         struct btrfs_key key;
6337         struct inode *inode = NULL;
6338         struct btrfs_file_extent_item *fi;
6339         u64 num_bytes;
6340         u64 skip_objectid = 0;
6341         u32 nritems;
6342         u32 i;
6343
6344         nritems = btrfs_header_nritems(leaf);
6345         for (i = 0; i < nritems; i++) {
6346                 btrfs_item_key_to_cpu(leaf, &key, i);
6347                 if (key.objectid == skip_objectid ||
6348                     key.type != BTRFS_EXTENT_DATA_KEY)
6349                         continue;
6350                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
6351                 if (btrfs_file_extent_type(leaf, fi) ==
6352                     BTRFS_FILE_EXTENT_INLINE)
6353                         continue;
6354                 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
6355                         continue;
6356                 if (!inode || inode->i_ino != key.objectid) {
6357                         iput(inode);
6358                         inode = btrfs_ilookup(target_root->fs_info->sb,
6359                                               key.objectid, target_root, 1);
6360                 }
6361                 if (!inode) {
6362                         skip_objectid = key.objectid;
6363                         continue;
6364                 }
6365                 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
6366
6367                 lock_extent(&BTRFS_I(inode)->io_tree, key.offset,
6368                             key.offset + num_bytes - 1, GFP_NOFS);
6369                 btrfs_drop_extent_cache(inode, key.offset,
6370                                         key.offset + num_bytes - 1, 1);
6371                 unlock_extent(&BTRFS_I(inode)->io_tree, key.offset,
6372                               key.offset + num_bytes - 1, GFP_NOFS);
6373                 cond_resched();
6374         }
6375         iput(inode);
6376         return 0;
6377 }
6378
6379 static noinline int replace_extents_in_leaf(struct btrfs_trans_handle *trans,
6380                                         struct btrfs_root *root,
6381                                         struct extent_buffer *leaf,
6382                                         struct btrfs_block_group_cache *group,
6383                                         struct inode *reloc_inode)
6384 {
6385         struct btrfs_key key;
6386         struct btrfs_key extent_key;
6387         struct btrfs_file_extent_item *fi;
6388         struct btrfs_leaf_ref *ref;
6389         struct disk_extent *new_extent;
6390         u64 bytenr;
6391         u64 num_bytes;
6392         u32 nritems;
6393         u32 i;
6394         int ext_index;
6395         int nr_extent;
6396         int ret;
6397
6398         new_extent = kmalloc(sizeof(*new_extent), GFP_NOFS);
6399         BUG_ON(!new_extent);
6400
6401         ref = btrfs_lookup_leaf_ref(root, leaf->start);
6402         BUG_ON(!ref);
6403
6404         ext_index = -1;
6405         nritems = btrfs_header_nritems(leaf);
6406         for (i = 0; i < nritems; i++) {
6407                 btrfs_item_key_to_cpu(leaf, &key, i);
6408                 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
6409                         continue;
6410                 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
6411                 if (btrfs_file_extent_type(leaf, fi) ==
6412                     BTRFS_FILE_EXTENT_INLINE)
6413                         continue;
6414                 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6415                 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6416                 if (bytenr == 0)
6417                         continue;
6418
6419                 ext_index++;
6420                 if (bytenr >= group->key.objectid + group->key.offset ||
6421                     bytenr + num_bytes <= group->key.objectid)
6422                         continue;
6423
6424                 extent_key.objectid = bytenr;
6425                 extent_key.offset = num_bytes;
6426                 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
6427                 nr_extent = 1;
6428                 ret = get_new_locations(reloc_inode, &extent_key,
6429                                         group->key.objectid, 1,
6430                                         &new_extent, &nr_extent);
6431                 if (ret > 0)
6432                         continue;
6433                 BUG_ON(ret < 0);
6434
6435                 BUG_ON(ref->extents[ext_index].bytenr != bytenr);
6436                 BUG_ON(ref->extents[ext_index].num_bytes != num_bytes);
6437                 ref->extents[ext_index].bytenr = new_extent->disk_bytenr;
6438                 ref->extents[ext_index].num_bytes = new_extent->disk_num_bytes;
6439
6440                 btrfs_set_file_extent_disk_bytenr(leaf, fi,
6441                                                 new_extent->disk_bytenr);
6442                 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
6443                                                 new_extent->disk_num_bytes);
6444                 btrfs_mark_buffer_dirty(leaf);
6445
6446                 ret = btrfs_inc_extent_ref(trans, root,
6447                                         new_extent->disk_bytenr,
6448                                         new_extent->disk_num_bytes,
6449                                         leaf->start,
6450                                         root->root_key.objectid,
6451                                         trans->transid, key.objectid);
6452                 BUG_ON(ret);
6453
6454                 ret = btrfs_free_extent(trans, root,
6455                                         bytenr, num_bytes, leaf->start,
6456                                         btrfs_header_owner(leaf),
6457                                         btrfs_header_generation(leaf),
6458                                         key.objectid, 0);
6459                 BUG_ON(ret);
6460                 cond_resched();
6461         }
6462         kfree(new_extent);
6463         BUG_ON(ext_index + 1 != ref->nritems);
6464         btrfs_free_leaf_ref(root, ref);
6465         return 0;
6466 }
6467
6468 int btrfs_free_reloc_root(struct btrfs_trans_handle *trans,
6469                           struct btrfs_root *root)
6470 {
6471         struct btrfs_root *reloc_root;
6472         int ret;
6473
6474         if (root->reloc_root) {
6475                 reloc_root = root->reloc_root;
6476                 root->reloc_root = NULL;
6477                 list_add(&reloc_root->dead_list,
6478                          &root->fs_info->dead_reloc_roots);
6479
6480                 btrfs_set_root_bytenr(&reloc_root->root_item,
6481                                       reloc_root->node->start);
6482                 btrfs_set_root_level(&root->root_item,
6483                                      btrfs_header_level(reloc_root->node));
6484                 memset(&reloc_root->root_item.drop_progress, 0,
6485                         sizeof(struct btrfs_disk_key));
6486                 reloc_root->root_item.drop_level = 0;
6487
6488                 ret = btrfs_update_root(trans, root->fs_info->tree_root,
6489                                         &reloc_root->root_key,
6490                                         &reloc_root->root_item);
6491                 BUG_ON(ret);
6492         }
6493         return 0;
6494 }
6495
6496 int btrfs_drop_dead_reloc_roots(struct btrfs_root *root)
6497 {
6498         struct btrfs_trans_handle *trans;
6499         struct btrfs_root *reloc_root;
6500         struct btrfs_root *prev_root = NULL;
6501         struct list_head dead_roots;
6502         int ret;
6503         unsigned long nr;
6504
6505         INIT_LIST_HEAD(&dead_roots);
6506         list_splice_init(&root->fs_info->dead_reloc_roots, &dead_roots);
6507
6508         while (!list_empty(&dead_roots)) {
6509                 reloc_root = list_entry(dead_roots.prev,
6510                                         struct btrfs_root, dead_list);
6511                 list_del_init(&reloc_root->dead_list);
6512
6513                 BUG_ON(reloc_root->commit_root != NULL);
6514                 while (1) {
6515                         trans = btrfs_join_transaction(root, 1);
6516                         BUG_ON(!trans);
6517
6518                         mutex_lock(&root->fs_info->drop_mutex);
6519                         ret = btrfs_drop_snapshot(trans, reloc_root);
6520                         if (ret != -EAGAIN)
6521                                 break;
6522                         mutex_unlock(&root->fs_info->drop_mutex);
6523
6524                         nr = trans->blocks_used;
6525                         ret = btrfs_end_transaction(trans, root);
6526                         BUG_ON(ret);
6527                         btrfs_btree_balance_dirty(root, nr);
6528                 }
6529
6530                 free_extent_buffer(reloc_root->node);
6531
6532                 ret = btrfs_del_root(trans, root->fs_info->tree_root,
6533                                      &reloc_root->root_key);
6534                 BUG_ON(ret);
6535                 mutex_unlock(&root->fs_info->drop_mutex);
6536
6537                 nr = trans->blocks_used;
6538                 ret = btrfs_end_transaction(trans, root);
6539                 BUG_ON(ret);
6540                 btrfs_btree_balance_dirty(root, nr);
6541
6542                 kfree(prev_root);
6543                 prev_root = reloc_root;
6544         }
6545         if (prev_root) {
6546                 btrfs_remove_leaf_refs(prev_root, (u64)-1, 0);
6547                 kfree(prev_root);
6548         }
6549         return 0;
6550 }
6551
6552 int btrfs_add_dead_reloc_root(struct btrfs_root *root)
6553 {
6554         list_add(&root->dead_list, &root->fs_info->dead_reloc_roots);
6555         return 0;
6556 }
6557
6558 int btrfs_cleanup_reloc_trees(struct btrfs_root *root)
6559 {
6560         struct btrfs_root *reloc_root;
6561         struct btrfs_trans_handle *trans;
6562         struct btrfs_key location;
6563         int found;
6564         int ret;
6565
6566         mutex_lock(&root->fs_info->tree_reloc_mutex);
6567         ret = btrfs_find_dead_roots(root, BTRFS_TREE_RELOC_OBJECTID, NULL);
6568         BUG_ON(ret);
6569         found = !list_empty(&root->fs_info->dead_reloc_roots);
6570         mutex_unlock(&root->fs_info->tree_reloc_mutex);
6571
6572         if (found) {
6573                 trans = btrfs_start_transaction(root, 1);
6574                 BUG_ON(!trans);
6575                 ret = btrfs_commit_transaction(trans, root);
6576                 BUG_ON(ret);
6577         }
6578
6579         location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
6580         location.offset = (u64)-1;
6581         location.type = BTRFS_ROOT_ITEM_KEY;
6582
6583         reloc_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
6584         BUG_ON(!reloc_root);
6585         btrfs_orphan_cleanup(reloc_root);
6586         return 0;
6587 }
6588
6589 static noinline int init_reloc_tree(struct btrfs_trans_handle *trans,
6590                                     struct btrfs_root *root)
6591 {
6592         struct btrfs_root *reloc_root;
6593         struct extent_buffer *eb;
6594         struct btrfs_root_item *root_item;
6595         struct btrfs_key root_key;
6596         int ret;
6597
6598         BUG_ON(!root->ref_cows);
6599         if (root->reloc_root)
6600                 return 0;
6601
6602         root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
6603         BUG_ON(!root_item);
6604
6605         ret = btrfs_copy_root(trans, root, root->commit_root,
6606                               &eb, BTRFS_TREE_RELOC_OBJECTID);
6607         BUG_ON(ret);
6608
6609         root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
6610         root_key.offset = root->root_key.objectid;
6611         root_key.type = BTRFS_ROOT_ITEM_KEY;
6612
6613         memcpy(root_item, &root->root_item, sizeof(root_item));
6614         btrfs_set_root_refs(root_item, 0);
6615         btrfs_set_root_bytenr(root_item, eb->start);
6616         btrfs_set_root_level(root_item, btrfs_header_level(eb));
6617         btrfs_set_root_generation(root_item, trans->transid);
6618
6619         btrfs_tree_unlock(eb);
6620         free_extent_buffer(eb);
6621
6622         ret = btrfs_insert_root(trans, root->fs_info->tree_root,
6623                                 &root_key, root_item);
6624         BUG_ON(ret);
6625         kfree(root_item);
6626
6627         reloc_root = btrfs_read_fs_root_no_radix(root->fs_info->tree_root,
6628                                                  &root_key);
6629         BUG_ON(!reloc_root);
6630         reloc_root->last_trans = trans->transid;
6631         reloc_root->commit_root = NULL;
6632         reloc_root->ref_tree = &root->fs_info->reloc_ref_tree;
6633
6634         root->reloc_root = reloc_root;
6635         return 0;
6636 }
6637
6638 /*
6639  * Core function of space balance.
6640  *
6641  * The idea is using reloc trees to relocate tree blocks in reference
6642  * counted roots. There is one reloc tree for each subvol, and all
6643  * reloc trees share same root key objectid. Reloc trees are snapshots
6644  * of the latest committed roots of subvols (root->commit_root).
6645  *
6646  * To relocate a tree block referenced by a subvol, there are two steps.
6647  * COW the block through subvol's reloc tree, then update block pointer
6648  * in the subvol to point to the new block. Since all reloc trees share
6649  * same root key objectid, doing special handing for tree blocks owned
6650  * by them is easy. Once a tree block has been COWed in one reloc tree,
6651  * we can use the resulting new block directly when the same block is
6652  * required to COW again through other reloc trees. By this way, relocated
6653  * tree blocks are shared between reloc trees, so they are also shared
6654  * between subvols.
6655  */
6656 static noinline int relocate_one_path(struct btrfs_trans_handle *trans,
6657                                       struct btrfs_root *root,
6658                                       struct btrfs_path *path,
6659                                       struct btrfs_key *first_key,
6660                                       struct btrfs_ref_path *ref_path,
6661                                       struct btrfs_block_group_cache *group,
6662                                       struct inode *reloc_inode)
6663 {
6664         struct btrfs_root *reloc_root;
6665         struct extent_buffer *eb = NULL;
6666         struct btrfs_key *keys;
6667         u64 *nodes;
6668         int level;
6669         int shared_level;
6670         int lowest_level = 0;
6671         int ret;
6672
6673         if (ref_path->owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
6674                 lowest_level = ref_path->owner_objectid;
6675
6676         if (!root->ref_cows) {
6677                 path->lowest_level = lowest_level;
6678                 ret = btrfs_search_slot(trans, root, first_key, path, 0, 1);
6679                 BUG_ON(ret < 0);
6680                 path->lowest_level = 0;
6681                 btrfs_release_path(root, path);
6682                 return 0;
6683         }
6684
6685         mutex_lock(&root->fs_info->tree_reloc_mutex);
6686         ret = init_reloc_tree(trans, root);
6687         BUG_ON(ret);
6688         reloc_root = root->reloc_root;
6689
6690         shared_level = ref_path->shared_level;
6691         ref_path->shared_level = BTRFS_MAX_LEVEL - 1;
6692
6693         keys = ref_path->node_keys;
6694         nodes = ref_path->new_nodes;
6695         memset(&keys[shared_level + 1], 0,
6696                sizeof(*keys) * (BTRFS_MAX_LEVEL - shared_level - 1));
6697         memset(&nodes[shared_level + 1], 0,
6698                sizeof(*nodes) * (BTRFS_MAX_LEVEL - shared_level - 1));
6699
6700         if (nodes[lowest_level] == 0) {
6701                 path->lowest_level = lowest_level;
6702                 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
6703                                         0, 1);
6704                 BUG_ON(ret);
6705                 for (level = lowest_level; level < BTRFS_MAX_LEVEL; level++) {
6706                         eb = path->nodes[level];
6707                         if (!eb || eb == reloc_root->node)
6708                                 break;
6709                         nodes[level] = eb->start;
6710                         if (level == 0)
6711                                 btrfs_item_key_to_cpu(eb, &keys[level], 0);
6712                         else
6713                                 btrfs_node_key_to_cpu(eb, &keys[level], 0);
6714                 }
6715                 if (nodes[0] &&
6716                     ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
6717                         eb = path->nodes[0];
6718                         ret = replace_extents_in_leaf(trans, reloc_root, eb,
6719                                                       group, reloc_inode);
6720                         BUG_ON(ret);
6721                 }
6722                 btrfs_release_path(reloc_root, path);
6723         } else {
6724                 ret = btrfs_merge_path(trans, reloc_root, keys, nodes,
6725                                        lowest_level);
6726                 BUG_ON(ret);
6727         }
6728
6729         /*
6730          * replace tree blocks in the fs tree with tree blocks in
6731          * the reloc tree.
6732          */
6733         ret = btrfs_merge_path(trans, root, keys, nodes, lowest_level);
6734         BUG_ON(ret < 0);
6735
6736         if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
6737                 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
6738                                         0, 0);
6739                 BUG_ON(ret);
6740                 extent_buffer_get(path->nodes[0]);
6741                 eb = path->nodes[0];
6742                 btrfs_release_path(reloc_root, path);
6743                 ret = invalidate_extent_cache(reloc_root, eb, group, root);
6744                 BUG_ON(ret);
6745                 free_extent_buffer(eb);
6746         }
6747
6748         mutex_unlock(&root->fs_info->tree_reloc_mutex);
6749         path->lowest_level = 0;
6750         return 0;
6751 }
6752
6753 static noinline int relocate_tree_block(struct btrfs_trans_handle *trans,
6754                                         struct btrfs_root *root,
6755                                         struct btrfs_path *path,
6756                                         struct btrfs_key *first_key,
6757                                         struct btrfs_ref_path *ref_path)
6758 {
6759         int ret;
6760
6761         ret = relocate_one_path(trans, root, path, first_key,
6762                                 ref_path, NULL, NULL);
6763         BUG_ON(ret);
6764
6765         return 0;
6766 }
6767
6768 static noinline int del_extent_zero(struct btrfs_trans_handle *trans,
6769                                     struct btrfs_root *extent_root,
6770                                     struct btrfs_path *path,
6771                                     struct btrfs_key *extent_key)
6772 {
6773         int ret;
6774
6775         ret = btrfs_search_slot(trans, extent_root, extent_key, path, -1, 1);
6776         if (ret)
6777                 goto out;
6778         ret = btrfs_del_item(trans, extent_root, path);
6779 out:
6780         btrfs_release_path(extent_root, path);
6781         return ret;
6782 }
6783
6784 static noinline struct btrfs_root *read_ref_root(struct btrfs_fs_info *fs_info,
6785                                                 struct btrfs_ref_path *ref_path)
6786 {
6787         struct btrfs_key root_key;
6788
6789         root_key.objectid = ref_path->root_objectid;
6790         root_key.type = BTRFS_ROOT_ITEM_KEY;
6791         if (is_cowonly_root(ref_path->root_objectid))
6792                 root_key.offset = 0;
6793         else
6794                 root_key.offset = (u64)-1;
6795
6796         return btrfs_read_fs_root_no_name(fs_info, &root_key);
6797 }
6798
6799 static noinline int relocate_one_extent(struct btrfs_root *extent_root,
6800                                         struct btrfs_path *path,
6801                                         struct btrfs_key *extent_key,
6802                                         struct btrfs_block_group_cache *group,
6803                                         struct inode *reloc_inode, int pass)
6804 {
6805         struct btrfs_trans_handle *trans;
6806         struct btrfs_root *found_root;
6807         struct btrfs_ref_path *ref_path = NULL;
6808         struct disk_extent *new_extents = NULL;
6809         int nr_extents = 0;
6810         int loops;
6811         int ret;
6812         int level;
6813         struct btrfs_key first_key;
6814         u64 prev_block = 0;
6815
6816
6817         trans = btrfs_start_transaction(extent_root, 1);
6818         BUG_ON(!trans);
6819
6820         if (extent_key->objectid == 0) {
6821                 ret = del_extent_zero(trans, extent_root, path, extent_key);
6822                 goto out;
6823         }
6824
6825         ref_path = kmalloc(sizeof(*ref_path), GFP_NOFS);
6826         if (!ref_path) {
6827                 ret = -ENOMEM;
6828                 goto out;
6829         }
6830
6831         for (loops = 0; ; loops++) {
6832                 if (loops == 0) {
6833                         ret = btrfs_first_ref_path(trans, extent_root, ref_path,
6834                                                    extent_key->objectid);
6835                 } else {
6836                         ret = btrfs_next_ref_path(trans, extent_root, ref_path);
6837                 }
6838                 if (ret < 0)
6839                         goto out;
6840                 if (ret > 0)
6841                         break;
6842
6843                 if (ref_path->root_objectid == BTRFS_TREE_LOG_OBJECTID ||
6844                     ref_path->root_objectid == BTRFS_TREE_RELOC_OBJECTID)
6845                         continue;
6846
6847                 found_root = read_ref_root(extent_root->fs_info, ref_path);
6848                 BUG_ON(!found_root);
6849                 /*
6850                  * for reference counted tree, only process reference paths
6851                  * rooted at the latest committed root.
6852                  */
6853                 if (found_root->ref_cows &&
6854                     ref_path->root_generation != found_root->root_key.offset)
6855                         continue;
6856
6857                 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
6858                         if (pass == 0) {
6859                                 /*
6860                                  * copy data extents to new locations
6861                                  */
6862                                 u64 group_start = group->key.objectid;
6863                                 ret = relocate_data_extent(reloc_inode,
6864                                                            extent_key,
6865                                                            group_start);
6866                                 if (ret < 0)
6867                                         goto out;
6868                                 break;
6869                         }
6870                         level = 0;
6871                 } else {
6872                         level = ref_path->owner_objectid;
6873                 }
6874
6875                 if (prev_block != ref_path->nodes[level]) {
6876                         struct extent_buffer *eb;
6877                         u64 block_start = ref_path->nodes[level];
6878                         u64 block_size = btrfs_level_size(found_root, level);
6879
6880                         eb = read_tree_block(found_root, block_start,
6881                                              block_size, 0);
6882                         btrfs_tree_lock(eb);
6883                         BUG_ON(level != btrfs_header_level(eb));
6884
6885                         if (level == 0)
6886                                 btrfs_item_key_to_cpu(eb, &first_key, 0);
6887                         else
6888                                 btrfs_node_key_to_cpu(eb, &first_key, 0);
6889
6890                         btrfs_tree_unlock(eb);
6891                         free_extent_buffer(eb);
6892                         prev_block = block_start;
6893                 }
6894
6895                 mutex_lock(&extent_root->fs_info->trans_mutex);
6896                 btrfs_record_root_in_trans(found_root);
6897                 mutex_unlock(&extent_root->fs_info->trans_mutex);
6898                 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
6899                         /*
6900                          * try to update data extent references while
6901                          * keeping metadata shared between snapshots.
6902                          */
6903                         if (pass == 1) {
6904                                 ret = relocate_one_path(trans, found_root,
6905                                                 path, &first_key, ref_path,
6906                                                 group, reloc_inode);
6907                                 if (ret < 0)
6908                                         goto out;
6909                                 continue;
6910                         }
6911                         /*
6912                          * use fallback method to process the remaining
6913                          * references.
6914                          */
6915                         if (!new_extents) {
6916                                 u64 group_start = group->key.objectid;
6917                                 new_extents = kmalloc(sizeof(*new_extents),
6918                                                       GFP_NOFS);
6919                                 nr_extents = 1;
6920                                 ret = get_new_locations(reloc_inode,
6921                                                         extent_key,
6922                                                         group_start, 1,
6923                                                         &new_extents,
6924                                                         &nr_extents);
6925                                 if (ret)
6926                                         goto out;
6927                         }
6928                         ret = replace_one_extent(trans, found_root,
6929                                                 path, extent_key,
6930                                                 &first_key, ref_path,
6931                                                 new_extents, nr_extents);
6932                 } else {
6933                         ret = relocate_tree_block(trans, found_root, path,
6934                                                   &first_key, ref_path);
6935                 }
6936                 if (ret < 0)
6937                         goto out;
6938         }
6939         ret = 0;
6940 out:
6941         btrfs_end_transaction(trans, extent_root);
6942         kfree(new_extents);
6943         kfree(ref_path);
6944         return ret;
6945 }
6946 #endif
6947
6948 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
6949 {
6950         u64 num_devices;
6951         u64 stripped = BTRFS_BLOCK_GROUP_RAID0 |
6952                 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
6953
6954         num_devices = root->fs_info->fs_devices->rw_devices;
6955         if (num_devices == 1) {
6956                 stripped |= BTRFS_BLOCK_GROUP_DUP;
6957                 stripped = flags & ~stripped;
6958
6959                 /* turn raid0 into single device chunks */
6960                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
6961                         return stripped;
6962
6963                 /* turn mirroring into duplication */
6964                 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
6965                              BTRFS_BLOCK_GROUP_RAID10))
6966                         return stripped | BTRFS_BLOCK_GROUP_DUP;
6967                 return flags;
6968         } else {
6969                 /* they already had raid on here, just return */
6970                 if (flags & stripped)
6971                         return flags;
6972
6973                 stripped |= BTRFS_BLOCK_GROUP_DUP;
6974                 stripped = flags & ~stripped;
6975
6976                 /* switch duplicated blocks with raid1 */
6977                 if (flags & BTRFS_BLOCK_GROUP_DUP)
6978                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
6979
6980                 /* turn single device chunks into raid0 */
6981                 return stripped | BTRFS_BLOCK_GROUP_RAID0;
6982         }
6983         return flags;
6984 }
6985
6986 static int __alloc_chunk_for_shrink(struct btrfs_root *root,
6987                      struct btrfs_block_group_cache *shrink_block_group,
6988                      int force)
6989 {
6990         struct btrfs_trans_handle *trans;
6991         u64 new_alloc_flags;
6992         u64 calc;
6993
6994         spin_lock(&shrink_block_group->lock);
6995         if (btrfs_block_group_used(&shrink_block_group->item) +
6996             shrink_block_group->reserved > 0) {
6997                 spin_unlock(&shrink_block_group->lock);
6998
6999                 trans = btrfs_start_transaction(root, 1);
7000                 spin_lock(&shrink_block_group->lock);
7001
7002                 new_alloc_flags = update_block_group_flags(root,
7003                                                    shrink_block_group->flags);
7004                 if (new_alloc_flags != shrink_block_group->flags) {
7005                         calc =
7006                              btrfs_block_group_used(&shrink_block_group->item);
7007                 } else {
7008                         calc = shrink_block_group->key.offset;
7009                 }
7010                 spin_unlock(&shrink_block_group->lock);
7011
7012                 do_chunk_alloc(trans, root->fs_info->extent_root,
7013                                calc + 2 * 1024 * 1024, new_alloc_flags, force);
7014
7015                 btrfs_end_transaction(trans, root);
7016         } else
7017                 spin_unlock(&shrink_block_group->lock);
7018         return 0;
7019 }
7020
7021
7022 int btrfs_prepare_block_group_relocation(struct btrfs_root *root,
7023                                          struct btrfs_block_group_cache *group)
7024
7025 {
7026         __alloc_chunk_for_shrink(root, group, 1);
7027         set_block_group_readonly(group);
7028         return 0;
7029 }
7030
7031 /*
7032  * checks to see if its even possible to relocate this block group.
7033  *
7034  * @return - -1 if it's not a good idea to relocate this block group, 0 if its
7035  * ok to go ahead and try.
7036  */
7037 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
7038 {
7039         struct btrfs_block_group_cache *block_group;
7040         struct btrfs_space_info *space_info;
7041         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
7042         struct btrfs_device *device;
7043         int full = 0;
7044         int ret = 0;
7045
7046         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
7047
7048         /* odd, couldn't find the block group, leave it alone */
7049         if (!block_group)
7050                 return -1;
7051
7052         /* no bytes used, we're good */
7053         if (!btrfs_block_group_used(&block_group->item))
7054                 goto out;
7055
7056         space_info = block_group->space_info;
7057         spin_lock(&space_info->lock);
7058
7059         full = space_info->full;
7060
7061         /*
7062          * if this is the last block group we have in this space, we can't
7063          * relocate it unless we're able to allocate a new chunk below.
7064          *
7065          * Otherwise, we need to make sure we have room in the space to handle
7066          * all of the extents from this block group.  If we can, we're good
7067          */
7068         if ((space_info->total_bytes != block_group->key.offset) &&
7069            (space_info->bytes_used + space_info->bytes_reserved +
7070             space_info->bytes_pinned + space_info->bytes_readonly +
7071             btrfs_block_group_used(&block_group->item) <
7072             space_info->total_bytes)) {
7073                 spin_unlock(&space_info->lock);
7074                 goto out;
7075         }
7076         spin_unlock(&space_info->lock);
7077
7078         /*
7079          * ok we don't have enough space, but maybe we have free space on our
7080          * devices to allocate new chunks for relocation, so loop through our
7081          * alloc devices and guess if we have enough space.  However, if we
7082          * were marked as full, then we know there aren't enough chunks, and we
7083          * can just return.
7084          */
7085         ret = -1;
7086         if (full)
7087                 goto out;
7088
7089         mutex_lock(&root->fs_info->chunk_mutex);
7090         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7091                 u64 min_free = btrfs_block_group_used(&block_group->item);
7092                 u64 dev_offset, max_avail;
7093
7094                 /*
7095                  * check to make sure we can actually find a chunk with enough
7096                  * space to fit our block group in.
7097                  */
7098                 if (device->total_bytes > device->bytes_used + min_free) {
7099                         ret = find_free_dev_extent(NULL, device, min_free,
7100                                                    &dev_offset, &max_avail);
7101                         if (!ret)
7102                                 break;
7103                         ret = -1;
7104                 }
7105         }
7106         mutex_unlock(&root->fs_info->chunk_mutex);
7107 out:
7108         btrfs_put_block_group(block_group);
7109         return ret;
7110 }
7111
7112 static int find_first_block_group(struct btrfs_root *root,
7113                 struct btrfs_path *path, struct btrfs_key *key)
7114 {
7115         int ret = 0;
7116         struct btrfs_key found_key;
7117         struct extent_buffer *leaf;
7118         int slot;
7119
7120         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7121         if (ret < 0)
7122                 goto out;
7123
7124         while (1) {
7125                 slot = path->slots[0];
7126                 leaf = path->nodes[0];
7127                 if (slot >= btrfs_header_nritems(leaf)) {
7128                         ret = btrfs_next_leaf(root, path);
7129                         if (ret == 0)
7130                                 continue;
7131                         if (ret < 0)
7132                                 goto out;
7133                         break;
7134                 }
7135                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7136
7137                 if (found_key.objectid >= key->objectid &&
7138                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
7139                         ret = 0;
7140                         goto out;
7141                 }
7142                 path->slots[0]++;
7143         }
7144         ret = -ENOENT;
7145 out:
7146         return ret;
7147 }
7148
7149 int btrfs_free_block_groups(struct btrfs_fs_info *info)
7150 {
7151         struct btrfs_block_group_cache *block_group;
7152         struct btrfs_space_info *space_info;
7153         struct btrfs_caching_control *caching_ctl;
7154         struct rb_node *n;
7155
7156         down_write(&info->extent_commit_sem);
7157         while (!list_empty(&info->caching_block_groups)) {
7158                 caching_ctl = list_entry(info->caching_block_groups.next,
7159                                          struct btrfs_caching_control, list);
7160                 list_del(&caching_ctl->list);
7161                 put_caching_control(caching_ctl);
7162         }
7163         up_write(&info->extent_commit_sem);
7164
7165         spin_lock(&info->block_group_cache_lock);
7166         while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
7167                 block_group = rb_entry(n, struct btrfs_block_group_cache,
7168                                        cache_node);
7169                 rb_erase(&block_group->cache_node,
7170                          &info->block_group_cache_tree);
7171                 spin_unlock(&info->block_group_cache_lock);
7172
7173                 down_write(&block_group->space_info->groups_sem);
7174                 list_del(&block_group->list);
7175                 up_write(&block_group->space_info->groups_sem);
7176
7177                 if (block_group->cached == BTRFS_CACHE_STARTED)
7178                         wait_block_group_cache_done(block_group);
7179
7180                 btrfs_remove_free_space_cache(block_group);
7181
7182                 WARN_ON(atomic_read(&block_group->count) != 1);
7183                 kfree(block_group);
7184
7185                 spin_lock(&info->block_group_cache_lock);
7186         }
7187         spin_unlock(&info->block_group_cache_lock);
7188
7189         /* now that all the block groups are freed, go through and
7190          * free all the space_info structs.  This is only called during
7191          * the final stages of unmount, and so we know nobody is
7192          * using them.  We call synchronize_rcu() once before we start,
7193          * just to be on the safe side.
7194          */
7195         synchronize_rcu();
7196
7197         while(!list_empty(&info->space_info)) {
7198                 space_info = list_entry(info->space_info.next,
7199                                         struct btrfs_space_info,
7200                                         list);
7201
7202                 list_del(&space_info->list);
7203                 kfree(space_info);
7204         }
7205         return 0;
7206 }
7207
7208 int btrfs_read_block_groups(struct btrfs_root *root)
7209 {
7210         struct btrfs_path *path;
7211         int ret;
7212         struct btrfs_block_group_cache *cache;
7213         struct btrfs_fs_info *info = root->fs_info;
7214         struct btrfs_space_info *space_info;
7215         struct btrfs_key key;
7216         struct btrfs_key found_key;
7217         struct extent_buffer *leaf;
7218
7219         root = info->extent_root;
7220         key.objectid = 0;
7221         key.offset = 0;
7222         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
7223         path = btrfs_alloc_path();
7224         if (!path)
7225                 return -ENOMEM;
7226
7227         while (1) {
7228                 ret = find_first_block_group(root, path, &key);
7229                 if (ret > 0) {
7230                         ret = 0;
7231                         goto error;
7232                 }
7233                 if (ret != 0)
7234                         goto error;
7235
7236                 leaf = path->nodes[0];
7237                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7238                 cache = kzalloc(sizeof(*cache), GFP_NOFS);
7239                 if (!cache) {
7240                         ret = -ENOMEM;
7241                         break;
7242                 }
7243
7244                 atomic_set(&cache->count, 1);
7245                 spin_lock_init(&cache->lock);
7246                 spin_lock_init(&cache->tree_lock);
7247                 cache->fs_info = info;
7248                 INIT_LIST_HEAD(&cache->list);
7249                 INIT_LIST_HEAD(&cache->cluster_list);
7250
7251                 /*
7252                  * we only want to have 32k of ram per block group for keeping
7253                  * track of free space, and if we pass 1/2 of that we want to
7254                  * start converting things over to using bitmaps
7255                  */
7256                 cache->extents_thresh = ((1024 * 32) / 2) /
7257                         sizeof(struct btrfs_free_space);
7258
7259                 read_extent_buffer(leaf, &cache->item,
7260                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
7261                                    sizeof(cache->item));
7262                 memcpy(&cache->key, &found_key, sizeof(found_key));
7263
7264                 key.objectid = found_key.objectid + found_key.offset;
7265                 btrfs_release_path(root, path);
7266                 cache->flags = btrfs_block_group_flags(&cache->item);
7267                 cache->sectorsize = root->sectorsize;
7268
7269                 /*
7270                  * check for two cases, either we are full, and therefore
7271                  * don't need to bother with the caching work since we won't
7272                  * find any space, or we are empty, and we can just add all
7273                  * the space in and be done with it.  This saves us _alot_ of
7274                  * time, particularly in the full case.
7275                  */
7276                 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
7277                         exclude_super_stripes(root, cache);
7278                         cache->last_byte_to_unpin = (u64)-1;
7279                         cache->cached = BTRFS_CACHE_FINISHED;
7280                         free_excluded_extents(root, cache);
7281                 } else if (btrfs_block_group_used(&cache->item) == 0) {
7282                         exclude_super_stripes(root, cache);
7283                         cache->last_byte_to_unpin = (u64)-1;
7284                         cache->cached = BTRFS_CACHE_FINISHED;
7285                         add_new_free_space(cache, root->fs_info,
7286                                            found_key.objectid,
7287                                            found_key.objectid +
7288                                            found_key.offset);
7289                         free_excluded_extents(root, cache);
7290                 }
7291
7292                 ret = update_space_info(info, cache->flags, found_key.offset,
7293                                         btrfs_block_group_used(&cache->item),
7294                                         &space_info);
7295                 BUG_ON(ret);
7296                 cache->space_info = space_info;
7297                 spin_lock(&cache->space_info->lock);
7298                 cache->space_info->bytes_super += cache->bytes_super;
7299                 spin_unlock(&cache->space_info->lock);
7300
7301                 down_write(&space_info->groups_sem);
7302                 list_add_tail(&cache->list, &space_info->block_groups);
7303                 up_write(&space_info->groups_sem);
7304
7305                 ret = btrfs_add_block_group_cache(root->fs_info, cache);
7306                 BUG_ON(ret);
7307
7308                 set_avail_alloc_bits(root->fs_info, cache->flags);
7309                 if (btrfs_chunk_readonly(root, cache->key.objectid))
7310                         set_block_group_readonly(cache);
7311         }
7312         ret = 0;
7313 error:
7314         btrfs_free_path(path);
7315         return ret;
7316 }
7317
7318 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
7319                            struct btrfs_root *root, u64 bytes_used,
7320                            u64 type, u64 chunk_objectid, u64 chunk_offset,
7321                            u64 size)
7322 {
7323         int ret;
7324         struct btrfs_root *extent_root;
7325         struct btrfs_block_group_cache *cache;
7326
7327         extent_root = root->fs_info->extent_root;
7328
7329         root->fs_info->last_trans_log_full_commit = trans->transid;
7330
7331         cache = kzalloc(sizeof(*cache), GFP_NOFS);
7332         if (!cache)
7333                 return -ENOMEM;
7334
7335         cache->key.objectid = chunk_offset;
7336         cache->key.offset = size;
7337         cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
7338         cache->sectorsize = root->sectorsize;
7339
7340         /*
7341          * we only want to have 32k of ram per block group for keeping track
7342          * of free space, and if we pass 1/2 of that we want to start
7343          * converting things over to using bitmaps
7344          */
7345         cache->extents_thresh = ((1024 * 32) / 2) /
7346                 sizeof(struct btrfs_free_space);
7347         atomic_set(&cache->count, 1);
7348         spin_lock_init(&cache->lock);
7349         spin_lock_init(&cache->tree_lock);
7350         INIT_LIST_HEAD(&cache->list);
7351         INIT_LIST_HEAD(&cache->cluster_list);
7352
7353         btrfs_set_block_group_used(&cache->item, bytes_used);
7354         btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
7355         cache->flags = type;
7356         btrfs_set_block_group_flags(&cache->item, type);
7357
7358         cache->last_byte_to_unpin = (u64)-1;
7359         cache->cached = BTRFS_CACHE_FINISHED;
7360         exclude_super_stripes(root, cache);
7361
7362         add_new_free_space(cache, root->fs_info, chunk_offset,
7363                            chunk_offset + size);
7364
7365         free_excluded_extents(root, cache);
7366
7367         ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
7368                                 &cache->space_info);
7369         BUG_ON(ret);
7370
7371         spin_lock(&cache->space_info->lock);
7372         cache->space_info->bytes_super += cache->bytes_super;
7373         spin_unlock(&cache->space_info->lock);
7374
7375         down_write(&cache->space_info->groups_sem);
7376         list_add_tail(&cache->list, &cache->space_info->block_groups);
7377         up_write(&cache->space_info->groups_sem);
7378
7379         ret = btrfs_add_block_group_cache(root->fs_info, cache);
7380         BUG_ON(ret);
7381
7382         ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
7383                                 sizeof(cache->item));
7384         BUG_ON(ret);
7385
7386         set_avail_alloc_bits(extent_root->fs_info, type);
7387
7388         return 0;
7389 }
7390
7391 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
7392                              struct btrfs_root *root, u64 group_start)
7393 {
7394         struct btrfs_path *path;
7395         struct btrfs_block_group_cache *block_group;
7396         struct btrfs_free_cluster *cluster;
7397         struct btrfs_key key;
7398         int ret;
7399
7400         root = root->fs_info->extent_root;
7401
7402         block_group = btrfs_lookup_block_group(root->fs_info, group_start);
7403         BUG_ON(!block_group);
7404         BUG_ON(!block_group->ro);
7405
7406         memcpy(&key, &block_group->key, sizeof(key));
7407
7408         /* make sure this block group isn't part of an allocation cluster */
7409         cluster = &root->fs_info->data_alloc_cluster;
7410         spin_lock(&cluster->refill_lock);
7411         btrfs_return_cluster_to_free_space(block_group, cluster);
7412         spin_unlock(&cluster->refill_lock);
7413
7414         /*
7415          * make sure this block group isn't part of a metadata
7416          * allocation cluster
7417          */
7418         cluster = &root->fs_info->meta_alloc_cluster;
7419         spin_lock(&cluster->refill_lock);
7420         btrfs_return_cluster_to_free_space(block_group, cluster);
7421         spin_unlock(&cluster->refill_lock);
7422
7423         path = btrfs_alloc_path();
7424         BUG_ON(!path);
7425
7426         spin_lock(&root->fs_info->block_group_cache_lock);
7427         rb_erase(&block_group->cache_node,
7428                  &root->fs_info->block_group_cache_tree);
7429         spin_unlock(&root->fs_info->block_group_cache_lock);
7430
7431         down_write(&block_group->space_info->groups_sem);
7432         /*
7433          * we must use list_del_init so people can check to see if they
7434          * are still on the list after taking the semaphore
7435          */
7436         list_del_init(&block_group->list);
7437         up_write(&block_group->space_info->groups_sem);
7438
7439         if (block_group->cached == BTRFS_CACHE_STARTED)
7440                 wait_block_group_cache_done(block_group);
7441
7442         btrfs_remove_free_space_cache(block_group);
7443
7444         spin_lock(&block_group->space_info->lock);
7445         block_group->space_info->total_bytes -= block_group->key.offset;
7446         block_group->space_info->bytes_readonly -= block_group->key.offset;
7447         spin_unlock(&block_group->space_info->lock);
7448
7449         btrfs_clear_space_info_full(root->fs_info);
7450
7451         btrfs_put_block_group(block_group);
7452         btrfs_put_block_group(block_group);
7453
7454         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
7455         if (ret > 0)
7456                 ret = -EIO;
7457         if (ret < 0)
7458                 goto out;
7459
7460         ret = btrfs_del_item(trans, root, path);
7461 out:
7462         btrfs_free_path(path);
7463         return ret;
7464 }