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