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