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