795547c860fcca3669d091112ef50e27ada6ec61
[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 <linux/percpu_counter.h>
28 #include "hash.h"
29 #include "tree-log.h"
30 #include "disk-io.h"
31 #include "print-tree.h"
32 #include "volumes.h"
33 #include "raid56.h"
34 #include "locking.h"
35 #include "free-space-cache.h"
36 #include "math.h"
37 #include "sysfs.h"
38 #include "qgroup.h"
39
40 #undef SCRAMBLE_DELAYED_REFS
41
42 /*
43  * control flags for do_chunk_alloc's force field
44  * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
45  * if we really need one.
46  *
47  * CHUNK_ALLOC_LIMITED means to only try and allocate one
48  * if we have very few chunks already allocated.  This is
49  * used as part of the clustering code to help make sure
50  * we have a good pool of storage to cluster in, without
51  * filling the FS with empty chunks
52  *
53  * CHUNK_ALLOC_FORCE means it must try to allocate one
54  *
55  */
56 enum {
57         CHUNK_ALLOC_NO_FORCE = 0,
58         CHUNK_ALLOC_LIMITED = 1,
59         CHUNK_ALLOC_FORCE = 2,
60 };
61
62 /*
63  * Control how reservations are dealt with.
64  *
65  * RESERVE_FREE - freeing a reservation.
66  * RESERVE_ALLOC - allocating space and we need to update bytes_may_use for
67  *   ENOSPC accounting
68  * RESERVE_ALLOC_NO_ACCOUNT - allocating space and we should not update
69  *   bytes_may_use as the ENOSPC accounting is done elsewhere
70  */
71 enum {
72         RESERVE_FREE = 0,
73         RESERVE_ALLOC = 1,
74         RESERVE_ALLOC_NO_ACCOUNT = 2,
75 };
76
77 static int update_block_group(struct btrfs_trans_handle *trans,
78                               struct btrfs_root *root, u64 bytenr,
79                               u64 num_bytes, int alloc);
80 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
81                                 struct btrfs_root *root,
82                                 struct btrfs_delayed_ref_node *node, u64 parent,
83                                 u64 root_objectid, u64 owner_objectid,
84                                 u64 owner_offset, int refs_to_drop,
85                                 struct btrfs_delayed_extent_op *extra_op);
86 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
87                                     struct extent_buffer *leaf,
88                                     struct btrfs_extent_item *ei);
89 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
90                                       struct btrfs_root *root,
91                                       u64 parent, u64 root_objectid,
92                                       u64 flags, u64 owner, u64 offset,
93                                       struct btrfs_key *ins, int ref_mod);
94 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
95                                      struct btrfs_root *root,
96                                      u64 parent, u64 root_objectid,
97                                      u64 flags, struct btrfs_disk_key *key,
98                                      int level, struct btrfs_key *ins);
99 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
100                           struct btrfs_root *extent_root, u64 flags,
101                           int force);
102 static int find_next_key(struct btrfs_path *path, int level,
103                          struct btrfs_key *key);
104 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
105                             int dump_block_groups);
106 static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
107                                        u64 num_bytes, int reserve,
108                                        int delalloc);
109 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
110                                u64 num_bytes);
111 int btrfs_pin_extent(struct btrfs_root *root,
112                      u64 bytenr, u64 num_bytes, int reserved);
113
114 static noinline int
115 block_group_cache_done(struct btrfs_block_group_cache *cache)
116 {
117         smp_mb();
118         return cache->cached == BTRFS_CACHE_FINISHED ||
119                 cache->cached == BTRFS_CACHE_ERROR;
120 }
121
122 static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
123 {
124         return (cache->flags & bits) == bits;
125 }
126
127 void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
128 {
129         atomic_inc(&cache->count);
130 }
131
132 void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
133 {
134         if (atomic_dec_and_test(&cache->count)) {
135                 WARN_ON(cache->pinned > 0);
136                 WARN_ON(cache->reserved > 0);
137                 kfree(cache->free_space_ctl);
138                 kfree(cache);
139         }
140 }
141
142 /*
143  * this adds the block group to the fs_info rb tree for the block group
144  * cache
145  */
146 static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
147                                 struct btrfs_block_group_cache *block_group)
148 {
149         struct rb_node **p;
150         struct rb_node *parent = NULL;
151         struct btrfs_block_group_cache *cache;
152
153         spin_lock(&info->block_group_cache_lock);
154         p = &info->block_group_cache_tree.rb_node;
155
156         while (*p) {
157                 parent = *p;
158                 cache = rb_entry(parent, struct btrfs_block_group_cache,
159                                  cache_node);
160                 if (block_group->key.objectid < cache->key.objectid) {
161                         p = &(*p)->rb_left;
162                 } else if (block_group->key.objectid > cache->key.objectid) {
163                         p = &(*p)->rb_right;
164                 } else {
165                         spin_unlock(&info->block_group_cache_lock);
166                         return -EEXIST;
167                 }
168         }
169
170         rb_link_node(&block_group->cache_node, parent, p);
171         rb_insert_color(&block_group->cache_node,
172                         &info->block_group_cache_tree);
173
174         if (info->first_logical_byte > block_group->key.objectid)
175                 info->first_logical_byte = block_group->key.objectid;
176
177         spin_unlock(&info->block_group_cache_lock);
178
179         return 0;
180 }
181
182 /*
183  * This will return the block group at or after bytenr if contains is 0, else
184  * it will return the block group that contains the bytenr
185  */
186 static struct btrfs_block_group_cache *
187 block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
188                               int contains)
189 {
190         struct btrfs_block_group_cache *cache, *ret = NULL;
191         struct rb_node *n;
192         u64 end, start;
193
194         spin_lock(&info->block_group_cache_lock);
195         n = info->block_group_cache_tree.rb_node;
196
197         while (n) {
198                 cache = rb_entry(n, struct btrfs_block_group_cache,
199                                  cache_node);
200                 end = cache->key.objectid + cache->key.offset - 1;
201                 start = cache->key.objectid;
202
203                 if (bytenr < start) {
204                         if (!contains && (!ret || start < ret->key.objectid))
205                                 ret = cache;
206                         n = n->rb_left;
207                 } else if (bytenr > start) {
208                         if (contains && bytenr <= end) {
209                                 ret = cache;
210                                 break;
211                         }
212                         n = n->rb_right;
213                 } else {
214                         ret = cache;
215                         break;
216                 }
217         }
218         if (ret) {
219                 btrfs_get_block_group(ret);
220                 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
221                         info->first_logical_byte = ret->key.objectid;
222         }
223         spin_unlock(&info->block_group_cache_lock);
224
225         return ret;
226 }
227
228 static int add_excluded_extent(struct btrfs_root *root,
229                                u64 start, u64 num_bytes)
230 {
231         u64 end = start + num_bytes - 1;
232         set_extent_bits(&root->fs_info->freed_extents[0],
233                         start, end, EXTENT_UPTODATE, GFP_NOFS);
234         set_extent_bits(&root->fs_info->freed_extents[1],
235                         start, end, EXTENT_UPTODATE, GFP_NOFS);
236         return 0;
237 }
238
239 static void free_excluded_extents(struct btrfs_root *root,
240                                   struct btrfs_block_group_cache *cache)
241 {
242         u64 start, end;
243
244         start = cache->key.objectid;
245         end = start + cache->key.offset - 1;
246
247         clear_extent_bits(&root->fs_info->freed_extents[0],
248                           start, end, EXTENT_UPTODATE, GFP_NOFS);
249         clear_extent_bits(&root->fs_info->freed_extents[1],
250                           start, end, EXTENT_UPTODATE, GFP_NOFS);
251 }
252
253 static int exclude_super_stripes(struct btrfs_root *root,
254                                  struct btrfs_block_group_cache *cache)
255 {
256         u64 bytenr;
257         u64 *logical;
258         int stripe_len;
259         int i, nr, ret;
260
261         if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
262                 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
263                 cache->bytes_super += stripe_len;
264                 ret = add_excluded_extent(root, cache->key.objectid,
265                                           stripe_len);
266                 if (ret)
267                         return ret;
268         }
269
270         for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
271                 bytenr = btrfs_sb_offset(i);
272                 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
273                                        cache->key.objectid, bytenr,
274                                        0, &logical, &nr, &stripe_len);
275                 if (ret)
276                         return ret;
277
278                 while (nr--) {
279                         u64 start, len;
280
281                         if (logical[nr] > cache->key.objectid +
282                             cache->key.offset)
283                                 continue;
284
285                         if (logical[nr] + stripe_len <= cache->key.objectid)
286                                 continue;
287
288                         start = logical[nr];
289                         if (start < cache->key.objectid) {
290                                 start = cache->key.objectid;
291                                 len = (logical[nr] + stripe_len) - start;
292                         } else {
293                                 len = min_t(u64, stripe_len,
294                                             cache->key.objectid +
295                                             cache->key.offset - start);
296                         }
297
298                         cache->bytes_super += len;
299                         ret = add_excluded_extent(root, start, len);
300                         if (ret) {
301                                 kfree(logical);
302                                 return ret;
303                         }
304                 }
305
306                 kfree(logical);
307         }
308         return 0;
309 }
310
311 static struct btrfs_caching_control *
312 get_caching_control(struct btrfs_block_group_cache *cache)
313 {
314         struct btrfs_caching_control *ctl;
315
316         spin_lock(&cache->lock);
317         if (!cache->caching_ctl) {
318                 spin_unlock(&cache->lock);
319                 return NULL;
320         }
321
322         ctl = cache->caching_ctl;
323         atomic_inc(&ctl->count);
324         spin_unlock(&cache->lock);
325         return ctl;
326 }
327
328 static void put_caching_control(struct btrfs_caching_control *ctl)
329 {
330         if (atomic_dec_and_test(&ctl->count))
331                 kfree(ctl);
332 }
333
334 #ifdef CONFIG_BTRFS_DEBUG
335 static void fragment_free_space(struct btrfs_root *root,
336                                 struct btrfs_block_group_cache *block_group)
337 {
338         u64 start = block_group->key.objectid;
339         u64 len = block_group->key.offset;
340         u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
341                 root->nodesize : root->sectorsize;
342         u64 step = chunk << 1;
343
344         while (len > chunk) {
345                 btrfs_remove_free_space(block_group, start, chunk);
346                 start += step;
347                 if (len < step)
348                         len = 0;
349                 else
350                         len -= step;
351         }
352 }
353 #endif
354
355 /*
356  * this is only called by cache_block_group, since we could have freed extents
357  * we need to check the pinned_extents for any extents that can't be used yet
358  * since their free space will be released as soon as the transaction commits.
359  */
360 static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
361                               struct btrfs_fs_info *info, u64 start, u64 end)
362 {
363         u64 extent_start, extent_end, size, total_added = 0;
364         int ret;
365
366         while (start < end) {
367                 ret = find_first_extent_bit(info->pinned_extents, start,
368                                             &extent_start, &extent_end,
369                                             EXTENT_DIRTY | EXTENT_UPTODATE,
370                                             NULL);
371                 if (ret)
372                         break;
373
374                 if (extent_start <= start) {
375                         start = extent_end + 1;
376                 } else if (extent_start > start && extent_start < end) {
377                         size = extent_start - start;
378                         total_added += size;
379                         ret = btrfs_add_free_space(block_group, start,
380                                                    size);
381                         BUG_ON(ret); /* -ENOMEM or logic error */
382                         start = extent_end + 1;
383                 } else {
384                         break;
385                 }
386         }
387
388         if (start < end) {
389                 size = end - start;
390                 total_added += size;
391                 ret = btrfs_add_free_space(block_group, start, size);
392                 BUG_ON(ret); /* -ENOMEM or logic error */
393         }
394
395         return total_added;
396 }
397
398 static noinline void caching_thread(struct btrfs_work *work)
399 {
400         struct btrfs_block_group_cache *block_group;
401         struct btrfs_fs_info *fs_info;
402         struct btrfs_caching_control *caching_ctl;
403         struct btrfs_root *extent_root;
404         struct btrfs_path *path;
405         struct extent_buffer *leaf;
406         struct btrfs_key key;
407         u64 total_found = 0;
408         u64 last = 0;
409         u32 nritems;
410         int ret = -ENOMEM;
411         bool wakeup = true;
412
413         caching_ctl = container_of(work, struct btrfs_caching_control, work);
414         block_group = caching_ctl->block_group;
415         fs_info = block_group->fs_info;
416         extent_root = fs_info->extent_root;
417
418         path = btrfs_alloc_path();
419         if (!path)
420                 goto out;
421
422         last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
423
424 #ifdef CONFIG_BTRFS_DEBUG
425         /*
426          * If we're fragmenting we don't want to make anybody think we can
427          * allocate from this block group until we've had a chance to fragment
428          * the free space.
429          */
430         if (btrfs_should_fragment_free_space(extent_root, block_group))
431                 wakeup = false;
432 #endif
433         /*
434          * We don't want to deadlock with somebody trying to allocate a new
435          * extent for the extent root while also trying to search the extent
436          * root to add free space.  So we skip locking and search the commit
437          * root, since its read-only
438          */
439         path->skip_locking = 1;
440         path->search_commit_root = 1;
441         path->reada = 1;
442
443         key.objectid = last;
444         key.offset = 0;
445         key.type = BTRFS_EXTENT_ITEM_KEY;
446 again:
447         mutex_lock(&caching_ctl->mutex);
448         /* need to make sure the commit_root doesn't disappear */
449         down_read(&fs_info->commit_root_sem);
450
451 next:
452         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
453         if (ret < 0)
454                 goto err;
455
456         leaf = path->nodes[0];
457         nritems = btrfs_header_nritems(leaf);
458
459         while (1) {
460                 if (btrfs_fs_closing(fs_info) > 1) {
461                         last = (u64)-1;
462                         break;
463                 }
464
465                 if (path->slots[0] < nritems) {
466                         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
467                 } else {
468                         ret = find_next_key(path, 0, &key);
469                         if (ret)
470                                 break;
471
472                         if (need_resched() ||
473                             rwsem_is_contended(&fs_info->commit_root_sem)) {
474                                 if (wakeup)
475                                         caching_ctl->progress = last;
476                                 btrfs_release_path(path);
477                                 up_read(&fs_info->commit_root_sem);
478                                 mutex_unlock(&caching_ctl->mutex);
479                                 cond_resched();
480                                 goto again;
481                         }
482
483                         ret = btrfs_next_leaf(extent_root, path);
484                         if (ret < 0)
485                                 goto err;
486                         if (ret)
487                                 break;
488                         leaf = path->nodes[0];
489                         nritems = btrfs_header_nritems(leaf);
490                         continue;
491                 }
492
493                 if (key.objectid < last) {
494                         key.objectid = last;
495                         key.offset = 0;
496                         key.type = BTRFS_EXTENT_ITEM_KEY;
497
498                         if (wakeup)
499                                 caching_ctl->progress = last;
500                         btrfs_release_path(path);
501                         goto next;
502                 }
503
504                 if (key.objectid < block_group->key.objectid) {
505                         path->slots[0]++;
506                         continue;
507                 }
508
509                 if (key.objectid >= block_group->key.objectid +
510                     block_group->key.offset)
511                         break;
512
513                 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
514                     key.type == BTRFS_METADATA_ITEM_KEY) {
515                         total_found += add_new_free_space(block_group,
516                                                           fs_info, last,
517                                                           key.objectid);
518                         if (key.type == BTRFS_METADATA_ITEM_KEY)
519                                 last = key.objectid +
520                                         fs_info->tree_root->nodesize;
521                         else
522                                 last = key.objectid + key.offset;
523
524                         if (total_found > (1024 * 1024 * 2)) {
525                                 total_found = 0;
526                                 if (wakeup)
527                                         wake_up(&caching_ctl->wait);
528                         }
529                 }
530                 path->slots[0]++;
531         }
532         ret = 0;
533
534         total_found += add_new_free_space(block_group, fs_info, last,
535                                           block_group->key.objectid +
536                                           block_group->key.offset);
537         spin_lock(&block_group->lock);
538         block_group->caching_ctl = NULL;
539         block_group->cached = BTRFS_CACHE_FINISHED;
540         spin_unlock(&block_group->lock);
541
542 #ifdef CONFIG_BTRFS_DEBUG
543         if (btrfs_should_fragment_free_space(extent_root, block_group)) {
544                 u64 bytes_used;
545
546                 spin_lock(&block_group->space_info->lock);
547                 spin_lock(&block_group->lock);
548                 bytes_used = block_group->key.offset -
549                         btrfs_block_group_used(&block_group->item);
550                 block_group->space_info->bytes_used += bytes_used >> 1;
551                 spin_unlock(&block_group->lock);
552                 spin_unlock(&block_group->space_info->lock);
553                 fragment_free_space(extent_root, block_group);
554         }
555 #endif
556
557         caching_ctl->progress = (u64)-1;
558 err:
559         btrfs_free_path(path);
560         up_read(&fs_info->commit_root_sem);
561
562         free_excluded_extents(extent_root, block_group);
563
564         mutex_unlock(&caching_ctl->mutex);
565 out:
566         if (ret) {
567                 spin_lock(&block_group->lock);
568                 block_group->caching_ctl = NULL;
569                 block_group->cached = BTRFS_CACHE_ERROR;
570                 spin_unlock(&block_group->lock);
571         }
572         wake_up(&caching_ctl->wait);
573
574         put_caching_control(caching_ctl);
575         btrfs_put_block_group(block_group);
576 }
577
578 static int cache_block_group(struct btrfs_block_group_cache *cache,
579                              int load_cache_only)
580 {
581         DEFINE_WAIT(wait);
582         struct btrfs_fs_info *fs_info = cache->fs_info;
583         struct btrfs_caching_control *caching_ctl;
584         int ret = 0;
585
586         caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
587         if (!caching_ctl)
588                 return -ENOMEM;
589
590         INIT_LIST_HEAD(&caching_ctl->list);
591         mutex_init(&caching_ctl->mutex);
592         init_waitqueue_head(&caching_ctl->wait);
593         caching_ctl->block_group = cache;
594         caching_ctl->progress = cache->key.objectid;
595         atomic_set(&caching_ctl->count, 1);
596         btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
597                         caching_thread, NULL, NULL);
598
599         spin_lock(&cache->lock);
600         /*
601          * This should be a rare occasion, but this could happen I think in the
602          * case where one thread starts to load the space cache info, and then
603          * some other thread starts a transaction commit which tries to do an
604          * allocation while the other thread is still loading the space cache
605          * info.  The previous loop should have kept us from choosing this block
606          * group, but if we've moved to the state where we will wait on caching
607          * block groups we need to first check if we're doing a fast load here,
608          * so we can wait for it to finish, otherwise we could end up allocating
609          * from a block group who's cache gets evicted for one reason or
610          * another.
611          */
612         while (cache->cached == BTRFS_CACHE_FAST) {
613                 struct btrfs_caching_control *ctl;
614
615                 ctl = cache->caching_ctl;
616                 atomic_inc(&ctl->count);
617                 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
618                 spin_unlock(&cache->lock);
619
620                 schedule();
621
622                 finish_wait(&ctl->wait, &wait);
623                 put_caching_control(ctl);
624                 spin_lock(&cache->lock);
625         }
626
627         if (cache->cached != BTRFS_CACHE_NO) {
628                 spin_unlock(&cache->lock);
629                 kfree(caching_ctl);
630                 return 0;
631         }
632         WARN_ON(cache->caching_ctl);
633         cache->caching_ctl = caching_ctl;
634         cache->cached = BTRFS_CACHE_FAST;
635         spin_unlock(&cache->lock);
636
637         if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
638                 mutex_lock(&caching_ctl->mutex);
639                 ret = load_free_space_cache(fs_info, cache);
640
641                 spin_lock(&cache->lock);
642                 if (ret == 1) {
643                         cache->caching_ctl = NULL;
644                         cache->cached = BTRFS_CACHE_FINISHED;
645                         cache->last_byte_to_unpin = (u64)-1;
646                         caching_ctl->progress = (u64)-1;
647                 } else {
648                         if (load_cache_only) {
649                                 cache->caching_ctl = NULL;
650                                 cache->cached = BTRFS_CACHE_NO;
651                         } else {
652                                 cache->cached = BTRFS_CACHE_STARTED;
653                                 cache->has_caching_ctl = 1;
654                         }
655                 }
656                 spin_unlock(&cache->lock);
657 #ifdef CONFIG_BTRFS_DEBUG
658                 if (ret == 1 &&
659                     btrfs_should_fragment_free_space(fs_info->extent_root,
660                                                      cache)) {
661                         u64 bytes_used;
662
663                         spin_lock(&cache->space_info->lock);
664                         spin_lock(&cache->lock);
665                         bytes_used = cache->key.offset -
666                                 btrfs_block_group_used(&cache->item);
667                         cache->space_info->bytes_used += bytes_used >> 1;
668                         spin_unlock(&cache->lock);
669                         spin_unlock(&cache->space_info->lock);
670                         fragment_free_space(fs_info->extent_root, cache);
671                 }
672 #endif
673                 mutex_unlock(&caching_ctl->mutex);
674
675                 wake_up(&caching_ctl->wait);
676                 if (ret == 1) {
677                         put_caching_control(caching_ctl);
678                         free_excluded_extents(fs_info->extent_root, cache);
679                         return 0;
680                 }
681         } else {
682                 /*
683                  * We are not going to do the fast caching, set cached to the
684                  * appropriate value and wakeup any waiters.
685                  */
686                 spin_lock(&cache->lock);
687                 if (load_cache_only) {
688                         cache->caching_ctl = NULL;
689                         cache->cached = BTRFS_CACHE_NO;
690                 } else {
691                         cache->cached = BTRFS_CACHE_STARTED;
692                         cache->has_caching_ctl = 1;
693                 }
694                 spin_unlock(&cache->lock);
695                 wake_up(&caching_ctl->wait);
696         }
697
698         if (load_cache_only) {
699                 put_caching_control(caching_ctl);
700                 return 0;
701         }
702
703         down_write(&fs_info->commit_root_sem);
704         atomic_inc(&caching_ctl->count);
705         list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
706         up_write(&fs_info->commit_root_sem);
707
708         btrfs_get_block_group(cache);
709
710         btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
711
712         return ret;
713 }
714
715 /*
716  * return the block group that starts at or after bytenr
717  */
718 static struct btrfs_block_group_cache *
719 btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
720 {
721         struct btrfs_block_group_cache *cache;
722
723         cache = block_group_cache_tree_search(info, bytenr, 0);
724
725         return cache;
726 }
727
728 /*
729  * return the block group that contains the given bytenr
730  */
731 struct btrfs_block_group_cache *btrfs_lookup_block_group(
732                                                  struct btrfs_fs_info *info,
733                                                  u64 bytenr)
734 {
735         struct btrfs_block_group_cache *cache;
736
737         cache = block_group_cache_tree_search(info, bytenr, 1);
738
739         return cache;
740 }
741
742 static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
743                                                   u64 flags)
744 {
745         struct list_head *head = &info->space_info;
746         struct btrfs_space_info *found;
747
748         flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
749
750         rcu_read_lock();
751         list_for_each_entry_rcu(found, head, list) {
752                 if (found->flags & flags) {
753                         rcu_read_unlock();
754                         return found;
755                 }
756         }
757         rcu_read_unlock();
758         return NULL;
759 }
760
761 /*
762  * after adding space to the filesystem, we need to clear the full flags
763  * on all the space infos.
764  */
765 void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
766 {
767         struct list_head *head = &info->space_info;
768         struct btrfs_space_info *found;
769
770         rcu_read_lock();
771         list_for_each_entry_rcu(found, head, list)
772                 found->full = 0;
773         rcu_read_unlock();
774 }
775
776 /* simple helper to search for an existing data extent at a given offset */
777 int btrfs_lookup_data_extent(struct btrfs_root *root, u64 start, u64 len)
778 {
779         int ret;
780         struct btrfs_key key;
781         struct btrfs_path *path;
782
783         path = btrfs_alloc_path();
784         if (!path)
785                 return -ENOMEM;
786
787         key.objectid = start;
788         key.offset = len;
789         key.type = BTRFS_EXTENT_ITEM_KEY;
790         ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
791                                 0, 0);
792         btrfs_free_path(path);
793         return ret;
794 }
795
796 /*
797  * helper function to lookup reference count and flags of a tree block.
798  *
799  * the head node for delayed ref is used to store the sum of all the
800  * reference count modifications queued up in the rbtree. the head
801  * node may also store the extent flags to set. This way you can check
802  * to see what the reference count and extent flags would be if all of
803  * the delayed refs are not processed.
804  */
805 int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
806                              struct btrfs_root *root, u64 bytenr,
807                              u64 offset, int metadata, u64 *refs, u64 *flags)
808 {
809         struct btrfs_delayed_ref_head *head;
810         struct btrfs_delayed_ref_root *delayed_refs;
811         struct btrfs_path *path;
812         struct btrfs_extent_item *ei;
813         struct extent_buffer *leaf;
814         struct btrfs_key key;
815         u32 item_size;
816         u64 num_refs;
817         u64 extent_flags;
818         int ret;
819
820         /*
821          * If we don't have skinny metadata, don't bother doing anything
822          * different
823          */
824         if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA)) {
825                 offset = root->nodesize;
826                 metadata = 0;
827         }
828
829         path = btrfs_alloc_path();
830         if (!path)
831                 return -ENOMEM;
832
833         if (!trans) {
834                 path->skip_locking = 1;
835                 path->search_commit_root = 1;
836         }
837
838 search_again:
839         key.objectid = bytenr;
840         key.offset = offset;
841         if (metadata)
842                 key.type = BTRFS_METADATA_ITEM_KEY;
843         else
844                 key.type = BTRFS_EXTENT_ITEM_KEY;
845
846         ret = btrfs_search_slot(trans, root->fs_info->extent_root,
847                                 &key, path, 0, 0);
848         if (ret < 0)
849                 goto out_free;
850
851         if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
852                 if (path->slots[0]) {
853                         path->slots[0]--;
854                         btrfs_item_key_to_cpu(path->nodes[0], &key,
855                                               path->slots[0]);
856                         if (key.objectid == bytenr &&
857                             key.type == BTRFS_EXTENT_ITEM_KEY &&
858                             key.offset == root->nodesize)
859                                 ret = 0;
860                 }
861         }
862
863         if (ret == 0) {
864                 leaf = path->nodes[0];
865                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
866                 if (item_size >= sizeof(*ei)) {
867                         ei = btrfs_item_ptr(leaf, path->slots[0],
868                                             struct btrfs_extent_item);
869                         num_refs = btrfs_extent_refs(leaf, ei);
870                         extent_flags = btrfs_extent_flags(leaf, ei);
871                 } else {
872 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
873                         struct btrfs_extent_item_v0 *ei0;
874                         BUG_ON(item_size != sizeof(*ei0));
875                         ei0 = btrfs_item_ptr(leaf, path->slots[0],
876                                              struct btrfs_extent_item_v0);
877                         num_refs = btrfs_extent_refs_v0(leaf, ei0);
878                         /* FIXME: this isn't correct for data */
879                         extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
880 #else
881                         BUG();
882 #endif
883                 }
884                 BUG_ON(num_refs == 0);
885         } else {
886                 num_refs = 0;
887                 extent_flags = 0;
888                 ret = 0;
889         }
890
891         if (!trans)
892                 goto out;
893
894         delayed_refs = &trans->transaction->delayed_refs;
895         spin_lock(&delayed_refs->lock);
896         head = btrfs_find_delayed_ref_head(trans, bytenr);
897         if (head) {
898                 if (!mutex_trylock(&head->mutex)) {
899                         atomic_inc(&head->node.refs);
900                         spin_unlock(&delayed_refs->lock);
901
902                         btrfs_release_path(path);
903
904                         /*
905                          * Mutex was contended, block until it's released and try
906                          * again
907                          */
908                         mutex_lock(&head->mutex);
909                         mutex_unlock(&head->mutex);
910                         btrfs_put_delayed_ref(&head->node);
911                         goto search_again;
912                 }
913                 spin_lock(&head->lock);
914                 if (head->extent_op && head->extent_op->update_flags)
915                         extent_flags |= head->extent_op->flags_to_set;
916                 else
917                         BUG_ON(num_refs == 0);
918
919                 num_refs += head->node.ref_mod;
920                 spin_unlock(&head->lock);
921                 mutex_unlock(&head->mutex);
922         }
923         spin_unlock(&delayed_refs->lock);
924 out:
925         WARN_ON(num_refs == 0);
926         if (refs)
927                 *refs = num_refs;
928         if (flags)
929                 *flags = extent_flags;
930 out_free:
931         btrfs_free_path(path);
932         return ret;
933 }
934
935 /*
936  * Back reference rules.  Back refs have three main goals:
937  *
938  * 1) differentiate between all holders of references to an extent so that
939  *    when a reference is dropped we can make sure it was a valid reference
940  *    before freeing the extent.
941  *
942  * 2) Provide enough information to quickly find the holders of an extent
943  *    if we notice a given block is corrupted or bad.
944  *
945  * 3) Make it easy to migrate blocks for FS shrinking or storage pool
946  *    maintenance.  This is actually the same as #2, but with a slightly
947  *    different use case.
948  *
949  * There are two kinds of back refs. The implicit back refs is optimized
950  * for pointers in non-shared tree blocks. For a given pointer in a block,
951  * back refs of this kind provide information about the block's owner tree
952  * and the pointer's key. These information allow us to find the block by
953  * b-tree searching. The full back refs is for pointers in tree blocks not
954  * referenced by their owner trees. The location of tree block is recorded
955  * in the back refs. Actually the full back refs is generic, and can be
956  * used in all cases the implicit back refs is used. The major shortcoming
957  * of the full back refs is its overhead. Every time a tree block gets
958  * COWed, we have to update back refs entry for all pointers in it.
959  *
960  * For a newly allocated tree block, we use implicit back refs for
961  * pointers in it. This means most tree related operations only involve
962  * implicit back refs. For a tree block created in old transaction, the
963  * only way to drop a reference to it is COW it. So we can detect the
964  * event that tree block loses its owner tree's reference and do the
965  * back refs conversion.
966  *
967  * When a tree block is COW'd through a tree, there are four cases:
968  *
969  * The reference count of the block is one and the tree is the block's
970  * owner tree. Nothing to do in this case.
971  *
972  * The reference count of the block is one and the tree is not the
973  * block's owner tree. In this case, full back refs is used for pointers
974  * in the block. Remove these full back refs, add implicit back refs for
975  * every pointers in the new block.
976  *
977  * The reference count of the block is greater than one and the tree is
978  * the block's owner tree. In this case, implicit back refs is used for
979  * pointers in the block. Add full back refs for every pointers in the
980  * block, increase lower level extents' reference counts. The original
981  * implicit back refs are entailed to the new block.
982  *
983  * The reference count of the block is greater than one and the tree is
984  * not the block's owner tree. Add implicit back refs for every pointer in
985  * the new block, increase lower level extents' reference count.
986  *
987  * Back Reference Key composing:
988  *
989  * The key objectid corresponds to the first byte in the extent,
990  * The key type is used to differentiate between types of back refs.
991  * There are different meanings of the key offset for different types
992  * of back refs.
993  *
994  * File extents can be referenced by:
995  *
996  * - multiple snapshots, subvolumes, or different generations in one subvol
997  * - different files inside a single subvolume
998  * - different offsets inside a file (bookend extents in file.c)
999  *
1000  * The extent ref structure for the implicit back refs has fields for:
1001  *
1002  * - Objectid of the subvolume root
1003  * - objectid of the file holding the reference
1004  * - original offset in the file
1005  * - how many bookend extents
1006  *
1007  * The key offset for the implicit back refs is hash of the first
1008  * three fields.
1009  *
1010  * The extent ref structure for the full back refs has field for:
1011  *
1012  * - number of pointers in the tree leaf
1013  *
1014  * The key offset for the implicit back refs is the first byte of
1015  * the tree leaf
1016  *
1017  * When a file extent is allocated, The implicit back refs is used.
1018  * the fields are filled in:
1019  *
1020  *     (root_key.objectid, inode objectid, offset in file, 1)
1021  *
1022  * When a file extent is removed file truncation, we find the
1023  * corresponding implicit back refs and check the following fields:
1024  *
1025  *     (btrfs_header_owner(leaf), inode objectid, offset in file)
1026  *
1027  * Btree extents can be referenced by:
1028  *
1029  * - Different subvolumes
1030  *
1031  * Both the implicit back refs and the full back refs for tree blocks
1032  * only consist of key. The key offset for the implicit back refs is
1033  * objectid of block's owner tree. The key offset for the full back refs
1034  * is the first byte of parent block.
1035  *
1036  * When implicit back refs is used, information about the lowest key and
1037  * level of the tree block are required. These information are stored in
1038  * tree block info structure.
1039  */
1040
1041 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1042 static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
1043                                   struct btrfs_root *root,
1044                                   struct btrfs_path *path,
1045                                   u64 owner, u32 extra_size)
1046 {
1047         struct btrfs_extent_item *item;
1048         struct btrfs_extent_item_v0 *ei0;
1049         struct btrfs_extent_ref_v0 *ref0;
1050         struct btrfs_tree_block_info *bi;
1051         struct extent_buffer *leaf;
1052         struct btrfs_key key;
1053         struct btrfs_key found_key;
1054         u32 new_size = sizeof(*item);
1055         u64 refs;
1056         int ret;
1057
1058         leaf = path->nodes[0];
1059         BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1060
1061         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1062         ei0 = btrfs_item_ptr(leaf, path->slots[0],
1063                              struct btrfs_extent_item_v0);
1064         refs = btrfs_extent_refs_v0(leaf, ei0);
1065
1066         if (owner == (u64)-1) {
1067                 while (1) {
1068                         if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1069                                 ret = btrfs_next_leaf(root, path);
1070                                 if (ret < 0)
1071                                         return ret;
1072                                 BUG_ON(ret > 0); /* Corruption */
1073                                 leaf = path->nodes[0];
1074                         }
1075                         btrfs_item_key_to_cpu(leaf, &found_key,
1076                                               path->slots[0]);
1077                         BUG_ON(key.objectid != found_key.objectid);
1078                         if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1079                                 path->slots[0]++;
1080                                 continue;
1081                         }
1082                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1083                                               struct btrfs_extent_ref_v0);
1084                         owner = btrfs_ref_objectid_v0(leaf, ref0);
1085                         break;
1086                 }
1087         }
1088         btrfs_release_path(path);
1089
1090         if (owner < BTRFS_FIRST_FREE_OBJECTID)
1091                 new_size += sizeof(*bi);
1092
1093         new_size -= sizeof(*ei0);
1094         ret = btrfs_search_slot(trans, root, &key, path,
1095                                 new_size + extra_size, 1);
1096         if (ret < 0)
1097                 return ret;
1098         BUG_ON(ret); /* Corruption */
1099
1100         btrfs_extend_item(root, path, new_size);
1101
1102         leaf = path->nodes[0];
1103         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1104         btrfs_set_extent_refs(leaf, item, refs);
1105         /* FIXME: get real generation */
1106         btrfs_set_extent_generation(leaf, item, 0);
1107         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1108                 btrfs_set_extent_flags(leaf, item,
1109                                        BTRFS_EXTENT_FLAG_TREE_BLOCK |
1110                                        BTRFS_BLOCK_FLAG_FULL_BACKREF);
1111                 bi = (struct btrfs_tree_block_info *)(item + 1);
1112                 /* FIXME: get first key of the block */
1113                 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
1114                 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1115         } else {
1116                 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1117         }
1118         btrfs_mark_buffer_dirty(leaf);
1119         return 0;
1120 }
1121 #endif
1122
1123 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1124 {
1125         u32 high_crc = ~(u32)0;
1126         u32 low_crc = ~(u32)0;
1127         __le64 lenum;
1128
1129         lenum = cpu_to_le64(root_objectid);
1130         high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1131         lenum = cpu_to_le64(owner);
1132         low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1133         lenum = cpu_to_le64(offset);
1134         low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1135
1136         return ((u64)high_crc << 31) ^ (u64)low_crc;
1137 }
1138
1139 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1140                                      struct btrfs_extent_data_ref *ref)
1141 {
1142         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1143                                     btrfs_extent_data_ref_objectid(leaf, ref),
1144                                     btrfs_extent_data_ref_offset(leaf, ref));
1145 }
1146
1147 static int match_extent_data_ref(struct extent_buffer *leaf,
1148                                  struct btrfs_extent_data_ref *ref,
1149                                  u64 root_objectid, u64 owner, u64 offset)
1150 {
1151         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1152             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1153             btrfs_extent_data_ref_offset(leaf, ref) != offset)
1154                 return 0;
1155         return 1;
1156 }
1157
1158 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1159                                            struct btrfs_root *root,
1160                                            struct btrfs_path *path,
1161                                            u64 bytenr, u64 parent,
1162                                            u64 root_objectid,
1163                                            u64 owner, u64 offset)
1164 {
1165         struct btrfs_key key;
1166         struct btrfs_extent_data_ref *ref;
1167         struct extent_buffer *leaf;
1168         u32 nritems;
1169         int ret;
1170         int recow;
1171         int err = -ENOENT;
1172
1173         key.objectid = bytenr;
1174         if (parent) {
1175                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1176                 key.offset = parent;
1177         } else {
1178                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1179                 key.offset = hash_extent_data_ref(root_objectid,
1180                                                   owner, offset);
1181         }
1182 again:
1183         recow = 0;
1184         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1185         if (ret < 0) {
1186                 err = ret;
1187                 goto fail;
1188         }
1189
1190         if (parent) {
1191                 if (!ret)
1192                         return 0;
1193 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1194                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1195                 btrfs_release_path(path);
1196                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1197                 if (ret < 0) {
1198                         err = ret;
1199                         goto fail;
1200                 }
1201                 if (!ret)
1202                         return 0;
1203 #endif
1204                 goto fail;
1205         }
1206
1207         leaf = path->nodes[0];
1208         nritems = btrfs_header_nritems(leaf);
1209         while (1) {
1210                 if (path->slots[0] >= nritems) {
1211                         ret = btrfs_next_leaf(root, path);
1212                         if (ret < 0)
1213                                 err = ret;
1214                         if (ret)
1215                                 goto fail;
1216
1217                         leaf = path->nodes[0];
1218                         nritems = btrfs_header_nritems(leaf);
1219                         recow = 1;
1220                 }
1221
1222                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1223                 if (key.objectid != bytenr ||
1224                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1225                         goto fail;
1226
1227                 ref = btrfs_item_ptr(leaf, path->slots[0],
1228                                      struct btrfs_extent_data_ref);
1229
1230                 if (match_extent_data_ref(leaf, ref, root_objectid,
1231                                           owner, offset)) {
1232                         if (recow) {
1233                                 btrfs_release_path(path);
1234                                 goto again;
1235                         }
1236                         err = 0;
1237                         break;
1238                 }
1239                 path->slots[0]++;
1240         }
1241 fail:
1242         return err;
1243 }
1244
1245 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1246                                            struct btrfs_root *root,
1247                                            struct btrfs_path *path,
1248                                            u64 bytenr, u64 parent,
1249                                            u64 root_objectid, u64 owner,
1250                                            u64 offset, int refs_to_add)
1251 {
1252         struct btrfs_key key;
1253         struct extent_buffer *leaf;
1254         u32 size;
1255         u32 num_refs;
1256         int ret;
1257
1258         key.objectid = bytenr;
1259         if (parent) {
1260                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1261                 key.offset = parent;
1262                 size = sizeof(struct btrfs_shared_data_ref);
1263         } else {
1264                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1265                 key.offset = hash_extent_data_ref(root_objectid,
1266                                                   owner, offset);
1267                 size = sizeof(struct btrfs_extent_data_ref);
1268         }
1269
1270         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1271         if (ret && ret != -EEXIST)
1272                 goto fail;
1273
1274         leaf = path->nodes[0];
1275         if (parent) {
1276                 struct btrfs_shared_data_ref *ref;
1277                 ref = btrfs_item_ptr(leaf, path->slots[0],
1278                                      struct btrfs_shared_data_ref);
1279                 if (ret == 0) {
1280                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1281                 } else {
1282                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1283                         num_refs += refs_to_add;
1284                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1285                 }
1286         } else {
1287                 struct btrfs_extent_data_ref *ref;
1288                 while (ret == -EEXIST) {
1289                         ref = btrfs_item_ptr(leaf, path->slots[0],
1290                                              struct btrfs_extent_data_ref);
1291                         if (match_extent_data_ref(leaf, ref, root_objectid,
1292                                                   owner, offset))
1293                                 break;
1294                         btrfs_release_path(path);
1295                         key.offset++;
1296                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1297                                                       size);
1298                         if (ret && ret != -EEXIST)
1299                                 goto fail;
1300
1301                         leaf = path->nodes[0];
1302                 }
1303                 ref = btrfs_item_ptr(leaf, path->slots[0],
1304                                      struct btrfs_extent_data_ref);
1305                 if (ret == 0) {
1306                         btrfs_set_extent_data_ref_root(leaf, ref,
1307                                                        root_objectid);
1308                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1309                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1310                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1311                 } else {
1312                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1313                         num_refs += refs_to_add;
1314                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1315                 }
1316         }
1317         btrfs_mark_buffer_dirty(leaf);
1318         ret = 0;
1319 fail:
1320         btrfs_release_path(path);
1321         return ret;
1322 }
1323
1324 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1325                                            struct btrfs_root *root,
1326                                            struct btrfs_path *path,
1327                                            int refs_to_drop, int *last_ref)
1328 {
1329         struct btrfs_key key;
1330         struct btrfs_extent_data_ref *ref1 = NULL;
1331         struct btrfs_shared_data_ref *ref2 = NULL;
1332         struct extent_buffer *leaf;
1333         u32 num_refs = 0;
1334         int ret = 0;
1335
1336         leaf = path->nodes[0];
1337         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1338
1339         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1340                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1341                                       struct btrfs_extent_data_ref);
1342                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1343         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1344                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1345                                       struct btrfs_shared_data_ref);
1346                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1347 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1348         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1349                 struct btrfs_extent_ref_v0 *ref0;
1350                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1351                                       struct btrfs_extent_ref_v0);
1352                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1353 #endif
1354         } else {
1355                 BUG();
1356         }
1357
1358         BUG_ON(num_refs < refs_to_drop);
1359         num_refs -= refs_to_drop;
1360
1361         if (num_refs == 0) {
1362                 ret = btrfs_del_item(trans, root, path);
1363                 *last_ref = 1;
1364         } else {
1365                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1366                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1367                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1368                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1369 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1370                 else {
1371                         struct btrfs_extent_ref_v0 *ref0;
1372                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1373                                         struct btrfs_extent_ref_v0);
1374                         btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1375                 }
1376 #endif
1377                 btrfs_mark_buffer_dirty(leaf);
1378         }
1379         return ret;
1380 }
1381
1382 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1383                                           struct btrfs_extent_inline_ref *iref)
1384 {
1385         struct btrfs_key key;
1386         struct extent_buffer *leaf;
1387         struct btrfs_extent_data_ref *ref1;
1388         struct btrfs_shared_data_ref *ref2;
1389         u32 num_refs = 0;
1390
1391         leaf = path->nodes[0];
1392         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1393         if (iref) {
1394                 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1395                     BTRFS_EXTENT_DATA_REF_KEY) {
1396                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1397                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1398                 } else {
1399                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1400                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1401                 }
1402         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1403                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1404                                       struct btrfs_extent_data_ref);
1405                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1406         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1407                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1408                                       struct btrfs_shared_data_ref);
1409                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1410 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1411         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1412                 struct btrfs_extent_ref_v0 *ref0;
1413                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1414                                       struct btrfs_extent_ref_v0);
1415                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1416 #endif
1417         } else {
1418                 WARN_ON(1);
1419         }
1420         return num_refs;
1421 }
1422
1423 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1424                                           struct btrfs_root *root,
1425                                           struct btrfs_path *path,
1426                                           u64 bytenr, u64 parent,
1427                                           u64 root_objectid)
1428 {
1429         struct btrfs_key key;
1430         int ret;
1431
1432         key.objectid = bytenr;
1433         if (parent) {
1434                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1435                 key.offset = parent;
1436         } else {
1437                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1438                 key.offset = root_objectid;
1439         }
1440
1441         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1442         if (ret > 0)
1443                 ret = -ENOENT;
1444 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1445         if (ret == -ENOENT && parent) {
1446                 btrfs_release_path(path);
1447                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1448                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1449                 if (ret > 0)
1450                         ret = -ENOENT;
1451         }
1452 #endif
1453         return ret;
1454 }
1455
1456 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1457                                           struct btrfs_root *root,
1458                                           struct btrfs_path *path,
1459                                           u64 bytenr, u64 parent,
1460                                           u64 root_objectid)
1461 {
1462         struct btrfs_key key;
1463         int ret;
1464
1465         key.objectid = bytenr;
1466         if (parent) {
1467                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1468                 key.offset = parent;
1469         } else {
1470                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1471                 key.offset = root_objectid;
1472         }
1473
1474         ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
1475         btrfs_release_path(path);
1476         return ret;
1477 }
1478
1479 static inline int extent_ref_type(u64 parent, u64 owner)
1480 {
1481         int type;
1482         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1483                 if (parent > 0)
1484                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1485                 else
1486                         type = BTRFS_TREE_BLOCK_REF_KEY;
1487         } else {
1488                 if (parent > 0)
1489                         type = BTRFS_SHARED_DATA_REF_KEY;
1490                 else
1491                         type = BTRFS_EXTENT_DATA_REF_KEY;
1492         }
1493         return type;
1494 }
1495
1496 static int find_next_key(struct btrfs_path *path, int level,
1497                          struct btrfs_key *key)
1498
1499 {
1500         for (; level < BTRFS_MAX_LEVEL; level++) {
1501                 if (!path->nodes[level])
1502                         break;
1503                 if (path->slots[level] + 1 >=
1504                     btrfs_header_nritems(path->nodes[level]))
1505                         continue;
1506                 if (level == 0)
1507                         btrfs_item_key_to_cpu(path->nodes[level], key,
1508                                               path->slots[level] + 1);
1509                 else
1510                         btrfs_node_key_to_cpu(path->nodes[level], key,
1511                                               path->slots[level] + 1);
1512                 return 0;
1513         }
1514         return 1;
1515 }
1516
1517 /*
1518  * look for inline back ref. if back ref is found, *ref_ret is set
1519  * to the address of inline back ref, and 0 is returned.
1520  *
1521  * if back ref isn't found, *ref_ret is set to the address where it
1522  * should be inserted, and -ENOENT is returned.
1523  *
1524  * if insert is true and there are too many inline back refs, the path
1525  * points to the extent item, and -EAGAIN is returned.
1526  *
1527  * NOTE: inline back refs are ordered in the same way that back ref
1528  *       items in the tree are ordered.
1529  */
1530 static noinline_for_stack
1531 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1532                                  struct btrfs_root *root,
1533                                  struct btrfs_path *path,
1534                                  struct btrfs_extent_inline_ref **ref_ret,
1535                                  u64 bytenr, u64 num_bytes,
1536                                  u64 parent, u64 root_objectid,
1537                                  u64 owner, u64 offset, int insert)
1538 {
1539         struct btrfs_key key;
1540         struct extent_buffer *leaf;
1541         struct btrfs_extent_item *ei;
1542         struct btrfs_extent_inline_ref *iref;
1543         u64 flags;
1544         u64 item_size;
1545         unsigned long ptr;
1546         unsigned long end;
1547         int extra_size;
1548         int type;
1549         int want;
1550         int ret;
1551         int err = 0;
1552         bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
1553                                                  SKINNY_METADATA);
1554
1555         key.objectid = bytenr;
1556         key.type = BTRFS_EXTENT_ITEM_KEY;
1557         key.offset = num_bytes;
1558
1559         want = extent_ref_type(parent, owner);
1560         if (insert) {
1561                 extra_size = btrfs_extent_inline_ref_size(want);
1562                 path->keep_locks = 1;
1563         } else
1564                 extra_size = -1;
1565
1566         /*
1567          * Owner is our parent level, so we can just add one to get the level
1568          * for the block we are interested in.
1569          */
1570         if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1571                 key.type = BTRFS_METADATA_ITEM_KEY;
1572                 key.offset = owner;
1573         }
1574
1575 again:
1576         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1577         if (ret < 0) {
1578                 err = ret;
1579                 goto out;
1580         }
1581
1582         /*
1583          * We may be a newly converted file system which still has the old fat
1584          * extent entries for metadata, so try and see if we have one of those.
1585          */
1586         if (ret > 0 && skinny_metadata) {
1587                 skinny_metadata = false;
1588                 if (path->slots[0]) {
1589                         path->slots[0]--;
1590                         btrfs_item_key_to_cpu(path->nodes[0], &key,
1591                                               path->slots[0]);
1592                         if (key.objectid == bytenr &&
1593                             key.type == BTRFS_EXTENT_ITEM_KEY &&
1594                             key.offset == num_bytes)
1595                                 ret = 0;
1596                 }
1597                 if (ret) {
1598                         key.objectid = bytenr;
1599                         key.type = BTRFS_EXTENT_ITEM_KEY;
1600                         key.offset = num_bytes;
1601                         btrfs_release_path(path);
1602                         goto again;
1603                 }
1604         }
1605
1606         if (ret && !insert) {
1607                 err = -ENOENT;
1608                 goto out;
1609         } else if (WARN_ON(ret)) {
1610                 err = -EIO;
1611                 goto out;
1612         }
1613
1614         leaf = path->nodes[0];
1615         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1616 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1617         if (item_size < sizeof(*ei)) {
1618                 if (!insert) {
1619                         err = -ENOENT;
1620                         goto out;
1621                 }
1622                 ret = convert_extent_item_v0(trans, root, path, owner,
1623                                              extra_size);
1624                 if (ret < 0) {
1625                         err = ret;
1626                         goto out;
1627                 }
1628                 leaf = path->nodes[0];
1629                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1630         }
1631 #endif
1632         BUG_ON(item_size < sizeof(*ei));
1633
1634         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1635         flags = btrfs_extent_flags(leaf, ei);
1636
1637         ptr = (unsigned long)(ei + 1);
1638         end = (unsigned long)ei + item_size;
1639
1640         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1641                 ptr += sizeof(struct btrfs_tree_block_info);
1642                 BUG_ON(ptr > end);
1643         }
1644
1645         err = -ENOENT;
1646         while (1) {
1647                 if (ptr >= end) {
1648                         WARN_ON(ptr > end);
1649                         break;
1650                 }
1651                 iref = (struct btrfs_extent_inline_ref *)ptr;
1652                 type = btrfs_extent_inline_ref_type(leaf, iref);
1653                 if (want < type)
1654                         break;
1655                 if (want > type) {
1656                         ptr += btrfs_extent_inline_ref_size(type);
1657                         continue;
1658                 }
1659
1660                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1661                         struct btrfs_extent_data_ref *dref;
1662                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1663                         if (match_extent_data_ref(leaf, dref, root_objectid,
1664                                                   owner, offset)) {
1665                                 err = 0;
1666                                 break;
1667                         }
1668                         if (hash_extent_data_ref_item(leaf, dref) <
1669                             hash_extent_data_ref(root_objectid, owner, offset))
1670                                 break;
1671                 } else {
1672                         u64 ref_offset;
1673                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1674                         if (parent > 0) {
1675                                 if (parent == ref_offset) {
1676                                         err = 0;
1677                                         break;
1678                                 }
1679                                 if (ref_offset < parent)
1680                                         break;
1681                         } else {
1682                                 if (root_objectid == ref_offset) {
1683                                         err = 0;
1684                                         break;
1685                                 }
1686                                 if (ref_offset < root_objectid)
1687                                         break;
1688                         }
1689                 }
1690                 ptr += btrfs_extent_inline_ref_size(type);
1691         }
1692         if (err == -ENOENT && insert) {
1693                 if (item_size + extra_size >=
1694                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1695                         err = -EAGAIN;
1696                         goto out;
1697                 }
1698                 /*
1699                  * To add new inline back ref, we have to make sure
1700                  * there is no corresponding back ref item.
1701                  * For simplicity, we just do not add new inline back
1702                  * ref if there is any kind of item for this block
1703                  */
1704                 if (find_next_key(path, 0, &key) == 0 &&
1705                     key.objectid == bytenr &&
1706                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1707                         err = -EAGAIN;
1708                         goto out;
1709                 }
1710         }
1711         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1712 out:
1713         if (insert) {
1714                 path->keep_locks = 0;
1715                 btrfs_unlock_up_safe(path, 1);
1716         }
1717         return err;
1718 }
1719
1720 /*
1721  * helper to add new inline back ref
1722  */
1723 static noinline_for_stack
1724 void setup_inline_extent_backref(struct btrfs_root *root,
1725                                  struct btrfs_path *path,
1726                                  struct btrfs_extent_inline_ref *iref,
1727                                  u64 parent, u64 root_objectid,
1728                                  u64 owner, u64 offset, int refs_to_add,
1729                                  struct btrfs_delayed_extent_op *extent_op)
1730 {
1731         struct extent_buffer *leaf;
1732         struct btrfs_extent_item *ei;
1733         unsigned long ptr;
1734         unsigned long end;
1735         unsigned long item_offset;
1736         u64 refs;
1737         int size;
1738         int type;
1739
1740         leaf = path->nodes[0];
1741         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1742         item_offset = (unsigned long)iref - (unsigned long)ei;
1743
1744         type = extent_ref_type(parent, owner);
1745         size = btrfs_extent_inline_ref_size(type);
1746
1747         btrfs_extend_item(root, path, size);
1748
1749         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1750         refs = btrfs_extent_refs(leaf, ei);
1751         refs += refs_to_add;
1752         btrfs_set_extent_refs(leaf, ei, refs);
1753         if (extent_op)
1754                 __run_delayed_extent_op(extent_op, leaf, ei);
1755
1756         ptr = (unsigned long)ei + item_offset;
1757         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1758         if (ptr < end - size)
1759                 memmove_extent_buffer(leaf, ptr + size, ptr,
1760                                       end - size - ptr);
1761
1762         iref = (struct btrfs_extent_inline_ref *)ptr;
1763         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1764         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1765                 struct btrfs_extent_data_ref *dref;
1766                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1767                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1768                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1769                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1770                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1771         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1772                 struct btrfs_shared_data_ref *sref;
1773                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1774                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1775                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1776         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1777                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1778         } else {
1779                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1780         }
1781         btrfs_mark_buffer_dirty(leaf);
1782 }
1783
1784 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1785                                  struct btrfs_root *root,
1786                                  struct btrfs_path *path,
1787                                  struct btrfs_extent_inline_ref **ref_ret,
1788                                  u64 bytenr, u64 num_bytes, u64 parent,
1789                                  u64 root_objectid, u64 owner, u64 offset)
1790 {
1791         int ret;
1792
1793         ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1794                                            bytenr, num_bytes, parent,
1795                                            root_objectid, owner, offset, 0);
1796         if (ret != -ENOENT)
1797                 return ret;
1798
1799         btrfs_release_path(path);
1800         *ref_ret = NULL;
1801
1802         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1803                 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1804                                             root_objectid);
1805         } else {
1806                 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1807                                              root_objectid, owner, offset);
1808         }
1809         return ret;
1810 }
1811
1812 /*
1813  * helper to update/remove inline back ref
1814  */
1815 static noinline_for_stack
1816 void update_inline_extent_backref(struct btrfs_root *root,
1817                                   struct btrfs_path *path,
1818                                   struct btrfs_extent_inline_ref *iref,
1819                                   int refs_to_mod,
1820                                   struct btrfs_delayed_extent_op *extent_op,
1821                                   int *last_ref)
1822 {
1823         struct extent_buffer *leaf;
1824         struct btrfs_extent_item *ei;
1825         struct btrfs_extent_data_ref *dref = NULL;
1826         struct btrfs_shared_data_ref *sref = NULL;
1827         unsigned long ptr;
1828         unsigned long end;
1829         u32 item_size;
1830         int size;
1831         int type;
1832         u64 refs;
1833
1834         leaf = path->nodes[0];
1835         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1836         refs = btrfs_extent_refs(leaf, ei);
1837         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1838         refs += refs_to_mod;
1839         btrfs_set_extent_refs(leaf, ei, refs);
1840         if (extent_op)
1841                 __run_delayed_extent_op(extent_op, leaf, ei);
1842
1843         type = btrfs_extent_inline_ref_type(leaf, iref);
1844
1845         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1846                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1847                 refs = btrfs_extent_data_ref_count(leaf, dref);
1848         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1849                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1850                 refs = btrfs_shared_data_ref_count(leaf, sref);
1851         } else {
1852                 refs = 1;
1853                 BUG_ON(refs_to_mod != -1);
1854         }
1855
1856         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1857         refs += refs_to_mod;
1858
1859         if (refs > 0) {
1860                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1861                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1862                 else
1863                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1864         } else {
1865                 *last_ref = 1;
1866                 size =  btrfs_extent_inline_ref_size(type);
1867                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1868                 ptr = (unsigned long)iref;
1869                 end = (unsigned long)ei + item_size;
1870                 if (ptr + size < end)
1871                         memmove_extent_buffer(leaf, ptr, ptr + size,
1872                                               end - ptr - size);
1873                 item_size -= size;
1874                 btrfs_truncate_item(root, path, item_size, 1);
1875         }
1876         btrfs_mark_buffer_dirty(leaf);
1877 }
1878
1879 static noinline_for_stack
1880 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1881                                  struct btrfs_root *root,
1882                                  struct btrfs_path *path,
1883                                  u64 bytenr, u64 num_bytes, u64 parent,
1884                                  u64 root_objectid, u64 owner,
1885                                  u64 offset, int refs_to_add,
1886                                  struct btrfs_delayed_extent_op *extent_op)
1887 {
1888         struct btrfs_extent_inline_ref *iref;
1889         int ret;
1890
1891         ret = lookup_inline_extent_backref(trans, root, path, &iref,
1892                                            bytenr, num_bytes, parent,
1893                                            root_objectid, owner, offset, 1);
1894         if (ret == 0) {
1895                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1896                 update_inline_extent_backref(root, path, iref,
1897                                              refs_to_add, extent_op, NULL);
1898         } else if (ret == -ENOENT) {
1899                 setup_inline_extent_backref(root, path, iref, parent,
1900                                             root_objectid, owner, offset,
1901                                             refs_to_add, extent_op);
1902                 ret = 0;
1903         }
1904         return ret;
1905 }
1906
1907 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1908                                  struct btrfs_root *root,
1909                                  struct btrfs_path *path,
1910                                  u64 bytenr, u64 parent, u64 root_objectid,
1911                                  u64 owner, u64 offset, int refs_to_add)
1912 {
1913         int ret;
1914         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1915                 BUG_ON(refs_to_add != 1);
1916                 ret = insert_tree_block_ref(trans, root, path, bytenr,
1917                                             parent, root_objectid);
1918         } else {
1919                 ret = insert_extent_data_ref(trans, root, path, bytenr,
1920                                              parent, root_objectid,
1921                                              owner, offset, refs_to_add);
1922         }
1923         return ret;
1924 }
1925
1926 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1927                                  struct btrfs_root *root,
1928                                  struct btrfs_path *path,
1929                                  struct btrfs_extent_inline_ref *iref,
1930                                  int refs_to_drop, int is_data, int *last_ref)
1931 {
1932         int ret = 0;
1933
1934         BUG_ON(!is_data && refs_to_drop != 1);
1935         if (iref) {
1936                 update_inline_extent_backref(root, path, iref,
1937                                              -refs_to_drop, NULL, last_ref);
1938         } else if (is_data) {
1939                 ret = remove_extent_data_ref(trans, root, path, refs_to_drop,
1940                                              last_ref);
1941         } else {
1942                 *last_ref = 1;
1943                 ret = btrfs_del_item(trans, root, path);
1944         }
1945         return ret;
1946 }
1947
1948 #define in_range(b, first, len)        ((b) >= (first) && (b) < (first) + (len))
1949 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1950                                u64 *discarded_bytes)
1951 {
1952         int j, ret = 0;
1953         u64 bytes_left, end;
1954         u64 aligned_start = ALIGN(start, 1 << 9);
1955
1956         if (WARN_ON(start != aligned_start)) {
1957                 len -= aligned_start - start;
1958                 len = round_down(len, 1 << 9);
1959                 start = aligned_start;
1960         }
1961
1962         *discarded_bytes = 0;
1963
1964         if (!len)
1965                 return 0;
1966
1967         end = start + len;
1968         bytes_left = len;
1969
1970         /* Skip any superblocks on this device. */
1971         for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1972                 u64 sb_start = btrfs_sb_offset(j);
1973                 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1974                 u64 size = sb_start - start;
1975
1976                 if (!in_range(sb_start, start, bytes_left) &&
1977                     !in_range(sb_end, start, bytes_left) &&
1978                     !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1979                         continue;
1980
1981                 /*
1982                  * Superblock spans beginning of range.  Adjust start and
1983                  * try again.
1984                  */
1985                 if (sb_start <= start) {
1986                         start += sb_end - start;
1987                         if (start > end) {
1988                                 bytes_left = 0;
1989                                 break;
1990                         }
1991                         bytes_left = end - start;
1992                         continue;
1993                 }
1994
1995                 if (size) {
1996                         ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1997                                                    GFP_NOFS, 0);
1998                         if (!ret)
1999                                 *discarded_bytes += size;
2000                         else if (ret != -EOPNOTSUPP)
2001                                 return ret;
2002                 }
2003
2004                 start = sb_end;
2005                 if (start > end) {
2006                         bytes_left = 0;
2007                         break;
2008                 }
2009                 bytes_left = end - start;
2010         }
2011
2012         if (bytes_left) {
2013                 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
2014                                            GFP_NOFS, 0);
2015                 if (!ret)
2016                         *discarded_bytes += bytes_left;
2017         }
2018         return ret;
2019 }
2020
2021 int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
2022                          u64 num_bytes, u64 *actual_bytes)
2023 {
2024         int ret;
2025         u64 discarded_bytes = 0;
2026         struct btrfs_bio *bbio = NULL;
2027
2028
2029         /* Tell the block device(s) that the sectors can be discarded */
2030         ret = btrfs_map_block(root->fs_info, REQ_DISCARD,
2031                               bytenr, &num_bytes, &bbio, 0);
2032         /* Error condition is -ENOMEM */
2033         if (!ret) {
2034                 struct btrfs_bio_stripe *stripe = bbio->stripes;
2035                 int i;
2036
2037
2038                 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2039                         u64 bytes;
2040                         if (!stripe->dev->can_discard)
2041                                 continue;
2042
2043                         ret = btrfs_issue_discard(stripe->dev->bdev,
2044                                                   stripe->physical,
2045                                                   stripe->length,
2046                                                   &bytes);
2047                         if (!ret)
2048                                 discarded_bytes += bytes;
2049                         else if (ret != -EOPNOTSUPP)
2050                                 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2051
2052                         /*
2053                          * Just in case we get back EOPNOTSUPP for some reason,
2054                          * just ignore the return value so we don't screw up
2055                          * people calling discard_extent.
2056                          */
2057                         ret = 0;
2058                 }
2059                 btrfs_put_bbio(bbio);
2060         }
2061
2062         if (actual_bytes)
2063                 *actual_bytes = discarded_bytes;
2064
2065
2066         if (ret == -EOPNOTSUPP)
2067                 ret = 0;
2068         return ret;
2069 }
2070
2071 /* Can return -ENOMEM */
2072 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2073                          struct btrfs_root *root,
2074                          u64 bytenr, u64 num_bytes, u64 parent,
2075                          u64 root_objectid, u64 owner, u64 offset)
2076 {
2077         int ret;
2078         struct btrfs_fs_info *fs_info = root->fs_info;
2079
2080         BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2081                root_objectid == BTRFS_TREE_LOG_OBJECTID);
2082
2083         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
2084                 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
2085                                         num_bytes,
2086                                         parent, root_objectid, (int)owner,
2087                                         BTRFS_ADD_DELAYED_REF, NULL);
2088         } else {
2089                 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
2090                                         num_bytes, parent, root_objectid,
2091                                         owner, offset, 0,
2092                                         BTRFS_ADD_DELAYED_REF, NULL);
2093         }
2094         return ret;
2095 }
2096
2097 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2098                                   struct btrfs_root *root,
2099                                   struct btrfs_delayed_ref_node *node,
2100                                   u64 parent, u64 root_objectid,
2101                                   u64 owner, u64 offset, int refs_to_add,
2102                                   struct btrfs_delayed_extent_op *extent_op)
2103 {
2104         struct btrfs_fs_info *fs_info = root->fs_info;
2105         struct btrfs_path *path;
2106         struct extent_buffer *leaf;
2107         struct btrfs_extent_item *item;
2108         struct btrfs_key key;
2109         u64 bytenr = node->bytenr;
2110         u64 num_bytes = node->num_bytes;
2111         u64 refs;
2112         int ret;
2113
2114         path = btrfs_alloc_path();
2115         if (!path)
2116                 return -ENOMEM;
2117
2118         path->reada = 1;
2119         path->leave_spinning = 1;
2120         /* this will setup the path even if it fails to insert the back ref */
2121         ret = insert_inline_extent_backref(trans, fs_info->extent_root, path,
2122                                            bytenr, num_bytes, parent,
2123                                            root_objectid, owner, offset,
2124                                            refs_to_add, extent_op);
2125         if ((ret < 0 && ret != -EAGAIN) || !ret)
2126                 goto out;
2127
2128         /*
2129          * Ok we had -EAGAIN which means we didn't have space to insert and
2130          * inline extent ref, so just update the reference count and add a
2131          * normal backref.
2132          */
2133         leaf = path->nodes[0];
2134         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2135         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2136         refs = btrfs_extent_refs(leaf, item);
2137         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2138         if (extent_op)
2139                 __run_delayed_extent_op(extent_op, leaf, item);
2140
2141         btrfs_mark_buffer_dirty(leaf);
2142         btrfs_release_path(path);
2143
2144         path->reada = 1;
2145         path->leave_spinning = 1;
2146         /* now insert the actual backref */
2147         ret = insert_extent_backref(trans, root->fs_info->extent_root,
2148                                     path, bytenr, parent, root_objectid,
2149                                     owner, offset, refs_to_add);
2150         if (ret)
2151                 btrfs_abort_transaction(trans, root, ret);
2152 out:
2153         btrfs_free_path(path);
2154         return ret;
2155 }
2156
2157 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2158                                 struct btrfs_root *root,
2159                                 struct btrfs_delayed_ref_node *node,
2160                                 struct btrfs_delayed_extent_op *extent_op,
2161                                 int insert_reserved)
2162 {
2163         int ret = 0;
2164         struct btrfs_delayed_data_ref *ref;
2165         struct btrfs_key ins;
2166         u64 parent = 0;
2167         u64 ref_root = 0;
2168         u64 flags = 0;
2169
2170         ins.objectid = node->bytenr;
2171         ins.offset = node->num_bytes;
2172         ins.type = BTRFS_EXTENT_ITEM_KEY;
2173
2174         ref = btrfs_delayed_node_to_data_ref(node);
2175         trace_run_delayed_data_ref(node, ref, node->action);
2176
2177         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2178                 parent = ref->parent;
2179         ref_root = ref->root;
2180
2181         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2182                 if (extent_op)
2183                         flags |= extent_op->flags_to_set;
2184                 ret = alloc_reserved_file_extent(trans, root,
2185                                                  parent, ref_root, flags,
2186                                                  ref->objectid, ref->offset,
2187                                                  &ins, node->ref_mod);
2188         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2189                 ret = __btrfs_inc_extent_ref(trans, root, node, parent,
2190                                              ref_root, ref->objectid,
2191                                              ref->offset, node->ref_mod,
2192                                              extent_op);
2193         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2194                 ret = __btrfs_free_extent(trans, root, node, parent,
2195                                           ref_root, ref->objectid,
2196                                           ref->offset, node->ref_mod,
2197                                           extent_op);
2198         } else {
2199                 BUG();
2200         }
2201         return ret;
2202 }
2203
2204 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2205                                     struct extent_buffer *leaf,
2206                                     struct btrfs_extent_item *ei)
2207 {
2208         u64 flags = btrfs_extent_flags(leaf, ei);
2209         if (extent_op->update_flags) {
2210                 flags |= extent_op->flags_to_set;
2211                 btrfs_set_extent_flags(leaf, ei, flags);
2212         }
2213
2214         if (extent_op->update_key) {
2215                 struct btrfs_tree_block_info *bi;
2216                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2217                 bi = (struct btrfs_tree_block_info *)(ei + 1);
2218                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2219         }
2220 }
2221
2222 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2223                                  struct btrfs_root *root,
2224                                  struct btrfs_delayed_ref_node *node,
2225                                  struct btrfs_delayed_extent_op *extent_op)
2226 {
2227         struct btrfs_key key;
2228         struct btrfs_path *path;
2229         struct btrfs_extent_item *ei;
2230         struct extent_buffer *leaf;
2231         u32 item_size;
2232         int ret;
2233         int err = 0;
2234         int metadata = !extent_op->is_data;
2235
2236         if (trans->aborted)
2237                 return 0;
2238
2239         if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
2240                 metadata = 0;
2241
2242         path = btrfs_alloc_path();
2243         if (!path)
2244                 return -ENOMEM;
2245
2246         key.objectid = node->bytenr;
2247
2248         if (metadata) {
2249                 key.type = BTRFS_METADATA_ITEM_KEY;
2250                 key.offset = extent_op->level;
2251         } else {
2252                 key.type = BTRFS_EXTENT_ITEM_KEY;
2253                 key.offset = node->num_bytes;
2254         }
2255
2256 again:
2257         path->reada = 1;
2258         path->leave_spinning = 1;
2259         ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
2260                                 path, 0, 1);
2261         if (ret < 0) {
2262                 err = ret;
2263                 goto out;
2264         }
2265         if (ret > 0) {
2266                 if (metadata) {
2267                         if (path->slots[0] > 0) {
2268                                 path->slots[0]--;
2269                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
2270                                                       path->slots[0]);
2271                                 if (key.objectid == node->bytenr &&
2272                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
2273                                     key.offset == node->num_bytes)
2274                                         ret = 0;
2275                         }
2276                         if (ret > 0) {
2277                                 btrfs_release_path(path);
2278                                 metadata = 0;
2279
2280                                 key.objectid = node->bytenr;
2281                                 key.offset = node->num_bytes;
2282                                 key.type = BTRFS_EXTENT_ITEM_KEY;
2283                                 goto again;
2284                         }
2285                 } else {
2286                         err = -EIO;
2287                         goto out;
2288                 }
2289         }
2290
2291         leaf = path->nodes[0];
2292         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2293 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2294         if (item_size < sizeof(*ei)) {
2295                 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
2296                                              path, (u64)-1, 0);
2297                 if (ret < 0) {
2298                         err = ret;
2299                         goto out;
2300                 }
2301                 leaf = path->nodes[0];
2302                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2303         }
2304 #endif
2305         BUG_ON(item_size < sizeof(*ei));
2306         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2307         __run_delayed_extent_op(extent_op, leaf, ei);
2308
2309         btrfs_mark_buffer_dirty(leaf);
2310 out:
2311         btrfs_free_path(path);
2312         return err;
2313 }
2314
2315 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2316                                 struct btrfs_root *root,
2317                                 struct btrfs_delayed_ref_node *node,
2318                                 struct btrfs_delayed_extent_op *extent_op,
2319                                 int insert_reserved)
2320 {
2321         int ret = 0;
2322         struct btrfs_delayed_tree_ref *ref;
2323         struct btrfs_key ins;
2324         u64 parent = 0;
2325         u64 ref_root = 0;
2326         bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
2327                                                  SKINNY_METADATA);
2328
2329         ref = btrfs_delayed_node_to_tree_ref(node);
2330         trace_run_delayed_tree_ref(node, ref, node->action);
2331
2332         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2333                 parent = ref->parent;
2334         ref_root = ref->root;
2335
2336         ins.objectid = node->bytenr;
2337         if (skinny_metadata) {
2338                 ins.offset = ref->level;
2339                 ins.type = BTRFS_METADATA_ITEM_KEY;
2340         } else {
2341                 ins.offset = node->num_bytes;
2342                 ins.type = BTRFS_EXTENT_ITEM_KEY;
2343         }
2344
2345         BUG_ON(node->ref_mod != 1);
2346         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2347                 BUG_ON(!extent_op || !extent_op->update_flags);
2348                 ret = alloc_reserved_tree_block(trans, root,
2349                                                 parent, ref_root,
2350                                                 extent_op->flags_to_set,
2351                                                 &extent_op->key,
2352                                                 ref->level, &ins);
2353         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2354                 ret = __btrfs_inc_extent_ref(trans, root, node,
2355                                              parent, ref_root,
2356                                              ref->level, 0, 1,
2357                                              extent_op);
2358         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2359                 ret = __btrfs_free_extent(trans, root, node,
2360                                           parent, ref_root,
2361                                           ref->level, 0, 1, extent_op);
2362         } else {
2363                 BUG();
2364         }
2365         return ret;
2366 }
2367
2368 /* helper function to actually process a single delayed ref entry */
2369 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2370                                struct btrfs_root *root,
2371                                struct btrfs_delayed_ref_node *node,
2372                                struct btrfs_delayed_extent_op *extent_op,
2373                                int insert_reserved)
2374 {
2375         int ret = 0;
2376
2377         if (trans->aborted) {
2378                 if (insert_reserved)
2379                         btrfs_pin_extent(root, node->bytenr,
2380                                          node->num_bytes, 1);
2381                 return 0;
2382         }
2383
2384         if (btrfs_delayed_ref_is_head(node)) {
2385                 struct btrfs_delayed_ref_head *head;
2386                 /*
2387                  * we've hit the end of the chain and we were supposed
2388                  * to insert this extent into the tree.  But, it got
2389                  * deleted before we ever needed to insert it, so all
2390                  * we have to do is clean up the accounting
2391                  */
2392                 BUG_ON(extent_op);
2393                 head = btrfs_delayed_node_to_head(node);
2394                 trace_run_delayed_ref_head(node, head, node->action);
2395
2396                 if (insert_reserved) {
2397                         btrfs_pin_extent(root, node->bytenr,
2398                                          node->num_bytes, 1);
2399                         if (head->is_data) {
2400                                 ret = btrfs_del_csums(trans, root,
2401                                                       node->bytenr,
2402                                                       node->num_bytes);
2403                         }
2404                 }
2405
2406                 /* Also free its reserved qgroup space */
2407                 btrfs_qgroup_free_delayed_ref(root->fs_info,
2408                                               head->qgroup_ref_root,
2409                                               head->qgroup_reserved);
2410                 return ret;
2411         }
2412
2413         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2414             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2415                 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2416                                            insert_reserved);
2417         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2418                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2419                 ret = run_delayed_data_ref(trans, root, node, extent_op,
2420                                            insert_reserved);
2421         else
2422                 BUG();
2423         return ret;
2424 }
2425
2426 static inline struct btrfs_delayed_ref_node *
2427 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2428 {
2429         struct btrfs_delayed_ref_node *ref;
2430
2431         if (list_empty(&head->ref_list))
2432                 return NULL;
2433
2434         /*
2435          * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2436          * This is to prevent a ref count from going down to zero, which deletes
2437          * the extent item from the extent tree, when there still are references
2438          * to add, which would fail because they would not find the extent item.
2439          */
2440         list_for_each_entry(ref, &head->ref_list, list) {
2441                 if (ref->action == BTRFS_ADD_DELAYED_REF)
2442                         return ref;
2443         }
2444
2445         return list_entry(head->ref_list.next, struct btrfs_delayed_ref_node,
2446                           list);
2447 }
2448
2449 /*
2450  * Returns 0 on success or if called with an already aborted transaction.
2451  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2452  */
2453 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2454                                              struct btrfs_root *root,
2455                                              unsigned long nr)
2456 {
2457         struct btrfs_delayed_ref_root *delayed_refs;
2458         struct btrfs_delayed_ref_node *ref;
2459         struct btrfs_delayed_ref_head *locked_ref = NULL;
2460         struct btrfs_delayed_extent_op *extent_op;
2461         struct btrfs_fs_info *fs_info = root->fs_info;
2462         ktime_t start = ktime_get();
2463         int ret;
2464         unsigned long count = 0;
2465         unsigned long actual_count = 0;
2466         int must_insert_reserved = 0;
2467
2468         delayed_refs = &trans->transaction->delayed_refs;
2469         while (1) {
2470                 if (!locked_ref) {
2471                         if (count >= nr)
2472                                 break;
2473
2474                         spin_lock(&delayed_refs->lock);
2475                         locked_ref = btrfs_select_ref_head(trans);
2476                         if (!locked_ref) {
2477                                 spin_unlock(&delayed_refs->lock);
2478                                 break;
2479                         }
2480
2481                         /* grab the lock that says we are going to process
2482                          * all the refs for this head */
2483                         ret = btrfs_delayed_ref_lock(trans, locked_ref);
2484                         spin_unlock(&delayed_refs->lock);
2485                         /*
2486                          * we may have dropped the spin lock to get the head
2487                          * mutex lock, and that might have given someone else
2488                          * time to free the head.  If that's true, it has been
2489                          * removed from our list and we can move on.
2490                          */
2491                         if (ret == -EAGAIN) {
2492                                 locked_ref = NULL;
2493                                 count++;
2494                                 continue;
2495                         }
2496                 }
2497
2498                 /*
2499                  * We need to try and merge add/drops of the same ref since we
2500                  * can run into issues with relocate dropping the implicit ref
2501                  * and then it being added back again before the drop can
2502                  * finish.  If we merged anything we need to re-loop so we can
2503                  * get a good ref.
2504                  * Or we can get node references of the same type that weren't
2505                  * merged when created due to bumps in the tree mod seq, and
2506                  * we need to merge them to prevent adding an inline extent
2507                  * backref before dropping it (triggering a BUG_ON at
2508                  * insert_inline_extent_backref()).
2509                  */
2510                 spin_lock(&locked_ref->lock);
2511                 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2512                                          locked_ref);
2513
2514                 /*
2515                  * locked_ref is the head node, so we have to go one
2516                  * node back for any delayed ref updates
2517                  */
2518                 ref = select_delayed_ref(locked_ref);
2519
2520                 if (ref && ref->seq &&
2521                     btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
2522                         spin_unlock(&locked_ref->lock);
2523                         spin_lock(&delayed_refs->lock);
2524                         locked_ref->processing = 0;
2525                         delayed_refs->num_heads_ready++;
2526                         spin_unlock(&delayed_refs->lock);
2527                         btrfs_delayed_ref_unlock(locked_ref);
2528                         locked_ref = NULL;
2529                         cond_resched();
2530                         count++;
2531                         continue;
2532                 }
2533
2534                 /*
2535                  * record the must insert reserved flag before we
2536                  * drop the spin lock.
2537                  */
2538                 must_insert_reserved = locked_ref->must_insert_reserved;
2539                 locked_ref->must_insert_reserved = 0;
2540
2541                 extent_op = locked_ref->extent_op;
2542                 locked_ref->extent_op = NULL;
2543
2544                 if (!ref) {
2545
2546
2547                         /* All delayed refs have been processed, Go ahead
2548                          * and send the head node to run_one_delayed_ref,
2549                          * so that any accounting fixes can happen
2550                          */
2551                         ref = &locked_ref->node;
2552
2553                         if (extent_op && must_insert_reserved) {
2554                                 btrfs_free_delayed_extent_op(extent_op);
2555                                 extent_op = NULL;
2556                         }
2557
2558                         if (extent_op) {
2559                                 spin_unlock(&locked_ref->lock);
2560                                 ret = run_delayed_extent_op(trans, root,
2561                                                             ref, extent_op);
2562                                 btrfs_free_delayed_extent_op(extent_op);
2563
2564                                 if (ret) {
2565                                         /*
2566                                          * Need to reset must_insert_reserved if
2567                                          * there was an error so the abort stuff
2568                                          * can cleanup the reserved space
2569                                          * properly.
2570                                          */
2571                                         if (must_insert_reserved)
2572                                                 locked_ref->must_insert_reserved = 1;
2573                                         locked_ref->processing = 0;
2574                                         btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
2575                                         btrfs_delayed_ref_unlock(locked_ref);
2576                                         return ret;
2577                                 }
2578                                 continue;
2579                         }
2580
2581                         /*
2582                          * Need to drop our head ref lock and re-aqcuire the
2583                          * delayed ref lock and then re-check to make sure
2584                          * nobody got added.
2585                          */
2586                         spin_unlock(&locked_ref->lock);
2587                         spin_lock(&delayed_refs->lock);
2588                         spin_lock(&locked_ref->lock);
2589                         if (!list_empty(&locked_ref->ref_list) ||
2590                             locked_ref->extent_op) {
2591                                 spin_unlock(&locked_ref->lock);
2592                                 spin_unlock(&delayed_refs->lock);
2593                                 continue;
2594                         }
2595                         ref->in_tree = 0;
2596                         delayed_refs->num_heads--;
2597                         rb_erase(&locked_ref->href_node,
2598                                  &delayed_refs->href_root);
2599                         spin_unlock(&delayed_refs->lock);
2600                 } else {
2601                         actual_count++;
2602                         ref->in_tree = 0;
2603                         list_del(&ref->list);
2604                 }
2605                 atomic_dec(&delayed_refs->num_entries);
2606
2607                 if (!btrfs_delayed_ref_is_head(ref)) {
2608                         /*
2609                          * when we play the delayed ref, also correct the
2610                          * ref_mod on head
2611                          */
2612                         switch (ref->action) {
2613                         case BTRFS_ADD_DELAYED_REF:
2614                         case BTRFS_ADD_DELAYED_EXTENT:
2615                                 locked_ref->node.ref_mod -= ref->ref_mod;
2616                                 break;
2617                         case BTRFS_DROP_DELAYED_REF:
2618                                 locked_ref->node.ref_mod += ref->ref_mod;
2619                                 break;
2620                         default:
2621                                 WARN_ON(1);
2622                         }
2623                 }
2624                 spin_unlock(&locked_ref->lock);
2625
2626                 ret = run_one_delayed_ref(trans, root, ref, extent_op,
2627                                           must_insert_reserved);
2628
2629                 btrfs_free_delayed_extent_op(extent_op);
2630                 if (ret) {
2631                         locked_ref->processing = 0;
2632                         btrfs_delayed_ref_unlock(locked_ref);
2633                         btrfs_put_delayed_ref(ref);
2634                         btrfs_debug(fs_info, "run_one_delayed_ref returned %d", ret);
2635                         return ret;
2636                 }
2637
2638                 /*
2639                  * If this node is a head, that means all the refs in this head
2640                  * have been dealt with, and we will pick the next head to deal
2641                  * with, so we must unlock the head and drop it from the cluster
2642                  * list before we release it.
2643                  */
2644                 if (btrfs_delayed_ref_is_head(ref)) {
2645                         if (locked_ref->is_data &&
2646                             locked_ref->total_ref_mod < 0) {
2647                                 spin_lock(&delayed_refs->lock);
2648                                 delayed_refs->pending_csums -= ref->num_bytes;
2649                                 spin_unlock(&delayed_refs->lock);
2650                         }
2651                         btrfs_delayed_ref_unlock(locked_ref);
2652                         locked_ref = NULL;
2653                 }
2654                 btrfs_put_delayed_ref(ref);
2655                 count++;
2656                 cond_resched();
2657         }
2658
2659         /*
2660          * We don't want to include ref heads since we can have empty ref heads
2661          * and those will drastically skew our runtime down since we just do
2662          * accounting, no actual extent tree updates.
2663          */
2664         if (actual_count > 0) {
2665                 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2666                 u64 avg;
2667
2668                 /*
2669                  * We weigh the current average higher than our current runtime
2670                  * to avoid large swings in the average.
2671                  */
2672                 spin_lock(&delayed_refs->lock);
2673                 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2674                 fs_info->avg_delayed_ref_runtime = avg >> 2;    /* div by 4 */
2675                 spin_unlock(&delayed_refs->lock);
2676         }
2677         return 0;
2678 }
2679
2680 #ifdef SCRAMBLE_DELAYED_REFS
2681 /*
2682  * Normally delayed refs get processed in ascending bytenr order. This
2683  * correlates in most cases to the order added. To expose dependencies on this
2684  * order, we start to process the tree in the middle instead of the beginning
2685  */
2686 static u64 find_middle(struct rb_root *root)
2687 {
2688         struct rb_node *n = root->rb_node;
2689         struct btrfs_delayed_ref_node *entry;
2690         int alt = 1;
2691         u64 middle;
2692         u64 first = 0, last = 0;
2693
2694         n = rb_first(root);
2695         if (n) {
2696                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2697                 first = entry->bytenr;
2698         }
2699         n = rb_last(root);
2700         if (n) {
2701                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2702                 last = entry->bytenr;
2703         }
2704         n = root->rb_node;
2705
2706         while (n) {
2707                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2708                 WARN_ON(!entry->in_tree);
2709
2710                 middle = entry->bytenr;
2711
2712                 if (alt)
2713                         n = n->rb_left;
2714                 else
2715                         n = n->rb_right;
2716
2717                 alt = 1 - alt;
2718         }
2719         return middle;
2720 }
2721 #endif
2722
2723 static inline u64 heads_to_leaves(struct btrfs_root *root, u64 heads)
2724 {
2725         u64 num_bytes;
2726
2727         num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2728                              sizeof(struct btrfs_extent_inline_ref));
2729         if (!btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
2730                 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2731
2732         /*
2733          * We don't ever fill up leaves all the way so multiply by 2 just to be
2734          * closer to what we're really going to want to ouse.
2735          */
2736         return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(root));
2737 }
2738
2739 /*
2740  * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2741  * would require to store the csums for that many bytes.
2742  */
2743 u64 btrfs_csum_bytes_to_leaves(struct btrfs_root *root, u64 csum_bytes)
2744 {
2745         u64 csum_size;
2746         u64 num_csums_per_leaf;
2747         u64 num_csums;
2748
2749         csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
2750         num_csums_per_leaf = div64_u64(csum_size,
2751                         (u64)btrfs_super_csum_size(root->fs_info->super_copy));
2752         num_csums = div64_u64(csum_bytes, root->sectorsize);
2753         num_csums += num_csums_per_leaf - 1;
2754         num_csums = div64_u64(num_csums, num_csums_per_leaf);
2755         return num_csums;
2756 }
2757
2758 int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2759                                        struct btrfs_root *root)
2760 {
2761         struct btrfs_block_rsv *global_rsv;
2762         u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2763         u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
2764         u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
2765         u64 num_bytes, num_dirty_bgs_bytes;
2766         int ret = 0;
2767
2768         num_bytes = btrfs_calc_trans_metadata_size(root, 1);
2769         num_heads = heads_to_leaves(root, num_heads);
2770         if (num_heads > 1)
2771                 num_bytes += (num_heads - 1) * root->nodesize;
2772         num_bytes <<= 1;
2773         num_bytes += btrfs_csum_bytes_to_leaves(root, csum_bytes) * root->nodesize;
2774         num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(root,
2775                                                              num_dirty_bgs);
2776         global_rsv = &root->fs_info->global_block_rsv;
2777
2778         /*
2779          * If we can't allocate any more chunks lets make sure we have _lots_ of
2780          * wiggle room since running delayed refs can create more delayed refs.
2781          */
2782         if (global_rsv->space_info->full) {
2783                 num_dirty_bgs_bytes <<= 1;
2784                 num_bytes <<= 1;
2785         }
2786
2787         spin_lock(&global_rsv->lock);
2788         if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
2789                 ret = 1;
2790         spin_unlock(&global_rsv->lock);
2791         return ret;
2792 }
2793
2794 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2795                                        struct btrfs_root *root)
2796 {
2797         struct btrfs_fs_info *fs_info = root->fs_info;
2798         u64 num_entries =
2799                 atomic_read(&trans->transaction->delayed_refs.num_entries);
2800         u64 avg_runtime;
2801         u64 val;
2802
2803         smp_mb();
2804         avg_runtime = fs_info->avg_delayed_ref_runtime;
2805         val = num_entries * avg_runtime;
2806         if (num_entries * avg_runtime >= NSEC_PER_SEC)
2807                 return 1;
2808         if (val >= NSEC_PER_SEC / 2)
2809                 return 2;
2810
2811         return btrfs_check_space_for_delayed_refs(trans, root);
2812 }
2813
2814 struct async_delayed_refs {
2815         struct btrfs_root *root;
2816         int count;
2817         int error;
2818         int sync;
2819         struct completion wait;
2820         struct btrfs_work work;
2821 };
2822
2823 static void delayed_ref_async_start(struct btrfs_work *work)
2824 {
2825         struct async_delayed_refs *async;
2826         struct btrfs_trans_handle *trans;
2827         int ret;
2828
2829         async = container_of(work, struct async_delayed_refs, work);
2830
2831         trans = btrfs_join_transaction(async->root);
2832         if (IS_ERR(trans)) {
2833                 async->error = PTR_ERR(trans);
2834                 goto done;
2835         }
2836
2837         /*
2838          * trans->sync means that when we call end_transaciton, we won't
2839          * wait on delayed refs
2840          */
2841         trans->sync = true;
2842         ret = btrfs_run_delayed_refs(trans, async->root, async->count);
2843         if (ret)
2844                 async->error = ret;
2845
2846         ret = btrfs_end_transaction(trans, async->root);
2847         if (ret && !async->error)
2848                 async->error = ret;
2849 done:
2850         if (async->sync)
2851                 complete(&async->wait);
2852         else
2853                 kfree(async);
2854 }
2855
2856 int btrfs_async_run_delayed_refs(struct btrfs_root *root,
2857                                  unsigned long count, int wait)
2858 {
2859         struct async_delayed_refs *async;
2860         int ret;
2861
2862         async = kmalloc(sizeof(*async), GFP_NOFS);
2863         if (!async)
2864                 return -ENOMEM;
2865
2866         async->root = root->fs_info->tree_root;
2867         async->count = count;
2868         async->error = 0;
2869         if (wait)
2870                 async->sync = 1;
2871         else
2872                 async->sync = 0;
2873         init_completion(&async->wait);
2874
2875         btrfs_init_work(&async->work, btrfs_extent_refs_helper,
2876                         delayed_ref_async_start, NULL, NULL);
2877
2878         btrfs_queue_work(root->fs_info->extent_workers, &async->work);
2879
2880         if (wait) {
2881                 wait_for_completion(&async->wait);
2882                 ret = async->error;
2883                 kfree(async);
2884                 return ret;
2885         }
2886         return 0;
2887 }
2888
2889 /*
2890  * this starts processing the delayed reference count updates and
2891  * extent insertions we have queued up so far.  count can be
2892  * 0, which means to process everything in the tree at the start
2893  * of the run (but not newly added entries), or it can be some target
2894  * number you'd like to process.
2895  *
2896  * Returns 0 on success or if called with an aborted transaction
2897  * Returns <0 on error and aborts the transaction
2898  */
2899 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2900                            struct btrfs_root *root, unsigned long count)
2901 {
2902         struct rb_node *node;
2903         struct btrfs_delayed_ref_root *delayed_refs;
2904         struct btrfs_delayed_ref_head *head;
2905         int ret;
2906         int run_all = count == (unsigned long)-1;
2907         bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
2908
2909         /* We'll clean this up in btrfs_cleanup_transaction */
2910         if (trans->aborted)
2911                 return 0;
2912
2913         if (root == root->fs_info->extent_root)
2914                 root = root->fs_info->tree_root;
2915
2916         delayed_refs = &trans->transaction->delayed_refs;
2917         if (count == 0)
2918                 count = atomic_read(&delayed_refs->num_entries) * 2;
2919
2920 again:
2921 #ifdef SCRAMBLE_DELAYED_REFS
2922         delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2923 #endif
2924         trans->can_flush_pending_bgs = false;
2925         ret = __btrfs_run_delayed_refs(trans, root, count);
2926         if (ret < 0) {
2927                 btrfs_abort_transaction(trans, root, ret);
2928                 return ret;
2929         }
2930
2931         if (run_all) {
2932                 if (!list_empty(&trans->new_bgs))
2933                         btrfs_create_pending_block_groups(trans, root);
2934
2935                 spin_lock(&delayed_refs->lock);
2936                 node = rb_first(&delayed_refs->href_root);
2937                 if (!node) {
2938                         spin_unlock(&delayed_refs->lock);
2939                         goto out;
2940                 }
2941                 count = (unsigned long)-1;
2942
2943                 while (node) {
2944                         head = rb_entry(node, struct btrfs_delayed_ref_head,
2945                                         href_node);
2946                         if (btrfs_delayed_ref_is_head(&head->node)) {
2947                                 struct btrfs_delayed_ref_node *ref;
2948
2949                                 ref = &head->node;
2950                                 atomic_inc(&ref->refs);
2951
2952                                 spin_unlock(&delayed_refs->lock);
2953                                 /*
2954                                  * Mutex was contended, block until it's
2955                                  * released and try again
2956                                  */
2957                                 mutex_lock(&head->mutex);
2958                                 mutex_unlock(&head->mutex);
2959
2960                                 btrfs_put_delayed_ref(ref);
2961                                 cond_resched();
2962                                 goto again;
2963                         } else {
2964                                 WARN_ON(1);
2965                         }
2966                         node = rb_next(node);
2967                 }
2968                 spin_unlock(&delayed_refs->lock);
2969                 cond_resched();
2970                 goto again;
2971         }
2972 out:
2973         assert_qgroups_uptodate(trans);
2974         trans->can_flush_pending_bgs = can_flush_pending_bgs;
2975         return 0;
2976 }
2977
2978 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2979                                 struct btrfs_root *root,
2980                                 u64 bytenr, u64 num_bytes, u64 flags,
2981                                 int level, int is_data)
2982 {
2983         struct btrfs_delayed_extent_op *extent_op;
2984         int ret;
2985
2986         extent_op = btrfs_alloc_delayed_extent_op();
2987         if (!extent_op)
2988                 return -ENOMEM;
2989
2990         extent_op->flags_to_set = flags;
2991         extent_op->update_flags = 1;
2992         extent_op->update_key = 0;
2993         extent_op->is_data = is_data ? 1 : 0;
2994         extent_op->level = level;
2995
2996         ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
2997                                           num_bytes, extent_op);
2998         if (ret)
2999                 btrfs_free_delayed_extent_op(extent_op);
3000         return ret;
3001 }
3002
3003 static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
3004                                       struct btrfs_root *root,
3005                                       struct btrfs_path *path,
3006                                       u64 objectid, u64 offset, u64 bytenr)
3007 {
3008         struct btrfs_delayed_ref_head *head;
3009         struct btrfs_delayed_ref_node *ref;
3010         struct btrfs_delayed_data_ref *data_ref;
3011         struct btrfs_delayed_ref_root *delayed_refs;
3012         int ret = 0;
3013
3014         delayed_refs = &trans->transaction->delayed_refs;
3015         spin_lock(&delayed_refs->lock);
3016         head = btrfs_find_delayed_ref_head(trans, bytenr);
3017         if (!head) {
3018                 spin_unlock(&delayed_refs->lock);
3019                 return 0;
3020         }
3021
3022         if (!mutex_trylock(&head->mutex)) {
3023                 atomic_inc(&head->node.refs);
3024                 spin_unlock(&delayed_refs->lock);
3025
3026                 btrfs_release_path(path);
3027
3028                 /*
3029                  * Mutex was contended, block until it's released and let
3030                  * caller try again
3031                  */
3032                 mutex_lock(&head->mutex);
3033                 mutex_unlock(&head->mutex);
3034                 btrfs_put_delayed_ref(&head->node);
3035                 return -EAGAIN;
3036         }
3037         spin_unlock(&delayed_refs->lock);
3038
3039         spin_lock(&head->lock);
3040         list_for_each_entry(ref, &head->ref_list, list) {
3041                 /* If it's a shared ref we know a cross reference exists */
3042                 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3043                         ret = 1;
3044                         break;
3045                 }
3046
3047                 data_ref = btrfs_delayed_node_to_data_ref(ref);
3048
3049                 /*
3050                  * If our ref doesn't match the one we're currently looking at
3051                  * then we have a cross reference.
3052                  */
3053                 if (data_ref->root != root->root_key.objectid ||
3054                     data_ref->objectid != objectid ||
3055                     data_ref->offset != offset) {
3056                         ret = 1;
3057                         break;
3058                 }
3059         }
3060         spin_unlock(&head->lock);
3061         mutex_unlock(&head->mutex);
3062         return ret;
3063 }
3064
3065 static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
3066                                         struct btrfs_root *root,
3067                                         struct btrfs_path *path,
3068                                         u64 objectid, u64 offset, u64 bytenr)
3069 {
3070         struct btrfs_root *extent_root = root->fs_info->extent_root;
3071         struct extent_buffer *leaf;
3072         struct btrfs_extent_data_ref *ref;
3073         struct btrfs_extent_inline_ref *iref;
3074         struct btrfs_extent_item *ei;
3075         struct btrfs_key key;
3076         u32 item_size;
3077         int ret;
3078
3079         key.objectid = bytenr;
3080         key.offset = (u64)-1;
3081         key.type = BTRFS_EXTENT_ITEM_KEY;
3082
3083         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3084         if (ret < 0)
3085                 goto out;
3086         BUG_ON(ret == 0); /* Corruption */
3087
3088         ret = -ENOENT;
3089         if (path->slots[0] == 0)
3090                 goto out;
3091
3092         path->slots[0]--;
3093         leaf = path->nodes[0];
3094         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3095
3096         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3097                 goto out;
3098
3099         ret = 1;
3100         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3101 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3102         if (item_size < sizeof(*ei)) {
3103                 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
3104                 goto out;
3105         }
3106 #endif
3107         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3108
3109         if (item_size != sizeof(*ei) +
3110             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3111                 goto out;
3112
3113         if (btrfs_extent_generation(leaf, ei) <=
3114             btrfs_root_last_snapshot(&root->root_item))
3115                 goto out;
3116
3117         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3118         if (btrfs_extent_inline_ref_type(leaf, iref) !=
3119             BTRFS_EXTENT_DATA_REF_KEY)
3120                 goto out;
3121
3122         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3123         if (btrfs_extent_refs(leaf, ei) !=
3124             btrfs_extent_data_ref_count(leaf, ref) ||
3125             btrfs_extent_data_ref_root(leaf, ref) !=
3126             root->root_key.objectid ||
3127             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3128             btrfs_extent_data_ref_offset(leaf, ref) != offset)
3129                 goto out;
3130
3131         ret = 0;
3132 out:
3133         return ret;
3134 }
3135
3136 int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
3137                           struct btrfs_root *root,
3138                           u64 objectid, u64 offset, u64 bytenr)
3139 {
3140         struct btrfs_path *path;
3141         int ret;
3142         int ret2;
3143
3144         path = btrfs_alloc_path();
3145         if (!path)
3146                 return -ENOENT;
3147
3148         do {
3149                 ret = check_committed_ref(trans, root, path, objectid,
3150                                           offset, bytenr);
3151                 if (ret && ret != -ENOENT)
3152                         goto out;
3153
3154                 ret2 = check_delayed_ref(trans, root, path, objectid,
3155                                          offset, bytenr);
3156         } while (ret2 == -EAGAIN);
3157
3158         if (ret2 && ret2 != -ENOENT) {
3159                 ret = ret2;
3160                 goto out;
3161         }
3162
3163         if (ret != -ENOENT || ret2 != -ENOENT)
3164                 ret = 0;
3165 out:
3166         btrfs_free_path(path);
3167         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3168                 WARN_ON(ret > 0);
3169         return ret;
3170 }
3171
3172 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3173                            struct btrfs_root *root,
3174                            struct extent_buffer *buf,
3175                            int full_backref, int inc)
3176 {
3177         u64 bytenr;
3178         u64 num_bytes;
3179         u64 parent;
3180         u64 ref_root;
3181         u32 nritems;
3182         struct btrfs_key key;
3183         struct btrfs_file_extent_item *fi;
3184         int i;
3185         int level;
3186         int ret = 0;
3187         int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
3188                             u64, u64, u64, u64, u64, u64);
3189
3190
3191         if (btrfs_test_is_dummy_root(root))
3192                 return 0;
3193
3194         ref_root = btrfs_header_owner(buf);
3195         nritems = btrfs_header_nritems(buf);
3196         level = btrfs_header_level(buf);
3197
3198         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3199                 return 0;
3200
3201         if (inc)
3202                 process_func = btrfs_inc_extent_ref;
3203         else
3204                 process_func = btrfs_free_extent;
3205
3206         if (full_backref)
3207                 parent = buf->start;
3208         else
3209                 parent = 0;
3210
3211         for (i = 0; i < nritems; i++) {
3212                 if (level == 0) {
3213                         btrfs_item_key_to_cpu(buf, &key, i);
3214                         if (key.type != BTRFS_EXTENT_DATA_KEY)
3215                                 continue;
3216                         fi = btrfs_item_ptr(buf, i,
3217                                             struct btrfs_file_extent_item);
3218                         if (btrfs_file_extent_type(buf, fi) ==
3219                             BTRFS_FILE_EXTENT_INLINE)
3220                                 continue;
3221                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3222                         if (bytenr == 0)
3223                                 continue;
3224
3225                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3226                         key.offset -= btrfs_file_extent_offset(buf, fi);
3227                         ret = process_func(trans, root, bytenr, num_bytes,
3228                                            parent, ref_root, key.objectid,
3229                                            key.offset);
3230                         if (ret)
3231                                 goto fail;
3232                 } else {
3233                         bytenr = btrfs_node_blockptr(buf, i);
3234                         num_bytes = root->nodesize;
3235                         ret = process_func(trans, root, bytenr, num_bytes,
3236                                            parent, ref_root, level - 1, 0);
3237                         if (ret)
3238                                 goto fail;
3239                 }
3240         }
3241         return 0;
3242 fail:
3243         return ret;
3244 }
3245
3246 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3247                   struct extent_buffer *buf, int full_backref)
3248 {
3249         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3250 }
3251
3252 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3253                   struct extent_buffer *buf, int full_backref)
3254 {
3255         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3256 }
3257
3258 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3259                                  struct btrfs_root *root,
3260                                  struct btrfs_path *path,
3261                                  struct btrfs_block_group_cache *cache)
3262 {
3263         int ret;
3264         struct btrfs_root *extent_root = root->fs_info->extent_root;
3265         unsigned long bi;
3266         struct extent_buffer *leaf;
3267
3268         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3269         if (ret) {
3270                 if (ret > 0)
3271                         ret = -ENOENT;
3272                 goto fail;
3273         }
3274
3275         leaf = path->nodes[0];
3276         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3277         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3278         btrfs_mark_buffer_dirty(leaf);
3279 fail:
3280         btrfs_release_path(path);
3281         return ret;
3282
3283 }
3284
3285 static struct btrfs_block_group_cache *
3286 next_block_group(struct btrfs_root *root,
3287                  struct btrfs_block_group_cache *cache)
3288 {
3289         struct rb_node *node;
3290
3291         spin_lock(&root->fs_info->block_group_cache_lock);
3292
3293         /* If our block group was removed, we need a full search. */
3294         if (RB_EMPTY_NODE(&cache->cache_node)) {
3295                 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3296
3297                 spin_unlock(&root->fs_info->block_group_cache_lock);
3298                 btrfs_put_block_group(cache);
3299                 cache = btrfs_lookup_first_block_group(root->fs_info,
3300                                                        next_bytenr);
3301                 return cache;
3302         }
3303         node = rb_next(&cache->cache_node);
3304         btrfs_put_block_group(cache);
3305         if (node) {
3306                 cache = rb_entry(node, struct btrfs_block_group_cache,
3307                                  cache_node);
3308                 btrfs_get_block_group(cache);
3309         } else
3310                 cache = NULL;
3311         spin_unlock(&root->fs_info->block_group_cache_lock);
3312         return cache;
3313 }
3314
3315 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3316                             struct btrfs_trans_handle *trans,
3317                             struct btrfs_path *path)
3318 {
3319         struct btrfs_root *root = block_group->fs_info->tree_root;
3320         struct inode *inode = NULL;
3321         u64 alloc_hint = 0;
3322         int dcs = BTRFS_DC_ERROR;
3323         u64 num_pages = 0;
3324         int retries = 0;
3325         int ret = 0;
3326
3327         /*
3328          * If this block group is smaller than 100 megs don't bother caching the
3329          * block group.
3330          */
3331         if (block_group->key.offset < (100 * 1024 * 1024)) {
3332                 spin_lock(&block_group->lock);
3333                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3334                 spin_unlock(&block_group->lock);
3335                 return 0;
3336         }
3337
3338         if (trans->aborted)
3339                 return 0;
3340 again:
3341         inode = lookup_free_space_inode(root, block_group, path);
3342         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3343                 ret = PTR_ERR(inode);
3344                 btrfs_release_path(path);
3345                 goto out;
3346         }
3347
3348         if (IS_ERR(inode)) {
3349                 BUG_ON(retries);
3350                 retries++;
3351
3352                 if (block_group->ro)
3353                         goto out_free;
3354
3355                 ret = create_free_space_inode(root, trans, block_group, path);
3356                 if (ret)
3357                         goto out_free;
3358                 goto again;
3359         }
3360
3361         /* We've already setup this transaction, go ahead and exit */
3362         if (block_group->cache_generation == trans->transid &&
3363             i_size_read(inode)) {
3364                 dcs = BTRFS_DC_SETUP;
3365                 goto out_put;
3366         }
3367
3368         /*
3369          * We want to set the generation to 0, that way if anything goes wrong
3370          * from here on out we know not to trust this cache when we load up next
3371          * time.
3372          */
3373         BTRFS_I(inode)->generation = 0;
3374         ret = btrfs_update_inode(trans, root, inode);
3375         if (ret) {
3376                 /*
3377                  * So theoretically we could recover from this, simply set the
3378                  * super cache generation to 0 so we know to invalidate the
3379                  * cache, but then we'd have to keep track of the block groups
3380                  * that fail this way so we know we _have_ to reset this cache
3381                  * before the next commit or risk reading stale cache.  So to
3382                  * limit our exposure to horrible edge cases lets just abort the
3383                  * transaction, this only happens in really bad situations
3384                  * anyway.
3385                  */
3386                 btrfs_abort_transaction(trans, root, ret);
3387                 goto out_put;
3388         }
3389         WARN_ON(ret);
3390
3391         if (i_size_read(inode) > 0) {
3392                 ret = btrfs_check_trunc_cache_free_space(root,
3393                                         &root->fs_info->global_block_rsv);
3394                 if (ret)
3395                         goto out_put;
3396
3397                 ret = btrfs_truncate_free_space_cache(root, trans, NULL, inode);
3398                 if (ret)
3399                         goto out_put;
3400         }
3401
3402         spin_lock(&block_group->lock);
3403         if (block_group->cached != BTRFS_CACHE_FINISHED ||
3404             !btrfs_test_opt(root, SPACE_CACHE)) {
3405                 /*
3406                  * don't bother trying to write stuff out _if_
3407                  * a) we're not cached,
3408                  * b) we're with nospace_cache mount option.
3409                  */
3410                 dcs = BTRFS_DC_WRITTEN;
3411                 spin_unlock(&block_group->lock);
3412                 goto out_put;
3413         }
3414         spin_unlock(&block_group->lock);
3415
3416         /*
3417          * We hit an ENOSPC when setting up the cache in this transaction, just
3418          * skip doing the setup, we've already cleared the cache so we're safe.
3419          */
3420         if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3421                 ret = -ENOSPC;
3422                 goto out_put;
3423         }
3424
3425         /*
3426          * Try to preallocate enough space based on how big the block group is.
3427          * Keep in mind this has to include any pinned space which could end up
3428          * taking up quite a bit since it's not folded into the other space
3429          * cache.
3430          */
3431         num_pages = div_u64(block_group->key.offset, 256 * 1024 * 1024);
3432         if (!num_pages)
3433                 num_pages = 1;
3434
3435         num_pages *= 16;
3436         num_pages *= PAGE_CACHE_SIZE;
3437
3438         ret = btrfs_check_data_free_space(inode, 0, num_pages);
3439         if (ret)
3440                 goto out_put;
3441
3442         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3443                                               num_pages, num_pages,
3444                                               &alloc_hint);
3445         /*
3446          * Our cache requires contiguous chunks so that we don't modify a bunch
3447          * of metadata or split extents when writing the cache out, which means
3448          * we can enospc if we are heavily fragmented in addition to just normal
3449          * out of space conditions.  So if we hit this just skip setting up any
3450          * other block groups for this transaction, maybe we'll unpin enough
3451          * space the next time around.
3452          */
3453         if (!ret)
3454                 dcs = BTRFS_DC_SETUP;
3455         else if (ret == -ENOSPC)
3456                 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3457         btrfs_free_reserved_data_space(inode, 0, num_pages);
3458
3459 out_put:
3460         iput(inode);
3461 out_free:
3462         btrfs_release_path(path);
3463 out:
3464         spin_lock(&block_group->lock);
3465         if (!ret && dcs == BTRFS_DC_SETUP)
3466                 block_group->cache_generation = trans->transid;
3467         block_group->disk_cache_state = dcs;
3468         spin_unlock(&block_group->lock);
3469
3470         return ret;
3471 }
3472
3473 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
3474                             struct btrfs_root *root)
3475 {
3476         struct btrfs_block_group_cache *cache, *tmp;
3477         struct btrfs_transaction *cur_trans = trans->transaction;
3478         struct btrfs_path *path;
3479
3480         if (list_empty(&cur_trans->dirty_bgs) ||
3481             !btrfs_test_opt(root, SPACE_CACHE))
3482                 return 0;
3483
3484         path = btrfs_alloc_path();
3485         if (!path)
3486                 return -ENOMEM;
3487
3488         /* Could add new block groups, use _safe just in case */
3489         list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3490                                  dirty_list) {
3491                 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3492                         cache_save_setup(cache, trans, path);
3493         }
3494
3495         btrfs_free_path(path);
3496         return 0;
3497 }
3498
3499 /*
3500  * transaction commit does final block group cache writeback during a
3501  * critical section where nothing is allowed to change the FS.  This is
3502  * required in order for the cache to actually match the block group,
3503  * but can introduce a lot of latency into the commit.
3504  *
3505  * So, btrfs_start_dirty_block_groups is here to kick off block group
3506  * cache IO.  There's a chance we'll have to redo some of it if the
3507  * block group changes again during the commit, but it greatly reduces
3508  * the commit latency by getting rid of the easy block groups while
3509  * we're still allowing others to join the commit.
3510  */
3511 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
3512                                    struct btrfs_root *root)
3513 {
3514         struct btrfs_block_group_cache *cache;
3515         struct btrfs_transaction *cur_trans = trans->transaction;
3516         int ret = 0;
3517         int should_put;
3518         struct btrfs_path *path = NULL;
3519         LIST_HEAD(dirty);
3520         struct list_head *io = &cur_trans->io_bgs;
3521         int num_started = 0;
3522         int loops = 0;
3523
3524         spin_lock(&cur_trans->dirty_bgs_lock);
3525         if (list_empty(&cur_trans->dirty_bgs)) {
3526                 spin_unlock(&cur_trans->dirty_bgs_lock);
3527                 return 0;
3528         }
3529         list_splice_init(&cur_trans->dirty_bgs, &dirty);
3530         spin_unlock(&cur_trans->dirty_bgs_lock);
3531
3532 again:
3533         /*
3534          * make sure all the block groups on our dirty list actually
3535          * exist
3536          */
3537         btrfs_create_pending_block_groups(trans, root);
3538
3539         if (!path) {
3540                 path = btrfs_alloc_path();
3541                 if (!path)
3542                         return -ENOMEM;
3543         }
3544
3545         /*
3546          * cache_write_mutex is here only to save us from balance or automatic
3547          * removal of empty block groups deleting this block group while we are
3548          * writing out the cache
3549          */
3550         mutex_lock(&trans->transaction->cache_write_mutex);
3551         while (!list_empty(&dirty)) {
3552                 cache = list_first_entry(&dirty,
3553                                          struct btrfs_block_group_cache,
3554                                          dirty_list);
3555                 /*
3556                  * this can happen if something re-dirties a block
3557                  * group that is already under IO.  Just wait for it to
3558                  * finish and then do it all again
3559                  */
3560                 if (!list_empty(&cache->io_list)) {
3561                         list_del_init(&cache->io_list);
3562                         btrfs_wait_cache_io(root, trans, cache,
3563                                             &cache->io_ctl, path,
3564                                             cache->key.objectid);
3565                         btrfs_put_block_group(cache);
3566                 }
3567
3568
3569                 /*
3570                  * btrfs_wait_cache_io uses the cache->dirty_list to decide
3571                  * if it should update the cache_state.  Don't delete
3572                  * until after we wait.
3573                  *
3574                  * Since we're not running in the commit critical section
3575                  * we need the dirty_bgs_lock to protect from update_block_group
3576                  */
3577                 spin_lock(&cur_trans->dirty_bgs_lock);
3578                 list_del_init(&cache->dirty_list);
3579                 spin_unlock(&cur_trans->dirty_bgs_lock);
3580
3581                 should_put = 1;
3582
3583                 cache_save_setup(cache, trans, path);
3584
3585                 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3586                         cache->io_ctl.inode = NULL;
3587                         ret = btrfs_write_out_cache(root, trans, cache, path);
3588                         if (ret == 0 && cache->io_ctl.inode) {
3589                                 num_started++;
3590                                 should_put = 0;
3591
3592                                 /*
3593                                  * the cache_write_mutex is protecting
3594                                  * the io_list
3595                                  */
3596                                 list_add_tail(&cache->io_list, io);
3597                         } else {
3598                                 /*
3599                                  * if we failed to write the cache, the
3600                                  * generation will be bad and life goes on
3601                                  */
3602                                 ret = 0;
3603                         }
3604                 }
3605                 if (!ret) {
3606                         ret = write_one_cache_group(trans, root, path, cache);
3607                         /*
3608                          * Our block group might still be attached to the list
3609                          * of new block groups in the transaction handle of some
3610                          * other task (struct btrfs_trans_handle->new_bgs). This
3611                          * means its block group item isn't yet in the extent
3612                          * tree. If this happens ignore the error, as we will
3613                          * try again later in the critical section of the
3614                          * transaction commit.
3615                          */
3616                         if (ret == -ENOENT) {
3617                                 ret = 0;
3618                                 spin_lock(&cur_trans->dirty_bgs_lock);
3619                                 if (list_empty(&cache->dirty_list)) {
3620                                         list_add_tail(&cache->dirty_list,
3621                                                       &cur_trans->dirty_bgs);
3622                                         btrfs_get_block_group(cache);
3623                                 }
3624                                 spin_unlock(&cur_trans->dirty_bgs_lock);
3625                         } else if (ret) {
3626                                 btrfs_abort_transaction(trans, root, ret);
3627                         }
3628                 }
3629
3630                 /* if its not on the io list, we need to put the block group */
3631                 if (should_put)
3632                         btrfs_put_block_group(cache);
3633
3634                 if (ret)
3635                         break;
3636
3637                 /*
3638                  * Avoid blocking other tasks for too long. It might even save
3639                  * us from writing caches for block groups that are going to be
3640                  * removed.
3641                  */
3642                 mutex_unlock(&trans->transaction->cache_write_mutex);
3643                 mutex_lock(&trans->transaction->cache_write_mutex);
3644         }
3645         mutex_unlock(&trans->transaction->cache_write_mutex);
3646
3647         /*
3648          * go through delayed refs for all the stuff we've just kicked off
3649          * and then loop back (just once)
3650          */
3651         ret = btrfs_run_delayed_refs(trans, root, 0);
3652         if (!ret && loops == 0) {
3653                 loops++;
3654                 spin_lock(&cur_trans->dirty_bgs_lock);
3655                 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3656                 /*
3657                  * dirty_bgs_lock protects us from concurrent block group
3658                  * deletes too (not just cache_write_mutex).
3659                  */
3660                 if (!list_empty(&dirty)) {
3661                         spin_unlock(&cur_trans->dirty_bgs_lock);
3662                         goto again;
3663                 }
3664                 spin_unlock(&cur_trans->dirty_bgs_lock);
3665         }
3666
3667         btrfs_free_path(path);
3668         return ret;
3669 }
3670
3671 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3672                                    struct btrfs_root *root)
3673 {
3674         struct btrfs_block_group_cache *cache;
3675         struct btrfs_transaction *cur_trans = trans->transaction;
3676         int ret = 0;
3677         int should_put;
3678         struct btrfs_path *path;
3679         struct list_head *io = &cur_trans->io_bgs;
3680         int num_started = 0;
3681
3682         path = btrfs_alloc_path();
3683         if (!path)
3684                 return -ENOMEM;
3685
3686         /*
3687          * We don't need the lock here since we are protected by the transaction
3688          * commit.  We want to do the cache_save_setup first and then run the
3689          * delayed refs to make sure we have the best chance at doing this all
3690          * in one shot.
3691          */
3692         while (!list_empty(&cur_trans->dirty_bgs)) {
3693                 cache = list_first_entry(&cur_trans->dirty_bgs,
3694                                          struct btrfs_block_group_cache,
3695                                          dirty_list);
3696
3697                 /*
3698                  * this can happen if cache_save_setup re-dirties a block
3699                  * group that is already under IO.  Just wait for it to
3700                  * finish and then do it all again
3701                  */
3702                 if (!list_empty(&cache->io_list)) {
3703                         list_del_init(&cache->io_list);
3704                         btrfs_wait_cache_io(root, trans, cache,
3705                                             &cache->io_ctl, path,
3706                                             cache->key.objectid);
3707                         btrfs_put_block_group(cache);
3708                 }
3709
3710                 /*
3711                  * don't remove from the dirty list until after we've waited
3712                  * on any pending IO
3713                  */
3714                 list_del_init(&cache->dirty_list);
3715                 should_put = 1;
3716
3717                 cache_save_setup(cache, trans, path);
3718
3719                 if (!ret)
3720                         ret = btrfs_run_delayed_refs(trans, root, (unsigned long) -1);
3721
3722                 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3723                         cache->io_ctl.inode = NULL;
3724                         ret = btrfs_write_out_cache(root, trans, cache, path);
3725                         if (ret == 0 && cache->io_ctl.inode) {
3726                                 num_started++;
3727                                 should_put = 0;
3728                                 list_add_tail(&cache->io_list, io);
3729                         } else {
3730                                 /*
3731                                  * if we failed to write the cache, the
3732                                  * generation will be bad and life goes on
3733                                  */
3734                                 ret = 0;
3735                         }
3736                 }
3737                 if (!ret) {
3738                         ret = write_one_cache_group(trans, root, path, cache);
3739                         if (ret)
3740                                 btrfs_abort_transaction(trans, root, ret);
3741                 }
3742
3743                 /* if its not on the io list, we need to put the block group */
3744                 if (should_put)
3745                         btrfs_put_block_group(cache);
3746         }
3747
3748         while (!list_empty(io)) {
3749                 cache = list_first_entry(io, struct btrfs_block_group_cache,
3750                                          io_list);
3751                 list_del_init(&cache->io_list);
3752                 btrfs_wait_cache_io(root, trans, cache,
3753                                     &cache->io_ctl, path, cache->key.objectid);
3754                 btrfs_put_block_group(cache);
3755         }
3756
3757         btrfs_free_path(path);
3758         return ret;
3759 }
3760
3761 int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3762 {
3763         struct btrfs_block_group_cache *block_group;
3764         int readonly = 0;
3765
3766         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
3767         if (!block_group || block_group->ro)
3768                 readonly = 1;
3769         if (block_group)
3770                 btrfs_put_block_group(block_group);
3771         return readonly;
3772 }
3773
3774 static const char *alloc_name(u64 flags)
3775 {
3776         switch (flags) {
3777         case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3778                 return "mixed";
3779         case BTRFS_BLOCK_GROUP_METADATA:
3780                 return "metadata";
3781         case BTRFS_BLOCK_GROUP_DATA:
3782                 return "data";
3783         case BTRFS_BLOCK_GROUP_SYSTEM:
3784                 return "system";
3785         default:
3786                 WARN_ON(1);
3787                 return "invalid-combination";
3788         };
3789 }
3790
3791 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3792                              u64 total_bytes, u64 bytes_used,
3793                              struct btrfs_space_info **space_info)
3794 {
3795         struct btrfs_space_info *found;
3796         int i;
3797         int factor;
3798         int ret;
3799
3800         if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3801                      BTRFS_BLOCK_GROUP_RAID10))
3802                 factor = 2;
3803         else
3804                 factor = 1;
3805
3806         found = __find_space_info(info, flags);
3807         if (found) {
3808                 spin_lock(&found->lock);
3809                 found->total_bytes += total_bytes;
3810                 found->disk_total += total_bytes * factor;
3811                 found->bytes_used += bytes_used;
3812                 found->disk_used += bytes_used * factor;
3813                 if (total_bytes > 0)
3814                         found->full = 0;
3815                 spin_unlock(&found->lock);
3816                 *space_info = found;
3817                 return 0;
3818         }
3819         found = kzalloc(sizeof(*found), GFP_NOFS);
3820         if (!found)
3821                 return -ENOMEM;
3822
3823         ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
3824         if (ret) {
3825                 kfree(found);
3826                 return ret;
3827         }
3828
3829         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3830                 INIT_LIST_HEAD(&found->block_groups[i]);
3831         init_rwsem(&found->groups_sem);
3832         spin_lock_init(&found->lock);
3833         found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3834         found->total_bytes = total_bytes;
3835         found->disk_total = total_bytes * factor;
3836         found->bytes_used = bytes_used;
3837         found->disk_used = bytes_used * factor;
3838         found->bytes_pinned = 0;
3839         found->bytes_reserved = 0;
3840         found->bytes_readonly = 0;
3841         found->bytes_may_use = 0;
3842         found->full = 0;
3843         found->max_extent_size = 0;
3844         found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3845         found->chunk_alloc = 0;
3846         found->flush = 0;
3847         init_waitqueue_head(&found->wait);
3848         INIT_LIST_HEAD(&found->ro_bgs);
3849
3850         ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
3851                                     info->space_info_kobj, "%s",
3852                                     alloc_name(found->flags));
3853         if (ret) {
3854                 kfree(found);
3855                 return ret;
3856         }
3857
3858         *space_info = found;
3859         list_add_rcu(&found->list, &info->space_info);
3860         if (flags & BTRFS_BLOCK_GROUP_DATA)
3861                 info->data_sinfo = found;
3862
3863         return ret;
3864 }
3865
3866 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3867 {
3868         u64 extra_flags = chunk_to_extended(flags) &
3869                                 BTRFS_EXTENDED_PROFILE_MASK;
3870
3871         write_seqlock(&fs_info->profiles_lock);
3872         if (flags & BTRFS_BLOCK_GROUP_DATA)
3873                 fs_info->avail_data_alloc_bits |= extra_flags;
3874         if (flags & BTRFS_BLOCK_GROUP_METADATA)
3875                 fs_info->avail_metadata_alloc_bits |= extra_flags;
3876         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3877                 fs_info->avail_system_alloc_bits |= extra_flags;
3878         write_sequnlock(&fs_info->profiles_lock);
3879 }
3880
3881 /*
3882  * returns target flags in extended format or 0 if restripe for this
3883  * chunk_type is not in progress
3884  *
3885  * should be called with either volume_mutex or balance_lock held
3886  */
3887 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3888 {
3889         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3890         u64 target = 0;
3891
3892         if (!bctl)
3893                 return 0;
3894
3895         if (flags & BTRFS_BLOCK_GROUP_DATA &&
3896             bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3897                 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3898         } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3899                    bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3900                 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3901         } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3902                    bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3903                 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3904         }
3905
3906         return target;
3907 }
3908
3909 /*
3910  * @flags: available profiles in extended format (see ctree.h)
3911  *
3912  * Returns reduced profile in chunk format.  If profile changing is in
3913  * progress (either running or paused) picks the target profile (if it's
3914  * already available), otherwise falls back to plain reducing.
3915  */
3916 static u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
3917 {
3918         u64 num_devices = root->fs_info->fs_devices->rw_devices;
3919         u64 target;
3920         u64 raid_type;
3921         u64 allowed = 0;
3922
3923         /*
3924          * see if restripe for this chunk_type is in progress, if so
3925          * try to reduce to the target profile
3926          */
3927         spin_lock(&root->fs_info->balance_lock);
3928         target = get_restripe_target(root->fs_info, flags);
3929         if (target) {
3930                 /* pick target profile only if it's already available */
3931                 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
3932                         spin_unlock(&root->fs_info->balance_lock);
3933                         return extended_to_chunk(target);
3934                 }
3935         }
3936         spin_unlock(&root->fs_info->balance_lock);
3937
3938         /* First, mask out the RAID levels which aren't possible */
3939         for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3940                 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
3941                         allowed |= btrfs_raid_group[raid_type];
3942         }
3943         allowed &= flags;
3944
3945         if (allowed & BTRFS_BLOCK_GROUP_RAID6)
3946                 allowed = BTRFS_BLOCK_GROUP_RAID6;
3947         else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
3948                 allowed = BTRFS_BLOCK_GROUP_RAID5;
3949         else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
3950                 allowed = BTRFS_BLOCK_GROUP_RAID10;
3951         else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
3952                 allowed = BTRFS_BLOCK_GROUP_RAID1;
3953         else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
3954                 allowed = BTRFS_BLOCK_GROUP_RAID0;
3955
3956         flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
3957
3958         return extended_to_chunk(flags | allowed);
3959 }
3960
3961 static u64 get_alloc_profile(struct btrfs_root *root, u64 orig_flags)
3962 {
3963         unsigned seq;
3964         u64 flags;
3965
3966         do {
3967                 flags = orig_flags;
3968                 seq = read_seqbegin(&root->fs_info->profiles_lock);
3969
3970                 if (flags & BTRFS_BLOCK_GROUP_DATA)
3971                         flags |= root->fs_info->avail_data_alloc_bits;
3972                 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3973                         flags |= root->fs_info->avail_system_alloc_bits;
3974                 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3975                         flags |= root->fs_info->avail_metadata_alloc_bits;
3976         } while (read_seqretry(&root->fs_info->profiles_lock, seq));
3977
3978         return btrfs_reduce_alloc_profile(root, flags);
3979 }
3980
3981 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
3982 {
3983         u64 flags;
3984         u64 ret;
3985
3986         if (data)
3987                 flags = BTRFS_BLOCK_GROUP_DATA;
3988         else if (root == root->fs_info->chunk_root)
3989                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
3990         else
3991                 flags = BTRFS_BLOCK_GROUP_METADATA;
3992
3993         ret = get_alloc_profile(root, flags);
3994         return ret;
3995 }
3996
3997 int btrfs_alloc_data_chunk_ondemand(struct inode *inode, u64 bytes)
3998 {
3999         struct btrfs_space_info *data_sinfo;
4000         struct btrfs_root *root = BTRFS_I(inode)->root;
4001         struct btrfs_fs_info *fs_info = root->fs_info;
4002         u64 used;
4003         int ret = 0;
4004         int need_commit = 2;
4005         int have_pinned_space;
4006
4007         /* make sure bytes are sectorsize aligned */
4008         bytes = ALIGN(bytes, root->sectorsize);
4009
4010         if (btrfs_is_free_space_inode(inode)) {
4011                 need_commit = 0;
4012                 ASSERT(current->journal_info);
4013         }
4014
4015         data_sinfo = fs_info->data_sinfo;
4016         if (!data_sinfo)
4017                 goto alloc;
4018
4019 again:
4020         /* make sure we have enough space to handle the data first */
4021         spin_lock(&data_sinfo->lock);
4022         used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
4023                 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
4024                 data_sinfo->bytes_may_use;
4025
4026         if (used + bytes > data_sinfo->total_bytes) {
4027                 struct btrfs_trans_handle *trans;
4028
4029                 /*
4030                  * if we don't have enough free bytes in this space then we need
4031                  * to alloc a new chunk.
4032                  */
4033                 if (!data_sinfo->full) {
4034                         u64 alloc_target;
4035
4036                         data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4037                         spin_unlock(&data_sinfo->lock);
4038 alloc:
4039                         alloc_target = btrfs_get_alloc_profile(root, 1);
4040                         /*
4041                          * It is ugly that we don't call nolock join
4042                          * transaction for the free space inode case here.
4043                          * But it is safe because we only do the data space
4044                          * reservation for the free space cache in the
4045                          * transaction context, the common join transaction
4046                          * just increase the counter of the current transaction
4047                          * handler, doesn't try to acquire the trans_lock of
4048                          * the fs.
4049                          */
4050                         trans = btrfs_join_transaction(root);
4051                         if (IS_ERR(trans))
4052                                 return PTR_ERR(trans);
4053
4054                         ret = do_chunk_alloc(trans, root->fs_info->extent_root,
4055                                              alloc_target,
4056                                              CHUNK_ALLOC_NO_FORCE);
4057                         btrfs_end_transaction(trans, root);
4058                         if (ret < 0) {
4059                                 if (ret != -ENOSPC)
4060                                         return ret;
4061                                 else {
4062                                         have_pinned_space = 1;
4063                                         goto commit_trans;
4064                                 }
4065                         }
4066
4067                         if (!data_sinfo)
4068                                 data_sinfo = fs_info->data_sinfo;
4069
4070                         goto again;
4071                 }
4072
4073                 /*
4074                  * If we don't have enough pinned space to deal with this
4075                  * allocation, and no removed chunk in current transaction,
4076                  * don't bother committing the transaction.
4077                  */
4078                 have_pinned_space = percpu_counter_compare(
4079                         &data_sinfo->total_bytes_pinned,
4080                         used + bytes - data_sinfo->total_bytes);
4081                 spin_unlock(&data_sinfo->lock);
4082
4083                 /* commit the current transaction and try again */
4084 commit_trans:
4085                 if (need_commit &&
4086                     !atomic_read(&root->fs_info->open_ioctl_trans)) {
4087                         need_commit--;
4088
4089                         if (need_commit > 0) {
4090                                 btrfs_start_delalloc_roots(fs_info, 0, -1);
4091                                 btrfs_wait_ordered_roots(fs_info, -1);
4092                         }
4093
4094                         trans = btrfs_join_transaction(root);
4095                         if (IS_ERR(trans))
4096                                 return PTR_ERR(trans);
4097                         if (have_pinned_space >= 0 ||
4098                             test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4099                                      &trans->transaction->flags) ||
4100                             need_commit > 0) {
4101                                 ret = btrfs_commit_transaction(trans, root);
4102                                 if (ret)
4103                                         return ret;
4104                                 /*
4105                                  * The cleaner kthread might still be doing iput
4106                                  * operations. Wait for it to finish so that
4107                                  * more space is released.
4108                                  */
4109                                 mutex_lock(&root->fs_info->cleaner_delayed_iput_mutex);
4110                                 mutex_unlock(&root->fs_info->cleaner_delayed_iput_mutex);
4111                                 goto again;
4112                         } else {
4113                                 btrfs_end_transaction(trans, root);
4114                         }
4115                 }
4116
4117                 trace_btrfs_space_reservation(root->fs_info,
4118                                               "space_info:enospc",
4119                                               data_sinfo->flags, bytes, 1);
4120                 return -ENOSPC;
4121         }
4122         data_sinfo->bytes_may_use += bytes;
4123         trace_btrfs_space_reservation(root->fs_info, "space_info",
4124                                       data_sinfo->flags, bytes, 1);
4125         spin_unlock(&data_sinfo->lock);
4126
4127         return ret;
4128 }
4129
4130 /*
4131  * New check_data_free_space() with ability for precious data reservation
4132  * Will replace old btrfs_check_data_free_space(), but for patch split,
4133  * add a new function first and then replace it.
4134  */
4135 int btrfs_check_data_free_space(struct inode *inode, u64 start, u64 len)
4136 {
4137         struct btrfs_root *root = BTRFS_I(inode)->root;
4138         int ret;
4139
4140         /* align the range */
4141         len = round_up(start + len, root->sectorsize) -
4142               round_down(start, root->sectorsize);
4143         start = round_down(start, root->sectorsize);
4144
4145         ret = btrfs_alloc_data_chunk_ondemand(inode, len);
4146         if (ret < 0)
4147                 return ret;
4148
4149         /*
4150          * Use new btrfs_qgroup_reserve_data to reserve precious data space
4151          *
4152          * TODO: Find a good method to avoid reserve data space for NOCOW
4153          * range, but don't impact performance on quota disable case.
4154          */
4155         ret = btrfs_qgroup_reserve_data(inode, start, len);
4156         return ret;
4157 }
4158
4159 /*
4160  * Called if we need to clear a data reservation for this inode
4161  * Normally in a error case.
4162  *
4163  * This one will *NOT* use accurate qgroup reserved space API, just for case
4164  * which we can't sleep and is sure it won't affect qgroup reserved space.
4165  * Like clear_bit_hook().
4166  */
4167 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4168                                             u64 len)
4169 {
4170         struct btrfs_root *root = BTRFS_I(inode)->root;
4171         struct btrfs_space_info *data_sinfo;
4172
4173         /* Make sure the range is aligned to sectorsize */
4174         len = round_up(start + len, root->sectorsize) -
4175               round_down(start, root->sectorsize);
4176         start = round_down(start, root->sectorsize);
4177
4178         data_sinfo = root->fs_info->data_sinfo;
4179         spin_lock(&data_sinfo->lock);
4180         if (WARN_ON(data_sinfo->bytes_may_use < len))
4181                 data_sinfo->bytes_may_use = 0;
4182         else
4183                 data_sinfo->bytes_may_use -= len;
4184         trace_btrfs_space_reservation(root->fs_info, "space_info",
4185                                       data_sinfo->flags, len, 0);
4186         spin_unlock(&data_sinfo->lock);
4187 }
4188
4189 /*
4190  * Called if we need to clear a data reservation for this inode
4191  * Normally in a error case.
4192  *
4193  * This one will handle the per-indoe data rsv map for accurate reserved
4194  * space framework.
4195  */
4196 void btrfs_free_reserved_data_space(struct inode *inode, u64 start, u64 len)
4197 {
4198         btrfs_free_reserved_data_space_noquota(inode, start, len);
4199         btrfs_qgroup_free_data(inode, start, len);
4200 }
4201
4202 static void force_metadata_allocation(struct btrfs_fs_info *info)
4203 {
4204         struct list_head *head = &info->space_info;
4205         struct btrfs_space_info *found;
4206
4207         rcu_read_lock();
4208         list_for_each_entry_rcu(found, head, list) {
4209                 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4210                         found->force_alloc = CHUNK_ALLOC_FORCE;
4211         }
4212         rcu_read_unlock();
4213 }
4214
4215 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4216 {
4217         return (global->size << 1);
4218 }
4219
4220 static int should_alloc_chunk(struct btrfs_root *root,
4221                               struct btrfs_space_info *sinfo, int force)
4222 {
4223         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4224         u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
4225         u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
4226         u64 thresh;
4227
4228         if (force == CHUNK_ALLOC_FORCE)
4229                 return 1;
4230
4231         /*
4232          * We need to take into account the global rsv because for all intents
4233          * and purposes it's used space.  Don't worry about locking the
4234          * global_rsv, it doesn't change except when the transaction commits.
4235          */
4236         if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
4237                 num_allocated += calc_global_rsv_need_space(global_rsv);
4238
4239         /*
4240          * in limited mode, we want to have some free space up to
4241          * about 1% of the FS size.
4242          */
4243         if (force == CHUNK_ALLOC_LIMITED) {
4244                 thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
4245                 thresh = max_t(u64, 64 * 1024 * 1024,
4246                                div_factor_fine(thresh, 1));
4247
4248                 if (num_bytes - num_allocated < thresh)
4249                         return 1;
4250         }
4251
4252         if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
4253                 return 0;
4254         return 1;
4255 }
4256
4257 static u64 get_profile_num_devs(struct btrfs_root *root, u64 type)
4258 {
4259         u64 num_dev;
4260
4261         if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4262                     BTRFS_BLOCK_GROUP_RAID0 |
4263                     BTRFS_BLOCK_GROUP_RAID5 |
4264                     BTRFS_BLOCK_GROUP_RAID6))
4265                 num_dev = root->fs_info->fs_devices->rw_devices;
4266         else if (type & BTRFS_BLOCK_GROUP_RAID1)
4267                 num_dev = 2;
4268         else
4269                 num_dev = 1;    /* DUP or single */
4270
4271         return num_dev;
4272 }
4273
4274 /*
4275  * If @is_allocation is true, reserve space in the system space info necessary
4276  * for allocating a chunk, otherwise if it's false, reserve space necessary for
4277  * removing a chunk.
4278  */
4279 void check_system_chunk(struct btrfs_trans_handle *trans,
4280                         struct btrfs_root *root,
4281                         u64 type)
4282 {
4283         struct btrfs_space_info *info;
4284         u64 left;
4285         u64 thresh;
4286         int ret = 0;
4287         u64 num_devs;
4288
4289         /*
4290          * Needed because we can end up allocating a system chunk and for an
4291          * atomic and race free space reservation in the chunk block reserve.
4292          */
4293         ASSERT(mutex_is_locked(&root->fs_info->chunk_mutex));
4294
4295         info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4296         spin_lock(&info->lock);
4297         left = info->total_bytes - info->bytes_used - info->bytes_pinned -
4298                 info->bytes_reserved - info->bytes_readonly -
4299                 info->bytes_may_use;
4300         spin_unlock(&info->lock);
4301
4302         num_devs = get_profile_num_devs(root, type);
4303
4304         /* num_devs device items to update and 1 chunk item to add or remove */
4305         thresh = btrfs_calc_trunc_metadata_size(root, num_devs) +
4306                 btrfs_calc_trans_metadata_size(root, 1);
4307
4308         if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
4309                 btrfs_info(root->fs_info, "left=%llu, need=%llu, flags=%llu",
4310                         left, thresh, type);
4311                 dump_space_info(info, 0, 0);
4312         }
4313
4314         if (left < thresh) {
4315                 u64 flags;
4316
4317                 flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
4318                 /*
4319                  * Ignore failure to create system chunk. We might end up not
4320                  * needing it, as we might not need to COW all nodes/leafs from
4321                  * the paths we visit in the chunk tree (they were already COWed
4322                  * or created in the current transaction for example).
4323                  */
4324                 ret = btrfs_alloc_chunk(trans, root, flags);
4325         }
4326
4327         if (!ret) {
4328                 ret = btrfs_block_rsv_add(root->fs_info->chunk_root,
4329                                           &root->fs_info->chunk_block_rsv,
4330                                           thresh, BTRFS_RESERVE_NO_FLUSH);
4331                 if (!ret)
4332                         trans->chunk_bytes_reserved += thresh;
4333         }
4334 }
4335
4336 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
4337                           struct btrfs_root *extent_root, u64 flags, int force)
4338 {
4339         struct btrfs_space_info *space_info;
4340         struct btrfs_fs_info *fs_info = extent_root->fs_info;
4341         int wait_for_alloc = 0;
4342         int ret = 0;
4343
4344         /* Don't re-enter if we're already allocating a chunk */
4345         if (trans->allocating_chunk)
4346                 return -ENOSPC;
4347
4348         space_info = __find_space_info(extent_root->fs_info, flags);
4349         if (!space_info) {
4350                 ret = update_space_info(extent_root->fs_info, flags,
4351                                         0, 0, &space_info);
4352                 BUG_ON(ret); /* -ENOMEM */
4353         }
4354         BUG_ON(!space_info); /* Logic error */
4355
4356 again:
4357         spin_lock(&space_info->lock);
4358         if (force < space_info->force_alloc)
4359                 force = space_info->force_alloc;
4360         if (space_info->full) {
4361                 if (should_alloc_chunk(extent_root, space_info, force))
4362                         ret = -ENOSPC;
4363                 else
4364                         ret = 0;
4365                 spin_unlock(&space_info->lock);
4366                 return ret;
4367         }
4368
4369         if (!should_alloc_chunk(extent_root, space_info, force)) {
4370                 spin_unlock(&space_info->lock);
4371                 return 0;
4372         } else if (space_info->chunk_alloc) {
4373                 wait_for_alloc = 1;
4374         } else {
4375                 space_info->chunk_alloc = 1;
4376         }
4377
4378         spin_unlock(&space_info->lock);
4379
4380         mutex_lock(&fs_info->chunk_mutex);
4381
4382         /*
4383          * The chunk_mutex is held throughout the entirety of a chunk
4384          * allocation, so once we've acquired the chunk_mutex we know that the
4385          * other guy is done and we need to recheck and see if we should
4386          * allocate.
4387          */
4388         if (wait_for_alloc) {
4389                 mutex_unlock(&fs_info->chunk_mutex);
4390                 wait_for_alloc = 0;
4391                 goto again;
4392         }
4393
4394         trans->allocating_chunk = true;
4395
4396         /*
4397          * If we have mixed data/metadata chunks we want to make sure we keep
4398          * allocating mixed chunks instead of individual chunks.
4399          */
4400         if (btrfs_mixed_space_info(space_info))
4401                 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4402
4403         /*
4404          * if we're doing a data chunk, go ahead and make sure that
4405          * we keep a reasonable number of metadata chunks allocated in the
4406          * FS as well.
4407          */
4408         if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4409                 fs_info->data_chunk_allocations++;
4410                 if (!(fs_info->data_chunk_allocations %
4411                       fs_info->metadata_ratio))
4412                         force_metadata_allocation(fs_info);
4413         }
4414
4415         /*
4416          * Check if we have enough space in SYSTEM chunk because we may need
4417          * to update devices.
4418          */
4419         check_system_chunk(trans, extent_root, flags);
4420
4421         ret = btrfs_alloc_chunk(trans, extent_root, flags);
4422         trans->allocating_chunk = false;
4423
4424         spin_lock(&space_info->lock);
4425         if (ret < 0 && ret != -ENOSPC)
4426                 goto out;
4427         if (ret)
4428                 space_info->full = 1;
4429         else
4430                 ret = 1;
4431
4432         space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4433 out:
4434         space_info->chunk_alloc = 0;
4435         spin_unlock(&space_info->lock);
4436         mutex_unlock(&fs_info->chunk_mutex);
4437         /*
4438          * When we allocate a new chunk we reserve space in the chunk block
4439          * reserve to make sure we can COW nodes/leafs in the chunk tree or
4440          * add new nodes/leafs to it if we end up needing to do it when
4441          * inserting the chunk item and updating device items as part of the
4442          * second phase of chunk allocation, performed by
4443          * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4444          * large number of new block groups to create in our transaction
4445          * handle's new_bgs list to avoid exhausting the chunk block reserve
4446          * in extreme cases - like having a single transaction create many new
4447          * block groups when starting to write out the free space caches of all
4448          * the block groups that were made dirty during the lifetime of the
4449          * transaction.
4450          */
4451         if (trans->can_flush_pending_bgs &&
4452             trans->chunk_bytes_reserved >= (2 * 1024 * 1024ull)) {
4453                 btrfs_create_pending_block_groups(trans, trans->root);
4454                 btrfs_trans_release_chunk_metadata(trans);
4455         }
4456         return ret;
4457 }
4458
4459 static int can_overcommit(struct btrfs_root *root,
4460                           struct btrfs_space_info *space_info, u64 bytes,
4461                           enum btrfs_reserve_flush_enum flush)
4462 {
4463         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
4464         u64 profile = btrfs_get_alloc_profile(root, 0);
4465         u64 space_size;
4466         u64 avail;
4467         u64 used;
4468
4469         used = space_info->bytes_used + space_info->bytes_reserved +
4470                 space_info->bytes_pinned + space_info->bytes_readonly;
4471
4472         /*
4473          * We only want to allow over committing if we have lots of actual space
4474          * free, but if we don't have enough space to handle the global reserve
4475          * space then we could end up having a real enospc problem when trying
4476          * to allocate a chunk or some other such important allocation.
4477          */
4478         spin_lock(&global_rsv->lock);
4479         space_size = calc_global_rsv_need_space(global_rsv);
4480         spin_unlock(&global_rsv->lock);
4481         if (used + space_size >= space_info->total_bytes)
4482                 return 0;
4483
4484         used += space_info->bytes_may_use;
4485
4486         spin_lock(&root->fs_info->free_chunk_lock);
4487         avail = root->fs_info->free_chunk_space;
4488         spin_unlock(&root->fs_info->free_chunk_lock);
4489
4490         /*
4491          * If we have dup, raid1 or raid10 then only half of the free
4492          * space is actually useable.  For raid56, the space info used
4493          * doesn't include the parity drive, so we don't have to
4494          * change the math
4495          */
4496         if (profile & (BTRFS_BLOCK_GROUP_DUP |
4497                        BTRFS_BLOCK_GROUP_RAID1 |
4498                        BTRFS_BLOCK_GROUP_RAID10))
4499                 avail >>= 1;
4500
4501         /*
4502          * If we aren't flushing all things, let us overcommit up to
4503          * 1/2th of the space. If we can flush, don't let us overcommit
4504          * too much, let it overcommit up to 1/8 of the space.
4505          */
4506         if (flush == BTRFS_RESERVE_FLUSH_ALL)
4507                 avail >>= 3;
4508         else
4509                 avail >>= 1;
4510
4511         if (used + bytes < space_info->total_bytes + avail)
4512                 return 1;
4513         return 0;
4514 }
4515
4516 static void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
4517                                          unsigned long nr_pages, int nr_items)
4518 {
4519         struct super_block *sb = root->fs_info->sb;
4520
4521         if (down_read_trylock(&sb->s_umount)) {
4522                 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4523                 up_read(&sb->s_umount);
4524         } else {
4525                 /*
4526                  * We needn't worry the filesystem going from r/w to r/o though
4527                  * we don't acquire ->s_umount mutex, because the filesystem
4528                  * should guarantee the delalloc inodes list be empty after
4529                  * the filesystem is readonly(all dirty pages are written to
4530                  * the disk).
4531                  */
4532                 btrfs_start_delalloc_roots(root->fs_info, 0, nr_items);
4533                 if (!current->journal_info)
4534                         btrfs_wait_ordered_roots(root->fs_info, nr_items);
4535         }
4536 }
4537
4538 static inline int calc_reclaim_items_nr(struct btrfs_root *root, u64 to_reclaim)
4539 {
4540         u64 bytes;
4541         int nr;
4542
4543         bytes = btrfs_calc_trans_metadata_size(root, 1);
4544         nr = (int)div64_u64(to_reclaim, bytes);
4545         if (!nr)
4546                 nr = 1;
4547         return nr;
4548 }
4549
4550 #define EXTENT_SIZE_PER_ITEM    (256 * 1024)
4551
4552 /*
4553  * shrink metadata reservation for delalloc
4554  */
4555 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
4556                             bool wait_ordered)
4557 {
4558         struct btrfs_block_rsv *block_rsv;
4559         struct btrfs_space_info *space_info;
4560         struct btrfs_trans_handle *trans;
4561         u64 delalloc_bytes;
4562         u64 max_reclaim;
4563         long time_left;
4564         unsigned long nr_pages;
4565         int loops;
4566         int items;
4567         enum btrfs_reserve_flush_enum flush;
4568
4569         /* Calc the number of the pages we need flush for space reservation */
4570         items = calc_reclaim_items_nr(root, to_reclaim);
4571         to_reclaim = items * EXTENT_SIZE_PER_ITEM;
4572
4573         trans = (struct btrfs_trans_handle *)current->journal_info;
4574         block_rsv = &root->fs_info->delalloc_block_rsv;
4575         space_info = block_rsv->space_info;
4576
4577         delalloc_bytes = percpu_counter_sum_positive(
4578                                                 &root->fs_info->delalloc_bytes);
4579         if (delalloc_bytes == 0) {
4580                 if (trans)
4581                         return;
4582                 if (wait_ordered)
4583                         btrfs_wait_ordered_roots(root->fs_info, items);
4584                 return;
4585         }
4586
4587         loops = 0;
4588         while (delalloc_bytes && loops < 3) {
4589                 max_reclaim = min(delalloc_bytes, to_reclaim);
4590                 nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
4591                 btrfs_writeback_inodes_sb_nr(root, nr_pages, items);
4592                 /*
4593                  * We need to wait for the async pages to actually start before
4594                  * we do anything.
4595                  */
4596                 max_reclaim = atomic_read(&root->fs_info->async_delalloc_pages);
4597                 if (!max_reclaim)
4598                         goto skip_async;
4599
4600                 if (max_reclaim <= nr_pages)
4601                         max_reclaim = 0;
4602                 else
4603                         max_reclaim -= nr_pages;
4604
4605                 wait_event(root->fs_info->async_submit_wait,
4606                            atomic_read(&root->fs_info->async_delalloc_pages) <=
4607                            (int)max_reclaim);
4608 skip_async:
4609                 if (!trans)
4610                         flush = BTRFS_RESERVE_FLUSH_ALL;
4611                 else
4612                         flush = BTRFS_RESERVE_NO_FLUSH;
4613                 spin_lock(&space_info->lock);
4614                 if (can_overcommit(root, space_info, orig, flush)) {
4615                         spin_unlock(&space_info->lock);
4616                         break;
4617                 }
4618                 spin_unlock(&space_info->lock);
4619
4620                 loops++;
4621                 if (wait_ordered && !trans) {
4622                         btrfs_wait_ordered_roots(root->fs_info, items);
4623                 } else {
4624                         time_left = schedule_timeout_killable(1);
4625                         if (time_left)
4626                                 break;
4627                 }
4628                 delalloc_bytes = percpu_counter_sum_positive(
4629                                                 &root->fs_info->delalloc_bytes);
4630         }
4631 }
4632
4633 /**
4634  * maybe_commit_transaction - possibly commit the transaction if its ok to
4635  * @root - the root we're allocating for
4636  * @bytes - the number of bytes we want to reserve
4637  * @force - force the commit
4638  *
4639  * This will check to make sure that committing the transaction will actually
4640  * get us somewhere and then commit the transaction if it does.  Otherwise it
4641  * will return -ENOSPC.
4642  */
4643 static int may_commit_transaction(struct btrfs_root *root,
4644                                   struct btrfs_space_info *space_info,
4645                                   u64 bytes, int force)
4646 {
4647         struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
4648         struct btrfs_trans_handle *trans;
4649
4650         trans = (struct btrfs_trans_handle *)current->journal_info;
4651         if (trans)
4652                 return -EAGAIN;
4653
4654         if (force)
4655                 goto commit;
4656
4657         /* See if there is enough pinned space to make this reservation */
4658         if (percpu_counter_compare(&space_info->total_bytes_pinned,
4659                                    bytes) >= 0)
4660                 goto commit;
4661
4662         /*
4663          * See if there is some space in the delayed insertion reservation for
4664          * this reservation.
4665          */
4666         if (space_info != delayed_rsv->space_info)
4667                 return -ENOSPC;
4668
4669         spin_lock(&delayed_rsv->lock);
4670         if (percpu_counter_compare(&space_info->total_bytes_pinned,
4671                                    bytes - delayed_rsv->size) >= 0) {
4672                 spin_unlock(&delayed_rsv->lock);
4673                 return -ENOSPC;
4674         }
4675         spin_unlock(&delayed_rsv->lock);
4676
4677 commit:
4678         trans = btrfs_join_transaction(root);
4679         if (IS_ERR(trans))
4680                 return -ENOSPC;
4681
4682         return btrfs_commit_transaction(trans, root);
4683 }
4684
4685 enum flush_state {
4686         FLUSH_DELAYED_ITEMS_NR  =       1,
4687         FLUSH_DELAYED_ITEMS     =       2,
4688         FLUSH_DELALLOC          =       3,
4689         FLUSH_DELALLOC_WAIT     =       4,
4690         ALLOC_CHUNK             =       5,
4691         COMMIT_TRANS            =       6,
4692 };
4693
4694 static int flush_space(struct btrfs_root *root,
4695                        struct btrfs_space_info *space_info, u64 num_bytes,
4696                        u64 orig_bytes, int state)
4697 {
4698         struct btrfs_trans_handle *trans;
4699         int nr;
4700         int ret = 0;
4701
4702         switch (state) {
4703         case FLUSH_DELAYED_ITEMS_NR:
4704         case FLUSH_DELAYED_ITEMS:
4705                 if (state == FLUSH_DELAYED_ITEMS_NR)
4706                         nr = calc_reclaim_items_nr(root, num_bytes) * 2;
4707                 else
4708                         nr = -1;
4709
4710                 trans = btrfs_join_transaction(root);
4711                 if (IS_ERR(trans)) {
4712                         ret = PTR_ERR(trans);
4713                         break;
4714                 }
4715                 ret = btrfs_run_delayed_items_nr(trans, root, nr);
4716                 btrfs_end_transaction(trans, root);
4717                 break;
4718         case FLUSH_DELALLOC:
4719         case FLUSH_DELALLOC_WAIT:
4720                 shrink_delalloc(root, num_bytes * 2, orig_bytes,
4721                                 state == FLUSH_DELALLOC_WAIT);
4722                 break;
4723         case ALLOC_CHUNK:
4724                 trans = btrfs_join_transaction(root);
4725                 if (IS_ERR(trans)) {
4726                         ret = PTR_ERR(trans);
4727                         break;
4728                 }
4729                 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
4730                                      btrfs_get_alloc_profile(root, 0),
4731                                      CHUNK_ALLOC_NO_FORCE);
4732                 btrfs_end_transaction(trans, root);
4733                 if (ret == -ENOSPC)
4734                         ret = 0;
4735                 break;
4736         case COMMIT_TRANS:
4737                 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4738                 break;
4739         default:
4740                 ret = -ENOSPC;
4741                 break;
4742         }
4743
4744         return ret;
4745 }
4746
4747 static inline u64
4748 btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
4749                                  struct btrfs_space_info *space_info)
4750 {
4751         u64 used;
4752         u64 expected;
4753         u64 to_reclaim;
4754
4755         to_reclaim = min_t(u64, num_online_cpus() * 1024 * 1024,
4756                                 16 * 1024 * 1024);
4757         spin_lock(&space_info->lock);
4758         if (can_overcommit(root, space_info, to_reclaim,
4759                            BTRFS_RESERVE_FLUSH_ALL)) {
4760                 to_reclaim = 0;
4761                 goto out;
4762         }
4763
4764         used = space_info->bytes_used + space_info->bytes_reserved +
4765                space_info->bytes_pinned + space_info->bytes_readonly +
4766                space_info->bytes_may_use;
4767         if (can_overcommit(root, space_info, 1024 * 1024,
4768                            BTRFS_RESERVE_FLUSH_ALL))
4769                 expected = div_factor_fine(space_info->total_bytes, 95);
4770         else
4771                 expected = div_factor_fine(space_info->total_bytes, 90);
4772
4773         if (used > expected)
4774                 to_reclaim = used - expected;
4775         else
4776                 to_reclaim = 0;
4777         to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4778                                      space_info->bytes_reserved);
4779 out:
4780         spin_unlock(&space_info->lock);
4781
4782         return to_reclaim;
4783 }
4784
4785 static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
4786                                         struct btrfs_fs_info *fs_info, u64 used)
4787 {
4788         u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4789
4790         /* If we're just plain full then async reclaim just slows us down. */
4791         if (space_info->bytes_used >= thresh)
4792                 return 0;
4793
4794         return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4795                 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4796 }
4797
4798 static int btrfs_need_do_async_reclaim(struct btrfs_space_info *space_info,
4799                                        struct btrfs_fs_info *fs_info,
4800                                        int flush_state)
4801 {
4802         u64 used;
4803
4804         spin_lock(&space_info->lock);
4805         /*
4806          * We run out of space and have not got any free space via flush_space,
4807          * so don't bother doing async reclaim.
4808          */
4809         if (flush_state > COMMIT_TRANS && space_info->full) {
4810                 spin_unlock(&space_info->lock);
4811                 return 0;
4812         }
4813
4814         used = space_info->bytes_used + space_info->bytes_reserved +
4815                space_info->bytes_pinned + space_info->bytes_readonly +
4816                space_info->bytes_may_use;
4817         if (need_do_async_reclaim(space_info, fs_info, used)) {
4818                 spin_unlock(&space_info->lock);
4819                 return 1;
4820         }
4821         spin_unlock(&space_info->lock);
4822
4823         return 0;
4824 }
4825
4826 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4827 {
4828         struct btrfs_fs_info *fs_info;
4829         struct btrfs_space_info *space_info;
4830         u64 to_reclaim;
4831         int flush_state;
4832
4833         fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4834         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4835
4836         to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
4837                                                       space_info);
4838         if (!to_reclaim)
4839                 return;
4840
4841         flush_state = FLUSH_DELAYED_ITEMS_NR;
4842         do {
4843                 flush_space(fs_info->fs_root, space_info, to_reclaim,
4844                             to_reclaim, flush_state);
4845                 flush_state++;
4846                 if (!btrfs_need_do_async_reclaim(space_info, fs_info,
4847                                                  flush_state))
4848                         return;
4849         } while (flush_state < COMMIT_TRANS);
4850 }
4851
4852 void btrfs_init_async_reclaim_work(struct work_struct *work)
4853 {
4854         INIT_WORK(work, btrfs_async_reclaim_metadata_space);
4855 }
4856
4857 /**
4858  * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
4859  * @root - the root we're allocating for
4860  * @block_rsv - the block_rsv we're allocating for
4861  * @orig_bytes - the number of bytes we want
4862  * @flush - whether or not we can flush to make our reservation
4863  *
4864  * This will reserve orgi_bytes number of bytes from the space info associated
4865  * with the block_rsv.  If there is not enough space it will make an attempt to
4866  * flush out space to make room.  It will do this by flushing delalloc if
4867  * possible or committing the transaction.  If flush is 0 then no attempts to
4868  * regain reservations will be made and this will fail if there is not enough
4869  * space already.
4870  */
4871 static int reserve_metadata_bytes(struct btrfs_root *root,
4872                                   struct btrfs_block_rsv *block_rsv,
4873                                   u64 orig_bytes,
4874                                   enum btrfs_reserve_flush_enum flush)
4875 {
4876         struct btrfs_space_info *space_info = block_rsv->space_info;
4877         u64 used;
4878         u64 num_bytes = orig_bytes;
4879         int flush_state = FLUSH_DELAYED_ITEMS_NR;
4880         int ret = 0;
4881         bool flushing = false;
4882
4883 again:
4884         ret = 0;
4885         spin_lock(&space_info->lock);
4886         /*
4887          * We only want to wait if somebody other than us is flushing and we
4888          * are actually allowed to flush all things.
4889          */
4890         while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
4891                space_info->flush) {
4892                 spin_unlock(&space_info->lock);
4893                 /*
4894                  * If we have a trans handle we can't wait because the flusher
4895                  * may have to commit the transaction, which would mean we would
4896                  * deadlock since we are waiting for the flusher to finish, but
4897                  * hold the current transaction open.
4898                  */
4899                 if (current->journal_info)
4900                         return -EAGAIN;
4901                 ret = wait_event_killable(space_info->wait, !space_info->flush);
4902                 /* Must have been killed, return */
4903                 if (ret)
4904                         return -EINTR;
4905
4906                 spin_lock(&space_info->lock);
4907         }
4908
4909         ret = -ENOSPC;
4910         used = space_info->bytes_used + space_info->bytes_reserved +
4911                 space_info->bytes_pinned + space_info->bytes_readonly +
4912                 space_info->bytes_may_use;
4913
4914         /*
4915          * The idea here is that we've not already over-reserved the block group
4916          * then we can go ahead and save our reservation first and then start
4917          * flushing if we need to.  Otherwise if we've already overcommitted
4918          * lets start flushing stuff first and then come back and try to make
4919          * our reservation.
4920          */
4921         if (used <= space_info->total_bytes) {
4922                 if (used + orig_bytes <= space_info->total_bytes) {
4923                         space_info->bytes_may_use += orig_bytes;
4924                         trace_btrfs_space_reservation(root->fs_info,
4925                                 "space_info", space_info->flags, orig_bytes, 1);
4926                         ret = 0;
4927                 } else {
4928                         /*
4929                          * Ok set num_bytes to orig_bytes since we aren't
4930                          * overocmmitted, this way we only try and reclaim what
4931                          * we need.
4932                          */
4933                         num_bytes = orig_bytes;
4934                 }
4935         } else {
4936                 /*
4937                  * Ok we're over committed, set num_bytes to the overcommitted
4938                  * amount plus the amount of bytes that we need for this
4939                  * reservation.
4940                  */
4941                 num_bytes = used - space_info->total_bytes +
4942                         (orig_bytes * 2);
4943         }
4944
4945         if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
4946                 space_info->bytes_may_use += orig_bytes;
4947                 trace_btrfs_space_reservation(root->fs_info, "space_info",
4948                                               space_info->flags, orig_bytes,
4949                                               1);
4950                 ret = 0;
4951         }
4952
4953         /*
4954          * Couldn't make our reservation, save our place so while we're trying
4955          * to reclaim space we can actually use it instead of somebody else
4956          * stealing it from us.
4957          *
4958          * We make the other tasks wait for the flush only when we can flush
4959          * all things.
4960          */
4961         if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
4962                 flushing = true;
4963                 space_info->flush = 1;
4964         } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
4965                 used += orig_bytes;
4966                 /*
4967                  * We will do the space reservation dance during log replay,
4968                  * which means we won't have fs_info->fs_root set, so don't do
4969                  * the async reclaim as we will panic.
4970                  */
4971                 if (!root->fs_info->log_root_recovering &&
4972                     need_do_async_reclaim(space_info, root->fs_info, used) &&
4973                     !work_busy(&root->fs_info->async_reclaim_work))
4974                         queue_work(system_unbound_wq,
4975                                    &root->fs_info->async_reclaim_work);
4976         }
4977         spin_unlock(&space_info->lock);
4978
4979         if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
4980                 goto out;
4981
4982         ret = flush_space(root, space_info, num_bytes, orig_bytes,
4983                           flush_state);
4984         flush_state++;
4985
4986         /*
4987          * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
4988          * would happen. So skip delalloc flush.
4989          */
4990         if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4991             (flush_state == FLUSH_DELALLOC ||
4992              flush_state == FLUSH_DELALLOC_WAIT))
4993                 flush_state = ALLOC_CHUNK;
4994
4995         if (!ret)
4996                 goto again;
4997         else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4998                  flush_state < COMMIT_TRANS)
4999                 goto again;
5000         else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
5001                  flush_state <= COMMIT_TRANS)
5002                 goto again;
5003
5004 out:
5005         if (ret == -ENOSPC &&
5006             unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5007                 struct btrfs_block_rsv *global_rsv =
5008                         &root->fs_info->global_block_rsv;
5009
5010                 if (block_rsv != global_rsv &&
5011                     !block_rsv_use_bytes(global_rsv, orig_bytes))
5012                         ret = 0;
5013         }
5014         if (ret == -ENOSPC)
5015                 trace_btrfs_space_reservation(root->fs_info,
5016                                               "space_info:enospc",
5017                                               space_info->flags, orig_bytes, 1);
5018         if (flushing) {
5019                 spin_lock(&space_info->lock);
5020                 space_info->flush = 0;
5021                 wake_up_all(&space_info->wait);
5022                 spin_unlock(&space_info->lock);
5023         }
5024         return ret;
5025 }
5026
5027 static struct btrfs_block_rsv *get_block_rsv(
5028                                         const struct btrfs_trans_handle *trans,
5029                                         const struct btrfs_root *root)
5030 {
5031         struct btrfs_block_rsv *block_rsv = NULL;
5032
5033         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5034             (root == root->fs_info->csum_root && trans->adding_csums) ||
5035              (root == root->fs_info->uuid_root))
5036                 block_rsv = trans->block_rsv;
5037
5038         if (!block_rsv)
5039                 block_rsv = root->block_rsv;
5040
5041         if (!block_rsv)
5042                 block_rsv = &root->fs_info->empty_block_rsv;
5043
5044         return block_rsv;
5045 }
5046
5047 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5048                                u64 num_bytes)
5049 {
5050         int ret = -ENOSPC;
5051         spin_lock(&block_rsv->lock);
5052         if (block_rsv->reserved >= num_bytes) {
5053                 block_rsv->reserved -= num_bytes;
5054                 if (block_rsv->reserved < block_rsv->size)
5055                         block_rsv->full = 0;
5056                 ret = 0;
5057         }
5058         spin_unlock(&block_rsv->lock);
5059         return ret;
5060 }
5061
5062 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5063                                 u64 num_bytes, int update_size)
5064 {
5065         spin_lock(&block_rsv->lock);
5066         block_rsv->reserved += num_bytes;
5067         if (update_size)
5068                 block_rsv->size += num_bytes;
5069         else if (block_rsv->reserved >= block_rsv->size)
5070                 block_rsv->full = 1;
5071         spin_unlock(&block_rsv->lock);
5072 }
5073
5074 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5075                              struct btrfs_block_rsv *dest, u64 num_bytes,
5076                              int min_factor)
5077 {
5078         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5079         u64 min_bytes;
5080
5081         if (global_rsv->space_info != dest->space_info)
5082                 return -ENOSPC;
5083
5084         spin_lock(&global_rsv->lock);
5085         min_bytes = div_factor(global_rsv->size, min_factor);
5086         if (global_rsv->reserved < min_bytes + num_bytes) {
5087                 spin_unlock(&global_rsv->lock);
5088                 return -ENOSPC;
5089         }
5090         global_rsv->reserved -= num_bytes;
5091         if (global_rsv->reserved < global_rsv->size)
5092                 global_rsv->full = 0;
5093         spin_unlock(&global_rsv->lock);
5094
5095         block_rsv_add_bytes(dest, num_bytes, 1);
5096         return 0;
5097 }
5098
5099 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5100                                     struct btrfs_block_rsv *block_rsv,
5101                                     struct btrfs_block_rsv *dest, u64 num_bytes)
5102 {
5103         struct btrfs_space_info *space_info = block_rsv->space_info;
5104
5105         spin_lock(&block_rsv->lock);
5106         if (num_bytes == (u64)-1)
5107                 num_bytes = block_rsv->size;
5108         block_rsv->size -= num_bytes;
5109         if (block_rsv->reserved >= block_rsv->size) {
5110                 num_bytes = block_rsv->reserved - block_rsv->size;
5111                 block_rsv->reserved = block_rsv->size;
5112                 block_rsv->full = 1;
5113         } else {
5114                 num_bytes = 0;
5115         }
5116         spin_unlock(&block_rsv->lock);
5117
5118         if (num_bytes > 0) {
5119                 if (dest) {
5120                         spin_lock(&dest->lock);
5121                         if (!dest->full) {
5122                                 u64 bytes_to_add;
5123
5124                                 bytes_to_add = dest->size - dest->reserved;
5125                                 bytes_to_add = min(num_bytes, bytes_to_add);
5126                                 dest->reserved += bytes_to_add;
5127                                 if (dest->reserved >= dest->size)
5128                                         dest->full = 1;
5129                                 num_bytes -= bytes_to_add;
5130                         }
5131                         spin_unlock(&dest->lock);
5132                 }
5133                 if (num_bytes) {
5134                         spin_lock(&space_info->lock);
5135                         space_info->bytes_may_use -= num_bytes;
5136                         trace_btrfs_space_reservation(fs_info, "space_info",
5137                                         space_info->flags, num_bytes, 0);
5138                         spin_unlock(&space_info->lock);
5139                 }
5140         }
5141 }
5142
5143 static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
5144                                    struct btrfs_block_rsv *dst, u64 num_bytes)
5145 {
5146         int ret;
5147
5148         ret = block_rsv_use_bytes(src, num_bytes);
5149         if (ret)
5150                 return ret;
5151
5152         block_rsv_add_bytes(dst, num_bytes, 1);
5153         return 0;
5154 }
5155
5156 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5157 {
5158         memset(rsv, 0, sizeof(*rsv));
5159         spin_lock_init(&rsv->lock);
5160         rsv->type = type;
5161 }
5162
5163 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
5164                                               unsigned short type)
5165 {
5166         struct btrfs_block_rsv *block_rsv;
5167         struct btrfs_fs_info *fs_info = root->fs_info;
5168
5169         block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5170         if (!block_rsv)
5171                 return NULL;
5172
5173         btrfs_init_block_rsv(block_rsv, type);
5174         block_rsv->space_info = __find_space_info(fs_info,
5175                                                   BTRFS_BLOCK_GROUP_METADATA);
5176         return block_rsv;
5177 }
5178
5179 void btrfs_free_block_rsv(struct btrfs_root *root,
5180                           struct btrfs_block_rsv *rsv)
5181 {
5182         if (!rsv)
5183                 return;
5184         btrfs_block_rsv_release(root, rsv, (u64)-1);
5185         kfree(rsv);
5186 }
5187
5188 void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
5189 {
5190         kfree(rsv);
5191 }
5192
5193 int btrfs_block_rsv_add(struct btrfs_root *root,
5194                         struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5195                         enum btrfs_reserve_flush_enum flush)
5196 {
5197         int ret;
5198
5199         if (num_bytes == 0)
5200                 return 0;
5201
5202         ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5203         if (!ret) {
5204                 block_rsv_add_bytes(block_rsv, num_bytes, 1);
5205                 return 0;
5206         }
5207
5208         return ret;
5209 }
5210
5211 int btrfs_block_rsv_check(struct btrfs_root *root,
5212                           struct btrfs_block_rsv *block_rsv, int min_factor)
5213 {
5214         u64 num_bytes = 0;
5215         int ret = -ENOSPC;
5216
5217         if (!block_rsv)
5218                 return 0;
5219
5220         spin_lock(&block_rsv->lock);
5221         num_bytes = div_factor(block_rsv->size, min_factor);
5222         if (block_rsv->reserved >= num_bytes)
5223                 ret = 0;
5224         spin_unlock(&block_rsv->lock);
5225
5226         return ret;
5227 }
5228
5229 int btrfs_block_rsv_refill(struct btrfs_root *root,
5230                            struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5231                            enum btrfs_reserve_flush_enum flush)
5232 {
5233         u64 num_bytes = 0;
5234         int ret = -ENOSPC;
5235
5236         if (!block_rsv)
5237                 return 0;
5238
5239         spin_lock(&block_rsv->lock);
5240         num_bytes = min_reserved;
5241         if (block_rsv->reserved >= num_bytes)
5242                 ret = 0;
5243         else
5244                 num_bytes -= block_rsv->reserved;
5245         spin_unlock(&block_rsv->lock);
5246
5247         if (!ret)
5248                 return 0;
5249
5250         ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5251         if (!ret) {
5252                 block_rsv_add_bytes(block_rsv, num_bytes, 0);
5253                 return 0;
5254         }
5255
5256         return ret;
5257 }
5258
5259 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
5260                             struct btrfs_block_rsv *dst_rsv,
5261                             u64 num_bytes)
5262 {
5263         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
5264 }
5265
5266 void btrfs_block_rsv_release(struct btrfs_root *root,
5267                              struct btrfs_block_rsv *block_rsv,
5268                              u64 num_bytes)
5269 {
5270         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
5271         if (global_rsv == block_rsv ||
5272             block_rsv->space_info != global_rsv->space_info)
5273                 global_rsv = NULL;
5274         block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
5275                                 num_bytes);
5276 }
5277
5278 /*
5279  * helper to calculate size of global block reservation.
5280  * the desired value is sum of space used by extent tree,
5281  * checksum tree and root tree
5282  */
5283 static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
5284 {
5285         struct btrfs_space_info *sinfo;
5286         u64 num_bytes;
5287         u64 meta_used;
5288         u64 data_used;
5289         int csum_size = btrfs_super_csum_size(fs_info->super_copy);
5290
5291         sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
5292         spin_lock(&sinfo->lock);
5293         data_used = sinfo->bytes_used;
5294         spin_unlock(&sinfo->lock);
5295
5296         sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5297         spin_lock(&sinfo->lock);
5298         if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
5299                 data_used = 0;
5300         meta_used = sinfo->bytes_used;
5301         spin_unlock(&sinfo->lock);
5302
5303         num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
5304                     csum_size * 2;
5305         num_bytes += div_u64(data_used + meta_used, 50);
5306
5307         if (num_bytes * 3 > meta_used)
5308                 num_bytes = div_u64(meta_used, 3);
5309
5310         return ALIGN(num_bytes, fs_info->extent_root->nodesize << 10);
5311 }
5312
5313 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5314 {
5315         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5316         struct btrfs_space_info *sinfo = block_rsv->space_info;
5317         u64 num_bytes;
5318
5319         num_bytes = calc_global_metadata_size(fs_info);
5320
5321         spin_lock(&sinfo->lock);
5322         spin_lock(&block_rsv->lock);
5323
5324         block_rsv->size = min_t(u64, num_bytes, 512 * 1024 * 1024);
5325
5326         num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
5327                     sinfo->bytes_reserved + sinfo->bytes_readonly +
5328                     sinfo->bytes_may_use;
5329
5330         if (sinfo->total_bytes > num_bytes) {
5331                 num_bytes = sinfo->total_bytes - num_bytes;
5332                 block_rsv->reserved += num_bytes;
5333                 sinfo->bytes_may_use += num_bytes;
5334                 trace_btrfs_space_reservation(fs_info, "space_info",
5335                                       sinfo->flags, num_bytes, 1);
5336         }
5337
5338         if (block_rsv->reserved >= block_rsv->size) {
5339                 num_bytes = block_rsv->reserved - block_rsv->size;
5340                 sinfo->bytes_may_use -= num_bytes;
5341                 trace_btrfs_space_reservation(fs_info, "space_info",
5342                                       sinfo->flags, num_bytes, 0);
5343                 block_rsv->reserved = block_rsv->size;
5344                 block_rsv->full = 1;
5345         }
5346
5347         spin_unlock(&block_rsv->lock);
5348         spin_unlock(&sinfo->lock);
5349 }
5350
5351 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5352 {
5353         struct btrfs_space_info *space_info;
5354
5355         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5356         fs_info->chunk_block_rsv.space_info = space_info;
5357
5358         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5359         fs_info->global_block_rsv.space_info = space_info;
5360         fs_info->delalloc_block_rsv.space_info = space_info;
5361         fs_info->trans_block_rsv.space_info = space_info;
5362         fs_info->empty_block_rsv.space_info = space_info;
5363         fs_info->delayed_block_rsv.space_info = space_info;
5364
5365         fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
5366         fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
5367         fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5368         fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5369         if (fs_info->quota_root)
5370                 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5371         fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5372
5373         update_global_block_rsv(fs_info);
5374 }
5375
5376 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5377 {
5378         block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5379                                 (u64)-1);
5380         WARN_ON(fs_info->delalloc_block_rsv.size > 0);
5381         WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
5382         WARN_ON(fs_info->trans_block_rsv.size > 0);
5383         WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5384         WARN_ON(fs_info->chunk_block_rsv.size > 0);
5385         WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5386         WARN_ON(fs_info->delayed_block_rsv.size > 0);
5387         WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5388 }
5389
5390 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
5391                                   struct btrfs_root *root)
5392 {
5393         if (!trans->block_rsv)
5394                 return;
5395
5396         if (!trans->bytes_reserved)
5397                 return;
5398
5399         trace_btrfs_space_reservation(root->fs_info, "transaction",
5400                                       trans->transid, trans->bytes_reserved, 0);
5401         btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
5402         trans->bytes_reserved = 0;
5403 }
5404
5405 /*
5406  * To be called after all the new block groups attached to the transaction
5407  * handle have been created (btrfs_create_pending_block_groups()).
5408  */
5409 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5410 {
5411         struct btrfs_fs_info *fs_info = trans->root->fs_info;
5412
5413         if (!trans->chunk_bytes_reserved)
5414                 return;
5415
5416         WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5417
5418         block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5419                                 trans->chunk_bytes_reserved);
5420         trans->chunk_bytes_reserved = 0;
5421 }
5422
5423 /* Can only return 0 or -ENOSPC */
5424 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
5425                                   struct inode *inode)
5426 {
5427         struct btrfs_root *root = BTRFS_I(inode)->root;
5428         struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
5429         struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
5430
5431         /*
5432          * We need to hold space in order to delete our orphan item once we've
5433          * added it, so this takes the reservation so we can release it later
5434          * when we are truly done with the orphan item.
5435          */
5436         u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
5437         trace_btrfs_space_reservation(root->fs_info, "orphan",
5438                                       btrfs_ino(inode), num_bytes, 1);
5439         return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
5440 }
5441
5442 void btrfs_orphan_release_metadata(struct inode *inode)
5443 {
5444         struct btrfs_root *root = BTRFS_I(inode)->root;
5445         u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
5446         trace_btrfs_space_reservation(root->fs_info, "orphan",
5447                                       btrfs_ino(inode), num_bytes, 0);
5448         btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
5449 }
5450
5451 /*
5452  * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5453  * root: the root of the parent directory
5454  * rsv: block reservation
5455  * items: the number of items that we need do reservation
5456  * qgroup_reserved: used to return the reserved size in qgroup
5457  *
5458  * This function is used to reserve the space for snapshot/subvolume
5459  * creation and deletion. Those operations are different with the
5460  * common file/directory operations, they change two fs/file trees
5461  * and root tree, the number of items that the qgroup reserves is
5462  * different with the free space reservation. So we can not use
5463  * the space reseravtion mechanism in start_transaction().
5464  */
5465 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5466                                      struct btrfs_block_rsv *rsv,
5467                                      int items,
5468                                      u64 *qgroup_reserved,
5469                                      bool use_global_rsv)
5470 {
5471         u64 num_bytes;
5472         int ret;
5473         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
5474
5475         if (root->fs_info->quota_enabled) {
5476                 /* One for parent inode, two for dir entries */
5477                 num_bytes = 3 * root->nodesize;
5478                 ret = btrfs_qgroup_reserve_meta(root, num_bytes);
5479                 if (ret)
5480                         return ret;
5481         } else {
5482                 num_bytes = 0;
5483         }
5484
5485         *qgroup_reserved = num_bytes;
5486
5487         num_bytes = btrfs_calc_trans_metadata_size(root, items);
5488         rsv->space_info = __find_space_info(root->fs_info,
5489                                             BTRFS_BLOCK_GROUP_METADATA);
5490         ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5491                                   BTRFS_RESERVE_FLUSH_ALL);
5492
5493         if (ret == -ENOSPC && use_global_rsv)
5494                 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes);
5495
5496         if (ret && *qgroup_reserved)
5497                 btrfs_qgroup_free_meta(root, *qgroup_reserved);
5498
5499         return ret;
5500 }
5501
5502 void btrfs_subvolume_release_metadata(struct btrfs_root *root,
5503                                       struct btrfs_block_rsv *rsv,
5504                                       u64 qgroup_reserved)
5505 {
5506         btrfs_block_rsv_release(root, rsv, (u64)-1);
5507 }
5508
5509 /**
5510  * drop_outstanding_extent - drop an outstanding extent
5511  * @inode: the inode we're dropping the extent for
5512  * @num_bytes: the number of bytes we're relaseing.
5513  *
5514  * This is called when we are freeing up an outstanding extent, either called
5515  * after an error or after an extent is written.  This will return the number of
5516  * reserved extents that need to be freed.  This must be called with
5517  * BTRFS_I(inode)->lock held.
5518  */
5519 static unsigned drop_outstanding_extent(struct inode *inode, u64 num_bytes)
5520 {
5521         unsigned drop_inode_space = 0;
5522         unsigned dropped_extents = 0;
5523         unsigned num_extents = 0;
5524
5525         num_extents = (unsigned)div64_u64(num_bytes +
5526                                           BTRFS_MAX_EXTENT_SIZE - 1,
5527                                           BTRFS_MAX_EXTENT_SIZE);
5528         ASSERT(num_extents);
5529         ASSERT(BTRFS_I(inode)->outstanding_extents >= num_extents);
5530         BTRFS_I(inode)->outstanding_extents -= num_extents;
5531
5532         if (BTRFS_I(inode)->outstanding_extents == 0 &&
5533             test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5534                                &BTRFS_I(inode)->runtime_flags))
5535                 drop_inode_space = 1;
5536
5537         /*
5538          * If we have more or the same amount of outsanding extents than we have
5539          * reserved then we need to leave the reserved extents count alone.
5540          */
5541         if (BTRFS_I(inode)->outstanding_extents >=
5542             BTRFS_I(inode)->reserved_extents)
5543                 return drop_inode_space;
5544
5545         dropped_extents = BTRFS_I(inode)->reserved_extents -
5546                 BTRFS_I(inode)->outstanding_extents;
5547         BTRFS_I(inode)->reserved_extents -= dropped_extents;
5548         return dropped_extents + drop_inode_space;
5549 }
5550
5551 /**
5552  * calc_csum_metadata_size - return the amount of metada space that must be
5553  *      reserved/free'd for the given bytes.
5554  * @inode: the inode we're manipulating
5555  * @num_bytes: the number of bytes in question
5556  * @reserve: 1 if we are reserving space, 0 if we are freeing space
5557  *
5558  * This adjusts the number of csum_bytes in the inode and then returns the
5559  * correct amount of metadata that must either be reserved or freed.  We
5560  * calculate how many checksums we can fit into one leaf and then divide the
5561  * number of bytes that will need to be checksumed by this value to figure out
5562  * how many checksums will be required.  If we are adding bytes then the number
5563  * may go up and we will return the number of additional bytes that must be
5564  * reserved.  If it is going down we will return the number of bytes that must
5565  * be freed.
5566  *
5567  * This must be called with BTRFS_I(inode)->lock held.
5568  */
5569 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
5570                                    int reserve)
5571 {
5572         struct btrfs_root *root = BTRFS_I(inode)->root;
5573         u64 old_csums, num_csums;
5574
5575         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
5576             BTRFS_I(inode)->csum_bytes == 0)
5577                 return 0;
5578
5579         old_csums = btrfs_csum_bytes_to_leaves(root, BTRFS_I(inode)->csum_bytes);
5580         if (reserve)
5581                 BTRFS_I(inode)->csum_bytes += num_bytes;
5582         else
5583                 BTRFS_I(inode)->csum_bytes -= num_bytes;
5584         num_csums = btrfs_csum_bytes_to_leaves(root, BTRFS_I(inode)->csum_bytes);
5585
5586         /* No change, no need to reserve more */
5587         if (old_csums == num_csums)
5588                 return 0;
5589
5590         if (reserve)
5591                 return btrfs_calc_trans_metadata_size(root,
5592                                                       num_csums - old_csums);
5593
5594         return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
5595 }
5596
5597 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
5598 {
5599         struct btrfs_root *root = BTRFS_I(inode)->root;
5600         struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
5601         u64 to_reserve = 0;
5602         u64 csum_bytes;
5603         unsigned nr_extents = 0;
5604         int extra_reserve = 0;
5605         enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
5606         int ret = 0;
5607         bool delalloc_lock = true;
5608         u64 to_free = 0;
5609         unsigned dropped;
5610
5611         /* If we are a free space inode we need to not flush since we will be in
5612          * the middle of a transaction commit.  We also don't need the delalloc
5613          * mutex since we won't race with anybody.  We need this mostly to make
5614          * lockdep shut its filthy mouth.
5615          */
5616         if (btrfs_is_free_space_inode(inode)) {
5617                 flush = BTRFS_RESERVE_NO_FLUSH;
5618                 delalloc_lock = false;
5619         }
5620
5621         if (flush != BTRFS_RESERVE_NO_FLUSH &&
5622             btrfs_transaction_in_commit(root->fs_info))
5623                 schedule_timeout(1);
5624
5625         if (delalloc_lock)
5626                 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
5627
5628         num_bytes = ALIGN(num_bytes, root->sectorsize);
5629
5630         spin_lock(&BTRFS_I(inode)->lock);
5631         nr_extents = (unsigned)div64_u64(num_bytes +
5632                                          BTRFS_MAX_EXTENT_SIZE - 1,
5633                                          BTRFS_MAX_EXTENT_SIZE);
5634         BTRFS_I(inode)->outstanding_extents += nr_extents;
5635         nr_extents = 0;
5636
5637         if (BTRFS_I(inode)->outstanding_extents >
5638             BTRFS_I(inode)->reserved_extents)
5639                 nr_extents = BTRFS_I(inode)->outstanding_extents -
5640                         BTRFS_I(inode)->reserved_extents;
5641
5642         /*
5643          * Add an item to reserve for updating the inode when we complete the
5644          * delalloc io.
5645          */
5646         if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5647                       &BTRFS_I(inode)->runtime_flags)) {
5648                 nr_extents++;
5649                 extra_reserve = 1;
5650         }
5651
5652         to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
5653         to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
5654         csum_bytes = BTRFS_I(inode)->csum_bytes;
5655         spin_unlock(&BTRFS_I(inode)->lock);
5656
5657         if (root->fs_info->quota_enabled) {
5658                 ret = btrfs_qgroup_reserve_meta(root,
5659                                 nr_extents * root->nodesize);
5660                 if (ret)
5661                         goto out_fail;
5662         }
5663
5664         ret = reserve_metadata_bytes(root, block_rsv, to_reserve, flush);
5665         if (unlikely(ret)) {
5666                 btrfs_qgroup_free_meta(root, nr_extents * root->nodesize);
5667                 goto out_fail;
5668         }
5669
5670         spin_lock(&BTRFS_I(inode)->lock);
5671         if (extra_reserve) {
5672                 set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5673                         &BTRFS_I(inode)->runtime_flags);
5674                 nr_extents--;
5675         }
5676         BTRFS_I(inode)->reserved_extents += nr_extents;
5677         spin_unlock(&BTRFS_I(inode)->lock);
5678
5679         if (delalloc_lock)
5680                 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
5681
5682         if (to_reserve)
5683                 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5684                                               btrfs_ino(inode), to_reserve, 1);
5685         block_rsv_add_bytes(block_rsv, to_reserve, 1);
5686
5687         return 0;
5688
5689 out_fail:
5690         spin_lock(&BTRFS_I(inode)->lock);
5691         dropped = drop_outstanding_extent(inode, num_bytes);
5692         /*
5693          * If the inodes csum_bytes is the same as the original
5694          * csum_bytes then we know we haven't raced with any free()ers
5695          * so we can just reduce our inodes csum bytes and carry on.
5696          */
5697         if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
5698                 calc_csum_metadata_size(inode, num_bytes, 0);
5699         } else {
5700                 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
5701                 u64 bytes;
5702
5703                 /*
5704                  * This is tricky, but first we need to figure out how much we
5705                  * free'd from any free-ers that occured during this
5706                  * reservation, so we reset ->csum_bytes to the csum_bytes
5707                  * before we dropped our lock, and then call the free for the
5708                  * number of bytes that were freed while we were trying our
5709                  * reservation.
5710                  */
5711                 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
5712                 BTRFS_I(inode)->csum_bytes = csum_bytes;
5713                 to_free = calc_csum_metadata_size(inode, bytes, 0);
5714
5715
5716                 /*
5717                  * Now we need to see how much we would have freed had we not
5718                  * been making this reservation and our ->csum_bytes were not
5719                  * artificially inflated.
5720                  */
5721                 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
5722                 bytes = csum_bytes - orig_csum_bytes;
5723                 bytes = calc_csum_metadata_size(inode, bytes, 0);
5724
5725                 /*
5726                  * Now reset ->csum_bytes to what it should be.  If bytes is
5727                  * more than to_free then we would have free'd more space had we
5728                  * not had an artificially high ->csum_bytes, so we need to free
5729                  * the remainder.  If bytes is the same or less then we don't
5730                  * need to do anything, the other free-ers did the correct
5731                  * thing.
5732                  */
5733                 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
5734                 if (bytes > to_free)
5735                         to_free = bytes - to_free;
5736                 else
5737                         to_free = 0;
5738         }
5739         spin_unlock(&BTRFS_I(inode)->lock);
5740         if (dropped)
5741                 to_free += btrfs_calc_trans_metadata_size(root, dropped);
5742
5743         if (to_free) {
5744                 btrfs_block_rsv_release(root, block_rsv, to_free);
5745                 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5746                                               btrfs_ino(inode), to_free, 0);
5747         }
5748         if (delalloc_lock)
5749                 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
5750         return ret;
5751 }
5752
5753 /**
5754  * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
5755  * @inode: the inode to release the reservation for
5756  * @num_bytes: the number of bytes we're releasing
5757  *
5758  * This will release the metadata reservation for an inode.  This can be called
5759  * once we complete IO for a given set of bytes to release their metadata
5760  * reservations.
5761  */
5762 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
5763 {
5764         struct btrfs_root *root = BTRFS_I(inode)->root;
5765         u64 to_free = 0;
5766         unsigned dropped;
5767
5768         num_bytes = ALIGN(num_bytes, root->sectorsize);
5769         spin_lock(&BTRFS_I(inode)->lock);
5770         dropped = drop_outstanding_extent(inode, num_bytes);
5771
5772         if (num_bytes)
5773                 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
5774         spin_unlock(&BTRFS_I(inode)->lock);
5775         if (dropped > 0)
5776                 to_free += btrfs_calc_trans_metadata_size(root, dropped);
5777
5778         if (btrfs_test_is_dummy_root(root))
5779                 return;
5780
5781         trace_btrfs_space_reservation(root->fs_info, "delalloc",
5782                                       btrfs_ino(inode), to_free, 0);
5783
5784         btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
5785                                 to_free);
5786 }
5787
5788 /**
5789  * btrfs_delalloc_reserve_space - reserve data and metadata space for
5790  * delalloc
5791  * @inode: inode we're writing to
5792  * @start: start range we are writing to
5793  * @len: how long the range we are writing to
5794  *
5795  * TODO: This function will finally replace old btrfs_delalloc_reserve_space()
5796  *
5797  * This will do the following things
5798  *
5799  * o reserve space in data space info for num bytes
5800  *   and reserve precious corresponding qgroup space
5801  *   (Done in check_data_free_space)
5802  *
5803  * o reserve space for metadata space, based on the number of outstanding
5804  *   extents and how much csums will be needed
5805  *   also reserve metadata space in a per root over-reserve method.
5806  * o add to the inodes->delalloc_bytes
5807  * o add it to the fs_info's delalloc inodes list.
5808  *   (Above 3 all done in delalloc_reserve_metadata)
5809  *
5810  * Return 0 for success
5811  * Return <0 for error(-ENOSPC or -EQUOT)
5812  */
5813 int btrfs_delalloc_reserve_space(struct inode *inode, u64 start, u64 len)
5814 {
5815         int ret;
5816
5817         ret = btrfs_check_data_free_space(inode, start, len);
5818         if (ret < 0)
5819                 return ret;
5820         ret = btrfs_delalloc_reserve_metadata(inode, len);
5821         if (ret < 0)
5822                 btrfs_free_reserved_data_space(inode, start, len);
5823         return ret;
5824 }
5825
5826 /**
5827  * btrfs_delalloc_release_space - release data and metadata space for delalloc
5828  * @inode: inode we're releasing space for
5829  * @start: start position of the space already reserved
5830  * @len: the len of the space already reserved
5831  *
5832  * This must be matched with a call to btrfs_delalloc_reserve_space.  This is
5833  * called in the case that we don't need the metadata AND data reservations
5834  * anymore.  So if there is an error or we insert an inline extent.
5835  *
5836  * This function will release the metadata space that was not used and will
5837  * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
5838  * list if there are no delalloc bytes left.
5839  * Also it will handle the qgroup reserved space.
5840  */
5841 void btrfs_delalloc_release_space(struct inode *inode, u64 start, u64 len)
5842 {
5843         btrfs_delalloc_release_metadata(inode, len);
5844         btrfs_free_reserved_data_space(inode, start, len);
5845 }
5846
5847 static int update_block_group(struct btrfs_trans_handle *trans,
5848                               struct btrfs_root *root, u64 bytenr,
5849                               u64 num_bytes, int alloc)
5850 {
5851         struct btrfs_block_group_cache *cache = NULL;
5852         struct btrfs_fs_info *info = root->fs_info;
5853         u64 total = num_bytes;
5854         u64 old_val;
5855         u64 byte_in_group;
5856         int factor;
5857
5858         /* block accounting for super block */
5859         spin_lock(&info->delalloc_root_lock);
5860         old_val = btrfs_super_bytes_used(info->super_copy);
5861         if (alloc)
5862                 old_val += num_bytes;
5863         else
5864                 old_val -= num_bytes;
5865         btrfs_set_super_bytes_used(info->super_copy, old_val);
5866         spin_unlock(&info->delalloc_root_lock);
5867
5868         while (total) {
5869                 cache = btrfs_lookup_block_group(info, bytenr);
5870                 if (!cache)
5871                         return -ENOENT;
5872                 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
5873                                     BTRFS_BLOCK_GROUP_RAID1 |
5874                                     BTRFS_BLOCK_GROUP_RAID10))
5875                         factor = 2;
5876                 else
5877                         factor = 1;
5878                 /*
5879                  * If this block group has free space cache written out, we
5880                  * need to make sure to load it if we are removing space.  This
5881                  * is because we need the unpinning stage to actually add the
5882                  * space back to the block group, otherwise we will leak space.
5883                  */
5884                 if (!alloc && cache->cached == BTRFS_CACHE_NO)
5885                         cache_block_group(cache, 1);
5886
5887                 byte_in_group = bytenr - cache->key.objectid;
5888                 WARN_ON(byte_in_group > cache->key.offset);
5889
5890                 spin_lock(&cache->space_info->lock);
5891                 spin_lock(&cache->lock);
5892
5893                 if (btrfs_test_opt(root, SPACE_CACHE) &&
5894                     cache->disk_cache_state < BTRFS_DC_CLEAR)
5895                         cache->disk_cache_state = BTRFS_DC_CLEAR;
5896
5897                 old_val = btrfs_block_group_used(&cache->item);
5898                 num_bytes = min(total, cache->key.offset - byte_in_group);
5899                 if (alloc) {
5900                         old_val += num_bytes;
5901                         btrfs_set_block_group_used(&cache->item, old_val);
5902                         cache->reserved -= num_bytes;
5903                         cache->space_info->bytes_reserved -= num_bytes;
5904                         cache->space_info->bytes_used += num_bytes;
5905                         cache->space_info->disk_used += num_bytes * factor;
5906                         spin_unlock(&cache->lock);
5907                         spin_unlock(&cache->space_info->lock);
5908                 } else {
5909                         old_val -= num_bytes;
5910                         btrfs_set_block_group_used(&cache->item, old_val);
5911                         cache->pinned += num_bytes;
5912                         cache->space_info->bytes_pinned += num_bytes;
5913                         cache->space_info->bytes_used -= num_bytes;
5914                         cache->space_info->disk_used -= num_bytes * factor;
5915                         spin_unlock(&cache->lock);
5916                         spin_unlock(&cache->space_info->lock);
5917
5918                         set_extent_dirty(info->pinned_extents,
5919                                          bytenr, bytenr + num_bytes - 1,
5920                                          GFP_NOFS | __GFP_NOFAIL);
5921                 }
5922
5923                 spin_lock(&trans->transaction->dirty_bgs_lock);
5924                 if (list_empty(&cache->dirty_list)) {
5925                         list_add_tail(&cache->dirty_list,
5926                                       &trans->transaction->dirty_bgs);
5927                                 trans->transaction->num_dirty_bgs++;
5928                         btrfs_get_block_group(cache);
5929                 }
5930                 spin_unlock(&trans->transaction->dirty_bgs_lock);
5931
5932                 /*
5933                  * No longer have used bytes in this block group, queue it for
5934                  * deletion. We do this after adding the block group to the
5935                  * dirty list to avoid races between cleaner kthread and space
5936                  * cache writeout.
5937                  */
5938                 if (!alloc && old_val == 0) {
5939                         spin_lock(&info->unused_bgs_lock);
5940                         if (list_empty(&cache->bg_list)) {
5941                                 btrfs_get_block_group(cache);
5942                                 list_add_tail(&cache->bg_list,
5943                                               &info->unused_bgs);
5944                         }
5945                         spin_unlock(&info->unused_bgs_lock);
5946                 }
5947
5948                 btrfs_put_block_group(cache);
5949                 total -= num_bytes;
5950                 bytenr += num_bytes;
5951         }
5952         return 0;
5953 }
5954
5955 static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
5956 {
5957         struct btrfs_block_group_cache *cache;
5958         u64 bytenr;
5959
5960         spin_lock(&root->fs_info->block_group_cache_lock);
5961         bytenr = root->fs_info->first_logical_byte;
5962         spin_unlock(&root->fs_info->block_group_cache_lock);
5963
5964         if (bytenr < (u64)-1)
5965                 return bytenr;
5966
5967         cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
5968         if (!cache)
5969                 return 0;
5970
5971         bytenr = cache->key.objectid;
5972         btrfs_put_block_group(cache);
5973
5974         return bytenr;
5975 }
5976
5977 static int pin_down_extent(struct btrfs_root *root,
5978                            struct btrfs_block_group_cache *cache,
5979                            u64 bytenr, u64 num_bytes, int reserved)
5980 {
5981         spin_lock(&cache->space_info->lock);
5982         spin_lock(&cache->lock);
5983         cache->pinned += num_bytes;
5984         cache->space_info->bytes_pinned += num_bytes;
5985         if (reserved) {
5986                 cache->reserved -= num_bytes;
5987                 cache->space_info->bytes_reserved -= num_bytes;
5988         }
5989         spin_unlock(&cache->lock);
5990         spin_unlock(&cache->space_info->lock);
5991
5992         set_extent_dirty(root->fs_info->pinned_extents, bytenr,
5993                          bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
5994         if (reserved)
5995                 trace_btrfs_reserved_extent_free(root, bytenr, num_bytes);
5996         return 0;
5997 }
5998
5999 /*
6000  * this function must be called within transaction
6001  */
6002 int btrfs_pin_extent(struct btrfs_root *root,
6003                      u64 bytenr, u64 num_bytes, int reserved)
6004 {
6005         struct btrfs_block_group_cache *cache;
6006
6007         cache = btrfs_lookup_block_group(root->fs_info, bytenr);
6008         BUG_ON(!cache); /* Logic error */
6009
6010         pin_down_extent(root, cache, bytenr, num_bytes, reserved);
6011
6012         btrfs_put_block_group(cache);
6013         return 0;
6014 }
6015
6016 /*
6017  * this function must be called within transaction
6018  */
6019 int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
6020                                     u64 bytenr, u64 num_bytes)
6021 {
6022         struct btrfs_block_group_cache *cache;
6023         int ret;
6024
6025         cache = btrfs_lookup_block_group(root->fs_info, bytenr);
6026         if (!cache)
6027                 return -EINVAL;
6028
6029         /*
6030          * pull in the free space cache (if any) so that our pin
6031          * removes the free space from the cache.  We have load_only set
6032          * to one because the slow code to read in the free extents does check
6033          * the pinned extents.
6034          */
6035         cache_block_group(cache, 1);
6036
6037         pin_down_extent(root, cache, bytenr, num_bytes, 0);
6038
6039         /* remove us from the free space cache (if we're there at all) */
6040         ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6041         btrfs_put_block_group(cache);
6042         return ret;
6043 }
6044
6045 static int __exclude_logged_extent(struct btrfs_root *root, u64 start, u64 num_bytes)
6046 {
6047         int ret;
6048         struct btrfs_block_group_cache *block_group;
6049         struct btrfs_caching_control *caching_ctl;
6050
6051         block_group = btrfs_lookup_block_group(root->fs_info, start);
6052         if (!block_group)
6053                 return -EINVAL;
6054
6055         cache_block_group(block_group, 0);
6056         caching_ctl = get_caching_control(block_group);
6057
6058         if (!caching_ctl) {
6059                 /* Logic error */
6060                 BUG_ON(!block_group_cache_done(block_group));
6061                 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6062         } else {
6063                 mutex_lock(&caching_ctl->mutex);
6064
6065                 if (start >= caching_ctl->progress) {
6066                         ret = add_excluded_extent(root, start, num_bytes);
6067                 } else if (start + num_bytes <= caching_ctl->progress) {
6068                         ret = btrfs_remove_free_space(block_group,
6069                                                       start, num_bytes);
6070                 } else {
6071                         num_bytes = caching_ctl->progress - start;
6072                         ret = btrfs_remove_free_space(block_group,
6073                                                       start, num_bytes);
6074                         if (ret)
6075                                 goto out_lock;
6076
6077                         num_bytes = (start + num_bytes) -
6078                                 caching_ctl->progress;
6079                         start = caching_ctl->progress;
6080                         ret = add_excluded_extent(root, start, num_bytes);
6081                 }
6082 out_lock:
6083                 mutex_unlock(&caching_ctl->mutex);
6084                 put_caching_control(caching_ctl);
6085         }
6086         btrfs_put_block_group(block_group);
6087         return ret;
6088 }
6089
6090 int btrfs_exclude_logged_extents(struct btrfs_root *log,
6091                                  struct extent_buffer *eb)
6092 {
6093         struct btrfs_file_extent_item *item;
6094         struct btrfs_key key;
6095         int found_type;
6096         int i;
6097
6098         if (!btrfs_fs_incompat(log->fs_info, MIXED_GROUPS))
6099                 return 0;
6100
6101         for (i = 0; i < btrfs_header_nritems(eb); i++) {
6102                 btrfs_item_key_to_cpu(eb, &key, i);
6103                 if (key.type != BTRFS_EXTENT_DATA_KEY)
6104                         continue;
6105                 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6106                 found_type = btrfs_file_extent_type(eb, item);
6107                 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6108                         continue;
6109                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6110                         continue;
6111                 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6112                 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6113                 __exclude_logged_extent(log, key.objectid, key.offset);
6114         }
6115
6116         return 0;
6117 }
6118
6119 /**
6120  * btrfs_update_reserved_bytes - update the block_group and space info counters
6121  * @cache:      The cache we are manipulating
6122  * @num_bytes:  The number of bytes in question
6123  * @reserve:    One of the reservation enums
6124  * @delalloc:   The blocks are allocated for the delalloc write
6125  *
6126  * This is called by the allocator when it reserves space, or by somebody who is
6127  * freeing space that was never actually used on disk.  For example if you
6128  * reserve some space for a new leaf in transaction A and before transaction A
6129  * commits you free that leaf, you call this with reserve set to 0 in order to
6130  * clear the reservation.
6131  *
6132  * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
6133  * ENOSPC accounting.  For data we handle the reservation through clearing the
6134  * delalloc bits in the io_tree.  We have to do this since we could end up
6135  * allocating less disk space for the amount of data we have reserved in the
6136  * case of compression.
6137  *
6138  * If this is a reservation and the block group has become read only we cannot
6139  * make the reservation and return -EAGAIN, otherwise this function always
6140  * succeeds.
6141  */
6142 static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
6143                                        u64 num_bytes, int reserve, int delalloc)
6144 {
6145         struct btrfs_space_info *space_info = cache->space_info;
6146         int ret = 0;
6147
6148         spin_lock(&space_info->lock);
6149         spin_lock(&cache->lock);
6150         if (reserve != RESERVE_FREE) {
6151                 if (cache->ro) {
6152                         ret = -EAGAIN;
6153                 } else {
6154                         cache->reserved += num_bytes;
6155                         space_info->bytes_reserved += num_bytes;
6156                         if (reserve == RESERVE_ALLOC) {
6157                                 trace_btrfs_space_reservation(cache->fs_info,
6158                                                 "space_info", space_info->flags,
6159                                                 num_bytes, 0);
6160                                 space_info->bytes_may_use -= num_bytes;
6161                         }
6162
6163                         if (delalloc)
6164                                 cache->delalloc_bytes += num_bytes;
6165                 }
6166         } else {
6167                 if (cache->ro)
6168                         space_info->bytes_readonly += num_bytes;
6169                 cache->reserved -= num_bytes;
6170                 space_info->bytes_reserved -= num_bytes;
6171
6172                 if (delalloc)
6173                         cache->delalloc_bytes -= num_bytes;
6174         }
6175         spin_unlock(&cache->lock);
6176         spin_unlock(&space_info->lock);
6177         return ret;
6178 }
6179
6180 void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
6181                                 struct btrfs_root *root)
6182 {
6183         struct btrfs_fs_info *fs_info = root->fs_info;
6184         struct btrfs_caching_control *next;
6185         struct btrfs_caching_control *caching_ctl;
6186         struct btrfs_block_group_cache *cache;
6187
6188         down_write(&fs_info->commit_root_sem);
6189
6190         list_for_each_entry_safe(caching_ctl, next,
6191                                  &fs_info->caching_block_groups, list) {
6192                 cache = caching_ctl->block_group;
6193                 if (block_group_cache_done(cache)) {
6194                         cache->last_byte_to_unpin = (u64)-1;
6195                         list_del_init(&caching_ctl->list);
6196                         put_caching_control(caching_ctl);
6197                 } else {
6198                         cache->last_byte_to_unpin = caching_ctl->progress;
6199                 }
6200         }
6201
6202         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6203                 fs_info->pinned_extents = &fs_info->freed_extents[1];
6204         else
6205                 fs_info->pinned_extents = &fs_info->freed_extents[0];
6206
6207         up_write(&fs_info->commit_root_sem);
6208
6209         update_global_block_rsv(fs_info);
6210 }
6211
6212 /*
6213  * Returns the free cluster for the given space info and sets empty_cluster to
6214  * what it should be based on the mount options.
6215  */
6216 static struct btrfs_free_cluster *
6217 fetch_cluster_info(struct btrfs_root *root, struct btrfs_space_info *space_info,
6218                    u64 *empty_cluster)
6219 {
6220         struct btrfs_free_cluster *ret = NULL;
6221         bool ssd = btrfs_test_opt(root, SSD);
6222
6223         *empty_cluster = 0;
6224         if (btrfs_mixed_space_info(space_info))
6225                 return ret;
6226
6227         if (ssd)
6228                 *empty_cluster = 2 * 1024 * 1024;
6229         if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6230                 ret = &root->fs_info->meta_alloc_cluster;
6231                 if (!ssd)
6232                         *empty_cluster = 64 * 1024;
6233         } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && ssd) {
6234                 ret = &root->fs_info->data_alloc_cluster;
6235         }
6236
6237         return ret;
6238 }
6239
6240 static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end,
6241                               const bool return_free_space)
6242 {
6243         struct btrfs_fs_info *fs_info = root->fs_info;
6244         struct btrfs_block_group_cache *cache = NULL;
6245         struct btrfs_space_info *space_info;
6246         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6247         struct btrfs_free_cluster *cluster = NULL;
6248         u64 len;
6249         u64 total_unpinned = 0;
6250         u64 empty_cluster = 0;
6251         bool readonly;
6252
6253         while (start <= end) {
6254                 readonly = false;
6255                 if (!cache ||
6256                     start >= cache->key.objectid + cache->key.offset) {
6257                         if (cache)
6258                                 btrfs_put_block_group(cache);
6259                         total_unpinned = 0;
6260                         cache = btrfs_lookup_block_group(fs_info, start);
6261                         BUG_ON(!cache); /* Logic error */
6262
6263                         cluster = fetch_cluster_info(root,
6264                                                      cache->space_info,
6265                                                      &empty_cluster);
6266                         empty_cluster <<= 1;
6267                 }
6268
6269                 len = cache->key.objectid + cache->key.offset - start;
6270                 len = min(len, end + 1 - start);
6271
6272                 if (start < cache->last_byte_to_unpin) {
6273                         len = min(len, cache->last_byte_to_unpin - start);
6274                         if (return_free_space)
6275                                 btrfs_add_free_space(cache, start, len);
6276                 }
6277
6278                 start += len;
6279                 total_unpinned += len;
6280                 space_info = cache->space_info;
6281
6282                 /*
6283                  * If this space cluster has been marked as fragmented and we've
6284                  * unpinned enough in this block group to potentially allow a
6285                  * cluster to be created inside of it go ahead and clear the
6286                  * fragmented check.
6287                  */
6288                 if (cluster && cluster->fragmented &&
6289                     total_unpinned > empty_cluster) {
6290                         spin_lock(&cluster->lock);
6291                         cluster->fragmented = 0;
6292                         spin_unlock(&cluster->lock);
6293                 }
6294
6295                 spin_lock(&space_info->lock);
6296                 spin_lock(&cache->lock);
6297                 cache->pinned -= len;
6298                 space_info->bytes_pinned -= len;
6299                 space_info->max_extent_size = 0;
6300                 percpu_counter_add(&space_info->total_bytes_pinned, -len);
6301                 if (cache->ro) {
6302                         space_info->bytes_readonly += len;
6303                         readonly = true;
6304                 }
6305                 spin_unlock(&cache->lock);
6306                 if (!readonly && global_rsv->space_info == space_info) {
6307                         spin_lock(&global_rsv->lock);
6308                         if (!global_rsv->full) {
6309                                 len = min(len, global_rsv->size -
6310                                           global_rsv->reserved);
6311                                 global_rsv->reserved += len;
6312                                 space_info->bytes_may_use += len;
6313                                 if (global_rsv->reserved >= global_rsv->size)
6314                                         global_rsv->full = 1;
6315                         }
6316                         spin_unlock(&global_rsv->lock);
6317                 }
6318                 spin_unlock(&space_info->lock);
6319         }
6320
6321         if (cache)
6322                 btrfs_put_block_group(cache);
6323         return 0;
6324 }
6325
6326 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
6327                                struct btrfs_root *root)
6328 {
6329         struct btrfs_fs_info *fs_info = root->fs_info;
6330         struct btrfs_block_group_cache *block_group, *tmp;
6331         struct list_head *deleted_bgs;
6332         struct extent_io_tree *unpin;
6333         u64 start;
6334         u64 end;
6335         int ret;
6336
6337         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6338                 unpin = &fs_info->freed_extents[1];
6339         else
6340                 unpin = &fs_info->freed_extents[0];
6341
6342         while (!trans->aborted) {
6343                 mutex_lock(&fs_info->unused_bg_unpin_mutex);
6344                 ret = find_first_extent_bit(unpin, 0, &start, &end,
6345                                             EXTENT_DIRTY, NULL);
6346                 if (ret) {
6347                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6348                         break;
6349                 }
6350
6351                 if (btrfs_test_opt(root, DISCARD))
6352                         ret = btrfs_discard_extent(root, start,
6353                                                    end + 1 - start, NULL);
6354
6355                 clear_extent_dirty(unpin, start, end, GFP_NOFS);
6356                 unpin_extent_range(root, start, end, true);
6357                 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6358                 cond_resched();
6359         }
6360
6361         /*
6362          * Transaction is finished.  We don't need the lock anymore.  We
6363          * do need to clean up the block groups in case of a transaction
6364          * abort.
6365          */
6366         deleted_bgs = &trans->transaction->deleted_bgs;
6367         list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6368                 u64 trimmed = 0;
6369
6370                 ret = -EROFS;
6371                 if (!trans->aborted)
6372                         ret = btrfs_discard_extent(root,
6373                                                    block_group->key.objectid,
6374                                                    block_group->key.offset,
6375                                                    &trimmed);
6376
6377                 list_del_init(&block_group->bg_list);
6378                 btrfs_put_block_group_trimming(block_group);
6379                 btrfs_put_block_group(block_group);
6380
6381                 if (ret) {
6382                         const char *errstr = btrfs_decode_error(ret);
6383                         btrfs_warn(fs_info,
6384                                    "Discard failed while removing blockgroup: errno=%d %s\n",
6385                                    ret, errstr);
6386                 }
6387         }
6388
6389         return 0;
6390 }
6391
6392 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
6393                              u64 owner, u64 root_objectid)
6394 {
6395         struct btrfs_space_info *space_info;
6396         u64 flags;
6397
6398         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6399                 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
6400                         flags = BTRFS_BLOCK_GROUP_SYSTEM;
6401                 else
6402                         flags = BTRFS_BLOCK_GROUP_METADATA;
6403         } else {
6404                 flags = BTRFS_BLOCK_GROUP_DATA;
6405         }
6406
6407         space_info = __find_space_info(fs_info, flags);
6408         BUG_ON(!space_info); /* Logic bug */
6409         percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
6410 }
6411
6412
6413 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6414                                 struct btrfs_root *root,
6415                                 struct btrfs_delayed_ref_node *node, u64 parent,
6416                                 u64 root_objectid, u64 owner_objectid,
6417                                 u64 owner_offset, int refs_to_drop,
6418                                 struct btrfs_delayed_extent_op *extent_op)
6419 {
6420         struct btrfs_key key;
6421         struct btrfs_path *path;
6422         struct btrfs_fs_info *info = root->fs_info;
6423         struct btrfs_root *extent_root = info->extent_root;
6424         struct extent_buffer *leaf;
6425         struct btrfs_extent_item *ei;
6426         struct btrfs_extent_inline_ref *iref;
6427         int ret;
6428         int is_data;
6429         int extent_slot = 0;
6430         int found_extent = 0;
6431         int num_to_del = 1;
6432         u32 item_size;
6433         u64 refs;
6434         u64 bytenr = node->bytenr;
6435         u64 num_bytes = node->num_bytes;
6436         int last_ref = 0;
6437         bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
6438                                                  SKINNY_METADATA);
6439
6440         path = btrfs_alloc_path();
6441         if (!path)
6442                 return -ENOMEM;
6443
6444         path->reada = 1;
6445         path->leave_spinning = 1;
6446
6447         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6448         BUG_ON(!is_data && refs_to_drop != 1);
6449
6450         if (is_data)
6451                 skinny_metadata = 0;
6452
6453         ret = lookup_extent_backref(trans, extent_root, path, &iref,
6454                                     bytenr, num_bytes, parent,
6455                                     root_objectid, owner_objectid,
6456                                     owner_offset);
6457         if (ret == 0) {
6458                 extent_slot = path->slots[0];
6459                 while (extent_slot >= 0) {
6460                         btrfs_item_key_to_cpu(path->nodes[0], &key,
6461                                               extent_slot);
6462                         if (key.objectid != bytenr)
6463                                 break;
6464                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6465                             key.offset == num_bytes) {
6466                                 found_extent = 1;
6467                                 break;
6468                         }
6469                         if (key.type == BTRFS_METADATA_ITEM_KEY &&
6470                             key.offset == owner_objectid) {
6471                                 found_extent = 1;
6472                                 break;
6473                         }
6474                         if (path->slots[0] - extent_slot > 5)
6475                                 break;
6476                         extent_slot--;
6477                 }
6478 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6479                 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
6480                 if (found_extent && item_size < sizeof(*ei))
6481                         found_extent = 0;
6482 #endif
6483                 if (!found_extent) {
6484                         BUG_ON(iref);
6485                         ret = remove_extent_backref(trans, extent_root, path,
6486                                                     NULL, refs_to_drop,
6487                                                     is_data, &last_ref);
6488                         if (ret) {
6489                                 btrfs_abort_transaction(trans, extent_root, ret);
6490                                 goto out;
6491                         }
6492                         btrfs_release_path(path);
6493                         path->leave_spinning = 1;
6494
6495                         key.objectid = bytenr;
6496                         key.type = BTRFS_EXTENT_ITEM_KEY;
6497                         key.offset = num_bytes;
6498
6499                         if (!is_data && skinny_metadata) {
6500                                 key.type = BTRFS_METADATA_ITEM_KEY;
6501                                 key.offset = owner_objectid;
6502                         }
6503
6504                         ret = btrfs_search_slot(trans, extent_root,
6505                                                 &key, path, -1, 1);
6506                         if (ret > 0 && skinny_metadata && path->slots[0]) {
6507                                 /*
6508                                  * Couldn't find our skinny metadata item,
6509                                  * see if we have ye olde extent item.
6510                                  */
6511                                 path->slots[0]--;
6512                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
6513                                                       path->slots[0]);
6514                                 if (key.objectid == bytenr &&
6515                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
6516                                     key.offset == num_bytes)
6517                                         ret = 0;
6518                         }
6519
6520                         if (ret > 0 && skinny_metadata) {
6521                                 skinny_metadata = false;
6522                                 key.objectid = bytenr;
6523                                 key.type = BTRFS_EXTENT_ITEM_KEY;
6524                                 key.offset = num_bytes;
6525                                 btrfs_release_path(path);
6526                                 ret = btrfs_search_slot(trans, extent_root,
6527                                                         &key, path, -1, 1);
6528                         }
6529
6530                         if (ret) {
6531                                 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
6532                                         ret, bytenr);
6533                                 if (ret > 0)
6534                                         btrfs_print_leaf(extent_root,
6535                                                          path->nodes[0]);
6536                         }
6537                         if (ret < 0) {
6538                                 btrfs_abort_transaction(trans, extent_root, ret);
6539                                 goto out;
6540                         }
6541                         extent_slot = path->slots[0];
6542                 }
6543         } else if (WARN_ON(ret == -ENOENT)) {
6544                 btrfs_print_leaf(extent_root, path->nodes[0]);
6545                 btrfs_err(info,
6546                         "unable to find ref byte nr %llu parent %llu root %llu  owner %llu offset %llu",
6547                         bytenr, parent, root_objectid, owner_objectid,
6548                         owner_offset);
6549                 btrfs_abort_transaction(trans, extent_root, ret);
6550                 goto out;
6551         } else {
6552                 btrfs_abort_transaction(trans, extent_root, ret);
6553                 goto out;
6554         }
6555
6556         leaf = path->nodes[0];
6557         item_size = btrfs_item_size_nr(leaf, extent_slot);
6558 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6559         if (item_size < sizeof(*ei)) {
6560                 BUG_ON(found_extent || extent_slot != path->slots[0]);
6561                 ret = convert_extent_item_v0(trans, extent_root, path,
6562                                              owner_objectid, 0);
6563                 if (ret < 0) {
6564                         btrfs_abort_transaction(trans, extent_root, ret);
6565                         goto out;
6566                 }
6567
6568                 btrfs_release_path(path);
6569                 path->leave_spinning = 1;
6570
6571                 key.objectid = bytenr;
6572                 key.type = BTRFS_EXTENT_ITEM_KEY;
6573                 key.offset = num_bytes;
6574
6575                 ret = btrfs_search_slot(trans, extent_root, &key, path,
6576                                         -1, 1);
6577                 if (ret) {
6578                         btrfs_err(info, "umm, got %d back from search, was looking for %llu",
6579                                 ret, bytenr);
6580                         btrfs_print_leaf(extent_root, path->nodes[0]);
6581                 }
6582                 if (ret < 0) {
6583                         btrfs_abort_transaction(trans, extent_root, ret);
6584                         goto out;
6585                 }
6586
6587                 extent_slot = path->slots[0];
6588                 leaf = path->nodes[0];
6589                 item_size = btrfs_item_size_nr(leaf, extent_slot);
6590         }
6591 #endif
6592         BUG_ON(item_size < sizeof(*ei));
6593         ei = btrfs_item_ptr(leaf, extent_slot,
6594                             struct btrfs_extent_item);
6595         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
6596             key.type == BTRFS_EXTENT_ITEM_KEY) {
6597                 struct btrfs_tree_block_info *bi;
6598                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
6599                 bi = (struct btrfs_tree_block_info *)(ei + 1);
6600                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
6601         }
6602
6603         refs = btrfs_extent_refs(leaf, ei);
6604         if (refs < refs_to_drop) {
6605                 btrfs_err(info, "trying to drop %d refs but we only have %Lu "
6606                           "for bytenr %Lu", refs_to_drop, refs, bytenr);
6607                 ret = -EINVAL;
6608                 btrfs_abort_transaction(trans, extent_root, ret);
6609                 goto out;
6610         }
6611         refs -= refs_to_drop;
6612
6613         if (refs > 0) {
6614                 if (extent_op)
6615                         __run_delayed_extent_op(extent_op, leaf, ei);
6616                 /*
6617                  * In the case of inline back ref, reference count will
6618                  * be updated by remove_extent_backref
6619                  */
6620                 if (iref) {
6621                         BUG_ON(!found_extent);
6622                 } else {
6623                         btrfs_set_extent_refs(leaf, ei, refs);
6624                         btrfs_mark_buffer_dirty(leaf);
6625                 }
6626                 if (found_extent) {
6627                         ret = remove_extent_backref(trans, extent_root, path,
6628                                                     iref, refs_to_drop,
6629                                                     is_data, &last_ref);
6630                         if (ret) {
6631                                 btrfs_abort_transaction(trans, extent_root, ret);
6632                                 goto out;
6633                         }
6634                 }
6635                 add_pinned_bytes(root->fs_info, -num_bytes, owner_objectid,
6636                                  root_objectid);
6637         } else {
6638                 if (found_extent) {
6639                         BUG_ON(is_data && refs_to_drop !=
6640                                extent_data_ref_count(path, iref));
6641                         if (iref) {
6642                                 BUG_ON(path->slots[0] != extent_slot);
6643                         } else {
6644                                 BUG_ON(path->slots[0] != extent_slot + 1);
6645                                 path->slots[0] = extent_slot;
6646                                 num_to_del = 2;
6647                         }
6648                 }
6649
6650                 last_ref = 1;
6651                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
6652                                       num_to_del);
6653                 if (ret) {
6654                         btrfs_abort_transaction(trans, extent_root, ret);
6655                         goto out;
6656                 }
6657                 btrfs_release_path(path);
6658
6659                 if (is_data) {
6660                         ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
6661                         if (ret) {
6662                                 btrfs_abort_transaction(trans, extent_root, ret);
6663                                 goto out;
6664                         }
6665                 }
6666
6667                 ret = update_block_group(trans, root, bytenr, num_bytes, 0);
6668                 if (ret) {
6669                         btrfs_abort_transaction(trans, extent_root, ret);
6670                         goto out;
6671                 }
6672         }
6673         btrfs_release_path(path);
6674
6675 out:
6676         btrfs_free_path(path);
6677         return ret;
6678 }
6679
6680 /*
6681  * when we free an block, it is possible (and likely) that we free the last
6682  * delayed ref for that extent as well.  This searches the delayed ref tree for
6683  * a given extent, and if there are no other delayed refs to be processed, it
6684  * removes it from the tree.
6685  */
6686 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
6687                                       struct btrfs_root *root, u64 bytenr)
6688 {
6689         struct btrfs_delayed_ref_head *head;
6690         struct btrfs_delayed_ref_root *delayed_refs;
6691         int ret = 0;
6692
6693         delayed_refs = &trans->transaction->delayed_refs;
6694         spin_lock(&delayed_refs->lock);
6695         head = btrfs_find_delayed_ref_head(trans, bytenr);
6696         if (!head)
6697                 goto out_delayed_unlock;
6698
6699         spin_lock(&head->lock);
6700         if (!list_empty(&head->ref_list))
6701                 goto out;
6702
6703         if (head->extent_op) {
6704                 if (!head->must_insert_reserved)
6705                         goto out;
6706                 btrfs_free_delayed_extent_op(head->extent_op);
6707                 head->extent_op = NULL;
6708         }
6709
6710         /*
6711          * waiting for the lock here would deadlock.  If someone else has it
6712          * locked they are already in the process of dropping it anyway
6713          */
6714         if (!mutex_trylock(&head->mutex))
6715                 goto out;
6716
6717         /*
6718          * at this point we have a head with no other entries.  Go
6719          * ahead and process it.
6720          */
6721         head->node.in_tree = 0;
6722         rb_erase(&head->href_node, &delayed_refs->href_root);
6723
6724         atomic_dec(&delayed_refs->num_entries);
6725
6726         /*
6727          * we don't take a ref on the node because we're removing it from the
6728          * tree, so we just steal the ref the tree was holding.
6729          */
6730         delayed_refs->num_heads--;
6731         if (head->processing == 0)
6732                 delayed_refs->num_heads_ready--;
6733         head->processing = 0;
6734         spin_unlock(&head->lock);
6735         spin_unlock(&delayed_refs->lock);
6736
6737         BUG_ON(head->extent_op);
6738         if (head->must_insert_reserved)
6739                 ret = 1;
6740
6741         mutex_unlock(&head->mutex);
6742         btrfs_put_delayed_ref(&head->node);
6743         return ret;
6744 out:
6745         spin_unlock(&head->lock);
6746
6747 out_delayed_unlock:
6748         spin_unlock(&delayed_refs->lock);
6749         return 0;
6750 }
6751
6752 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
6753                            struct btrfs_root *root,
6754                            struct extent_buffer *buf,
6755                            u64 parent, int last_ref)
6756 {
6757         int pin = 1;
6758         int ret;
6759
6760         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6761                 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
6762                                         buf->start, buf->len,
6763                                         parent, root->root_key.objectid,
6764                                         btrfs_header_level(buf),
6765                                         BTRFS_DROP_DELAYED_REF, NULL);
6766                 BUG_ON(ret); /* -ENOMEM */
6767         }
6768
6769         if (!last_ref)
6770                 return;
6771
6772         if (btrfs_header_generation(buf) == trans->transid) {
6773                 struct btrfs_block_group_cache *cache;
6774
6775                 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6776                         ret = check_ref_cleanup(trans, root, buf->start);
6777                         if (!ret)
6778                                 goto out;
6779                 }
6780
6781                 cache = btrfs_lookup_block_group(root->fs_info, buf->start);
6782
6783                 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
6784                         pin_down_extent(root, cache, buf->start, buf->len, 1);
6785                         btrfs_put_block_group(cache);
6786                         goto out;
6787                 }
6788
6789                 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
6790
6791                 btrfs_add_free_space(cache, buf->start, buf->len);
6792                 btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE, 0);
6793                 btrfs_put_block_group(cache);
6794                 trace_btrfs_reserved_extent_free(root, buf->start, buf->len);
6795                 pin = 0;
6796         }
6797 out:
6798         if (pin)
6799                 add_pinned_bytes(root->fs_info, buf->len,
6800                                  btrfs_header_level(buf),
6801                                  root->root_key.objectid);
6802
6803         /*
6804          * Deleting the buffer, clear the corrupt flag since it doesn't matter
6805          * anymore.
6806          */
6807         clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
6808 }
6809
6810 /* Can return -ENOMEM */
6811 int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
6812                       u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
6813                       u64 owner, u64 offset)
6814 {
6815         int ret;
6816         struct btrfs_fs_info *fs_info = root->fs_info;
6817
6818         if (btrfs_test_is_dummy_root(root))
6819                 return 0;
6820
6821         add_pinned_bytes(root->fs_info, num_bytes, owner, root_objectid);
6822
6823         /*
6824          * tree log blocks never actually go into the extent allocation
6825          * tree, just update pinning info and exit early.
6826          */
6827         if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
6828                 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
6829                 /* unlocks the pinned mutex */
6830                 btrfs_pin_extent(root, bytenr, num_bytes, 1);
6831                 ret = 0;
6832         } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6833                 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
6834                                         num_bytes,
6835                                         parent, root_objectid, (int)owner,
6836                                         BTRFS_DROP_DELAYED_REF, NULL);
6837         } else {
6838                 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
6839                                                 num_bytes,
6840                                                 parent, root_objectid, owner,
6841                                                 offset, 0,
6842                                                 BTRFS_DROP_DELAYED_REF, NULL);
6843         }
6844         return ret;
6845 }
6846
6847 /*
6848  * when we wait for progress in the block group caching, its because
6849  * our allocation attempt failed at least once.  So, we must sleep
6850  * and let some progress happen before we try again.
6851  *
6852  * This function will sleep at least once waiting for new free space to
6853  * show up, and then it will check the block group free space numbers
6854  * for our min num_bytes.  Another option is to have it go ahead
6855  * and look in the rbtree for a free extent of a given size, but this
6856  * is a good start.
6857  *
6858  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
6859  * any of the information in this block group.
6860  */
6861 static noinline void
6862 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
6863                                 u64 num_bytes)
6864 {
6865         struct btrfs_caching_control *caching_ctl;
6866
6867         caching_ctl = get_caching_control(cache);
6868         if (!caching_ctl)
6869                 return;
6870
6871         wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
6872                    (cache->free_space_ctl->free_space >= num_bytes));
6873
6874         put_caching_control(caching_ctl);
6875 }
6876
6877 static noinline int
6878 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
6879 {
6880         struct btrfs_caching_control *caching_ctl;
6881         int ret = 0;
6882
6883         caching_ctl = get_caching_control(cache);
6884         if (!caching_ctl)
6885                 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
6886
6887         wait_event(caching_ctl->wait, block_group_cache_done(cache));
6888         if (cache->cached == BTRFS_CACHE_ERROR)
6889                 ret = -EIO;
6890         put_caching_control(caching_ctl);
6891         return ret;
6892 }
6893
6894 int __get_raid_index(u64 flags)
6895 {
6896         if (flags & BTRFS_BLOCK_GROUP_RAID10)
6897                 return BTRFS_RAID_RAID10;
6898         else if (flags & BTRFS_BLOCK_GROUP_RAID1)
6899                 return BTRFS_RAID_RAID1;
6900         else if (flags & BTRFS_BLOCK_GROUP_DUP)
6901                 return BTRFS_RAID_DUP;
6902         else if (flags & BTRFS_BLOCK_GROUP_RAID0)
6903                 return BTRFS_RAID_RAID0;
6904         else if (flags & BTRFS_BLOCK_GROUP_RAID5)
6905                 return BTRFS_RAID_RAID5;
6906         else if (flags & BTRFS_BLOCK_GROUP_RAID6)
6907                 return BTRFS_RAID_RAID6;
6908
6909         return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
6910 }
6911
6912 int get_block_group_index(struct btrfs_block_group_cache *cache)
6913 {
6914         return __get_raid_index(cache->flags);
6915 }
6916
6917 static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
6918         [BTRFS_RAID_RAID10]     = "raid10",
6919         [BTRFS_RAID_RAID1]      = "raid1",
6920         [BTRFS_RAID_DUP]        = "dup",
6921         [BTRFS_RAID_RAID0]      = "raid0",
6922         [BTRFS_RAID_SINGLE]     = "single",
6923         [BTRFS_RAID_RAID5]      = "raid5",
6924         [BTRFS_RAID_RAID6]      = "raid6",
6925 };
6926
6927 static const char *get_raid_name(enum btrfs_raid_types type)
6928 {
6929         if (type >= BTRFS_NR_RAID_TYPES)
6930                 return NULL;
6931
6932         return btrfs_raid_type_names[type];
6933 }
6934
6935 enum btrfs_loop_type {
6936         LOOP_CACHING_NOWAIT = 0,
6937         LOOP_CACHING_WAIT = 1,
6938         LOOP_ALLOC_CHUNK = 2,
6939         LOOP_NO_EMPTY_SIZE = 3,
6940 };
6941
6942 static inline void
6943 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
6944                        int delalloc)
6945 {
6946         if (delalloc)
6947                 down_read(&cache->data_rwsem);
6948 }
6949
6950 static inline void
6951 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
6952                        int delalloc)
6953 {
6954         btrfs_get_block_group(cache);
6955         if (delalloc)
6956                 down_read(&cache->data_rwsem);
6957 }
6958
6959 static struct btrfs_block_group_cache *
6960 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
6961                    struct btrfs_free_cluster *cluster,
6962                    int delalloc)
6963 {
6964         struct btrfs_block_group_cache *used_bg;
6965         bool locked = false;
6966 again:
6967         spin_lock(&cluster->refill_lock);
6968         if (locked) {
6969                 if (used_bg == cluster->block_group)
6970                         return used_bg;
6971
6972                 up_read(&used_bg->data_rwsem);
6973                 btrfs_put_block_group(used_bg);
6974         }
6975
6976         used_bg = cluster->block_group;
6977         if (!used_bg)
6978                 return NULL;
6979
6980         if (used_bg == block_group)
6981                 return used_bg;
6982
6983         btrfs_get_block_group(used_bg);
6984
6985         if (!delalloc)
6986                 return used_bg;
6987
6988         if (down_read_trylock(&used_bg->data_rwsem))
6989                 return used_bg;
6990
6991         spin_unlock(&cluster->refill_lock);
6992         down_read(&used_bg->data_rwsem);
6993         locked = true;
6994         goto again;
6995 }
6996
6997 static inline void
6998 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
6999                          int delalloc)
7000 {
7001         if (delalloc)
7002                 up_read(&cache->data_rwsem);
7003         btrfs_put_block_group(cache);
7004 }
7005
7006 /*
7007  * walks the btree of allocated extents and find a hole of a given size.
7008  * The key ins is changed to record the hole:
7009  * ins->objectid == start position
7010  * ins->flags = BTRFS_EXTENT_ITEM_KEY
7011  * ins->offset == the size of the hole.
7012  * Any available blocks before search_start are skipped.
7013  *
7014  * If there is no suitable free space, we will record the max size of
7015  * the free space extent currently.
7016  */
7017 static noinline int find_free_extent(struct btrfs_root *orig_root,
7018                                      u64 num_bytes, u64 empty_size,
7019                                      u64 hint_byte, struct btrfs_key *ins,
7020                                      u64 flags, int delalloc)
7021 {
7022         int ret = 0;
7023         struct btrfs_root *root = orig_root->fs_info->extent_root;
7024         struct btrfs_free_cluster *last_ptr = NULL;
7025         struct btrfs_block_group_cache *block_group = NULL;
7026         u64 search_start = 0;
7027         u64 max_extent_size = 0;
7028         u64 empty_cluster = 0;
7029         struct btrfs_space_info *space_info;
7030         int loop = 0;
7031         int index = __get_raid_index(flags);
7032         int alloc_type = (flags & BTRFS_BLOCK_GROUP_DATA) ?
7033                 RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
7034         bool failed_cluster_refill = false;
7035         bool failed_alloc = false;
7036         bool use_cluster = true;
7037         bool have_caching_bg = false;
7038         bool orig_have_caching_bg = false;
7039         bool full_search = false;
7040
7041         WARN_ON(num_bytes < root->sectorsize);
7042         ins->type = BTRFS_EXTENT_ITEM_KEY;
7043         ins->objectid = 0;
7044         ins->offset = 0;
7045
7046         trace_find_free_extent(orig_root, num_bytes, empty_size, flags);
7047
7048         space_info = __find_space_info(root->fs_info, flags);
7049         if (!space_info) {
7050                 btrfs_err(root->fs_info, "No space info for %llu", flags);
7051                 return -ENOSPC;
7052         }
7053
7054         /*
7055          * If our free space is heavily fragmented we may not be able to make
7056          * big contiguous allocations, so instead of doing the expensive search
7057          * for free space, simply return ENOSPC with our max_extent_size so we
7058          * can go ahead and search for a more manageable chunk.
7059          *
7060          * If our max_extent_size is large enough for our allocation simply
7061          * disable clustering since we will likely not be able to find enough
7062          * space to create a cluster and induce latency trying.
7063          */
7064         if (unlikely(space_info->max_extent_size)) {
7065                 spin_lock(&space_info->lock);
7066                 if (space_info->max_extent_size &&
7067                     num_bytes > space_info->max_extent_size) {
7068                         ins->offset = space_info->max_extent_size;
7069                         spin_unlock(&space_info->lock);
7070                         return -ENOSPC;
7071                 } else if (space_info->max_extent_size) {
7072                         use_cluster = false;
7073                 }
7074                 spin_unlock(&space_info->lock);
7075         }
7076
7077         last_ptr = fetch_cluster_info(orig_root, space_info, &empty_cluster);
7078         if (last_ptr) {
7079                 spin_lock(&last_ptr->lock);
7080                 if (last_ptr->block_group)
7081                         hint_byte = last_ptr->window_start;
7082                 if (last_ptr->fragmented) {
7083                         /*
7084                          * We still set window_start so we can keep track of the
7085                          * last place we found an allocation to try and save
7086                          * some time.
7087                          */
7088                         hint_byte = last_ptr->window_start;
7089                         use_cluster = false;
7090                 }
7091                 spin_unlock(&last_ptr->lock);
7092         }
7093
7094         search_start = max(search_start, first_logical_byte(root, 0));
7095         search_start = max(search_start, hint_byte);
7096         if (search_start == hint_byte) {
7097                 block_group = btrfs_lookup_block_group(root->fs_info,
7098                                                        search_start);
7099                 /*
7100                  * we don't want to use the block group if it doesn't match our
7101                  * allocation bits, or if its not cached.
7102                  *
7103                  * However if we are re-searching with an ideal block group
7104                  * picked out then we don't care that the block group is cached.
7105                  */
7106                 if (block_group && block_group_bits(block_group, flags) &&
7107                     block_group->cached != BTRFS_CACHE_NO) {
7108                         down_read(&space_info->groups_sem);
7109                         if (list_empty(&block_group->list) ||
7110                             block_group->ro) {
7111                                 /*
7112                                  * someone is removing this block group,
7113                                  * we can't jump into the have_block_group
7114                                  * target because our list pointers are not
7115                                  * valid
7116                                  */
7117                                 btrfs_put_block_group(block_group);
7118                                 up_read(&space_info->groups_sem);
7119                         } else {
7120                                 index = get_block_group_index(block_group);
7121                                 btrfs_lock_block_group(block_group, delalloc);
7122                                 goto have_block_group;
7123                         }
7124                 } else if (block_group) {
7125                         btrfs_put_block_group(block_group);
7126                 }
7127         }
7128 search:
7129         have_caching_bg = false;
7130         if (index == 0 || index == __get_raid_index(flags))
7131                 full_search = true;
7132         down_read(&space_info->groups_sem);
7133         list_for_each_entry(block_group, &space_info->block_groups[index],
7134                             list) {
7135                 u64 offset;
7136                 int cached;
7137
7138                 btrfs_grab_block_group(block_group, delalloc);
7139                 search_start = block_group->key.objectid;
7140
7141                 /*
7142                  * this can happen if we end up cycling through all the
7143                  * raid types, but we want to make sure we only allocate
7144                  * for the proper type.
7145                  */
7146                 if (!block_group_bits(block_group, flags)) {
7147                     u64 extra = BTRFS_BLOCK_GROUP_DUP |
7148                                 BTRFS_BLOCK_GROUP_RAID1 |
7149                                 BTRFS_BLOCK_GROUP_RAID5 |
7150                                 BTRFS_BLOCK_GROUP_RAID6 |
7151                                 BTRFS_BLOCK_GROUP_RAID10;
7152
7153                         /*
7154                          * if they asked for extra copies and this block group
7155                          * doesn't provide them, bail.  This does allow us to
7156                          * fill raid0 from raid1.
7157                          */
7158                         if ((flags & extra) && !(block_group->flags & extra))
7159                                 goto loop;
7160                 }
7161
7162 have_block_group:
7163                 cached = block_group_cache_done(block_group);
7164                 if (unlikely(!cached)) {
7165                         have_caching_bg = true;
7166                         ret = cache_block_group(block_group, 0);
7167                         BUG_ON(ret < 0);
7168                         ret = 0;
7169                 }
7170
7171                 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7172                         goto loop;
7173                 if (unlikely(block_group->ro))
7174                         goto loop;
7175
7176                 /*
7177                  * Ok we want to try and use the cluster allocator, so
7178                  * lets look there
7179                  */
7180                 if (last_ptr && use_cluster) {
7181                         struct btrfs_block_group_cache *used_block_group;
7182                         unsigned long aligned_cluster;
7183                         /*
7184                          * the refill lock keeps out other
7185                          * people trying to start a new cluster
7186                          */
7187                         used_block_group = btrfs_lock_cluster(block_group,
7188                                                               last_ptr,
7189                                                               delalloc);
7190                         if (!used_block_group)
7191                                 goto refill_cluster;
7192
7193                         if (used_block_group != block_group &&
7194                             (used_block_group->ro ||
7195                              !block_group_bits(used_block_group, flags)))
7196                                 goto release_cluster;
7197
7198                         offset = btrfs_alloc_from_cluster(used_block_group,
7199                                                 last_ptr,
7200                                                 num_bytes,
7201                                                 used_block_group->key.objectid,
7202                                                 &max_extent_size);
7203                         if (offset) {
7204                                 /* we have a block, we're done */
7205                                 spin_unlock(&last_ptr->refill_lock);
7206                                 trace_btrfs_reserve_extent_cluster(root,
7207                                                 used_block_group,
7208                                                 search_start, num_bytes);
7209                                 if (used_block_group != block_group) {
7210                                         btrfs_release_block_group(block_group,
7211                                                                   delalloc);
7212                                         block_group = used_block_group;
7213                                 }
7214                                 goto checks;
7215                         }
7216
7217                         WARN_ON(last_ptr->block_group != used_block_group);
7218 release_cluster:
7219                         /* If we are on LOOP_NO_EMPTY_SIZE, we can't
7220                          * set up a new clusters, so lets just skip it
7221                          * and let the allocator find whatever block
7222                          * it can find.  If we reach this point, we
7223                          * will have tried the cluster allocator
7224                          * plenty of times and not have found
7225                          * anything, so we are likely way too
7226                          * fragmented for the clustering stuff to find
7227                          * anything.
7228                          *
7229                          * However, if the cluster is taken from the
7230                          * current block group, release the cluster
7231                          * first, so that we stand a better chance of
7232                          * succeeding in the unclustered
7233                          * allocation.  */
7234                         if (loop >= LOOP_NO_EMPTY_SIZE &&
7235                             used_block_group != block_group) {
7236                                 spin_unlock(&last_ptr->refill_lock);
7237                                 btrfs_release_block_group(used_block_group,
7238                                                           delalloc);
7239                                 goto unclustered_alloc;
7240                         }
7241
7242                         /*
7243                          * this cluster didn't work out, free it and
7244                          * start over
7245                          */
7246                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
7247
7248                         if (used_block_group != block_group)
7249                                 btrfs_release_block_group(used_block_group,
7250                                                           delalloc);
7251 refill_cluster:
7252                         if (loop >= LOOP_NO_EMPTY_SIZE) {
7253                                 spin_unlock(&last_ptr->refill_lock);
7254                                 goto unclustered_alloc;
7255                         }
7256
7257                         aligned_cluster = max_t(unsigned long,
7258                                                 empty_cluster + empty_size,
7259                                               block_group->full_stripe_len);
7260
7261                         /* allocate a cluster in this block group */
7262                         ret = btrfs_find_space_cluster(root, block_group,
7263                                                        last_ptr, search_start,
7264                                                        num_bytes,
7265                                                        aligned_cluster);
7266                         if (ret == 0) {
7267                                 /*
7268                                  * now pull our allocation out of this
7269                                  * cluster
7270                                  */
7271                                 offset = btrfs_alloc_from_cluster(block_group,
7272                                                         last_ptr,
7273                                                         num_bytes,
7274                                                         search_start,
7275                                                         &max_extent_size);
7276                                 if (offset) {
7277                                         /* we found one, proceed */
7278                                         spin_unlock(&last_ptr->refill_lock);
7279                                         trace_btrfs_reserve_extent_cluster(root,
7280                                                 block_group, search_start,
7281                                                 num_bytes);
7282                                         goto checks;
7283                                 }
7284                         } else if (!cached && loop > LOOP_CACHING_NOWAIT
7285                                    && !failed_cluster_refill) {
7286                                 spin_unlock(&last_ptr->refill_lock);
7287
7288                                 failed_cluster_refill = true;
7289                                 wait_block_group_cache_progress(block_group,
7290                                        num_bytes + empty_cluster + empty_size);
7291                                 goto have_block_group;
7292                         }
7293
7294                         /*
7295                          * at this point we either didn't find a cluster
7296                          * or we weren't able to allocate a block from our
7297                          * cluster.  Free the cluster we've been trying
7298                          * to use, and go to the next block group
7299                          */
7300                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
7301                         spin_unlock(&last_ptr->refill_lock);
7302                         goto loop;
7303                 }
7304
7305 unclustered_alloc:
7306                 /*
7307                  * We are doing an unclustered alloc, set the fragmented flag so
7308                  * we don't bother trying to setup a cluster again until we get
7309                  * more space.
7310                  */
7311                 if (unlikely(last_ptr)) {
7312                         spin_lock(&last_ptr->lock);
7313                         last_ptr->fragmented = 1;
7314                         spin_unlock(&last_ptr->lock);
7315                 }
7316                 spin_lock(&block_group->free_space_ctl->tree_lock);
7317                 if (cached &&
7318                     block_group->free_space_ctl->free_space <
7319                     num_bytes + empty_cluster + empty_size) {
7320                         if (block_group->free_space_ctl->free_space >
7321                             max_extent_size)
7322                                 max_extent_size =
7323                                         block_group->free_space_ctl->free_space;
7324                         spin_unlock(&block_group->free_space_ctl->tree_lock);
7325                         goto loop;
7326                 }
7327                 spin_unlock(&block_group->free_space_ctl->tree_lock);
7328
7329                 offset = btrfs_find_space_for_alloc(block_group, search_start,
7330                                                     num_bytes, empty_size,
7331                                                     &max_extent_size);
7332                 /*
7333                  * If we didn't find a chunk, and we haven't failed on this
7334                  * block group before, and this block group is in the middle of
7335                  * caching and we are ok with waiting, then go ahead and wait
7336                  * for progress to be made, and set failed_alloc to true.
7337                  *
7338                  * If failed_alloc is true then we've already waited on this
7339                  * block group once and should move on to the next block group.
7340                  */
7341                 if (!offset && !failed_alloc && !cached &&
7342                     loop > LOOP_CACHING_NOWAIT) {
7343                         wait_block_group_cache_progress(block_group,
7344                                                 num_bytes + empty_size);
7345                         failed_alloc = true;
7346                         goto have_block_group;
7347                 } else if (!offset) {
7348                         goto loop;
7349                 }
7350 checks:
7351                 search_start = ALIGN(offset, root->stripesize);
7352
7353                 /* move on to the next group */
7354                 if (search_start + num_bytes >
7355                     block_group->key.objectid + block_group->key.offset) {
7356                         btrfs_add_free_space(block_group, offset, num_bytes);
7357                         goto loop;
7358                 }
7359
7360                 if (offset < search_start)
7361                         btrfs_add_free_space(block_group, offset,
7362                                              search_start - offset);
7363                 BUG_ON(offset > search_start);
7364
7365                 ret = btrfs_update_reserved_bytes(block_group, num_bytes,
7366                                                   alloc_type, delalloc);
7367                 if (ret == -EAGAIN) {
7368                         btrfs_add_free_space(block_group, offset, num_bytes);
7369                         goto loop;
7370                 }
7371
7372                 /* we are all good, lets return */
7373                 ins->objectid = search_start;
7374                 ins->offset = num_bytes;
7375
7376                 trace_btrfs_reserve_extent(orig_root, block_group,
7377                                            search_start, num_bytes);
7378                 btrfs_release_block_group(block_group, delalloc);
7379                 break;
7380 loop:
7381                 failed_cluster_refill = false;
7382                 failed_alloc = false;
7383                 BUG_ON(index != get_block_group_index(block_group));
7384                 btrfs_release_block_group(block_group, delalloc);
7385         }
7386         up_read(&space_info->groups_sem);
7387
7388         if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
7389                 && !orig_have_caching_bg)
7390                 orig_have_caching_bg = true;
7391
7392         if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
7393                 goto search;
7394
7395         if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
7396                 goto search;
7397
7398         /*
7399          * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7400          *                      caching kthreads as we move along
7401          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7402          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7403          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7404          *                      again
7405          */
7406         if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
7407                 index = 0;
7408                 if (loop == LOOP_CACHING_NOWAIT) {
7409                         /*
7410                          * We want to skip the LOOP_CACHING_WAIT step if we
7411                          * don't have any unached bgs and we've alrelady done a
7412                          * full search through.
7413                          */
7414                         if (orig_have_caching_bg || !full_search)
7415                                 loop = LOOP_CACHING_WAIT;
7416                         else
7417                                 loop = LOOP_ALLOC_CHUNK;
7418                 } else {
7419                         loop++;
7420                 }
7421
7422                 if (loop == LOOP_ALLOC_CHUNK) {
7423                         struct btrfs_trans_handle *trans;
7424                         int exist = 0;
7425
7426                         trans = current->journal_info;
7427                         if (trans)
7428                                 exist = 1;
7429                         else
7430                                 trans = btrfs_join_transaction(root);
7431
7432                         if (IS_ERR(trans)) {
7433                                 ret = PTR_ERR(trans);
7434                                 goto out;
7435                         }
7436
7437                         ret = do_chunk_alloc(trans, root, flags,
7438                                              CHUNK_ALLOC_FORCE);
7439
7440                         /*
7441                          * If we can't allocate a new chunk we've already looped
7442                          * through at least once, move on to the NO_EMPTY_SIZE
7443                          * case.
7444                          */
7445                         if (ret == -ENOSPC)
7446                                 loop = LOOP_NO_EMPTY_SIZE;
7447
7448                         /*
7449                          * Do not bail out on ENOSPC since we
7450                          * can do more things.
7451                          */
7452                         if (ret < 0 && ret != -ENOSPC)
7453                                 btrfs_abort_transaction(trans,
7454                                                         root, ret);
7455                         else
7456                                 ret = 0;
7457                         if (!exist)
7458                                 btrfs_end_transaction(trans, root);
7459                         if (ret)
7460                                 goto out;
7461                 }
7462
7463                 if (loop == LOOP_NO_EMPTY_SIZE) {
7464                         /*
7465                          * Don't loop again if we already have no empty_size and
7466                          * no empty_cluster.
7467                          */
7468                         if (empty_size == 0 &&
7469                             empty_cluster == 0) {
7470                                 ret = -ENOSPC;
7471                                 goto out;
7472                         }
7473                         empty_size = 0;
7474                         empty_cluster = 0;
7475                 }
7476
7477                 goto search;
7478         } else if (!ins->objectid) {
7479                 ret = -ENOSPC;
7480         } else if (ins->objectid) {
7481                 if (!use_cluster && last_ptr) {
7482                         spin_lock(&last_ptr->lock);
7483                         last_ptr->window_start = ins->objectid;
7484                         spin_unlock(&last_ptr->lock);
7485                 }
7486                 ret = 0;
7487         }
7488 out:
7489         if (ret == -ENOSPC) {
7490                 spin_lock(&space_info->lock);
7491                 space_info->max_extent_size = max_extent_size;
7492                 spin_unlock(&space_info->lock);
7493                 ins->offset = max_extent_size;
7494         }
7495         return ret;
7496 }
7497
7498 static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
7499                             int dump_block_groups)
7500 {
7501         struct btrfs_block_group_cache *cache;
7502         int index = 0;
7503
7504         spin_lock(&info->lock);
7505         printk(KERN_INFO "BTRFS: space_info %llu has %llu free, is %sfull\n",
7506                info->flags,
7507                info->total_bytes - info->bytes_used - info->bytes_pinned -
7508                info->bytes_reserved - info->bytes_readonly,
7509                (info->full) ? "" : "not ");
7510         printk(KERN_INFO "BTRFS: space_info total=%llu, used=%llu, pinned=%llu, "
7511                "reserved=%llu, may_use=%llu, readonly=%llu\n",
7512                info->total_bytes, info->bytes_used, info->bytes_pinned,
7513                info->bytes_reserved, info->bytes_may_use,
7514                info->bytes_readonly);
7515         spin_unlock(&info->lock);
7516
7517         if (!dump_block_groups)
7518                 return;
7519
7520         down_read(&info->groups_sem);
7521 again:
7522         list_for_each_entry(cache, &info->block_groups[index], list) {
7523                 spin_lock(&cache->lock);
7524                 printk(KERN_INFO "BTRFS: "
7525                            "block group %llu has %llu bytes, "
7526                            "%llu used %llu pinned %llu reserved %s\n",
7527                        cache->key.objectid, cache->key.offset,
7528                        btrfs_block_group_used(&cache->item), cache->pinned,
7529                        cache->reserved, cache->ro ? "[readonly]" : "");
7530                 btrfs_dump_free_space(cache, bytes);
7531                 spin_unlock(&cache->lock);
7532         }
7533         if (++index < BTRFS_NR_RAID_TYPES)
7534                 goto again;
7535         up_read(&info->groups_sem);
7536 }
7537
7538 int btrfs_reserve_extent(struct btrfs_root *root,
7539                          u64 num_bytes, u64 min_alloc_size,
7540                          u64 empty_size, u64 hint_byte,
7541                          struct btrfs_key *ins, int is_data, int delalloc)
7542 {
7543         bool final_tried = num_bytes == min_alloc_size;
7544         u64 flags;
7545         int ret;
7546
7547         flags = btrfs_get_alloc_profile(root, is_data);
7548 again:
7549         WARN_ON(num_bytes < root->sectorsize);
7550         ret = find_free_extent(root, num_bytes, empty_size, hint_byte, ins,
7551                                flags, delalloc);
7552
7553         if (ret == -ENOSPC) {
7554                 if (!final_tried && ins->offset) {
7555                         num_bytes = min(num_bytes >> 1, ins->offset);
7556                         num_bytes = round_down(num_bytes, root->sectorsize);
7557                         num_bytes = max(num_bytes, min_alloc_size);
7558                         if (num_bytes == min_alloc_size)
7559                                 final_tried = true;
7560                         goto again;
7561                 } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
7562                         struct btrfs_space_info *sinfo;
7563
7564                         sinfo = __find_space_info(root->fs_info, flags);
7565                         btrfs_err(root->fs_info, "allocation failed flags %llu, wanted %llu",
7566                                 flags, num_bytes);
7567                         if (sinfo)
7568                                 dump_space_info(sinfo, num_bytes, 1);
7569                 }
7570         }
7571
7572         return ret;
7573 }
7574
7575 static int __btrfs_free_reserved_extent(struct btrfs_root *root,
7576                                         u64 start, u64 len,
7577                                         int pin, int delalloc)
7578 {
7579         struct btrfs_block_group_cache *cache;
7580         int ret = 0;
7581
7582         cache = btrfs_lookup_block_group(root->fs_info, start);
7583         if (!cache) {
7584                 btrfs_err(root->fs_info, "Unable to find block group for %llu",
7585                         start);
7586                 return -ENOSPC;
7587         }
7588
7589         if (pin)
7590                 pin_down_extent(root, cache, start, len, 1);
7591         else {
7592                 if (btrfs_test_opt(root, DISCARD))
7593                         ret = btrfs_discard_extent(root, start, len, NULL);
7594                 btrfs_add_free_space(cache, start, len);
7595                 btrfs_update_reserved_bytes(cache, len, RESERVE_FREE, delalloc);
7596         }
7597
7598         btrfs_put_block_group(cache);
7599
7600         trace_btrfs_reserved_extent_free(root, start, len);
7601
7602         return ret;
7603 }
7604
7605 int btrfs_free_reserved_extent(struct btrfs_root *root,
7606                                u64 start, u64 len, int delalloc)
7607 {
7608         return __btrfs_free_reserved_extent(root, start, len, 0, delalloc);
7609 }
7610
7611 int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
7612                                        u64 start, u64 len)
7613 {
7614         return __btrfs_free_reserved_extent(root, start, len, 1, 0);
7615 }
7616
7617 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7618                                       struct btrfs_root *root,
7619                                       u64 parent, u64 root_objectid,
7620                                       u64 flags, u64 owner, u64 offset,
7621                                       struct btrfs_key *ins, int ref_mod)
7622 {
7623         int ret;
7624         struct btrfs_fs_info *fs_info = root->fs_info;
7625         struct btrfs_extent_item *extent_item;
7626         struct btrfs_extent_inline_ref *iref;
7627         struct btrfs_path *path;
7628         struct extent_buffer *leaf;
7629         int type;
7630         u32 size;
7631
7632         if (parent > 0)
7633                 type = BTRFS_SHARED_DATA_REF_KEY;
7634         else
7635                 type = BTRFS_EXTENT_DATA_REF_KEY;
7636
7637         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7638
7639         path = btrfs_alloc_path();
7640         if (!path)
7641                 return -ENOMEM;
7642
7643         path->leave_spinning = 1;
7644         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7645                                       ins, size);
7646         if (ret) {
7647                 btrfs_free_path(path);
7648                 return ret;
7649         }
7650
7651         leaf = path->nodes[0];
7652         extent_item = btrfs_item_ptr(leaf, path->slots[0],
7653                                      struct btrfs_extent_item);
7654         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
7655         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7656         btrfs_set_extent_flags(leaf, extent_item,
7657                                flags | BTRFS_EXTENT_FLAG_DATA);
7658
7659         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
7660         btrfs_set_extent_inline_ref_type(leaf, iref, type);
7661         if (parent > 0) {
7662                 struct btrfs_shared_data_ref *ref;
7663                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
7664                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
7665                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
7666         } else {
7667                 struct btrfs_extent_data_ref *ref;
7668                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
7669                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
7670                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
7671                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
7672                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
7673         }
7674
7675         btrfs_mark_buffer_dirty(path->nodes[0]);
7676         btrfs_free_path(path);
7677
7678         ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
7679         if (ret) { /* -ENOENT, logic error */
7680                 btrfs_err(fs_info, "update block group failed for %llu %llu",
7681                         ins->objectid, ins->offset);
7682                 BUG();
7683         }
7684         trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
7685         return ret;
7686 }
7687
7688 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
7689                                      struct btrfs_root *root,
7690                                      u64 parent, u64 root_objectid,
7691                                      u64 flags, struct btrfs_disk_key *key,
7692                                      int level, struct btrfs_key *ins)
7693 {
7694         int ret;
7695         struct btrfs_fs_info *fs_info = root->fs_info;
7696         struct btrfs_extent_item *extent_item;
7697         struct btrfs_tree_block_info *block_info;
7698         struct btrfs_extent_inline_ref *iref;
7699         struct btrfs_path *path;
7700         struct extent_buffer *leaf;
7701         u32 size = sizeof(*extent_item) + sizeof(*iref);
7702         u64 num_bytes = ins->offset;
7703         bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
7704                                                  SKINNY_METADATA);
7705
7706         if (!skinny_metadata)
7707                 size += sizeof(*block_info);
7708
7709         path = btrfs_alloc_path();
7710         if (!path) {
7711                 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
7712                                                    root->nodesize);
7713                 return -ENOMEM;
7714         }
7715
7716         path->leave_spinning = 1;
7717         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7718                                       ins, size);
7719         if (ret) {
7720                 btrfs_free_path(path);
7721                 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
7722                                                    root->nodesize);
7723                 return ret;
7724         }
7725
7726         leaf = path->nodes[0];
7727         extent_item = btrfs_item_ptr(leaf, path->slots[0],
7728                                      struct btrfs_extent_item);
7729         btrfs_set_extent_refs(leaf, extent_item, 1);
7730         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7731         btrfs_set_extent_flags(leaf, extent_item,
7732                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
7733
7734         if (skinny_metadata) {
7735                 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
7736                 num_bytes = root->nodesize;
7737         } else {
7738                 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
7739                 btrfs_set_tree_block_key(leaf, block_info, key);
7740                 btrfs_set_tree_block_level(leaf, block_info, level);
7741                 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
7742         }
7743
7744         if (parent > 0) {
7745                 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
7746                 btrfs_set_extent_inline_ref_type(leaf, iref,
7747                                                  BTRFS_SHARED_BLOCK_REF_KEY);
7748                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
7749         } else {
7750                 btrfs_set_extent_inline_ref_type(leaf, iref,
7751                                                  BTRFS_TREE_BLOCK_REF_KEY);
7752                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
7753         }
7754
7755         btrfs_mark_buffer_dirty(leaf);
7756         btrfs_free_path(path);
7757
7758         ret = update_block_group(trans, root, ins->objectid, root->nodesize,
7759                                  1);
7760         if (ret) { /* -ENOENT, logic error */
7761                 btrfs_err(fs_info, "update block group failed for %llu %llu",
7762                         ins->objectid, ins->offset);
7763                 BUG();
7764         }
7765
7766         trace_btrfs_reserved_extent_alloc(root, ins->objectid, root->nodesize);
7767         return ret;
7768 }
7769
7770 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7771                                      struct btrfs_root *root,
7772                                      u64 root_objectid, u64 owner,
7773                                      u64 offset, u64 ram_bytes,
7774                                      struct btrfs_key *ins)
7775 {
7776         int ret;
7777
7778         BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
7779
7780         ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
7781                                          ins->offset, 0,
7782                                          root_objectid, owner, offset,
7783                                          ram_bytes, BTRFS_ADD_DELAYED_EXTENT,
7784                                          NULL);
7785         return ret;
7786 }
7787
7788 /*
7789  * this is used by the tree logging recovery code.  It records that
7790  * an extent has been allocated and makes sure to clear the free
7791  * space cache bits as well
7792  */
7793 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
7794                                    struct btrfs_root *root,
7795                                    u64 root_objectid, u64 owner, u64 offset,
7796                                    struct btrfs_key *ins)
7797 {
7798         int ret;
7799         struct btrfs_block_group_cache *block_group;
7800
7801         /*
7802          * Mixed block groups will exclude before processing the log so we only
7803          * need to do the exlude dance if this fs isn't mixed.
7804          */
7805         if (!btrfs_fs_incompat(root->fs_info, MIXED_GROUPS)) {
7806                 ret = __exclude_logged_extent(root, ins->objectid, ins->offset);
7807                 if (ret)
7808                         return ret;
7809         }
7810
7811         block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
7812         if (!block_group)
7813                 return -EINVAL;
7814
7815         ret = btrfs_update_reserved_bytes(block_group, ins->offset,
7816                                           RESERVE_ALLOC_NO_ACCOUNT, 0);
7817         BUG_ON(ret); /* logic error */
7818         ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
7819                                          0, owner, offset, ins, 1);
7820         btrfs_put_block_group(block_group);
7821         return ret;
7822 }
7823
7824 static struct extent_buffer *
7825 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
7826                       u64 bytenr, int level)
7827 {
7828         struct extent_buffer *buf;
7829
7830         buf = btrfs_find_create_tree_block(root, bytenr);
7831         if (!buf)
7832                 return ERR_PTR(-ENOMEM);
7833         btrfs_set_header_generation(buf, trans->transid);
7834         btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
7835         btrfs_tree_lock(buf);
7836         clean_tree_block(trans, root->fs_info, buf);
7837         clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
7838
7839         btrfs_set_lock_blocking(buf);
7840         btrfs_set_buffer_uptodate(buf);
7841
7842         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
7843                 buf->log_index = root->log_transid % 2;
7844                 /*
7845                  * we allow two log transactions at a time, use different
7846                  * EXENT bit to differentiate dirty pages.
7847                  */
7848                 if (buf->log_index == 0)
7849                         set_extent_dirty(&root->dirty_log_pages, buf->start,
7850                                         buf->start + buf->len - 1, GFP_NOFS);
7851                 else
7852                         set_extent_new(&root->dirty_log_pages, buf->start,
7853                                         buf->start + buf->len - 1, GFP_NOFS);
7854         } else {
7855                 buf->log_index = -1;
7856                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
7857                          buf->start + buf->len - 1, GFP_NOFS);
7858         }
7859         trans->dirty = true;
7860         /* this returns a buffer locked for blocking */
7861         return buf;
7862 }
7863
7864 static struct btrfs_block_rsv *
7865 use_block_rsv(struct btrfs_trans_handle *trans,
7866               struct btrfs_root *root, u32 blocksize)
7867 {
7868         struct btrfs_block_rsv *block_rsv;
7869         struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
7870         int ret;
7871         bool global_updated = false;
7872
7873         block_rsv = get_block_rsv(trans, root);
7874
7875         if (unlikely(block_rsv->size == 0))
7876                 goto try_reserve;
7877 again:
7878         ret = block_rsv_use_bytes(block_rsv, blocksize);
7879         if (!ret)
7880                 return block_rsv;
7881
7882         if (block_rsv->failfast)
7883                 return ERR_PTR(ret);
7884
7885         if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
7886                 global_updated = true;
7887                 update_global_block_rsv(root->fs_info);
7888                 goto again;
7889         }
7890
7891         if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
7892                 static DEFINE_RATELIMIT_STATE(_rs,
7893                                 DEFAULT_RATELIMIT_INTERVAL * 10,
7894                                 /*DEFAULT_RATELIMIT_BURST*/ 1);
7895                 if (__ratelimit(&_rs))
7896                         WARN(1, KERN_DEBUG
7897                                 "BTRFS: block rsv returned %d\n", ret);
7898         }
7899 try_reserve:
7900         ret = reserve_metadata_bytes(root, block_rsv, blocksize,
7901                                      BTRFS_RESERVE_NO_FLUSH);
7902         if (!ret)
7903                 return block_rsv;
7904         /*
7905          * If we couldn't reserve metadata bytes try and use some from
7906          * the global reserve if its space type is the same as the global
7907          * reservation.
7908          */
7909         if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
7910             block_rsv->space_info == global_rsv->space_info) {
7911                 ret = block_rsv_use_bytes(global_rsv, blocksize);
7912                 if (!ret)
7913                         return global_rsv;
7914         }
7915         return ERR_PTR(ret);
7916 }
7917
7918 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
7919                             struct btrfs_block_rsv *block_rsv, u32 blocksize)
7920 {
7921         block_rsv_add_bytes(block_rsv, blocksize, 0);
7922         block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
7923 }
7924
7925 /*
7926  * finds a free extent and does all the dirty work required for allocation
7927  * returns the tree buffer or an ERR_PTR on error.
7928  */
7929 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
7930                                         struct btrfs_root *root,
7931                                         u64 parent, u64 root_objectid,
7932                                         struct btrfs_disk_key *key, int level,
7933                                         u64 hint, u64 empty_size)
7934 {
7935         struct btrfs_key ins;
7936         struct btrfs_block_rsv *block_rsv;
7937         struct extent_buffer *buf;
7938         struct btrfs_delayed_extent_op *extent_op;
7939         u64 flags = 0;
7940         int ret;
7941         u32 blocksize = root->nodesize;
7942         bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
7943                                                  SKINNY_METADATA);
7944
7945         if (btrfs_test_is_dummy_root(root)) {
7946                 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
7947                                             level);
7948                 if (!IS_ERR(buf))
7949                         root->alloc_bytenr += blocksize;
7950                 return buf;
7951         }
7952
7953         block_rsv = use_block_rsv(trans, root, blocksize);
7954         if (IS_ERR(block_rsv))
7955                 return ERR_CAST(block_rsv);
7956
7957         ret = btrfs_reserve_extent(root, blocksize, blocksize,
7958                                    empty_size, hint, &ins, 0, 0);
7959         if (ret)
7960                 goto out_unuse;
7961
7962         buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
7963         if (IS_ERR(buf)) {
7964                 ret = PTR_ERR(buf);
7965                 goto out_free_reserved;
7966         }
7967
7968         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
7969                 if (parent == 0)
7970                         parent = ins.objectid;
7971                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7972         } else
7973                 BUG_ON(parent > 0);
7974
7975         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
7976                 extent_op = btrfs_alloc_delayed_extent_op();
7977                 if (!extent_op) {
7978                         ret = -ENOMEM;
7979                         goto out_free_buf;
7980                 }
7981                 if (key)
7982                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
7983                 else
7984                         memset(&extent_op->key, 0, sizeof(extent_op->key));
7985                 extent_op->flags_to_set = flags;
7986                 if (skinny_metadata)
7987                         extent_op->update_key = 0;
7988                 else
7989                         extent_op->update_key = 1;
7990                 extent_op->update_flags = 1;
7991                 extent_op->is_data = 0;
7992                 extent_op->level = level;
7993
7994                 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
7995                                                  ins.objectid, ins.offset,
7996                                                  parent, root_objectid, level,
7997                                                  BTRFS_ADD_DELAYED_EXTENT,
7998                                                  extent_op);
7999                 if (ret)
8000                         goto out_free_delayed;
8001         }
8002         return buf;
8003
8004 out_free_delayed:
8005         btrfs_free_delayed_extent_op(extent_op);
8006 out_free_buf:
8007         free_extent_buffer(buf);
8008 out_free_reserved:
8009         btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 0);
8010 out_unuse:
8011         unuse_block_rsv(root->fs_info, block_rsv, blocksize);
8012         return ERR_PTR(ret);
8013 }
8014
8015 struct walk_control {
8016         u64 refs[BTRFS_MAX_LEVEL];
8017         u64 flags[BTRFS_MAX_LEVEL];
8018         struct btrfs_key update_progress;
8019         int stage;
8020         int level;
8021         int shared_level;
8022         int update_ref;
8023         int keep_locks;
8024         int reada_slot;
8025         int reada_count;
8026         int for_reloc;
8027 };
8028
8029 #define DROP_REFERENCE  1
8030 #define UPDATE_BACKREF  2
8031
8032 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8033                                      struct btrfs_root *root,
8034                                      struct walk_control *wc,
8035                                      struct btrfs_path *path)
8036 {
8037         u64 bytenr;
8038         u64 generation;
8039         u64 refs;
8040         u64 flags;
8041         u32 nritems;
8042         u32 blocksize;
8043         struct btrfs_key key;
8044         struct extent_buffer *eb;
8045         int ret;
8046         int slot;
8047         int nread = 0;
8048
8049         if (path->slots[wc->level] < wc->reada_slot) {
8050                 wc->reada_count = wc->reada_count * 2 / 3;
8051                 wc->reada_count = max(wc->reada_count, 2);
8052         } else {
8053                 wc->reada_count = wc->reada_count * 3 / 2;
8054                 wc->reada_count = min_t(int, wc->reada_count,
8055                                         BTRFS_NODEPTRS_PER_BLOCK(root));
8056         }
8057
8058         eb = path->nodes[wc->level];
8059         nritems = btrfs_header_nritems(eb);
8060         blocksize = root->nodesize;
8061
8062         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8063                 if (nread >= wc->reada_count)
8064                         break;
8065
8066                 cond_resched();
8067                 bytenr = btrfs_node_blockptr(eb, slot);
8068                 generation = btrfs_node_ptr_generation(eb, slot);
8069
8070                 if (slot == path->slots[wc->level])
8071                         goto reada;
8072
8073                 if (wc->stage == UPDATE_BACKREF &&
8074                     generation <= root->root_key.offset)
8075                         continue;
8076
8077                 /* We don't lock the tree block, it's OK to be racy here */
8078                 ret = btrfs_lookup_extent_info(trans, root, bytenr,
8079                                                wc->level - 1, 1, &refs,
8080                                                &flags);
8081                 /* We don't care about errors in readahead. */
8082                 if (ret < 0)
8083                         continue;
8084                 BUG_ON(refs == 0);
8085
8086                 if (wc->stage == DROP_REFERENCE) {
8087                         if (refs == 1)
8088                                 goto reada;
8089
8090                         if (wc->level == 1 &&
8091                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8092                                 continue;
8093                         if (!wc->update_ref ||
8094                             generation <= root->root_key.offset)
8095                                 continue;
8096                         btrfs_node_key_to_cpu(eb, &key, slot);
8097                         ret = btrfs_comp_cpu_keys(&key,
8098                                                   &wc->update_progress);
8099                         if (ret < 0)
8100                                 continue;
8101                 } else {
8102                         if (wc->level == 1 &&
8103                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8104                                 continue;
8105                 }
8106 reada:
8107                 readahead_tree_block(root, bytenr);
8108                 nread++;
8109         }
8110         wc->reada_slot = slot;
8111 }
8112
8113 /*
8114  * These may not be seen by the usual inc/dec ref code so we have to
8115  * add them here.
8116  */
8117 static int record_one_subtree_extent(struct btrfs_trans_handle *trans,
8118                                      struct btrfs_root *root, u64 bytenr,
8119                                      u64 num_bytes)
8120 {
8121         struct btrfs_qgroup_extent_record *qrecord;
8122         struct btrfs_delayed_ref_root *delayed_refs;
8123
8124         qrecord = kmalloc(sizeof(*qrecord), GFP_NOFS);
8125         if (!qrecord)
8126                 return -ENOMEM;
8127
8128         qrecord->bytenr = bytenr;
8129         qrecord->num_bytes = num_bytes;
8130         qrecord->old_roots = NULL;
8131
8132         delayed_refs = &trans->transaction->delayed_refs;
8133         spin_lock(&delayed_refs->lock);
8134         if (btrfs_qgroup_insert_dirty_extent(delayed_refs, qrecord))
8135                 kfree(qrecord);
8136         spin_unlock(&delayed_refs->lock);
8137
8138         return 0;
8139 }
8140
8141 static int account_leaf_items(struct btrfs_trans_handle *trans,
8142                               struct btrfs_root *root,
8143                               struct extent_buffer *eb)
8144 {
8145         int nr = btrfs_header_nritems(eb);
8146         int i, extent_type, ret;
8147         struct btrfs_key key;
8148         struct btrfs_file_extent_item *fi;
8149         u64 bytenr, num_bytes;
8150
8151         /* We can be called directly from walk_up_proc() */
8152         if (!root->fs_info->quota_enabled)
8153                 return 0;
8154
8155         for (i = 0; i < nr; i++) {
8156                 btrfs_item_key_to_cpu(eb, &key, i);
8157
8158                 if (key.type != BTRFS_EXTENT_DATA_KEY)
8159                         continue;
8160
8161                 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
8162                 /* filter out non qgroup-accountable extents  */
8163                 extent_type = btrfs_file_extent_type(eb, fi);
8164
8165                 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
8166                         continue;
8167
8168                 bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
8169                 if (!bytenr)
8170                         continue;
8171
8172                 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
8173
8174                 ret = record_one_subtree_extent(trans, root, bytenr, num_bytes);
8175                 if (ret)
8176                         return ret;
8177         }
8178         return 0;
8179 }
8180
8181 /*
8182  * Walk up the tree from the bottom, freeing leaves and any interior
8183  * nodes which have had all slots visited. If a node (leaf or
8184  * interior) is freed, the node above it will have it's slot
8185  * incremented. The root node will never be freed.
8186  *
8187  * At the end of this function, we should have a path which has all
8188  * slots incremented to the next position for a search. If we need to
8189  * read a new node it will be NULL and the node above it will have the
8190  * correct slot selected for a later read.
8191  *
8192  * If we increment the root nodes slot counter past the number of
8193  * elements, 1 is returned to signal completion of the search.
8194  */
8195 static int adjust_slots_upwards(struct btrfs_root *root,
8196                                 struct btrfs_path *path, int root_level)
8197 {
8198         int level = 0;
8199         int nr, slot;
8200         struct extent_buffer *eb;
8201
8202         if (root_level == 0)
8203                 return 1;
8204
8205         while (level <= root_level) {
8206                 eb = path->nodes[level];
8207                 nr = btrfs_header_nritems(eb);
8208                 path->slots[level]++;
8209                 slot = path->slots[level];
8210                 if (slot >= nr || level == 0) {
8211                         /*
8212                          * Don't free the root -  we will detect this
8213                          * condition after our loop and return a
8214                          * positive value for caller to stop walking the tree.
8215                          */
8216                         if (level != root_level) {
8217                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8218                                 path->locks[level] = 0;
8219
8220                                 free_extent_buffer(eb);
8221                                 path->nodes[level] = NULL;
8222                                 path->slots[level] = 0;
8223                         }
8224                 } else {
8225                         /*
8226                          * We have a valid slot to walk back down
8227                          * from. Stop here so caller can process these
8228                          * new nodes.
8229                          */
8230                         break;
8231                 }
8232
8233                 level++;
8234         }
8235
8236         eb = path->nodes[root_level];
8237         if (path->slots[root_level] >= btrfs_header_nritems(eb))
8238                 return 1;
8239
8240         return 0;
8241 }
8242
8243 /*
8244  * root_eb is the subtree root and is locked before this function is called.
8245  */
8246 static int account_shared_subtree(struct btrfs_trans_handle *trans,
8247                                   struct btrfs_root *root,
8248                                   struct extent_buffer *root_eb,
8249                                   u64 root_gen,
8250                                   int root_level)
8251 {
8252         int ret = 0;
8253         int level;
8254         struct extent_buffer *eb = root_eb;
8255         struct btrfs_path *path = NULL;
8256
8257         BUG_ON(root_level < 0 || root_level > BTRFS_MAX_LEVEL);
8258         BUG_ON(root_eb == NULL);
8259
8260         if (!root->fs_info->quota_enabled)
8261                 return 0;
8262
8263         if (!extent_buffer_uptodate(root_eb)) {
8264                 ret = btrfs_read_buffer(root_eb, root_gen);
8265                 if (ret)
8266                         goto out;
8267         }
8268
8269         if (root_level == 0) {
8270                 ret = account_leaf_items(trans, root, root_eb);
8271                 goto out;
8272         }
8273
8274         path = btrfs_alloc_path();
8275         if (!path)
8276                 return -ENOMEM;
8277
8278         /*
8279          * Walk down the tree.  Missing extent blocks are filled in as
8280          * we go. Metadata is accounted every time we read a new
8281          * extent block.
8282          *
8283          * When we reach a leaf, we account for file extent items in it,
8284          * walk back up the tree (adjusting slot pointers as we go)
8285          * and restart the search process.
8286          */
8287         extent_buffer_get(root_eb); /* For path */
8288         path->nodes[root_level] = root_eb;
8289         path->slots[root_level] = 0;
8290         path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
8291 walk_down:
8292         level = root_level;
8293         while (level >= 0) {
8294                 if (path->nodes[level] == NULL) {
8295                         int parent_slot;
8296                         u64 child_gen;
8297                         u64 child_bytenr;
8298
8299                         /* We need to get child blockptr/gen from
8300                          * parent before we can read it. */
8301                         eb = path->nodes[level + 1];
8302                         parent_slot = path->slots[level + 1];
8303                         child_bytenr = btrfs_node_blockptr(eb, parent_slot);
8304                         child_gen = btrfs_node_ptr_generation(eb, parent_slot);
8305
8306                         eb = read_tree_block(root, child_bytenr, child_gen);
8307                         if (IS_ERR(eb)) {
8308                                 ret = PTR_ERR(eb);
8309                                 goto out;
8310                         } else if (!extent_buffer_uptodate(eb)) {
8311                                 free_extent_buffer(eb);
8312                                 ret = -EIO;
8313                                 goto out;
8314                         }
8315
8316                         path->nodes[level] = eb;
8317                         path->slots[level] = 0;
8318
8319                         btrfs_tree_read_lock(eb);
8320                         btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
8321                         path->locks[level] = BTRFS_READ_LOCK_BLOCKING;
8322
8323                         ret = record_one_subtree_extent(trans, root, child_bytenr,
8324                                                         root->nodesize);
8325                         if (ret)
8326                                 goto out;
8327                 }
8328
8329                 if (level == 0) {
8330                         ret = account_leaf_items(trans, root, path->nodes[level]);
8331                         if (ret)
8332                                 goto out;
8333
8334                         /* Nonzero return here means we completed our search */
8335                         ret = adjust_slots_upwards(root, path, root_level);
8336                         if (ret)
8337                                 break;
8338
8339                         /* Restart search with new slots */
8340                         goto walk_down;
8341                 }
8342
8343                 level--;
8344         }
8345
8346         ret = 0;
8347 out:
8348         btrfs_free_path(path);
8349
8350         return ret;
8351 }
8352
8353 /*
8354  * helper to process tree block while walking down the tree.
8355  *
8356  * when wc->stage == UPDATE_BACKREF, this function updates
8357  * back refs for pointers in the block.
8358  *
8359  * NOTE: return value 1 means we should stop walking down.
8360  */
8361 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8362                                    struct btrfs_root *root,
8363                                    struct btrfs_path *path,
8364                                    struct walk_control *wc, int lookup_info)
8365 {
8366         int level = wc->level;
8367         struct extent_buffer *eb = path->nodes[level];
8368         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8369         int ret;
8370
8371         if (wc->stage == UPDATE_BACKREF &&
8372             btrfs_header_owner(eb) != root->root_key.objectid)
8373                 return 1;
8374
8375         /*
8376          * when reference count of tree block is 1, it won't increase
8377          * again. once full backref flag is set, we never clear it.
8378          */
8379         if (lookup_info &&
8380             ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8381              (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8382                 BUG_ON(!path->locks[level]);
8383                 ret = btrfs_lookup_extent_info(trans, root,
8384                                                eb->start, level, 1,
8385                                                &wc->refs[level],
8386                                                &wc->flags[level]);
8387                 BUG_ON(ret == -ENOMEM);
8388                 if (ret)
8389                         return ret;
8390                 BUG_ON(wc->refs[level] == 0);
8391         }
8392
8393         if (wc->stage == DROP_REFERENCE) {
8394                 if (wc->refs[level] > 1)
8395                         return 1;
8396
8397                 if (path->locks[level] && !wc->keep_locks) {
8398                         btrfs_tree_unlock_rw(eb, path->locks[level]);
8399                         path->locks[level] = 0;
8400                 }
8401                 return 0;
8402         }
8403
8404         /* wc->stage == UPDATE_BACKREF */
8405         if (!(wc->flags[level] & flag)) {
8406                 BUG_ON(!path->locks[level]);
8407                 ret = btrfs_inc_ref(trans, root, eb, 1);
8408                 BUG_ON(ret); /* -ENOMEM */
8409                 ret = btrfs_dec_ref(trans, root, eb, 0);
8410                 BUG_ON(ret); /* -ENOMEM */
8411                 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
8412                                                   eb->len, flag,
8413                                                   btrfs_header_level(eb), 0);
8414                 BUG_ON(ret); /* -ENOMEM */
8415                 wc->flags[level] |= flag;
8416         }
8417
8418         /*
8419          * the block is shared by multiple trees, so it's not good to
8420          * keep the tree lock
8421          */
8422         if (path->locks[level] && level > 0) {
8423                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8424                 path->locks[level] = 0;
8425         }
8426         return 0;
8427 }
8428
8429 /*
8430  * helper to process tree block pointer.
8431  *
8432  * when wc->stage == DROP_REFERENCE, this function checks
8433  * reference count of the block pointed to. if the block
8434  * is shared and we need update back refs for the subtree
8435  * rooted at the block, this function changes wc->stage to
8436  * UPDATE_BACKREF. if the block is shared and there is no
8437  * need to update back, this function drops the reference
8438  * to the block.
8439  *
8440  * NOTE: return value 1 means we should stop walking down.
8441  */
8442 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8443                                  struct btrfs_root *root,
8444                                  struct btrfs_path *path,
8445                                  struct walk_control *wc, int *lookup_info)
8446 {
8447         u64 bytenr;
8448         u64 generation;
8449         u64 parent;
8450         u32 blocksize;
8451         struct btrfs_key key;
8452         struct extent_buffer *next;
8453         int level = wc->level;
8454         int reada = 0;
8455         int ret = 0;
8456         bool need_account = false;
8457
8458         generation = btrfs_node_ptr_generation(path->nodes[level],
8459                                                path->slots[level]);
8460         /*
8461          * if the lower level block was created before the snapshot
8462          * was created, we know there is no need to update back refs
8463          * for the subtree
8464          */
8465         if (wc->stage == UPDATE_BACKREF &&
8466             generation <= root->root_key.offset) {
8467                 *lookup_info = 1;
8468                 return 1;
8469         }
8470
8471         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8472         blocksize = root->nodesize;
8473
8474         next = btrfs_find_tree_block(root->fs_info, bytenr);
8475         if (!next) {
8476                 next = btrfs_find_create_tree_block(root, bytenr);
8477                 if (!next)
8478                         return -ENOMEM;
8479                 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8480                                                level - 1);
8481                 reada = 1;
8482         }
8483         btrfs_tree_lock(next);
8484         btrfs_set_lock_blocking(next);
8485
8486         ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
8487                                        &wc->refs[level - 1],
8488                                        &wc->flags[level - 1]);
8489         if (ret < 0)
8490                 goto out_unlock;
8491
8492         if (unlikely(wc->refs[level - 1] == 0)) {
8493                 btrfs_err(root->fs_info, "Missing references.");
8494                 ret = -EIO;
8495                 goto out_unlock;
8496         }
8497         *lookup_info = 0;
8498
8499         if (wc->stage == DROP_REFERENCE) {
8500                 if (wc->refs[level - 1] > 1) {
8501                         need_account = true;
8502                         if (level == 1 &&
8503                             (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8504                                 goto skip;
8505
8506                         if (!wc->update_ref ||
8507                             generation <= root->root_key.offset)
8508                                 goto skip;
8509
8510                         btrfs_node_key_to_cpu(path->nodes[level], &key,
8511                                               path->slots[level]);
8512                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8513                         if (ret < 0)
8514                                 goto skip;
8515
8516                         wc->stage = UPDATE_BACKREF;
8517                         wc->shared_level = level - 1;
8518                 }
8519         } else {
8520                 if (level == 1 &&
8521                     (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8522                         goto skip;
8523         }
8524
8525         if (!btrfs_buffer_uptodate(next, generation, 0)) {
8526                 btrfs_tree_unlock(next);
8527                 free_extent_buffer(next);
8528                 next = NULL;
8529                 *lookup_info = 1;
8530         }
8531
8532         if (!next) {
8533                 if (reada && level == 1)
8534                         reada_walk_down(trans, root, wc, path);
8535                 next = read_tree_block(root, bytenr, generation);
8536                 if (IS_ERR(next)) {
8537                         return PTR_ERR(next);
8538                 } else if (!extent_buffer_uptodate(next)) {
8539                         free_extent_buffer(next);
8540                         return -EIO;
8541                 }
8542                 btrfs_tree_lock(next);
8543                 btrfs_set_lock_blocking(next);
8544         }
8545
8546         level--;
8547         ASSERT(level == btrfs_header_level(next));
8548         if (level != btrfs_header_level(next)) {
8549                 btrfs_err(root->fs_info, "mismatched level");
8550                 ret = -EIO;
8551                 goto out_unlock;
8552         }
8553         path->nodes[level] = next;
8554         path->slots[level] = 0;
8555         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8556         wc->level = level;
8557         if (wc->level == 1)
8558                 wc->reada_slot = 0;
8559         return 0;
8560 skip:
8561         wc->refs[level - 1] = 0;
8562         wc->flags[level - 1] = 0;
8563         if (wc->stage == DROP_REFERENCE) {
8564                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8565                         parent = path->nodes[level]->start;
8566                 } else {
8567                         ASSERT(root->root_key.objectid ==
8568                                btrfs_header_owner(path->nodes[level]));
8569                         if (root->root_key.objectid !=
8570                             btrfs_header_owner(path->nodes[level])) {
8571                                 btrfs_err(root->fs_info,
8572                                                 "mismatched block owner");
8573                                 ret = -EIO;
8574                                 goto out_unlock;
8575                         }
8576                         parent = 0;
8577                 }
8578
8579                 if (need_account) {
8580                         ret = account_shared_subtree(trans, root, next,
8581                                                      generation, level - 1);
8582                         if (ret) {
8583                                 btrfs_err_rl(root->fs_info,
8584                                         "Error "
8585                                         "%d accounting shared subtree. Quota "
8586                                         "is out of sync, rescan required.",
8587                                         ret);
8588                         }
8589                 }
8590                 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
8591                                 root->root_key.objectid, level - 1, 0);
8592                 if (ret)
8593                         goto out_unlock;
8594         }
8595
8596         *lookup_info = 1;
8597         ret = 1;
8598
8599 out_unlock:
8600         btrfs_tree_unlock(next);
8601         free_extent_buffer(next);
8602
8603         return ret;
8604 }
8605
8606 /*
8607  * helper to process tree block while walking up the tree.
8608  *
8609  * when wc->stage == DROP_REFERENCE, this function drops
8610  * reference count on the block.
8611  *
8612  * when wc->stage == UPDATE_BACKREF, this function changes
8613  * wc->stage back to DROP_REFERENCE if we changed wc->stage
8614  * to UPDATE_BACKREF previously while processing the block.
8615  *
8616  * NOTE: return value 1 means we should stop walking up.
8617  */
8618 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
8619                                  struct btrfs_root *root,
8620                                  struct btrfs_path *path,
8621                                  struct walk_control *wc)
8622 {
8623         int ret;
8624         int level = wc->level;
8625         struct extent_buffer *eb = path->nodes[level];
8626         u64 parent = 0;
8627
8628         if (wc->stage == UPDATE_BACKREF) {
8629                 BUG_ON(wc->shared_level < level);
8630                 if (level < wc->shared_level)
8631                         goto out;
8632
8633                 ret = find_next_key(path, level + 1, &wc->update_progress);
8634                 if (ret > 0)
8635                         wc->update_ref = 0;
8636
8637                 wc->stage = DROP_REFERENCE;
8638                 wc->shared_level = -1;
8639                 path->slots[level] = 0;
8640
8641                 /*
8642                  * check reference count again if the block isn't locked.
8643                  * we should start walking down the tree again if reference
8644                  * count is one.
8645                  */
8646                 if (!path->locks[level]) {
8647                         BUG_ON(level == 0);
8648                         btrfs_tree_lock(eb);
8649                         btrfs_set_lock_blocking(eb);
8650                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8651
8652                         ret = btrfs_lookup_extent_info(trans, root,
8653                                                        eb->start, level, 1,
8654                                                        &wc->refs[level],
8655                                                        &wc->flags[level]);
8656                         if (ret < 0) {
8657                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8658                                 path->locks[level] = 0;
8659                                 return ret;
8660                         }
8661                         BUG_ON(wc->refs[level] == 0);
8662                         if (wc->refs[level] == 1) {
8663                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8664                                 path->locks[level] = 0;
8665                                 return 1;
8666                         }
8667                 }
8668         }
8669
8670         /* wc->stage == DROP_REFERENCE */
8671         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
8672
8673         if (wc->refs[level] == 1) {
8674                 if (level == 0) {
8675                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8676                                 ret = btrfs_dec_ref(trans, root, eb, 1);
8677                         else
8678                                 ret = btrfs_dec_ref(trans, root, eb, 0);
8679                         BUG_ON(ret); /* -ENOMEM */
8680                         ret = account_leaf_items(trans, root, eb);
8681                         if (ret) {
8682                                 btrfs_err_rl(root->fs_info,
8683                                         "error "
8684                                         "%d accounting leaf items. Quota "
8685                                         "is out of sync, rescan required.",
8686                                         ret);
8687                         }
8688                 }
8689                 /* make block locked assertion in clean_tree_block happy */
8690                 if (!path->locks[level] &&
8691                     btrfs_header_generation(eb) == trans->transid) {
8692                         btrfs_tree_lock(eb);
8693                         btrfs_set_lock_blocking(eb);
8694                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8695                 }
8696                 clean_tree_block(trans, root->fs_info, eb);
8697         }
8698
8699         if (eb == root->node) {
8700                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8701                         parent = eb->start;
8702                 else
8703                         BUG_ON(root->root_key.objectid !=
8704                                btrfs_header_owner(eb));
8705         } else {
8706                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8707                         parent = path->nodes[level + 1]->start;
8708                 else
8709                         BUG_ON(root->root_key.objectid !=
8710                                btrfs_header_owner(path->nodes[level + 1]));
8711         }
8712
8713         btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
8714 out:
8715         wc->refs[level] = 0;
8716         wc->flags[level] = 0;
8717         return 0;
8718 }
8719
8720 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8721                                    struct btrfs_root *root,
8722                                    struct btrfs_path *path,
8723                                    struct walk_control *wc)
8724 {
8725         int level = wc->level;
8726         int lookup_info = 1;
8727         int ret;
8728
8729         while (level >= 0) {
8730                 ret = walk_down_proc(trans, root, path, wc, lookup_info);
8731                 if (ret > 0)
8732                         break;
8733
8734                 if (level == 0)
8735                         break;
8736
8737                 if (path->slots[level] >=
8738                     btrfs_header_nritems(path->nodes[level]))
8739                         break;
8740
8741                 ret = do_walk_down(trans, root, path, wc, &lookup_info);
8742                 if (ret > 0) {
8743                         path->slots[level]++;
8744                         continue;
8745                 } else if (ret < 0)
8746                         return ret;
8747                 level = wc->level;
8748         }
8749         return 0;
8750 }
8751
8752 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
8753                                  struct btrfs_root *root,
8754                                  struct btrfs_path *path,
8755                                  struct walk_control *wc, int max_level)
8756 {
8757         int level = wc->level;
8758         int ret;
8759
8760         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8761         while (level < max_level && path->nodes[level]) {
8762                 wc->level = level;
8763                 if (path->slots[level] + 1 <
8764                     btrfs_header_nritems(path->nodes[level])) {
8765                         path->slots[level]++;
8766                         return 0;
8767                 } else {
8768                         ret = walk_up_proc(trans, root, path, wc);
8769                         if (ret > 0)
8770                                 return 0;
8771
8772                         if (path->locks[level]) {
8773                                 btrfs_tree_unlock_rw(path->nodes[level],
8774                                                      path->locks[level]);
8775                                 path->locks[level] = 0;
8776                         }
8777                         free_extent_buffer(path->nodes[level]);
8778                         path->nodes[level] = NULL;
8779                         level++;
8780                 }
8781         }
8782         return 1;
8783 }
8784
8785 /*
8786  * drop a subvolume tree.
8787  *
8788  * this function traverses the tree freeing any blocks that only
8789  * referenced by the tree.
8790  *
8791  * when a shared tree block is found. this function decreases its
8792  * reference count by one. if update_ref is true, this function
8793  * also make sure backrefs for the shared block and all lower level
8794  * blocks are properly updated.
8795  *
8796  * If called with for_reloc == 0, may exit early with -EAGAIN
8797  */
8798 int btrfs_drop_snapshot(struct btrfs_root *root,
8799                          struct btrfs_block_rsv *block_rsv, int update_ref,
8800                          int for_reloc)
8801 {
8802         struct btrfs_path *path;
8803         struct btrfs_trans_handle *trans;
8804         struct btrfs_root *tree_root = root->fs_info->tree_root;
8805         struct btrfs_root_item *root_item = &root->root_item;
8806         struct walk_control *wc;
8807         struct btrfs_key key;
8808         int err = 0;
8809         int ret;
8810         int level;
8811         bool root_dropped = false;
8812
8813         btrfs_debug(root->fs_info, "Drop subvolume %llu", root->objectid);
8814
8815         path = btrfs_alloc_path();
8816         if (!path) {
8817                 err = -ENOMEM;
8818                 goto out;
8819         }
8820
8821         wc = kzalloc(sizeof(*wc), GFP_NOFS);
8822         if (!wc) {
8823                 btrfs_free_path(path);
8824                 err = -ENOMEM;
8825                 goto out;
8826         }
8827
8828         trans = btrfs_start_transaction(tree_root, 0);
8829         if (IS_ERR(trans)) {
8830                 err = PTR_ERR(trans);
8831                 goto out_free;
8832         }
8833
8834         if (block_rsv)
8835                 trans->block_rsv = block_rsv;
8836
8837         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
8838                 level = btrfs_header_level(root->node);
8839                 path->nodes[level] = btrfs_lock_root_node(root);
8840                 btrfs_set_lock_blocking(path->nodes[level]);
8841                 path->slots[level] = 0;
8842                 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8843                 memset(&wc->update_progress, 0,
8844                        sizeof(wc->update_progress));
8845         } else {
8846                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
8847                 memcpy(&wc->update_progress, &key,
8848                        sizeof(wc->update_progress));
8849
8850                 level = root_item->drop_level;
8851                 BUG_ON(level == 0);
8852                 path->lowest_level = level;
8853                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8854                 path->lowest_level = 0;
8855                 if (ret < 0) {
8856                         err = ret;
8857                         goto out_end_trans;
8858                 }
8859                 WARN_ON(ret > 0);
8860
8861                 /*
8862                  * unlock our path, this is safe because only this
8863                  * function is allowed to delete this snapshot
8864                  */
8865                 btrfs_unlock_up_safe(path, 0);
8866
8867                 level = btrfs_header_level(root->node);
8868                 while (1) {
8869                         btrfs_tree_lock(path->nodes[level]);
8870                         btrfs_set_lock_blocking(path->nodes[level]);
8871                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8872
8873                         ret = btrfs_lookup_extent_info(trans, root,
8874                                                 path->nodes[level]->start,
8875                                                 level, 1, &wc->refs[level],
8876                                                 &wc->flags[level]);
8877                         if (ret < 0) {
8878                                 err = ret;
8879                                 goto out_end_trans;
8880                         }
8881                         BUG_ON(wc->refs[level] == 0);
8882
8883                         if (level == root_item->drop_level)
8884                                 break;
8885
8886                         btrfs_tree_unlock(path->nodes[level]);
8887                         path->locks[level] = 0;
8888                         WARN_ON(wc->refs[level] != 1);
8889                         level--;
8890                 }
8891         }
8892
8893         wc->level = level;
8894         wc->shared_level = -1;
8895         wc->stage = DROP_REFERENCE;
8896         wc->update_ref = update_ref;
8897         wc->keep_locks = 0;
8898         wc->for_reloc = for_reloc;
8899         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
8900
8901         while (1) {
8902
8903                 ret = walk_down_tree(trans, root, path, wc);
8904                 if (ret < 0) {
8905                         err = ret;
8906                         break;
8907                 }
8908
8909                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
8910                 if (ret < 0) {
8911                         err = ret;
8912                         break;
8913                 }
8914
8915                 if (ret > 0) {
8916                         BUG_ON(wc->stage != DROP_REFERENCE);
8917                         break;
8918                 }
8919
8920                 if (wc->stage == DROP_REFERENCE) {
8921                         level = wc->level;
8922                         btrfs_node_key(path->nodes[level],
8923                                        &root_item->drop_progress,
8924                                        path->slots[level]);
8925                         root_item->drop_level = level;
8926                 }
8927
8928                 BUG_ON(wc->level == 0);
8929                 if (btrfs_should_end_transaction(trans, tree_root) ||
8930                     (!for_reloc && btrfs_need_cleaner_sleep(root))) {
8931                         ret = btrfs_update_root(trans, tree_root,
8932                                                 &root->root_key,
8933                                                 root_item);
8934                         if (ret) {
8935                                 btrfs_abort_transaction(trans, tree_root, ret);
8936                                 err = ret;
8937                                 goto out_end_trans;
8938                         }
8939
8940                         btrfs_end_transaction_throttle(trans, tree_root);
8941                         if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
8942                                 pr_debug("BTRFS: drop snapshot early exit\n");
8943                                 err = -EAGAIN;
8944                                 goto out_free;
8945                         }
8946
8947                         trans = btrfs_start_transaction(tree_root, 0);
8948                         if (IS_ERR(trans)) {
8949                                 err = PTR_ERR(trans);
8950                                 goto out_free;
8951                         }
8952                         if (block_rsv)
8953                                 trans->block_rsv = block_rsv;
8954                 }
8955         }
8956         btrfs_release_path(path);
8957         if (err)
8958                 goto out_end_trans;
8959
8960         ret = btrfs_del_root(trans, tree_root, &root->root_key);
8961         if (ret) {
8962                 btrfs_abort_transaction(trans, tree_root, ret);
8963                 goto out_end_trans;
8964         }
8965
8966         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
8967                 ret = btrfs_find_root(tree_root, &root->root_key, path,
8968                                       NULL, NULL);
8969                 if (ret < 0) {
8970                         btrfs_abort_transaction(trans, tree_root, ret);
8971                         err = ret;
8972                         goto out_end_trans;
8973                 } else if (ret > 0) {
8974                         /* if we fail to delete the orphan item this time
8975                          * around, it'll get picked up the next time.
8976                          *
8977                          * The most common failure here is just -ENOENT.
8978                          */
8979                         btrfs_del_orphan_item(trans, tree_root,
8980                                               root->root_key.objectid);
8981                 }
8982         }
8983
8984         if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
8985                 btrfs_add_dropped_root(trans, root);
8986         } else {
8987                 free_extent_buffer(root->node);
8988                 free_extent_buffer(root->commit_root);
8989                 btrfs_put_fs_root(root);
8990         }
8991         root_dropped = true;
8992 out_end_trans:
8993         btrfs_end_transaction_throttle(trans, tree_root);
8994 out_free:
8995         kfree(wc);
8996         btrfs_free_path(path);
8997 out:
8998         /*
8999          * So if we need to stop dropping the snapshot for whatever reason we
9000          * need to make sure to add it back to the dead root list so that we
9001          * keep trying to do the work later.  This also cleans up roots if we
9002          * don't have it in the radix (like when we recover after a power fail
9003          * or unmount) so we don't leak memory.
9004          */
9005         if (!for_reloc && root_dropped == false)
9006                 btrfs_add_dead_root(root);
9007         if (err && err != -EAGAIN)
9008                 btrfs_std_error(root->fs_info, err, NULL);
9009         return err;
9010 }
9011
9012 /*
9013  * drop subtree rooted at tree block 'node'.
9014  *
9015  * NOTE: this function will unlock and release tree block 'node'
9016  * only used by relocation code
9017  */
9018 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9019                         struct btrfs_root *root,
9020                         struct extent_buffer *node,
9021                         struct extent_buffer *parent)
9022 {
9023         struct btrfs_path *path;
9024         struct walk_control *wc;
9025         int level;
9026         int parent_level;
9027         int ret = 0;
9028         int wret;
9029
9030         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9031
9032         path = btrfs_alloc_path();
9033         if (!path)
9034                 return -ENOMEM;
9035
9036         wc = kzalloc(sizeof(*wc), GFP_NOFS);
9037         if (!wc) {
9038                 btrfs_free_path(path);
9039                 return -ENOMEM;
9040         }
9041
9042         btrfs_assert_tree_locked(parent);
9043         parent_level = btrfs_header_level(parent);
9044         extent_buffer_get(parent);
9045         path->nodes[parent_level] = parent;
9046         path->slots[parent_level] = btrfs_header_nritems(parent);
9047
9048         btrfs_assert_tree_locked(node);
9049         level = btrfs_header_level(node);
9050         path->nodes[level] = node;
9051         path->slots[level] = 0;
9052         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9053
9054         wc->refs[parent_level] = 1;
9055         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9056         wc->level = level;
9057         wc->shared_level = -1;
9058         wc->stage = DROP_REFERENCE;
9059         wc->update_ref = 0;
9060         wc->keep_locks = 1;
9061         wc->for_reloc = 1;
9062         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
9063
9064         while (1) {
9065                 wret = walk_down_tree(trans, root, path, wc);
9066                 if (wret < 0) {
9067                         ret = wret;
9068                         break;
9069                 }
9070
9071                 wret = walk_up_tree(trans, root, path, wc, parent_level);
9072                 if (wret < 0)
9073                         ret = wret;
9074                 if (wret != 0)
9075                         break;
9076         }
9077
9078         kfree(wc);
9079         btrfs_free_path(path);
9080         return ret;
9081 }
9082
9083 static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
9084 {
9085         u64 num_devices;
9086         u64 stripped;
9087
9088         /*
9089          * if restripe for this chunk_type is on pick target profile and
9090          * return, otherwise do the usual balance
9091          */
9092         stripped = get_restripe_target(root->fs_info, flags);
9093         if (stripped)
9094                 return extended_to_chunk(stripped);
9095
9096         num_devices = root->fs_info->fs_devices->rw_devices;
9097
9098         stripped = BTRFS_BLOCK_GROUP_RAID0 |
9099                 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
9100                 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9101
9102         if (num_devices == 1) {
9103                 stripped |= BTRFS_BLOCK_GROUP_DUP;
9104                 stripped = flags & ~stripped;
9105
9106                 /* turn raid0 into single device chunks */
9107                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9108                         return stripped;
9109
9110                 /* turn mirroring into duplication */
9111                 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9112                              BTRFS_BLOCK_GROUP_RAID10))
9113                         return stripped | BTRFS_BLOCK_GROUP_DUP;
9114         } else {
9115                 /* they already had raid on here, just return */
9116                 if (flags & stripped)
9117                         return flags;
9118
9119                 stripped |= BTRFS_BLOCK_GROUP_DUP;
9120                 stripped = flags & ~stripped;
9121
9122                 /* switch duplicated blocks with raid1 */
9123                 if (flags & BTRFS_BLOCK_GROUP_DUP)
9124                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
9125
9126                 /* this is drive concat, leave it alone */
9127         }
9128
9129         return flags;
9130 }
9131
9132 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9133 {
9134         struct btrfs_space_info *sinfo = cache->space_info;
9135         u64 num_bytes;
9136         u64 min_allocable_bytes;
9137         int ret = -ENOSPC;
9138
9139         /*
9140          * We need some metadata space and system metadata space for
9141          * allocating chunks in some corner cases until we force to set
9142          * it to be readonly.
9143          */
9144         if ((sinfo->flags &
9145              (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9146             !force)
9147                 min_allocable_bytes = 1 * 1024 * 1024;
9148         else
9149                 min_allocable_bytes = 0;
9150
9151         spin_lock(&sinfo->lock);
9152         spin_lock(&cache->lock);
9153
9154         if (cache->ro) {
9155                 cache->ro++;
9156                 ret = 0;
9157                 goto out;
9158         }
9159
9160         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9161                     cache->bytes_super - btrfs_block_group_used(&cache->item);
9162
9163         if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
9164             sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
9165             min_allocable_bytes <= sinfo->total_bytes) {
9166                 sinfo->bytes_readonly += num_bytes;
9167                 cache->ro++;
9168                 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9169                 ret = 0;
9170         }
9171 out:
9172         spin_unlock(&cache->lock);
9173         spin_unlock(&sinfo->lock);
9174         return ret;
9175 }
9176
9177 int btrfs_inc_block_group_ro(struct btrfs_root *root,
9178                              struct btrfs_block_group_cache *cache)
9179
9180 {
9181         struct btrfs_trans_handle *trans;
9182         u64 alloc_flags;
9183         int ret;
9184
9185 again:
9186         trans = btrfs_join_transaction(root);
9187         if (IS_ERR(trans))
9188                 return PTR_ERR(trans);
9189
9190         /*
9191          * we're not allowed to set block groups readonly after the dirty
9192          * block groups cache has started writing.  If it already started,
9193          * back off and let this transaction commit
9194          */
9195         mutex_lock(&root->fs_info->ro_block_group_mutex);
9196         if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
9197                 u64 transid = trans->transid;
9198
9199                 mutex_unlock(&root->fs_info->ro_block_group_mutex);
9200                 btrfs_end_transaction(trans, root);
9201
9202                 ret = btrfs_wait_for_commit(root, transid);
9203                 if (ret)
9204                         return ret;
9205                 goto again;
9206         }
9207
9208         /*
9209          * if we are changing raid levels, try to allocate a corresponding
9210          * block group with the new raid level.
9211          */
9212         alloc_flags = update_block_group_flags(root, cache->flags);
9213         if (alloc_flags != cache->flags) {
9214                 ret = do_chunk_alloc(trans, root, alloc_flags,
9215                                      CHUNK_ALLOC_FORCE);
9216                 /*
9217                  * ENOSPC is allowed here, we may have enough space
9218                  * already allocated at the new raid level to
9219                  * carry on
9220                  */
9221                 if (ret == -ENOSPC)
9222                         ret = 0;
9223                 if (ret < 0)
9224                         goto out;
9225         }
9226
9227         ret = inc_block_group_ro(cache, 0);
9228         if (!ret)
9229                 goto out;
9230         alloc_flags = get_alloc_profile(root, cache->space_info->flags);
9231         ret = do_chunk_alloc(trans, root, alloc_flags,
9232                              CHUNK_ALLOC_FORCE);
9233         if (ret < 0)
9234                 goto out;
9235         ret = inc_block_group_ro(cache, 0);
9236 out:
9237         if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9238                 alloc_flags = update_block_group_flags(root, cache->flags);
9239                 lock_chunks(root->fs_info->chunk_root);
9240                 check_system_chunk(trans, root, alloc_flags);
9241                 unlock_chunks(root->fs_info->chunk_root);
9242         }
9243         mutex_unlock(&root->fs_info->ro_block_group_mutex);
9244
9245         btrfs_end_transaction(trans, root);
9246         return ret;
9247 }
9248
9249 int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
9250                             struct btrfs_root *root, u64 type)
9251 {
9252         u64 alloc_flags = get_alloc_profile(root, type);
9253         return do_chunk_alloc(trans, root, alloc_flags,
9254                               CHUNK_ALLOC_FORCE);
9255 }
9256
9257 /*
9258  * helper to account the unused space of all the readonly block group in the
9259  * space_info. takes mirrors into account.
9260  */
9261 u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
9262 {
9263         struct btrfs_block_group_cache *block_group;
9264         u64 free_bytes = 0;
9265         int factor;
9266
9267         /* It's df, we don't care if it's racey */
9268         if (list_empty(&sinfo->ro_bgs))
9269                 return 0;
9270
9271         spin_lock(&sinfo->lock);
9272         list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
9273                 spin_lock(&block_group->lock);
9274
9275                 if (!block_group->ro) {
9276                         spin_unlock(&block_group->lock);
9277                         continue;
9278                 }
9279
9280                 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
9281                                           BTRFS_BLOCK_GROUP_RAID10 |
9282                                           BTRFS_BLOCK_GROUP_DUP))
9283                         factor = 2;
9284                 else
9285                         factor = 1;
9286
9287                 free_bytes += (block_group->key.offset -
9288                                btrfs_block_group_used(&block_group->item)) *
9289                                factor;
9290
9291                 spin_unlock(&block_group->lock);
9292         }
9293         spin_unlock(&sinfo->lock);
9294
9295         return free_bytes;
9296 }
9297
9298 void btrfs_dec_block_group_ro(struct btrfs_root *root,
9299                               struct btrfs_block_group_cache *cache)
9300 {
9301         struct btrfs_space_info *sinfo = cache->space_info;
9302         u64 num_bytes;
9303
9304         BUG_ON(!cache->ro);
9305
9306         spin_lock(&sinfo->lock);
9307         spin_lock(&cache->lock);
9308         if (!--cache->ro) {
9309                 num_bytes = cache->key.offset - cache->reserved -
9310                             cache->pinned - cache->bytes_super -
9311                             btrfs_block_group_used(&cache->item);
9312                 sinfo->bytes_readonly -= num_bytes;
9313                 list_del_init(&cache->ro_list);
9314         }
9315         spin_unlock(&cache->lock);
9316         spin_unlock(&sinfo->lock);
9317 }
9318
9319 /*
9320  * checks to see if its even possible to relocate this block group.
9321  *
9322  * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9323  * ok to go ahead and try.
9324  */
9325 int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
9326 {
9327         struct btrfs_block_group_cache *block_group;
9328         struct btrfs_space_info *space_info;
9329         struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
9330         struct btrfs_device *device;
9331         struct btrfs_trans_handle *trans;
9332         u64 min_free;
9333         u64 dev_min = 1;
9334         u64 dev_nr = 0;
9335         u64 target;
9336         int index;
9337         int full = 0;
9338         int ret = 0;
9339
9340         block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
9341
9342         /* odd, couldn't find the block group, leave it alone */
9343         if (!block_group)
9344                 return -1;
9345
9346         min_free = btrfs_block_group_used(&block_group->item);
9347
9348         /* no bytes used, we're good */
9349         if (!min_free)
9350                 goto out;
9351
9352         space_info = block_group->space_info;
9353         spin_lock(&space_info->lock);
9354
9355         full = space_info->full;
9356
9357         /*
9358          * if this is the last block group we have in this space, we can't
9359          * relocate it unless we're able to allocate a new chunk below.
9360          *
9361          * Otherwise, we need to make sure we have room in the space to handle
9362          * all of the extents from this block group.  If we can, we're good
9363          */
9364         if ((space_info->total_bytes != block_group->key.offset) &&
9365             (space_info->bytes_used + space_info->bytes_reserved +
9366              space_info->bytes_pinned + space_info->bytes_readonly +
9367              min_free < space_info->total_bytes)) {
9368                 spin_unlock(&space_info->lock);
9369                 goto out;
9370         }
9371         spin_unlock(&space_info->lock);
9372
9373         /*
9374          * ok we don't have enough space, but maybe we have free space on our
9375          * devices to allocate new chunks for relocation, so loop through our
9376          * alloc devices and guess if we have enough space.  if this block
9377          * group is going to be restriped, run checks against the target
9378          * profile instead of the current one.
9379          */
9380         ret = -1;
9381
9382         /*
9383          * index:
9384          *      0: raid10
9385          *      1: raid1
9386          *      2: dup
9387          *      3: raid0
9388          *      4: single
9389          */
9390         target = get_restripe_target(root->fs_info, block_group->flags);
9391         if (target) {
9392                 index = __get_raid_index(extended_to_chunk(target));
9393         } else {
9394                 /*
9395                  * this is just a balance, so if we were marked as full
9396                  * we know there is no space for a new chunk
9397                  */
9398                 if (full)
9399                         goto out;
9400
9401                 index = get_block_group_index(block_group);
9402         }
9403
9404         if (index == BTRFS_RAID_RAID10) {
9405                 dev_min = 4;
9406                 /* Divide by 2 */
9407                 min_free >>= 1;
9408         } else if (index == BTRFS_RAID_RAID1) {
9409                 dev_min = 2;
9410         } else if (index == BTRFS_RAID_DUP) {
9411                 /* Multiply by 2 */
9412                 min_free <<= 1;
9413         } else if (index == BTRFS_RAID_RAID0) {
9414                 dev_min = fs_devices->rw_devices;
9415                 min_free = div64_u64(min_free, dev_min);
9416         }
9417
9418         /* We need to do this so that we can look at pending chunks */
9419         trans = btrfs_join_transaction(root);
9420         if (IS_ERR(trans)) {
9421                 ret = PTR_ERR(trans);
9422                 goto out;
9423         }
9424
9425         mutex_lock(&root->fs_info->chunk_mutex);
9426         list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
9427                 u64 dev_offset;
9428
9429                 /*
9430                  * check to make sure we can actually find a chunk with enough
9431                  * space to fit our block group in.
9432                  */
9433                 if (device->total_bytes > device->bytes_used + min_free &&
9434                     !device->is_tgtdev_for_dev_replace) {
9435                         ret = find_free_dev_extent(trans, device, min_free,
9436                                                    &dev_offset, NULL);
9437                         if (!ret)
9438                                 dev_nr++;
9439
9440                         if (dev_nr >= dev_min)
9441                                 break;
9442
9443                         ret = -1;
9444                 }
9445         }
9446         mutex_unlock(&root->fs_info->chunk_mutex);
9447         btrfs_end_transaction(trans, root);
9448 out:
9449         btrfs_put_block_group(block_group);
9450         return ret;
9451 }
9452
9453 static int find_first_block_group(struct btrfs_root *root,
9454                 struct btrfs_path *path, struct btrfs_key *key)
9455 {
9456         int ret = 0;
9457         struct btrfs_key found_key;
9458         struct extent_buffer *leaf;
9459         int slot;
9460
9461         ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9462         if (ret < 0)
9463                 goto out;
9464
9465         while (1) {
9466                 slot = path->slots[0];
9467                 leaf = path->nodes[0];
9468                 if (slot >= btrfs_header_nritems(leaf)) {
9469                         ret = btrfs_next_leaf(root, path);
9470                         if (ret == 0)
9471                                 continue;
9472                         if (ret < 0)
9473                                 goto out;
9474                         break;
9475                 }
9476                 btrfs_item_key_to_cpu(leaf, &found_key, slot);
9477
9478                 if (found_key.objectid >= key->objectid &&
9479                     found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9480                         ret = 0;
9481                         goto out;
9482                 }
9483                 path->slots[0]++;
9484         }
9485 out:
9486         return ret;
9487 }
9488
9489 void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
9490 {
9491         struct btrfs_block_group_cache *block_group;
9492         u64 last = 0;
9493
9494         while (1) {
9495                 struct inode *inode;
9496
9497                 block_group = btrfs_lookup_first_block_group(info, last);
9498                 while (block_group) {
9499                         spin_lock(&block_group->lock);
9500                         if (block_group->iref)
9501                                 break;
9502                         spin_unlock(&block_group->lock);
9503                         block_group = next_block_group(info->tree_root,
9504                                                        block_group);
9505                 }
9506                 if (!block_group) {
9507                         if (last == 0)
9508                                 break;
9509                         last = 0;
9510                         continue;
9511                 }
9512
9513                 inode = block_group->inode;
9514                 block_group->iref = 0;
9515                 block_group->inode = NULL;
9516                 spin_unlock(&block_group->lock);
9517                 iput(inode);
9518                 last = block_group->key.objectid + block_group->key.offset;
9519                 btrfs_put_block_group(block_group);
9520         }
9521 }
9522
9523 int btrfs_free_block_groups(struct btrfs_fs_info *info)
9524 {
9525         struct btrfs_block_group_cache *block_group;
9526         struct btrfs_space_info *space_info;
9527         struct btrfs_caching_control *caching_ctl;
9528         struct rb_node *n;
9529
9530         down_write(&info->commit_root_sem);
9531         while (!list_empty(&info->caching_block_groups)) {
9532                 caching_ctl = list_entry(info->caching_block_groups.next,
9533                                          struct btrfs_caching_control, list);
9534                 list_del(&caching_ctl->list);
9535                 put_caching_control(caching_ctl);
9536         }
9537         up_write(&info->commit_root_sem);
9538
9539         spin_lock(&info->unused_bgs_lock);
9540         while (!list_empty(&info->unused_bgs)) {
9541                 block_group = list_first_entry(&info->unused_bgs,
9542                                                struct btrfs_block_group_cache,
9543                                                bg_list);
9544                 list_del_init(&block_group->bg_list);
9545                 btrfs_put_block_group(block_group);
9546         }
9547         spin_unlock(&info->unused_bgs_lock);
9548
9549         spin_lock(&info->block_group_cache_lock);
9550         while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
9551                 block_group = rb_entry(n, struct btrfs_block_group_cache,
9552                                        cache_node);
9553                 rb_erase(&block_group->cache_node,
9554                          &info->block_group_cache_tree);
9555                 RB_CLEAR_NODE(&block_group->cache_node);
9556                 spin_unlock(&info->block_group_cache_lock);
9557
9558                 down_write(&block_group->space_info->groups_sem);
9559                 list_del(&block_group->list);
9560                 up_write(&block_group->space_info->groups_sem);
9561
9562                 if (block_group->cached == BTRFS_CACHE_STARTED)
9563                         wait_block_group_cache_done(block_group);
9564
9565                 /*
9566                  * We haven't cached this block group, which means we could
9567                  * possibly have excluded extents on this block group.
9568                  */
9569                 if (block_group->cached == BTRFS_CACHE_NO ||
9570                     block_group->cached == BTRFS_CACHE_ERROR)
9571                         free_excluded_extents(info->extent_root, block_group);
9572
9573                 btrfs_remove_free_space_cache(block_group);
9574                 btrfs_put_block_group(block_group);
9575
9576                 spin_lock(&info->block_group_cache_lock);
9577         }
9578         spin_unlock(&info->block_group_cache_lock);
9579
9580         /* now that all the block groups are freed, go through and
9581          * free all the space_info structs.  This is only called during
9582          * the final stages of unmount, and so we know nobody is
9583          * using them.  We call synchronize_rcu() once before we start,
9584          * just to be on the safe side.
9585          */
9586         synchronize_rcu();
9587
9588         release_global_block_rsv(info);
9589
9590         while (!list_empty(&info->space_info)) {
9591                 int i;
9592
9593                 space_info = list_entry(info->space_info.next,
9594                                         struct btrfs_space_info,
9595                                         list);
9596                 if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
9597                         if (WARN_ON(space_info->bytes_pinned > 0 ||
9598                             space_info->bytes_reserved > 0 ||
9599                             space_info->bytes_may_use > 0)) {
9600                                 dump_space_info(space_info, 0, 0);
9601                         }
9602                 }
9603                 list_del(&space_info->list);
9604                 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
9605                         struct kobject *kobj;
9606                         kobj = space_info->block_group_kobjs[i];
9607                         space_info->block_group_kobjs[i] = NULL;
9608                         if (kobj) {
9609                                 kobject_del(kobj);
9610                                 kobject_put(kobj);
9611                         }
9612                 }
9613                 kobject_del(&space_info->kobj);
9614                 kobject_put(&space_info->kobj);
9615         }
9616         return 0;
9617 }
9618
9619 static void __link_block_group(struct btrfs_space_info *space_info,
9620                                struct btrfs_block_group_cache *cache)
9621 {
9622         int index = get_block_group_index(cache);
9623         bool first = false;
9624
9625         down_write(&space_info->groups_sem);
9626         if (list_empty(&space_info->block_groups[index]))
9627                 first = true;
9628         list_add_tail(&cache->list, &space_info->block_groups[index]);
9629         up_write(&space_info->groups_sem);
9630
9631         if (first) {
9632                 struct raid_kobject *rkobj;
9633                 int ret;
9634
9635                 rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
9636                 if (!rkobj)
9637                         goto out_err;
9638                 rkobj->raid_type = index;
9639                 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
9640                 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
9641                                   "%s", get_raid_name(index));
9642                 if (ret) {
9643                         kobject_put(&rkobj->kobj);
9644                         goto out_err;
9645                 }
9646                 space_info->block_group_kobjs[index] = &rkobj->kobj;
9647         }
9648
9649         return;
9650 out_err:
9651         pr_warn("BTRFS: failed to add kobject for block cache. ignoring.\n");
9652 }
9653
9654 static struct btrfs_block_group_cache *
9655 btrfs_create_block_group_cache(struct btrfs_root *root, u64 start, u64 size)
9656 {
9657         struct btrfs_block_group_cache *cache;
9658
9659         cache = kzalloc(sizeof(*cache), GFP_NOFS);
9660         if (!cache)
9661                 return NULL;
9662
9663         cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
9664                                         GFP_NOFS);
9665         if (!cache->free_space_ctl) {
9666                 kfree(cache);
9667                 return NULL;
9668         }
9669
9670         cache->key.objectid = start;
9671         cache->key.offset = size;
9672         cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9673
9674         cache->sectorsize = root->sectorsize;
9675         cache->fs_info = root->fs_info;
9676         cache->full_stripe_len = btrfs_full_stripe_len(root,
9677                                                &root->fs_info->mapping_tree,
9678                                                start);
9679         atomic_set(&cache->count, 1);
9680         spin_lock_init(&cache->lock);
9681         init_rwsem(&cache->data_rwsem);
9682         INIT_LIST_HEAD(&cache->list);
9683         INIT_LIST_HEAD(&cache->cluster_list);
9684         INIT_LIST_HEAD(&cache->bg_list);
9685         INIT_LIST_HEAD(&cache->ro_list);
9686         INIT_LIST_HEAD(&cache->dirty_list);
9687         INIT_LIST_HEAD(&cache->io_list);
9688         btrfs_init_free_space_ctl(cache);
9689         atomic_set(&cache->trimming, 0);
9690
9691         return cache;
9692 }
9693
9694 int btrfs_read_block_groups(struct btrfs_root *root)
9695 {
9696         struct btrfs_path *path;
9697         int ret;
9698         struct btrfs_block_group_cache *cache;
9699         struct btrfs_fs_info *info = root->fs_info;
9700         struct btrfs_space_info *space_info;
9701         struct btrfs_key key;
9702         struct btrfs_key found_key;
9703         struct extent_buffer *leaf;
9704         int need_clear = 0;
9705         u64 cache_gen;
9706         u64 feature;
9707         int mixed;
9708
9709         feature = btrfs_super_incompat_flags(info->super_copy);
9710         mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
9711
9712         root = info->extent_root;
9713         key.objectid = 0;
9714         key.offset = 0;
9715         key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9716         path = btrfs_alloc_path();
9717         if (!path)
9718                 return -ENOMEM;
9719         path->reada = 1;
9720
9721         cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
9722         if (btrfs_test_opt(root, SPACE_CACHE) &&
9723             btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
9724                 need_clear = 1;
9725         if (btrfs_test_opt(root, CLEAR_CACHE))
9726                 need_clear = 1;
9727
9728         while (1) {
9729                 ret = find_first_block_group(root, path, &key);
9730                 if (ret > 0)
9731                         break;
9732                 if (ret != 0)
9733                         goto error;
9734
9735                 leaf = path->nodes[0];
9736                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
9737
9738                 cache = btrfs_create_block_group_cache(root, found_key.objectid,
9739                                                        found_key.offset);
9740                 if (!cache) {
9741                         ret = -ENOMEM;
9742                         goto error;
9743                 }
9744
9745                 if (need_clear) {
9746                         /*
9747                          * When we mount with old space cache, we need to
9748                          * set BTRFS_DC_CLEAR and set dirty flag.
9749                          *
9750                          * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
9751                          *    truncate the old free space cache inode and
9752                          *    setup a new one.
9753                          * b) Setting 'dirty flag' makes sure that we flush
9754                          *    the new space cache info onto disk.
9755                          */
9756                         if (btrfs_test_opt(root, SPACE_CACHE))
9757                                 cache->disk_cache_state = BTRFS_DC_CLEAR;
9758                 }
9759
9760                 read_extent_buffer(leaf, &cache->item,
9761                                    btrfs_item_ptr_offset(leaf, path->slots[0]),
9762                                    sizeof(cache->item));
9763                 cache->flags = btrfs_block_group_flags(&cache->item);
9764                 if (!mixed &&
9765                     ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
9766                     (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
9767                         btrfs_err(info,
9768 "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
9769                                   cache->key.objectid);
9770                         ret = -EINVAL;
9771                         goto error;
9772                 }
9773
9774                 key.objectid = found_key.objectid + found_key.offset;
9775                 btrfs_release_path(path);
9776
9777                 /*
9778                  * We need to exclude the super stripes now so that the space
9779                  * info has super bytes accounted for, otherwise we'll think
9780                  * we have more space than we actually do.
9781                  */
9782                 ret = exclude_super_stripes(root, cache);
9783                 if (ret) {
9784                         /*
9785                          * We may have excluded something, so call this just in
9786                          * case.
9787                          */
9788                         free_excluded_extents(root, cache);
9789                         btrfs_put_block_group(cache);
9790                         goto error;
9791                 }
9792
9793                 /*
9794                  * check for two cases, either we are full, and therefore
9795                  * don't need to bother with the caching work since we won't
9796                  * find any space, or we are empty, and we can just add all
9797                  * the space in and be done with it.  This saves us _alot_ of
9798                  * time, particularly in the full case.
9799                  */
9800                 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
9801                         cache->last_byte_to_unpin = (u64)-1;
9802                         cache->cached = BTRFS_CACHE_FINISHED;
9803                         free_excluded_extents(root, cache);
9804                 } else if (btrfs_block_group_used(&cache->item) == 0) {
9805                         cache->last_byte_to_unpin = (u64)-1;
9806                         cache->cached = BTRFS_CACHE_FINISHED;
9807                         add_new_free_space(cache, root->fs_info,
9808                                            found_key.objectid,
9809                                            found_key.objectid +
9810                                            found_key.offset);
9811                         free_excluded_extents(root, cache);
9812                 }
9813
9814                 ret = btrfs_add_block_group_cache(root->fs_info, cache);
9815                 if (ret) {
9816                         btrfs_remove_free_space_cache(cache);
9817                         btrfs_put_block_group(cache);
9818                         goto error;
9819                 }
9820
9821                 ret = update_space_info(info, cache->flags, found_key.offset,
9822                                         btrfs_block_group_used(&cache->item),
9823                                         &space_info);
9824                 if (ret) {
9825                         btrfs_remove_free_space_cache(cache);
9826                         spin_lock(&info->block_group_cache_lock);
9827                         rb_erase(&cache->cache_node,
9828                                  &info->block_group_cache_tree);
9829                         RB_CLEAR_NODE(&cache->cache_node);
9830                         spin_unlock(&info->block_group_cache_lock);
9831                         btrfs_put_block_group(cache);
9832                         goto error;
9833                 }
9834
9835                 cache->space_info = space_info;
9836                 spin_lock(&cache->space_info->lock);
9837                 cache->space_info->bytes_readonly += cache->bytes_super;
9838                 spin_unlock(&cache->space_info->lock);
9839
9840                 __link_block_group(space_info, cache);
9841
9842                 set_avail_alloc_bits(root->fs_info, cache->flags);
9843                 if (btrfs_chunk_readonly(root, cache->key.objectid)) {
9844                         inc_block_group_ro(cache, 1);
9845                 } else if (btrfs_block_group_used(&cache->item) == 0) {
9846                         spin_lock(&info->unused_bgs_lock);
9847                         /* Should always be true but just in case. */
9848                         if (list_empty(&cache->bg_list)) {
9849                                 btrfs_get_block_group(cache);
9850                                 list_add_tail(&cache->bg_list,
9851                                               &info->unused_bgs);
9852                         }
9853                         spin_unlock(&info->unused_bgs_lock);
9854                 }
9855         }
9856
9857         list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
9858                 if (!(get_alloc_profile(root, space_info->flags) &
9859                       (BTRFS_BLOCK_GROUP_RAID10 |
9860                        BTRFS_BLOCK_GROUP_RAID1 |
9861                        BTRFS_BLOCK_GROUP_RAID5 |
9862                        BTRFS_BLOCK_GROUP_RAID6 |
9863                        BTRFS_BLOCK_GROUP_DUP)))
9864                         continue;
9865                 /*
9866                  * avoid allocating from un-mirrored block group if there are
9867                  * mirrored block groups.
9868                  */
9869                 list_for_each_entry(cache,
9870                                 &space_info->block_groups[BTRFS_RAID_RAID0],
9871                                 list)
9872                         inc_block_group_ro(cache, 1);
9873                 list_for_each_entry(cache,
9874                                 &space_info->block_groups[BTRFS_RAID_SINGLE],
9875                                 list)
9876                         inc_block_group_ro(cache, 1);
9877         }
9878
9879         init_global_block_rsv(info);
9880         ret = 0;
9881 error:
9882         btrfs_free_path(path);
9883         return ret;
9884 }
9885
9886 void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
9887                                        struct btrfs_root *root)
9888 {
9889         struct btrfs_block_group_cache *block_group, *tmp;
9890         struct btrfs_root *extent_root = root->fs_info->extent_root;
9891         struct btrfs_block_group_item item;
9892         struct btrfs_key key;
9893         int ret = 0;
9894         bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
9895
9896         trans->can_flush_pending_bgs = false;
9897         list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
9898                 if (ret)
9899                         goto next;
9900
9901                 spin_lock(&block_group->lock);
9902                 memcpy(&item, &block_group->item, sizeof(item));
9903                 memcpy(&key, &block_group->key, sizeof(key));
9904                 spin_unlock(&block_group->lock);
9905
9906                 ret = btrfs_insert_item(trans, extent_root, &key, &item,
9907                                         sizeof(item));
9908                 if (ret)
9909                         btrfs_abort_transaction(trans, extent_root, ret);
9910                 ret = btrfs_finish_chunk_alloc(trans, extent_root,
9911                                                key.objectid, key.offset);
9912                 if (ret)
9913                         btrfs_abort_transaction(trans, extent_root, ret);
9914 next:
9915                 list_del_init(&block_group->bg_list);
9916         }
9917         trans->can_flush_pending_bgs = can_flush_pending_bgs;
9918 }
9919
9920 int btrfs_make_block_group(struct btrfs_trans_handle *trans,
9921                            struct btrfs_root *root, u64 bytes_used,
9922                            u64 type, u64 chunk_objectid, u64 chunk_offset,
9923                            u64 size)
9924 {
9925         int ret;
9926         struct btrfs_root *extent_root;
9927         struct btrfs_block_group_cache *cache;
9928
9929         extent_root = root->fs_info->extent_root;
9930
9931         btrfs_set_log_full_commit(root->fs_info, trans);
9932
9933         cache = btrfs_create_block_group_cache(root, chunk_offset, size);
9934         if (!cache)
9935                 return -ENOMEM;
9936
9937         btrfs_set_block_group_used(&cache->item, bytes_used);
9938         btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
9939         btrfs_set_block_group_flags(&cache->item, type);
9940
9941         cache->flags = type;
9942         cache->last_byte_to_unpin = (u64)-1;
9943         cache->cached = BTRFS_CACHE_FINISHED;
9944         ret = exclude_super_stripes(root, cache);
9945         if (ret) {
9946                 /*
9947                  * We may have excluded something, so call this just in
9948                  * case.
9949                  */
9950                 free_excluded_extents(root, cache);
9951                 btrfs_put_block_group(cache);
9952                 return ret;
9953         }
9954
9955         add_new_free_space(cache, root->fs_info, chunk_offset,
9956                            chunk_offset + size);
9957
9958         free_excluded_extents(root, cache);
9959
9960 #ifdef CONFIG_BTRFS_DEBUG
9961         if (btrfs_should_fragment_free_space(root, cache)) {
9962                 u64 new_bytes_used = size - bytes_used;
9963
9964                 bytes_used += new_bytes_used >> 1;
9965                 fragment_free_space(root, cache);
9966         }
9967 #endif
9968         /*
9969          * Call to ensure the corresponding space_info object is created and
9970          * assigned to our block group, but don't update its counters just yet.
9971          * We want our bg to be added to the rbtree with its ->space_info set.
9972          */
9973         ret = update_space_info(root->fs_info, cache->flags, 0, 0,
9974                                 &cache->space_info);
9975         if (ret) {
9976                 btrfs_remove_free_space_cache(cache);
9977                 btrfs_put_block_group(cache);
9978                 return ret;
9979         }
9980
9981         ret = btrfs_add_block_group_cache(root->fs_info, cache);
9982         if (ret) {
9983                 btrfs_remove_free_space_cache(cache);
9984                 btrfs_put_block_group(cache);
9985                 return ret;
9986         }
9987
9988         /*
9989          * Now that our block group has its ->space_info set and is inserted in
9990          * the rbtree, update the space info's counters.
9991          */
9992         ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
9993                                 &cache->space_info);
9994         if (ret) {
9995                 btrfs_remove_free_space_cache(cache);
9996                 spin_lock(&root->fs_info->block_group_cache_lock);
9997                 rb_erase(&cache->cache_node,
9998                          &root->fs_info->block_group_cache_tree);
9999                 RB_CLEAR_NODE(&cache->cache_node);
10000                 spin_unlock(&root->fs_info->block_group_cache_lock);
10001                 btrfs_put_block_group(cache);
10002                 return ret;
10003         }
10004         update_global_block_rsv(root->fs_info);
10005
10006         spin_lock(&cache->space_info->lock);
10007         cache->space_info->bytes_readonly += cache->bytes_super;
10008         spin_unlock(&cache->space_info->lock);
10009
10010         __link_block_group(cache->space_info, cache);
10011
10012         list_add_tail(&cache->bg_list, &trans->new_bgs);
10013
10014         set_avail_alloc_bits(extent_root->fs_info, type);
10015
10016         return 0;
10017 }
10018
10019 static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
10020 {
10021         u64 extra_flags = chunk_to_extended(flags) &
10022                                 BTRFS_EXTENDED_PROFILE_MASK;
10023
10024         write_seqlock(&fs_info->profiles_lock);
10025         if (flags & BTRFS_BLOCK_GROUP_DATA)
10026                 fs_info->avail_data_alloc_bits &= ~extra_flags;
10027         if (flags & BTRFS_BLOCK_GROUP_METADATA)
10028                 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
10029         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
10030                 fs_info->avail_system_alloc_bits &= ~extra_flags;
10031         write_sequnlock(&fs_info->profiles_lock);
10032 }
10033
10034 int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
10035                              struct btrfs_root *root, u64 group_start,
10036                              struct extent_map *em)
10037 {
10038         struct btrfs_path *path;
10039         struct btrfs_block_group_cache *block_group;
10040         struct btrfs_free_cluster *cluster;
10041         struct btrfs_root *tree_root = root->fs_info->tree_root;
10042         struct btrfs_key key;
10043         struct inode *inode;
10044         struct kobject *kobj = NULL;
10045         int ret;
10046         int index;
10047         int factor;
10048         struct btrfs_caching_control *caching_ctl = NULL;
10049         bool remove_em;
10050
10051         root = root->fs_info->extent_root;
10052
10053         block_group = btrfs_lookup_block_group(root->fs_info, group_start);
10054         BUG_ON(!block_group);
10055         BUG_ON(!block_group->ro);
10056
10057         /*
10058          * Free the reserved super bytes from this block group before
10059          * remove it.
10060          */
10061         free_excluded_extents(root, block_group);
10062
10063         memcpy(&key, &block_group->key, sizeof(key));
10064         index = get_block_group_index(block_group);
10065         if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
10066                                   BTRFS_BLOCK_GROUP_RAID1 |
10067                                   BTRFS_BLOCK_GROUP_RAID10))
10068                 factor = 2;
10069         else
10070                 factor = 1;
10071
10072         /* make sure this block group isn't part of an allocation cluster */
10073         cluster = &root->fs_info->data_alloc_cluster;
10074         spin_lock(&cluster->refill_lock);
10075         btrfs_return_cluster_to_free_space(block_group, cluster);
10076         spin_unlock(&cluster->refill_lock);
10077
10078         /*
10079          * make sure this block group isn't part of a metadata
10080          * allocation cluster
10081          */
10082         cluster = &root->fs_info->meta_alloc_cluster;
10083         spin_lock(&cluster->refill_lock);
10084         btrfs_return_cluster_to_free_space(block_group, cluster);
10085         spin_unlock(&cluster->refill_lock);
10086
10087         path = btrfs_alloc_path();
10088         if (!path) {
10089                 ret = -ENOMEM;
10090                 goto out;
10091         }
10092
10093         /*
10094          * get the inode first so any iput calls done for the io_list
10095          * aren't the final iput (no unlinks allowed now)
10096          */
10097         inode = lookup_free_space_inode(tree_root, block_group, path);
10098
10099         mutex_lock(&trans->transaction->cache_write_mutex);
10100         /*
10101          * make sure our free spache cache IO is done before remove the
10102          * free space inode
10103          */
10104         spin_lock(&trans->transaction->dirty_bgs_lock);
10105         if (!list_empty(&block_group->io_list)) {
10106                 list_del_init(&block_group->io_list);
10107
10108                 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10109
10110                 spin_unlock(&trans->transaction->dirty_bgs_lock);
10111                 btrfs_wait_cache_io(root, trans, block_group,
10112                                     &block_group->io_ctl, path,
10113                                     block_group->key.objectid);
10114                 btrfs_put_block_group(block_group);
10115                 spin_lock(&trans->transaction->dirty_bgs_lock);
10116         }
10117
10118         if (!list_empty(&block_group->dirty_list)) {
10119                 list_del_init(&block_group->dirty_list);
10120                 btrfs_put_block_group(block_group);
10121         }
10122         spin_unlock(&trans->transaction->dirty_bgs_lock);
10123         mutex_unlock(&trans->transaction->cache_write_mutex);
10124
10125         if (!IS_ERR(inode)) {
10126                 ret = btrfs_orphan_add(trans, inode);
10127                 if (ret) {
10128                         btrfs_add_delayed_iput(inode);
10129                         goto out;
10130                 }
10131                 clear_nlink(inode);
10132                 /* One for the block groups ref */
10133                 spin_lock(&block_group->lock);
10134                 if (block_group->iref) {
10135                         block_group->iref = 0;
10136                         block_group->inode = NULL;
10137                         spin_unlock(&block_group->lock);
10138                         iput(inode);
10139                 } else {
10140                         spin_unlock(&block_group->lock);
10141                 }
10142                 /* One for our lookup ref */
10143                 btrfs_add_delayed_iput(inode);
10144         }
10145
10146         key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10147         key.offset = block_group->key.objectid;
10148         key.type = 0;
10149
10150         ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10151         if (ret < 0)
10152                 goto out;
10153         if (ret > 0)
10154                 btrfs_release_path(path);
10155         if (ret == 0) {
10156                 ret = btrfs_del_item(trans, tree_root, path);
10157                 if (ret)
10158                         goto out;
10159                 btrfs_release_path(path);
10160         }
10161
10162         spin_lock(&root->fs_info->block_group_cache_lock);
10163         rb_erase(&block_group->cache_node,
10164                  &root->fs_info->block_group_cache_tree);
10165         RB_CLEAR_NODE(&block_group->cache_node);
10166
10167         if (root->fs_info->first_logical_byte == block_group->key.objectid)
10168                 root->fs_info->first_logical_byte = (u64)-1;
10169         spin_unlock(&root->fs_info->block_group_cache_lock);
10170
10171         down_write(&block_group->space_info->groups_sem);
10172         /*
10173          * we must use list_del_init so people can check to see if they
10174          * are still on the list after taking the semaphore
10175          */
10176         list_del_init(&block_group->list);
10177         if (list_empty(&block_group->space_info->block_groups[index])) {
10178                 kobj = block_group->space_info->block_group_kobjs[index];
10179                 block_group->space_info->block_group_kobjs[index] = NULL;
10180                 clear_avail_alloc_bits(root->fs_info, block_group->flags);
10181         }
10182         up_write(&block_group->space_info->groups_sem);
10183         if (kobj) {
10184                 kobject_del(kobj);
10185                 kobject_put(kobj);
10186         }
10187
10188         if (block_group->has_caching_ctl)
10189                 caching_ctl = get_caching_control(block_group);
10190         if (block_group->cached == BTRFS_CACHE_STARTED)
10191                 wait_block_group_cache_done(block_group);
10192         if (block_group->has_caching_ctl) {
10193                 down_write(&root->fs_info->commit_root_sem);
10194                 if (!caching_ctl) {
10195                         struct btrfs_caching_control *ctl;
10196
10197                         list_for_each_entry(ctl,
10198                                     &root->fs_info->caching_block_groups, list)
10199                                 if (ctl->block_group == block_group) {
10200                                         caching_ctl = ctl;
10201                                         atomic_inc(&caching_ctl->count);
10202                                         break;
10203                                 }
10204                 }
10205                 if (caching_ctl)
10206                         list_del_init(&caching_ctl->list);
10207                 up_write(&root->fs_info->commit_root_sem);
10208                 if (caching_ctl) {
10209                         /* Once for the caching bgs list and once for us. */
10210                         put_caching_control(caching_ctl);
10211                         put_caching_control(caching_ctl);
10212                 }
10213         }
10214
10215         spin_lock(&trans->transaction->dirty_bgs_lock);
10216         if (!list_empty(&block_group->dirty_list)) {
10217                 WARN_ON(1);
10218         }
10219         if (!list_empty(&block_group->io_list)) {
10220                 WARN_ON(1);
10221         }
10222         spin_unlock(&trans->transaction->dirty_bgs_lock);
10223         btrfs_remove_free_space_cache(block_group);
10224
10225         spin_lock(&block_group->space_info->lock);
10226         list_del_init(&block_group->ro_list);
10227
10228         if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
10229                 WARN_ON(block_group->space_info->total_bytes
10230                         < block_group->key.offset);
10231                 WARN_ON(block_group->space_info->bytes_readonly
10232                         < block_group->key.offset);
10233                 WARN_ON(block_group->space_info->disk_total
10234                         < block_group->key.offset * factor);
10235         }
10236         block_group->space_info->total_bytes -= block_group->key.offset;
10237         block_group->space_info->bytes_readonly -= block_group->key.offset;
10238         block_group->space_info->disk_total -= block_group->key.offset * factor;
10239
10240         spin_unlock(&block_group->space_info->lock);
10241
10242         memcpy(&key, &block_group->key, sizeof(key));
10243
10244         lock_chunks(root);
10245         if (!list_empty(&em->list)) {
10246                 /* We're in the transaction->pending_chunks list. */
10247                 free_extent_map(em);
10248         }
10249         spin_lock(&block_group->lock);
10250         block_group->removed = 1;
10251         /*
10252          * At this point trimming can't start on this block group, because we
10253          * removed the block group from the tree fs_info->block_group_cache_tree
10254          * so no one can't find it anymore and even if someone already got this
10255          * block group before we removed it from the rbtree, they have already
10256          * incremented block_group->trimming - if they didn't, they won't find
10257          * any free space entries because we already removed them all when we
10258          * called btrfs_remove_free_space_cache().
10259          *
10260          * And we must not remove the extent map from the fs_info->mapping_tree
10261          * to prevent the same logical address range and physical device space
10262          * ranges from being reused for a new block group. This is because our
10263          * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10264          * completely transactionless, so while it is trimming a range the
10265          * currently running transaction might finish and a new one start,
10266          * allowing for new block groups to be created that can reuse the same
10267          * physical device locations unless we take this special care.
10268          *
10269          * There may also be an implicit trim operation if the file system
10270          * is mounted with -odiscard. The same protections must remain
10271          * in place until the extents have been discarded completely when
10272          * the transaction commit has completed.
10273          */
10274         remove_em = (atomic_read(&block_group->trimming) == 0);
10275         /*
10276          * Make sure a trimmer task always sees the em in the pinned_chunks list
10277          * if it sees block_group->removed == 1 (needs to lock block_group->lock
10278          * before checking block_group->removed).
10279          */
10280         if (!remove_em) {
10281                 /*
10282                  * Our em might be in trans->transaction->pending_chunks which
10283                  * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
10284                  * and so is the fs_info->pinned_chunks list.
10285                  *
10286                  * So at this point we must be holding the chunk_mutex to avoid
10287                  * any races with chunk allocation (more specifically at
10288                  * volumes.c:contains_pending_extent()), to ensure it always
10289                  * sees the em, either in the pending_chunks list or in the
10290                  * pinned_chunks list.
10291                  */
10292                 list_move_tail(&em->list, &root->fs_info->pinned_chunks);
10293         }
10294         spin_unlock(&block_group->lock);
10295
10296         if (remove_em) {
10297                 struct extent_map_tree *em_tree;
10298
10299                 em_tree = &root->fs_info->mapping_tree.map_tree;
10300                 write_lock(&em_tree->lock);
10301                 /*
10302                  * The em might be in the pending_chunks list, so make sure the
10303                  * chunk mutex is locked, since remove_extent_mapping() will
10304                  * delete us from that list.
10305                  */
10306                 remove_extent_mapping(em_tree, em);
10307                 write_unlock(&em_tree->lock);
10308                 /* once for the tree */
10309                 free_extent_map(em);
10310         }
10311
10312         unlock_chunks(root);
10313
10314         btrfs_put_block_group(block_group);
10315         btrfs_put_block_group(block_group);
10316
10317         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10318         if (ret > 0)
10319                 ret = -EIO;
10320         if (ret < 0)
10321                 goto out;
10322
10323         ret = btrfs_del_item(trans, root, path);
10324 out:
10325         btrfs_free_path(path);
10326         return ret;
10327 }
10328
10329 struct btrfs_trans_handle *
10330 btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
10331                                      const u64 chunk_offset)
10332 {
10333         struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
10334         struct extent_map *em;
10335         struct map_lookup *map;
10336         unsigned int num_items;
10337
10338         read_lock(&em_tree->lock);
10339         em = lookup_extent_mapping(em_tree, chunk_offset, 1);
10340         read_unlock(&em_tree->lock);
10341         ASSERT(em && em->start == chunk_offset);
10342
10343         /*
10344          * We need to reserve 3 + N units from the metadata space info in order
10345          * to remove a block group (done at btrfs_remove_chunk() and at
10346          * btrfs_remove_block_group()), which are used for:
10347          *
10348          * 1 unit for adding the free space inode's orphan (located in the tree
10349          * of tree roots).
10350          * 1 unit for deleting the block group item (located in the extent
10351          * tree).
10352          * 1 unit for deleting the free space item (located in tree of tree
10353          * roots).
10354          * N units for deleting N device extent items corresponding to each
10355          * stripe (located in the device tree).
10356          *
10357          * In order to remove a block group we also need to reserve units in the
10358          * system space info in order to update the chunk tree (update one or
10359          * more device items and remove one chunk item), but this is done at
10360          * btrfs_remove_chunk() through a call to check_system_chunk().
10361          */
10362         map = (struct map_lookup *)em->bdev;
10363         num_items = 3 + map->num_stripes;
10364         free_extent_map(em);
10365
10366         return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
10367                                                            num_items, 1);
10368 }
10369
10370 /*
10371  * Process the unused_bgs list and remove any that don't have any allocated
10372  * space inside of them.
10373  */
10374 void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10375 {
10376         struct btrfs_block_group_cache *block_group;
10377         struct btrfs_space_info *space_info;
10378         struct btrfs_root *root = fs_info->extent_root;
10379         struct btrfs_trans_handle *trans;
10380         int ret = 0;
10381
10382         if (!fs_info->open)
10383                 return;
10384
10385         spin_lock(&fs_info->unused_bgs_lock);
10386         while (!list_empty(&fs_info->unused_bgs)) {
10387                 u64 start, end;
10388                 int trimming;
10389
10390                 block_group = list_first_entry(&fs_info->unused_bgs,
10391                                                struct btrfs_block_group_cache,
10392                                                bg_list);
10393                 list_del_init(&block_group->bg_list);
10394
10395                 space_info = block_group->space_info;
10396
10397                 if (ret || btrfs_mixed_space_info(space_info)) {
10398                         btrfs_put_block_group(block_group);
10399                         continue;
10400                 }
10401                 spin_unlock(&fs_info->unused_bgs_lock);
10402
10403                 mutex_lock(&fs_info->delete_unused_bgs_mutex);
10404
10405                 /* Don't want to race with allocators so take the groups_sem */
10406                 down_write(&space_info->groups_sem);
10407                 spin_lock(&block_group->lock);
10408                 if (block_group->reserved ||
10409                     btrfs_block_group_used(&block_group->item) ||
10410                     block_group->ro ||
10411                     list_is_singular(&block_group->list)) {
10412                         /*
10413                          * We want to bail if we made new allocations or have
10414                          * outstanding allocations in this block group.  We do
10415                          * the ro check in case balance is currently acting on
10416                          * this block group.
10417                          */
10418                         spin_unlock(&block_group->lock);
10419                         up_write(&space_info->groups_sem);
10420                         goto next;
10421                 }
10422                 spin_unlock(&block_group->lock);
10423
10424                 /* We don't want to force the issue, only flip if it's ok. */
10425                 ret = inc_block_group_ro(block_group, 0);
10426                 up_write(&space_info->groups_sem);
10427                 if (ret < 0) {
10428                         ret = 0;
10429                         goto next;
10430                 }
10431
10432                 /*
10433                  * Want to do this before we do anything else so we can recover
10434                  * properly if we fail to join the transaction.
10435                  */
10436                 trans = btrfs_start_trans_remove_block_group(fs_info,
10437                                                      block_group->key.objectid);
10438                 if (IS_ERR(trans)) {
10439                         btrfs_dec_block_group_ro(root, block_group);
10440                         ret = PTR_ERR(trans);
10441                         goto next;
10442                 }
10443
10444                 /*
10445                  * We could have pending pinned extents for this block group,
10446                  * just delete them, we don't care about them anymore.
10447                  */
10448                 start = block_group->key.objectid;
10449                 end = start + block_group->key.offset - 1;
10450                 /*
10451                  * Hold the unused_bg_unpin_mutex lock to avoid racing with
10452                  * btrfs_finish_extent_commit(). If we are at transaction N,
10453                  * another task might be running finish_extent_commit() for the
10454                  * previous transaction N - 1, and have seen a range belonging
10455                  * to the block group in freed_extents[] before we were able to
10456                  * clear the whole block group range from freed_extents[]. This
10457                  * means that task can lookup for the block group after we
10458                  * unpinned it from freed_extents[] and removed it, leading to
10459                  * a BUG_ON() at btrfs_unpin_extent_range().
10460                  */
10461                 mutex_lock(&fs_info->unused_bg_unpin_mutex);
10462                 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
10463                                   EXTENT_DIRTY, GFP_NOFS);
10464                 if (ret) {
10465                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10466                         btrfs_dec_block_group_ro(root, block_group);
10467                         goto end_trans;
10468                 }
10469                 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
10470                                   EXTENT_DIRTY, GFP_NOFS);
10471                 if (ret) {
10472                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10473                         btrfs_dec_block_group_ro(root, block_group);
10474                         goto end_trans;
10475                 }
10476                 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
10477
10478                 /* Reset pinned so btrfs_put_block_group doesn't complain */
10479                 spin_lock(&space_info->lock);
10480                 spin_lock(&block_group->lock);
10481
10482                 space_info->bytes_pinned -= block_group->pinned;
10483                 space_info->bytes_readonly += block_group->pinned;
10484                 percpu_counter_add(&space_info->total_bytes_pinned,
10485                                    -block_group->pinned);
10486                 block_group->pinned = 0;
10487
10488                 spin_unlock(&block_group->lock);
10489                 spin_unlock(&space_info->lock);
10490
10491                 /* DISCARD can flip during remount */
10492                 trimming = btrfs_test_opt(root, DISCARD);
10493
10494                 /* Implicit trim during transaction commit. */
10495                 if (trimming)
10496                         btrfs_get_block_group_trimming(block_group);
10497
10498                 /*
10499                  * Btrfs_remove_chunk will abort the transaction if things go
10500                  * horribly wrong.
10501                  */
10502                 ret = btrfs_remove_chunk(trans, root,
10503                                          block_group->key.objectid);
10504
10505                 if (ret) {
10506                         if (trimming)
10507                                 btrfs_put_block_group_trimming(block_group);
10508                         goto end_trans;
10509                 }
10510
10511                 /*
10512                  * If we're not mounted with -odiscard, we can just forget
10513                  * about this block group. Otherwise we'll need to wait
10514                  * until transaction commit to do the actual discard.
10515                  */
10516                 if (trimming) {
10517                         spin_lock(&fs_info->unused_bgs_lock);
10518                         /*
10519                          * A concurrent scrub might have added us to the list
10520                          * fs_info->unused_bgs, so use a list_move operation
10521                          * to add the block group to the deleted_bgs list.
10522                          */
10523                         list_move(&block_group->bg_list,
10524                                   &trans->transaction->deleted_bgs);
10525                         spin_unlock(&fs_info->unused_bgs_lock);
10526                         btrfs_get_block_group(block_group);
10527                 }
10528 end_trans:
10529                 btrfs_end_transaction(trans, root);
10530 next:
10531                 mutex_unlock(&fs_info->delete_unused_bgs_mutex);
10532                 btrfs_put_block_group(block_group);
10533                 spin_lock(&fs_info->unused_bgs_lock);
10534         }
10535         spin_unlock(&fs_info->unused_bgs_lock);
10536 }
10537
10538 int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
10539 {
10540         struct btrfs_space_info *space_info;
10541         struct btrfs_super_block *disk_super;
10542         u64 features;
10543         u64 flags;
10544         int mixed = 0;
10545         int ret;
10546
10547         disk_super = fs_info->super_copy;
10548         if (!btrfs_super_root(disk_super))
10549                 return 1;
10550
10551         features = btrfs_super_incompat_flags(disk_super);
10552         if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
10553                 mixed = 1;
10554
10555         flags = BTRFS_BLOCK_GROUP_SYSTEM;
10556         ret = update_space_info(fs_info, flags, 0, 0, &space_info);
10557         if (ret)
10558                 goto out;
10559
10560         if (mixed) {
10561                 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
10562                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
10563         } else {
10564                 flags = BTRFS_BLOCK_GROUP_METADATA;
10565                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
10566                 if (ret)
10567                         goto out;
10568
10569                 flags = BTRFS_BLOCK_GROUP_DATA;
10570                 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
10571         }
10572 out:
10573         return ret;
10574 }
10575
10576 int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
10577 {
10578         return unpin_extent_range(root, start, end, false);
10579 }
10580
10581 /*
10582  * It used to be that old block groups would be left around forever.
10583  * Iterating over them would be enough to trim unused space.  Since we
10584  * now automatically remove them, we also need to iterate over unallocated
10585  * space.
10586  *
10587  * We don't want a transaction for this since the discard may take a
10588  * substantial amount of time.  We don't require that a transaction be
10589  * running, but we do need to take a running transaction into account
10590  * to ensure that we're not discarding chunks that were released in
10591  * the current transaction.
10592  *
10593  * Holding the chunks lock will prevent other threads from allocating
10594  * or releasing chunks, but it won't prevent a running transaction
10595  * from committing and releasing the memory that the pending chunks
10596  * list head uses.  For that, we need to take a reference to the
10597  * transaction.
10598  */
10599 static int btrfs_trim_free_extents(struct btrfs_device *device,
10600                                    u64 minlen, u64 *trimmed)
10601 {
10602         u64 start = 0, len = 0;
10603         int ret;
10604
10605         *trimmed = 0;
10606
10607         /* Not writeable = nothing to do. */
10608         if (!device->writeable)
10609                 return 0;
10610
10611         /* No free space = nothing to do. */
10612         if (device->total_bytes <= device->bytes_used)
10613                 return 0;
10614
10615         ret = 0;
10616
10617         while (1) {
10618                 struct btrfs_fs_info *fs_info = device->dev_root->fs_info;
10619                 struct btrfs_transaction *trans;
10620                 u64 bytes;
10621
10622                 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
10623                 if (ret)
10624                         return ret;
10625
10626                 down_read(&fs_info->commit_root_sem);
10627
10628                 spin_lock(&fs_info->trans_lock);
10629                 trans = fs_info->running_transaction;
10630                 if (trans)
10631                         atomic_inc(&trans->use_count);
10632                 spin_unlock(&fs_info->trans_lock);
10633
10634                 ret = find_free_dev_extent_start(trans, device, minlen, start,
10635                                                  &start, &len);
10636                 if (trans)
10637                         btrfs_put_transaction(trans);
10638
10639                 if (ret) {
10640                         up_read(&fs_info->commit_root_sem);
10641                         mutex_unlock(&fs_info->chunk_mutex);
10642                         if (ret == -ENOSPC)
10643                                 ret = 0;
10644                         break;
10645                 }
10646
10647                 ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
10648                 up_read(&fs_info->commit_root_sem);
10649                 mutex_unlock(&fs_info->chunk_mutex);
10650
10651                 if (ret)
10652                         break;
10653
10654                 start += len;
10655                 *trimmed += bytes;
10656
10657                 if (fatal_signal_pending(current)) {
10658                         ret = -ERESTARTSYS;
10659                         break;
10660                 }
10661
10662                 cond_resched();
10663         }
10664
10665         return ret;
10666 }
10667
10668 int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
10669 {
10670         struct btrfs_fs_info *fs_info = root->fs_info;
10671         struct btrfs_block_group_cache *cache = NULL;
10672         struct btrfs_device *device;
10673         struct list_head *devices;
10674         u64 group_trimmed;
10675         u64 start;
10676         u64 end;
10677         u64 trimmed = 0;
10678         u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
10679         int ret = 0;
10680
10681         /*
10682          * try to trim all FS space, our block group may start from non-zero.
10683          */
10684         if (range->len == total_bytes)
10685                 cache = btrfs_lookup_first_block_group(fs_info, range->start);
10686         else
10687                 cache = btrfs_lookup_block_group(fs_info, range->start);
10688
10689         while (cache) {
10690                 if (cache->key.objectid >= (range->start + range->len)) {
10691                         btrfs_put_block_group(cache);
10692                         break;
10693                 }
10694
10695                 start = max(range->start, cache->key.objectid);
10696                 end = min(range->start + range->len,
10697                                 cache->key.objectid + cache->key.offset);
10698
10699                 if (end - start >= range->minlen) {
10700                         if (!block_group_cache_done(cache)) {
10701                                 ret = cache_block_group(cache, 0);
10702                                 if (ret) {
10703                                         btrfs_put_block_group(cache);
10704                                         break;
10705                                 }
10706                                 ret = wait_block_group_cache_done(cache);
10707                                 if (ret) {
10708                                         btrfs_put_block_group(cache);
10709                                         break;
10710                                 }
10711                         }
10712                         ret = btrfs_trim_block_group(cache,
10713                                                      &group_trimmed,
10714                                                      start,
10715                                                      end,
10716                                                      range->minlen);
10717
10718                         trimmed += group_trimmed;
10719                         if (ret) {
10720                                 btrfs_put_block_group(cache);
10721                                 break;
10722                         }
10723                 }
10724
10725                 cache = next_block_group(fs_info->tree_root, cache);
10726         }
10727
10728         mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
10729         devices = &root->fs_info->fs_devices->alloc_list;
10730         list_for_each_entry(device, devices, dev_alloc_list) {
10731                 ret = btrfs_trim_free_extents(device, range->minlen,
10732                                               &group_trimmed);
10733                 if (ret)
10734                         break;
10735
10736                 trimmed += group_trimmed;
10737         }
10738         mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
10739
10740         range->len = trimmed;
10741         return ret;
10742 }
10743
10744 /*
10745  * btrfs_{start,end}_write_no_snapshoting() are similar to
10746  * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
10747  * data into the page cache through nocow before the subvolume is snapshoted,
10748  * but flush the data into disk after the snapshot creation, or to prevent
10749  * operations while snapshoting is ongoing and that cause the snapshot to be
10750  * inconsistent (writes followed by expanding truncates for example).
10751  */
10752 void btrfs_end_write_no_snapshoting(struct btrfs_root *root)
10753 {
10754         percpu_counter_dec(&root->subv_writers->counter);
10755         /*
10756          * Make sure counter is updated before we wake up waiters.
10757          */
10758         smp_mb();
10759         if (waitqueue_active(&root->subv_writers->wait))
10760                 wake_up(&root->subv_writers->wait);
10761 }
10762
10763 int btrfs_start_write_no_snapshoting(struct btrfs_root *root)
10764 {
10765         if (atomic_read(&root->will_be_snapshoted))
10766                 return 0;
10767
10768         percpu_counter_inc(&root->subv_writers->counter);
10769         /*
10770          * Make sure counter is updated before we check for snapshot creation.
10771          */
10772         smp_mb();
10773         if (atomic_read(&root->will_be_snapshoted)) {
10774                 btrfs_end_write_no_snapshoting(root);
10775                 return 0;
10776         }
10777         return 1;
10778 }