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