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