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