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