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