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