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