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