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