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