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