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