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