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