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