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