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