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