Btrfs: improve the noflush reservation
[sfrench/cifs-2.6.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->mapping_tree, 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                                         printk(KERN_DEBUG "btrfs: run_delayed_extent_op returned %d\n", ret);
2301                                         spin_lock(&delayed_refs->lock);
2302                                         return ret;
2303                                 }
2304
2305                                 goto next;
2306                         }
2307
2308                         list_del_init(&locked_ref->cluster);
2309                         locked_ref = NULL;
2310                 }
2311
2312                 ref->in_tree = 0;
2313                 rb_erase(&ref->rb_node, &delayed_refs->root);
2314                 delayed_refs->num_entries--;
2315                 if (locked_ref) {
2316                         /*
2317                          * when we play the delayed ref, also correct the
2318                          * ref_mod on head
2319                          */
2320                         switch (ref->action) {
2321                         case BTRFS_ADD_DELAYED_REF:
2322                         case BTRFS_ADD_DELAYED_EXTENT:
2323                                 locked_ref->node.ref_mod -= ref->ref_mod;
2324                                 break;
2325                         case BTRFS_DROP_DELAYED_REF:
2326                                 locked_ref->node.ref_mod += ref->ref_mod;
2327                                 break;
2328                         default:
2329                                 WARN_ON(1);
2330                         }
2331                 }
2332                 spin_unlock(&delayed_refs->lock);
2333
2334                 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2335                                           must_insert_reserved);
2336
2337                 btrfs_put_delayed_ref(ref);
2338                 kfree(extent_op);
2339                 count++;
2340
2341                 if (ret) {
2342                         printk(KERN_DEBUG "btrfs: run_one_delayed_ref returned %d\n", ret);
2343                         spin_lock(&delayed_refs->lock);
2344                         return ret;
2345                 }
2346
2347 next:
2348                 cond_resched();
2349                 spin_lock(&delayed_refs->lock);
2350         }
2351         return count;
2352 }
2353
2354 #ifdef SCRAMBLE_DELAYED_REFS
2355 /*
2356  * Normally delayed refs get processed in ascending bytenr order. This
2357  * correlates in most cases to the order added. To expose dependencies on this
2358  * order, we start to process the tree in the middle instead of the beginning
2359  */
2360 static u64 find_middle(struct rb_root *root)
2361 {
2362         struct rb_node *n = root->rb_node;
2363         struct btrfs_delayed_ref_node *entry;
2364         int alt = 1;
2365         u64 middle;
2366         u64 first = 0, last = 0;
2367
2368         n = rb_first(root);
2369         if (n) {
2370                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2371                 first = entry->bytenr;
2372         }
2373         n = rb_last(root);
2374         if (n) {
2375                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2376                 last = entry->bytenr;
2377         }
2378         n = root->rb_node;
2379
2380         while (n) {
2381                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2382                 WARN_ON(!entry->in_tree);
2383
2384                 middle = entry->bytenr;
2385
2386                 if (alt)
2387                         n = n->rb_left;
2388                 else
2389                         n = n->rb_right;
2390
2391                 alt = 1 - alt;
2392         }
2393         return middle;
2394 }
2395 #endif
2396
2397 int btrfs_delayed_refs_qgroup_accounting(struct btrfs_trans_handle *trans,
2398                                          struct btrfs_fs_info *fs_info)
2399 {
2400         struct qgroup_update *qgroup_update;
2401         int ret = 0;
2402
2403         if (list_empty(&trans->qgroup_ref_list) !=
2404             !trans->delayed_ref_elem.seq) {
2405                 /* list without seq or seq without list */
2406                 printk(KERN_ERR "btrfs: qgroup accounting update error, list is%s empty, seq is %llu\n",
2407                         list_empty(&trans->qgroup_ref_list) ? "" : " not",
2408                         trans->delayed_ref_elem.seq);
2409                 BUG();
2410         }
2411
2412         if (!trans->delayed_ref_elem.seq)
2413                 return 0;
2414
2415         while (!list_empty(&trans->qgroup_ref_list)) {
2416                 qgroup_update = list_first_entry(&trans->qgroup_ref_list,
2417                                                  struct qgroup_update, list);
2418                 list_del(&qgroup_update->list);
2419                 if (!ret)
2420                         ret = btrfs_qgroup_account_ref(
2421                                         trans, fs_info, qgroup_update->node,
2422                                         qgroup_update->extent_op);
2423                 kfree(qgroup_update);
2424         }
2425
2426         btrfs_put_tree_mod_seq(fs_info, &trans->delayed_ref_elem);
2427
2428         return ret;
2429 }
2430
2431 /*
2432  * this starts processing the delayed reference count updates and
2433  * extent insertions we have queued up so far.  count can be
2434  * 0, which means to process everything in the tree at the start
2435  * of the run (but not newly added entries), or it can be some target
2436  * number you'd like to process.
2437  *
2438  * Returns 0 on success or if called with an aborted transaction
2439  * Returns <0 on error and aborts the transaction
2440  */
2441 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2442                            struct btrfs_root *root, unsigned long count)
2443 {
2444         struct rb_node *node;
2445         struct btrfs_delayed_ref_root *delayed_refs;
2446         struct btrfs_delayed_ref_node *ref;
2447         struct list_head cluster;
2448         int ret;
2449         u64 delayed_start;
2450         int run_all = count == (unsigned long)-1;
2451         int run_most = 0;
2452         int loops;
2453
2454         /* We'll clean this up in btrfs_cleanup_transaction */
2455         if (trans->aborted)
2456                 return 0;
2457
2458         if (root == root->fs_info->extent_root)
2459                 root = root->fs_info->tree_root;
2460
2461         btrfs_delayed_refs_qgroup_accounting(trans, root->fs_info);
2462
2463         delayed_refs = &trans->transaction->delayed_refs;
2464         INIT_LIST_HEAD(&cluster);
2465 again:
2466         loops = 0;
2467         spin_lock(&delayed_refs->lock);
2468
2469 #ifdef SCRAMBLE_DELAYED_REFS
2470         delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2471 #endif
2472
2473         if (count == 0) {
2474                 count = delayed_refs->num_entries * 2;
2475                 run_most = 1;
2476         }
2477         while (1) {
2478                 if (!(run_all || run_most) &&
2479                     delayed_refs->num_heads_ready < 64)
2480                         break;
2481
2482                 /*
2483                  * go find something we can process in the rbtree.  We start at
2484                  * the beginning of the tree, and then build a cluster
2485                  * of refs to process starting at the first one we are able to
2486                  * lock
2487                  */
2488                 delayed_start = delayed_refs->run_delayed_start;
2489                 ret = btrfs_find_ref_cluster(trans, &cluster,
2490                                              delayed_refs->run_delayed_start);
2491                 if (ret)
2492                         break;
2493
2494                 ret = run_clustered_refs(trans, root, &cluster);
2495                 if (ret < 0) {
2496                         spin_unlock(&delayed_refs->lock);
2497                         btrfs_abort_transaction(trans, root, ret);
2498                         return ret;
2499                 }
2500
2501                 count -= min_t(unsigned long, ret, count);
2502
2503                 if (count == 0)
2504                         break;
2505
2506                 if (delayed_start >= delayed_refs->run_delayed_start) {
2507                         if (loops == 0) {
2508                                 /*
2509                                  * btrfs_find_ref_cluster looped. let's do one
2510                                  * more cycle. if we don't run any delayed ref
2511                                  * during that cycle (because we can't because
2512                                  * all of them are blocked), bail out.
2513                                  */
2514                                 loops = 1;
2515                         } else {
2516                                 /*
2517                                  * no runnable refs left, stop trying
2518                                  */
2519                                 BUG_ON(run_all);
2520                                 break;
2521                         }
2522                 }
2523                 if (ret) {
2524                         /* refs were run, let's reset staleness detection */
2525                         loops = 0;
2526                 }
2527         }
2528
2529         if (run_all) {
2530                 if (!list_empty(&trans->new_bgs)) {
2531                         spin_unlock(&delayed_refs->lock);
2532                         btrfs_create_pending_block_groups(trans, root);
2533                         spin_lock(&delayed_refs->lock);
2534                 }
2535
2536                 node = rb_first(&delayed_refs->root);
2537                 if (!node)
2538                         goto out;
2539                 count = (unsigned long)-1;
2540
2541                 while (node) {
2542                         ref = rb_entry(node, struct btrfs_delayed_ref_node,
2543                                        rb_node);
2544                         if (btrfs_delayed_ref_is_head(ref)) {
2545                                 struct btrfs_delayed_ref_head *head;
2546
2547                                 head = btrfs_delayed_node_to_head(ref);
2548                                 atomic_inc(&ref->refs);
2549
2550                                 spin_unlock(&delayed_refs->lock);
2551                                 /*
2552                                  * Mutex was contended, block until it's
2553                                  * released and try again
2554                                  */
2555                                 mutex_lock(&head->mutex);
2556                                 mutex_unlock(&head->mutex);
2557
2558                                 btrfs_put_delayed_ref(ref);
2559                                 cond_resched();
2560                                 goto again;
2561                         }
2562                         node = rb_next(node);
2563                 }
2564                 spin_unlock(&delayed_refs->lock);
2565                 schedule_timeout(1);
2566                 goto again;
2567         }
2568 out:
2569         spin_unlock(&delayed_refs->lock);
2570         assert_qgroups_uptodate(trans);
2571         return 0;
2572 }
2573
2574 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2575                                 struct btrfs_root *root,
2576                                 u64 bytenr, u64 num_bytes, u64 flags,
2577                                 int is_data)
2578 {
2579         struct btrfs_delayed_extent_op *extent_op;
2580         int ret;
2581
2582         extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
2583         if (!extent_op)
2584                 return -ENOMEM;
2585
2586         extent_op->flags_to_set = flags;
2587         extent_op->update_flags = 1;
2588         extent_op->update_key = 0;
2589         extent_op->is_data = is_data ? 1 : 0;
2590
2591         ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
2592                                           num_bytes, extent_op);
2593         if (ret)
2594                 kfree(extent_op);
2595         return ret;
2596 }
2597
2598 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
2599                                       struct btrfs_root *root,
2600                                       struct btrfs_path *path,
2601                                       u64 objectid, u64 offset, u64 bytenr)
2602 {
2603         struct btrfs_delayed_ref_head *head;
2604         struct btrfs_delayed_ref_node *ref;
2605         struct btrfs_delayed_data_ref *data_ref;
2606         struct btrfs_delayed_ref_root *delayed_refs;
2607         struct rb_node *node;
2608         int ret = 0;
2609
2610         ret = -ENOENT;
2611         delayed_refs = &trans->transaction->delayed_refs;
2612         spin_lock(&delayed_refs->lock);
2613         head = btrfs_find_delayed_ref_head(trans, bytenr);
2614         if (!head)
2615                 goto out;
2616
2617         if (!mutex_trylock(&head->mutex)) {
2618                 atomic_inc(&head->node.refs);
2619                 spin_unlock(&delayed_refs->lock);
2620
2621                 btrfs_release_path(path);
2622
2623                 /*
2624                  * Mutex was contended, block until it's released and let
2625                  * caller try again
2626                  */
2627                 mutex_lock(&head->mutex);
2628                 mutex_unlock(&head->mutex);
2629                 btrfs_put_delayed_ref(&head->node);
2630                 return -EAGAIN;
2631         }
2632
2633         node = rb_prev(&head->node.rb_node);
2634         if (!node)
2635                 goto out_unlock;
2636
2637         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2638
2639         if (ref->bytenr != bytenr)
2640                 goto out_unlock;
2641
2642         ret = 1;
2643         if (ref->type != BTRFS_EXTENT_DATA_REF_KEY)
2644                 goto out_unlock;
2645
2646         data_ref = btrfs_delayed_node_to_data_ref(ref);
2647
2648         node = rb_prev(node);
2649         if (node) {
2650                 int seq = ref->seq;
2651
2652                 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
2653                 if (ref->bytenr == bytenr && ref->seq == seq)
2654                         goto out_unlock;
2655         }
2656
2657         if (data_ref->root != root->root_key.objectid ||
2658             data_ref->objectid != objectid || data_ref->offset != offset)
2659                 goto out_unlock;
2660
2661         ret = 0;
2662 out_unlock:
2663         mutex_unlock(&head->mutex);
2664 out:
2665         spin_unlock(&delayed_refs->lock);
2666         return ret;
2667 }
2668
2669 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
2670                                         struct btrfs_root *root,
2671                                         struct btrfs_path *path,
2672                                         u64 objectid, u64 offset, u64 bytenr)
2673 {
2674         struct btrfs_root *extent_root = root->fs_info->extent_root;
2675         struct extent_buffer *leaf;
2676         struct btrfs_extent_data_ref *ref;
2677         struct btrfs_extent_inline_ref *iref;
2678         struct btrfs_extent_item *ei;
2679         struct btrfs_key key;
2680         u32 item_size;
2681         int ret;
2682
2683         key.objectid = bytenr;
2684         key.offset = (u64)-1;
2685         key.type = BTRFS_EXTENT_ITEM_KEY;
2686
2687         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
2688         if (ret < 0)
2689                 goto out;
2690         BUG_ON(ret == 0); /* Corruption */
2691
2692         ret = -ENOENT;
2693         if (path->slots[0] == 0)
2694                 goto out;
2695
2696         path->slots[0]--;
2697         leaf = path->nodes[0];
2698         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2699
2700         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
2701                 goto out;
2702
2703         ret = 1;
2704         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2705 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2706         if (item_size < sizeof(*ei)) {
2707                 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
2708                 goto out;
2709         }
2710 #endif
2711         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2712
2713         if (item_size != sizeof(*ei) +
2714             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
2715                 goto out;
2716
2717         if (btrfs_extent_generation(leaf, ei) <=
2718             btrfs_root_last_snapshot(&root->root_item))
2719                 goto out;
2720
2721         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
2722         if (btrfs_extent_inline_ref_type(leaf, iref) !=
2723             BTRFS_EXTENT_DATA_REF_KEY)
2724                 goto out;
2725
2726         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
2727         if (btrfs_extent_refs(leaf, ei) !=
2728             btrfs_extent_data_ref_count(leaf, ref) ||
2729             btrfs_extent_data_ref_root(leaf, ref) !=
2730             root->root_key.objectid ||
2731             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
2732             btrfs_extent_data_ref_offset(leaf, ref) != offset)
2733                 goto out;
2734
2735         ret = 0;
2736 out:
2737         return ret;
2738 }
2739
2740 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
2741                           struct btrfs_root *root,
2742                           u64 objectid, u64 offset, u64 bytenr)
2743 {
2744         struct btrfs_path *path;
2745         int ret;
2746         int ret2;
2747
2748         path = btrfs_alloc_path();
2749         if (!path)
2750                 return -ENOENT;
2751
2752         do {
2753                 ret = check_committed_ref(trans, root, path, objectid,
2754                                           offset, bytenr);
2755                 if (ret && ret != -ENOENT)
2756                         goto out;
2757
2758                 ret2 = check_delayed_ref(trans, root, path, objectid,
2759                                          offset, bytenr);
2760         } while (ret2 == -EAGAIN);
2761
2762         if (ret2 && ret2 != -ENOENT) {
2763                 ret = ret2;
2764                 goto out;
2765         }
2766
2767         if (ret != -ENOENT || ret2 != -ENOENT)
2768                 ret = 0;
2769 out:
2770         btrfs_free_path(path);
2771         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
2772                 WARN_ON(ret > 0);
2773         return ret;
2774 }
2775
2776 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
2777                            struct btrfs_root *root,
2778                            struct extent_buffer *buf,
2779                            int full_backref, int inc, int for_cow)
2780 {
2781         u64 bytenr;
2782         u64 num_bytes;
2783         u64 parent;
2784         u64 ref_root;
2785         u32 nritems;
2786         struct btrfs_key key;
2787         struct btrfs_file_extent_item *fi;
2788         int i;
2789         int level;
2790         int ret = 0;
2791         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
2792                             u64, u64, u64, u64, u64, u64, int);
2793
2794         ref_root = btrfs_header_owner(buf);
2795         nritems = btrfs_header_nritems(buf);
2796         level = btrfs_header_level(buf);
2797
2798         if (!root->ref_cows && level == 0)
2799                 return 0;
2800
2801         if (inc)
2802                 process_func = btrfs_inc_extent_ref;
2803         else
2804                 process_func = btrfs_free_extent;
2805
2806         if (full_backref)
2807                 parent = buf->start;
2808         else
2809                 parent = 0;
2810
2811         for (i = 0; i < nritems; i++) {
2812                 if (level == 0) {
2813                         btrfs_item_key_to_cpu(buf, &key, i);
2814                         if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
2815                                 continue;
2816                         fi = btrfs_item_ptr(buf, i,
2817                                             struct btrfs_file_extent_item);
2818                         if (btrfs_file_extent_type(buf, fi) ==
2819                             BTRFS_FILE_EXTENT_INLINE)
2820                                 continue;
2821                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
2822                         if (bytenr == 0)
2823                                 continue;
2824
2825                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
2826                         key.offset -= btrfs_file_extent_offset(buf, fi);
2827                         ret = process_func(trans, root, bytenr, num_bytes,
2828                                            parent, ref_root, key.objectid,
2829                                            key.offset, for_cow);
2830                         if (ret)
2831                                 goto fail;
2832                 } else {
2833                         bytenr = btrfs_node_blockptr(buf, i);
2834                         num_bytes = btrfs_level_size(root, level - 1);
2835                         ret = process_func(trans, root, bytenr, num_bytes,
2836                                            parent, ref_root, level - 1, 0,
2837                                            for_cow);
2838                         if (ret)
2839                                 goto fail;
2840                 }
2841         }
2842         return 0;
2843 fail:
2844         return ret;
2845 }
2846
2847 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2848                   struct extent_buffer *buf, int full_backref, int for_cow)
2849 {
2850         return __btrfs_mod_ref(trans, root, buf, full_backref, 1, for_cow);
2851 }
2852
2853 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
2854                   struct extent_buffer *buf, int full_backref, int for_cow)
2855 {
2856         return __btrfs_mod_ref(trans, root, buf, full_backref, 0, for_cow);
2857 }
2858
2859 static int write_one_cache_group(struct btrfs_trans_handle *trans,
2860                                  struct btrfs_root *root,
2861                                  struct btrfs_path *path,
2862                                  struct btrfs_block_group_cache *cache)
2863 {
2864         int ret;
2865         struct btrfs_root *extent_root = root->fs_info->extent_root;
2866         unsigned long bi;
2867         struct extent_buffer *leaf;
2868
2869         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
2870         if (ret < 0)
2871                 goto fail;
2872         BUG_ON(ret); /* Corruption */
2873
2874         leaf = path->nodes[0];
2875         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
2876         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
2877         btrfs_mark_buffer_dirty(leaf);
2878         btrfs_release_path(path);
2879 fail:
2880         if (ret) {
2881                 btrfs_abort_transaction(trans, root, ret);
2882                 return ret;
2883         }
2884         return 0;
2885
2886 }
2887
2888 static struct btrfs_block_group_cache *
2889 next_block_group(struct btrfs_root *root,
2890                  struct btrfs_block_group_cache *cache)
2891 {
2892         struct rb_node *node;
2893         spin_lock(&root->fs_info->block_group_cache_lock);
2894         node = rb_next(&cache->cache_node);
2895         btrfs_put_block_group(cache);
2896         if (node) {
2897                 cache = rb_entry(node, struct btrfs_block_group_cache,
2898                                  cache_node);
2899                 btrfs_get_block_group(cache);
2900         } else
2901                 cache = NULL;
2902         spin_unlock(&root->fs_info->block_group_cache_lock);
2903         return cache;
2904 }
2905
2906 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
2907                             struct btrfs_trans_handle *trans,
2908                             struct btrfs_path *path)
2909 {
2910         struct btrfs_root *root = block_group->fs_info->tree_root;
2911         struct inode *inode = NULL;
2912         u64 alloc_hint = 0;
2913         int dcs = BTRFS_DC_ERROR;
2914         int num_pages = 0;
2915         int retries = 0;
2916         int ret = 0;
2917
2918         /*
2919          * If this block group is smaller than 100 megs don't bother caching the
2920          * block group.
2921          */
2922         if (block_group->key.offset < (100 * 1024 * 1024)) {
2923                 spin_lock(&block_group->lock);
2924                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
2925                 spin_unlock(&block_group->lock);
2926                 return 0;
2927         }
2928
2929 again:
2930         inode = lookup_free_space_inode(root, block_group, path);
2931         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
2932                 ret = PTR_ERR(inode);
2933                 btrfs_release_path(path);
2934                 goto out;
2935         }
2936
2937         if (IS_ERR(inode)) {
2938                 BUG_ON(retries);
2939                 retries++;
2940
2941                 if (block_group->ro)
2942                         goto out_free;
2943
2944                 ret = create_free_space_inode(root, trans, block_group, path);
2945                 if (ret)
2946                         goto out_free;
2947                 goto again;
2948         }
2949
2950         /* We've already setup this transaction, go ahead and exit */
2951         if (block_group->cache_generation == trans->transid &&
2952             i_size_read(inode)) {
2953                 dcs = BTRFS_DC_SETUP;
2954                 goto out_put;
2955         }
2956
2957         /*
2958          * We want to set the generation to 0, that way if anything goes wrong
2959          * from here on out we know not to trust this cache when we load up next
2960          * time.
2961          */
2962         BTRFS_I(inode)->generation = 0;
2963         ret = btrfs_update_inode(trans, root, inode);
2964         WARN_ON(ret);
2965
2966         if (i_size_read(inode) > 0) {
2967                 ret = btrfs_truncate_free_space_cache(root, trans, path,
2968                                                       inode);
2969                 if (ret)
2970                         goto out_put;
2971         }
2972
2973         spin_lock(&block_group->lock);
2974         if (block_group->cached != BTRFS_CACHE_FINISHED ||
2975             !btrfs_test_opt(root, SPACE_CACHE)) {
2976                 /*
2977                  * don't bother trying to write stuff out _if_
2978                  * a) we're not cached,
2979                  * b) we're with nospace_cache mount option.
2980                  */
2981                 dcs = BTRFS_DC_WRITTEN;
2982                 spin_unlock(&block_group->lock);
2983                 goto out_put;
2984         }
2985         spin_unlock(&block_group->lock);
2986
2987         /*
2988          * Try to preallocate enough space based on how big the block group is.
2989          * Keep in mind this has to include any pinned space which could end up
2990          * taking up quite a bit since it's not folded into the other space
2991          * cache.
2992          */
2993         num_pages = (int)div64_u64(block_group->key.offset, 256 * 1024 * 1024);
2994         if (!num_pages)
2995                 num_pages = 1;
2996
2997         num_pages *= 16;
2998         num_pages *= PAGE_CACHE_SIZE;
2999
3000         ret = btrfs_check_data_free_space(inode, num_pages);
3001         if (ret)
3002                 goto out_put;
3003
3004         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3005                                               num_pages, num_pages,
3006                                               &alloc_hint);
3007         if (!ret)
3008                 dcs = BTRFS_DC_SETUP;
3009         btrfs_free_reserved_data_space(inode, num_pages);
3010
3011 out_put:
3012         iput(inode);
3013 out_free:
3014         btrfs_release_path(path);
3015 out:
3016         spin_lock(&block_group->lock);
3017         if (!ret && dcs == BTRFS_DC_SETUP)
3018                 block_group->cache_generation = trans->transid;
3019         block_group->disk_cache_state = dcs;
3020         spin_unlock(&block_group->lock);
3021
3022         return ret;
3023 }
3024
3025 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3026                                    struct btrfs_root *root)
3027 {
3028         struct btrfs_block_group_cache *cache;
3029         int err = 0;
3030         struct btrfs_path *path;
3031         u64 last = 0;
3032
3033         path = btrfs_alloc_path();
3034         if (!path)
3035                 return -ENOMEM;
3036
3037 again:
3038         while (1) {
3039                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3040                 while (cache) {
3041                         if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3042                                 break;
3043                         cache = next_block_group(root, cache);
3044                 }
3045                 if (!cache) {
3046                         if (last == 0)
3047                                 break;
3048                         last = 0;
3049                         continue;
3050                 }
3051                 err = cache_save_setup(cache, trans, path);
3052                 last = cache->key.objectid + cache->key.offset;
3053                 btrfs_put_block_group(cache);
3054         }
3055
3056         while (1) {
3057                 if (last == 0) {
3058                         err = btrfs_run_delayed_refs(trans, root,
3059                                                      (unsigned long)-1);
3060                         if (err) /* File system offline */
3061                                 goto out;
3062                 }
3063
3064                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3065                 while (cache) {
3066                         if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
3067                                 btrfs_put_block_group(cache);
3068                                 goto again;
3069                         }
3070
3071                         if (cache->dirty)
3072                                 break;
3073                         cache = next_block_group(root, cache);
3074                 }
3075                 if (!cache) {
3076                         if (last == 0)
3077                                 break;
3078                         last = 0;
3079                         continue;
3080                 }
3081
3082                 if (cache->disk_cache_state == BTRFS_DC_SETUP)
3083                         cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
3084                 cache->dirty = 0;
3085                 last = cache->key.objectid + cache->key.offset;
3086
3087                 err = write_one_cache_group(trans, root, path, cache);
3088                 if (err) /* File system offline */
3089                         goto out;
3090
3091                 btrfs_put_block_group(cache);
3092         }
3093
3094         while (1) {
3095                 /*
3096                  * I don't think this is needed since we're just marking our
3097                  * preallocated extent as written, but just in case it can't
3098                  * hurt.
3099                  */
3100                 if (last == 0) {
3101                         err = btrfs_run_delayed_refs(trans, root,
3102                                                      (unsigned long)-1);
3103                         if (err) /* File system offline */
3104                                 goto out;
3105                 }
3106
3107                 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3108                 while (cache) {
3109                         /*
3110                          * Really this shouldn't happen, but it could if we
3111                          * couldn't write the entire preallocated extent and
3112                          * splitting the extent resulted in a new block.
3113                          */
3114                         if (cache->dirty) {
3115                                 btrfs_put_block_group(cache);
3116                                 goto again;
3117                         }
3118                         if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3119                                 break;
3120                         cache = next_block_group(root, cache);
3121                 }
3122                 if (!cache) {
3123                         if (last == 0)
3124                                 break;
3125                         last = 0;
3126                         continue;
3127                 }
3128
3129                 err = btrfs_write_out_cache(root, trans, cache, path);
3130
3131                 /*
3132                  * If we didn't have an error then the cache state is still
3133                  * NEED_WRITE, so we can set it to WRITTEN.
3134                  */
3135                 if (!err && cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3136                         cache->disk_cache_state = BTRFS_DC_WRITTEN;
3137                 last = cache->key.objectid + cache->key.offset;
3138                 btrfs_put_block_group(cache);
3139         }
3140 out:
3141
3142         btrfs_free_path(path);
3143         return err;
3144 }
3145
3146 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3147 {
3148         struct btrfs_block_group_cache *block_group;
3149         int readonly = 0;
3150
3151         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
3152         if (!block_group || block_group->ro)
3153                 readonly = 1;
3154         if (block_group)
3155                 btrfs_put_block_group(block_group);
3156         return readonly;
3157 }
3158
3159 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3160                              u64 total_bytes, u64 bytes_used,
3161                              struct btrfs_space_info **space_info)
3162 {
3163         struct btrfs_space_info *found;
3164         int i;
3165         int factor;
3166
3167         if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3168                      BTRFS_BLOCK_GROUP_RAID10))
3169                 factor = 2;
3170         else
3171                 factor = 1;
3172
3173         found = __find_space_info(info, flags);
3174         if (found) {
3175                 spin_lock(&found->lock);
3176                 found->total_bytes += total_bytes;
3177                 found->disk_total += total_bytes * factor;
3178                 found->bytes_used += bytes_used;
3179                 found->disk_used += bytes_used * factor;
3180                 found->full = 0;
3181                 spin_unlock(&found->lock);
3182                 *space_info = found;
3183                 return 0;
3184         }
3185         found = kzalloc(sizeof(*found), GFP_NOFS);
3186         if (!found)
3187                 return -ENOMEM;
3188
3189         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3190                 INIT_LIST_HEAD(&found->block_groups[i]);
3191         init_rwsem(&found->groups_sem);
3192         spin_lock_init(&found->lock);
3193         found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3194         found->total_bytes = total_bytes;
3195         found->disk_total = total_bytes * factor;
3196         found->bytes_used = bytes_used;
3197         found->disk_used = bytes_used * factor;
3198         found->bytes_pinned = 0;
3199         found->bytes_reserved = 0;
3200         found->bytes_readonly = 0;
3201         found->bytes_may_use = 0;
3202         found->full = 0;
3203         found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3204         found->chunk_alloc = 0;
3205         found->flush = 0;
3206         init_waitqueue_head(&found->wait);
3207         *space_info = found;
3208         list_add_rcu(&found->list, &info->space_info);
3209         if (flags & BTRFS_BLOCK_GROUP_DATA)
3210                 info->data_sinfo = found;
3211         return 0;
3212 }
3213
3214 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3215 {
3216         u64 extra_flags = chunk_to_extended(flags) &
3217                                 BTRFS_EXTENDED_PROFILE_MASK;
3218
3219         if (flags & BTRFS_BLOCK_GROUP_DATA)
3220                 fs_info->avail_data_alloc_bits |= extra_flags;
3221         if (flags & BTRFS_BLOCK_GROUP_METADATA)
3222                 fs_info->avail_metadata_alloc_bits |= extra_flags;
3223         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3224                 fs_info->avail_system_alloc_bits |= extra_flags;
3225 }
3226
3227 /*
3228  * returns target flags in extended format or 0 if restripe for this
3229  * chunk_type is not in progress
3230  *
3231  * should be called with either volume_mutex or balance_lock held
3232  */
3233 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3234 {
3235         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3236         u64 target = 0;
3237
3238         if (!bctl)
3239                 return 0;
3240
3241         if (flags & BTRFS_BLOCK_GROUP_DATA &&
3242             bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3243                 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3244         } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3245                    bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3246                 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3247         } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3248                    bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3249                 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3250         }
3251
3252         return target;
3253 }
3254
3255 /*
3256  * @flags: available profiles in extended format (see ctree.h)
3257  *
3258  * Returns reduced profile in chunk format.  If profile changing is in
3259  * progress (either running or paused) picks the target profile (if it's
3260  * already available), otherwise falls back to plain reducing.
3261  */
3262 u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
3263 {
3264         /*
3265          * we add in the count of missing devices because we want
3266          * to make sure that any RAID levels on a degraded FS
3267          * continue to be honored.
3268          */
3269         u64 num_devices = root->fs_info->fs_devices->rw_devices +
3270                 root->fs_info->fs_devices->missing_devices;
3271         u64 target;
3272
3273         /*
3274          * see if restripe for this chunk_type is in progress, if so
3275          * try to reduce to the target profile
3276          */
3277         spin_lock(&root->fs_info->balance_lock);
3278         target = get_restripe_target(root->fs_info, flags);
3279         if (target) {
3280                 /* pick target profile only if it's already available */
3281                 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3282                         spin_unlock(&root->fs_info->balance_lock);
3283                         return extended_to_chunk(target);
3284                 }
3285         }
3286         spin_unlock(&root->fs_info->balance_lock);
3287
3288         if (num_devices == 1)
3289                 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0);
3290         if (num_devices < 4)
3291                 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3292
3293         if ((flags & BTRFS_BLOCK_GROUP_DUP) &&
3294             (flags & (BTRFS_BLOCK_GROUP_RAID1 |
3295                       BTRFS_BLOCK_GROUP_RAID10))) {
3296                 flags &= ~BTRFS_BLOCK_GROUP_DUP;
3297         }
3298
3299         if ((flags & BTRFS_BLOCK_GROUP_RAID1) &&
3300             (flags & BTRFS_BLOCK_GROUP_RAID10)) {
3301                 flags &= ~BTRFS_BLOCK_GROUP_RAID1;
3302         }
3303
3304         if ((flags & BTRFS_BLOCK_GROUP_RAID0) &&
3305             ((flags & BTRFS_BLOCK_GROUP_RAID1) |
3306              (flags & BTRFS_BLOCK_GROUP_RAID10) |
3307              (flags & BTRFS_BLOCK_GROUP_DUP))) {
3308                 flags &= ~BTRFS_BLOCK_GROUP_RAID0;
3309         }
3310
3311         return extended_to_chunk(flags);
3312 }
3313
3314 static u64 get_alloc_profile(struct btrfs_root *root, u64 flags)
3315 {
3316         if (flags & BTRFS_BLOCK_GROUP_DATA)
3317                 flags |= root->fs_info->avail_data_alloc_bits;
3318         else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3319                 flags |= root->fs_info->avail_system_alloc_bits;
3320         else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3321                 flags |= root->fs_info->avail_metadata_alloc_bits;
3322
3323         return btrfs_reduce_alloc_profile(root, flags);
3324 }
3325
3326 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3327 {
3328         u64 flags;
3329
3330         if (data)
3331                 flags = BTRFS_BLOCK_GROUP_DATA;
3332         else if (root == root->fs_info->chunk_root)
3333                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3334         else
3335                 flags = BTRFS_BLOCK_GROUP_METADATA;
3336
3337         return get_alloc_profile(root, flags);
3338 }
3339
3340 /*
3341  * This will check the space that the inode allocates from to make sure we have
3342  * enough space for bytes.
3343  */
3344 int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
3345 {
3346         struct btrfs_space_info *data_sinfo;
3347         struct btrfs_root *root = BTRFS_I(inode)->root;
3348         struct btrfs_fs_info *fs_info = root->fs_info;
3349         u64 used;
3350         int ret = 0, committed = 0, alloc_chunk = 1;
3351
3352         /* make sure bytes are sectorsize aligned */
3353         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3354
3355         if (root == root->fs_info->tree_root ||
3356             BTRFS_I(inode)->location.objectid == BTRFS_FREE_INO_OBJECTID) {
3357                 alloc_chunk = 0;
3358                 committed = 1;
3359         }
3360
3361         data_sinfo = fs_info->data_sinfo;
3362         if (!data_sinfo)
3363                 goto alloc;
3364
3365 again:
3366         /* make sure we have enough space to handle the data first */
3367         spin_lock(&data_sinfo->lock);
3368         used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3369                 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3370                 data_sinfo->bytes_may_use;
3371
3372         if (used + bytes > data_sinfo->total_bytes) {
3373                 struct btrfs_trans_handle *trans;
3374
3375                 /*
3376                  * if we don't have enough free bytes in this space then we need
3377                  * to alloc a new chunk.
3378                  */
3379                 if (!data_sinfo->full && alloc_chunk) {
3380                         u64 alloc_target;
3381
3382                         data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
3383                         spin_unlock(&data_sinfo->lock);
3384 alloc:
3385                         alloc_target = btrfs_get_alloc_profile(root, 1);
3386                         trans = btrfs_join_transaction(root);
3387                         if (IS_ERR(trans))
3388                                 return PTR_ERR(trans);
3389
3390                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3391                                              alloc_target,
3392                                              CHUNK_ALLOC_NO_FORCE);
3393                         btrfs_end_transaction(trans, root);
3394                         if (ret < 0) {
3395                                 if (ret != -ENOSPC)
3396                                         return ret;
3397                                 else
3398                                         goto commit_trans;
3399                         }
3400
3401                         if (!data_sinfo)
3402                                 data_sinfo = fs_info->data_sinfo;
3403
3404                         goto again;
3405                 }
3406
3407                 /*
3408                  * If we have less pinned bytes than we want to allocate then
3409                  * don't bother committing the transaction, it won't help us.
3410                  */
3411                 if (data_sinfo->bytes_pinned < bytes)
3412                         committed = 1;
3413                 spin_unlock(&data_sinfo->lock);
3414
3415                 /* commit the current transaction and try again */
3416 commit_trans:
3417                 if (!committed &&
3418                     !atomic_read(&root->fs_info->open_ioctl_trans)) {
3419                         committed = 1;
3420                         trans = btrfs_join_transaction(root);
3421                         if (IS_ERR(trans))
3422                                 return PTR_ERR(trans);
3423                         ret = btrfs_commit_transaction(trans, root);
3424                         if (ret)
3425                                 return ret;
3426                         goto again;
3427                 }
3428
3429                 return -ENOSPC;
3430         }
3431         data_sinfo->bytes_may_use += bytes;
3432         trace_btrfs_space_reservation(root->fs_info, "space_info",
3433                                       data_sinfo->flags, bytes, 1);
3434         spin_unlock(&data_sinfo->lock);
3435
3436         return 0;
3437 }
3438
3439 /*
3440  * Called if we need to clear a data reservation for this inode.
3441  */
3442 void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
3443 {
3444         struct btrfs_root *root = BTRFS_I(inode)->root;
3445         struct btrfs_space_info *data_sinfo;
3446
3447         /* make sure bytes are sectorsize aligned */
3448         bytes = (bytes + root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
3449
3450         data_sinfo = root->fs_info->data_sinfo;
3451         spin_lock(&data_sinfo->lock);
3452         data_sinfo->bytes_may_use -= bytes;
3453         trace_btrfs_space_reservation(root->fs_info, "space_info",
3454                                       data_sinfo->flags, bytes, 0);
3455         spin_unlock(&data_sinfo->lock);
3456 }
3457
3458 static void force_metadata_allocation(struct btrfs_fs_info *info)
3459 {
3460         struct list_head *head = &info->space_info;
3461         struct btrfs_space_info *found;
3462
3463         rcu_read_lock();
3464         list_for_each_entry_rcu(found, head, list) {
3465                 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
3466                         found->force_alloc = CHUNK_ALLOC_FORCE;
3467         }
3468         rcu_read_unlock();
3469 }
3470
3471 static int should_alloc_chunk(struct btrfs_root *root,
3472                               struct btrfs_space_info *sinfo, int force)
3473 {
3474         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
3475         u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
3476         u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
3477         u64 thresh;
3478
3479         if (force == CHUNK_ALLOC_FORCE)
3480                 return 1;
3481
3482         /*
3483          * We need to take into account the global rsv because for all intents
3484          * and purposes it's used space.  Don't worry about locking the
3485          * global_rsv, it doesn't change except when the transaction commits.
3486          */
3487         if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
3488                 num_allocated += global_rsv->size;
3489
3490         /*
3491          * in limited mode, we want to have some free space up to
3492          * about 1% of the FS size.
3493          */
3494         if (force == CHUNK_ALLOC_LIMITED) {
3495                 thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
3496                 thresh = max_t(u64, 64 * 1024 * 1024,
3497                                div_factor_fine(thresh, 1));
3498
3499                 if (num_bytes - num_allocated < thresh)
3500                         return 1;
3501         }
3502
3503         if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
3504                 return 0;
3505         return 1;
3506 }
3507
3508 static u64 get_system_chunk_thresh(struct btrfs_root *root, u64 type)
3509 {
3510         u64 num_dev;
3511
3512         if (type & BTRFS_BLOCK_GROUP_RAID10 ||
3513             type & BTRFS_BLOCK_GROUP_RAID0)
3514                 num_dev = root->fs_info->fs_devices->rw_devices;
3515         else if (type & BTRFS_BLOCK_GROUP_RAID1)
3516                 num_dev = 2;
3517         else
3518                 num_dev = 1;    /* DUP or single */
3519
3520         /* metadata for updaing devices and chunk tree */
3521         return btrfs_calc_trans_metadata_size(root, num_dev + 1);
3522 }
3523
3524 static void check_system_chunk(struct btrfs_trans_handle *trans,
3525                                struct btrfs_root *root, u64 type)
3526 {
3527         struct btrfs_space_info *info;
3528         u64 left;
3529         u64 thresh;
3530
3531         info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3532         spin_lock(&info->lock);
3533         left = info->total_bytes - info->bytes_used - info->bytes_pinned -
3534                 info->bytes_reserved - info->bytes_readonly;
3535         spin_unlock(&info->lock);
3536
3537         thresh = get_system_chunk_thresh(root, type);
3538         if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
3539                 printk(KERN_INFO "left=%llu, need=%llu, flags=%llu\n",
3540                        left, thresh, type);
3541                 dump_space_info(info, 0, 0);
3542         }
3543
3544         if (left < thresh) {
3545                 u64 flags;
3546
3547                 flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
3548                 btrfs_alloc_chunk(trans, root, flags);
3549         }
3550 }
3551
3552 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
3553                           struct btrfs_root *extent_root, u64 flags, int force)
3554 {
3555         struct btrfs_space_info *space_info;
3556         struct btrfs_fs_info *fs_info = extent_root->fs_info;
3557         int wait_for_alloc = 0;
3558         int ret = 0;
3559
3560         space_info = __find_space_info(extent_root->fs_info, flags);
3561         if (!space_info) {
3562                 ret = update_space_info(extent_root->fs_info, flags,
3563                                         0, 0, &space_info);
3564                 BUG_ON(ret); /* -ENOMEM */
3565         }
3566         BUG_ON(!space_info); /* Logic error */
3567
3568 again:
3569         spin_lock(&space_info->lock);
3570         if (force < space_info->force_alloc)
3571                 force = space_info->force_alloc;
3572         if (space_info->full) {
3573                 spin_unlock(&space_info->lock);
3574                 return 0;
3575         }
3576
3577         if (!should_alloc_chunk(extent_root, space_info, force)) {
3578                 spin_unlock(&space_info->lock);
3579                 return 0;
3580         } else if (space_info->chunk_alloc) {
3581                 wait_for_alloc = 1;
3582         } else {
3583                 space_info->chunk_alloc = 1;
3584         }
3585
3586         spin_unlock(&space_info->lock);
3587
3588         mutex_lock(&fs_info->chunk_mutex);
3589
3590         /*
3591          * The chunk_mutex is held throughout the entirety of a chunk
3592          * allocation, so once we've acquired the chunk_mutex we know that the
3593          * other guy is done and we need to recheck and see if we should
3594          * allocate.
3595          */
3596         if (wait_for_alloc) {
3597                 mutex_unlock(&fs_info->chunk_mutex);
3598                 wait_for_alloc = 0;
3599                 goto again;
3600         }
3601
3602         /*
3603          * If we have mixed data/metadata chunks we want to make sure we keep
3604          * allocating mixed chunks instead of individual chunks.
3605          */
3606         if (btrfs_mixed_space_info(space_info))
3607                 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3608
3609         /*
3610          * if we're doing a data chunk, go ahead and make sure that
3611          * we keep a reasonable number of metadata chunks allocated in the
3612          * FS as well.
3613          */
3614         if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
3615                 fs_info->data_chunk_allocations++;
3616                 if (!(fs_info->data_chunk_allocations %
3617                       fs_info->metadata_ratio))
3618                         force_metadata_allocation(fs_info);
3619         }
3620
3621         /*
3622          * Check if we have enough space in SYSTEM chunk because we may need
3623          * to update devices.
3624          */
3625         check_system_chunk(trans, extent_root, flags);
3626
3627         ret = btrfs_alloc_chunk(trans, extent_root, flags);
3628         if (ret < 0 && ret != -ENOSPC)
3629                 goto out;
3630
3631         spin_lock(&space_info->lock);
3632         if (ret)
3633                 space_info->full = 1;
3634         else
3635                 ret = 1;
3636
3637         space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
3638         space_info->chunk_alloc = 0;
3639         spin_unlock(&space_info->lock);
3640 out:
3641         mutex_unlock(&fs_info->chunk_mutex);
3642         return ret;
3643 }
3644
3645 static int can_overcommit(struct btrfs_root *root,
3646                           struct btrfs_space_info *space_info, u64 bytes,
3647                           enum btrfs_reserve_flush_enum flush)
3648 {
3649         u64 profile = btrfs_get_alloc_profile(root, 0);
3650         u64 avail;
3651         u64 used;
3652
3653         used = space_info->bytes_used + space_info->bytes_reserved +
3654                 space_info->bytes_pinned + space_info->bytes_readonly +
3655                 space_info->bytes_may_use;
3656
3657         spin_lock(&root->fs_info->free_chunk_lock);
3658         avail = root->fs_info->free_chunk_space;
3659         spin_unlock(&root->fs_info->free_chunk_lock);
3660
3661         /*
3662          * If we have dup, raid1 or raid10 then only half of the free
3663          * space is actually useable.
3664          */
3665         if (profile & (BTRFS_BLOCK_GROUP_DUP |
3666                        BTRFS_BLOCK_GROUP_RAID1 |
3667                        BTRFS_BLOCK_GROUP_RAID10))
3668                 avail >>= 1;
3669
3670         /*
3671          * If we aren't flushing all things, let us overcommit up to
3672          * 1/2th of the space. If we can flush, don't let us overcommit
3673          * too much, let it overcommit up to 1/8 of the space.
3674          */
3675         if (flush == BTRFS_RESERVE_FLUSH_ALL)
3676                 avail >>= 3;
3677         else
3678                 avail >>= 1;
3679
3680         if (used + bytes < space_info->total_bytes + avail)
3681                 return 1;
3682         return 0;
3683 }
3684
3685 /*
3686  * shrink metadata reservation for delalloc
3687  */
3688 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
3689                             bool wait_ordered)
3690 {
3691         struct btrfs_block_rsv *block_rsv;
3692         struct btrfs_space_info *space_info;
3693         struct btrfs_trans_handle *trans;
3694         u64 delalloc_bytes;
3695         u64 max_reclaim;
3696         long time_left;
3697         unsigned long nr_pages = (2 * 1024 * 1024) >> PAGE_CACHE_SHIFT;
3698         int loops = 0;
3699         enum btrfs_reserve_flush_enum flush;
3700
3701         trans = (struct btrfs_trans_handle *)current->journal_info;
3702         block_rsv = &root->fs_info->delalloc_block_rsv;
3703         space_info = block_rsv->space_info;
3704
3705         smp_mb();
3706         delalloc_bytes = root->fs_info->delalloc_bytes;
3707         if (delalloc_bytes == 0) {
3708                 if (trans)
3709                         return;
3710                 btrfs_wait_ordered_extents(root, 0);
3711                 return;
3712         }
3713
3714         while (delalloc_bytes && loops < 3) {
3715                 max_reclaim = min(delalloc_bytes, to_reclaim);
3716                 nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
3717                 writeback_inodes_sb_nr_if_idle(root->fs_info->sb, nr_pages,
3718                                                WB_REASON_FS_FREE_SPACE);
3719
3720                 /*
3721                  * We need to wait for the async pages to actually start before
3722                  * we do anything.
3723                  */
3724                 wait_event(root->fs_info->async_submit_wait,
3725                            !atomic_read(&root->fs_info->async_delalloc_pages));
3726
3727                 if (!trans)
3728                         flush = BTRFS_RESERVE_FLUSH_ALL;
3729                 else
3730                         flush = BTRFS_RESERVE_NO_FLUSH;
3731                 spin_lock(&space_info->lock);
3732                 if (can_overcommit(root, space_info, orig, flush)) {
3733                         spin_unlock(&space_info->lock);
3734                         break;
3735                 }
3736                 spin_unlock(&space_info->lock);
3737
3738                 loops++;
3739                 if (wait_ordered && !trans) {
3740                         btrfs_wait_ordered_extents(root, 0);
3741                 } else {
3742                         time_left = schedule_timeout_killable(1);
3743                         if (time_left)
3744                                 break;
3745                 }
3746                 smp_mb();
3747                 delalloc_bytes = root->fs_info->delalloc_bytes;
3748         }
3749 }
3750
3751 /**
3752  * maybe_commit_transaction - possibly commit the transaction if its ok to
3753  * @root - the root we're allocating for
3754  * @bytes - the number of bytes we want to reserve
3755  * @force - force the commit
3756  *
3757  * This will check to make sure that committing the transaction will actually
3758  * get us somewhere and then commit the transaction if it does.  Otherwise it
3759  * will return -ENOSPC.
3760  */
3761 static int may_commit_transaction(struct btrfs_root *root,
3762                                   struct btrfs_space_info *space_info,
3763                                   u64 bytes, int force)
3764 {
3765         struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
3766         struct btrfs_trans_handle *trans;
3767
3768         trans = (struct btrfs_trans_handle *)current->journal_info;
3769         if (trans)
3770                 return -EAGAIN;
3771
3772         if (force)
3773                 goto commit;
3774
3775         /* See if there is enough pinned space to make this reservation */
3776         spin_lock(&space_info->lock);
3777         if (space_info->bytes_pinned >= bytes) {
3778                 spin_unlock(&space_info->lock);
3779                 goto commit;
3780         }
3781         spin_unlock(&space_info->lock);
3782
3783         /*
3784          * See if there is some space in the delayed insertion reservation for
3785          * this reservation.
3786          */
3787         if (space_info != delayed_rsv->space_info)
3788                 return -ENOSPC;
3789
3790         spin_lock(&space_info->lock);
3791         spin_lock(&delayed_rsv->lock);
3792         if (space_info->bytes_pinned + delayed_rsv->size < bytes) {
3793                 spin_unlock(&delayed_rsv->lock);
3794                 spin_unlock(&space_info->lock);
3795                 return -ENOSPC;
3796         }
3797         spin_unlock(&delayed_rsv->lock);
3798         spin_unlock(&space_info->lock);
3799
3800 commit:
3801         trans = btrfs_join_transaction(root);
3802         if (IS_ERR(trans))
3803                 return -ENOSPC;
3804
3805         return btrfs_commit_transaction(trans, root);
3806 }
3807
3808 enum flush_state {
3809         FLUSH_DELAYED_ITEMS_NR  =       1,
3810         FLUSH_DELAYED_ITEMS     =       2,
3811         FLUSH_DELALLOC          =       3,
3812         FLUSH_DELALLOC_WAIT     =       4,
3813         ALLOC_CHUNK             =       5,
3814         COMMIT_TRANS            =       6,
3815 };
3816
3817 static int flush_space(struct btrfs_root *root,
3818                        struct btrfs_space_info *space_info, u64 num_bytes,
3819                        u64 orig_bytes, int state)
3820 {
3821         struct btrfs_trans_handle *trans;
3822         int nr;
3823         int ret = 0;
3824
3825         switch (state) {
3826         case FLUSH_DELAYED_ITEMS_NR:
3827         case FLUSH_DELAYED_ITEMS:
3828                 if (state == FLUSH_DELAYED_ITEMS_NR) {
3829                         u64 bytes = btrfs_calc_trans_metadata_size(root, 1);
3830
3831                         nr = (int)div64_u64(num_bytes, bytes);
3832                         if (!nr)
3833                                 nr = 1;
3834                         nr *= 2;
3835                 } else {
3836                         nr = -1;
3837                 }
3838                 trans = btrfs_join_transaction(root);
3839                 if (IS_ERR(trans)) {
3840                         ret = PTR_ERR(trans);
3841                         break;
3842                 }
3843                 ret = btrfs_run_delayed_items_nr(trans, root, nr);
3844                 btrfs_end_transaction(trans, root);
3845                 break;
3846         case FLUSH_DELALLOC:
3847         case FLUSH_DELALLOC_WAIT:
3848                 shrink_delalloc(root, num_bytes, orig_bytes,
3849                                 state == FLUSH_DELALLOC_WAIT);
3850                 break;
3851         case ALLOC_CHUNK:
3852                 trans = btrfs_join_transaction(root);
3853                 if (IS_ERR(trans)) {
3854                         ret = PTR_ERR(trans);
3855                         break;
3856                 }
3857                 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
3858                                      btrfs_get_alloc_profile(root, 0),
3859                                      CHUNK_ALLOC_NO_FORCE);
3860                 btrfs_end_transaction(trans, root);
3861                 if (ret == -ENOSPC)
3862                         ret = 0;
3863                 break;
3864         case COMMIT_TRANS:
3865                 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
3866                 break;
3867         default:
3868                 ret = -ENOSPC;
3869                 break;
3870         }
3871
3872         return ret;
3873 }
3874 /**
3875  * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
3876  * @root - the root we're allocating for
3877  * @block_rsv - the block_rsv we're allocating for
3878  * @orig_bytes - the number of bytes we want
3879  * @flush - wether or not we can flush to make our reservation
3880  *
3881  * This will reserve orgi_bytes number of bytes from the space info associated
3882  * with the block_rsv.  If there is not enough space it will make an attempt to
3883  * flush out space to make room.  It will do this by flushing delalloc if
3884  * possible or committing the transaction.  If flush is 0 then no attempts to
3885  * regain reservations will be made and this will fail if there is not enough
3886  * space already.
3887  */
3888 static int reserve_metadata_bytes(struct btrfs_root *root,
3889                                   struct btrfs_block_rsv *block_rsv,
3890                                   u64 orig_bytes,
3891                                   enum btrfs_reserve_flush_enum flush)
3892 {
3893         struct btrfs_space_info *space_info = block_rsv->space_info;
3894         u64 used;
3895         u64 num_bytes = orig_bytes;
3896         int flush_state = FLUSH_DELAYED_ITEMS_NR;
3897         int ret = 0;
3898         bool flushing = false;
3899
3900 again:
3901         ret = 0;
3902         spin_lock(&space_info->lock);
3903         /*
3904          * We only want to wait if somebody other than us is flushing and we
3905          * are actually allowed to flush all things.
3906          */
3907         while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
3908                space_info->flush) {
3909                 spin_unlock(&space_info->lock);
3910                 /*
3911                  * If we have a trans handle we can't wait because the flusher
3912                  * may have to commit the transaction, which would mean we would
3913                  * deadlock since we are waiting for the flusher to finish, but
3914                  * hold the current transaction open.
3915                  */
3916                 if (current->journal_info)
3917                         return -EAGAIN;
3918                 ret = wait_event_killable(space_info->wait, !space_info->flush);
3919                 /* Must have been killed, return */
3920                 if (ret)
3921                         return -EINTR;
3922
3923                 spin_lock(&space_info->lock);
3924         }
3925
3926         ret = -ENOSPC;
3927         used = space_info->bytes_used + space_info->bytes_reserved +
3928                 space_info->bytes_pinned + space_info->bytes_readonly +
3929                 space_info->bytes_may_use;
3930
3931         /*
3932          * The idea here is that we've not already over-reserved the block group
3933          * then we can go ahead and save our reservation first and then start
3934          * flushing if we need to.  Otherwise if we've already overcommitted
3935          * lets start flushing stuff first and then come back and try to make
3936          * our reservation.
3937          */
3938         if (used <= space_info->total_bytes) {
3939                 if (used + orig_bytes <= space_info->total_bytes) {
3940                         space_info->bytes_may_use += orig_bytes;
3941                         trace_btrfs_space_reservation(root->fs_info,
3942                                 "space_info", space_info->flags, orig_bytes, 1);
3943                         ret = 0;
3944                 } else {
3945                         /*
3946                          * Ok set num_bytes to orig_bytes since we aren't
3947                          * overocmmitted, this way we only try and reclaim what
3948                          * we need.
3949                          */
3950                         num_bytes = orig_bytes;
3951                 }
3952         } else {
3953                 /*
3954                  * Ok we're over committed, set num_bytes to the overcommitted
3955                  * amount plus the amount of bytes that we need for this
3956                  * reservation.
3957                  */
3958                 num_bytes = used - space_info->total_bytes +
3959                         (orig_bytes * 2);
3960         }
3961
3962         if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
3963                 space_info->bytes_may_use += orig_bytes;
3964                 trace_btrfs_space_reservation(root->fs_info, "space_info",
3965                                               space_info->flags, orig_bytes,
3966                                               1);
3967                 ret = 0;
3968         }
3969
3970         /*
3971          * Couldn't make our reservation, save our place so while we're trying
3972          * to reclaim space we can actually use it instead of somebody else
3973          * stealing it from us.
3974          *
3975          * We make the other tasks wait for the flush only when we can flush
3976          * all things.
3977          */
3978         if (ret && flush == BTRFS_RESERVE_FLUSH_ALL) {
3979                 flushing = true;
3980                 space_info->flush = 1;
3981         }
3982
3983         spin_unlock(&space_info->lock);
3984
3985         if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
3986                 goto out;
3987
3988         ret = flush_space(root, space_info, num_bytes, orig_bytes,
3989                           flush_state);
3990         flush_state++;
3991
3992         /*
3993          * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
3994          * would happen. So skip delalloc flush.
3995          */
3996         if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
3997             (flush_state == FLUSH_DELALLOC ||
3998              flush_state == FLUSH_DELALLOC_WAIT))
3999                 flush_state = ALLOC_CHUNK;
4000
4001         if (!ret)
4002                 goto again;
4003         else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4004                  flush_state < COMMIT_TRANS)
4005                 goto again;
4006         else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
4007                  flush_state <= COMMIT_TRANS)
4008                 goto again;
4009
4010 out:
4011         if (flushing) {
4012                 spin_lock(&space_info->lock);
4013                 space_info->flush = 0;
4014                 wake_up_all(&space_info->wait);
4015                 spin_unlock(&space_info->lock);
4016         }
4017         return ret;
4018 }
4019
4020 static struct btrfs_block_rsv *get_block_rsv(
4021                                         const struct btrfs_trans_handle *trans,
4022                                         const struct btrfs_root *root)
4023 {
4024         struct btrfs_block_rsv *block_rsv = NULL;
4025
4026         if (root->ref_cows)
4027                 block_rsv = trans->block_rsv;
4028
4029         if (root == root->fs_info->csum_root && trans->adding_csums)
4030                 block_rsv = trans->block_rsv;
4031
4032         if (!block_rsv)
4033                 block_rsv = root->block_rsv;
4034
4035         if (!block_rsv)
4036                 block_rsv = &root->fs_info->empty_block_rsv;
4037
4038         return block_rsv;
4039 }
4040
4041 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
4042                                u64 num_bytes)
4043 {
4044         int ret = -ENOSPC;
4045         spin_lock(&block_rsv->lock);
4046         if (block_rsv->reserved >= num_bytes) {
4047                 block_rsv->reserved -= num_bytes;
4048                 if (block_rsv->reserved < block_rsv->size)
4049                         block_rsv->full = 0;
4050                 ret = 0;
4051         }
4052         spin_unlock(&block_rsv->lock);
4053         return ret;
4054 }
4055
4056 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
4057                                 u64 num_bytes, int update_size)
4058 {
4059         spin_lock(&block_rsv->lock);
4060         block_rsv->reserved += num_bytes;
4061         if (update_size)
4062                 block_rsv->size += num_bytes;
4063         else if (block_rsv->reserved >= block_rsv->size)
4064                 block_rsv->full = 1;
4065         spin_unlock(&block_rsv->lock);
4066 }
4067
4068 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
4069                                     struct btrfs_block_rsv *block_rsv,
4070                                     struct btrfs_block_rsv *dest, u64 num_bytes)
4071 {
4072         struct btrfs_space_info *space_info = block_rsv->space_info;
4073
4074         spin_lock(&block_rsv->lock);
4075         if (num_bytes == (u64)-1)
4076                 num_bytes = block_rsv->size;
4077         block_rsv->size -= num_bytes;
4078         if (block_rsv->reserved >= block_rsv->size) {
4079                 num_bytes = block_rsv->reserved - block_rsv->size;
4080                 block_rsv->reserved = block_rsv->size;
4081                 block_rsv->full = 1;
4082         } else {
4083                 num_bytes = 0;
4084         }
4085         spin_unlock(&block_rsv->lock);
4086
4087         if (num_bytes > 0) {
4088                 if (dest) {
4089                         spin_lock(&dest->lock);
4090                         if (!dest->full) {
4091                                 u64 bytes_to_add;
4092
4093                                 bytes_to_add = dest->size - dest->reserved;
4094                                 bytes_to_add = min(num_bytes, bytes_to_add);
4095                                 dest->reserved += bytes_to_add;
4096                                 if (dest->reserved >= dest->size)
4097                                         dest->full = 1;
4098                                 num_bytes -= bytes_to_add;
4099                         }
4100                         spin_unlock(&dest->lock);
4101                 }
4102                 if (num_bytes) {
4103                         spin_lock(&space_info->lock);
4104                         space_info->bytes_may_use -= num_bytes;
4105                         trace_btrfs_space_reservation(fs_info, "space_info",
4106                                         space_info->flags, num_bytes, 0);
4107                         space_info->reservation_progress++;
4108                         spin_unlock(&space_info->lock);
4109                 }
4110         }
4111 }
4112
4113 static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
4114                                    struct btrfs_block_rsv *dst, u64 num_bytes)
4115 {
4116         int ret;
4117
4118         ret = block_rsv_use_bytes(src, num_bytes);
4119         if (ret)
4120                 return ret;
4121
4122         block_rsv_add_bytes(dst, num_bytes, 1);
4123         return 0;
4124 }
4125
4126 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
4127 {
4128         memset(rsv, 0, sizeof(*rsv));
4129         spin_lock_init(&rsv->lock);
4130         rsv->type = type;
4131 }
4132
4133 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
4134                                               unsigned short type)
4135 {
4136         struct btrfs_block_rsv *block_rsv;
4137         struct btrfs_fs_info *fs_info = root->fs_info;
4138
4139         block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
4140         if (!block_rsv)
4141                 return NULL;
4142
4143         btrfs_init_block_rsv(block_rsv, type);
4144         block_rsv->space_info = __find_space_info(fs_info,
4145                                                   BTRFS_BLOCK_GROUP_METADATA);
4146         return block_rsv;
4147 }
4148
4149 void btrfs_free_block_rsv(struct btrfs_root *root,
4150                           struct btrfs_block_rsv *rsv)
4151 {
4152         if (!rsv)
4153                 return;
4154         btrfs_block_rsv_release(root, rsv, (u64)-1);
4155         kfree(rsv);
4156 }
4157
4158 int btrfs_block_rsv_add(struct btrfs_root *root,
4159                         struct btrfs_block_rsv *block_rsv, u64 num_bytes,
4160                         enum btrfs_reserve_flush_enum flush)
4161 {
4162         int ret;
4163
4164         if (num_bytes == 0)
4165                 return 0;
4166
4167         ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4168         if (!ret) {
4169                 block_rsv_add_bytes(block_rsv, num_bytes, 1);
4170                 return 0;
4171         }
4172
4173         return ret;
4174 }
4175
4176 int btrfs_block_rsv_check(struct btrfs_root *root,
4177                           struct btrfs_block_rsv *block_rsv, int min_factor)
4178 {
4179         u64 num_bytes = 0;
4180         int ret = -ENOSPC;
4181
4182         if (!block_rsv)
4183                 return 0;
4184
4185         spin_lock(&block_rsv->lock);
4186         num_bytes = div_factor(block_rsv->size, min_factor);
4187         if (block_rsv->reserved >= num_bytes)
4188                 ret = 0;
4189         spin_unlock(&block_rsv->lock);
4190
4191         return ret;
4192 }
4193
4194 int btrfs_block_rsv_refill(struct btrfs_root *root,
4195                            struct btrfs_block_rsv *block_rsv, u64 min_reserved,
4196                            enum btrfs_reserve_flush_enum flush)
4197 {
4198         u64 num_bytes = 0;
4199         int ret = -ENOSPC;
4200
4201         if (!block_rsv)
4202                 return 0;
4203
4204         spin_lock(&block_rsv->lock);
4205         num_bytes = min_reserved;
4206         if (block_rsv->reserved >= num_bytes)
4207                 ret = 0;
4208         else
4209                 num_bytes -= block_rsv->reserved;
4210         spin_unlock(&block_rsv->lock);
4211
4212         if (!ret)
4213                 return 0;
4214
4215         ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
4216         if (!ret) {
4217                 block_rsv_add_bytes(block_rsv, num_bytes, 0);
4218                 return 0;
4219         }
4220
4221         return ret;
4222 }
4223
4224 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
4225                             struct btrfs_block_rsv *dst_rsv,
4226                             u64 num_bytes)
4227 {
4228         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4229 }
4230
4231 void btrfs_block_rsv_release(struct btrfs_root *root,
4232                              struct btrfs_block_rsv *block_rsv,
4233                              u64 num_bytes)
4234 {
4235         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4236         if (global_rsv->full || global_rsv == block_rsv ||
4237             block_rsv->space_info != global_rsv->space_info)
4238                 global_rsv = NULL;
4239         block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
4240                                 num_bytes);
4241 }
4242
4243 /*
4244  * helper to calculate size of global block reservation.
4245  * the desired value is sum of space used by extent tree,
4246  * checksum tree and root tree
4247  */
4248 static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
4249 {
4250         struct btrfs_space_info *sinfo;
4251         u64 num_bytes;
4252         u64 meta_used;
4253         u64 data_used;
4254         int csum_size = btrfs_super_csum_size(fs_info->super_copy);
4255
4256         sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
4257         spin_lock(&sinfo->lock);
4258         data_used = sinfo->bytes_used;
4259         spin_unlock(&sinfo->lock);
4260
4261         sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4262         spin_lock(&sinfo->lock);
4263         if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
4264                 data_used = 0;
4265         meta_used = sinfo->bytes_used;
4266         spin_unlock(&sinfo->lock);
4267
4268         num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
4269                     csum_size * 2;
4270         num_bytes += div64_u64(data_used + meta_used, 50);
4271
4272         if (num_bytes * 3 > meta_used)
4273                 num_bytes = div64_u64(meta_used, 3);
4274
4275         return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
4276 }
4277
4278 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
4279 {
4280         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4281         struct btrfs_space_info *sinfo = block_rsv->space_info;
4282         u64 num_bytes;
4283
4284         num_bytes = calc_global_metadata_size(fs_info);
4285
4286         spin_lock(&sinfo->lock);
4287         spin_lock(&block_rsv->lock);
4288
4289         block_rsv->size = num_bytes;
4290
4291         num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
4292                     sinfo->bytes_reserved + sinfo->bytes_readonly +
4293                     sinfo->bytes_may_use;
4294
4295         if (sinfo->total_bytes > num_bytes) {
4296                 num_bytes = sinfo->total_bytes - num_bytes;
4297                 block_rsv->reserved += num_bytes;
4298                 sinfo->bytes_may_use += num_bytes;
4299                 trace_btrfs_space_reservation(fs_info, "space_info",
4300                                       sinfo->flags, num_bytes, 1);
4301         }
4302
4303         if (block_rsv->reserved >= block_rsv->size) {
4304                 num_bytes = block_rsv->reserved - block_rsv->size;
4305                 sinfo->bytes_may_use -= num_bytes;
4306                 trace_btrfs_space_reservation(fs_info, "space_info",
4307                                       sinfo->flags, num_bytes, 0);
4308                 sinfo->reservation_progress++;
4309                 block_rsv->reserved = block_rsv->size;
4310                 block_rsv->full = 1;
4311         }
4312
4313         spin_unlock(&block_rsv->lock);
4314         spin_unlock(&sinfo->lock);
4315 }
4316
4317 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
4318 {
4319         struct btrfs_space_info *space_info;
4320
4321         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4322         fs_info->chunk_block_rsv.space_info = space_info;
4323
4324         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4325         fs_info->global_block_rsv.space_info = space_info;
4326         fs_info->delalloc_block_rsv.space_info = space_info;
4327         fs_info->trans_block_rsv.space_info = space_info;
4328         fs_info->empty_block_rsv.space_info = space_info;
4329         fs_info->delayed_block_rsv.space_info = space_info;
4330
4331         fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
4332         fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
4333         fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
4334         fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
4335         fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
4336
4337         update_global_block_rsv(fs_info);
4338 }
4339
4340 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
4341 {
4342         block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
4343                                 (u64)-1);
4344         WARN_ON(fs_info->delalloc_block_rsv.size > 0);
4345         WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
4346         WARN_ON(fs_info->trans_block_rsv.size > 0);
4347         WARN_ON(fs_info->trans_block_rsv.reserved > 0);
4348         WARN_ON(fs_info->chunk_block_rsv.size > 0);
4349         WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
4350         WARN_ON(fs_info->delayed_block_rsv.size > 0);
4351         WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
4352 }
4353
4354 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
4355                                   struct btrfs_root *root)
4356 {
4357         if (!trans->block_rsv)
4358                 return;
4359
4360         if (!trans->bytes_reserved)
4361                 return;
4362
4363         trace_btrfs_space_reservation(root->fs_info, "transaction",
4364                                       trans->transid, trans->bytes_reserved, 0);
4365         btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
4366         trans->bytes_reserved = 0;
4367 }
4368
4369 /* Can only return 0 or -ENOSPC */
4370 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
4371                                   struct inode *inode)
4372 {
4373         struct btrfs_root *root = BTRFS_I(inode)->root;
4374         struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4375         struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
4376
4377         /*
4378          * We need to hold space in order to delete our orphan item once we've
4379          * added it, so this takes the reservation so we can release it later
4380          * when we are truly done with the orphan item.
4381          */
4382         u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
4383         trace_btrfs_space_reservation(root->fs_info, "orphan",
4384                                       btrfs_ino(inode), num_bytes, 1);
4385         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4386 }
4387
4388 void btrfs_orphan_release_metadata(struct inode *inode)
4389 {
4390         struct btrfs_root *root = BTRFS_I(inode)->root;
4391         u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
4392         trace_btrfs_space_reservation(root->fs_info, "orphan",
4393                                       btrfs_ino(inode), num_bytes, 0);
4394         btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
4395 }
4396
4397 int btrfs_snap_reserve_metadata(struct btrfs_trans_handle *trans,
4398                                 struct btrfs_pending_snapshot *pending)
4399 {
4400         struct btrfs_root *root = pending->root;
4401         struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4402         struct btrfs_block_rsv *dst_rsv = &pending->block_rsv;
4403         /*
4404          * two for root back/forward refs, two for directory entries,
4405          * one for root of the snapshot and one for parent inode.
4406          */
4407         u64 num_bytes = btrfs_calc_trans_metadata_size(root, 6);
4408         dst_rsv->space_info = src_rsv->space_info;
4409         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4410 }
4411
4412 /**
4413  * drop_outstanding_extent - drop an outstanding extent
4414  * @inode: the inode we're dropping the extent for
4415  *
4416  * This is called when we are freeing up an outstanding extent, either called
4417  * after an error or after an extent is written.  This will return the number of
4418  * reserved extents that need to be freed.  This must be called with
4419  * BTRFS_I(inode)->lock held.
4420  */
4421 static unsigned drop_outstanding_extent(struct inode *inode)
4422 {
4423         unsigned drop_inode_space = 0;
4424         unsigned dropped_extents = 0;
4425
4426         BUG_ON(!BTRFS_I(inode)->outstanding_extents);
4427         BTRFS_I(inode)->outstanding_extents--;
4428
4429         if (BTRFS_I(inode)->outstanding_extents == 0 &&
4430             test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4431                                &BTRFS_I(inode)->runtime_flags))
4432                 drop_inode_space = 1;
4433
4434         /*
4435          * If we have more or the same amount of outsanding extents than we have
4436          * reserved then we need to leave the reserved extents count alone.
4437          */
4438         if (BTRFS_I(inode)->outstanding_extents >=
4439             BTRFS_I(inode)->reserved_extents)
4440                 return drop_inode_space;
4441
4442         dropped_extents = BTRFS_I(inode)->reserved_extents -
4443                 BTRFS_I(inode)->outstanding_extents;
4444         BTRFS_I(inode)->reserved_extents -= dropped_extents;
4445         return dropped_extents + drop_inode_space;
4446 }
4447
4448 /**
4449  * calc_csum_metadata_size - return the amount of metada space that must be
4450  *      reserved/free'd for the given bytes.
4451  * @inode: the inode we're manipulating
4452  * @num_bytes: the number of bytes in question
4453  * @reserve: 1 if we are reserving space, 0 if we are freeing space
4454  *
4455  * This adjusts the number of csum_bytes in the inode and then returns the
4456  * correct amount of metadata that must either be reserved or freed.  We
4457  * calculate how many checksums we can fit into one leaf and then divide the
4458  * number of bytes that will need to be checksumed by this value to figure out
4459  * how many checksums will be required.  If we are adding bytes then the number
4460  * may go up and we will return the number of additional bytes that must be
4461  * reserved.  If it is going down we will return the number of bytes that must
4462  * be freed.
4463  *
4464  * This must be called with BTRFS_I(inode)->lock held.
4465  */
4466 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
4467                                    int reserve)
4468 {
4469         struct btrfs_root *root = BTRFS_I(inode)->root;
4470         u64 csum_size;
4471         int num_csums_per_leaf;
4472         int num_csums;
4473         int old_csums;
4474
4475         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
4476             BTRFS_I(inode)->csum_bytes == 0)
4477                 return 0;
4478
4479         old_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
4480         if (reserve)
4481                 BTRFS_I(inode)->csum_bytes += num_bytes;
4482         else
4483                 BTRFS_I(inode)->csum_bytes -= num_bytes;
4484         csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
4485         num_csums_per_leaf = (int)div64_u64(csum_size,
4486                                             sizeof(struct btrfs_csum_item) +
4487                                             sizeof(struct btrfs_disk_key));
4488         num_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
4489         num_csums = num_csums + num_csums_per_leaf - 1;
4490         num_csums = num_csums / num_csums_per_leaf;
4491
4492         old_csums = old_csums + num_csums_per_leaf - 1;
4493         old_csums = old_csums / num_csums_per_leaf;
4494
4495         /* No change, no need to reserve more */
4496         if (old_csums == num_csums)
4497                 return 0;
4498
4499         if (reserve)
4500                 return btrfs_calc_trans_metadata_size(root,
4501                                                       num_csums - old_csums);
4502
4503         return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
4504 }
4505
4506 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
4507 {
4508         struct btrfs_root *root = BTRFS_I(inode)->root;
4509         struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
4510         u64 to_reserve = 0;
4511         u64 csum_bytes;
4512         unsigned nr_extents = 0;
4513         int extra_reserve = 0;
4514         enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
4515         int ret;
4516
4517         /* Need to be holding the i_mutex here if we aren't free space cache */
4518         if (btrfs_is_free_space_inode(inode))
4519                 flush = BTRFS_RESERVE_NO_FLUSH;
4520
4521         if (flush != BTRFS_RESERVE_NO_FLUSH &&
4522             btrfs_transaction_in_commit(root->fs_info))
4523                 schedule_timeout(1);
4524
4525         mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
4526         num_bytes = ALIGN(num_bytes, root->sectorsize);
4527
4528         spin_lock(&BTRFS_I(inode)->lock);
4529         BTRFS_I(inode)->outstanding_extents++;
4530
4531         if (BTRFS_I(inode)->outstanding_extents >
4532             BTRFS_I(inode)->reserved_extents)
4533                 nr_extents = BTRFS_I(inode)->outstanding_extents -
4534                         BTRFS_I(inode)->reserved_extents;
4535
4536         /*
4537          * Add an item to reserve for updating the inode when we complete the
4538          * delalloc io.
4539          */
4540         if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4541                       &BTRFS_I(inode)->runtime_flags)) {
4542                 nr_extents++;
4543                 extra_reserve = 1;
4544         }
4545
4546         to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
4547         to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
4548         csum_bytes = BTRFS_I(inode)->csum_bytes;
4549         spin_unlock(&BTRFS_I(inode)->lock);
4550
4551         if (root->fs_info->quota_enabled) {
4552                 ret = btrfs_qgroup_reserve(root, num_bytes +
4553                                            nr_extents * root->leafsize);
4554                 if (ret) {
4555                         mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
4556                         return ret;
4557                 }
4558         }
4559
4560         ret = reserve_metadata_bytes(root, block_rsv, to_reserve, flush);
4561         if (ret) {
4562                 u64 to_free = 0;
4563                 unsigned dropped;
4564
4565                 spin_lock(&BTRFS_I(inode)->lock);
4566                 dropped = drop_outstanding_extent(inode);
4567                 /*
4568                  * If the inodes csum_bytes is the same as the original
4569                  * csum_bytes then we know we haven't raced with any free()ers
4570                  * so we can just reduce our inodes csum bytes and carry on.
4571                  * Otherwise we have to do the normal free thing to account for
4572                  * the case that the free side didn't free up its reserve
4573                  * because of this outstanding reservation.
4574                  */
4575                 if (BTRFS_I(inode)->csum_bytes == csum_bytes)
4576                         calc_csum_metadata_size(inode, num_bytes, 0);
4577                 else
4578                         to_free = calc_csum_metadata_size(inode, num_bytes, 0);
4579                 spin_unlock(&BTRFS_I(inode)->lock);
4580                 if (dropped)
4581                         to_free += btrfs_calc_trans_metadata_size(root, dropped);
4582
4583                 if (to_free) {
4584                         btrfs_block_rsv_release(root, block_rsv, to_free);
4585                         trace_btrfs_space_reservation(root->fs_info,
4586                                                       "delalloc",
4587                                                       btrfs_ino(inode),
4588                                                       to_free, 0);
4589                 }
4590                 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
4591                 return ret;
4592         }
4593
4594         spin_lock(&BTRFS_I(inode)->lock);
4595         if (extra_reserve) {
4596                 set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4597                         &BTRFS_I(inode)->runtime_flags);
4598                 nr_extents--;
4599         }
4600         BTRFS_I(inode)->reserved_extents += nr_extents;
4601         spin_unlock(&BTRFS_I(inode)->lock);
4602         mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
4603
4604         if (to_reserve)
4605                 trace_btrfs_space_reservation(root->fs_info,"delalloc",
4606                                               btrfs_ino(inode), to_reserve, 1);
4607         block_rsv_add_bytes(block_rsv, to_reserve, 1);
4608
4609         return 0;
4610 }
4611
4612 /**
4613  * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
4614  * @inode: the inode to release the reservation for
4615  * @num_bytes: the number of bytes we're releasing
4616  *
4617  * This will release the metadata reservation for an inode.  This can be called
4618  * once we complete IO for a given set of bytes to release their metadata
4619  * reservations.
4620  */
4621 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
4622 {
4623         struct btrfs_root *root = BTRFS_I(inode)->root;
4624         u64 to_free = 0;
4625         unsigned dropped;
4626
4627         num_bytes = ALIGN(num_bytes, root->sectorsize);
4628         spin_lock(&BTRFS_I(inode)->lock);
4629         dropped = drop_outstanding_extent(inode);
4630
4631         to_free = calc_csum_metadata_size(inode, num_bytes, 0);
4632         spin_unlock(&BTRFS_I(inode)->lock);
4633         if (dropped > 0)
4634                 to_free += btrfs_calc_trans_metadata_size(root, dropped);
4635
4636         trace_btrfs_space_reservation(root->fs_info, "delalloc",
4637                                       btrfs_ino(inode), to_free, 0);
4638         if (root->fs_info->quota_enabled) {
4639                 btrfs_qgroup_free(root, num_bytes +
4640                                         dropped * root->leafsize);
4641         }
4642
4643         btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
4644                                 to_free);
4645 }
4646
4647 /**
4648  * btrfs_delalloc_reserve_space - reserve data and metadata space for delalloc
4649  * @inode: inode we're writing to
4650  * @num_bytes: the number of bytes we want to allocate
4651  *
4652  * This will do the following things
4653  *
4654  * o reserve space in the data space info for num_bytes
4655  * o reserve space in the metadata space info based on number of outstanding
4656  *   extents and how much csums will be needed
4657  * o add to the inodes ->delalloc_bytes
4658  * o add it to the fs_info's delalloc inodes list.
4659  *
4660  * This will return 0 for success and -ENOSPC if there is no space left.
4661  */
4662 int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
4663 {
4664         int ret;
4665
4666         ret = btrfs_check_data_free_space(inode, num_bytes);
4667         if (ret)
4668                 return ret;
4669
4670         ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
4671         if (ret) {
4672                 btrfs_free_reserved_data_space(inode, num_bytes);
4673                 return ret;
4674         }
4675
4676         return 0;
4677 }
4678
4679 /**
4680  * btrfs_delalloc_release_space - release data and metadata space for delalloc
4681  * @inode: inode we're releasing space for
4682  * @num_bytes: the number of bytes we want to free up
4683  *
4684  * This must be matched with a call to btrfs_delalloc_reserve_space.  This is
4685  * called in the case that we don't need the metadata AND data reservations
4686  * anymore.  So if there is an error or we insert an inline extent.
4687  *
4688  * This function will release the metadata space that was not used and will
4689  * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
4690  * list if there are no delalloc bytes left.
4691  */
4692 void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
4693 {
4694         btrfs_delalloc_release_metadata(inode, num_bytes);
4695         btrfs_free_reserved_data_space(inode, num_bytes);
4696 }
4697
4698 static int update_block_group(struct btrfs_trans_handle *trans,
4699                               struct btrfs_root *root,
4700                               u64 bytenr, u64 num_bytes, int alloc)
4701 {
4702         struct btrfs_block_group_cache *cache = NULL;
4703         struct btrfs_fs_info *info = root->fs_info;
4704         u64 total = num_bytes;
4705         u64 old_val;
4706         u64 byte_in_group;
4707         int factor;
4708
4709         /* block accounting for super block */
4710         spin_lock(&info->delalloc_lock);
4711         old_val = btrfs_super_bytes_used(info->super_copy);
4712         if (alloc)
4713                 old_val += num_bytes;
4714         else
4715                 old_val -= num_bytes;
4716         btrfs_set_super_bytes_used(info->super_copy, old_val);
4717         spin_unlock(&info->delalloc_lock);
4718
4719         while (total) {
4720                 cache = btrfs_lookup_block_group(info, bytenr);
4721                 if (!cache)
4722                         return -ENOENT;
4723                 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
4724                                     BTRFS_BLOCK_GROUP_RAID1 |
4725                                     BTRFS_BLOCK_GROUP_RAID10))
4726                         factor = 2;
4727                 else
4728                         factor = 1;
4729                 /*
4730                  * If this block group has free space cache written out, we
4731                  * need to make sure to load it if we are removing space.  This
4732                  * is because we need the unpinning stage to actually add the
4733                  * space back to the block group, otherwise we will leak space.
4734                  */
4735                 if (!alloc && cache->cached == BTRFS_CACHE_NO)
4736                         cache_block_group(cache, trans, NULL, 1);
4737
4738                 byte_in_group = bytenr - cache->key.objectid;
4739                 WARN_ON(byte_in_group > cache->key.offset);
4740
4741                 spin_lock(&cache->space_info->lock);
4742                 spin_lock(&cache->lock);
4743
4744                 if (btrfs_test_opt(root, SPACE_CACHE) &&
4745                     cache->disk_cache_state < BTRFS_DC_CLEAR)
4746                         cache->disk_cache_state = BTRFS_DC_CLEAR;
4747
4748                 cache->dirty = 1;
4749                 old_val = btrfs_block_group_used(&cache->item);
4750                 num_bytes = min(total, cache->key.offset - byte_in_group);
4751                 if (alloc) {
4752                         old_val += num_bytes;
4753                         btrfs_set_block_group_used(&cache->item, old_val);
4754                         cache->reserved -= num_bytes;
4755                         cache->space_info->bytes_reserved -= num_bytes;
4756                         cache->space_info->bytes_used += num_bytes;
4757                         cache->space_info->disk_used += num_bytes * factor;
4758                         spin_unlock(&cache->lock);
4759                         spin_unlock(&cache->space_info->lock);
4760                 } else {
4761                         old_val -= num_bytes;
4762                         btrfs_set_block_group_used(&cache->item, old_val);
4763                         cache->pinned += num_bytes;
4764                         cache->space_info->bytes_pinned += num_bytes;
4765                         cache->space_info->bytes_used -= num_bytes;
4766                         cache->space_info->disk_used -= num_bytes * factor;
4767                         spin_unlock(&cache->lock);
4768                         spin_unlock(&cache->space_info->lock);
4769
4770                         set_extent_dirty(info->pinned_extents,
4771                                          bytenr, bytenr + num_bytes - 1,
4772                                          GFP_NOFS | __GFP_NOFAIL);
4773                 }
4774                 btrfs_put_block_group(cache);
4775                 total -= num_bytes;
4776                 bytenr += num_bytes;
4777         }
4778         return 0;
4779 }
4780
4781 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
4782 {
4783         struct btrfs_block_group_cache *cache;
4784         u64 bytenr;
4785
4786         cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
4787         if (!cache)
4788                 return 0;
4789
4790         bytenr = cache->key.objectid;
4791         btrfs_put_block_group(cache);
4792
4793         return bytenr;
4794 }
4795
4796 static int pin_down_extent(struct btrfs_root *root,
4797                            struct btrfs_block_group_cache *cache,
4798                            u64 bytenr, u64 num_bytes, int reserved)
4799 {
4800         spin_lock(&cache->space_info->lock);
4801         spin_lock(&cache->lock);
4802         cache->pinned += num_bytes;
4803         cache->space_info->bytes_pinned += num_bytes;
4804         if (reserved) {
4805                 cache->reserved -= num_bytes;
4806                 cache->space_info->bytes_reserved -= num_bytes;
4807         }
4808         spin_unlock(&cache->lock);
4809         spin_unlock(&cache->space_info->lock);
4810
4811         set_extent_dirty(root->fs_info->pinned_extents, bytenr,
4812                          bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
4813         return 0;
4814 }
4815
4816 /*
4817  * this function must be called within transaction
4818  */
4819 int btrfs_pin_extent(struct btrfs_root *root,
4820                      u64 bytenr, u64 num_bytes, int reserved)
4821 {
4822         struct btrfs_block_group_cache *cache;
4823
4824         cache = btrfs_lookup_block_group(root->fs_info, bytenr);
4825         BUG_ON(!cache); /* Logic error */
4826
4827         pin_down_extent(root, cache, bytenr, num_bytes, reserved);
4828
4829         btrfs_put_block_group(cache);
4830         return 0;
4831 }
4832
4833 /*
4834  * this function must be called within transaction
4835  */
4836 int btrfs_pin_extent_for_log_replay(struct btrfs_trans_handle *trans,
4837                                     struct btrfs_root *root,
4838                                     u64 bytenr, u64 num_bytes)
4839 {
4840         struct btrfs_block_group_cache *cache;
4841
4842         cache = btrfs_lookup_block_group(root->fs_info, bytenr);
4843         BUG_ON(!cache); /* Logic error */
4844
4845         /*
4846          * pull in the free space cache (if any) so that our pin
4847          * removes the free space from the cache.  We have load_only set
4848          * to one because the slow code to read in the free extents does check
4849          * the pinned extents.
4850          */
4851         cache_block_group(cache, trans, root, 1);
4852
4853         pin_down_extent(root, cache, bytenr, num_bytes, 0);
4854
4855         /* remove us from the free space cache (if we're there at all) */
4856         btrfs_remove_free_space(cache, bytenr, num_bytes);
4857         btrfs_put_block_group(cache);
4858         return 0;
4859 }
4860
4861 /**
4862  * btrfs_update_reserved_bytes - update the block_group and space info counters
4863  * @cache:      The cache we are manipulating
4864  * @num_bytes:  The number of bytes in question
4865  * @reserve:    One of the reservation enums
4866  *
4867  * This is called by the allocator when it reserves space, or by somebody who is
4868  * freeing space that was never actually used on disk.  For example if you
4869  * reserve some space for a new leaf in transaction A and before transaction A
4870  * commits you free that leaf, you call this with reserve set to 0 in order to
4871  * clear the reservation.
4872  *
4873  * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
4874  * ENOSPC accounting.  For data we handle the reservation through clearing the
4875  * delalloc bits in the io_tree.  We have to do this since we could end up
4876  * allocating less disk space for the amount of data we have reserved in the
4877  * case of compression.
4878  *
4879  * If this is a reservation and the block group has become read only we cannot
4880  * make the reservation and return -EAGAIN, otherwise this function always
4881  * succeeds.
4882  */
4883 static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
4884                                        u64 num_bytes, int reserve)
4885 {
4886         struct btrfs_space_info *space_info = cache->space_info;
4887         int ret = 0;
4888
4889         spin_lock(&space_info->lock);
4890         spin_lock(&cache->lock);
4891         if (reserve != RESERVE_FREE) {
4892                 if (cache->ro) {
4893                         ret = -EAGAIN;
4894                 } else {
4895                         cache->reserved += num_bytes;
4896                         space_info->bytes_reserved += num_bytes;
4897                         if (reserve == RESERVE_ALLOC) {
4898                                 trace_btrfs_space_reservation(cache->fs_info,
4899                                                 "space_info", space_info->flags,
4900                                                 num_bytes, 0);
4901                                 space_info->bytes_may_use -= num_bytes;
4902                         }
4903                 }
4904         } else {
4905                 if (cache->ro)
4906                         space_info->bytes_readonly += num_bytes;
4907                 cache->reserved -= num_bytes;
4908                 space_info->bytes_reserved -= num_bytes;
4909                 space_info->reservation_progress++;
4910         }
4911         spin_unlock(&cache->lock);
4912         spin_unlock(&space_info->lock);
4913         return ret;
4914 }
4915
4916 void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
4917                                 struct btrfs_root *root)
4918 {
4919         struct btrfs_fs_info *fs_info = root->fs_info;
4920         struct btrfs_caching_control *next;
4921         struct btrfs_caching_control *caching_ctl;
4922         struct btrfs_block_group_cache *cache;
4923
4924         down_write(&fs_info->extent_commit_sem);
4925
4926         list_for_each_entry_safe(caching_ctl, next,
4927                                  &fs_info->caching_block_groups, list) {
4928                 cache = caching_ctl->block_group;
4929                 if (block_group_cache_done(cache)) {
4930                         cache->last_byte_to_unpin = (u64)-1;
4931                         list_del_init(&caching_ctl->list);
4932                         put_caching_control(caching_ctl);
4933                 } else {
4934                         cache->last_byte_to_unpin = caching_ctl->progress;
4935                 }
4936         }
4937
4938         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
4939                 fs_info->pinned_extents = &fs_info->freed_extents[1];
4940         else
4941                 fs_info->pinned_extents = &fs_info->freed_extents[0];
4942
4943         up_write(&fs_info->extent_commit_sem);
4944
4945         update_global_block_rsv(fs_info);
4946 }
4947
4948 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
4949 {
4950         struct btrfs_fs_info *fs_info = root->fs_info;
4951         struct btrfs_block_group_cache *cache = NULL;
4952         u64 len;
4953
4954         while (start <= end) {
4955                 if (!cache ||
4956                     start >= cache->key.objectid + cache->key.offset) {
4957                         if (cache)
4958                                 btrfs_put_block_group(cache);
4959                         cache = btrfs_lookup_block_group(fs_info, start);
4960                         BUG_ON(!cache); /* Logic error */
4961                 }
4962
4963                 len = cache->key.objectid + cache->key.offset - start;
4964                 len = min(len, end + 1 - start);
4965
4966                 if (start < cache->last_byte_to_unpin) {
4967                         len = min(len, cache->last_byte_to_unpin - start);
4968                         btrfs_add_free_space(cache, start, len);
4969                 }
4970
4971                 start += len;
4972
4973                 spin_lock(&cache->space_info->lock);
4974                 spin_lock(&cache->lock);
4975                 cache->pinned -= len;
4976                 cache->space_info->bytes_pinned -= len;
4977                 if (cache->ro)
4978                         cache->space_info->bytes_readonly += len;
4979                 spin_unlock(&cache->lock);
4980                 spin_unlock(&cache->space_info->lock);
4981         }
4982
4983         if (cache)
4984                 btrfs_put_block_group(cache);
4985         return 0;
4986 }
4987
4988 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
4989                                struct btrfs_root *root)
4990 {
4991         struct btrfs_fs_info *fs_info = root->fs_info;
4992         struct extent_io_tree *unpin;
4993         u64 start;
4994         u64 end;
4995         int ret;
4996
4997         if (trans->aborted)
4998                 return 0;
4999
5000         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5001                 unpin = &fs_info->freed_extents[1];
5002         else
5003                 unpin = &fs_info->freed_extents[0];
5004
5005         while (1) {
5006                 ret = find_first_extent_bit(unpin, 0, &start, &end,
5007                                             EXTENT_DIRTY, NULL);
5008                 if (ret)
5009                         break;
5010
5011                 if (btrfs_test_opt(root, DISCARD))
5012                         ret = btrfs_discard_extent(root, start,
5013                                                    end + 1 - start, NULL);
5014
5015                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
5016                 unpin_extent_range(root, start, end);
5017                 cond_resched();
5018         }
5019
5020         return 0;
5021 }
5022
5023 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
5024                                 struct btrfs_root *root,
5025                                 u64 bytenr, u64 num_bytes, u64 parent,
5026                                 u64 root_objectid, u64 owner_objectid,
5027                                 u64 owner_offset, int refs_to_drop,
5028                                 struct btrfs_delayed_extent_op *extent_op)
5029 {
5030         struct btrfs_key key;
5031         struct btrfs_path *path;
5032         struct btrfs_fs_info *info = root->fs_info;
5033         struct btrfs_root *extent_root = info->extent_root;
5034         struct extent_buffer *leaf;
5035         struct btrfs_extent_item *ei;
5036         struct btrfs_extent_inline_ref *iref;
5037         int ret;
5038         int is_data;
5039         int extent_slot = 0;
5040         int found_extent = 0;
5041         int num_to_del = 1;
5042         u32 item_size;
5043         u64 refs;
5044
5045         path = btrfs_alloc_path();
5046         if (!path)
5047                 return -ENOMEM;
5048
5049         path->reada = 1;
5050         path->leave_spinning = 1;
5051
5052         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
5053         BUG_ON(!is_data && refs_to_drop != 1);
5054
5055         ret = lookup_extent_backref(trans, extent_root, path, &iref,
5056                                     bytenr, num_bytes, parent,
5057                                     root_objectid, owner_objectid,
5058                                     owner_offset);
5059         if (ret == 0) {
5060                 extent_slot = path->slots[0];
5061                 while (extent_slot >= 0) {
5062                         btrfs_item_key_to_cpu(path->nodes[0], &key,
5063                                               extent_slot);
5064                         if (key.objectid != bytenr)
5065                                 break;
5066                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5067                             key.offset == num_bytes) {
5068                                 found_extent = 1;
5069                                 break;
5070                         }
5071                         if (path->slots[0] - extent_slot > 5)
5072                                 break;
5073                         extent_slot--;
5074                 }
5075 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5076                 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
5077                 if (found_extent && item_size < sizeof(*ei))
5078                         found_extent = 0;
5079 #endif
5080                 if (!found_extent) {
5081                         BUG_ON(iref);
5082                         ret = remove_extent_backref(trans, extent_root, path,
5083                                                     NULL, refs_to_drop,
5084                                                     is_data);
5085                         if (ret) {
5086                                 btrfs_abort_transaction(trans, extent_root, ret);
5087                                 goto out;
5088                         }
5089                         btrfs_release_path(path);
5090                         path->leave_spinning = 1;
5091
5092                         key.objectid = bytenr;
5093                         key.type = BTRFS_EXTENT_ITEM_KEY;
5094                         key.offset = num_bytes;
5095
5096                         ret = btrfs_search_slot(trans, extent_root,
5097                                                 &key, path, -1, 1);
5098                         if (ret) {
5099                                 printk(KERN_ERR "umm, got %d back from search"
5100                                        ", was looking for %llu\n", ret,
5101                                        (unsigned long long)bytenr);
5102                                 if (ret > 0)
5103                                         btrfs_print_leaf(extent_root,
5104                                                          path->nodes[0]);
5105                         }
5106                         if (ret < 0) {
5107                                 btrfs_abort_transaction(trans, extent_root, ret);
5108                                 goto out;
5109                         }
5110                         extent_slot = path->slots[0];
5111                 }
5112         } else if (ret == -ENOENT) {
5113                 btrfs_print_leaf(extent_root, path->nodes[0]);
5114                 WARN_ON(1);
5115                 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
5116                        "parent %llu root %llu  owner %llu offset %llu\n",
5117                        (unsigned long long)bytenr,
5118                        (unsigned long long)parent,
5119                        (unsigned long long)root_objectid,
5120                        (unsigned long long)owner_objectid,
5121                        (unsigned long long)owner_offset);
5122         } else {
5123                 btrfs_abort_transaction(trans, extent_root, ret);
5124                 goto out;
5125         }
5126
5127         leaf = path->nodes[0];
5128         item_size = btrfs_item_size_nr(leaf, extent_slot);
5129 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5130         if (item_size < sizeof(*ei)) {
5131                 BUG_ON(found_extent || extent_slot != path->slots[0]);
5132                 ret = convert_extent_item_v0(trans, extent_root, path,
5133                                              owner_objectid, 0);
5134                 if (ret < 0) {
5135                         btrfs_abort_transaction(trans, extent_root, ret);
5136                         goto out;
5137                 }
5138
5139                 btrfs_release_path(path);
5140                 path->leave_spinning = 1;
5141
5142                 key.objectid = bytenr;
5143                 key.type = BTRFS_EXTENT_ITEM_KEY;
5144                 key.offset = num_bytes;
5145
5146                 ret = btrfs_search_slot(trans, extent_root, &key, path,
5147                                         -1, 1);
5148                 if (ret) {
5149                         printk(KERN_ERR "umm, got %d back from search"
5150                                ", was looking for %llu\n", ret,
5151                                (unsigned long long)bytenr);
5152                         btrfs_print_leaf(extent_root, path->nodes[0]);
5153                 }
5154                 if (ret < 0) {
5155                         btrfs_abort_transaction(trans, extent_root, ret);
5156                         goto out;
5157                 }
5158
5159                 extent_slot = path->slots[0];
5160                 leaf = path->nodes[0];
5161                 item_size = btrfs_item_size_nr(leaf, extent_slot);
5162         }
5163 #endif
5164         BUG_ON(item_size < sizeof(*ei));
5165         ei = btrfs_item_ptr(leaf, extent_slot,
5166                             struct btrfs_extent_item);
5167         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
5168                 struct btrfs_tree_block_info *bi;
5169                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
5170                 bi = (struct btrfs_tree_block_info *)(ei + 1);
5171                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
5172         }
5173
5174         refs = btrfs_extent_refs(leaf, ei);
5175         BUG_ON(refs < refs_to_drop);
5176         refs -= refs_to_drop;
5177
5178         if (refs > 0) {
5179                 if (extent_op)
5180                         __run_delayed_extent_op(extent_op, leaf, ei);
5181                 /*
5182                  * In the case of inline back ref, reference count will
5183                  * be updated by remove_extent_backref
5184                  */
5185                 if (iref) {
5186                         BUG_ON(!found_extent);
5187                 } else {
5188                         btrfs_set_extent_refs(leaf, ei, refs);
5189                         btrfs_mark_buffer_dirty(leaf);
5190                 }
5191                 if (found_extent) {
5192                         ret = remove_extent_backref(trans, extent_root, path,
5193                                                     iref, refs_to_drop,
5194                                                     is_data);
5195                         if (ret) {
5196                                 btrfs_abort_transaction(trans, extent_root, ret);
5197                                 goto out;
5198                         }
5199                 }
5200         } else {
5201                 if (found_extent) {
5202                         BUG_ON(is_data && refs_to_drop !=
5203                                extent_data_ref_count(root, path, iref));
5204                         if (iref) {
5205                                 BUG_ON(path->slots[0] != extent_slot);
5206                         } else {
5207                                 BUG_ON(path->slots[0] != extent_slot + 1);
5208                                 path->slots[0] = extent_slot;
5209                                 num_to_del = 2;
5210                         }
5211                 }
5212
5213                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
5214                                       num_to_del);
5215                 if (ret) {
5216                         btrfs_abort_transaction(trans, extent_root, ret);
5217                         goto out;
5218                 }
5219                 btrfs_release_path(path);
5220
5221                 if (is_data) {
5222                         ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
5223                         if (ret) {
5224                                 btrfs_abort_transaction(trans, extent_root, ret);
5225                                 goto out;
5226                         }
5227                 }
5228
5229                 ret = update_block_group(trans, root, bytenr, num_bytes, 0);
5230                 if (ret) {
5231                         btrfs_abort_transaction(trans, extent_root, ret);
5232                         goto out;
5233                 }
5234         }
5235 out:
5236         btrfs_free_path(path);
5237         return ret;
5238 }
5239
5240 /*
5241  * when we free an block, it is possible (and likely) that we free the last
5242  * delayed ref for that extent as well.  This searches the delayed ref tree for
5243  * a given extent, and if there are no other delayed refs to be processed, it
5244  * removes it from the tree.
5245  */
5246 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
5247                                       struct btrfs_root *root, u64 bytenr)
5248 {
5249         struct btrfs_delayed_ref_head *head;
5250         struct btrfs_delayed_ref_root *delayed_refs;
5251         struct btrfs_delayed_ref_node *ref;
5252         struct rb_node *node;
5253         int ret = 0;
5254
5255         delayed_refs = &trans->transaction->delayed_refs;
5256         spin_lock(&delayed_refs->lock);
5257         head = btrfs_find_delayed_ref_head(trans, bytenr);
5258         if (!head)
5259                 goto out;
5260
5261         node = rb_prev(&head->node.rb_node);
5262         if (!node)
5263                 goto out;
5264
5265         ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
5266
5267         /* there are still entries for this ref, we can't drop it */
5268         if (ref->bytenr == bytenr)
5269                 goto out;
5270
5271         if (head->extent_op) {
5272                 if (!head->must_insert_reserved)
5273                         goto out;
5274                 kfree(head->extent_op);
5275                 head->extent_op = NULL;
5276         }
5277
5278         /*
5279          * waiting for the lock here would deadlock.  If someone else has it
5280          * locked they are already in the process of dropping it anyway
5281          */
5282         if (!mutex_trylock(&head->mutex))
5283                 goto out;
5284
5285         /*
5286          * at this point we have a head with no other entries.  Go
5287          * ahead and process it.
5288          */
5289         head->node.in_tree = 0;
5290         rb_erase(&head->node.rb_node, &delayed_refs->root);
5291
5292         delayed_refs->num_entries--;
5293
5294         /*
5295          * we don't take a ref on the node because we're removing it from the
5296          * tree, so we just steal the ref the tree was holding.
5297          */
5298         delayed_refs->num_heads--;
5299         if (list_empty(&head->cluster))
5300                 delayed_refs->num_heads_ready--;
5301
5302         list_del_init(&head->cluster);
5303         spin_unlock(&delayed_refs->lock);
5304
5305         BUG_ON(head->extent_op);
5306         if (head->must_insert_reserved)
5307                 ret = 1;
5308
5309         mutex_unlock(&head->mutex);
5310         btrfs_put_delayed_ref(&head->node);
5311         return ret;
5312 out:
5313         spin_unlock(&delayed_refs->lock);
5314         return 0;
5315 }
5316
5317 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
5318                            struct btrfs_root *root,
5319                            struct extent_buffer *buf,
5320                            u64 parent, int last_ref)
5321 {
5322         struct btrfs_block_group_cache *cache = NULL;
5323         int ret;
5324
5325         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5326                 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
5327                                         buf->start, buf->len,
5328                                         parent, root->root_key.objectid,
5329                                         btrfs_header_level(buf),
5330                                         BTRFS_DROP_DELAYED_REF, NULL, 0);
5331                 BUG_ON(ret); /* -ENOMEM */
5332         }
5333
5334         if (!last_ref)
5335                 return;
5336
5337         cache = btrfs_lookup_block_group(root->fs_info, buf->start);
5338
5339         if (btrfs_header_generation(buf) == trans->transid) {
5340                 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
5341                         ret = check_ref_cleanup(trans, root, buf->start);
5342                         if (!ret)
5343                                 goto out;
5344                 }
5345
5346                 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
5347                         pin_down_extent(root, cache, buf->start, buf->len, 1);
5348                         goto out;
5349                 }
5350
5351                 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
5352
5353                 btrfs_add_free_space(cache, buf->start, buf->len);
5354                 btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE);
5355         }
5356 out:
5357         /*
5358          * Deleting the buffer, clear the corrupt flag since it doesn't matter
5359          * anymore.
5360          */
5361         clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
5362         btrfs_put_block_group(cache);
5363 }
5364
5365 /* Can return -ENOMEM */
5366 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
5367                       u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
5368                       u64 owner, u64 offset, int for_cow)
5369 {
5370         int ret;
5371         struct btrfs_fs_info *fs_info = root->fs_info;
5372
5373         /*
5374          * tree log blocks never actually go into the extent allocation
5375          * tree, just update pinning info and exit early.
5376          */
5377         if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
5378                 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
5379                 /* unlocks the pinned mutex */
5380                 btrfs_pin_extent(root, bytenr, num_bytes, 1);
5381                 ret = 0;
5382         } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
5383                 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
5384                                         num_bytes,
5385                                         parent, root_objectid, (int)owner,
5386                                         BTRFS_DROP_DELAYED_REF, NULL, for_cow);
5387         } else {
5388                 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
5389                                                 num_bytes,
5390                                                 parent, root_objectid, owner,
5391                                                 offset, BTRFS_DROP_DELAYED_REF,
5392                                                 NULL, for_cow);
5393         }
5394         return ret;
5395 }
5396
5397 static u64 stripe_align(struct btrfs_root *root, u64 val)
5398 {
5399         u64 mask = ((u64)root->stripesize - 1);
5400         u64 ret = (val + mask) & ~mask;
5401         return ret;
5402 }
5403
5404 /*
5405  * when we wait for progress in the block group caching, its because
5406  * our allocation attempt failed at least once.  So, we must sleep
5407  * and let some progress happen before we try again.
5408  *
5409  * This function will sleep at least once waiting for new free space to
5410  * show up, and then it will check the block group free space numbers
5411  * for our min num_bytes.  Another option is to have it go ahead
5412  * and look in the rbtree for a free extent of a given size, but this
5413  * is a good start.
5414  */
5415 static noinline int
5416 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
5417                                 u64 num_bytes)
5418 {
5419         struct btrfs_caching_control *caching_ctl;
5420         DEFINE_WAIT(wait);
5421
5422         caching_ctl = get_caching_control(cache);
5423         if (!caching_ctl)
5424                 return 0;
5425
5426         wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
5427                    (cache->free_space_ctl->free_space >= num_bytes));
5428
5429         put_caching_control(caching_ctl);
5430         return 0;
5431 }
5432
5433 static noinline int
5434 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
5435 {
5436         struct btrfs_caching_control *caching_ctl;
5437         DEFINE_WAIT(wait);
5438
5439         caching_ctl = get_caching_control(cache);
5440         if (!caching_ctl)
5441                 return 0;
5442
5443         wait_event(caching_ctl->wait, block_group_cache_done(cache));
5444
5445         put_caching_control(caching_ctl);
5446         return 0;
5447 }
5448
5449 static int __get_block_group_index(u64 flags)
5450 {
5451         int index;
5452
5453         if (flags & BTRFS_BLOCK_GROUP_RAID10)
5454                 index = 0;
5455         else if (flags & BTRFS_BLOCK_GROUP_RAID1)
5456                 index = 1;
5457         else if (flags & BTRFS_BLOCK_GROUP_DUP)
5458                 index = 2;
5459         else if (flags & BTRFS_BLOCK_GROUP_RAID0)
5460                 index = 3;
5461         else
5462                 index = 4;
5463
5464         return index;
5465 }
5466
5467 static int get_block_group_index(struct btrfs_block_group_cache *cache)
5468 {
5469         return __get_block_group_index(cache->flags);
5470 }
5471
5472 enum btrfs_loop_type {
5473         LOOP_CACHING_NOWAIT = 0,
5474         LOOP_CACHING_WAIT = 1,
5475         LOOP_ALLOC_CHUNK = 2,
5476         LOOP_NO_EMPTY_SIZE = 3,
5477 };
5478
5479 /*
5480  * walks the btree of allocated extents and find a hole of a given size.
5481  * The key ins is changed to record the hole:
5482  * ins->objectid == block start
5483  * ins->flags = BTRFS_EXTENT_ITEM_KEY
5484  * ins->offset == number of blocks
5485  * Any available blocks before search_start are skipped.
5486  */
5487 static noinline int find_free_extent(struct btrfs_trans_handle *trans,
5488                                      struct btrfs_root *orig_root,
5489                                      u64 num_bytes, u64 empty_size,
5490                                      u64 hint_byte, struct btrfs_key *ins,
5491                                      u64 data)
5492 {
5493         int ret = 0;
5494         struct btrfs_root *root = orig_root->fs_info->extent_root;
5495         struct btrfs_free_cluster *last_ptr = NULL;
5496         struct btrfs_block_group_cache *block_group = NULL;
5497         struct btrfs_block_group_cache *used_block_group;
5498         u64 search_start = 0;
5499         int empty_cluster = 2 * 1024 * 1024;
5500         struct btrfs_space_info *space_info;
5501         int loop = 0;
5502         int index = 0;
5503         int alloc_type = (data & BTRFS_BLOCK_GROUP_DATA) ?
5504                 RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
5505         bool found_uncached_bg = false;
5506         bool failed_cluster_refill = false;
5507         bool failed_alloc = false;
5508         bool use_cluster = true;
5509         bool have_caching_bg = false;
5510
5511         WARN_ON(num_bytes < root->sectorsize);
5512         btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
5513         ins->objectid = 0;
5514         ins->offset = 0;
5515
5516         trace_find_free_extent(orig_root, num_bytes, empty_size, data);
5517
5518         space_info = __find_space_info(root->fs_info, data);
5519         if (!space_info) {
5520                 printk(KERN_ERR "No space info for %llu\n", data);
5521                 return -ENOSPC;
5522         }
5523
5524         /*
5525          * If the space info is for both data and metadata it means we have a
5526          * small filesystem and we can't use the clustering stuff.
5527          */
5528         if (btrfs_mixed_space_info(space_info))
5529                 use_cluster = false;
5530
5531         if (data & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
5532                 last_ptr = &root->fs_info->meta_alloc_cluster;
5533                 if (!btrfs_test_opt(root, SSD))
5534                         empty_cluster = 64 * 1024;
5535         }
5536
5537         if ((data & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
5538             btrfs_test_opt(root, SSD)) {
5539                 last_ptr = &root->fs_info->data_alloc_cluster;
5540         }
5541
5542         if (last_ptr) {
5543                 spin_lock(&last_ptr->lock);
5544                 if (last_ptr->block_group)
5545                         hint_byte = last_ptr->window_start;
5546                 spin_unlock(&last_ptr->lock);
5547         }
5548
5549         search_start = max(search_start, first_logical_byte(root, 0));
5550         search_start = max(search_start, hint_byte);
5551
5552         if (!last_ptr)
5553                 empty_cluster = 0;
5554
5555         if (search_start == hint_byte) {
5556                 block_group = btrfs_lookup_block_group(root->fs_info,
5557                                                        search_start);
5558                 used_block_group = block_group;
5559                 /*
5560                  * we don't want to use the block group if it doesn't match our
5561                  * allocation bits, or if its not cached.
5562                  *
5563                  * However if we are re-searching with an ideal block group
5564                  * picked out then we don't care that the block group is cached.
5565                  */
5566                 if (block_group && block_group_bits(block_group, data) &&
5567                     block_group->cached != BTRFS_CACHE_NO) {
5568                         down_read(&space_info->groups_sem);
5569                         if (list_empty(&block_group->list) ||
5570                             block_group->ro) {
5571                                 /*
5572                                  * someone is removing this block group,
5573                                  * we can't jump into the have_block_group
5574                                  * target because our list pointers are not
5575                                  * valid
5576                                  */
5577                                 btrfs_put_block_group(block_group);
5578                                 up_read(&space_info->groups_sem);
5579                         } else {
5580                                 index = get_block_group_index(block_group);
5581                                 goto have_block_group;
5582                         }
5583                 } else if (block_group) {
5584                         btrfs_put_block_group(block_group);
5585                 }
5586         }
5587 search:
5588         have_caching_bg = false;
5589         down_read(&space_info->groups_sem);
5590         list_for_each_entry(block_group, &space_info->block_groups[index],
5591                             list) {
5592                 u64 offset;
5593                 int cached;
5594
5595                 used_block_group = block_group;
5596                 btrfs_get_block_group(block_group);
5597                 search_start = block_group->key.objectid;
5598
5599                 /*
5600                  * this can happen if we end up cycling through all the
5601                  * raid types, but we want to make sure we only allocate
5602                  * for the proper type.
5603                  */
5604                 if (!block_group_bits(block_group, data)) {
5605                     u64 extra = BTRFS_BLOCK_GROUP_DUP |
5606                                 BTRFS_BLOCK_GROUP_RAID1 |
5607                                 BTRFS_BLOCK_GROUP_RAID10;
5608
5609                         /*
5610                          * if they asked for extra copies and this block group
5611                          * doesn't provide them, bail.  This does allow us to
5612                          * fill raid0 from raid1.
5613                          */
5614                         if ((data & extra) && !(block_group->flags & extra))
5615                                 goto loop;
5616                 }
5617
5618 have_block_group:
5619                 cached = block_group_cache_done(block_group);
5620                 if (unlikely(!cached)) {
5621                         found_uncached_bg = true;
5622                         ret = cache_block_group(block_group, trans,
5623                                                 orig_root, 0);
5624                         BUG_ON(ret < 0);
5625                         ret = 0;
5626                 }
5627
5628                 if (unlikely(block_group->ro))
5629                         goto loop;
5630
5631                 /*
5632                  * Ok we want to try and use the cluster allocator, so
5633                  * lets look there
5634                  */
5635                 if (last_ptr) {
5636                         /*
5637                          * the refill lock keeps out other
5638                          * people trying to start a new cluster
5639                          */
5640                         spin_lock(&last_ptr->refill_lock);
5641                         used_block_group = last_ptr->block_group;
5642                         if (used_block_group != block_group &&
5643                             (!used_block_group ||
5644                              used_block_group->ro ||
5645                              !block_group_bits(used_block_group, data))) {
5646                                 used_block_group = block_group;
5647                                 goto refill_cluster;
5648                         }
5649
5650                         if (used_block_group != block_group)
5651                                 btrfs_get_block_group(used_block_group);
5652
5653                         offset = btrfs_alloc_from_cluster(used_block_group,
5654                           last_ptr, num_bytes, used_block_group->key.objectid);
5655                         if (offset) {
5656                                 /* we have a block, we're done */
5657                                 spin_unlock(&last_ptr->refill_lock);
5658                                 trace_btrfs_reserve_extent_cluster(root,
5659                                         block_group, search_start, num_bytes);
5660                                 goto checks;
5661                         }
5662
5663                         WARN_ON(last_ptr->block_group != used_block_group);
5664                         if (used_block_group != block_group) {
5665                                 btrfs_put_block_group(used_block_group);
5666                                 used_block_group = block_group;
5667                         }
5668 refill_cluster:
5669                         BUG_ON(used_block_group != block_group);
5670                         /* If we are on LOOP_NO_EMPTY_SIZE, we can't
5671                          * set up a new clusters, so lets just skip it
5672                          * and let the allocator find whatever block
5673                          * it can find.  If we reach this point, we
5674                          * will have tried the cluster allocator
5675                          * plenty of times and not have found
5676                          * anything, so we are likely way too
5677                          * fragmented for the clustering stuff to find
5678                          * anything.
5679                          *
5680                          * However, if the cluster is taken from the
5681                          * current block group, release the cluster
5682                          * first, so that we stand a better chance of
5683                          * succeeding in the unclustered
5684                          * allocation.  */
5685                         if (loop >= LOOP_NO_EMPTY_SIZE &&
5686                             last_ptr->block_group != block_group) {
5687                                 spin_unlock(&last_ptr->refill_lock);
5688                                 goto unclustered_alloc;
5689                         }
5690
5691                         /*
5692                          * this cluster didn't work out, free it and
5693                          * start over
5694                          */
5695                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
5696
5697                         if (loop >= LOOP_NO_EMPTY_SIZE) {
5698                                 spin_unlock(&last_ptr->refill_lock);
5699                                 goto unclustered_alloc;
5700                         }
5701
5702                         /* allocate a cluster in this block group */
5703                         ret = btrfs_find_space_cluster(trans, root,
5704                                                block_group, last_ptr,
5705                                                search_start, num_bytes,
5706                                                empty_cluster + empty_size);
5707                         if (ret == 0) {
5708                                 /*
5709                                  * now pull our allocation out of this
5710                                  * cluster
5711                                  */
5712                                 offset = btrfs_alloc_from_cluster(block_group,
5713                                                   last_ptr, num_bytes,
5714                                                   search_start);
5715                                 if (offset) {
5716                                         /* we found one, proceed */
5717                                         spin_unlock(&last_ptr->refill_lock);
5718                                         trace_btrfs_reserve_extent_cluster(root,
5719                                                 block_group, search_start,
5720                                                 num_bytes);
5721                                         goto checks;
5722                                 }
5723                         } else if (!cached && loop > LOOP_CACHING_NOWAIT
5724                                    && !failed_cluster_refill) {
5725                                 spin_unlock(&last_ptr->refill_lock);
5726
5727                                 failed_cluster_refill = true;
5728                                 wait_block_group_cache_progress(block_group,
5729                                        num_bytes + empty_cluster + empty_size);
5730                                 goto have_block_group;
5731                         }
5732
5733                         /*
5734                          * at this point we either didn't find a cluster
5735                          * or we weren't able to allocate a block from our
5736                          * cluster.  Free the cluster we've been trying
5737                          * to use, and go to the next block group
5738                          */
5739                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
5740                         spin_unlock(&last_ptr->refill_lock);
5741                         goto loop;
5742                 }
5743
5744 unclustered_alloc:
5745                 spin_lock(&block_group->free_space_ctl->tree_lock);
5746                 if (cached &&
5747                     block_group->free_space_ctl->free_space <
5748                     num_bytes + empty_cluster + empty_size) {
5749                         spin_unlock(&block_group->free_space_ctl->tree_lock);
5750                         goto loop;
5751                 }
5752                 spin_unlock(&block_group->free_space_ctl->tree_lock);
5753
5754                 offset = btrfs_find_space_for_alloc(block_group, search_start,
5755                                                     num_bytes, empty_size);
5756                 /*
5757                  * If we didn't find a chunk, and we haven't failed on this
5758                  * block group before, and this block group is in the middle of
5759                  * caching and we are ok with waiting, then go ahead and wait
5760                  * for progress to be made, and set failed_alloc to true.
5761                  *
5762                  * If failed_alloc is true then we've already waited on this
5763                  * block group once and should move on to the next block group.
5764                  */
5765                 if (!offset && !failed_alloc && !cached &&
5766                     loop > LOOP_CACHING_NOWAIT) {
5767                         wait_block_group_cache_progress(block_group,
5768                                                 num_bytes + empty_size);
5769                         failed_alloc = true;
5770                         goto have_block_group;
5771                 } else if (!offset) {
5772                         if (!cached)
5773                                 have_caching_bg = true;
5774                         goto loop;
5775                 }
5776 checks:
5777                 search_start = stripe_align(root, offset);
5778
5779                 /* move on to the next group */
5780                 if (search_start + num_bytes >
5781                     used_block_group->key.objectid + used_block_group->key.offset) {
5782                         btrfs_add_free_space(used_block_group, offset, num_bytes);
5783                         goto loop;
5784                 }
5785
5786                 if (offset < search_start)
5787                         btrfs_add_free_space(used_block_group, offset,
5788                                              search_start - offset);
5789                 BUG_ON(offset > search_start);
5790
5791                 ret = btrfs_update_reserved_bytes(used_block_group, num_bytes,
5792                                                   alloc_type);
5793                 if (ret == -EAGAIN) {
5794                         btrfs_add_free_space(used_block_group, offset, num_bytes);
5795                         goto loop;
5796                 }
5797
5798                 /* we are all good, lets return */
5799                 ins->objectid = search_start;
5800                 ins->offset = num_bytes;
5801
5802                 trace_btrfs_reserve_extent(orig_root, block_group,
5803                                            search_start, num_bytes);
5804                 if (used_block_group != block_group)
5805                         btrfs_put_block_group(used_block_group);
5806                 btrfs_put_block_group(block_group);
5807                 break;
5808 loop:
5809                 failed_cluster_refill = false;
5810                 failed_alloc = false;
5811                 BUG_ON(index != get_block_group_index(block_group));
5812                 if (used_block_group != block_group)
5813                         btrfs_put_block_group(used_block_group);
5814                 btrfs_put_block_group(block_group);
5815         }
5816         up_read(&space_info->groups_sem);
5817
5818         if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
5819                 goto search;
5820
5821         if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
5822                 goto search;
5823
5824         /*
5825          * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
5826          *                      caching kthreads as we move along
5827          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
5828          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
5829          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
5830          *                      again
5831          */
5832         if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
5833                 index = 0;
5834                 loop++;
5835                 if (loop == LOOP_ALLOC_CHUNK) {
5836                         ret = do_chunk_alloc(trans, root, data,
5837                                              CHUNK_ALLOC_FORCE);
5838                         /*
5839                          * Do not bail out on ENOSPC since we
5840                          * can do more things.
5841                          */
5842                         if (ret < 0 && ret != -ENOSPC) {
5843                                 btrfs_abort_transaction(trans,
5844                                                         root, ret);
5845                                 goto out;
5846                         }
5847                 }
5848
5849                 if (loop == LOOP_NO_EMPTY_SIZE) {
5850                         empty_size = 0;
5851                         empty_cluster = 0;
5852                 }
5853
5854                 goto search;
5855         } else if (!ins->objectid) {
5856                 ret = -ENOSPC;
5857         } else if (ins->objectid) {
5858                 ret = 0;
5859         }
5860 out:
5861
5862         return ret;
5863 }
5864
5865 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
5866                             int dump_block_groups)
5867 {
5868         struct btrfs_block_group_cache *cache;
5869         int index = 0;
5870
5871         spin_lock(&info->lock);
5872         printk(KERN_INFO "space_info %llu has %llu free, is %sfull\n",
5873                (unsigned long long)info->flags,
5874                (unsigned long long)(info->total_bytes - info->bytes_used -
5875                                     info->bytes_pinned - info->bytes_reserved -
5876                                     info->bytes_readonly),
5877                (info->full) ? "" : "not ");
5878         printk(KERN_INFO "space_info total=%llu, used=%llu, pinned=%llu, "
5879                "reserved=%llu, may_use=%llu, readonly=%llu\n",
5880                (unsigned long long)info->total_bytes,
5881                (unsigned long long)info->bytes_used,
5882                (unsigned long long)info->bytes_pinned,
5883                (unsigned long long)info->bytes_reserved,
5884                (unsigned long long)info->bytes_may_use,
5885                (unsigned long long)info->bytes_readonly);
5886         spin_unlock(&info->lock);
5887
5888         if (!dump_block_groups)
5889                 return;
5890
5891         down_read(&info->groups_sem);
5892 again:
5893         list_for_each_entry(cache, &info->block_groups[index], list) {
5894                 spin_lock(&cache->lock);
5895                 printk(KERN_INFO "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s\n",
5896                        (unsigned long long)cache->key.objectid,
5897                        (unsigned long long)cache->key.offset,
5898                        (unsigned long long)btrfs_block_group_used(&cache->item),
5899                        (unsigned long long)cache->pinned,
5900                        (unsigned long long)cache->reserved,
5901                        cache->ro ? "[readonly]" : "");
5902                 btrfs_dump_free_space(cache, bytes);
5903                 spin_unlock(&cache->lock);
5904         }
5905         if (++index < BTRFS_NR_RAID_TYPES)
5906                 goto again;
5907         up_read(&info->groups_sem);
5908 }
5909
5910 int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
5911                          struct btrfs_root *root,
5912                          u64 num_bytes, u64 min_alloc_size,
5913                          u64 empty_size, u64 hint_byte,
5914                          struct btrfs_key *ins, u64 data)
5915 {
5916         bool final_tried = false;
5917         int ret;
5918
5919         data = btrfs_get_alloc_profile(root, data);
5920 again:
5921         WARN_ON(num_bytes < root->sectorsize);
5922         ret = find_free_extent(trans, root, num_bytes, empty_size,
5923                                hint_byte, ins, data);
5924
5925         if (ret == -ENOSPC) {
5926                 if (!final_tried) {
5927                         num_bytes = num_bytes >> 1;
5928                         num_bytes = num_bytes & ~(root->sectorsize - 1);
5929                         num_bytes = max(num_bytes, min_alloc_size);
5930                         if (num_bytes == min_alloc_size)
5931                                 final_tried = true;
5932                         goto again;
5933                 } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
5934                         struct btrfs_space_info *sinfo;
5935
5936                         sinfo = __find_space_info(root->fs_info, data);
5937                         printk(KERN_ERR "btrfs allocation failed flags %llu, "
5938                                "wanted %llu\n", (unsigned long long)data,
5939                                (unsigned long long)num_bytes);
5940                         if (sinfo)
5941                                 dump_space_info(sinfo, num_bytes, 1);
5942                 }
5943         }
5944
5945         trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
5946
5947         return ret;
5948 }
5949
5950 static int __btrfs_free_reserved_extent(struct btrfs_root *root,
5951                                         u64 start, u64 len, int pin)
5952 {
5953         struct btrfs_block_group_cache *cache;
5954         int ret = 0;
5955
5956         cache = btrfs_lookup_block_group(root->fs_info, start);
5957         if (!cache) {
5958                 printk(KERN_ERR "Unable to find block group for %llu\n",
5959                        (unsigned long long)start);
5960                 return -ENOSPC;
5961         }
5962
5963         if (btrfs_test_opt(root, DISCARD))
5964                 ret = btrfs_discard_extent(root, start, len, NULL);
5965
5966         if (pin)
5967                 pin_down_extent(root, cache, start, len, 1);
5968         else {
5969                 btrfs_add_free_space(cache, start, len);
5970                 btrfs_update_reserved_bytes(cache, len, RESERVE_FREE);
5971         }
5972         btrfs_put_block_group(cache);
5973
5974         trace_btrfs_reserved_extent_free(root, start, len);
5975
5976         return ret;
5977 }
5978
5979 int btrfs_free_reserved_extent(struct btrfs_root *root,
5980                                         u64 start, u64 len)
5981 {
5982         return __btrfs_free_reserved_extent(root, start, len, 0);
5983 }
5984
5985 int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
5986                                        u64 start, u64 len)
5987 {
5988         return __btrfs_free_reserved_extent(root, start, len, 1);
5989 }
5990
5991 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
5992                                       struct btrfs_root *root,
5993                                       u64 parent, u64 root_objectid,
5994                                       u64 flags, u64 owner, u64 offset,
5995                                       struct btrfs_key *ins, int ref_mod)
5996 {
5997         int ret;
5998         struct btrfs_fs_info *fs_info = root->fs_info;
5999         struct btrfs_extent_item *extent_item;
6000         struct btrfs_extent_inline_ref *iref;
6001         struct btrfs_path *path;
6002         struct extent_buffer *leaf;
6003         int type;
6004         u32 size;
6005
6006         if (parent > 0)
6007                 type = BTRFS_SHARED_DATA_REF_KEY;
6008         else
6009                 type = BTRFS_EXTENT_DATA_REF_KEY;
6010
6011         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
6012
6013         path = btrfs_alloc_path();
6014         if (!path)
6015                 return -ENOMEM;
6016
6017         path->leave_spinning = 1;
6018         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6019                                       ins, size);
6020         if (ret) {
6021                 btrfs_free_path(path);
6022                 return ret;
6023         }
6024
6025         leaf = path->nodes[0];
6026         extent_item = btrfs_item_ptr(leaf, path->slots[0],
6027                                      struct btrfs_extent_item);
6028         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
6029         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6030         btrfs_set_extent_flags(leaf, extent_item,
6031                                flags | BTRFS_EXTENT_FLAG_DATA);
6032
6033         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6034         btrfs_set_extent_inline_ref_type(leaf, iref, type);
6035         if (parent > 0) {
6036                 struct btrfs_shared_data_ref *ref;
6037                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
6038                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6039                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
6040         } else {
6041                 struct btrfs_extent_data_ref *ref;
6042                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
6043                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
6044                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
6045                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
6046                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
6047         }
6048
6049         btrfs_mark_buffer_dirty(path->nodes[0]);
6050         btrfs_free_path(path);
6051
6052         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
6053         if (ret) { /* -ENOENT, logic error */
6054                 printk(KERN_ERR "btrfs update block group failed for %llu "
6055                        "%llu\n", (unsigned long long)ins->objectid,
6056                        (unsigned long long)ins->offset);
6057                 BUG();
6058         }
6059         return ret;
6060 }
6061
6062 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
6063                                      struct btrfs_root *root,
6064                                      u64 parent, u64 root_objectid,
6065                                      u64 flags, struct btrfs_disk_key *key,
6066                                      int level, struct btrfs_key *ins)
6067 {
6068         int ret;
6069         struct btrfs_fs_info *fs_info = root->fs_info;
6070         struct btrfs_extent_item *extent_item;
6071         struct btrfs_tree_block_info *block_info;
6072         struct btrfs_extent_inline_ref *iref;
6073         struct btrfs_path *path;
6074         struct extent_buffer *leaf;
6075         u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
6076
6077         path = btrfs_alloc_path();
6078         if (!path)
6079                 return -ENOMEM;
6080
6081         path->leave_spinning = 1;
6082         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6083                                       ins, size);
6084         if (ret) {
6085                 btrfs_free_path(path);
6086                 return ret;
6087         }
6088
6089         leaf = path->nodes[0];
6090         extent_item = btrfs_item_ptr(leaf, path->slots[0],
6091                                      struct btrfs_extent_item);
6092         btrfs_set_extent_refs(leaf, extent_item, 1);
6093         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6094         btrfs_set_extent_flags(leaf, extent_item,
6095                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
6096         block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
6097
6098         btrfs_set_tree_block_key(leaf, block_info, key);
6099         btrfs_set_tree_block_level(leaf, block_info, level);
6100
6101         iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
6102         if (parent > 0) {
6103                 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
6104                 btrfs_set_extent_inline_ref_type(leaf, iref,
6105                                                  BTRFS_SHARED_BLOCK_REF_KEY);
6106                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6107         } else {
6108                 btrfs_set_extent_inline_ref_type(leaf, iref,
6109                                                  BTRFS_TREE_BLOCK_REF_KEY);
6110                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
6111         }
6112
6113         btrfs_mark_buffer_dirty(leaf);
6114         btrfs_free_path(path);
6115
6116         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
6117         if (ret) { /* -ENOENT, logic error */
6118                 printk(KERN_ERR "btrfs update block group failed for %llu "
6119                        "%llu\n", (unsigned long long)ins->objectid,
6120                        (unsigned long long)ins->offset);
6121                 BUG();
6122         }
6123         return ret;
6124 }
6125
6126 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6127                                      struct btrfs_root *root,
6128                                      u64 root_objectid, u64 owner,
6129                                      u64 offset, struct btrfs_key *ins)
6130 {
6131         int ret;
6132
6133         BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
6134
6135         ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
6136                                          ins->offset, 0,
6137                                          root_objectid, owner, offset,
6138                                          BTRFS_ADD_DELAYED_EXTENT, NULL, 0);
6139         return ret;
6140 }
6141
6142 /*
6143  * this is used by the tree logging recovery code.  It records that
6144  * an extent has been allocated and makes sure to clear the free
6145  * space cache bits as well
6146  */
6147 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
6148                                    struct btrfs_root *root,
6149                                    u64 root_objectid, u64 owner, u64 offset,
6150                                    struct btrfs_key *ins)
6151 {
6152         int ret;
6153         struct btrfs_block_group_cache *block_group;
6154         struct btrfs_caching_control *caching_ctl;
6155         u64 start = ins->objectid;
6156         u64 num_bytes = ins->offset;
6157
6158         block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
6159         cache_block_group(block_group, trans, NULL, 0);
6160         caching_ctl = get_caching_control(block_group);
6161
6162         if (!caching_ctl) {
6163                 BUG_ON(!block_group_cache_done(block_group));
6164                 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6165                 BUG_ON(ret); /* -ENOMEM */
6166         } else {
6167                 mutex_lock(&caching_ctl->mutex);
6168
6169                 if (start >= caching_ctl->progress) {
6170                         ret = add_excluded_extent(root, start, num_bytes);
6171                         BUG_ON(ret); /* -ENOMEM */
6172                 } else if (start + num_bytes <= caching_ctl->progress) {
6173                         ret = btrfs_remove_free_space(block_group,
6174                                                       start, num_bytes);
6175                         BUG_ON(ret); /* -ENOMEM */
6176                 } else {
6177                         num_bytes = caching_ctl->progress - start;
6178                         ret = btrfs_remove_free_space(block_group,
6179                                                       start, num_bytes);
6180                         BUG_ON(ret); /* -ENOMEM */
6181
6182                         start = caching_ctl->progress;
6183                         num_bytes = ins->objectid + ins->offset -
6184                                     caching_ctl->progress;
6185                         ret = add_excluded_extent(root, start, num_bytes);
6186                         BUG_ON(ret); /* -ENOMEM */
6187                 }
6188
6189                 mutex_unlock(&caching_ctl->mutex);
6190                 put_caching_control(caching_ctl);
6191         }
6192
6193         ret = btrfs_update_reserved_bytes(block_group, ins->offset,
6194                                           RESERVE_ALLOC_NO_ACCOUNT);
6195         BUG_ON(ret); /* logic error */
6196         btrfs_put_block_group(block_group);
6197         ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
6198                                          0, owner, offset, ins, 1);
6199         return ret;
6200 }
6201
6202 struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
6203                                             struct btrfs_root *root,
6204                                             u64 bytenr, u32 blocksize,
6205                                             int level)
6206 {
6207         struct extent_buffer *buf;
6208
6209         buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
6210         if (!buf)
6211                 return ERR_PTR(-ENOMEM);
6212         btrfs_set_header_generation(buf, trans->transid);
6213         btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
6214         btrfs_tree_lock(buf);
6215         clean_tree_block(trans, root, buf);
6216         clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
6217
6218         btrfs_set_lock_blocking(buf);
6219         btrfs_set_buffer_uptodate(buf);
6220
6221         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
6222                 /*
6223                  * we allow two log transactions at a time, use different
6224                  * EXENT bit to differentiate dirty pages.
6225                  */
6226                 if (root->log_transid % 2 == 0)
6227                         set_extent_dirty(&root->dirty_log_pages, buf->start,
6228                                         buf->start + buf->len - 1, GFP_NOFS);
6229                 else
6230                         set_extent_new(&root->dirty_log_pages, buf->start,
6231                                         buf->start + buf->len - 1, GFP_NOFS);
6232         } else {
6233                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
6234                          buf->start + buf->len - 1, GFP_NOFS);
6235         }
6236         trans->blocks_used++;
6237         /* this returns a buffer locked for blocking */
6238         return buf;
6239 }
6240
6241 static struct btrfs_block_rsv *
6242 use_block_rsv(struct btrfs_trans_handle *trans,
6243               struct btrfs_root *root, u32 blocksize)
6244 {
6245         struct btrfs_block_rsv *block_rsv;
6246         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
6247         int ret;
6248
6249         block_rsv = get_block_rsv(trans, root);
6250
6251         if (block_rsv->size == 0) {
6252                 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
6253                                              BTRFS_RESERVE_NO_FLUSH);
6254                 /*
6255                  * If we couldn't reserve metadata bytes try and use some from
6256                  * the global reserve.
6257                  */
6258                 if (ret && block_rsv != global_rsv) {
6259                         ret = block_rsv_use_bytes(global_rsv, blocksize);
6260                         if (!ret)
6261                                 return global_rsv;
6262                         return ERR_PTR(ret);
6263                 } else if (ret) {
6264                         return ERR_PTR(ret);
6265                 }
6266                 return block_rsv;
6267         }
6268
6269         ret = block_rsv_use_bytes(block_rsv, blocksize);
6270         if (!ret)
6271                 return block_rsv;
6272         if (ret && !block_rsv->failfast) {
6273                 static DEFINE_RATELIMIT_STATE(_rs,
6274                                 DEFAULT_RATELIMIT_INTERVAL,
6275                                 /*DEFAULT_RATELIMIT_BURST*/ 2);
6276                 if (__ratelimit(&_rs)) {
6277                         printk(KERN_DEBUG "btrfs: block rsv returned %d\n", ret);
6278                         WARN_ON(1);
6279                 }
6280                 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
6281                                              BTRFS_RESERVE_NO_FLUSH);
6282                 if (!ret) {
6283                         return block_rsv;
6284                 } else if (ret && block_rsv != global_rsv) {
6285                         ret = block_rsv_use_bytes(global_rsv, blocksize);
6286                         if (!ret)
6287                                 return global_rsv;
6288                 }
6289         }
6290
6291         return ERR_PTR(-ENOSPC);
6292 }
6293
6294 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
6295                             struct btrfs_block_rsv *block_rsv, u32 blocksize)
6296 {
6297         block_rsv_add_bytes(block_rsv, blocksize, 0);
6298         block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
6299 }
6300
6301 /*
6302  * finds a free extent and does all the dirty work required for allocation
6303  * returns the key for the extent through ins, and a tree buffer for
6304  * the first block of the extent through buf.
6305  *
6306  * returns the tree buffer or NULL.
6307  */
6308 struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
6309                                         struct btrfs_root *root, u32 blocksize,
6310                                         u64 parent, u64 root_objectid,
6311                                         struct btrfs_disk_key *key, int level,
6312                                         u64 hint, u64 empty_size)
6313 {
6314         struct btrfs_key ins;
6315         struct btrfs_block_rsv *block_rsv;
6316         struct extent_buffer *buf;
6317         u64 flags = 0;
6318         int ret;
6319
6320
6321         block_rsv = use_block_rsv(trans, root, blocksize);
6322         if (IS_ERR(block_rsv))
6323                 return ERR_CAST(block_rsv);
6324
6325         ret = btrfs_reserve_extent(trans, root, blocksize, blocksize,
6326                                    empty_size, hint, &ins, 0);
6327         if (ret) {
6328                 unuse_block_rsv(root->fs_info, block_rsv, blocksize);
6329                 return ERR_PTR(ret);
6330         }
6331
6332         buf = btrfs_init_new_buffer(trans, root, ins.objectid,
6333                                     blocksize, level);
6334         BUG_ON(IS_ERR(buf)); /* -ENOMEM */
6335
6336         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
6337                 if (parent == 0)
6338                         parent = ins.objectid;
6339                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
6340         } else
6341                 BUG_ON(parent > 0);
6342
6343         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
6344                 struct btrfs_delayed_extent_op *extent_op;
6345                 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
6346                 BUG_ON(!extent_op); /* -ENOMEM */
6347                 if (key)
6348                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
6349                 else
6350                         memset(&extent_op->key, 0, sizeof(extent_op->key));
6351                 extent_op->flags_to_set = flags;
6352                 extent_op->update_key = 1;
6353                 extent_op->update_flags = 1;
6354                 extent_op->is_data = 0;
6355
6356                 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
6357                                         ins.objectid,
6358                                         ins.offset, parent, root_objectid,
6359                                         level, BTRFS_ADD_DELAYED_EXTENT,
6360                                         extent_op, 0);
6361                 BUG_ON(ret); /* -ENOMEM */
6362         }
6363         return buf;
6364 }
6365
6366 struct walk_control {
6367         u64 refs[BTRFS_MAX_LEVEL];
6368         u64 flags[BTRFS_MAX_LEVEL];
6369         struct btrfs_key update_progress;
6370         int stage;
6371         int level;
6372         int shared_level;
6373         int update_ref;
6374         int keep_locks;
6375         int reada_slot;
6376         int reada_count;
6377         int for_reloc;
6378 };
6379
6380 #define DROP_REFERENCE  1
6381 #define UPDATE_BACKREF  2
6382
6383 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
6384                                      struct btrfs_root *root,
6385                                      struct walk_control *wc,
6386                                      struct btrfs_path *path)
6387 {
6388         u64 bytenr;
6389         u64 generation;
6390         u64 refs;
6391         u64 flags;
6392         u32 nritems;
6393         u32 blocksize;
6394         struct btrfs_key key;
6395         struct extent_buffer *eb;
6396         int ret;
6397         int slot;
6398         int nread = 0;
6399
6400         if (path->slots[wc->level] < wc->reada_slot) {
6401                 wc->reada_count = wc->reada_count * 2 / 3;
6402                 wc->reada_count = max(wc->reada_count, 2);
6403         } else {
6404                 wc->reada_count = wc->reada_count * 3 / 2;
6405                 wc->reada_count = min_t(int, wc->reada_count,
6406                                         BTRFS_NODEPTRS_PER_BLOCK(root));
6407         }
6408
6409         eb = path->nodes[wc->level];
6410         nritems = btrfs_header_nritems(eb);
6411         blocksize = btrfs_level_size(root, wc->level - 1);
6412
6413         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
6414                 if (nread >= wc->reada_count)
6415                         break;
6416
6417                 cond_resched();
6418                 bytenr = btrfs_node_blockptr(eb, slot);
6419                 generation = btrfs_node_ptr_generation(eb, slot);
6420
6421                 if (slot == path->slots[wc->level])
6422                         goto reada;
6423
6424                 if (wc->stage == UPDATE_BACKREF &&
6425                     generation <= root->root_key.offset)
6426                         continue;
6427
6428                 /* We don't lock the tree block, it's OK to be racy here */
6429                 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
6430                                                &refs, &flags);
6431                 /* We don't care about errors in readahead. */
6432                 if (ret < 0)
6433                         continue;
6434                 BUG_ON(refs == 0);
6435
6436                 if (wc->stage == DROP_REFERENCE) {
6437                         if (refs == 1)
6438                                 goto reada;
6439
6440                         if (wc->level == 1 &&
6441                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6442                                 continue;
6443                         if (!wc->update_ref ||
6444                             generation <= root->root_key.offset)
6445                                 continue;
6446                         btrfs_node_key_to_cpu(eb, &key, slot);
6447                         ret = btrfs_comp_cpu_keys(&key,
6448                                                   &wc->update_progress);
6449                         if (ret < 0)
6450                                 continue;
6451                 } else {
6452                         if (wc->level == 1 &&
6453                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6454                                 continue;
6455                 }
6456 reada:
6457                 ret = readahead_tree_block(root, bytenr, blocksize,
6458                                            generation);
6459                 if (ret)
6460                         break;
6461                 nread++;
6462         }
6463         wc->reada_slot = slot;
6464 }
6465
6466 /*
6467  * hepler to process tree block while walking down the tree.
6468  *
6469  * when wc->stage == UPDATE_BACKREF, this function updates
6470  * back refs for pointers in the block.
6471  *
6472  * NOTE: return value 1 means we should stop walking down.
6473  */
6474 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
6475                                    struct btrfs_root *root,
6476                                    struct btrfs_path *path,
6477                                    struct walk_control *wc, int lookup_info)
6478 {
6479         int level = wc->level;
6480         struct extent_buffer *eb = path->nodes[level];
6481         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
6482         int ret;
6483
6484         if (wc->stage == UPDATE_BACKREF &&
6485             btrfs_header_owner(eb) != root->root_key.objectid)
6486                 return 1;
6487
6488         /*
6489          * when reference count of tree block is 1, it won't increase
6490          * again. once full backref flag is set, we never clear it.
6491          */
6492         if (lookup_info &&
6493             ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
6494              (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
6495                 BUG_ON(!path->locks[level]);
6496                 ret = btrfs_lookup_extent_info(trans, root,
6497                                                eb->start, eb->len,
6498                                                &wc->refs[level],
6499                                                &wc->flags[level]);
6500                 BUG_ON(ret == -ENOMEM);
6501                 if (ret)
6502                         return ret;
6503                 BUG_ON(wc->refs[level] == 0);
6504         }
6505
6506         if (wc->stage == DROP_REFERENCE) {
6507                 if (wc->refs[level] > 1)
6508                         return 1;
6509
6510                 if (path->locks[level] && !wc->keep_locks) {
6511                         btrfs_tree_unlock_rw(eb, path->locks[level]);
6512                         path->locks[level] = 0;
6513                 }
6514                 return 0;
6515         }
6516
6517         /* wc->stage == UPDATE_BACKREF */
6518         if (!(wc->flags[level] & flag)) {
6519                 BUG_ON(!path->locks[level]);
6520                 ret = btrfs_inc_ref(trans, root, eb, 1, wc->for_reloc);
6521                 BUG_ON(ret); /* -ENOMEM */
6522                 ret = btrfs_dec_ref(trans, root, eb, 0, wc->for_reloc);
6523                 BUG_ON(ret); /* -ENOMEM */
6524                 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
6525                                                   eb->len, flag, 0);
6526                 BUG_ON(ret); /* -ENOMEM */
6527                 wc->flags[level] |= flag;
6528         }
6529
6530         /*
6531          * the block is shared by multiple trees, so it's not good to
6532          * keep the tree lock
6533          */
6534         if (path->locks[level] && level > 0) {
6535                 btrfs_tree_unlock_rw(eb, path->locks[level]);
6536                 path->locks[level] = 0;
6537         }
6538         return 0;
6539 }
6540
6541 /*
6542  * hepler to process tree block pointer.
6543  *
6544  * when wc->stage == DROP_REFERENCE, this function checks
6545  * reference count of the block pointed to. if the block
6546  * is shared and we need update back refs for the subtree
6547  * rooted at the block, this function changes wc->stage to
6548  * UPDATE_BACKREF. if the block is shared and there is no
6549  * need to update back, this function drops the reference
6550  * to the block.
6551  *
6552  * NOTE: return value 1 means we should stop walking down.
6553  */
6554 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
6555                                  struct btrfs_root *root,
6556                                  struct btrfs_path *path,
6557                                  struct walk_control *wc, int *lookup_info)
6558 {
6559         u64 bytenr;
6560         u64 generation;
6561         u64 parent;
6562         u32 blocksize;
6563         struct btrfs_key key;
6564         struct extent_buffer *next;
6565         int level = wc->level;
6566         int reada = 0;
6567         int ret = 0;
6568
6569         generation = btrfs_node_ptr_generation(path->nodes[level],
6570                                                path->slots[level]);
6571         /*
6572          * if the lower level block was created before the snapshot
6573          * was created, we know there is no need to update back refs
6574          * for the subtree
6575          */
6576         if (wc->stage == UPDATE_BACKREF &&
6577             generation <= root->root_key.offset) {
6578                 *lookup_info = 1;
6579                 return 1;
6580         }
6581
6582         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
6583         blocksize = btrfs_level_size(root, level - 1);
6584
6585         next = btrfs_find_tree_block(root, bytenr, blocksize);
6586         if (!next) {
6587                 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
6588                 if (!next)
6589                         return -ENOMEM;
6590                 reada = 1;
6591         }
6592         btrfs_tree_lock(next);
6593         btrfs_set_lock_blocking(next);
6594
6595         ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
6596                                        &wc->refs[level - 1],
6597                                        &wc->flags[level - 1]);
6598         if (ret < 0) {
6599                 btrfs_tree_unlock(next);
6600                 return ret;
6601         }
6602
6603         BUG_ON(wc->refs[level - 1] == 0);
6604         *lookup_info = 0;
6605
6606         if (wc->stage == DROP_REFERENCE) {
6607                 if (wc->refs[level - 1] > 1) {
6608                         if (level == 1 &&
6609                             (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6610                                 goto skip;
6611
6612                         if (!wc->update_ref ||
6613                             generation <= root->root_key.offset)
6614                                 goto skip;
6615
6616                         btrfs_node_key_to_cpu(path->nodes[level], &key,
6617                                               path->slots[level]);
6618                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
6619                         if (ret < 0)
6620                                 goto skip;
6621
6622                         wc->stage = UPDATE_BACKREF;
6623                         wc->shared_level = level - 1;
6624                 }
6625         } else {
6626                 if (level == 1 &&
6627                     (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
6628                         goto skip;
6629         }
6630
6631         if (!btrfs_buffer_uptodate(next, generation, 0)) {
6632                 btrfs_tree_unlock(next);
6633                 free_extent_buffer(next);
6634                 next = NULL;
6635                 *lookup_info = 1;
6636         }
6637
6638         if (!next) {
6639                 if (reada && level == 1)
6640                         reada_walk_down(trans, root, wc, path);
6641                 next = read_tree_block(root, bytenr, blocksize, generation);
6642                 if (!next)
6643                         return -EIO;
6644                 btrfs_tree_lock(next);
6645                 btrfs_set_lock_blocking(next);
6646         }
6647
6648         level--;
6649         BUG_ON(level != btrfs_header_level(next));
6650         path->nodes[level] = next;
6651         path->slots[level] = 0;
6652         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6653         wc->level = level;
6654         if (wc->level == 1)
6655                 wc->reada_slot = 0;
6656         return 0;
6657 skip:
6658         wc->refs[level - 1] = 0;
6659         wc->flags[level - 1] = 0;
6660         if (wc->stage == DROP_REFERENCE) {
6661                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
6662                         parent = path->nodes[level]->start;
6663                 } else {
6664                         BUG_ON(root->root_key.objectid !=
6665                                btrfs_header_owner(path->nodes[level]));
6666                         parent = 0;
6667                 }
6668
6669                 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
6670                                 root->root_key.objectid, level - 1, 0, 0);
6671                 BUG_ON(ret); /* -ENOMEM */
6672         }
6673         btrfs_tree_unlock(next);
6674         free_extent_buffer(next);
6675         *lookup_info = 1;
6676         return 1;
6677 }
6678
6679 /*
6680  * hepler to process tree block while walking up the tree.
6681  *
6682  * when wc->stage == DROP_REFERENCE, this function drops
6683  * reference count on the block.
6684  *
6685  * when wc->stage == UPDATE_BACKREF, this function changes
6686  * wc->stage back to DROP_REFERENCE if we changed wc->stage
6687  * to UPDATE_BACKREF previously while processing the block.
6688  *
6689  * NOTE: return value 1 means we should stop walking up.
6690  */
6691 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
6692                                  struct btrfs_root *root,
6693                                  struct btrfs_path *path,
6694                                  struct walk_control *wc)
6695 {
6696         int ret;
6697         int level = wc->level;
6698         struct extent_buffer *eb = path->nodes[level];
6699         u64 parent = 0;
6700
6701         if (wc->stage == UPDATE_BACKREF) {
6702                 BUG_ON(wc->shared_level < level);
6703                 if (level < wc->shared_level)
6704                         goto out;
6705
6706                 ret = find_next_key(path, level + 1, &wc->update_progress);
6707                 if (ret > 0)
6708                         wc->update_ref = 0;
6709
6710                 wc->stage = DROP_REFERENCE;
6711                 wc->shared_level = -1;
6712                 path->slots[level] = 0;
6713
6714                 /*
6715                  * check reference count again if the block isn't locked.
6716                  * we should start walking down the tree again if reference
6717                  * count is one.
6718                  */
6719                 if (!path->locks[level]) {
6720                         BUG_ON(level == 0);
6721                         btrfs_tree_lock(eb);
6722                         btrfs_set_lock_blocking(eb);
6723                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6724
6725                         ret = btrfs_lookup_extent_info(trans, root,
6726                                                        eb->start, eb->len,
6727                                                        &wc->refs[level],
6728                                                        &wc->flags[level]);
6729                         if (ret < 0) {
6730                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
6731                                 return ret;
6732                         }
6733                         BUG_ON(wc->refs[level] == 0);
6734                         if (wc->refs[level] == 1) {
6735                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
6736                                 return 1;
6737                         }
6738                 }
6739         }
6740
6741         /* wc->stage == DROP_REFERENCE */
6742         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
6743
6744         if (wc->refs[level] == 1) {
6745                 if (level == 0) {
6746                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6747                                 ret = btrfs_dec_ref(trans, root, eb, 1,
6748                                                     wc->for_reloc);
6749                         else
6750                                 ret = btrfs_dec_ref(trans, root, eb, 0,
6751                                                     wc->for_reloc);
6752                         BUG_ON(ret); /* -ENOMEM */
6753                 }
6754                 /* make block locked assertion in clean_tree_block happy */
6755                 if (!path->locks[level] &&
6756                     btrfs_header_generation(eb) == trans->transid) {
6757                         btrfs_tree_lock(eb);
6758                         btrfs_set_lock_blocking(eb);
6759                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6760                 }
6761                 clean_tree_block(trans, root, eb);
6762         }
6763
6764         if (eb == root->node) {
6765                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6766                         parent = eb->start;
6767                 else
6768                         BUG_ON(root->root_key.objectid !=
6769                                btrfs_header_owner(eb));
6770         } else {
6771                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
6772                         parent = path->nodes[level + 1]->start;
6773                 else
6774                         BUG_ON(root->root_key.objectid !=
6775                                btrfs_header_owner(path->nodes[level + 1]));
6776         }
6777
6778         btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
6779 out:
6780         wc->refs[level] = 0;
6781         wc->flags[level] = 0;
6782         return 0;
6783 }
6784
6785 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
6786                                    struct btrfs_root *root,
6787                                    struct btrfs_path *path,
6788                                    struct walk_control *wc)
6789 {
6790         int level = wc->level;
6791         int lookup_info = 1;
6792         int ret;
6793
6794         while (level >= 0) {
6795                 ret = walk_down_proc(trans, root, path, wc, lookup_info);
6796                 if (ret > 0)
6797                         break;
6798
6799                 if (level == 0)
6800                         break;
6801
6802                 if (path->slots[level] >=
6803                     btrfs_header_nritems(path->nodes[level]))
6804                         break;
6805
6806                 ret = do_walk_down(trans, root, path, wc, &lookup_info);
6807                 if (ret > 0) {
6808                         path->slots[level]++;
6809                         continue;
6810                 } else if (ret < 0)
6811                         return ret;
6812                 level = wc->level;
6813         }
6814         return 0;
6815 }
6816
6817 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
6818                                  struct btrfs_root *root,
6819                                  struct btrfs_path *path,
6820                                  struct walk_control *wc, int max_level)
6821 {
6822         int level = wc->level;
6823         int ret;
6824
6825         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
6826         while (level < max_level && path->nodes[level]) {
6827                 wc->level = level;
6828                 if (path->slots[level] + 1 <
6829                     btrfs_header_nritems(path->nodes[level])) {
6830                         path->slots[level]++;
6831                         return 0;
6832                 } else {
6833                         ret = walk_up_proc(trans, root, path, wc);
6834                         if (ret > 0)
6835                                 return 0;
6836
6837                         if (path->locks[level]) {
6838                                 btrfs_tree_unlock_rw(path->nodes[level],
6839                                                      path->locks[level]);
6840                                 path->locks[level] = 0;
6841                         }
6842                         free_extent_buffer(path->nodes[level]);
6843                         path->nodes[level] = NULL;
6844                         level++;
6845                 }
6846         }
6847         return 1;
6848 }
6849
6850 /*
6851  * drop a subvolume tree.
6852  *
6853  * this function traverses the tree freeing any blocks that only
6854  * referenced by the tree.
6855  *
6856  * when a shared tree block is found. this function decreases its
6857  * reference count by one. if update_ref is true, this function
6858  * also make sure backrefs for the shared block and all lower level
6859  * blocks are properly updated.
6860  */
6861 int btrfs_drop_snapshot(struct btrfs_root *root,
6862                          struct btrfs_block_rsv *block_rsv, int update_ref,
6863                          int for_reloc)
6864 {
6865         struct btrfs_path *path;
6866         struct btrfs_trans_handle *trans;
6867         struct btrfs_root *tree_root = root->fs_info->tree_root;
6868         struct btrfs_root_item *root_item = &root->root_item;
6869         struct walk_control *wc;
6870         struct btrfs_key key;
6871         int err = 0;
6872         int ret;
6873         int level;
6874
6875         path = btrfs_alloc_path();
6876         if (!path) {
6877                 err = -ENOMEM;
6878                 goto out;
6879         }
6880
6881         wc = kzalloc(sizeof(*wc), GFP_NOFS);
6882         if (!wc) {
6883                 btrfs_free_path(path);
6884                 err = -ENOMEM;
6885                 goto out;
6886         }
6887
6888         trans = btrfs_start_transaction(tree_root, 0);
6889         if (IS_ERR(trans)) {
6890                 err = PTR_ERR(trans);
6891                 goto out_free;
6892         }
6893
6894         if (block_rsv)
6895                 trans->block_rsv = block_rsv;
6896
6897         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
6898                 level = btrfs_header_level(root->node);
6899                 path->nodes[level] = btrfs_lock_root_node(root);
6900                 btrfs_set_lock_blocking(path->nodes[level]);
6901                 path->slots[level] = 0;
6902                 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
6903                 memset(&wc->update_progress, 0,
6904                        sizeof(wc->update_progress));
6905         } else {
6906                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
6907                 memcpy(&wc->update_progress, &key,
6908                        sizeof(wc->update_progress));
6909
6910                 level = root_item->drop_level;
6911                 BUG_ON(level == 0);
6912                 path->lowest_level = level;
6913                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6914                 path->lowest_level = 0;
6915                 if (ret < 0) {
6916                         err = ret;
6917                         goto out_end_trans;
6918                 }
6919                 WARN_ON(ret > 0);
6920
6921                 /*
6922                  * unlock our path, this is safe because only this
6923                  * function is allowed to delete this snapshot
6924                  */
6925                 btrfs_unlock_up_safe(path, 0);
6926
6927                 level = btrfs_header_level(root->node);
6928                 while (1) {
6929                         btrfs_tree_lock(path->nodes[level]);
6930                         btrfs_set_lock_blocking(path->nodes[level]);
6931
6932                         ret = btrfs_lookup_extent_info(trans, root,
6933                                                 path->nodes[level]->start,
6934                                                 path->nodes[level]->len,
6935                                                 &wc->refs[level],
6936                                                 &wc->flags[level]);
6937                         if (ret < 0) {
6938                                 err = ret;
6939                                 goto out_end_trans;
6940                         }
6941                         BUG_ON(wc->refs[level] == 0);
6942
6943                         if (level == root_item->drop_level)
6944                                 break;
6945
6946                         btrfs_tree_unlock(path->nodes[level]);
6947                         WARN_ON(wc->refs[level] != 1);
6948                         level--;
6949                 }
6950         }
6951
6952         wc->level = level;
6953         wc->shared_level = -1;
6954         wc->stage = DROP_REFERENCE;
6955         wc->update_ref = update_ref;
6956         wc->keep_locks = 0;
6957         wc->for_reloc = for_reloc;
6958         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
6959
6960         while (1) {
6961                 ret = walk_down_tree(trans, root, path, wc);
6962                 if (ret < 0) {
6963                         err = ret;
6964                         break;
6965                 }
6966
6967                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
6968                 if (ret < 0) {
6969                         err = ret;
6970                         break;
6971                 }
6972
6973                 if (ret > 0) {
6974                         BUG_ON(wc->stage != DROP_REFERENCE);
6975                         break;
6976                 }
6977
6978                 if (wc->stage == DROP_REFERENCE) {
6979                         level = wc->level;
6980                         btrfs_node_key(path->nodes[level],
6981                                        &root_item->drop_progress,
6982                                        path->slots[level]);
6983                         root_item->drop_level = level;
6984                 }
6985
6986                 BUG_ON(wc->level == 0);
6987                 if (btrfs_should_end_transaction(trans, tree_root)) {
6988                         ret = btrfs_update_root(trans, tree_root,
6989                                                 &root->root_key,
6990                                                 root_item);
6991                         if (ret) {
6992                                 btrfs_abort_transaction(trans, tree_root, ret);
6993                                 err = ret;
6994                                 goto out_end_trans;
6995                         }
6996
6997                         btrfs_end_transaction_throttle(trans, tree_root);
6998                         trans = btrfs_start_transaction(tree_root, 0);
6999                         if (IS_ERR(trans)) {
7000                                 err = PTR_ERR(trans);
7001                                 goto out_free;
7002                         }
7003                         if (block_rsv)
7004                                 trans->block_rsv = block_rsv;
7005                 }
7006         }
7007         btrfs_release_path(path);
7008         if (err)
7009                 goto out_end_trans;
7010
7011         ret = btrfs_del_root(trans, tree_root, &root->root_key);
7012         if (ret) {
7013                 btrfs_abort_transaction(trans, tree_root, ret);
7014                 goto out_end_trans;
7015         }
7016
7017         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
7018                 ret = btrfs_find_last_root(tree_root, root->root_key.objectid,
7019                                            NULL, NULL);
7020                 if (ret < 0) {
7021                         btrfs_abort_transaction(trans, tree_root, ret);
7022                         err = ret;
7023                         goto out_end_trans;
7024                 } else if (ret > 0) {
7025                         /* if we fail to delete the orphan item this time
7026                          * around, it'll get picked up the next time.
7027                          *
7028                          * The most common failure here is just -ENOENT.
7029                          */
7030                         btrfs_del_orphan_item(trans, tree_root,
7031                                               root->root_key.objectid);
7032                 }
7033         }
7034
7035         if (root->in_radix) {
7036                 btrfs_free_fs_root(tree_root->fs_info, root);
7037         } else {
7038                 free_extent_buffer(root->node);
7039                 free_extent_buffer(root->commit_root);
7040                 kfree(root);
7041         }
7042 out_end_trans:
7043         btrfs_end_transaction_throttle(trans, tree_root);
7044 out_free:
7045         kfree(wc);
7046         btrfs_free_path(path);
7047 out:
7048         if (err)
7049                 btrfs_std_error(root->fs_info, err);
7050         return err;
7051 }
7052
7053 /*
7054  * drop subtree rooted at tree block 'node'.
7055  *
7056  * NOTE: this function will unlock and release tree block 'node'
7057  * only used by relocation code
7058  */
7059 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
7060                         struct btrfs_root *root,
7061                         struct extent_buffer *node,
7062                         struct extent_buffer *parent)
7063 {
7064         struct btrfs_path *path;
7065         struct walk_control *wc;
7066         int level;
7067         int parent_level;
7068         int ret = 0;
7069         int wret;
7070
7071         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7072
7073         path = btrfs_alloc_path();
7074         if (!path)
7075                 return -ENOMEM;
7076
7077         wc = kzalloc(sizeof(*wc), GFP_NOFS);
7078         if (!wc) {
7079                 btrfs_free_path(path);
7080                 return -ENOMEM;
7081         }
7082
7083         btrfs_assert_tree_locked(parent);
7084         parent_level = btrfs_header_level(parent);
7085         extent_buffer_get(parent);
7086         path->nodes[parent_level] = parent;
7087         path->slots[parent_level] = btrfs_header_nritems(parent);
7088
7089         btrfs_assert_tree_locked(node);
7090         level = btrfs_header_level(node);
7091         path->nodes[level] = node;
7092         path->slots[level] = 0;
7093         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
7094
7095         wc->refs[parent_level] = 1;
7096         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7097         wc->level = level;
7098         wc->shared_level = -1;
7099         wc->stage = DROP_REFERENCE;
7100         wc->update_ref = 0;
7101         wc->keep_locks = 1;
7102         wc->for_reloc = 1;
7103         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
7104
7105         while (1) {
7106                 wret = walk_down_tree(trans, root, path, wc);
7107                 if (wret < 0) {
7108                         ret = wret;
7109                         break;
7110                 }
7111
7112                 wret = walk_up_tree(trans, root, path, wc, parent_level);
7113                 if (wret < 0)
7114                         ret = wret;
7115                 if (wret != 0)
7116                         break;
7117         }
7118
7119         kfree(wc);
7120         btrfs_free_path(path);
7121         return ret;
7122 }
7123
7124 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
7125 {
7126         u64 num_devices;
7127         u64 stripped;
7128
7129         /*
7130          * if restripe for this chunk_type is on pick target profile and
7131          * return, otherwise do the usual balance
7132          */
7133         stripped = get_restripe_target(root->fs_info, flags);
7134         if (stripped)
7135                 return extended_to_chunk(stripped);
7136
7137         /*
7138          * we add in the count of missing devices because we want
7139          * to make sure that any RAID levels on a degraded FS
7140          * continue to be honored.
7141          */
7142         num_devices = root->fs_info->fs_devices->rw_devices +
7143                 root->fs_info->fs_devices->missing_devices;
7144
7145         stripped = BTRFS_BLOCK_GROUP_RAID0 |
7146                 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
7147
7148         if (num_devices == 1) {
7149                 stripped |= BTRFS_BLOCK_GROUP_DUP;
7150                 stripped = flags & ~stripped;
7151
7152                 /* turn raid0 into single device chunks */
7153                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
7154                         return stripped;
7155
7156                 /* turn mirroring into duplication */
7157                 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
7158                              BTRFS_BLOCK_GROUP_RAID10))
7159                         return stripped | BTRFS_BLOCK_GROUP_DUP;
7160         } else {
7161                 /* they already had raid on here, just return */
7162                 if (flags & stripped)
7163                         return flags;
7164
7165                 stripped |= BTRFS_BLOCK_GROUP_DUP;
7166                 stripped = flags & ~stripped;
7167
7168                 /* switch duplicated blocks with raid1 */
7169                 if (flags & BTRFS_BLOCK_GROUP_DUP)
7170                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
7171
7172                 /* this is drive concat, leave it alone */
7173         }
7174
7175         return flags;
7176 }
7177
7178 static int set_block_group_ro(struct btrfs_block_group_cache *cache, int force)
7179 {
7180         struct btrfs_space_info *sinfo = cache->space_info;
7181         u64 num_bytes;
7182         u64 min_allocable_bytes;
7183         int ret = -ENOSPC;
7184
7185
7186         /*
7187          * We need some metadata space and system metadata space for
7188          * allocating chunks in some corner cases until we force to set
7189          * it to be readonly.
7190          */
7191         if ((sinfo->flags &
7192              (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
7193             !force)
7194                 min_allocable_bytes = 1 * 1024 * 1024;
7195         else
7196                 min_allocable_bytes = 0;
7197
7198         spin_lock(&sinfo->lock);
7199         spin_lock(&cache->lock);
7200
7201         if (cache->ro) {
7202                 ret = 0;
7203                 goto out;
7204         }
7205
7206         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7207                     cache->bytes_super - btrfs_block_group_used(&cache->item);
7208
7209         if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
7210             sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
7211             min_allocable_bytes <= sinfo->total_bytes) {
7212                 sinfo->bytes_readonly += num_bytes;
7213                 cache->ro = 1;
7214                 ret = 0;
7215         }
7216 out:
7217         spin_unlock(&cache->lock);
7218         spin_unlock(&sinfo->lock);
7219         return ret;
7220 }
7221
7222 int btrfs_set_block_group_ro(struct btrfs_root *root,
7223                              struct btrfs_block_group_cache *cache)
7224
7225 {
7226         struct btrfs_trans_handle *trans;
7227         u64 alloc_flags;
7228         int ret;
7229
7230         BUG_ON(cache->ro);
7231
7232         trans = btrfs_join_transaction(root);
7233         if (IS_ERR(trans))
7234                 return PTR_ERR(trans);
7235
7236         alloc_flags = update_block_group_flags(root, cache->flags);
7237         if (alloc_flags != cache->flags) {
7238                 ret = do_chunk_alloc(trans, root, alloc_flags,
7239                                      CHUNK_ALLOC_FORCE);
7240                 if (ret < 0)
7241                         goto out;
7242         }
7243
7244         ret = set_block_group_ro(cache, 0);
7245         if (!ret)
7246                 goto out;
7247         alloc_flags = get_alloc_profile(root, cache->space_info->flags);
7248         ret = do_chunk_alloc(trans, root, alloc_flags,
7249                              CHUNK_ALLOC_FORCE);
7250         if (ret < 0)
7251                 goto out;
7252         ret = set_block_group_ro(cache, 0);
7253 out:
7254         btrfs_end_transaction(trans, root);
7255         return ret;
7256 }
7257
7258 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
7259                             struct btrfs_root *root, u64 type)
7260 {
7261         u64 alloc_flags = get_alloc_profile(root, type);
7262         return do_chunk_alloc(trans, root, alloc_flags,
7263                               CHUNK_ALLOC_FORCE);
7264 }
7265
7266 /*
7267  * helper to account the unused space of all the readonly block group in the
7268  * list. takes mirrors into account.
7269  */
7270 static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
7271 {
7272         struct btrfs_block_group_cache *block_group;
7273         u64 free_bytes = 0;
7274         int factor;
7275
7276         list_for_each_entry(block_group, groups_list, list) {
7277                 spin_lock(&block_group->lock);
7278
7279                 if (!block_group->ro) {
7280                         spin_unlock(&block_group->lock);
7281                         continue;
7282                 }
7283
7284                 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
7285                                           BTRFS_BLOCK_GROUP_RAID10 |
7286                                           BTRFS_BLOCK_GROUP_DUP))
7287                         factor = 2;
7288                 else
7289                         factor = 1;
7290
7291                 free_bytes += (block_group->key.offset -
7292                                btrfs_block_group_used(&block_group->item)) *
7293                                factor;
7294
7295                 spin_unlock(&block_group->lock);
7296         }
7297
7298         return free_bytes;
7299 }
7300
7301 /*
7302  * helper to account the unused space of all the readonly block group in the
7303  * space_info. takes mirrors into account.
7304  */
7305 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
7306 {
7307         int i;
7308         u64 free_bytes = 0;
7309
7310         spin_lock(&sinfo->lock);
7311
7312         for(i = 0; i < BTRFS_NR_RAID_TYPES; i++)
7313                 if (!list_empty(&sinfo->block_groups[i]))
7314                         free_bytes += __btrfs_get_ro_block_group_free_space(
7315                                                 &sinfo->block_groups[i]);
7316
7317         spin_unlock(&sinfo->lock);
7318
7319         return free_bytes;
7320 }
7321
7322 void btrfs_set_block_group_rw(struct btrfs_root *root,
7323                               struct btrfs_block_group_cache *cache)
7324 {
7325         struct btrfs_space_info *sinfo = cache->space_info;
7326         u64 num_bytes;
7327
7328         BUG_ON(!cache->ro);
7329
7330         spin_lock(&sinfo->lock);
7331         spin_lock(&cache->lock);
7332         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
7333                     cache->bytes_super - btrfs_block_group_used(&cache->item);
7334         sinfo->bytes_readonly -= num_bytes;
7335         cache->ro = 0;
7336         spin_unlock(&cache->lock);
7337         spin_unlock(&sinfo->lock);
7338 }
7339
7340 /*
7341  * checks to see if its even possible to relocate this block group.
7342  *
7343  * @return - -1 if it's not a good idea to relocate this block group, 0 if its
7344  * ok to go ahead and try.
7345  */
7346 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
7347 {
7348         struct btrfs_block_group_cache *block_group;
7349         struct btrfs_space_info *space_info;
7350         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
7351         struct btrfs_device *device;
7352         u64 min_free;
7353         u64 dev_min = 1;
7354         u64 dev_nr = 0;
7355         u64 target;
7356         int index;
7357         int full = 0;
7358         int ret = 0;
7359
7360         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
7361
7362         /* odd, couldn't find the block group, leave it alone */
7363         if (!block_group)
7364                 return -1;
7365
7366         min_free = btrfs_block_group_used(&block_group->item);
7367
7368         /* no bytes used, we're good */
7369         if (!min_free)
7370                 goto out;
7371
7372         space_info = block_group->space_info;
7373         spin_lock(&space_info->lock);
7374
7375         full = space_info->full;
7376
7377         /*
7378          * if this is the last block group we have in this space, we can't
7379          * relocate it unless we're able to allocate a new chunk below.
7380          *
7381          * Otherwise, we need to make sure we have room in the space to handle
7382          * all of the extents from this block group.  If we can, we're good
7383          */
7384         if ((space_info->total_bytes != block_group->key.offset) &&
7385             (space_info->bytes_used + space_info->bytes_reserved +
7386              space_info->bytes_pinned + space_info->bytes_readonly +
7387              min_free < space_info->total_bytes)) {
7388                 spin_unlock(&space_info->lock);
7389                 goto out;
7390         }
7391         spin_unlock(&space_info->lock);
7392
7393         /*
7394          * ok we don't have enough space, but maybe we have free space on our
7395          * devices to allocate new chunks for relocation, so loop through our
7396          * alloc devices and guess if we have enough space.  if this block
7397          * group is going to be restriped, run checks against the target
7398          * profile instead of the current one.
7399          */
7400         ret = -1;
7401
7402         /*
7403          * index:
7404          *      0: raid10
7405          *      1: raid1
7406          *      2: dup
7407          *      3: raid0
7408          *      4: single
7409          */
7410         target = get_restripe_target(root->fs_info, block_group->flags);
7411         if (target) {
7412                 index = __get_block_group_index(extended_to_chunk(target));
7413         } else {
7414                 /*
7415                  * this is just a balance, so if we were marked as full
7416                  * we know there is no space for a new chunk
7417                  */
7418                 if (full)
7419                         goto out;
7420
7421                 index = get_block_group_index(block_group);
7422         }
7423
7424         if (index == 0) {
7425                 dev_min = 4;
7426                 /* Divide by 2 */
7427                 min_free >>= 1;
7428         } else if (index == 1) {
7429                 dev_min = 2;
7430         } else if (index == 2) {
7431                 /* Multiply by 2 */
7432                 min_free <<= 1;
7433         } else if (index == 3) {
7434                 dev_min = fs_devices->rw_devices;
7435                 do_div(min_free, dev_min);
7436         }
7437
7438         mutex_lock(&root->fs_info->chunk_mutex);
7439         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7440                 u64 dev_offset;
7441
7442                 /*
7443                  * check to make sure we can actually find a chunk with enough
7444                  * space to fit our block group in.
7445                  */
7446                 if (device->total_bytes > device->bytes_used + min_free) {
7447                         ret = find_free_dev_extent(device, min_free,
7448                                                    &dev_offset, NULL);
7449                         if (!ret)
7450                                 dev_nr++;
7451
7452                         if (dev_nr >= dev_min)
7453                                 break;
7454
7455                         ret = -1;
7456                 }
7457         }
7458         mutex_unlock(&root->fs_info->chunk_mutex);
7459 out:
7460         btrfs_put_block_group(block_group);
7461         return ret;
7462 }
7463
7464 static int find_first_block_group(struct btrfs_root *root,
7465                 struct btrfs_path *path, struct btrfs_key *key)
7466 {
7467         int ret = 0;
7468         struct btrfs_key found_key;
7469         struct extent_buffer *leaf;
7470         int slot;
7471
7472         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7473         if (ret < 0)
7474                 goto out;
7475
7476         while (1) {
7477                 slot = path->slots[0];
7478                 leaf = path->nodes[0];
7479                 if (slot >= btrfs_header_nritems(leaf)) {
7480                         ret = btrfs_next_leaf(root, path);
7481                         if (ret == 0)
7482                                 continue;
7483                         if (ret < 0)
7484                                 goto out;
7485                         break;
7486                 }
7487                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
7488
7489                 if (found_key.objectid >= key->objectid &&
7490                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
7491                         ret = 0;
7492                         goto out;
7493                 }
7494                 path->slots[0]++;
7495         }
7496 out:
7497         return ret;
7498 }
7499
7500 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
7501 {
7502         struct btrfs_block_group_cache *block_group;
7503         u64 last = 0;
7504
7505         while (1) {
7506                 struct inode *inode;
7507
7508                 block_group = btrfs_lookup_first_block_group(info, last);
7509                 while (block_group) {
7510                         spin_lock(&block_group->lock);
7511                         if (block_group->iref)
7512                                 break;
7513                         spin_unlock(&block_group->lock);
7514                         block_group = next_block_group(info->tree_root,
7515                                                        block_group);
7516                 }
7517                 if (!block_group) {
7518                         if (last == 0)
7519                                 break;
7520                         last = 0;
7521                         continue;
7522                 }
7523
7524                 inode = block_group->inode;
7525                 block_group->iref = 0;
7526                 block_group->inode = NULL;
7527                 spin_unlock(&block_group->lock);
7528                 iput(inode);
7529                 last = block_group->key.objectid + block_group->key.offset;
7530                 btrfs_put_block_group(block_group);
7531         }
7532 }
7533
7534 int btrfs_free_block_groups(struct btrfs_fs_info *info)
7535 {
7536         struct btrfs_block_group_cache *block_group;
7537         struct btrfs_space_info *space_info;
7538         struct btrfs_caching_control *caching_ctl;
7539         struct rb_node *n;
7540
7541         down_write(&info->extent_commit_sem);
7542         while (!list_empty(&info->caching_block_groups)) {
7543                 caching_ctl = list_entry(info->caching_block_groups.next,
7544                                          struct btrfs_caching_control, list);
7545                 list_del(&caching_ctl->list);
7546                 put_caching_control(caching_ctl);
7547         }
7548         up_write(&info->extent_commit_sem);
7549
7550         spin_lock(&info->block_group_cache_lock);
7551         while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
7552                 block_group = rb_entry(n, struct btrfs_block_group_cache,
7553                                        cache_node);
7554                 rb_erase(&block_group->cache_node,
7555                          &info->block_group_cache_tree);
7556                 spin_unlock(&info->block_group_cache_lock);
7557
7558                 down_write(&block_group->space_info->groups_sem);
7559                 list_del(&block_group->list);
7560                 up_write(&block_group->space_info->groups_sem);
7561
7562                 if (block_group->cached == BTRFS_CACHE_STARTED)
7563                         wait_block_group_cache_done(block_group);
7564
7565                 /*
7566                  * We haven't cached this block group, which means we could
7567                  * possibly have excluded extents on this block group.
7568                  */
7569                 if (block_group->cached == BTRFS_CACHE_NO)
7570                         free_excluded_extents(info->extent_root, block_group);
7571
7572                 btrfs_remove_free_space_cache(block_group);
7573                 btrfs_put_block_group(block_group);
7574
7575                 spin_lock(&info->block_group_cache_lock);
7576         }
7577         spin_unlock(&info->block_group_cache_lock);
7578
7579         /* now that all the block groups are freed, go through and
7580          * free all the space_info structs.  This is only called during
7581          * the final stages of unmount, and so we know nobody is
7582          * using them.  We call synchronize_rcu() once before we start,
7583          * just to be on the safe side.
7584          */
7585         synchronize_rcu();
7586
7587         release_global_block_rsv(info);
7588
7589         while(!list_empty(&info->space_info)) {
7590                 space_info = list_entry(info->space_info.next,
7591                                         struct btrfs_space_info,
7592                                         list);
7593                 if (space_info->bytes_pinned > 0 ||
7594                     space_info->bytes_reserved > 0 ||
7595                     space_info->bytes_may_use > 0) {
7596                         WARN_ON(1);
7597                         dump_space_info(space_info, 0, 0);
7598                 }
7599                 list_del(&space_info->list);
7600                 kfree(space_info);
7601         }
7602         return 0;
7603 }
7604
7605 static void __link_block_group(struct btrfs_space_info *space_info,
7606                                struct btrfs_block_group_cache *cache)
7607 {
7608         int index = get_block_group_index(cache);
7609
7610         down_write(&space_info->groups_sem);
7611         list_add_tail(&cache->list, &space_info->block_groups[index]);
7612         up_write(&space_info->groups_sem);
7613 }
7614
7615 int btrfs_read_block_groups(struct btrfs_root *root)
7616 {
7617         struct btrfs_path *path;
7618         int ret;
7619         struct btrfs_block_group_cache *cache;
7620         struct btrfs_fs_info *info = root->fs_info;
7621         struct btrfs_space_info *space_info;
7622         struct btrfs_key key;
7623         struct btrfs_key found_key;
7624         struct extent_buffer *leaf;
7625         int need_clear = 0;
7626         u64 cache_gen;
7627
7628         root = info->extent_root;
7629         key.objectid = 0;
7630         key.offset = 0;
7631         btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
7632         path = btrfs_alloc_path();
7633         if (!path)
7634                 return -ENOMEM;
7635         path->reada = 1;
7636
7637         cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
7638         if (btrfs_test_opt(root, SPACE_CACHE) &&
7639             btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
7640                 need_clear = 1;
7641         if (btrfs_test_opt(root, CLEAR_CACHE))
7642                 need_clear = 1;
7643
7644         while (1) {
7645                 ret = find_first_block_group(root, path, &key);
7646                 if (ret > 0)
7647                         break;
7648                 if (ret != 0)
7649                         goto error;
7650                 leaf = path->nodes[0];
7651                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7652                 cache = kzalloc(sizeof(*cache), GFP_NOFS);
7653                 if (!cache) {
7654                         ret = -ENOMEM;
7655                         goto error;
7656                 }
7657                 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
7658                                                 GFP_NOFS);
7659                 if (!cache->free_space_ctl) {
7660                         kfree(cache);
7661                         ret = -ENOMEM;
7662                         goto error;
7663                 }
7664
7665                 atomic_set(&cache->count, 1);
7666                 spin_lock_init(&cache->lock);
7667                 cache->fs_info = info;
7668                 INIT_LIST_HEAD(&cache->list);
7669                 INIT_LIST_HEAD(&cache->cluster_list);
7670
7671                 if (need_clear) {
7672                         /*
7673                          * When we mount with old space cache, we need to
7674                          * set BTRFS_DC_CLEAR and set dirty flag.
7675                          *
7676                          * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
7677                          *    truncate the old free space cache inode and
7678                          *    setup a new one.
7679                          * b) Setting 'dirty flag' makes sure that we flush
7680                          *    the new space cache info onto disk.
7681                          */
7682                         cache->disk_cache_state = BTRFS_DC_CLEAR;
7683                         if (btrfs_test_opt(root, SPACE_CACHE))
7684                                 cache->dirty = 1;
7685                 }
7686
7687                 read_extent_buffer(leaf, &cache->item,
7688                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
7689                                    sizeof(cache->item));
7690                 memcpy(&cache->key, &found_key, sizeof(found_key));
7691
7692                 key.objectid = found_key.objectid + found_key.offset;
7693                 btrfs_release_path(path);
7694                 cache->flags = btrfs_block_group_flags(&cache->item);
7695                 cache->sectorsize = root->sectorsize;
7696
7697                 btrfs_init_free_space_ctl(cache);
7698
7699                 /*
7700                  * We need to exclude the super stripes now so that the space
7701                  * info has super bytes accounted for, otherwise we'll think
7702                  * we have more space than we actually do.
7703                  */
7704                 exclude_super_stripes(root, cache);
7705
7706                 /*
7707                  * check for two cases, either we are full, and therefore
7708                  * don't need to bother with the caching work since we won't
7709                  * find any space, or we are empty, and we can just add all
7710                  * the space in and be done with it.  This saves us _alot_ of
7711                  * time, particularly in the full case.
7712                  */
7713                 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
7714                         cache->last_byte_to_unpin = (u64)-1;
7715                         cache->cached = BTRFS_CACHE_FINISHED;
7716                         free_excluded_extents(root, cache);
7717                 } else if (btrfs_block_group_used(&cache->item) == 0) {
7718                         cache->last_byte_to_unpin = (u64)-1;
7719                         cache->cached = BTRFS_CACHE_FINISHED;
7720                         add_new_free_space(cache, root->fs_info,
7721                                            found_key.objectid,
7722                                            found_key.objectid +
7723                                            found_key.offset);
7724                         free_excluded_extents(root, cache);
7725                 }
7726
7727                 ret = update_space_info(info, cache->flags, found_key.offset,
7728                                         btrfs_block_group_used(&cache->item),
7729                                         &space_info);
7730                 BUG_ON(ret); /* -ENOMEM */
7731                 cache->space_info = space_info;
7732                 spin_lock(&cache->space_info->lock);
7733                 cache->space_info->bytes_readonly += cache->bytes_super;
7734                 spin_unlock(&cache->space_info->lock);
7735
7736                 __link_block_group(space_info, cache);
7737
7738                 ret = btrfs_add_block_group_cache(root->fs_info, cache);
7739                 BUG_ON(ret); /* Logic error */
7740
7741                 set_avail_alloc_bits(root->fs_info, cache->flags);
7742                 if (btrfs_chunk_readonly(root, cache->key.objectid))
7743                         set_block_group_ro(cache, 1);
7744         }
7745
7746         list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
7747                 if (!(get_alloc_profile(root, space_info->flags) &
7748                       (BTRFS_BLOCK_GROUP_RAID10 |
7749                        BTRFS_BLOCK_GROUP_RAID1 |
7750                        BTRFS_BLOCK_GROUP_DUP)))
7751                         continue;
7752                 /*
7753                  * avoid allocating from un-mirrored block group if there are
7754                  * mirrored block groups.
7755                  */
7756                 list_for_each_entry(cache, &space_info->block_groups[3], list)
7757                         set_block_group_ro(cache, 1);
7758                 list_for_each_entry(cache, &space_info->block_groups[4], list)
7759                         set_block_group_ro(cache, 1);
7760         }
7761
7762         init_global_block_rsv(info);
7763         ret = 0;
7764 error:
7765         btrfs_free_path(path);
7766         return ret;
7767 }
7768
7769 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
7770                                        struct btrfs_root *root)
7771 {
7772         struct btrfs_block_group_cache *block_group, *tmp;
7773         struct btrfs_root *extent_root = root->fs_info->extent_root;
7774         struct btrfs_block_group_item item;
7775         struct btrfs_key key;
7776         int ret = 0;
7777
7778         list_for_each_entry_safe(block_group, tmp, &trans->new_bgs,
7779                                  new_bg_list) {
7780                 list_del_init(&block_group->new_bg_list);
7781
7782                 if (ret)
7783                         continue;
7784
7785                 spin_lock(&block_group->lock);
7786                 memcpy(&item, &block_group->item, sizeof(item));
7787                 memcpy(&key, &block_group->key, sizeof(key));
7788                 spin_unlock(&block_group->lock);
7789
7790                 ret = btrfs_insert_item(trans, extent_root, &key, &item,
7791                                         sizeof(item));
7792                 if (ret)
7793                         btrfs_abort_transaction(trans, extent_root, ret);
7794         }
7795 }
7796
7797 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
7798                            struct btrfs_root *root, u64 bytes_used,
7799                            u64 type, u64 chunk_objectid, u64 chunk_offset,
7800                            u64 size)
7801 {
7802         int ret;
7803         struct btrfs_root *extent_root;
7804         struct btrfs_block_group_cache *cache;
7805
7806         extent_root = root->fs_info->extent_root;
7807
7808         root->fs_info->last_trans_log_full_commit = trans->transid;
7809
7810         cache = kzalloc(sizeof(*cache), GFP_NOFS);
7811         if (!cache)
7812                 return -ENOMEM;
7813         cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
7814                                         GFP_NOFS);
7815         if (!cache->free_space_ctl) {
7816                 kfree(cache);
7817                 return -ENOMEM;
7818         }
7819
7820         cache->key.objectid = chunk_offset;
7821         cache->key.offset = size;
7822         cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
7823         cache->sectorsize = root->sectorsize;
7824         cache->fs_info = root->fs_info;
7825
7826         atomic_set(&cache->count, 1);
7827         spin_lock_init(&cache->lock);
7828         INIT_LIST_HEAD(&cache->list);
7829         INIT_LIST_HEAD(&cache->cluster_list);
7830         INIT_LIST_HEAD(&cache->new_bg_list);
7831
7832         btrfs_init_free_space_ctl(cache);
7833
7834         btrfs_set_block_group_used(&cache->item, bytes_used);
7835         btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
7836         cache->flags = type;
7837         btrfs_set_block_group_flags(&cache->item, type);
7838
7839         cache->last_byte_to_unpin = (u64)-1;
7840         cache->cached = BTRFS_CACHE_FINISHED;
7841         exclude_super_stripes(root, cache);
7842
7843         add_new_free_space(cache, root->fs_info, chunk_offset,
7844                            chunk_offset + size);
7845
7846         free_excluded_extents(root, cache);
7847
7848         ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
7849                                 &cache->space_info);
7850         BUG_ON(ret); /* -ENOMEM */
7851         update_global_block_rsv(root->fs_info);
7852
7853         spin_lock(&cache->space_info->lock);
7854         cache->space_info->bytes_readonly += cache->bytes_super;
7855         spin_unlock(&cache->space_info->lock);
7856
7857         __link_block_group(cache->space_info, cache);
7858
7859         ret = btrfs_add_block_group_cache(root->fs_info, cache);
7860         BUG_ON(ret); /* Logic error */
7861
7862         list_add_tail(&cache->new_bg_list, &trans->new_bgs);
7863
7864         set_avail_alloc_bits(extent_root->fs_info, type);
7865
7866         return 0;
7867 }
7868
7869 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
7870 {
7871         u64 extra_flags = chunk_to_extended(flags) &
7872                                 BTRFS_EXTENDED_PROFILE_MASK;
7873
7874         if (flags & BTRFS_BLOCK_GROUP_DATA)
7875                 fs_info->avail_data_alloc_bits &= ~extra_flags;
7876         if (flags & BTRFS_BLOCK_GROUP_METADATA)
7877                 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
7878         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
7879                 fs_info->avail_system_alloc_bits &= ~extra_flags;
7880 }
7881
7882 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
7883                              struct btrfs_root *root, u64 group_start)
7884 {
7885         struct btrfs_path *path;
7886         struct btrfs_block_group_cache *block_group;
7887         struct btrfs_free_cluster *cluster;
7888         struct btrfs_root *tree_root = root->fs_info->tree_root;
7889         struct btrfs_key key;
7890         struct inode *inode;
7891         int ret;
7892         int index;
7893         int factor;
7894
7895         root = root->fs_info->extent_root;
7896
7897         block_group = btrfs_lookup_block_group(root->fs_info, group_start);
7898         BUG_ON(!block_group);
7899         BUG_ON(!block_group->ro);
7900
7901         /*
7902          * Free the reserved super bytes from this block group before
7903          * remove it.
7904          */
7905         free_excluded_extents(root, block_group);
7906
7907         memcpy(&key, &block_group->key, sizeof(key));
7908         index = get_block_group_index(block_group);
7909         if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
7910                                   BTRFS_BLOCK_GROUP_RAID1 |
7911                                   BTRFS_BLOCK_GROUP_RAID10))
7912                 factor = 2;
7913         else
7914                 factor = 1;
7915
7916         /* make sure this block group isn't part of an allocation cluster */
7917         cluster = &root->fs_info->data_alloc_cluster;
7918         spin_lock(&cluster->refill_lock);
7919         btrfs_return_cluster_to_free_space(block_group, cluster);
7920         spin_unlock(&cluster->refill_lock);
7921
7922         /*
7923          * make sure this block group isn't part of a metadata
7924          * allocation cluster
7925          */
7926         cluster = &root->fs_info->meta_alloc_cluster;
7927         spin_lock(&cluster->refill_lock);
7928         btrfs_return_cluster_to_free_space(block_group, cluster);
7929         spin_unlock(&cluster->refill_lock);
7930
7931         path = btrfs_alloc_path();
7932         if (!path) {
7933                 ret = -ENOMEM;
7934                 goto out;
7935         }
7936
7937         inode = lookup_free_space_inode(tree_root, block_group, path);
7938         if (!IS_ERR(inode)) {
7939                 ret = btrfs_orphan_add(trans, inode);
7940                 if (ret) {
7941                         btrfs_add_delayed_iput(inode);
7942                         goto out;
7943                 }
7944                 clear_nlink(inode);
7945                 /* One for the block groups ref */
7946                 spin_lock(&block_group->lock);
7947                 if (block_group->iref) {
7948                         block_group->iref = 0;
7949                         block_group->inode = NULL;
7950                         spin_unlock(&block_group->lock);
7951                         iput(inode);
7952                 } else {
7953                         spin_unlock(&block_group->lock);
7954                 }
7955                 /* One for our lookup ref */
7956                 btrfs_add_delayed_iput(inode);
7957         }
7958
7959         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
7960         key.offset = block_group->key.objectid;
7961         key.type = 0;
7962
7963         ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
7964         if (ret < 0)
7965                 goto out;
7966         if (ret > 0)
7967                 btrfs_release_path(path);
7968         if (ret == 0) {
7969                 ret = btrfs_del_item(trans, tree_root, path);
7970                 if (ret)
7971                         goto out;
7972                 btrfs_release_path(path);
7973         }
7974
7975         spin_lock(&root->fs_info->block_group_cache_lock);
7976         rb_erase(&block_group->cache_node,
7977                  &root->fs_info->block_group_cache_tree);
7978         spin_unlock(&root->fs_info->block_group_cache_lock);
7979
7980         down_write(&block_group->space_info->groups_sem);
7981         /*
7982          * we must use list_del_init so people can check to see if they
7983          * are still on the list after taking the semaphore
7984          */
7985         list_del_init(&block_group->list);
7986         if (list_empty(&block_group->space_info->block_groups[index]))
7987                 clear_avail_alloc_bits(root->fs_info, block_group->flags);
7988         up_write(&block_group->space_info->groups_sem);
7989
7990         if (block_group->cached == BTRFS_CACHE_STARTED)
7991                 wait_block_group_cache_done(block_group);
7992
7993         btrfs_remove_free_space_cache(block_group);
7994
7995         spin_lock(&block_group->space_info->lock);
7996         block_group->space_info->total_bytes -= block_group->key.offset;
7997         block_group->space_info->bytes_readonly -= block_group->key.offset;
7998         block_group->space_info->disk_total -= block_group->key.offset * factor;
7999         spin_unlock(&block_group->space_info->lock);
8000
8001         memcpy(&key, &block_group->key, sizeof(key));
8002
8003         btrfs_clear_space_info_full(root->fs_info);
8004
8005         btrfs_put_block_group(block_group);
8006         btrfs_put_block_group(block_group);
8007
8008         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8009         if (ret > 0)
8010                 ret = -EIO;
8011         if (ret < 0)
8012                 goto out;
8013
8014         ret = btrfs_del_item(trans, root, path);
8015 out:
8016         btrfs_free_path(path);
8017         return ret;
8018 }
8019
8020 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
8021 {
8022         struct btrfs_space_info *space_info;
8023         struct btrfs_super_block *disk_super;
8024         u64 features;
8025         u64 flags;
8026         int mixed = 0;
8027         int ret;
8028
8029         disk_super = fs_info->super_copy;
8030         if (!btrfs_super_root(disk_super))
8031                 return 1;
8032
8033         features = btrfs_super_incompat_flags(disk_super);
8034         if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
8035                 mixed = 1;
8036
8037         flags = BTRFS_BLOCK_GROUP_SYSTEM;
8038         ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8039         if (ret)
8040                 goto out;
8041
8042         if (mixed) {
8043                 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
8044                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8045         } else {
8046                 flags = BTRFS_BLOCK_GROUP_METADATA;
8047                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8048                 if (ret)
8049                         goto out;
8050
8051                 flags = BTRFS_BLOCK_GROUP_DATA;
8052                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
8053         }
8054 out:
8055         return ret;
8056 }
8057
8058 int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
8059 {
8060         return unpin_extent_range(root, start, end);
8061 }
8062
8063 int btrfs_error_discard_extent(struct btrfs_root *root, u64 bytenr,
8064                                u64 num_bytes, u64 *actual_bytes)
8065 {
8066         return btrfs_discard_extent(root, bytenr, num_bytes, actual_bytes);
8067 }
8068
8069 int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
8070 {
8071         struct btrfs_fs_info *fs_info = root->fs_info;
8072         struct btrfs_block_group_cache *cache = NULL;
8073         u64 group_trimmed;
8074         u64 start;
8075         u64 end;
8076         u64 trimmed = 0;
8077         u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
8078         int ret = 0;
8079
8080         /*
8081          * try to trim all FS space, our block group may start from non-zero.
8082          */
8083         if (range->len == total_bytes)
8084                 cache = btrfs_lookup_first_block_group(fs_info, range->start);
8085         else
8086                 cache = btrfs_lookup_block_group(fs_info, range->start);
8087
8088         while (cache) {
8089                 if (cache->key.objectid >= (range->start + range->len)) {
8090                         btrfs_put_block_group(cache);
8091                         break;
8092                 }
8093
8094                 start = max(range->start, cache->key.objectid);
8095                 end = min(range->start + range->len,
8096                                 cache->key.objectid + cache->key.offset);
8097
8098                 if (end - start >= range->minlen) {
8099                         if (!block_group_cache_done(cache)) {
8100                                 ret = cache_block_group(cache, NULL, root, 0);
8101                                 if (!ret)
8102                                         wait_block_group_cache_done(cache);
8103                         }
8104                         ret = btrfs_trim_block_group(cache,
8105                                                      &group_trimmed,
8106                                                      start,
8107                                                      end,
8108                                                      range->minlen);
8109
8110                         trimmed += group_trimmed;
8111                         if (ret) {
8112                                 btrfs_put_block_group(cache);
8113                                 break;
8114                         }
8115                 }
8116
8117                 cache = next_block_group(fs_info->tree_root, cache);
8118         }
8119
8120         range->len = trimmed;
8121         return ret;
8122 }