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