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