]> git.karo-electronics.de Git - karo-tx-linux.git/blob - fs/btrfs/extent-tree.c
24d6adcecdded00e1baf7d7b28284d3db0a8a396
[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_fs_info *fs_info,
1039                                   struct btrfs_path *path,
1040                                   u64 owner, u32 extra_size)
1041 {
1042         struct btrfs_root *root = fs_info->extent_root;
1043         struct btrfs_extent_item *item;
1044         struct btrfs_extent_item_v0 *ei0;
1045         struct btrfs_extent_ref_v0 *ref0;
1046         struct btrfs_tree_block_info *bi;
1047         struct extent_buffer *leaf;
1048         struct btrfs_key key;
1049         struct btrfs_key found_key;
1050         u32 new_size = sizeof(*item);
1051         u64 refs;
1052         int ret;
1053
1054         leaf = path->nodes[0];
1055         BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1056
1057         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1058         ei0 = btrfs_item_ptr(leaf, path->slots[0],
1059                              struct btrfs_extent_item_v0);
1060         refs = btrfs_extent_refs_v0(leaf, ei0);
1061
1062         if (owner == (u64)-1) {
1063                 while (1) {
1064                         if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1065                                 ret = btrfs_next_leaf(root, path);
1066                                 if (ret < 0)
1067                                         return ret;
1068                                 BUG_ON(ret > 0); /* Corruption */
1069                                 leaf = path->nodes[0];
1070                         }
1071                         btrfs_item_key_to_cpu(leaf, &found_key,
1072                                               path->slots[0]);
1073                         BUG_ON(key.objectid != found_key.objectid);
1074                         if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1075                                 path->slots[0]++;
1076                                 continue;
1077                         }
1078                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1079                                               struct btrfs_extent_ref_v0);
1080                         owner = btrfs_ref_objectid_v0(leaf, ref0);
1081                         break;
1082                 }
1083         }
1084         btrfs_release_path(path);
1085
1086         if (owner < BTRFS_FIRST_FREE_OBJECTID)
1087                 new_size += sizeof(*bi);
1088
1089         new_size -= sizeof(*ei0);
1090         ret = btrfs_search_slot(trans, root, &key, path,
1091                                 new_size + extra_size, 1);
1092         if (ret < 0)
1093                 return ret;
1094         BUG_ON(ret); /* Corruption */
1095
1096         btrfs_extend_item(fs_info, path, new_size);
1097
1098         leaf = path->nodes[0];
1099         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1100         btrfs_set_extent_refs(leaf, item, refs);
1101         /* FIXME: get real generation */
1102         btrfs_set_extent_generation(leaf, item, 0);
1103         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1104                 btrfs_set_extent_flags(leaf, item,
1105                                        BTRFS_EXTENT_FLAG_TREE_BLOCK |
1106                                        BTRFS_BLOCK_FLAG_FULL_BACKREF);
1107                 bi = (struct btrfs_tree_block_info *)(item + 1);
1108                 /* FIXME: get first key of the block */
1109                 memzero_extent_buffer(leaf, (unsigned long)bi, sizeof(*bi));
1110                 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1111         } else {
1112                 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1113         }
1114         btrfs_mark_buffer_dirty(leaf);
1115         return 0;
1116 }
1117 #endif
1118
1119 static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1120 {
1121         u32 high_crc = ~(u32)0;
1122         u32 low_crc = ~(u32)0;
1123         __le64 lenum;
1124
1125         lenum = cpu_to_le64(root_objectid);
1126         high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
1127         lenum = cpu_to_le64(owner);
1128         low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1129         lenum = cpu_to_le64(offset);
1130         low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
1131
1132         return ((u64)high_crc << 31) ^ (u64)low_crc;
1133 }
1134
1135 static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1136                                      struct btrfs_extent_data_ref *ref)
1137 {
1138         return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1139                                     btrfs_extent_data_ref_objectid(leaf, ref),
1140                                     btrfs_extent_data_ref_offset(leaf, ref));
1141 }
1142
1143 static int match_extent_data_ref(struct extent_buffer *leaf,
1144                                  struct btrfs_extent_data_ref *ref,
1145                                  u64 root_objectid, u64 owner, u64 offset)
1146 {
1147         if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1148             btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1149             btrfs_extent_data_ref_offset(leaf, ref) != offset)
1150                 return 0;
1151         return 1;
1152 }
1153
1154 static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1155                                            struct btrfs_fs_info *fs_info,
1156                                            struct btrfs_path *path,
1157                                            u64 bytenr, u64 parent,
1158                                            u64 root_objectid,
1159                                            u64 owner, u64 offset)
1160 {
1161         struct btrfs_root *root = fs_info->extent_root;
1162         struct btrfs_key key;
1163         struct btrfs_extent_data_ref *ref;
1164         struct extent_buffer *leaf;
1165         u32 nritems;
1166         int ret;
1167         int recow;
1168         int err = -ENOENT;
1169
1170         key.objectid = bytenr;
1171         if (parent) {
1172                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1173                 key.offset = parent;
1174         } else {
1175                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1176                 key.offset = hash_extent_data_ref(root_objectid,
1177                                                   owner, offset);
1178         }
1179 again:
1180         recow = 0;
1181         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1182         if (ret < 0) {
1183                 err = ret;
1184                 goto fail;
1185         }
1186
1187         if (parent) {
1188                 if (!ret)
1189                         return 0;
1190 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1191                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1192                 btrfs_release_path(path);
1193                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1194                 if (ret < 0) {
1195                         err = ret;
1196                         goto fail;
1197                 }
1198                 if (!ret)
1199                         return 0;
1200 #endif
1201                 goto fail;
1202         }
1203
1204         leaf = path->nodes[0];
1205         nritems = btrfs_header_nritems(leaf);
1206         while (1) {
1207                 if (path->slots[0] >= nritems) {
1208                         ret = btrfs_next_leaf(root, path);
1209                         if (ret < 0)
1210                                 err = ret;
1211                         if (ret)
1212                                 goto fail;
1213
1214                         leaf = path->nodes[0];
1215                         nritems = btrfs_header_nritems(leaf);
1216                         recow = 1;
1217                 }
1218
1219                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1220                 if (key.objectid != bytenr ||
1221                     key.type != BTRFS_EXTENT_DATA_REF_KEY)
1222                         goto fail;
1223
1224                 ref = btrfs_item_ptr(leaf, path->slots[0],
1225                                      struct btrfs_extent_data_ref);
1226
1227                 if (match_extent_data_ref(leaf, ref, root_objectid,
1228                                           owner, offset)) {
1229                         if (recow) {
1230                                 btrfs_release_path(path);
1231                                 goto again;
1232                         }
1233                         err = 0;
1234                         break;
1235                 }
1236                 path->slots[0]++;
1237         }
1238 fail:
1239         return err;
1240 }
1241
1242 static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1243                                            struct btrfs_fs_info *fs_info,
1244                                            struct btrfs_path *path,
1245                                            u64 bytenr, u64 parent,
1246                                            u64 root_objectid, u64 owner,
1247                                            u64 offset, int refs_to_add)
1248 {
1249         struct btrfs_root *root = fs_info->extent_root;
1250         struct btrfs_key key;
1251         struct extent_buffer *leaf;
1252         u32 size;
1253         u32 num_refs;
1254         int ret;
1255
1256         key.objectid = bytenr;
1257         if (parent) {
1258                 key.type = BTRFS_SHARED_DATA_REF_KEY;
1259                 key.offset = parent;
1260                 size = sizeof(struct btrfs_shared_data_ref);
1261         } else {
1262                 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1263                 key.offset = hash_extent_data_ref(root_objectid,
1264                                                   owner, offset);
1265                 size = sizeof(struct btrfs_extent_data_ref);
1266         }
1267
1268         ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1269         if (ret && ret != -EEXIST)
1270                 goto fail;
1271
1272         leaf = path->nodes[0];
1273         if (parent) {
1274                 struct btrfs_shared_data_ref *ref;
1275                 ref = btrfs_item_ptr(leaf, path->slots[0],
1276                                      struct btrfs_shared_data_ref);
1277                 if (ret == 0) {
1278                         btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1279                 } else {
1280                         num_refs = btrfs_shared_data_ref_count(leaf, ref);
1281                         num_refs += refs_to_add;
1282                         btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
1283                 }
1284         } else {
1285                 struct btrfs_extent_data_ref *ref;
1286                 while (ret == -EEXIST) {
1287                         ref = btrfs_item_ptr(leaf, path->slots[0],
1288                                              struct btrfs_extent_data_ref);
1289                         if (match_extent_data_ref(leaf, ref, root_objectid,
1290                                                   owner, offset))
1291                                 break;
1292                         btrfs_release_path(path);
1293                         key.offset++;
1294                         ret = btrfs_insert_empty_item(trans, root, path, &key,
1295                                                       size);
1296                         if (ret && ret != -EEXIST)
1297                                 goto fail;
1298
1299                         leaf = path->nodes[0];
1300                 }
1301                 ref = btrfs_item_ptr(leaf, path->slots[0],
1302                                      struct btrfs_extent_data_ref);
1303                 if (ret == 0) {
1304                         btrfs_set_extent_data_ref_root(leaf, ref,
1305                                                        root_objectid);
1306                         btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1307                         btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1308                         btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1309                 } else {
1310                         num_refs = btrfs_extent_data_ref_count(leaf, ref);
1311                         num_refs += refs_to_add;
1312                         btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
1313                 }
1314         }
1315         btrfs_mark_buffer_dirty(leaf);
1316         ret = 0;
1317 fail:
1318         btrfs_release_path(path);
1319         return ret;
1320 }
1321
1322 static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1323                                            struct btrfs_fs_info *fs_info,
1324                                            struct btrfs_path *path,
1325                                            int refs_to_drop, int *last_ref)
1326 {
1327         struct btrfs_key key;
1328         struct btrfs_extent_data_ref *ref1 = NULL;
1329         struct btrfs_shared_data_ref *ref2 = NULL;
1330         struct extent_buffer *leaf;
1331         u32 num_refs = 0;
1332         int ret = 0;
1333
1334         leaf = path->nodes[0];
1335         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1336
1337         if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1338                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1339                                       struct btrfs_extent_data_ref);
1340                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1341         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1342                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1343                                       struct btrfs_shared_data_ref);
1344                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1345 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1346         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1347                 struct btrfs_extent_ref_v0 *ref0;
1348                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1349                                       struct btrfs_extent_ref_v0);
1350                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1351 #endif
1352         } else {
1353                 BUG();
1354         }
1355
1356         BUG_ON(num_refs < refs_to_drop);
1357         num_refs -= refs_to_drop;
1358
1359         if (num_refs == 0) {
1360                 ret = btrfs_del_item(trans, fs_info->extent_root, path);
1361                 *last_ref = 1;
1362         } else {
1363                 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1364                         btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1365                 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1366                         btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1367 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1368                 else {
1369                         struct btrfs_extent_ref_v0 *ref0;
1370                         ref0 = btrfs_item_ptr(leaf, path->slots[0],
1371                                         struct btrfs_extent_ref_v0);
1372                         btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1373                 }
1374 #endif
1375                 btrfs_mark_buffer_dirty(leaf);
1376         }
1377         return ret;
1378 }
1379
1380 static noinline u32 extent_data_ref_count(struct btrfs_path *path,
1381                                           struct btrfs_extent_inline_ref *iref)
1382 {
1383         struct btrfs_key key;
1384         struct extent_buffer *leaf;
1385         struct btrfs_extent_data_ref *ref1;
1386         struct btrfs_shared_data_ref *ref2;
1387         u32 num_refs = 0;
1388
1389         leaf = path->nodes[0];
1390         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1391         if (iref) {
1392                 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1393                     BTRFS_EXTENT_DATA_REF_KEY) {
1394                         ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1395                         num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1396                 } else {
1397                         ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1398                         num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1399                 }
1400         } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1401                 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1402                                       struct btrfs_extent_data_ref);
1403                 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1404         } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1405                 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1406                                       struct btrfs_shared_data_ref);
1407                 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1408 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1409         } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1410                 struct btrfs_extent_ref_v0 *ref0;
1411                 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1412                                       struct btrfs_extent_ref_v0);
1413                 num_refs = btrfs_ref_count_v0(leaf, ref0);
1414 #endif
1415         } else {
1416                 WARN_ON(1);
1417         }
1418         return num_refs;
1419 }
1420
1421 static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1422                                           struct btrfs_fs_info *fs_info,
1423                                           struct btrfs_path *path,
1424                                           u64 bytenr, u64 parent,
1425                                           u64 root_objectid)
1426 {
1427         struct btrfs_root *root = fs_info->extent_root;
1428         struct btrfs_key key;
1429         int ret;
1430
1431         key.objectid = bytenr;
1432         if (parent) {
1433                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1434                 key.offset = parent;
1435         } else {
1436                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1437                 key.offset = root_objectid;
1438         }
1439
1440         ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1441         if (ret > 0)
1442                 ret = -ENOENT;
1443 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1444         if (ret == -ENOENT && parent) {
1445                 btrfs_release_path(path);
1446                 key.type = BTRFS_EXTENT_REF_V0_KEY;
1447                 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1448                 if (ret > 0)
1449                         ret = -ENOENT;
1450         }
1451 #endif
1452         return ret;
1453 }
1454
1455 static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1456                                           struct btrfs_fs_info *fs_info,
1457                                           struct btrfs_path *path,
1458                                           u64 bytenr, u64 parent,
1459                                           u64 root_objectid)
1460 {
1461         struct btrfs_key key;
1462         int ret;
1463
1464         key.objectid = bytenr;
1465         if (parent) {
1466                 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1467                 key.offset = parent;
1468         } else {
1469                 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1470                 key.offset = root_objectid;
1471         }
1472
1473         ret = btrfs_insert_empty_item(trans, fs_info->extent_root,
1474                                       path, &key, 0);
1475         btrfs_release_path(path);
1476         return ret;
1477 }
1478
1479 static inline int extent_ref_type(u64 parent, u64 owner)
1480 {
1481         int type;
1482         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1483                 if (parent > 0)
1484                         type = BTRFS_SHARED_BLOCK_REF_KEY;
1485                 else
1486                         type = BTRFS_TREE_BLOCK_REF_KEY;
1487         } else {
1488                 if (parent > 0)
1489                         type = BTRFS_SHARED_DATA_REF_KEY;
1490                 else
1491                         type = BTRFS_EXTENT_DATA_REF_KEY;
1492         }
1493         return type;
1494 }
1495
1496 static int find_next_key(struct btrfs_path *path, int level,
1497                          struct btrfs_key *key)
1498
1499 {
1500         for (; level < BTRFS_MAX_LEVEL; level++) {
1501                 if (!path->nodes[level])
1502                         break;
1503                 if (path->slots[level] + 1 >=
1504                     btrfs_header_nritems(path->nodes[level]))
1505                         continue;
1506                 if (level == 0)
1507                         btrfs_item_key_to_cpu(path->nodes[level], key,
1508                                               path->slots[level] + 1);
1509                 else
1510                         btrfs_node_key_to_cpu(path->nodes[level], key,
1511                                               path->slots[level] + 1);
1512                 return 0;
1513         }
1514         return 1;
1515 }
1516
1517 /*
1518  * look for inline back ref. if back ref is found, *ref_ret is set
1519  * to the address of inline back ref, and 0 is returned.
1520  *
1521  * if back ref isn't found, *ref_ret is set to the address where it
1522  * should be inserted, and -ENOENT is returned.
1523  *
1524  * if insert is true and there are too many inline back refs, the path
1525  * points to the extent item, and -EAGAIN is returned.
1526  *
1527  * NOTE: inline back refs are ordered in the same way that back ref
1528  *       items in the tree are ordered.
1529  */
1530 static noinline_for_stack
1531 int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1532                                  struct btrfs_fs_info *fs_info,
1533                                  struct btrfs_path *path,
1534                                  struct btrfs_extent_inline_ref **ref_ret,
1535                                  u64 bytenr, u64 num_bytes,
1536                                  u64 parent, u64 root_objectid,
1537                                  u64 owner, u64 offset, int insert)
1538 {
1539         struct btrfs_root *root = fs_info->extent_root;
1540         struct btrfs_key key;
1541         struct extent_buffer *leaf;
1542         struct btrfs_extent_item *ei;
1543         struct btrfs_extent_inline_ref *iref;
1544         u64 flags;
1545         u64 item_size;
1546         unsigned long ptr;
1547         unsigned long end;
1548         int extra_size;
1549         int type;
1550         int want;
1551         int ret;
1552         int err = 0;
1553         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
1554
1555         key.objectid = bytenr;
1556         key.type = BTRFS_EXTENT_ITEM_KEY;
1557         key.offset = num_bytes;
1558
1559         want = extent_ref_type(parent, owner);
1560         if (insert) {
1561                 extra_size = btrfs_extent_inline_ref_size(want);
1562                 path->keep_locks = 1;
1563         } else
1564                 extra_size = -1;
1565
1566         /*
1567          * Owner is our parent level, so we can just add one to get the level
1568          * for the block we are interested in.
1569          */
1570         if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1571                 key.type = BTRFS_METADATA_ITEM_KEY;
1572                 key.offset = owner;
1573         }
1574
1575 again:
1576         ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
1577         if (ret < 0) {
1578                 err = ret;
1579                 goto out;
1580         }
1581
1582         /*
1583          * We may be a newly converted file system which still has the old fat
1584          * extent entries for metadata, so try and see if we have one of those.
1585          */
1586         if (ret > 0 && skinny_metadata) {
1587                 skinny_metadata = false;
1588                 if (path->slots[0]) {
1589                         path->slots[0]--;
1590                         btrfs_item_key_to_cpu(path->nodes[0], &key,
1591                                               path->slots[0]);
1592                         if (key.objectid == bytenr &&
1593                             key.type == BTRFS_EXTENT_ITEM_KEY &&
1594                             key.offset == num_bytes)
1595                                 ret = 0;
1596                 }
1597                 if (ret) {
1598                         key.objectid = bytenr;
1599                         key.type = BTRFS_EXTENT_ITEM_KEY;
1600                         key.offset = num_bytes;
1601                         btrfs_release_path(path);
1602                         goto again;
1603                 }
1604         }
1605
1606         if (ret && !insert) {
1607                 err = -ENOENT;
1608                 goto out;
1609         } else if (WARN_ON(ret)) {
1610                 err = -EIO;
1611                 goto out;
1612         }
1613
1614         leaf = path->nodes[0];
1615         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1616 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1617         if (item_size < sizeof(*ei)) {
1618                 if (!insert) {
1619                         err = -ENOENT;
1620                         goto out;
1621                 }
1622                 ret = convert_extent_item_v0(trans, fs_info, path, owner,
1623                                              extra_size);
1624                 if (ret < 0) {
1625                         err = ret;
1626                         goto out;
1627                 }
1628                 leaf = path->nodes[0];
1629                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1630         }
1631 #endif
1632         BUG_ON(item_size < sizeof(*ei));
1633
1634         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1635         flags = btrfs_extent_flags(leaf, ei);
1636
1637         ptr = (unsigned long)(ei + 1);
1638         end = (unsigned long)ei + item_size;
1639
1640         if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
1641                 ptr += sizeof(struct btrfs_tree_block_info);
1642                 BUG_ON(ptr > end);
1643         }
1644
1645         err = -ENOENT;
1646         while (1) {
1647                 if (ptr >= end) {
1648                         WARN_ON(ptr > end);
1649                         break;
1650                 }
1651                 iref = (struct btrfs_extent_inline_ref *)ptr;
1652                 type = btrfs_extent_inline_ref_type(leaf, iref);
1653                 if (want < type)
1654                         break;
1655                 if (want > type) {
1656                         ptr += btrfs_extent_inline_ref_size(type);
1657                         continue;
1658                 }
1659
1660                 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1661                         struct btrfs_extent_data_ref *dref;
1662                         dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1663                         if (match_extent_data_ref(leaf, dref, root_objectid,
1664                                                   owner, offset)) {
1665                                 err = 0;
1666                                 break;
1667                         }
1668                         if (hash_extent_data_ref_item(leaf, dref) <
1669                             hash_extent_data_ref(root_objectid, owner, offset))
1670                                 break;
1671                 } else {
1672                         u64 ref_offset;
1673                         ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1674                         if (parent > 0) {
1675                                 if (parent == ref_offset) {
1676                                         err = 0;
1677                                         break;
1678                                 }
1679                                 if (ref_offset < parent)
1680                                         break;
1681                         } else {
1682                                 if (root_objectid == ref_offset) {
1683                                         err = 0;
1684                                         break;
1685                                 }
1686                                 if (ref_offset < root_objectid)
1687                                         break;
1688                         }
1689                 }
1690                 ptr += btrfs_extent_inline_ref_size(type);
1691         }
1692         if (err == -ENOENT && insert) {
1693                 if (item_size + extra_size >=
1694                     BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1695                         err = -EAGAIN;
1696                         goto out;
1697                 }
1698                 /*
1699                  * To add new inline back ref, we have to make sure
1700                  * there is no corresponding back ref item.
1701                  * For simplicity, we just do not add new inline back
1702                  * ref if there is any kind of item for this block
1703                  */
1704                 if (find_next_key(path, 0, &key) == 0 &&
1705                     key.objectid == bytenr &&
1706                     key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
1707                         err = -EAGAIN;
1708                         goto out;
1709                 }
1710         }
1711         *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1712 out:
1713         if (insert) {
1714                 path->keep_locks = 0;
1715                 btrfs_unlock_up_safe(path, 1);
1716         }
1717         return err;
1718 }
1719
1720 /*
1721  * helper to add new inline back ref
1722  */
1723 static noinline_for_stack
1724 void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
1725                                  struct btrfs_path *path,
1726                                  struct btrfs_extent_inline_ref *iref,
1727                                  u64 parent, u64 root_objectid,
1728                                  u64 owner, u64 offset, int refs_to_add,
1729                                  struct btrfs_delayed_extent_op *extent_op)
1730 {
1731         struct extent_buffer *leaf;
1732         struct btrfs_extent_item *ei;
1733         unsigned long ptr;
1734         unsigned long end;
1735         unsigned long item_offset;
1736         u64 refs;
1737         int size;
1738         int type;
1739
1740         leaf = path->nodes[0];
1741         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1742         item_offset = (unsigned long)iref - (unsigned long)ei;
1743
1744         type = extent_ref_type(parent, owner);
1745         size = btrfs_extent_inline_ref_size(type);
1746
1747         btrfs_extend_item(fs_info, path, size);
1748
1749         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1750         refs = btrfs_extent_refs(leaf, ei);
1751         refs += refs_to_add;
1752         btrfs_set_extent_refs(leaf, ei, refs);
1753         if (extent_op)
1754                 __run_delayed_extent_op(extent_op, leaf, ei);
1755
1756         ptr = (unsigned long)ei + item_offset;
1757         end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1758         if (ptr < end - size)
1759                 memmove_extent_buffer(leaf, ptr + size, ptr,
1760                                       end - size - ptr);
1761
1762         iref = (struct btrfs_extent_inline_ref *)ptr;
1763         btrfs_set_extent_inline_ref_type(leaf, iref, type);
1764         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1765                 struct btrfs_extent_data_ref *dref;
1766                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1767                 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1768                 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1769                 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1770                 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1771         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1772                 struct btrfs_shared_data_ref *sref;
1773                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1774                 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1775                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1776         } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1777                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1778         } else {
1779                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1780         }
1781         btrfs_mark_buffer_dirty(leaf);
1782 }
1783
1784 static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1785                                  struct btrfs_fs_info *fs_info,
1786                                  struct btrfs_path *path,
1787                                  struct btrfs_extent_inline_ref **ref_ret,
1788                                  u64 bytenr, u64 num_bytes, u64 parent,
1789                                  u64 root_objectid, u64 owner, u64 offset)
1790 {
1791         int ret;
1792
1793         ret = lookup_inline_extent_backref(trans, fs_info, path, ref_ret,
1794                                            bytenr, num_bytes, parent,
1795                                            root_objectid, owner, offset, 0);
1796         if (ret != -ENOENT)
1797                 return ret;
1798
1799         btrfs_release_path(path);
1800         *ref_ret = NULL;
1801
1802         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1803                 ret = lookup_tree_block_ref(trans, fs_info, path, bytenr,
1804                                             parent, root_objectid);
1805         } else {
1806                 ret = lookup_extent_data_ref(trans, fs_info, path, bytenr,
1807                                              parent, root_objectid, owner,
1808                                              offset);
1809         }
1810         return ret;
1811 }
1812
1813 /*
1814  * helper to update/remove inline back ref
1815  */
1816 static noinline_for_stack
1817 void update_inline_extent_backref(struct btrfs_fs_info *fs_info,
1818                                   struct btrfs_path *path,
1819                                   struct btrfs_extent_inline_ref *iref,
1820                                   int refs_to_mod,
1821                                   struct btrfs_delayed_extent_op *extent_op,
1822                                   int *last_ref)
1823 {
1824         struct extent_buffer *leaf;
1825         struct btrfs_extent_item *ei;
1826         struct btrfs_extent_data_ref *dref = NULL;
1827         struct btrfs_shared_data_ref *sref = NULL;
1828         unsigned long ptr;
1829         unsigned long end;
1830         u32 item_size;
1831         int size;
1832         int type;
1833         u64 refs;
1834
1835         leaf = path->nodes[0];
1836         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1837         refs = btrfs_extent_refs(leaf, ei);
1838         WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1839         refs += refs_to_mod;
1840         btrfs_set_extent_refs(leaf, ei, refs);
1841         if (extent_op)
1842                 __run_delayed_extent_op(extent_op, leaf, ei);
1843
1844         type = btrfs_extent_inline_ref_type(leaf, iref);
1845
1846         if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1847                 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1848                 refs = btrfs_extent_data_ref_count(leaf, dref);
1849         } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1850                 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1851                 refs = btrfs_shared_data_ref_count(leaf, sref);
1852         } else {
1853                 refs = 1;
1854                 BUG_ON(refs_to_mod != -1);
1855         }
1856
1857         BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1858         refs += refs_to_mod;
1859
1860         if (refs > 0) {
1861                 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1862                         btrfs_set_extent_data_ref_count(leaf, dref, refs);
1863                 else
1864                         btrfs_set_shared_data_ref_count(leaf, sref, refs);
1865         } else {
1866                 *last_ref = 1;
1867                 size =  btrfs_extent_inline_ref_size(type);
1868                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1869                 ptr = (unsigned long)iref;
1870                 end = (unsigned long)ei + item_size;
1871                 if (ptr + size < end)
1872                         memmove_extent_buffer(leaf, ptr, ptr + size,
1873                                               end - ptr - size);
1874                 item_size -= size;
1875                 btrfs_truncate_item(fs_info, path, item_size, 1);
1876         }
1877         btrfs_mark_buffer_dirty(leaf);
1878 }
1879
1880 static noinline_for_stack
1881 int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1882                                  struct btrfs_fs_info *fs_info,
1883                                  struct btrfs_path *path,
1884                                  u64 bytenr, u64 num_bytes, u64 parent,
1885                                  u64 root_objectid, u64 owner,
1886                                  u64 offset, int refs_to_add,
1887                                  struct btrfs_delayed_extent_op *extent_op)
1888 {
1889         struct btrfs_extent_inline_ref *iref;
1890         int ret;
1891
1892         ret = lookup_inline_extent_backref(trans, fs_info, path, &iref,
1893                                            bytenr, num_bytes, parent,
1894                                            root_objectid, owner, offset, 1);
1895         if (ret == 0) {
1896                 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
1897                 update_inline_extent_backref(fs_info, path, iref,
1898                                              refs_to_add, extent_op, NULL);
1899         } else if (ret == -ENOENT) {
1900                 setup_inline_extent_backref(fs_info, path, iref, parent,
1901                                             root_objectid, owner, offset,
1902                                             refs_to_add, extent_op);
1903                 ret = 0;
1904         }
1905         return ret;
1906 }
1907
1908 static int insert_extent_backref(struct btrfs_trans_handle *trans,
1909                                  struct btrfs_fs_info *fs_info,
1910                                  struct btrfs_path *path,
1911                                  u64 bytenr, u64 parent, u64 root_objectid,
1912                                  u64 owner, u64 offset, int refs_to_add)
1913 {
1914         int ret;
1915         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1916                 BUG_ON(refs_to_add != 1);
1917                 ret = insert_tree_block_ref(trans, fs_info, path, bytenr,
1918                                             parent, root_objectid);
1919         } else {
1920                 ret = insert_extent_data_ref(trans, fs_info, path, bytenr,
1921                                              parent, root_objectid,
1922                                              owner, offset, refs_to_add);
1923         }
1924         return ret;
1925 }
1926
1927 static int remove_extent_backref(struct btrfs_trans_handle *trans,
1928                                  struct btrfs_fs_info *fs_info,
1929                                  struct btrfs_path *path,
1930                                  struct btrfs_extent_inline_ref *iref,
1931                                  int refs_to_drop, int is_data, int *last_ref)
1932 {
1933         int ret = 0;
1934
1935         BUG_ON(!is_data && refs_to_drop != 1);
1936         if (iref) {
1937                 update_inline_extent_backref(fs_info, path, iref,
1938                                              -refs_to_drop, NULL, last_ref);
1939         } else if (is_data) {
1940                 ret = remove_extent_data_ref(trans, fs_info, path, refs_to_drop,
1941                                              last_ref);
1942         } else {
1943                 *last_ref = 1;
1944                 ret = btrfs_del_item(trans, fs_info->extent_root, path);
1945         }
1946         return ret;
1947 }
1948
1949 #define in_range(b, first, len)        ((b) >= (first) && (b) < (first) + (len))
1950 static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1951                                u64 *discarded_bytes)
1952 {
1953         int j, ret = 0;
1954         u64 bytes_left, end;
1955         u64 aligned_start = ALIGN(start, 1 << 9);
1956
1957         if (WARN_ON(start != aligned_start)) {
1958                 len -= aligned_start - start;
1959                 len = round_down(len, 1 << 9);
1960                 start = aligned_start;
1961         }
1962
1963         *discarded_bytes = 0;
1964
1965         if (!len)
1966                 return 0;
1967
1968         end = start + len;
1969         bytes_left = len;
1970
1971         /* Skip any superblocks on this device. */
1972         for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1973                 u64 sb_start = btrfs_sb_offset(j);
1974                 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1975                 u64 size = sb_start - start;
1976
1977                 if (!in_range(sb_start, start, bytes_left) &&
1978                     !in_range(sb_end, start, bytes_left) &&
1979                     !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1980                         continue;
1981
1982                 /*
1983                  * Superblock spans beginning of range.  Adjust start and
1984                  * try again.
1985                  */
1986                 if (sb_start <= start) {
1987                         start += sb_end - start;
1988                         if (start > end) {
1989                                 bytes_left = 0;
1990                                 break;
1991                         }
1992                         bytes_left = end - start;
1993                         continue;
1994                 }
1995
1996                 if (size) {
1997                         ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1998                                                    GFP_NOFS, 0);
1999                         if (!ret)
2000                                 *discarded_bytes += size;
2001                         else if (ret != -EOPNOTSUPP)
2002                                 return ret;
2003                 }
2004
2005                 start = sb_end;
2006                 if (start > end) {
2007                         bytes_left = 0;
2008                         break;
2009                 }
2010                 bytes_left = end - start;
2011         }
2012
2013         if (bytes_left) {
2014                 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
2015                                            GFP_NOFS, 0);
2016                 if (!ret)
2017                         *discarded_bytes += bytes_left;
2018         }
2019         return ret;
2020 }
2021
2022 int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
2023                          u64 num_bytes, u64 *actual_bytes)
2024 {
2025         int ret;
2026         u64 discarded_bytes = 0;
2027         struct btrfs_bio *bbio = NULL;
2028
2029
2030         /*
2031          * Avoid races with device replace and make sure our bbio has devices
2032          * associated to its stripes that don't go away while we are discarding.
2033          */
2034         btrfs_bio_counter_inc_blocked(fs_info);
2035         /* Tell the block device(s) that the sectors can be discarded */
2036         ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
2037                               &bbio, 0);
2038         /* Error condition is -ENOMEM */
2039         if (!ret) {
2040                 struct btrfs_bio_stripe *stripe = bbio->stripes;
2041                 int i;
2042
2043
2044                 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
2045                         u64 bytes;
2046                         if (!stripe->dev->can_discard)
2047                                 continue;
2048
2049                         ret = btrfs_issue_discard(stripe->dev->bdev,
2050                                                   stripe->physical,
2051                                                   stripe->length,
2052                                                   &bytes);
2053                         if (!ret)
2054                                 discarded_bytes += bytes;
2055                         else if (ret != -EOPNOTSUPP)
2056                                 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
2057
2058                         /*
2059                          * Just in case we get back EOPNOTSUPP for some reason,
2060                          * just ignore the return value so we don't screw up
2061                          * people calling discard_extent.
2062                          */
2063                         ret = 0;
2064                 }
2065                 btrfs_put_bbio(bbio);
2066         }
2067         btrfs_bio_counter_dec(fs_info);
2068
2069         if (actual_bytes)
2070                 *actual_bytes = discarded_bytes;
2071
2072
2073         if (ret == -EOPNOTSUPP)
2074                 ret = 0;
2075         return ret;
2076 }
2077
2078 /* Can return -ENOMEM */
2079 int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2080                          struct btrfs_fs_info *fs_info,
2081                          u64 bytenr, u64 num_bytes, u64 parent,
2082                          u64 root_objectid, u64 owner, u64 offset)
2083 {
2084         int ret;
2085
2086         BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2087                root_objectid == BTRFS_TREE_LOG_OBJECTID);
2088
2089         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
2090                 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
2091                                         num_bytes,
2092                                         parent, root_objectid, (int)owner,
2093                                         BTRFS_ADD_DELAYED_REF, NULL);
2094         } else {
2095                 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
2096                                         num_bytes, parent, root_objectid,
2097                                         owner, offset, 0,
2098                                         BTRFS_ADD_DELAYED_REF);
2099         }
2100         return ret;
2101 }
2102
2103 static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2104                                   struct btrfs_fs_info *fs_info,
2105                                   struct btrfs_delayed_ref_node *node,
2106                                   u64 parent, u64 root_objectid,
2107                                   u64 owner, u64 offset, int refs_to_add,
2108                                   struct btrfs_delayed_extent_op *extent_op)
2109 {
2110         struct btrfs_path *path;
2111         struct extent_buffer *leaf;
2112         struct btrfs_extent_item *item;
2113         struct btrfs_key key;
2114         u64 bytenr = node->bytenr;
2115         u64 num_bytes = node->num_bytes;
2116         u64 refs;
2117         int ret;
2118
2119         path = btrfs_alloc_path();
2120         if (!path)
2121                 return -ENOMEM;
2122
2123         path->reada = READA_FORWARD;
2124         path->leave_spinning = 1;
2125         /* this will setup the path even if it fails to insert the back ref */
2126         ret = insert_inline_extent_backref(trans, fs_info, path, bytenr,
2127                                            num_bytes, parent, root_objectid,
2128                                            owner, offset,
2129                                            refs_to_add, extent_op);
2130         if ((ret < 0 && ret != -EAGAIN) || !ret)
2131                 goto out;
2132
2133         /*
2134          * Ok we had -EAGAIN which means we didn't have space to insert and
2135          * inline extent ref, so just update the reference count and add a
2136          * normal backref.
2137          */
2138         leaf = path->nodes[0];
2139         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
2140         item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2141         refs = btrfs_extent_refs(leaf, item);
2142         btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2143         if (extent_op)
2144                 __run_delayed_extent_op(extent_op, leaf, item);
2145
2146         btrfs_mark_buffer_dirty(leaf);
2147         btrfs_release_path(path);
2148
2149         path->reada = READA_FORWARD;
2150         path->leave_spinning = 1;
2151         /* now insert the actual backref */
2152         ret = insert_extent_backref(trans, fs_info, path, bytenr, parent,
2153                                     root_objectid, owner, offset, refs_to_add);
2154         if (ret)
2155                 btrfs_abort_transaction(trans, ret);
2156 out:
2157         btrfs_free_path(path);
2158         return ret;
2159 }
2160
2161 static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2162                                 struct btrfs_fs_info *fs_info,
2163                                 struct btrfs_delayed_ref_node *node,
2164                                 struct btrfs_delayed_extent_op *extent_op,
2165                                 int insert_reserved)
2166 {
2167         int ret = 0;
2168         struct btrfs_delayed_data_ref *ref;
2169         struct btrfs_key ins;
2170         u64 parent = 0;
2171         u64 ref_root = 0;
2172         u64 flags = 0;
2173
2174         ins.objectid = node->bytenr;
2175         ins.offset = node->num_bytes;
2176         ins.type = BTRFS_EXTENT_ITEM_KEY;
2177
2178         ref = btrfs_delayed_node_to_data_ref(node);
2179         trace_run_delayed_data_ref(fs_info, node, ref, node->action);
2180
2181         if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2182                 parent = ref->parent;
2183         ref_root = ref->root;
2184
2185         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2186                 if (extent_op)
2187                         flags |= extent_op->flags_to_set;
2188                 ret = alloc_reserved_file_extent(trans, fs_info,
2189                                                  parent, ref_root, flags,
2190                                                  ref->objectid, ref->offset,
2191                                                  &ins, node->ref_mod);
2192         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2193                 ret = __btrfs_inc_extent_ref(trans, fs_info, node, parent,
2194                                              ref_root, ref->objectid,
2195                                              ref->offset, node->ref_mod,
2196                                              extent_op);
2197         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2198                 ret = __btrfs_free_extent(trans, fs_info, node, parent,
2199                                           ref_root, ref->objectid,
2200                                           ref->offset, node->ref_mod,
2201                                           extent_op);
2202         } else {
2203                 BUG();
2204         }
2205         return ret;
2206 }
2207
2208 static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2209                                     struct extent_buffer *leaf,
2210                                     struct btrfs_extent_item *ei)
2211 {
2212         u64 flags = btrfs_extent_flags(leaf, ei);
2213         if (extent_op->update_flags) {
2214                 flags |= extent_op->flags_to_set;
2215                 btrfs_set_extent_flags(leaf, ei, flags);
2216         }
2217
2218         if (extent_op->update_key) {
2219                 struct btrfs_tree_block_info *bi;
2220                 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2221                 bi = (struct btrfs_tree_block_info *)(ei + 1);
2222                 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2223         }
2224 }
2225
2226 static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2227                                  struct btrfs_fs_info *fs_info,
2228                                  struct btrfs_delayed_ref_node *node,
2229                                  struct btrfs_delayed_extent_op *extent_op)
2230 {
2231         struct btrfs_key key;
2232         struct btrfs_path *path;
2233         struct btrfs_extent_item *ei;
2234         struct extent_buffer *leaf;
2235         u32 item_size;
2236         int ret;
2237         int err = 0;
2238         int metadata = !extent_op->is_data;
2239
2240         if (trans->aborted)
2241                 return 0;
2242
2243         if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2244                 metadata = 0;
2245
2246         path = btrfs_alloc_path();
2247         if (!path)
2248                 return -ENOMEM;
2249
2250         key.objectid = node->bytenr;
2251
2252         if (metadata) {
2253                 key.type = BTRFS_METADATA_ITEM_KEY;
2254                 key.offset = extent_op->level;
2255         } else {
2256                 key.type = BTRFS_EXTENT_ITEM_KEY;
2257                 key.offset = node->num_bytes;
2258         }
2259
2260 again:
2261         path->reada = READA_FORWARD;
2262         path->leave_spinning = 1;
2263         ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
2264         if (ret < 0) {
2265                 err = ret;
2266                 goto out;
2267         }
2268         if (ret > 0) {
2269                 if (metadata) {
2270                         if (path->slots[0] > 0) {
2271                                 path->slots[0]--;
2272                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
2273                                                       path->slots[0]);
2274                                 if (key.objectid == node->bytenr &&
2275                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
2276                                     key.offset == node->num_bytes)
2277                                         ret = 0;
2278                         }
2279                         if (ret > 0) {
2280                                 btrfs_release_path(path);
2281                                 metadata = 0;
2282
2283                                 key.objectid = node->bytenr;
2284                                 key.offset = node->num_bytes;
2285                                 key.type = BTRFS_EXTENT_ITEM_KEY;
2286                                 goto again;
2287                         }
2288                 } else {
2289                         err = -EIO;
2290                         goto out;
2291                 }
2292         }
2293
2294         leaf = path->nodes[0];
2295         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2296 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2297         if (item_size < sizeof(*ei)) {
2298                 ret = convert_extent_item_v0(trans, fs_info, path, (u64)-1, 0);
2299                 if (ret < 0) {
2300                         err = ret;
2301                         goto out;
2302                 }
2303                 leaf = path->nodes[0];
2304                 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2305         }
2306 #endif
2307         BUG_ON(item_size < sizeof(*ei));
2308         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2309         __run_delayed_extent_op(extent_op, leaf, ei);
2310
2311         btrfs_mark_buffer_dirty(leaf);
2312 out:
2313         btrfs_free_path(path);
2314         return err;
2315 }
2316
2317 static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2318                                 struct btrfs_fs_info *fs_info,
2319                                 struct btrfs_delayed_ref_node *node,
2320                                 struct btrfs_delayed_extent_op *extent_op,
2321                                 int insert_reserved)
2322 {
2323         int ret = 0;
2324         struct btrfs_delayed_tree_ref *ref;
2325         struct btrfs_key ins;
2326         u64 parent = 0;
2327         u64 ref_root = 0;
2328         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
2329
2330         ref = btrfs_delayed_node_to_tree_ref(node);
2331         trace_run_delayed_tree_ref(fs_info, node, ref, node->action);
2332
2333         if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2334                 parent = ref->parent;
2335         ref_root = ref->root;
2336
2337         ins.objectid = node->bytenr;
2338         if (skinny_metadata) {
2339                 ins.offset = ref->level;
2340                 ins.type = BTRFS_METADATA_ITEM_KEY;
2341         } else {
2342                 ins.offset = node->num_bytes;
2343                 ins.type = BTRFS_EXTENT_ITEM_KEY;
2344         }
2345
2346         if (node->ref_mod != 1) {
2347                 btrfs_err(fs_info,
2348         "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
2349                           node->bytenr, node->ref_mod, node->action, ref_root,
2350                           parent);
2351                 return -EIO;
2352         }
2353         if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
2354                 BUG_ON(!extent_op || !extent_op->update_flags);
2355                 ret = alloc_reserved_tree_block(trans, fs_info,
2356                                                 parent, ref_root,
2357                                                 extent_op->flags_to_set,
2358                                                 &extent_op->key,
2359                                                 ref->level, &ins);
2360         } else if (node->action == BTRFS_ADD_DELAYED_REF) {
2361                 ret = __btrfs_inc_extent_ref(trans, fs_info, node,
2362                                              parent, ref_root,
2363                                              ref->level, 0, 1,
2364                                              extent_op);
2365         } else if (node->action == BTRFS_DROP_DELAYED_REF) {
2366                 ret = __btrfs_free_extent(trans, fs_info, node,
2367                                           parent, ref_root,
2368                                           ref->level, 0, 1, extent_op);
2369         } else {
2370                 BUG();
2371         }
2372         return ret;
2373 }
2374
2375 /* helper function to actually process a single delayed ref entry */
2376 static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2377                                struct btrfs_fs_info *fs_info,
2378                                struct btrfs_delayed_ref_node *node,
2379                                struct btrfs_delayed_extent_op *extent_op,
2380                                int insert_reserved)
2381 {
2382         int ret = 0;
2383
2384         if (trans->aborted) {
2385                 if (insert_reserved)
2386                         btrfs_pin_extent(fs_info, node->bytenr,
2387                                          node->num_bytes, 1);
2388                 return 0;
2389         }
2390
2391         if (btrfs_delayed_ref_is_head(node)) {
2392                 struct btrfs_delayed_ref_head *head;
2393                 /*
2394                  * we've hit the end of the chain and we were supposed
2395                  * to insert this extent into the tree.  But, it got
2396                  * deleted before we ever needed to insert it, so all
2397                  * we have to do is clean up the accounting
2398                  */
2399                 BUG_ON(extent_op);
2400                 head = btrfs_delayed_node_to_head(node);
2401                 trace_run_delayed_ref_head(fs_info, node, head, node->action);
2402
2403                 if (insert_reserved) {
2404                         btrfs_pin_extent(fs_info, node->bytenr,
2405                                          node->num_bytes, 1);
2406                         if (head->is_data) {
2407                                 ret = btrfs_del_csums(trans, fs_info,
2408                                                       node->bytenr,
2409                                                       node->num_bytes);
2410                         }
2411                 }
2412
2413                 /* Also free its reserved qgroup space */
2414                 btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
2415                                               head->qgroup_reserved);
2416                 return ret;
2417         }
2418
2419         if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2420             node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2421                 ret = run_delayed_tree_ref(trans, fs_info, node, extent_op,
2422                                            insert_reserved);
2423         else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2424                  node->type == BTRFS_SHARED_DATA_REF_KEY)
2425                 ret = run_delayed_data_ref(trans, fs_info, node, extent_op,
2426                                            insert_reserved);
2427         else
2428                 BUG();
2429         return ret;
2430 }
2431
2432 static inline struct btrfs_delayed_ref_node *
2433 select_delayed_ref(struct btrfs_delayed_ref_head *head)
2434 {
2435         struct btrfs_delayed_ref_node *ref;
2436
2437         if (list_empty(&head->ref_list))
2438                 return NULL;
2439
2440         /*
2441          * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2442          * This is to prevent a ref count from going down to zero, which deletes
2443          * the extent item from the extent tree, when there still are references
2444          * to add, which would fail because they would not find the extent item.
2445          */
2446         if (!list_empty(&head->ref_add_list))
2447                 return list_first_entry(&head->ref_add_list,
2448                                 struct btrfs_delayed_ref_node, add_list);
2449
2450         ref = list_first_entry(&head->ref_list, struct btrfs_delayed_ref_node,
2451                                list);
2452         ASSERT(list_empty(&ref->add_list));
2453         return ref;
2454 }
2455
2456 /*
2457  * Returns 0 on success or if called with an already aborted transaction.
2458  * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2459  */
2460 static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2461                                              struct btrfs_fs_info *fs_info,
2462                                              unsigned long nr)
2463 {
2464         struct btrfs_delayed_ref_root *delayed_refs;
2465         struct btrfs_delayed_ref_node *ref;
2466         struct btrfs_delayed_ref_head *locked_ref = NULL;
2467         struct btrfs_delayed_extent_op *extent_op;
2468         ktime_t start = ktime_get();
2469         int ret;
2470         unsigned long count = 0;
2471         unsigned long actual_count = 0;
2472         int must_insert_reserved = 0;
2473
2474         delayed_refs = &trans->transaction->delayed_refs;
2475         while (1) {
2476                 if (!locked_ref) {
2477                         if (count >= nr)
2478                                 break;
2479
2480                         spin_lock(&delayed_refs->lock);
2481                         locked_ref = btrfs_select_ref_head(trans);
2482                         if (!locked_ref) {
2483                                 spin_unlock(&delayed_refs->lock);
2484                                 break;
2485                         }
2486
2487                         /* grab the lock that says we are going to process
2488                          * all the refs for this head */
2489                         ret = btrfs_delayed_ref_lock(trans, locked_ref);
2490                         spin_unlock(&delayed_refs->lock);
2491                         /*
2492                          * we may have dropped the spin lock to get the head
2493                          * mutex lock, and that might have given someone else
2494                          * time to free the head.  If that's true, it has been
2495                          * removed from our list and we can move on.
2496                          */
2497                         if (ret == -EAGAIN) {
2498                                 locked_ref = NULL;
2499                                 count++;
2500                                 continue;
2501                         }
2502                 }
2503
2504                 /*
2505                  * We need to try and merge add/drops of the same ref since we
2506                  * can run into issues with relocate dropping the implicit ref
2507                  * and then it being added back again before the drop can
2508                  * finish.  If we merged anything we need to re-loop so we can
2509                  * get a good ref.
2510                  * Or we can get node references of the same type that weren't
2511                  * merged when created due to bumps in the tree mod seq, and
2512                  * we need to merge them to prevent adding an inline extent
2513                  * backref before dropping it (triggering a BUG_ON at
2514                  * insert_inline_extent_backref()).
2515                  */
2516                 spin_lock(&locked_ref->lock);
2517                 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2518                                          locked_ref);
2519
2520                 /*
2521                  * locked_ref is the head node, so we have to go one
2522                  * node back for any delayed ref updates
2523                  */
2524                 ref = select_delayed_ref(locked_ref);
2525
2526                 if (ref && ref->seq &&
2527                     btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
2528                         spin_unlock(&locked_ref->lock);
2529                         spin_lock(&delayed_refs->lock);
2530                         locked_ref->processing = 0;
2531                         delayed_refs->num_heads_ready++;
2532                         spin_unlock(&delayed_refs->lock);
2533                         btrfs_delayed_ref_unlock(locked_ref);
2534                         locked_ref = NULL;
2535                         cond_resched();
2536                         count++;
2537                         continue;
2538                 }
2539
2540                 /*
2541                  * record the must insert reserved flag before we
2542                  * drop the spin lock.
2543                  */
2544                 must_insert_reserved = locked_ref->must_insert_reserved;
2545                 locked_ref->must_insert_reserved = 0;
2546
2547                 extent_op = locked_ref->extent_op;
2548                 locked_ref->extent_op = NULL;
2549
2550                 if (!ref) {
2551
2552
2553                         /* All delayed refs have been processed, Go ahead
2554                          * and send the head node to run_one_delayed_ref,
2555                          * so that any accounting fixes can happen
2556                          */
2557                         ref = &locked_ref->node;
2558
2559                         if (extent_op && must_insert_reserved) {
2560                                 btrfs_free_delayed_extent_op(extent_op);
2561                                 extent_op = NULL;
2562                         }
2563
2564                         if (extent_op) {
2565                                 spin_unlock(&locked_ref->lock);
2566                                 ret = run_delayed_extent_op(trans, fs_info,
2567                                                             ref, extent_op);
2568                                 btrfs_free_delayed_extent_op(extent_op);
2569
2570                                 if (ret) {
2571                                         /*
2572                                          * Need to reset must_insert_reserved if
2573                                          * there was an error so the abort stuff
2574                                          * can cleanup the reserved space
2575                                          * properly.
2576                                          */
2577                                         if (must_insert_reserved)
2578                                                 locked_ref->must_insert_reserved = 1;
2579                                         spin_lock(&delayed_refs->lock);
2580                                         locked_ref->processing = 0;
2581                                         delayed_refs->num_heads_ready++;
2582                                         spin_unlock(&delayed_refs->lock);
2583                                         btrfs_debug(fs_info,
2584                                                     "run_delayed_extent_op returned %d",
2585                                                     ret);
2586                                         btrfs_delayed_ref_unlock(locked_ref);
2587                                         return ret;
2588                                 }
2589                                 continue;
2590                         }
2591
2592                         /*
2593                          * Need to drop our head ref lock and re-acquire the
2594                          * delayed ref lock and then re-check to make sure
2595                          * nobody got added.
2596                          */
2597                         spin_unlock(&locked_ref->lock);
2598                         spin_lock(&delayed_refs->lock);
2599                         spin_lock(&locked_ref->lock);
2600                         if (!list_empty(&locked_ref->ref_list) ||
2601                             locked_ref->extent_op) {
2602                                 spin_unlock(&locked_ref->lock);
2603                                 spin_unlock(&delayed_refs->lock);
2604                                 continue;
2605                         }
2606                         ref->in_tree = 0;
2607                         delayed_refs->num_heads--;
2608                         rb_erase(&locked_ref->href_node,
2609                                  &delayed_refs->href_root);
2610                         spin_unlock(&delayed_refs->lock);
2611                 } else {
2612                         actual_count++;
2613                         ref->in_tree = 0;
2614                         list_del(&ref->list);
2615                         if (!list_empty(&ref->add_list))
2616                                 list_del(&ref->add_list);
2617                 }
2618                 atomic_dec(&delayed_refs->num_entries);
2619
2620                 if (!btrfs_delayed_ref_is_head(ref)) {
2621                         /*
2622                          * when we play the delayed ref, also correct the
2623                          * ref_mod on head
2624                          */
2625                         switch (ref->action) {
2626                         case BTRFS_ADD_DELAYED_REF:
2627                         case BTRFS_ADD_DELAYED_EXTENT:
2628                                 locked_ref->node.ref_mod -= ref->ref_mod;
2629                                 break;
2630                         case BTRFS_DROP_DELAYED_REF:
2631                                 locked_ref->node.ref_mod += ref->ref_mod;
2632                                 break;
2633                         default:
2634                                 WARN_ON(1);
2635                         }
2636                 }
2637                 spin_unlock(&locked_ref->lock);
2638
2639                 ret = run_one_delayed_ref(trans, fs_info, ref, extent_op,
2640                                           must_insert_reserved);
2641
2642                 btrfs_free_delayed_extent_op(extent_op);
2643                 if (ret) {
2644                         spin_lock(&delayed_refs->lock);
2645                         locked_ref->processing = 0;
2646                         delayed_refs->num_heads_ready++;
2647                         spin_unlock(&delayed_refs->lock);
2648                         btrfs_delayed_ref_unlock(locked_ref);
2649                         btrfs_put_delayed_ref(ref);
2650                         btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
2651                                     ret);
2652                         return ret;
2653                 }
2654
2655                 /*
2656                  * If this node is a head, that means all the refs in this head
2657                  * have been dealt with, and we will pick the next head to deal
2658                  * with, so we must unlock the head and drop it from the cluster
2659                  * list before we release it.
2660                  */
2661                 if (btrfs_delayed_ref_is_head(ref)) {
2662                         if (locked_ref->is_data &&
2663                             locked_ref->total_ref_mod < 0) {
2664                                 spin_lock(&delayed_refs->lock);
2665                                 delayed_refs->pending_csums -= ref->num_bytes;
2666                                 spin_unlock(&delayed_refs->lock);
2667                         }
2668                         btrfs_delayed_ref_unlock(locked_ref);
2669                         locked_ref = NULL;
2670                 }
2671                 btrfs_put_delayed_ref(ref);
2672                 count++;
2673                 cond_resched();
2674         }
2675
2676         /*
2677          * We don't want to include ref heads since we can have empty ref heads
2678          * and those will drastically skew our runtime down since we just do
2679          * accounting, no actual extent tree updates.
2680          */
2681         if (actual_count > 0) {
2682                 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2683                 u64 avg;
2684
2685                 /*
2686                  * We weigh the current average higher than our current runtime
2687                  * to avoid large swings in the average.
2688                  */
2689                 spin_lock(&delayed_refs->lock);
2690                 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
2691                 fs_info->avg_delayed_ref_runtime = avg >> 2;    /* div by 4 */
2692                 spin_unlock(&delayed_refs->lock);
2693         }
2694         return 0;
2695 }
2696
2697 #ifdef SCRAMBLE_DELAYED_REFS
2698 /*
2699  * Normally delayed refs get processed in ascending bytenr order. This
2700  * correlates in most cases to the order added. To expose dependencies on this
2701  * order, we start to process the tree in the middle instead of the beginning
2702  */
2703 static u64 find_middle(struct rb_root *root)
2704 {
2705         struct rb_node *n = root->rb_node;
2706         struct btrfs_delayed_ref_node *entry;
2707         int alt = 1;
2708         u64 middle;
2709         u64 first = 0, last = 0;
2710
2711         n = rb_first(root);
2712         if (n) {
2713                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2714                 first = entry->bytenr;
2715         }
2716         n = rb_last(root);
2717         if (n) {
2718                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2719                 last = entry->bytenr;
2720         }
2721         n = root->rb_node;
2722
2723         while (n) {
2724                 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2725                 WARN_ON(!entry->in_tree);
2726
2727                 middle = entry->bytenr;
2728
2729                 if (alt)
2730                         n = n->rb_left;
2731                 else
2732                         n = n->rb_right;
2733
2734                 alt = 1 - alt;
2735         }
2736         return middle;
2737 }
2738 #endif
2739
2740 static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
2741 {
2742         u64 num_bytes;
2743
2744         num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2745                              sizeof(struct btrfs_extent_inline_ref));
2746         if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
2747                 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2748
2749         /*
2750          * We don't ever fill up leaves all the way so multiply by 2 just to be
2751          * closer to what we're really going to want to use.
2752          */
2753         return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
2754 }
2755
2756 /*
2757  * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2758  * would require to store the csums for that many bytes.
2759  */
2760 u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
2761 {
2762         u64 csum_size;
2763         u64 num_csums_per_leaf;
2764         u64 num_csums;
2765
2766         csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
2767         num_csums_per_leaf = div64_u64(csum_size,
2768                         (u64)btrfs_super_csum_size(fs_info->super_copy));
2769         num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
2770         num_csums += num_csums_per_leaf - 1;
2771         num_csums = div64_u64(num_csums, num_csums_per_leaf);
2772         return num_csums;
2773 }
2774
2775 int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
2776                                        struct btrfs_fs_info *fs_info)
2777 {
2778         struct btrfs_block_rsv *global_rsv;
2779         u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
2780         u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
2781         u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
2782         u64 num_bytes, num_dirty_bgs_bytes;
2783         int ret = 0;
2784
2785         num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
2786         num_heads = heads_to_leaves(fs_info, num_heads);
2787         if (num_heads > 1)
2788                 num_bytes += (num_heads - 1) * fs_info->nodesize;
2789         num_bytes <<= 1;
2790         num_bytes += btrfs_csum_bytes_to_leaves(fs_info, csum_bytes) *
2791                                                         fs_info->nodesize;
2792         num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
2793                                                              num_dirty_bgs);
2794         global_rsv = &fs_info->global_block_rsv;
2795
2796         /*
2797          * If we can't allocate any more chunks lets make sure we have _lots_ of
2798          * wiggle room since running delayed refs can create more delayed refs.
2799          */
2800         if (global_rsv->space_info->full) {
2801                 num_dirty_bgs_bytes <<= 1;
2802                 num_bytes <<= 1;
2803         }
2804
2805         spin_lock(&global_rsv->lock);
2806         if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
2807                 ret = 1;
2808         spin_unlock(&global_rsv->lock);
2809         return ret;
2810 }
2811
2812 int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2813                                        struct btrfs_fs_info *fs_info)
2814 {
2815         u64 num_entries =
2816                 atomic_read(&trans->transaction->delayed_refs.num_entries);
2817         u64 avg_runtime;
2818         u64 val;
2819
2820         smp_mb();
2821         avg_runtime = fs_info->avg_delayed_ref_runtime;
2822         val = num_entries * avg_runtime;
2823         if (val >= NSEC_PER_SEC)
2824                 return 1;
2825         if (val >= NSEC_PER_SEC / 2)
2826                 return 2;
2827
2828         return btrfs_check_space_for_delayed_refs(trans, fs_info);
2829 }
2830
2831 struct async_delayed_refs {
2832         struct btrfs_root *root;
2833         u64 transid;
2834         int count;
2835         int error;
2836         int sync;
2837         struct completion wait;
2838         struct btrfs_work work;
2839 };
2840
2841 static inline struct async_delayed_refs *
2842 to_async_delayed_refs(struct btrfs_work *work)
2843 {
2844         return container_of(work, struct async_delayed_refs, work);
2845 }
2846
2847 static void delayed_ref_async_start(struct btrfs_work *work)
2848 {
2849         struct async_delayed_refs *async = to_async_delayed_refs(work);
2850         struct btrfs_trans_handle *trans;
2851         struct btrfs_fs_info *fs_info = async->root->fs_info;
2852         int ret;
2853
2854         /* if the commit is already started, we don't need to wait here */
2855         if (btrfs_transaction_blocked(fs_info))
2856                 goto done;
2857
2858         trans = btrfs_join_transaction(async->root);
2859         if (IS_ERR(trans)) {
2860                 async->error = PTR_ERR(trans);
2861                 goto done;
2862         }
2863
2864         /*
2865          * trans->sync means that when we call end_transaction, we won't
2866          * wait on delayed refs
2867          */
2868         trans->sync = true;
2869
2870         /* Don't bother flushing if we got into a different transaction */
2871         if (trans->transid > async->transid)
2872                 goto end;
2873
2874         ret = btrfs_run_delayed_refs(trans, fs_info, async->count);
2875         if (ret)
2876                 async->error = ret;
2877 end:
2878         ret = btrfs_end_transaction(trans);
2879         if (ret && !async->error)
2880                 async->error = ret;
2881 done:
2882         if (async->sync)
2883                 complete(&async->wait);
2884         else
2885                 kfree(async);
2886 }
2887
2888 int btrfs_async_run_delayed_refs(struct btrfs_fs_info *fs_info,
2889                                  unsigned long count, u64 transid, int wait)
2890 {
2891         struct async_delayed_refs *async;
2892         int ret;
2893
2894         async = kmalloc(sizeof(*async), GFP_NOFS);
2895         if (!async)
2896                 return -ENOMEM;
2897
2898         async->root = fs_info->tree_root;
2899         async->count = count;
2900         async->error = 0;
2901         async->transid = transid;
2902         if (wait)
2903                 async->sync = 1;
2904         else
2905                 async->sync = 0;
2906         init_completion(&async->wait);
2907
2908         btrfs_init_work(&async->work, btrfs_extent_refs_helper,
2909                         delayed_ref_async_start, NULL, NULL);
2910
2911         btrfs_queue_work(fs_info->extent_workers, &async->work);
2912
2913         if (wait) {
2914                 wait_for_completion(&async->wait);
2915                 ret = async->error;
2916                 kfree(async);
2917                 return ret;
2918         }
2919         return 0;
2920 }
2921
2922 /*
2923  * this starts processing the delayed reference count updates and
2924  * extent insertions we have queued up so far.  count can be
2925  * 0, which means to process everything in the tree at the start
2926  * of the run (but not newly added entries), or it can be some target
2927  * number you'd like to process.
2928  *
2929  * Returns 0 on success or if called with an aborted transaction
2930  * Returns <0 on error and aborts the transaction
2931  */
2932 int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2933                            struct btrfs_fs_info *fs_info, unsigned long count)
2934 {
2935         struct rb_node *node;
2936         struct btrfs_delayed_ref_root *delayed_refs;
2937         struct btrfs_delayed_ref_head *head;
2938         int ret;
2939         int run_all = count == (unsigned long)-1;
2940         bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
2941
2942         /* We'll clean this up in btrfs_cleanup_transaction */
2943         if (trans->aborted)
2944                 return 0;
2945
2946         if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
2947                 return 0;
2948
2949         delayed_refs = &trans->transaction->delayed_refs;
2950         if (count == 0)
2951                 count = atomic_read(&delayed_refs->num_entries) * 2;
2952
2953 again:
2954 #ifdef SCRAMBLE_DELAYED_REFS
2955         delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2956 #endif
2957         trans->can_flush_pending_bgs = false;
2958         ret = __btrfs_run_delayed_refs(trans, fs_info, count);
2959         if (ret < 0) {
2960                 btrfs_abort_transaction(trans, ret);
2961                 return ret;
2962         }
2963
2964         if (run_all) {
2965                 if (!list_empty(&trans->new_bgs))
2966                         btrfs_create_pending_block_groups(trans, fs_info);
2967
2968                 spin_lock(&delayed_refs->lock);
2969                 node = rb_first(&delayed_refs->href_root);
2970                 if (!node) {
2971                         spin_unlock(&delayed_refs->lock);
2972                         goto out;
2973                 }
2974
2975                 while (node) {
2976                         head = rb_entry(node, struct btrfs_delayed_ref_head,
2977                                         href_node);
2978                         if (btrfs_delayed_ref_is_head(&head->node)) {
2979                                 struct btrfs_delayed_ref_node *ref;
2980
2981                                 ref = &head->node;
2982                                 atomic_inc(&ref->refs);
2983
2984                                 spin_unlock(&delayed_refs->lock);
2985                                 /*
2986                                  * Mutex was contended, block until it's
2987                                  * released and try again
2988                                  */
2989                                 mutex_lock(&head->mutex);
2990                                 mutex_unlock(&head->mutex);
2991
2992                                 btrfs_put_delayed_ref(ref);
2993                                 cond_resched();
2994                                 goto again;
2995                         } else {
2996                                 WARN_ON(1);
2997                         }
2998                         node = rb_next(node);
2999                 }
3000                 spin_unlock(&delayed_refs->lock);
3001                 cond_resched();
3002                 goto again;
3003         }
3004 out:
3005         assert_qgroups_uptodate(trans);
3006         trans->can_flush_pending_bgs = can_flush_pending_bgs;
3007         return 0;
3008 }
3009
3010 int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
3011                                 struct btrfs_fs_info *fs_info,
3012                                 u64 bytenr, u64 num_bytes, u64 flags,
3013                                 int level, int is_data)
3014 {
3015         struct btrfs_delayed_extent_op *extent_op;
3016         int ret;
3017
3018         extent_op = btrfs_alloc_delayed_extent_op();
3019         if (!extent_op)
3020                 return -ENOMEM;
3021
3022         extent_op->flags_to_set = flags;
3023         extent_op->update_flags = true;
3024         extent_op->update_key = false;
3025         extent_op->is_data = is_data ? true : false;
3026         extent_op->level = level;
3027
3028         ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
3029                                           num_bytes, extent_op);
3030         if (ret)
3031                 btrfs_free_delayed_extent_op(extent_op);
3032         return ret;
3033 }
3034
3035 static noinline int check_delayed_ref(struct btrfs_root *root,
3036                                       struct btrfs_path *path,
3037                                       u64 objectid, u64 offset, u64 bytenr)
3038 {
3039         struct btrfs_delayed_ref_head *head;
3040         struct btrfs_delayed_ref_node *ref;
3041         struct btrfs_delayed_data_ref *data_ref;
3042         struct btrfs_delayed_ref_root *delayed_refs;
3043         struct btrfs_transaction *cur_trans;
3044         int ret = 0;
3045
3046         cur_trans = root->fs_info->running_transaction;
3047         if (!cur_trans)
3048                 return 0;
3049
3050         delayed_refs = &cur_trans->delayed_refs;
3051         spin_lock(&delayed_refs->lock);
3052         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
3053         if (!head) {
3054                 spin_unlock(&delayed_refs->lock);
3055                 return 0;
3056         }
3057
3058         if (!mutex_trylock(&head->mutex)) {
3059                 atomic_inc(&head->node.refs);
3060                 spin_unlock(&delayed_refs->lock);
3061
3062                 btrfs_release_path(path);
3063
3064                 /*
3065                  * Mutex was contended, block until it's released and let
3066                  * caller try again
3067                  */
3068                 mutex_lock(&head->mutex);
3069                 mutex_unlock(&head->mutex);
3070                 btrfs_put_delayed_ref(&head->node);
3071                 return -EAGAIN;
3072         }
3073         spin_unlock(&delayed_refs->lock);
3074
3075         spin_lock(&head->lock);
3076         list_for_each_entry(ref, &head->ref_list, list) {
3077                 /* If it's a shared ref we know a cross reference exists */
3078                 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3079                         ret = 1;
3080                         break;
3081                 }
3082
3083                 data_ref = btrfs_delayed_node_to_data_ref(ref);
3084
3085                 /*
3086                  * If our ref doesn't match the one we're currently looking at
3087                  * then we have a cross reference.
3088                  */
3089                 if (data_ref->root != root->root_key.objectid ||
3090                     data_ref->objectid != objectid ||
3091                     data_ref->offset != offset) {
3092                         ret = 1;
3093                         break;
3094                 }
3095         }
3096         spin_unlock(&head->lock);
3097         mutex_unlock(&head->mutex);
3098         return ret;
3099 }
3100
3101 static noinline int check_committed_ref(struct btrfs_root *root,
3102                                         struct btrfs_path *path,
3103                                         u64 objectid, u64 offset, u64 bytenr)
3104 {
3105         struct btrfs_fs_info *fs_info = root->fs_info;
3106         struct btrfs_root *extent_root = fs_info->extent_root;
3107         struct extent_buffer *leaf;
3108         struct btrfs_extent_data_ref *ref;
3109         struct btrfs_extent_inline_ref *iref;
3110         struct btrfs_extent_item *ei;
3111         struct btrfs_key key;
3112         u32 item_size;
3113         int ret;
3114
3115         key.objectid = bytenr;
3116         key.offset = (u64)-1;
3117         key.type = BTRFS_EXTENT_ITEM_KEY;
3118
3119         ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3120         if (ret < 0)
3121                 goto out;
3122         BUG_ON(ret == 0); /* Corruption */
3123
3124         ret = -ENOENT;
3125         if (path->slots[0] == 0)
3126                 goto out;
3127
3128         path->slots[0]--;
3129         leaf = path->nodes[0];
3130         btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3131
3132         if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
3133                 goto out;
3134
3135         ret = 1;
3136         item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3137 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3138         if (item_size < sizeof(*ei)) {
3139                 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
3140                 goto out;
3141         }
3142 #endif
3143         ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
3144
3145         if (item_size != sizeof(*ei) +
3146             btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3147                 goto out;
3148
3149         if (btrfs_extent_generation(leaf, ei) <=
3150             btrfs_root_last_snapshot(&root->root_item))
3151                 goto out;
3152
3153         iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3154         if (btrfs_extent_inline_ref_type(leaf, iref) !=
3155             BTRFS_EXTENT_DATA_REF_KEY)
3156                 goto out;
3157
3158         ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3159         if (btrfs_extent_refs(leaf, ei) !=
3160             btrfs_extent_data_ref_count(leaf, ref) ||
3161             btrfs_extent_data_ref_root(leaf, ref) !=
3162             root->root_key.objectid ||
3163             btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3164             btrfs_extent_data_ref_offset(leaf, ref) != offset)
3165                 goto out;
3166
3167         ret = 0;
3168 out:
3169         return ret;
3170 }
3171
3172 int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
3173                           u64 bytenr)
3174 {
3175         struct btrfs_path *path;
3176         int ret;
3177         int ret2;
3178
3179         path = btrfs_alloc_path();
3180         if (!path)
3181                 return -ENOENT;
3182
3183         do {
3184                 ret = check_committed_ref(root, path, objectid,
3185                                           offset, bytenr);
3186                 if (ret && ret != -ENOENT)
3187                         goto out;
3188
3189                 ret2 = check_delayed_ref(root, path, objectid,
3190                                          offset, bytenr);
3191         } while (ret2 == -EAGAIN);
3192
3193         if (ret2 && ret2 != -ENOENT) {
3194                 ret = ret2;
3195                 goto out;
3196         }
3197
3198         if (ret != -ENOENT || ret2 != -ENOENT)
3199                 ret = 0;
3200 out:
3201         btrfs_free_path(path);
3202         if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3203                 WARN_ON(ret > 0);
3204         return ret;
3205 }
3206
3207 static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
3208                            struct btrfs_root *root,
3209                            struct extent_buffer *buf,
3210                            int full_backref, int inc)
3211 {
3212         struct btrfs_fs_info *fs_info = root->fs_info;
3213         u64 bytenr;
3214         u64 num_bytes;
3215         u64 parent;
3216         u64 ref_root;
3217         u32 nritems;
3218         struct btrfs_key key;
3219         struct btrfs_file_extent_item *fi;
3220         int i;
3221         int level;
3222         int ret = 0;
3223         int (*process_func)(struct btrfs_trans_handle *,
3224                             struct btrfs_fs_info *,
3225                             u64, u64, u64, u64, u64, u64);
3226
3227
3228         if (btrfs_is_testing(fs_info))
3229                 return 0;
3230
3231         ref_root = btrfs_header_owner(buf);
3232         nritems = btrfs_header_nritems(buf);
3233         level = btrfs_header_level(buf);
3234
3235         if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
3236                 return 0;
3237
3238         if (inc)
3239                 process_func = btrfs_inc_extent_ref;
3240         else
3241                 process_func = btrfs_free_extent;
3242
3243         if (full_backref)
3244                 parent = buf->start;
3245         else
3246                 parent = 0;
3247
3248         for (i = 0; i < nritems; i++) {
3249                 if (level == 0) {
3250                         btrfs_item_key_to_cpu(buf, &key, i);
3251                         if (key.type != BTRFS_EXTENT_DATA_KEY)
3252                                 continue;
3253                         fi = btrfs_item_ptr(buf, i,
3254                                             struct btrfs_file_extent_item);
3255                         if (btrfs_file_extent_type(buf, fi) ==
3256                             BTRFS_FILE_EXTENT_INLINE)
3257                                 continue;
3258                         bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3259                         if (bytenr == 0)
3260                                 continue;
3261
3262                         num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3263                         key.offset -= btrfs_file_extent_offset(buf, fi);
3264                         ret = process_func(trans, fs_info, bytenr, num_bytes,
3265                                            parent, ref_root, key.objectid,
3266                                            key.offset);
3267                         if (ret)
3268                                 goto fail;
3269                 } else {
3270                         bytenr = btrfs_node_blockptr(buf, i);
3271                         num_bytes = fs_info->nodesize;
3272                         ret = process_func(trans, fs_info, bytenr, num_bytes,
3273                                            parent, ref_root, level - 1, 0);
3274                         if (ret)
3275                                 goto fail;
3276                 }
3277         }
3278         return 0;
3279 fail:
3280         return ret;
3281 }
3282
3283 int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3284                   struct extent_buffer *buf, int full_backref)
3285 {
3286         return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
3287 }
3288
3289 int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
3290                   struct extent_buffer *buf, int full_backref)
3291 {
3292         return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
3293 }
3294
3295 static int write_one_cache_group(struct btrfs_trans_handle *trans,
3296                                  struct btrfs_fs_info *fs_info,
3297                                  struct btrfs_path *path,
3298                                  struct btrfs_block_group_cache *cache)
3299 {
3300         int ret;
3301         struct btrfs_root *extent_root = fs_info->extent_root;
3302         unsigned long bi;
3303         struct extent_buffer *leaf;
3304
3305         ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
3306         if (ret) {
3307                 if (ret > 0)
3308                         ret = -ENOENT;
3309                 goto fail;
3310         }
3311
3312         leaf = path->nodes[0];
3313         bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3314         write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3315         btrfs_mark_buffer_dirty(leaf);
3316 fail:
3317         btrfs_release_path(path);
3318         return ret;
3319
3320 }
3321
3322 static struct btrfs_block_group_cache *
3323 next_block_group(struct btrfs_fs_info *fs_info,
3324                  struct btrfs_block_group_cache *cache)
3325 {
3326         struct rb_node *node;
3327
3328         spin_lock(&fs_info->block_group_cache_lock);
3329
3330         /* If our block group was removed, we need a full search. */
3331         if (RB_EMPTY_NODE(&cache->cache_node)) {
3332                 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3333
3334                 spin_unlock(&fs_info->block_group_cache_lock);
3335                 btrfs_put_block_group(cache);
3336                 cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
3337         }
3338         node = rb_next(&cache->cache_node);
3339         btrfs_put_block_group(cache);
3340         if (node) {
3341                 cache = rb_entry(node, struct btrfs_block_group_cache,
3342                                  cache_node);
3343                 btrfs_get_block_group(cache);
3344         } else
3345                 cache = NULL;
3346         spin_unlock(&fs_info->block_group_cache_lock);
3347         return cache;
3348 }
3349
3350 static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3351                             struct btrfs_trans_handle *trans,
3352                             struct btrfs_path *path)
3353 {
3354         struct btrfs_fs_info *fs_info = block_group->fs_info;
3355         struct btrfs_root *root = fs_info->tree_root;
3356         struct inode *inode = NULL;
3357         u64 alloc_hint = 0;
3358         int dcs = BTRFS_DC_ERROR;
3359         u64 num_pages = 0;
3360         int retries = 0;
3361         int ret = 0;
3362
3363         /*
3364          * If this block group is smaller than 100 megs don't bother caching the
3365          * block group.
3366          */
3367         if (block_group->key.offset < (100 * SZ_1M)) {
3368                 spin_lock(&block_group->lock);
3369                 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3370                 spin_unlock(&block_group->lock);
3371                 return 0;
3372         }
3373
3374         if (trans->aborted)
3375                 return 0;
3376 again:
3377         inode = lookup_free_space_inode(root, block_group, path);
3378         if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3379                 ret = PTR_ERR(inode);
3380                 btrfs_release_path(path);
3381                 goto out;
3382         }
3383
3384         if (IS_ERR(inode)) {
3385                 BUG_ON(retries);
3386                 retries++;
3387
3388                 if (block_group->ro)
3389                         goto out_free;
3390
3391                 ret = create_free_space_inode(root, trans, block_group, path);
3392                 if (ret)
3393                         goto out_free;
3394                 goto again;
3395         }
3396
3397         /* We've already setup this transaction, go ahead and exit */
3398         if (block_group->cache_generation == trans->transid &&
3399             i_size_read(inode)) {
3400                 dcs = BTRFS_DC_SETUP;
3401                 goto out_put;
3402         }
3403
3404         /*
3405          * We want to set the generation to 0, that way if anything goes wrong
3406          * from here on out we know not to trust this cache when we load up next
3407          * time.
3408          */
3409         BTRFS_I(inode)->generation = 0;
3410         ret = btrfs_update_inode(trans, root, inode);
3411         if (ret) {
3412                 /*
3413                  * So theoretically we could recover from this, simply set the
3414                  * super cache generation to 0 so we know to invalidate the
3415                  * cache, but then we'd have to keep track of the block groups
3416                  * that fail this way so we know we _have_ to reset this cache
3417                  * before the next commit or risk reading stale cache.  So to
3418                  * limit our exposure to horrible edge cases lets just abort the
3419                  * transaction, this only happens in really bad situations
3420                  * anyway.
3421                  */
3422                 btrfs_abort_transaction(trans, ret);
3423                 goto out_put;
3424         }
3425         WARN_ON(ret);
3426
3427         if (i_size_read(inode) > 0) {
3428                 ret = btrfs_check_trunc_cache_free_space(fs_info,
3429                                         &fs_info->global_block_rsv);
3430                 if (ret)
3431                         goto out_put;
3432
3433                 ret = btrfs_truncate_free_space_cache(root, trans, NULL, inode);
3434                 if (ret)
3435                         goto out_put;
3436         }
3437
3438         spin_lock(&block_group->lock);
3439         if (block_group->cached != BTRFS_CACHE_FINISHED ||
3440             !btrfs_test_opt(fs_info, SPACE_CACHE)) {
3441                 /*
3442                  * don't bother trying to write stuff out _if_
3443                  * a) we're not cached,
3444                  * b) we're with nospace_cache mount option.
3445                  */
3446                 dcs = BTRFS_DC_WRITTEN;
3447                 spin_unlock(&block_group->lock);
3448                 goto out_put;
3449         }
3450         spin_unlock(&block_group->lock);
3451
3452         /*
3453          * We hit an ENOSPC when setting up the cache in this transaction, just
3454          * skip doing the setup, we've already cleared the cache so we're safe.
3455          */
3456         if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3457                 ret = -ENOSPC;
3458                 goto out_put;
3459         }
3460
3461         /*
3462          * Try to preallocate enough space based on how big the block group is.
3463          * Keep in mind this has to include any pinned space which could end up
3464          * taking up quite a bit since it's not folded into the other space
3465          * cache.
3466          */
3467         num_pages = div_u64(block_group->key.offset, SZ_256M);
3468         if (!num_pages)
3469                 num_pages = 1;
3470
3471         num_pages *= 16;
3472         num_pages *= PAGE_SIZE;
3473
3474         ret = btrfs_check_data_free_space(inode, 0, num_pages);
3475         if (ret)
3476                 goto out_put;
3477
3478         ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3479                                               num_pages, num_pages,
3480                                               &alloc_hint);
3481         /*
3482          * Our cache requires contiguous chunks so that we don't modify a bunch
3483          * of metadata or split extents when writing the cache out, which means
3484          * we can enospc if we are heavily fragmented in addition to just normal
3485          * out of space conditions.  So if we hit this just skip setting up any
3486          * other block groups for this transaction, maybe we'll unpin enough
3487          * space the next time around.
3488          */
3489         if (!ret)
3490                 dcs = BTRFS_DC_SETUP;
3491         else if (ret == -ENOSPC)
3492                 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
3493
3494 out_put:
3495         iput(inode);
3496 out_free:
3497         btrfs_release_path(path);
3498 out:
3499         spin_lock(&block_group->lock);
3500         if (!ret && dcs == BTRFS_DC_SETUP)
3501                 block_group->cache_generation = trans->transid;
3502         block_group->disk_cache_state = dcs;
3503         spin_unlock(&block_group->lock);
3504
3505         return ret;
3506 }
3507
3508 int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
3509                             struct btrfs_fs_info *fs_info)
3510 {
3511         struct btrfs_block_group_cache *cache, *tmp;
3512         struct btrfs_transaction *cur_trans = trans->transaction;
3513         struct btrfs_path *path;
3514
3515         if (list_empty(&cur_trans->dirty_bgs) ||
3516             !btrfs_test_opt(fs_info, SPACE_CACHE))
3517                 return 0;
3518
3519         path = btrfs_alloc_path();
3520         if (!path)
3521                 return -ENOMEM;
3522
3523         /* Could add new block groups, use _safe just in case */
3524         list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3525                                  dirty_list) {
3526                 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3527                         cache_save_setup(cache, trans, path);
3528         }
3529
3530         btrfs_free_path(path);
3531         return 0;
3532 }
3533
3534 /*
3535  * transaction commit does final block group cache writeback during a
3536  * critical section where nothing is allowed to change the FS.  This is
3537  * required in order for the cache to actually match the block group,
3538  * but can introduce a lot of latency into the commit.
3539  *
3540  * So, btrfs_start_dirty_block_groups is here to kick off block group
3541  * cache IO.  There's a chance we'll have to redo some of it if the
3542  * block group changes again during the commit, but it greatly reduces
3543  * the commit latency by getting rid of the easy block groups while
3544  * we're still allowing others to join the commit.
3545  */
3546 int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
3547                                    struct btrfs_fs_info *fs_info)
3548 {
3549         struct btrfs_block_group_cache *cache;
3550         struct btrfs_transaction *cur_trans = trans->transaction;
3551         int ret = 0;
3552         int should_put;
3553         struct btrfs_path *path = NULL;
3554         LIST_HEAD(dirty);
3555         struct list_head *io = &cur_trans->io_bgs;
3556         int num_started = 0;
3557         int loops = 0;
3558
3559         spin_lock(&cur_trans->dirty_bgs_lock);
3560         if (list_empty(&cur_trans->dirty_bgs)) {
3561                 spin_unlock(&cur_trans->dirty_bgs_lock);
3562                 return 0;
3563         }
3564         list_splice_init(&cur_trans->dirty_bgs, &dirty);
3565         spin_unlock(&cur_trans->dirty_bgs_lock);
3566
3567 again:
3568         /*
3569          * make sure all the block groups on our dirty list actually
3570          * exist
3571          */
3572         btrfs_create_pending_block_groups(trans, fs_info);
3573
3574         if (!path) {
3575                 path = btrfs_alloc_path();
3576                 if (!path)
3577                         return -ENOMEM;
3578         }
3579
3580         /*
3581          * cache_write_mutex is here only to save us from balance or automatic
3582          * removal of empty block groups deleting this block group while we are
3583          * writing out the cache
3584          */
3585         mutex_lock(&trans->transaction->cache_write_mutex);
3586         while (!list_empty(&dirty)) {
3587                 cache = list_first_entry(&dirty,
3588                                          struct btrfs_block_group_cache,
3589                                          dirty_list);
3590                 /*
3591                  * this can happen if something re-dirties a block
3592                  * group that is already under IO.  Just wait for it to
3593                  * finish and then do it all again
3594                  */
3595                 if (!list_empty(&cache->io_list)) {
3596                         list_del_init(&cache->io_list);
3597                         btrfs_wait_cache_io(trans, cache, path);
3598                         btrfs_put_block_group(cache);
3599                 }
3600
3601
3602                 /*
3603                  * btrfs_wait_cache_io uses the cache->dirty_list to decide
3604                  * if it should update the cache_state.  Don't delete
3605                  * until after we wait.
3606                  *
3607                  * Since we're not running in the commit critical section
3608                  * we need the dirty_bgs_lock to protect from update_block_group
3609                  */
3610                 spin_lock(&cur_trans->dirty_bgs_lock);
3611                 list_del_init(&cache->dirty_list);
3612                 spin_unlock(&cur_trans->dirty_bgs_lock);
3613
3614                 should_put = 1;
3615
3616                 cache_save_setup(cache, trans, path);
3617
3618                 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3619                         cache->io_ctl.inode = NULL;
3620                         ret = btrfs_write_out_cache(fs_info, trans,
3621                                                     cache, path);
3622                         if (ret == 0 && cache->io_ctl.inode) {
3623                                 num_started++;
3624                                 should_put = 0;
3625
3626                                 /*
3627                                  * the cache_write_mutex is protecting
3628                                  * the io_list
3629                                  */
3630                                 list_add_tail(&cache->io_list, io);
3631                         } else {
3632                                 /*
3633                                  * if we failed to write the cache, the
3634                                  * generation will be bad and life goes on
3635                                  */
3636                                 ret = 0;
3637                         }
3638                 }
3639                 if (!ret) {
3640                         ret = write_one_cache_group(trans, fs_info,
3641                                                     path, cache);
3642                         /*
3643                          * Our block group might still be attached to the list
3644                          * of new block groups in the transaction handle of some
3645                          * other task (struct btrfs_trans_handle->new_bgs). This
3646                          * means its block group item isn't yet in the extent
3647                          * tree. If this happens ignore the error, as we will
3648                          * try again later in the critical section of the
3649                          * transaction commit.
3650                          */
3651                         if (ret == -ENOENT) {
3652                                 ret = 0;
3653                                 spin_lock(&cur_trans->dirty_bgs_lock);
3654                                 if (list_empty(&cache->dirty_list)) {
3655                                         list_add_tail(&cache->dirty_list,
3656                                                       &cur_trans->dirty_bgs);
3657                                         btrfs_get_block_group(cache);
3658                                 }
3659                                 spin_unlock(&cur_trans->dirty_bgs_lock);
3660                         } else if (ret) {
3661                                 btrfs_abort_transaction(trans, ret);
3662                         }
3663                 }
3664
3665                 /* if its not on the io list, we need to put the block group */
3666                 if (should_put)
3667                         btrfs_put_block_group(cache);
3668
3669                 if (ret)
3670                         break;
3671
3672                 /*
3673                  * Avoid blocking other tasks for too long. It might even save
3674                  * us from writing caches for block groups that are going to be
3675                  * removed.
3676                  */
3677                 mutex_unlock(&trans->transaction->cache_write_mutex);
3678                 mutex_lock(&trans->transaction->cache_write_mutex);
3679         }
3680         mutex_unlock(&trans->transaction->cache_write_mutex);
3681
3682         /*
3683          * go through delayed refs for all the stuff we've just kicked off
3684          * and then loop back (just once)
3685          */
3686         ret = btrfs_run_delayed_refs(trans, fs_info, 0);
3687         if (!ret && loops == 0) {
3688                 loops++;
3689                 spin_lock(&cur_trans->dirty_bgs_lock);
3690                 list_splice_init(&cur_trans->dirty_bgs, &dirty);
3691                 /*
3692                  * dirty_bgs_lock protects us from concurrent block group
3693                  * deletes too (not just cache_write_mutex).
3694                  */
3695                 if (!list_empty(&dirty)) {
3696                         spin_unlock(&cur_trans->dirty_bgs_lock);
3697                         goto again;
3698                 }
3699                 spin_unlock(&cur_trans->dirty_bgs_lock);
3700         } else if (ret < 0) {
3701                 btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
3702         }
3703
3704         btrfs_free_path(path);
3705         return ret;
3706 }
3707
3708 int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3709                                    struct btrfs_fs_info *fs_info)
3710 {
3711         struct btrfs_block_group_cache *cache;
3712         struct btrfs_transaction *cur_trans = trans->transaction;
3713         int ret = 0;
3714         int should_put;
3715         struct btrfs_path *path;
3716         struct list_head *io = &cur_trans->io_bgs;
3717         int num_started = 0;
3718
3719         path = btrfs_alloc_path();
3720         if (!path)
3721                 return -ENOMEM;
3722
3723         /*
3724          * Even though we are in the critical section of the transaction commit,
3725          * we can still have concurrent tasks adding elements to this
3726          * transaction's list of dirty block groups. These tasks correspond to
3727          * endio free space workers started when writeback finishes for a
3728          * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
3729          * allocate new block groups as a result of COWing nodes of the root
3730          * tree when updating the free space inode. The writeback for the space
3731          * caches is triggered by an earlier call to
3732          * btrfs_start_dirty_block_groups() and iterations of the following
3733          * loop.
3734          * Also we want to do the cache_save_setup first and then run the
3735          * delayed refs to make sure we have the best chance at doing this all
3736          * in one shot.
3737          */
3738         spin_lock(&cur_trans->dirty_bgs_lock);
3739         while (!list_empty(&cur_trans->dirty_bgs)) {
3740                 cache = list_first_entry(&cur_trans->dirty_bgs,
3741                                          struct btrfs_block_group_cache,
3742                                          dirty_list);
3743
3744                 /*
3745                  * this can happen if cache_save_setup re-dirties a block
3746                  * group that is already under IO.  Just wait for it to
3747                  * finish and then do it all again
3748                  */
3749                 if (!list_empty(&cache->io_list)) {
3750                         spin_unlock(&cur_trans->dirty_bgs_lock);
3751                         list_del_init(&cache->io_list);
3752                         btrfs_wait_cache_io(trans, cache, path);
3753                         btrfs_put_block_group(cache);
3754                         spin_lock(&cur_trans->dirty_bgs_lock);
3755                 }
3756
3757                 /*
3758                  * don't remove from the dirty list until after we've waited
3759                  * on any pending IO
3760                  */
3761                 list_del_init(&cache->dirty_list);
3762                 spin_unlock(&cur_trans->dirty_bgs_lock);
3763                 should_put = 1;
3764
3765                 cache_save_setup(cache, trans, path);
3766
3767                 if (!ret)
3768                         ret = btrfs_run_delayed_refs(trans, fs_info,
3769                                                      (unsigned long) -1);
3770
3771                 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3772                         cache->io_ctl.inode = NULL;
3773                         ret = btrfs_write_out_cache(fs_info, trans,
3774                                                     cache, path);
3775                         if (ret == 0 && cache->io_ctl.inode) {
3776                                 num_started++;
3777                                 should_put = 0;
3778                                 list_add_tail(&cache->io_list, io);
3779                         } else {
3780                                 /*
3781                                  * if we failed to write the cache, the
3782                                  * generation will be bad and life goes on
3783                                  */
3784                                 ret = 0;
3785                         }
3786                 }
3787                 if (!ret) {
3788                         ret = write_one_cache_group(trans, fs_info,
3789                                                     path, cache);
3790                         /*
3791                          * One of the free space endio workers might have
3792                          * created a new block group while updating a free space
3793                          * cache's inode (at inode.c:btrfs_finish_ordered_io())
3794                          * and hasn't released its transaction handle yet, in
3795                          * which case the new block group is still attached to
3796                          * its transaction handle and its creation has not
3797                          * finished yet (no block group item in the extent tree
3798                          * yet, etc). If this is the case, wait for all free
3799                          * space endio workers to finish and retry. This is a
3800                          * a very rare case so no need for a more efficient and
3801                          * complex approach.
3802                          */
3803                         if (ret == -ENOENT) {
3804                                 wait_event(cur_trans->writer_wait,
3805                                    atomic_read(&cur_trans->num_writers) == 1);
3806                                 ret = write_one_cache_group(trans, fs_info,
3807                                                             path, cache);
3808                         }
3809                         if (ret)
3810                                 btrfs_abort_transaction(trans, ret);
3811                 }
3812
3813                 /* if its not on the io list, we need to put the block group */
3814                 if (should_put)
3815                         btrfs_put_block_group(cache);
3816                 spin_lock(&cur_trans->dirty_bgs_lock);
3817         }
3818         spin_unlock(&cur_trans->dirty_bgs_lock);
3819
3820         while (!list_empty(io)) {
3821                 cache = list_first_entry(io, struct btrfs_block_group_cache,
3822                                          io_list);
3823                 list_del_init(&cache->io_list);
3824                 btrfs_wait_cache_io(trans, cache, path);
3825                 btrfs_put_block_group(cache);
3826         }
3827
3828         btrfs_free_path(path);
3829         return ret;
3830 }
3831
3832 int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
3833 {
3834         struct btrfs_block_group_cache *block_group;
3835         int readonly = 0;
3836
3837         block_group = btrfs_lookup_block_group(fs_info, bytenr);
3838         if (!block_group || block_group->ro)
3839                 readonly = 1;
3840         if (block_group)
3841                 btrfs_put_block_group(block_group);
3842         return readonly;
3843 }
3844
3845 bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3846 {
3847         struct btrfs_block_group_cache *bg;
3848         bool ret = true;
3849
3850         bg = btrfs_lookup_block_group(fs_info, bytenr);
3851         if (!bg)
3852                 return false;
3853
3854         spin_lock(&bg->lock);
3855         if (bg->ro)
3856                 ret = false;
3857         else
3858                 atomic_inc(&bg->nocow_writers);
3859         spin_unlock(&bg->lock);
3860
3861         /* no put on block group, done by btrfs_dec_nocow_writers */
3862         if (!ret)
3863                 btrfs_put_block_group(bg);
3864
3865         return ret;
3866
3867 }
3868
3869 void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
3870 {
3871         struct btrfs_block_group_cache *bg;
3872
3873         bg = btrfs_lookup_block_group(fs_info, bytenr);
3874         ASSERT(bg);
3875         if (atomic_dec_and_test(&bg->nocow_writers))
3876                 wake_up_atomic_t(&bg->nocow_writers);
3877         /*
3878          * Once for our lookup and once for the lookup done by a previous call
3879          * to btrfs_inc_nocow_writers()
3880          */
3881         btrfs_put_block_group(bg);
3882         btrfs_put_block_group(bg);
3883 }
3884
3885 static int btrfs_wait_nocow_writers_atomic_t(atomic_t *a)
3886 {
3887         schedule();
3888         return 0;
3889 }
3890
3891 void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
3892 {
3893         wait_on_atomic_t(&bg->nocow_writers,
3894                          btrfs_wait_nocow_writers_atomic_t,
3895                          TASK_UNINTERRUPTIBLE);
3896 }
3897
3898 static const char *alloc_name(u64 flags)
3899 {
3900         switch (flags) {
3901         case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3902                 return "mixed";
3903         case BTRFS_BLOCK_GROUP_METADATA:
3904                 return "metadata";
3905         case BTRFS_BLOCK_GROUP_DATA:
3906                 return "data";
3907         case BTRFS_BLOCK_GROUP_SYSTEM:
3908                 return "system";
3909         default:
3910                 WARN_ON(1);
3911                 return "invalid-combination";
3912         };
3913 }
3914
3915 static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3916                              u64 total_bytes, u64 bytes_used,
3917                              u64 bytes_readonly,
3918                              struct btrfs_space_info **space_info)
3919 {
3920         struct btrfs_space_info *found;
3921         int i;
3922         int factor;
3923         int ret;
3924
3925         if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3926                      BTRFS_BLOCK_GROUP_RAID10))
3927                 factor = 2;
3928         else
3929                 factor = 1;
3930
3931         found = __find_space_info(info, flags);
3932         if (found) {
3933                 spin_lock(&found->lock);
3934                 found->total_bytes += total_bytes;
3935                 found->disk_total += total_bytes * factor;
3936                 found->bytes_used += bytes_used;
3937                 found->disk_used += bytes_used * factor;
3938                 found->bytes_readonly += bytes_readonly;
3939                 if (total_bytes > 0)
3940                         found->full = 0;
3941                 space_info_add_new_bytes(info, found, total_bytes -
3942                                          bytes_used - bytes_readonly);
3943                 spin_unlock(&found->lock);
3944                 *space_info = found;
3945                 return 0;
3946         }
3947         found = kzalloc(sizeof(*found), GFP_NOFS);
3948         if (!found)
3949                 return -ENOMEM;
3950
3951         ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
3952         if (ret) {
3953                 kfree(found);
3954                 return ret;
3955         }
3956
3957         for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
3958                 INIT_LIST_HEAD(&found->block_groups[i]);
3959         init_rwsem(&found->groups_sem);
3960         spin_lock_init(&found->lock);
3961         found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
3962         found->total_bytes = total_bytes;
3963         found->disk_total = total_bytes * factor;
3964         found->bytes_used = bytes_used;
3965         found->disk_used = bytes_used * factor;
3966         found->bytes_pinned = 0;
3967         found->bytes_reserved = 0;
3968         found->bytes_readonly = bytes_readonly;
3969         found->bytes_may_use = 0;
3970         found->full = 0;
3971         found->max_extent_size = 0;
3972         found->force_alloc = CHUNK_ALLOC_NO_FORCE;
3973         found->chunk_alloc = 0;
3974         found->flush = 0;
3975         init_waitqueue_head(&found->wait);
3976         INIT_LIST_HEAD(&found->ro_bgs);
3977         INIT_LIST_HEAD(&found->tickets);
3978         INIT_LIST_HEAD(&found->priority_tickets);
3979
3980         ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
3981                                     info->space_info_kobj, "%s",
3982                                     alloc_name(found->flags));
3983         if (ret) {
3984                 kfree(found);
3985                 return ret;
3986         }
3987
3988         *space_info = found;
3989         list_add_rcu(&found->list, &info->space_info);
3990         if (flags & BTRFS_BLOCK_GROUP_DATA)
3991                 info->data_sinfo = found;
3992
3993         return ret;
3994 }
3995
3996 static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3997 {
3998         u64 extra_flags = chunk_to_extended(flags) &
3999                                 BTRFS_EXTENDED_PROFILE_MASK;
4000
4001         write_seqlock(&fs_info->profiles_lock);
4002         if (flags & BTRFS_BLOCK_GROUP_DATA)
4003                 fs_info->avail_data_alloc_bits |= extra_flags;
4004         if (flags & BTRFS_BLOCK_GROUP_METADATA)
4005                 fs_info->avail_metadata_alloc_bits |= extra_flags;
4006         if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4007                 fs_info->avail_system_alloc_bits |= extra_flags;
4008         write_sequnlock(&fs_info->profiles_lock);
4009 }
4010
4011 /*
4012  * returns target flags in extended format or 0 if restripe for this
4013  * chunk_type is not in progress
4014  *
4015  * should be called with either volume_mutex or balance_lock held
4016  */
4017 static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
4018 {
4019         struct btrfs_balance_control *bctl = fs_info->balance_ctl;
4020         u64 target = 0;
4021
4022         if (!bctl)
4023                 return 0;
4024
4025         if (flags & BTRFS_BLOCK_GROUP_DATA &&
4026             bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4027                 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
4028         } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
4029                    bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4030                 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
4031         } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
4032                    bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
4033                 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
4034         }
4035
4036         return target;
4037 }
4038
4039 /*
4040  * @flags: available profiles in extended format (see ctree.h)
4041  *
4042  * Returns reduced profile in chunk format.  If profile changing is in
4043  * progress (either running or paused) picks the target profile (if it's
4044  * already available), otherwise falls back to plain reducing.
4045  */
4046 static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
4047 {
4048         u64 num_devices = fs_info->fs_devices->rw_devices;
4049         u64 target;
4050         u64 raid_type;
4051         u64 allowed = 0;
4052
4053         /*
4054          * see if restripe for this chunk_type is in progress, if so
4055          * try to reduce to the target profile
4056          */
4057         spin_lock(&fs_info->balance_lock);
4058         target = get_restripe_target(fs_info, flags);
4059         if (target) {
4060                 /* pick target profile only if it's already available */
4061                 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
4062                         spin_unlock(&fs_info->balance_lock);
4063                         return extended_to_chunk(target);
4064                 }
4065         }
4066         spin_unlock(&fs_info->balance_lock);
4067
4068         /* First, mask out the RAID levels which aren't possible */
4069         for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
4070                 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
4071                         allowed |= btrfs_raid_group[raid_type];
4072         }
4073         allowed &= flags;
4074
4075         if (allowed & BTRFS_BLOCK_GROUP_RAID6)
4076                 allowed = BTRFS_BLOCK_GROUP_RAID6;
4077         else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
4078                 allowed = BTRFS_BLOCK_GROUP_RAID5;
4079         else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
4080                 allowed = BTRFS_BLOCK_GROUP_RAID10;
4081         else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
4082                 allowed = BTRFS_BLOCK_GROUP_RAID1;
4083         else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
4084                 allowed = BTRFS_BLOCK_GROUP_RAID0;
4085
4086         flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
4087
4088         return extended_to_chunk(flags | allowed);
4089 }
4090
4091 static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
4092 {
4093         unsigned seq;
4094         u64 flags;
4095
4096         do {
4097                 flags = orig_flags;
4098                 seq = read_seqbegin(&fs_info->profiles_lock);
4099
4100                 if (flags & BTRFS_BLOCK_GROUP_DATA)
4101                         flags |= fs_info->avail_data_alloc_bits;
4102                 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
4103                         flags |= fs_info->avail_system_alloc_bits;
4104                 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
4105                         flags |= fs_info->avail_metadata_alloc_bits;
4106         } while (read_seqretry(&fs_info->profiles_lock, seq));
4107
4108         return btrfs_reduce_alloc_profile(fs_info, flags);
4109 }
4110
4111 u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
4112 {
4113         struct btrfs_fs_info *fs_info = root->fs_info;
4114         u64 flags;
4115         u64 ret;
4116
4117         if (data)
4118                 flags = BTRFS_BLOCK_GROUP_DATA;
4119         else if (root == fs_info->chunk_root)
4120                 flags = BTRFS_BLOCK_GROUP_SYSTEM;
4121         else
4122                 flags = BTRFS_BLOCK_GROUP_METADATA;
4123
4124         ret = get_alloc_profile(fs_info, flags);
4125         return ret;
4126 }
4127
4128 static u64 btrfs_space_info_used(struct btrfs_space_info *s_info,
4129                                  bool may_use_included)
4130 {
4131         ASSERT(s_info);
4132         return s_info->bytes_used + s_info->bytes_reserved +
4133                 s_info->bytes_pinned + s_info->bytes_readonly +
4134                 (may_use_included ? s_info->bytes_may_use : 0);
4135 }
4136
4137 int btrfs_alloc_data_chunk_ondemand(struct inode *inode, u64 bytes)
4138 {
4139         struct btrfs_space_info *data_sinfo;
4140         struct btrfs_root *root = BTRFS_I(inode)->root;
4141         struct btrfs_fs_info *fs_info = root->fs_info;
4142         u64 used;
4143         int ret = 0;
4144         int need_commit = 2;
4145         int have_pinned_space;
4146
4147         /* make sure bytes are sectorsize aligned */
4148         bytes = ALIGN(bytes, fs_info->sectorsize);
4149
4150         if (btrfs_is_free_space_inode(inode)) {
4151                 need_commit = 0;
4152                 ASSERT(current->journal_info);
4153         }
4154
4155         data_sinfo = fs_info->data_sinfo;
4156         if (!data_sinfo)
4157                 goto alloc;
4158
4159 again:
4160         /* make sure we have enough space to handle the data first */
4161         spin_lock(&data_sinfo->lock);
4162         used = btrfs_space_info_used(data_sinfo, true);
4163
4164         if (used + bytes > data_sinfo->total_bytes) {
4165                 struct btrfs_trans_handle *trans;
4166
4167                 /*
4168                  * if we don't have enough free bytes in this space then we need
4169                  * to alloc a new chunk.
4170                  */
4171                 if (!data_sinfo->full) {
4172                         u64 alloc_target;
4173
4174                         data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
4175                         spin_unlock(&data_sinfo->lock);
4176 alloc:
4177                         alloc_target = btrfs_get_alloc_profile(root, 1);
4178                         /*
4179                          * It is ugly that we don't call nolock join
4180                          * transaction for the free space inode case here.
4181                          * But it is safe because we only do the data space
4182                          * reservation for the free space cache in the
4183                          * transaction context, the common join transaction
4184                          * just increase the counter of the current transaction
4185                          * handler, doesn't try to acquire the trans_lock of
4186                          * the fs.
4187                          */
4188                         trans = btrfs_join_transaction(root);
4189                         if (IS_ERR(trans))
4190                                 return PTR_ERR(trans);
4191
4192                         ret = do_chunk_alloc(trans, fs_info, alloc_target,
4193                                              CHUNK_ALLOC_NO_FORCE);
4194                         btrfs_end_transaction(trans);
4195                         if (ret < 0) {
4196                                 if (ret != -ENOSPC)
4197                                         return ret;
4198                                 else {
4199                                         have_pinned_space = 1;
4200                                         goto commit_trans;
4201                                 }
4202                         }
4203
4204                         if (!data_sinfo)
4205                                 data_sinfo = fs_info->data_sinfo;
4206
4207                         goto again;
4208                 }
4209
4210                 /*
4211                  * If we don't have enough pinned space to deal with this
4212                  * allocation, and no removed chunk in current transaction,
4213                  * don't bother committing the transaction.
4214                  */
4215                 have_pinned_space = percpu_counter_compare(
4216                         &data_sinfo->total_bytes_pinned,
4217                         used + bytes - data_sinfo->total_bytes);
4218                 spin_unlock(&data_sinfo->lock);
4219
4220                 /* commit the current transaction and try again */
4221 commit_trans:
4222                 if (need_commit &&
4223                     !atomic_read(&fs_info->open_ioctl_trans)) {
4224                         need_commit--;
4225
4226                         if (need_commit > 0) {
4227                                 btrfs_start_delalloc_roots(fs_info, 0, -1);
4228                                 btrfs_wait_ordered_roots(fs_info, -1, 0,
4229                                                          (u64)-1);
4230                         }
4231
4232                         trans = btrfs_join_transaction(root);
4233                         if (IS_ERR(trans))
4234                                 return PTR_ERR(trans);
4235                         if (have_pinned_space >= 0 ||
4236                             test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4237                                      &trans->transaction->flags) ||
4238                             need_commit > 0) {
4239                                 ret = btrfs_commit_transaction(trans);
4240                                 if (ret)
4241                                         return ret;
4242                                 /*
4243                                  * The cleaner kthread might still be doing iput
4244                                  * operations. Wait for it to finish so that
4245                                  * more space is released.
4246                                  */
4247                                 mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
4248                                 mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
4249                                 goto again;
4250                         } else {
4251                                 btrfs_end_transaction(trans);
4252                         }
4253                 }
4254
4255                 trace_btrfs_space_reservation(fs_info,
4256                                               "space_info:enospc",
4257                                               data_sinfo->flags, bytes, 1);
4258                 return -ENOSPC;
4259         }
4260         data_sinfo->bytes_may_use += bytes;
4261         trace_btrfs_space_reservation(fs_info, "space_info",
4262                                       data_sinfo->flags, bytes, 1);
4263         spin_unlock(&data_sinfo->lock);
4264
4265         return ret;
4266 }
4267
4268 /*
4269  * New check_data_free_space() with ability for precious data reservation
4270  * Will replace old btrfs_check_data_free_space(), but for patch split,
4271  * add a new function first and then replace it.
4272  */
4273 int btrfs_check_data_free_space(struct inode *inode, u64 start, u64 len)
4274 {
4275         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4276         int ret;
4277
4278         /* align the range */
4279         len = round_up(start + len, fs_info->sectorsize) -
4280               round_down(start, fs_info->sectorsize);
4281         start = round_down(start, fs_info->sectorsize);
4282
4283         ret = btrfs_alloc_data_chunk_ondemand(inode, len);
4284         if (ret < 0)
4285                 return ret;
4286
4287         /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
4288         ret = btrfs_qgroup_reserve_data(inode, start, len);
4289         if (ret)
4290                 btrfs_free_reserved_data_space_noquota(inode, start, len);
4291         return ret;
4292 }
4293
4294 /*
4295  * Called if we need to clear a data reservation for this inode
4296  * Normally in a error case.
4297  *
4298  * This one will *NOT* use accurate qgroup reserved space API, just for case
4299  * which we can't sleep and is sure it won't affect qgroup reserved space.
4300  * Like clear_bit_hook().
4301  */
4302 void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4303                                             u64 len)
4304 {
4305         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
4306         struct btrfs_space_info *data_sinfo;
4307
4308         /* Make sure the range is aligned to sectorsize */
4309         len = round_up(start + len, fs_info->sectorsize) -
4310               round_down(start, fs_info->sectorsize);
4311         start = round_down(start, fs_info->sectorsize);
4312
4313         data_sinfo = fs_info->data_sinfo;
4314         spin_lock(&data_sinfo->lock);
4315         if (WARN_ON(data_sinfo->bytes_may_use < len))
4316                 data_sinfo->bytes_may_use = 0;
4317         else
4318                 data_sinfo->bytes_may_use -= len;
4319         trace_btrfs_space_reservation(fs_info, "space_info",
4320                                       data_sinfo->flags, len, 0);
4321         spin_unlock(&data_sinfo->lock);
4322 }
4323
4324 /*
4325  * Called if we need to clear a data reservation for this inode
4326  * Normally in a error case.
4327  *
4328  * This one will handle the per-inode data rsv map for accurate reserved
4329  * space framework.
4330  */
4331 void btrfs_free_reserved_data_space(struct inode *inode, u64 start, u64 len)
4332 {
4333         struct btrfs_root *root = BTRFS_I(inode)->root;
4334
4335         /* Make sure the range is aligned to sectorsize */
4336         len = round_up(start + len, root->fs_info->sectorsize) -
4337               round_down(start, root->fs_info->sectorsize);
4338         start = round_down(start, root->fs_info->sectorsize);
4339
4340         btrfs_free_reserved_data_space_noquota(inode, start, len);
4341         btrfs_qgroup_free_data(inode, start, len);
4342 }
4343
4344 static void force_metadata_allocation(struct btrfs_fs_info *info)
4345 {
4346         struct list_head *head = &info->space_info;
4347         struct btrfs_space_info *found;
4348
4349         rcu_read_lock();
4350         list_for_each_entry_rcu(found, head, list) {
4351                 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
4352                         found->force_alloc = CHUNK_ALLOC_FORCE;
4353         }
4354         rcu_read_unlock();
4355 }
4356
4357 static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4358 {
4359         return (global->size << 1);
4360 }
4361
4362 static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
4363                               struct btrfs_space_info *sinfo, int force)
4364 {
4365         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4366         u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
4367         u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
4368         u64 thresh;
4369
4370         if (force == CHUNK_ALLOC_FORCE)
4371                 return 1;
4372
4373         /*
4374          * We need to take into account the global rsv because for all intents
4375          * and purposes it's used space.  Don't worry about locking the
4376          * global_rsv, it doesn't change except when the transaction commits.
4377          */
4378         if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
4379                 num_allocated += calc_global_rsv_need_space(global_rsv);
4380
4381         /*
4382          * in limited mode, we want to have some free space up to
4383          * about 1% of the FS size.
4384          */
4385         if (force == CHUNK_ALLOC_LIMITED) {
4386                 thresh = btrfs_super_total_bytes(fs_info->super_copy);
4387                 thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
4388
4389                 if (num_bytes - num_allocated < thresh)
4390                         return 1;
4391         }
4392
4393         if (num_allocated + SZ_2M < div_factor(num_bytes, 8))
4394                 return 0;
4395         return 1;
4396 }
4397
4398 static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
4399 {
4400         u64 num_dev;
4401
4402         if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4403                     BTRFS_BLOCK_GROUP_RAID0 |
4404                     BTRFS_BLOCK_GROUP_RAID5 |
4405                     BTRFS_BLOCK_GROUP_RAID6))
4406                 num_dev = fs_info->fs_devices->rw_devices;
4407         else if (type & BTRFS_BLOCK_GROUP_RAID1)
4408                 num_dev = 2;
4409         else
4410                 num_dev = 1;    /* DUP or single */
4411
4412         return num_dev;
4413 }
4414
4415 /*
4416  * If @is_allocation is true, reserve space in the system space info necessary
4417  * for allocating a chunk, otherwise if it's false, reserve space necessary for
4418  * removing a chunk.
4419  */
4420 void check_system_chunk(struct btrfs_trans_handle *trans,
4421                         struct btrfs_fs_info *fs_info, u64 type)
4422 {
4423         struct btrfs_space_info *info;
4424         u64 left;
4425         u64 thresh;
4426         int ret = 0;
4427         u64 num_devs;
4428
4429         /*
4430          * Needed because we can end up allocating a system chunk and for an
4431          * atomic and race free space reservation in the chunk block reserve.
4432          */
4433         ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
4434
4435         info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4436         spin_lock(&info->lock);
4437         left = info->total_bytes - btrfs_space_info_used(info, true);
4438         spin_unlock(&info->lock);
4439
4440         num_devs = get_profile_num_devs(fs_info, type);
4441
4442         /* num_devs device items to update and 1 chunk item to add or remove */
4443         thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
4444                 btrfs_calc_trans_metadata_size(fs_info, 1);
4445
4446         if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
4447                 btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
4448                            left, thresh, type);
4449                 dump_space_info(fs_info, info, 0, 0);
4450         }
4451
4452         if (left < thresh) {
4453                 u64 flags;
4454
4455                 flags = btrfs_get_alloc_profile(fs_info->chunk_root, 0);
4456                 /*
4457                  * Ignore failure to create system chunk. We might end up not
4458                  * needing it, as we might not need to COW all nodes/leafs from
4459                  * the paths we visit in the chunk tree (they were already COWed
4460                  * or created in the current transaction for example).
4461                  */
4462                 ret = btrfs_alloc_chunk(trans, fs_info, flags);
4463         }
4464
4465         if (!ret) {
4466                 ret = btrfs_block_rsv_add(fs_info->chunk_root,
4467                                           &fs_info->chunk_block_rsv,
4468                                           thresh, BTRFS_RESERVE_NO_FLUSH);
4469                 if (!ret)
4470                         trans->chunk_bytes_reserved += thresh;
4471         }
4472 }
4473
4474 /*
4475  * If force is CHUNK_ALLOC_FORCE:
4476  *    - return 1 if it successfully allocates a chunk,
4477  *    - return errors including -ENOSPC otherwise.
4478  * If force is NOT CHUNK_ALLOC_FORCE:
4479  *    - return 0 if it doesn't need to allocate a new chunk,
4480  *    - return 1 if it successfully allocates a chunk,
4481  *    - return errors including -ENOSPC otherwise.
4482  */
4483 static int do_chunk_alloc(struct btrfs_trans_handle *trans,
4484                           struct btrfs_fs_info *fs_info, u64 flags, int force)
4485 {
4486         struct btrfs_space_info *space_info;
4487         int wait_for_alloc = 0;
4488         int ret = 0;
4489
4490         /* Don't re-enter if we're already allocating a chunk */
4491         if (trans->allocating_chunk)
4492                 return -ENOSPC;
4493
4494         space_info = __find_space_info(fs_info, flags);
4495         if (!space_info) {
4496                 ret = update_space_info(fs_info, flags, 0, 0, 0, &space_info);
4497                 BUG_ON(ret); /* -ENOMEM */
4498         }
4499         BUG_ON(!space_info); /* Logic error */
4500
4501 again:
4502         spin_lock(&space_info->lock);
4503         if (force < space_info->force_alloc)
4504                 force = space_info->force_alloc;
4505         if (space_info->full) {
4506                 if (should_alloc_chunk(fs_info, space_info, force))
4507                         ret = -ENOSPC;
4508                 else
4509                         ret = 0;
4510                 spin_unlock(&space_info->lock);
4511                 return ret;
4512         }
4513
4514         if (!should_alloc_chunk(fs_info, space_info, force)) {
4515                 spin_unlock(&space_info->lock);
4516                 return 0;
4517         } else if (space_info->chunk_alloc) {
4518                 wait_for_alloc = 1;
4519         } else {
4520                 space_info->chunk_alloc = 1;
4521         }
4522
4523         spin_unlock(&space_info->lock);
4524
4525         mutex_lock(&fs_info->chunk_mutex);
4526
4527         /*
4528          * The chunk_mutex is held throughout the entirety of a chunk
4529          * allocation, so once we've acquired the chunk_mutex we know that the
4530          * other guy is done and we need to recheck and see if we should
4531          * allocate.
4532          */
4533         if (wait_for_alloc) {
4534                 mutex_unlock(&fs_info->chunk_mutex);
4535                 wait_for_alloc = 0;
4536                 goto again;
4537         }
4538
4539         trans->allocating_chunk = true;
4540
4541         /*
4542          * If we have mixed data/metadata chunks we want to make sure we keep
4543          * allocating mixed chunks instead of individual chunks.
4544          */
4545         if (btrfs_mixed_space_info(space_info))
4546                 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4547
4548         /*
4549          * if we're doing a data chunk, go ahead and make sure that
4550          * we keep a reasonable number of metadata chunks allocated in the
4551          * FS as well.
4552          */
4553         if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
4554                 fs_info->data_chunk_allocations++;
4555                 if (!(fs_info->data_chunk_allocations %
4556                       fs_info->metadata_ratio))
4557                         force_metadata_allocation(fs_info);
4558         }
4559
4560         /*
4561          * Check if we have enough space in SYSTEM chunk because we may need
4562          * to update devices.
4563          */
4564         check_system_chunk(trans, fs_info, flags);
4565
4566         ret = btrfs_alloc_chunk(trans, fs_info, flags);
4567         trans->allocating_chunk = false;
4568
4569         spin_lock(&space_info->lock);
4570         if (ret < 0 && ret != -ENOSPC)
4571                 goto out;
4572         if (ret)
4573                 space_info->full = 1;
4574         else
4575                 ret = 1;
4576
4577         space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
4578 out:
4579         space_info->chunk_alloc = 0;
4580         spin_unlock(&space_info->lock);
4581         mutex_unlock(&fs_info->chunk_mutex);
4582         /*
4583          * When we allocate a new chunk we reserve space in the chunk block
4584          * reserve to make sure we can COW nodes/leafs in the chunk tree or
4585          * add new nodes/leafs to it if we end up needing to do it when
4586          * inserting the chunk item and updating device items as part of the
4587          * second phase of chunk allocation, performed by
4588          * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4589          * large number of new block groups to create in our transaction
4590          * handle's new_bgs list to avoid exhausting the chunk block reserve
4591          * in extreme cases - like having a single transaction create many new
4592          * block groups when starting to write out the free space caches of all
4593          * the block groups that were made dirty during the lifetime of the
4594          * transaction.
4595          */
4596         if (trans->can_flush_pending_bgs &&
4597             trans->chunk_bytes_reserved >= (u64)SZ_2M) {
4598                 btrfs_create_pending_block_groups(trans, fs_info);
4599                 btrfs_trans_release_chunk_metadata(trans);
4600         }
4601         return ret;
4602 }
4603
4604 static int can_overcommit(struct btrfs_root *root,
4605                           struct btrfs_space_info *space_info, u64 bytes,
4606                           enum btrfs_reserve_flush_enum flush)
4607 {
4608         struct btrfs_fs_info *fs_info = root->fs_info;
4609         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4610         u64 profile;
4611         u64 space_size;
4612         u64 avail;
4613         u64 used;
4614
4615         /* Don't overcommit when in mixed mode. */
4616         if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
4617                 return 0;
4618
4619         profile = btrfs_get_alloc_profile(root, 0);
4620         used = btrfs_space_info_used(space_info, false);
4621
4622         /*
4623          * We only want to allow over committing if we have lots of actual space
4624          * free, but if we don't have enough space to handle the global reserve
4625          * space then we could end up having a real enospc problem when trying
4626          * to allocate a chunk or some other such important allocation.
4627          */
4628         spin_lock(&global_rsv->lock);
4629         space_size = calc_global_rsv_need_space(global_rsv);
4630         spin_unlock(&global_rsv->lock);
4631         if (used + space_size >= space_info->total_bytes)
4632                 return 0;
4633
4634         used += space_info->bytes_may_use;
4635
4636         spin_lock(&fs_info->free_chunk_lock);
4637         avail = fs_info->free_chunk_space;
4638         spin_unlock(&fs_info->free_chunk_lock);
4639
4640         /*
4641          * If we have dup, raid1 or raid10 then only half of the free
4642          * space is actually useable.  For raid56, the space info used
4643          * doesn't include the parity drive, so we don't have to
4644          * change the math
4645          */
4646         if (profile & (BTRFS_BLOCK_GROUP_DUP |
4647                        BTRFS_BLOCK_GROUP_RAID1 |
4648                        BTRFS_BLOCK_GROUP_RAID10))
4649                 avail >>= 1;
4650
4651         /*
4652          * If we aren't flushing all things, let us overcommit up to
4653          * 1/2th of the space. If we can flush, don't let us overcommit
4654          * too much, let it overcommit up to 1/8 of the space.
4655          */
4656         if (flush == BTRFS_RESERVE_FLUSH_ALL)
4657                 avail >>= 3;
4658         else
4659                 avail >>= 1;
4660
4661         if (used + bytes < space_info->total_bytes + avail)
4662                 return 1;
4663         return 0;
4664 }
4665
4666 static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
4667                                          unsigned long nr_pages, int nr_items)
4668 {
4669         struct super_block *sb = fs_info->sb;
4670
4671         if (down_read_trylock(&sb->s_umount)) {
4672                 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4673                 up_read(&sb->s_umount);
4674         } else {
4675                 /*
4676                  * We needn't worry the filesystem going from r/w to r/o though
4677                  * we don't acquire ->s_umount mutex, because the filesystem
4678                  * should guarantee the delalloc inodes list be empty after
4679                  * the filesystem is readonly(all dirty pages are written to
4680                  * the disk).
4681                  */
4682                 btrfs_start_delalloc_roots(fs_info, 0, nr_items);
4683                 if (!current->journal_info)
4684                         btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
4685         }
4686 }
4687
4688 static inline int calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
4689                                         u64 to_reclaim)
4690 {
4691         u64 bytes;
4692         int nr;
4693
4694         bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
4695         nr = (int)div64_u64(to_reclaim, bytes);
4696         if (!nr)
4697                 nr = 1;
4698         return nr;
4699 }
4700
4701 #define EXTENT_SIZE_PER_ITEM    SZ_256K
4702
4703 /*
4704  * shrink metadata reservation for delalloc
4705  */
4706 static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
4707                             bool wait_ordered)
4708 {
4709         struct btrfs_fs_info *fs_info = root->fs_info;
4710         struct btrfs_block_rsv *block_rsv;
4711         struct btrfs_space_info *space_info;
4712         struct btrfs_trans_handle *trans;
4713         u64 delalloc_bytes;
4714         u64 max_reclaim;
4715         long time_left;
4716         unsigned long nr_pages;
4717         int loops;
4718         int items;
4719         enum btrfs_reserve_flush_enum flush;
4720
4721         /* Calc the number of the pages we need flush for space reservation */
4722         items = calc_reclaim_items_nr(fs_info, to_reclaim);
4723         to_reclaim = (u64)items * EXTENT_SIZE_PER_ITEM;
4724
4725         trans = (struct btrfs_trans_handle *)current->journal_info;
4726         block_rsv = &fs_info->delalloc_block_rsv;
4727         space_info = block_rsv->space_info;
4728
4729         delalloc_bytes = percpu_counter_sum_positive(
4730                                                 &fs_info->delalloc_bytes);
4731         if (delalloc_bytes == 0) {
4732                 if (trans)
4733                         return;
4734                 if (wait_ordered)
4735                         btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4736                 return;
4737         }
4738
4739         loops = 0;
4740         while (delalloc_bytes && loops < 3) {
4741                 max_reclaim = min(delalloc_bytes, to_reclaim);
4742                 nr_pages = max_reclaim >> PAGE_SHIFT;
4743                 btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
4744                 /*
4745                  * We need to wait for the async pages to actually start before
4746                  * we do anything.
4747                  */
4748                 max_reclaim = atomic_read(&fs_info->async_delalloc_pages);
4749                 if (!max_reclaim)
4750                         goto skip_async;
4751
4752                 if (max_reclaim <= nr_pages)
4753                         max_reclaim = 0;
4754                 else
4755                         max_reclaim -= nr_pages;
4756
4757                 wait_event(fs_info->async_submit_wait,
4758                            atomic_read(&fs_info->async_delalloc_pages) <=
4759                            (int)max_reclaim);
4760 skip_async:
4761                 if (!trans)
4762                         flush = BTRFS_RESERVE_FLUSH_ALL;
4763                 else
4764                         flush = BTRFS_RESERVE_NO_FLUSH;
4765                 spin_lock(&space_info->lock);
4766                 if (can_overcommit(root, space_info, orig, flush)) {
4767                         spin_unlock(&space_info->lock);
4768                         break;
4769                 }
4770                 if (list_empty(&space_info->tickets) &&
4771                     list_empty(&space_info->priority_tickets)) {
4772                         spin_unlock(&space_info->lock);
4773                         break;
4774                 }
4775                 spin_unlock(&space_info->lock);
4776
4777                 loops++;
4778                 if (wait_ordered && !trans) {
4779                         btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
4780                 } else {
4781                         time_left = schedule_timeout_killable(1);
4782                         if (time_left)
4783                                 break;
4784                 }
4785                 delalloc_bytes = percpu_counter_sum_positive(
4786                                                 &fs_info->delalloc_bytes);
4787         }
4788 }
4789
4790 /**
4791  * maybe_commit_transaction - possibly commit the transaction if its ok to
4792  * @root - the root we're allocating for
4793  * @bytes - the number of bytes we want to reserve
4794  * @force - force the commit
4795  *
4796  * This will check to make sure that committing the transaction will actually
4797  * get us somewhere and then commit the transaction if it does.  Otherwise it
4798  * will return -ENOSPC.
4799  */
4800 static int may_commit_transaction(struct btrfs_fs_info *fs_info,
4801                                   struct btrfs_space_info *space_info,
4802                                   u64 bytes, int force)
4803 {
4804         struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
4805         struct btrfs_trans_handle *trans;
4806
4807         trans = (struct btrfs_trans_handle *)current->journal_info;
4808         if (trans)
4809                 return -EAGAIN;
4810
4811         if (force)
4812                 goto commit;
4813
4814         /* See if there is enough pinned space to make this reservation */
4815         if (percpu_counter_compare(&space_info->total_bytes_pinned,
4816                                    bytes) >= 0)
4817                 goto commit;
4818
4819         /*
4820          * See if there is some space in the delayed insertion reservation for
4821          * this reservation.
4822          */
4823         if (space_info != delayed_rsv->space_info)
4824                 return -ENOSPC;
4825
4826         spin_lock(&delayed_rsv->lock);
4827         if (percpu_counter_compare(&space_info->total_bytes_pinned,
4828                                    bytes - delayed_rsv->size) >= 0) {
4829                 spin_unlock(&delayed_rsv->lock);
4830                 return -ENOSPC;
4831         }
4832         spin_unlock(&delayed_rsv->lock);
4833
4834 commit:
4835         trans = btrfs_join_transaction(fs_info->fs_root);
4836         if (IS_ERR(trans))
4837                 return -ENOSPC;
4838
4839         return btrfs_commit_transaction(trans);
4840 }
4841
4842 struct reserve_ticket {
4843         u64 bytes;
4844         int error;
4845         struct list_head list;
4846         wait_queue_head_t wait;
4847 };
4848
4849 static int flush_space(struct btrfs_fs_info *fs_info,
4850                        struct btrfs_space_info *space_info, u64 num_bytes,
4851                        u64 orig_bytes, int state)
4852 {
4853         struct btrfs_root *root = fs_info->fs_root;
4854         struct btrfs_trans_handle *trans;
4855         int nr;
4856         int ret = 0;
4857
4858         switch (state) {
4859         case FLUSH_DELAYED_ITEMS_NR:
4860         case FLUSH_DELAYED_ITEMS:
4861                 if (state == FLUSH_DELAYED_ITEMS_NR)
4862                         nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
4863                 else
4864                         nr = -1;
4865
4866                 trans = btrfs_join_transaction(root);
4867                 if (IS_ERR(trans)) {
4868                         ret = PTR_ERR(trans);
4869                         break;
4870                 }
4871                 ret = btrfs_run_delayed_items_nr(trans, fs_info, nr);
4872                 btrfs_end_transaction(trans);
4873                 break;
4874         case FLUSH_DELALLOC:
4875         case FLUSH_DELALLOC_WAIT:
4876                 shrink_delalloc(root, num_bytes * 2, orig_bytes,
4877                                 state == FLUSH_DELALLOC_WAIT);
4878                 break;
4879         case ALLOC_CHUNK:
4880                 trans = btrfs_join_transaction(root);
4881                 if (IS_ERR(trans)) {
4882                         ret = PTR_ERR(trans);
4883                         break;
4884                 }
4885                 ret = do_chunk_alloc(trans, fs_info,
4886                                      btrfs_get_alloc_profile(root, 0),
4887                                      CHUNK_ALLOC_NO_FORCE);
4888                 btrfs_end_transaction(trans);
4889                 if (ret > 0 || ret == -ENOSPC)
4890                         ret = 0;
4891                 break;
4892         case COMMIT_TRANS:
4893                 ret = may_commit_transaction(fs_info, space_info,
4894                                              orig_bytes, 0);
4895                 break;
4896         default:
4897                 ret = -ENOSPC;
4898                 break;
4899         }
4900
4901         trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes,
4902                                 orig_bytes, state, ret);
4903         return ret;
4904 }
4905
4906 static inline u64
4907 btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
4908                                  struct btrfs_space_info *space_info)
4909 {
4910         struct reserve_ticket *ticket;
4911         u64 used;
4912         u64 expected;
4913         u64 to_reclaim = 0;
4914
4915         list_for_each_entry(ticket, &space_info->tickets, list)
4916                 to_reclaim += ticket->bytes;
4917         list_for_each_entry(ticket, &space_info->priority_tickets, list)
4918                 to_reclaim += ticket->bytes;
4919         if (to_reclaim)
4920                 return to_reclaim;
4921
4922         to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
4923         if (can_overcommit(root, space_info, to_reclaim,
4924                            BTRFS_RESERVE_FLUSH_ALL))
4925                 return 0;
4926
4927         used = space_info->bytes_used + space_info->bytes_reserved +
4928                space_info->bytes_pinned + space_info->bytes_readonly +
4929                space_info->bytes_may_use;
4930         if (can_overcommit(root, space_info, SZ_1M, BTRFS_RESERVE_FLUSH_ALL))
4931                 expected = div_factor_fine(space_info->total_bytes, 95);
4932         else
4933                 expected = div_factor_fine(space_info->total_bytes, 90);
4934
4935         if (used > expected)
4936                 to_reclaim = used - expected;
4937         else
4938                 to_reclaim = 0;
4939         to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4940                                      space_info->bytes_reserved);
4941         return to_reclaim;
4942 }
4943
4944 static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
4945                                         struct btrfs_root *root, u64 used)
4946 {
4947         struct btrfs_fs_info *fs_info = root->fs_info;
4948         u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4949
4950         /* If we're just plain full then async reclaim just slows us down. */
4951         if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
4952                 return 0;
4953
4954         if (!btrfs_calc_reclaim_metadata_size(root, space_info))
4955                 return 0;
4956
4957         return (used >= thresh && !btrfs_fs_closing(fs_info) &&
4958                 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4959 }
4960
4961 static void wake_all_tickets(struct list_head *head)
4962 {
4963         struct reserve_ticket *ticket;
4964
4965         while (!list_empty(head)) {
4966                 ticket = list_first_entry(head, struct reserve_ticket, list);
4967                 list_del_init(&ticket->list);
4968                 ticket->error = -ENOSPC;
4969                 wake_up(&ticket->wait);
4970         }
4971 }
4972
4973 /*
4974  * This is for normal flushers, we can wait all goddamned day if we want to.  We
4975  * will loop and continuously try to flush as long as we are making progress.
4976  * We count progress as clearing off tickets each time we have to loop.
4977  */
4978 static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4979 {
4980         struct btrfs_fs_info *fs_info;
4981         struct btrfs_space_info *space_info;
4982         u64 to_reclaim;
4983         int flush_state;
4984         int commit_cycles = 0;
4985         u64 last_tickets_id;
4986
4987         fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4988         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4989
4990         spin_lock(&space_info->lock);
4991         to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
4992                                                       space_info);
4993         if (!to_reclaim) {
4994                 space_info->flush = 0;
4995                 spin_unlock(&space_info->lock);
4996                 return;
4997         }
4998         last_tickets_id = space_info->tickets_id;
4999         spin_unlock(&space_info->lock);
5000
5001         flush_state = FLUSH_DELAYED_ITEMS_NR;
5002         do {
5003                 struct reserve_ticket *ticket;
5004                 int ret;
5005
5006                 ret = flush_space(fs_info, space_info, to_reclaim, to_reclaim,
5007                                   flush_state);
5008                 spin_lock(&space_info->lock);
5009                 if (list_empty(&space_info->tickets)) {
5010                         space_info->flush = 0;
5011                         spin_unlock(&space_info->lock);
5012                         return;
5013                 }
5014                 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5015                                                               space_info);
5016                 ticket = list_first_entry(&space_info->tickets,
5017                                           struct reserve_ticket, list);
5018                 if (last_tickets_id == space_info->tickets_id) {
5019                         flush_state++;
5020                 } else {
5021                         last_tickets_id = space_info->tickets_id;
5022                         flush_state = FLUSH_DELAYED_ITEMS_NR;
5023                         if (commit_cycles)
5024                                 commit_cycles--;
5025                 }
5026
5027                 if (flush_state > COMMIT_TRANS) {
5028                         commit_cycles++;
5029                         if (commit_cycles > 2) {
5030                                 wake_all_tickets(&space_info->tickets);
5031                                 space_info->flush = 0;
5032                         } else {
5033                                 flush_state = FLUSH_DELAYED_ITEMS_NR;
5034                         }
5035                 }
5036                 spin_unlock(&space_info->lock);
5037         } while (flush_state <= COMMIT_TRANS);
5038 }
5039
5040 void btrfs_init_async_reclaim_work(struct work_struct *work)
5041 {
5042         INIT_WORK(work, btrfs_async_reclaim_metadata_space);
5043 }
5044
5045 static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
5046                                             struct btrfs_space_info *space_info,
5047                                             struct reserve_ticket *ticket)
5048 {
5049         u64 to_reclaim;
5050         int flush_state = FLUSH_DELAYED_ITEMS_NR;
5051
5052         spin_lock(&space_info->lock);
5053         to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
5054                                                       space_info);
5055         if (!to_reclaim) {
5056                 spin_unlock(&space_info->lock);
5057                 return;
5058         }
5059         spin_unlock(&space_info->lock);
5060
5061         do {
5062                 flush_space(fs_info, space_info, to_reclaim, to_reclaim,
5063                             flush_state);
5064                 flush_state++;
5065                 spin_lock(&space_info->lock);
5066                 if (ticket->bytes == 0) {
5067                         spin_unlock(&space_info->lock);
5068                         return;
5069                 }
5070                 spin_unlock(&space_info->lock);
5071
5072                 /*
5073                  * Priority flushers can't wait on delalloc without
5074                  * deadlocking.
5075                  */
5076                 if (flush_state == FLUSH_DELALLOC ||
5077                     flush_state == FLUSH_DELALLOC_WAIT)
5078                         flush_state = ALLOC_CHUNK;
5079         } while (flush_state < COMMIT_TRANS);
5080 }
5081
5082 static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
5083                                struct btrfs_space_info *space_info,
5084                                struct reserve_ticket *ticket, u64 orig_bytes)
5085
5086 {
5087         DEFINE_WAIT(wait);
5088         int ret = 0;
5089
5090         spin_lock(&space_info->lock);
5091         while (ticket->bytes > 0 && ticket->error == 0) {
5092                 ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
5093                 if (ret) {
5094                         ret = -EINTR;
5095                         break;
5096                 }
5097                 spin_unlock(&space_info->lock);
5098
5099                 schedule();
5100
5101                 finish_wait(&ticket->wait, &wait);
5102                 spin_lock(&space_info->lock);
5103         }
5104         if (!ret)
5105                 ret = ticket->error;
5106         if (!list_empty(&ticket->list))
5107                 list_del_init(&ticket->list);
5108         if (ticket->bytes && ticket->bytes < orig_bytes) {
5109                 u64 num_bytes = orig_bytes - ticket->bytes;
5110                 space_info->bytes_may_use -= num_bytes;
5111                 trace_btrfs_space_reservation(fs_info, "space_info",
5112                                               space_info->flags, num_bytes, 0);
5113         }
5114         spin_unlock(&space_info->lock);
5115
5116         return ret;
5117 }
5118
5119 /**
5120  * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5121  * @root - the root we're allocating for
5122  * @space_info - the space info we want to allocate from
5123  * @orig_bytes - the number of bytes we want
5124  * @flush - whether or not we can flush to make our reservation
5125  *
5126  * This will reserve orig_bytes number of bytes from the space info associated
5127  * with the block_rsv.  If there is not enough space it will make an attempt to
5128  * flush out space to make room.  It will do this by flushing delalloc if
5129  * possible or committing the transaction.  If flush is 0 then no attempts to
5130  * regain reservations will be made and this will fail if there is not enough
5131  * space already.
5132  */
5133 static int __reserve_metadata_bytes(struct btrfs_root *root,
5134                                     struct btrfs_space_info *space_info,
5135                                     u64 orig_bytes,
5136                                     enum btrfs_reserve_flush_enum flush)
5137 {
5138         struct btrfs_fs_info *fs_info = root->fs_info;
5139         struct reserve_ticket ticket;
5140         u64 used;
5141         int ret = 0;
5142
5143         ASSERT(orig_bytes);
5144         ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
5145
5146         spin_lock(&space_info->lock);
5147         ret = -ENOSPC;
5148         used = btrfs_space_info_used(space_info, true);
5149
5150         /*
5151          * If we have enough space then hooray, make our reservation and carry
5152          * on.  If not see if we can overcommit, and if we can, hooray carry on.
5153          * If not things get more complicated.
5154          */
5155         if (used + orig_bytes <= space_info->total_bytes) {
5156                 space_info->bytes_may_use += orig_bytes;
5157                 trace_btrfs_space_reservation(fs_info, "space_info",
5158                                               space_info->flags, orig_bytes, 1);
5159                 ret = 0;
5160         } else if (can_overcommit(root, space_info, orig_bytes, flush)) {
5161                 space_info->bytes_may_use += orig_bytes;
5162                 trace_btrfs_space_reservation(fs_info, "space_info",
5163                                               space_info->flags, orig_bytes, 1);
5164                 ret = 0;
5165         }
5166
5167         /*
5168          * If we couldn't make a reservation then setup our reservation ticket
5169          * and kick the async worker if it's not already running.
5170          *
5171          * If we are a priority flusher then we just need to add our ticket to
5172          * the list and we will do our own flushing further down.
5173          */
5174         if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
5175                 ticket.bytes = orig_bytes;
5176                 ticket.error = 0;
5177                 init_waitqueue_head(&ticket.wait);
5178                 if (flush == BTRFS_RESERVE_FLUSH_ALL) {
5179                         list_add_tail(&ticket.list, &space_info->tickets);
5180                         if (!space_info->flush) {
5181                                 space_info->flush = 1;
5182                                 trace_btrfs_trigger_flush(fs_info,
5183                                                           space_info->flags,
5184                                                           orig_bytes, flush,
5185                                                           "enospc");
5186                                 queue_work(system_unbound_wq,
5187                                            &root->fs_info->async_reclaim_work);
5188                         }
5189                 } else {
5190                         list_add_tail(&ticket.list,
5191                                       &space_info->priority_tickets);
5192                 }
5193         } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
5194                 used += orig_bytes;
5195                 /*
5196                  * We will do the space reservation dance during log replay,
5197                  * which means we won't have fs_info->fs_root set, so don't do
5198                  * the async reclaim as we will panic.
5199                  */
5200                 if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
5201                     need_do_async_reclaim(space_info, root, used) &&
5202                     !work_busy(&fs_info->async_reclaim_work)) {
5203                         trace_btrfs_trigger_flush(fs_info, space_info->flags,
5204                                                   orig_bytes, flush, "preempt");
5205                         queue_work(system_unbound_wq,
5206                                    &fs_info->async_reclaim_work);
5207                 }
5208         }
5209         spin_unlock(&space_info->lock);
5210         if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
5211                 return ret;
5212
5213         if (flush == BTRFS_RESERVE_FLUSH_ALL)
5214                 return wait_reserve_ticket(fs_info, space_info, &ticket,
5215                                            orig_bytes);
5216
5217         ret = 0;
5218         priority_reclaim_metadata_space(fs_info, space_info, &ticket);
5219         spin_lock(&space_info->lock);
5220         if (ticket.bytes) {
5221                 if (ticket.bytes < orig_bytes) {
5222                         u64 num_bytes = orig_bytes - ticket.bytes;
5223                         space_info->bytes_may_use -= num_bytes;
5224                         trace_btrfs_space_reservation(fs_info, "space_info",
5225                                                       space_info->flags,
5226                                                       num_bytes, 0);
5227
5228                 }
5229                 list_del_init(&ticket.list);
5230                 ret = -ENOSPC;
5231         }
5232         spin_unlock(&space_info->lock);
5233         ASSERT(list_empty(&ticket.list));
5234         return ret;
5235 }
5236
5237 /**
5238  * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
5239  * @root - the root we're allocating for
5240  * @block_rsv - the block_rsv we're allocating for
5241  * @orig_bytes - the number of bytes we want
5242  * @flush - whether or not we can flush to make our reservation
5243  *
5244  * This will reserve orgi_bytes number of bytes from the space info associated
5245  * with the block_rsv.  If there is not enough space it will make an attempt to
5246  * flush out space to make room.  It will do this by flushing delalloc if
5247  * possible or committing the transaction.  If flush is 0 then no attempts to
5248  * regain reservations will be made and this will fail if there is not enough
5249  * space already.
5250  */
5251 static int reserve_metadata_bytes(struct btrfs_root *root,
5252                                   struct btrfs_block_rsv *block_rsv,
5253                                   u64 orig_bytes,
5254                                   enum btrfs_reserve_flush_enum flush)
5255 {
5256         struct btrfs_fs_info *fs_info = root->fs_info;
5257         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5258         int ret;
5259
5260         ret = __reserve_metadata_bytes(root, block_rsv->space_info, orig_bytes,
5261                                        flush);
5262         if (ret == -ENOSPC &&
5263             unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5264                 if (block_rsv != global_rsv &&
5265                     !block_rsv_use_bytes(global_rsv, orig_bytes))
5266                         ret = 0;
5267         }
5268         if (ret == -ENOSPC)
5269                 trace_btrfs_space_reservation(fs_info, "space_info:enospc",
5270                                               block_rsv->space_info->flags,
5271                                               orig_bytes, 1);
5272         return ret;
5273 }
5274
5275 static struct btrfs_block_rsv *get_block_rsv(
5276                                         const struct btrfs_trans_handle *trans,
5277                                         const struct btrfs_root *root)
5278 {
5279         struct btrfs_fs_info *fs_info = root->fs_info;
5280         struct btrfs_block_rsv *block_rsv = NULL;
5281
5282         if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5283             (root == fs_info->csum_root && trans->adding_csums) ||
5284             (root == fs_info->uuid_root))
5285                 block_rsv = trans->block_rsv;
5286
5287         if (!block_rsv)
5288                 block_rsv = root->block_rsv;
5289
5290         if (!block_rsv)
5291                 block_rsv = &fs_info->empty_block_rsv;
5292
5293         return block_rsv;
5294 }
5295
5296 static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5297                                u64 num_bytes)
5298 {
5299         int ret = -ENOSPC;
5300         spin_lock(&block_rsv->lock);
5301         if (block_rsv->reserved >= num_bytes) {
5302                 block_rsv->reserved -= num_bytes;
5303                 if (block_rsv->reserved < block_rsv->size)
5304                         block_rsv->full = 0;
5305                 ret = 0;
5306         }
5307         spin_unlock(&block_rsv->lock);
5308         return ret;
5309 }
5310
5311 static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5312                                 u64 num_bytes, int update_size)
5313 {
5314         spin_lock(&block_rsv->lock);
5315         block_rsv->reserved += num_bytes;
5316         if (update_size)
5317                 block_rsv->size += num_bytes;
5318         else if (block_rsv->reserved >= block_rsv->size)
5319                 block_rsv->full = 1;
5320         spin_unlock(&block_rsv->lock);
5321 }
5322
5323 int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5324                              struct btrfs_block_rsv *dest, u64 num_bytes,
5325                              int min_factor)
5326 {
5327         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5328         u64 min_bytes;
5329
5330         if (global_rsv->space_info != dest->space_info)
5331                 return -ENOSPC;
5332
5333         spin_lock(&global_rsv->lock);
5334         min_bytes = div_factor(global_rsv->size, min_factor);
5335         if (global_rsv->reserved < min_bytes + num_bytes) {
5336                 spin_unlock(&global_rsv->lock);
5337                 return -ENOSPC;
5338         }
5339         global_rsv->reserved -= num_bytes;
5340         if (global_rsv->reserved < global_rsv->size)
5341                 global_rsv->full = 0;
5342         spin_unlock(&global_rsv->lock);
5343
5344         block_rsv_add_bytes(dest, num_bytes, 1);
5345         return 0;
5346 }
5347
5348 /*
5349  * This is for space we already have accounted in space_info->bytes_may_use, so
5350  * basically when we're returning space from block_rsv's.
5351  */
5352 static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
5353                                      struct btrfs_space_info *space_info,
5354                                      u64 num_bytes)
5355 {
5356         struct reserve_ticket *ticket;
5357         struct list_head *head;
5358         u64 used;
5359         enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
5360         bool check_overcommit = false;
5361
5362         spin_lock(&space_info->lock);
5363         head = &space_info->priority_tickets;
5364
5365         /*
5366          * If we are over our limit then we need to check and see if we can
5367          * overcommit, and if we can't then we just need to free up our space
5368          * and not satisfy any requests.
5369          */
5370         used = space_info->bytes_used + space_info->bytes_reserved +
5371                 space_info->bytes_pinned + space_info->bytes_readonly +
5372                 space_info->bytes_may_use;
5373         if (used - num_bytes >= space_info->total_bytes)
5374                 check_overcommit = true;
5375 again:
5376         while (!list_empty(head) && num_bytes) {
5377                 ticket = list_first_entry(head, struct reserve_ticket,
5378                                           list);
5379                 /*
5380                  * We use 0 bytes because this space is already reserved, so
5381                  * adding the ticket space would be a double count.
5382                  */
5383                 if (check_overcommit &&
5384                     !can_overcommit(fs_info->extent_root, space_info, 0,
5385                                     flush))
5386                         break;
5387                 if (num_bytes >= ticket->bytes) {
5388                         list_del_init(&ticket->list);
5389                         num_bytes -= ticket->bytes;
5390                         ticket->bytes = 0;
5391                         space_info->tickets_id++;
5392                         wake_up(&ticket->wait);
5393                 } else {
5394                         ticket->bytes -= num_bytes;
5395                         num_bytes = 0;
5396                 }
5397         }
5398
5399         if (num_bytes && head == &space_info->priority_tickets) {
5400                 head = &space_info->tickets;
5401                 flush = BTRFS_RESERVE_FLUSH_ALL;
5402                 goto again;
5403         }
5404         space_info->bytes_may_use -= num_bytes;
5405         trace_btrfs_space_reservation(fs_info, "space_info",
5406                                       space_info->flags, num_bytes, 0);
5407         spin_unlock(&space_info->lock);
5408 }
5409
5410 /*
5411  * This is for newly allocated space that isn't accounted in
5412  * space_info->bytes_may_use yet.  So if we allocate a chunk or unpin an extent
5413  * we use this helper.
5414  */
5415 static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
5416                                      struct btrfs_space_info *space_info,
5417                                      u64 num_bytes)
5418 {
5419         struct reserve_ticket *ticket;
5420         struct list_head *head = &space_info->priority_tickets;
5421
5422 again:
5423         while (!list_empty(head) && num_bytes) {
5424                 ticket = list_first_entry(head, struct reserve_ticket,
5425                                           list);
5426                 if (num_bytes >= ticket->bytes) {
5427                         trace_btrfs_space_reservation(fs_info, "space_info",
5428                                                       space_info->flags,
5429                                                       ticket->bytes, 1);
5430                         list_del_init(&ticket->list);
5431                         num_bytes -= ticket->bytes;
5432                         space_info->bytes_may_use += ticket->bytes;
5433                         ticket->bytes = 0;
5434                         space_info->tickets_id++;
5435                         wake_up(&ticket->wait);
5436                 } else {
5437                         trace_btrfs_space_reservation(fs_info, "space_info",
5438                                                       space_info->flags,
5439                                                       num_bytes, 1);
5440                         space_info->bytes_may_use += num_bytes;
5441                         ticket->bytes -= num_bytes;
5442                         num_bytes = 0;
5443                 }
5444         }
5445
5446         if (num_bytes && head == &space_info->priority_tickets) {
5447                 head = &space_info->tickets;
5448                 goto again;
5449         }
5450 }
5451
5452 static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5453                                     struct btrfs_block_rsv *block_rsv,
5454                                     struct btrfs_block_rsv *dest, u64 num_bytes)
5455 {
5456         struct btrfs_space_info *space_info = block_rsv->space_info;
5457
5458         spin_lock(&block_rsv->lock);
5459         if (num_bytes == (u64)-1)
5460                 num_bytes = block_rsv->size;
5461         block_rsv->size -= num_bytes;
5462         if (block_rsv->reserved >= block_rsv->size) {
5463                 num_bytes = block_rsv->reserved - block_rsv->size;
5464                 block_rsv->reserved = block_rsv->size;
5465                 block_rsv->full = 1;
5466         } else {
5467                 num_bytes = 0;
5468         }
5469         spin_unlock(&block_rsv->lock);
5470
5471         if (num_bytes > 0) {
5472                 if (dest) {
5473                         spin_lock(&dest->lock);
5474                         if (!dest->full) {
5475                                 u64 bytes_to_add;
5476
5477                                 bytes_to_add = dest->size - dest->reserved;
5478                                 bytes_to_add = min(num_bytes, bytes_to_add);
5479                                 dest->reserved += bytes_to_add;
5480                                 if (dest->reserved >= dest->size)
5481                                         dest->full = 1;
5482                                 num_bytes -= bytes_to_add;
5483                         }
5484                         spin_unlock(&dest->lock);
5485                 }
5486                 if (num_bytes)
5487                         space_info_add_old_bytes(fs_info, space_info,
5488                                                  num_bytes);
5489         }
5490 }
5491
5492 int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
5493                             struct btrfs_block_rsv *dst, u64 num_bytes,
5494                             int update_size)
5495 {
5496         int ret;
5497
5498         ret = block_rsv_use_bytes(src, num_bytes);
5499         if (ret)
5500                 return ret;
5501
5502         block_rsv_add_bytes(dst, num_bytes, update_size);
5503         return 0;
5504 }
5505
5506 void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
5507 {
5508         memset(rsv, 0, sizeof(*rsv));
5509         spin_lock_init(&rsv->lock);
5510         rsv->type = type;
5511 }
5512
5513 struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
5514                                               unsigned short type)
5515 {
5516         struct btrfs_block_rsv *block_rsv;
5517
5518         block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5519         if (!block_rsv)
5520                 return NULL;
5521
5522         btrfs_init_block_rsv(block_rsv, type);
5523         block_rsv->space_info = __find_space_info(fs_info,
5524                                                   BTRFS_BLOCK_GROUP_METADATA);
5525         return block_rsv;
5526 }
5527
5528 void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
5529                           struct btrfs_block_rsv *rsv)
5530 {
5531         if (!rsv)
5532                 return;
5533         btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5534         kfree(rsv);
5535 }
5536
5537 void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
5538 {
5539         kfree(rsv);
5540 }
5541
5542 int btrfs_block_rsv_add(struct btrfs_root *root,
5543                         struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5544                         enum btrfs_reserve_flush_enum flush)
5545 {
5546         int ret;
5547
5548         if (num_bytes == 0)
5549                 return 0;
5550
5551         ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5552         if (!ret) {
5553                 block_rsv_add_bytes(block_rsv, num_bytes, 1);
5554                 return 0;
5555         }
5556
5557         return ret;
5558 }
5559
5560 int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
5561 {
5562         u64 num_bytes = 0;
5563         int ret = -ENOSPC;
5564
5565         if (!block_rsv)
5566                 return 0;
5567
5568         spin_lock(&block_rsv->lock);
5569         num_bytes = div_factor(block_rsv->size, min_factor);
5570         if (block_rsv->reserved >= num_bytes)
5571                 ret = 0;
5572         spin_unlock(&block_rsv->lock);
5573
5574         return ret;
5575 }
5576
5577 int btrfs_block_rsv_refill(struct btrfs_root *root,
5578                            struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5579                            enum btrfs_reserve_flush_enum flush)
5580 {
5581         u64 num_bytes = 0;
5582         int ret = -ENOSPC;
5583
5584         if (!block_rsv)
5585                 return 0;
5586
5587         spin_lock(&block_rsv->lock);
5588         num_bytes = min_reserved;
5589         if (block_rsv->reserved >= num_bytes)
5590                 ret = 0;
5591         else
5592                 num_bytes -= block_rsv->reserved;
5593         spin_unlock(&block_rsv->lock);
5594
5595         if (!ret)
5596                 return 0;
5597
5598         ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
5599         if (!ret) {
5600                 block_rsv_add_bytes(block_rsv, num_bytes, 0);
5601                 return 0;
5602         }
5603
5604         return ret;
5605 }
5606
5607 void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
5608                              struct btrfs_block_rsv *block_rsv,
5609                              u64 num_bytes)
5610 {
5611         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5612
5613         if (global_rsv == block_rsv ||
5614             block_rsv->space_info != global_rsv->space_info)
5615                 global_rsv = NULL;
5616         block_rsv_release_bytes(fs_info, block_rsv, global_rsv, num_bytes);
5617 }
5618
5619 static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5620 {
5621         struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5622         struct btrfs_space_info *sinfo = block_rsv->space_info;
5623         u64 num_bytes;
5624
5625         /*
5626          * The global block rsv is based on the size of the extent tree, the
5627          * checksum tree and the root tree.  If the fs is empty we want to set
5628          * it to a minimal amount for safety.
5629          */
5630         num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
5631                 btrfs_root_used(&fs_info->csum_root->root_item) +
5632                 btrfs_root_used(&fs_info->tree_root->root_item);
5633         num_bytes = max_t(u64, num_bytes, SZ_16M);
5634
5635         spin_lock(&sinfo->lock);
5636         spin_lock(&block_rsv->lock);
5637
5638         block_rsv->size = min_t(u64, num_bytes, SZ_512M);
5639
5640         if (block_rsv->reserved < block_rsv->size) {
5641                 num_bytes = btrfs_space_info_used(sinfo, true);
5642                 if (sinfo->total_bytes > num_bytes) {
5643                         num_bytes = sinfo->total_bytes - num_bytes;
5644                         num_bytes = min(num_bytes,
5645                                         block_rsv->size - block_rsv->reserved);
5646                         block_rsv->reserved += num_bytes;
5647                         sinfo->bytes_may_use += num_bytes;
5648                         trace_btrfs_space_reservation(fs_info, "space_info",
5649                                                       sinfo->flags, num_bytes,
5650                                                       1);
5651                 }
5652         } else if (block_rsv->reserved > block_rsv->size) {
5653                 num_bytes = block_rsv->reserved - block_rsv->size;
5654                 sinfo->bytes_may_use -= num_bytes;
5655                 trace_btrfs_space_reservation(fs_info, "space_info",
5656                                       sinfo->flags, num_bytes, 0);
5657                 block_rsv->reserved = block_rsv->size;
5658         }
5659
5660         if (block_rsv->reserved == block_rsv->size)
5661                 block_rsv->full = 1;
5662         else
5663                 block_rsv->full = 0;
5664
5665         spin_unlock(&block_rsv->lock);
5666         spin_unlock(&sinfo->lock);
5667 }
5668
5669 static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
5670 {
5671         struct btrfs_space_info *space_info;
5672
5673         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5674         fs_info->chunk_block_rsv.space_info = space_info;
5675
5676         space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5677         fs_info->global_block_rsv.space_info = space_info;
5678         fs_info->delalloc_block_rsv.space_info = space_info;
5679         fs_info->trans_block_rsv.space_info = space_info;
5680         fs_info->empty_block_rsv.space_info = space_info;
5681         fs_info->delayed_block_rsv.space_info = space_info;
5682
5683         fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
5684         fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
5685         fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5686         fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
5687         if (fs_info->quota_root)
5688                 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
5689         fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
5690
5691         update_global_block_rsv(fs_info);
5692 }
5693
5694 static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
5695 {
5696         block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5697                                 (u64)-1);
5698         WARN_ON(fs_info->delalloc_block_rsv.size > 0);
5699         WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
5700         WARN_ON(fs_info->trans_block_rsv.size > 0);
5701         WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5702         WARN_ON(fs_info->chunk_block_rsv.size > 0);
5703         WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
5704         WARN_ON(fs_info->delayed_block_rsv.size > 0);
5705         WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
5706 }
5707
5708 void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
5709                                   struct btrfs_fs_info *fs_info)
5710 {
5711         if (!trans->block_rsv)
5712                 return;
5713
5714         if (!trans->bytes_reserved)
5715                 return;
5716
5717         trace_btrfs_space_reservation(fs_info, "transaction",
5718                                       trans->transid, trans->bytes_reserved, 0);
5719         btrfs_block_rsv_release(fs_info, trans->block_rsv,
5720                                 trans->bytes_reserved);
5721         trans->bytes_reserved = 0;
5722 }
5723
5724 /*
5725  * To be called after all the new block groups attached to the transaction
5726  * handle have been created (btrfs_create_pending_block_groups()).
5727  */
5728 void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5729 {
5730         struct btrfs_fs_info *fs_info = trans->fs_info;
5731
5732         if (!trans->chunk_bytes_reserved)
5733                 return;
5734
5735         WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5736
5737         block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5738                                 trans->chunk_bytes_reserved);
5739         trans->chunk_bytes_reserved = 0;
5740 }
5741
5742 /* Can only return 0 or -ENOSPC */
5743 int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
5744                                   struct inode *inode)
5745 {
5746         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5747         struct btrfs_root *root = BTRFS_I(inode)->root;
5748         /*
5749          * We always use trans->block_rsv here as we will have reserved space
5750          * for our orphan when starting the transaction, using get_block_rsv()
5751          * here will sometimes make us choose the wrong block rsv as we could be
5752          * doing a reloc inode for a non refcounted root.
5753          */
5754         struct btrfs_block_rsv *src_rsv = trans->block_rsv;
5755         struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
5756
5757         /*
5758          * We need to hold space in order to delete our orphan item once we've
5759          * added it, so this takes the reservation so we can release it later
5760          * when we are truly done with the orphan item.
5761          */
5762         u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5763
5764         trace_btrfs_space_reservation(fs_info, "orphan",
5765                                       btrfs_ino(BTRFS_I(inode)), num_bytes, 1);
5766         return btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, 1);
5767 }
5768
5769 void btrfs_orphan_release_metadata(struct inode *inode)
5770 {
5771         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5772         struct btrfs_root *root = BTRFS_I(inode)->root;
5773         u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
5774
5775         trace_btrfs_space_reservation(fs_info, "orphan",
5776                                       btrfs_ino(BTRFS_I(inode)), num_bytes, 0);
5777         btrfs_block_rsv_release(fs_info, root->orphan_block_rsv, num_bytes);
5778 }
5779
5780 /*
5781  * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5782  * root: the root of the parent directory
5783  * rsv: block reservation
5784  * items: the number of items that we need do reservation
5785  * qgroup_reserved: used to return the reserved size in qgroup
5786  *
5787  * This function is used to reserve the space for snapshot/subvolume
5788  * creation and deletion. Those operations are different with the
5789  * common file/directory operations, they change two fs/file trees
5790  * and root tree, the number of items that the qgroup reserves is
5791  * different with the free space reservation. So we can not use
5792  * the space reservation mechanism in start_transaction().
5793  */
5794 int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5795                                      struct btrfs_block_rsv *rsv,
5796                                      int items,
5797                                      u64 *qgroup_reserved,
5798                                      bool use_global_rsv)
5799 {
5800         u64 num_bytes;
5801         int ret;
5802         struct btrfs_fs_info *fs_info = root->fs_info;
5803         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5804
5805         if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5806                 /* One for parent inode, two for dir entries */
5807                 num_bytes = 3 * fs_info->nodesize;
5808                 ret = btrfs_qgroup_reserve_meta(root, num_bytes, true);
5809                 if (ret)
5810                         return ret;
5811         } else {
5812                 num_bytes = 0;
5813         }
5814
5815         *qgroup_reserved = num_bytes;
5816
5817         num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
5818         rsv->space_info = __find_space_info(fs_info,
5819                                             BTRFS_BLOCK_GROUP_METADATA);
5820         ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5821                                   BTRFS_RESERVE_FLUSH_ALL);
5822
5823         if (ret == -ENOSPC && use_global_rsv)
5824                 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
5825
5826         if (ret && *qgroup_reserved)
5827                 btrfs_qgroup_free_meta(root, *qgroup_reserved);
5828
5829         return ret;
5830 }
5831
5832 void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
5833                                       struct btrfs_block_rsv *rsv)
5834 {
5835         btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
5836 }
5837
5838 /**
5839  * drop_outstanding_extent - drop an outstanding extent
5840  * @inode: the inode we're dropping the extent for
5841  * @num_bytes: the number of bytes we're releasing.
5842  *
5843  * This is called when we are freeing up an outstanding extent, either called
5844  * after an error or after an extent is written.  This will return the number of
5845  * reserved extents that need to be freed.  This must be called with
5846  * BTRFS_I(inode)->lock held.
5847  */
5848 static unsigned drop_outstanding_extent(struct inode *inode, u64 num_bytes)
5849 {
5850         unsigned drop_inode_space = 0;
5851         unsigned dropped_extents = 0;
5852         unsigned num_extents;
5853
5854         num_extents = count_max_extents(num_bytes);
5855         ASSERT(num_extents);
5856         ASSERT(BTRFS_I(inode)->outstanding_extents >= num_extents);
5857         BTRFS_I(inode)->outstanding_extents -= num_extents;
5858
5859         if (BTRFS_I(inode)->outstanding_extents == 0 &&
5860             test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5861                                &BTRFS_I(inode)->runtime_flags))
5862                 drop_inode_space = 1;
5863
5864         /*
5865          * If we have more or the same amount of outstanding extents than we have
5866          * reserved then we need to leave the reserved extents count alone.
5867          */
5868         if (BTRFS_I(inode)->outstanding_extents >=
5869             BTRFS_I(inode)->reserved_extents)
5870                 return drop_inode_space;
5871
5872         dropped_extents = BTRFS_I(inode)->reserved_extents -
5873                 BTRFS_I(inode)->outstanding_extents;
5874         BTRFS_I(inode)->reserved_extents -= dropped_extents;
5875         return dropped_extents + drop_inode_space;
5876 }
5877
5878 /**
5879  * calc_csum_metadata_size - return the amount of metadata space that must be
5880  *      reserved/freed for the given bytes.
5881  * @inode: the inode we're manipulating
5882  * @num_bytes: the number of bytes in question
5883  * @reserve: 1 if we are reserving space, 0 if we are freeing space
5884  *
5885  * This adjusts the number of csum_bytes in the inode and then returns the
5886  * correct amount of metadata that must either be reserved or freed.  We
5887  * calculate how many checksums we can fit into one leaf and then divide the
5888  * number of bytes that will need to be checksumed by this value to figure out
5889  * how many checksums will be required.  If we are adding bytes then the number
5890  * may go up and we will return the number of additional bytes that must be
5891  * reserved.  If it is going down we will return the number of bytes that must
5892  * be freed.
5893  *
5894  * This must be called with BTRFS_I(inode)->lock held.
5895  */
5896 static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
5897                                    int reserve)
5898 {
5899         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5900         u64 old_csums, num_csums;
5901
5902         if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
5903             BTRFS_I(inode)->csum_bytes == 0)
5904                 return 0;
5905
5906         old_csums = btrfs_csum_bytes_to_leaves(fs_info,
5907                                                BTRFS_I(inode)->csum_bytes);
5908         if (reserve)
5909                 BTRFS_I(inode)->csum_bytes += num_bytes;
5910         else
5911                 BTRFS_I(inode)->csum_bytes -= num_bytes;
5912         num_csums = btrfs_csum_bytes_to_leaves(fs_info,
5913                                                BTRFS_I(inode)->csum_bytes);
5914
5915         /* No change, no need to reserve more */
5916         if (old_csums == num_csums)
5917                 return 0;
5918
5919         if (reserve)
5920                 return btrfs_calc_trans_metadata_size(fs_info,
5921                                                       num_csums - old_csums);
5922
5923         return btrfs_calc_trans_metadata_size(fs_info, old_csums - num_csums);
5924 }
5925
5926 int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
5927 {
5928         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
5929         struct btrfs_root *root = BTRFS_I(inode)->root;
5930         struct btrfs_block_rsv *block_rsv = &fs_info->delalloc_block_rsv;
5931         u64 to_reserve = 0;
5932         u64 csum_bytes;
5933         unsigned nr_extents;
5934         enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
5935         int ret = 0;
5936         bool delalloc_lock = true;
5937         u64 to_free = 0;
5938         unsigned dropped;
5939         bool release_extra = false;
5940
5941         /* If we are a free space inode we need to not flush since we will be in
5942          * the middle of a transaction commit.  We also don't need the delalloc
5943          * mutex since we won't race with anybody.  We need this mostly to make
5944          * lockdep shut its filthy mouth.
5945          *
5946          * If we have a transaction open (can happen if we call truncate_block
5947          * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
5948          */
5949         if (btrfs_is_free_space_inode(inode)) {
5950                 flush = BTRFS_RESERVE_NO_FLUSH;
5951                 delalloc_lock = false;
5952         } else if (current->journal_info) {
5953                 flush = BTRFS_RESERVE_FLUSH_LIMIT;
5954         }
5955
5956         if (flush != BTRFS_RESERVE_NO_FLUSH &&
5957             btrfs_transaction_in_commit(fs_info))
5958                 schedule_timeout(1);
5959
5960         if (delalloc_lock)
5961                 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
5962
5963         num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
5964
5965         spin_lock(&BTRFS_I(inode)->lock);
5966         nr_extents = count_max_extents(num_bytes);
5967         BTRFS_I(inode)->outstanding_extents += nr_extents;
5968
5969         nr_extents = 0;
5970         if (BTRFS_I(inode)->outstanding_extents >
5971             BTRFS_I(inode)->reserved_extents)
5972                 nr_extents += BTRFS_I(inode)->outstanding_extents -
5973                         BTRFS_I(inode)->reserved_extents;
5974
5975         /* We always want to reserve a slot for updating the inode. */
5976         to_reserve = btrfs_calc_trans_metadata_size(fs_info, nr_extents + 1);
5977         to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
5978         csum_bytes = BTRFS_I(inode)->csum_bytes;
5979         spin_unlock(&BTRFS_I(inode)->lock);
5980
5981         if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
5982                 ret = btrfs_qgroup_reserve_meta(root,
5983                                 nr_extents * fs_info->nodesize, true);
5984                 if (ret)
5985                         goto out_fail;
5986         }
5987
5988         ret = btrfs_block_rsv_add(root, block_rsv, to_reserve, flush);
5989         if (unlikely(ret)) {
5990                 btrfs_qgroup_free_meta(root,
5991                                        nr_extents * fs_info->nodesize);
5992                 goto out_fail;
5993         }
5994
5995         spin_lock(&BTRFS_I(inode)->lock);
5996         if (test_and_set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5997                              &BTRFS_I(inode)->runtime_flags)) {
5998                 to_reserve -= btrfs_calc_trans_metadata_size(fs_info, 1);
5999                 release_extra = true;
6000         }
6001         BTRFS_I(inode)->reserved_extents += nr_extents;
6002         spin_unlock(&BTRFS_I(inode)->lock);
6003
6004         if (delalloc_lock)
6005                 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
6006
6007         if (to_reserve)
6008                 trace_btrfs_space_reservation(fs_info, "delalloc",
6009                                       btrfs_ino(BTRFS_I(inode)), to_reserve, 1);
6010         if (release_extra)
6011                 btrfs_block_rsv_release(fs_info, block_rsv,
6012                                 btrfs_calc_trans_metadata_size(fs_info, 1));
6013         return 0;
6014
6015 out_fail:
6016         spin_lock(&BTRFS_I(inode)->lock);
6017         dropped = drop_outstanding_extent(inode, num_bytes);
6018         /*
6019          * If the inodes csum_bytes is the same as the original
6020          * csum_bytes then we know we haven't raced with any free()ers
6021          * so we can just reduce our inodes csum bytes and carry on.
6022          */
6023         if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
6024                 calc_csum_metadata_size(inode, num_bytes, 0);
6025         } else {
6026                 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
6027                 u64 bytes;
6028
6029                 /*
6030                  * This is tricky, but first we need to figure out how much we
6031                  * freed from any free-ers that occurred during this
6032                  * reservation, so we reset ->csum_bytes to the csum_bytes
6033                  * before we dropped our lock, and then call the free for the
6034                  * number of bytes that were freed while we were trying our
6035                  * reservation.
6036                  */
6037                 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
6038                 BTRFS_I(inode)->csum_bytes = csum_bytes;
6039                 to_free = calc_csum_metadata_size(inode, bytes, 0);
6040
6041
6042                 /*
6043                  * Now we need to see how much we would have freed had we not
6044                  * been making this reservation and our ->csum_bytes were not
6045                  * artificially inflated.
6046                  */
6047                 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
6048                 bytes = csum_bytes - orig_csum_bytes;
6049                 bytes = calc_csum_metadata_size(inode, bytes, 0);
6050
6051                 /*
6052                  * Now reset ->csum_bytes to what it should be.  If bytes is
6053                  * more than to_free then we would have freed more space had we
6054                  * not had an artificially high ->csum_bytes, so we need to free
6055                  * the remainder.  If bytes is the same or less then we don't
6056                  * need to do anything, the other free-ers did the correct
6057                  * thing.
6058                  */
6059                 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
6060                 if (bytes > to_free)
6061                         to_free = bytes - to_free;
6062                 else
6063                         to_free = 0;
6064         }
6065         spin_unlock(&BTRFS_I(inode)->lock);
6066         if (dropped)
6067                 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
6068
6069         if (to_free) {
6070                 btrfs_block_rsv_release(fs_info, block_rsv, to_free);
6071                 trace_btrfs_space_reservation(fs_info, "delalloc",
6072                                       btrfs_ino(BTRFS_I(inode)), to_free, 0);
6073         }
6074         if (delalloc_lock)
6075                 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
6076         return ret;
6077 }
6078
6079 /**
6080  * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
6081  * @inode: the inode to release the reservation for
6082  * @num_bytes: the number of bytes we're releasing
6083  *
6084  * This will release the metadata reservation for an inode.  This can be called
6085  * once we complete IO for a given set of bytes to release their metadata
6086  * reservations.
6087  */
6088 void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
6089 {
6090         struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
6091         u64 to_free = 0;
6092         unsigned dropped;
6093
6094         num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
6095         spin_lock(&BTRFS_I(inode)->lock);
6096         dropped = drop_outstanding_extent(inode, num_bytes);
6097
6098         if (num_bytes)
6099                 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
6100         spin_unlock(&BTRFS_I(inode)->lock);
6101         if (dropped > 0)
6102                 to_free += btrfs_calc_trans_metadata_size(fs_info, dropped);
6103
6104         if (btrfs_is_testing(fs_info))
6105                 return;
6106
6107         trace_btrfs_space_reservation(fs_info, "delalloc",
6108                                       btrfs_ino(BTRFS_I(inode)), to_free, 0);
6109
6110         btrfs_block_rsv_release(fs_info, &fs_info->delalloc_block_rsv, to_free);
6111 }
6112
6113 /**
6114  * btrfs_delalloc_reserve_space - reserve data and metadata space for
6115  * delalloc
6116  * @inode: inode we're writing to
6117  * @start: start range we are writing to
6118  * @len: how long the range we are writing to
6119  *
6120  * This will do the following things
6121  *
6122  * o reserve space in data space info for num bytes
6123  *   and reserve precious corresponding qgroup space
6124  *   (Done in check_data_free_space)
6125  *
6126  * o reserve space for metadata space, based on the number of outstanding
6127  *   extents and how much csums will be needed
6128  *   also reserve metadata space in a per root over-reserve method.
6129  * o add to the inodes->delalloc_bytes
6130  * o add it to the fs_info's delalloc inodes list.
6131  *   (Above 3 all done in delalloc_reserve_metadata)
6132  *
6133  * Return 0 for success
6134  * Return <0 for error(-ENOSPC or -EQUOT)
6135  */
6136 int btrfs_delalloc_reserve_space(struct inode *inode, u64 start, u64 len)
6137 {
6138         int ret;
6139
6140         ret = btrfs_check_data_free_space(inode, start, len);
6141         if (ret < 0)
6142                 return ret;
6143         ret = btrfs_delalloc_reserve_metadata(inode, len);
6144         if (ret < 0)
6145                 btrfs_free_reserved_data_space(inode, start, len);
6146         return ret;
6147 }
6148
6149 /**
6150  * btrfs_delalloc_release_space - release data and metadata space for delalloc
6151  * @inode: inode we're releasing space for
6152  * @start: start position of the space already reserved
6153  * @len: the len of the space already reserved
6154  *
6155  * This must be matched with a call to btrfs_delalloc_reserve_space.  This is
6156  * called in the case that we don't need the metadata AND data reservations
6157  * anymore.  So if there is an error or we insert an inline extent.
6158  *
6159  * This function will release the metadata space that was not used and will
6160  * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
6161  * list if there are no delalloc bytes left.
6162  * Also it will handle the qgroup reserved space.
6163  */
6164 void btrfs_delalloc_release_space(struct inode *inode, u64 start, u64 len)
6165 {
6166         btrfs_delalloc_release_metadata(inode, len);
6167         btrfs_free_reserved_data_space(inode, start, len);
6168 }
6169
6170 static int update_block_group(struct btrfs_trans_handle *trans,
6171                               struct btrfs_fs_info *info, u64 bytenr,
6172                               u64 num_bytes, int alloc)
6173 {
6174         struct btrfs_block_group_cache *cache = NULL;
6175         u64 total = num_bytes;
6176         u64 old_val;
6177         u64 byte_in_group;
6178         int factor;
6179
6180         /* block accounting for super block */
6181         spin_lock(&info->delalloc_root_lock);
6182         old_val = btrfs_super_bytes_used(info->super_copy);
6183         if (alloc)
6184                 old_val += num_bytes;
6185         else
6186                 old_val -= num_bytes;
6187         btrfs_set_super_bytes_used(info->super_copy, old_val);
6188         spin_unlock(&info->delalloc_root_lock);
6189
6190         while (total) {
6191                 cache = btrfs_lookup_block_group(info, bytenr);
6192                 if (!cache)
6193                         return -ENOENT;
6194                 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
6195                                     BTRFS_BLOCK_GROUP_RAID1 |
6196                                     BTRFS_BLOCK_GROUP_RAID10))
6197                         factor = 2;
6198                 else
6199                         factor = 1;
6200                 /*
6201                  * If this block group has free space cache written out, we
6202                  * need to make sure to load it if we are removing space.  This
6203                  * is because we need the unpinning stage to actually add the
6204                  * space back to the block group, otherwise we will leak space.
6205                  */
6206                 if (!alloc && cache->cached == BTRFS_CACHE_NO)
6207                         cache_block_group(cache, 1);
6208
6209                 byte_in_group = bytenr - cache->key.objectid;
6210                 WARN_ON(byte_in_group > cache->key.offset);
6211
6212                 spin_lock(&cache->space_info->lock);
6213                 spin_lock(&cache->lock);
6214
6215                 if (btrfs_test_opt(info, SPACE_CACHE) &&
6216                     cache->disk_cache_state < BTRFS_DC_CLEAR)
6217                         cache->disk_cache_state = BTRFS_DC_CLEAR;
6218
6219                 old_val = btrfs_block_group_used(&cache->item);
6220                 num_bytes = min(total, cache->key.offset - byte_in_group);
6221                 if (alloc) {
6222                         old_val += num_bytes;
6223                         btrfs_set_block_group_used(&cache->item, old_val);
6224                         cache->reserved -= num_bytes;
6225                         cache->space_info->bytes_reserved -= num_bytes;
6226                         cache->space_info->bytes_used += num_bytes;
6227                         cache->space_info->disk_used += num_bytes * factor;
6228                         spin_unlock(&cache->lock);
6229                         spin_unlock(&cache->space_info->lock);
6230                 } else {
6231                         old_val -= num_bytes;
6232                         btrfs_set_block_group_used(&cache->item, old_val);
6233                         cache->pinned += num_bytes;
6234                         cache->space_info->bytes_pinned += num_bytes;
6235                         cache->space_info->bytes_used -= num_bytes;
6236                         cache->space_info->disk_used -= num_bytes * factor;
6237                         spin_unlock(&cache->lock);
6238                         spin_unlock(&cache->space_info->lock);
6239
6240                         trace_btrfs_space_reservation(info, "pinned",
6241                                                       cache->space_info->flags,
6242                                                       num_bytes, 1);
6243                         set_extent_dirty(info->pinned_extents,
6244                                          bytenr, bytenr + num_bytes - 1,
6245                                          GFP_NOFS | __GFP_NOFAIL);
6246                 }
6247
6248                 spin_lock(&trans->transaction->dirty_bgs_lock);
6249                 if (list_empty(&cache->dirty_list)) {
6250                         list_add_tail(&cache->dirty_list,
6251                                       &trans->transaction->dirty_bgs);
6252                                 trans->transaction->num_dirty_bgs++;
6253                         btrfs_get_block_group(cache);
6254                 }
6255                 spin_unlock(&trans->transaction->dirty_bgs_lock);
6256
6257                 /*
6258                  * No longer have used bytes in this block group, queue it for
6259                  * deletion. We do this after adding the block group to the
6260                  * dirty list to avoid races between cleaner kthread and space
6261                  * cache writeout.
6262                  */
6263                 if (!alloc && old_val == 0) {
6264                         spin_lock(&info->unused_bgs_lock);
6265                         if (list_empty(&cache->bg_list)) {
6266                                 btrfs_get_block_group(cache);
6267                                 list_add_tail(&cache->bg_list,
6268                                               &info->unused_bgs);
6269                         }
6270                         spin_unlock(&info->unused_bgs_lock);
6271                 }
6272
6273                 btrfs_put_block_group(cache);
6274                 total -= num_bytes;
6275                 bytenr += num_bytes;
6276         }
6277         return 0;
6278 }
6279
6280 static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
6281 {
6282         struct btrfs_block_group_cache *cache;
6283         u64 bytenr;
6284
6285         spin_lock(&fs_info->block_group_cache_lock);
6286         bytenr = fs_info->first_logical_byte;
6287         spin_unlock(&fs_info->block_group_cache_lock);
6288
6289         if (bytenr < (u64)-1)
6290                 return bytenr;
6291
6292         cache = btrfs_lookup_first_block_group(fs_info, search_start);
6293         if (!cache)
6294                 return 0;
6295
6296         bytenr = cache->key.objectid;
6297         btrfs_put_block_group(cache);
6298
6299         return bytenr;
6300 }
6301
6302 static int pin_down_extent(struct btrfs_fs_info *fs_info,
6303                            struct btrfs_block_group_cache *cache,
6304                            u64 bytenr, u64 num_bytes, int reserved)
6305 {
6306         spin_lock(&cache->space_info->lock);
6307         spin_lock(&cache->lock);
6308         cache->pinned += num_bytes;
6309         cache->space_info->bytes_pinned += num_bytes;
6310         if (reserved) {
6311                 cache->reserved -= num_bytes;
6312                 cache->space_info->bytes_reserved -= num_bytes;
6313         }
6314         spin_unlock(&cache->lock);
6315         spin_unlock(&cache->space_info->lock);
6316
6317         trace_btrfs_space_reservation(fs_info, "pinned",
6318                                       cache->space_info->flags, num_bytes, 1);
6319         set_extent_dirty(fs_info->pinned_extents, bytenr,
6320                          bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
6321         return 0;
6322 }
6323
6324 /*
6325  * this function must be called within transaction
6326  */
6327 int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
6328                      u64 bytenr, u64 num_bytes, int reserved)
6329 {
6330         struct btrfs_block_group_cache *cache;
6331
6332         cache = btrfs_lookup_block_group(fs_info, bytenr);
6333         BUG_ON(!cache); /* Logic error */
6334
6335         pin_down_extent(fs_info, cache, bytenr, num_bytes, reserved);
6336
6337         btrfs_put_block_group(cache);
6338         return 0;
6339 }
6340
6341 /*
6342  * this function must be called within transaction
6343  */
6344 int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
6345                                     u64 bytenr, u64 num_bytes)
6346 {
6347         struct btrfs_block_group_cache *cache;
6348         int ret;
6349
6350         cache = btrfs_lookup_block_group(fs_info, bytenr);
6351         if (!cache)
6352                 return -EINVAL;
6353
6354         /*
6355          * pull in the free space cache (if any) so that our pin
6356          * removes the free space from the cache.  We have load_only set
6357          * to one because the slow code to read in the free extents does check
6358          * the pinned extents.
6359          */
6360         cache_block_group(cache, 1);
6361
6362         pin_down_extent(fs_info, cache, bytenr, num_bytes, 0);
6363
6364         /* remove us from the free space cache (if we're there at all) */
6365         ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
6366         btrfs_put_block_group(cache);
6367         return ret;
6368 }
6369
6370 static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
6371                                    u64 start, u64 num_bytes)
6372 {
6373         int ret;
6374         struct btrfs_block_group_cache *block_group;
6375         struct btrfs_caching_control *caching_ctl;
6376
6377         block_group = btrfs_lookup_block_group(fs_info, start);
6378         if (!block_group)
6379                 return -EINVAL;
6380
6381         cache_block_group(block_group, 0);
6382         caching_ctl = get_caching_control(block_group);
6383
6384         if (!caching_ctl) {
6385                 /* Logic error */
6386                 BUG_ON(!block_group_cache_done(block_group));
6387                 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6388         } else {
6389                 mutex_lock(&caching_ctl->mutex);
6390
6391                 if (start >= caching_ctl->progress) {
6392                         ret = add_excluded_extent(fs_info, start, num_bytes);
6393                 } else if (start + num_bytes <= caching_ctl->progress) {
6394                         ret = btrfs_remove_free_space(block_group,
6395                                                       start, num_bytes);
6396                 } else {
6397                         num_bytes = caching_ctl->progress - start;
6398                         ret = btrfs_remove_free_space(block_group,
6399                                                       start, num_bytes);
6400                         if (ret)
6401                                 goto out_lock;
6402
6403                         num_bytes = (start + num_bytes) -
6404                                 caching_ctl->progress;
6405                         start = caching_ctl->progress;
6406                         ret = add_excluded_extent(fs_info, start, num_bytes);
6407                 }
6408 out_lock:
6409                 mutex_unlock(&caching_ctl->mutex);
6410                 put_caching_control(caching_ctl);
6411         }
6412         btrfs_put_block_group(block_group);
6413         return ret;
6414 }
6415
6416 int btrfs_exclude_logged_extents(struct btrfs_fs_info *fs_info,
6417                                  struct extent_buffer *eb)
6418 {
6419         struct btrfs_file_extent_item *item;
6420         struct btrfs_key key;
6421         int found_type;
6422         int i;
6423
6424         if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
6425                 return 0;
6426
6427         for (i = 0; i < btrfs_header_nritems(eb); i++) {
6428                 btrfs_item_key_to_cpu(eb, &key, i);
6429                 if (key.type != BTRFS_EXTENT_DATA_KEY)
6430                         continue;
6431                 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6432                 found_type = btrfs_file_extent_type(eb, item);
6433                 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6434                         continue;
6435                 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6436                         continue;
6437                 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6438                 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6439                 __exclude_logged_extent(fs_info, key.objectid, key.offset);
6440         }
6441
6442         return 0;
6443 }
6444
6445 static void
6446 btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
6447 {
6448         atomic_inc(&bg->reservations);
6449 }
6450
6451 void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
6452                                         const u64 start)
6453 {
6454         struct btrfs_block_group_cache *bg;
6455
6456         bg = btrfs_lookup_block_group(fs_info, start);
6457         ASSERT(bg);
6458         if (atomic_dec_and_test(&bg->reservations))
6459                 wake_up_atomic_t(&bg->reservations);
6460         btrfs_put_block_group(bg);
6461 }
6462
6463 static int btrfs_wait_bg_reservations_atomic_t(atomic_t *a)
6464 {
6465         schedule();
6466         return 0;
6467 }
6468
6469 void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
6470 {
6471         struct btrfs_space_info *space_info = bg->space_info;
6472
6473         ASSERT(bg->ro);
6474
6475         if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
6476                 return;
6477
6478         /*
6479          * Our block group is read only but before we set it to read only,
6480          * some task might have had allocated an extent from it already, but it
6481          * has not yet created a respective ordered extent (and added it to a
6482          * root's list of ordered extents).
6483          * Therefore wait for any task currently allocating extents, since the
6484          * block group's reservations counter is incremented while a read lock
6485          * on the groups' semaphore is held and decremented after releasing
6486          * the read access on that semaphore and creating the ordered extent.
6487          */
6488         down_write(&space_info->groups_sem);
6489         up_write(&space_info->groups_sem);
6490
6491         wait_on_atomic_t(&bg->reservations,
6492                          btrfs_wait_bg_reservations_atomic_t,
6493                          TASK_UNINTERRUPTIBLE);
6494 }
6495
6496 /**
6497  * btrfs_add_reserved_bytes - update the block_group and space info counters
6498  * @cache:      The cache we are manipulating
6499  * @ram_bytes:  The number of bytes of file content, and will be same to
6500  *              @num_bytes except for the compress path.
6501  * @num_bytes:  The number of bytes in question
6502  * @delalloc:   The blocks are allocated for the delalloc write
6503  *
6504  * This is called by the allocator when it reserves space. If this is a
6505  * reservation and the block group has become read only we cannot make the
6506  * reservation and return -EAGAIN, otherwise this function always succeeds.
6507  */
6508 static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
6509                                     u64 ram_bytes, u64 num_bytes, int delalloc)
6510 {
6511         struct btrfs_space_info *space_info = cache->space_info;
6512         int ret = 0;
6513
6514         spin_lock(&space_info->lock);
6515         spin_lock(&cache->lock);
6516         if (cache->ro) {
6517                 ret = -EAGAIN;
6518         } else {
6519                 cache->reserved += num_bytes;
6520                 space_info->bytes_reserved += num_bytes;
6521
6522                 trace_btrfs_space_reservation(cache->fs_info,
6523                                 "space_info", space_info->flags,
6524                                 ram_bytes, 0);
6525                 space_info->bytes_may_use -= ram_bytes;
6526                 if (delalloc)
6527                         cache->delalloc_bytes += num_bytes;
6528         }
6529         spin_unlock(&cache->lock);
6530         spin_unlock(&space_info->lock);
6531         return ret;
6532 }
6533
6534 /**
6535  * btrfs_free_reserved_bytes - update the block_group and space info counters
6536  * @cache:      The cache we are manipulating
6537  * @num_bytes:  The number of bytes in question
6538  * @delalloc:   The blocks are allocated for the delalloc write
6539  *
6540  * This is called by somebody who is freeing space that was never actually used
6541  * on disk.  For example if you reserve some space for a new leaf in transaction
6542  * A and before transaction A commits you free that leaf, you call this with
6543  * reserve set to 0 in order to clear the reservation.
6544  */
6545
6546 static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
6547                                      u64 num_bytes, int delalloc)
6548 {
6549         struct btrfs_space_info *space_info = cache->space_info;
6550         int ret = 0;
6551
6552         spin_lock(&space_info->lock);
6553         spin_lock(&cache->lock);
6554         if (cache->ro)
6555                 space_info->bytes_readonly += num_bytes;
6556         cache->reserved -= num_bytes;
6557         space_info->bytes_reserved -= num_bytes;
6558
6559         if (delalloc)
6560                 cache->delalloc_bytes -= num_bytes;
6561         spin_unlock(&cache->lock);
6562         spin_unlock(&space_info->lock);
6563         return ret;
6564 }
6565 void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
6566 {
6567         struct btrfs_caching_control *next;
6568         struct btrfs_caching_control *caching_ctl;
6569         struct btrfs_block_group_cache *cache;
6570
6571         down_write(&fs_info->commit_root_sem);
6572
6573         list_for_each_entry_safe(caching_ctl, next,
6574                                  &fs_info->caching_block_groups, list) {
6575                 cache = caching_ctl->block_group;
6576                 if (block_group_cache_done(cache)) {
6577                         cache->last_byte_to_unpin = (u64)-1;
6578                         list_del_init(&caching_ctl->list);
6579                         put_caching_control(caching_ctl);
6580                 } else {
6581                         cache->last_byte_to_unpin = caching_ctl->progress;
6582                 }
6583         }
6584
6585         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6586                 fs_info->pinned_extents = &fs_info->freed_extents[1];
6587         else
6588                 fs_info->pinned_extents = &fs_info->freed_extents[0];
6589
6590         up_write(&fs_info->commit_root_sem);
6591
6592         update_global_block_rsv(fs_info);
6593 }
6594
6595 /*
6596  * Returns the free cluster for the given space info and sets empty_cluster to
6597  * what it should be based on the mount options.
6598  */
6599 static struct btrfs_free_cluster *
6600 fetch_cluster_info(struct btrfs_fs_info *fs_info,
6601                    struct btrfs_space_info *space_info, u64 *empty_cluster)
6602 {
6603         struct btrfs_free_cluster *ret = NULL;
6604         bool ssd = btrfs_test_opt(fs_info, SSD);
6605
6606         *empty_cluster = 0;
6607         if (btrfs_mixed_space_info(space_info))
6608                 return ret;
6609
6610         if (ssd)
6611                 *empty_cluster = SZ_2M;
6612         if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6613                 ret = &fs_info->meta_alloc_cluster;
6614                 if (!ssd)
6615                         *empty_cluster = SZ_64K;
6616         } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && ssd) {
6617                 ret = &fs_info->data_alloc_cluster;
6618         }
6619
6620         return ret;
6621 }
6622
6623 static int unpin_extent_range(struct btrfs_fs_info *fs_info,
6624                               u64 start, u64 end,
6625                               const bool return_free_space)
6626 {
6627         struct btrfs_block_group_cache *cache = NULL;
6628         struct btrfs_space_info *space_info;
6629         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
6630         struct btrfs_free_cluster *cluster = NULL;
6631         u64 len;
6632         u64 total_unpinned = 0;
6633         u64 empty_cluster = 0;
6634         bool readonly;
6635
6636         while (start <= end) {
6637                 readonly = false;
6638                 if (!cache ||
6639                     start >= cache->key.objectid + cache->key.offset) {
6640                         if (cache)
6641                                 btrfs_put_block_group(cache);
6642                         total_unpinned = 0;
6643                         cache = btrfs_lookup_block_group(fs_info, start);
6644                         BUG_ON(!cache); /* Logic error */
6645
6646                         cluster = fetch_cluster_info(fs_info,
6647                                                      cache->space_info,
6648                                                      &empty_cluster);
6649                         empty_cluster <<= 1;
6650                 }
6651
6652                 len = cache->key.objectid + cache->key.offset - start;
6653                 len = min(len, end + 1 - start);
6654
6655                 if (start < cache->last_byte_to_unpin) {
6656                         len = min(len, cache->last_byte_to_unpin - start);
6657                         if (return_free_space)
6658                                 btrfs_add_free_space(cache, start, len);
6659                 }
6660
6661                 start += len;
6662                 total_unpinned += len;
6663                 space_info = cache->space_info;
6664
6665                 /*
6666                  * If this space cluster has been marked as fragmented and we've
6667                  * unpinned enough in this block group to potentially allow a
6668                  * cluster to be created inside of it go ahead and clear the
6669                  * fragmented check.
6670                  */
6671                 if (cluster && cluster->fragmented &&
6672                     total_unpinned > empty_cluster) {
6673                         spin_lock(&cluster->lock);
6674                         cluster->fragmented = 0;
6675                         spin_unlock(&cluster->lock);
6676                 }
6677
6678                 spin_lock(&space_info->lock);
6679                 spin_lock(&cache->lock);
6680                 cache->pinned -= len;
6681                 space_info->bytes_pinned -= len;
6682
6683                 trace_btrfs_space_reservation(fs_info, "pinned",
6684                                               space_info->flags, len, 0);
6685                 space_info->max_extent_size = 0;
6686                 percpu_counter_add(&space_info->total_bytes_pinned, -len);
6687                 if (cache->ro) {
6688                         space_info->bytes_readonly += len;
6689                         readonly = true;
6690                 }
6691                 spin_unlock(&cache->lock);
6692                 if (!readonly && return_free_space &&
6693                     global_rsv->space_info == space_info) {
6694                         u64 to_add = len;
6695                         WARN_ON(!return_free_space);
6696                         spin_lock(&global_rsv->lock);
6697                         if (!global_rsv->full) {
6698                                 to_add = min(len, global_rsv->size -
6699                                              global_rsv->reserved);
6700                                 global_rsv->reserved += to_add;
6701                                 space_info->bytes_may_use += to_add;
6702                                 if (global_rsv->reserved >= global_rsv->size)
6703                                         global_rsv->full = 1;
6704                                 trace_btrfs_space_reservation(fs_info,
6705                                                               "space_info",
6706                                                               space_info->flags,
6707                                                               to_add, 1);
6708                                 len -= to_add;
6709                         }
6710                         spin_unlock(&global_rsv->lock);
6711                         /* Add to any tickets we may have */
6712                         if (len)
6713                                 space_info_add_new_bytes(fs_info, space_info,
6714                                                          len);
6715                 }
6716                 spin_unlock(&space_info->lock);
6717         }
6718
6719         if (cache)
6720                 btrfs_put_block_group(cache);
6721         return 0;
6722 }
6723
6724 int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
6725                                struct btrfs_fs_info *fs_info)
6726 {
6727         struct btrfs_block_group_cache *block_group, *tmp;
6728         struct list_head *deleted_bgs;
6729         struct extent_io_tree *unpin;
6730         u64 start;
6731         u64 end;
6732         int ret;
6733
6734         if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6735                 unpin = &fs_info->freed_extents[1];
6736         else
6737                 unpin = &fs_info->freed_extents[0];
6738
6739         while (!trans->aborted) {
6740                 mutex_lock(&fs_info->unused_bg_unpin_mutex);
6741                 ret = find_first_extent_bit(unpin, 0, &start, &end,
6742                                             EXTENT_DIRTY, NULL);
6743                 if (ret) {
6744                         mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6745                         break;
6746                 }
6747
6748                 if (btrfs_test_opt(fs_info, DISCARD))
6749                         ret = btrfs_discard_extent(fs_info, start,
6750                                                    end + 1 - start, NULL);
6751
6752                 clear_extent_dirty(unpin, start, end);
6753                 unpin_extent_range(fs_info, start, end, true);
6754                 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
6755                 cond_resched();
6756         }
6757
6758         /*
6759          * Transaction is finished.  We don't need the lock anymore.  We
6760          * do need to clean up the block groups in case of a transaction
6761          * abort.
6762          */
6763         deleted_bgs = &trans->transaction->deleted_bgs;
6764         list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6765                 u64 trimmed = 0;
6766
6767                 ret = -EROFS;
6768                 if (!trans->aborted)
6769                         ret = btrfs_discard_extent(fs_info,
6770                                                    block_group->key.objectid,
6771                                                    block_group->key.offset,
6772                                                    &trimmed);
6773
6774                 list_del_init(&block_group->bg_list);
6775                 btrfs_put_block_group_trimming(block_group);
6776                 btrfs_put_block_group(block_group);
6777
6778                 if (ret) {
6779                         const char *errstr = btrfs_decode_error(ret);
6780                         btrfs_warn(fs_info,
6781                                    "Discard failed while removing blockgroup: errno=%d %s\n",
6782                                    ret, errstr);
6783                 }
6784         }
6785
6786         return 0;
6787 }
6788
6789 static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
6790                              u64 owner, u64 root_objectid)
6791 {
6792         struct btrfs_space_info *space_info;
6793         u64 flags;
6794
6795         if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6796                 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
6797                         flags = BTRFS_BLOCK_GROUP_SYSTEM;
6798                 else
6799                         flags = BTRFS_BLOCK_GROUP_METADATA;
6800         } else {
6801                 flags = BTRFS_BLOCK_GROUP_DATA;
6802         }
6803
6804         space_info = __find_space_info(fs_info, flags);
6805         BUG_ON(!space_info); /* Logic bug */
6806         percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
6807 }
6808
6809
6810 static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6811                                 struct btrfs_fs_info *info,
6812                                 struct btrfs_delayed_ref_node *node, u64 parent,
6813                                 u64 root_objectid, u64 owner_objectid,
6814                                 u64 owner_offset, int refs_to_drop,
6815                                 struct btrfs_delayed_extent_op *extent_op)
6816 {
6817         struct btrfs_key key;
6818         struct btrfs_path *path;
6819         struct btrfs_root *extent_root = info->extent_root;
6820         struct extent_buffer *leaf;
6821         struct btrfs_extent_item *ei;
6822         struct btrfs_extent_inline_ref *iref;
6823         int ret;
6824         int is_data;
6825         int extent_slot = 0;
6826         int found_extent = 0;
6827         int num_to_del = 1;
6828         u32 item_size;
6829         u64 refs;
6830         u64 bytenr = node->bytenr;
6831         u64 num_bytes = node->num_bytes;
6832         int last_ref = 0;
6833         bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
6834
6835         path = btrfs_alloc_path();
6836         if (!path)
6837                 return -ENOMEM;
6838
6839         path->reada = READA_FORWARD;
6840         path->leave_spinning = 1;
6841
6842         is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6843         BUG_ON(!is_data && refs_to_drop != 1);
6844
6845         if (is_data)
6846                 skinny_metadata = 0;
6847
6848         ret = lookup_extent_backref(trans, info, path, &iref,
6849                                     bytenr, num_bytes, parent,
6850                                     root_objectid, owner_objectid,
6851                                     owner_offset);
6852         if (ret == 0) {
6853                 extent_slot = path->slots[0];
6854                 while (extent_slot >= 0) {
6855                         btrfs_item_key_to_cpu(path->nodes[0], &key,
6856                                               extent_slot);
6857                         if (key.objectid != bytenr)
6858                                 break;
6859                         if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6860                             key.offset == num_bytes) {
6861                                 found_extent = 1;
6862                                 break;
6863                         }
6864                         if (key.type == BTRFS_METADATA_ITEM_KEY &&
6865                             key.offset == owner_objectid) {
6866                                 found_extent = 1;
6867                                 break;
6868                         }
6869                         if (path->slots[0] - extent_slot > 5)
6870                                 break;
6871                         extent_slot--;
6872                 }
6873 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6874                 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
6875                 if (found_extent && item_size < sizeof(*ei))
6876                         found_extent = 0;
6877 #endif
6878                 if (!found_extent) {
6879                         BUG_ON(iref);
6880                         ret = remove_extent_backref(trans, info, path, NULL,
6881                                                     refs_to_drop,
6882                                                     is_data, &last_ref);
6883                         if (ret) {
6884                                 btrfs_abort_transaction(trans, ret);
6885                                 goto out;
6886                         }
6887                         btrfs_release_path(path);
6888                         path->leave_spinning = 1;
6889
6890                         key.objectid = bytenr;
6891                         key.type = BTRFS_EXTENT_ITEM_KEY;
6892                         key.offset = num_bytes;
6893
6894                         if (!is_data && skinny_metadata) {
6895                                 key.type = BTRFS_METADATA_ITEM_KEY;
6896                                 key.offset = owner_objectid;
6897                         }
6898
6899                         ret = btrfs_search_slot(trans, extent_root,
6900                                                 &key, path, -1, 1);
6901                         if (ret > 0 && skinny_metadata && path->slots[0]) {
6902                                 /*
6903                                  * Couldn't find our skinny metadata item,
6904                                  * see if we have ye olde extent item.
6905                                  */
6906                                 path->slots[0]--;
6907                                 btrfs_item_key_to_cpu(path->nodes[0], &key,
6908                                                       path->slots[0]);
6909                                 if (key.objectid == bytenr &&
6910                                     key.type == BTRFS_EXTENT_ITEM_KEY &&
6911                                     key.offset == num_bytes)
6912                                         ret = 0;
6913                         }
6914
6915                         if (ret > 0 && skinny_metadata) {
6916                                 skinny_metadata = false;
6917                                 key.objectid = bytenr;
6918                                 key.type = BTRFS_EXTENT_ITEM_KEY;
6919                                 key.offset = num_bytes;
6920                                 btrfs_release_path(path);
6921                                 ret = btrfs_search_slot(trans, extent_root,
6922                                                         &key, path, -1, 1);
6923                         }
6924
6925                         if (ret) {
6926                                 btrfs_err(info,
6927                                           "umm, got %d back from search, was looking for %llu",
6928                                           ret, bytenr);
6929                                 if (ret > 0)
6930                                         btrfs_print_leaf(info, path->nodes[0]);
6931                         }
6932                         if (ret < 0) {
6933                                 btrfs_abort_transaction(trans, ret);
6934                                 goto out;
6935                         }
6936                         extent_slot = path->slots[0];
6937                 }
6938         } else if (WARN_ON(ret == -ENOENT)) {
6939                 btrfs_print_leaf(info, path->nodes[0]);
6940                 btrfs_err(info,
6941                         "unable to find ref byte nr %llu parent %llu root %llu  owner %llu offset %llu",
6942                         bytenr, parent, root_objectid, owner_objectid,
6943                         owner_offset);
6944                 btrfs_abort_transaction(trans, ret);
6945                 goto out;
6946         } else {
6947                 btrfs_abort_transaction(trans, ret);
6948                 goto out;
6949         }
6950
6951         leaf = path->nodes[0];
6952         item_size = btrfs_item_size_nr(leaf, extent_slot);
6953 #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6954         if (item_size < sizeof(*ei)) {
6955                 BUG_ON(found_extent || extent_slot != path->slots[0]);
6956                 ret = convert_extent_item_v0(trans, info, path, owner_objectid,
6957                                              0);
6958                 if (ret < 0) {
6959                         btrfs_abort_transaction(trans, ret);
6960                         goto out;
6961                 }
6962
6963                 btrfs_release_path(path);
6964                 path->leave_spinning = 1;
6965
6966                 key.objectid = bytenr;
6967                 key.type = BTRFS_EXTENT_ITEM_KEY;
6968                 key.offset = num_bytes;
6969
6970                 ret = btrfs_search_slot(trans, extent_root, &key, path,
6971                                         -1, 1);
6972                 if (ret) {
6973                         btrfs_err(info,
6974                                   "umm, got %d back from search, was looking for %llu",
6975                                 ret, bytenr);
6976                         btrfs_print_leaf(info, path->nodes[0]);
6977                 }
6978                 if (ret < 0) {
6979                         btrfs_abort_transaction(trans, ret);
6980                         goto out;
6981                 }
6982
6983                 extent_slot = path->slots[0];
6984                 leaf = path->nodes[0];
6985                 item_size = btrfs_item_size_nr(leaf, extent_slot);
6986         }
6987 #endif
6988         BUG_ON(item_size < sizeof(*ei));
6989         ei = btrfs_item_ptr(leaf, extent_slot,
6990                             struct btrfs_extent_item);
6991         if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
6992             key.type == BTRFS_EXTENT_ITEM_KEY) {
6993                 struct btrfs_tree_block_info *bi;
6994                 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
6995                 bi = (struct btrfs_tree_block_info *)(ei + 1);
6996                 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
6997         }
6998
6999         refs = btrfs_extent_refs(leaf, ei);
7000         if (refs < refs_to_drop) {
7001                 btrfs_err(info,
7002                           "trying to drop %d refs but we only have %Lu for bytenr %Lu",
7003                           refs_to_drop, refs, bytenr);
7004                 ret = -EINVAL;
7005                 btrfs_abort_transaction(trans, ret);
7006                 goto out;
7007         }
7008         refs -= refs_to_drop;
7009
7010         if (refs > 0) {
7011                 if (extent_op)
7012                         __run_delayed_extent_op(extent_op, leaf, ei);
7013                 /*
7014                  * In the case of inline back ref, reference count will
7015                  * be updated by remove_extent_backref
7016                  */
7017                 if (iref) {
7018                         BUG_ON(!found_extent);
7019                 } else {
7020                         btrfs_set_extent_refs(leaf, ei, refs);
7021                         btrfs_mark_buffer_dirty(leaf);
7022                 }
7023                 if (found_extent) {
7024                         ret = remove_extent_backref(trans, info, path,
7025                                                     iref, refs_to_drop,
7026                                                     is_data, &last_ref);
7027                         if (ret) {
7028                                 btrfs_abort_transaction(trans, ret);
7029                                 goto out;
7030                         }
7031                 }
7032                 add_pinned_bytes(info, -num_bytes, owner_objectid,
7033                                  root_objectid);
7034         } else {
7035                 if (found_extent) {
7036                         BUG_ON(is_data && refs_to_drop !=
7037                                extent_data_ref_count(path, iref));
7038                         if (iref) {
7039                                 BUG_ON(path->slots[0] != extent_slot);
7040                         } else {
7041                                 BUG_ON(path->slots[0] != extent_slot + 1);
7042                                 path->slots[0] = extent_slot;
7043                                 num_to_del = 2;
7044                         }
7045                 }
7046
7047                 last_ref = 1;
7048                 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
7049                                       num_to_del);
7050                 if (ret) {
7051                         btrfs_abort_transaction(trans, ret);
7052                         goto out;
7053                 }
7054                 btrfs_release_path(path);
7055
7056                 if (is_data) {
7057                         ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
7058                         if (ret) {
7059                                 btrfs_abort_transaction(trans, ret);
7060                                 goto out;
7061                         }
7062                 }
7063
7064                 ret = add_to_free_space_tree(trans, info, bytenr, num_bytes);
7065                 if (ret) {
7066                         btrfs_abort_transaction(trans, ret);
7067                         goto out;
7068                 }
7069
7070                 ret = update_block_group(trans, info, bytenr, num_bytes, 0);
7071                 if (ret) {
7072                         btrfs_abort_transaction(trans, ret);
7073                         goto out;
7074                 }
7075         }
7076         btrfs_release_path(path);
7077
7078 out:
7079         btrfs_free_path(path);
7080         return ret;
7081 }
7082
7083 /*
7084  * when we free an block, it is possible (and likely) that we free the last
7085  * delayed ref for that extent as well.  This searches the delayed ref tree for
7086  * a given extent, and if there are no other delayed refs to be processed, it
7087  * removes it from the tree.
7088  */
7089 static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
7090                                       u64 bytenr)
7091 {
7092         struct btrfs_delayed_ref_head *head;
7093         struct btrfs_delayed_ref_root *delayed_refs;
7094         int ret = 0;
7095
7096         delayed_refs = &trans->transaction->delayed_refs;
7097         spin_lock(&delayed_refs->lock);
7098         head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
7099         if (!head)
7100                 goto out_delayed_unlock;
7101
7102         spin_lock(&head->lock);
7103         if (!list_empty(&head->ref_list))
7104                 goto out;
7105
7106         if (head->extent_op) {
7107                 if (!head->must_insert_reserved)
7108                         goto out;
7109                 btrfs_free_delayed_extent_op(head->extent_op);
7110                 head->extent_op = NULL;
7111         }
7112
7113         /*
7114          * waiting for the lock here would deadlock.  If someone else has it
7115          * locked they are already in the process of dropping it anyway
7116          */
7117         if (!mutex_trylock(&head->mutex))
7118                 goto out;
7119
7120         /*
7121          * at this point we have a head with no other entries.  Go
7122          * ahead and process it.
7123          */
7124         head->node.in_tree = 0;
7125         rb_erase(&head->href_node, &delayed_refs->href_root);
7126
7127         atomic_dec(&delayed_refs->num_entries);
7128
7129         /*
7130          * we don't take a ref on the node because we're removing it from the
7131          * tree, so we just steal the ref the tree was holding.
7132          */
7133         delayed_refs->num_heads--;
7134         if (head->processing == 0)
7135                 delayed_refs->num_heads_ready--;
7136         head->processing = 0;
7137         spin_unlock(&head->lock);
7138         spin_unlock(&delayed_refs->lock);
7139
7140         BUG_ON(head->extent_op);
7141         if (head->must_insert_reserved)
7142                 ret = 1;
7143
7144         mutex_unlock(&head->mutex);
7145         btrfs_put_delayed_ref(&head->node);
7146         return ret;
7147 out:
7148         spin_unlock(&head->lock);
7149
7150 out_delayed_unlock:
7151         spin_unlock(&delayed_refs->lock);
7152         return 0;
7153 }
7154
7155 void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
7156                            struct btrfs_root *root,
7157                            struct extent_buffer *buf,
7158                            u64 parent, int last_ref)
7159 {
7160         struct btrfs_fs_info *fs_info = root->fs_info;
7161         int pin = 1;
7162         int ret;
7163
7164         if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7165                 ret = btrfs_add_delayed_tree_ref(fs_info, trans,
7166                                                  buf->start, buf->len,
7167                                                  parent,
7168                                                  root->root_key.objectid,
7169                                                  btrfs_header_level(buf),
7170                                                  BTRFS_DROP_DELAYED_REF, NULL);
7171                 BUG_ON(ret); /* -ENOMEM */
7172         }
7173
7174         if (!last_ref)
7175                 return;
7176
7177         if (btrfs_header_generation(buf) == trans->transid) {
7178                 struct btrfs_block_group_cache *cache;
7179
7180                 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
7181                         ret = check_ref_cleanup(trans, buf->start);
7182                         if (!ret)
7183                                 goto out;
7184                 }
7185
7186                 cache = btrfs_lookup_block_group(fs_info, buf->start);
7187
7188                 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
7189                         pin_down_extent(fs_info, cache, buf->start,
7190                                         buf->len, 1);
7191                         btrfs_put_block_group(cache);
7192                         goto out;
7193                 }
7194
7195                 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
7196
7197                 btrfs_add_free_space(cache, buf->start, buf->len);
7198                 btrfs_free_reserved_bytes(cache, buf->len, 0);
7199                 btrfs_put_block_group(cache);
7200                 trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
7201                 pin = 0;
7202         }
7203 out:
7204         if (pin)
7205                 add_pinned_bytes(fs_info, buf->len, btrfs_header_level(buf),
7206                                  root->root_key.objectid);
7207
7208         /*
7209          * Deleting the buffer, clear the corrupt flag since it doesn't matter
7210          * anymore.
7211          */
7212         clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
7213 }
7214
7215 /* Can return -ENOMEM */
7216 int btrfs_free_extent(struct btrfs_trans_handle *trans,
7217                       struct btrfs_fs_info *fs_info,
7218                       u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
7219                       u64 owner, u64 offset)
7220 {
7221         int ret;
7222
7223         if (btrfs_is_testing(fs_info))
7224                 return 0;
7225
7226         add_pinned_bytes(fs_info, num_bytes, owner, root_objectid);
7227
7228         /*
7229          * tree log blocks never actually go into the extent allocation
7230          * tree, just update pinning info and exit early.
7231          */
7232         if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
7233                 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
7234                 /* unlocks the pinned mutex */
7235                 btrfs_pin_extent(fs_info, bytenr, num_bytes, 1);
7236                 ret = 0;
7237         } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
7238                 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
7239                                         num_bytes,
7240                                         parent, root_objectid, (int)owner,
7241                                         BTRFS_DROP_DELAYED_REF, NULL);
7242         } else {
7243                 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
7244                                                 num_bytes,
7245                                                 parent, root_objectid, owner,
7246                                                 offset, 0,
7247                                                 BTRFS_DROP_DELAYED_REF);
7248         }
7249         return ret;
7250 }
7251
7252 /*
7253  * when we wait for progress in the block group caching, its because
7254  * our allocation attempt failed at least once.  So, we must sleep
7255  * and let some progress happen before we try again.
7256  *
7257  * This function will sleep at least once waiting for new free space to
7258  * show up, and then it will check the block group free space numbers
7259  * for our min num_bytes.  Another option is to have it go ahead
7260  * and look in the rbtree for a free extent of a given size, but this
7261  * is a good start.
7262  *
7263  * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
7264  * any of the information in this block group.
7265  */
7266 static noinline void
7267 wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
7268                                 u64 num_bytes)
7269 {
7270         struct btrfs_caching_control *caching_ctl;
7271
7272         caching_ctl = get_caching_control(cache);
7273         if (!caching_ctl)
7274                 return;
7275
7276         wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
7277                    (cache->free_space_ctl->free_space >= num_bytes));
7278
7279         put_caching_control(caching_ctl);
7280 }
7281
7282 static noinline int
7283 wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
7284 {
7285         struct btrfs_caching_control *caching_ctl;
7286         int ret = 0;
7287
7288         caching_ctl = get_caching_control(cache);
7289         if (!caching_ctl)
7290                 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
7291
7292         wait_event(caching_ctl->wait, block_group_cache_done(cache));
7293         if (cache->cached == BTRFS_CACHE_ERROR)
7294                 ret = -EIO;
7295         put_caching_control(caching_ctl);
7296         return ret;
7297 }
7298
7299 int __get_raid_index(u64 flags)
7300 {
7301         if (flags & BTRFS_BLOCK_GROUP_RAID10)
7302                 return BTRFS_RAID_RAID10;
7303         else if (flags & BTRFS_BLOCK_GROUP_RAID1)
7304                 return BTRFS_RAID_RAID1;
7305         else if (flags & BTRFS_BLOCK_GROUP_DUP)
7306                 return BTRFS_RAID_DUP;
7307         else if (flags & BTRFS_BLOCK_GROUP_RAID0)
7308                 return BTRFS_RAID_RAID0;
7309         else if (flags & BTRFS_BLOCK_GROUP_RAID5)
7310                 return BTRFS_RAID_RAID5;
7311         else if (flags & BTRFS_BLOCK_GROUP_RAID6)
7312                 return BTRFS_RAID_RAID6;
7313
7314         return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
7315 }
7316
7317 int get_block_group_index(struct btrfs_block_group_cache *cache)
7318 {
7319         return __get_raid_index(cache->flags);
7320 }
7321
7322 static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
7323         [BTRFS_RAID_RAID10]     = "raid10",
7324         [BTRFS_RAID_RAID1]      = "raid1",
7325         [BTRFS_RAID_DUP]        = "dup",
7326         [BTRFS_RAID_RAID0]      = "raid0",
7327         [BTRFS_RAID_SINGLE]     = "single",
7328         [BTRFS_RAID_RAID5]      = "raid5",
7329         [BTRFS_RAID_RAID6]      = "raid6",
7330 };
7331
7332 static const char *get_raid_name(enum btrfs_raid_types type)
7333 {
7334         if (type >= BTRFS_NR_RAID_TYPES)
7335                 return NULL;
7336
7337         return btrfs_raid_type_names[type];
7338 }
7339
7340 enum btrfs_loop_type {
7341         LOOP_CACHING_NOWAIT = 0,
7342         LOOP_CACHING_WAIT = 1,
7343         LOOP_ALLOC_CHUNK = 2,
7344         LOOP_NO_EMPTY_SIZE = 3,
7345 };
7346
7347 static inline void
7348 btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
7349                        int delalloc)
7350 {
7351         if (delalloc)
7352                 down_read(&cache->data_rwsem);
7353 }
7354
7355 static inline void
7356 btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
7357                        int delalloc)
7358 {
7359         btrfs_get_block_group(cache);
7360         if (delalloc)
7361                 down_read(&cache->data_rwsem);
7362 }
7363
7364 static struct btrfs_block_group_cache *
7365 btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
7366                    struct btrfs_free_cluster *cluster,
7367                    int delalloc)
7368 {
7369         struct btrfs_block_group_cache *used_bg = NULL;
7370
7371         spin_lock(&cluster->refill_lock);
7372         while (1) {
7373                 used_bg = cluster->block_group;
7374                 if (!used_bg)
7375                         return NULL;
7376
7377                 if (used_bg == block_group)
7378                         return used_bg;
7379
7380                 btrfs_get_block_group(used_bg);
7381
7382                 if (!delalloc)
7383                         return used_bg;
7384
7385                 if (down_read_trylock(&used_bg->data_rwsem))
7386                         return used_bg;
7387
7388                 spin_unlock(&cluster->refill_lock);
7389
7390                 /* We should only have one-level nested. */
7391                 down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
7392
7393                 spin_lock(&cluster->refill_lock);
7394                 if (used_bg == cluster->block_group)
7395                         return used_bg;
7396
7397                 up_read(&used_bg->data_rwsem);
7398                 btrfs_put_block_group(used_bg);
7399         }
7400 }
7401
7402 static inline void
7403 btrfs_release_block_group(struct btrfs_block_group_cache *cache,
7404                          int delalloc)
7405 {
7406         if (delalloc)
7407                 up_read(&cache->data_rwsem);
7408         btrfs_put_block_group(cache);
7409 }
7410
7411 /*
7412  * walks the btree of allocated extents and find a hole of a given size.
7413  * The key ins is changed to record the hole:
7414  * ins->objectid == start position
7415  * ins->flags = BTRFS_EXTENT_ITEM_KEY
7416  * ins->offset == the size of the hole.
7417  * Any available blocks before search_start are skipped.
7418  *
7419  * If there is no suitable free space, we will record the max size of
7420  * the free space extent currently.
7421  */
7422 static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
7423                                 u64 ram_bytes, u64 num_bytes, u64 empty_size,
7424                                 u64 hint_byte, struct btrfs_key *ins,
7425                                 u64 flags, int delalloc)
7426 {
7427         int ret = 0;
7428         struct btrfs_root *root = fs_info->extent_root;
7429         struct btrfs_free_cluster *last_ptr = NULL;
7430         struct btrfs_block_group_cache *block_group = NULL;
7431         u64 search_start = 0;
7432         u64 max_extent_size = 0;
7433         u64 empty_cluster = 0;
7434         struct btrfs_space_info *space_info;
7435         int loop = 0;
7436         int index = __get_raid_index(flags);
7437         bool failed_cluster_refill = false;
7438         bool failed_alloc = false;
7439         bool use_cluster = true;
7440         bool have_caching_bg = false;
7441         bool orig_have_caching_bg = false;
7442         bool full_search = false;
7443
7444         WARN_ON(num_bytes < fs_info->sectorsize);
7445         ins->type = BTRFS_EXTENT_ITEM_KEY;
7446         ins->objectid = 0;
7447         ins->offset = 0;
7448
7449         trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
7450
7451         space_info = __find_space_info(fs_info, flags);
7452         if (!space_info) {
7453                 btrfs_err(fs_info, "No space info for %llu", flags);
7454                 return -ENOSPC;
7455         }
7456
7457         /*
7458          * If our free space is heavily fragmented we may not be able to make
7459          * big contiguous allocations, so instead of doing the expensive search
7460          * for free space, simply return ENOSPC with our max_extent_size so we
7461          * can go ahead and search for a more manageable chunk.
7462          *
7463          * If our max_extent_size is large enough for our allocation simply
7464          * disable clustering since we will likely not be able to find enough
7465          * space to create a cluster and induce latency trying.
7466          */
7467         if (unlikely(space_info->max_extent_size)) {
7468                 spin_lock(&space_info->lock);
7469                 if (space_info->max_extent_size &&
7470                     num_bytes > space_info->max_extent_size) {
7471                         ins->offset = space_info->max_extent_size;
7472                         spin_unlock(&space_info->lock);
7473                         return -ENOSPC;
7474                 } else if (space_info->max_extent_size) {
7475                         use_cluster = false;
7476                 }
7477                 spin_unlock(&space_info->lock);
7478         }
7479
7480         last_ptr = fetch_cluster_info(fs_info, space_info, &empty_cluster);
7481         if (last_ptr) {
7482                 spin_lock(&last_ptr->lock);
7483                 if (last_ptr->block_group)
7484                         hint_byte = last_ptr->window_start;
7485                 if (last_ptr->fragmented) {
7486                         /*
7487                          * We still set window_start so we can keep track of the
7488                          * last place we found an allocation to try and save
7489                          * some time.
7490                          */
7491                         hint_byte = last_ptr->window_start;
7492                         use_cluster = false;
7493                 }
7494                 spin_unlock(&last_ptr->lock);
7495         }
7496
7497         search_start = max(search_start, first_logical_byte(fs_info, 0));
7498         search_start = max(search_start, hint_byte);
7499         if (search_start == hint_byte) {
7500                 block_group = btrfs_lookup_block_group(fs_info, search_start);
7501                 /*
7502                  * we don't want to use the block group if it doesn't match our
7503                  * allocation bits, or if its not cached.
7504                  *
7505                  * However if we are re-searching with an ideal block group
7506                  * picked out then we don't care that the block group is cached.
7507                  */
7508                 if (block_group && block_group_bits(block_group, flags) &&
7509                     block_group->cached != BTRFS_CACHE_NO) {
7510                         down_read(&space_info->groups_sem);
7511                         if (list_empty(&block_group->list) ||
7512                             block_group->ro) {
7513                                 /*
7514                                  * someone is removing this block group,
7515                                  * we can't jump into the have_block_group
7516                                  * target because our list pointers are not
7517                                  * valid
7518                                  */
7519                                 btrfs_put_block_group(block_group);
7520                                 up_read(&space_info->groups_sem);
7521                         } else {
7522                                 index = get_block_group_index(block_group);
7523                                 btrfs_lock_block_group(block_group, delalloc);
7524                                 goto have_block_group;
7525                         }
7526                 } else if (block_group) {
7527                         btrfs_put_block_group(block_group);
7528                 }
7529         }
7530 search:
7531         have_caching_bg = false;
7532         if (index == 0 || index == __get_raid_index(flags))
7533                 full_search = true;
7534         down_read(&space_info->groups_sem);
7535         list_for_each_entry(block_group, &space_info->block_groups[index],
7536                             list) {
7537                 u64 offset;
7538                 int cached;
7539
7540                 btrfs_grab_block_group(block_group, delalloc);
7541                 search_start = block_group->key.objectid;
7542
7543                 /*
7544                  * this can happen if we end up cycling through all the
7545                  * raid types, but we want to make sure we only allocate
7546                  * for the proper type.
7547                  */
7548                 if (!block_group_bits(block_group, flags)) {
7549                     u64 extra = BTRFS_BLOCK_GROUP_DUP |
7550                                 BTRFS_BLOCK_GROUP_RAID1 |
7551                                 BTRFS_BLOCK_GROUP_RAID5 |
7552                                 BTRFS_BLOCK_GROUP_RAID6 |
7553                                 BTRFS_BLOCK_GROUP_RAID10;
7554
7555                         /*
7556                          * if they asked for extra copies and this block group
7557                          * doesn't provide them, bail.  This does allow us to
7558                          * fill raid0 from raid1.
7559                          */
7560                         if ((flags & extra) && !(block_group->flags & extra))
7561                                 goto loop;
7562                 }
7563
7564 have_block_group:
7565                 cached = block_group_cache_done(block_group);
7566                 if (unlikely(!cached)) {
7567                         have_caching_bg = true;
7568                         ret = cache_block_group(block_group, 0);
7569                         BUG_ON(ret < 0);
7570                         ret = 0;
7571                 }
7572
7573                 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7574                         goto loop;
7575                 if (unlikely(block_group->ro))
7576                         goto loop;
7577
7578                 /*
7579                  * Ok we want to try and use the cluster allocator, so
7580                  * lets look there
7581                  */
7582                 if (last_ptr && use_cluster) {
7583                         struct btrfs_block_group_cache *used_block_group;
7584                         unsigned long aligned_cluster;
7585                         /*
7586                          * the refill lock keeps out other
7587                          * people trying to start a new cluster
7588                          */
7589                         used_block_group = btrfs_lock_cluster(block_group,
7590                                                               last_ptr,
7591                                                               delalloc);
7592                         if (!used_block_group)
7593                                 goto refill_cluster;
7594
7595                         if (used_block_group != block_group &&
7596                             (used_block_group->ro ||
7597                              !block_group_bits(used_block_group, flags)))
7598                                 goto release_cluster;
7599
7600                         offset = btrfs_alloc_from_cluster(used_block_group,
7601                                                 last_ptr,
7602                                                 num_bytes,
7603                                                 used_block_group->key.objectid,
7604                                                 &max_extent_size);
7605                         if (offset) {
7606                                 /* we have a block, we're done */
7607                                 spin_unlock(&last_ptr->refill_lock);
7608                                 trace_btrfs_reserve_extent_cluster(fs_info,
7609                                                 used_block_group,
7610                                                 search_start, num_bytes);
7611                                 if (used_block_group != block_group) {
7612                                         btrfs_release_block_group(block_group,
7613                                                                   delalloc);
7614                                         block_group = used_block_group;
7615                                 }
7616                                 goto checks;
7617                         }
7618
7619                         WARN_ON(last_ptr->block_group != used_block_group);
7620 release_cluster:
7621                         /* If we are on LOOP_NO_EMPTY_SIZE, we can't
7622                          * set up a new clusters, so lets just skip it
7623                          * and let the allocator find whatever block
7624                          * it can find.  If we reach this point, we
7625                          * will have tried the cluster allocator
7626                          * plenty of times and not have found
7627                          * anything, so we are likely way too
7628                          * fragmented for the clustering stuff to find
7629                          * anything.
7630                          *
7631                          * However, if the cluster is taken from the
7632                          * current block group, release the cluster
7633                          * first, so that we stand a better chance of
7634                          * succeeding in the unclustered
7635                          * allocation.  */
7636                         if (loop >= LOOP_NO_EMPTY_SIZE &&
7637                             used_block_group != block_group) {
7638                                 spin_unlock(&last_ptr->refill_lock);
7639                                 btrfs_release_block_group(used_block_group,
7640                                                           delalloc);
7641                                 goto unclustered_alloc;
7642                         }
7643
7644                         /*
7645                          * this cluster didn't work out, free it and
7646                          * start over
7647                          */
7648                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
7649
7650                         if (used_block_group != block_group)
7651                                 btrfs_release_block_group(used_block_group,
7652                                                           delalloc);
7653 refill_cluster:
7654                         if (loop >= LOOP_NO_EMPTY_SIZE) {
7655                                 spin_unlock(&last_ptr->refill_lock);
7656                                 goto unclustered_alloc;
7657                         }
7658
7659                         aligned_cluster = max_t(unsigned long,
7660                                                 empty_cluster + empty_size,
7661                                               block_group->full_stripe_len);
7662
7663                         /* allocate a cluster in this block group */
7664                         ret = btrfs_find_space_cluster(fs_info, block_group,
7665                                                        last_ptr, search_start,
7666                                                        num_bytes,
7667                                                        aligned_cluster);
7668                         if (ret == 0) {
7669                                 /*
7670                                  * now pull our allocation out of this
7671                                  * cluster
7672                                  */
7673                                 offset = btrfs_alloc_from_cluster(block_group,
7674                                                         last_ptr,
7675                                                         num_bytes,
7676                                                         search_start,
7677                                                         &max_extent_size);
7678                                 if (offset) {
7679                                         /* we found one, proceed */
7680                                         spin_unlock(&last_ptr->refill_lock);
7681                                         trace_btrfs_reserve_extent_cluster(fs_info,
7682                                                 block_group, search_start,
7683                                                 num_bytes);
7684                                         goto checks;
7685                                 }
7686                         } else if (!cached && loop > LOOP_CACHING_NOWAIT
7687                                    && !failed_cluster_refill) {
7688                                 spin_unlock(&last_ptr->refill_lock);
7689
7690                                 failed_cluster_refill = true;
7691                                 wait_block_group_cache_progress(block_group,
7692                                        num_bytes + empty_cluster + empty_size);
7693                                 goto have_block_group;
7694                         }
7695
7696                         /*
7697                          * at this point we either didn't find a cluster
7698                          * or we weren't able to allocate a block from our
7699                          * cluster.  Free the cluster we've been trying
7700                          * to use, and go to the next block group
7701                          */
7702                         btrfs_return_cluster_to_free_space(NULL, last_ptr);
7703                         spin_unlock(&last_ptr->refill_lock);
7704                         goto loop;
7705                 }
7706
7707 unclustered_alloc:
7708                 /*
7709                  * We are doing an unclustered alloc, set the fragmented flag so
7710                  * we don't bother trying to setup a cluster again until we get
7711                  * more space.
7712                  */
7713                 if (unlikely(last_ptr)) {
7714                         spin_lock(&last_ptr->lock);
7715                         last_ptr->fragmented = 1;
7716                         spin_unlock(&last_ptr->lock);
7717                 }
7718                 if (cached) {
7719                         struct btrfs_free_space_ctl *ctl =
7720                                 block_group->free_space_ctl;
7721
7722                         spin_lock(&ctl->tree_lock);
7723                         if (ctl->free_space <
7724                             num_bytes + empty_cluster + empty_size) {
7725                                 if (ctl->free_space > max_extent_size)
7726                                         max_extent_size = ctl->free_space;
7727                                 spin_unlock(&ctl->tree_lock);
7728                                 goto loop;
7729                         }
7730                         spin_unlock(&ctl->tree_lock);
7731                 }
7732
7733                 offset = btrfs_find_space_for_alloc(block_group, search_start,
7734                                                     num_bytes, empty_size,
7735                                                     &max_extent_size);
7736                 /*
7737                  * If we didn't find a chunk, and we haven't failed on this
7738                  * block group before, and this block group is in the middle of
7739                  * caching and we are ok with waiting, then go ahead and wait
7740                  * for progress to be made, and set failed_alloc to true.
7741                  *
7742                  * If failed_alloc is true then we've already waited on this
7743                  * block group once and should move on to the next block group.
7744                  */
7745                 if (!offset && !failed_alloc && !cached &&
7746                     loop > LOOP_CACHING_NOWAIT) {
7747                         wait_block_group_cache_progress(block_group,
7748                                                 num_bytes + empty_size);
7749                         failed_alloc = true;
7750                         goto have_block_group;
7751                 } else if (!offset) {
7752                         goto loop;
7753                 }
7754 checks:
7755                 search_start = ALIGN(offset, fs_info->stripesize);
7756
7757                 /* move on to the next group */
7758                 if (search_start + num_bytes >
7759                     block_group->key.objectid + block_group->key.offset) {
7760                         btrfs_add_free_space(block_group, offset, num_bytes);
7761                         goto loop;
7762                 }
7763
7764                 if (offset < search_start)
7765                         btrfs_add_free_space(block_group, offset,
7766                                              search_start - offset);
7767                 BUG_ON(offset > search_start);
7768
7769                 ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
7770                                 num_bytes, delalloc);
7771                 if (ret == -EAGAIN) {
7772                         btrfs_add_free_space(block_group, offset, num_bytes);
7773                         goto loop;
7774                 }
7775                 btrfs_inc_block_group_reservations(block_group);
7776
7777                 /* we are all good, lets return */
7778                 ins->objectid = search_start;
7779                 ins->offset = num_bytes;
7780
7781                 trace_btrfs_reserve_extent(fs_info, block_group,
7782                                            search_start, num_bytes);
7783                 btrfs_release_block_group(block_group, delalloc);
7784                 break;
7785 loop:
7786                 failed_cluster_refill = false;
7787                 failed_alloc = false;
7788                 BUG_ON(index != get_block_group_index(block_group));
7789                 btrfs_release_block_group(block_group, delalloc);
7790         }
7791         up_read(&space_info->groups_sem);
7792
7793         if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
7794                 && !orig_have_caching_bg)
7795                 orig_have_caching_bg = true;
7796
7797         if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
7798                 goto search;
7799
7800         if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
7801                 goto search;
7802
7803         /*
7804          * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7805          *                      caching kthreads as we move along
7806          * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7807          * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7808          * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7809          *                      again
7810          */
7811         if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
7812                 index = 0;
7813                 if (loop == LOOP_CACHING_NOWAIT) {
7814                         /*
7815                          * We want to skip the LOOP_CACHING_WAIT step if we
7816                          * don't have any uncached bgs and we've already done a
7817                          * full search through.
7818                          */
7819                         if (orig_have_caching_bg || !full_search)
7820                                 loop = LOOP_CACHING_WAIT;
7821                         else
7822                                 loop = LOOP_ALLOC_CHUNK;
7823                 } else {
7824                         loop++;
7825                 }
7826
7827                 if (loop == LOOP_ALLOC_CHUNK) {
7828                         struct btrfs_trans_handle *trans;
7829                         int exist = 0;
7830
7831                         trans = current->journal_info;
7832                         if (trans)
7833                                 exist = 1;
7834                         else
7835                                 trans = btrfs_join_transaction(root);
7836
7837                         if (IS_ERR(trans)) {
7838                                 ret = PTR_ERR(trans);
7839                                 goto out;
7840                         }
7841
7842                         ret = do_chunk_alloc(trans, fs_info, flags,
7843                                              CHUNK_ALLOC_FORCE);
7844
7845                         /*
7846                          * If we can't allocate a new chunk we've already looped
7847                          * through at least once, move on to the NO_EMPTY_SIZE
7848                          * case.
7849                          */
7850                         if (ret == -ENOSPC)
7851                                 loop = LOOP_NO_EMPTY_SIZE;
7852
7853                         /*
7854                          * Do not bail out on ENOSPC since we
7855                          * can do more things.
7856                          */
7857                         if (ret < 0 && ret != -ENOSPC)
7858                                 btrfs_abort_transaction(trans, ret);
7859                         else
7860                                 ret = 0;
7861                         if (!exist)
7862                                 btrfs_end_transaction(trans);
7863                         if (ret)
7864                                 goto out;
7865                 }
7866
7867                 if (loop == LOOP_NO_EMPTY_SIZE) {
7868                         /*
7869                          * Don't loop again if we already have no empty_size and
7870                          * no empty_cluster.
7871                          */
7872                         if (empty_size == 0 &&
7873                             empty_cluster == 0) {
7874                                 ret = -ENOSPC;
7875                                 goto out;
7876                         }
7877                         empty_size = 0;
7878                         empty_cluster = 0;
7879                 }
7880
7881                 goto search;
7882         } else if (!ins->objectid) {
7883                 ret = -ENOSPC;
7884         } else if (ins->objectid) {
7885                 if (!use_cluster && last_ptr) {
7886                         spin_lock(&last_ptr->lock);
7887                         last_ptr->window_start = ins->objectid;
7888                         spin_unlock(&last_ptr->lock);
7889                 }
7890                 ret = 0;
7891         }
7892 out:
7893         if (ret == -ENOSPC) {
7894                 spin_lock(&space_info->lock);
7895                 space_info->max_extent_size = max_extent_size;
7896                 spin_unlock(&space_info->lock);
7897                 ins->offset = max_extent_size;
7898         }
7899         return ret;
7900 }
7901
7902 static void dump_space_info(struct btrfs_fs_info *fs_info,
7903                             struct btrfs_space_info *info, u64 bytes,
7904                             int dump_block_groups)
7905 {
7906         struct btrfs_block_group_cache *cache;
7907         int index = 0;
7908
7909         spin_lock(&info->lock);
7910         btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
7911                    info->flags,
7912                    info->total_bytes - btrfs_space_info_used(info, true),
7913                    info->full ? "" : "not ");
7914         btrfs_info(fs_info,
7915                 "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
7916                 info->total_bytes, info->bytes_used, info->bytes_pinned,
7917                 info->bytes_reserved, info->bytes_may_use,
7918                 info->bytes_readonly);
7919         spin_unlock(&info->lock);
7920
7921         if (!dump_block_groups)
7922                 return;
7923
7924         down_read(&info->groups_sem);
7925 again:
7926         list_for_each_entry(cache, &info->block_groups[index], list) {
7927                 spin_lock(&cache->lock);
7928                 btrfs_info(fs_info,
7929                         "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
7930                         cache->key.objectid, cache->key.offset,
7931                         btrfs_block_group_used(&cache->item), cache->pinned,
7932                         cache->reserved, cache->ro ? "[readonly]" : "");
7933                 btrfs_dump_free_space(cache, bytes);
7934                 spin_unlock(&cache->lock);
7935         }
7936         if (++index < BTRFS_NR_RAID_TYPES)
7937                 goto again;
7938         up_read(&info->groups_sem);
7939 }
7940
7941 int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
7942                          u64 num_bytes, u64 min_alloc_size,
7943                          u64 empty_size, u64 hint_byte,
7944                          struct btrfs_key *ins, int is_data, int delalloc)
7945 {
7946         struct btrfs_fs_info *fs_info = root->fs_info;
7947         bool final_tried = num_bytes == min_alloc_size;
7948         u64 flags;
7949         int ret;
7950
7951         flags = btrfs_get_alloc_profile(root, is_data);
7952 again:
7953         WARN_ON(num_bytes < fs_info->sectorsize);
7954         ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
7955                                hint_byte, ins, flags, delalloc);
7956         if (!ret && !is_data) {
7957                 btrfs_dec_block_group_reservations(fs_info, ins->objectid);
7958         } else if (ret == -ENOSPC) {
7959                 if (!final_tried && ins->offset) {
7960                         num_bytes = min(num_bytes >> 1, ins->offset);
7961                         num_bytes = round_down(num_bytes,
7962                                                fs_info->sectorsize);
7963                         num_bytes = max(num_bytes, min_alloc_size);
7964                         ram_bytes = num_bytes;
7965                         if (num_bytes == min_alloc_size)
7966                                 final_tried = true;
7967                         goto again;
7968                 } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
7969                         struct btrfs_space_info *sinfo;
7970
7971                         sinfo = __find_space_info(fs_info, flags);
7972                         btrfs_err(fs_info,
7973                                   "allocation failed flags %llu, wanted %llu",
7974                                   flags, num_bytes);
7975                         if (sinfo)
7976                                 dump_space_info(fs_info, sinfo, num_bytes, 1);
7977                 }
7978         }
7979
7980         return ret;
7981 }
7982
7983 static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
7984                                         u64 start, u64 len,
7985                                         int pin, int delalloc)
7986 {
7987         struct btrfs_block_group_cache *cache;
7988         int ret = 0;
7989
7990         cache = btrfs_lookup_block_group(fs_info, start);
7991         if (!cache) {
7992                 btrfs_err(fs_info, "Unable to find block group for %llu",
7993                           start);
7994                 return -ENOSPC;
7995         }
7996
7997         if (pin)
7998                 pin_down_extent(fs_info, cache, start, len, 1);
7999         else {
8000                 if (btrfs_test_opt(fs_info, DISCARD))
8001                         ret = btrfs_discard_extent(fs_info, start, len, NULL);
8002                 btrfs_add_free_space(cache, start, len);
8003                 btrfs_free_reserved_bytes(cache, len, delalloc);
8004                 trace_btrfs_reserved_extent_free(fs_info, start, len);
8005         }
8006
8007         btrfs_put_block_group(cache);
8008         return ret;
8009 }
8010
8011 int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
8012                                u64 start, u64 len, int delalloc)
8013 {
8014         return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
8015 }
8016
8017 int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
8018                                        u64 start, u64 len)
8019 {
8020         return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
8021 }
8022
8023 static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8024                                       struct btrfs_fs_info *fs_info,
8025                                       u64 parent, u64 root_objectid,
8026                                       u64 flags, u64 owner, u64 offset,
8027                                       struct btrfs_key *ins, int ref_mod)
8028 {
8029         int ret;
8030         struct btrfs_extent_item *extent_item;
8031         struct btrfs_extent_inline_ref *iref;
8032         struct btrfs_path *path;
8033         struct extent_buffer *leaf;
8034         int type;
8035         u32 size;
8036
8037         if (parent > 0)
8038                 type = BTRFS_SHARED_DATA_REF_KEY;
8039         else
8040                 type = BTRFS_EXTENT_DATA_REF_KEY;
8041
8042         size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
8043
8044         path = btrfs_alloc_path();
8045         if (!path)
8046                 return -ENOMEM;
8047
8048         path->leave_spinning = 1;
8049         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8050                                       ins, size);
8051         if (ret) {
8052                 btrfs_free_path(path);
8053                 return ret;
8054         }
8055
8056         leaf = path->nodes[0];
8057         extent_item = btrfs_item_ptr(leaf, path->slots[0],
8058                                      struct btrfs_extent_item);
8059         btrfs_set_extent_refs(leaf, extent_item, ref_mod);
8060         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8061         btrfs_set_extent_flags(leaf, extent_item,
8062                                flags | BTRFS_EXTENT_FLAG_DATA);
8063
8064         iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8065         btrfs_set_extent_inline_ref_type(leaf, iref, type);
8066         if (parent > 0) {
8067                 struct btrfs_shared_data_ref *ref;
8068                 ref = (struct btrfs_shared_data_ref *)(iref + 1);
8069                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8070                 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
8071         } else {
8072                 struct btrfs_extent_data_ref *ref;
8073                 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
8074                 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
8075                 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
8076                 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
8077                 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
8078         }
8079
8080         btrfs_mark_buffer_dirty(path->nodes[0]);
8081         btrfs_free_path(path);
8082
8083         ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8084                                           ins->offset);
8085         if (ret)
8086                 return ret;
8087
8088         ret = update_block_group(trans, fs_info, ins->objectid, ins->offset, 1);
8089         if (ret) { /* -ENOENT, logic error */
8090                 btrfs_err(fs_info, "update block group failed for %llu %llu",
8091                         ins->objectid, ins->offset);
8092                 BUG();
8093         }
8094         trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
8095         return ret;
8096 }
8097
8098 static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
8099                                      struct btrfs_fs_info *fs_info,
8100                                      u64 parent, u64 root_objectid,
8101                                      u64 flags, struct btrfs_disk_key *key,
8102                                      int level, struct btrfs_key *ins)
8103 {
8104         int ret;
8105         struct btrfs_extent_item *extent_item;
8106         struct btrfs_tree_block_info *block_info;
8107         struct btrfs_extent_inline_ref *iref;
8108         struct btrfs_path *path;
8109         struct extent_buffer *leaf;
8110         u32 size = sizeof(*extent_item) + sizeof(*iref);
8111         u64 num_bytes = ins->offset;
8112         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8113
8114         if (!skinny_metadata)
8115                 size += sizeof(*block_info);
8116
8117         path = btrfs_alloc_path();
8118         if (!path) {
8119                 btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
8120                                                    fs_info->nodesize);
8121                 return -ENOMEM;
8122         }
8123
8124         path->leave_spinning = 1;
8125         ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
8126                                       ins, size);
8127         if (ret) {
8128                 btrfs_free_path(path);
8129                 btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
8130                                                    fs_info->nodesize);
8131                 return ret;
8132         }
8133
8134         leaf = path->nodes[0];
8135         extent_item = btrfs_item_ptr(leaf, path->slots[0],
8136                                      struct btrfs_extent_item);
8137         btrfs_set_extent_refs(leaf, extent_item, 1);
8138         btrfs_set_extent_generation(leaf, extent_item, trans->transid);
8139         btrfs_set_extent_flags(leaf, extent_item,
8140                                flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
8141
8142         if (skinny_metadata) {
8143                 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
8144                 num_bytes = fs_info->nodesize;
8145         } else {
8146                 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
8147                 btrfs_set_tree_block_key(leaf, block_info, key);
8148                 btrfs_set_tree_block_level(leaf, block_info, level);
8149                 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
8150         }
8151
8152         if (parent > 0) {
8153                 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
8154                 btrfs_set_extent_inline_ref_type(leaf, iref,
8155                                                  BTRFS_SHARED_BLOCK_REF_KEY);
8156                 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
8157         } else {
8158                 btrfs_set_extent_inline_ref_type(leaf, iref,
8159                                                  BTRFS_TREE_BLOCK_REF_KEY);
8160                 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
8161         }
8162
8163         btrfs_mark_buffer_dirty(leaf);
8164         btrfs_free_path(path);
8165
8166         ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
8167                                           num_bytes);
8168         if (ret)
8169                 return ret;
8170
8171         ret = update_block_group(trans, fs_info, ins->objectid,
8172                                  fs_info->nodesize, 1);
8173         if (ret) { /* -ENOENT, logic error */
8174                 btrfs_err(fs_info, "update block group failed for %llu %llu",
8175                         ins->objectid, ins->offset);
8176                 BUG();
8177         }
8178
8179         trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid,
8180                                           fs_info->nodesize);
8181         return ret;
8182 }
8183
8184 int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
8185                                      u64 root_objectid, u64 owner,
8186                                      u64 offset, u64 ram_bytes,
8187                                      struct btrfs_key *ins)
8188 {
8189         struct btrfs_fs_info *fs_info = trans->fs_info;
8190         int ret;
8191
8192         BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
8193
8194         ret = btrfs_add_delayed_data_ref(fs_info, trans, ins->objectid,
8195                                          ins->offset, 0,
8196                                          root_objectid, owner, offset,
8197                                          ram_bytes, BTRFS_ADD_DELAYED_EXTENT);
8198         return ret;
8199 }
8200
8201 /*
8202  * this is used by the tree logging recovery code.  It records that
8203  * an extent has been allocated and makes sure to clear the free
8204  * space cache bits as well
8205  */
8206 int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
8207                                    struct btrfs_fs_info *fs_info,
8208                                    u64 root_objectid, u64 owner, u64 offset,
8209                                    struct btrfs_key *ins)
8210 {
8211         int ret;
8212         struct btrfs_block_group_cache *block_group;
8213         struct btrfs_space_info *space_info;
8214
8215         /*
8216          * Mixed block groups will exclude before processing the log so we only
8217          * need to do the exclude dance if this fs isn't mixed.
8218          */
8219         if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
8220                 ret = __exclude_logged_extent(fs_info, ins->objectid,
8221                                               ins->offset);
8222                 if (ret)
8223                         return ret;
8224         }
8225
8226         block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
8227         if (!block_group)
8228                 return -EINVAL;
8229
8230         space_info = block_group->space_info;
8231         spin_lock(&space_info->lock);
8232         spin_lock(&block_group->lock);
8233         space_info->bytes_reserved += ins->offset;
8234         block_group->reserved += ins->offset;
8235         spin_unlock(&block_group->lock);
8236         spin_unlock(&space_info->lock);
8237
8238         ret = alloc_reserved_file_extent(trans, fs_info, 0, root_objectid,
8239                                          0, owner, offset, ins, 1);
8240         btrfs_put_block_group(block_group);
8241         return ret;
8242 }
8243
8244 static struct extent_buffer *
8245 btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
8246                       u64 bytenr, int level)
8247 {
8248         struct btrfs_fs_info *fs_info = root->fs_info;
8249         struct extent_buffer *buf;
8250
8251         buf = btrfs_find_create_tree_block(fs_info, bytenr);
8252         if (IS_ERR(buf))
8253                 return buf;
8254
8255         btrfs_set_header_generation(buf, trans->transid);
8256         btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
8257         btrfs_tree_lock(buf);
8258         clean_tree_block(fs_info, buf);
8259         clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
8260
8261         btrfs_set_lock_blocking(buf);
8262         set_extent_buffer_uptodate(buf);
8263
8264         if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8265                 buf->log_index = root->log_transid % 2;
8266                 /*
8267                  * we allow two log transactions at a time, use different
8268                  * EXENT bit to differentiate dirty pages.
8269                  */
8270                 if (buf->log_index == 0)
8271                         set_extent_dirty(&root->dirty_log_pages, buf->start,
8272                                         buf->start + buf->len - 1, GFP_NOFS);
8273                 else
8274                         set_extent_new(&root->dirty_log_pages, buf->start,
8275                                         buf->start + buf->len - 1);
8276         } else {
8277                 buf->log_index = -1;
8278                 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
8279                          buf->start + buf->len - 1, GFP_NOFS);
8280         }
8281         trans->dirty = true;
8282         /* this returns a buffer locked for blocking */
8283         return buf;
8284 }
8285
8286 static struct btrfs_block_rsv *
8287 use_block_rsv(struct btrfs_trans_handle *trans,
8288               struct btrfs_root *root, u32 blocksize)
8289 {
8290         struct btrfs_fs_info *fs_info = root->fs_info;
8291         struct btrfs_block_rsv *block_rsv;
8292         struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
8293         int ret;
8294         bool global_updated = false;
8295
8296         block_rsv = get_block_rsv(trans, root);
8297
8298         if (unlikely(block_rsv->size == 0))
8299                 goto try_reserve;
8300 again:
8301         ret = block_rsv_use_bytes(block_rsv, blocksize);
8302         if (!ret)
8303                 return block_rsv;
8304
8305         if (block_rsv->failfast)
8306                 return ERR_PTR(ret);
8307
8308         if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
8309                 global_updated = true;
8310                 update_global_block_rsv(fs_info);
8311                 goto again;
8312         }
8313
8314         if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
8315                 static DEFINE_RATELIMIT_STATE(_rs,
8316                                 DEFAULT_RATELIMIT_INTERVAL * 10,
8317                                 /*DEFAULT_RATELIMIT_BURST*/ 1);
8318                 if (__ratelimit(&_rs))
8319                         WARN(1, KERN_DEBUG
8320                                 "BTRFS: block rsv returned %d\n", ret);
8321         }
8322 try_reserve:
8323         ret = reserve_metadata_bytes(root, block_rsv, blocksize,
8324                                      BTRFS_RESERVE_NO_FLUSH);
8325         if (!ret)
8326                 return block_rsv;
8327         /*
8328          * If we couldn't reserve metadata bytes try and use some from
8329          * the global reserve if its space type is the same as the global
8330          * reservation.
8331          */
8332         if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
8333             block_rsv->space_info == global_rsv->space_info) {
8334                 ret = block_rsv_use_bytes(global_rsv, blocksize);
8335                 if (!ret)
8336                         return global_rsv;
8337         }
8338         return ERR_PTR(ret);
8339 }
8340
8341 static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
8342                             struct btrfs_block_rsv *block_rsv, u32 blocksize)
8343 {
8344         block_rsv_add_bytes(block_rsv, blocksize, 0);
8345         block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
8346 }
8347
8348 /*
8349  * finds a free extent and does all the dirty work required for allocation
8350  * returns the tree buffer or an ERR_PTR on error.
8351  */
8352 struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
8353                                              struct btrfs_root *root,
8354                                              u64 parent, u64 root_objectid,
8355                                              const struct btrfs_disk_key *key,
8356                                              int level, u64 hint,
8357                                              u64 empty_size)
8358 {
8359         struct btrfs_fs_info *fs_info = root->fs_info;
8360         struct btrfs_key ins;
8361         struct btrfs_block_rsv *block_rsv;
8362         struct extent_buffer *buf;
8363         struct btrfs_delayed_extent_op *extent_op;
8364         u64 flags = 0;
8365         int ret;
8366         u32 blocksize = fs_info->nodesize;
8367         bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
8368
8369 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8370         if (btrfs_is_testing(fs_info)) {
8371                 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
8372                                             level);
8373                 if (!IS_ERR(buf))
8374                         root->alloc_bytenr += blocksize;
8375                 return buf;
8376         }
8377 #endif
8378
8379         block_rsv = use_block_rsv(trans, root, blocksize);
8380         if (IS_ERR(block_rsv))
8381                 return ERR_CAST(block_rsv);
8382
8383         ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
8384                                    empty_size, hint, &ins, 0, 0);
8385         if (ret)
8386                 goto out_unuse;
8387
8388         buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
8389         if (IS_ERR(buf)) {
8390                 ret = PTR_ERR(buf);
8391                 goto out_free_reserved;
8392         }
8393
8394         if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
8395                 if (parent == 0)
8396                         parent = ins.objectid;
8397                 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
8398         } else
8399                 BUG_ON(parent > 0);
8400
8401         if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
8402                 extent_op = btrfs_alloc_delayed_extent_op();
8403                 if (!extent_op) {
8404                         ret = -ENOMEM;
8405                         goto out_free_buf;
8406                 }
8407                 if (key)
8408                         memcpy(&extent_op->key, key, sizeof(extent_op->key));
8409                 else
8410                         memset(&extent_op->key, 0, sizeof(extent_op->key));
8411                 extent_op->flags_to_set = flags;
8412                 extent_op->update_key = skinny_metadata ? false : true;
8413                 extent_op->update_flags = true;
8414                 extent_op->is_data = false;
8415                 extent_op->level = level;
8416
8417                 ret = btrfs_add_delayed_tree_ref(fs_info, trans,
8418                                                  ins.objectid, ins.offset,
8419                                                  parent, root_objectid, level,
8420                                                  BTRFS_ADD_DELAYED_EXTENT,
8421                                                  extent_op);
8422                 if (ret)
8423                         goto out_free_delayed;
8424         }
8425         return buf;
8426
8427 out_free_delayed:
8428         btrfs_free_delayed_extent_op(extent_op);
8429 out_free_buf:
8430         free_extent_buffer(buf);
8431 out_free_reserved:
8432         btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
8433 out_unuse:
8434         unuse_block_rsv(fs_info, block_rsv, blocksize);
8435         return ERR_PTR(ret);
8436 }
8437
8438 struct walk_control {
8439         u64 refs[BTRFS_MAX_LEVEL];
8440         u64 flags[BTRFS_MAX_LEVEL];
8441         struct btrfs_key update_progress;
8442         int stage;
8443         int level;
8444         int shared_level;
8445         int update_ref;
8446         int keep_locks;
8447         int reada_slot;
8448         int reada_count;
8449         int for_reloc;
8450 };
8451
8452 #define DROP_REFERENCE  1
8453 #define UPDATE_BACKREF  2
8454
8455 static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8456                                      struct btrfs_root *root,
8457                                      struct walk_control *wc,
8458                                      struct btrfs_path *path)
8459 {
8460         struct btrfs_fs_info *fs_info = root->fs_info;
8461         u64 bytenr;
8462         u64 generation;
8463         u64 refs;
8464         u64 flags;
8465         u32 nritems;
8466         struct btrfs_key key;
8467         struct extent_buffer *eb;
8468         int ret;
8469         int slot;
8470         int nread = 0;
8471
8472         if (path->slots[wc->level] < wc->reada_slot) {
8473                 wc->reada_count = wc->reada_count * 2 / 3;
8474                 wc->reada_count = max(wc->reada_count, 2);
8475         } else {
8476                 wc->reada_count = wc->reada_count * 3 / 2;
8477                 wc->reada_count = min_t(int, wc->reada_count,
8478                                         BTRFS_NODEPTRS_PER_BLOCK(fs_info));
8479         }
8480
8481         eb = path->nodes[wc->level];
8482         nritems = btrfs_header_nritems(eb);
8483
8484         for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8485                 if (nread >= wc->reada_count)
8486                         break;
8487
8488                 cond_resched();
8489                 bytenr = btrfs_node_blockptr(eb, slot);
8490                 generation = btrfs_node_ptr_generation(eb, slot);
8491
8492                 if (slot == path->slots[wc->level])
8493                         goto reada;
8494
8495                 if (wc->stage == UPDATE_BACKREF &&
8496                     generation <= root->root_key.offset)
8497                         continue;
8498
8499                 /* We don't lock the tree block, it's OK to be racy here */
8500                 ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
8501                                                wc->level - 1, 1, &refs,
8502                                                &flags);
8503                 /* We don't care about errors in readahead. */
8504                 if (ret < 0)
8505                         continue;
8506                 BUG_ON(refs == 0);
8507
8508                 if (wc->stage == DROP_REFERENCE) {
8509                         if (refs == 1)
8510                                 goto reada;
8511
8512                         if (wc->level == 1 &&
8513                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8514                                 continue;
8515                         if (!wc->update_ref ||
8516                             generation <= root->root_key.offset)
8517                                 continue;
8518                         btrfs_node_key_to_cpu(eb, &key, slot);
8519                         ret = btrfs_comp_cpu_keys(&key,
8520                                                   &wc->update_progress);
8521                         if (ret < 0)
8522                                 continue;
8523                 } else {
8524                         if (wc->level == 1 &&
8525                             (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8526                                 continue;
8527                 }
8528 reada:
8529                 readahead_tree_block(fs_info, bytenr);
8530                 nread++;
8531         }
8532         wc->reada_slot = slot;
8533 }
8534
8535 /*
8536  * helper to process tree block while walking down the tree.
8537  *
8538  * when wc->stage == UPDATE_BACKREF, this function updates
8539  * back refs for pointers in the block.
8540  *
8541  * NOTE: return value 1 means we should stop walking down.
8542  */
8543 static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
8544                                    struct btrfs_root *root,
8545                                    struct btrfs_path *path,
8546                                    struct walk_control *wc, int lookup_info)
8547 {
8548         struct btrfs_fs_info *fs_info = root->fs_info;
8549         int level = wc->level;
8550         struct extent_buffer *eb = path->nodes[level];
8551         u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8552         int ret;
8553
8554         if (wc->stage == UPDATE_BACKREF &&
8555             btrfs_header_owner(eb) != root->root_key.objectid)
8556                 return 1;
8557
8558         /*
8559          * when reference count of tree block is 1, it won't increase
8560          * again. once full backref flag is set, we never clear it.
8561          */
8562         if (lookup_info &&
8563             ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8564              (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
8565                 BUG_ON(!path->locks[level]);
8566                 ret = btrfs_lookup_extent_info(trans, fs_info,
8567                                                eb->start, level, 1,
8568                                                &wc->refs[level],
8569                                                &wc->flags[level]);
8570                 BUG_ON(ret == -ENOMEM);
8571                 if (ret)
8572                         return ret;
8573                 BUG_ON(wc->refs[level] == 0);
8574         }
8575
8576         if (wc->stage == DROP_REFERENCE) {
8577                 if (wc->refs[level] > 1)
8578                         return 1;
8579
8580                 if (path->locks[level] && !wc->keep_locks) {
8581                         btrfs_tree_unlock_rw(eb, path->locks[level]);
8582                         path->locks[level] = 0;
8583                 }
8584                 return 0;
8585         }
8586
8587         /* wc->stage == UPDATE_BACKREF */
8588         if (!(wc->flags[level] & flag)) {
8589                 BUG_ON(!path->locks[level]);
8590                 ret = btrfs_inc_ref(trans, root, eb, 1);
8591                 BUG_ON(ret); /* -ENOMEM */
8592                 ret = btrfs_dec_ref(trans, root, eb, 0);
8593                 BUG_ON(ret); /* -ENOMEM */
8594                 ret = btrfs_set_disk_extent_flags(trans, fs_info, eb->start,
8595                                                   eb->len, flag,
8596                                                   btrfs_header_level(eb), 0);
8597                 BUG_ON(ret); /* -ENOMEM */
8598                 wc->flags[level] |= flag;
8599         }
8600
8601         /*
8602          * the block is shared by multiple trees, so it's not good to
8603          * keep the tree lock
8604          */
8605         if (path->locks[level] && level > 0) {
8606                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8607                 path->locks[level] = 0;
8608         }
8609         return 0;
8610 }
8611
8612 /*
8613  * helper to process tree block pointer.
8614  *
8615  * when wc->stage == DROP_REFERENCE, this function checks
8616  * reference count of the block pointed to. if the block
8617  * is shared and we need update back refs for the subtree
8618  * rooted at the block, this function changes wc->stage to
8619  * UPDATE_BACKREF. if the block is shared and there is no
8620  * need to update back, this function drops the reference
8621  * to the block.
8622  *
8623  * NOTE: return value 1 means we should stop walking down.
8624  */
8625 static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8626                                  struct btrfs_root *root,
8627                                  struct btrfs_path *path,
8628                                  struct walk_control *wc, int *lookup_info)
8629 {
8630         struct btrfs_fs_info *fs_info = root->fs_info;
8631         u64 bytenr;
8632         u64 generation;
8633         u64 parent;
8634         u32 blocksize;
8635         struct btrfs_key key;
8636         struct extent_buffer *next;
8637         int level = wc->level;
8638         int reada = 0;
8639         int ret = 0;
8640         bool need_account = false;
8641
8642         generation = btrfs_node_ptr_generation(path->nodes[level],
8643                                                path->slots[level]);
8644         /*
8645          * if the lower level block was created before the snapshot
8646          * was created, we know there is no need to update back refs
8647          * for the subtree
8648          */
8649         if (wc->stage == UPDATE_BACKREF &&
8650             generation <= root->root_key.offset) {
8651                 *lookup_info = 1;
8652                 return 1;
8653         }
8654
8655         bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
8656         blocksize = fs_info->nodesize;
8657
8658         next = find_extent_buffer(fs_info, bytenr);
8659         if (!next) {
8660                 next = btrfs_find_create_tree_block(fs_info, bytenr);
8661                 if (IS_ERR(next))
8662                         return PTR_ERR(next);
8663
8664                 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8665                                                level - 1);
8666                 reada = 1;
8667         }
8668         btrfs_tree_lock(next);
8669         btrfs_set_lock_blocking(next);
8670
8671         ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
8672                                        &wc->refs[level - 1],
8673                                        &wc->flags[level - 1]);
8674         if (ret < 0)
8675                 goto out_unlock;
8676
8677         if (unlikely(wc->refs[level - 1] == 0)) {
8678                 btrfs_err(fs_info, "Missing references.");
8679                 ret = -EIO;
8680                 goto out_unlock;
8681         }
8682         *lookup_info = 0;
8683
8684         if (wc->stage == DROP_REFERENCE) {
8685                 if (wc->refs[level - 1] > 1) {
8686                         need_account = true;
8687                         if (level == 1 &&
8688                             (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8689                                 goto skip;
8690
8691                         if (!wc->update_ref ||
8692                             generation <= root->root_key.offset)
8693                                 goto skip;
8694
8695                         btrfs_node_key_to_cpu(path->nodes[level], &key,
8696                                               path->slots[level]);
8697                         ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8698                         if (ret < 0)
8699                                 goto skip;
8700
8701                         wc->stage = UPDATE_BACKREF;
8702                         wc->shared_level = level - 1;
8703                 }
8704         } else {
8705                 if (level == 1 &&
8706                     (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8707                         goto skip;
8708         }
8709
8710         if (!btrfs_buffer_uptodate(next, generation, 0)) {
8711                 btrfs_tree_unlock(next);
8712                 free_extent_buffer(next);
8713                 next = NULL;
8714                 *lookup_info = 1;
8715         }
8716
8717         if (!next) {
8718                 if (reada && level == 1)
8719                         reada_walk_down(trans, root, wc, path);
8720                 next = read_tree_block(fs_info, bytenr, generation);
8721                 if (IS_ERR(next)) {
8722                         return PTR_ERR(next);
8723                 } else if (!extent_buffer_uptodate(next)) {
8724                         free_extent_buffer(next);
8725                         return -EIO;
8726                 }
8727                 btrfs_tree_lock(next);
8728                 btrfs_set_lock_blocking(next);
8729         }
8730
8731         level--;
8732         ASSERT(level == btrfs_header_level(next));
8733         if (level != btrfs_header_level(next)) {
8734                 btrfs_err(root->fs_info, "mismatched level");
8735                 ret = -EIO;
8736                 goto out_unlock;
8737         }
8738         path->nodes[level] = next;
8739         path->slots[level] = 0;
8740         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8741         wc->level = level;
8742         if (wc->level == 1)
8743                 wc->reada_slot = 0;
8744         return 0;
8745 skip:
8746         wc->refs[level - 1] = 0;
8747         wc->flags[level - 1] = 0;
8748         if (wc->stage == DROP_REFERENCE) {
8749                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8750                         parent = path->nodes[level]->start;
8751                 } else {
8752                         ASSERT(root->root_key.objectid ==
8753                                btrfs_header_owner(path->nodes[level]));
8754                         if (root->root_key.objectid !=
8755                             btrfs_header_owner(path->nodes[level])) {
8756                                 btrfs_err(root->fs_info,
8757                                                 "mismatched block owner");
8758                                 ret = -EIO;
8759                                 goto out_unlock;
8760                         }
8761                         parent = 0;
8762                 }
8763
8764                 if (need_account) {
8765                         ret = btrfs_qgroup_trace_subtree(trans, root, next,
8766                                                          generation, level - 1);
8767                         if (ret) {
8768                                 btrfs_err_rl(fs_info,
8769                                              "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
8770                                              ret);
8771                         }
8772                 }
8773                 ret = btrfs_free_extent(trans, fs_info, bytenr, blocksize,
8774                                         parent, root->root_key.objectid,
8775                                         level - 1, 0);
8776                 if (ret)
8777                         goto out_unlock;
8778         }
8779
8780         *lookup_info = 1;
8781         ret = 1;
8782
8783 out_unlock:
8784         btrfs_tree_unlock(next);
8785         free_extent_buffer(next);
8786
8787         return ret;
8788 }
8789
8790 /*
8791  * helper to process tree block while walking up the tree.
8792  *
8793  * when wc->stage == DROP_REFERENCE, this function drops
8794  * reference count on the block.
8795  *
8796  * when wc->stage == UPDATE_BACKREF, this function changes
8797  * wc->stage back to DROP_REFERENCE if we changed wc->stage
8798  * to UPDATE_BACKREF previously while processing the block.
8799  *
8800  * NOTE: return value 1 means we should stop walking up.
8801  */
8802 static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
8803                                  struct btrfs_root *root,
8804                                  struct btrfs_path *path,
8805                                  struct walk_control *wc)
8806 {
8807         struct btrfs_fs_info *fs_info = root->fs_info;
8808         int ret;
8809         int level = wc->level;
8810         struct extent_buffer *eb = path->nodes[level];
8811         u64 parent = 0;
8812
8813         if (wc->stage == UPDATE_BACKREF) {
8814                 BUG_ON(wc->shared_level < level);
8815                 if (level < wc->shared_level)
8816                         goto out;
8817
8818                 ret = find_next_key(path, level + 1, &wc->update_progress);
8819                 if (ret > 0)
8820                         wc->update_ref = 0;
8821
8822                 wc->stage = DROP_REFERENCE;
8823                 wc->shared_level = -1;
8824                 path->slots[level] = 0;
8825
8826                 /*
8827                  * check reference count again if the block isn't locked.
8828                  * we should start walking down the tree again if reference
8829                  * count is one.
8830                  */
8831                 if (!path->locks[level]) {
8832                         BUG_ON(level == 0);
8833                         btrfs_tree_lock(eb);
8834                         btrfs_set_lock_blocking(eb);
8835                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8836
8837                         ret = btrfs_lookup_extent_info(trans, fs_info,
8838                                                        eb->start, level, 1,
8839                                                        &wc->refs[level],
8840                                                        &wc->flags[level]);
8841                         if (ret < 0) {
8842                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8843                                 path->locks[level] = 0;
8844                                 return ret;
8845                         }
8846                         BUG_ON(wc->refs[level] == 0);
8847                         if (wc->refs[level] == 1) {
8848                                 btrfs_tree_unlock_rw(eb, path->locks[level]);
8849                                 path->locks[level] = 0;
8850                                 return 1;
8851                         }
8852                 }
8853         }
8854
8855         /* wc->stage == DROP_REFERENCE */
8856         BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
8857
8858         if (wc->refs[level] == 1) {
8859                 if (level == 0) {
8860                         if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8861                                 ret = btrfs_dec_ref(trans, root, eb, 1);
8862                         else
8863                                 ret = btrfs_dec_ref(trans, root, eb, 0);
8864                         BUG_ON(ret); /* -ENOMEM */
8865                         ret = btrfs_qgroup_trace_leaf_items(trans, fs_info, eb);
8866                         if (ret) {
8867                                 btrfs_err_rl(fs_info,
8868                                              "error %d accounting leaf items. Quota is out of sync, rescan required.",
8869                                              ret);
8870                         }
8871                 }
8872                 /* make block locked assertion in clean_tree_block happy */
8873                 if (!path->locks[level] &&
8874                     btrfs_header_generation(eb) == trans->transid) {
8875                         btrfs_tree_lock(eb);
8876                         btrfs_set_lock_blocking(eb);
8877                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
8878                 }
8879                 clean_tree_block(fs_info, eb);
8880         }
8881
8882         if (eb == root->node) {
8883                 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8884                         parent = eb->start;
8885                 else
8886                         BUG_ON(root->root_key.objectid !=
8887                                btrfs_header_owner(eb));
8888         } else {
8889                 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8890                         parent = path->nodes[level + 1]->start;
8891                 else
8892                         BUG_ON(root->root_key.objectid !=
8893                                btrfs_header_owner(path->nodes[level + 1]));
8894         }
8895
8896         btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
8897 out:
8898         wc->refs[level] = 0;
8899         wc->flags[level] = 0;
8900         return 0;
8901 }
8902
8903 static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8904                                    struct btrfs_root *root,
8905                                    struct btrfs_path *path,
8906                                    struct walk_control *wc)
8907 {
8908         int level = wc->level;
8909         int lookup_info = 1;
8910         int ret;
8911
8912         while (level >= 0) {
8913                 ret = walk_down_proc(trans, root, path, wc, lookup_info);
8914                 if (ret > 0)
8915                         break;
8916
8917                 if (level == 0)
8918                         break;
8919
8920                 if (path->slots[level] >=
8921                     btrfs_header_nritems(path->nodes[level]))
8922                         break;
8923
8924                 ret = do_walk_down(trans, root, path, wc, &lookup_info);
8925                 if (ret > 0) {
8926                         path->slots[level]++;
8927                         continue;
8928                 } else if (ret < 0)
8929                         return ret;
8930                 level = wc->level;
8931         }
8932         return 0;
8933 }
8934
8935 static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
8936                                  struct btrfs_root *root,
8937                                  struct btrfs_path *path,
8938                                  struct walk_control *wc, int max_level)
8939 {
8940         int level = wc->level;
8941         int ret;
8942
8943         path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8944         while (level < max_level && path->nodes[level]) {
8945                 wc->level = level;
8946                 if (path->slots[level] + 1 <
8947                     btrfs_header_nritems(path->nodes[level])) {
8948                         path->slots[level]++;
8949                         return 0;
8950                 } else {
8951                         ret = walk_up_proc(trans, root, path, wc);
8952                         if (ret > 0)
8953                                 return 0;
8954
8955                         if (path->locks[level]) {
8956                                 btrfs_tree_unlock_rw(path->nodes[level],
8957                                                      path->locks[level]);
8958                                 path->locks[level] = 0;
8959                         }
8960                         free_extent_buffer(path->nodes[level]);
8961                         path->nodes[level] = NULL;
8962                         level++;
8963                 }
8964         }
8965         return 1;
8966 }
8967
8968 /*
8969  * drop a subvolume tree.
8970  *
8971  * this function traverses the tree freeing any blocks that only
8972  * referenced by the tree.
8973  *
8974  * when a shared tree block is found. this function decreases its
8975  * reference count by one. if update_ref is true, this function
8976  * also make sure backrefs for the shared block and all lower level
8977  * blocks are properly updated.
8978  *
8979  * If called with for_reloc == 0, may exit early with -EAGAIN
8980  */
8981 int btrfs_drop_snapshot(struct btrfs_root *root,
8982                          struct btrfs_block_rsv *block_rsv, int update_ref,
8983                          int for_reloc)
8984 {
8985         struct btrfs_fs_info *fs_info = root->fs_info;
8986         struct btrfs_path *path;
8987         struct btrfs_trans_handle *trans;
8988         struct btrfs_root *tree_root = fs_info->tree_root;
8989         struct btrfs_root_item *root_item = &root->root_item;
8990         struct walk_control *wc;
8991         struct btrfs_key key;
8992         int err = 0;
8993         int ret;
8994         int level;
8995         bool root_dropped = false;
8996
8997         btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
8998
8999         path = btrfs_alloc_path();
9000         if (!path) {
9001                 err = -ENOMEM;
9002                 goto out;
9003         }
9004
9005         wc = kzalloc(sizeof(*wc), GFP_NOFS);
9006         if (!wc) {
9007                 btrfs_free_path(path);
9008                 err = -ENOMEM;
9009                 goto out;
9010         }
9011
9012         trans = btrfs_start_transaction(tree_root, 0);
9013         if (IS_ERR(trans)) {
9014                 err = PTR_ERR(trans);
9015                 goto out_free;
9016         }
9017
9018         if (block_rsv)
9019                 trans->block_rsv = block_rsv;
9020
9021         if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
9022                 level = btrfs_header_level(root->node);
9023                 path->nodes[level] = btrfs_lock_root_node(root);
9024                 btrfs_set_lock_blocking(path->nodes[level]);
9025                 path->slots[level] = 0;
9026                 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9027                 memset(&wc->update_progress, 0,
9028                        sizeof(wc->update_progress));
9029         } else {
9030                 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
9031                 memcpy(&wc->update_progress, &key,
9032                        sizeof(wc->update_progress));
9033
9034                 level = root_item->drop_level;
9035                 BUG_ON(level == 0);
9036                 path->lowest_level = level;
9037                 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
9038                 path->lowest_level = 0;
9039                 if (ret < 0) {
9040                         err = ret;
9041                         goto out_end_trans;
9042                 }
9043                 WARN_ON(ret > 0);
9044
9045                 /*
9046                  * unlock our path, this is safe because only this
9047                  * function is allowed to delete this snapshot
9048                  */
9049                 btrfs_unlock_up_safe(path, 0);
9050
9051                 level = btrfs_header_level(root->node);
9052                 while (1) {
9053                         btrfs_tree_lock(path->nodes[level]);
9054                         btrfs_set_lock_blocking(path->nodes[level]);
9055                         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9056
9057                         ret = btrfs_lookup_extent_info(trans, fs_info,
9058                                                 path->nodes[level]->start,
9059                                                 level, 1, &wc->refs[level],
9060                                                 &wc->flags[level]);
9061                         if (ret < 0) {
9062                                 err = ret;
9063                                 goto out_end_trans;
9064                         }
9065                         BUG_ON(wc->refs[level] == 0);
9066
9067                         if (level == root_item->drop_level)
9068                                 break;
9069
9070                         btrfs_tree_unlock(path->nodes[level]);
9071                         path->locks[level] = 0;
9072                         WARN_ON(wc->refs[level] != 1);
9073                         level--;
9074                 }
9075         }
9076
9077         wc->level = level;
9078         wc->shared_level = -1;
9079         wc->stage = DROP_REFERENCE;
9080         wc->update_ref = update_ref;
9081         wc->keep_locks = 0;
9082         wc->for_reloc = for_reloc;
9083         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9084
9085         while (1) {
9086
9087                 ret = walk_down_tree(trans, root, path, wc);
9088                 if (ret < 0) {
9089                         err = ret;
9090                         break;
9091                 }
9092
9093                 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
9094                 if (ret < 0) {
9095                         err = ret;
9096                         break;
9097                 }
9098
9099                 if (ret > 0) {
9100                         BUG_ON(wc->stage != DROP_REFERENCE);
9101                         break;
9102                 }
9103
9104                 if (wc->stage == DROP_REFERENCE) {
9105                         level = wc->level;
9106                         btrfs_node_key(path->nodes[level],
9107                                        &root_item->drop_progress,
9108                                        path->slots[level]);
9109                         root_item->drop_level = level;
9110                 }
9111
9112                 BUG_ON(wc->level == 0);
9113                 if (btrfs_should_end_transaction(trans) ||
9114                     (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
9115                         ret = btrfs_update_root(trans, tree_root,
9116                                                 &root->root_key,
9117                                                 root_item);
9118                         if (ret) {
9119                                 btrfs_abort_transaction(trans, ret);
9120                                 err = ret;
9121                                 goto out_end_trans;
9122                         }
9123
9124                         btrfs_end_transaction_throttle(trans);
9125                         if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
9126                                 btrfs_debug(fs_info,
9127                                             "drop snapshot early exit");
9128                                 err = -EAGAIN;
9129                                 goto out_free;
9130                         }
9131
9132                         trans = btrfs_start_transaction(tree_root, 0);
9133                         if (IS_ERR(trans)) {
9134                                 err = PTR_ERR(trans);
9135                                 goto out_free;
9136                         }
9137                         if (block_rsv)
9138                                 trans->block_rsv = block_rsv;
9139                 }
9140         }
9141         btrfs_release_path(path);
9142         if (err)
9143                 goto out_end_trans;
9144
9145         ret = btrfs_del_root(trans, tree_root, &root->root_key);
9146         if (ret) {
9147                 btrfs_abort_transaction(trans, ret);
9148                 goto out_end_trans;
9149         }
9150
9151         if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
9152                 ret = btrfs_find_root(tree_root, &root->root_key, path,
9153                                       NULL, NULL);
9154                 if (ret < 0) {
9155                         btrfs_abort_transaction(trans, ret);
9156                         err = ret;
9157                         goto out_end_trans;
9158                 } else if (ret > 0) {
9159                         /* if we fail to delete the orphan item this time
9160                          * around, it'll get picked up the next time.
9161                          *
9162                          * The most common failure here is just -ENOENT.
9163                          */
9164                         btrfs_del_orphan_item(trans, tree_root,
9165                                               root->root_key.objectid);
9166                 }
9167         }
9168
9169         if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
9170                 btrfs_add_dropped_root(trans, root);
9171         } else {
9172                 free_extent_buffer(root->node);
9173                 free_extent_buffer(root->commit_root);
9174                 btrfs_put_fs_root(root);
9175         }
9176         root_dropped = true;
9177 out_end_trans:
9178         btrfs_end_transaction_throttle(trans);
9179 out_free:
9180         kfree(wc);
9181         btrfs_free_path(path);
9182 out:
9183         /*
9184          * So if we need to stop dropping the snapshot for whatever reason we
9185          * need to make sure to add it back to the dead root list so that we
9186          * keep trying to do the work later.  This also cleans up roots if we
9187          * don't have it in the radix (like when we recover after a power fail
9188          * or unmount) so we don't leak memory.
9189          */
9190         if (!for_reloc && root_dropped == false)
9191                 btrfs_add_dead_root(root);
9192         if (err && err != -EAGAIN)
9193                 btrfs_handle_fs_error(fs_info, err, NULL);
9194         return err;
9195 }
9196
9197 /*
9198  * drop subtree rooted at tree block 'node'.
9199  *
9200  * NOTE: this function will unlock and release tree block 'node'
9201  * only used by relocation code
9202  */
9203 int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
9204                         struct btrfs_root *root,
9205                         struct extent_buffer *node,
9206                         struct extent_buffer *parent)
9207 {
9208         struct btrfs_fs_info *fs_info = root->fs_info;
9209         struct btrfs_path *path;
9210         struct walk_control *wc;
9211         int level;
9212         int parent_level;
9213         int ret = 0;
9214         int wret;
9215
9216         BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
9217
9218         path = btrfs_alloc_path();
9219         if (!path)
9220                 return -ENOMEM;
9221
9222         wc = kzalloc(sizeof(*wc), GFP_NOFS);
9223         if (!wc) {
9224                 btrfs_free_path(path);
9225                 return -ENOMEM;
9226         }
9227
9228         btrfs_assert_tree_locked(parent);
9229         parent_level = btrfs_header_level(parent);
9230         extent_buffer_get(parent);
9231         path->nodes[parent_level] = parent;
9232         path->slots[parent_level] = btrfs_header_nritems(parent);
9233
9234         btrfs_assert_tree_locked(node);
9235         level = btrfs_header_level(node);
9236         path->nodes[level] = node;
9237         path->slots[level] = 0;
9238         path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
9239
9240         wc->refs[parent_level] = 1;
9241         wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
9242         wc->level = level;
9243         wc->shared_level = -1;
9244         wc->stage = DROP_REFERENCE;
9245         wc->update_ref = 0;
9246         wc->keep_locks = 1;
9247         wc->for_reloc = 1;
9248         wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
9249
9250         while (1) {
9251                 wret = walk_down_tree(trans, root, path, wc);
9252                 if (wret < 0) {
9253                         ret = wret;
9254                         break;
9255                 }
9256
9257                 wret = walk_up_tree(trans, root, path, wc, parent_level);
9258                 if (wret < 0)
9259                         ret = wret;
9260                 if (wret != 0)
9261                         break;
9262         }
9263
9264         kfree(wc);
9265         btrfs_free_path(path);
9266         return ret;
9267 }
9268
9269 static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
9270 {
9271         u64 num_devices;
9272         u64 stripped;
9273
9274         /*
9275          * if restripe for this chunk_type is on pick target profile and
9276          * return, otherwise do the usual balance
9277          */
9278         stripped = get_restripe_target(fs_info, flags);
9279         if (stripped)
9280                 return extended_to_chunk(stripped);
9281
9282         num_devices = fs_info->fs_devices->rw_devices;
9283
9284         stripped = BTRFS_BLOCK_GROUP_RAID0 |
9285                 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
9286                 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9287
9288         if (num_devices == 1) {
9289                 stripped |= BTRFS_BLOCK_GROUP_DUP;
9290                 stripped = flags & ~stripped;
9291
9292                 /* turn raid0 into single device chunks */
9293                 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9294                         return stripped;
9295
9296                 /* turn mirroring into duplication */
9297                 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9298                              BTRFS_BLOCK_GROUP_RAID10))
9299                         return stripped | BTRFS_BLOCK_GROUP_DUP;
9300         } else {
9301                 /* they already had raid on here, just return */
9302                 if (flags & stripped)
9303                         return flags;
9304
9305                 stripped |= BTRFS_BLOCK_GROUP_DUP;
9306                 stripped = flags & ~stripped;
9307
9308                 /* switch duplicated blocks with raid1 */
9309                 if (flags & BTRFS_BLOCK_GROUP_DUP)
9310                         return stripped | BTRFS_BLOCK_GROUP_RAID1;
9311
9312                 /* this is drive concat, leave it alone */
9313         }
9314
9315         return flags;
9316 }
9317
9318 static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
9319 {
9320         struct btrfs_space_info *sinfo = cache->space_info;
9321         u64 num_bytes;
9322         u64 min_allocable_bytes;
9323         int ret = -ENOSPC;
9324
9325         /*
9326          * We need some metadata space and system metadata space for
9327          * allocating chunks in some corner cases until we force to set
9328          * it to be readonly.
9329          */
9330         if ((sinfo->flags &
9331              (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9332             !force)
9333                 min_allocable_bytes = SZ_1M;
9334         else
9335                 min_allocable_bytes = 0;
9336
9337         spin_lock(&sinfo->lock);
9338         spin_lock(&cache->lock);
9339
9340         if (cache->ro) {
9341                 cache->ro++;
9342                 ret = 0;
9343                 goto out;
9344         }
9345
9346         num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9347                     cache->bytes_super - btrfs_block_group_used(&cache->item);
9348
9349         if (btrfs_space_info_used(sinfo, true) + num_bytes +
9350             min_allocable_bytes <= sinfo->total_bytes) {
9351                 sinfo->bytes_readonly += num_bytes;
9352                 cache->ro++;
9353                 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
9354                 ret = 0;
9355         }
9356 out:
9357         spin_unlock(&cache->lock);
9358         spin_unlock(&sinfo->lock);
9359         return ret;
9360 }
9361
9362 int btrfs_inc_block_group_ro(struct btrfs_fs_info *fs_info,
9363                              struct btrfs_block_group_cache *cache)
9364
9365 {
9366         struct btrfs_trans_handle *trans;
9367         u64 alloc_flags;
9368         int ret;
9369
9370 again:
9371         trans = btrfs_join_transaction(fs_info->extent_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 }