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