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