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