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