]> bbs.cooldavid.org Git - net-next-2.6.git/blame - fs/btrfs/extent-tree.c
Btrfs: avoid null deref in unpin_extent_cache()
[net-next-2.6.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
444528b3
CM
3689 /*
3690 * discard is sloooow, and so triggering discards on
3691 * individual btree blocks isn't a good plan. Just
3692 * pin everything in discard mode.
3693 */
3694 if (btrfs_test_opt(root, DISCARD))
3695 goto pinit;
3696
31840ae1
ZY
3697 buf = btrfs_find_tree_block(root, bytenr, num_bytes);
3698 if (!buf)
3699 goto pinit;
3700
3701 /* we can reuse a block if it hasn't been written
3702 * and it is from this transaction. We can't
3703 * reuse anything from the tree log root because
3704 * it has tiny sub-transactions.
3705 */
3706 if (btrfs_buffer_uptodate(buf, 0) &&
3707 btrfs_try_tree_lock(buf)) {
3708 u64 header_owner = btrfs_header_owner(buf);
3709 u64 header_transid = btrfs_header_generation(buf);
3710 if (header_owner != BTRFS_TREE_LOG_OBJECTID &&
3711 header_transid == trans->transid &&
3712 !btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
b9473439 3713 *must_clean = buf;
31840ae1 3714 return 1;
8ef97622 3715 }
31840ae1 3716 btrfs_tree_unlock(buf);
f4b9aa8d 3717 }
31840ae1
ZY
3718 free_extent_buffer(buf);
3719pinit:
11833d66
YZ
3720 if (path)
3721 btrfs_set_path_blocking(path);
b9473439 3722 /* unlocks the pinned mutex */
11833d66 3723 btrfs_pin_extent(root, bytenr, num_bytes, reserved);
31840ae1 3724
be744175 3725 BUG_ON(err < 0);
e20d96d6
CM
3726 return 0;
3727}
3728
5d4f98a2
YZ
3729static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
3730 struct btrfs_root *root,
3731 u64 bytenr, u64 num_bytes, u64 parent,
3732 u64 root_objectid, u64 owner_objectid,
3733 u64 owner_offset, int refs_to_drop,
3734 struct btrfs_delayed_extent_op *extent_op)
a28ec197 3735{
e2fa7227 3736 struct btrfs_key key;
5d4f98a2 3737 struct btrfs_path *path;
1261ec42
CM
3738 struct btrfs_fs_info *info = root->fs_info;
3739 struct btrfs_root *extent_root = info->extent_root;
5f39d397 3740 struct extent_buffer *leaf;
5d4f98a2
YZ
3741 struct btrfs_extent_item *ei;
3742 struct btrfs_extent_inline_ref *iref;
a28ec197 3743 int ret;
5d4f98a2 3744 int is_data;
952fccac
CM
3745 int extent_slot = 0;
3746 int found_extent = 0;
3747 int num_to_del = 1;
5d4f98a2
YZ
3748 u32 item_size;
3749 u64 refs;
037e6390 3750
5caf2a00 3751 path = btrfs_alloc_path();
54aa1f4d
CM
3752 if (!path)
3753 return -ENOMEM;
5f26f772 3754
3c12ac72 3755 path->reada = 1;
b9473439 3756 path->leave_spinning = 1;
5d4f98a2
YZ
3757
3758 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
3759 BUG_ON(!is_data && refs_to_drop != 1);
3760
3761 ret = lookup_extent_backref(trans, extent_root, path, &iref,
3762 bytenr, num_bytes, parent,
3763 root_objectid, owner_objectid,
3764 owner_offset);
7bb86316 3765 if (ret == 0) {
952fccac 3766 extent_slot = path->slots[0];
5d4f98a2
YZ
3767 while (extent_slot >= 0) {
3768 btrfs_item_key_to_cpu(path->nodes[0], &key,
952fccac 3769 extent_slot);
5d4f98a2 3770 if (key.objectid != bytenr)
952fccac 3771 break;
5d4f98a2
YZ
3772 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
3773 key.offset == num_bytes) {
952fccac
CM
3774 found_extent = 1;
3775 break;
3776 }
3777 if (path->slots[0] - extent_slot > 5)
3778 break;
5d4f98a2 3779 extent_slot--;
952fccac 3780 }
5d4f98a2
YZ
3781#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3782 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
3783 if (found_extent && item_size < sizeof(*ei))
3784 found_extent = 0;
3785#endif
31840ae1 3786 if (!found_extent) {
5d4f98a2 3787 BUG_ON(iref);
56bec294 3788 ret = remove_extent_backref(trans, extent_root, path,
5d4f98a2
YZ
3789 NULL, refs_to_drop,
3790 is_data);
31840ae1
ZY
3791 BUG_ON(ret);
3792 btrfs_release_path(extent_root, path);
b9473439 3793 path->leave_spinning = 1;
5d4f98a2
YZ
3794
3795 key.objectid = bytenr;
3796 key.type = BTRFS_EXTENT_ITEM_KEY;
3797 key.offset = num_bytes;
3798
31840ae1
ZY
3799 ret = btrfs_search_slot(trans, extent_root,
3800 &key, path, -1, 1);
f3465ca4
JB
3801 if (ret) {
3802 printk(KERN_ERR "umm, got %d back from search"
d397712b
CM
3803 ", was looking for %llu\n", ret,
3804 (unsigned long long)bytenr);
f3465ca4
JB
3805 btrfs_print_leaf(extent_root, path->nodes[0]);
3806 }
31840ae1
ZY
3807 BUG_ON(ret);
3808 extent_slot = path->slots[0];
3809 }
7bb86316
CM
3810 } else {
3811 btrfs_print_leaf(extent_root, path->nodes[0]);
3812 WARN_ON(1);
d397712b 3813 printk(KERN_ERR "btrfs unable to find ref byte nr %llu "
5d4f98a2 3814 "parent %llu root %llu owner %llu offset %llu\n",
d397712b 3815 (unsigned long long)bytenr,
56bec294 3816 (unsigned long long)parent,
d397712b 3817 (unsigned long long)root_objectid,
5d4f98a2
YZ
3818 (unsigned long long)owner_objectid,
3819 (unsigned long long)owner_offset);
7bb86316 3820 }
5f39d397
CM
3821
3822 leaf = path->nodes[0];
5d4f98a2
YZ
3823 item_size = btrfs_item_size_nr(leaf, extent_slot);
3824#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3825 if (item_size < sizeof(*ei)) {
3826 BUG_ON(found_extent || extent_slot != path->slots[0]);
3827 ret = convert_extent_item_v0(trans, extent_root, path,
3828 owner_objectid, 0);
3829 BUG_ON(ret < 0);
3830
3831 btrfs_release_path(extent_root, path);
3832 path->leave_spinning = 1;
3833
3834 key.objectid = bytenr;
3835 key.type = BTRFS_EXTENT_ITEM_KEY;
3836 key.offset = num_bytes;
3837
3838 ret = btrfs_search_slot(trans, extent_root, &key, path,
3839 -1, 1);
3840 if (ret) {
3841 printk(KERN_ERR "umm, got %d back from search"
3842 ", was looking for %llu\n", ret,
3843 (unsigned long long)bytenr);
3844 btrfs_print_leaf(extent_root, path->nodes[0]);
3845 }
3846 BUG_ON(ret);
3847 extent_slot = path->slots[0];
3848 leaf = path->nodes[0];
3849 item_size = btrfs_item_size_nr(leaf, extent_slot);
3850 }
3851#endif
3852 BUG_ON(item_size < sizeof(*ei));
952fccac 3853 ei = btrfs_item_ptr(leaf, extent_slot,
123abc88 3854 struct btrfs_extent_item);
5d4f98a2
YZ
3855 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID) {
3856 struct btrfs_tree_block_info *bi;
3857 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
3858 bi = (struct btrfs_tree_block_info *)(ei + 1);
3859 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
3860 }
56bec294 3861
5d4f98a2 3862 refs = btrfs_extent_refs(leaf, ei);
56bec294
CM
3863 BUG_ON(refs < refs_to_drop);
3864 refs -= refs_to_drop;
5f39d397 3865
5d4f98a2
YZ
3866 if (refs > 0) {
3867 if (extent_op)
3868 __run_delayed_extent_op(extent_op, leaf, ei);
3869 /*
3870 * In the case of inline back ref, reference count will
3871 * be updated by remove_extent_backref
952fccac 3872 */
5d4f98a2
YZ
3873 if (iref) {
3874 BUG_ON(!found_extent);
3875 } else {
3876 btrfs_set_extent_refs(leaf, ei, refs);
3877 btrfs_mark_buffer_dirty(leaf);
3878 }
3879 if (found_extent) {
3880 ret = remove_extent_backref(trans, extent_root, path,
3881 iref, refs_to_drop,
3882 is_data);
952fccac
CM
3883 BUG_ON(ret);
3884 }
5d4f98a2
YZ
3885 } else {
3886 int mark_free = 0;
b9473439 3887 struct extent_buffer *must_clean = NULL;
78fae27e 3888
5d4f98a2
YZ
3889 if (found_extent) {
3890 BUG_ON(is_data && refs_to_drop !=
3891 extent_data_ref_count(root, path, iref));
3892 if (iref) {
3893 BUG_ON(path->slots[0] != extent_slot);
3894 } else {
3895 BUG_ON(path->slots[0] != extent_slot + 1);
3896 path->slots[0] = extent_slot;
3897 num_to_del = 2;
3898 }
78fae27e 3899 }
b9473439 3900
5d4f98a2 3901 ret = pin_down_bytes(trans, root, path, bytenr,
11833d66 3902 num_bytes, is_data, 0, &must_clean);
5d4f98a2
YZ
3903 if (ret > 0)
3904 mark_free = 1;
3905 BUG_ON(ret < 0);
b9473439
CM
3906 /*
3907 * it is going to be very rare for someone to be waiting
3908 * on the block we're freeing. del_items might need to
3909 * schedule, so rather than get fancy, just force it
3910 * to blocking here
3911 */
3912 if (must_clean)
3913 btrfs_set_lock_blocking(must_clean);
3914
952fccac
CM
3915 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
3916 num_to_del);
31840ae1 3917 BUG_ON(ret);
25179201 3918 btrfs_release_path(extent_root, path);
21af804c 3919
b9473439
CM
3920 if (must_clean) {
3921 clean_tree_block(NULL, root, must_clean);
3922 btrfs_tree_unlock(must_clean);
3923 free_extent_buffer(must_clean);
3924 }
3925
5d4f98a2 3926 if (is_data) {
459931ec
CM
3927 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
3928 BUG_ON(ret);
d57e62b8
CM
3929 } else {
3930 invalidate_mapping_pages(info->btree_inode->i_mapping,
3931 bytenr >> PAGE_CACHE_SHIFT,
3932 (bytenr + num_bytes - 1) >> PAGE_CACHE_SHIFT);
459931ec
CM
3933 }
3934
dcbdd4dc
CM
3935 ret = update_block_group(trans, root, bytenr, num_bytes, 0,
3936 mark_free);
3937 BUG_ON(ret);
a28ec197 3938 }
5caf2a00 3939 btrfs_free_path(path);
a28ec197
CM
3940 return ret;
3941}
3942
1887be66
CM
3943/*
3944 * when we free an extent, it is possible (and likely) that we free the last
3945 * delayed ref for that extent as well. This searches the delayed ref tree for
3946 * a given extent, and if there are no other delayed refs to be processed, it
3947 * removes it from the tree.
3948 */
3949static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
3950 struct btrfs_root *root, u64 bytenr)
3951{
3952 struct btrfs_delayed_ref_head *head;
3953 struct btrfs_delayed_ref_root *delayed_refs;
3954 struct btrfs_delayed_ref_node *ref;
3955 struct rb_node *node;
3956 int ret;
3957
3958 delayed_refs = &trans->transaction->delayed_refs;
3959 spin_lock(&delayed_refs->lock);
3960 head = btrfs_find_delayed_ref_head(trans, bytenr);
3961 if (!head)
3962 goto out;
3963
3964 node = rb_prev(&head->node.rb_node);
3965 if (!node)
3966 goto out;
3967
3968 ref = rb_entry(node, struct btrfs_delayed_ref_node, rb_node);
3969
3970 /* there are still entries for this ref, we can't drop it */
3971 if (ref->bytenr == bytenr)
3972 goto out;
3973
5d4f98a2
YZ
3974 if (head->extent_op) {
3975 if (!head->must_insert_reserved)
3976 goto out;
3977 kfree(head->extent_op);
3978 head->extent_op = NULL;
3979 }
3980
1887be66
CM
3981 /*
3982 * waiting for the lock here would deadlock. If someone else has it
3983 * locked they are already in the process of dropping it anyway
3984 */
3985 if (!mutex_trylock(&head->mutex))
3986 goto out;
3987
3988 /*
3989 * at this point we have a head with no other entries. Go
3990 * ahead and process it.
3991 */
3992 head->node.in_tree = 0;
3993 rb_erase(&head->node.rb_node, &delayed_refs->root);
c3e69d58 3994
1887be66
CM
3995 delayed_refs->num_entries--;
3996
3997 /*
3998 * we don't take a ref on the node because we're removing it from the
3999 * tree, so we just steal the ref the tree was holding.
4000 */
c3e69d58
CM
4001 delayed_refs->num_heads--;
4002 if (list_empty(&head->cluster))
4003 delayed_refs->num_heads_ready--;
4004
4005 list_del_init(&head->cluster);
1887be66
CM
4006 spin_unlock(&delayed_refs->lock);
4007
4008 ret = run_one_delayed_ref(trans, root->fs_info->tree_root,
5d4f98a2
YZ
4009 &head->node, head->extent_op,
4010 head->must_insert_reserved);
1887be66
CM
4011 BUG_ON(ret);
4012 btrfs_put_delayed_ref(&head->node);
4013 return 0;
4014out:
4015 spin_unlock(&delayed_refs->lock);
4016 return 0;
4017}
4018
925baedd 4019int btrfs_free_extent(struct btrfs_trans_handle *trans,
31840ae1
ZY
4020 struct btrfs_root *root,
4021 u64 bytenr, u64 num_bytes, u64 parent,
5d4f98a2 4022 u64 root_objectid, u64 owner, u64 offset)
925baedd
CM
4023{
4024 int ret;
4025
56bec294
CM
4026 /*
4027 * tree log blocks never actually go into the extent allocation
4028 * tree, just update pinning info and exit early.
56bec294 4029 */
5d4f98a2
YZ
4030 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
4031 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
b9473439 4032 /* unlocks the pinned mutex */
11833d66 4033 btrfs_pin_extent(root, bytenr, num_bytes, 1);
56bec294 4034 ret = 0;
5d4f98a2
YZ
4035 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
4036 ret = btrfs_add_delayed_tree_ref(trans, bytenr, num_bytes,
4037 parent, root_objectid, (int)owner,
4038 BTRFS_DROP_DELAYED_REF, NULL);
1887be66
CM
4039 BUG_ON(ret);
4040 ret = check_ref_cleanup(trans, root, bytenr);
4041 BUG_ON(ret);
5d4f98a2
YZ
4042 } else {
4043 ret = btrfs_add_delayed_data_ref(trans, bytenr, num_bytes,
4044 parent, root_objectid, owner,
4045 offset, BTRFS_DROP_DELAYED_REF, NULL);
4046 BUG_ON(ret);
56bec294 4047 }
925baedd
CM
4048 return ret;
4049}
4050
87ee04eb
CM
4051static u64 stripe_align(struct btrfs_root *root, u64 val)
4052{
4053 u64 mask = ((u64)root->stripesize - 1);
4054 u64 ret = (val + mask) & ~mask;
4055 return ret;
4056}
4057
817d52f8
JB
4058/*
4059 * when we wait for progress in the block group caching, its because
4060 * our allocation attempt failed at least once. So, we must sleep
4061 * and let some progress happen before we try again.
4062 *
4063 * This function will sleep at least once waiting for new free space to
4064 * show up, and then it will check the block group free space numbers
4065 * for our min num_bytes. Another option is to have it go ahead
4066 * and look in the rbtree for a free extent of a given size, but this
4067 * is a good start.
4068 */
4069static noinline int
4070wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
4071 u64 num_bytes)
4072{
11833d66 4073 struct btrfs_caching_control *caching_ctl;
817d52f8
JB
4074 DEFINE_WAIT(wait);
4075
11833d66
YZ
4076 caching_ctl = get_caching_control(cache);
4077 if (!caching_ctl)
817d52f8 4078 return 0;
817d52f8 4079
11833d66 4080 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
817d52f8 4081 (cache->free_space >= num_bytes));
11833d66
YZ
4082
4083 put_caching_control(caching_ctl);
4084 return 0;
4085}
4086
4087static noinline int
4088wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
4089{
4090 struct btrfs_caching_control *caching_ctl;
4091 DEFINE_WAIT(wait);
4092
4093 caching_ctl = get_caching_control(cache);
4094 if (!caching_ctl)
4095 return 0;
4096
4097 wait_event(caching_ctl->wait, block_group_cache_done(cache));
4098
4099 put_caching_control(caching_ctl);
817d52f8
JB
4100 return 0;
4101}
4102
4103enum btrfs_loop_type {
4104 LOOP_CACHED_ONLY = 0,
4105 LOOP_CACHING_NOWAIT = 1,
4106 LOOP_CACHING_WAIT = 2,
4107 LOOP_ALLOC_CHUNK = 3,
4108 LOOP_NO_EMPTY_SIZE = 4,
4109};
4110
fec577fb
CM
4111/*
4112 * walks the btree of allocated extents and find a hole of a given size.
4113 * The key ins is changed to record the hole:
4114 * ins->objectid == block start
62e2749e 4115 * ins->flags = BTRFS_EXTENT_ITEM_KEY
fec577fb
CM
4116 * ins->offset == number of blocks
4117 * Any available blocks before search_start are skipped.
4118 */
d397712b 4119static noinline int find_free_extent(struct btrfs_trans_handle *trans,
98ed5174
CM
4120 struct btrfs_root *orig_root,
4121 u64 num_bytes, u64 empty_size,
4122 u64 search_start, u64 search_end,
4123 u64 hint_byte, struct btrfs_key *ins,
4124 u64 exclude_start, u64 exclude_nr,
4125 int data)
fec577fb 4126{
80eb234a 4127 int ret = 0;
d397712b 4128 struct btrfs_root *root = orig_root->fs_info->extent_root;
fa9c0d79 4129 struct btrfs_free_cluster *last_ptr = NULL;
80eb234a 4130 struct btrfs_block_group_cache *block_group = NULL;
239b14b3 4131 int empty_cluster = 2 * 1024 * 1024;
0ef3e66b 4132 int allowed_chunk_alloc = 0;
80eb234a 4133 struct btrfs_space_info *space_info;
fa9c0d79
CM
4134 int last_ptr_loop = 0;
4135 int loop = 0;
817d52f8 4136 bool found_uncached_bg = false;
0a24325e 4137 bool failed_cluster_refill = false;
1cdda9b8 4138 bool failed_alloc = false;
fec577fb 4139
db94535d 4140 WARN_ON(num_bytes < root->sectorsize);
b1a4d965 4141 btrfs_set_key_type(ins, BTRFS_EXTENT_ITEM_KEY);
80eb234a
JB
4142 ins->objectid = 0;
4143 ins->offset = 0;
b1a4d965 4144
2552d17e
JB
4145 space_info = __find_space_info(root->fs_info, data);
4146
0ef3e66b
CM
4147 if (orig_root->ref_cows || empty_size)
4148 allowed_chunk_alloc = 1;
4149
239b14b3 4150 if (data & BTRFS_BLOCK_GROUP_METADATA) {
fa9c0d79 4151 last_ptr = &root->fs_info->meta_alloc_cluster;
536ac8ae
CM
4152 if (!btrfs_test_opt(root, SSD))
4153 empty_cluster = 64 * 1024;
239b14b3
CM
4154 }
4155
fa9c0d79
CM
4156 if ((data & BTRFS_BLOCK_GROUP_DATA) && btrfs_test_opt(root, SSD)) {
4157 last_ptr = &root->fs_info->data_alloc_cluster;
4158 }
0f9dd46c 4159
239b14b3 4160 if (last_ptr) {
fa9c0d79
CM
4161 spin_lock(&last_ptr->lock);
4162 if (last_ptr->block_group)
4163 hint_byte = last_ptr->window_start;
4164 spin_unlock(&last_ptr->lock);
239b14b3 4165 }
fa9c0d79 4166
a061fc8d 4167 search_start = max(search_start, first_logical_byte(root, 0));
239b14b3 4168 search_start = max(search_start, hint_byte);
0b86a832 4169
817d52f8 4170 if (!last_ptr)
fa9c0d79 4171 empty_cluster = 0;
fa9c0d79 4172
2552d17e 4173 if (search_start == hint_byte) {
2552d17e
JB
4174 block_group = btrfs_lookup_block_group(root->fs_info,
4175 search_start);
817d52f8
JB
4176 /*
4177 * we don't want to use the block group if it doesn't match our
4178 * allocation bits, or if its not cached.
4179 */
4180 if (block_group && block_group_bits(block_group, data) &&
4181 block_group_cache_done(block_group)) {
2552d17e 4182 down_read(&space_info->groups_sem);
44fb5511
CM
4183 if (list_empty(&block_group->list) ||
4184 block_group->ro) {
4185 /*
4186 * someone is removing this block group,
4187 * we can't jump into the have_block_group
4188 * target because our list pointers are not
4189 * valid
4190 */
4191 btrfs_put_block_group(block_group);
4192 up_read(&space_info->groups_sem);
4193 } else
4194 goto have_block_group;
2552d17e 4195 } else if (block_group) {
fa9c0d79 4196 btrfs_put_block_group(block_group);
2552d17e 4197 }
42e70e7a 4198 }
4366211c 4199
2552d17e 4200search:
80eb234a 4201 down_read(&space_info->groups_sem);
2552d17e 4202 list_for_each_entry(block_group, &space_info->block_groups, list) {
6226cb0a 4203 u64 offset;
817d52f8 4204 int cached;
8a1413a2 4205
2552d17e
JB
4206 atomic_inc(&block_group->count);
4207 search_start = block_group->key.objectid;
42e70e7a 4208
2552d17e 4209have_block_group:
817d52f8
JB
4210 if (unlikely(block_group->cached == BTRFS_CACHE_NO)) {
4211 /*
4212 * we want to start caching kthreads, but not too many
4213 * right off the bat so we don't overwhelm the system,
4214 * so only start them if there are less than 2 and we're
4215 * in the initial allocation phase.
4216 */
4217 if (loop > LOOP_CACHING_NOWAIT ||
4218 atomic_read(&space_info->caching_threads) < 2) {
4219 ret = cache_block_group(block_group);
4220 BUG_ON(ret);
2552d17e 4221 }
ea6a478e
JB
4222 }
4223
817d52f8
JB
4224 cached = block_group_cache_done(block_group);
4225 if (unlikely(!cached)) {
4226 found_uncached_bg = true;
4227
4228 /* if we only want cached bgs, loop */
4229 if (loop == LOOP_CACHED_ONLY)
4230 goto loop;
4231 }
4232
ea6a478e 4233 if (unlikely(block_group->ro))
2552d17e 4234 goto loop;
0f9dd46c 4235
0a24325e
JB
4236 /*
4237 * Ok we want to try and use the cluster allocator, so lets look
4238 * there, unless we are on LOOP_NO_EMPTY_SIZE, since we will
4239 * have tried the cluster allocator plenty of times at this
4240 * point and not have found anything, so we are likely way too
4241 * fragmented for the clustering stuff to find anything, so lets
4242 * just skip it and let the allocator find whatever block it can
4243 * find
4244 */
4245 if (last_ptr && loop < LOOP_NO_EMPTY_SIZE) {
fa9c0d79
CM
4246 /*
4247 * the refill lock keeps out other
4248 * people trying to start a new cluster
4249 */
4250 spin_lock(&last_ptr->refill_lock);
44fb5511
CM
4251 if (last_ptr->block_group &&
4252 (last_ptr->block_group->ro ||
4253 !block_group_bits(last_ptr->block_group, data))) {
4254 offset = 0;
4255 goto refill_cluster;
4256 }
4257
fa9c0d79
CM
4258 offset = btrfs_alloc_from_cluster(block_group, last_ptr,
4259 num_bytes, search_start);
4260 if (offset) {
4261 /* we have a block, we're done */
4262 spin_unlock(&last_ptr->refill_lock);
4263 goto checks;
4264 }
4265
4266 spin_lock(&last_ptr->lock);
4267 /*
4268 * whoops, this cluster doesn't actually point to
4269 * this block group. Get a ref on the block
4270 * group is does point to and try again
4271 */
4272 if (!last_ptr_loop && last_ptr->block_group &&
4273 last_ptr->block_group != block_group) {
4274
4275 btrfs_put_block_group(block_group);
4276 block_group = last_ptr->block_group;
4277 atomic_inc(&block_group->count);
4278 spin_unlock(&last_ptr->lock);
4279 spin_unlock(&last_ptr->refill_lock);
4280
4281 last_ptr_loop = 1;
4282 search_start = block_group->key.objectid;
44fb5511
CM
4283 /*
4284 * we know this block group is properly
4285 * in the list because
4286 * btrfs_remove_block_group, drops the
4287 * cluster before it removes the block
4288 * group from the list
4289 */
fa9c0d79
CM
4290 goto have_block_group;
4291 }
4292 spin_unlock(&last_ptr->lock);
44fb5511 4293refill_cluster:
fa9c0d79
CM
4294 /*
4295 * this cluster didn't work out, free it and
4296 * start over
4297 */
4298 btrfs_return_cluster_to_free_space(NULL, last_ptr);
4299
4300 last_ptr_loop = 0;
4301
4302 /* allocate a cluster in this block group */
451d7585 4303 ret = btrfs_find_space_cluster(trans, root,
fa9c0d79
CM
4304 block_group, last_ptr,
4305 offset, num_bytes,
4306 empty_cluster + empty_size);
4307 if (ret == 0) {
4308 /*
4309 * now pull our allocation out of this
4310 * cluster
4311 */
4312 offset = btrfs_alloc_from_cluster(block_group,
4313 last_ptr, num_bytes,
4314 search_start);
4315 if (offset) {
4316 /* we found one, proceed */
4317 spin_unlock(&last_ptr->refill_lock);
4318 goto checks;
4319 }
0a24325e
JB
4320 } else if (!cached && loop > LOOP_CACHING_NOWAIT
4321 && !failed_cluster_refill) {
817d52f8
JB
4322 spin_unlock(&last_ptr->refill_lock);
4323
0a24325e 4324 failed_cluster_refill = true;
817d52f8
JB
4325 wait_block_group_cache_progress(block_group,
4326 num_bytes + empty_cluster + empty_size);
4327 goto have_block_group;
fa9c0d79 4328 }
817d52f8 4329
fa9c0d79
CM
4330 /*
4331 * at this point we either didn't find a cluster
4332 * or we weren't able to allocate a block from our
4333 * cluster. Free the cluster we've been trying
4334 * to use, and go to the next block group
4335 */
0a24325e 4336 btrfs_return_cluster_to_free_space(NULL, last_ptr);
fa9c0d79 4337 spin_unlock(&last_ptr->refill_lock);
0a24325e 4338 goto loop;
fa9c0d79
CM
4339 }
4340
6226cb0a
JB
4341 offset = btrfs_find_space_for_alloc(block_group, search_start,
4342 num_bytes, empty_size);
1cdda9b8
JB
4343 /*
4344 * If we didn't find a chunk, and we haven't failed on this
4345 * block group before, and this block group is in the middle of
4346 * caching and we are ok with waiting, then go ahead and wait
4347 * for progress to be made, and set failed_alloc to true.
4348 *
4349 * If failed_alloc is true then we've already waited on this
4350 * block group once and should move on to the next block group.
4351 */
4352 if (!offset && !failed_alloc && !cached &&
4353 loop > LOOP_CACHING_NOWAIT) {
817d52f8 4354 wait_block_group_cache_progress(block_group,
1cdda9b8
JB
4355 num_bytes + empty_size);
4356 failed_alloc = true;
817d52f8 4357 goto have_block_group;
1cdda9b8
JB
4358 } else if (!offset) {
4359 goto loop;
817d52f8 4360 }
fa9c0d79 4361checks:
6226cb0a 4362 search_start = stripe_align(root, offset);
2552d17e 4363 /* move on to the next group */
6226cb0a
JB
4364 if (search_start + num_bytes >= search_end) {
4365 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e 4366 goto loop;
6226cb0a 4367 }
25179201 4368
2552d17e
JB
4369 /* move on to the next group */
4370 if (search_start + num_bytes >
6226cb0a
JB
4371 block_group->key.objectid + block_group->key.offset) {
4372 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e 4373 goto loop;
6226cb0a 4374 }
f5a31e16 4375
2552d17e
JB
4376 if (exclude_nr > 0 &&
4377 (search_start + num_bytes > exclude_start &&
4378 search_start < exclude_start + exclude_nr)) {
4379 search_start = exclude_start + exclude_nr;
4380
6226cb0a 4381 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e
JB
4382 /*
4383 * if search_start is still in this block group
4384 * then we just re-search this block group
f5a31e16 4385 */
2552d17e
JB
4386 if (search_start >= block_group->key.objectid &&
4387 search_start < (block_group->key.objectid +
6226cb0a 4388 block_group->key.offset))
2552d17e 4389 goto have_block_group;
2552d17e 4390 goto loop;
0f9dd46c 4391 }
0b86a832 4392
2552d17e
JB
4393 ins->objectid = search_start;
4394 ins->offset = num_bytes;
d2fb3437 4395
6226cb0a
JB
4396 if (offset < search_start)
4397 btrfs_add_free_space(block_group, offset,
4398 search_start - offset);
4399 BUG_ON(offset > search_start);
4400
11833d66
YZ
4401 update_reserved_extents(block_group, num_bytes, 1);
4402
2552d17e 4403 /* we are all good, lets return */
2552d17e
JB
4404 break;
4405loop:
0a24325e 4406 failed_cluster_refill = false;
1cdda9b8 4407 failed_alloc = false;
fa9c0d79 4408 btrfs_put_block_group(block_group);
2552d17e
JB
4409 }
4410 up_read(&space_info->groups_sem);
4411
817d52f8
JB
4412 /* LOOP_CACHED_ONLY, only search fully cached block groups
4413 * LOOP_CACHING_NOWAIT, search partially cached block groups, but
4414 * dont wait foR them to finish caching
4415 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
4416 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
4417 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
4418 * again
fa9c0d79 4419 */
817d52f8
JB
4420 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE &&
4421 (found_uncached_bg || empty_size || empty_cluster ||
4422 allowed_chunk_alloc)) {
4423 if (found_uncached_bg) {
4424 found_uncached_bg = false;
4425 if (loop < LOOP_CACHING_WAIT) {
4426 loop++;
4427 goto search;
4428 }
4429 }
4430
4431 if (loop == LOOP_ALLOC_CHUNK) {
fa9c0d79
CM
4432 empty_size = 0;
4433 empty_cluster = 0;
4434 }
2552d17e
JB
4435
4436 if (allowed_chunk_alloc) {
4437 ret = do_chunk_alloc(trans, root, num_bytes +
4438 2 * 1024 * 1024, data, 1);
2552d17e
JB
4439 allowed_chunk_alloc = 0;
4440 } else {
4441 space_info->force_alloc = 1;
4442 }
4443
817d52f8 4444 if (loop < LOOP_NO_EMPTY_SIZE) {
fa9c0d79 4445 loop++;
2552d17e 4446 goto search;
fa9c0d79 4447 }
2552d17e
JB
4448 ret = -ENOSPC;
4449 } else if (!ins->objectid) {
4450 ret = -ENOSPC;
f2654de4 4451 }
0b86a832 4452
80eb234a
JB
4453 /* we found what we needed */
4454 if (ins->objectid) {
4455 if (!(data & BTRFS_BLOCK_GROUP_DATA))
d2fb3437 4456 trans->block_group = block_group->key.objectid;
0f9dd46c 4457
fa9c0d79 4458 btrfs_put_block_group(block_group);
80eb234a 4459 ret = 0;
be744175 4460 }
be744175 4461
0f70abe2 4462 return ret;
fec577fb 4463}
ec44a35c 4464
9ed74f2d
JB
4465static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
4466 int dump_block_groups)
0f9dd46c
JB
4467{
4468 struct btrfs_block_group_cache *cache;
0f9dd46c 4469
9ed74f2d 4470 spin_lock(&info->lock);
d397712b
CM
4471 printk(KERN_INFO "space_info has %llu free, is %sfull\n",
4472 (unsigned long long)(info->total_bytes - info->bytes_used -
9ed74f2d
JB
4473 info->bytes_pinned - info->bytes_reserved -
4474 info->bytes_super),
d397712b 4475 (info->full) ? "" : "not ");
6a63209f 4476 printk(KERN_INFO "space_info total=%llu, pinned=%llu, delalloc=%llu,"
9ed74f2d
JB
4477 " may_use=%llu, used=%llu, root=%llu, super=%llu, reserved=%llu"
4478 "\n",
21380931
JB
4479 (unsigned long long)info->total_bytes,
4480 (unsigned long long)info->bytes_pinned,
4481 (unsigned long long)info->bytes_delalloc,
4482 (unsigned long long)info->bytes_may_use,
9ed74f2d
JB
4483 (unsigned long long)info->bytes_used,
4484 (unsigned long long)info->bytes_root,
4485 (unsigned long long)info->bytes_super,
4486 (unsigned long long)info->bytes_reserved);
4487 spin_unlock(&info->lock);
4488
4489 if (!dump_block_groups)
4490 return;
0f9dd46c 4491
80eb234a 4492 down_read(&info->groups_sem);
c6e30871 4493 list_for_each_entry(cache, &info->block_groups, list) {
0f9dd46c 4494 spin_lock(&cache->lock);
d397712b
CM
4495 printk(KERN_INFO "block group %llu has %llu bytes, %llu used "
4496 "%llu pinned %llu reserved\n",
4497 (unsigned long long)cache->key.objectid,
4498 (unsigned long long)cache->key.offset,
4499 (unsigned long long)btrfs_block_group_used(&cache->item),
4500 (unsigned long long)cache->pinned,
4501 (unsigned long long)cache->reserved);
0f9dd46c
JB
4502 btrfs_dump_free_space(cache, bytes);
4503 spin_unlock(&cache->lock);
4504 }
80eb234a 4505 up_read(&info->groups_sem);
0f9dd46c 4506}
e8569813 4507
11833d66
YZ
4508int btrfs_reserve_extent(struct btrfs_trans_handle *trans,
4509 struct btrfs_root *root,
4510 u64 num_bytes, u64 min_alloc_size,
4511 u64 empty_size, u64 hint_byte,
4512 u64 search_end, struct btrfs_key *ins,
4513 u64 data)
fec577fb
CM
4514{
4515 int ret;
fbdc762b 4516 u64 search_start = 0;
1261ec42 4517 struct btrfs_fs_info *info = root->fs_info;
925baedd 4518
6a63209f 4519 data = btrfs_get_alloc_profile(root, data);
98d20f67 4520again:
0ef3e66b
CM
4521 /*
4522 * the only place that sets empty_size is btrfs_realloc_node, which
4523 * is not called recursively on allocations
4524 */
4525 if (empty_size || root->ref_cows) {
593060d7 4526 if (!(data & BTRFS_BLOCK_GROUP_METADATA)) {
6324fbf3 4527 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
0ef3e66b
CM
4528 2 * 1024 * 1024,
4529 BTRFS_BLOCK_GROUP_METADATA |
4530 (info->metadata_alloc_profile &
4531 info->avail_metadata_alloc_bits), 0);
6324fbf3
CM
4532 }
4533 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
0ef3e66b 4534 num_bytes + 2 * 1024 * 1024, data, 0);
6324fbf3 4535 }
0b86a832 4536
db94535d
CM
4537 WARN_ON(num_bytes < root->sectorsize);
4538 ret = find_free_extent(trans, root, num_bytes, empty_size,
4539 search_start, search_end, hint_byte, ins,
26b8003f
CM
4540 trans->alloc_exclude_start,
4541 trans->alloc_exclude_nr, data);
3b951516 4542
98d20f67
CM
4543 if (ret == -ENOSPC && num_bytes > min_alloc_size) {
4544 num_bytes = num_bytes >> 1;
0f9dd46c 4545 num_bytes = num_bytes & ~(root->sectorsize - 1);
98d20f67 4546 num_bytes = max(num_bytes, min_alloc_size);
0ef3e66b
CM
4547 do_chunk_alloc(trans, root->fs_info->extent_root,
4548 num_bytes, data, 1);
98d20f67
CM
4549 goto again;
4550 }
817d52f8 4551 if (ret == -ENOSPC) {
0f9dd46c
JB
4552 struct btrfs_space_info *sinfo;
4553
4554 sinfo = __find_space_info(root->fs_info, data);
d397712b
CM
4555 printk(KERN_ERR "btrfs allocation failed flags %llu, "
4556 "wanted %llu\n", (unsigned long long)data,
4557 (unsigned long long)num_bytes);
9ed74f2d 4558 dump_space_info(sinfo, num_bytes, 1);
925baedd 4559 }
0f9dd46c
JB
4560
4561 return ret;
e6dcd2dc
CM
4562}
4563
65b51a00
CM
4564int btrfs_free_reserved_extent(struct btrfs_root *root, u64 start, u64 len)
4565{
0f9dd46c 4566 struct btrfs_block_group_cache *cache;
1f3c79a2 4567 int ret = 0;
0f9dd46c 4568
0f9dd46c
JB
4569 cache = btrfs_lookup_block_group(root->fs_info, start);
4570 if (!cache) {
d397712b
CM
4571 printk(KERN_ERR "Unable to find block group for %llu\n",
4572 (unsigned long long)start);
0f9dd46c
JB
4573 return -ENOSPC;
4574 }
1f3c79a2
LH
4575
4576 ret = btrfs_discard_extent(root, start, len);
4577
0f9dd46c 4578 btrfs_add_free_space(cache, start, len);
11833d66 4579 update_reserved_extents(cache, len, 0);
fa9c0d79 4580 btrfs_put_block_group(cache);
817d52f8 4581
e6dcd2dc
CM
4582 return ret;
4583}
4584
5d4f98a2
YZ
4585static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4586 struct btrfs_root *root,
4587 u64 parent, u64 root_objectid,
4588 u64 flags, u64 owner, u64 offset,
4589 struct btrfs_key *ins, int ref_mod)
e6dcd2dc
CM
4590{
4591 int ret;
5d4f98a2 4592 struct btrfs_fs_info *fs_info = root->fs_info;
e6dcd2dc 4593 struct btrfs_extent_item *extent_item;
5d4f98a2 4594 struct btrfs_extent_inline_ref *iref;
e6dcd2dc 4595 struct btrfs_path *path;
5d4f98a2
YZ
4596 struct extent_buffer *leaf;
4597 int type;
4598 u32 size;
26b8003f 4599
5d4f98a2
YZ
4600 if (parent > 0)
4601 type = BTRFS_SHARED_DATA_REF_KEY;
4602 else
4603 type = BTRFS_EXTENT_DATA_REF_KEY;
58176a96 4604
5d4f98a2 4605 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7bb86316
CM
4606
4607 path = btrfs_alloc_path();
4608 BUG_ON(!path);
47e4bb98 4609
b9473439 4610 path->leave_spinning = 1;
5d4f98a2
YZ
4611 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4612 ins, size);
ccd467d6 4613 BUG_ON(ret);
0f9dd46c 4614
5d4f98a2
YZ
4615 leaf = path->nodes[0];
4616 extent_item = btrfs_item_ptr(leaf, path->slots[0],
47e4bb98 4617 struct btrfs_extent_item);
5d4f98a2
YZ
4618 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
4619 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4620 btrfs_set_extent_flags(leaf, extent_item,
4621 flags | BTRFS_EXTENT_FLAG_DATA);
4622
4623 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
4624 btrfs_set_extent_inline_ref_type(leaf, iref, type);
4625 if (parent > 0) {
4626 struct btrfs_shared_data_ref *ref;
4627 ref = (struct btrfs_shared_data_ref *)(iref + 1);
4628 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4629 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
4630 } else {
4631 struct btrfs_extent_data_ref *ref;
4632 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
4633 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
4634 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
4635 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
4636 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
4637 }
47e4bb98
CM
4638
4639 btrfs_mark_buffer_dirty(path->nodes[0]);
7bb86316 4640 btrfs_free_path(path);
f510cfec 4641
5d4f98a2
YZ
4642 ret = update_block_group(trans, root, ins->objectid, ins->offset,
4643 1, 0);
f5947066 4644 if (ret) {
d397712b
CM
4645 printk(KERN_ERR "btrfs update block group failed for %llu "
4646 "%llu\n", (unsigned long long)ins->objectid,
4647 (unsigned long long)ins->offset);
f5947066
CM
4648 BUG();
4649 }
e6dcd2dc
CM
4650 return ret;
4651}
4652
5d4f98a2
YZ
4653static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
4654 struct btrfs_root *root,
4655 u64 parent, u64 root_objectid,
4656 u64 flags, struct btrfs_disk_key *key,
4657 int level, struct btrfs_key *ins)
e6dcd2dc
CM
4658{
4659 int ret;
5d4f98a2
YZ
4660 struct btrfs_fs_info *fs_info = root->fs_info;
4661 struct btrfs_extent_item *extent_item;
4662 struct btrfs_tree_block_info *block_info;
4663 struct btrfs_extent_inline_ref *iref;
4664 struct btrfs_path *path;
4665 struct extent_buffer *leaf;
4666 u32 size = sizeof(*extent_item) + sizeof(*block_info) + sizeof(*iref);
1c2308f8 4667
5d4f98a2
YZ
4668 path = btrfs_alloc_path();
4669 BUG_ON(!path);
56bec294 4670
5d4f98a2
YZ
4671 path->leave_spinning = 1;
4672 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
4673 ins, size);
56bec294 4674 BUG_ON(ret);
5d4f98a2
YZ
4675
4676 leaf = path->nodes[0];
4677 extent_item = btrfs_item_ptr(leaf, path->slots[0],
4678 struct btrfs_extent_item);
4679 btrfs_set_extent_refs(leaf, extent_item, 1);
4680 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
4681 btrfs_set_extent_flags(leaf, extent_item,
4682 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
4683 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
4684
4685 btrfs_set_tree_block_key(leaf, block_info, key);
4686 btrfs_set_tree_block_level(leaf, block_info, level);
4687
4688 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
4689 if (parent > 0) {
4690 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
4691 btrfs_set_extent_inline_ref_type(leaf, iref,
4692 BTRFS_SHARED_BLOCK_REF_KEY);
4693 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
4694 } else {
4695 btrfs_set_extent_inline_ref_type(leaf, iref,
4696 BTRFS_TREE_BLOCK_REF_KEY);
4697 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
4698 }
4699
4700 btrfs_mark_buffer_dirty(leaf);
4701 btrfs_free_path(path);
4702
4703 ret = update_block_group(trans, root, ins->objectid, ins->offset,
4704 1, 0);
4705 if (ret) {
4706 printk(KERN_ERR "btrfs update block group failed for %llu "
4707 "%llu\n", (unsigned long long)ins->objectid,
4708 (unsigned long long)ins->offset);
4709 BUG();
4710 }
4711 return ret;
4712}
4713
4714int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
4715 struct btrfs_root *root,
4716 u64 root_objectid, u64 owner,
4717 u64 offset, struct btrfs_key *ins)
4718{
4719 int ret;
4720
4721 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
4722
4723 ret = btrfs_add_delayed_data_ref(trans, ins->objectid, ins->offset,
4724 0, root_objectid, owner, offset,
4725 BTRFS_ADD_DELAYED_EXTENT, NULL);
e6dcd2dc
CM
4726 return ret;
4727}
e02119d5
CM
4728
4729/*
4730 * this is used by the tree logging recovery code. It records that
4731 * an extent has been allocated and makes sure to clear the free
4732 * space cache bits as well
4733 */
5d4f98a2
YZ
4734int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
4735 struct btrfs_root *root,
4736 u64 root_objectid, u64 owner, u64 offset,
4737 struct btrfs_key *ins)
e02119d5
CM
4738{
4739 int ret;
4740 struct btrfs_block_group_cache *block_group;
11833d66
YZ
4741 struct btrfs_caching_control *caching_ctl;
4742 u64 start = ins->objectid;
4743 u64 num_bytes = ins->offset;
e02119d5 4744
e02119d5 4745 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
817d52f8 4746 cache_block_group(block_group);
11833d66 4747 caching_ctl = get_caching_control(block_group);
e02119d5 4748
11833d66
YZ
4749 if (!caching_ctl) {
4750 BUG_ON(!block_group_cache_done(block_group));
4751 ret = btrfs_remove_free_space(block_group, start, num_bytes);
4752 BUG_ON(ret);
4753 } else {
4754 mutex_lock(&caching_ctl->mutex);
4755
4756 if (start >= caching_ctl->progress) {
4757 ret = add_excluded_extent(root, start, num_bytes);
4758 BUG_ON(ret);
4759 } else if (start + num_bytes <= caching_ctl->progress) {
4760 ret = btrfs_remove_free_space(block_group,
4761 start, num_bytes);
4762 BUG_ON(ret);
4763 } else {
4764 num_bytes = caching_ctl->progress - start;
4765 ret = btrfs_remove_free_space(block_group,
4766 start, num_bytes);
4767 BUG_ON(ret);
4768
4769 start = caching_ctl->progress;
4770 num_bytes = ins->objectid + ins->offset -
4771 caching_ctl->progress;
4772 ret = add_excluded_extent(root, start, num_bytes);
4773 BUG_ON(ret);
4774 }
4775
4776 mutex_unlock(&caching_ctl->mutex);
4777 put_caching_control(caching_ctl);
4778 }
4779
4780 update_reserved_extents(block_group, ins->offset, 1);
fa9c0d79 4781 btrfs_put_block_group(block_group);
5d4f98a2
YZ
4782 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
4783 0, owner, offset, ins, 1);
e02119d5
CM
4784 return ret;
4785}
4786
e6dcd2dc
CM
4787/*
4788 * finds a free extent and does all the dirty work required for allocation
4789 * returns the key for the extent through ins, and a tree buffer for
4790 * the first block of the extent through buf.
4791 *
4792 * returns 0 if everything worked, non-zero otherwise.
4793 */
5d4f98a2
YZ
4794static int alloc_tree_block(struct btrfs_trans_handle *trans,
4795 struct btrfs_root *root,
4796 u64 num_bytes, u64 parent, u64 root_objectid,
4797 struct btrfs_disk_key *key, int level,
4798 u64 empty_size, u64 hint_byte, u64 search_end,
4799 struct btrfs_key *ins)
e6dcd2dc
CM
4800{
4801 int ret;
5d4f98a2
YZ
4802 u64 flags = 0;
4803
11833d66
YZ
4804 ret = btrfs_reserve_extent(trans, root, num_bytes, num_bytes,
4805 empty_size, hint_byte, search_end,
4806 ins, 0);
817d52f8
JB
4807 if (ret)
4808 return ret;
5d4f98a2
YZ
4809
4810 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
4811 if (parent == 0)
4812 parent = ins->objectid;
4813 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
4814 } else
4815 BUG_ON(parent > 0);
4816
d00aff00 4817 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
5d4f98a2
YZ
4818 struct btrfs_delayed_extent_op *extent_op;
4819 extent_op = kmalloc(sizeof(*extent_op), GFP_NOFS);
4820 BUG_ON(!extent_op);
4821 if (key)
4822 memcpy(&extent_op->key, key, sizeof(extent_op->key));
4823 else
4824 memset(&extent_op->key, 0, sizeof(extent_op->key));
4825 extent_op->flags_to_set = flags;
4826 extent_op->update_key = 1;
4827 extent_op->update_flags = 1;
4828 extent_op->is_data = 0;
4829
4830 ret = btrfs_add_delayed_tree_ref(trans, ins->objectid,
4831 ins->offset, parent, root_objectid,
4832 level, BTRFS_ADD_DELAYED_EXTENT,
4833 extent_op);
d00aff00 4834 BUG_ON(ret);
d00aff00 4835 }
925baedd 4836 return ret;
fec577fb 4837}
65b51a00
CM
4838
4839struct extent_buffer *btrfs_init_new_buffer(struct btrfs_trans_handle *trans,
4840 struct btrfs_root *root,
4008c04a
CM
4841 u64 bytenr, u32 blocksize,
4842 int level)
65b51a00
CM
4843{
4844 struct extent_buffer *buf;
4845
4846 buf = btrfs_find_create_tree_block(root, bytenr, blocksize);
4847 if (!buf)
4848 return ERR_PTR(-ENOMEM);
4849 btrfs_set_header_generation(buf, trans->transid);
4008c04a 4850 btrfs_set_buffer_lockdep_class(buf, level);
65b51a00
CM
4851 btrfs_tree_lock(buf);
4852 clean_tree_block(trans, root, buf);
b4ce94de
CM
4853
4854 btrfs_set_lock_blocking(buf);
65b51a00 4855 btrfs_set_buffer_uptodate(buf);
b4ce94de 4856
d0c803c4
CM
4857 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
4858 set_extent_dirty(&root->dirty_log_pages, buf->start,
4859 buf->start + buf->len - 1, GFP_NOFS);
4860 } else {
4861 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
65b51a00 4862 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4 4863 }
65b51a00 4864 trans->blocks_used++;
b4ce94de 4865 /* this returns a buffer locked for blocking */
65b51a00
CM
4866 return buf;
4867}
4868
fec577fb
CM
4869/*
4870 * helper function to allocate a block for a given tree
4871 * returns the tree buffer or NULL.
4872 */
5f39d397 4873struct extent_buffer *btrfs_alloc_free_block(struct btrfs_trans_handle *trans,
5d4f98a2
YZ
4874 struct btrfs_root *root, u32 blocksize,
4875 u64 parent, u64 root_objectid,
4876 struct btrfs_disk_key *key, int level,
4877 u64 hint, u64 empty_size)
fec577fb 4878{
e2fa7227 4879 struct btrfs_key ins;
fec577fb 4880 int ret;
5f39d397 4881 struct extent_buffer *buf;
fec577fb 4882
5d4f98a2
YZ
4883 ret = alloc_tree_block(trans, root, blocksize, parent, root_objectid,
4884 key, level, empty_size, hint, (u64)-1, &ins);
fec577fb 4885 if (ret) {
54aa1f4d
CM
4886 BUG_ON(ret > 0);
4887 return ERR_PTR(ret);
fec577fb 4888 }
55c69072 4889
4008c04a
CM
4890 buf = btrfs_init_new_buffer(trans, root, ins.objectid,
4891 blocksize, level);
fec577fb
CM
4892 return buf;
4893}
a28ec197 4894
2c47e605
YZ
4895struct walk_control {
4896 u64 refs[BTRFS_MAX_LEVEL];
4897 u64 flags[BTRFS_MAX_LEVEL];
4898 struct btrfs_key update_progress;
4899 int stage;
4900 int level;
4901 int shared_level;
4902 int update_ref;
4903 int keep_locks;
1c4850e2
YZ
4904 int reada_slot;
4905 int reada_count;
2c47e605
YZ
4906};
4907
4908#define DROP_REFERENCE 1
4909#define UPDATE_BACKREF 2
4910
1c4850e2
YZ
4911static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
4912 struct btrfs_root *root,
4913 struct walk_control *wc,
4914 struct btrfs_path *path)
4915{
4916 u64 bytenr;
4917 u64 generation;
4918 u64 refs;
94fcca9f 4919 u64 flags;
1c4850e2
YZ
4920 u64 last = 0;
4921 u32 nritems;
4922 u32 blocksize;
4923 struct btrfs_key key;
4924 struct extent_buffer *eb;
4925 int ret;
4926 int slot;
4927 int nread = 0;
4928
4929 if (path->slots[wc->level] < wc->reada_slot) {
4930 wc->reada_count = wc->reada_count * 2 / 3;
4931 wc->reada_count = max(wc->reada_count, 2);
4932 } else {
4933 wc->reada_count = wc->reada_count * 3 / 2;
4934 wc->reada_count = min_t(int, wc->reada_count,
4935 BTRFS_NODEPTRS_PER_BLOCK(root));
4936 }
4937
4938 eb = path->nodes[wc->level];
4939 nritems = btrfs_header_nritems(eb);
4940 blocksize = btrfs_level_size(root, wc->level - 1);
4941
4942 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
4943 if (nread >= wc->reada_count)
4944 break;
4945
4946 cond_resched();
4947 bytenr = btrfs_node_blockptr(eb, slot);
4948 generation = btrfs_node_ptr_generation(eb, slot);
4949
4950 if (slot == path->slots[wc->level])
4951 goto reada;
4952
4953 if (wc->stage == UPDATE_BACKREF &&
4954 generation <= root->root_key.offset)
4955 continue;
4956
94fcca9f
YZ
4957 /* We don't lock the tree block, it's OK to be racy here */
4958 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
4959 &refs, &flags);
4960 BUG_ON(ret);
4961 BUG_ON(refs == 0);
4962
1c4850e2 4963 if (wc->stage == DROP_REFERENCE) {
1c4850e2
YZ
4964 if (refs == 1)
4965 goto reada;
4966
94fcca9f
YZ
4967 if (wc->level == 1 &&
4968 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4969 continue;
1c4850e2
YZ
4970 if (!wc->update_ref ||
4971 generation <= root->root_key.offset)
4972 continue;
4973 btrfs_node_key_to_cpu(eb, &key, slot);
4974 ret = btrfs_comp_cpu_keys(&key,
4975 &wc->update_progress);
4976 if (ret < 0)
4977 continue;
94fcca9f
YZ
4978 } else {
4979 if (wc->level == 1 &&
4980 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
4981 continue;
1c4850e2
YZ
4982 }
4983reada:
4984 ret = readahead_tree_block(root, bytenr, blocksize,
4985 generation);
4986 if (ret)
4987 break;
4988 last = bytenr + blocksize;
4989 nread++;
4990 }
4991 wc->reada_slot = slot;
4992}
4993
f82d02d9 4994/*
2c47e605
YZ
4995 * hepler to process tree block while walking down the tree.
4996 *
2c47e605
YZ
4997 * when wc->stage == UPDATE_BACKREF, this function updates
4998 * back refs for pointers in the block.
4999 *
5000 * NOTE: return value 1 means we should stop walking down.
f82d02d9 5001 */
2c47e605 5002static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5d4f98a2 5003 struct btrfs_root *root,
2c47e605 5004 struct btrfs_path *path,
94fcca9f 5005 struct walk_control *wc, int lookup_info)
f82d02d9 5006{
2c47e605
YZ
5007 int level = wc->level;
5008 struct extent_buffer *eb = path->nodes[level];
2c47e605 5009 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
f82d02d9
YZ
5010 int ret;
5011
2c47e605
YZ
5012 if (wc->stage == UPDATE_BACKREF &&
5013 btrfs_header_owner(eb) != root->root_key.objectid)
5014 return 1;
f82d02d9 5015
2c47e605
YZ
5016 /*
5017 * when reference count of tree block is 1, it won't increase
5018 * again. once full backref flag is set, we never clear it.
5019 */
94fcca9f
YZ
5020 if (lookup_info &&
5021 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
5022 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
2c47e605
YZ
5023 BUG_ON(!path->locks[level]);
5024 ret = btrfs_lookup_extent_info(trans, root,
5025 eb->start, eb->len,
5026 &wc->refs[level],
5027 &wc->flags[level]);
5028 BUG_ON(ret);
5029 BUG_ON(wc->refs[level] == 0);
5030 }
5d4f98a2 5031
2c47e605
YZ
5032 if (wc->stage == DROP_REFERENCE) {
5033 if (wc->refs[level] > 1)
5034 return 1;
f82d02d9 5035
2c47e605
YZ
5036 if (path->locks[level] && !wc->keep_locks) {
5037 btrfs_tree_unlock(eb);
5038 path->locks[level] = 0;
5039 }
5040 return 0;
5041 }
f82d02d9 5042
2c47e605
YZ
5043 /* wc->stage == UPDATE_BACKREF */
5044 if (!(wc->flags[level] & flag)) {
5045 BUG_ON(!path->locks[level]);
5046 ret = btrfs_inc_ref(trans, root, eb, 1);
f82d02d9 5047 BUG_ON(ret);
2c47e605
YZ
5048 ret = btrfs_dec_ref(trans, root, eb, 0);
5049 BUG_ON(ret);
5050 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
5051 eb->len, flag, 0);
5052 BUG_ON(ret);
5053 wc->flags[level] |= flag;
5054 }
5055
5056 /*
5057 * the block is shared by multiple trees, so it's not good to
5058 * keep the tree lock
5059 */
5060 if (path->locks[level] && level > 0) {
5061 btrfs_tree_unlock(eb);
5062 path->locks[level] = 0;
5063 }
5064 return 0;
5065}
5066
1c4850e2
YZ
5067/*
5068 * hepler to process tree block pointer.
5069 *
5070 * when wc->stage == DROP_REFERENCE, this function checks
5071 * reference count of the block pointed to. if the block
5072 * is shared and we need update back refs for the subtree
5073 * rooted at the block, this function changes wc->stage to
5074 * UPDATE_BACKREF. if the block is shared and there is no
5075 * need to update back, this function drops the reference
5076 * to the block.
5077 *
5078 * NOTE: return value 1 means we should stop walking down.
5079 */
5080static noinline int do_walk_down(struct btrfs_trans_handle *trans,
5081 struct btrfs_root *root,
5082 struct btrfs_path *path,
94fcca9f 5083 struct walk_control *wc, int *lookup_info)
1c4850e2
YZ
5084{
5085 u64 bytenr;
5086 u64 generation;
5087 u64 parent;
5088 u32 blocksize;
5089 struct btrfs_key key;
5090 struct extent_buffer *next;
5091 int level = wc->level;
5092 int reada = 0;
5093 int ret = 0;
5094
5095 generation = btrfs_node_ptr_generation(path->nodes[level],
5096 path->slots[level]);
5097 /*
5098 * if the lower level block was created before the snapshot
5099 * was created, we know there is no need to update back refs
5100 * for the subtree
5101 */
5102 if (wc->stage == UPDATE_BACKREF &&
94fcca9f
YZ
5103 generation <= root->root_key.offset) {
5104 *lookup_info = 1;
1c4850e2 5105 return 1;
94fcca9f 5106 }
1c4850e2
YZ
5107
5108 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
5109 blocksize = btrfs_level_size(root, level - 1);
5110
5111 next = btrfs_find_tree_block(root, bytenr, blocksize);
5112 if (!next) {
5113 next = btrfs_find_create_tree_block(root, bytenr, blocksize);
5114 reada = 1;
5115 }
5116 btrfs_tree_lock(next);
5117 btrfs_set_lock_blocking(next);
5118
94fcca9f
YZ
5119 ret = btrfs_lookup_extent_info(trans, root, bytenr, blocksize,
5120 &wc->refs[level - 1],
5121 &wc->flags[level - 1]);
5122 BUG_ON(ret);
5123 BUG_ON(wc->refs[level - 1] == 0);
5124 *lookup_info = 0;
1c4850e2 5125
94fcca9f 5126 if (wc->stage == DROP_REFERENCE) {
1c4850e2 5127 if (wc->refs[level - 1] > 1) {
94fcca9f
YZ
5128 if (level == 1 &&
5129 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5130 goto skip;
5131
1c4850e2
YZ
5132 if (!wc->update_ref ||
5133 generation <= root->root_key.offset)
5134 goto skip;
5135
5136 btrfs_node_key_to_cpu(path->nodes[level], &key,
5137 path->slots[level]);
5138 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
5139 if (ret < 0)
5140 goto skip;
5141
5142 wc->stage = UPDATE_BACKREF;
5143 wc->shared_level = level - 1;
5144 }
94fcca9f
YZ
5145 } else {
5146 if (level == 1 &&
5147 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
5148 goto skip;
1c4850e2
YZ
5149 }
5150
5151 if (!btrfs_buffer_uptodate(next, generation)) {
5152 btrfs_tree_unlock(next);
5153 free_extent_buffer(next);
5154 next = NULL;
94fcca9f 5155 *lookup_info = 1;
1c4850e2
YZ
5156 }
5157
5158 if (!next) {
5159 if (reada && level == 1)
5160 reada_walk_down(trans, root, wc, path);
5161 next = read_tree_block(root, bytenr, blocksize, generation);
5162 btrfs_tree_lock(next);
5163 btrfs_set_lock_blocking(next);
5164 }
5165
5166 level--;
5167 BUG_ON(level != btrfs_header_level(next));
5168 path->nodes[level] = next;
5169 path->slots[level] = 0;
5170 path->locks[level] = 1;
5171 wc->level = level;
5172 if (wc->level == 1)
5173 wc->reada_slot = 0;
5174 return 0;
5175skip:
5176 wc->refs[level - 1] = 0;
5177 wc->flags[level - 1] = 0;
94fcca9f
YZ
5178 if (wc->stage == DROP_REFERENCE) {
5179 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
5180 parent = path->nodes[level]->start;
5181 } else {
5182 BUG_ON(root->root_key.objectid !=
5183 btrfs_header_owner(path->nodes[level]));
5184 parent = 0;
5185 }
1c4850e2 5186
94fcca9f
YZ
5187 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
5188 root->root_key.objectid, level - 1, 0);
5189 BUG_ON(ret);
1c4850e2 5190 }
1c4850e2
YZ
5191 btrfs_tree_unlock(next);
5192 free_extent_buffer(next);
94fcca9f 5193 *lookup_info = 1;
1c4850e2
YZ
5194 return 1;
5195}
5196
2c47e605
YZ
5197/*
5198 * hepler to process tree block while walking up the tree.
5199 *
5200 * when wc->stage == DROP_REFERENCE, this function drops
5201 * reference count on the block.
5202 *
5203 * when wc->stage == UPDATE_BACKREF, this function changes
5204 * wc->stage back to DROP_REFERENCE if we changed wc->stage
5205 * to UPDATE_BACKREF previously while processing the block.
5206 *
5207 * NOTE: return value 1 means we should stop walking up.
5208 */
5209static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
5210 struct btrfs_root *root,
5211 struct btrfs_path *path,
5212 struct walk_control *wc)
5213{
5214 int ret = 0;
5215 int level = wc->level;
5216 struct extent_buffer *eb = path->nodes[level];
5217 u64 parent = 0;
5218
5219 if (wc->stage == UPDATE_BACKREF) {
5220 BUG_ON(wc->shared_level < level);
5221 if (level < wc->shared_level)
5222 goto out;
5223
2c47e605
YZ
5224 ret = find_next_key(path, level + 1, &wc->update_progress);
5225 if (ret > 0)
5226 wc->update_ref = 0;
5227
5228 wc->stage = DROP_REFERENCE;
5229 wc->shared_level = -1;
5230 path->slots[level] = 0;
5231
5232 /*
5233 * check reference count again if the block isn't locked.
5234 * we should start walking down the tree again if reference
5235 * count is one.
5236 */
5237 if (!path->locks[level]) {
5238 BUG_ON(level == 0);
5239 btrfs_tree_lock(eb);
5240 btrfs_set_lock_blocking(eb);
5241 path->locks[level] = 1;
5242
5243 ret = btrfs_lookup_extent_info(trans, root,
5244 eb->start, eb->len,
5245 &wc->refs[level],
5246 &wc->flags[level]);
f82d02d9 5247 BUG_ON(ret);
2c47e605
YZ
5248 BUG_ON(wc->refs[level] == 0);
5249 if (wc->refs[level] == 1) {
5250 btrfs_tree_unlock(eb);
5251 path->locks[level] = 0;
5252 return 1;
5253 }
f82d02d9 5254 }
2c47e605 5255 }
f82d02d9 5256
2c47e605
YZ
5257 /* wc->stage == DROP_REFERENCE */
5258 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5d4f98a2 5259
2c47e605
YZ
5260 if (wc->refs[level] == 1) {
5261 if (level == 0) {
5262 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5263 ret = btrfs_dec_ref(trans, root, eb, 1);
5264 else
5265 ret = btrfs_dec_ref(trans, root, eb, 0);
5266 BUG_ON(ret);
5267 }
5268 /* make block locked assertion in clean_tree_block happy */
5269 if (!path->locks[level] &&
5270 btrfs_header_generation(eb) == trans->transid) {
5271 btrfs_tree_lock(eb);
5272 btrfs_set_lock_blocking(eb);
5273 path->locks[level] = 1;
5274 }
5275 clean_tree_block(trans, root, eb);
5276 }
5277
5278 if (eb == root->node) {
5279 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5280 parent = eb->start;
5281 else
5282 BUG_ON(root->root_key.objectid !=
5283 btrfs_header_owner(eb));
5284 } else {
5285 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
5286 parent = path->nodes[level + 1]->start;
5287 else
5288 BUG_ON(root->root_key.objectid !=
5289 btrfs_header_owner(path->nodes[level + 1]));
f82d02d9 5290 }
f82d02d9 5291
2c47e605
YZ
5292 ret = btrfs_free_extent(trans, root, eb->start, eb->len, parent,
5293 root->root_key.objectid, level, 0);
f82d02d9 5294 BUG_ON(ret);
2c47e605
YZ
5295out:
5296 wc->refs[level] = 0;
5297 wc->flags[level] = 0;
5298 return ret;
5299}
5300
5301static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
5302 struct btrfs_root *root,
5303 struct btrfs_path *path,
5304 struct walk_control *wc)
5305{
2c47e605 5306 int level = wc->level;
94fcca9f 5307 int lookup_info = 1;
2c47e605
YZ
5308 int ret;
5309
5310 while (level >= 0) {
1c4850e2
YZ
5311 if (path->slots[level] >=
5312 btrfs_header_nritems(path->nodes[level]))
5313 break;
f82d02d9 5314
94fcca9f 5315 ret = walk_down_proc(trans, root, path, wc, lookup_info);
2c47e605
YZ
5316 if (ret > 0)
5317 break;
5318
5319 if (level == 0)
5320 break;
5321
94fcca9f 5322 ret = do_walk_down(trans, root, path, wc, &lookup_info);
1c4850e2
YZ
5323 if (ret > 0) {
5324 path->slots[level]++;
5325 continue;
5326 }
5327 level = wc->level;
f82d02d9 5328 }
f82d02d9
YZ
5329 return 0;
5330}
5331
d397712b 5332static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
98ed5174 5333 struct btrfs_root *root,
f82d02d9 5334 struct btrfs_path *path,
2c47e605 5335 struct walk_control *wc, int max_level)
20524f02 5336{
2c47e605 5337 int level = wc->level;
20524f02 5338 int ret;
9f3a7427 5339
2c47e605
YZ
5340 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
5341 while (level < max_level && path->nodes[level]) {
5342 wc->level = level;
5343 if (path->slots[level] + 1 <
5344 btrfs_header_nritems(path->nodes[level])) {
5345 path->slots[level]++;
20524f02
CM
5346 return 0;
5347 } else {
2c47e605
YZ
5348 ret = walk_up_proc(trans, root, path, wc);
5349 if (ret > 0)
5350 return 0;
bd56b302 5351
2c47e605
YZ
5352 if (path->locks[level]) {
5353 btrfs_tree_unlock(path->nodes[level]);
5354 path->locks[level] = 0;
f82d02d9 5355 }
2c47e605
YZ
5356 free_extent_buffer(path->nodes[level]);
5357 path->nodes[level] = NULL;
5358 level++;
20524f02
CM
5359 }
5360 }
5361 return 1;
5362}
5363
9aca1d51 5364/*
2c47e605
YZ
5365 * drop a subvolume tree.
5366 *
5367 * this function traverses the tree freeing any blocks that only
5368 * referenced by the tree.
5369 *
5370 * when a shared tree block is found. this function decreases its
5371 * reference count by one. if update_ref is true, this function
5372 * also make sure backrefs for the shared block and all lower level
5373 * blocks are properly updated.
9aca1d51 5374 */
2c47e605 5375int btrfs_drop_snapshot(struct btrfs_root *root, int update_ref)
20524f02 5376{
5caf2a00 5377 struct btrfs_path *path;
2c47e605
YZ
5378 struct btrfs_trans_handle *trans;
5379 struct btrfs_root *tree_root = root->fs_info->tree_root;
9f3a7427 5380 struct btrfs_root_item *root_item = &root->root_item;
2c47e605
YZ
5381 struct walk_control *wc;
5382 struct btrfs_key key;
5383 int err = 0;
5384 int ret;
5385 int level;
20524f02 5386
5caf2a00
CM
5387 path = btrfs_alloc_path();
5388 BUG_ON(!path);
20524f02 5389
2c47e605
YZ
5390 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5391 BUG_ON(!wc);
5392
5393 trans = btrfs_start_transaction(tree_root, 1);
5394
9f3a7427 5395 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
2c47e605 5396 level = btrfs_header_level(root->node);
5d4f98a2
YZ
5397 path->nodes[level] = btrfs_lock_root_node(root);
5398 btrfs_set_lock_blocking(path->nodes[level]);
9f3a7427 5399 path->slots[level] = 0;
5d4f98a2 5400 path->locks[level] = 1;
2c47e605
YZ
5401 memset(&wc->update_progress, 0,
5402 sizeof(wc->update_progress));
9f3a7427 5403 } else {
9f3a7427 5404 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
2c47e605
YZ
5405 memcpy(&wc->update_progress, &key,
5406 sizeof(wc->update_progress));
5407
6702ed49 5408 level = root_item->drop_level;
2c47e605 5409 BUG_ON(level == 0);
6702ed49 5410 path->lowest_level = level;
2c47e605
YZ
5411 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5412 path->lowest_level = 0;
5413 if (ret < 0) {
5414 err = ret;
9f3a7427
CM
5415 goto out;
5416 }
1c4850e2 5417 WARN_ON(ret > 0);
2c47e605 5418
7d9eb12c
CM
5419 /*
5420 * unlock our path, this is safe because only this
5421 * function is allowed to delete this snapshot
5422 */
5d4f98a2 5423 btrfs_unlock_up_safe(path, 0);
2c47e605
YZ
5424
5425 level = btrfs_header_level(root->node);
5426 while (1) {
5427 btrfs_tree_lock(path->nodes[level]);
5428 btrfs_set_lock_blocking(path->nodes[level]);
5429
5430 ret = btrfs_lookup_extent_info(trans, root,
5431 path->nodes[level]->start,
5432 path->nodes[level]->len,
5433 &wc->refs[level],
5434 &wc->flags[level]);
5435 BUG_ON(ret);
5436 BUG_ON(wc->refs[level] == 0);
5437
5438 if (level == root_item->drop_level)
5439 break;
5440
5441 btrfs_tree_unlock(path->nodes[level]);
5442 WARN_ON(wc->refs[level] != 1);
5443 level--;
5444 }
9f3a7427 5445 }
2c47e605
YZ
5446
5447 wc->level = level;
5448 wc->shared_level = -1;
5449 wc->stage = DROP_REFERENCE;
5450 wc->update_ref = update_ref;
5451 wc->keep_locks = 0;
1c4850e2 5452 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
2c47e605 5453
d397712b 5454 while (1) {
2c47e605
YZ
5455 ret = walk_down_tree(trans, root, path, wc);
5456 if (ret < 0) {
5457 err = ret;
20524f02 5458 break;
2c47e605 5459 }
9aca1d51 5460
2c47e605
YZ
5461 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
5462 if (ret < 0) {
5463 err = ret;
20524f02 5464 break;
2c47e605
YZ
5465 }
5466
5467 if (ret > 0) {
5468 BUG_ON(wc->stage != DROP_REFERENCE);
e7a84565
CM
5469 break;
5470 }
2c47e605
YZ
5471
5472 if (wc->stage == DROP_REFERENCE) {
5473 level = wc->level;
5474 btrfs_node_key(path->nodes[level],
5475 &root_item->drop_progress,
5476 path->slots[level]);
5477 root_item->drop_level = level;
5478 }
5479
5480 BUG_ON(wc->level == 0);
5481 if (trans->transaction->in_commit ||
5482 trans->transaction->delayed_refs.flushing) {
5483 ret = btrfs_update_root(trans, tree_root,
5484 &root->root_key,
5485 root_item);
5486 BUG_ON(ret);
5487
5488 btrfs_end_transaction(trans, tree_root);
5489 trans = btrfs_start_transaction(tree_root, 1);
5490 } else {
5491 unsigned long update;
c3e69d58
CM
5492 update = trans->delayed_ref_updates;
5493 trans->delayed_ref_updates = 0;
5494 if (update)
2c47e605
YZ
5495 btrfs_run_delayed_refs(trans, tree_root,
5496 update);
c3e69d58 5497 }
20524f02 5498 }
2c47e605
YZ
5499 btrfs_release_path(root, path);
5500 BUG_ON(err);
5501
5502 ret = btrfs_del_root(trans, tree_root, &root->root_key);
5503 BUG_ON(ret);
5504
76dda93c
YZ
5505 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
5506 ret = btrfs_find_last_root(tree_root, root->root_key.objectid,
5507 NULL, NULL);
5508 BUG_ON(ret < 0);
5509 if (ret > 0) {
5510 ret = btrfs_del_orphan_item(trans, tree_root,
5511 root->root_key.objectid);
5512 BUG_ON(ret);
5513 }
5514 }
5515
5516 if (root->in_radix) {
5517 btrfs_free_fs_root(tree_root->fs_info, root);
5518 } else {
5519 free_extent_buffer(root->node);
5520 free_extent_buffer(root->commit_root);
5521 kfree(root);
5522 }
9f3a7427 5523out:
2c47e605
YZ
5524 btrfs_end_transaction(trans, tree_root);
5525 kfree(wc);
5caf2a00 5526 btrfs_free_path(path);
2c47e605 5527 return err;
20524f02 5528}
9078a3e1 5529
2c47e605
YZ
5530/*
5531 * drop subtree rooted at tree block 'node'.
5532 *
5533 * NOTE: this function will unlock and release tree block 'node'
5534 */
f82d02d9
YZ
5535int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
5536 struct btrfs_root *root,
5537 struct extent_buffer *node,
5538 struct extent_buffer *parent)
5539{
5540 struct btrfs_path *path;
2c47e605 5541 struct walk_control *wc;
f82d02d9
YZ
5542 int level;
5543 int parent_level;
5544 int ret = 0;
5545 int wret;
5546
2c47e605
YZ
5547 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
5548
f82d02d9
YZ
5549 path = btrfs_alloc_path();
5550 BUG_ON(!path);
5551
2c47e605
YZ
5552 wc = kzalloc(sizeof(*wc), GFP_NOFS);
5553 BUG_ON(!wc);
5554
b9447ef8 5555 btrfs_assert_tree_locked(parent);
f82d02d9
YZ
5556 parent_level = btrfs_header_level(parent);
5557 extent_buffer_get(parent);
5558 path->nodes[parent_level] = parent;
5559 path->slots[parent_level] = btrfs_header_nritems(parent);
5560
b9447ef8 5561 btrfs_assert_tree_locked(node);
f82d02d9 5562 level = btrfs_header_level(node);
f82d02d9
YZ
5563 path->nodes[level] = node;
5564 path->slots[level] = 0;
2c47e605
YZ
5565 path->locks[level] = 1;
5566
5567 wc->refs[parent_level] = 1;
5568 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
5569 wc->level = level;
5570 wc->shared_level = -1;
5571 wc->stage = DROP_REFERENCE;
5572 wc->update_ref = 0;
5573 wc->keep_locks = 1;
1c4850e2 5574 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
f82d02d9
YZ
5575
5576 while (1) {
2c47e605
YZ
5577 wret = walk_down_tree(trans, root, path, wc);
5578 if (wret < 0) {
f82d02d9 5579 ret = wret;
f82d02d9 5580 break;
2c47e605 5581 }
f82d02d9 5582
2c47e605 5583 wret = walk_up_tree(trans, root, path, wc, parent_level);
f82d02d9
YZ
5584 if (wret < 0)
5585 ret = wret;
5586 if (wret != 0)
5587 break;
5588 }
5589
2c47e605 5590 kfree(wc);
f82d02d9
YZ
5591 btrfs_free_path(path);
5592 return ret;
5593}
5594
5d4f98a2 5595#if 0
8e7bf94f
CM
5596static unsigned long calc_ra(unsigned long start, unsigned long last,
5597 unsigned long nr)
5598{
5599 return min(last, start + nr - 1);
5600}
5601
d397712b 5602static noinline int relocate_inode_pages(struct inode *inode, u64 start,
98ed5174 5603 u64 len)
edbd8d4e
CM
5604{
5605 u64 page_start;
5606 u64 page_end;
1a40e23b 5607 unsigned long first_index;
edbd8d4e 5608 unsigned long last_index;
edbd8d4e
CM
5609 unsigned long i;
5610 struct page *page;
d1310b2e 5611 struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
4313b399 5612 struct file_ra_state *ra;
3eaa2885 5613 struct btrfs_ordered_extent *ordered;
1a40e23b
ZY
5614 unsigned int total_read = 0;
5615 unsigned int total_dirty = 0;
5616 int ret = 0;
4313b399
CM
5617
5618 ra = kzalloc(sizeof(*ra), GFP_NOFS);
edbd8d4e
CM
5619
5620 mutex_lock(&inode->i_mutex);
1a40e23b 5621 first_index = start >> PAGE_CACHE_SHIFT;
edbd8d4e
CM
5622 last_index = (start + len - 1) >> PAGE_CACHE_SHIFT;
5623
1a40e23b
ZY
5624 /* make sure the dirty trick played by the caller work */
5625 ret = invalidate_inode_pages2_range(inode->i_mapping,
5626 first_index, last_index);
5627 if (ret)
5628 goto out_unlock;
8e7bf94f 5629
4313b399 5630 file_ra_state_init(ra, inode->i_mapping);
edbd8d4e 5631
1a40e23b
ZY
5632 for (i = first_index ; i <= last_index; i++) {
5633 if (total_read % ra->ra_pages == 0) {
8e7bf94f 5634 btrfs_force_ra(inode->i_mapping, ra, NULL, i,
1a40e23b 5635 calc_ra(i, last_index, ra->ra_pages));
8e7bf94f
CM
5636 }
5637 total_read++;
3eaa2885
CM
5638again:
5639 if (((u64)i << PAGE_CACHE_SHIFT) > i_size_read(inode))
1a40e23b 5640 BUG_ON(1);
edbd8d4e 5641 page = grab_cache_page(inode->i_mapping, i);
a061fc8d 5642 if (!page) {
1a40e23b 5643 ret = -ENOMEM;
edbd8d4e 5644 goto out_unlock;
a061fc8d 5645 }
edbd8d4e
CM
5646 if (!PageUptodate(page)) {
5647 btrfs_readpage(NULL, page);
5648 lock_page(page);
5649 if (!PageUptodate(page)) {
5650 unlock_page(page);
5651 page_cache_release(page);
1a40e23b 5652 ret = -EIO;
edbd8d4e
CM
5653 goto out_unlock;
5654 }
5655 }
ec44a35c 5656 wait_on_page_writeback(page);
3eaa2885 5657
edbd8d4e
CM
5658 page_start = (u64)page->index << PAGE_CACHE_SHIFT;
5659 page_end = page_start + PAGE_CACHE_SIZE - 1;
d1310b2e 5660 lock_extent(io_tree, page_start, page_end, GFP_NOFS);
edbd8d4e 5661
3eaa2885
CM
5662 ordered = btrfs_lookup_ordered_extent(inode, page_start);
5663 if (ordered) {
5664 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
5665 unlock_page(page);
5666 page_cache_release(page);
5667 btrfs_start_ordered_extent(inode, ordered, 1);
5668 btrfs_put_ordered_extent(ordered);
5669 goto again;
5670 }
5671 set_page_extent_mapped(page);
5672
1a40e23b
ZY
5673 if (i == first_index)
5674 set_extent_bits(io_tree, page_start, page_end,
5675 EXTENT_BOUNDARY, GFP_NOFS);
1f80e4db 5676 btrfs_set_extent_delalloc(inode, page_start, page_end);
1a40e23b 5677
a061fc8d 5678 set_page_dirty(page);
1a40e23b 5679 total_dirty++;
edbd8d4e 5680
d1310b2e 5681 unlock_extent(io_tree, page_start, page_end, GFP_NOFS);
edbd8d4e
CM
5682 unlock_page(page);
5683 page_cache_release(page);
5684 }
5685
5686out_unlock:
ec44a35c 5687 kfree(ra);
edbd8d4e 5688 mutex_unlock(&inode->i_mutex);
1a40e23b
ZY
5689 balance_dirty_pages_ratelimited_nr(inode->i_mapping, total_dirty);
5690 return ret;
edbd8d4e
CM
5691}
5692
d397712b 5693static noinline int relocate_data_extent(struct inode *reloc_inode,
1a40e23b
ZY
5694 struct btrfs_key *extent_key,
5695 u64 offset)
5696{
5697 struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
5698 struct extent_map_tree *em_tree = &BTRFS_I(reloc_inode)->extent_tree;
5699 struct extent_map *em;
6643558d
YZ
5700 u64 start = extent_key->objectid - offset;
5701 u64 end = start + extent_key->offset - 1;
bf4ef679 5702
1a40e23b
ZY
5703 em = alloc_extent_map(GFP_NOFS);
5704 BUG_ON(!em || IS_ERR(em));
bf4ef679 5705
6643558d 5706 em->start = start;
1a40e23b 5707 em->len = extent_key->offset;
c8b97818 5708 em->block_len = extent_key->offset;
1a40e23b
ZY
5709 em->block_start = extent_key->objectid;
5710 em->bdev = root->fs_info->fs_devices->latest_bdev;
5711 set_bit(EXTENT_FLAG_PINNED, &em->flags);
5712
5713 /* setup extent map to cheat btrfs_readpage */
6643558d 5714 lock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
1a40e23b
ZY
5715 while (1) {
5716 int ret;
890871be 5717 write_lock(&em_tree->lock);
1a40e23b 5718 ret = add_extent_mapping(em_tree, em);
890871be 5719 write_unlock(&em_tree->lock);
1a40e23b
ZY
5720 if (ret != -EEXIST) {
5721 free_extent_map(em);
bf4ef679
CM
5722 break;
5723 }
6643558d 5724 btrfs_drop_extent_cache(reloc_inode, start, end, 0);
bf4ef679 5725 }
6643558d 5726 unlock_extent(&BTRFS_I(reloc_inode)->io_tree, start, end, GFP_NOFS);
bf4ef679 5727
6643558d 5728 return relocate_inode_pages(reloc_inode, start, extent_key->offset);
1a40e23b 5729}
edbd8d4e 5730
1a40e23b
ZY
5731struct btrfs_ref_path {
5732 u64 extent_start;
5733 u64 nodes[BTRFS_MAX_LEVEL];
5734 u64 root_objectid;
5735 u64 root_generation;
5736 u64 owner_objectid;
1a40e23b
ZY
5737 u32 num_refs;
5738 int lowest_level;
5739 int current_level;
f82d02d9
YZ
5740 int shared_level;
5741
5742 struct btrfs_key node_keys[BTRFS_MAX_LEVEL];
5743 u64 new_nodes[BTRFS_MAX_LEVEL];
1a40e23b 5744};
7d9eb12c 5745
1a40e23b 5746struct disk_extent {
c8b97818 5747 u64 ram_bytes;
1a40e23b
ZY
5748 u64 disk_bytenr;
5749 u64 disk_num_bytes;
5750 u64 offset;
5751 u64 num_bytes;
c8b97818
CM
5752 u8 compression;
5753 u8 encryption;
5754 u16 other_encoding;
1a40e23b 5755};
4313b399 5756
1a40e23b
ZY
5757static int is_cowonly_root(u64 root_objectid)
5758{
5759 if (root_objectid == BTRFS_ROOT_TREE_OBJECTID ||
5760 root_objectid == BTRFS_EXTENT_TREE_OBJECTID ||
5761 root_objectid == BTRFS_CHUNK_TREE_OBJECTID ||
5762 root_objectid == BTRFS_DEV_TREE_OBJECTID ||
0403e47e
YZ
5763 root_objectid == BTRFS_TREE_LOG_OBJECTID ||
5764 root_objectid == BTRFS_CSUM_TREE_OBJECTID)
1a40e23b
ZY
5765 return 1;
5766 return 0;
5767}
edbd8d4e 5768
d397712b 5769static noinline int __next_ref_path(struct btrfs_trans_handle *trans,
1a40e23b
ZY
5770 struct btrfs_root *extent_root,
5771 struct btrfs_ref_path *ref_path,
5772 int first_time)
5773{
5774 struct extent_buffer *leaf;
5775 struct btrfs_path *path;
5776 struct btrfs_extent_ref *ref;
5777 struct btrfs_key key;
5778 struct btrfs_key found_key;
5779 u64 bytenr;
5780 u32 nritems;
5781 int level;
5782 int ret = 1;
edbd8d4e 5783
1a40e23b
ZY
5784 path = btrfs_alloc_path();
5785 if (!path)
5786 return -ENOMEM;
bf4ef679 5787
1a40e23b
ZY
5788 if (first_time) {
5789 ref_path->lowest_level = -1;
5790 ref_path->current_level = -1;
f82d02d9 5791 ref_path->shared_level = -1;
1a40e23b
ZY
5792 goto walk_up;
5793 }
5794walk_down:
5795 level = ref_path->current_level - 1;
5796 while (level >= -1) {
5797 u64 parent;
5798 if (level < ref_path->lowest_level)
5799 break;
bf4ef679 5800
d397712b 5801 if (level >= 0)
1a40e23b 5802 bytenr = ref_path->nodes[level];
d397712b 5803 else
1a40e23b 5804 bytenr = ref_path->extent_start;
1a40e23b 5805 BUG_ON(bytenr == 0);
bf4ef679 5806
1a40e23b
ZY
5807 parent = ref_path->nodes[level + 1];
5808 ref_path->nodes[level + 1] = 0;
5809 ref_path->current_level = level;
5810 BUG_ON(parent == 0);
0ef3e66b 5811
1a40e23b
ZY
5812 key.objectid = bytenr;
5813 key.offset = parent + 1;
5814 key.type = BTRFS_EXTENT_REF_KEY;
edbd8d4e 5815
1a40e23b
ZY
5816 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
5817 if (ret < 0)
edbd8d4e 5818 goto out;
1a40e23b 5819 BUG_ON(ret == 0);
7d9eb12c 5820
1a40e23b
ZY
5821 leaf = path->nodes[0];
5822 nritems = btrfs_header_nritems(leaf);
5823 if (path->slots[0] >= nritems) {
5824 ret = btrfs_next_leaf(extent_root, path);
5825 if (ret < 0)
5826 goto out;
5827 if (ret > 0)
5828 goto next;
5829 leaf = path->nodes[0];
5830 }
0ef3e66b 5831
1a40e23b
ZY
5832 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5833 if (found_key.objectid == bytenr &&
f82d02d9
YZ
5834 found_key.type == BTRFS_EXTENT_REF_KEY) {
5835 if (level < ref_path->shared_level)
5836 ref_path->shared_level = level;
1a40e23b 5837 goto found;
f82d02d9 5838 }
1a40e23b
ZY
5839next:
5840 level--;
5841 btrfs_release_path(extent_root, path);
d899e052 5842 cond_resched();
1a40e23b
ZY
5843 }
5844 /* reached lowest level */
5845 ret = 1;
5846 goto out;
5847walk_up:
5848 level = ref_path->current_level;
5849 while (level < BTRFS_MAX_LEVEL - 1) {
5850 u64 ref_objectid;
d397712b
CM
5851
5852 if (level >= 0)
1a40e23b 5853 bytenr = ref_path->nodes[level];
d397712b 5854 else
1a40e23b 5855 bytenr = ref_path->extent_start;
d397712b 5856
1a40e23b 5857 BUG_ON(bytenr == 0);
edbd8d4e 5858
1a40e23b
ZY
5859 key.objectid = bytenr;
5860 key.offset = 0;
5861 key.type = BTRFS_EXTENT_REF_KEY;
edbd8d4e 5862
1a40e23b
ZY
5863 ret = btrfs_search_slot(trans, extent_root, &key, path, 0, 0);
5864 if (ret < 0)
5865 goto out;
edbd8d4e 5866
1a40e23b
ZY
5867 leaf = path->nodes[0];
5868 nritems = btrfs_header_nritems(leaf);
5869 if (path->slots[0] >= nritems) {
5870 ret = btrfs_next_leaf(extent_root, path);
5871 if (ret < 0)
5872 goto out;
5873 if (ret > 0) {
5874 /* the extent was freed by someone */
5875 if (ref_path->lowest_level == level)
5876 goto out;
5877 btrfs_release_path(extent_root, path);
5878 goto walk_down;
5879 }
5880 leaf = path->nodes[0];
5881 }
edbd8d4e 5882
1a40e23b
ZY
5883 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
5884 if (found_key.objectid != bytenr ||
5885 found_key.type != BTRFS_EXTENT_REF_KEY) {
5886 /* the extent was freed by someone */
5887 if (ref_path->lowest_level == level) {
5888 ret = 1;
5889 goto out;
5890 }
5891 btrfs_release_path(extent_root, path);
5892 goto walk_down;
5893 }
5894found:
5895 ref = btrfs_item_ptr(leaf, path->slots[0],
5896 struct btrfs_extent_ref);
5897 ref_objectid = btrfs_ref_objectid(leaf, ref);
5898 if (ref_objectid < BTRFS_FIRST_FREE_OBJECTID) {
5899 if (first_time) {
5900 level = (int)ref_objectid;
5901 BUG_ON(level >= BTRFS_MAX_LEVEL);
5902 ref_path->lowest_level = level;
5903 ref_path->current_level = level;
5904 ref_path->nodes[level] = bytenr;
5905 } else {
5906 WARN_ON(ref_objectid != level);
5907 }
5908 } else {
5909 WARN_ON(level != -1);
5910 }
5911 first_time = 0;
bf4ef679 5912
1a40e23b
ZY
5913 if (ref_path->lowest_level == level) {
5914 ref_path->owner_objectid = ref_objectid;
1a40e23b
ZY
5915 ref_path->num_refs = btrfs_ref_num_refs(leaf, ref);
5916 }
bf4ef679 5917
7d9eb12c 5918 /*
1a40e23b
ZY
5919 * the block is tree root or the block isn't in reference
5920 * counted tree.
7d9eb12c 5921 */
1a40e23b
ZY
5922 if (found_key.objectid == found_key.offset ||
5923 is_cowonly_root(btrfs_ref_root(leaf, ref))) {
5924 ref_path->root_objectid = btrfs_ref_root(leaf, ref);
5925 ref_path->root_generation =
5926 btrfs_ref_generation(leaf, ref);
5927 if (level < 0) {
5928 /* special reference from the tree log */
5929 ref_path->nodes[0] = found_key.offset;
5930 ref_path->current_level = 0;
5931 }
5932 ret = 0;
5933 goto out;
5934 }
7d9eb12c 5935
1a40e23b
ZY
5936 level++;
5937 BUG_ON(ref_path->nodes[level] != 0);
5938 ref_path->nodes[level] = found_key.offset;
5939 ref_path->current_level = level;
bf4ef679 5940
1a40e23b
ZY
5941 /*
5942 * the reference was created in the running transaction,
5943 * no need to continue walking up.
5944 */
5945 if (btrfs_ref_generation(leaf, ref) == trans->transid) {
5946 ref_path->root_objectid = btrfs_ref_root(leaf, ref);
5947 ref_path->root_generation =
5948 btrfs_ref_generation(leaf, ref);
5949 ret = 0;
5950 goto out;
7d9eb12c
CM
5951 }
5952
1a40e23b 5953 btrfs_release_path(extent_root, path);
d899e052 5954 cond_resched();
7d9eb12c 5955 }
1a40e23b
ZY
5956 /* reached max tree level, but no tree root found. */
5957 BUG();
edbd8d4e 5958out:
1a40e23b
ZY
5959 btrfs_free_path(path);
5960 return ret;
edbd8d4e
CM
5961}
5962
1a40e23b
ZY
5963static int btrfs_first_ref_path(struct btrfs_trans_handle *trans,
5964 struct btrfs_root *extent_root,
5965 struct btrfs_ref_path *ref_path,
5966 u64 extent_start)
a061fc8d 5967{
1a40e23b
ZY
5968 memset(ref_path, 0, sizeof(*ref_path));
5969 ref_path->extent_start = extent_start;
a061fc8d 5970
1a40e23b 5971 return __next_ref_path(trans, extent_root, ref_path, 1);
a061fc8d
CM
5972}
5973
1a40e23b
ZY
5974static int btrfs_next_ref_path(struct btrfs_trans_handle *trans,
5975 struct btrfs_root *extent_root,
5976 struct btrfs_ref_path *ref_path)
edbd8d4e 5977{
1a40e23b
ZY
5978 return __next_ref_path(trans, extent_root, ref_path, 0);
5979}
5980
d397712b 5981static noinline int get_new_locations(struct inode *reloc_inode,
1a40e23b
ZY
5982 struct btrfs_key *extent_key,
5983 u64 offset, int no_fragment,
5984 struct disk_extent **extents,
5985 int *nr_extents)
5986{
5987 struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
5988 struct btrfs_path *path;
5989 struct btrfs_file_extent_item *fi;
edbd8d4e 5990 struct extent_buffer *leaf;
1a40e23b
ZY
5991 struct disk_extent *exts = *extents;
5992 struct btrfs_key found_key;
5993 u64 cur_pos;
5994 u64 last_byte;
edbd8d4e 5995 u32 nritems;
1a40e23b
ZY
5996 int nr = 0;
5997 int max = *nr_extents;
5998 int ret;
edbd8d4e 5999
1a40e23b
ZY
6000 WARN_ON(!no_fragment && *extents);
6001 if (!exts) {
6002 max = 1;
6003 exts = kmalloc(sizeof(*exts) * max, GFP_NOFS);
6004 if (!exts)
6005 return -ENOMEM;
a061fc8d 6006 }
edbd8d4e 6007
1a40e23b
ZY
6008 path = btrfs_alloc_path();
6009 BUG_ON(!path);
edbd8d4e 6010
1a40e23b
ZY
6011 cur_pos = extent_key->objectid - offset;
6012 last_byte = extent_key->objectid + extent_key->offset;
6013 ret = btrfs_lookup_file_extent(NULL, root, path, reloc_inode->i_ino,
6014 cur_pos, 0);
6015 if (ret < 0)
6016 goto out;
6017 if (ret > 0) {
6018 ret = -ENOENT;
6019 goto out;
6020 }
edbd8d4e 6021
1a40e23b 6022 while (1) {
edbd8d4e
CM
6023 leaf = path->nodes[0];
6024 nritems = btrfs_header_nritems(leaf);
1a40e23b
ZY
6025 if (path->slots[0] >= nritems) {
6026 ret = btrfs_next_leaf(root, path);
a061fc8d
CM
6027 if (ret < 0)
6028 goto out;
1a40e23b
ZY
6029 if (ret > 0)
6030 break;
bf4ef679 6031 leaf = path->nodes[0];
a061fc8d 6032 }
edbd8d4e
CM
6033
6034 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
1a40e23b
ZY
6035 if (found_key.offset != cur_pos ||
6036 found_key.type != BTRFS_EXTENT_DATA_KEY ||
6037 found_key.objectid != reloc_inode->i_ino)
edbd8d4e
CM
6038 break;
6039
1a40e23b
ZY
6040 fi = btrfs_item_ptr(leaf, path->slots[0],
6041 struct btrfs_file_extent_item);
6042 if (btrfs_file_extent_type(leaf, fi) !=
6043 BTRFS_FILE_EXTENT_REG ||
6044 btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
edbd8d4e 6045 break;
1a40e23b
ZY
6046
6047 if (nr == max) {
6048 struct disk_extent *old = exts;
6049 max *= 2;
6050 exts = kzalloc(sizeof(*exts) * max, GFP_NOFS);
6051 memcpy(exts, old, sizeof(*exts) * nr);
6052 if (old != *extents)
6053 kfree(old);
a061fc8d 6054 }
edbd8d4e 6055
1a40e23b
ZY
6056 exts[nr].disk_bytenr =
6057 btrfs_file_extent_disk_bytenr(leaf, fi);
6058 exts[nr].disk_num_bytes =
6059 btrfs_file_extent_disk_num_bytes(leaf, fi);
6060 exts[nr].offset = btrfs_file_extent_offset(leaf, fi);
6061 exts[nr].num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
c8b97818
CM
6062 exts[nr].ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
6063 exts[nr].compression = btrfs_file_extent_compression(leaf, fi);
6064 exts[nr].encryption = btrfs_file_extent_encryption(leaf, fi);
6065 exts[nr].other_encoding = btrfs_file_extent_other_encoding(leaf,
6066 fi);
d899e052
YZ
6067 BUG_ON(exts[nr].offset > 0);
6068 BUG_ON(exts[nr].compression || exts[nr].encryption);
6069 BUG_ON(exts[nr].num_bytes != exts[nr].disk_num_bytes);
edbd8d4e 6070
1a40e23b
ZY
6071 cur_pos += exts[nr].num_bytes;
6072 nr++;
6073
6074 if (cur_pos + offset >= last_byte)
6075 break;
6076
6077 if (no_fragment) {
6078 ret = 1;
edbd8d4e 6079 goto out;
1a40e23b
ZY
6080 }
6081 path->slots[0]++;
6082 }
6083
1f80e4db 6084 BUG_ON(cur_pos + offset > last_byte);
1a40e23b
ZY
6085 if (cur_pos + offset < last_byte) {
6086 ret = -ENOENT;
6087 goto out;
edbd8d4e
CM
6088 }
6089 ret = 0;
6090out:
1a40e23b
ZY
6091 btrfs_free_path(path);
6092 if (ret) {
6093 if (exts != *extents)
6094 kfree(exts);
6095 } else {
6096 *extents = exts;
6097 *nr_extents = nr;
6098 }
6099 return ret;
6100}
6101
d397712b 6102static noinline int replace_one_extent(struct btrfs_trans_handle *trans,
1a40e23b
ZY
6103 struct btrfs_root *root,
6104 struct btrfs_path *path,
6105 struct btrfs_key *extent_key,
6106 struct btrfs_key *leaf_key,
6107 struct btrfs_ref_path *ref_path,
6108 struct disk_extent *new_extents,
6109 int nr_extents)
6110{
6111 struct extent_buffer *leaf;
6112 struct btrfs_file_extent_item *fi;
6113 struct inode *inode = NULL;
6114 struct btrfs_key key;
6115 u64 lock_start = 0;
6116 u64 lock_end = 0;
6117 u64 num_bytes;
6118 u64 ext_offset;
86288a19 6119 u64 search_end = (u64)-1;
1a40e23b 6120 u32 nritems;
3bb1a1bc 6121 int nr_scaned = 0;
1a40e23b 6122 int extent_locked = 0;
d899e052 6123 int extent_type;
1a40e23b
ZY
6124 int ret;
6125
3bb1a1bc 6126 memcpy(&key, leaf_key, sizeof(key));
1a40e23b 6127 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
3bb1a1bc
YZ
6128 if (key.objectid < ref_path->owner_objectid ||
6129 (key.objectid == ref_path->owner_objectid &&
6130 key.type < BTRFS_EXTENT_DATA_KEY)) {
6131 key.objectid = ref_path->owner_objectid;
6132 key.type = BTRFS_EXTENT_DATA_KEY;
6133 key.offset = 0;
6134 }
1a40e23b
ZY
6135 }
6136
6137 while (1) {
6138 ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
6139 if (ret < 0)
6140 goto out;
6141
6142 leaf = path->nodes[0];
6143 nritems = btrfs_header_nritems(leaf);
6144next:
6145 if (extent_locked && ret > 0) {
6146 /*
6147 * the file extent item was modified by someone
6148 * before the extent got locked.
6149 */
1a40e23b
ZY
6150 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6151 lock_end, GFP_NOFS);
6152 extent_locked = 0;
6153 }
6154
6155 if (path->slots[0] >= nritems) {
3bb1a1bc 6156 if (++nr_scaned > 2)
1a40e23b
ZY
6157 break;
6158
6159 BUG_ON(extent_locked);
6160 ret = btrfs_next_leaf(root, path);
6161 if (ret < 0)
6162 goto out;
6163 if (ret > 0)
6164 break;
6165 leaf = path->nodes[0];
6166 nritems = btrfs_header_nritems(leaf);
6167 }
6168
6169 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
6170
6171 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS) {
6172 if ((key.objectid > ref_path->owner_objectid) ||
6173 (key.objectid == ref_path->owner_objectid &&
6174 key.type > BTRFS_EXTENT_DATA_KEY) ||
86288a19 6175 key.offset >= search_end)
1a40e23b
ZY
6176 break;
6177 }
6178
6179 if (inode && key.objectid != inode->i_ino) {
6180 BUG_ON(extent_locked);
6181 btrfs_release_path(root, path);
6182 mutex_unlock(&inode->i_mutex);
6183 iput(inode);
6184 inode = NULL;
6185 continue;
6186 }
6187
6188 if (key.type != BTRFS_EXTENT_DATA_KEY) {
6189 path->slots[0]++;
6190 ret = 1;
6191 goto next;
6192 }
6193 fi = btrfs_item_ptr(leaf, path->slots[0],
6194 struct btrfs_file_extent_item);
d899e052
YZ
6195 extent_type = btrfs_file_extent_type(leaf, fi);
6196 if ((extent_type != BTRFS_FILE_EXTENT_REG &&
6197 extent_type != BTRFS_FILE_EXTENT_PREALLOC) ||
1a40e23b
ZY
6198 (btrfs_file_extent_disk_bytenr(leaf, fi) !=
6199 extent_key->objectid)) {
6200 path->slots[0]++;
6201 ret = 1;
6202 goto next;
6203 }
6204
6205 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
6206 ext_offset = btrfs_file_extent_offset(leaf, fi);
6207
86288a19
YZ
6208 if (search_end == (u64)-1) {
6209 search_end = key.offset - ext_offset +
6210 btrfs_file_extent_ram_bytes(leaf, fi);
6211 }
1a40e23b
ZY
6212
6213 if (!extent_locked) {
6214 lock_start = key.offset;
6215 lock_end = lock_start + num_bytes - 1;
6216 } else {
6643558d
YZ
6217 if (lock_start > key.offset ||
6218 lock_end + 1 < key.offset + num_bytes) {
6219 unlock_extent(&BTRFS_I(inode)->io_tree,
6220 lock_start, lock_end, GFP_NOFS);
6221 extent_locked = 0;
6222 }
1a40e23b
ZY
6223 }
6224
6225 if (!inode) {
6226 btrfs_release_path(root, path);
6227
6228 inode = btrfs_iget_locked(root->fs_info->sb,
6229 key.objectid, root);
6230 if (inode->i_state & I_NEW) {
6231 BTRFS_I(inode)->root = root;
6232 BTRFS_I(inode)->location.objectid =
6233 key.objectid;
6234 BTRFS_I(inode)->location.type =
6235 BTRFS_INODE_ITEM_KEY;
6236 BTRFS_I(inode)->location.offset = 0;
6237 btrfs_read_locked_inode(inode);
6238 unlock_new_inode(inode);
6239 }
6240 /*
6241 * some code call btrfs_commit_transaction while
6242 * holding the i_mutex, so we can't use mutex_lock
6243 * here.
6244 */
6245 if (is_bad_inode(inode) ||
6246 !mutex_trylock(&inode->i_mutex)) {
6247 iput(inode);
6248 inode = NULL;
6249 key.offset = (u64)-1;
6250 goto skip;
6251 }
6252 }
6253
6254 if (!extent_locked) {
6255 struct btrfs_ordered_extent *ordered;
6256
6257 btrfs_release_path(root, path);
6258
6259 lock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6260 lock_end, GFP_NOFS);
6261 ordered = btrfs_lookup_first_ordered_extent(inode,
6262 lock_end);
6263 if (ordered &&
6264 ordered->file_offset <= lock_end &&
6265 ordered->file_offset + ordered->len > lock_start) {
6266 unlock_extent(&BTRFS_I(inode)->io_tree,
6267 lock_start, lock_end, GFP_NOFS);
6268 btrfs_start_ordered_extent(inode, ordered, 1);
6269 btrfs_put_ordered_extent(ordered);
6270 key.offset += num_bytes;
6271 goto skip;
6272 }
6273 if (ordered)
6274 btrfs_put_ordered_extent(ordered);
6275
1a40e23b
ZY
6276 extent_locked = 1;
6277 continue;
6278 }
6279
6280 if (nr_extents == 1) {
6281 /* update extent pointer in place */
1a40e23b
ZY
6282 btrfs_set_file_extent_disk_bytenr(leaf, fi,
6283 new_extents[0].disk_bytenr);
6284 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
6285 new_extents[0].disk_num_bytes);
1a40e23b
ZY
6286 btrfs_mark_buffer_dirty(leaf);
6287
6288 btrfs_drop_extent_cache(inode, key.offset,
6289 key.offset + num_bytes - 1, 0);
6290
6291 ret = btrfs_inc_extent_ref(trans, root,
6292 new_extents[0].disk_bytenr,
6293 new_extents[0].disk_num_bytes,
6294 leaf->start,
6295 root->root_key.objectid,
6296 trans->transid,
3bb1a1bc 6297 key.objectid);
1a40e23b
ZY
6298 BUG_ON(ret);
6299
6300 ret = btrfs_free_extent(trans, root,
6301 extent_key->objectid,
6302 extent_key->offset,
6303 leaf->start,
6304 btrfs_header_owner(leaf),
6305 btrfs_header_generation(leaf),
3bb1a1bc 6306 key.objectid, 0);
1a40e23b
ZY
6307 BUG_ON(ret);
6308
6309 btrfs_release_path(root, path);
6310 key.offset += num_bytes;
6311 } else {
d899e052
YZ
6312 BUG_ON(1);
6313#if 0
1a40e23b
ZY
6314 u64 alloc_hint;
6315 u64 extent_len;
6316 int i;
6317 /*
6318 * drop old extent pointer at first, then insert the
6319 * new pointers one bye one
6320 */
6321 btrfs_release_path(root, path);
6322 ret = btrfs_drop_extents(trans, root, inode, key.offset,
6323 key.offset + num_bytes,
6324 key.offset, &alloc_hint);
6325 BUG_ON(ret);
6326
6327 for (i = 0; i < nr_extents; i++) {
6328 if (ext_offset >= new_extents[i].num_bytes) {
6329 ext_offset -= new_extents[i].num_bytes;
6330 continue;
6331 }
6332 extent_len = min(new_extents[i].num_bytes -
6333 ext_offset, num_bytes);
6334
6335 ret = btrfs_insert_empty_item(trans, root,
6336 path, &key,
6337 sizeof(*fi));
6338 BUG_ON(ret);
6339
6340 leaf = path->nodes[0];
6341 fi = btrfs_item_ptr(leaf, path->slots[0],
6342 struct btrfs_file_extent_item);
6343 btrfs_set_file_extent_generation(leaf, fi,
6344 trans->transid);
6345 btrfs_set_file_extent_type(leaf, fi,
6346 BTRFS_FILE_EXTENT_REG);
6347 btrfs_set_file_extent_disk_bytenr(leaf, fi,
6348 new_extents[i].disk_bytenr);
6349 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
6350 new_extents[i].disk_num_bytes);
c8b97818
CM
6351 btrfs_set_file_extent_ram_bytes(leaf, fi,
6352 new_extents[i].ram_bytes);
6353
6354 btrfs_set_file_extent_compression(leaf, fi,
6355 new_extents[i].compression);
6356 btrfs_set_file_extent_encryption(leaf, fi,
6357 new_extents[i].encryption);
6358 btrfs_set_file_extent_other_encoding(leaf, fi,
6359 new_extents[i].other_encoding);
6360
1a40e23b
ZY
6361 btrfs_set_file_extent_num_bytes(leaf, fi,
6362 extent_len);
6363 ext_offset += new_extents[i].offset;
6364 btrfs_set_file_extent_offset(leaf, fi,
6365 ext_offset);
6366 btrfs_mark_buffer_dirty(leaf);
6367
6368 btrfs_drop_extent_cache(inode, key.offset,
6369 key.offset + extent_len - 1, 0);
6370
6371 ret = btrfs_inc_extent_ref(trans, root,
6372 new_extents[i].disk_bytenr,
6373 new_extents[i].disk_num_bytes,
6374 leaf->start,
6375 root->root_key.objectid,
3bb1a1bc 6376 trans->transid, key.objectid);
1a40e23b
ZY
6377 BUG_ON(ret);
6378 btrfs_release_path(root, path);
6379
a76a3cd4 6380 inode_add_bytes(inode, extent_len);
1a40e23b
ZY
6381
6382 ext_offset = 0;
6383 num_bytes -= extent_len;
6384 key.offset += extent_len;
6385
6386 if (num_bytes == 0)
6387 break;
6388 }
6389 BUG_ON(i >= nr_extents);
d899e052 6390#endif
1a40e23b
ZY
6391 }
6392
6393 if (extent_locked) {
1a40e23b
ZY
6394 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6395 lock_end, GFP_NOFS);
6396 extent_locked = 0;
6397 }
6398skip:
6399 if (ref_path->owner_objectid != BTRFS_MULTIPLE_OBJECTIDS &&
86288a19 6400 key.offset >= search_end)
1a40e23b
ZY
6401 break;
6402
6403 cond_resched();
6404 }
6405 ret = 0;
6406out:
6407 btrfs_release_path(root, path);
6408 if (inode) {
6409 mutex_unlock(&inode->i_mutex);
6410 if (extent_locked) {
1a40e23b
ZY
6411 unlock_extent(&BTRFS_I(inode)->io_tree, lock_start,
6412 lock_end, GFP_NOFS);
6413 }
6414 iput(inode);
6415 }
6416 return ret;
6417}
6418
1a40e23b
ZY
6419int btrfs_reloc_tree_cache_ref(struct btrfs_trans_handle *trans,
6420 struct btrfs_root *root,
6421 struct extent_buffer *buf, u64 orig_start)
6422{
6423 int level;
6424 int ret;
6425
6426 BUG_ON(btrfs_header_generation(buf) != trans->transid);
6427 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
6428
6429 level = btrfs_header_level(buf);
6430 if (level == 0) {
6431 struct btrfs_leaf_ref *ref;
6432 struct btrfs_leaf_ref *orig_ref;
6433
6434 orig_ref = btrfs_lookup_leaf_ref(root, orig_start);
6435 if (!orig_ref)
6436 return -ENOENT;
6437
6438 ref = btrfs_alloc_leaf_ref(root, orig_ref->nritems);
6439 if (!ref) {
6440 btrfs_free_leaf_ref(root, orig_ref);
6441 return -ENOMEM;
6442 }
6443
6444 ref->nritems = orig_ref->nritems;
6445 memcpy(ref->extents, orig_ref->extents,
6446 sizeof(ref->extents[0]) * ref->nritems);
6447
6448 btrfs_free_leaf_ref(root, orig_ref);
6449
6450 ref->root_gen = trans->transid;
6451 ref->bytenr = buf->start;
6452 ref->owner = btrfs_header_owner(buf);
6453 ref->generation = btrfs_header_generation(buf);
bd56b302 6454
1a40e23b
ZY
6455 ret = btrfs_add_leaf_ref(root, ref, 0);
6456 WARN_ON(ret);
6457 btrfs_free_leaf_ref(root, ref);
6458 }
6459 return 0;
6460}
6461
d397712b 6462static noinline int invalidate_extent_cache(struct btrfs_root *root,
1a40e23b
ZY
6463 struct extent_buffer *leaf,
6464 struct btrfs_block_group_cache *group,
6465 struct btrfs_root *target_root)
6466{
6467 struct btrfs_key key;
6468 struct inode *inode = NULL;
6469 struct btrfs_file_extent_item *fi;
6470 u64 num_bytes;
6471 u64 skip_objectid = 0;
6472 u32 nritems;
6473 u32 i;
6474
6475 nritems = btrfs_header_nritems(leaf);
6476 for (i = 0; i < nritems; i++) {
6477 btrfs_item_key_to_cpu(leaf, &key, i);
6478 if (key.objectid == skip_objectid ||
6479 key.type != BTRFS_EXTENT_DATA_KEY)
6480 continue;
6481 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
6482 if (btrfs_file_extent_type(leaf, fi) ==
6483 BTRFS_FILE_EXTENT_INLINE)
6484 continue;
6485 if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
6486 continue;
6487 if (!inode || inode->i_ino != key.objectid) {
6488 iput(inode);
6489 inode = btrfs_ilookup(target_root->fs_info->sb,
6490 key.objectid, target_root, 1);
6491 }
6492 if (!inode) {
6493 skip_objectid = key.objectid;
6494 continue;
6495 }
6496 num_bytes = btrfs_file_extent_num_bytes(leaf, fi);
6497
6498 lock_extent(&BTRFS_I(inode)->io_tree, key.offset,
6499 key.offset + num_bytes - 1, GFP_NOFS);
1a40e23b
ZY
6500 btrfs_drop_extent_cache(inode, key.offset,
6501 key.offset + num_bytes - 1, 1);
1a40e23b
ZY
6502 unlock_extent(&BTRFS_I(inode)->io_tree, key.offset,
6503 key.offset + num_bytes - 1, GFP_NOFS);
6504 cond_resched();
6505 }
6506 iput(inode);
6507 return 0;
6508}
6509
d397712b 6510static noinline int replace_extents_in_leaf(struct btrfs_trans_handle *trans,
1a40e23b
ZY
6511 struct btrfs_root *root,
6512 struct extent_buffer *leaf,
6513 struct btrfs_block_group_cache *group,
6514 struct inode *reloc_inode)
6515{
6516 struct btrfs_key key;
6517 struct btrfs_key extent_key;
6518 struct btrfs_file_extent_item *fi;
6519 struct btrfs_leaf_ref *ref;
6520 struct disk_extent *new_extent;
6521 u64 bytenr;
6522 u64 num_bytes;
6523 u32 nritems;
6524 u32 i;
6525 int ext_index;
6526 int nr_extent;
6527 int ret;
6528
6529 new_extent = kmalloc(sizeof(*new_extent), GFP_NOFS);
6530 BUG_ON(!new_extent);
6531
6532 ref = btrfs_lookup_leaf_ref(root, leaf->start);
6533 BUG_ON(!ref);
6534
6535 ext_index = -1;
6536 nritems = btrfs_header_nritems(leaf);
6537 for (i = 0; i < nritems; i++) {
6538 btrfs_item_key_to_cpu(leaf, &key, i);
6539 if (btrfs_key_type(&key) != BTRFS_EXTENT_DATA_KEY)
6540 continue;
6541 fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
6542 if (btrfs_file_extent_type(leaf, fi) ==
6543 BTRFS_FILE_EXTENT_INLINE)
6544 continue;
6545 bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
6546 num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
6547 if (bytenr == 0)
6548 continue;
6549
6550 ext_index++;
6551 if (bytenr >= group->key.objectid + group->key.offset ||
6552 bytenr + num_bytes <= group->key.objectid)
6553 continue;
6554
6555 extent_key.objectid = bytenr;
6556 extent_key.offset = num_bytes;
6557 extent_key.type = BTRFS_EXTENT_ITEM_KEY;
6558 nr_extent = 1;
6559 ret = get_new_locations(reloc_inode, &extent_key,
6560 group->key.objectid, 1,
6561 &new_extent, &nr_extent);
6562 if (ret > 0)
6563 continue;
6564 BUG_ON(ret < 0);
6565
6566 BUG_ON(ref->extents[ext_index].bytenr != bytenr);
6567 BUG_ON(ref->extents[ext_index].num_bytes != num_bytes);
6568 ref->extents[ext_index].bytenr = new_extent->disk_bytenr;
6569 ref->extents[ext_index].num_bytes = new_extent->disk_num_bytes;
6570
1a40e23b
ZY
6571 btrfs_set_file_extent_disk_bytenr(leaf, fi,
6572 new_extent->disk_bytenr);
6573 btrfs_set_file_extent_disk_num_bytes(leaf, fi,
6574 new_extent->disk_num_bytes);
1a40e23b
ZY
6575 btrfs_mark_buffer_dirty(leaf);
6576
6577 ret = btrfs_inc_extent_ref(trans, root,
6578 new_extent->disk_bytenr,
6579 new_extent->disk_num_bytes,
6580 leaf->start,
6581 root->root_key.objectid,
3bb1a1bc 6582 trans->transid, key.objectid);
1a40e23b 6583 BUG_ON(ret);
56bec294 6584
1a40e23b
ZY
6585 ret = btrfs_free_extent(trans, root,
6586 bytenr, num_bytes, leaf->start,
6587 btrfs_header_owner(leaf),
6588 btrfs_header_generation(leaf),
3bb1a1bc 6589 key.objectid, 0);
1a40e23b
ZY
6590 BUG_ON(ret);
6591 cond_resched();
6592 }
6593 kfree(new_extent);
6594 BUG_ON(ext_index + 1 != ref->nritems);
6595 btrfs_free_leaf_ref(root, ref);
6596 return 0;
6597}
6598
f82d02d9
YZ
6599int btrfs_free_reloc_root(struct btrfs_trans_handle *trans,
6600 struct btrfs_root *root)
1a40e23b
ZY
6601{
6602 struct btrfs_root *reloc_root;
f82d02d9 6603 int ret;
1a40e23b
ZY
6604
6605 if (root->reloc_root) {
6606 reloc_root = root->reloc_root;
6607 root->reloc_root = NULL;
6608 list_add(&reloc_root->dead_list,
6609 &root->fs_info->dead_reloc_roots);
f82d02d9
YZ
6610
6611 btrfs_set_root_bytenr(&reloc_root->root_item,
6612 reloc_root->node->start);
6613 btrfs_set_root_level(&root->root_item,
6614 btrfs_header_level(reloc_root->node));
6615 memset(&reloc_root->root_item.drop_progress, 0,
6616 sizeof(struct btrfs_disk_key));
6617 reloc_root->root_item.drop_level = 0;
6618
6619 ret = btrfs_update_root(trans, root->fs_info->tree_root,
6620 &reloc_root->root_key,
6621 &reloc_root->root_item);
6622 BUG_ON(ret);
1a40e23b
ZY
6623 }
6624 return 0;
6625}
6626
6627int btrfs_drop_dead_reloc_roots(struct btrfs_root *root)
6628{
6629 struct btrfs_trans_handle *trans;
6630 struct btrfs_root *reloc_root;
6631 struct btrfs_root *prev_root = NULL;
6632 struct list_head dead_roots;
6633 int ret;
6634 unsigned long nr;
6635
6636 INIT_LIST_HEAD(&dead_roots);
6637 list_splice_init(&root->fs_info->dead_reloc_roots, &dead_roots);
6638
6639 while (!list_empty(&dead_roots)) {
6640 reloc_root = list_entry(dead_roots.prev,
6641 struct btrfs_root, dead_list);
6642 list_del_init(&reloc_root->dead_list);
6643
6644 BUG_ON(reloc_root->commit_root != NULL);
6645 while (1) {
6646 trans = btrfs_join_transaction(root, 1);
6647 BUG_ON(!trans);
6648
6649 mutex_lock(&root->fs_info->drop_mutex);
6650 ret = btrfs_drop_snapshot(trans, reloc_root);
6651 if (ret != -EAGAIN)
6652 break;
6653 mutex_unlock(&root->fs_info->drop_mutex);
6654
6655 nr = trans->blocks_used;
6656 ret = btrfs_end_transaction(trans, root);
6657 BUG_ON(ret);
6658 btrfs_btree_balance_dirty(root, nr);
6659 }
6660
6661 free_extent_buffer(reloc_root->node);
6662
6663 ret = btrfs_del_root(trans, root->fs_info->tree_root,
6664 &reloc_root->root_key);
6665 BUG_ON(ret);
6666 mutex_unlock(&root->fs_info->drop_mutex);
6667
6668 nr = trans->blocks_used;
6669 ret = btrfs_end_transaction(trans, root);
6670 BUG_ON(ret);
6671 btrfs_btree_balance_dirty(root, nr);
6672
6673 kfree(prev_root);
6674 prev_root = reloc_root;
6675 }
6676 if (prev_root) {
6677 btrfs_remove_leaf_refs(prev_root, (u64)-1, 0);
6678 kfree(prev_root);
6679 }
6680 return 0;
6681}
6682
6683int btrfs_add_dead_reloc_root(struct btrfs_root *root)
6684{
6685 list_add(&root->dead_list, &root->fs_info->dead_reloc_roots);
6686 return 0;
6687}
6688
6689int btrfs_cleanup_reloc_trees(struct btrfs_root *root)
6690{
6691 struct btrfs_root *reloc_root;
6692 struct btrfs_trans_handle *trans;
6693 struct btrfs_key location;
6694 int found;
6695 int ret;
6696
6697 mutex_lock(&root->fs_info->tree_reloc_mutex);
6698 ret = btrfs_find_dead_roots(root, BTRFS_TREE_RELOC_OBJECTID, NULL);
6699 BUG_ON(ret);
6700 found = !list_empty(&root->fs_info->dead_reloc_roots);
6701 mutex_unlock(&root->fs_info->tree_reloc_mutex);
6702
6703 if (found) {
6704 trans = btrfs_start_transaction(root, 1);
6705 BUG_ON(!trans);
6706 ret = btrfs_commit_transaction(trans, root);
6707 BUG_ON(ret);
6708 }
6709
6710 location.objectid = BTRFS_DATA_RELOC_TREE_OBJECTID;
6711 location.offset = (u64)-1;
6712 location.type = BTRFS_ROOT_ITEM_KEY;
6713
6714 reloc_root = btrfs_read_fs_root_no_name(root->fs_info, &location);
6715 BUG_ON(!reloc_root);
6716 btrfs_orphan_cleanup(reloc_root);
6717 return 0;
6718}
6719
d397712b 6720static noinline int init_reloc_tree(struct btrfs_trans_handle *trans,
1a40e23b
ZY
6721 struct btrfs_root *root)
6722{
6723 struct btrfs_root *reloc_root;
6724 struct extent_buffer *eb;
6725 struct btrfs_root_item *root_item;
6726 struct btrfs_key root_key;
6727 int ret;
6728
6729 BUG_ON(!root->ref_cows);
6730 if (root->reloc_root)
6731 return 0;
6732
6733 root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
6734 BUG_ON(!root_item);
6735
6736 ret = btrfs_copy_root(trans, root, root->commit_root,
6737 &eb, BTRFS_TREE_RELOC_OBJECTID);
6738 BUG_ON(ret);
6739
6740 root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
6741 root_key.offset = root->root_key.objectid;
6742 root_key.type = BTRFS_ROOT_ITEM_KEY;
6743
6744 memcpy(root_item, &root->root_item, sizeof(root_item));
6745 btrfs_set_root_refs(root_item, 0);
6746 btrfs_set_root_bytenr(root_item, eb->start);
6747 btrfs_set_root_level(root_item, btrfs_header_level(eb));
84234f3a 6748 btrfs_set_root_generation(root_item, trans->transid);
1a40e23b
ZY
6749
6750 btrfs_tree_unlock(eb);
6751 free_extent_buffer(eb);
6752
6753 ret = btrfs_insert_root(trans, root->fs_info->tree_root,
6754 &root_key, root_item);
6755 BUG_ON(ret);
6756 kfree(root_item);
6757
6758 reloc_root = btrfs_read_fs_root_no_radix(root->fs_info->tree_root,
6759 &root_key);
6760 BUG_ON(!reloc_root);
6761 reloc_root->last_trans = trans->transid;
6762 reloc_root->commit_root = NULL;
6763 reloc_root->ref_tree = &root->fs_info->reloc_ref_tree;
6764
6765 root->reloc_root = reloc_root;
6766 return 0;
6767}
6768
6769/*
6770 * Core function of space balance.
6771 *
6772 * The idea is using reloc trees to relocate tree blocks in reference
f82d02d9
YZ
6773 * counted roots. There is one reloc tree for each subvol, and all
6774 * reloc trees share same root key objectid. Reloc trees are snapshots
6775 * of the latest committed roots of subvols (root->commit_root).
6776 *
6777 * To relocate a tree block referenced by a subvol, there are two steps.
6778 * COW the block through subvol's reloc tree, then update block pointer
6779 * in the subvol to point to the new block. Since all reloc trees share
6780 * same root key objectid, doing special handing for tree blocks owned
6781 * by them is easy. Once a tree block has been COWed in one reloc tree,
6782 * we can use the resulting new block directly when the same block is
6783 * required to COW again through other reloc trees. By this way, relocated
6784 * tree blocks are shared between reloc trees, so they are also shared
6785 * between subvols.
1a40e23b 6786 */
d397712b 6787static noinline int relocate_one_path(struct btrfs_trans_handle *trans,
1a40e23b
ZY
6788 struct btrfs_root *root,
6789 struct btrfs_path *path,
6790 struct btrfs_key *first_key,
6791 struct btrfs_ref_path *ref_path,
6792 struct btrfs_block_group_cache *group,
6793 struct inode *reloc_inode)
6794{
6795 struct btrfs_root *reloc_root;
6796 struct extent_buffer *eb = NULL;
6797 struct btrfs_key *keys;
6798 u64 *nodes;
6799 int level;
f82d02d9 6800 int shared_level;
1a40e23b 6801 int lowest_level = 0;
1a40e23b
ZY
6802 int ret;
6803
6804 if (ref_path->owner_objectid < BTRFS_FIRST_FREE_OBJECTID)
6805 lowest_level = ref_path->owner_objectid;
6806
f82d02d9 6807 if (!root->ref_cows) {
1a40e23b
ZY
6808 path->lowest_level = lowest_level;
6809 ret = btrfs_search_slot(trans, root, first_key, path, 0, 1);
6810 BUG_ON(ret < 0);
6811 path->lowest_level = 0;
6812 btrfs_release_path(root, path);
6813 return 0;
6814 }
6815
1a40e23b
ZY
6816 mutex_lock(&root->fs_info->tree_reloc_mutex);
6817 ret = init_reloc_tree(trans, root);
6818 BUG_ON(ret);
6819 reloc_root = root->reloc_root;
6820
f82d02d9
YZ
6821 shared_level = ref_path->shared_level;
6822 ref_path->shared_level = BTRFS_MAX_LEVEL - 1;
1a40e23b 6823
f82d02d9
YZ
6824 keys = ref_path->node_keys;
6825 nodes = ref_path->new_nodes;
6826 memset(&keys[shared_level + 1], 0,
6827 sizeof(*keys) * (BTRFS_MAX_LEVEL - shared_level - 1));
6828 memset(&nodes[shared_level + 1], 0,
6829 sizeof(*nodes) * (BTRFS_MAX_LEVEL - shared_level - 1));
1a40e23b 6830
f82d02d9
YZ
6831 if (nodes[lowest_level] == 0) {
6832 path->lowest_level = lowest_level;
6833 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
6834 0, 1);
6835 BUG_ON(ret);
6836 for (level = lowest_level; level < BTRFS_MAX_LEVEL; level++) {
6837 eb = path->nodes[level];
6838 if (!eb || eb == reloc_root->node)
6839 break;
6840 nodes[level] = eb->start;
6841 if (level == 0)
6842 btrfs_item_key_to_cpu(eb, &keys[level], 0);
6843 else
6844 btrfs_node_key_to_cpu(eb, &keys[level], 0);
6845 }
2b82032c
YZ
6846 if (nodes[0] &&
6847 ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
f82d02d9
YZ
6848 eb = path->nodes[0];
6849 ret = replace_extents_in_leaf(trans, reloc_root, eb,
6850 group, reloc_inode);
6851 BUG_ON(ret);
6852 }
6853 btrfs_release_path(reloc_root, path);
6854 } else {
1a40e23b 6855 ret = btrfs_merge_path(trans, reloc_root, keys, nodes,
f82d02d9 6856 lowest_level);
1a40e23b
ZY
6857 BUG_ON(ret);
6858 }
6859
1a40e23b
ZY
6860 /*
6861 * replace tree blocks in the fs tree with tree blocks in
6862 * the reloc tree.
6863 */
6864 ret = btrfs_merge_path(trans, root, keys, nodes, lowest_level);
6865 BUG_ON(ret < 0);
6866
6867 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
f82d02d9
YZ
6868 ret = btrfs_search_slot(trans, reloc_root, first_key, path,
6869 0, 0);
6870 BUG_ON(ret);
6871 extent_buffer_get(path->nodes[0]);
6872 eb = path->nodes[0];
6873 btrfs_release_path(reloc_root, path);
1a40e23b
ZY
6874 ret = invalidate_extent_cache(reloc_root, eb, group, root);
6875 BUG_ON(ret);
6876 free_extent_buffer(eb);
6877 }
1a40e23b 6878
f82d02d9 6879 mutex_unlock(&root->fs_info->tree_reloc_mutex);
1a40e23b 6880 path->lowest_level = 0;
1a40e23b
ZY
6881 return 0;
6882}
6883
d397712b 6884static noinline int relocate_tree_block(struct btrfs_trans_handle *trans,
1a40e23b
ZY
6885 struct btrfs_root *root,
6886 struct btrfs_path *path,
6887 struct btrfs_key *first_key,
6888 struct btrfs_ref_path *ref_path)
6889{
6890 int ret;
1a40e23b
ZY
6891
6892 ret = relocate_one_path(trans, root, path, first_key,
6893 ref_path, NULL, NULL);
6894 BUG_ON(ret);
6895
1a40e23b
ZY
6896 return 0;
6897}
6898
d397712b 6899static noinline int del_extent_zero(struct btrfs_trans_handle *trans,
1a40e23b
ZY
6900 struct btrfs_root *extent_root,
6901 struct btrfs_path *path,
6902 struct btrfs_key *extent_key)
6903{
6904 int ret;
6905
1a40e23b
ZY
6906 ret = btrfs_search_slot(trans, extent_root, extent_key, path, -1, 1);
6907 if (ret)
6908 goto out;
6909 ret = btrfs_del_item(trans, extent_root, path);
6910out:
6911 btrfs_release_path(extent_root, path);
1a40e23b
ZY
6912 return ret;
6913}
6914
d397712b 6915static noinline struct btrfs_root *read_ref_root(struct btrfs_fs_info *fs_info,
1a40e23b
ZY
6916 struct btrfs_ref_path *ref_path)
6917{
6918 struct btrfs_key root_key;
6919
6920 root_key.objectid = ref_path->root_objectid;
6921 root_key.type = BTRFS_ROOT_ITEM_KEY;
6922 if (is_cowonly_root(ref_path->root_objectid))
6923 root_key.offset = 0;
6924 else
6925 root_key.offset = (u64)-1;
6926
6927 return btrfs_read_fs_root_no_name(fs_info, &root_key);
6928}
6929
d397712b 6930static noinline int relocate_one_extent(struct btrfs_root *extent_root,
1a40e23b
ZY
6931 struct btrfs_path *path,
6932 struct btrfs_key *extent_key,
6933 struct btrfs_block_group_cache *group,
6934 struct inode *reloc_inode, int pass)
6935{
6936 struct btrfs_trans_handle *trans;
6937 struct btrfs_root *found_root;
6938 struct btrfs_ref_path *ref_path = NULL;
6939 struct disk_extent *new_extents = NULL;
6940 int nr_extents = 0;
6941 int loops;
6942 int ret;
6943 int level;
6944 struct btrfs_key first_key;
6945 u64 prev_block = 0;
6946
1a40e23b
ZY
6947
6948 trans = btrfs_start_transaction(extent_root, 1);
6949 BUG_ON(!trans);
6950
6951 if (extent_key->objectid == 0) {
6952 ret = del_extent_zero(trans, extent_root, path, extent_key);
6953 goto out;
6954 }
6955
6956 ref_path = kmalloc(sizeof(*ref_path), GFP_NOFS);
6957 if (!ref_path) {
d397712b
CM
6958 ret = -ENOMEM;
6959 goto out;
1a40e23b
ZY
6960 }
6961
6962 for (loops = 0; ; loops++) {
6963 if (loops == 0) {
6964 ret = btrfs_first_ref_path(trans, extent_root, ref_path,
6965 extent_key->objectid);
6966 } else {
6967 ret = btrfs_next_ref_path(trans, extent_root, ref_path);
6968 }
6969 if (ret < 0)
6970 goto out;
6971 if (ret > 0)
6972 break;
6973
6974 if (ref_path->root_objectid == BTRFS_TREE_LOG_OBJECTID ||
6975 ref_path->root_objectid == BTRFS_TREE_RELOC_OBJECTID)
6976 continue;
6977
6978 found_root = read_ref_root(extent_root->fs_info, ref_path);
6979 BUG_ON(!found_root);
6980 /*
6981 * for reference counted tree, only process reference paths
6982 * rooted at the latest committed root.
6983 */
6984 if (found_root->ref_cows &&
6985 ref_path->root_generation != found_root->root_key.offset)
6986 continue;
6987
6988 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
6989 if (pass == 0) {
6990 /*
6991 * copy data extents to new locations
6992 */
6993 u64 group_start = group->key.objectid;
6994 ret = relocate_data_extent(reloc_inode,
6995 extent_key,
6996 group_start);
6997 if (ret < 0)
6998 goto out;
6999 break;
7000 }
7001 level = 0;
7002 } else {
7003 level = ref_path->owner_objectid;
7004 }
7005
7006 if (prev_block != ref_path->nodes[level]) {
7007 struct extent_buffer *eb;
7008 u64 block_start = ref_path->nodes[level];
7009 u64 block_size = btrfs_level_size(found_root, level);
7010
7011 eb = read_tree_block(found_root, block_start,
7012 block_size, 0);
7013 btrfs_tree_lock(eb);
7014 BUG_ON(level != btrfs_header_level(eb));
7015
7016 if (level == 0)
7017 btrfs_item_key_to_cpu(eb, &first_key, 0);
7018 else
7019 btrfs_node_key_to_cpu(eb, &first_key, 0);
7020
7021 btrfs_tree_unlock(eb);
7022 free_extent_buffer(eb);
7023 prev_block = block_start;
7024 }
7025
24562425 7026 mutex_lock(&extent_root->fs_info->trans_mutex);
e4404d6e 7027 btrfs_record_root_in_trans(found_root);
24562425 7028 mutex_unlock(&extent_root->fs_info->trans_mutex);
e4404d6e
YZ
7029 if (ref_path->owner_objectid >= BTRFS_FIRST_FREE_OBJECTID) {
7030 /*
7031 * try to update data extent references while
7032 * keeping metadata shared between snapshots.
7033 */
7034 if (pass == 1) {
7035 ret = relocate_one_path(trans, found_root,
7036 path, &first_key, ref_path,
7037 group, reloc_inode);
7038 if (ret < 0)
7039 goto out;
7040 continue;
7041 }
1a40e23b
ZY
7042 /*
7043 * use fallback method to process the remaining
7044 * references.
7045 */
7046 if (!new_extents) {
7047 u64 group_start = group->key.objectid;
d899e052
YZ
7048 new_extents = kmalloc(sizeof(*new_extents),
7049 GFP_NOFS);
7050 nr_extents = 1;
1a40e23b
ZY
7051 ret = get_new_locations(reloc_inode,
7052 extent_key,
d899e052 7053 group_start, 1,
1a40e23b
ZY
7054 &new_extents,
7055 &nr_extents);
d899e052 7056 if (ret)
1a40e23b
ZY
7057 goto out;
7058 }
1a40e23b
ZY
7059 ret = replace_one_extent(trans, found_root,
7060 path, extent_key,
7061 &first_key, ref_path,
7062 new_extents, nr_extents);
e4404d6e 7063 } else {
1a40e23b
ZY
7064 ret = relocate_tree_block(trans, found_root, path,
7065 &first_key, ref_path);
1a40e23b
ZY
7066 }
7067 if (ret < 0)
7068 goto out;
7069 }
7070 ret = 0;
7071out:
7072 btrfs_end_transaction(trans, extent_root);
7073 kfree(new_extents);
7074 kfree(ref_path);
1a40e23b
ZY
7075 return ret;
7076}
5d4f98a2 7077#endif
1a40e23b 7078
ec44a35c
CM
7079static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
7080{
7081 u64 num_devices;
7082 u64 stripped = BTRFS_BLOCK_GROUP_RAID0 |
7083 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
7084
2b82032c 7085 num_devices = root->fs_info->fs_devices->rw_devices;
ec44a35c
CM
7086 if (num_devices == 1) {
7087 stripped |= BTRFS_BLOCK_GROUP_DUP;
7088 stripped = flags & ~stripped;
7089
7090 /* turn raid0 into single device chunks */
7091 if (flags & BTRFS_BLOCK_GROUP_RAID0)
7092 return stripped;
7093
7094 /* turn mirroring into duplication */
7095 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
7096 BTRFS_BLOCK_GROUP_RAID10))
7097 return stripped | BTRFS_BLOCK_GROUP_DUP;
7098 return flags;
7099 } else {
7100 /* they already had raid on here, just return */
ec44a35c
CM
7101 if (flags & stripped)
7102 return flags;
7103
7104 stripped |= BTRFS_BLOCK_GROUP_DUP;
7105 stripped = flags & ~stripped;
7106
7107 /* switch duplicated blocks with raid1 */
7108 if (flags & BTRFS_BLOCK_GROUP_DUP)
7109 return stripped | BTRFS_BLOCK_GROUP_RAID1;
7110
7111 /* turn single device chunks into raid0 */
7112 return stripped | BTRFS_BLOCK_GROUP_RAID0;
7113 }
7114 return flags;
7115}
7116
b2950863 7117static int __alloc_chunk_for_shrink(struct btrfs_root *root,
0ef3e66b
CM
7118 struct btrfs_block_group_cache *shrink_block_group,
7119 int force)
7120{
7121 struct btrfs_trans_handle *trans;
7122 u64 new_alloc_flags;
7123 u64 calc;
7124
c286ac48 7125 spin_lock(&shrink_block_group->lock);
5d4f98a2
YZ
7126 if (btrfs_block_group_used(&shrink_block_group->item) +
7127 shrink_block_group->reserved > 0) {
c286ac48 7128 spin_unlock(&shrink_block_group->lock);
c286ac48 7129
0ef3e66b 7130 trans = btrfs_start_transaction(root, 1);
c286ac48 7131 spin_lock(&shrink_block_group->lock);
7d9eb12c 7132
0ef3e66b
CM
7133 new_alloc_flags = update_block_group_flags(root,
7134 shrink_block_group->flags);
7135 if (new_alloc_flags != shrink_block_group->flags) {
7136 calc =
7137 btrfs_block_group_used(&shrink_block_group->item);
7138 } else {
7139 calc = shrink_block_group->key.offset;
7140 }
c286ac48
CM
7141 spin_unlock(&shrink_block_group->lock);
7142
0ef3e66b
CM
7143 do_chunk_alloc(trans, root->fs_info->extent_root,
7144 calc + 2 * 1024 * 1024, new_alloc_flags, force);
7d9eb12c 7145
0ef3e66b 7146 btrfs_end_transaction(trans, root);
c286ac48
CM
7147 } else
7148 spin_unlock(&shrink_block_group->lock);
0ef3e66b
CM
7149 return 0;
7150}
7151
5d4f98a2
YZ
7152
7153int btrfs_prepare_block_group_relocation(struct btrfs_root *root,
7154 struct btrfs_block_group_cache *group)
7155
7156{
7157 __alloc_chunk_for_shrink(root, group, 1);
7158 set_block_group_readonly(group);
7159 return 0;
7160}
7161
ba1bf481
JB
7162/*
7163 * checks to see if its even possible to relocate this block group.
7164 *
7165 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
7166 * ok to go ahead and try.
7167 */
7168int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
7169{
7170 struct btrfs_block_group_cache *block_group;
7171 struct btrfs_space_info *space_info;
7172 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
7173 struct btrfs_device *device;
7174 int full = 0;
7175 int ret = 0;
7176
7177 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
7178
7179 /* odd, couldn't find the block group, leave it alone */
7180 if (!block_group)
7181 return -1;
7182
7183 /* no bytes used, we're good */
7184 if (!btrfs_block_group_used(&block_group->item))
7185 goto out;
7186
7187 space_info = block_group->space_info;
7188 spin_lock(&space_info->lock);
7189
7190 full = space_info->full;
7191
7192 /*
7193 * if this is the last block group we have in this space, we can't
7ce618db
CM
7194 * relocate it unless we're able to allocate a new chunk below.
7195 *
7196 * Otherwise, we need to make sure we have room in the space to handle
7197 * all of the extents from this block group. If we can, we're good
ba1bf481 7198 */
7ce618db
CM
7199 if ((space_info->total_bytes != block_group->key.offset) &&
7200 (space_info->bytes_used + space_info->bytes_reserved +
ba1bf481
JB
7201 space_info->bytes_pinned + space_info->bytes_readonly +
7202 btrfs_block_group_used(&block_group->item) <
7ce618db 7203 space_info->total_bytes)) {
ba1bf481
JB
7204 spin_unlock(&space_info->lock);
7205 goto out;
7206 }
7207 spin_unlock(&space_info->lock);
7208
7209 /*
7210 * ok we don't have enough space, but maybe we have free space on our
7211 * devices to allocate new chunks for relocation, so loop through our
7212 * alloc devices and guess if we have enough space. However, if we
7213 * were marked as full, then we know there aren't enough chunks, and we
7214 * can just return.
7215 */
7216 ret = -1;
7217 if (full)
7218 goto out;
7219
7220 mutex_lock(&root->fs_info->chunk_mutex);
7221 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7222 u64 min_free = btrfs_block_group_used(&block_group->item);
7223 u64 dev_offset, max_avail;
7224
7225 /*
7226 * check to make sure we can actually find a chunk with enough
7227 * space to fit our block group in.
7228 */
7229 if (device->total_bytes > device->bytes_used + min_free) {
7230 ret = find_free_dev_extent(NULL, device, min_free,
7231 &dev_offset, &max_avail);
7232 if (!ret)
7233 break;
7234 ret = -1;
7235 }
7236 }
7237 mutex_unlock(&root->fs_info->chunk_mutex);
7238out:
7239 btrfs_put_block_group(block_group);
7240 return ret;
7241}
7242
b2950863
CH
7243static int find_first_block_group(struct btrfs_root *root,
7244 struct btrfs_path *path, struct btrfs_key *key)
0b86a832 7245{
925baedd 7246 int ret = 0;
0b86a832
CM
7247 struct btrfs_key found_key;
7248 struct extent_buffer *leaf;
7249 int slot;
edbd8d4e 7250
0b86a832
CM
7251 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
7252 if (ret < 0)
925baedd
CM
7253 goto out;
7254
d397712b 7255 while (1) {
0b86a832 7256 slot = path->slots[0];
edbd8d4e 7257 leaf = path->nodes[0];
0b86a832
CM
7258 if (slot >= btrfs_header_nritems(leaf)) {
7259 ret = btrfs_next_leaf(root, path);
7260 if (ret == 0)
7261 continue;
7262 if (ret < 0)
925baedd 7263 goto out;
0b86a832 7264 break;
edbd8d4e 7265 }
0b86a832 7266 btrfs_item_key_to_cpu(leaf, &found_key, slot);
edbd8d4e 7267
0b86a832 7268 if (found_key.objectid >= key->objectid &&
925baedd
CM
7269 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
7270 ret = 0;
7271 goto out;
7272 }
0b86a832 7273 path->slots[0]++;
edbd8d4e 7274 }
0b86a832 7275 ret = -ENOENT;
925baedd 7276out:
0b86a832 7277 return ret;
edbd8d4e
CM
7278}
7279
1a40e23b
ZY
7280int btrfs_free_block_groups(struct btrfs_fs_info *info)
7281{
7282 struct btrfs_block_group_cache *block_group;
4184ea7f 7283 struct btrfs_space_info *space_info;
11833d66 7284 struct btrfs_caching_control *caching_ctl;
1a40e23b
ZY
7285 struct rb_node *n;
7286
11833d66
YZ
7287 down_write(&info->extent_commit_sem);
7288 while (!list_empty(&info->caching_block_groups)) {
7289 caching_ctl = list_entry(info->caching_block_groups.next,
7290 struct btrfs_caching_control, list);
7291 list_del(&caching_ctl->list);
7292 put_caching_control(caching_ctl);
7293 }
7294 up_write(&info->extent_commit_sem);
7295
1a40e23b
ZY
7296 spin_lock(&info->block_group_cache_lock);
7297 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
7298 block_group = rb_entry(n, struct btrfs_block_group_cache,
7299 cache_node);
1a40e23b
ZY
7300 rb_erase(&block_group->cache_node,
7301 &info->block_group_cache_tree);
d899e052
YZ
7302 spin_unlock(&info->block_group_cache_lock);
7303
80eb234a 7304 down_write(&block_group->space_info->groups_sem);
1a40e23b 7305 list_del(&block_group->list);
80eb234a 7306 up_write(&block_group->space_info->groups_sem);
d2fb3437 7307
817d52f8 7308 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 7309 wait_block_group_cache_done(block_group);
817d52f8
JB
7310
7311 btrfs_remove_free_space_cache(block_group);
7312
d2fb3437 7313 WARN_ON(atomic_read(&block_group->count) != 1);
1a40e23b 7314 kfree(block_group);
d899e052
YZ
7315
7316 spin_lock(&info->block_group_cache_lock);
1a40e23b
ZY
7317 }
7318 spin_unlock(&info->block_group_cache_lock);
4184ea7f
CM
7319
7320 /* now that all the block groups are freed, go through and
7321 * free all the space_info structs. This is only called during
7322 * the final stages of unmount, and so we know nobody is
7323 * using them. We call synchronize_rcu() once before we start,
7324 * just to be on the safe side.
7325 */
7326 synchronize_rcu();
7327
7328 while(!list_empty(&info->space_info)) {
7329 space_info = list_entry(info->space_info.next,
7330 struct btrfs_space_info,
7331 list);
7332
7333 list_del(&space_info->list);
7334 kfree(space_info);
7335 }
1a40e23b
ZY
7336 return 0;
7337}
7338
9078a3e1
CM
7339int btrfs_read_block_groups(struct btrfs_root *root)
7340{
7341 struct btrfs_path *path;
7342 int ret;
9078a3e1 7343 struct btrfs_block_group_cache *cache;
be744175 7344 struct btrfs_fs_info *info = root->fs_info;
6324fbf3 7345 struct btrfs_space_info *space_info;
9078a3e1
CM
7346 struct btrfs_key key;
7347 struct btrfs_key found_key;
5f39d397 7348 struct extent_buffer *leaf;
96b5179d 7349
be744175 7350 root = info->extent_root;
9078a3e1 7351 key.objectid = 0;
0b86a832 7352 key.offset = 0;
9078a3e1 7353 btrfs_set_key_type(&key, BTRFS_BLOCK_GROUP_ITEM_KEY);
9078a3e1
CM
7354 path = btrfs_alloc_path();
7355 if (!path)
7356 return -ENOMEM;
7357
d397712b 7358 while (1) {
0b86a832
CM
7359 ret = find_first_block_group(root, path, &key);
7360 if (ret > 0) {
7361 ret = 0;
7362 goto error;
9078a3e1 7363 }
0b86a832
CM
7364 if (ret != 0)
7365 goto error;
7366
5f39d397
CM
7367 leaf = path->nodes[0];
7368 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
8f18cf13 7369 cache = kzalloc(sizeof(*cache), GFP_NOFS);
9078a3e1 7370 if (!cache) {
0b86a832 7371 ret = -ENOMEM;
9078a3e1
CM
7372 break;
7373 }
3e1ad54f 7374
d2fb3437 7375 atomic_set(&cache->count, 1);
c286ac48 7376 spin_lock_init(&cache->lock);
6226cb0a 7377 spin_lock_init(&cache->tree_lock);
817d52f8 7378 cache->fs_info = info;
0f9dd46c 7379 INIT_LIST_HEAD(&cache->list);
fa9c0d79 7380 INIT_LIST_HEAD(&cache->cluster_list);
96303081
JB
7381
7382 /*
7383 * we only want to have 32k of ram per block group for keeping
7384 * track of free space, and if we pass 1/2 of that we want to
7385 * start converting things over to using bitmaps
7386 */
7387 cache->extents_thresh = ((1024 * 32) / 2) /
7388 sizeof(struct btrfs_free_space);
7389
5f39d397
CM
7390 read_extent_buffer(leaf, &cache->item,
7391 btrfs_item_ptr_offset(leaf, path->slots[0]),
7392 sizeof(cache->item));
9078a3e1 7393 memcpy(&cache->key, &found_key, sizeof(found_key));
0b86a832 7394
9078a3e1
CM
7395 key.objectid = found_key.objectid + found_key.offset;
7396 btrfs_release_path(root, path);
0b86a832 7397 cache->flags = btrfs_block_group_flags(&cache->item);
817d52f8
JB
7398 cache->sectorsize = root->sectorsize;
7399
817d52f8
JB
7400 /*
7401 * check for two cases, either we are full, and therefore
7402 * don't need to bother with the caching work since we won't
7403 * find any space, or we are empty, and we can just add all
7404 * the space in and be done with it. This saves us _alot_ of
7405 * time, particularly in the full case.
7406 */
7407 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
1b2da372 7408 exclude_super_stripes(root, cache);
11833d66 7409 cache->last_byte_to_unpin = (u64)-1;
817d52f8 7410 cache->cached = BTRFS_CACHE_FINISHED;
1b2da372 7411 free_excluded_extents(root, cache);
817d52f8 7412 } else if (btrfs_block_group_used(&cache->item) == 0) {
11833d66
YZ
7413 exclude_super_stripes(root, cache);
7414 cache->last_byte_to_unpin = (u64)-1;
817d52f8
JB
7415 cache->cached = BTRFS_CACHE_FINISHED;
7416 add_new_free_space(cache, root->fs_info,
7417 found_key.objectid,
7418 found_key.objectid +
7419 found_key.offset);
11833d66 7420 free_excluded_extents(root, cache);
817d52f8 7421 }
96b5179d 7422
6324fbf3
CM
7423 ret = update_space_info(info, cache->flags, found_key.offset,
7424 btrfs_block_group_used(&cache->item),
7425 &space_info);
7426 BUG_ON(ret);
7427 cache->space_info = space_info;
1b2da372
JB
7428 spin_lock(&cache->space_info->lock);
7429 cache->space_info->bytes_super += cache->bytes_super;
7430 spin_unlock(&cache->space_info->lock);
7431
80eb234a
JB
7432 down_write(&space_info->groups_sem);
7433 list_add_tail(&cache->list, &space_info->block_groups);
7434 up_write(&space_info->groups_sem);
0f9dd46c
JB
7435
7436 ret = btrfs_add_block_group_cache(root->fs_info, cache);
7437 BUG_ON(ret);
75ccf47d
CM
7438
7439 set_avail_alloc_bits(root->fs_info, cache->flags);
2b82032c
YZ
7440 if (btrfs_chunk_readonly(root, cache->key.objectid))
7441 set_block_group_readonly(cache);
9078a3e1 7442 }
0b86a832
CM
7443 ret = 0;
7444error:
9078a3e1 7445 btrfs_free_path(path);
0b86a832 7446 return ret;
9078a3e1 7447}
6324fbf3
CM
7448
7449int btrfs_make_block_group(struct btrfs_trans_handle *trans,
7450 struct btrfs_root *root, u64 bytes_used,
e17cade2 7451 u64 type, u64 chunk_objectid, u64 chunk_offset,
6324fbf3
CM
7452 u64 size)
7453{
7454 int ret;
6324fbf3
CM
7455 struct btrfs_root *extent_root;
7456 struct btrfs_block_group_cache *cache;
6324fbf3
CM
7457
7458 extent_root = root->fs_info->extent_root;
6324fbf3 7459
12fcfd22 7460 root->fs_info->last_trans_log_full_commit = trans->transid;
e02119d5 7461
8f18cf13 7462 cache = kzalloc(sizeof(*cache), GFP_NOFS);
0f9dd46c
JB
7463 if (!cache)
7464 return -ENOMEM;
7465
e17cade2 7466 cache->key.objectid = chunk_offset;
6324fbf3 7467 cache->key.offset = size;
d2fb3437 7468 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
96303081
JB
7469 cache->sectorsize = root->sectorsize;
7470
7471 /*
7472 * we only want to have 32k of ram per block group for keeping track
7473 * of free space, and if we pass 1/2 of that we want to start
7474 * converting things over to using bitmaps
7475 */
7476 cache->extents_thresh = ((1024 * 32) / 2) /
7477 sizeof(struct btrfs_free_space);
d2fb3437 7478 atomic_set(&cache->count, 1);
c286ac48 7479 spin_lock_init(&cache->lock);
6226cb0a 7480 spin_lock_init(&cache->tree_lock);
0f9dd46c 7481 INIT_LIST_HEAD(&cache->list);
fa9c0d79 7482 INIT_LIST_HEAD(&cache->cluster_list);
0ef3e66b 7483
6324fbf3 7484 btrfs_set_block_group_used(&cache->item, bytes_used);
6324fbf3
CM
7485 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
7486 cache->flags = type;
7487 btrfs_set_block_group_flags(&cache->item, type);
7488
11833d66 7489 cache->last_byte_to_unpin = (u64)-1;
817d52f8 7490 cache->cached = BTRFS_CACHE_FINISHED;
11833d66 7491 exclude_super_stripes(root, cache);
96303081 7492
817d52f8
JB
7493 add_new_free_space(cache, root->fs_info, chunk_offset,
7494 chunk_offset + size);
7495
11833d66
YZ
7496 free_excluded_extents(root, cache);
7497
6324fbf3
CM
7498 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
7499 &cache->space_info);
7500 BUG_ON(ret);
1b2da372
JB
7501
7502 spin_lock(&cache->space_info->lock);
7503 cache->space_info->bytes_super += cache->bytes_super;
7504 spin_unlock(&cache->space_info->lock);
7505
80eb234a
JB
7506 down_write(&cache->space_info->groups_sem);
7507 list_add_tail(&cache->list, &cache->space_info->block_groups);
7508 up_write(&cache->space_info->groups_sem);
6324fbf3 7509
0f9dd46c
JB
7510 ret = btrfs_add_block_group_cache(root->fs_info, cache);
7511 BUG_ON(ret);
c286ac48 7512
6324fbf3
CM
7513 ret = btrfs_insert_item(trans, extent_root, &cache->key, &cache->item,
7514 sizeof(cache->item));
7515 BUG_ON(ret);
7516
d18a2c44 7517 set_avail_alloc_bits(extent_root->fs_info, type);
925baedd 7518
6324fbf3
CM
7519 return 0;
7520}
1a40e23b
ZY
7521
7522int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
7523 struct btrfs_root *root, u64 group_start)
7524{
7525 struct btrfs_path *path;
7526 struct btrfs_block_group_cache *block_group;
44fb5511 7527 struct btrfs_free_cluster *cluster;
1a40e23b
ZY
7528 struct btrfs_key key;
7529 int ret;
7530
1a40e23b
ZY
7531 root = root->fs_info->extent_root;
7532
7533 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
7534 BUG_ON(!block_group);
c146afad 7535 BUG_ON(!block_group->ro);
1a40e23b
ZY
7536
7537 memcpy(&key, &block_group->key, sizeof(key));
7538
44fb5511
CM
7539 /* make sure this block group isn't part of an allocation cluster */
7540 cluster = &root->fs_info->data_alloc_cluster;
7541 spin_lock(&cluster->refill_lock);
7542 btrfs_return_cluster_to_free_space(block_group, cluster);
7543 spin_unlock(&cluster->refill_lock);
7544
7545 /*
7546 * make sure this block group isn't part of a metadata
7547 * allocation cluster
7548 */
7549 cluster = &root->fs_info->meta_alloc_cluster;
7550 spin_lock(&cluster->refill_lock);
7551 btrfs_return_cluster_to_free_space(block_group, cluster);
7552 spin_unlock(&cluster->refill_lock);
7553
1a40e23b
ZY
7554 path = btrfs_alloc_path();
7555 BUG_ON(!path);
7556
3dfdb934 7557 spin_lock(&root->fs_info->block_group_cache_lock);
1a40e23b
ZY
7558 rb_erase(&block_group->cache_node,
7559 &root->fs_info->block_group_cache_tree);
3dfdb934 7560 spin_unlock(&root->fs_info->block_group_cache_lock);
817d52f8 7561
80eb234a 7562 down_write(&block_group->space_info->groups_sem);
44fb5511
CM
7563 /*
7564 * we must use list_del_init so people can check to see if they
7565 * are still on the list after taking the semaphore
7566 */
7567 list_del_init(&block_group->list);
80eb234a 7568 up_write(&block_group->space_info->groups_sem);
1a40e23b 7569
817d52f8 7570 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 7571 wait_block_group_cache_done(block_group);
817d52f8
JB
7572
7573 btrfs_remove_free_space_cache(block_group);
7574
c146afad
YZ
7575 spin_lock(&block_group->space_info->lock);
7576 block_group->space_info->total_bytes -= block_group->key.offset;
7577 block_group->space_info->bytes_readonly -= block_group->key.offset;
7578 spin_unlock(&block_group->space_info->lock);
283bb197
CM
7579
7580 btrfs_clear_space_info_full(root->fs_info);
c146afad 7581
fa9c0d79
CM
7582 btrfs_put_block_group(block_group);
7583 btrfs_put_block_group(block_group);
1a40e23b
ZY
7584
7585 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
7586 if (ret > 0)
7587 ret = -EIO;
7588 if (ret < 0)
7589 goto out;
7590
7591 ret = btrfs_del_item(trans, root, path);
7592out:
7593 btrfs_free_path(path);
7594 return ret;
7595}