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