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