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