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