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