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