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