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