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