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