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