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