Btrfs: rework qgroup accounting
[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
ZY
2994
2995 ref_root = btrfs_header_owner(buf);
31840ae1
ZY
2996 nritems = btrfs_header_nritems(buf);
2997 level = btrfs_header_level(buf);
2998
27cdeb70 2999 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
5d4f98a2 3000 return 0;
31840ae1 3001
5d4f98a2
YZ
3002 if (inc)
3003 process_func = btrfs_inc_extent_ref;
3004 else
3005 process_func = btrfs_free_extent;
31840ae1 3006
5d4f98a2
YZ
3007 if (full_backref)
3008 parent = buf->start;
3009 else
3010 parent = 0;
3011
3012 for (i = 0; i < nritems; i++) {
31840ae1 3013 if (level == 0) {
5d4f98a2 3014 btrfs_item_key_to_cpu(buf, &key, i);
31840ae1
ZY
3015 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
3016 continue;
5d4f98a2 3017 fi = btrfs_item_ptr(buf, i,
31840ae1
ZY
3018 struct btrfs_file_extent_item);
3019 if (btrfs_file_extent_type(buf, fi) ==
3020 BTRFS_FILE_EXTENT_INLINE)
3021 continue;
3022 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3023 if (bytenr == 0)
3024 continue;
5d4f98a2
YZ
3025
3026 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3027 key.offset -= btrfs_file_extent_offset(buf, fi);
3028 ret = process_func(trans, root, bytenr, num_bytes,
3029 parent, ref_root, key.objectid,
fcebe456 3030 key.offset, no_quota);
31840ae1
ZY
3031 if (ret)
3032 goto fail;
3033 } else {
5d4f98a2
YZ
3034 bytenr = btrfs_node_blockptr(buf, i);
3035 num_bytes = btrfs_level_size(root, level - 1);
3036 ret = process_func(trans, root, bytenr, num_bytes,
66d7e7f0 3037 parent, ref_root, level - 1, 0,
fcebe456 3038 no_quota);
31840ae1
ZY
3039 if (ret)
3040 goto fail;
3041 }
3042 }
3043 return 0;
3044fail:
5d4f98a2
YZ
3045 return ret;
3046}
3047
3048int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
fcebe456 3049 struct extent_buffer *buf, int full_backref, int no_quota)
5d4f98a2 3050{
fcebe456 3051 return __btrfs_mod_ref(trans, root, buf, full_backref, 1, no_quota);
5d4f98a2
YZ
3052}
3053
3054int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
fcebe456 3055 struct extent_buffer *buf, int full_backref, int no_quota)
5d4f98a2 3056{
fcebe456 3057 return __btrfs_mod_ref(trans, root, buf, full_backref, 0, no_quota);
31840ae1
ZY
3058}
3059
9078a3e1
CM
3060static int write_one_cache_group(struct btrfs_trans_handle *trans,
3061 struct btrfs_root *root,
3062 struct btrfs_path *path,
3063 struct btrfs_block_group_cache *cache)
3064{
3065 int ret;
9078a3e1 3066 struct btrfs_root *extent_root = root->fs_info->extent_root;
5f39d397
CM
3067 unsigned long bi;
3068 struct extent_buffer *leaf;
9078a3e1 3069
9078a3e1 3070 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
54aa1f4d
CM
3071 if (ret < 0)
3072 goto fail;
79787eaa 3073 BUG_ON(ret); /* Corruption */
5f39d397
CM
3074
3075 leaf = path->nodes[0];
3076 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3077 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3078 btrfs_mark_buffer_dirty(leaf);
b3b4aa74 3079 btrfs_release_path(path);
54aa1f4d 3080fail:
79787eaa
JM
3081 if (ret) {
3082 btrfs_abort_transaction(trans, root, ret);
9078a3e1 3083 return ret;
79787eaa 3084 }
9078a3e1
CM
3085 return 0;
3086
3087}
3088
4a8c9a62
YZ
3089static struct btrfs_block_group_cache *
3090next_block_group(struct btrfs_root *root,
3091 struct btrfs_block_group_cache *cache)
3092{
3093 struct rb_node *node;
3094 spin_lock(&root->fs_info->block_group_cache_lock);
3095 node = rb_next(&cache->cache_node);
3096 btrfs_put_block_group(cache);
3097 if (node) {
3098 cache = rb_entry(node, struct btrfs_block_group_cache,
3099 cache_node);
11dfe35a 3100 btrfs_get_block_group(cache);
4a8c9a62
YZ
3101 } else
3102 cache = NULL;
3103 spin_unlock(&root->fs_info->block_group_cache_lock);
3104 return cache;
3105}
3106
0af3d00b
JB
3107static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3108 struct btrfs_trans_handle *trans,
3109 struct btrfs_path *path)
3110{
3111 struct btrfs_root *root = block_group->fs_info->tree_root;
3112 struct inode *inode = NULL;
3113 u64 alloc_hint = 0;
2b20982e 3114 int dcs = BTRFS_DC_ERROR;
0af3d00b
JB
3115 int num_pages = 0;
3116 int retries = 0;
3117 int ret = 0;
3118
3119 /*
3120 * If this block group is smaller than 100 megs don't bother caching the
3121 * block group.
3122 */
3123 if (block_group->key.offset < (100 * 1024 * 1024)) {
3124 spin_lock(&block_group->lock);
3125 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3126 spin_unlock(&block_group->lock);
3127 return 0;
3128 }
3129
3130again:
3131 inode = lookup_free_space_inode(root, block_group, path);
3132 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3133 ret = PTR_ERR(inode);
b3b4aa74 3134 btrfs_release_path(path);
0af3d00b
JB
3135 goto out;
3136 }
3137
3138 if (IS_ERR(inode)) {
3139 BUG_ON(retries);
3140 retries++;
3141
3142 if (block_group->ro)
3143 goto out_free;
3144
3145 ret = create_free_space_inode(root, trans, block_group, path);
3146 if (ret)
3147 goto out_free;
3148 goto again;
3149 }
3150
5b0e95bf
JB
3151 /* We've already setup this transaction, go ahead and exit */
3152 if (block_group->cache_generation == trans->transid &&
3153 i_size_read(inode)) {
3154 dcs = BTRFS_DC_SETUP;
3155 goto out_put;
3156 }
3157
0af3d00b
JB
3158 /*
3159 * We want to set the generation to 0, that way if anything goes wrong
3160 * from here on out we know not to trust this cache when we load up next
3161 * time.
3162 */
3163 BTRFS_I(inode)->generation = 0;
3164 ret = btrfs_update_inode(trans, root, inode);
3165 WARN_ON(ret);
3166
3167 if (i_size_read(inode) > 0) {
7b61cd92
MX
3168 ret = btrfs_check_trunc_cache_free_space(root,
3169 &root->fs_info->global_block_rsv);
3170 if (ret)
3171 goto out_put;
3172
74514323 3173 ret = btrfs_truncate_free_space_cache(root, trans, inode);
0af3d00b
JB
3174 if (ret)
3175 goto out_put;
3176 }
3177
3178 spin_lock(&block_group->lock);
cf7c1ef6
LB
3179 if (block_group->cached != BTRFS_CACHE_FINISHED ||
3180 !btrfs_test_opt(root, SPACE_CACHE)) {
3181 /*
3182 * don't bother trying to write stuff out _if_
3183 * a) we're not cached,
3184 * b) we're with nospace_cache mount option.
3185 */
2b20982e 3186 dcs = BTRFS_DC_WRITTEN;
0af3d00b
JB
3187 spin_unlock(&block_group->lock);
3188 goto out_put;
3189 }
3190 spin_unlock(&block_group->lock);
3191
6fc823b1
JB
3192 /*
3193 * Try to preallocate enough space based on how big the block group is.
3194 * Keep in mind this has to include any pinned space which could end up
3195 * taking up quite a bit since it's not folded into the other space
3196 * cache.
3197 */
3198 num_pages = (int)div64_u64(block_group->key.offset, 256 * 1024 * 1024);
0af3d00b
JB
3199 if (!num_pages)
3200 num_pages = 1;
3201
0af3d00b
JB
3202 num_pages *= 16;
3203 num_pages *= PAGE_CACHE_SIZE;
3204
3205 ret = btrfs_check_data_free_space(inode, num_pages);
3206 if (ret)
3207 goto out_put;
3208
3209 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3210 num_pages, num_pages,
3211 &alloc_hint);
2b20982e
JB
3212 if (!ret)
3213 dcs = BTRFS_DC_SETUP;
0af3d00b 3214 btrfs_free_reserved_data_space(inode, num_pages);
c09544e0 3215
0af3d00b
JB
3216out_put:
3217 iput(inode);
3218out_free:
b3b4aa74 3219 btrfs_release_path(path);
0af3d00b
JB
3220out:
3221 spin_lock(&block_group->lock);
e65cbb94 3222 if (!ret && dcs == BTRFS_DC_SETUP)
5b0e95bf 3223 block_group->cache_generation = trans->transid;
2b20982e 3224 block_group->disk_cache_state = dcs;
0af3d00b
JB
3225 spin_unlock(&block_group->lock);
3226
3227 return ret;
3228}
3229
96b5179d
CM
3230int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3231 struct btrfs_root *root)
9078a3e1 3232{
4a8c9a62 3233 struct btrfs_block_group_cache *cache;
9078a3e1 3234 int err = 0;
9078a3e1 3235 struct btrfs_path *path;
96b5179d 3236 u64 last = 0;
9078a3e1
CM
3237
3238 path = btrfs_alloc_path();
3239 if (!path)
3240 return -ENOMEM;
3241
0af3d00b
JB
3242again:
3243 while (1) {
3244 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3245 while (cache) {
3246 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3247 break;
3248 cache = next_block_group(root, cache);
3249 }
3250 if (!cache) {
3251 if (last == 0)
3252 break;
3253 last = 0;
3254 continue;
3255 }
3256 err = cache_save_setup(cache, trans, path);
3257 last = cache->key.objectid + cache->key.offset;
3258 btrfs_put_block_group(cache);
3259 }
3260
d397712b 3261 while (1) {
4a8c9a62
YZ
3262 if (last == 0) {
3263 err = btrfs_run_delayed_refs(trans, root,
3264 (unsigned long)-1);
79787eaa
JM
3265 if (err) /* File system offline */
3266 goto out;
0f9dd46c 3267 }
54aa1f4d 3268
4a8c9a62
YZ
3269 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3270 while (cache) {
0af3d00b
JB
3271 if (cache->disk_cache_state == BTRFS_DC_CLEAR) {
3272 btrfs_put_block_group(cache);
3273 goto again;
3274 }
3275
4a8c9a62
YZ
3276 if (cache->dirty)
3277 break;
3278 cache = next_block_group(root, cache);
3279 }
3280 if (!cache) {
3281 if (last == 0)
3282 break;
3283 last = 0;
3284 continue;
3285 }
0f9dd46c 3286
0cb59c99
JB
3287 if (cache->disk_cache_state == BTRFS_DC_SETUP)
3288 cache->disk_cache_state = BTRFS_DC_NEED_WRITE;
e8569813 3289 cache->dirty = 0;
4a8c9a62 3290 last = cache->key.objectid + cache->key.offset;
0f9dd46c 3291
4a8c9a62 3292 err = write_one_cache_group(trans, root, path, cache);
e84cc142 3293 btrfs_put_block_group(cache);
79787eaa
JM
3294 if (err) /* File system offline */
3295 goto out;
9078a3e1 3296 }
4a8c9a62 3297
0cb59c99
JB
3298 while (1) {
3299 /*
3300 * I don't think this is needed since we're just marking our
3301 * preallocated extent as written, but just in case it can't
3302 * hurt.
3303 */
3304 if (last == 0) {
3305 err = btrfs_run_delayed_refs(trans, root,
3306 (unsigned long)-1);
79787eaa
JM
3307 if (err) /* File system offline */
3308 goto out;
0cb59c99
JB
3309 }
3310
3311 cache = btrfs_lookup_first_block_group(root->fs_info, last);
3312 while (cache) {
3313 /*
3314 * Really this shouldn't happen, but it could if we
3315 * couldn't write the entire preallocated extent and
3316 * splitting the extent resulted in a new block.
3317 */
3318 if (cache->dirty) {
3319 btrfs_put_block_group(cache);
3320 goto again;
3321 }
3322 if (cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
3323 break;
3324 cache = next_block_group(root, cache);
3325 }
3326 if (!cache) {
3327 if (last == 0)
3328 break;
3329 last = 0;
3330 continue;
3331 }
3332
79787eaa 3333 err = btrfs_write_out_cache(root, trans, cache, path);
0cb59c99
JB
3334
3335 /*
3336 * If we didn't have an error then the cache state is still
3337 * NEED_WRITE, so we can set it to WRITTEN.
3338 */
79787eaa 3339 if (!err && cache->disk_cache_state == BTRFS_DC_NEED_WRITE)
0cb59c99
JB
3340 cache->disk_cache_state = BTRFS_DC_WRITTEN;
3341 last = cache->key.objectid + cache->key.offset;
3342 btrfs_put_block_group(cache);
3343 }
79787eaa 3344out:
0cb59c99 3345
9078a3e1 3346 btrfs_free_path(path);
79787eaa 3347 return err;
9078a3e1
CM
3348}
3349
d2fb3437
YZ
3350int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3351{
3352 struct btrfs_block_group_cache *block_group;
3353 int readonly = 0;
3354
3355 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
3356 if (!block_group || block_group->ro)
3357 readonly = 1;
3358 if (block_group)
fa9c0d79 3359 btrfs_put_block_group(block_group);
d2fb3437
YZ
3360 return readonly;
3361}
3362
6ab0a202
JM
3363static const char *alloc_name(u64 flags)
3364{
3365 switch (flags) {
3366 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3367 return "mixed";
3368 case BTRFS_BLOCK_GROUP_METADATA:
3369 return "metadata";
3370 case BTRFS_BLOCK_GROUP_DATA:
3371 return "data";
3372 case BTRFS_BLOCK_GROUP_SYSTEM:
3373 return "system";
3374 default:
3375 WARN_ON(1);
3376 return "invalid-combination";
3377 };
3378}
3379
593060d7
CM
3380static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3381 u64 total_bytes, u64 bytes_used,
3382 struct btrfs_space_info **space_info)
3383{
3384 struct btrfs_space_info *found;
b742bb82
YZ
3385 int i;
3386 int factor;
b150a4f1 3387 int ret;
b742bb82
YZ
3388
3389 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3390 BTRFS_BLOCK_GROUP_RAID10))
3391 factor = 2;
3392 else
3393 factor = 1;
593060d7
CM
3394
3395 found = __find_space_info(info, flags);
3396 if (found) {
25179201 3397 spin_lock(&found->lock);
593060d7 3398 found->total_bytes += total_bytes;
89a55897 3399 found->disk_total += total_bytes * factor;
593060d7 3400 found->bytes_used += bytes_used;
b742bb82 3401 found->disk_used += bytes_used * factor;
8f18cf13 3402 found->full = 0;
25179201 3403 spin_unlock(&found->lock);
593060d7
CM
3404 *space_info = found;
3405 return 0;
3406 }
c146afad 3407 found = kzalloc(sizeof(*found), GFP_NOFS);
593060d7
CM
3408 if (!found)
3409 return -ENOMEM;
3410
b150a4f1
JB
3411 ret = percpu_counter_init(&found->total_bytes_pinned, 0);
3412 if (ret) {
3413 kfree(found);
3414 return ret;
3415 }
3416
536cd964 3417 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
b742bb82 3418 INIT_LIST_HEAD(&found->block_groups[i]);
536cd964
MX
3419 kobject_init(&found->block_group_kobjs[i], &btrfs_raid_ktype);
3420 }
80eb234a 3421 init_rwsem(&found->groups_sem);
0f9dd46c 3422 spin_lock_init(&found->lock);
52ba6929 3423 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
593060d7 3424 found->total_bytes = total_bytes;
89a55897 3425 found->disk_total = total_bytes * factor;
593060d7 3426 found->bytes_used = bytes_used;
b742bb82 3427 found->disk_used = bytes_used * factor;
593060d7 3428 found->bytes_pinned = 0;
e8569813 3429 found->bytes_reserved = 0;
c146afad 3430 found->bytes_readonly = 0;
f0486c68 3431 found->bytes_may_use = 0;
593060d7 3432 found->full = 0;
0e4f8f88 3433 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
6d74119f 3434 found->chunk_alloc = 0;
fdb5effd
JB
3435 found->flush = 0;
3436 init_waitqueue_head(&found->wait);
6ab0a202
JM
3437
3438 ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
3439 info->space_info_kobj, "%s",
3440 alloc_name(found->flags));
3441 if (ret) {
3442 kfree(found);
3443 return ret;
3444 }
3445
593060d7 3446 *space_info = found;
4184ea7f 3447 list_add_rcu(&found->list, &info->space_info);
b4d7c3c9
LZ
3448 if (flags & BTRFS_BLOCK_GROUP_DATA)
3449 info->data_sinfo = found;
6ab0a202
JM
3450
3451 return ret;
593060d7
CM
3452}
3453
8790d502
CM
3454static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3455{
899c81ea
ID
3456 u64 extra_flags = chunk_to_extended(flags) &
3457 BTRFS_EXTENDED_PROFILE_MASK;
a46d11a8 3458
de98ced9 3459 write_seqlock(&fs_info->profiles_lock);
a46d11a8
ID
3460 if (flags & BTRFS_BLOCK_GROUP_DATA)
3461 fs_info->avail_data_alloc_bits |= extra_flags;
3462 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3463 fs_info->avail_metadata_alloc_bits |= extra_flags;
3464 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3465 fs_info->avail_system_alloc_bits |= extra_flags;
de98ced9 3466 write_sequnlock(&fs_info->profiles_lock);
8790d502 3467}
593060d7 3468
fc67c450
ID
3469/*
3470 * returns target flags in extended format or 0 if restripe for this
3471 * chunk_type is not in progress
c6664b42
ID
3472 *
3473 * should be called with either volume_mutex or balance_lock held
fc67c450
ID
3474 */
3475static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3476{
3477 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3478 u64 target = 0;
3479
fc67c450
ID
3480 if (!bctl)
3481 return 0;
3482
3483 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3484 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3485 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3486 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3487 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3488 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3489 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3490 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3491 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3492 }
3493
3494 return target;
3495}
3496
a46d11a8
ID
3497/*
3498 * @flags: available profiles in extended format (see ctree.h)
3499 *
e4d8ec0f
ID
3500 * Returns reduced profile in chunk format. If profile changing is in
3501 * progress (either running or paused) picks the target profile (if it's
3502 * already available), otherwise falls back to plain reducing.
a46d11a8 3503 */
48a3b636 3504static u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
ec44a35c 3505{
cd02dca5
CM
3506 /*
3507 * we add in the count of missing devices because we want
3508 * to make sure that any RAID levels on a degraded FS
3509 * continue to be honored.
3510 */
3511 u64 num_devices = root->fs_info->fs_devices->rw_devices +
3512 root->fs_info->fs_devices->missing_devices;
fc67c450 3513 u64 target;
53b381b3 3514 u64 tmp;
a061fc8d 3515
fc67c450
ID
3516 /*
3517 * see if restripe for this chunk_type is in progress, if so
3518 * try to reduce to the target profile
3519 */
e4d8ec0f 3520 spin_lock(&root->fs_info->balance_lock);
fc67c450
ID
3521 target = get_restripe_target(root->fs_info, flags);
3522 if (target) {
3523 /* pick target profile only if it's already available */
3524 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
e4d8ec0f 3525 spin_unlock(&root->fs_info->balance_lock);
fc67c450 3526 return extended_to_chunk(target);
e4d8ec0f
ID
3527 }
3528 }
3529 spin_unlock(&root->fs_info->balance_lock);
3530
53b381b3 3531 /* First, mask out the RAID levels which aren't possible */
a061fc8d 3532 if (num_devices == 1)
53b381b3
DW
3533 flags &= ~(BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID0 |
3534 BTRFS_BLOCK_GROUP_RAID5);
3535 if (num_devices < 3)
3536 flags &= ~BTRFS_BLOCK_GROUP_RAID6;
a061fc8d
CM
3537 if (num_devices < 4)
3538 flags &= ~BTRFS_BLOCK_GROUP_RAID10;
3539
53b381b3
DW
3540 tmp = flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID0 |
3541 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID5 |
3542 BTRFS_BLOCK_GROUP_RAID6 | BTRFS_BLOCK_GROUP_RAID10);
3543 flags &= ~tmp;
ec44a35c 3544
53b381b3
DW
3545 if (tmp & BTRFS_BLOCK_GROUP_RAID6)
3546 tmp = BTRFS_BLOCK_GROUP_RAID6;
3547 else if (tmp & BTRFS_BLOCK_GROUP_RAID5)
3548 tmp = BTRFS_BLOCK_GROUP_RAID5;
3549 else if (tmp & BTRFS_BLOCK_GROUP_RAID10)
3550 tmp = BTRFS_BLOCK_GROUP_RAID10;
3551 else if (tmp & BTRFS_BLOCK_GROUP_RAID1)
3552 tmp = BTRFS_BLOCK_GROUP_RAID1;
3553 else if (tmp & BTRFS_BLOCK_GROUP_RAID0)
3554 tmp = BTRFS_BLOCK_GROUP_RAID0;
a46d11a8 3555
53b381b3 3556 return extended_to_chunk(flags | tmp);
ec44a35c
CM
3557}
3558
f8213bdc 3559static u64 get_alloc_profile(struct btrfs_root *root, u64 orig_flags)
6a63209f 3560{
de98ced9 3561 unsigned seq;
f8213bdc 3562 u64 flags;
de98ced9
MX
3563
3564 do {
f8213bdc 3565 flags = orig_flags;
de98ced9
MX
3566 seq = read_seqbegin(&root->fs_info->profiles_lock);
3567
3568 if (flags & BTRFS_BLOCK_GROUP_DATA)
3569 flags |= root->fs_info->avail_data_alloc_bits;
3570 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3571 flags |= root->fs_info->avail_system_alloc_bits;
3572 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3573 flags |= root->fs_info->avail_metadata_alloc_bits;
3574 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
6fef8df1 3575
b742bb82 3576 return btrfs_reduce_alloc_profile(root, flags);
6a63209f
JB
3577}
3578
6d07bcec 3579u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
9ed74f2d 3580{
b742bb82 3581 u64 flags;
53b381b3 3582 u64 ret;
9ed74f2d 3583
b742bb82
YZ
3584 if (data)
3585 flags = BTRFS_BLOCK_GROUP_DATA;
3586 else if (root == root->fs_info->chunk_root)
3587 flags = BTRFS_BLOCK_GROUP_SYSTEM;
9ed74f2d 3588 else
b742bb82 3589 flags = BTRFS_BLOCK_GROUP_METADATA;
9ed74f2d 3590
53b381b3
DW
3591 ret = get_alloc_profile(root, flags);
3592 return ret;
6a63209f 3593}
9ed74f2d 3594
6a63209f 3595/*
6a63209f
JB
3596 * This will check the space that the inode allocates from to make sure we have
3597 * enough space for bytes.
6a63209f 3598 */
0ca1f7ce 3599int btrfs_check_data_free_space(struct inode *inode, u64 bytes)
6a63209f 3600{
6a63209f 3601 struct btrfs_space_info *data_sinfo;
0ca1f7ce 3602 struct btrfs_root *root = BTRFS_I(inode)->root;
b4d7c3c9 3603 struct btrfs_fs_info *fs_info = root->fs_info;
ab6e2410 3604 u64 used;
0af3d00b 3605 int ret = 0, committed = 0, alloc_chunk = 1;
6a63209f 3606
6a63209f 3607 /* make sure bytes are sectorsize aligned */
fda2832f 3608 bytes = ALIGN(bytes, root->sectorsize);
6a63209f 3609
9dced186 3610 if (btrfs_is_free_space_inode(inode)) {
0af3d00b 3611 committed = 1;
9dced186 3612 ASSERT(current->journal_info);
0af3d00b
JB
3613 }
3614
b4d7c3c9 3615 data_sinfo = fs_info->data_sinfo;
33b4d47f
CM
3616 if (!data_sinfo)
3617 goto alloc;
9ed74f2d 3618
6a63209f
JB
3619again:
3620 /* make sure we have enough space to handle the data first */
3621 spin_lock(&data_sinfo->lock);
8929ecfa
YZ
3622 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
3623 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
3624 data_sinfo->bytes_may_use;
ab6e2410
JB
3625
3626 if (used + bytes > data_sinfo->total_bytes) {
4e06bdd6 3627 struct btrfs_trans_handle *trans;
9ed74f2d 3628
6a63209f
JB
3629 /*
3630 * if we don't have enough free bytes in this space then we need
3631 * to alloc a new chunk.
3632 */
0af3d00b 3633 if (!data_sinfo->full && alloc_chunk) {
6a63209f 3634 u64 alloc_target;
9ed74f2d 3635
0e4f8f88 3636 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
6a63209f 3637 spin_unlock(&data_sinfo->lock);
33b4d47f 3638alloc:
6a63209f 3639 alloc_target = btrfs_get_alloc_profile(root, 1);
9dced186
MX
3640 /*
3641 * It is ugly that we don't call nolock join
3642 * transaction for the free space inode case here.
3643 * But it is safe because we only do the data space
3644 * reservation for the free space cache in the
3645 * transaction context, the common join transaction
3646 * just increase the counter of the current transaction
3647 * handler, doesn't try to acquire the trans_lock of
3648 * the fs.
3649 */
7a7eaa40 3650 trans = btrfs_join_transaction(root);
a22285a6
YZ
3651 if (IS_ERR(trans))
3652 return PTR_ERR(trans);
9ed74f2d 3653
6a63209f 3654 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
0e4f8f88
CM
3655 alloc_target,
3656 CHUNK_ALLOC_NO_FORCE);
6a63209f 3657 btrfs_end_transaction(trans, root);
d52a5b5f
MX
3658 if (ret < 0) {
3659 if (ret != -ENOSPC)
3660 return ret;
3661 else
3662 goto commit_trans;
3663 }
9ed74f2d 3664
b4d7c3c9
LZ
3665 if (!data_sinfo)
3666 data_sinfo = fs_info->data_sinfo;
3667
6a63209f
JB
3668 goto again;
3669 }
f2bb8f5c
JB
3670
3671 /*
b150a4f1
JB
3672 * If we don't have enough pinned space to deal with this
3673 * allocation don't bother committing the transaction.
f2bb8f5c 3674 */
b150a4f1
JB
3675 if (percpu_counter_compare(&data_sinfo->total_bytes_pinned,
3676 bytes) < 0)
f2bb8f5c 3677 committed = 1;
6a63209f 3678 spin_unlock(&data_sinfo->lock);
6a63209f 3679
4e06bdd6 3680 /* commit the current transaction and try again */
d52a5b5f 3681commit_trans:
a4abeea4
JB
3682 if (!committed &&
3683 !atomic_read(&root->fs_info->open_ioctl_trans)) {
4e06bdd6 3684 committed = 1;
b150a4f1 3685
7a7eaa40 3686 trans = btrfs_join_transaction(root);
a22285a6
YZ
3687 if (IS_ERR(trans))
3688 return PTR_ERR(trans);
4e06bdd6
JB
3689 ret = btrfs_commit_transaction(trans, root);
3690 if (ret)
3691 return ret;
3692 goto again;
3693 }
9ed74f2d 3694
cab45e22
JM
3695 trace_btrfs_space_reservation(root->fs_info,
3696 "space_info:enospc",
3697 data_sinfo->flags, bytes, 1);
6a63209f
JB
3698 return -ENOSPC;
3699 }
3700 data_sinfo->bytes_may_use += bytes;
8c2a3ca2 3701 trace_btrfs_space_reservation(root->fs_info, "space_info",
2bcc0328 3702 data_sinfo->flags, bytes, 1);
6a63209f 3703 spin_unlock(&data_sinfo->lock);
6a63209f 3704
9ed74f2d 3705 return 0;
9ed74f2d 3706}
6a63209f 3707
6a63209f 3708/*
fb25e914 3709 * Called if we need to clear a data reservation for this inode.
6a63209f 3710 */
0ca1f7ce 3711void btrfs_free_reserved_data_space(struct inode *inode, u64 bytes)
e3ccfa98 3712{
0ca1f7ce 3713 struct btrfs_root *root = BTRFS_I(inode)->root;
6a63209f 3714 struct btrfs_space_info *data_sinfo;
e3ccfa98 3715
6a63209f 3716 /* make sure bytes are sectorsize aligned */
fda2832f 3717 bytes = ALIGN(bytes, root->sectorsize);
e3ccfa98 3718
b4d7c3c9 3719 data_sinfo = root->fs_info->data_sinfo;
6a63209f 3720 spin_lock(&data_sinfo->lock);
7ee9e440 3721 WARN_ON(data_sinfo->bytes_may_use < bytes);
6a63209f 3722 data_sinfo->bytes_may_use -= bytes;
8c2a3ca2 3723 trace_btrfs_space_reservation(root->fs_info, "space_info",
2bcc0328 3724 data_sinfo->flags, bytes, 0);
6a63209f 3725 spin_unlock(&data_sinfo->lock);
e3ccfa98
JB
3726}
3727
97e728d4 3728static void force_metadata_allocation(struct btrfs_fs_info *info)
e3ccfa98 3729{
97e728d4
JB
3730 struct list_head *head = &info->space_info;
3731 struct btrfs_space_info *found;
e3ccfa98 3732
97e728d4
JB
3733 rcu_read_lock();
3734 list_for_each_entry_rcu(found, head, list) {
3735 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
0e4f8f88 3736 found->force_alloc = CHUNK_ALLOC_FORCE;
e3ccfa98 3737 }
97e728d4 3738 rcu_read_unlock();
e3ccfa98
JB
3739}
3740
3c76cd84
MX
3741static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
3742{
3743 return (global->size << 1);
3744}
3745
e5bc2458 3746static int should_alloc_chunk(struct btrfs_root *root,
698d0082 3747 struct btrfs_space_info *sinfo, int force)
32c00aff 3748{
fb25e914 3749 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
424499db 3750 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
0e4f8f88 3751 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
e5bc2458 3752 u64 thresh;
e3ccfa98 3753
0e4f8f88
CM
3754 if (force == CHUNK_ALLOC_FORCE)
3755 return 1;
3756
fb25e914
JB
3757 /*
3758 * We need to take into account the global rsv because for all intents
3759 * and purposes it's used space. Don't worry about locking the
3760 * global_rsv, it doesn't change except when the transaction commits.
3761 */
54338b5c 3762 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
3c76cd84 3763 num_allocated += calc_global_rsv_need_space(global_rsv);
fb25e914 3764
0e4f8f88
CM
3765 /*
3766 * in limited mode, we want to have some free space up to
3767 * about 1% of the FS size.
3768 */
3769 if (force == CHUNK_ALLOC_LIMITED) {
6c41761f 3770 thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
0e4f8f88
CM
3771 thresh = max_t(u64, 64 * 1024 * 1024,
3772 div_factor_fine(thresh, 1));
3773
3774 if (num_bytes - num_allocated < thresh)
3775 return 1;
3776 }
0e4f8f88 3777
698d0082 3778 if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
14ed0ca6 3779 return 0;
424499db 3780 return 1;
32c00aff
JB
3781}
3782
15d1ff81
LB
3783static u64 get_system_chunk_thresh(struct btrfs_root *root, u64 type)
3784{
3785 u64 num_dev;
3786
53b381b3
DW
3787 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
3788 BTRFS_BLOCK_GROUP_RAID0 |
3789 BTRFS_BLOCK_GROUP_RAID5 |
3790 BTRFS_BLOCK_GROUP_RAID6))
15d1ff81
LB
3791 num_dev = root->fs_info->fs_devices->rw_devices;
3792 else if (type & BTRFS_BLOCK_GROUP_RAID1)
3793 num_dev = 2;
3794 else
3795 num_dev = 1; /* DUP or single */
3796
3797 /* metadata for updaing devices and chunk tree */
3798 return btrfs_calc_trans_metadata_size(root, num_dev + 1);
3799}
3800
3801static void check_system_chunk(struct btrfs_trans_handle *trans,
3802 struct btrfs_root *root, u64 type)
3803{
3804 struct btrfs_space_info *info;
3805 u64 left;
3806 u64 thresh;
3807
3808 info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
3809 spin_lock(&info->lock);
3810 left = info->total_bytes - info->bytes_used - info->bytes_pinned -
3811 info->bytes_reserved - info->bytes_readonly;
3812 spin_unlock(&info->lock);
3813
3814 thresh = get_system_chunk_thresh(root, type);
3815 if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
c2cf52eb
SK
3816 btrfs_info(root->fs_info, "left=%llu, need=%llu, flags=%llu",
3817 left, thresh, type);
15d1ff81
LB
3818 dump_space_info(info, 0, 0);
3819 }
3820
3821 if (left < thresh) {
3822 u64 flags;
3823
3824 flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
3825 btrfs_alloc_chunk(trans, root, flags);
3826 }
3827}
3828
6324fbf3 3829static int do_chunk_alloc(struct btrfs_trans_handle *trans,
698d0082 3830 struct btrfs_root *extent_root, u64 flags, int force)
9ed74f2d 3831{
6324fbf3 3832 struct btrfs_space_info *space_info;
97e728d4 3833 struct btrfs_fs_info *fs_info = extent_root->fs_info;
6d74119f 3834 int wait_for_alloc = 0;
9ed74f2d 3835 int ret = 0;
9ed74f2d 3836
c6b305a8
JB
3837 /* Don't re-enter if we're already allocating a chunk */
3838 if (trans->allocating_chunk)
3839 return -ENOSPC;
3840
6324fbf3 3841 space_info = __find_space_info(extent_root->fs_info, flags);
593060d7
CM
3842 if (!space_info) {
3843 ret = update_space_info(extent_root->fs_info, flags,
3844 0, 0, &space_info);
79787eaa 3845 BUG_ON(ret); /* -ENOMEM */
9ed74f2d 3846 }
79787eaa 3847 BUG_ON(!space_info); /* Logic error */
9ed74f2d 3848
6d74119f 3849again:
25179201 3850 spin_lock(&space_info->lock);
9e622d6b 3851 if (force < space_info->force_alloc)
0e4f8f88 3852 force = space_info->force_alloc;
25179201 3853 if (space_info->full) {
09fb99a6
FDBM
3854 if (should_alloc_chunk(extent_root, space_info, force))
3855 ret = -ENOSPC;
3856 else
3857 ret = 0;
25179201 3858 spin_unlock(&space_info->lock);
09fb99a6 3859 return ret;
9ed74f2d
JB
3860 }
3861
698d0082 3862 if (!should_alloc_chunk(extent_root, space_info, force)) {
25179201 3863 spin_unlock(&space_info->lock);
6d74119f
JB
3864 return 0;
3865 } else if (space_info->chunk_alloc) {
3866 wait_for_alloc = 1;
3867 } else {
3868 space_info->chunk_alloc = 1;
9ed74f2d 3869 }
0e4f8f88 3870
25179201 3871 spin_unlock(&space_info->lock);
9ed74f2d 3872
6d74119f
JB
3873 mutex_lock(&fs_info->chunk_mutex);
3874
3875 /*
3876 * The chunk_mutex is held throughout the entirety of a chunk
3877 * allocation, so once we've acquired the chunk_mutex we know that the
3878 * other guy is done and we need to recheck and see if we should
3879 * allocate.
3880 */
3881 if (wait_for_alloc) {
3882 mutex_unlock(&fs_info->chunk_mutex);
3883 wait_for_alloc = 0;
3884 goto again;
3885 }
3886
c6b305a8
JB
3887 trans->allocating_chunk = true;
3888
67377734
JB
3889 /*
3890 * If we have mixed data/metadata chunks we want to make sure we keep
3891 * allocating mixed chunks instead of individual chunks.
3892 */
3893 if (btrfs_mixed_space_info(space_info))
3894 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
3895
97e728d4
JB
3896 /*
3897 * if we're doing a data chunk, go ahead and make sure that
3898 * we keep a reasonable number of metadata chunks allocated in the
3899 * FS as well.
3900 */
9ed74f2d 3901 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
97e728d4
JB
3902 fs_info->data_chunk_allocations++;
3903 if (!(fs_info->data_chunk_allocations %
3904 fs_info->metadata_ratio))
3905 force_metadata_allocation(fs_info);
9ed74f2d
JB
3906 }
3907
15d1ff81
LB
3908 /*
3909 * Check if we have enough space in SYSTEM chunk because we may need
3910 * to update devices.
3911 */
3912 check_system_chunk(trans, extent_root, flags);
3913
2b82032c 3914 ret = btrfs_alloc_chunk(trans, extent_root, flags);
c6b305a8 3915 trans->allocating_chunk = false;
92b8e897 3916
9ed74f2d 3917 spin_lock(&space_info->lock);
a81cb9a2
AO
3918 if (ret < 0 && ret != -ENOSPC)
3919 goto out;
9ed74f2d 3920 if (ret)
6324fbf3 3921 space_info->full = 1;
424499db
YZ
3922 else
3923 ret = 1;
6d74119f 3924
0e4f8f88 3925 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
a81cb9a2 3926out:
6d74119f 3927 space_info->chunk_alloc = 0;
9ed74f2d 3928 spin_unlock(&space_info->lock);
a25c75d5 3929 mutex_unlock(&fs_info->chunk_mutex);
0f9dd46c 3930 return ret;
6324fbf3 3931}
9ed74f2d 3932
a80c8dcf
JB
3933static int can_overcommit(struct btrfs_root *root,
3934 struct btrfs_space_info *space_info, u64 bytes,
08e007d2 3935 enum btrfs_reserve_flush_enum flush)
a80c8dcf 3936{
96f1bb57 3937 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
a80c8dcf 3938 u64 profile = btrfs_get_alloc_profile(root, 0);
3c76cd84 3939 u64 space_size;
a80c8dcf
JB
3940 u64 avail;
3941 u64 used;
3942
3943 used = space_info->bytes_used + space_info->bytes_reserved +
96f1bb57
JB
3944 space_info->bytes_pinned + space_info->bytes_readonly;
3945
96f1bb57
JB
3946 /*
3947 * We only want to allow over committing if we have lots of actual space
3948 * free, but if we don't have enough space to handle the global reserve
3949 * space then we could end up having a real enospc problem when trying
3950 * to allocate a chunk or some other such important allocation.
3951 */
3c76cd84
MX
3952 spin_lock(&global_rsv->lock);
3953 space_size = calc_global_rsv_need_space(global_rsv);
3954 spin_unlock(&global_rsv->lock);
3955 if (used + space_size >= space_info->total_bytes)
96f1bb57
JB
3956 return 0;
3957
3958 used += space_info->bytes_may_use;
a80c8dcf
JB
3959
3960 spin_lock(&root->fs_info->free_chunk_lock);
3961 avail = root->fs_info->free_chunk_space;
3962 spin_unlock(&root->fs_info->free_chunk_lock);
3963
3964 /*
3965 * If we have dup, raid1 or raid10 then only half of the free
53b381b3
DW
3966 * space is actually useable. For raid56, the space info used
3967 * doesn't include the parity drive, so we don't have to
3968 * change the math
a80c8dcf
JB
3969 */
3970 if (profile & (BTRFS_BLOCK_GROUP_DUP |
3971 BTRFS_BLOCK_GROUP_RAID1 |
3972 BTRFS_BLOCK_GROUP_RAID10))
3973 avail >>= 1;
3974
3975 /*
561c294d
MX
3976 * If we aren't flushing all things, let us overcommit up to
3977 * 1/2th of the space. If we can flush, don't let us overcommit
3978 * too much, let it overcommit up to 1/8 of the space.
a80c8dcf 3979 */
08e007d2 3980 if (flush == BTRFS_RESERVE_FLUSH_ALL)
14575aef 3981 avail >>= 3;
a80c8dcf 3982 else
14575aef 3983 avail >>= 1;
a80c8dcf 3984
14575aef 3985 if (used + bytes < space_info->total_bytes + avail)
a80c8dcf
JB
3986 return 1;
3987 return 0;
3988}
3989
48a3b636 3990static void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
6c255e67 3991 unsigned long nr_pages, int nr_items)
da633a42
MX
3992{
3993 struct super_block *sb = root->fs_info->sb;
da633a42 3994
925a6efb
JB
3995 if (down_read_trylock(&sb->s_umount)) {
3996 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
3997 up_read(&sb->s_umount);
3998 } else {
da633a42
MX
3999 /*
4000 * We needn't worry the filesystem going from r/w to r/o though
4001 * we don't acquire ->s_umount mutex, because the filesystem
4002 * should guarantee the delalloc inodes list be empty after
4003 * the filesystem is readonly(all dirty pages are written to
4004 * the disk).
4005 */
6c255e67 4006 btrfs_start_delalloc_roots(root->fs_info, 0, nr_items);
98ad69cf 4007 if (!current->journal_info)
6c255e67 4008 btrfs_wait_ordered_roots(root->fs_info, nr_items);
da633a42
MX
4009 }
4010}
4011
18cd8ea6
MX
4012static inline int calc_reclaim_items_nr(struct btrfs_root *root, u64 to_reclaim)
4013{
4014 u64 bytes;
4015 int nr;
4016
4017 bytes = btrfs_calc_trans_metadata_size(root, 1);
4018 nr = (int)div64_u64(to_reclaim, bytes);
4019 if (!nr)
4020 nr = 1;
4021 return nr;
4022}
4023
c61a16a7
MX
4024#define EXTENT_SIZE_PER_ITEM (256 * 1024)
4025
9ed74f2d 4026/*
5da9d01b 4027 * shrink metadata reservation for delalloc
9ed74f2d 4028 */
f4c738c2
JB
4029static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
4030 bool wait_ordered)
5da9d01b 4031{
0ca1f7ce 4032 struct btrfs_block_rsv *block_rsv;
0019f10d 4033 struct btrfs_space_info *space_info;
663350ac 4034 struct btrfs_trans_handle *trans;
f4c738c2 4035 u64 delalloc_bytes;
5da9d01b 4036 u64 max_reclaim;
b1953bce 4037 long time_left;
d3ee29e3
MX
4038 unsigned long nr_pages;
4039 int loops;
b0244199 4040 int items;
08e007d2 4041 enum btrfs_reserve_flush_enum flush;
5da9d01b 4042
c61a16a7 4043 /* Calc the number of the pages we need flush for space reservation */
b0244199
MX
4044 items = calc_reclaim_items_nr(root, to_reclaim);
4045 to_reclaim = items * EXTENT_SIZE_PER_ITEM;
c61a16a7 4046
663350ac 4047 trans = (struct btrfs_trans_handle *)current->journal_info;
0ca1f7ce 4048 block_rsv = &root->fs_info->delalloc_block_rsv;
0019f10d 4049 space_info = block_rsv->space_info;
bf9022e0 4050
963d678b
MX
4051 delalloc_bytes = percpu_counter_sum_positive(
4052 &root->fs_info->delalloc_bytes);
f4c738c2 4053 if (delalloc_bytes == 0) {
fdb5effd 4054 if (trans)
f4c738c2 4055 return;
38c135af 4056 if (wait_ordered)
b0244199 4057 btrfs_wait_ordered_roots(root->fs_info, items);
f4c738c2 4058 return;
fdb5effd
JB
4059 }
4060
d3ee29e3 4061 loops = 0;
f4c738c2
JB
4062 while (delalloc_bytes && loops < 3) {
4063 max_reclaim = min(delalloc_bytes, to_reclaim);
4064 nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
6c255e67 4065 btrfs_writeback_inodes_sb_nr(root, nr_pages, items);
dea31f52
JB
4066 /*
4067 * We need to wait for the async pages to actually start before
4068 * we do anything.
4069 */
9f3a074d
MX
4070 max_reclaim = atomic_read(&root->fs_info->async_delalloc_pages);
4071 if (!max_reclaim)
4072 goto skip_async;
4073
4074 if (max_reclaim <= nr_pages)
4075 max_reclaim = 0;
4076 else
4077 max_reclaim -= nr_pages;
dea31f52 4078
9f3a074d
MX
4079 wait_event(root->fs_info->async_submit_wait,
4080 atomic_read(&root->fs_info->async_delalloc_pages) <=
4081 (int)max_reclaim);
4082skip_async:
08e007d2
MX
4083 if (!trans)
4084 flush = BTRFS_RESERVE_FLUSH_ALL;
4085 else
4086 flush = BTRFS_RESERVE_NO_FLUSH;
0019f10d 4087 spin_lock(&space_info->lock);
08e007d2 4088 if (can_overcommit(root, space_info, orig, flush)) {
f4c738c2
JB
4089 spin_unlock(&space_info->lock);
4090 break;
4091 }
0019f10d 4092 spin_unlock(&space_info->lock);
5da9d01b 4093
36e39c40 4094 loops++;
f104d044 4095 if (wait_ordered && !trans) {
b0244199 4096 btrfs_wait_ordered_roots(root->fs_info, items);
f104d044 4097 } else {
f4c738c2 4098 time_left = schedule_timeout_killable(1);
f104d044
JB
4099 if (time_left)
4100 break;
4101 }
963d678b
MX
4102 delalloc_bytes = percpu_counter_sum_positive(
4103 &root->fs_info->delalloc_bytes);
5da9d01b 4104 }
5da9d01b
YZ
4105}
4106
663350ac
JB
4107/**
4108 * maybe_commit_transaction - possibly commit the transaction if its ok to
4109 * @root - the root we're allocating for
4110 * @bytes - the number of bytes we want to reserve
4111 * @force - force the commit
8bb8ab2e 4112 *
663350ac
JB
4113 * This will check to make sure that committing the transaction will actually
4114 * get us somewhere and then commit the transaction if it does. Otherwise it
4115 * will return -ENOSPC.
8bb8ab2e 4116 */
663350ac
JB
4117static int may_commit_transaction(struct btrfs_root *root,
4118 struct btrfs_space_info *space_info,
4119 u64 bytes, int force)
4120{
4121 struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
4122 struct btrfs_trans_handle *trans;
4123
4124 trans = (struct btrfs_trans_handle *)current->journal_info;
4125 if (trans)
4126 return -EAGAIN;
4127
4128 if (force)
4129 goto commit;
4130
4131 /* See if there is enough pinned space to make this reservation */
b150a4f1 4132 if (percpu_counter_compare(&space_info->total_bytes_pinned,
0424c548 4133 bytes) >= 0)
663350ac 4134 goto commit;
663350ac
JB
4135
4136 /*
4137 * See if there is some space in the delayed insertion reservation for
4138 * this reservation.
4139 */
4140 if (space_info != delayed_rsv->space_info)
4141 return -ENOSPC;
4142
4143 spin_lock(&delayed_rsv->lock);
b150a4f1
JB
4144 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4145 bytes - delayed_rsv->size) >= 0) {
663350ac
JB
4146 spin_unlock(&delayed_rsv->lock);
4147 return -ENOSPC;
4148 }
4149 spin_unlock(&delayed_rsv->lock);
4150
4151commit:
4152 trans = btrfs_join_transaction(root);
4153 if (IS_ERR(trans))
4154 return -ENOSPC;
4155
4156 return btrfs_commit_transaction(trans, root);
4157}
4158
96c3f433 4159enum flush_state {
67b0fd63
JB
4160 FLUSH_DELAYED_ITEMS_NR = 1,
4161 FLUSH_DELAYED_ITEMS = 2,
4162 FLUSH_DELALLOC = 3,
4163 FLUSH_DELALLOC_WAIT = 4,
ea658bad
JB
4164 ALLOC_CHUNK = 5,
4165 COMMIT_TRANS = 6,
96c3f433
JB
4166};
4167
4168static int flush_space(struct btrfs_root *root,
4169 struct btrfs_space_info *space_info, u64 num_bytes,
4170 u64 orig_bytes, int state)
4171{
4172 struct btrfs_trans_handle *trans;
4173 int nr;
f4c738c2 4174 int ret = 0;
96c3f433
JB
4175
4176 switch (state) {
96c3f433
JB
4177 case FLUSH_DELAYED_ITEMS_NR:
4178 case FLUSH_DELAYED_ITEMS:
18cd8ea6
MX
4179 if (state == FLUSH_DELAYED_ITEMS_NR)
4180 nr = calc_reclaim_items_nr(root, num_bytes) * 2;
4181 else
96c3f433 4182 nr = -1;
18cd8ea6 4183
96c3f433
JB
4184 trans = btrfs_join_transaction(root);
4185 if (IS_ERR(trans)) {
4186 ret = PTR_ERR(trans);
4187 break;
4188 }
4189 ret = btrfs_run_delayed_items_nr(trans, root, nr);
4190 btrfs_end_transaction(trans, root);
4191 break;
67b0fd63
JB
4192 case FLUSH_DELALLOC:
4193 case FLUSH_DELALLOC_WAIT:
24af7dd1 4194 shrink_delalloc(root, num_bytes * 2, orig_bytes,
67b0fd63
JB
4195 state == FLUSH_DELALLOC_WAIT);
4196 break;
ea658bad
JB
4197 case ALLOC_CHUNK:
4198 trans = btrfs_join_transaction(root);
4199 if (IS_ERR(trans)) {
4200 ret = PTR_ERR(trans);
4201 break;
4202 }
4203 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
ea658bad
JB
4204 btrfs_get_alloc_profile(root, 0),
4205 CHUNK_ALLOC_NO_FORCE);
4206 btrfs_end_transaction(trans, root);
4207 if (ret == -ENOSPC)
4208 ret = 0;
4209 break;
96c3f433
JB
4210 case COMMIT_TRANS:
4211 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4212 break;
4213 default:
4214 ret = -ENOSPC;
4215 break;
4216 }
4217
4218 return ret;
4219}
21c7e756
MX
4220
4221static inline u64
4222btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
4223 struct btrfs_space_info *space_info)
4224{
4225 u64 used;
4226 u64 expected;
4227 u64 to_reclaim;
4228
4229 to_reclaim = min_t(u64, num_online_cpus() * 1024 * 1024,
4230 16 * 1024 * 1024);
4231 spin_lock(&space_info->lock);
4232 if (can_overcommit(root, space_info, to_reclaim,
4233 BTRFS_RESERVE_FLUSH_ALL)) {
4234 to_reclaim = 0;
4235 goto out;
4236 }
4237
4238 used = space_info->bytes_used + space_info->bytes_reserved +
4239 space_info->bytes_pinned + space_info->bytes_readonly +
4240 space_info->bytes_may_use;
4241 if (can_overcommit(root, space_info, 1024 * 1024,
4242 BTRFS_RESERVE_FLUSH_ALL))
4243 expected = div_factor_fine(space_info->total_bytes, 95);
4244 else
4245 expected = div_factor_fine(space_info->total_bytes, 90);
4246
4247 if (used > expected)
4248 to_reclaim = used - expected;
4249 else
4250 to_reclaim = 0;
4251 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4252 space_info->bytes_reserved);
4253out:
4254 spin_unlock(&space_info->lock);
4255
4256 return to_reclaim;
4257}
4258
4259static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
4260 struct btrfs_fs_info *fs_info, u64 used)
4261{
4262 return (used >= div_factor_fine(space_info->total_bytes, 98) &&
4263 !btrfs_fs_closing(fs_info) &&
4264 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4265}
4266
4267static int btrfs_need_do_async_reclaim(struct btrfs_space_info *space_info,
4268 struct btrfs_fs_info *fs_info)
4269{
4270 u64 used;
4271
4272 spin_lock(&space_info->lock);
4273 used = space_info->bytes_used + space_info->bytes_reserved +
4274 space_info->bytes_pinned + space_info->bytes_readonly +
4275 space_info->bytes_may_use;
4276 if (need_do_async_reclaim(space_info, fs_info, used)) {
4277 spin_unlock(&space_info->lock);
4278 return 1;
4279 }
4280 spin_unlock(&space_info->lock);
4281
4282 return 0;
4283}
4284
4285static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4286{
4287 struct btrfs_fs_info *fs_info;
4288 struct btrfs_space_info *space_info;
4289 u64 to_reclaim;
4290 int flush_state;
4291
4292 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4293 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4294
4295 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
4296 space_info);
4297 if (!to_reclaim)
4298 return;
4299
4300 flush_state = FLUSH_DELAYED_ITEMS_NR;
4301 do {
4302 flush_space(fs_info->fs_root, space_info, to_reclaim,
4303 to_reclaim, flush_state);
4304 flush_state++;
4305 if (!btrfs_need_do_async_reclaim(space_info, fs_info))
4306 return;
4307 } while (flush_state <= COMMIT_TRANS);
4308
4309 if (btrfs_need_do_async_reclaim(space_info, fs_info))
4310 queue_work(system_unbound_wq, work);
4311}
4312
4313void btrfs_init_async_reclaim_work(struct work_struct *work)
4314{
4315 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
4316}
4317
4a92b1b8
JB
4318/**
4319 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
4320 * @root - the root we're allocating for
4321 * @block_rsv - the block_rsv we're allocating for
4322 * @orig_bytes - the number of bytes we want
48fc7f7e 4323 * @flush - whether or not we can flush to make our reservation
8bb8ab2e 4324 *
4a92b1b8
JB
4325 * This will reserve orgi_bytes number of bytes from the space info associated
4326 * with the block_rsv. If there is not enough space it will make an attempt to
4327 * flush out space to make room. It will do this by flushing delalloc if
4328 * possible or committing the transaction. If flush is 0 then no attempts to
4329 * regain reservations will be made and this will fail if there is not enough
4330 * space already.
8bb8ab2e 4331 */
4a92b1b8 4332static int reserve_metadata_bytes(struct btrfs_root *root,
8bb8ab2e 4333 struct btrfs_block_rsv *block_rsv,
08e007d2
MX
4334 u64 orig_bytes,
4335 enum btrfs_reserve_flush_enum flush)
9ed74f2d 4336{
f0486c68 4337 struct btrfs_space_info *space_info = block_rsv->space_info;
2bf64758 4338 u64 used;
8bb8ab2e 4339 u64 num_bytes = orig_bytes;
67b0fd63 4340 int flush_state = FLUSH_DELAYED_ITEMS_NR;
8bb8ab2e 4341 int ret = 0;
fdb5effd 4342 bool flushing = false;
9ed74f2d 4343
8bb8ab2e 4344again:
fdb5effd 4345 ret = 0;
8bb8ab2e 4346 spin_lock(&space_info->lock);
fdb5effd 4347 /*
08e007d2
MX
4348 * We only want to wait if somebody other than us is flushing and we
4349 * are actually allowed to flush all things.
fdb5effd 4350 */
08e007d2
MX
4351 while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
4352 space_info->flush) {
fdb5effd
JB
4353 spin_unlock(&space_info->lock);
4354 /*
4355 * If we have a trans handle we can't wait because the flusher
4356 * may have to commit the transaction, which would mean we would
4357 * deadlock since we are waiting for the flusher to finish, but
4358 * hold the current transaction open.
4359 */
663350ac 4360 if (current->journal_info)
fdb5effd 4361 return -EAGAIN;
b9688bb8
AJ
4362 ret = wait_event_killable(space_info->wait, !space_info->flush);
4363 /* Must have been killed, return */
4364 if (ret)
fdb5effd
JB
4365 return -EINTR;
4366
4367 spin_lock(&space_info->lock);
4368 }
4369
4370 ret = -ENOSPC;
2bf64758
JB
4371 used = space_info->bytes_used + space_info->bytes_reserved +
4372 space_info->bytes_pinned + space_info->bytes_readonly +
4373 space_info->bytes_may_use;
9ed74f2d 4374
8bb8ab2e
JB
4375 /*
4376 * The idea here is that we've not already over-reserved the block group
4377 * then we can go ahead and save our reservation first and then start
4378 * flushing if we need to. Otherwise if we've already overcommitted
4379 * lets start flushing stuff first and then come back and try to make
4380 * our reservation.
4381 */
2bf64758
JB
4382 if (used <= space_info->total_bytes) {
4383 if (used + orig_bytes <= space_info->total_bytes) {
fb25e914 4384 space_info->bytes_may_use += orig_bytes;
8c2a3ca2 4385 trace_btrfs_space_reservation(root->fs_info,
2bcc0328 4386 "space_info", space_info->flags, orig_bytes, 1);
8bb8ab2e
JB
4387 ret = 0;
4388 } else {
4389 /*
4390 * Ok set num_bytes to orig_bytes since we aren't
4391 * overocmmitted, this way we only try and reclaim what
4392 * we need.
4393 */
4394 num_bytes = orig_bytes;
4395 }
4396 } else {
4397 /*
4398 * Ok we're over committed, set num_bytes to the overcommitted
4399 * amount plus the amount of bytes that we need for this
4400 * reservation.
4401 */
2bf64758 4402 num_bytes = used - space_info->total_bytes +
96c3f433 4403 (orig_bytes * 2);
8bb8ab2e 4404 }
9ed74f2d 4405
44734ed1
JB
4406 if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
4407 space_info->bytes_may_use += orig_bytes;
4408 trace_btrfs_space_reservation(root->fs_info, "space_info",
4409 space_info->flags, orig_bytes,
4410 1);
4411 ret = 0;
2bf64758
JB
4412 }
4413
8bb8ab2e
JB
4414 /*
4415 * Couldn't make our reservation, save our place so while we're trying
4416 * to reclaim space we can actually use it instead of somebody else
4417 * stealing it from us.
08e007d2
MX
4418 *
4419 * We make the other tasks wait for the flush only when we can flush
4420 * all things.
8bb8ab2e 4421 */
72bcd99d 4422 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
fdb5effd
JB
4423 flushing = true;
4424 space_info->flush = 1;
21c7e756
MX
4425 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
4426 used += orig_bytes;
4427 if (need_do_async_reclaim(space_info, root->fs_info, used) &&
4428 !work_busy(&root->fs_info->async_reclaim_work))
4429 queue_work(system_unbound_wq,
4430 &root->fs_info->async_reclaim_work);
8bb8ab2e 4431 }
f0486c68 4432 spin_unlock(&space_info->lock);
9ed74f2d 4433
08e007d2 4434 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
8bb8ab2e 4435 goto out;
f0486c68 4436
96c3f433
JB
4437 ret = flush_space(root, space_info, num_bytes, orig_bytes,
4438 flush_state);
4439 flush_state++;
08e007d2
MX
4440
4441 /*
4442 * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
4443 * would happen. So skip delalloc flush.
4444 */
4445 if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4446 (flush_state == FLUSH_DELALLOC ||
4447 flush_state == FLUSH_DELALLOC_WAIT))
4448 flush_state = ALLOC_CHUNK;
4449
96c3f433 4450 if (!ret)
8bb8ab2e 4451 goto again;
08e007d2
MX
4452 else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4453 flush_state < COMMIT_TRANS)
4454 goto again;
4455 else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
4456 flush_state <= COMMIT_TRANS)
8bb8ab2e
JB
4457 goto again;
4458
4459out:
5d80366e
JB
4460 if (ret == -ENOSPC &&
4461 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
4462 struct btrfs_block_rsv *global_rsv =
4463 &root->fs_info->global_block_rsv;
4464
4465 if (block_rsv != global_rsv &&
4466 !block_rsv_use_bytes(global_rsv, orig_bytes))
4467 ret = 0;
4468 }
cab45e22
JM
4469 if (ret == -ENOSPC)
4470 trace_btrfs_space_reservation(root->fs_info,
4471 "space_info:enospc",
4472 space_info->flags, orig_bytes, 1);
fdb5effd 4473 if (flushing) {
8bb8ab2e 4474 spin_lock(&space_info->lock);
fdb5effd
JB
4475 space_info->flush = 0;
4476 wake_up_all(&space_info->wait);
8bb8ab2e 4477 spin_unlock(&space_info->lock);
f0486c68 4478 }
f0486c68
YZ
4479 return ret;
4480}
4481
79787eaa
JM
4482static struct btrfs_block_rsv *get_block_rsv(
4483 const struct btrfs_trans_handle *trans,
4484 const struct btrfs_root *root)
f0486c68 4485{
4c13d758
JB
4486 struct btrfs_block_rsv *block_rsv = NULL;
4487
27cdeb70 4488 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state))
0e721106
JB
4489 block_rsv = trans->block_rsv;
4490
4491 if (root == root->fs_info->csum_root && trans->adding_csums)
f0486c68 4492 block_rsv = trans->block_rsv;
4c13d758 4493
f7a81ea4
SB
4494 if (root == root->fs_info->uuid_root)
4495 block_rsv = trans->block_rsv;
4496
4c13d758 4497 if (!block_rsv)
f0486c68
YZ
4498 block_rsv = root->block_rsv;
4499
4500 if (!block_rsv)
4501 block_rsv = &root->fs_info->empty_block_rsv;
4502
4503 return block_rsv;
4504}
4505
4506static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
4507 u64 num_bytes)
4508{
4509 int ret = -ENOSPC;
4510 spin_lock(&block_rsv->lock);
4511 if (block_rsv->reserved >= num_bytes) {
4512 block_rsv->reserved -= num_bytes;
4513 if (block_rsv->reserved < block_rsv->size)
4514 block_rsv->full = 0;
4515 ret = 0;
4516 }
4517 spin_unlock(&block_rsv->lock);
4518 return ret;
4519}
4520
4521static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
4522 u64 num_bytes, int update_size)
4523{
4524 spin_lock(&block_rsv->lock);
4525 block_rsv->reserved += num_bytes;
4526 if (update_size)
4527 block_rsv->size += num_bytes;
4528 else if (block_rsv->reserved >= block_rsv->size)
4529 block_rsv->full = 1;
4530 spin_unlock(&block_rsv->lock);
4531}
4532
d52be818
JB
4533int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
4534 struct btrfs_block_rsv *dest, u64 num_bytes,
4535 int min_factor)
4536{
4537 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
4538 u64 min_bytes;
4539
4540 if (global_rsv->space_info != dest->space_info)
4541 return -ENOSPC;
4542
4543 spin_lock(&global_rsv->lock);
4544 min_bytes = div_factor(global_rsv->size, min_factor);
4545 if (global_rsv->reserved < min_bytes + num_bytes) {
4546 spin_unlock(&global_rsv->lock);
4547 return -ENOSPC;
4548 }
4549 global_rsv->reserved -= num_bytes;
4550 if (global_rsv->reserved < global_rsv->size)
4551 global_rsv->full = 0;
4552 spin_unlock(&global_rsv->lock);
4553
4554 block_rsv_add_bytes(dest, num_bytes, 1);
4555 return 0;
4556}
4557
8c2a3ca2
JB
4558static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
4559 struct btrfs_block_rsv *block_rsv,
62a45b60 4560 struct btrfs_block_rsv *dest, u64 num_bytes)
f0486c68
YZ
4561{
4562 struct btrfs_space_info *space_info = block_rsv->space_info;
4563
4564 spin_lock(&block_rsv->lock);
4565 if (num_bytes == (u64)-1)
4566 num_bytes = block_rsv->size;
4567 block_rsv->size -= num_bytes;
4568 if (block_rsv->reserved >= block_rsv->size) {
4569 num_bytes = block_rsv->reserved - block_rsv->size;
4570 block_rsv->reserved = block_rsv->size;
4571 block_rsv->full = 1;
4572 } else {
4573 num_bytes = 0;
4574 }
4575 spin_unlock(&block_rsv->lock);
4576
4577 if (num_bytes > 0) {
4578 if (dest) {
e9e22899
JB
4579 spin_lock(&dest->lock);
4580 if (!dest->full) {
4581 u64 bytes_to_add;
4582
4583 bytes_to_add = dest->size - dest->reserved;
4584 bytes_to_add = min(num_bytes, bytes_to_add);
4585 dest->reserved += bytes_to_add;
4586 if (dest->reserved >= dest->size)
4587 dest->full = 1;
4588 num_bytes -= bytes_to_add;
4589 }
4590 spin_unlock(&dest->lock);
4591 }
4592 if (num_bytes) {
f0486c68 4593 spin_lock(&space_info->lock);
fb25e914 4594 space_info->bytes_may_use -= num_bytes;
8c2a3ca2 4595 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 4596 space_info->flags, num_bytes, 0);
f0486c68 4597 spin_unlock(&space_info->lock);
4e06bdd6 4598 }
9ed74f2d 4599 }
f0486c68 4600}
4e06bdd6 4601
f0486c68
YZ
4602static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
4603 struct btrfs_block_rsv *dst, u64 num_bytes)
4604{
4605 int ret;
9ed74f2d 4606
f0486c68
YZ
4607 ret = block_rsv_use_bytes(src, num_bytes);
4608 if (ret)
4609 return ret;
9ed74f2d 4610
f0486c68 4611 block_rsv_add_bytes(dst, num_bytes, 1);
9ed74f2d
JB
4612 return 0;
4613}
4614
66d8f3dd 4615void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
9ed74f2d 4616{
f0486c68
YZ
4617 memset(rsv, 0, sizeof(*rsv));
4618 spin_lock_init(&rsv->lock);
66d8f3dd 4619 rsv->type = type;
f0486c68
YZ
4620}
4621
66d8f3dd
MX
4622struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
4623 unsigned short type)
f0486c68
YZ
4624{
4625 struct btrfs_block_rsv *block_rsv;
4626 struct btrfs_fs_info *fs_info = root->fs_info;
9ed74f2d 4627
f0486c68
YZ
4628 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
4629 if (!block_rsv)
4630 return NULL;
9ed74f2d 4631
66d8f3dd 4632 btrfs_init_block_rsv(block_rsv, type);
f0486c68
YZ
4633 block_rsv->space_info = __find_space_info(fs_info,
4634 BTRFS_BLOCK_GROUP_METADATA);
f0486c68
YZ
4635 return block_rsv;
4636}
9ed74f2d 4637
f0486c68
YZ
4638void btrfs_free_block_rsv(struct btrfs_root *root,
4639 struct btrfs_block_rsv *rsv)
4640{
2aaa6655
JB
4641 if (!rsv)
4642 return;
dabdb640
JB
4643 btrfs_block_rsv_release(root, rsv, (u64)-1);
4644 kfree(rsv);
9ed74f2d
JB
4645}
4646
08e007d2
MX
4647int btrfs_block_rsv_add(struct btrfs_root *root,
4648 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
4649 enum btrfs_reserve_flush_enum flush)
9ed74f2d 4650{
f0486c68 4651 int ret;
9ed74f2d 4652
f0486c68
YZ
4653 if (num_bytes == 0)
4654 return 0;
8bb8ab2e 4655
61b520a9 4656 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
f0486c68
YZ
4657 if (!ret) {
4658 block_rsv_add_bytes(block_rsv, num_bytes, 1);
4659 return 0;
4660 }
9ed74f2d 4661
f0486c68 4662 return ret;
f0486c68 4663}
9ed74f2d 4664
4a92b1b8 4665int btrfs_block_rsv_check(struct btrfs_root *root,
36ba022a 4666 struct btrfs_block_rsv *block_rsv, int min_factor)
f0486c68
YZ
4667{
4668 u64 num_bytes = 0;
f0486c68 4669 int ret = -ENOSPC;
9ed74f2d 4670
f0486c68
YZ
4671 if (!block_rsv)
4672 return 0;
9ed74f2d 4673
f0486c68 4674 spin_lock(&block_rsv->lock);
36ba022a
JB
4675 num_bytes = div_factor(block_rsv->size, min_factor);
4676 if (block_rsv->reserved >= num_bytes)
4677 ret = 0;
4678 spin_unlock(&block_rsv->lock);
9ed74f2d 4679
36ba022a
JB
4680 return ret;
4681}
4682
08e007d2
MX
4683int btrfs_block_rsv_refill(struct btrfs_root *root,
4684 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
4685 enum btrfs_reserve_flush_enum flush)
36ba022a
JB
4686{
4687 u64 num_bytes = 0;
4688 int ret = -ENOSPC;
4689
4690 if (!block_rsv)
4691 return 0;
4692
4693 spin_lock(&block_rsv->lock);
4694 num_bytes = min_reserved;
13553e52 4695 if (block_rsv->reserved >= num_bytes)
f0486c68 4696 ret = 0;
13553e52 4697 else
f0486c68 4698 num_bytes -= block_rsv->reserved;
f0486c68 4699 spin_unlock(&block_rsv->lock);
13553e52 4700
f0486c68
YZ
4701 if (!ret)
4702 return 0;
4703
aa38a711 4704 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
dabdb640
JB
4705 if (!ret) {
4706 block_rsv_add_bytes(block_rsv, num_bytes, 0);
f0486c68 4707 return 0;
6a63209f 4708 }
9ed74f2d 4709
13553e52 4710 return ret;
f0486c68
YZ
4711}
4712
4713int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
4714 struct btrfs_block_rsv *dst_rsv,
4715 u64 num_bytes)
4716{
4717 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
4718}
4719
4720void btrfs_block_rsv_release(struct btrfs_root *root,
4721 struct btrfs_block_rsv *block_rsv,
4722 u64 num_bytes)
4723{
4724 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
17504584 4725 if (global_rsv == block_rsv ||
f0486c68
YZ
4726 block_rsv->space_info != global_rsv->space_info)
4727 global_rsv = NULL;
8c2a3ca2
JB
4728 block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
4729 num_bytes);
6a63209f
JB
4730}
4731
4732/*
8929ecfa
YZ
4733 * helper to calculate size of global block reservation.
4734 * the desired value is sum of space used by extent tree,
4735 * checksum tree and root tree
6a63209f 4736 */
8929ecfa 4737static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
6a63209f 4738{
8929ecfa
YZ
4739 struct btrfs_space_info *sinfo;
4740 u64 num_bytes;
4741 u64 meta_used;
4742 u64 data_used;
6c41761f 4743 int csum_size = btrfs_super_csum_size(fs_info->super_copy);
6a63209f 4744
8929ecfa
YZ
4745 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
4746 spin_lock(&sinfo->lock);
4747 data_used = sinfo->bytes_used;
4748 spin_unlock(&sinfo->lock);
33b4d47f 4749
8929ecfa
YZ
4750 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4751 spin_lock(&sinfo->lock);
6d48755d
JB
4752 if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
4753 data_used = 0;
8929ecfa
YZ
4754 meta_used = sinfo->bytes_used;
4755 spin_unlock(&sinfo->lock);
ab6e2410 4756
8929ecfa
YZ
4757 num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
4758 csum_size * 2;
4759 num_bytes += div64_u64(data_used + meta_used, 50);
4e06bdd6 4760
8929ecfa 4761 if (num_bytes * 3 > meta_used)
8e62c2de 4762 num_bytes = div64_u64(meta_used, 3);
ab6e2410 4763
8929ecfa
YZ
4764 return ALIGN(num_bytes, fs_info->extent_root->leafsize << 10);
4765}
6a63209f 4766
8929ecfa
YZ
4767static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
4768{
4769 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
4770 struct btrfs_space_info *sinfo = block_rsv->space_info;
4771 u64 num_bytes;
6a63209f 4772
8929ecfa 4773 num_bytes = calc_global_metadata_size(fs_info);
33b4d47f 4774
8929ecfa 4775 spin_lock(&sinfo->lock);
1f699d38 4776 spin_lock(&block_rsv->lock);
4e06bdd6 4777
fdf30d1c 4778 block_rsv->size = min_t(u64, num_bytes, 512 * 1024 * 1024);
4e06bdd6 4779
8929ecfa 4780 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
6d48755d
JB
4781 sinfo->bytes_reserved + sinfo->bytes_readonly +
4782 sinfo->bytes_may_use;
8929ecfa
YZ
4783
4784 if (sinfo->total_bytes > num_bytes) {
4785 num_bytes = sinfo->total_bytes - num_bytes;
4786 block_rsv->reserved += num_bytes;
fb25e914 4787 sinfo->bytes_may_use += num_bytes;
8c2a3ca2 4788 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 4789 sinfo->flags, num_bytes, 1);
6a63209f 4790 }
6a63209f 4791
8929ecfa
YZ
4792 if (block_rsv->reserved >= block_rsv->size) {
4793 num_bytes = block_rsv->reserved - block_rsv->size;
fb25e914 4794 sinfo->bytes_may_use -= num_bytes;
8c2a3ca2 4795 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 4796 sinfo->flags, num_bytes, 0);
8929ecfa
YZ
4797 block_rsv->reserved = block_rsv->size;
4798 block_rsv->full = 1;
4799 }
182608c8 4800
8929ecfa 4801 spin_unlock(&block_rsv->lock);
1f699d38 4802 spin_unlock(&sinfo->lock);
6a63209f
JB
4803}
4804
f0486c68 4805static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
6a63209f 4806{
f0486c68 4807 struct btrfs_space_info *space_info;
6a63209f 4808
f0486c68
YZ
4809 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4810 fs_info->chunk_block_rsv.space_info = space_info;
6a63209f 4811
f0486c68 4812 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
8929ecfa 4813 fs_info->global_block_rsv.space_info = space_info;
8929ecfa 4814 fs_info->delalloc_block_rsv.space_info = space_info;
f0486c68
YZ
4815 fs_info->trans_block_rsv.space_info = space_info;
4816 fs_info->empty_block_rsv.space_info = space_info;
6d668dda 4817 fs_info->delayed_block_rsv.space_info = space_info;
f0486c68 4818
8929ecfa
YZ
4819 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
4820 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
4821 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
4822 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
3a6cad90
SB
4823 if (fs_info->quota_root)
4824 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
f0486c68 4825 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
8929ecfa 4826
8929ecfa 4827 update_global_block_rsv(fs_info);
6a63209f
JB
4828}
4829
8929ecfa 4830static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
6a63209f 4831{
8c2a3ca2
JB
4832 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
4833 (u64)-1);
8929ecfa
YZ
4834 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
4835 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
4836 WARN_ON(fs_info->trans_block_rsv.size > 0);
4837 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
4838 WARN_ON(fs_info->chunk_block_rsv.size > 0);
4839 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
6d668dda
JB
4840 WARN_ON(fs_info->delayed_block_rsv.size > 0);
4841 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
fcb80c2a
JB
4842}
4843
a22285a6
YZ
4844void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
4845 struct btrfs_root *root)
6a63209f 4846{
0e721106
JB
4847 if (!trans->block_rsv)
4848 return;
4849
a22285a6
YZ
4850 if (!trans->bytes_reserved)
4851 return;
6a63209f 4852
e77266e4 4853 trace_btrfs_space_reservation(root->fs_info, "transaction",
2bcc0328 4854 trans->transid, trans->bytes_reserved, 0);
b24e03db 4855 btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
a22285a6
YZ
4856 trans->bytes_reserved = 0;
4857}
6a63209f 4858
79787eaa 4859/* Can only return 0 or -ENOSPC */
d68fc57b
YZ
4860int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
4861 struct inode *inode)
4862{
4863 struct btrfs_root *root = BTRFS_I(inode)->root;
4864 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
4865 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
4866
4867 /*
fcb80c2a
JB
4868 * We need to hold space in order to delete our orphan item once we've
4869 * added it, so this takes the reservation so we can release it later
4870 * when we are truly done with the orphan item.
d68fc57b 4871 */
ff5714cc 4872 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
8c2a3ca2
JB
4873 trace_btrfs_space_reservation(root->fs_info, "orphan",
4874 btrfs_ino(inode), num_bytes, 1);
d68fc57b 4875 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
6a63209f
JB
4876}
4877
d68fc57b 4878void btrfs_orphan_release_metadata(struct inode *inode)
97e728d4 4879{
d68fc57b 4880 struct btrfs_root *root = BTRFS_I(inode)->root;
ff5714cc 4881 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
8c2a3ca2
JB
4882 trace_btrfs_space_reservation(root->fs_info, "orphan",
4883 btrfs_ino(inode), num_bytes, 0);
d68fc57b
YZ
4884 btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
4885}
97e728d4 4886
d5c12070
MX
4887/*
4888 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
4889 * root: the root of the parent directory
4890 * rsv: block reservation
4891 * items: the number of items that we need do reservation
4892 * qgroup_reserved: used to return the reserved size in qgroup
4893 *
4894 * This function is used to reserve the space for snapshot/subvolume
4895 * creation and deletion. Those operations are different with the
4896 * common file/directory operations, they change two fs/file trees
4897 * and root tree, the number of items that the qgroup reserves is
4898 * different with the free space reservation. So we can not use
4899 * the space reseravtion mechanism in start_transaction().
4900 */
4901int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
4902 struct btrfs_block_rsv *rsv,
4903 int items,
ee3441b4
JM
4904 u64 *qgroup_reserved,
4905 bool use_global_rsv)
a22285a6 4906{
d5c12070
MX
4907 u64 num_bytes;
4908 int ret;
ee3441b4 4909 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
d5c12070
MX
4910
4911 if (root->fs_info->quota_enabled) {
4912 /* One for parent inode, two for dir entries */
4913 num_bytes = 3 * root->leafsize;
4914 ret = btrfs_qgroup_reserve(root, num_bytes);
4915 if (ret)
4916 return ret;
4917 } else {
4918 num_bytes = 0;
4919 }
4920
4921 *qgroup_reserved = num_bytes;
4922
4923 num_bytes = btrfs_calc_trans_metadata_size(root, items);
4924 rsv->space_info = __find_space_info(root->fs_info,
4925 BTRFS_BLOCK_GROUP_METADATA);
4926 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
4927 BTRFS_RESERVE_FLUSH_ALL);
ee3441b4
JM
4928
4929 if (ret == -ENOSPC && use_global_rsv)
4930 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes);
4931
d5c12070
MX
4932 if (ret) {
4933 if (*qgroup_reserved)
4934 btrfs_qgroup_free(root, *qgroup_reserved);
4935 }
4936
4937 return ret;
4938}
4939
4940void btrfs_subvolume_release_metadata(struct btrfs_root *root,
4941 struct btrfs_block_rsv *rsv,
4942 u64 qgroup_reserved)
4943{
4944 btrfs_block_rsv_release(root, rsv, (u64)-1);
4945 if (qgroup_reserved)
4946 btrfs_qgroup_free(root, qgroup_reserved);
97e728d4
JB
4947}
4948
7709cde3
JB
4949/**
4950 * drop_outstanding_extent - drop an outstanding extent
4951 * @inode: the inode we're dropping the extent for
4952 *
4953 * This is called when we are freeing up an outstanding extent, either called
4954 * after an error or after an extent is written. This will return the number of
4955 * reserved extents that need to be freed. This must be called with
4956 * BTRFS_I(inode)->lock held.
4957 */
9e0baf60
JB
4958static unsigned drop_outstanding_extent(struct inode *inode)
4959{
7fd2ae21 4960 unsigned drop_inode_space = 0;
9e0baf60
JB
4961 unsigned dropped_extents = 0;
4962
9e0baf60
JB
4963 BUG_ON(!BTRFS_I(inode)->outstanding_extents);
4964 BTRFS_I(inode)->outstanding_extents--;
4965
7fd2ae21 4966 if (BTRFS_I(inode)->outstanding_extents == 0 &&
72ac3c0d
JB
4967 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
4968 &BTRFS_I(inode)->runtime_flags))
7fd2ae21 4969 drop_inode_space = 1;
7fd2ae21 4970
9e0baf60
JB
4971 /*
4972 * If we have more or the same amount of outsanding extents than we have
4973 * reserved then we need to leave the reserved extents count alone.
4974 */
4975 if (BTRFS_I(inode)->outstanding_extents >=
4976 BTRFS_I(inode)->reserved_extents)
7fd2ae21 4977 return drop_inode_space;
9e0baf60
JB
4978
4979 dropped_extents = BTRFS_I(inode)->reserved_extents -
4980 BTRFS_I(inode)->outstanding_extents;
4981 BTRFS_I(inode)->reserved_extents -= dropped_extents;
7fd2ae21 4982 return dropped_extents + drop_inode_space;
9e0baf60
JB
4983}
4984
7709cde3
JB
4985/**
4986 * calc_csum_metadata_size - return the amount of metada space that must be
4987 * reserved/free'd for the given bytes.
4988 * @inode: the inode we're manipulating
4989 * @num_bytes: the number of bytes in question
4990 * @reserve: 1 if we are reserving space, 0 if we are freeing space
4991 *
4992 * This adjusts the number of csum_bytes in the inode and then returns the
4993 * correct amount of metadata that must either be reserved or freed. We
4994 * calculate how many checksums we can fit into one leaf and then divide the
4995 * number of bytes that will need to be checksumed by this value to figure out
4996 * how many checksums will be required. If we are adding bytes then the number
4997 * may go up and we will return the number of additional bytes that must be
4998 * reserved. If it is going down we will return the number of bytes that must
4999 * be freed.
5000 *
5001 * This must be called with BTRFS_I(inode)->lock held.
5002 */
5003static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
5004 int reserve)
6324fbf3 5005{
7709cde3
JB
5006 struct btrfs_root *root = BTRFS_I(inode)->root;
5007 u64 csum_size;
5008 int num_csums_per_leaf;
5009 int num_csums;
5010 int old_csums;
5011
5012 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
5013 BTRFS_I(inode)->csum_bytes == 0)
5014 return 0;
5015
5016 old_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
5017 if (reserve)
5018 BTRFS_I(inode)->csum_bytes += num_bytes;
5019 else
5020 BTRFS_I(inode)->csum_bytes -= num_bytes;
5021 csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
5022 num_csums_per_leaf = (int)div64_u64(csum_size,
5023 sizeof(struct btrfs_csum_item) +
5024 sizeof(struct btrfs_disk_key));
5025 num_csums = (int)div64_u64(BTRFS_I(inode)->csum_bytes, root->sectorsize);
5026 num_csums = num_csums + num_csums_per_leaf - 1;
5027 num_csums = num_csums / num_csums_per_leaf;
5028
5029 old_csums = old_csums + num_csums_per_leaf - 1;
5030 old_csums = old_csums / num_csums_per_leaf;
5031
5032 /* No change, no need to reserve more */
5033 if (old_csums == num_csums)
5034 return 0;
5035
5036 if (reserve)
5037 return btrfs_calc_trans_metadata_size(root,
5038 num_csums - old_csums);
5039
5040 return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
0ca1f7ce 5041}
c146afad 5042
0ca1f7ce
YZ
5043int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
5044{
5045 struct btrfs_root *root = BTRFS_I(inode)->root;
5046 struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
9e0baf60 5047 u64 to_reserve = 0;
660d3f6c 5048 u64 csum_bytes;
9e0baf60 5049 unsigned nr_extents = 0;
660d3f6c 5050 int extra_reserve = 0;
08e007d2 5051 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
eb6b88d9 5052 int ret = 0;
c64c2bd8 5053 bool delalloc_lock = true;
88e081bf
WS
5054 u64 to_free = 0;
5055 unsigned dropped;
6324fbf3 5056
c64c2bd8
JB
5057 /* If we are a free space inode we need to not flush since we will be in
5058 * the middle of a transaction commit. We also don't need the delalloc
5059 * mutex since we won't race with anybody. We need this mostly to make
5060 * lockdep shut its filthy mouth.
5061 */
5062 if (btrfs_is_free_space_inode(inode)) {
08e007d2 5063 flush = BTRFS_RESERVE_NO_FLUSH;
c64c2bd8
JB
5064 delalloc_lock = false;
5065 }
c09544e0 5066
08e007d2
MX
5067 if (flush != BTRFS_RESERVE_NO_FLUSH &&
5068 btrfs_transaction_in_commit(root->fs_info))
0ca1f7ce 5069 schedule_timeout(1);
ec44a35c 5070
c64c2bd8
JB
5071 if (delalloc_lock)
5072 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
5073
0ca1f7ce 5074 num_bytes = ALIGN(num_bytes, root->sectorsize);
8bb8ab2e 5075
9e0baf60
JB
5076 spin_lock(&BTRFS_I(inode)->lock);
5077 BTRFS_I(inode)->outstanding_extents++;
5078
5079 if (BTRFS_I(inode)->outstanding_extents >
660d3f6c 5080 BTRFS_I(inode)->reserved_extents)
9e0baf60
JB
5081 nr_extents = BTRFS_I(inode)->outstanding_extents -
5082 BTRFS_I(inode)->reserved_extents;
57a45ced 5083
7fd2ae21
JB
5084 /*
5085 * Add an item to reserve for updating the inode when we complete the
5086 * delalloc io.
5087 */
72ac3c0d
JB
5088 if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5089 &BTRFS_I(inode)->runtime_flags)) {
7fd2ae21 5090 nr_extents++;
660d3f6c 5091 extra_reserve = 1;
593060d7 5092 }
7fd2ae21
JB
5093
5094 to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
7709cde3 5095 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
660d3f6c 5096 csum_bytes = BTRFS_I(inode)->csum_bytes;
9e0baf60 5097 spin_unlock(&BTRFS_I(inode)->lock);
57a45ced 5098
88e081bf 5099 if (root->fs_info->quota_enabled) {
c5567237
AJ
5100 ret = btrfs_qgroup_reserve(root, num_bytes +
5101 nr_extents * root->leafsize);
88e081bf
WS
5102 if (ret)
5103 goto out_fail;
5104 }
c5567237 5105
88e081bf
WS
5106 ret = reserve_metadata_bytes(root, block_rsv, to_reserve, flush);
5107 if (unlikely(ret)) {
5108 if (root->fs_info->quota_enabled)
4b5829a8
MX
5109 btrfs_qgroup_free(root, num_bytes +
5110 nr_extents * root->leafsize);
88e081bf 5111 goto out_fail;
9e0baf60 5112 }
25179201 5113
660d3f6c
JB
5114 spin_lock(&BTRFS_I(inode)->lock);
5115 if (extra_reserve) {
72ac3c0d
JB
5116 set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5117 &BTRFS_I(inode)->runtime_flags);
660d3f6c
JB
5118 nr_extents--;
5119 }
5120 BTRFS_I(inode)->reserved_extents += nr_extents;
5121 spin_unlock(&BTRFS_I(inode)->lock);
c64c2bd8
JB
5122
5123 if (delalloc_lock)
5124 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
660d3f6c 5125
8c2a3ca2 5126 if (to_reserve)
67871254 5127 trace_btrfs_space_reservation(root->fs_info, "delalloc",
8c2a3ca2 5128 btrfs_ino(inode), to_reserve, 1);
0ca1f7ce
YZ
5129 block_rsv_add_bytes(block_rsv, to_reserve, 1);
5130
0ca1f7ce 5131 return 0;
88e081bf
WS
5132
5133out_fail:
5134 spin_lock(&BTRFS_I(inode)->lock);
5135 dropped = drop_outstanding_extent(inode);
5136 /*
5137 * If the inodes csum_bytes is the same as the original
5138 * csum_bytes then we know we haven't raced with any free()ers
5139 * so we can just reduce our inodes csum bytes and carry on.
88e081bf 5140 */
f4881bc7 5141 if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
88e081bf 5142 calc_csum_metadata_size(inode, num_bytes, 0);
f4881bc7
JB
5143 } else {
5144 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
5145 u64 bytes;
5146
5147 /*
5148 * This is tricky, but first we need to figure out how much we
5149 * free'd from any free-ers that occured during this
5150 * reservation, so we reset ->csum_bytes to the csum_bytes
5151 * before we dropped our lock, and then call the free for the
5152 * number of bytes that were freed while we were trying our
5153 * reservation.
5154 */
5155 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
5156 BTRFS_I(inode)->csum_bytes = csum_bytes;
5157 to_free = calc_csum_metadata_size(inode, bytes, 0);
5158
5159
5160 /*
5161 * Now we need to see how much we would have freed had we not
5162 * been making this reservation and our ->csum_bytes were not
5163 * artificially inflated.
5164 */
5165 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
5166 bytes = csum_bytes - orig_csum_bytes;
5167 bytes = calc_csum_metadata_size(inode, bytes, 0);
5168
5169 /*
5170 * Now reset ->csum_bytes to what it should be. If bytes is
5171 * more than to_free then we would have free'd more space had we
5172 * not had an artificially high ->csum_bytes, so we need to free
5173 * the remainder. If bytes is the same or less then we don't
5174 * need to do anything, the other free-ers did the correct
5175 * thing.
5176 */
5177 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
5178 if (bytes > to_free)
5179 to_free = bytes - to_free;
5180 else
5181 to_free = 0;
5182 }
88e081bf
WS
5183 spin_unlock(&BTRFS_I(inode)->lock);
5184 if (dropped)
5185 to_free += btrfs_calc_trans_metadata_size(root, dropped);
5186
5187 if (to_free) {
5188 btrfs_block_rsv_release(root, block_rsv, to_free);
5189 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5190 btrfs_ino(inode), to_free, 0);
5191 }
5192 if (delalloc_lock)
5193 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
5194 return ret;
0ca1f7ce
YZ
5195}
5196
7709cde3
JB
5197/**
5198 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
5199 * @inode: the inode to release the reservation for
5200 * @num_bytes: the number of bytes we're releasing
5201 *
5202 * This will release the metadata reservation for an inode. This can be called
5203 * once we complete IO for a given set of bytes to release their metadata
5204 * reservations.
5205 */
0ca1f7ce
YZ
5206void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
5207{
5208 struct btrfs_root *root = BTRFS_I(inode)->root;
9e0baf60
JB
5209 u64 to_free = 0;
5210 unsigned dropped;
0ca1f7ce
YZ
5211
5212 num_bytes = ALIGN(num_bytes, root->sectorsize);
7709cde3 5213 spin_lock(&BTRFS_I(inode)->lock);
9e0baf60 5214 dropped = drop_outstanding_extent(inode);
97e728d4 5215
0934856d
MX
5216 if (num_bytes)
5217 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
7709cde3 5218 spin_unlock(&BTRFS_I(inode)->lock);
9e0baf60
JB
5219 if (dropped > 0)
5220 to_free += btrfs_calc_trans_metadata_size(root, dropped);
0ca1f7ce 5221
8c2a3ca2
JB
5222 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5223 btrfs_ino(inode), to_free, 0);
c5567237
AJ
5224 if (root->fs_info->quota_enabled) {
5225 btrfs_qgroup_free(root, num_bytes +
5226 dropped * root->leafsize);
5227 }
5228
0ca1f7ce
YZ
5229 btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
5230 to_free);
5231}
5232
7709cde3
JB
5233/**
5234 * btrfs_delalloc_reserve_space - reserve data and metadata space for delalloc
5235 * @inode: inode we're writing to
5236 * @num_bytes: the number of bytes we want to allocate
5237 *
5238 * This will do the following things
5239 *
5240 * o reserve space in the data space info for num_bytes
5241 * o reserve space in the metadata space info based on number of outstanding
5242 * extents and how much csums will be needed
5243 * o add to the inodes ->delalloc_bytes
5244 * o add it to the fs_info's delalloc inodes list.
5245 *
5246 * This will return 0 for success and -ENOSPC if there is no space left.
5247 */
0ca1f7ce
YZ
5248int btrfs_delalloc_reserve_space(struct inode *inode, u64 num_bytes)
5249{
5250 int ret;
5251
5252 ret = btrfs_check_data_free_space(inode, num_bytes);
d397712b 5253 if (ret)
0ca1f7ce
YZ
5254 return ret;
5255
5256 ret = btrfs_delalloc_reserve_metadata(inode, num_bytes);
5257 if (ret) {
5258 btrfs_free_reserved_data_space(inode, num_bytes);
5259 return ret;
5260 }
5261
5262 return 0;
5263}
5264
7709cde3
JB
5265/**
5266 * btrfs_delalloc_release_space - release data and metadata space for delalloc
5267 * @inode: inode we're releasing space for
5268 * @num_bytes: the number of bytes we want to free up
5269 *
5270 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
5271 * called in the case that we don't need the metadata AND data reservations
5272 * anymore. So if there is an error or we insert an inline extent.
5273 *
5274 * This function will release the metadata space that was not used and will
5275 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
5276 * list if there are no delalloc bytes left.
5277 */
0ca1f7ce
YZ
5278void btrfs_delalloc_release_space(struct inode *inode, u64 num_bytes)
5279{
5280 btrfs_delalloc_release_metadata(inode, num_bytes);
5281 btrfs_free_reserved_data_space(inode, num_bytes);
6324fbf3
CM
5282}
5283
c53d613e 5284static int update_block_group(struct btrfs_root *root,
f0486c68 5285 u64 bytenr, u64 num_bytes, int alloc)
9078a3e1 5286{
0af3d00b 5287 struct btrfs_block_group_cache *cache = NULL;
9078a3e1 5288 struct btrfs_fs_info *info = root->fs_info;
db94535d 5289 u64 total = num_bytes;
9078a3e1 5290 u64 old_val;
db94535d 5291 u64 byte_in_group;
0af3d00b 5292 int factor;
3e1ad54f 5293
5d4f98a2 5294 /* block accounting for super block */
eb73c1b7 5295 spin_lock(&info->delalloc_root_lock);
6c41761f 5296 old_val = btrfs_super_bytes_used(info->super_copy);
5d4f98a2
YZ
5297 if (alloc)
5298 old_val += num_bytes;
5299 else
5300 old_val -= num_bytes;
6c41761f 5301 btrfs_set_super_bytes_used(info->super_copy, old_val);
eb73c1b7 5302 spin_unlock(&info->delalloc_root_lock);
5d4f98a2 5303
d397712b 5304 while (total) {
db94535d 5305 cache = btrfs_lookup_block_group(info, bytenr);
f3465ca4 5306 if (!cache)
79787eaa 5307 return -ENOENT;
b742bb82
YZ
5308 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
5309 BTRFS_BLOCK_GROUP_RAID1 |
5310 BTRFS_BLOCK_GROUP_RAID10))
5311 factor = 2;
5312 else
5313 factor = 1;
9d66e233
JB
5314 /*
5315 * If this block group has free space cache written out, we
5316 * need to make sure to load it if we are removing space. This
5317 * is because we need the unpinning stage to actually add the
5318 * space back to the block group, otherwise we will leak space.
5319 */
5320 if (!alloc && cache->cached == BTRFS_CACHE_NO)
f6373bf3 5321 cache_block_group(cache, 1);
0af3d00b 5322
db94535d
CM
5323 byte_in_group = bytenr - cache->key.objectid;
5324 WARN_ON(byte_in_group > cache->key.offset);
9078a3e1 5325
25179201 5326 spin_lock(&cache->space_info->lock);
c286ac48 5327 spin_lock(&cache->lock);
0af3d00b 5328
73bc1876 5329 if (btrfs_test_opt(root, SPACE_CACHE) &&
0af3d00b
JB
5330 cache->disk_cache_state < BTRFS_DC_CLEAR)
5331 cache->disk_cache_state = BTRFS_DC_CLEAR;
5332
0f9dd46c 5333 cache->dirty = 1;
9078a3e1 5334 old_val = btrfs_block_group_used(&cache->item);
db94535d 5335 num_bytes = min(total, cache->key.offset - byte_in_group);
cd1bc465 5336 if (alloc) {
db94535d 5337 old_val += num_bytes;
11833d66
YZ
5338 btrfs_set_block_group_used(&cache->item, old_val);
5339 cache->reserved -= num_bytes;
11833d66 5340 cache->space_info->bytes_reserved -= num_bytes;
b742bb82
YZ
5341 cache->space_info->bytes_used += num_bytes;
5342 cache->space_info->disk_used += num_bytes * factor;
c286ac48 5343 spin_unlock(&cache->lock);
25179201 5344 spin_unlock(&cache->space_info->lock);
cd1bc465 5345 } else {
db94535d 5346 old_val -= num_bytes;
c286ac48 5347 btrfs_set_block_group_used(&cache->item, old_val);
f0486c68
YZ
5348 cache->pinned += num_bytes;
5349 cache->space_info->bytes_pinned += num_bytes;
6324fbf3 5350 cache->space_info->bytes_used -= num_bytes;
b742bb82 5351 cache->space_info->disk_used -= num_bytes * factor;
c286ac48 5352 spin_unlock(&cache->lock);
25179201 5353 spin_unlock(&cache->space_info->lock);
1f3c79a2 5354
f0486c68
YZ
5355 set_extent_dirty(info->pinned_extents,
5356 bytenr, bytenr + num_bytes - 1,
5357 GFP_NOFS | __GFP_NOFAIL);
cd1bc465 5358 }
fa9c0d79 5359 btrfs_put_block_group(cache);
db94535d
CM
5360 total -= num_bytes;
5361 bytenr += num_bytes;
9078a3e1
CM
5362 }
5363 return 0;
5364}
6324fbf3 5365
a061fc8d
CM
5366static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
5367{
0f9dd46c 5368 struct btrfs_block_group_cache *cache;
d2fb3437 5369 u64 bytenr;
0f9dd46c 5370
a1897fdd
LB
5371 spin_lock(&root->fs_info->block_group_cache_lock);
5372 bytenr = root->fs_info->first_logical_byte;
5373 spin_unlock(&root->fs_info->block_group_cache_lock);
5374
5375 if (bytenr < (u64)-1)
5376 return bytenr;
5377
0f9dd46c
JB
5378 cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
5379 if (!cache)
a061fc8d 5380 return 0;
0f9dd46c 5381
d2fb3437 5382 bytenr = cache->key.objectid;
fa9c0d79 5383 btrfs_put_block_group(cache);
d2fb3437
YZ
5384
5385 return bytenr;
a061fc8d
CM
5386}
5387
f0486c68
YZ
5388static int pin_down_extent(struct btrfs_root *root,
5389 struct btrfs_block_group_cache *cache,
5390 u64 bytenr, u64 num_bytes, int reserved)
324ae4df 5391{
11833d66
YZ
5392 spin_lock(&cache->space_info->lock);
5393 spin_lock(&cache->lock);
5394 cache->pinned += num_bytes;
5395 cache->space_info->bytes_pinned += num_bytes;
5396 if (reserved) {
5397 cache->reserved -= num_bytes;
5398 cache->space_info->bytes_reserved -= num_bytes;
5399 }
5400 spin_unlock(&cache->lock);
5401 spin_unlock(&cache->space_info->lock);
68b38550 5402
f0486c68
YZ
5403 set_extent_dirty(root->fs_info->pinned_extents, bytenr,
5404 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
0be5dc67
JB
5405 if (reserved)
5406 trace_btrfs_reserved_extent_free(root, bytenr, num_bytes);
f0486c68
YZ
5407 return 0;
5408}
68b38550 5409
f0486c68
YZ
5410/*
5411 * this function must be called within transaction
5412 */
5413int btrfs_pin_extent(struct btrfs_root *root,
5414 u64 bytenr, u64 num_bytes, int reserved)
5415{
5416 struct btrfs_block_group_cache *cache;
68b38550 5417
f0486c68 5418 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
79787eaa 5419 BUG_ON(!cache); /* Logic error */
f0486c68
YZ
5420
5421 pin_down_extent(root, cache, bytenr, num_bytes, reserved);
5422
5423 btrfs_put_block_group(cache);
11833d66
YZ
5424 return 0;
5425}
5426
f0486c68 5427/*
e688b725
CM
5428 * this function must be called within transaction
5429 */
dcfac415 5430int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
e688b725
CM
5431 u64 bytenr, u64 num_bytes)
5432{
5433 struct btrfs_block_group_cache *cache;
b50c6e25 5434 int ret;
e688b725
CM
5435
5436 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
b50c6e25
JB
5437 if (!cache)
5438 return -EINVAL;
e688b725
CM
5439
5440 /*
5441 * pull in the free space cache (if any) so that our pin
5442 * removes the free space from the cache. We have load_only set
5443 * to one because the slow code to read in the free extents does check
5444 * the pinned extents.
5445 */
f6373bf3 5446 cache_block_group(cache, 1);
e688b725
CM
5447
5448 pin_down_extent(root, cache, bytenr, num_bytes, 0);
5449
5450 /* remove us from the free space cache (if we're there at all) */
b50c6e25 5451 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
e688b725 5452 btrfs_put_block_group(cache);
b50c6e25 5453 return ret;
e688b725
CM
5454}
5455
8c2a1a30
JB
5456static int __exclude_logged_extent(struct btrfs_root *root, u64 start, u64 num_bytes)
5457{
5458 int ret;
5459 struct btrfs_block_group_cache *block_group;
5460 struct btrfs_caching_control *caching_ctl;
5461
5462 block_group = btrfs_lookup_block_group(root->fs_info, start);
5463 if (!block_group)
5464 return -EINVAL;
5465
5466 cache_block_group(block_group, 0);
5467 caching_ctl = get_caching_control(block_group);
5468
5469 if (!caching_ctl) {
5470 /* Logic error */
5471 BUG_ON(!block_group_cache_done(block_group));
5472 ret = btrfs_remove_free_space(block_group, start, num_bytes);
5473 } else {
5474 mutex_lock(&caching_ctl->mutex);
5475
5476 if (start >= caching_ctl->progress) {
5477 ret = add_excluded_extent(root, start, num_bytes);
5478 } else if (start + num_bytes <= caching_ctl->progress) {
5479 ret = btrfs_remove_free_space(block_group,
5480 start, num_bytes);
5481 } else {
5482 num_bytes = caching_ctl->progress - start;
5483 ret = btrfs_remove_free_space(block_group,
5484 start, num_bytes);
5485 if (ret)
5486 goto out_lock;
5487
5488 num_bytes = (start + num_bytes) -
5489 caching_ctl->progress;
5490 start = caching_ctl->progress;
5491 ret = add_excluded_extent(root, start, num_bytes);
5492 }
5493out_lock:
5494 mutex_unlock(&caching_ctl->mutex);
5495 put_caching_control(caching_ctl);
5496 }
5497 btrfs_put_block_group(block_group);
5498 return ret;
5499}
5500
5501int btrfs_exclude_logged_extents(struct btrfs_root *log,
5502 struct extent_buffer *eb)
5503{
5504 struct btrfs_file_extent_item *item;
5505 struct btrfs_key key;
5506 int found_type;
5507 int i;
5508
5509 if (!btrfs_fs_incompat(log->fs_info, MIXED_GROUPS))
5510 return 0;
5511
5512 for (i = 0; i < btrfs_header_nritems(eb); i++) {
5513 btrfs_item_key_to_cpu(eb, &key, i);
5514 if (key.type != BTRFS_EXTENT_DATA_KEY)
5515 continue;
5516 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
5517 found_type = btrfs_file_extent_type(eb, item);
5518 if (found_type == BTRFS_FILE_EXTENT_INLINE)
5519 continue;
5520 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
5521 continue;
5522 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
5523 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
5524 __exclude_logged_extent(log, key.objectid, key.offset);
5525 }
5526
5527 return 0;
5528}
5529
fb25e914
JB
5530/**
5531 * btrfs_update_reserved_bytes - update the block_group and space info counters
5532 * @cache: The cache we are manipulating
5533 * @num_bytes: The number of bytes in question
5534 * @reserve: One of the reservation enums
5535 *
5536 * This is called by the allocator when it reserves space, or by somebody who is
5537 * freeing space that was never actually used on disk. For example if you
5538 * reserve some space for a new leaf in transaction A and before transaction A
5539 * commits you free that leaf, you call this with reserve set to 0 in order to
5540 * clear the reservation.
5541 *
5542 * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
5543 * ENOSPC accounting. For data we handle the reservation through clearing the
5544 * delalloc bits in the io_tree. We have to do this since we could end up
5545 * allocating less disk space for the amount of data we have reserved in the
5546 * case of compression.
5547 *
5548 * If this is a reservation and the block group has become read only we cannot
5549 * make the reservation and return -EAGAIN, otherwise this function always
5550 * succeeds.
f0486c68 5551 */
fb25e914
JB
5552static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
5553 u64 num_bytes, int reserve)
11833d66 5554{
fb25e914 5555 struct btrfs_space_info *space_info = cache->space_info;
f0486c68 5556 int ret = 0;
79787eaa 5557
fb25e914
JB
5558 spin_lock(&space_info->lock);
5559 spin_lock(&cache->lock);
5560 if (reserve != RESERVE_FREE) {
f0486c68
YZ
5561 if (cache->ro) {
5562 ret = -EAGAIN;
5563 } else {
fb25e914
JB
5564 cache->reserved += num_bytes;
5565 space_info->bytes_reserved += num_bytes;
5566 if (reserve == RESERVE_ALLOC) {
8c2a3ca2 5567 trace_btrfs_space_reservation(cache->fs_info,
2bcc0328
LB
5568 "space_info", space_info->flags,
5569 num_bytes, 0);
fb25e914
JB
5570 space_info->bytes_may_use -= num_bytes;
5571 }
f0486c68 5572 }
fb25e914
JB
5573 } else {
5574 if (cache->ro)
5575 space_info->bytes_readonly += num_bytes;
5576 cache->reserved -= num_bytes;
5577 space_info->bytes_reserved -= num_bytes;
324ae4df 5578 }
fb25e914
JB
5579 spin_unlock(&cache->lock);
5580 spin_unlock(&space_info->lock);
f0486c68 5581 return ret;
324ae4df 5582}
9078a3e1 5583
143bede5 5584void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
11833d66 5585 struct btrfs_root *root)
e8569813 5586{
e8569813 5587 struct btrfs_fs_info *fs_info = root->fs_info;
11833d66
YZ
5588 struct btrfs_caching_control *next;
5589 struct btrfs_caching_control *caching_ctl;
5590 struct btrfs_block_group_cache *cache;
b150a4f1 5591 struct btrfs_space_info *space_info;
e8569813 5592
9e351cc8 5593 down_write(&fs_info->commit_root_sem);
25179201 5594
11833d66
YZ
5595 list_for_each_entry_safe(caching_ctl, next,
5596 &fs_info->caching_block_groups, list) {
5597 cache = caching_ctl->block_group;
5598 if (block_group_cache_done(cache)) {
5599 cache->last_byte_to_unpin = (u64)-1;
5600 list_del_init(&caching_ctl->list);
5601 put_caching_control(caching_ctl);
e8569813 5602 } else {
11833d66 5603 cache->last_byte_to_unpin = caching_ctl->progress;
e8569813 5604 }
e8569813 5605 }
11833d66
YZ
5606
5607 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5608 fs_info->pinned_extents = &fs_info->freed_extents[1];
5609 else
5610 fs_info->pinned_extents = &fs_info->freed_extents[0];
5611
9e351cc8 5612 up_write(&fs_info->commit_root_sem);
8929ecfa 5613
b150a4f1
JB
5614 list_for_each_entry_rcu(space_info, &fs_info->space_info, list)
5615 percpu_counter_set(&space_info->total_bytes_pinned, 0);
5616
8929ecfa 5617 update_global_block_rsv(fs_info);
e8569813
ZY
5618}
5619
11833d66 5620static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
ccd467d6 5621{
11833d66
YZ
5622 struct btrfs_fs_info *fs_info = root->fs_info;
5623 struct btrfs_block_group_cache *cache = NULL;
7b398f8e
JB
5624 struct btrfs_space_info *space_info;
5625 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
11833d66 5626 u64 len;
7b398f8e 5627 bool readonly;
ccd467d6 5628
11833d66 5629 while (start <= end) {
7b398f8e 5630 readonly = false;
11833d66
YZ
5631 if (!cache ||
5632 start >= cache->key.objectid + cache->key.offset) {
5633 if (cache)
5634 btrfs_put_block_group(cache);
5635 cache = btrfs_lookup_block_group(fs_info, start);
79787eaa 5636 BUG_ON(!cache); /* Logic error */
11833d66
YZ
5637 }
5638
5639 len = cache->key.objectid + cache->key.offset - start;
5640 len = min(len, end + 1 - start);
5641
5642 if (start < cache->last_byte_to_unpin) {
5643 len = min(len, cache->last_byte_to_unpin - start);
5644 btrfs_add_free_space(cache, start, len);
5645 }
5646
f0486c68 5647 start += len;
7b398f8e 5648 space_info = cache->space_info;
f0486c68 5649
7b398f8e 5650 spin_lock(&space_info->lock);
11833d66
YZ
5651 spin_lock(&cache->lock);
5652 cache->pinned -= len;
7b398f8e
JB
5653 space_info->bytes_pinned -= len;
5654 if (cache->ro) {
5655 space_info->bytes_readonly += len;
5656 readonly = true;
5657 }
11833d66 5658 spin_unlock(&cache->lock);
7b398f8e
JB
5659 if (!readonly && global_rsv->space_info == space_info) {
5660 spin_lock(&global_rsv->lock);
5661 if (!global_rsv->full) {
5662 len = min(len, global_rsv->size -
5663 global_rsv->reserved);
5664 global_rsv->reserved += len;
5665 space_info->bytes_may_use += len;
5666 if (global_rsv->reserved >= global_rsv->size)
5667 global_rsv->full = 1;
5668 }
5669 spin_unlock(&global_rsv->lock);
5670 }
5671 spin_unlock(&space_info->lock);
ccd467d6 5672 }
11833d66
YZ
5673
5674 if (cache)
5675 btrfs_put_block_group(cache);
ccd467d6
CM
5676 return 0;
5677}
5678
5679int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
11833d66 5680 struct btrfs_root *root)
a28ec197 5681{
11833d66
YZ
5682 struct btrfs_fs_info *fs_info = root->fs_info;
5683 struct extent_io_tree *unpin;
1a5bc167
CM
5684 u64 start;
5685 u64 end;
a28ec197 5686 int ret;
a28ec197 5687
79787eaa
JM
5688 if (trans->aborted)
5689 return 0;
5690
11833d66
YZ
5691 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
5692 unpin = &fs_info->freed_extents[1];
5693 else
5694 unpin = &fs_info->freed_extents[0];
5695
d397712b 5696 while (1) {
1a5bc167 5697 ret = find_first_extent_bit(unpin, 0, &start, &end,
e6138876 5698 EXTENT_DIRTY, NULL);
1a5bc167 5699 if (ret)
a28ec197 5700 break;
1f3c79a2 5701
5378e607
LD
5702 if (btrfs_test_opt(root, DISCARD))
5703 ret = btrfs_discard_extent(root, start,
5704 end + 1 - start, NULL);
1f3c79a2 5705
1a5bc167 5706 clear_extent_dirty(unpin, start, end, GFP_NOFS);
11833d66 5707 unpin_extent_range(root, start, end);
b9473439 5708 cond_resched();
a28ec197 5709 }
817d52f8 5710
e20d96d6
CM
5711 return 0;
5712}
5713
b150a4f1
JB
5714static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
5715 u64 owner, u64 root_objectid)
5716{
5717 struct btrfs_space_info *space_info;
5718 u64 flags;
5719
5720 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
5721 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
5722 flags = BTRFS_BLOCK_GROUP_SYSTEM;
5723 else
5724 flags = BTRFS_BLOCK_GROUP_METADATA;
5725 } else {
5726 flags = BTRFS_BLOCK_GROUP_DATA;
5727 }
5728
5729 space_info = __find_space_info(fs_info, flags);
5730 BUG_ON(!space_info); /* Logic bug */
5731 percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
5732}
5733
5734
5d4f98a2
YZ
5735static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
5736 struct btrfs_root *root,
5737 u64 bytenr, u64 num_bytes, u64 parent,
5738 u64 root_objectid, u64 owner_objectid,
5739 u64 owner_offset, int refs_to_drop,
fcebe456
JB
5740 struct btrfs_delayed_extent_op *extent_op,
5741 int no_quota)
a28ec197 5742{
e2fa7227 5743 struct btrfs_key key;
5d4f98a2 5744 struct btrfs_path *path;
1261ec42
CM
5745 struct btrfs_fs_info *info = root->fs_info;
5746 struct btrfs_root *extent_root = info->extent_root;
5f39d397 5747 struct extent_buffer *leaf;
5d4f98a2
YZ
5748 struct btrfs_extent_item *ei;
5749 struct btrfs_extent_inline_ref *iref;
a28ec197 5750 int ret;
5d4f98a2 5751 int is_data;
952fccac
CM
5752 int extent_slot = 0;
5753 int found_extent = 0;
5754 int num_to_del = 1;
5d4f98a2
YZ
5755 u32 item_size;
5756 u64 refs;
fcebe456
JB
5757 int last_ref = 0;
5758 enum btrfs_qgroup_operation_type type = BTRFS_QGROUP_OPER_SUB_EXCL;
3173a18f
JB
5759 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
5760 SKINNY_METADATA);
037e6390 5761
fcebe456
JB
5762 if (!info->quota_enabled || !is_fstree(root_objectid))
5763 no_quota = 1;
5764
5caf2a00 5765 path = btrfs_alloc_path();
54aa1f4d
CM
5766 if (!path)
5767 return -ENOMEM;
5f26f772 5768
3c12ac72 5769 path->reada = 1;
b9473439 5770 path->leave_spinning = 1;
5d4f98a2
YZ
5771
5772 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
5773 BUG_ON(!is_data && refs_to_drop != 1);
5774
3173a18f
JB
5775 if (is_data)
5776 skinny_metadata = 0;
5777
5d4f98a2
YZ
5778 ret = lookup_extent_backref(trans, extent_root, path, &iref,
5779 bytenr, num_bytes, parent,
5780 root_objectid, owner_objectid,
5781 owner_offset);
7bb86316 5782 if (ret == 0) {
952fccac 5783 extent_slot = path->slots[0];
5d4f98a2
YZ
5784 while (extent_slot >= 0) {
5785 btrfs_item_key_to_cpu(path->nodes[0], &key,
952fccac 5786 extent_slot);
5d4f98a2 5787 if (key.objectid != bytenr)
952fccac 5788 break;
5d4f98a2
YZ
5789 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
5790 key.offset == num_bytes) {
952fccac
CM
5791 found_extent = 1;
5792 break;
5793 }
3173a18f
JB
5794 if (key.type == BTRFS_METADATA_ITEM_KEY &&
5795 key.offset == owner_objectid) {
5796 found_extent = 1;
5797 break;
5798 }
952fccac
CM
5799 if (path->slots[0] - extent_slot > 5)
5800 break;
5d4f98a2 5801 extent_slot--;
952fccac 5802 }
5d4f98a2
YZ
5803#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5804 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
5805 if (found_extent && item_size < sizeof(*ei))
5806 found_extent = 0;
5807#endif
31840ae1 5808 if (!found_extent) {
5d4f98a2 5809 BUG_ON(iref);
56bec294 5810 ret = remove_extent_backref(trans, extent_root, path,
5d4f98a2 5811 NULL, refs_to_drop,
fcebe456 5812 is_data, &last_ref);
005d6427
DS
5813 if (ret) {
5814 btrfs_abort_transaction(trans, extent_root, ret);
5815 goto out;
5816 }
b3b4aa74 5817 btrfs_release_path(path);
b9473439 5818 path->leave_spinning = 1;
5d4f98a2
YZ
5819
5820 key.objectid = bytenr;
5821 key.type = BTRFS_EXTENT_ITEM_KEY;
5822 key.offset = num_bytes;
5823
3173a18f
JB
5824 if (!is_data && skinny_metadata) {
5825 key.type = BTRFS_METADATA_ITEM_KEY;
5826 key.offset = owner_objectid;
5827 }
5828
31840ae1
ZY
5829 ret = btrfs_search_slot(trans, extent_root,
5830 &key, path, -1, 1);
3173a18f
JB
5831 if (ret > 0 && skinny_metadata && path->slots[0]) {
5832 /*
5833 * Couldn't find our skinny metadata item,
5834 * see if we have ye olde extent item.
5835 */
5836 path->slots[0]--;
5837 btrfs_item_key_to_cpu(path->nodes[0], &key,
5838 path->slots[0]);
5839 if (key.objectid == bytenr &&
5840 key.type == BTRFS_EXTENT_ITEM_KEY &&
5841 key.offset == num_bytes)
5842 ret = 0;
5843 }
5844
5845 if (ret > 0 && skinny_metadata) {
5846 skinny_metadata = false;
9ce49a0b 5847 key.objectid = bytenr;
3173a18f
JB
5848 key.type = BTRFS_EXTENT_ITEM_KEY;
5849 key.offset = num_bytes;
5850 btrfs_release_path(path);
5851 ret = btrfs_search_slot(trans, extent_root,
5852 &key, path, -1, 1);
5853 }
5854
f3465ca4 5855 if (ret) {
c2cf52eb 5856 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
c1c9ff7c 5857 ret, bytenr);
b783e62d
JB
5858 if (ret > 0)
5859 btrfs_print_leaf(extent_root,
5860 path->nodes[0]);
f3465ca4 5861 }
005d6427
DS
5862 if (ret < 0) {
5863 btrfs_abort_transaction(trans, extent_root, ret);
5864 goto out;
5865 }
31840ae1
ZY
5866 extent_slot = path->slots[0];
5867 }
fae7f21c 5868 } else if (WARN_ON(ret == -ENOENT)) {
7bb86316 5869 btrfs_print_leaf(extent_root, path->nodes[0]);
c2cf52eb
SK
5870 btrfs_err(info,
5871 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
c1c9ff7c
GU
5872 bytenr, parent, root_objectid, owner_objectid,
5873 owner_offset);
c4a050bb
JB
5874 btrfs_abort_transaction(trans, extent_root, ret);
5875 goto out;
79787eaa 5876 } else {
005d6427
DS
5877 btrfs_abort_transaction(trans, extent_root, ret);
5878 goto out;
7bb86316 5879 }
5f39d397
CM
5880
5881 leaf = path->nodes[0];
5d4f98a2
YZ
5882 item_size = btrfs_item_size_nr(leaf, extent_slot);
5883#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
5884 if (item_size < sizeof(*ei)) {
5885 BUG_ON(found_extent || extent_slot != path->slots[0]);
5886 ret = convert_extent_item_v0(trans, extent_root, path,
5887 owner_objectid, 0);
005d6427
DS
5888 if (ret < 0) {
5889 btrfs_abort_transaction(trans, extent_root, ret);
5890 goto out;
5891 }
5d4f98a2 5892
b3b4aa74 5893 btrfs_release_path(path);
5d4f98a2
YZ
5894 path->leave_spinning = 1;
5895
5896 key.objectid = bytenr;
5897 key.type = BTRFS_EXTENT_ITEM_KEY;
5898 key.offset = num_bytes;
5899
5900 ret = btrfs_search_slot(trans, extent_root, &key, path,
5901 -1, 1);
5902 if (ret) {
c2cf52eb 5903 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
c1c9ff7c 5904 ret, bytenr);
5d4f98a2
YZ
5905 btrfs_print_leaf(extent_root, path->nodes[0]);
5906 }
005d6427
DS
5907 if (ret < 0) {
5908 btrfs_abort_transaction(trans, extent_root, ret);
5909 goto out;
5910 }
5911
5d4f98a2
YZ
5912 extent_slot = path->slots[0];
5913 leaf = path->nodes[0];
5914 item_size = btrfs_item_size_nr(leaf, extent_slot);
5915 }
5916#endif
5917 BUG_ON(item_size < sizeof(*ei));
952fccac 5918 ei = btrfs_item_ptr(leaf, extent_slot,
123abc88 5919 struct btrfs_extent_item);
3173a18f
JB
5920 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
5921 key.type == BTRFS_EXTENT_ITEM_KEY) {
5d4f98a2
YZ
5922 struct btrfs_tree_block_info *bi;
5923 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
5924 bi = (struct btrfs_tree_block_info *)(ei + 1);
5925 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
5926 }
56bec294 5927
5d4f98a2 5928 refs = btrfs_extent_refs(leaf, ei);
32b02538
JB
5929 if (refs < refs_to_drop) {
5930 btrfs_err(info, "trying to drop %d refs but we only have %Lu "
5931 "for bytenr %Lu\n", refs_to_drop, refs, bytenr);
5932 ret = -EINVAL;
5933 btrfs_abort_transaction(trans, extent_root, ret);
5934 goto out;
5935 }
56bec294 5936 refs -= refs_to_drop;
5f39d397 5937
5d4f98a2 5938 if (refs > 0) {
fcebe456 5939 type = BTRFS_QGROUP_OPER_SUB_SHARED;
5d4f98a2
YZ
5940 if (extent_op)
5941 __run_delayed_extent_op(extent_op, leaf, ei);
5942 /*
5943 * In the case of inline back ref, reference count will
5944 * be updated by remove_extent_backref
952fccac 5945 */
5d4f98a2
YZ
5946 if (iref) {
5947 BUG_ON(!found_extent);
5948 } else {
5949 btrfs_set_extent_refs(leaf, ei, refs);
5950 btrfs_mark_buffer_dirty(leaf);
5951 }
5952 if (found_extent) {
5953 ret = remove_extent_backref(trans, extent_root, path,
5954 iref, refs_to_drop,
fcebe456 5955 is_data, &last_ref);
005d6427
DS
5956 if (ret) {
5957 btrfs_abort_transaction(trans, extent_root, ret);
5958 goto out;
5959 }
952fccac 5960 }
b150a4f1
JB
5961 add_pinned_bytes(root->fs_info, -num_bytes, owner_objectid,
5962 root_objectid);
5d4f98a2 5963 } else {
5d4f98a2
YZ
5964 if (found_extent) {
5965 BUG_ON(is_data && refs_to_drop !=
5966 extent_data_ref_count(root, path, iref));
5967 if (iref) {
5968 BUG_ON(path->slots[0] != extent_slot);
5969 } else {
5970 BUG_ON(path->slots[0] != extent_slot + 1);
5971 path->slots[0] = extent_slot;
5972 num_to_del = 2;
5973 }
78fae27e 5974 }
b9473439 5975
fcebe456 5976 last_ref = 1;
952fccac
CM
5977 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
5978 num_to_del);
005d6427
DS
5979 if (ret) {
5980 btrfs_abort_transaction(trans, extent_root, ret);
5981 goto out;
5982 }
b3b4aa74 5983 btrfs_release_path(path);
21af804c 5984
5d4f98a2 5985 if (is_data) {
459931ec 5986 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
005d6427
DS
5987 if (ret) {
5988 btrfs_abort_transaction(trans, extent_root, ret);
5989 goto out;
5990 }
459931ec
CM
5991 }
5992
c53d613e 5993 ret = update_block_group(root, bytenr, num_bytes, 0);
005d6427
DS
5994 if (ret) {
5995 btrfs_abort_transaction(trans, extent_root, ret);
5996 goto out;
5997 }
a28ec197 5998 }
fcebe456
JB
5999 btrfs_release_path(path);
6000
6001 /* Deal with the quota accounting */
6002 if (!ret && last_ref && !no_quota) {
6003 int mod_seq = 0;
6004
6005 if (owner_objectid >= BTRFS_FIRST_FREE_OBJECTID &&
6006 type == BTRFS_QGROUP_OPER_SUB_SHARED)
6007 mod_seq = 1;
6008
6009 ret = btrfs_qgroup_record_ref(trans, info, root_objectid,
6010 bytenr, num_bytes, type,
6011 mod_seq);
6012 }
79787eaa 6013out:
5caf2a00 6014 btrfs_free_path(path);
a28ec197
CM
6015 return ret;
6016}
6017
1887be66 6018/*
f0486c68 6019 * when we free an block, it is possible (and likely) that we free the last
1887be66
CM
6020 * delayed ref for that extent as well. This searches the delayed ref tree for
6021 * a given extent, and if there are no other delayed refs to be processed, it
6022 * removes it from the tree.
6023 */
6024static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
6025 struct btrfs_root *root, u64 bytenr)
6026{
6027 struct btrfs_delayed_ref_head *head;
6028 struct btrfs_delayed_ref_root *delayed_refs;
f0486c68 6029 int ret = 0;
1887be66
CM
6030
6031 delayed_refs = &trans->transaction->delayed_refs;
6032 spin_lock(&delayed_refs->lock);
6033 head = btrfs_find_delayed_ref_head(trans, bytenr);
6034 if (!head)
cf93da7b 6035 goto out_delayed_unlock;
1887be66 6036
d7df2c79
JB
6037 spin_lock(&head->lock);
6038 if (rb_first(&head->ref_root))
1887be66
CM
6039 goto out;
6040
5d4f98a2
YZ
6041 if (head->extent_op) {
6042 if (!head->must_insert_reserved)
6043 goto out;
78a6184a 6044 btrfs_free_delayed_extent_op(head->extent_op);
5d4f98a2
YZ
6045 head->extent_op = NULL;
6046 }
6047
1887be66
CM
6048 /*
6049 * waiting for the lock here would deadlock. If someone else has it
6050 * locked they are already in the process of dropping it anyway
6051 */
6052 if (!mutex_trylock(&head->mutex))
6053 goto out;
6054
6055 /*
6056 * at this point we have a head with no other entries. Go
6057 * ahead and process it.
6058 */
6059 head->node.in_tree = 0;
c46effa6 6060 rb_erase(&head->href_node, &delayed_refs->href_root);
c3e69d58 6061
d7df2c79 6062 atomic_dec(&delayed_refs->num_entries);
1887be66
CM
6063
6064 /*
6065 * we don't take a ref on the node because we're removing it from the
6066 * tree, so we just steal the ref the tree was holding.
6067 */
c3e69d58 6068 delayed_refs->num_heads--;
d7df2c79 6069 if (head->processing == 0)
c3e69d58 6070 delayed_refs->num_heads_ready--;
d7df2c79
JB
6071 head->processing = 0;
6072 spin_unlock(&head->lock);
1887be66
CM
6073 spin_unlock(&delayed_refs->lock);
6074
f0486c68
YZ
6075 BUG_ON(head->extent_op);
6076 if (head->must_insert_reserved)
6077 ret = 1;
6078
6079 mutex_unlock(&head->mutex);
1887be66 6080 btrfs_put_delayed_ref(&head->node);
f0486c68 6081 return ret;
1887be66 6082out:
d7df2c79 6083 spin_unlock(&head->lock);
cf93da7b
CM
6084
6085out_delayed_unlock:
1887be66
CM
6086 spin_unlock(&delayed_refs->lock);
6087 return 0;
6088}
6089
f0486c68
YZ
6090void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
6091 struct btrfs_root *root,
6092 struct extent_buffer *buf,
5581a51a 6093 u64 parent, int last_ref)
f0486c68 6094{
f0486c68 6095 struct btrfs_block_group_cache *cache = NULL;
b150a4f1 6096 int pin = 1;
f0486c68
YZ
6097 int ret;
6098
6099 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
66d7e7f0
AJ
6100 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
6101 buf->start, buf->len,
6102 parent, root->root_key.objectid,
6103 btrfs_header_level(buf),
5581a51a 6104 BTRFS_DROP_DELAYED_REF, NULL, 0);
79787eaa 6105 BUG_ON(ret); /* -ENOMEM */
f0486c68
YZ
6106 }
6107
6108 if (!last_ref)
6109 return;
6110
f0486c68 6111 cache = btrfs_lookup_block_group(root->fs_info, buf->start);
f0486c68
YZ
6112
6113 if (btrfs_header_generation(buf) == trans->transid) {
6114 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6115 ret = check_ref_cleanup(trans, root, buf->start);
6116 if (!ret)
37be25bc 6117 goto out;
f0486c68
YZ
6118 }
6119
6120 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
6121 pin_down_extent(root, cache, buf->start, buf->len, 1);
37be25bc 6122 goto out;
f0486c68
YZ
6123 }
6124
6125 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
6126
6127 btrfs_add_free_space(cache, buf->start, buf->len);
fb25e914 6128 btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE);
0be5dc67 6129 trace_btrfs_reserved_extent_free(root, buf->start, buf->len);
b150a4f1 6130 pin = 0;
f0486c68
YZ
6131 }
6132out:
b150a4f1
JB
6133 if (pin)
6134 add_pinned_bytes(root->fs_info, buf->len,
6135 btrfs_header_level(buf),
6136 root->root_key.objectid);
6137
a826d6dc
JB
6138 /*
6139 * Deleting the buffer, clear the corrupt flag since it doesn't matter
6140 * anymore.
6141 */
6142 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
f0486c68
YZ
6143 btrfs_put_block_group(cache);
6144}
6145
79787eaa 6146/* Can return -ENOMEM */
66d7e7f0
AJ
6147int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
6148 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
fcebe456 6149 u64 owner, u64 offset, int no_quota)
925baedd
CM
6150{
6151 int ret;
66d7e7f0 6152 struct btrfs_fs_info *fs_info = root->fs_info;
925baedd 6153
b150a4f1
JB
6154 add_pinned_bytes(root->fs_info, num_bytes, owner, root_objectid);
6155
56bec294
CM
6156 /*
6157 * tree log blocks never actually go into the extent allocation
6158 * tree, just update pinning info and exit early.
56bec294 6159 */
5d4f98a2
YZ
6160 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
6161 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
b9473439 6162 /* unlocks the pinned mutex */
11833d66 6163 btrfs_pin_extent(root, bytenr, num_bytes, 1);
56bec294 6164 ret = 0;
5d4f98a2 6165 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
66d7e7f0
AJ
6166 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
6167 num_bytes,
5d4f98a2 6168 parent, root_objectid, (int)owner,
fcebe456 6169 BTRFS_DROP_DELAYED_REF, NULL, no_quota);
5d4f98a2 6170 } else {
66d7e7f0
AJ
6171 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
6172 num_bytes,
6173 parent, root_objectid, owner,
6174 offset, BTRFS_DROP_DELAYED_REF,
fcebe456 6175 NULL, no_quota);
56bec294 6176 }
925baedd
CM
6177 return ret;
6178}
6179
53b381b3
DW
6180static u64 stripe_align(struct btrfs_root *root,
6181 struct btrfs_block_group_cache *cache,
6182 u64 val, u64 num_bytes)
87ee04eb 6183{
fda2832f 6184 u64 ret = ALIGN(val, root->stripesize);
87ee04eb
CM
6185 return ret;
6186}
6187
817d52f8
JB
6188/*
6189 * when we wait for progress in the block group caching, its because
6190 * our allocation attempt failed at least once. So, we must sleep
6191 * and let some progress happen before we try again.
6192 *
6193 * This function will sleep at least once waiting for new free space to
6194 * show up, and then it will check the block group free space numbers
6195 * for our min num_bytes. Another option is to have it go ahead
6196 * and look in the rbtree for a free extent of a given size, but this
6197 * is a good start.
36cce922
JB
6198 *
6199 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
6200 * any of the information in this block group.
817d52f8 6201 */
36cce922 6202static noinline void
817d52f8
JB
6203wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
6204 u64 num_bytes)
6205{
11833d66 6206 struct btrfs_caching_control *caching_ctl;
817d52f8 6207
11833d66
YZ
6208 caching_ctl = get_caching_control(cache);
6209 if (!caching_ctl)
36cce922 6210 return;
817d52f8 6211
11833d66 6212 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
34d52cb6 6213 (cache->free_space_ctl->free_space >= num_bytes));
11833d66
YZ
6214
6215 put_caching_control(caching_ctl);
11833d66
YZ
6216}
6217
6218static noinline int
6219wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
6220{
6221 struct btrfs_caching_control *caching_ctl;
36cce922 6222 int ret = 0;
11833d66
YZ
6223
6224 caching_ctl = get_caching_control(cache);
6225 if (!caching_ctl)
36cce922 6226 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
11833d66
YZ
6227
6228 wait_event(caching_ctl->wait, block_group_cache_done(cache));
36cce922
JB
6229 if (cache->cached == BTRFS_CACHE_ERROR)
6230 ret = -EIO;
11833d66 6231 put_caching_control(caching_ctl);
36cce922 6232 return ret;
817d52f8
JB
6233}
6234
31e50229 6235int __get_raid_index(u64 flags)
b742bb82 6236{
7738a53a 6237 if (flags & BTRFS_BLOCK_GROUP_RAID10)
e6ec716f 6238 return BTRFS_RAID_RAID10;
7738a53a 6239 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
e6ec716f 6240 return BTRFS_RAID_RAID1;
7738a53a 6241 else if (flags & BTRFS_BLOCK_GROUP_DUP)
e6ec716f 6242 return BTRFS_RAID_DUP;
7738a53a 6243 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
e6ec716f 6244 return BTRFS_RAID_RAID0;
53b381b3 6245 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
e942f883 6246 return BTRFS_RAID_RAID5;
53b381b3 6247 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
e942f883 6248 return BTRFS_RAID_RAID6;
7738a53a 6249
e942f883 6250 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
b742bb82
YZ
6251}
6252
6ab0a202 6253int get_block_group_index(struct btrfs_block_group_cache *cache)
7738a53a 6254{
31e50229 6255 return __get_raid_index(cache->flags);
7738a53a
ID
6256}
6257
6ab0a202
JM
6258static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
6259 [BTRFS_RAID_RAID10] = "raid10",
6260 [BTRFS_RAID_RAID1] = "raid1",
6261 [BTRFS_RAID_DUP] = "dup",
6262 [BTRFS_RAID_RAID0] = "raid0",
6263 [BTRFS_RAID_SINGLE] = "single",
6264 [BTRFS_RAID_RAID5] = "raid5",
6265 [BTRFS_RAID_RAID6] = "raid6",
6266};
6267
1b8e5df6 6268static const char *get_raid_name(enum btrfs_raid_types type)
6ab0a202
JM
6269{
6270 if (type >= BTRFS_NR_RAID_TYPES)
6271 return NULL;
6272
6273 return btrfs_raid_type_names[type];
6274}
6275
817d52f8 6276enum btrfs_loop_type {
285ff5af
JB
6277 LOOP_CACHING_NOWAIT = 0,
6278 LOOP_CACHING_WAIT = 1,
6279 LOOP_ALLOC_CHUNK = 2,
6280 LOOP_NO_EMPTY_SIZE = 3,
817d52f8
JB
6281};
6282
fec577fb
CM
6283/*
6284 * walks the btree of allocated extents and find a hole of a given size.
6285 * The key ins is changed to record the hole:
a4820398 6286 * ins->objectid == start position
62e2749e 6287 * ins->flags = BTRFS_EXTENT_ITEM_KEY
a4820398 6288 * ins->offset == the size of the hole.
fec577fb 6289 * Any available blocks before search_start are skipped.
a4820398
MX
6290 *
6291 * If there is no suitable free space, we will record the max size of
6292 * the free space extent currently.
fec577fb 6293 */
00361589 6294static noinline int find_free_extent(struct btrfs_root *orig_root,
98ed5174 6295 u64 num_bytes, u64 empty_size,
98ed5174 6296 u64 hint_byte, struct btrfs_key *ins,
b6919a58 6297 u64 flags)
fec577fb 6298{
80eb234a 6299 int ret = 0;
d397712b 6300 struct btrfs_root *root = orig_root->fs_info->extent_root;
fa9c0d79 6301 struct btrfs_free_cluster *last_ptr = NULL;
80eb234a 6302 struct btrfs_block_group_cache *block_group = NULL;
81c9ad23 6303 u64 search_start = 0;
a4820398 6304 u64 max_extent_size = 0;
239b14b3 6305 int empty_cluster = 2 * 1024 * 1024;
80eb234a 6306 struct btrfs_space_info *space_info;
fa9c0d79 6307 int loop = 0;
b6919a58
DS
6308 int index = __get_raid_index(flags);
6309 int alloc_type = (flags & BTRFS_BLOCK_GROUP_DATA) ?
fb25e914 6310 RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
0a24325e 6311 bool failed_cluster_refill = false;
1cdda9b8 6312 bool failed_alloc = false;
67377734 6313 bool use_cluster = true;
60d2adbb 6314 bool have_caching_bg = false;
fec577fb 6315
db94535d 6316 WARN_ON(num_bytes < root->sectorsize);
b1a4d965 6317 btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
80eb234a
JB
6318 ins->objectid = 0;
6319 ins->offset = 0;
b1a4d965 6320
b6919a58 6321 trace_find_free_extent(orig_root, num_bytes, empty_size, flags);
3f7de037 6322
b6919a58 6323 space_info = __find_space_info(root->fs_info, flags);
1b1d1f66 6324 if (!space_info) {
b6919a58 6325 btrfs_err(root->fs_info, "No space info for %llu", flags);
1b1d1f66
JB
6326 return -ENOSPC;
6327 }
2552d17e 6328
67377734
JB
6329 /*
6330 * If the space info is for both data and metadata it means we have a
6331 * small filesystem and we can't use the clustering stuff.
6332 */
6333 if (btrfs_mixed_space_info(space_info))
6334 use_cluster = false;
6335
b6919a58 6336 if (flags & BTRFS_BLOCK_GROUP_METADATA && use_cluster) {
fa9c0d79 6337 last_ptr = &root->fs_info->meta_alloc_cluster;
536ac8ae
CM
6338 if (!btrfs_test_opt(root, SSD))
6339 empty_cluster = 64 * 1024;
239b14b3
CM
6340 }
6341
b6919a58 6342 if ((flags & BTRFS_BLOCK_GROUP_DATA) && use_cluster &&
67377734 6343 btrfs_test_opt(root, SSD)) {
fa9c0d79
CM
6344 last_ptr = &root->fs_info->data_alloc_cluster;
6345 }
0f9dd46c 6346
239b14b3 6347 if (last_ptr) {
fa9c0d79
CM
6348 spin_lock(&last_ptr->lock);
6349 if (last_ptr->block_group)
6350 hint_byte = last_ptr->window_start;
6351 spin_unlock(&last_ptr->lock);
239b14b3 6352 }
fa9c0d79 6353
a061fc8d 6354 search_start = max(search_start, first_logical_byte(root, 0));
239b14b3 6355 search_start = max(search_start, hint_byte);
0b86a832 6356
817d52f8 6357 if (!last_ptr)
fa9c0d79 6358 empty_cluster = 0;
fa9c0d79 6359
2552d17e 6360 if (search_start == hint_byte) {
2552d17e
JB
6361 block_group = btrfs_lookup_block_group(root->fs_info,
6362 search_start);
817d52f8
JB
6363 /*
6364 * we don't want to use the block group if it doesn't match our
6365 * allocation bits, or if its not cached.
ccf0e725
JB
6366 *
6367 * However if we are re-searching with an ideal block group
6368 * picked out then we don't care that the block group is cached.
817d52f8 6369 */
b6919a58 6370 if (block_group && block_group_bits(block_group, flags) &&
285ff5af 6371 block_group->cached != BTRFS_CACHE_NO) {
2552d17e 6372 down_read(&space_info->groups_sem);
44fb5511
CM
6373 if (list_empty(&block_group->list) ||
6374 block_group->ro) {
6375 /*
6376 * someone is removing this block group,
6377 * we can't jump into the have_block_group
6378 * target because our list pointers are not
6379 * valid
6380 */
6381 btrfs_put_block_group(block_group);
6382 up_read(&space_info->groups_sem);
ccf0e725 6383 } else {
b742bb82 6384 index = get_block_group_index(block_group);
44fb5511 6385 goto have_block_group;
ccf0e725 6386 }
2552d17e 6387 } else if (block_group) {
fa9c0d79 6388 btrfs_put_block_group(block_group);
2552d17e 6389 }
42e70e7a 6390 }
2552d17e 6391search:
60d2adbb 6392 have_caching_bg = false;
80eb234a 6393 down_read(&space_info->groups_sem);
b742bb82
YZ
6394 list_for_each_entry(block_group, &space_info->block_groups[index],
6395 list) {
6226cb0a 6396 u64 offset;
817d52f8 6397 int cached;
8a1413a2 6398
11dfe35a 6399 btrfs_get_block_group(block_group);
2552d17e 6400 search_start = block_group->key.objectid;
42e70e7a 6401
83a50de9
CM
6402 /*
6403 * this can happen if we end up cycling through all the
6404 * raid types, but we want to make sure we only allocate
6405 * for the proper type.
6406 */
b6919a58 6407 if (!block_group_bits(block_group, flags)) {
83a50de9
CM
6408 u64 extra = BTRFS_BLOCK_GROUP_DUP |
6409 BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
6410 BTRFS_BLOCK_GROUP_RAID5 |
6411 BTRFS_BLOCK_GROUP_RAID6 |
83a50de9
CM
6412 BTRFS_BLOCK_GROUP_RAID10;
6413
6414 /*
6415 * if they asked for extra copies and this block group
6416 * doesn't provide them, bail. This does allow us to
6417 * fill raid0 from raid1.
6418 */
b6919a58 6419 if ((flags & extra) && !(block_group->flags & extra))
83a50de9
CM
6420 goto loop;
6421 }
6422
2552d17e 6423have_block_group:
291c7d2f
JB
6424 cached = block_group_cache_done(block_group);
6425 if (unlikely(!cached)) {
f6373bf3 6426 ret = cache_block_group(block_group, 0);
1d4284bd
CM
6427 BUG_ON(ret < 0);
6428 ret = 0;
817d52f8
JB
6429 }
6430
36cce922
JB
6431 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
6432 goto loop;
ea6a478e 6433 if (unlikely(block_group->ro))
2552d17e 6434 goto loop;
0f9dd46c 6435
0a24325e 6436 /*
062c05c4
AO
6437 * Ok we want to try and use the cluster allocator, so
6438 * lets look there
0a24325e 6439 */
062c05c4 6440 if (last_ptr) {
215a63d1 6441 struct btrfs_block_group_cache *used_block_group;
8de972b4 6442 unsigned long aligned_cluster;
fa9c0d79
CM
6443 /*
6444 * the refill lock keeps out other
6445 * people trying to start a new cluster
6446 */
6447 spin_lock(&last_ptr->refill_lock);
274bd4fb
AO
6448 used_block_group = last_ptr->block_group;
6449 if (used_block_group != block_group &&
6450 (!used_block_group ||
6451 used_block_group->ro ||
215a63d1 6452 !block_group_bits(used_block_group, flags)))
44fb5511 6453 goto refill_cluster;
274bd4fb
AO
6454
6455 if (used_block_group != block_group)
6456 btrfs_get_block_group(used_block_group);
44fb5511 6457
274bd4fb 6458 offset = btrfs_alloc_from_cluster(used_block_group,
a4820398
MX
6459 last_ptr,
6460 num_bytes,
6461 used_block_group->key.objectid,
6462 &max_extent_size);
fa9c0d79
CM
6463 if (offset) {
6464 /* we have a block, we're done */
6465 spin_unlock(&last_ptr->refill_lock);
3f7de037 6466 trace_btrfs_reserve_extent_cluster(root,
89d4346a
MX
6467 used_block_group,
6468 search_start, num_bytes);
215a63d1
MX
6469 if (used_block_group != block_group) {
6470 btrfs_put_block_group(block_group);
6471 block_group = used_block_group;
6472 }
fa9c0d79
CM
6473 goto checks;
6474 }
6475
274bd4fb 6476 WARN_ON(last_ptr->block_group != used_block_group);
215a63d1 6477 if (used_block_group != block_group)
274bd4fb 6478 btrfs_put_block_group(used_block_group);
44fb5511 6479refill_cluster:
062c05c4
AO
6480 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
6481 * set up a new clusters, so lets just skip it
6482 * and let the allocator find whatever block
6483 * it can find. If we reach this point, we
6484 * will have tried the cluster allocator
6485 * plenty of times and not have found
6486 * anything, so we are likely way too
6487 * fragmented for the clustering stuff to find
a5f6f719
AO
6488 * anything.
6489 *
6490 * However, if the cluster is taken from the
6491 * current block group, release the cluster
6492 * first, so that we stand a better chance of
6493 * succeeding in the unclustered
6494 * allocation. */
6495 if (loop >= LOOP_NO_EMPTY_SIZE &&
6496 last_ptr->block_group != block_group) {
062c05c4
AO
6497 spin_unlock(&last_ptr->refill_lock);
6498 goto unclustered_alloc;
6499 }
6500
fa9c0d79
CM
6501 /*
6502 * this cluster didn't work out, free it and
6503 * start over
6504 */
6505 btrfs_return_cluster_to_free_space(NULL, last_ptr);
6506
a5f6f719
AO
6507 if (loop >= LOOP_NO_EMPTY_SIZE) {
6508 spin_unlock(&last_ptr->refill_lock);
6509 goto unclustered_alloc;
6510 }
6511
8de972b4
CM
6512 aligned_cluster = max_t(unsigned long,
6513 empty_cluster + empty_size,
6514 block_group->full_stripe_len);
6515
fa9c0d79 6516 /* allocate a cluster in this block group */
00361589
JB
6517 ret = btrfs_find_space_cluster(root, block_group,
6518 last_ptr, search_start,
6519 num_bytes,
6520 aligned_cluster);
fa9c0d79
CM
6521 if (ret == 0) {
6522 /*
6523 * now pull our allocation out of this
6524 * cluster
6525 */
6526 offset = btrfs_alloc_from_cluster(block_group,
a4820398
MX
6527 last_ptr,
6528 num_bytes,
6529 search_start,
6530 &max_extent_size);
fa9c0d79
CM
6531 if (offset) {
6532 /* we found one, proceed */
6533 spin_unlock(&last_ptr->refill_lock);
3f7de037
JB
6534 trace_btrfs_reserve_extent_cluster(root,
6535 block_group, search_start,
6536 num_bytes);
fa9c0d79
CM
6537 goto checks;
6538 }
0a24325e
JB
6539 } else if (!cached && loop > LOOP_CACHING_NOWAIT
6540 && !failed_cluster_refill) {
817d52f8
JB
6541 spin_unlock(&last_ptr->refill_lock);
6542
0a24325e 6543 failed_cluster_refill = true;
817d52f8
JB
6544 wait_block_group_cache_progress(block_group,
6545 num_bytes + empty_cluster + empty_size);
6546 goto have_block_group;
fa9c0d79 6547 }
817d52f8 6548
fa9c0d79
CM
6549 /*
6550 * at this point we either didn't find a cluster
6551 * or we weren't able to allocate a block from our
6552 * cluster. Free the cluster we've been trying
6553 * to use, and go to the next block group
6554 */
0a24325e 6555 btrfs_return_cluster_to_free_space(NULL, last_ptr);
fa9c0d79 6556 spin_unlock(&last_ptr->refill_lock);
0a24325e 6557 goto loop;
fa9c0d79
CM
6558 }
6559
062c05c4 6560unclustered_alloc:
a5f6f719
AO
6561 spin_lock(&block_group->free_space_ctl->tree_lock);
6562 if (cached &&
6563 block_group->free_space_ctl->free_space <
6564 num_bytes + empty_cluster + empty_size) {
a4820398
MX
6565 if (block_group->free_space_ctl->free_space >
6566 max_extent_size)
6567 max_extent_size =
6568 block_group->free_space_ctl->free_space;
a5f6f719
AO
6569 spin_unlock(&block_group->free_space_ctl->tree_lock);
6570 goto loop;
6571 }
6572 spin_unlock(&block_group->free_space_ctl->tree_lock);
6573
6226cb0a 6574 offset = btrfs_find_space_for_alloc(block_group, search_start,
a4820398
MX
6575 num_bytes, empty_size,
6576 &max_extent_size);
1cdda9b8
JB
6577 /*
6578 * If we didn't find a chunk, and we haven't failed on this
6579 * block group before, and this block group is in the middle of
6580 * caching and we are ok with waiting, then go ahead and wait
6581 * for progress to be made, and set failed_alloc to true.
6582 *
6583 * If failed_alloc is true then we've already waited on this
6584 * block group once and should move on to the next block group.
6585 */
6586 if (!offset && !failed_alloc && !cached &&
6587 loop > LOOP_CACHING_NOWAIT) {
817d52f8 6588 wait_block_group_cache_progress(block_group,
1cdda9b8
JB
6589 num_bytes + empty_size);
6590 failed_alloc = true;
817d52f8 6591 goto have_block_group;
1cdda9b8 6592 } else if (!offset) {
60d2adbb
MX
6593 if (!cached)
6594 have_caching_bg = true;
1cdda9b8 6595 goto loop;
817d52f8 6596 }
fa9c0d79 6597checks:
215a63d1 6598 search_start = stripe_align(root, block_group,
53b381b3 6599 offset, num_bytes);
25179201 6600
2552d17e
JB
6601 /* move on to the next group */
6602 if (search_start + num_bytes >
215a63d1
MX
6603 block_group->key.objectid + block_group->key.offset) {
6604 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e 6605 goto loop;
6226cb0a 6606 }
f5a31e16 6607
f0486c68 6608 if (offset < search_start)
215a63d1 6609 btrfs_add_free_space(block_group, offset,
f0486c68
YZ
6610 search_start - offset);
6611 BUG_ON(offset > search_start);
2552d17e 6612
215a63d1 6613 ret = btrfs_update_reserved_bytes(block_group, num_bytes,
fb25e914 6614 alloc_type);
f0486c68 6615 if (ret == -EAGAIN) {
215a63d1 6616 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e 6617 goto loop;
0f9dd46c 6618 }
0b86a832 6619
f0486c68 6620 /* we are all good, lets return */
2552d17e
JB
6621 ins->objectid = search_start;
6622 ins->offset = num_bytes;
d2fb3437 6623
3f7de037
JB
6624 trace_btrfs_reserve_extent(orig_root, block_group,
6625 search_start, num_bytes);
d82a6f1d 6626 btrfs_put_block_group(block_group);
2552d17e
JB
6627 break;
6628loop:
0a24325e 6629 failed_cluster_refill = false;
1cdda9b8 6630 failed_alloc = false;
b742bb82 6631 BUG_ON(index != get_block_group_index(block_group));
fa9c0d79 6632 btrfs_put_block_group(block_group);
2552d17e
JB
6633 }
6634 up_read(&space_info->groups_sem);
6635
60d2adbb
MX
6636 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
6637 goto search;
6638
b742bb82
YZ
6639 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
6640 goto search;
6641
285ff5af 6642 /*
ccf0e725
JB
6643 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
6644 * caching kthreads as we move along
817d52f8
JB
6645 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
6646 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
6647 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
6648 * again
fa9c0d79 6649 */
723bda20 6650 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
b742bb82 6651 index = 0;
723bda20 6652 loop++;
817d52f8 6653 if (loop == LOOP_ALLOC_CHUNK) {
00361589 6654 struct btrfs_trans_handle *trans;
f017f15f
WS
6655 int exist = 0;
6656
6657 trans = current->journal_info;
6658 if (trans)
6659 exist = 1;
6660 else
6661 trans = btrfs_join_transaction(root);
00361589 6662
00361589
JB
6663 if (IS_ERR(trans)) {
6664 ret = PTR_ERR(trans);
6665 goto out;
6666 }
6667
b6919a58 6668 ret = do_chunk_alloc(trans, root, flags,
ea658bad
JB
6669 CHUNK_ALLOC_FORCE);
6670 /*
6671 * Do not bail out on ENOSPC since we
6672 * can do more things.
6673 */
00361589 6674 if (ret < 0 && ret != -ENOSPC)
ea658bad
JB
6675 btrfs_abort_transaction(trans,
6676 root, ret);
00361589
JB
6677 else
6678 ret = 0;
f017f15f
WS
6679 if (!exist)
6680 btrfs_end_transaction(trans, root);
00361589 6681 if (ret)
ea658bad 6682 goto out;
2552d17e
JB
6683 }
6684
723bda20
JB
6685 if (loop == LOOP_NO_EMPTY_SIZE) {
6686 empty_size = 0;
6687 empty_cluster = 0;
fa9c0d79 6688 }
723bda20
JB
6689
6690 goto search;
2552d17e
JB
6691 } else if (!ins->objectid) {
6692 ret = -ENOSPC;
d82a6f1d 6693 } else if (ins->objectid) {
80eb234a 6694 ret = 0;
be744175 6695 }
79787eaa 6696out:
a4820398
MX
6697 if (ret == -ENOSPC)
6698 ins->offset = max_extent_size;
0f70abe2 6699 return ret;
fec577fb 6700}
ec44a35c 6701
9ed74f2d
JB
6702static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
6703 int dump_block_groups)
0f9dd46c
JB
6704{
6705 struct btrfs_block_group_cache *cache;
b742bb82 6706 int index = 0;
0f9dd46c 6707
9ed74f2d 6708 spin_lock(&info->lock);
efe120a0 6709 printk(KERN_INFO "BTRFS: space_info %llu has %llu free, is %sfull\n",
c1c9ff7c
GU
6710 info->flags,
6711 info->total_bytes - info->bytes_used - info->bytes_pinned -
6712 info->bytes_reserved - info->bytes_readonly,
d397712b 6713 (info->full) ? "" : "not ");
efe120a0 6714 printk(KERN_INFO "BTRFS: space_info total=%llu, used=%llu, pinned=%llu, "
8929ecfa 6715 "reserved=%llu, may_use=%llu, readonly=%llu\n",
c1c9ff7c
GU
6716 info->total_bytes, info->bytes_used, info->bytes_pinned,
6717 info->bytes_reserved, info->bytes_may_use,
6718 info->bytes_readonly);
9ed74f2d
JB
6719 spin_unlock(&info->lock);
6720
6721 if (!dump_block_groups)
6722 return;
0f9dd46c 6723
80eb234a 6724 down_read(&info->groups_sem);
b742bb82
YZ
6725again:
6726 list_for_each_entry(cache, &info->block_groups[index], list) {
0f9dd46c 6727 spin_lock(&cache->lock);
efe120a0
FH
6728 printk(KERN_INFO "BTRFS: "
6729 "block group %llu has %llu bytes, "
6730 "%llu used %llu pinned %llu reserved %s\n",
c1c9ff7c
GU
6731 cache->key.objectid, cache->key.offset,
6732 btrfs_block_group_used(&cache->item), cache->pinned,
6733 cache->reserved, cache->ro ? "[readonly]" : "");
0f9dd46c
JB
6734 btrfs_dump_free_space(cache, bytes);
6735 spin_unlock(&cache->lock);
6736 }
b742bb82
YZ
6737 if (++index < BTRFS_NR_RAID_TYPES)
6738 goto again;
80eb234a 6739 up_read(&info->groups_sem);
0f9dd46c 6740}
e8569813 6741
00361589 6742int btrfs_reserve_extent(struct btrfs_root *root,
11833d66
YZ
6743 u64 num_bytes, u64 min_alloc_size,
6744 u64 empty_size, u64 hint_byte,
b6919a58 6745 struct btrfs_key *ins, int is_data)
fec577fb 6746{
9e622d6b 6747 bool final_tried = false;
b6919a58 6748 u64 flags;
fec577fb 6749 int ret;
925baedd 6750
b6919a58 6751 flags = btrfs_get_alloc_profile(root, is_data);
98d20f67 6752again:
db94535d 6753 WARN_ON(num_bytes < root->sectorsize);
00361589
JB
6754 ret = find_free_extent(root, num_bytes, empty_size, hint_byte, ins,
6755 flags);
3b951516 6756
9e622d6b 6757 if (ret == -ENOSPC) {
a4820398
MX
6758 if (!final_tried && ins->offset) {
6759 num_bytes = min(num_bytes >> 1, ins->offset);
24542bf7 6760 num_bytes = round_down(num_bytes, root->sectorsize);
9e622d6b 6761 num_bytes = max(num_bytes, min_alloc_size);
9e622d6b
MX
6762 if (num_bytes == min_alloc_size)
6763 final_tried = true;
6764 goto again;
6765 } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
6766 struct btrfs_space_info *sinfo;
6767
b6919a58 6768 sinfo = __find_space_info(root->fs_info, flags);
c2cf52eb 6769 btrfs_err(root->fs_info, "allocation failed flags %llu, wanted %llu",
c1c9ff7c 6770 flags, num_bytes);
53804280
JM
6771 if (sinfo)
6772 dump_space_info(sinfo, num_bytes, 1);
9e622d6b 6773 }
925baedd 6774 }
0f9dd46c
JB
6775
6776 return ret;
e6dcd2dc
CM
6777}
6778
e688b725
CM
6779static int __btrfs_free_reserved_extent(struct btrfs_root *root,
6780 u64 start, u64 len, int pin)
65b51a00 6781{
0f9dd46c 6782 struct btrfs_block_group_cache *cache;
1f3c79a2 6783 int ret = 0;
0f9dd46c 6784
0f9dd46c
JB
6785 cache = btrfs_lookup_block_group(root->fs_info, start);
6786 if (!cache) {
c2cf52eb 6787 btrfs_err(root->fs_info, "Unable to find block group for %llu",
c1c9ff7c 6788 start);
0f9dd46c
JB
6789 return -ENOSPC;
6790 }
1f3c79a2 6791
5378e607
LD
6792 if (btrfs_test_opt(root, DISCARD))
6793 ret = btrfs_discard_extent(root, start, len, NULL);
1f3c79a2 6794
e688b725
CM
6795 if (pin)
6796 pin_down_extent(root, cache, start, len, 1);
6797 else {
6798 btrfs_add_free_space(cache, start, len);
6799 btrfs_update_reserved_bytes(cache, len, RESERVE_FREE);
6800 }
fa9c0d79 6801 btrfs_put_block_group(cache);
817d52f8 6802
1abe9b8a 6803 trace_btrfs_reserved_extent_free(root, start, len);
6804
e6dcd2dc
CM
6805 return ret;
6806}
6807
e688b725
CM
6808int btrfs_free_reserved_extent(struct btrfs_root *root,
6809 u64 start, u64 len)
6810{
6811 return __btrfs_free_reserved_extent(root, start, len, 0);
6812}
6813
6814int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
6815 u64 start, u64 len)
6816{
6817 return __btrfs_free_reserved_extent(root, start, len, 1);
6818}
6819
5d4f98a2
YZ
6820static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6821 struct btrfs_root *root,
6822 u64 parent, u64 root_objectid,
6823 u64 flags, u64 owner, u64 offset,
6824 struct btrfs_key *ins, int ref_mod)
e6dcd2dc
CM
6825{
6826 int ret;
5d4f98a2 6827 struct btrfs_fs_info *fs_info = root->fs_info;
e6dcd2dc 6828 struct btrfs_extent_item *extent_item;
5d4f98a2 6829 struct btrfs_extent_inline_ref *iref;
e6dcd2dc 6830 struct btrfs_path *path;
5d4f98a2
YZ
6831 struct extent_buffer *leaf;
6832 int type;
6833 u32 size;
26b8003f 6834
5d4f98a2
YZ
6835 if (parent > 0)
6836 type = BTRFS_SHARED_DATA_REF_KEY;
6837 else
6838 type = BTRFS_EXTENT_DATA_REF_KEY;
58176a96 6839
5d4f98a2 6840 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7bb86316
CM
6841
6842 path = btrfs_alloc_path();
db5b493a
TI
6843 if (!path)
6844 return -ENOMEM;
47e4bb98 6845
b9473439 6846 path->leave_spinning = 1;
5d4f98a2
YZ
6847 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6848 ins, size);
79787eaa
JM
6849 if (ret) {
6850 btrfs_free_path(path);
6851 return ret;
6852 }
0f9dd46c 6853
5d4f98a2
YZ
6854 leaf = path->nodes[0];
6855 extent_item = btrfs_item_ptr(leaf, path->slots[0],
47e4bb98 6856 struct btrfs_extent_item);
5d4f98a2
YZ
6857 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
6858 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6859 btrfs_set_extent_flags(leaf, extent_item,
6860 flags | BTRFS_EXTENT_FLAG_DATA);
6861
6862 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
6863 btrfs_set_extent_inline_ref_type(leaf, iref, type);
6864 if (parent > 0) {
6865 struct btrfs_shared_data_ref *ref;
6866 ref = (struct btrfs_shared_data_ref *)(iref + 1);
6867 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6868 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
6869 } else {
6870 struct btrfs_extent_data_ref *ref;
6871 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
6872 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
6873 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
6874 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
6875 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
6876 }
47e4bb98
CM
6877
6878 btrfs_mark_buffer_dirty(path->nodes[0]);
7bb86316 6879 btrfs_free_path(path);
f510cfec 6880
fcebe456
JB
6881 /* Always set parent to 0 here since its exclusive anyway. */
6882 ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
6883 ins->objectid, ins->offset,
6884 BTRFS_QGROUP_OPER_ADD_EXCL, 0);
6885 if (ret)
6886 return ret;
6887
c53d613e 6888 ret = update_block_group(root, ins->objectid, ins->offset, 1);
79787eaa 6889 if (ret) { /* -ENOENT, logic error */
c2cf52eb 6890 btrfs_err(fs_info, "update block group failed for %llu %llu",
c1c9ff7c 6891 ins->objectid, ins->offset);
f5947066
CM
6892 BUG();
6893 }
0be5dc67 6894 trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
e6dcd2dc
CM
6895 return ret;
6896}
6897
5d4f98a2
YZ
6898static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
6899 struct btrfs_root *root,
6900 u64 parent, u64 root_objectid,
6901 u64 flags, struct btrfs_disk_key *key,
fcebe456
JB
6902 int level, struct btrfs_key *ins,
6903 int no_quota)
e6dcd2dc
CM
6904{
6905 int ret;
5d4f98a2
YZ
6906 struct btrfs_fs_info *fs_info = root->fs_info;
6907 struct btrfs_extent_item *extent_item;
6908 struct btrfs_tree_block_info *block_info;
6909 struct btrfs_extent_inline_ref *iref;
6910 struct btrfs_path *path;
6911 struct extent_buffer *leaf;
3173a18f 6912 u32 size = sizeof(*extent_item) + sizeof(*iref);
fcebe456 6913 u64 num_bytes = ins->offset;
3173a18f
JB
6914 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
6915 SKINNY_METADATA);
6916
6917 if (!skinny_metadata)
6918 size += sizeof(*block_info);
1c2308f8 6919
5d4f98a2 6920 path = btrfs_alloc_path();
857cc2fc
JB
6921 if (!path) {
6922 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
6923 root->leafsize);
d8926bb3 6924 return -ENOMEM;
857cc2fc 6925 }
56bec294 6926
5d4f98a2
YZ
6927 path->leave_spinning = 1;
6928 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
6929 ins, size);
79787eaa 6930 if (ret) {
857cc2fc
JB
6931 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
6932 root->leafsize);
79787eaa
JM
6933 btrfs_free_path(path);
6934 return ret;
6935 }
5d4f98a2
YZ
6936
6937 leaf = path->nodes[0];
6938 extent_item = btrfs_item_ptr(leaf, path->slots[0],
6939 struct btrfs_extent_item);
6940 btrfs_set_extent_refs(leaf, extent_item, 1);
6941 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
6942 btrfs_set_extent_flags(leaf, extent_item,
6943 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
5d4f98a2 6944
3173a18f
JB
6945 if (skinny_metadata) {
6946 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
fcebe456 6947 num_bytes = root->leafsize;
3173a18f
JB
6948 } else {
6949 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
6950 btrfs_set_tree_block_key(leaf, block_info, key);
6951 btrfs_set_tree_block_level(leaf, block_info, level);
6952 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
6953 }
5d4f98a2 6954
5d4f98a2
YZ
6955 if (parent > 0) {
6956 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
6957 btrfs_set_extent_inline_ref_type(leaf, iref,
6958 BTRFS_SHARED_BLOCK_REF_KEY);
6959 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
6960 } else {
6961 btrfs_set_extent_inline_ref_type(leaf, iref,
6962 BTRFS_TREE_BLOCK_REF_KEY);
6963 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
6964 }
6965
6966 btrfs_mark_buffer_dirty(leaf);
6967 btrfs_free_path(path);
6968
fcebe456
JB
6969 if (!no_quota) {
6970 ret = btrfs_qgroup_record_ref(trans, fs_info, root_objectid,
6971 ins->objectid, num_bytes,
6972 BTRFS_QGROUP_OPER_ADD_EXCL, 0);
6973 if (ret)
6974 return ret;
6975 }
6976
3173a18f 6977 ret = update_block_group(root, ins->objectid, root->leafsize, 1);
79787eaa 6978 if (ret) { /* -ENOENT, logic error */
c2cf52eb 6979 btrfs_err(fs_info, "update block group failed for %llu %llu",
c1c9ff7c 6980 ins->objectid, ins->offset);
5d4f98a2
YZ
6981 BUG();
6982 }
0be5dc67
JB
6983
6984 trace_btrfs_reserved_extent_alloc(root, ins->objectid, root->leafsize);
5d4f98a2
YZ
6985 return ret;
6986}
6987
6988int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
6989 struct btrfs_root *root,
6990 u64 root_objectid, u64 owner,
6991 u64 offset, struct btrfs_key *ins)
6992{
6993 int ret;
6994
6995 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
6996
66d7e7f0
AJ
6997 ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
6998 ins->offset, 0,
6999 root_objectid, owner, offset,
7000 BTRFS_ADD_DELAYED_EXTENT, NULL, 0);
e6dcd2dc
CM
7001 return ret;
7002}
e02119d5
CM
7003
7004/*
7005 * this is used by the tree logging recovery code. It records that
7006 * an extent has been allocated and makes sure to clear the free
7007 * space cache bits as well
7008 */
5d4f98a2
YZ
7009int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
7010 struct btrfs_root *root,
7011 u64 root_objectid, u64 owner, u64 offset,
7012 struct btrfs_key *ins)
e02119d5
CM
7013{
7014 int ret;
7015 struct btrfs_block_group_cache *block_group;
11833d66 7016
8c2a1a30
JB
7017 /*
7018 * Mixed block groups will exclude before processing the log so we only
7019 * need to do the exlude dance if this fs isn't mixed.
7020 */
7021 if (!btrfs_fs_incompat(root->fs_info, MIXED_GROUPS)) {
7022 ret = __exclude_logged_extent(root, ins->objectid, ins->offset);
b50c6e25 7023 if (ret)
8c2a1a30 7024 return ret;
11833d66
YZ
7025 }
7026
8c2a1a30
JB
7027 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
7028 if (!block_group)
7029 return -EINVAL;
7030
fb25e914
JB
7031 ret = btrfs_update_reserved_bytes(block_group, ins->offset,
7032 RESERVE_ALLOC_NO_ACCOUNT);
79787eaa 7033 BUG_ON(ret); /* logic error */
5d4f98a2
YZ
7034 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
7035 0, owner, offset, ins, 1);
b50c6e25 7036 btrfs_put_block_group(block_group);
e02119d5
CM
7037 return ret;
7038}
7039
48a3b636
ES
7040static struct extent_buffer *
7041btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
7042 u64 bytenr, u32 blocksize, int level)
65b51a00
CM
7043{
7044 struct extent_buffer *buf;
7045
7046 buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
7047 if (!buf)
7048 return ERR_PTR(-ENOMEM);
7049 btrfs_set_header_generation(buf, trans->transid);
85d4e461 7050 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
65b51a00
CM
7051 btrfs_tree_lock(buf);
7052 clean_tree_block(trans, root, buf);
3083ee2e 7053 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
b4ce94de
CM
7054
7055 btrfs_set_lock_blocking(buf);
65b51a00 7056 btrfs_set_buffer_uptodate(buf);
b4ce94de 7057
d0c803c4 7058 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
8cef4e16
YZ
7059 /*
7060 * we allow two log transactions at a time, use different
7061 * EXENT bit to differentiate dirty pages.
7062 */
7063 if (root->log_transid % 2 == 0)
7064 set_extent_dirty(&root->dirty_log_pages, buf->start,
7065 buf->start + buf->len - 1, GFP_NOFS);
7066 else
7067 set_extent_new(&root->dirty_log_pages, buf->start,
7068 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4
CM
7069 } else {
7070 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
65b51a00 7071 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4 7072 }
65b51a00 7073 trans->blocks_used++;
b4ce94de 7074 /* this returns a buffer locked for blocking */
65b51a00
CM
7075 return buf;
7076}
7077
f0486c68
YZ
7078static struct btrfs_block_rsv *
7079use_block_rsv(struct btrfs_trans_handle *trans,
7080 struct btrfs_root *root, u32 blocksize)
7081{
7082 struct btrfs_block_rsv *block_rsv;
68a82277 7083 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
f0486c68 7084 int ret;
d88033db 7085 bool global_updated = false;
f0486c68
YZ
7086
7087 block_rsv = get_block_rsv(trans, root);
7088
b586b323
MX
7089 if (unlikely(block_rsv->size == 0))
7090 goto try_reserve;
d88033db 7091again:
f0486c68
YZ
7092 ret = block_rsv_use_bytes(block_rsv, blocksize);
7093 if (!ret)
7094 return block_rsv;
7095
b586b323
MX
7096 if (block_rsv->failfast)
7097 return ERR_PTR(ret);
7098
d88033db
MX
7099 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
7100 global_updated = true;
7101 update_global_block_rsv(root->fs_info);
7102 goto again;
7103 }
7104
b586b323
MX
7105 if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
7106 static DEFINE_RATELIMIT_STATE(_rs,
7107 DEFAULT_RATELIMIT_INTERVAL * 10,
7108 /*DEFAULT_RATELIMIT_BURST*/ 1);
7109 if (__ratelimit(&_rs))
7110 WARN(1, KERN_DEBUG
efe120a0 7111 "BTRFS: block rsv returned %d\n", ret);
b586b323
MX
7112 }
7113try_reserve:
7114 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
7115 BTRFS_RESERVE_NO_FLUSH);
7116 if (!ret)
7117 return block_rsv;
7118 /*
7119 * If we couldn't reserve metadata bytes try and use some from
5881cfc9
MX
7120 * the global reserve if its space type is the same as the global
7121 * reservation.
b586b323 7122 */
5881cfc9
MX
7123 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
7124 block_rsv->space_info == global_rsv->space_info) {
b586b323
MX
7125 ret = block_rsv_use_bytes(global_rsv, blocksize);
7126 if (!ret)
7127 return global_rsv;
7128 }
7129 return ERR_PTR(ret);
f0486c68
YZ
7130}
7131
8c2a3ca2
JB
7132static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
7133 struct btrfs_block_rsv *block_rsv, u32 blocksize)
f0486c68
YZ
7134{
7135 block_rsv_add_bytes(block_rsv, blocksize, 0);
8c2a3ca2 7136 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
f0486c68
YZ
7137}
7138
fec577fb 7139/*
f0486c68
YZ
7140 * finds a free extent and does all the dirty work required for allocation
7141 * returns the key for the extent through ins, and a tree buffer for
7142 * the first block of the extent through buf.
7143 *
fec577fb
CM
7144 * returns the tree buffer or NULL.
7145 */
5f39d397 7146struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
5d4f98a2
YZ
7147 struct btrfs_root *root, u32 blocksize,
7148 u64 parent, u64 root_objectid,
7149 struct btrfs_disk_key *key, int level,
5581a51a 7150 u64 hint, u64 empty_size)
fec577fb 7151{
e2fa7227 7152 struct btrfs_key ins;
f0486c68 7153 struct btrfs_block_rsv *block_rsv;
5f39d397 7154 struct extent_buffer *buf;
f0486c68
YZ
7155 u64 flags = 0;
7156 int ret;
3173a18f
JB
7157 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
7158 SKINNY_METADATA);
fec577fb 7159
f0486c68
YZ
7160 block_rsv = use_block_rsv(trans, root, blocksize);
7161 if (IS_ERR(block_rsv))
7162 return ERR_CAST(block_rsv);
7163
00361589 7164 ret = btrfs_reserve_extent(root, blocksize, blocksize,
81c9ad23 7165 empty_size, hint, &ins, 0);
fec577fb 7166 if (ret) {
8c2a3ca2 7167 unuse_block_rsv(root->fs_info, block_rsv, blocksize);
54aa1f4d 7168 return ERR_PTR(ret);
fec577fb 7169 }
55c69072 7170
4008c04a
CM
7171 buf = btrfs_init_new_buffer(trans, root, ins.objectid,
7172 blocksize, level);
79787eaa 7173 BUG_ON(IS_ERR(buf)); /* -ENOMEM */
f0486c68
YZ
7174
7175 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
7176 if (parent == 0)
7177 parent = ins.objectid;
7178 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7179 } else
7180 BUG_ON(parent > 0);
7181
7182 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
7183 struct btrfs_delayed_extent_op *extent_op;
78a6184a 7184 extent_op = btrfs_alloc_delayed_extent_op();
79787eaa 7185 BUG_ON(!extent_op); /* -ENOMEM */
f0486c68
YZ
7186 if (key)
7187 memcpy(&extent_op->key, key, sizeof(extent_op->key));
7188 else
7189 memset(&extent_op->key, 0, sizeof(extent_op->key));
7190 extent_op->flags_to_set = flags;
3173a18f
JB
7191 if (skinny_metadata)
7192 extent_op->update_key = 0;
7193 else
7194 extent_op->update_key = 1;
f0486c68
YZ
7195 extent_op->update_flags = 1;
7196 extent_op->is_data = 0;
b1c79e09 7197 extent_op->level = level;
f0486c68 7198
66d7e7f0
AJ
7199 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
7200 ins.objectid,
f0486c68
YZ
7201 ins.offset, parent, root_objectid,
7202 level, BTRFS_ADD_DELAYED_EXTENT,
5581a51a 7203 extent_op, 0);
79787eaa 7204 BUG_ON(ret); /* -ENOMEM */
f0486c68 7205 }
fec577fb
CM
7206 return buf;
7207}
a28ec197 7208
2c47e605
YZ
7209struct walk_control {
7210 u64 refs[BTRFS_MAX_LEVEL];
7211 u64 flags[BTRFS_MAX_LEVEL];
7212 struct btrfs_key update_progress;
7213 int stage;
7214 int level;
7215 int shared_level;
7216 int update_ref;
7217 int keep_locks;
1c4850e2
YZ
7218 int reada_slot;
7219 int reada_count;
66d7e7f0 7220 int for_reloc;
2c47e605
YZ
7221};
7222
7223#define DROP_REFERENCE 1
7224#define UPDATE_BACKREF 2
7225
1c4850e2
YZ
7226static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
7227 struct btrfs_root *root,
7228 struct walk_control *wc,
7229 struct btrfs_path *path)
6407bf6d 7230{
1c4850e2
YZ
7231 u64 bytenr;
7232 u64 generation;
7233 u64 refs;
94fcca9f 7234 u64 flags;
5d4f98a2 7235 u32 nritems;
1c4850e2
YZ
7236 u32 blocksize;
7237 struct btrfs_key key;
7238 struct extent_buffer *eb;
6407bf6d 7239 int ret;
1c4850e2
YZ
7240 int slot;
7241 int nread = 0;
6407bf6d 7242
1c4850e2
YZ
7243 if (path->slots[wc->level] < wc->reada_slot) {
7244 wc->reada_count = wc->reada_count * 2 / 3;
7245 wc->reada_count = max(wc->reada_count, 2);
7246 } else {
7247 wc->reada_count = wc->reada_count * 3 / 2;
7248 wc->reada_count = min_t(int, wc->reada_count,
7249 BTRFS_NODEPTRS_PER_BLOCK(root));
7250 }
7bb86316 7251
1c4850e2
YZ
7252 eb = path->nodes[wc->level];
7253 nritems = btrfs_header_nritems(eb);
7254 blocksize = btrfs_level_size(root, wc->level - 1);
bd56b302 7255
1c4850e2
YZ
7256 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
7257 if (nread >= wc->reada_count)
7258 break;
bd56b302 7259
2dd3e67b 7260 cond_resched();
1c4850e2
YZ
7261 bytenr = btrfs_node_blockptr(eb, slot);
7262 generation = btrfs_node_ptr_generation(eb, slot);
2dd3e67b 7263
1c4850e2
YZ
7264 if (slot == path->slots[wc->level])
7265 goto reada;
5d4f98a2 7266
1c4850e2
YZ
7267 if (wc->stage == UPDATE_BACKREF &&
7268 generation <= root->root_key.offset)
bd56b302
CM
7269 continue;
7270
94fcca9f 7271 /* We don't lock the tree block, it's OK to be racy here */
3173a18f
JB
7272 ret = btrfs_lookup_extent_info(trans, root, bytenr,
7273 wc->level - 1, 1, &refs,
7274 &flags);
79787eaa
JM
7275 /* We don't care about errors in readahead. */
7276 if (ret < 0)
7277 continue;
94fcca9f
YZ
7278 BUG_ON(refs == 0);
7279
1c4850e2 7280 if (wc->stage == DROP_REFERENCE) {
1c4850e2
YZ
7281 if (refs == 1)
7282 goto reada;
bd56b302 7283
94fcca9f
YZ
7284 if (wc->level == 1 &&
7285 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7286 continue;
1c4850e2
YZ
7287 if (!wc->update_ref ||
7288 generation <= root->root_key.offset)
7289 continue;
7290 btrfs_node_key_to_cpu(eb, &key, slot);
7291 ret = btrfs_comp_cpu_keys(&key,
7292 &wc->update_progress);
7293 if (ret < 0)
7294 continue;
94fcca9f
YZ
7295 } else {
7296 if (wc->level == 1 &&
7297 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7298 continue;
6407bf6d 7299 }
1c4850e2
YZ
7300reada:
7301 ret = readahead_tree_block(root, bytenr, blocksize,
7302 generation);
7303 if (ret)
bd56b302 7304 break;
1c4850e2 7305 nread++;
20524f02 7306 }
1c4850e2 7307 wc->reada_slot = slot;
20524f02 7308}
2c47e605 7309
f82d02d9 7310/*
2c016dc2 7311 * helper to process tree block while walking down the tree.
2c47e605 7312 *
2c47e605
YZ
7313 * when wc->stage == UPDATE_BACKREF, this function updates
7314 * back refs for pointers in the block.
7315 *
7316 * NOTE: return value 1 means we should stop walking down.
f82d02d9 7317 */
2c47e605 7318static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5d4f98a2 7319 struct btrfs_root *root,
2c47e605 7320 struct btrfs_path *path,
94fcca9f 7321 struct walk_control *wc, int lookup_info)
f82d02d9 7322{
2c47e605
YZ
7323 int level = wc->level;
7324 struct extent_buffer *eb = path->nodes[level];
2c47e605 7325 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
f82d02d9
YZ
7326 int ret;
7327
2c47e605
YZ
7328 if (wc->stage == UPDATE_BACKREF &&
7329 btrfs_header_owner(eb) != root->root_key.objectid)
7330 return 1;
f82d02d9 7331
2c47e605
YZ
7332 /*
7333 * when reference count of tree block is 1, it won't increase
7334 * again. once full backref flag is set, we never clear it.
7335 */
94fcca9f
YZ
7336 if (lookup_info &&
7337 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
7338 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
2c47e605
YZ
7339 BUG_ON(!path->locks[level]);
7340 ret = btrfs_lookup_extent_info(trans, root,
3173a18f 7341 eb->start, level, 1,
2c47e605
YZ
7342 &wc->refs[level],
7343 &wc->flags[level]);
79787eaa
JM
7344 BUG_ON(ret == -ENOMEM);
7345 if (ret)
7346 return ret;
2c47e605
YZ
7347 BUG_ON(wc->refs[level] == 0);
7348 }
5d4f98a2 7349
2c47e605
YZ
7350 if (wc->stage == DROP_REFERENCE) {
7351 if (wc->refs[level] > 1)
7352 return 1;
f82d02d9 7353
2c47e605 7354 if (path->locks[level] && !wc->keep_locks) {
bd681513 7355 btrfs_tree_unlock_rw(eb, path->locks[level]);
2c47e605
YZ
7356 path->locks[level] = 0;
7357 }
7358 return 0;
7359 }
f82d02d9 7360
2c47e605
YZ
7361 /* wc->stage == UPDATE_BACKREF */
7362 if (!(wc->flags[level] & flag)) {
7363 BUG_ON(!path->locks[level]);
66d7e7f0 7364 ret = btrfs_inc_ref(trans, root, eb, 1, wc->for_reloc);
79787eaa 7365 BUG_ON(ret); /* -ENOMEM */
66d7e7f0 7366 ret = btrfs_dec_ref(trans, root, eb, 0, wc->for_reloc);
79787eaa 7367 BUG_ON(ret); /* -ENOMEM */
2c47e605 7368 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
b1c79e09
JB
7369 eb->len, flag,
7370 btrfs_header_level(eb), 0);
79787eaa 7371 BUG_ON(ret); /* -ENOMEM */
2c47e605
YZ
7372 wc->flags[level] |= flag;
7373 }
7374
7375 /*
7376 * the block is shared by multiple trees, so it's not good to
7377 * keep the tree lock
7378 */
7379 if (path->locks[level] && level > 0) {
bd681513 7380 btrfs_tree_unlock_rw(eb, path->locks[level]);
2c47e605
YZ
7381 path->locks[level] = 0;
7382 }
7383 return 0;
7384}
7385
1c4850e2 7386/*
2c016dc2 7387 * helper to process tree block pointer.
1c4850e2
YZ
7388 *
7389 * when wc->stage == DROP_REFERENCE, this function checks
7390 * reference count of the block pointed to. if the block
7391 * is shared and we need update back refs for the subtree
7392 * rooted at the block, this function changes wc->stage to
7393 * UPDATE_BACKREF. if the block is shared and there is no
7394 * need to update back, this function drops the reference
7395 * to the block.
7396 *
7397 * NOTE: return value 1 means we should stop walking down.
7398 */
7399static noinline int do_walk_down(struct btrfs_trans_handle *trans,
7400 struct btrfs_root *root,
7401 struct btrfs_path *path,
94fcca9f 7402 struct walk_control *wc, int *lookup_info)
1c4850e2
YZ
7403{
7404 u64 bytenr;
7405 u64 generation;
7406 u64 parent;
7407 u32 blocksize;
7408 struct btrfs_key key;
7409 struct extent_buffer *next;
7410 int level = wc->level;
7411 int reada = 0;
7412 int ret = 0;
7413
7414 generation = btrfs_node_ptr_generation(path->nodes[level],
7415 path->slots[level]);
7416 /*
7417 * if the lower level block was created before the snapshot
7418 * was created, we know there is no need to update back refs
7419 * for the subtree
7420 */
7421 if (wc->stage == UPDATE_BACKREF &&
94fcca9f
YZ
7422 generation <= root->root_key.offset) {
7423 *lookup_info = 1;
1c4850e2 7424 return 1;
94fcca9f 7425 }
1c4850e2
YZ
7426
7427 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
7428 blocksize = btrfs_level_size(root, level - 1);
7429
7430 next = btrfs_find_tree_block(root, bytenr, blocksize);
7431 if (!next) {
7432 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
90d2c51d
MX
7433 if (!next)
7434 return -ENOMEM;
b2aaaa3b
JB
7435 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
7436 level - 1);
1c4850e2
YZ
7437 reada = 1;
7438 }
7439 btrfs_tree_lock(next);
7440 btrfs_set_lock_blocking(next);
7441
3173a18f 7442 ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
94fcca9f
YZ
7443 &wc->refs[level - 1],
7444 &wc->flags[level - 1]);
79787eaa
JM
7445 if (ret < 0) {
7446 btrfs_tree_unlock(next);
7447 return ret;
7448 }
7449
c2cf52eb
SK
7450 if (unlikely(wc->refs[level - 1] == 0)) {
7451 btrfs_err(root->fs_info, "Missing references.");
7452 BUG();
7453 }
94fcca9f 7454 *lookup_info = 0;
1c4850e2 7455
94fcca9f 7456 if (wc->stage == DROP_REFERENCE) {
1c4850e2 7457 if (wc->refs[level - 1] > 1) {
94fcca9f
YZ
7458 if (level == 1 &&
7459 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7460 goto skip;
7461
1c4850e2
YZ
7462 if (!wc->update_ref ||
7463 generation <= root->root_key.offset)
7464 goto skip;
7465
7466 btrfs_node_key_to_cpu(path->nodes[level], &key,
7467 path->slots[level]);
7468 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
7469 if (ret < 0)
7470 goto skip;
7471
7472 wc->stage = UPDATE_BACKREF;
7473 wc->shared_level = level - 1;
7474 }
94fcca9f
YZ
7475 } else {
7476 if (level == 1 &&
7477 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
7478 goto skip;
1c4850e2
YZ
7479 }
7480
b9fab919 7481 if (!btrfs_buffer_uptodate(next, generation, 0)) {
1c4850e2
YZ
7482 btrfs_tree_unlock(next);
7483 free_extent_buffer(next);
7484 next = NULL;
94fcca9f 7485 *lookup_info = 1;
1c4850e2
YZ
7486 }
7487
7488 if (!next) {
7489 if (reada && level == 1)
7490 reada_walk_down(trans, root, wc, path);
7491 next = read_tree_block(root, bytenr, blocksize, generation);
416bc658
JB
7492 if (!next || !extent_buffer_uptodate(next)) {
7493 free_extent_buffer(next);
97d9a8a4 7494 return -EIO;
416bc658 7495 }
1c4850e2
YZ
7496 btrfs_tree_lock(next);
7497 btrfs_set_lock_blocking(next);
7498 }
7499
7500 level--;
7501 BUG_ON(level != btrfs_header_level(next));
7502 path->nodes[level] = next;
7503 path->slots[level] = 0;
bd681513 7504 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
1c4850e2
YZ
7505 wc->level = level;
7506 if (wc->level == 1)
7507 wc->reada_slot = 0;
7508 return 0;
7509skip:
7510 wc->refs[level - 1] = 0;
7511 wc->flags[level - 1] = 0;
94fcca9f
YZ
7512 if (wc->stage == DROP_REFERENCE) {
7513 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
7514 parent = path->nodes[level]->start;
7515 } else {
7516 BUG_ON(root->root_key.objectid !=
7517 btrfs_header_owner(path->nodes[level]));
7518 parent = 0;
7519 }
1c4850e2 7520
94fcca9f 7521 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
66d7e7f0 7522 root->root_key.objectid, level - 1, 0, 0);
79787eaa 7523 BUG_ON(ret); /* -ENOMEM */
1c4850e2 7524 }
1c4850e2
YZ
7525 btrfs_tree_unlock(next);
7526 free_extent_buffer(next);
94fcca9f 7527 *lookup_info = 1;
1c4850e2
YZ
7528 return 1;
7529}
7530
2c47e605 7531/*
2c016dc2 7532 * helper to process tree block while walking up the tree.
2c47e605
YZ
7533 *
7534 * when wc->stage == DROP_REFERENCE, this function drops
7535 * reference count on the block.
7536 *
7537 * when wc->stage == UPDATE_BACKREF, this function changes
7538 * wc->stage back to DROP_REFERENCE if we changed wc->stage
7539 * to UPDATE_BACKREF previously while processing the block.
7540 *
7541 * NOTE: return value 1 means we should stop walking up.
7542 */
7543static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
7544 struct btrfs_root *root,
7545 struct btrfs_path *path,
7546 struct walk_control *wc)
7547{
f0486c68 7548 int ret;
2c47e605
YZ
7549 int level = wc->level;
7550 struct extent_buffer *eb = path->nodes[level];
7551 u64 parent = 0;
7552
7553 if (wc->stage == UPDATE_BACKREF) {
7554 BUG_ON(wc->shared_level < level);
7555 if (level < wc->shared_level)
7556 goto out;
7557
2c47e605
YZ
7558 ret = find_next_key(path, level + 1, &wc->update_progress);
7559 if (ret > 0)
7560 wc->update_ref = 0;
7561
7562 wc->stage = DROP_REFERENCE;
7563 wc->shared_level = -1;
7564 path->slots[level] = 0;
7565
7566 /*
7567 * check reference count again if the block isn't locked.
7568 * we should start walking down the tree again if reference
7569 * count is one.
7570 */
7571 if (!path->locks[level]) {
7572 BUG_ON(level == 0);
7573 btrfs_tree_lock(eb);
7574 btrfs_set_lock_blocking(eb);
bd681513 7575 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
7576
7577 ret = btrfs_lookup_extent_info(trans, root,
3173a18f 7578 eb->start, level, 1,
2c47e605
YZ
7579 &wc->refs[level],
7580 &wc->flags[level]);
79787eaa
JM
7581 if (ret < 0) {
7582 btrfs_tree_unlock_rw(eb, path->locks[level]);
3268a246 7583 path->locks[level] = 0;
79787eaa
JM
7584 return ret;
7585 }
2c47e605
YZ
7586 BUG_ON(wc->refs[level] == 0);
7587 if (wc->refs[level] == 1) {
bd681513 7588 btrfs_tree_unlock_rw(eb, path->locks[level]);
3268a246 7589 path->locks[level] = 0;
2c47e605
YZ
7590 return 1;
7591 }
f82d02d9 7592 }
2c47e605 7593 }
f82d02d9 7594
2c47e605
YZ
7595 /* wc->stage == DROP_REFERENCE */
7596 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5d4f98a2 7597
2c47e605
YZ
7598 if (wc->refs[level] == 1) {
7599 if (level == 0) {
7600 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
66d7e7f0
AJ
7601 ret = btrfs_dec_ref(trans, root, eb, 1,
7602 wc->for_reloc);
2c47e605 7603 else
66d7e7f0
AJ
7604 ret = btrfs_dec_ref(trans, root, eb, 0,
7605 wc->for_reloc);
79787eaa 7606 BUG_ON(ret); /* -ENOMEM */
2c47e605
YZ
7607 }
7608 /* make block locked assertion in clean_tree_block happy */
7609 if (!path->locks[level] &&
7610 btrfs_header_generation(eb) == trans->transid) {
7611 btrfs_tree_lock(eb);
7612 btrfs_set_lock_blocking(eb);
bd681513 7613 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
7614 }
7615 clean_tree_block(trans, root, eb);
7616 }
7617
7618 if (eb == root->node) {
7619 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7620 parent = eb->start;
7621 else
7622 BUG_ON(root->root_key.objectid !=
7623 btrfs_header_owner(eb));
7624 } else {
7625 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
7626 parent = path->nodes[level + 1]->start;
7627 else
7628 BUG_ON(root->root_key.objectid !=
7629 btrfs_header_owner(path->nodes[level + 1]));
f82d02d9 7630 }
f82d02d9 7631
5581a51a 7632 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
2c47e605
YZ
7633out:
7634 wc->refs[level] = 0;
7635 wc->flags[level] = 0;
f0486c68 7636 return 0;
2c47e605
YZ
7637}
7638
7639static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
7640 struct btrfs_root *root,
7641 struct btrfs_path *path,
7642 struct walk_control *wc)
7643{
2c47e605 7644 int level = wc->level;
94fcca9f 7645 int lookup_info = 1;
2c47e605
YZ
7646 int ret;
7647
7648 while (level >= 0) {
94fcca9f 7649 ret = walk_down_proc(trans, root, path, wc, lookup_info);
2c47e605
YZ
7650 if (ret > 0)
7651 break;
7652
7653 if (level == 0)
7654 break;
7655
7a7965f8
YZ
7656 if (path->slots[level] >=
7657 btrfs_header_nritems(path->nodes[level]))
7658 break;
7659
94fcca9f 7660 ret = do_walk_down(trans, root, path, wc, &lookup_info);
1c4850e2
YZ
7661 if (ret > 0) {
7662 path->slots[level]++;
7663 continue;
90d2c51d
MX
7664 } else if (ret < 0)
7665 return ret;
1c4850e2 7666 level = wc->level;
f82d02d9 7667 }
f82d02d9
YZ
7668 return 0;
7669}
7670
d397712b 7671static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
98ed5174 7672 struct btrfs_root *root,
f82d02d9 7673 struct btrfs_path *path,
2c47e605 7674 struct walk_control *wc, int max_level)
20524f02 7675{
2c47e605 7676 int level = wc->level;
20524f02 7677 int ret;
9f3a7427 7678
2c47e605
YZ
7679 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
7680 while (level < max_level && path->nodes[level]) {
7681 wc->level = level;
7682 if (path->slots[level] + 1 <
7683 btrfs_header_nritems(path->nodes[level])) {
7684 path->slots[level]++;
20524f02
CM
7685 return 0;
7686 } else {
2c47e605
YZ
7687 ret = walk_up_proc(trans, root, path, wc);
7688 if (ret > 0)
7689 return 0;
bd56b302 7690
2c47e605 7691 if (path->locks[level]) {
bd681513
CM
7692 btrfs_tree_unlock_rw(path->nodes[level],
7693 path->locks[level]);
2c47e605 7694 path->locks[level] = 0;
f82d02d9 7695 }
2c47e605
YZ
7696 free_extent_buffer(path->nodes[level]);
7697 path->nodes[level] = NULL;
7698 level++;
20524f02
CM
7699 }
7700 }
7701 return 1;
7702}
7703
9aca1d51 7704/*
2c47e605
YZ
7705 * drop a subvolume tree.
7706 *
7707 * this function traverses the tree freeing any blocks that only
7708 * referenced by the tree.
7709 *
7710 * when a shared tree block is found. this function decreases its
7711 * reference count by one. if update_ref is true, this function
7712 * also make sure backrefs for the shared block and all lower level
7713 * blocks are properly updated.
9d1a2a3a
DS
7714 *
7715 * If called with for_reloc == 0, may exit early with -EAGAIN
9aca1d51 7716 */
2c536799 7717int btrfs_drop_snapshot(struct btrfs_root *root,
66d7e7f0
AJ
7718 struct btrfs_block_rsv *block_rsv, int update_ref,
7719 int for_reloc)
20524f02 7720{
5caf2a00 7721 struct btrfs_path *path;
2c47e605
YZ
7722 struct btrfs_trans_handle *trans;
7723 struct btrfs_root *tree_root = root->fs_info->tree_root;
9f3a7427 7724 struct btrfs_root_item *root_item = &root->root_item;
2c47e605
YZ
7725 struct walk_control *wc;
7726 struct btrfs_key key;
7727 int err = 0;
7728 int ret;
7729 int level;
d29a9f62 7730 bool root_dropped = false;
20524f02 7731
5caf2a00 7732 path = btrfs_alloc_path();
cb1b69f4
TI
7733 if (!path) {
7734 err = -ENOMEM;
7735 goto out;
7736 }
20524f02 7737
2c47e605 7738 wc = kzalloc(sizeof(*wc), GFP_NOFS);
38a1a919
MF
7739 if (!wc) {
7740 btrfs_free_path(path);
cb1b69f4
TI
7741 err = -ENOMEM;
7742 goto out;
38a1a919 7743 }
2c47e605 7744
a22285a6 7745 trans = btrfs_start_transaction(tree_root, 0);
79787eaa
JM
7746 if (IS_ERR(trans)) {
7747 err = PTR_ERR(trans);
7748 goto out_free;
7749 }
98d5dc13 7750
3fd0a558
YZ
7751 if (block_rsv)
7752 trans->block_rsv = block_rsv;
2c47e605 7753
9f3a7427 7754 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
2c47e605 7755 level = btrfs_header_level(root->node);
5d4f98a2
YZ
7756 path->nodes[level] = btrfs_lock_root_node(root);
7757 btrfs_set_lock_blocking(path->nodes[level]);
9f3a7427 7758 path->slots[level] = 0;
bd681513 7759 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
7760 memset(&wc->update_progress, 0,
7761 sizeof(wc->update_progress));
9f3a7427 7762 } else {
9f3a7427 7763 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
2c47e605
YZ
7764 memcpy(&wc->update_progress, &key,
7765 sizeof(wc->update_progress));
7766
6702ed49 7767 level = root_item->drop_level;
2c47e605 7768 BUG_ON(level == 0);
6702ed49 7769 path->lowest_level = level;
2c47e605
YZ
7770 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
7771 path->lowest_level = 0;
7772 if (ret < 0) {
7773 err = ret;
79787eaa 7774 goto out_end_trans;
9f3a7427 7775 }
1c4850e2 7776 WARN_ON(ret > 0);
2c47e605 7777
7d9eb12c
CM
7778 /*
7779 * unlock our path, this is safe because only this
7780 * function is allowed to delete this snapshot
7781 */
5d4f98a2 7782 btrfs_unlock_up_safe(path, 0);
2c47e605
YZ
7783
7784 level = btrfs_header_level(root->node);
7785 while (1) {
7786 btrfs_tree_lock(path->nodes[level]);
7787 btrfs_set_lock_blocking(path->nodes[level]);
fec386ac 7788 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
7789
7790 ret = btrfs_lookup_extent_info(trans, root,
7791 path->nodes[level]->start,
3173a18f 7792 level, 1, &wc->refs[level],
2c47e605 7793 &wc->flags[level]);
79787eaa
JM
7794 if (ret < 0) {
7795 err = ret;
7796 goto out_end_trans;
7797 }
2c47e605
YZ
7798 BUG_ON(wc->refs[level] == 0);
7799
7800 if (level == root_item->drop_level)
7801 break;
7802
7803 btrfs_tree_unlock(path->nodes[level]);
fec386ac 7804 path->locks[level] = 0;
2c47e605
YZ
7805 WARN_ON(wc->refs[level] != 1);
7806 level--;
7807 }
9f3a7427 7808 }
2c47e605
YZ
7809
7810 wc->level = level;
7811 wc->shared_level = -1;
7812 wc->stage = DROP_REFERENCE;
7813 wc->update_ref = update_ref;
7814 wc->keep_locks = 0;
66d7e7f0 7815 wc->for_reloc = for_reloc;
1c4850e2 7816 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
2c47e605 7817
d397712b 7818 while (1) {
9d1a2a3a 7819
2c47e605
YZ
7820 ret = walk_down_tree(trans, root, path, wc);
7821 if (ret < 0) {
7822 err = ret;
20524f02 7823 break;
2c47e605 7824 }
9aca1d51 7825
2c47e605
YZ
7826 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
7827 if (ret < 0) {
7828 err = ret;
20524f02 7829 break;
2c47e605
YZ
7830 }
7831
7832 if (ret > 0) {
7833 BUG_ON(wc->stage != DROP_REFERENCE);
e7a84565
CM
7834 break;
7835 }
2c47e605
YZ
7836
7837 if (wc->stage == DROP_REFERENCE) {
7838 level = wc->level;
7839 btrfs_node_key(path->nodes[level],
7840 &root_item->drop_progress,
7841 path->slots[level]);
7842 root_item->drop_level = level;
7843 }
7844
7845 BUG_ON(wc->level == 0);
3c8f2422
JB
7846 if (btrfs_should_end_transaction(trans, tree_root) ||
7847 (!for_reloc && btrfs_need_cleaner_sleep(root))) {
2c47e605
YZ
7848 ret = btrfs_update_root(trans, tree_root,
7849 &root->root_key,
7850 root_item);
79787eaa
JM
7851 if (ret) {
7852 btrfs_abort_transaction(trans, tree_root, ret);
7853 err = ret;
7854 goto out_end_trans;
7855 }
2c47e605 7856
3fd0a558 7857 btrfs_end_transaction_throttle(trans, tree_root);
3c8f2422 7858 if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
efe120a0 7859 pr_debug("BTRFS: drop snapshot early exit\n");
3c8f2422
JB
7860 err = -EAGAIN;
7861 goto out_free;
7862 }
7863
a22285a6 7864 trans = btrfs_start_transaction(tree_root, 0);
79787eaa
JM
7865 if (IS_ERR(trans)) {
7866 err = PTR_ERR(trans);
7867 goto out_free;
7868 }
3fd0a558
YZ
7869 if (block_rsv)
7870 trans->block_rsv = block_rsv;
c3e69d58 7871 }
20524f02 7872 }
b3b4aa74 7873 btrfs_release_path(path);
79787eaa
JM
7874 if (err)
7875 goto out_end_trans;
2c47e605
YZ
7876
7877 ret = btrfs_del_root(trans, tree_root, &root->root_key);
79787eaa
JM
7878 if (ret) {
7879 btrfs_abort_transaction(trans, tree_root, ret);
7880 goto out_end_trans;
7881 }
2c47e605 7882
76dda93c 7883 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
cb517eab
MX
7884 ret = btrfs_find_root(tree_root, &root->root_key, path,
7885 NULL, NULL);
79787eaa
JM
7886 if (ret < 0) {
7887 btrfs_abort_transaction(trans, tree_root, ret);
7888 err = ret;
7889 goto out_end_trans;
7890 } else if (ret > 0) {
84cd948c
JB
7891 /* if we fail to delete the orphan item this time
7892 * around, it'll get picked up the next time.
7893 *
7894 * The most common failure here is just -ENOENT.
7895 */
7896 btrfs_del_orphan_item(trans, tree_root,
7897 root->root_key.objectid);
76dda93c
YZ
7898 }
7899 }
7900
27cdeb70 7901 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
cb517eab 7902 btrfs_drop_and_free_fs_root(tree_root->fs_info, root);
76dda93c
YZ
7903 } else {
7904 free_extent_buffer(root->node);
7905 free_extent_buffer(root->commit_root);
b0feb9d9 7906 btrfs_put_fs_root(root);
76dda93c 7907 }
d29a9f62 7908 root_dropped = true;
79787eaa 7909out_end_trans:
3fd0a558 7910 btrfs_end_transaction_throttle(trans, tree_root);
79787eaa 7911out_free:
2c47e605 7912 kfree(wc);
5caf2a00 7913 btrfs_free_path(path);
cb1b69f4 7914out:
d29a9f62
JB
7915 /*
7916 * So if we need to stop dropping the snapshot for whatever reason we
7917 * need to make sure to add it back to the dead root list so that we
7918 * keep trying to do the work later. This also cleans up roots if we
7919 * don't have it in the radix (like when we recover after a power fail
7920 * or unmount) so we don't leak memory.
7921 */
b37b39cd 7922 if (!for_reloc && root_dropped == false)
d29a9f62 7923 btrfs_add_dead_root(root);
90515e7f 7924 if (err && err != -EAGAIN)
cb1b69f4 7925 btrfs_std_error(root->fs_info, err);
2c536799 7926 return err;
20524f02 7927}
9078a3e1 7928
2c47e605
YZ
7929/*
7930 * drop subtree rooted at tree block 'node'.
7931 *
7932 * NOTE: this function will unlock and release tree block 'node'
66d7e7f0 7933 * only used by relocation code
2c47e605 7934 */
f82d02d9
YZ
7935int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
7936 struct btrfs_root *root,
7937 struct extent_buffer *node,
7938 struct extent_buffer *parent)
7939{
7940 struct btrfs_path *path;
2c47e605 7941 struct walk_control *wc;
f82d02d9
YZ
7942 int level;
7943 int parent_level;
7944 int ret = 0;
7945 int wret;
7946
2c47e605
YZ
7947 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
7948
f82d02d9 7949 path = btrfs_alloc_path();
db5b493a
TI
7950 if (!path)
7951 return -ENOMEM;
f82d02d9 7952
2c47e605 7953 wc = kzalloc(sizeof(*wc), GFP_NOFS);
db5b493a
TI
7954 if (!wc) {
7955 btrfs_free_path(path);
7956 return -ENOMEM;
7957 }
2c47e605 7958
b9447ef8 7959 btrfs_assert_tree_locked(parent);
f82d02d9
YZ
7960 parent_level = btrfs_header_level(parent);
7961 extent_buffer_get(parent);
7962 path->nodes[parent_level] = parent;
7963 path->slots[parent_level] = btrfs_header_nritems(parent);
7964
b9447ef8 7965 btrfs_assert_tree_locked(node);
f82d02d9 7966 level = btrfs_header_level(node);
f82d02d9
YZ
7967 path->nodes[level] = node;
7968 path->slots[level] = 0;
bd681513 7969 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
7970
7971 wc->refs[parent_level] = 1;
7972 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
7973 wc->level = level;
7974 wc->shared_level = -1;
7975 wc->stage = DROP_REFERENCE;
7976 wc->update_ref = 0;
7977 wc->keep_locks = 1;
66d7e7f0 7978 wc->for_reloc = 1;
1c4850e2 7979 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
f82d02d9
YZ
7980
7981 while (1) {
2c47e605
YZ
7982 wret = walk_down_tree(trans, root, path, wc);
7983 if (wret < 0) {
f82d02d9 7984 ret = wret;
f82d02d9 7985 break;
2c47e605 7986 }
f82d02d9 7987
2c47e605 7988 wret = walk_up_tree(trans, root, path, wc, parent_level);
f82d02d9
YZ
7989 if (wret < 0)
7990 ret = wret;
7991 if (wret != 0)
7992 break;
7993 }
7994
2c47e605 7995 kfree(wc);
f82d02d9
YZ
7996 btrfs_free_path(path);
7997 return ret;
7998}
7999
ec44a35c
CM
8000static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
8001{
8002 u64 num_devices;
fc67c450 8003 u64 stripped;
e4d8ec0f 8004
fc67c450
ID
8005 /*
8006 * if restripe for this chunk_type is on pick target profile and
8007 * return, otherwise do the usual balance
8008 */
8009 stripped = get_restripe_target(root->fs_info, flags);
8010 if (stripped)
8011 return extended_to_chunk(stripped);
e4d8ec0f 8012
cd02dca5
CM
8013 /*
8014 * we add in the count of missing devices because we want
8015 * to make sure that any RAID levels on a degraded FS
8016 * continue to be honored.
8017 */
8018 num_devices = root->fs_info->fs_devices->rw_devices +
8019 root->fs_info->fs_devices->missing_devices;
8020
fc67c450 8021 stripped = BTRFS_BLOCK_GROUP_RAID0 |
53b381b3 8022 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
fc67c450
ID
8023 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
8024
ec44a35c
CM
8025 if (num_devices == 1) {
8026 stripped |= BTRFS_BLOCK_GROUP_DUP;
8027 stripped = flags & ~stripped;
8028
8029 /* turn raid0 into single device chunks */
8030 if (flags & BTRFS_BLOCK_GROUP_RAID0)
8031 return stripped;
8032
8033 /* turn mirroring into duplication */
8034 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
8035 BTRFS_BLOCK_GROUP_RAID10))
8036 return stripped | BTRFS_BLOCK_GROUP_DUP;
ec44a35c
CM
8037 } else {
8038 /* they already had raid on here, just return */
ec44a35c
CM
8039 if (flags & stripped)
8040 return flags;
8041
8042 stripped |= BTRFS_BLOCK_GROUP_DUP;
8043 stripped = flags & ~stripped;
8044
8045 /* switch duplicated blocks with raid1 */
8046 if (flags & BTRFS_BLOCK_GROUP_DUP)
8047 return stripped | BTRFS_BLOCK_GROUP_RAID1;
8048
e3176ca2 8049 /* this is drive concat, leave it alone */
ec44a35c 8050 }
e3176ca2 8051
ec44a35c
CM
8052 return flags;
8053}
8054
199c36ea 8055static int set_block_group_ro(struct btrfs_block_group_cache *cache, int force)
0ef3e66b 8056{
f0486c68
YZ
8057 struct btrfs_space_info *sinfo = cache->space_info;
8058 u64 num_bytes;
199c36ea 8059 u64 min_allocable_bytes;
f0486c68 8060 int ret = -ENOSPC;
0ef3e66b 8061
c286ac48 8062
199c36ea
MX
8063 /*
8064 * We need some metadata space and system metadata space for
8065 * allocating chunks in some corner cases until we force to set
8066 * it to be readonly.
8067 */
8068 if ((sinfo->flags &
8069 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
8070 !force)
8071 min_allocable_bytes = 1 * 1024 * 1024;
8072 else
8073 min_allocable_bytes = 0;
8074
f0486c68
YZ
8075 spin_lock(&sinfo->lock);
8076 spin_lock(&cache->lock);
61cfea9b
W
8077
8078 if (cache->ro) {
8079 ret = 0;
8080 goto out;
8081 }
8082
f0486c68
YZ
8083 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8084 cache->bytes_super - btrfs_block_group_used(&cache->item);
8085
8086 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
37be25bc
JB
8087 sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
8088 min_allocable_bytes <= sinfo->total_bytes) {
f0486c68 8089 sinfo->bytes_readonly += num_bytes;
f0486c68
YZ
8090 cache->ro = 1;
8091 ret = 0;
8092 }
61cfea9b 8093out:
f0486c68
YZ
8094 spin_unlock(&cache->lock);
8095 spin_unlock(&sinfo->lock);
8096 return ret;
8097}
7d9eb12c 8098
f0486c68
YZ
8099int btrfs_set_block_group_ro(struct btrfs_root *root,
8100 struct btrfs_block_group_cache *cache)
c286ac48 8101
f0486c68
YZ
8102{
8103 struct btrfs_trans_handle *trans;
8104 u64 alloc_flags;
8105 int ret;
7d9eb12c 8106
f0486c68 8107 BUG_ON(cache->ro);
0ef3e66b 8108
ff5714cc 8109 trans = btrfs_join_transaction(root);
79787eaa
JM
8110 if (IS_ERR(trans))
8111 return PTR_ERR(trans);
5d4f98a2 8112
f0486c68 8113 alloc_flags = update_block_group_flags(root, cache->flags);
79787eaa 8114 if (alloc_flags != cache->flags) {
698d0082 8115 ret = do_chunk_alloc(trans, root, alloc_flags,
79787eaa
JM
8116 CHUNK_ALLOC_FORCE);
8117 if (ret < 0)
8118 goto out;
8119 }
5d4f98a2 8120
199c36ea 8121 ret = set_block_group_ro(cache, 0);
f0486c68
YZ
8122 if (!ret)
8123 goto out;
8124 alloc_flags = get_alloc_profile(root, cache->space_info->flags);
698d0082 8125 ret = do_chunk_alloc(trans, root, alloc_flags,
0e4f8f88 8126 CHUNK_ALLOC_FORCE);
f0486c68
YZ
8127 if (ret < 0)
8128 goto out;
199c36ea 8129 ret = set_block_group_ro(cache, 0);
f0486c68
YZ
8130out:
8131 btrfs_end_transaction(trans, root);
8132 return ret;
8133}
5d4f98a2 8134
c87f08ca
CM
8135int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
8136 struct btrfs_root *root, u64 type)
8137{
8138 u64 alloc_flags = get_alloc_profile(root, type);
698d0082 8139 return do_chunk_alloc(trans, root, alloc_flags,
0e4f8f88 8140 CHUNK_ALLOC_FORCE);
c87f08ca
CM
8141}
8142
6d07bcec
MX
8143/*
8144 * helper to account the unused space of all the readonly block group in the
8145 * list. takes mirrors into account.
8146 */
8147static u64 __btrfs_get_ro_block_group_free_space(struct list_head *groups_list)
8148{
8149 struct btrfs_block_group_cache *block_group;
8150 u64 free_bytes = 0;
8151 int factor;
8152
8153 list_for_each_entry(block_group, groups_list, list) {
8154 spin_lock(&block_group->lock);
8155
8156 if (!block_group->ro) {
8157 spin_unlock(&block_group->lock);
8158 continue;
8159 }
8160
8161 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
8162 BTRFS_BLOCK_GROUP_RAID10 |
8163 BTRFS_BLOCK_GROUP_DUP))
8164 factor = 2;
8165 else
8166 factor = 1;
8167
8168 free_bytes += (block_group->key.offset -
8169 btrfs_block_group_used(&block_group->item)) *
8170 factor;
8171
8172 spin_unlock(&block_group->lock);
8173 }
8174
8175 return free_bytes;
8176}
8177
8178/*
8179 * helper to account the unused space of all the readonly block group in the
8180 * space_info. takes mirrors into account.
8181 */
8182u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
8183{
8184 int i;
8185 u64 free_bytes = 0;
8186
8187 spin_lock(&sinfo->lock);
8188
67871254 8189 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
6d07bcec
MX
8190 if (!list_empty(&sinfo->block_groups[i]))
8191 free_bytes += __btrfs_get_ro_block_group_free_space(
8192 &sinfo->block_groups[i]);
8193
8194 spin_unlock(&sinfo->lock);
8195
8196 return free_bytes;
8197}
8198
143bede5 8199void btrfs_set_block_group_rw(struct btrfs_root *root,
f0486c68 8200 struct btrfs_block_group_cache *cache)
5d4f98a2 8201{
f0486c68
YZ
8202 struct btrfs_space_info *sinfo = cache->space_info;
8203 u64 num_bytes;
8204
8205 BUG_ON(!cache->ro);
8206
8207 spin_lock(&sinfo->lock);
8208 spin_lock(&cache->lock);
8209 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
8210 cache->bytes_super - btrfs_block_group_used(&cache->item);
8211 sinfo->bytes_readonly -= num_bytes;
8212 cache->ro = 0;
8213 spin_unlock(&cache->lock);
8214 spin_unlock(&sinfo->lock);
5d4f98a2
YZ
8215}
8216
ba1bf481
JB
8217/*
8218 * checks to see if its even possible to relocate this block group.
8219 *
8220 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
8221 * ok to go ahead and try.
8222 */
8223int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
1a40e23b 8224{
ba1bf481
JB
8225 struct btrfs_block_group_cache *block_group;
8226 struct btrfs_space_info *space_info;
8227 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
8228 struct btrfs_device *device;
6df9a95e 8229 struct btrfs_trans_handle *trans;
cdcb725c 8230 u64 min_free;
6719db6a
JB
8231 u64 dev_min = 1;
8232 u64 dev_nr = 0;
4a5e98f5 8233 u64 target;
cdcb725c 8234 int index;
ba1bf481
JB
8235 int full = 0;
8236 int ret = 0;
1a40e23b 8237
ba1bf481 8238 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
1a40e23b 8239
ba1bf481
JB
8240 /* odd, couldn't find the block group, leave it alone */
8241 if (!block_group)
8242 return -1;
1a40e23b 8243
cdcb725c 8244 min_free = btrfs_block_group_used(&block_group->item);
8245
ba1bf481 8246 /* no bytes used, we're good */
cdcb725c 8247 if (!min_free)
1a40e23b
ZY
8248 goto out;
8249
ba1bf481
JB
8250 space_info = block_group->space_info;
8251 spin_lock(&space_info->lock);
17d217fe 8252
ba1bf481 8253 full = space_info->full;
17d217fe 8254
ba1bf481
JB
8255 /*
8256 * if this is the last block group we have in this space, we can't
7ce618db
CM
8257 * relocate it unless we're able to allocate a new chunk below.
8258 *
8259 * Otherwise, we need to make sure we have room in the space to handle
8260 * all of the extents from this block group. If we can, we're good
ba1bf481 8261 */
7ce618db 8262 if ((space_info->total_bytes != block_group->key.offset) &&
cdcb725c 8263 (space_info->bytes_used + space_info->bytes_reserved +
8264 space_info->bytes_pinned + space_info->bytes_readonly +
8265 min_free < space_info->total_bytes)) {
ba1bf481
JB
8266 spin_unlock(&space_info->lock);
8267 goto out;
17d217fe 8268 }
ba1bf481 8269 spin_unlock(&space_info->lock);
ea8c2819 8270
ba1bf481
JB
8271 /*
8272 * ok we don't have enough space, but maybe we have free space on our
8273 * devices to allocate new chunks for relocation, so loop through our
4a5e98f5
ID
8274 * alloc devices and guess if we have enough space. if this block
8275 * group is going to be restriped, run checks against the target
8276 * profile instead of the current one.
ba1bf481
JB
8277 */
8278 ret = -1;
ea8c2819 8279
cdcb725c 8280 /*
8281 * index:
8282 * 0: raid10
8283 * 1: raid1
8284 * 2: dup
8285 * 3: raid0
8286 * 4: single
8287 */
4a5e98f5
ID
8288 target = get_restripe_target(root->fs_info, block_group->flags);
8289 if (target) {
31e50229 8290 index = __get_raid_index(extended_to_chunk(target));
4a5e98f5
ID
8291 } else {
8292 /*
8293 * this is just a balance, so if we were marked as full
8294 * we know there is no space for a new chunk
8295 */
8296 if (full)
8297 goto out;
8298
8299 index = get_block_group_index(block_group);
8300 }
8301
e6ec716f 8302 if (index == BTRFS_RAID_RAID10) {
cdcb725c 8303 dev_min = 4;
6719db6a
JB
8304 /* Divide by 2 */
8305 min_free >>= 1;
e6ec716f 8306 } else if (index == BTRFS_RAID_RAID1) {
cdcb725c 8307 dev_min = 2;
e6ec716f 8308 } else if (index == BTRFS_RAID_DUP) {
6719db6a
JB
8309 /* Multiply by 2 */
8310 min_free <<= 1;
e6ec716f 8311 } else if (index == BTRFS_RAID_RAID0) {
cdcb725c 8312 dev_min = fs_devices->rw_devices;
6719db6a 8313 do_div(min_free, dev_min);
cdcb725c 8314 }
8315
6df9a95e
JB
8316 /* We need to do this so that we can look at pending chunks */
8317 trans = btrfs_join_transaction(root);
8318 if (IS_ERR(trans)) {
8319 ret = PTR_ERR(trans);
8320 goto out;
8321 }
8322
ba1bf481
JB
8323 mutex_lock(&root->fs_info->chunk_mutex);
8324 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7bfc837d 8325 u64 dev_offset;
56bec294 8326
ba1bf481
JB
8327 /*
8328 * check to make sure we can actually find a chunk with enough
8329 * space to fit our block group in.
8330 */
63a212ab
SB
8331 if (device->total_bytes > device->bytes_used + min_free &&
8332 !device->is_tgtdev_for_dev_replace) {
6df9a95e 8333 ret = find_free_dev_extent(trans, device, min_free,
7bfc837d 8334 &dev_offset, NULL);
ba1bf481 8335 if (!ret)
cdcb725c 8336 dev_nr++;
8337
8338 if (dev_nr >= dev_min)
73e48b27 8339 break;
cdcb725c 8340
ba1bf481 8341 ret = -1;
725c8463 8342 }
edbd8d4e 8343 }
ba1bf481 8344 mutex_unlock(&root->fs_info->chunk_mutex);
6df9a95e 8345 btrfs_end_transaction(trans, root);
edbd8d4e 8346out:
ba1bf481 8347 btrfs_put_block_group(block_group);
edbd8d4e
CM
8348 return ret;
8349}
8350
b2950863
CH
8351static int find_first_block_group(struct btrfs_root *root,
8352 struct btrfs_path *path, struct btrfs_key *key)
0b86a832 8353{
925baedd 8354 int ret = 0;
0b86a832
CM
8355 struct btrfs_key found_key;
8356 struct extent_buffer *leaf;
8357 int slot;
edbd8d4e 8358
0b86a832
CM
8359 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
8360 if (ret < 0)
925baedd
CM
8361 goto out;
8362
d397712b 8363 while (1) {
0b86a832 8364 slot = path->slots[0];
edbd8d4e 8365 leaf = path->nodes[0];
0b86a832
CM
8366 if (slot >= btrfs_header_nritems(leaf)) {
8367 ret = btrfs_next_leaf(root, path);
8368 if (ret == 0)
8369 continue;
8370 if (ret < 0)
925baedd 8371 goto out;
0b86a832 8372 break;
edbd8d4e 8373 }
0b86a832 8374 btrfs_item_key_to_cpu(leaf, &found_key, slot);
edbd8d4e 8375
0b86a832 8376 if (found_key.objectid >= key->objectid &&
925baedd
CM
8377 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
8378 ret = 0;
8379 goto out;
8380 }
0b86a832 8381 path->slots[0]++;
edbd8d4e 8382 }
925baedd 8383out:
0b86a832 8384 return ret;
edbd8d4e
CM
8385}
8386
0af3d00b
JB
8387void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
8388{
8389 struct btrfs_block_group_cache *block_group;
8390 u64 last = 0;
8391
8392 while (1) {
8393 struct inode *inode;
8394
8395 block_group = btrfs_lookup_first_block_group(info, last);
8396 while (block_group) {
8397 spin_lock(&block_group->lock);
8398 if (block_group->iref)
8399 break;
8400 spin_unlock(&block_group->lock);
8401 block_group = next_block_group(info->tree_root,
8402 block_group);
8403 }
8404 if (!block_group) {
8405 if (last == 0)
8406 break;
8407 last = 0;
8408 continue;
8409 }
8410
8411 inode = block_group->inode;
8412 block_group->iref = 0;
8413 block_group->inode = NULL;
8414 spin_unlock(&block_group->lock);
8415 iput(inode);
8416 last = block_group->key.objectid + block_group->key.offset;
8417 btrfs_put_block_group(block_group);
8418 }
8419}
8420
1a40e23b
ZY
8421int btrfs_free_block_groups(struct btrfs_fs_info *info)
8422{
8423 struct btrfs_block_group_cache *block_group;
4184ea7f 8424 struct btrfs_space_info *space_info;
11833d66 8425 struct btrfs_caching_control *caching_ctl;
1a40e23b
ZY
8426 struct rb_node *n;
8427
9e351cc8 8428 down_write(&info->commit_root_sem);
11833d66
YZ
8429 while (!list_empty(&info->caching_block_groups)) {
8430 caching_ctl = list_entry(info->caching_block_groups.next,
8431 struct btrfs_caching_control, list);
8432 list_del(&caching_ctl->list);
8433 put_caching_control(caching_ctl);
8434 }
9e351cc8 8435 up_write(&info->commit_root_sem);
11833d66 8436
1a40e23b
ZY
8437 spin_lock(&info->block_group_cache_lock);
8438 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
8439 block_group = rb_entry(n, struct btrfs_block_group_cache,
8440 cache_node);
1a40e23b
ZY
8441 rb_erase(&block_group->cache_node,
8442 &info->block_group_cache_tree);
d899e052
YZ
8443 spin_unlock(&info->block_group_cache_lock);
8444
80eb234a 8445 down_write(&block_group->space_info->groups_sem);
1a40e23b 8446 list_del(&block_group->list);
80eb234a 8447 up_write(&block_group->space_info->groups_sem);
d2fb3437 8448
817d52f8 8449 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 8450 wait_block_group_cache_done(block_group);
817d52f8 8451
3c14874a
JB
8452 /*
8453 * We haven't cached this block group, which means we could
8454 * possibly have excluded extents on this block group.
8455 */
36cce922
JB
8456 if (block_group->cached == BTRFS_CACHE_NO ||
8457 block_group->cached == BTRFS_CACHE_ERROR)
3c14874a
JB
8458 free_excluded_extents(info->extent_root, block_group);
8459
817d52f8 8460 btrfs_remove_free_space_cache(block_group);
11dfe35a 8461 btrfs_put_block_group(block_group);
d899e052
YZ
8462
8463 spin_lock(&info->block_group_cache_lock);
1a40e23b
ZY
8464 }
8465 spin_unlock(&info->block_group_cache_lock);
4184ea7f
CM
8466
8467 /* now that all the block groups are freed, go through and
8468 * free all the space_info structs. This is only called during
8469 * the final stages of unmount, and so we know nobody is
8470 * using them. We call synchronize_rcu() once before we start,
8471 * just to be on the safe side.
8472 */
8473 synchronize_rcu();
8474
8929ecfa
YZ
8475 release_global_block_rsv(info);
8476
67871254 8477 while (!list_empty(&info->space_info)) {
6ab0a202
JM
8478 int i;
8479
4184ea7f
CM
8480 space_info = list_entry(info->space_info.next,
8481 struct btrfs_space_info,
8482 list);
b069e0c3 8483 if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
fae7f21c 8484 if (WARN_ON(space_info->bytes_pinned > 0 ||
b069e0c3 8485 space_info->bytes_reserved > 0 ||
fae7f21c 8486 space_info->bytes_may_use > 0)) {
b069e0c3
DS
8487 dump_space_info(space_info, 0, 0);
8488 }
f0486c68 8489 }
4184ea7f 8490 list_del(&space_info->list);
6ab0a202
JM
8491 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
8492 struct kobject *kobj;
8493 kobj = &space_info->block_group_kobjs[i];
8494 if (kobj->parent) {
8495 kobject_del(kobj);
8496 kobject_put(kobj);
8497 }
8498 }
8499 kobject_del(&space_info->kobj);
8500 kobject_put(&space_info->kobj);
4184ea7f 8501 }
1a40e23b
ZY
8502 return 0;
8503}
8504
b742bb82
YZ
8505static void __link_block_group(struct btrfs_space_info *space_info,
8506 struct btrfs_block_group_cache *cache)
8507{
8508 int index = get_block_group_index(cache);
ed55b6ac 8509 bool first = false;
b742bb82
YZ
8510
8511 down_write(&space_info->groups_sem);
ed55b6ac
JM
8512 if (list_empty(&space_info->block_groups[index]))
8513 first = true;
8514 list_add_tail(&cache->list, &space_info->block_groups[index]);
8515 up_write(&space_info->groups_sem);
8516
8517 if (first) {
6ab0a202
JM
8518 struct kobject *kobj = &space_info->block_group_kobjs[index];
8519 int ret;
8520
8521 kobject_get(&space_info->kobj); /* put in release */
536cd964
MX
8522 ret = kobject_add(kobj, &space_info->kobj, "%s",
8523 get_raid_name(index));
6ab0a202 8524 if (ret) {
efe120a0 8525 pr_warn("BTRFS: failed to add kobject for block cache. ignoring.\n");
6ab0a202
JM
8526 kobject_put(&space_info->kobj);
8527 }
8528 }
b742bb82
YZ
8529}
8530
920e4a58
MX
8531static struct btrfs_block_group_cache *
8532btrfs_create_block_group_cache(struct btrfs_root *root, u64 start, u64 size)
8533{
8534 struct btrfs_block_group_cache *cache;
8535
8536 cache = kzalloc(sizeof(*cache), GFP_NOFS);
8537 if (!cache)
8538 return NULL;
8539
8540 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
8541 GFP_NOFS);
8542 if (!cache->free_space_ctl) {
8543 kfree(cache);
8544 return NULL;
8545 }
8546
8547 cache->key.objectid = start;
8548 cache->key.offset = size;
8549 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
8550
8551 cache->sectorsize = root->sectorsize;
8552 cache->fs_info = root->fs_info;
8553 cache->full_stripe_len = btrfs_full_stripe_len(root,
8554 &root->fs_info->mapping_tree,
8555 start);
8556 atomic_set(&cache->count, 1);
8557 spin_lock_init(&cache->lock);
8558 INIT_LIST_HEAD(&cache->list);
8559 INIT_LIST_HEAD(&cache->cluster_list);
8560 INIT_LIST_HEAD(&cache->new_bg_list);
8561 btrfs_init_free_space_ctl(cache);
8562
8563 return cache;
8564}
8565
9078a3e1
CM
8566int btrfs_read_block_groups(struct btrfs_root *root)
8567{
8568 struct btrfs_path *path;
8569 int ret;
9078a3e1 8570 struct btrfs_block_group_cache *cache;
be744175 8571 struct btrfs_fs_info *info = root->fs_info;
6324fbf3 8572 struct btrfs_space_info *space_info;
9078a3e1
CM
8573 struct btrfs_key key;
8574 struct btrfs_key found_key;
5f39d397 8575 struct extent_buffer *leaf;
0af3d00b
JB
8576 int need_clear = 0;
8577 u64 cache_gen;
96b5179d 8578
be744175 8579 root = info->extent_root;
9078a3e1 8580 key.objectid = 0;
0b86a832 8581 key.offset = 0;
9078a3e1 8582 btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
9078a3e1
CM
8583 path = btrfs_alloc_path();
8584 if (!path)
8585 return -ENOMEM;
026fd317 8586 path->reada = 1;
9078a3e1 8587
6c41761f 8588 cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
73bc1876 8589 if (btrfs_test_opt(root, SPACE_CACHE) &&
6c41761f 8590 btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
0af3d00b 8591 need_clear = 1;
88c2ba3b
JB
8592 if (btrfs_test_opt(root, CLEAR_CACHE))
8593 need_clear = 1;
0af3d00b 8594
d397712b 8595 while (1) {
0b86a832 8596 ret = find_first_block_group(root, path, &key);
b742bb82
YZ
8597 if (ret > 0)
8598 break;
0b86a832
CM
8599 if (ret != 0)
8600 goto error;
920e4a58 8601
5f39d397
CM
8602 leaf = path->nodes[0];
8603 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
920e4a58
MX
8604
8605 cache = btrfs_create_block_group_cache(root, found_key.objectid,
8606 found_key.offset);
9078a3e1 8607 if (!cache) {
0b86a832 8608 ret = -ENOMEM;
f0486c68 8609 goto error;
9078a3e1 8610 }
96303081 8611
cf7c1ef6
LB
8612 if (need_clear) {
8613 /*
8614 * When we mount with old space cache, we need to
8615 * set BTRFS_DC_CLEAR and set dirty flag.
8616 *
8617 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
8618 * truncate the old free space cache inode and
8619 * setup a new one.
8620 * b) Setting 'dirty flag' makes sure that we flush
8621 * the new space cache info onto disk.
8622 */
0af3d00b 8623 cache->disk_cache_state = BTRFS_DC_CLEAR;
cf7c1ef6
LB
8624 if (btrfs_test_opt(root, SPACE_CACHE))
8625 cache->dirty = 1;
8626 }
0af3d00b 8627
5f39d397
CM
8628 read_extent_buffer(leaf, &cache->item,
8629 btrfs_item_ptr_offset(leaf, path->slots[0]),
8630 sizeof(cache->item));
920e4a58 8631 cache->flags = btrfs_block_group_flags(&cache->item);
0b86a832 8632
9078a3e1 8633 key.objectid = found_key.objectid + found_key.offset;
b3b4aa74 8634 btrfs_release_path(path);
34d52cb6 8635
3c14874a
JB
8636 /*
8637 * We need to exclude the super stripes now so that the space
8638 * info has super bytes accounted for, otherwise we'll think
8639 * we have more space than we actually do.
8640 */
835d974f
JB
8641 ret = exclude_super_stripes(root, cache);
8642 if (ret) {
8643 /*
8644 * We may have excluded something, so call this just in
8645 * case.
8646 */
8647 free_excluded_extents(root, cache);
920e4a58 8648 btrfs_put_block_group(cache);
835d974f
JB
8649 goto error;
8650 }
3c14874a 8651
817d52f8
JB
8652 /*
8653 * check for two cases, either we are full, and therefore
8654 * don't need to bother with the caching work since we won't
8655 * find any space, or we are empty, and we can just add all
8656 * the space in and be done with it. This saves us _alot_ of
8657 * time, particularly in the full case.
8658 */
8659 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
11833d66 8660 cache->last_byte_to_unpin = (u64)-1;
817d52f8 8661 cache->cached = BTRFS_CACHE_FINISHED;
1b2da372 8662 free_excluded_extents(root, cache);
817d52f8 8663 } else if (btrfs_block_group_used(&cache->item) == 0) {
11833d66 8664 cache->last_byte_to_unpin = (u64)-1;
817d52f8
JB
8665 cache->cached = BTRFS_CACHE_FINISHED;
8666 add_new_free_space(cache, root->fs_info,
8667 found_key.objectid,
8668 found_key.objectid +
8669 found_key.offset);
11833d66 8670 free_excluded_extents(root, cache);
817d52f8 8671 }
96b5179d 8672
8c579fe7
JB
8673 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8674 if (ret) {
8675 btrfs_remove_free_space_cache(cache);
8676 btrfs_put_block_group(cache);
8677 goto error;
8678 }
8679
6324fbf3
CM
8680 ret = update_space_info(info, cache->flags, found_key.offset,
8681 btrfs_block_group_used(&cache->item),
8682 &space_info);
8c579fe7
JB
8683 if (ret) {
8684 btrfs_remove_free_space_cache(cache);
8685 spin_lock(&info->block_group_cache_lock);
8686 rb_erase(&cache->cache_node,
8687 &info->block_group_cache_tree);
8688 spin_unlock(&info->block_group_cache_lock);
8689 btrfs_put_block_group(cache);
8690 goto error;
8691 }
8692
6324fbf3 8693 cache->space_info = space_info;
1b2da372 8694 spin_lock(&cache->space_info->lock);
f0486c68 8695 cache->space_info->bytes_readonly += cache->bytes_super;
1b2da372
JB
8696 spin_unlock(&cache->space_info->lock);
8697
b742bb82 8698 __link_block_group(space_info, cache);
0f9dd46c 8699
75ccf47d 8700 set_avail_alloc_bits(root->fs_info, cache->flags);
2b82032c 8701 if (btrfs_chunk_readonly(root, cache->key.objectid))
199c36ea 8702 set_block_group_ro(cache, 1);
9078a3e1 8703 }
b742bb82
YZ
8704
8705 list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
8706 if (!(get_alloc_profile(root, space_info->flags) &
8707 (BTRFS_BLOCK_GROUP_RAID10 |
8708 BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
8709 BTRFS_BLOCK_GROUP_RAID5 |
8710 BTRFS_BLOCK_GROUP_RAID6 |
b742bb82
YZ
8711 BTRFS_BLOCK_GROUP_DUP)))
8712 continue;
8713 /*
8714 * avoid allocating from un-mirrored block group if there are
8715 * mirrored block groups.
8716 */
1095cc0d 8717 list_for_each_entry(cache,
8718 &space_info->block_groups[BTRFS_RAID_RAID0],
8719 list)
199c36ea 8720 set_block_group_ro(cache, 1);
1095cc0d 8721 list_for_each_entry(cache,
8722 &space_info->block_groups[BTRFS_RAID_SINGLE],
8723 list)
199c36ea 8724 set_block_group_ro(cache, 1);
9078a3e1 8725 }
f0486c68
YZ
8726
8727 init_global_block_rsv(info);
0b86a832
CM
8728 ret = 0;
8729error:
9078a3e1 8730 btrfs_free_path(path);
0b86a832 8731 return ret;
9078a3e1 8732}
6324fbf3 8733
ea658bad
JB
8734void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
8735 struct btrfs_root *root)
8736{
8737 struct btrfs_block_group_cache *block_group, *tmp;
8738 struct btrfs_root *extent_root = root->fs_info->extent_root;
8739 struct btrfs_block_group_item item;
8740 struct btrfs_key key;
8741 int ret = 0;
8742
8743 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs,
8744 new_bg_list) {
8745 list_del_init(&block_group->new_bg_list);
8746
8747 if (ret)
8748 continue;
8749
8750 spin_lock(&block_group->lock);
8751 memcpy(&item, &block_group->item, sizeof(item));
8752 memcpy(&key, &block_group->key, sizeof(key));
8753 spin_unlock(&block_group->lock);
8754
8755 ret = btrfs_insert_item(trans, extent_root, &key, &item,
8756 sizeof(item));
8757 if (ret)
8758 btrfs_abort_transaction(trans, extent_root, ret);
6df9a95e
JB
8759 ret = btrfs_finish_chunk_alloc(trans, extent_root,
8760 key.objectid, key.offset);
8761 if (ret)
8762 btrfs_abort_transaction(trans, extent_root, ret);
ea658bad
JB
8763 }
8764}
8765
6324fbf3
CM
8766int btrfs_make_block_group(struct btrfs_trans_handle *trans,
8767 struct btrfs_root *root, u64 bytes_used,
e17cade2 8768 u64 type, u64 chunk_objectid, u64 chunk_offset,
6324fbf3
CM
8769 u64 size)
8770{
8771 int ret;
6324fbf3
CM
8772 struct btrfs_root *extent_root;
8773 struct btrfs_block_group_cache *cache;
6324fbf3
CM
8774
8775 extent_root = root->fs_info->extent_root;
6324fbf3 8776
995946dd 8777 btrfs_set_log_full_commit(root->fs_info, trans);
e02119d5 8778
920e4a58 8779 cache = btrfs_create_block_group_cache(root, chunk_offset, size);
0f9dd46c
JB
8780 if (!cache)
8781 return -ENOMEM;
34d52cb6 8782
6324fbf3 8783 btrfs_set_block_group_used(&cache->item, bytes_used);
6324fbf3 8784 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
6324fbf3
CM
8785 btrfs_set_block_group_flags(&cache->item, type);
8786
920e4a58 8787 cache->flags = type;
11833d66 8788 cache->last_byte_to_unpin = (u64)-1;
817d52f8 8789 cache->cached = BTRFS_CACHE_FINISHED;
835d974f
JB
8790 ret = exclude_super_stripes(root, cache);
8791 if (ret) {
8792 /*
8793 * We may have excluded something, so call this just in
8794 * case.
8795 */
8796 free_excluded_extents(root, cache);
920e4a58 8797 btrfs_put_block_group(cache);
835d974f
JB
8798 return ret;
8799 }
96303081 8800
817d52f8
JB
8801 add_new_free_space(cache, root->fs_info, chunk_offset,
8802 chunk_offset + size);
8803
11833d66
YZ
8804 free_excluded_extents(root, cache);
8805
8c579fe7
JB
8806 ret = btrfs_add_block_group_cache(root->fs_info, cache);
8807 if (ret) {
8808 btrfs_remove_free_space_cache(cache);
8809 btrfs_put_block_group(cache);
8810 return ret;
8811 }
8812
6324fbf3
CM
8813 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
8814 &cache->space_info);
8c579fe7
JB
8815 if (ret) {
8816 btrfs_remove_free_space_cache(cache);
8817 spin_lock(&root->fs_info->block_group_cache_lock);
8818 rb_erase(&cache->cache_node,
8819 &root->fs_info->block_group_cache_tree);
8820 spin_unlock(&root->fs_info->block_group_cache_lock);
8821 btrfs_put_block_group(cache);
8822 return ret;
8823 }
c7c144db 8824 update_global_block_rsv(root->fs_info);
1b2da372
JB
8825
8826 spin_lock(&cache->space_info->lock);
f0486c68 8827 cache->space_info->bytes_readonly += cache->bytes_super;
1b2da372
JB
8828 spin_unlock(&cache->space_info->lock);
8829
b742bb82 8830 __link_block_group(cache->space_info, cache);
6324fbf3 8831
ea658bad 8832 list_add_tail(&cache->new_bg_list, &trans->new_bgs);
6324fbf3 8833
d18a2c44 8834 set_avail_alloc_bits(extent_root->fs_info, type);
925baedd 8835
6324fbf3
CM
8836 return 0;
8837}
1a40e23b 8838
10ea00f5
ID
8839static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
8840{
899c81ea
ID
8841 u64 extra_flags = chunk_to_extended(flags) &
8842 BTRFS_EXTENDED_PROFILE_MASK;
10ea00f5 8843
de98ced9 8844 write_seqlock(&fs_info->profiles_lock);
10ea00f5
ID
8845 if (flags & BTRFS_BLOCK_GROUP_DATA)
8846 fs_info->avail_data_alloc_bits &= ~extra_flags;
8847 if (flags & BTRFS_BLOCK_GROUP_METADATA)
8848 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
8849 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
8850 fs_info->avail_system_alloc_bits &= ~extra_flags;
de98ced9 8851 write_sequnlock(&fs_info->profiles_lock);
10ea00f5
ID
8852}
8853
1a40e23b
ZY
8854int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
8855 struct btrfs_root *root, u64 group_start)
8856{
8857 struct btrfs_path *path;
8858 struct btrfs_block_group_cache *block_group;
44fb5511 8859 struct btrfs_free_cluster *cluster;
0af3d00b 8860 struct btrfs_root *tree_root = root->fs_info->tree_root;
1a40e23b 8861 struct btrfs_key key;
0af3d00b 8862 struct inode *inode;
1a40e23b 8863 int ret;
10ea00f5 8864 int index;
89a55897 8865 int factor;
1a40e23b 8866
1a40e23b
ZY
8867 root = root->fs_info->extent_root;
8868
8869 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
8870 BUG_ON(!block_group);
c146afad 8871 BUG_ON(!block_group->ro);
1a40e23b 8872
9f7c43c9 8873 /*
8874 * Free the reserved super bytes from this block group before
8875 * remove it.
8876 */
8877 free_excluded_extents(root, block_group);
8878
1a40e23b 8879 memcpy(&key, &block_group->key, sizeof(key));
10ea00f5 8880 index = get_block_group_index(block_group);
89a55897
JB
8881 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
8882 BTRFS_BLOCK_GROUP_RAID1 |
8883 BTRFS_BLOCK_GROUP_RAID10))
8884 factor = 2;
8885 else
8886 factor = 1;
1a40e23b 8887
44fb5511
CM
8888 /* make sure this block group isn't part of an allocation cluster */
8889 cluster = &root->fs_info->data_alloc_cluster;
8890 spin_lock(&cluster->refill_lock);
8891 btrfs_return_cluster_to_free_space(block_group, cluster);
8892 spin_unlock(&cluster->refill_lock);
8893
8894 /*
8895 * make sure this block group isn't part of a metadata
8896 * allocation cluster
8897 */
8898 cluster = &root->fs_info->meta_alloc_cluster;
8899 spin_lock(&cluster->refill_lock);
8900 btrfs_return_cluster_to_free_space(block_group, cluster);
8901 spin_unlock(&cluster->refill_lock);
8902
1a40e23b 8903 path = btrfs_alloc_path();
d8926bb3
MF
8904 if (!path) {
8905 ret = -ENOMEM;
8906 goto out;
8907 }
1a40e23b 8908
10b2f34d 8909 inode = lookup_free_space_inode(tree_root, block_group, path);
0af3d00b 8910 if (!IS_ERR(inode)) {
b532402e 8911 ret = btrfs_orphan_add(trans, inode);
79787eaa
JM
8912 if (ret) {
8913 btrfs_add_delayed_iput(inode);
8914 goto out;
8915 }
0af3d00b
JB
8916 clear_nlink(inode);
8917 /* One for the block groups ref */
8918 spin_lock(&block_group->lock);
8919 if (block_group->iref) {
8920 block_group->iref = 0;
8921 block_group->inode = NULL;
8922 spin_unlock(&block_group->lock);
8923 iput(inode);
8924 } else {
8925 spin_unlock(&block_group->lock);
8926 }
8927 /* One for our lookup ref */
455757c3 8928 btrfs_add_delayed_iput(inode);
0af3d00b
JB
8929 }
8930
8931 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
8932 key.offset = block_group->key.objectid;
8933 key.type = 0;
8934
8935 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
8936 if (ret < 0)
8937 goto out;
8938 if (ret > 0)
b3b4aa74 8939 btrfs_release_path(path);
0af3d00b
JB
8940 if (ret == 0) {
8941 ret = btrfs_del_item(trans, tree_root, path);
8942 if (ret)
8943 goto out;
b3b4aa74 8944 btrfs_release_path(path);
0af3d00b
JB
8945 }
8946
3dfdb934 8947 spin_lock(&root->fs_info->block_group_cache_lock);
1a40e23b
ZY
8948 rb_erase(&block_group->cache_node,
8949 &root->fs_info->block_group_cache_tree);
a1897fdd
LB
8950
8951 if (root->fs_info->first_logical_byte == block_group->key.objectid)
8952 root->fs_info->first_logical_byte = (u64)-1;
3dfdb934 8953 spin_unlock(&root->fs_info->block_group_cache_lock);
817d52f8 8954
80eb234a 8955 down_write(&block_group->space_info->groups_sem);
44fb5511
CM
8956 /*
8957 * we must use list_del_init so people can check to see if they
8958 * are still on the list after taking the semaphore
8959 */
8960 list_del_init(&block_group->list);
6ab0a202
JM
8961 if (list_empty(&block_group->space_info->block_groups[index])) {
8962 kobject_del(&block_group->space_info->block_group_kobjs[index]);
8963 kobject_put(&block_group->space_info->block_group_kobjs[index]);
10ea00f5 8964 clear_avail_alloc_bits(root->fs_info, block_group->flags);
6ab0a202 8965 }
80eb234a 8966 up_write(&block_group->space_info->groups_sem);
1a40e23b 8967
817d52f8 8968 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 8969 wait_block_group_cache_done(block_group);
817d52f8
JB
8970
8971 btrfs_remove_free_space_cache(block_group);
8972
c146afad
YZ
8973 spin_lock(&block_group->space_info->lock);
8974 block_group->space_info->total_bytes -= block_group->key.offset;
8975 block_group->space_info->bytes_readonly -= block_group->key.offset;
89a55897 8976 block_group->space_info->disk_total -= block_group->key.offset * factor;
c146afad 8977 spin_unlock(&block_group->space_info->lock);
283bb197 8978
0af3d00b
JB
8979 memcpy(&key, &block_group->key, sizeof(key));
8980
283bb197 8981 btrfs_clear_space_info_full(root->fs_info);
c146afad 8982
fa9c0d79
CM
8983 btrfs_put_block_group(block_group);
8984 btrfs_put_block_group(block_group);
1a40e23b
ZY
8985
8986 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
8987 if (ret > 0)
8988 ret = -EIO;
8989 if (ret < 0)
8990 goto out;
8991
8992 ret = btrfs_del_item(trans, root, path);
8993out:
8994 btrfs_free_path(path);
8995 return ret;
8996}
acce952b 8997
c59021f8 8998int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
8999{
9000 struct btrfs_space_info *space_info;
1aba86d6 9001 struct btrfs_super_block *disk_super;
9002 u64 features;
9003 u64 flags;
9004 int mixed = 0;
c59021f8 9005 int ret;
9006
6c41761f 9007 disk_super = fs_info->super_copy;
1aba86d6 9008 if (!btrfs_super_root(disk_super))
9009 return 1;
c59021f8 9010
1aba86d6 9011 features = btrfs_super_incompat_flags(disk_super);
9012 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
9013 mixed = 1;
c59021f8 9014
1aba86d6 9015 flags = BTRFS_BLOCK_GROUP_SYSTEM;
9016 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
c59021f8 9017 if (ret)
1aba86d6 9018 goto out;
c59021f8 9019
1aba86d6 9020 if (mixed) {
9021 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
9022 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
9023 } else {
9024 flags = BTRFS_BLOCK_GROUP_METADATA;
9025 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
9026 if (ret)
9027 goto out;
9028
9029 flags = BTRFS_BLOCK_GROUP_DATA;
9030 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
9031 }
9032out:
c59021f8 9033 return ret;
9034}
9035
acce952b 9036int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
9037{
9038 return unpin_extent_range(root, start, end);
9039}
9040
9041int btrfs_error_discard_extent(struct btrfs_root *root, u64 bytenr,
5378e607 9042 u64 num_bytes, u64 *actual_bytes)
acce952b 9043{
5378e607 9044 return btrfs_discard_extent(root, bytenr, num_bytes, actual_bytes);
acce952b 9045}
f7039b1d
LD
9046
9047int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
9048{
9049 struct btrfs_fs_info *fs_info = root->fs_info;
9050 struct btrfs_block_group_cache *cache = NULL;
9051 u64 group_trimmed;
9052 u64 start;
9053 u64 end;
9054 u64 trimmed = 0;
2cac13e4 9055 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
f7039b1d
LD
9056 int ret = 0;
9057
2cac13e4
LB
9058 /*
9059 * try to trim all FS space, our block group may start from non-zero.
9060 */
9061 if (range->len == total_bytes)
9062 cache = btrfs_lookup_first_block_group(fs_info, range->start);
9063 else
9064 cache = btrfs_lookup_block_group(fs_info, range->start);
f7039b1d
LD
9065
9066 while (cache) {
9067 if (cache->key.objectid >= (range->start + range->len)) {
9068 btrfs_put_block_group(cache);
9069 break;
9070 }
9071
9072 start = max(range->start, cache->key.objectid);
9073 end = min(range->start + range->len,
9074 cache->key.objectid + cache->key.offset);
9075
9076 if (end - start >= range->minlen) {
9077 if (!block_group_cache_done(cache)) {
f6373bf3 9078 ret = cache_block_group(cache, 0);
1be41b78
JB
9079 if (ret) {
9080 btrfs_put_block_group(cache);
9081 break;
9082 }
9083 ret = wait_block_group_cache_done(cache);
9084 if (ret) {
9085 btrfs_put_block_group(cache);
9086 break;
9087 }
f7039b1d
LD
9088 }
9089 ret = btrfs_trim_block_group(cache,
9090 &group_trimmed,
9091 start,
9092 end,
9093 range->minlen);
9094
9095 trimmed += group_trimmed;
9096 if (ret) {
9097 btrfs_put_block_group(cache);
9098 break;
9099 }
9100 }
9101
9102 cache = next_block_group(fs_info->tree_root, cache);
9103 }
9104
9105 range->len = trimmed;
9106 return ret;
9107}
8257b2dc
MX
9108
9109/*
9110 * btrfs_{start,end}_write() is similar to mnt_{want, drop}_write(),
9111 * they are used to prevent the some tasks writing data into the page cache
9112 * by nocow before the subvolume is snapshoted, but flush the data into
9113 * the disk after the snapshot creation.
9114 */
9115void btrfs_end_nocow_write(struct btrfs_root *root)
9116{
9117 percpu_counter_dec(&root->subv_writers->counter);
9118 /*
9119 * Make sure counter is updated before we wake up
9120 * waiters.
9121 */
9122 smp_mb();
9123 if (waitqueue_active(&root->subv_writers->wait))
9124 wake_up(&root->subv_writers->wait);
9125}
9126
9127int btrfs_start_nocow_write(struct btrfs_root *root)
9128{
9129 if (unlikely(atomic_read(&root->will_be_snapshoted)))
9130 return 0;
9131
9132 percpu_counter_inc(&root->subv_writers->counter);
9133 /*
9134 * Make sure counter is updated before we check for snapshot creation.
9135 */
9136 smp_mb();
9137 if (unlikely(atomic_read(&root->will_be_snapshoted))) {
9138 btrfs_end_nocow_write(root);
9139 return 0;
9140 }
9141 return 1;
9142}