btrfs: Fix a data space underflow warning
[deliverable/linux.git] / fs / btrfs / extent-tree.c
CommitLineData
6cbd5570
CM
1/*
2 * Copyright (C) 2007 Oracle. All rights reserved.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public
6 * License v2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public
14 * License along with this program; if not, write to the
15 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16 * Boston, MA 021110-1307, USA.
17 */
ec6b910f 18#include <linux/sched.h>
edbd8d4e 19#include <linux/pagemap.h>
ec44a35c 20#include <linux/writeback.h>
21af804c 21#include <linux/blkdev.h>
b7a9f29f 22#include <linux/sort.h>
4184ea7f 23#include <linux/rcupdate.h>
817d52f8 24#include <linux/kthread.h>
5a0e3ad6 25#include <linux/slab.h>
dff51cd1 26#include <linux/ratelimit.h>
b150a4f1 27#include <linux/percpu_counter.h>
74493f7a 28#include "hash.h"
995946dd 29#include "tree-log.h"
fec577fb
CM
30#include "disk-io.h"
31#include "print-tree.h"
0b86a832 32#include "volumes.h"
53b381b3 33#include "raid56.h"
925baedd 34#include "locking.h"
fa9c0d79 35#include "free-space-cache.h"
3fed40cc 36#include "math.h"
6ab0a202 37#include "sysfs.h"
fcebe456 38#include "qgroup.h"
fec577fb 39
709c0486
AJ
40#undef SCRAMBLE_DELAYED_REFS
41
9e622d6b
MX
42/*
43 * control flags for do_chunk_alloc's force field
0e4f8f88
CM
44 * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
45 * if we really need one.
46 *
0e4f8f88
CM
47 * CHUNK_ALLOC_LIMITED means to only try and allocate one
48 * if we have very few chunks already allocated. This is
49 * used as part of the clustering code to help make sure
50 * we have a good pool of storage to cluster in, without
51 * filling the FS with empty chunks
52 *
9e622d6b
MX
53 * CHUNK_ALLOC_FORCE means it must try to allocate one
54 *
0e4f8f88
CM
55 */
56enum {
57 CHUNK_ALLOC_NO_FORCE = 0,
9e622d6b
MX
58 CHUNK_ALLOC_LIMITED = 1,
59 CHUNK_ALLOC_FORCE = 2,
0e4f8f88
CM
60};
61
fb25e914
JB
62/*
63 * Control how reservations are dealt with.
64 *
65 * RESERVE_FREE - freeing a reservation.
66 * RESERVE_ALLOC - allocating space and we need to update bytes_may_use for
67 * ENOSPC accounting
68 * RESERVE_ALLOC_NO_ACCOUNT - allocating space and we should not update
69 * bytes_may_use as the ENOSPC accounting is done elsewhere
70 */
71enum {
72 RESERVE_FREE = 0,
73 RESERVE_ALLOC = 1,
74 RESERVE_ALLOC_NO_ACCOUNT = 2,
75};
76
ce93ec54
JB
77static int update_block_group(struct btrfs_trans_handle *trans,
78 struct btrfs_root *root, u64 bytenr,
79 u64 num_bytes, int alloc);
5d4f98a2
YZ
80static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
81 struct btrfs_root *root,
c682f9b3 82 struct btrfs_delayed_ref_node *node, u64 parent,
5d4f98a2
YZ
83 u64 root_objectid, u64 owner_objectid,
84 u64 owner_offset, int refs_to_drop,
c682f9b3 85 struct btrfs_delayed_extent_op *extra_op);
5d4f98a2
YZ
86static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
87 struct extent_buffer *leaf,
88 struct btrfs_extent_item *ei);
89static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
90 struct btrfs_root *root,
91 u64 parent, u64 root_objectid,
92 u64 flags, u64 owner, u64 offset,
93 struct btrfs_key *ins, int ref_mod);
94static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
95 struct btrfs_root *root,
96 u64 parent, u64 root_objectid,
97 u64 flags, struct btrfs_disk_key *key,
b06c4bf5 98 int level, struct btrfs_key *ins);
6a63209f 99static int do_chunk_alloc(struct btrfs_trans_handle *trans,
698d0082
JB
100 struct btrfs_root *extent_root, u64 flags,
101 int force);
11833d66
YZ
102static int find_next_key(struct btrfs_path *path, int level,
103 struct btrfs_key *key);
9ed74f2d
JB
104static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
105 int dump_block_groups);
fb25e914 106static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
e570fd27
MX
107 u64 num_bytes, int reserve,
108 int delalloc);
5d80366e
JB
109static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
110 u64 num_bytes);
48a3b636
ES
111int btrfs_pin_extent(struct btrfs_root *root,
112 u64 bytenr, u64 num_bytes, int reserved);
6a63209f 113
817d52f8
JB
114static noinline int
115block_group_cache_done(struct btrfs_block_group_cache *cache)
116{
117 smp_mb();
36cce922
JB
118 return cache->cached == BTRFS_CACHE_FINISHED ||
119 cache->cached == BTRFS_CACHE_ERROR;
817d52f8
JB
120}
121
0f9dd46c
JB
122static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
123{
124 return (cache->flags & bits) == bits;
125}
126
62a45b60 127static void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
11dfe35a
JB
128{
129 atomic_inc(&cache->count);
130}
131
132void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
133{
f0486c68
YZ
134 if (atomic_dec_and_test(&cache->count)) {
135 WARN_ON(cache->pinned > 0);
136 WARN_ON(cache->reserved > 0);
34d52cb6 137 kfree(cache->free_space_ctl);
11dfe35a 138 kfree(cache);
f0486c68 139 }
11dfe35a
JB
140}
141
0f9dd46c
JB
142/*
143 * this adds the block group to the fs_info rb tree for the block group
144 * cache
145 */
b2950863 146static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
0f9dd46c
JB
147 struct btrfs_block_group_cache *block_group)
148{
149 struct rb_node **p;
150 struct rb_node *parent = NULL;
151 struct btrfs_block_group_cache *cache;
152
153 spin_lock(&info->block_group_cache_lock);
154 p = &info->block_group_cache_tree.rb_node;
155
156 while (*p) {
157 parent = *p;
158 cache = rb_entry(parent, struct btrfs_block_group_cache,
159 cache_node);
160 if (block_group->key.objectid < cache->key.objectid) {
161 p = &(*p)->rb_left;
162 } else if (block_group->key.objectid > cache->key.objectid) {
163 p = &(*p)->rb_right;
164 } else {
165 spin_unlock(&info->block_group_cache_lock);
166 return -EEXIST;
167 }
168 }
169
170 rb_link_node(&block_group->cache_node, parent, p);
171 rb_insert_color(&block_group->cache_node,
172 &info->block_group_cache_tree);
a1897fdd
LB
173
174 if (info->first_logical_byte > block_group->key.objectid)
175 info->first_logical_byte = block_group->key.objectid;
176
0f9dd46c
JB
177 spin_unlock(&info->block_group_cache_lock);
178
179 return 0;
180}
181
182/*
183 * This will return the block group at or after bytenr if contains is 0, else
184 * it will return the block group that contains the bytenr
185 */
186static struct btrfs_block_group_cache *
187block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
188 int contains)
189{
190 struct btrfs_block_group_cache *cache, *ret = NULL;
191 struct rb_node *n;
192 u64 end, start;
193
194 spin_lock(&info->block_group_cache_lock);
195 n = info->block_group_cache_tree.rb_node;
196
197 while (n) {
198 cache = rb_entry(n, struct btrfs_block_group_cache,
199 cache_node);
200 end = cache->key.objectid + cache->key.offset - 1;
201 start = cache->key.objectid;
202
203 if (bytenr < start) {
204 if (!contains && (!ret || start < ret->key.objectid))
205 ret = cache;
206 n = n->rb_left;
207 } else if (bytenr > start) {
208 if (contains && bytenr <= end) {
209 ret = cache;
210 break;
211 }
212 n = n->rb_right;
213 } else {
214 ret = cache;
215 break;
216 }
217 }
a1897fdd 218 if (ret) {
11dfe35a 219 btrfs_get_block_group(ret);
a1897fdd
LB
220 if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
221 info->first_logical_byte = ret->key.objectid;
222 }
0f9dd46c
JB
223 spin_unlock(&info->block_group_cache_lock);
224
225 return ret;
226}
227
11833d66
YZ
228static int add_excluded_extent(struct btrfs_root *root,
229 u64 start, u64 num_bytes)
817d52f8 230{
11833d66
YZ
231 u64 end = start + num_bytes - 1;
232 set_extent_bits(&root->fs_info->freed_extents[0],
233 start, end, EXTENT_UPTODATE, GFP_NOFS);
234 set_extent_bits(&root->fs_info->freed_extents[1],
235 start, end, EXTENT_UPTODATE, GFP_NOFS);
236 return 0;
237}
817d52f8 238
11833d66
YZ
239static void free_excluded_extents(struct btrfs_root *root,
240 struct btrfs_block_group_cache *cache)
241{
242 u64 start, end;
817d52f8 243
11833d66
YZ
244 start = cache->key.objectid;
245 end = start + cache->key.offset - 1;
246
247 clear_extent_bits(&root->fs_info->freed_extents[0],
248 start, end, EXTENT_UPTODATE, GFP_NOFS);
249 clear_extent_bits(&root->fs_info->freed_extents[1],
250 start, end, EXTENT_UPTODATE, GFP_NOFS);
817d52f8
JB
251}
252
11833d66
YZ
253static int exclude_super_stripes(struct btrfs_root *root,
254 struct btrfs_block_group_cache *cache)
817d52f8 255{
817d52f8
JB
256 u64 bytenr;
257 u64 *logical;
258 int stripe_len;
259 int i, nr, ret;
260
06b2331f
YZ
261 if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
262 stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
263 cache->bytes_super += stripe_len;
264 ret = add_excluded_extent(root, cache->key.objectid,
265 stripe_len);
835d974f
JB
266 if (ret)
267 return ret;
06b2331f
YZ
268 }
269
817d52f8
JB
270 for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
271 bytenr = btrfs_sb_offset(i);
272 ret = btrfs_rmap_block(&root->fs_info->mapping_tree,
273 cache->key.objectid, bytenr,
274 0, &logical, &nr, &stripe_len);
835d974f
JB
275 if (ret)
276 return ret;
11833d66 277
817d52f8 278 while (nr--) {
51bf5f0b
JB
279 u64 start, len;
280
281 if (logical[nr] > cache->key.objectid +
282 cache->key.offset)
283 continue;
284
285 if (logical[nr] + stripe_len <= cache->key.objectid)
286 continue;
287
288 start = logical[nr];
289 if (start < cache->key.objectid) {
290 start = cache->key.objectid;
291 len = (logical[nr] + stripe_len) - start;
292 } else {
293 len = min_t(u64, stripe_len,
294 cache->key.objectid +
295 cache->key.offset - start);
296 }
297
298 cache->bytes_super += len;
299 ret = add_excluded_extent(root, start, len);
835d974f
JB
300 if (ret) {
301 kfree(logical);
302 return ret;
303 }
817d52f8 304 }
11833d66 305
817d52f8
JB
306 kfree(logical);
307 }
817d52f8
JB
308 return 0;
309}
310
11833d66
YZ
311static struct btrfs_caching_control *
312get_caching_control(struct btrfs_block_group_cache *cache)
313{
314 struct btrfs_caching_control *ctl;
315
316 spin_lock(&cache->lock);
dde5abee
JB
317 if (!cache->caching_ctl) {
318 spin_unlock(&cache->lock);
11833d66
YZ
319 return NULL;
320 }
321
322 ctl = cache->caching_ctl;
323 atomic_inc(&ctl->count);
324 spin_unlock(&cache->lock);
325 return ctl;
326}
327
328static void put_caching_control(struct btrfs_caching_control *ctl)
329{
330 if (atomic_dec_and_test(&ctl->count))
331 kfree(ctl);
332}
333
d0bd4560
JB
334#ifdef CONFIG_BTRFS_DEBUG
335static void fragment_free_space(struct btrfs_root *root,
336 struct btrfs_block_group_cache *block_group)
337{
338 u64 start = block_group->key.objectid;
339 u64 len = block_group->key.offset;
340 u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
341 root->nodesize : root->sectorsize;
342 u64 step = chunk << 1;
343
344 while (len > chunk) {
345 btrfs_remove_free_space(block_group, start, chunk);
346 start += step;
347 if (len < step)
348 len = 0;
349 else
350 len -= step;
351 }
352}
353#endif
354
0f9dd46c
JB
355/*
356 * this is only called by cache_block_group, since we could have freed extents
357 * we need to check the pinned_extents for any extents that can't be used yet
358 * since their free space will be released as soon as the transaction commits.
359 */
817d52f8 360static u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
0f9dd46c
JB
361 struct btrfs_fs_info *info, u64 start, u64 end)
362{
817d52f8 363 u64 extent_start, extent_end, size, total_added = 0;
0f9dd46c
JB
364 int ret;
365
366 while (start < end) {
11833d66 367 ret = find_first_extent_bit(info->pinned_extents, start,
0f9dd46c 368 &extent_start, &extent_end,
e6138876
JB
369 EXTENT_DIRTY | EXTENT_UPTODATE,
370 NULL);
0f9dd46c
JB
371 if (ret)
372 break;
373
06b2331f 374 if (extent_start <= start) {
0f9dd46c
JB
375 start = extent_end + 1;
376 } else if (extent_start > start && extent_start < end) {
377 size = extent_start - start;
817d52f8 378 total_added += size;
ea6a478e
JB
379 ret = btrfs_add_free_space(block_group, start,
380 size);
79787eaa 381 BUG_ON(ret); /* -ENOMEM or logic error */
0f9dd46c
JB
382 start = extent_end + 1;
383 } else {
384 break;
385 }
386 }
387
388 if (start < end) {
389 size = end - start;
817d52f8 390 total_added += size;
ea6a478e 391 ret = btrfs_add_free_space(block_group, start, size);
79787eaa 392 BUG_ON(ret); /* -ENOMEM or logic error */
0f9dd46c
JB
393 }
394
817d52f8 395 return total_added;
0f9dd46c
JB
396}
397
d458b054 398static noinline void caching_thread(struct btrfs_work *work)
e37c9e69 399{
bab39bf9
JB
400 struct btrfs_block_group_cache *block_group;
401 struct btrfs_fs_info *fs_info;
402 struct btrfs_caching_control *caching_ctl;
403 struct btrfs_root *extent_root;
e37c9e69 404 struct btrfs_path *path;
5f39d397 405 struct extent_buffer *leaf;
11833d66 406 struct btrfs_key key;
817d52f8 407 u64 total_found = 0;
11833d66
YZ
408 u64 last = 0;
409 u32 nritems;
36cce922 410 int ret = -ENOMEM;
d0bd4560 411 bool wakeup = true;
f510cfec 412
bab39bf9
JB
413 caching_ctl = container_of(work, struct btrfs_caching_control, work);
414 block_group = caching_ctl->block_group;
415 fs_info = block_group->fs_info;
416 extent_root = fs_info->extent_root;
417
e37c9e69
CM
418 path = btrfs_alloc_path();
419 if (!path)
bab39bf9 420 goto out;
7d7d6068 421
817d52f8 422 last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
11833d66 423
d0bd4560
JB
424#ifdef CONFIG_BTRFS_DEBUG
425 /*
426 * If we're fragmenting we don't want to make anybody think we can
427 * allocate from this block group until we've had a chance to fragment
428 * the free space.
429 */
430 if (btrfs_should_fragment_free_space(extent_root, block_group))
431 wakeup = false;
432#endif
5cd57b2c 433 /*
817d52f8
JB
434 * We don't want to deadlock with somebody trying to allocate a new
435 * extent for the extent root while also trying to search the extent
436 * root to add free space. So we skip locking and search the commit
437 * root, since its read-only
5cd57b2c
CM
438 */
439 path->skip_locking = 1;
817d52f8 440 path->search_commit_root = 1;
026fd317 441 path->reada = 1;
817d52f8 442
e4404d6e 443 key.objectid = last;
e37c9e69 444 key.offset = 0;
11833d66 445 key.type = BTRFS_EXTENT_ITEM_KEY;
013f1b12 446again:
11833d66 447 mutex_lock(&caching_ctl->mutex);
013f1b12 448 /* need to make sure the commit_root doesn't disappear */
9e351cc8 449 down_read(&fs_info->commit_root_sem);
013f1b12 450
52ee28d2 451next:
11833d66 452 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
e37c9e69 453 if (ret < 0)
ef8bbdfe 454 goto err;
a512bbf8 455
11833d66
YZ
456 leaf = path->nodes[0];
457 nritems = btrfs_header_nritems(leaf);
458
d397712b 459 while (1) {
7841cb28 460 if (btrfs_fs_closing(fs_info) > 1) {
f25784b3 461 last = (u64)-1;
817d52f8 462 break;
f25784b3 463 }
817d52f8 464
11833d66
YZ
465 if (path->slots[0] < nritems) {
466 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
467 } else {
468 ret = find_next_key(path, 0, &key);
469 if (ret)
e37c9e69 470 break;
817d52f8 471
c9ea7b24 472 if (need_resched() ||
9e351cc8 473 rwsem_is_contended(&fs_info->commit_root_sem)) {
d0bd4560
JB
474 if (wakeup)
475 caching_ctl->progress = last;
ff5714cc 476 btrfs_release_path(path);
9e351cc8 477 up_read(&fs_info->commit_root_sem);
589d8ade 478 mutex_unlock(&caching_ctl->mutex);
11833d66 479 cond_resched();
589d8ade
JB
480 goto again;
481 }
0a3896d0
JB
482
483 ret = btrfs_next_leaf(extent_root, path);
484 if (ret < 0)
485 goto err;
486 if (ret)
487 break;
589d8ade
JB
488 leaf = path->nodes[0];
489 nritems = btrfs_header_nritems(leaf);
490 continue;
11833d66 491 }
817d52f8 492
52ee28d2
LB
493 if (key.objectid < last) {
494 key.objectid = last;
495 key.offset = 0;
496 key.type = BTRFS_EXTENT_ITEM_KEY;
497
d0bd4560
JB
498 if (wakeup)
499 caching_ctl->progress = last;
52ee28d2
LB
500 btrfs_release_path(path);
501 goto next;
502 }
503
11833d66
YZ
504 if (key.objectid < block_group->key.objectid) {
505 path->slots[0]++;
817d52f8 506 continue;
e37c9e69 507 }
0f9dd46c 508
e37c9e69 509 if (key.objectid >= block_group->key.objectid +
0f9dd46c 510 block_group->key.offset)
e37c9e69 511 break;
7d7d6068 512
3173a18f
JB
513 if (key.type == BTRFS_EXTENT_ITEM_KEY ||
514 key.type == BTRFS_METADATA_ITEM_KEY) {
817d52f8
JB
515 total_found += add_new_free_space(block_group,
516 fs_info, last,
517 key.objectid);
3173a18f
JB
518 if (key.type == BTRFS_METADATA_ITEM_KEY)
519 last = key.objectid +
707e8a07 520 fs_info->tree_root->nodesize;
3173a18f
JB
521 else
522 last = key.objectid + key.offset;
817d52f8 523
11833d66
YZ
524 if (total_found > (1024 * 1024 * 2)) {
525 total_found = 0;
d0bd4560
JB
526 if (wakeup)
527 wake_up(&caching_ctl->wait);
11833d66 528 }
817d52f8 529 }
e37c9e69
CM
530 path->slots[0]++;
531 }
817d52f8 532 ret = 0;
e37c9e69 533
817d52f8
JB
534 total_found += add_new_free_space(block_group, fs_info, last,
535 block_group->key.objectid +
536 block_group->key.offset);
817d52f8 537 spin_lock(&block_group->lock);
11833d66 538 block_group->caching_ctl = NULL;
817d52f8
JB
539 block_group->cached = BTRFS_CACHE_FINISHED;
540 spin_unlock(&block_group->lock);
0f9dd46c 541
d0bd4560
JB
542#ifdef CONFIG_BTRFS_DEBUG
543 if (btrfs_should_fragment_free_space(extent_root, block_group)) {
544 u64 bytes_used;
545
546 spin_lock(&block_group->space_info->lock);
547 spin_lock(&block_group->lock);
548 bytes_used = block_group->key.offset -
549 btrfs_block_group_used(&block_group->item);
550 block_group->space_info->bytes_used += bytes_used >> 1;
551 spin_unlock(&block_group->lock);
552 spin_unlock(&block_group->space_info->lock);
553 fragment_free_space(extent_root, block_group);
554 }
555#endif
556
557 caching_ctl->progress = (u64)-1;
54aa1f4d 558err:
e37c9e69 559 btrfs_free_path(path);
9e351cc8 560 up_read(&fs_info->commit_root_sem);
817d52f8 561
11833d66
YZ
562 free_excluded_extents(extent_root, block_group);
563
564 mutex_unlock(&caching_ctl->mutex);
bab39bf9 565out:
36cce922
JB
566 if (ret) {
567 spin_lock(&block_group->lock);
568 block_group->caching_ctl = NULL;
569 block_group->cached = BTRFS_CACHE_ERROR;
570 spin_unlock(&block_group->lock);
571 }
11833d66
YZ
572 wake_up(&caching_ctl->wait);
573
574 put_caching_control(caching_ctl);
11dfe35a 575 btrfs_put_block_group(block_group);
817d52f8
JB
576}
577
9d66e233 578static int cache_block_group(struct btrfs_block_group_cache *cache,
9d66e233 579 int load_cache_only)
817d52f8 580{
291c7d2f 581 DEFINE_WAIT(wait);
11833d66
YZ
582 struct btrfs_fs_info *fs_info = cache->fs_info;
583 struct btrfs_caching_control *caching_ctl;
817d52f8
JB
584 int ret = 0;
585
291c7d2f 586 caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
79787eaa
JM
587 if (!caching_ctl)
588 return -ENOMEM;
291c7d2f
JB
589
590 INIT_LIST_HEAD(&caching_ctl->list);
591 mutex_init(&caching_ctl->mutex);
592 init_waitqueue_head(&caching_ctl->wait);
593 caching_ctl->block_group = cache;
594 caching_ctl->progress = cache->key.objectid;
595 atomic_set(&caching_ctl->count, 1);
9e0af237
LB
596 btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
597 caching_thread, NULL, NULL);
291c7d2f
JB
598
599 spin_lock(&cache->lock);
600 /*
601 * This should be a rare occasion, but this could happen I think in the
602 * case where one thread starts to load the space cache info, and then
603 * some other thread starts a transaction commit which tries to do an
604 * allocation while the other thread is still loading the space cache
605 * info. The previous loop should have kept us from choosing this block
606 * group, but if we've moved to the state where we will wait on caching
607 * block groups we need to first check if we're doing a fast load here,
608 * so we can wait for it to finish, otherwise we could end up allocating
609 * from a block group who's cache gets evicted for one reason or
610 * another.
611 */
612 while (cache->cached == BTRFS_CACHE_FAST) {
613 struct btrfs_caching_control *ctl;
614
615 ctl = cache->caching_ctl;
616 atomic_inc(&ctl->count);
617 prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
618 spin_unlock(&cache->lock);
619
620 schedule();
621
622 finish_wait(&ctl->wait, &wait);
623 put_caching_control(ctl);
624 spin_lock(&cache->lock);
625 }
626
627 if (cache->cached != BTRFS_CACHE_NO) {
628 spin_unlock(&cache->lock);
629 kfree(caching_ctl);
11833d66 630 return 0;
291c7d2f
JB
631 }
632 WARN_ON(cache->caching_ctl);
633 cache->caching_ctl = caching_ctl;
634 cache->cached = BTRFS_CACHE_FAST;
635 spin_unlock(&cache->lock);
11833d66 636
d53ba474 637 if (fs_info->mount_opt & BTRFS_MOUNT_SPACE_CACHE) {
cb83b7b8 638 mutex_lock(&caching_ctl->mutex);
9d66e233
JB
639 ret = load_free_space_cache(fs_info, cache);
640
641 spin_lock(&cache->lock);
642 if (ret == 1) {
291c7d2f 643 cache->caching_ctl = NULL;
9d66e233
JB
644 cache->cached = BTRFS_CACHE_FINISHED;
645 cache->last_byte_to_unpin = (u64)-1;
cb83b7b8 646 caching_ctl->progress = (u64)-1;
9d66e233 647 } else {
291c7d2f
JB
648 if (load_cache_only) {
649 cache->caching_ctl = NULL;
650 cache->cached = BTRFS_CACHE_NO;
651 } else {
652 cache->cached = BTRFS_CACHE_STARTED;
4f69cb98 653 cache->has_caching_ctl = 1;
291c7d2f 654 }
9d66e233
JB
655 }
656 spin_unlock(&cache->lock);
d0bd4560
JB
657#ifdef CONFIG_BTRFS_DEBUG
658 if (ret == 1 &&
659 btrfs_should_fragment_free_space(fs_info->extent_root,
660 cache)) {
661 u64 bytes_used;
662
663 spin_lock(&cache->space_info->lock);
664 spin_lock(&cache->lock);
665 bytes_used = cache->key.offset -
666 btrfs_block_group_used(&cache->item);
667 cache->space_info->bytes_used += bytes_used >> 1;
668 spin_unlock(&cache->lock);
669 spin_unlock(&cache->space_info->lock);
670 fragment_free_space(fs_info->extent_root, cache);
671 }
672#endif
cb83b7b8
JB
673 mutex_unlock(&caching_ctl->mutex);
674
291c7d2f 675 wake_up(&caching_ctl->wait);
3c14874a 676 if (ret == 1) {
291c7d2f 677 put_caching_control(caching_ctl);
3c14874a 678 free_excluded_extents(fs_info->extent_root, cache);
9d66e233 679 return 0;
3c14874a 680 }
291c7d2f
JB
681 } else {
682 /*
683 * We are not going to do the fast caching, set cached to the
684 * appropriate value and wakeup any waiters.
685 */
686 spin_lock(&cache->lock);
687 if (load_cache_only) {
688 cache->caching_ctl = NULL;
689 cache->cached = BTRFS_CACHE_NO;
690 } else {
691 cache->cached = BTRFS_CACHE_STARTED;
4f69cb98 692 cache->has_caching_ctl = 1;
291c7d2f
JB
693 }
694 spin_unlock(&cache->lock);
695 wake_up(&caching_ctl->wait);
9d66e233
JB
696 }
697
291c7d2f
JB
698 if (load_cache_only) {
699 put_caching_control(caching_ctl);
11833d66 700 return 0;
817d52f8 701 }
817d52f8 702
9e351cc8 703 down_write(&fs_info->commit_root_sem);
291c7d2f 704 atomic_inc(&caching_ctl->count);
11833d66 705 list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
9e351cc8 706 up_write(&fs_info->commit_root_sem);
11833d66 707
11dfe35a 708 btrfs_get_block_group(cache);
11833d66 709
e66f0bb1 710 btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
817d52f8 711
ef8bbdfe 712 return ret;
e37c9e69
CM
713}
714
0f9dd46c
JB
715/*
716 * return the block group that starts at or after bytenr
717 */
d397712b
CM
718static struct btrfs_block_group_cache *
719btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
0ef3e66b 720{
0f9dd46c 721 struct btrfs_block_group_cache *cache;
0ef3e66b 722
0f9dd46c 723 cache = block_group_cache_tree_search(info, bytenr, 0);
0ef3e66b 724
0f9dd46c 725 return cache;
0ef3e66b
CM
726}
727
0f9dd46c 728/*
9f55684c 729 * return the block group that contains the given bytenr
0f9dd46c 730 */
d397712b
CM
731struct btrfs_block_group_cache *btrfs_lookup_block_group(
732 struct btrfs_fs_info *info,
733 u64 bytenr)
be744175 734{
0f9dd46c 735 struct btrfs_block_group_cache *cache;
be744175 736
0f9dd46c 737 cache = block_group_cache_tree_search(info, bytenr, 1);
96b5179d 738
0f9dd46c 739 return cache;
be744175 740}
0b86a832 741
0f9dd46c
JB
742static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
743 u64 flags)
6324fbf3 744{
0f9dd46c 745 struct list_head *head = &info->space_info;
0f9dd46c 746 struct btrfs_space_info *found;
4184ea7f 747
52ba6929 748 flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
b742bb82 749
4184ea7f
CM
750 rcu_read_lock();
751 list_for_each_entry_rcu(found, head, list) {
67377734 752 if (found->flags & flags) {
4184ea7f 753 rcu_read_unlock();
0f9dd46c 754 return found;
4184ea7f 755 }
0f9dd46c 756 }
4184ea7f 757 rcu_read_unlock();
0f9dd46c 758 return NULL;
6324fbf3
CM
759}
760
4184ea7f
CM
761/*
762 * after adding space to the filesystem, we need to clear the full flags
763 * on all the space infos.
764 */
765void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
766{
767 struct list_head *head = &info->space_info;
768 struct btrfs_space_info *found;
769
770 rcu_read_lock();
771 list_for_each_entry_rcu(found, head, list)
772 found->full = 0;
773 rcu_read_unlock();
774}
775
1a4ed8fd
FM
776/* simple helper to search for an existing data extent at a given offset */
777int btrfs_lookup_data_extent(struct btrfs_root *root, u64 start, u64 len)
e02119d5
CM
778{
779 int ret;
780 struct btrfs_key key;
31840ae1 781 struct btrfs_path *path;
e02119d5 782
31840ae1 783 path = btrfs_alloc_path();
d8926bb3
MF
784 if (!path)
785 return -ENOMEM;
786
e02119d5
CM
787 key.objectid = start;
788 key.offset = len;
3173a18f 789 key.type = BTRFS_EXTENT_ITEM_KEY;
e02119d5
CM
790 ret = btrfs_search_slot(NULL, root->fs_info->extent_root, &key, path,
791 0, 0);
31840ae1 792 btrfs_free_path(path);
7bb86316
CM
793 return ret;
794}
795
a22285a6 796/*
3173a18f 797 * helper function to lookup reference count and flags of a tree block.
a22285a6
YZ
798 *
799 * the head node for delayed ref is used to store the sum of all the
800 * reference count modifications queued up in the rbtree. the head
801 * node may also store the extent flags to set. This way you can check
802 * to see what the reference count and extent flags would be if all of
803 * the delayed refs are not processed.
804 */
805int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
806 struct btrfs_root *root, u64 bytenr,
3173a18f 807 u64 offset, int metadata, u64 *refs, u64 *flags)
a22285a6
YZ
808{
809 struct btrfs_delayed_ref_head *head;
810 struct btrfs_delayed_ref_root *delayed_refs;
811 struct btrfs_path *path;
812 struct btrfs_extent_item *ei;
813 struct extent_buffer *leaf;
814 struct btrfs_key key;
815 u32 item_size;
816 u64 num_refs;
817 u64 extent_flags;
818 int ret;
819
3173a18f
JB
820 /*
821 * If we don't have skinny metadata, don't bother doing anything
822 * different
823 */
824 if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA)) {
707e8a07 825 offset = root->nodesize;
3173a18f
JB
826 metadata = 0;
827 }
828
a22285a6
YZ
829 path = btrfs_alloc_path();
830 if (!path)
831 return -ENOMEM;
832
a22285a6
YZ
833 if (!trans) {
834 path->skip_locking = 1;
835 path->search_commit_root = 1;
836 }
639eefc8
FDBM
837
838search_again:
839 key.objectid = bytenr;
840 key.offset = offset;
841 if (metadata)
842 key.type = BTRFS_METADATA_ITEM_KEY;
843 else
844 key.type = BTRFS_EXTENT_ITEM_KEY;
845
a22285a6
YZ
846 ret = btrfs_search_slot(trans, root->fs_info->extent_root,
847 &key, path, 0, 0);
848 if (ret < 0)
849 goto out_free;
850
3173a18f 851 if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
74be9510
FDBM
852 if (path->slots[0]) {
853 path->slots[0]--;
854 btrfs_item_key_to_cpu(path->nodes[0], &key,
855 path->slots[0]);
856 if (key.objectid == bytenr &&
857 key.type == BTRFS_EXTENT_ITEM_KEY &&
707e8a07 858 key.offset == root->nodesize)
74be9510
FDBM
859 ret = 0;
860 }
3173a18f
JB
861 }
862
a22285a6
YZ
863 if (ret == 0) {
864 leaf = path->nodes[0];
865 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
866 if (item_size >= sizeof(*ei)) {
867 ei = btrfs_item_ptr(leaf, path->slots[0],
868 struct btrfs_extent_item);
869 num_refs = btrfs_extent_refs(leaf, ei);
870 extent_flags = btrfs_extent_flags(leaf, ei);
871 } else {
872#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
873 struct btrfs_extent_item_v0 *ei0;
874 BUG_ON(item_size != sizeof(*ei0));
875 ei0 = btrfs_item_ptr(leaf, path->slots[0],
876 struct btrfs_extent_item_v0);
877 num_refs = btrfs_extent_refs_v0(leaf, ei0);
878 /* FIXME: this isn't correct for data */
879 extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
880#else
881 BUG();
882#endif
883 }
884 BUG_ON(num_refs == 0);
885 } else {
886 num_refs = 0;
887 extent_flags = 0;
888 ret = 0;
889 }
890
891 if (!trans)
892 goto out;
893
894 delayed_refs = &trans->transaction->delayed_refs;
895 spin_lock(&delayed_refs->lock);
896 head = btrfs_find_delayed_ref_head(trans, bytenr);
897 if (head) {
898 if (!mutex_trylock(&head->mutex)) {
899 atomic_inc(&head->node.refs);
900 spin_unlock(&delayed_refs->lock);
901
b3b4aa74 902 btrfs_release_path(path);
a22285a6 903
8cc33e5c
DS
904 /*
905 * Mutex was contended, block until it's released and try
906 * again
907 */
a22285a6
YZ
908 mutex_lock(&head->mutex);
909 mutex_unlock(&head->mutex);
910 btrfs_put_delayed_ref(&head->node);
639eefc8 911 goto search_again;
a22285a6 912 }
d7df2c79 913 spin_lock(&head->lock);
a22285a6
YZ
914 if (head->extent_op && head->extent_op->update_flags)
915 extent_flags |= head->extent_op->flags_to_set;
916 else
917 BUG_ON(num_refs == 0);
918
919 num_refs += head->node.ref_mod;
d7df2c79 920 spin_unlock(&head->lock);
a22285a6
YZ
921 mutex_unlock(&head->mutex);
922 }
923 spin_unlock(&delayed_refs->lock);
924out:
925 WARN_ON(num_refs == 0);
926 if (refs)
927 *refs = num_refs;
928 if (flags)
929 *flags = extent_flags;
930out_free:
931 btrfs_free_path(path);
932 return ret;
933}
934
d8d5f3e1
CM
935/*
936 * Back reference rules. Back refs have three main goals:
937 *
938 * 1) differentiate between all holders of references to an extent so that
939 * when a reference is dropped we can make sure it was a valid reference
940 * before freeing the extent.
941 *
942 * 2) Provide enough information to quickly find the holders of an extent
943 * if we notice a given block is corrupted or bad.
944 *
945 * 3) Make it easy to migrate blocks for FS shrinking or storage pool
946 * maintenance. This is actually the same as #2, but with a slightly
947 * different use case.
948 *
5d4f98a2
YZ
949 * There are two kinds of back refs. The implicit back refs is optimized
950 * for pointers in non-shared tree blocks. For a given pointer in a block,
951 * back refs of this kind provide information about the block's owner tree
952 * and the pointer's key. These information allow us to find the block by
953 * b-tree searching. The full back refs is for pointers in tree blocks not
954 * referenced by their owner trees. The location of tree block is recorded
955 * in the back refs. Actually the full back refs is generic, and can be
956 * used in all cases the implicit back refs is used. The major shortcoming
957 * of the full back refs is its overhead. Every time a tree block gets
958 * COWed, we have to update back refs entry for all pointers in it.
959 *
960 * For a newly allocated tree block, we use implicit back refs for
961 * pointers in it. This means most tree related operations only involve
962 * implicit back refs. For a tree block created in old transaction, the
963 * only way to drop a reference to it is COW it. So we can detect the
964 * event that tree block loses its owner tree's reference and do the
965 * back refs conversion.
966 *
967 * When a tree block is COW'd through a tree, there are four cases:
968 *
969 * The reference count of the block is one and the tree is the block's
970 * owner tree. Nothing to do in this case.
971 *
972 * The reference count of the block is one and the tree is not the
973 * block's owner tree. In this case, full back refs is used for pointers
974 * in the block. Remove these full back refs, add implicit back refs for
975 * every pointers in the new block.
976 *
977 * The reference count of the block is greater than one and the tree is
978 * the block's owner tree. In this case, implicit back refs is used for
979 * pointers in the block. Add full back refs for every pointers in the
980 * block, increase lower level extents' reference counts. The original
981 * implicit back refs are entailed to the new block.
982 *
983 * The reference count of the block is greater than one and the tree is
984 * not the block's owner tree. Add implicit back refs for every pointer in
985 * the new block, increase lower level extents' reference count.
986 *
987 * Back Reference Key composing:
988 *
989 * The key objectid corresponds to the first byte in the extent,
990 * The key type is used to differentiate between types of back refs.
991 * There are different meanings of the key offset for different types
992 * of back refs.
993 *
d8d5f3e1
CM
994 * File extents can be referenced by:
995 *
996 * - multiple snapshots, subvolumes, or different generations in one subvol
31840ae1 997 * - different files inside a single subvolume
d8d5f3e1
CM
998 * - different offsets inside a file (bookend extents in file.c)
999 *
5d4f98a2 1000 * The extent ref structure for the implicit back refs has fields for:
d8d5f3e1
CM
1001 *
1002 * - Objectid of the subvolume root
d8d5f3e1 1003 * - objectid of the file holding the reference
5d4f98a2
YZ
1004 * - original offset in the file
1005 * - how many bookend extents
d8d5f3e1 1006 *
5d4f98a2
YZ
1007 * The key offset for the implicit back refs is hash of the first
1008 * three fields.
d8d5f3e1 1009 *
5d4f98a2 1010 * The extent ref structure for the full back refs has field for:
d8d5f3e1 1011 *
5d4f98a2 1012 * - number of pointers in the tree leaf
d8d5f3e1 1013 *
5d4f98a2
YZ
1014 * The key offset for the implicit back refs is the first byte of
1015 * the tree leaf
d8d5f3e1 1016 *
5d4f98a2
YZ
1017 * When a file extent is allocated, The implicit back refs is used.
1018 * the fields are filled in:
d8d5f3e1 1019 *
5d4f98a2 1020 * (root_key.objectid, inode objectid, offset in file, 1)
d8d5f3e1 1021 *
5d4f98a2
YZ
1022 * When a file extent is removed file truncation, we find the
1023 * corresponding implicit back refs and check the following fields:
d8d5f3e1 1024 *
5d4f98a2 1025 * (btrfs_header_owner(leaf), inode objectid, offset in file)
d8d5f3e1 1026 *
5d4f98a2 1027 * Btree extents can be referenced by:
d8d5f3e1 1028 *
5d4f98a2 1029 * - Different subvolumes
d8d5f3e1 1030 *
5d4f98a2
YZ
1031 * Both the implicit back refs and the full back refs for tree blocks
1032 * only consist of key. The key offset for the implicit back refs is
1033 * objectid of block's owner tree. The key offset for the full back refs
1034 * is the first byte of parent block.
d8d5f3e1 1035 *
5d4f98a2
YZ
1036 * When implicit back refs is used, information about the lowest key and
1037 * level of the tree block are required. These information are stored in
1038 * tree block info structure.
d8d5f3e1 1039 */
31840ae1 1040
5d4f98a2
YZ
1041#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1042static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
1043 struct btrfs_root *root,
1044 struct btrfs_path *path,
1045 u64 owner, u32 extra_size)
7bb86316 1046{
5d4f98a2
YZ
1047 struct btrfs_extent_item *item;
1048 struct btrfs_extent_item_v0 *ei0;
1049 struct btrfs_extent_ref_v0 *ref0;
1050 struct btrfs_tree_block_info *bi;
1051 struct extent_buffer *leaf;
7bb86316 1052 struct btrfs_key key;
5d4f98a2
YZ
1053 struct btrfs_key found_key;
1054 u32 new_size = sizeof(*item);
1055 u64 refs;
1056 int ret;
1057
1058 leaf = path->nodes[0];
1059 BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
1060
1061 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1062 ei0 = btrfs_item_ptr(leaf, path->slots[0],
1063 struct btrfs_extent_item_v0);
1064 refs = btrfs_extent_refs_v0(leaf, ei0);
1065
1066 if (owner == (u64)-1) {
1067 while (1) {
1068 if (path->slots[0] >= btrfs_header_nritems(leaf)) {
1069 ret = btrfs_next_leaf(root, path);
1070 if (ret < 0)
1071 return ret;
79787eaa 1072 BUG_ON(ret > 0); /* Corruption */
5d4f98a2
YZ
1073 leaf = path->nodes[0];
1074 }
1075 btrfs_item_key_to_cpu(leaf, &found_key,
1076 path->slots[0]);
1077 BUG_ON(key.objectid != found_key.objectid);
1078 if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
1079 path->slots[0]++;
1080 continue;
1081 }
1082 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1083 struct btrfs_extent_ref_v0);
1084 owner = btrfs_ref_objectid_v0(leaf, ref0);
1085 break;
1086 }
1087 }
b3b4aa74 1088 btrfs_release_path(path);
5d4f98a2
YZ
1089
1090 if (owner < BTRFS_FIRST_FREE_OBJECTID)
1091 new_size += sizeof(*bi);
1092
1093 new_size -= sizeof(*ei0);
1094 ret = btrfs_search_slot(trans, root, &key, path,
1095 new_size + extra_size, 1);
1096 if (ret < 0)
1097 return ret;
79787eaa 1098 BUG_ON(ret); /* Corruption */
5d4f98a2 1099
4b90c680 1100 btrfs_extend_item(root, path, new_size);
5d4f98a2
YZ
1101
1102 leaf = path->nodes[0];
1103 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1104 btrfs_set_extent_refs(leaf, item, refs);
1105 /* FIXME: get real generation */
1106 btrfs_set_extent_generation(leaf, item, 0);
1107 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1108 btrfs_set_extent_flags(leaf, item,
1109 BTRFS_EXTENT_FLAG_TREE_BLOCK |
1110 BTRFS_BLOCK_FLAG_FULL_BACKREF);
1111 bi = (struct btrfs_tree_block_info *)(item + 1);
1112 /* FIXME: get first key of the block */
1113 memset_extent_buffer(leaf, 0, (unsigned long)bi, sizeof(*bi));
1114 btrfs_set_tree_block_level(leaf, bi, (int)owner);
1115 } else {
1116 btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
1117 }
1118 btrfs_mark_buffer_dirty(leaf);
1119 return 0;
1120}
1121#endif
1122
1123static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
1124{
1125 u32 high_crc = ~(u32)0;
1126 u32 low_crc = ~(u32)0;
1127 __le64 lenum;
1128
1129 lenum = cpu_to_le64(root_objectid);
14a958e6 1130 high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
5d4f98a2 1131 lenum = cpu_to_le64(owner);
14a958e6 1132 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
5d4f98a2 1133 lenum = cpu_to_le64(offset);
14a958e6 1134 low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
5d4f98a2
YZ
1135
1136 return ((u64)high_crc << 31) ^ (u64)low_crc;
1137}
1138
1139static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
1140 struct btrfs_extent_data_ref *ref)
1141{
1142 return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
1143 btrfs_extent_data_ref_objectid(leaf, ref),
1144 btrfs_extent_data_ref_offset(leaf, ref));
1145}
1146
1147static int match_extent_data_ref(struct extent_buffer *leaf,
1148 struct btrfs_extent_data_ref *ref,
1149 u64 root_objectid, u64 owner, u64 offset)
1150{
1151 if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
1152 btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
1153 btrfs_extent_data_ref_offset(leaf, ref) != offset)
1154 return 0;
1155 return 1;
1156}
1157
1158static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
1159 struct btrfs_root *root,
1160 struct btrfs_path *path,
1161 u64 bytenr, u64 parent,
1162 u64 root_objectid,
1163 u64 owner, u64 offset)
1164{
1165 struct btrfs_key key;
1166 struct btrfs_extent_data_ref *ref;
31840ae1 1167 struct extent_buffer *leaf;
5d4f98a2 1168 u32 nritems;
74493f7a 1169 int ret;
5d4f98a2
YZ
1170 int recow;
1171 int err = -ENOENT;
74493f7a 1172
31840ae1 1173 key.objectid = bytenr;
5d4f98a2
YZ
1174 if (parent) {
1175 key.type = BTRFS_SHARED_DATA_REF_KEY;
1176 key.offset = parent;
1177 } else {
1178 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1179 key.offset = hash_extent_data_ref(root_objectid,
1180 owner, offset);
1181 }
1182again:
1183 recow = 0;
1184 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1185 if (ret < 0) {
1186 err = ret;
1187 goto fail;
1188 }
31840ae1 1189
5d4f98a2
YZ
1190 if (parent) {
1191 if (!ret)
1192 return 0;
1193#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1194 key.type = BTRFS_EXTENT_REF_V0_KEY;
b3b4aa74 1195 btrfs_release_path(path);
5d4f98a2
YZ
1196 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1197 if (ret < 0) {
1198 err = ret;
1199 goto fail;
1200 }
1201 if (!ret)
1202 return 0;
1203#endif
1204 goto fail;
31840ae1
ZY
1205 }
1206
1207 leaf = path->nodes[0];
5d4f98a2
YZ
1208 nritems = btrfs_header_nritems(leaf);
1209 while (1) {
1210 if (path->slots[0] >= nritems) {
1211 ret = btrfs_next_leaf(root, path);
1212 if (ret < 0)
1213 err = ret;
1214 if (ret)
1215 goto fail;
1216
1217 leaf = path->nodes[0];
1218 nritems = btrfs_header_nritems(leaf);
1219 recow = 1;
1220 }
1221
1222 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1223 if (key.objectid != bytenr ||
1224 key.type != BTRFS_EXTENT_DATA_REF_KEY)
1225 goto fail;
1226
1227 ref = btrfs_item_ptr(leaf, path->slots[0],
1228 struct btrfs_extent_data_ref);
1229
1230 if (match_extent_data_ref(leaf, ref, root_objectid,
1231 owner, offset)) {
1232 if (recow) {
b3b4aa74 1233 btrfs_release_path(path);
5d4f98a2
YZ
1234 goto again;
1235 }
1236 err = 0;
1237 break;
1238 }
1239 path->slots[0]++;
31840ae1 1240 }
5d4f98a2
YZ
1241fail:
1242 return err;
31840ae1
ZY
1243}
1244
5d4f98a2
YZ
1245static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
1246 struct btrfs_root *root,
1247 struct btrfs_path *path,
1248 u64 bytenr, u64 parent,
1249 u64 root_objectid, u64 owner,
1250 u64 offset, int refs_to_add)
31840ae1
ZY
1251{
1252 struct btrfs_key key;
1253 struct extent_buffer *leaf;
5d4f98a2 1254 u32 size;
31840ae1
ZY
1255 u32 num_refs;
1256 int ret;
74493f7a 1257
74493f7a 1258 key.objectid = bytenr;
5d4f98a2
YZ
1259 if (parent) {
1260 key.type = BTRFS_SHARED_DATA_REF_KEY;
1261 key.offset = parent;
1262 size = sizeof(struct btrfs_shared_data_ref);
1263 } else {
1264 key.type = BTRFS_EXTENT_DATA_REF_KEY;
1265 key.offset = hash_extent_data_ref(root_objectid,
1266 owner, offset);
1267 size = sizeof(struct btrfs_extent_data_ref);
1268 }
74493f7a 1269
5d4f98a2
YZ
1270 ret = btrfs_insert_empty_item(trans, root, path, &key, size);
1271 if (ret && ret != -EEXIST)
1272 goto fail;
1273
1274 leaf = path->nodes[0];
1275 if (parent) {
1276 struct btrfs_shared_data_ref *ref;
31840ae1 1277 ref = btrfs_item_ptr(leaf, path->slots[0],
5d4f98a2
YZ
1278 struct btrfs_shared_data_ref);
1279 if (ret == 0) {
1280 btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
1281 } else {
1282 num_refs = btrfs_shared_data_ref_count(leaf, ref);
1283 num_refs += refs_to_add;
1284 btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
31840ae1 1285 }
5d4f98a2
YZ
1286 } else {
1287 struct btrfs_extent_data_ref *ref;
1288 while (ret == -EEXIST) {
1289 ref = btrfs_item_ptr(leaf, path->slots[0],
1290 struct btrfs_extent_data_ref);
1291 if (match_extent_data_ref(leaf, ref, root_objectid,
1292 owner, offset))
1293 break;
b3b4aa74 1294 btrfs_release_path(path);
5d4f98a2
YZ
1295 key.offset++;
1296 ret = btrfs_insert_empty_item(trans, root, path, &key,
1297 size);
1298 if (ret && ret != -EEXIST)
1299 goto fail;
31840ae1 1300
5d4f98a2
YZ
1301 leaf = path->nodes[0];
1302 }
1303 ref = btrfs_item_ptr(leaf, path->slots[0],
1304 struct btrfs_extent_data_ref);
1305 if (ret == 0) {
1306 btrfs_set_extent_data_ref_root(leaf, ref,
1307 root_objectid);
1308 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
1309 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
1310 btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
1311 } else {
1312 num_refs = btrfs_extent_data_ref_count(leaf, ref);
1313 num_refs += refs_to_add;
1314 btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
31840ae1 1315 }
31840ae1 1316 }
5d4f98a2
YZ
1317 btrfs_mark_buffer_dirty(leaf);
1318 ret = 0;
1319fail:
b3b4aa74 1320 btrfs_release_path(path);
7bb86316 1321 return ret;
74493f7a
CM
1322}
1323
5d4f98a2
YZ
1324static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
1325 struct btrfs_root *root,
1326 struct btrfs_path *path,
fcebe456 1327 int refs_to_drop, int *last_ref)
31840ae1 1328{
5d4f98a2
YZ
1329 struct btrfs_key key;
1330 struct btrfs_extent_data_ref *ref1 = NULL;
1331 struct btrfs_shared_data_ref *ref2 = NULL;
31840ae1 1332 struct extent_buffer *leaf;
5d4f98a2 1333 u32 num_refs = 0;
31840ae1
ZY
1334 int ret = 0;
1335
1336 leaf = path->nodes[0];
5d4f98a2
YZ
1337 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1338
1339 if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1340 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1341 struct btrfs_extent_data_ref);
1342 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1343 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1344 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1345 struct btrfs_shared_data_ref);
1346 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1347#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1348 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1349 struct btrfs_extent_ref_v0 *ref0;
1350 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1351 struct btrfs_extent_ref_v0);
1352 num_refs = btrfs_ref_count_v0(leaf, ref0);
1353#endif
1354 } else {
1355 BUG();
1356 }
1357
56bec294
CM
1358 BUG_ON(num_refs < refs_to_drop);
1359 num_refs -= refs_to_drop;
5d4f98a2 1360
31840ae1
ZY
1361 if (num_refs == 0) {
1362 ret = btrfs_del_item(trans, root, path);
fcebe456 1363 *last_ref = 1;
31840ae1 1364 } else {
5d4f98a2
YZ
1365 if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
1366 btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
1367 else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
1368 btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
1369#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1370 else {
1371 struct btrfs_extent_ref_v0 *ref0;
1372 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1373 struct btrfs_extent_ref_v0);
1374 btrfs_set_ref_count_v0(leaf, ref0, num_refs);
1375 }
1376#endif
31840ae1
ZY
1377 btrfs_mark_buffer_dirty(leaf);
1378 }
31840ae1
ZY
1379 return ret;
1380}
1381
9ed0dea0 1382static noinline u32 extent_data_ref_count(struct btrfs_path *path,
5d4f98a2 1383 struct btrfs_extent_inline_ref *iref)
15916de8 1384{
5d4f98a2
YZ
1385 struct btrfs_key key;
1386 struct extent_buffer *leaf;
1387 struct btrfs_extent_data_ref *ref1;
1388 struct btrfs_shared_data_ref *ref2;
1389 u32 num_refs = 0;
1390
1391 leaf = path->nodes[0];
1392 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1393 if (iref) {
1394 if (btrfs_extent_inline_ref_type(leaf, iref) ==
1395 BTRFS_EXTENT_DATA_REF_KEY) {
1396 ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
1397 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1398 } else {
1399 ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
1400 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1401 }
1402 } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
1403 ref1 = btrfs_item_ptr(leaf, path->slots[0],
1404 struct btrfs_extent_data_ref);
1405 num_refs = btrfs_extent_data_ref_count(leaf, ref1);
1406 } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
1407 ref2 = btrfs_item_ptr(leaf, path->slots[0],
1408 struct btrfs_shared_data_ref);
1409 num_refs = btrfs_shared_data_ref_count(leaf, ref2);
1410#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1411 } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
1412 struct btrfs_extent_ref_v0 *ref0;
1413 ref0 = btrfs_item_ptr(leaf, path->slots[0],
1414 struct btrfs_extent_ref_v0);
1415 num_refs = btrfs_ref_count_v0(leaf, ref0);
4b4e25f2 1416#endif
5d4f98a2
YZ
1417 } else {
1418 WARN_ON(1);
1419 }
1420 return num_refs;
1421}
15916de8 1422
5d4f98a2
YZ
1423static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
1424 struct btrfs_root *root,
1425 struct btrfs_path *path,
1426 u64 bytenr, u64 parent,
1427 u64 root_objectid)
1f3c79a2 1428{
5d4f98a2 1429 struct btrfs_key key;
1f3c79a2 1430 int ret;
1f3c79a2 1431
5d4f98a2
YZ
1432 key.objectid = bytenr;
1433 if (parent) {
1434 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1435 key.offset = parent;
1436 } else {
1437 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1438 key.offset = root_objectid;
1f3c79a2
LH
1439 }
1440
5d4f98a2
YZ
1441 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1442 if (ret > 0)
1443 ret = -ENOENT;
1444#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1445 if (ret == -ENOENT && parent) {
b3b4aa74 1446 btrfs_release_path(path);
5d4f98a2
YZ
1447 key.type = BTRFS_EXTENT_REF_V0_KEY;
1448 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1449 if (ret > 0)
1450 ret = -ENOENT;
1451 }
1f3c79a2 1452#endif
5d4f98a2 1453 return ret;
1f3c79a2
LH
1454}
1455
5d4f98a2
YZ
1456static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
1457 struct btrfs_root *root,
1458 struct btrfs_path *path,
1459 u64 bytenr, u64 parent,
1460 u64 root_objectid)
31840ae1 1461{
5d4f98a2 1462 struct btrfs_key key;
31840ae1 1463 int ret;
31840ae1 1464
5d4f98a2
YZ
1465 key.objectid = bytenr;
1466 if (parent) {
1467 key.type = BTRFS_SHARED_BLOCK_REF_KEY;
1468 key.offset = parent;
1469 } else {
1470 key.type = BTRFS_TREE_BLOCK_REF_KEY;
1471 key.offset = root_objectid;
1472 }
1473
1474 ret = btrfs_insert_empty_item(trans, root, path, &key, 0);
b3b4aa74 1475 btrfs_release_path(path);
31840ae1
ZY
1476 return ret;
1477}
1478
5d4f98a2 1479static inline int extent_ref_type(u64 parent, u64 owner)
31840ae1 1480{
5d4f98a2
YZ
1481 int type;
1482 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1483 if (parent > 0)
1484 type = BTRFS_SHARED_BLOCK_REF_KEY;
1485 else
1486 type = BTRFS_TREE_BLOCK_REF_KEY;
1487 } else {
1488 if (parent > 0)
1489 type = BTRFS_SHARED_DATA_REF_KEY;
1490 else
1491 type = BTRFS_EXTENT_DATA_REF_KEY;
1492 }
1493 return type;
31840ae1 1494}
56bec294 1495
2c47e605
YZ
1496static int find_next_key(struct btrfs_path *path, int level,
1497 struct btrfs_key *key)
56bec294 1498
02217ed2 1499{
2c47e605 1500 for (; level < BTRFS_MAX_LEVEL; level++) {
5d4f98a2
YZ
1501 if (!path->nodes[level])
1502 break;
5d4f98a2
YZ
1503 if (path->slots[level] + 1 >=
1504 btrfs_header_nritems(path->nodes[level]))
1505 continue;
1506 if (level == 0)
1507 btrfs_item_key_to_cpu(path->nodes[level], key,
1508 path->slots[level] + 1);
1509 else
1510 btrfs_node_key_to_cpu(path->nodes[level], key,
1511 path->slots[level] + 1);
1512 return 0;
1513 }
1514 return 1;
1515}
037e6390 1516
5d4f98a2
YZ
1517/*
1518 * look for inline back ref. if back ref is found, *ref_ret is set
1519 * to the address of inline back ref, and 0 is returned.
1520 *
1521 * if back ref isn't found, *ref_ret is set to the address where it
1522 * should be inserted, and -ENOENT is returned.
1523 *
1524 * if insert is true and there are too many inline back refs, the path
1525 * points to the extent item, and -EAGAIN is returned.
1526 *
1527 * NOTE: inline back refs are ordered in the same way that back ref
1528 * items in the tree are ordered.
1529 */
1530static noinline_for_stack
1531int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
1532 struct btrfs_root *root,
1533 struct btrfs_path *path,
1534 struct btrfs_extent_inline_ref **ref_ret,
1535 u64 bytenr, u64 num_bytes,
1536 u64 parent, u64 root_objectid,
1537 u64 owner, u64 offset, int insert)
1538{
1539 struct btrfs_key key;
1540 struct extent_buffer *leaf;
1541 struct btrfs_extent_item *ei;
1542 struct btrfs_extent_inline_ref *iref;
1543 u64 flags;
1544 u64 item_size;
1545 unsigned long ptr;
1546 unsigned long end;
1547 int extra_size;
1548 int type;
1549 int want;
1550 int ret;
1551 int err = 0;
3173a18f
JB
1552 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
1553 SKINNY_METADATA);
26b8003f 1554
db94535d 1555 key.objectid = bytenr;
31840ae1 1556 key.type = BTRFS_EXTENT_ITEM_KEY;
56bec294 1557 key.offset = num_bytes;
31840ae1 1558
5d4f98a2
YZ
1559 want = extent_ref_type(parent, owner);
1560 if (insert) {
1561 extra_size = btrfs_extent_inline_ref_size(want);
85d4198e 1562 path->keep_locks = 1;
5d4f98a2
YZ
1563 } else
1564 extra_size = -1;
3173a18f
JB
1565
1566 /*
1567 * Owner is our parent level, so we can just add one to get the level
1568 * for the block we are interested in.
1569 */
1570 if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
1571 key.type = BTRFS_METADATA_ITEM_KEY;
1572 key.offset = owner;
1573 }
1574
1575again:
5d4f98a2 1576 ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
b9473439 1577 if (ret < 0) {
5d4f98a2
YZ
1578 err = ret;
1579 goto out;
1580 }
3173a18f
JB
1581
1582 /*
1583 * We may be a newly converted file system which still has the old fat
1584 * extent entries for metadata, so try and see if we have one of those.
1585 */
1586 if (ret > 0 && skinny_metadata) {
1587 skinny_metadata = false;
1588 if (path->slots[0]) {
1589 path->slots[0]--;
1590 btrfs_item_key_to_cpu(path->nodes[0], &key,
1591 path->slots[0]);
1592 if (key.objectid == bytenr &&
1593 key.type == BTRFS_EXTENT_ITEM_KEY &&
1594 key.offset == num_bytes)
1595 ret = 0;
1596 }
1597 if (ret) {
9ce49a0b 1598 key.objectid = bytenr;
3173a18f
JB
1599 key.type = BTRFS_EXTENT_ITEM_KEY;
1600 key.offset = num_bytes;
1601 btrfs_release_path(path);
1602 goto again;
1603 }
1604 }
1605
79787eaa
JM
1606 if (ret && !insert) {
1607 err = -ENOENT;
1608 goto out;
fae7f21c 1609 } else if (WARN_ON(ret)) {
492104c8 1610 err = -EIO;
492104c8 1611 goto out;
79787eaa 1612 }
5d4f98a2
YZ
1613
1614 leaf = path->nodes[0];
1615 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1616#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
1617 if (item_size < sizeof(*ei)) {
1618 if (!insert) {
1619 err = -ENOENT;
1620 goto out;
1621 }
1622 ret = convert_extent_item_v0(trans, root, path, owner,
1623 extra_size);
1624 if (ret < 0) {
1625 err = ret;
1626 goto out;
1627 }
1628 leaf = path->nodes[0];
1629 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1630 }
1631#endif
1632 BUG_ON(item_size < sizeof(*ei));
1633
5d4f98a2
YZ
1634 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1635 flags = btrfs_extent_flags(leaf, ei);
1636
1637 ptr = (unsigned long)(ei + 1);
1638 end = (unsigned long)ei + item_size;
1639
3173a18f 1640 if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
5d4f98a2
YZ
1641 ptr += sizeof(struct btrfs_tree_block_info);
1642 BUG_ON(ptr > end);
5d4f98a2
YZ
1643 }
1644
1645 err = -ENOENT;
1646 while (1) {
1647 if (ptr >= end) {
1648 WARN_ON(ptr > end);
1649 break;
1650 }
1651 iref = (struct btrfs_extent_inline_ref *)ptr;
1652 type = btrfs_extent_inline_ref_type(leaf, iref);
1653 if (want < type)
1654 break;
1655 if (want > type) {
1656 ptr += btrfs_extent_inline_ref_size(type);
1657 continue;
1658 }
1659
1660 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1661 struct btrfs_extent_data_ref *dref;
1662 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1663 if (match_extent_data_ref(leaf, dref, root_objectid,
1664 owner, offset)) {
1665 err = 0;
1666 break;
1667 }
1668 if (hash_extent_data_ref_item(leaf, dref) <
1669 hash_extent_data_ref(root_objectid, owner, offset))
1670 break;
1671 } else {
1672 u64 ref_offset;
1673 ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
1674 if (parent > 0) {
1675 if (parent == ref_offset) {
1676 err = 0;
1677 break;
1678 }
1679 if (ref_offset < parent)
1680 break;
1681 } else {
1682 if (root_objectid == ref_offset) {
1683 err = 0;
1684 break;
1685 }
1686 if (ref_offset < root_objectid)
1687 break;
1688 }
1689 }
1690 ptr += btrfs_extent_inline_ref_size(type);
1691 }
1692 if (err == -ENOENT && insert) {
1693 if (item_size + extra_size >=
1694 BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
1695 err = -EAGAIN;
1696 goto out;
1697 }
1698 /*
1699 * To add new inline back ref, we have to make sure
1700 * there is no corresponding back ref item.
1701 * For simplicity, we just do not add new inline back
1702 * ref if there is any kind of item for this block
1703 */
2c47e605
YZ
1704 if (find_next_key(path, 0, &key) == 0 &&
1705 key.objectid == bytenr &&
85d4198e 1706 key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
5d4f98a2
YZ
1707 err = -EAGAIN;
1708 goto out;
1709 }
1710 }
1711 *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
1712out:
85d4198e 1713 if (insert) {
5d4f98a2
YZ
1714 path->keep_locks = 0;
1715 btrfs_unlock_up_safe(path, 1);
1716 }
1717 return err;
1718}
1719
1720/*
1721 * helper to add new inline back ref
1722 */
1723static noinline_for_stack
fd279fae 1724void setup_inline_extent_backref(struct btrfs_root *root,
143bede5
JM
1725 struct btrfs_path *path,
1726 struct btrfs_extent_inline_ref *iref,
1727 u64 parent, u64 root_objectid,
1728 u64 owner, u64 offset, int refs_to_add,
1729 struct btrfs_delayed_extent_op *extent_op)
5d4f98a2
YZ
1730{
1731 struct extent_buffer *leaf;
1732 struct btrfs_extent_item *ei;
1733 unsigned long ptr;
1734 unsigned long end;
1735 unsigned long item_offset;
1736 u64 refs;
1737 int size;
1738 int type;
5d4f98a2
YZ
1739
1740 leaf = path->nodes[0];
1741 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1742 item_offset = (unsigned long)iref - (unsigned long)ei;
1743
1744 type = extent_ref_type(parent, owner);
1745 size = btrfs_extent_inline_ref_size(type);
1746
4b90c680 1747 btrfs_extend_item(root, path, size);
5d4f98a2
YZ
1748
1749 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1750 refs = btrfs_extent_refs(leaf, ei);
1751 refs += refs_to_add;
1752 btrfs_set_extent_refs(leaf, ei, refs);
1753 if (extent_op)
1754 __run_delayed_extent_op(extent_op, leaf, ei);
1755
1756 ptr = (unsigned long)ei + item_offset;
1757 end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
1758 if (ptr < end - size)
1759 memmove_extent_buffer(leaf, ptr + size, ptr,
1760 end - size - ptr);
1761
1762 iref = (struct btrfs_extent_inline_ref *)ptr;
1763 btrfs_set_extent_inline_ref_type(leaf, iref, type);
1764 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1765 struct btrfs_extent_data_ref *dref;
1766 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1767 btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
1768 btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
1769 btrfs_set_extent_data_ref_offset(leaf, dref, offset);
1770 btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
1771 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1772 struct btrfs_shared_data_ref *sref;
1773 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1774 btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
1775 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1776 } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
1777 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
1778 } else {
1779 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
1780 }
1781 btrfs_mark_buffer_dirty(leaf);
5d4f98a2
YZ
1782}
1783
1784static int lookup_extent_backref(struct btrfs_trans_handle *trans,
1785 struct btrfs_root *root,
1786 struct btrfs_path *path,
1787 struct btrfs_extent_inline_ref **ref_ret,
1788 u64 bytenr, u64 num_bytes, u64 parent,
1789 u64 root_objectid, u64 owner, u64 offset)
1790{
1791 int ret;
1792
1793 ret = lookup_inline_extent_backref(trans, root, path, ref_ret,
1794 bytenr, num_bytes, parent,
1795 root_objectid, owner, offset, 0);
1796 if (ret != -ENOENT)
54aa1f4d 1797 return ret;
5d4f98a2 1798
b3b4aa74 1799 btrfs_release_path(path);
5d4f98a2
YZ
1800 *ref_ret = NULL;
1801
1802 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1803 ret = lookup_tree_block_ref(trans, root, path, bytenr, parent,
1804 root_objectid);
1805 } else {
1806 ret = lookup_extent_data_ref(trans, root, path, bytenr, parent,
1807 root_objectid, owner, offset);
b9473439 1808 }
5d4f98a2
YZ
1809 return ret;
1810}
31840ae1 1811
5d4f98a2
YZ
1812/*
1813 * helper to update/remove inline back ref
1814 */
1815static noinline_for_stack
afe5fea7 1816void update_inline_extent_backref(struct btrfs_root *root,
143bede5
JM
1817 struct btrfs_path *path,
1818 struct btrfs_extent_inline_ref *iref,
1819 int refs_to_mod,
fcebe456
JB
1820 struct btrfs_delayed_extent_op *extent_op,
1821 int *last_ref)
5d4f98a2
YZ
1822{
1823 struct extent_buffer *leaf;
1824 struct btrfs_extent_item *ei;
1825 struct btrfs_extent_data_ref *dref = NULL;
1826 struct btrfs_shared_data_ref *sref = NULL;
1827 unsigned long ptr;
1828 unsigned long end;
1829 u32 item_size;
1830 int size;
1831 int type;
5d4f98a2
YZ
1832 u64 refs;
1833
1834 leaf = path->nodes[0];
1835 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
1836 refs = btrfs_extent_refs(leaf, ei);
1837 WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
1838 refs += refs_to_mod;
1839 btrfs_set_extent_refs(leaf, ei, refs);
1840 if (extent_op)
1841 __run_delayed_extent_op(extent_op, leaf, ei);
1842
1843 type = btrfs_extent_inline_ref_type(leaf, iref);
1844
1845 if (type == BTRFS_EXTENT_DATA_REF_KEY) {
1846 dref = (struct btrfs_extent_data_ref *)(&iref->offset);
1847 refs = btrfs_extent_data_ref_count(leaf, dref);
1848 } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
1849 sref = (struct btrfs_shared_data_ref *)(iref + 1);
1850 refs = btrfs_shared_data_ref_count(leaf, sref);
1851 } else {
1852 refs = 1;
1853 BUG_ON(refs_to_mod != -1);
56bec294 1854 }
31840ae1 1855
5d4f98a2
YZ
1856 BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
1857 refs += refs_to_mod;
1858
1859 if (refs > 0) {
1860 if (type == BTRFS_EXTENT_DATA_REF_KEY)
1861 btrfs_set_extent_data_ref_count(leaf, dref, refs);
1862 else
1863 btrfs_set_shared_data_ref_count(leaf, sref, refs);
1864 } else {
fcebe456 1865 *last_ref = 1;
5d4f98a2
YZ
1866 size = btrfs_extent_inline_ref_size(type);
1867 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
1868 ptr = (unsigned long)iref;
1869 end = (unsigned long)ei + item_size;
1870 if (ptr + size < end)
1871 memmove_extent_buffer(leaf, ptr, ptr + size,
1872 end - ptr - size);
1873 item_size -= size;
afe5fea7 1874 btrfs_truncate_item(root, path, item_size, 1);
5d4f98a2
YZ
1875 }
1876 btrfs_mark_buffer_dirty(leaf);
5d4f98a2
YZ
1877}
1878
1879static noinline_for_stack
1880int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
1881 struct btrfs_root *root,
1882 struct btrfs_path *path,
1883 u64 bytenr, u64 num_bytes, u64 parent,
1884 u64 root_objectid, u64 owner,
1885 u64 offset, int refs_to_add,
1886 struct btrfs_delayed_extent_op *extent_op)
1887{
1888 struct btrfs_extent_inline_ref *iref;
1889 int ret;
1890
1891 ret = lookup_inline_extent_backref(trans, root, path, &iref,
1892 bytenr, num_bytes, parent,
1893 root_objectid, owner, offset, 1);
1894 if (ret == 0) {
1895 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
afe5fea7 1896 update_inline_extent_backref(root, path, iref,
fcebe456 1897 refs_to_add, extent_op, NULL);
5d4f98a2 1898 } else if (ret == -ENOENT) {
fd279fae 1899 setup_inline_extent_backref(root, path, iref, parent,
143bede5
JM
1900 root_objectid, owner, offset,
1901 refs_to_add, extent_op);
1902 ret = 0;
771ed689 1903 }
5d4f98a2
YZ
1904 return ret;
1905}
31840ae1 1906
5d4f98a2
YZ
1907static int insert_extent_backref(struct btrfs_trans_handle *trans,
1908 struct btrfs_root *root,
1909 struct btrfs_path *path,
1910 u64 bytenr, u64 parent, u64 root_objectid,
1911 u64 owner, u64 offset, int refs_to_add)
1912{
1913 int ret;
1914 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
1915 BUG_ON(refs_to_add != 1);
1916 ret = insert_tree_block_ref(trans, root, path, bytenr,
1917 parent, root_objectid);
1918 } else {
1919 ret = insert_extent_data_ref(trans, root, path, bytenr,
1920 parent, root_objectid,
1921 owner, offset, refs_to_add);
1922 }
1923 return ret;
1924}
56bec294 1925
5d4f98a2
YZ
1926static int remove_extent_backref(struct btrfs_trans_handle *trans,
1927 struct btrfs_root *root,
1928 struct btrfs_path *path,
1929 struct btrfs_extent_inline_ref *iref,
fcebe456 1930 int refs_to_drop, int is_data, int *last_ref)
5d4f98a2 1931{
143bede5 1932 int ret = 0;
b9473439 1933
5d4f98a2
YZ
1934 BUG_ON(!is_data && refs_to_drop != 1);
1935 if (iref) {
afe5fea7 1936 update_inline_extent_backref(root, path, iref,
fcebe456 1937 -refs_to_drop, NULL, last_ref);
5d4f98a2 1938 } else if (is_data) {
fcebe456
JB
1939 ret = remove_extent_data_ref(trans, root, path, refs_to_drop,
1940 last_ref);
5d4f98a2 1941 } else {
fcebe456 1942 *last_ref = 1;
5d4f98a2
YZ
1943 ret = btrfs_del_item(trans, root, path);
1944 }
1945 return ret;
1946}
1947
86557861 1948#define in_range(b, first, len) ((b) >= (first) && (b) < (first) + (len))
d04c6b88
JM
1949static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
1950 u64 *discarded_bytes)
5d4f98a2 1951{
86557861
JM
1952 int j, ret = 0;
1953 u64 bytes_left, end;
4d89d377 1954 u64 aligned_start = ALIGN(start, 1 << 9);
d04c6b88 1955
4d89d377
JM
1956 if (WARN_ON(start != aligned_start)) {
1957 len -= aligned_start - start;
1958 len = round_down(len, 1 << 9);
1959 start = aligned_start;
1960 }
d04c6b88 1961
4d89d377 1962 *discarded_bytes = 0;
86557861
JM
1963
1964 if (!len)
1965 return 0;
1966
1967 end = start + len;
1968 bytes_left = len;
1969
1970 /* Skip any superblocks on this device. */
1971 for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
1972 u64 sb_start = btrfs_sb_offset(j);
1973 u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
1974 u64 size = sb_start - start;
1975
1976 if (!in_range(sb_start, start, bytes_left) &&
1977 !in_range(sb_end, start, bytes_left) &&
1978 !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
1979 continue;
1980
1981 /*
1982 * Superblock spans beginning of range. Adjust start and
1983 * try again.
1984 */
1985 if (sb_start <= start) {
1986 start += sb_end - start;
1987 if (start > end) {
1988 bytes_left = 0;
1989 break;
1990 }
1991 bytes_left = end - start;
1992 continue;
1993 }
1994
1995 if (size) {
1996 ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
1997 GFP_NOFS, 0);
1998 if (!ret)
1999 *discarded_bytes += size;
2000 else if (ret != -EOPNOTSUPP)
2001 return ret;
2002 }
2003
2004 start = sb_end;
2005 if (start > end) {
2006 bytes_left = 0;
2007 break;
2008 }
2009 bytes_left = end - start;
2010 }
2011
2012 if (bytes_left) {
2013 ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
4d89d377
JM
2014 GFP_NOFS, 0);
2015 if (!ret)
86557861 2016 *discarded_bytes += bytes_left;
4d89d377 2017 }
d04c6b88 2018 return ret;
5d4f98a2 2019}
5d4f98a2 2020
1edb647b
FM
2021int btrfs_discard_extent(struct btrfs_root *root, u64 bytenr,
2022 u64 num_bytes, u64 *actual_bytes)
5d4f98a2 2023{
5d4f98a2 2024 int ret;
5378e607 2025 u64 discarded_bytes = 0;
a1d3c478 2026 struct btrfs_bio *bbio = NULL;
5d4f98a2 2027
e244a0ae 2028
5d4f98a2 2029 /* Tell the block device(s) that the sectors can be discarded */
3ec706c8 2030 ret = btrfs_map_block(root->fs_info, REQ_DISCARD,
a1d3c478 2031 bytenr, &num_bytes, &bbio, 0);
79787eaa 2032 /* Error condition is -ENOMEM */
5d4f98a2 2033 if (!ret) {
a1d3c478 2034 struct btrfs_bio_stripe *stripe = bbio->stripes;
5d4f98a2
YZ
2035 int i;
2036
5d4f98a2 2037
a1d3c478 2038 for (i = 0; i < bbio->num_stripes; i++, stripe++) {
d04c6b88 2039 u64 bytes;
d5e2003c
JB
2040 if (!stripe->dev->can_discard)
2041 continue;
2042
5378e607
LD
2043 ret = btrfs_issue_discard(stripe->dev->bdev,
2044 stripe->physical,
d04c6b88
JM
2045 stripe->length,
2046 &bytes);
5378e607 2047 if (!ret)
d04c6b88 2048 discarded_bytes += bytes;
5378e607 2049 else if (ret != -EOPNOTSUPP)
79787eaa 2050 break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
d5e2003c
JB
2051
2052 /*
2053 * Just in case we get back EOPNOTSUPP for some reason,
2054 * just ignore the return value so we don't screw up
2055 * people calling discard_extent.
2056 */
2057 ret = 0;
5d4f98a2 2058 }
6e9606d2 2059 btrfs_put_bbio(bbio);
5d4f98a2 2060 }
5378e607
LD
2061
2062 if (actual_bytes)
2063 *actual_bytes = discarded_bytes;
2064
5d4f98a2 2065
53b381b3
DW
2066 if (ret == -EOPNOTSUPP)
2067 ret = 0;
5d4f98a2 2068 return ret;
5d4f98a2
YZ
2069}
2070
79787eaa 2071/* Can return -ENOMEM */
5d4f98a2
YZ
2072int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2073 struct btrfs_root *root,
2074 u64 bytenr, u64 num_bytes, u64 parent,
b06c4bf5 2075 u64 root_objectid, u64 owner, u64 offset)
5d4f98a2
YZ
2076{
2077 int ret;
66d7e7f0
AJ
2078 struct btrfs_fs_info *fs_info = root->fs_info;
2079
5d4f98a2
YZ
2080 BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
2081 root_objectid == BTRFS_TREE_LOG_OBJECTID);
2082
2083 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
66d7e7f0
AJ
2084 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
2085 num_bytes,
5d4f98a2 2086 parent, root_objectid, (int)owner,
b06c4bf5 2087 BTRFS_ADD_DELAYED_REF, NULL);
5d4f98a2 2088 } else {
66d7e7f0 2089 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
5846a3c2
QW
2090 num_bytes, parent, root_objectid,
2091 owner, offset, 0,
b06c4bf5 2092 BTRFS_ADD_DELAYED_REF, NULL);
5d4f98a2
YZ
2093 }
2094 return ret;
2095}
2096
2097static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
2098 struct btrfs_root *root,
c682f9b3 2099 struct btrfs_delayed_ref_node *node,
5d4f98a2
YZ
2100 u64 parent, u64 root_objectid,
2101 u64 owner, u64 offset, int refs_to_add,
2102 struct btrfs_delayed_extent_op *extent_op)
2103{
fcebe456 2104 struct btrfs_fs_info *fs_info = root->fs_info;
5d4f98a2
YZ
2105 struct btrfs_path *path;
2106 struct extent_buffer *leaf;
2107 struct btrfs_extent_item *item;
fcebe456 2108 struct btrfs_key key;
c682f9b3
QW
2109 u64 bytenr = node->bytenr;
2110 u64 num_bytes = node->num_bytes;
5d4f98a2
YZ
2111 u64 refs;
2112 int ret;
5d4f98a2
YZ
2113
2114 path = btrfs_alloc_path();
2115 if (!path)
2116 return -ENOMEM;
2117
2118 path->reada = 1;
2119 path->leave_spinning = 1;
2120 /* this will setup the path even if it fails to insert the back ref */
fcebe456
JB
2121 ret = insert_inline_extent_backref(trans, fs_info->extent_root, path,
2122 bytenr, num_bytes, parent,
5d4f98a2
YZ
2123 root_objectid, owner, offset,
2124 refs_to_add, extent_op);
0ed4792a 2125 if ((ret < 0 && ret != -EAGAIN) || !ret)
5d4f98a2 2126 goto out;
fcebe456
JB
2127
2128 /*
2129 * Ok we had -EAGAIN which means we didn't have space to insert and
2130 * inline extent ref, so just update the reference count and add a
2131 * normal backref.
2132 */
5d4f98a2 2133 leaf = path->nodes[0];
fcebe456 2134 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
5d4f98a2
YZ
2135 item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2136 refs = btrfs_extent_refs(leaf, item);
2137 btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
2138 if (extent_op)
2139 __run_delayed_extent_op(extent_op, leaf, item);
56bec294 2140
5d4f98a2 2141 btrfs_mark_buffer_dirty(leaf);
b3b4aa74 2142 btrfs_release_path(path);
56bec294
CM
2143
2144 path->reada = 1;
b9473439 2145 path->leave_spinning = 1;
56bec294
CM
2146 /* now insert the actual backref */
2147 ret = insert_extent_backref(trans, root->fs_info->extent_root,
5d4f98a2
YZ
2148 path, bytenr, parent, root_objectid,
2149 owner, offset, refs_to_add);
79787eaa
JM
2150 if (ret)
2151 btrfs_abort_transaction(trans, root, ret);
5d4f98a2 2152out:
56bec294 2153 btrfs_free_path(path);
30d133fc 2154 return ret;
56bec294
CM
2155}
2156
5d4f98a2
YZ
2157static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
2158 struct btrfs_root *root,
2159 struct btrfs_delayed_ref_node *node,
2160 struct btrfs_delayed_extent_op *extent_op,
2161 int insert_reserved)
56bec294 2162{
5d4f98a2
YZ
2163 int ret = 0;
2164 struct btrfs_delayed_data_ref *ref;
2165 struct btrfs_key ins;
2166 u64 parent = 0;
2167 u64 ref_root = 0;
2168 u64 flags = 0;
2169
2170 ins.objectid = node->bytenr;
2171 ins.offset = node->num_bytes;
2172 ins.type = BTRFS_EXTENT_ITEM_KEY;
2173
2174 ref = btrfs_delayed_node_to_data_ref(node);
599c75ec
LB
2175 trace_run_delayed_data_ref(node, ref, node->action);
2176
5d4f98a2
YZ
2177 if (node->type == BTRFS_SHARED_DATA_REF_KEY)
2178 parent = ref->parent;
fcebe456 2179 ref_root = ref->root;
5d4f98a2
YZ
2180
2181 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
3173a18f 2182 if (extent_op)
5d4f98a2 2183 flags |= extent_op->flags_to_set;
5d4f98a2
YZ
2184 ret = alloc_reserved_file_extent(trans, root,
2185 parent, ref_root, flags,
2186 ref->objectid, ref->offset,
2187 &ins, node->ref_mod);
5d4f98a2 2188 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
c682f9b3 2189 ret = __btrfs_inc_extent_ref(trans, root, node, parent,
5d4f98a2
YZ
2190 ref_root, ref->objectid,
2191 ref->offset, node->ref_mod,
c682f9b3 2192 extent_op);
5d4f98a2 2193 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
c682f9b3 2194 ret = __btrfs_free_extent(trans, root, node, parent,
5d4f98a2
YZ
2195 ref_root, ref->objectid,
2196 ref->offset, node->ref_mod,
c682f9b3 2197 extent_op);
5d4f98a2
YZ
2198 } else {
2199 BUG();
2200 }
2201 return ret;
2202}
2203
2204static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
2205 struct extent_buffer *leaf,
2206 struct btrfs_extent_item *ei)
2207{
2208 u64 flags = btrfs_extent_flags(leaf, ei);
2209 if (extent_op->update_flags) {
2210 flags |= extent_op->flags_to_set;
2211 btrfs_set_extent_flags(leaf, ei, flags);
2212 }
2213
2214 if (extent_op->update_key) {
2215 struct btrfs_tree_block_info *bi;
2216 BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
2217 bi = (struct btrfs_tree_block_info *)(ei + 1);
2218 btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
2219 }
2220}
2221
2222static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
2223 struct btrfs_root *root,
2224 struct btrfs_delayed_ref_node *node,
2225 struct btrfs_delayed_extent_op *extent_op)
2226{
2227 struct btrfs_key key;
2228 struct btrfs_path *path;
2229 struct btrfs_extent_item *ei;
2230 struct extent_buffer *leaf;
2231 u32 item_size;
56bec294 2232 int ret;
5d4f98a2 2233 int err = 0;
b1c79e09 2234 int metadata = !extent_op->is_data;
5d4f98a2 2235
79787eaa
JM
2236 if (trans->aborted)
2237 return 0;
2238
3173a18f
JB
2239 if (metadata && !btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
2240 metadata = 0;
2241
5d4f98a2
YZ
2242 path = btrfs_alloc_path();
2243 if (!path)
2244 return -ENOMEM;
2245
2246 key.objectid = node->bytenr;
5d4f98a2 2247
3173a18f 2248 if (metadata) {
3173a18f 2249 key.type = BTRFS_METADATA_ITEM_KEY;
b1c79e09 2250 key.offset = extent_op->level;
3173a18f
JB
2251 } else {
2252 key.type = BTRFS_EXTENT_ITEM_KEY;
2253 key.offset = node->num_bytes;
2254 }
2255
2256again:
5d4f98a2
YZ
2257 path->reada = 1;
2258 path->leave_spinning = 1;
2259 ret = btrfs_search_slot(trans, root->fs_info->extent_root, &key,
2260 path, 0, 1);
2261 if (ret < 0) {
2262 err = ret;
2263 goto out;
2264 }
2265 if (ret > 0) {
3173a18f 2266 if (metadata) {
55994887
FDBM
2267 if (path->slots[0] > 0) {
2268 path->slots[0]--;
2269 btrfs_item_key_to_cpu(path->nodes[0], &key,
2270 path->slots[0]);
2271 if (key.objectid == node->bytenr &&
2272 key.type == BTRFS_EXTENT_ITEM_KEY &&
2273 key.offset == node->num_bytes)
2274 ret = 0;
2275 }
2276 if (ret > 0) {
2277 btrfs_release_path(path);
2278 metadata = 0;
3173a18f 2279
55994887
FDBM
2280 key.objectid = node->bytenr;
2281 key.offset = node->num_bytes;
2282 key.type = BTRFS_EXTENT_ITEM_KEY;
2283 goto again;
2284 }
2285 } else {
2286 err = -EIO;
2287 goto out;
3173a18f 2288 }
5d4f98a2
YZ
2289 }
2290
2291 leaf = path->nodes[0];
2292 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2293#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
2294 if (item_size < sizeof(*ei)) {
2295 ret = convert_extent_item_v0(trans, root->fs_info->extent_root,
2296 path, (u64)-1, 0);
2297 if (ret < 0) {
2298 err = ret;
2299 goto out;
2300 }
2301 leaf = path->nodes[0];
2302 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
2303 }
2304#endif
2305 BUG_ON(item_size < sizeof(*ei));
2306 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
2307 __run_delayed_extent_op(extent_op, leaf, ei);
56bec294 2308
5d4f98a2
YZ
2309 btrfs_mark_buffer_dirty(leaf);
2310out:
2311 btrfs_free_path(path);
2312 return err;
56bec294
CM
2313}
2314
5d4f98a2
YZ
2315static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
2316 struct btrfs_root *root,
2317 struct btrfs_delayed_ref_node *node,
2318 struct btrfs_delayed_extent_op *extent_op,
2319 int insert_reserved)
56bec294
CM
2320{
2321 int ret = 0;
5d4f98a2
YZ
2322 struct btrfs_delayed_tree_ref *ref;
2323 struct btrfs_key ins;
2324 u64 parent = 0;
2325 u64 ref_root = 0;
3173a18f
JB
2326 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
2327 SKINNY_METADATA);
56bec294 2328
5d4f98a2 2329 ref = btrfs_delayed_node_to_tree_ref(node);
599c75ec
LB
2330 trace_run_delayed_tree_ref(node, ref, node->action);
2331
5d4f98a2
YZ
2332 if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2333 parent = ref->parent;
fcebe456 2334 ref_root = ref->root;
5d4f98a2 2335
3173a18f
JB
2336 ins.objectid = node->bytenr;
2337 if (skinny_metadata) {
2338 ins.offset = ref->level;
2339 ins.type = BTRFS_METADATA_ITEM_KEY;
2340 } else {
2341 ins.offset = node->num_bytes;
2342 ins.type = BTRFS_EXTENT_ITEM_KEY;
2343 }
2344
5d4f98a2
YZ
2345 BUG_ON(node->ref_mod != 1);
2346 if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
3173a18f 2347 BUG_ON(!extent_op || !extent_op->update_flags);
5d4f98a2
YZ
2348 ret = alloc_reserved_tree_block(trans, root,
2349 parent, ref_root,
2350 extent_op->flags_to_set,
2351 &extent_op->key,
b06c4bf5 2352 ref->level, &ins);
5d4f98a2 2353 } else if (node->action == BTRFS_ADD_DELAYED_REF) {
c682f9b3
QW
2354 ret = __btrfs_inc_extent_ref(trans, root, node,
2355 parent, ref_root,
2356 ref->level, 0, 1,
fcebe456 2357 extent_op);
5d4f98a2 2358 } else if (node->action == BTRFS_DROP_DELAYED_REF) {
c682f9b3
QW
2359 ret = __btrfs_free_extent(trans, root, node,
2360 parent, ref_root,
2361 ref->level, 0, 1, extent_op);
5d4f98a2
YZ
2362 } else {
2363 BUG();
2364 }
56bec294
CM
2365 return ret;
2366}
2367
2368/* helper function to actually process a single delayed ref entry */
5d4f98a2
YZ
2369static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
2370 struct btrfs_root *root,
2371 struct btrfs_delayed_ref_node *node,
2372 struct btrfs_delayed_extent_op *extent_op,
2373 int insert_reserved)
56bec294 2374{
79787eaa
JM
2375 int ret = 0;
2376
857cc2fc
JB
2377 if (trans->aborted) {
2378 if (insert_reserved)
2379 btrfs_pin_extent(root, node->bytenr,
2380 node->num_bytes, 1);
79787eaa 2381 return 0;
857cc2fc 2382 }
79787eaa 2383
5d4f98a2 2384 if (btrfs_delayed_ref_is_head(node)) {
56bec294
CM
2385 struct btrfs_delayed_ref_head *head;
2386 /*
2387 * we've hit the end of the chain and we were supposed
2388 * to insert this extent into the tree. But, it got
2389 * deleted before we ever needed to insert it, so all
2390 * we have to do is clean up the accounting
2391 */
5d4f98a2
YZ
2392 BUG_ON(extent_op);
2393 head = btrfs_delayed_node_to_head(node);
599c75ec
LB
2394 trace_run_delayed_ref_head(node, head, node->action);
2395
56bec294 2396 if (insert_reserved) {
f0486c68
YZ
2397 btrfs_pin_extent(root, node->bytenr,
2398 node->num_bytes, 1);
5d4f98a2
YZ
2399 if (head->is_data) {
2400 ret = btrfs_del_csums(trans, root,
2401 node->bytenr,
2402 node->num_bytes);
5d4f98a2 2403 }
56bec294 2404 }
297d750b
QW
2405
2406 /* Also free its reserved qgroup space */
2407 btrfs_qgroup_free_delayed_ref(root->fs_info,
2408 head->qgroup_ref_root,
2409 head->qgroup_reserved);
79787eaa 2410 return ret;
56bec294
CM
2411 }
2412
5d4f98a2
YZ
2413 if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
2414 node->type == BTRFS_SHARED_BLOCK_REF_KEY)
2415 ret = run_delayed_tree_ref(trans, root, node, extent_op,
2416 insert_reserved);
2417 else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
2418 node->type == BTRFS_SHARED_DATA_REF_KEY)
2419 ret = run_delayed_data_ref(trans, root, node, extent_op,
2420 insert_reserved);
2421 else
2422 BUG();
2423 return ret;
56bec294
CM
2424}
2425
c6fc2454 2426static inline struct btrfs_delayed_ref_node *
56bec294
CM
2427select_delayed_ref(struct btrfs_delayed_ref_head *head)
2428{
cffc3374
FM
2429 struct btrfs_delayed_ref_node *ref;
2430
c6fc2454
QW
2431 if (list_empty(&head->ref_list))
2432 return NULL;
d7df2c79 2433
cffc3374
FM
2434 /*
2435 * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
2436 * This is to prevent a ref count from going down to zero, which deletes
2437 * the extent item from the extent tree, when there still are references
2438 * to add, which would fail because they would not find the extent item.
2439 */
2440 list_for_each_entry(ref, &head->ref_list, list) {
2441 if (ref->action == BTRFS_ADD_DELAYED_REF)
2442 return ref;
2443 }
2444
c6fc2454
QW
2445 return list_entry(head->ref_list.next, struct btrfs_delayed_ref_node,
2446 list);
56bec294
CM
2447}
2448
79787eaa
JM
2449/*
2450 * Returns 0 on success or if called with an already aborted transaction.
2451 * Returns -ENOMEM or -EIO on failure and will abort the transaction.
2452 */
d7df2c79
JB
2453static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2454 struct btrfs_root *root,
2455 unsigned long nr)
56bec294 2456{
56bec294
CM
2457 struct btrfs_delayed_ref_root *delayed_refs;
2458 struct btrfs_delayed_ref_node *ref;
2459 struct btrfs_delayed_ref_head *locked_ref = NULL;
5d4f98a2 2460 struct btrfs_delayed_extent_op *extent_op;
097b8a7c 2461 struct btrfs_fs_info *fs_info = root->fs_info;
0a2b2a84 2462 ktime_t start = ktime_get();
56bec294 2463 int ret;
d7df2c79 2464 unsigned long count = 0;
0a2b2a84 2465 unsigned long actual_count = 0;
56bec294 2466 int must_insert_reserved = 0;
56bec294
CM
2467
2468 delayed_refs = &trans->transaction->delayed_refs;
56bec294
CM
2469 while (1) {
2470 if (!locked_ref) {
d7df2c79 2471 if (count >= nr)
56bec294 2472 break;
56bec294 2473
d7df2c79
JB
2474 spin_lock(&delayed_refs->lock);
2475 locked_ref = btrfs_select_ref_head(trans);
2476 if (!locked_ref) {
2477 spin_unlock(&delayed_refs->lock);
2478 break;
2479 }
c3e69d58
CM
2480
2481 /* grab the lock that says we are going to process
2482 * all the refs for this head */
2483 ret = btrfs_delayed_ref_lock(trans, locked_ref);
d7df2c79 2484 spin_unlock(&delayed_refs->lock);
c3e69d58
CM
2485 /*
2486 * we may have dropped the spin lock to get the head
2487 * mutex lock, and that might have given someone else
2488 * time to free the head. If that's true, it has been
2489 * removed from our list and we can move on.
2490 */
2491 if (ret == -EAGAIN) {
2492 locked_ref = NULL;
2493 count++;
2494 continue;
56bec294
CM
2495 }
2496 }
a28ec197 2497
2c3cf7d5
FM
2498 /*
2499 * We need to try and merge add/drops of the same ref since we
2500 * can run into issues with relocate dropping the implicit ref
2501 * and then it being added back again before the drop can
2502 * finish. If we merged anything we need to re-loop so we can
2503 * get a good ref.
2504 * Or we can get node references of the same type that weren't
2505 * merged when created due to bumps in the tree mod seq, and
2506 * we need to merge them to prevent adding an inline extent
2507 * backref before dropping it (triggering a BUG_ON at
2508 * insert_inline_extent_backref()).
2509 */
d7df2c79 2510 spin_lock(&locked_ref->lock);
2c3cf7d5
FM
2511 btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
2512 locked_ref);
ae1e206b 2513
d1270cd9
AJ
2514 /*
2515 * locked_ref is the head node, so we have to go one
2516 * node back for any delayed ref updates
2517 */
2518 ref = select_delayed_ref(locked_ref);
2519
2520 if (ref && ref->seq &&
097b8a7c 2521 btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
d7df2c79 2522 spin_unlock(&locked_ref->lock);
093486c4 2523 btrfs_delayed_ref_unlock(locked_ref);
d7df2c79
JB
2524 spin_lock(&delayed_refs->lock);
2525 locked_ref->processing = 0;
d1270cd9
AJ
2526 delayed_refs->num_heads_ready++;
2527 spin_unlock(&delayed_refs->lock);
d7df2c79 2528 locked_ref = NULL;
d1270cd9 2529 cond_resched();
27a377db 2530 count++;
d1270cd9
AJ
2531 continue;
2532 }
2533
56bec294
CM
2534 /*
2535 * record the must insert reserved flag before we
2536 * drop the spin lock.
2537 */
2538 must_insert_reserved = locked_ref->must_insert_reserved;
2539 locked_ref->must_insert_reserved = 0;
7bb86316 2540
5d4f98a2
YZ
2541 extent_op = locked_ref->extent_op;
2542 locked_ref->extent_op = NULL;
2543
56bec294 2544 if (!ref) {
d7df2c79
JB
2545
2546
56bec294
CM
2547 /* All delayed refs have been processed, Go ahead
2548 * and send the head node to run_one_delayed_ref,
2549 * so that any accounting fixes can happen
2550 */
2551 ref = &locked_ref->node;
5d4f98a2
YZ
2552
2553 if (extent_op && must_insert_reserved) {
78a6184a 2554 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2
YZ
2555 extent_op = NULL;
2556 }
2557
2558 if (extent_op) {
d7df2c79 2559 spin_unlock(&locked_ref->lock);
5d4f98a2
YZ
2560 ret = run_delayed_extent_op(trans, root,
2561 ref, extent_op);
78a6184a 2562 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2 2563
79787eaa 2564 if (ret) {
857cc2fc
JB
2565 /*
2566 * Need to reset must_insert_reserved if
2567 * there was an error so the abort stuff
2568 * can cleanup the reserved space
2569 * properly.
2570 */
2571 if (must_insert_reserved)
2572 locked_ref->must_insert_reserved = 1;
d7df2c79 2573 locked_ref->processing = 0;
c2cf52eb 2574 btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
093486c4 2575 btrfs_delayed_ref_unlock(locked_ref);
79787eaa
JM
2576 return ret;
2577 }
d7df2c79 2578 continue;
5d4f98a2 2579 }
02217ed2 2580
d7df2c79
JB
2581 /*
2582 * Need to drop our head ref lock and re-aqcuire the
2583 * delayed ref lock and then re-check to make sure
2584 * nobody got added.
2585 */
2586 spin_unlock(&locked_ref->lock);
2587 spin_lock(&delayed_refs->lock);
2588 spin_lock(&locked_ref->lock);
c6fc2454 2589 if (!list_empty(&locked_ref->ref_list) ||
573a0755 2590 locked_ref->extent_op) {
d7df2c79
JB
2591 spin_unlock(&locked_ref->lock);
2592 spin_unlock(&delayed_refs->lock);
2593 continue;
2594 }
2595 ref->in_tree = 0;
2596 delayed_refs->num_heads--;
c46effa6
LB
2597 rb_erase(&locked_ref->href_node,
2598 &delayed_refs->href_root);
d7df2c79
JB
2599 spin_unlock(&delayed_refs->lock);
2600 } else {
0a2b2a84 2601 actual_count++;
d7df2c79 2602 ref->in_tree = 0;
c6fc2454 2603 list_del(&ref->list);
c46effa6 2604 }
d7df2c79
JB
2605 atomic_dec(&delayed_refs->num_entries);
2606
093486c4 2607 if (!btrfs_delayed_ref_is_head(ref)) {
22cd2e7d
AJ
2608 /*
2609 * when we play the delayed ref, also correct the
2610 * ref_mod on head
2611 */
2612 switch (ref->action) {
2613 case BTRFS_ADD_DELAYED_REF:
2614 case BTRFS_ADD_DELAYED_EXTENT:
2615 locked_ref->node.ref_mod -= ref->ref_mod;
2616 break;
2617 case BTRFS_DROP_DELAYED_REF:
2618 locked_ref->node.ref_mod += ref->ref_mod;
2619 break;
2620 default:
2621 WARN_ON(1);
2622 }
2623 }
d7df2c79 2624 spin_unlock(&locked_ref->lock);
925baedd 2625
5d4f98a2 2626 ret = run_one_delayed_ref(trans, root, ref, extent_op,
56bec294 2627 must_insert_reserved);
eb099670 2628
78a6184a 2629 btrfs_free_delayed_extent_op(extent_op);
79787eaa 2630 if (ret) {
d7df2c79 2631 locked_ref->processing = 0;
093486c4
MX
2632 btrfs_delayed_ref_unlock(locked_ref);
2633 btrfs_put_delayed_ref(ref);
c2cf52eb 2634 btrfs_debug(fs_info, "run_one_delayed_ref returned %d", ret);
79787eaa
JM
2635 return ret;
2636 }
2637
093486c4
MX
2638 /*
2639 * If this node is a head, that means all the refs in this head
2640 * have been dealt with, and we will pick the next head to deal
2641 * with, so we must unlock the head and drop it from the cluster
2642 * list before we release it.
2643 */
2644 if (btrfs_delayed_ref_is_head(ref)) {
1262133b
JB
2645 if (locked_ref->is_data &&
2646 locked_ref->total_ref_mod < 0) {
2647 spin_lock(&delayed_refs->lock);
2648 delayed_refs->pending_csums -= ref->num_bytes;
2649 spin_unlock(&delayed_refs->lock);
2650 }
093486c4
MX
2651 btrfs_delayed_ref_unlock(locked_ref);
2652 locked_ref = NULL;
2653 }
2654 btrfs_put_delayed_ref(ref);
2655 count++;
c3e69d58 2656 cond_resched();
c3e69d58 2657 }
0a2b2a84
JB
2658
2659 /*
2660 * We don't want to include ref heads since we can have empty ref heads
2661 * and those will drastically skew our runtime down since we just do
2662 * accounting, no actual extent tree updates.
2663 */
2664 if (actual_count > 0) {
2665 u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
2666 u64 avg;
2667
2668 /*
2669 * We weigh the current average higher than our current runtime
2670 * to avoid large swings in the average.
2671 */
2672 spin_lock(&delayed_refs->lock);
2673 avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
f8c269d7 2674 fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
0a2b2a84
JB
2675 spin_unlock(&delayed_refs->lock);
2676 }
d7df2c79 2677 return 0;
c3e69d58
CM
2678}
2679
709c0486
AJ
2680#ifdef SCRAMBLE_DELAYED_REFS
2681/*
2682 * Normally delayed refs get processed in ascending bytenr order. This
2683 * correlates in most cases to the order added. To expose dependencies on this
2684 * order, we start to process the tree in the middle instead of the beginning
2685 */
2686static u64 find_middle(struct rb_root *root)
2687{
2688 struct rb_node *n = root->rb_node;
2689 struct btrfs_delayed_ref_node *entry;
2690 int alt = 1;
2691 u64 middle;
2692 u64 first = 0, last = 0;
2693
2694 n = rb_first(root);
2695 if (n) {
2696 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2697 first = entry->bytenr;
2698 }
2699 n = rb_last(root);
2700 if (n) {
2701 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2702 last = entry->bytenr;
2703 }
2704 n = root->rb_node;
2705
2706 while (n) {
2707 entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
2708 WARN_ON(!entry->in_tree);
2709
2710 middle = entry->bytenr;
2711
2712 if (alt)
2713 n = n->rb_left;
2714 else
2715 n = n->rb_right;
2716
2717 alt = 1 - alt;
2718 }
2719 return middle;
2720}
2721#endif
2722
1be41b78
JB
2723static inline u64 heads_to_leaves(struct btrfs_root *root, u64 heads)
2724{
2725 u64 num_bytes;
2726
2727 num_bytes = heads * (sizeof(struct btrfs_extent_item) +
2728 sizeof(struct btrfs_extent_inline_ref));
2729 if (!btrfs_fs_incompat(root->fs_info, SKINNY_METADATA))
2730 num_bytes += heads * sizeof(struct btrfs_tree_block_info);
2731
2732 /*
2733 * We don't ever fill up leaves all the way so multiply by 2 just to be
2734 * closer to what we're really going to want to ouse.
2735 */
f8c269d7 2736 return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(root));
1be41b78
JB
2737}
2738
1262133b
JB
2739/*
2740 * Takes the number of bytes to be csumm'ed and figures out how many leaves it
2741 * would require to store the csums for that many bytes.
2742 */
28f75a0e 2743u64 btrfs_csum_bytes_to_leaves(struct btrfs_root *root, u64 csum_bytes)
1262133b
JB
2744{
2745 u64 csum_size;
2746 u64 num_csums_per_leaf;
2747 u64 num_csums;
2748
2749 csum_size = BTRFS_LEAF_DATA_SIZE(root) - sizeof(struct btrfs_item);
2750 num_csums_per_leaf = div64_u64(csum_size,
2751 (u64)btrfs_super_csum_size(root->fs_info->super_copy));
2752 num_csums = div64_u64(csum_bytes, root->sectorsize);
2753 num_csums += num_csums_per_leaf - 1;
2754 num_csums = div64_u64(num_csums, num_csums_per_leaf);
2755 return num_csums;
2756}
2757
0a2b2a84 2758int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
1be41b78
JB
2759 struct btrfs_root *root)
2760{
2761 struct btrfs_block_rsv *global_rsv;
2762 u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
1262133b 2763 u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
cb723e49
JB
2764 u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
2765 u64 num_bytes, num_dirty_bgs_bytes;
1be41b78
JB
2766 int ret = 0;
2767
2768 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
2769 num_heads = heads_to_leaves(root, num_heads);
2770 if (num_heads > 1)
707e8a07 2771 num_bytes += (num_heads - 1) * root->nodesize;
1be41b78 2772 num_bytes <<= 1;
28f75a0e 2773 num_bytes += btrfs_csum_bytes_to_leaves(root, csum_bytes) * root->nodesize;
cb723e49
JB
2774 num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(root,
2775 num_dirty_bgs);
1be41b78
JB
2776 global_rsv = &root->fs_info->global_block_rsv;
2777
2778 /*
2779 * If we can't allocate any more chunks lets make sure we have _lots_ of
2780 * wiggle room since running delayed refs can create more delayed refs.
2781 */
cb723e49
JB
2782 if (global_rsv->space_info->full) {
2783 num_dirty_bgs_bytes <<= 1;
1be41b78 2784 num_bytes <<= 1;
cb723e49 2785 }
1be41b78
JB
2786
2787 spin_lock(&global_rsv->lock);
cb723e49 2788 if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
1be41b78
JB
2789 ret = 1;
2790 spin_unlock(&global_rsv->lock);
2791 return ret;
2792}
2793
0a2b2a84
JB
2794int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
2795 struct btrfs_root *root)
2796{
2797 struct btrfs_fs_info *fs_info = root->fs_info;
2798 u64 num_entries =
2799 atomic_read(&trans->transaction->delayed_refs.num_entries);
2800 u64 avg_runtime;
a79b7d4b 2801 u64 val;
0a2b2a84
JB
2802
2803 smp_mb();
2804 avg_runtime = fs_info->avg_delayed_ref_runtime;
a79b7d4b 2805 val = num_entries * avg_runtime;
0a2b2a84
JB
2806 if (num_entries * avg_runtime >= NSEC_PER_SEC)
2807 return 1;
a79b7d4b
CM
2808 if (val >= NSEC_PER_SEC / 2)
2809 return 2;
0a2b2a84
JB
2810
2811 return btrfs_check_space_for_delayed_refs(trans, root);
2812}
2813
a79b7d4b
CM
2814struct async_delayed_refs {
2815 struct btrfs_root *root;
2816 int count;
2817 int error;
2818 int sync;
2819 struct completion wait;
2820 struct btrfs_work work;
2821};
2822
2823static void delayed_ref_async_start(struct btrfs_work *work)
2824{
2825 struct async_delayed_refs *async;
2826 struct btrfs_trans_handle *trans;
2827 int ret;
2828
2829 async = container_of(work, struct async_delayed_refs, work);
2830
2831 trans = btrfs_join_transaction(async->root);
2832 if (IS_ERR(trans)) {
2833 async->error = PTR_ERR(trans);
2834 goto done;
2835 }
2836
2837 /*
2838 * trans->sync means that when we call end_transaciton, we won't
2839 * wait on delayed refs
2840 */
2841 trans->sync = true;
2842 ret = btrfs_run_delayed_refs(trans, async->root, async->count);
2843 if (ret)
2844 async->error = ret;
2845
2846 ret = btrfs_end_transaction(trans, async->root);
2847 if (ret && !async->error)
2848 async->error = ret;
2849done:
2850 if (async->sync)
2851 complete(&async->wait);
2852 else
2853 kfree(async);
2854}
2855
2856int btrfs_async_run_delayed_refs(struct btrfs_root *root,
2857 unsigned long count, int wait)
2858{
2859 struct async_delayed_refs *async;
2860 int ret;
2861
2862 async = kmalloc(sizeof(*async), GFP_NOFS);
2863 if (!async)
2864 return -ENOMEM;
2865
2866 async->root = root->fs_info->tree_root;
2867 async->count = count;
2868 async->error = 0;
2869 if (wait)
2870 async->sync = 1;
2871 else
2872 async->sync = 0;
2873 init_completion(&async->wait);
2874
9e0af237
LB
2875 btrfs_init_work(&async->work, btrfs_extent_refs_helper,
2876 delayed_ref_async_start, NULL, NULL);
a79b7d4b
CM
2877
2878 btrfs_queue_work(root->fs_info->extent_workers, &async->work);
2879
2880 if (wait) {
2881 wait_for_completion(&async->wait);
2882 ret = async->error;
2883 kfree(async);
2884 return ret;
2885 }
2886 return 0;
2887}
2888
c3e69d58
CM
2889/*
2890 * this starts processing the delayed reference count updates and
2891 * extent insertions we have queued up so far. count can be
2892 * 0, which means to process everything in the tree at the start
2893 * of the run (but not newly added entries), or it can be some target
2894 * number you'd like to process.
79787eaa
JM
2895 *
2896 * Returns 0 on success or if called with an aborted transaction
2897 * Returns <0 on error and aborts the transaction
c3e69d58
CM
2898 */
2899int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
2900 struct btrfs_root *root, unsigned long count)
2901{
2902 struct rb_node *node;
2903 struct btrfs_delayed_ref_root *delayed_refs;
c46effa6 2904 struct btrfs_delayed_ref_head *head;
c3e69d58
CM
2905 int ret;
2906 int run_all = count == (unsigned long)-1;
d9a0540a 2907 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
c3e69d58 2908
79787eaa
JM
2909 /* We'll clean this up in btrfs_cleanup_transaction */
2910 if (trans->aborted)
2911 return 0;
2912
c3e69d58
CM
2913 if (root == root->fs_info->extent_root)
2914 root = root->fs_info->tree_root;
2915
2916 delayed_refs = &trans->transaction->delayed_refs;
26455d33 2917 if (count == 0)
d7df2c79 2918 count = atomic_read(&delayed_refs->num_entries) * 2;
bb721703 2919
c3e69d58 2920again:
709c0486
AJ
2921#ifdef SCRAMBLE_DELAYED_REFS
2922 delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
2923#endif
d9a0540a 2924 trans->can_flush_pending_bgs = false;
d7df2c79
JB
2925 ret = __btrfs_run_delayed_refs(trans, root, count);
2926 if (ret < 0) {
2927 btrfs_abort_transaction(trans, root, ret);
2928 return ret;
eb099670 2929 }
c3e69d58 2930
56bec294 2931 if (run_all) {
d7df2c79 2932 if (!list_empty(&trans->new_bgs))
ea658bad 2933 btrfs_create_pending_block_groups(trans, root);
ea658bad 2934
d7df2c79 2935 spin_lock(&delayed_refs->lock);
c46effa6 2936 node = rb_first(&delayed_refs->href_root);
d7df2c79
JB
2937 if (!node) {
2938 spin_unlock(&delayed_refs->lock);
56bec294 2939 goto out;
d7df2c79 2940 }
c3e69d58 2941 count = (unsigned long)-1;
e9d0b13b 2942
56bec294 2943 while (node) {
c46effa6
LB
2944 head = rb_entry(node, struct btrfs_delayed_ref_head,
2945 href_node);
2946 if (btrfs_delayed_ref_is_head(&head->node)) {
2947 struct btrfs_delayed_ref_node *ref;
5caf2a00 2948
c46effa6 2949 ref = &head->node;
56bec294
CM
2950 atomic_inc(&ref->refs);
2951
2952 spin_unlock(&delayed_refs->lock);
8cc33e5c
DS
2953 /*
2954 * Mutex was contended, block until it's
2955 * released and try again
2956 */
56bec294
CM
2957 mutex_lock(&head->mutex);
2958 mutex_unlock(&head->mutex);
2959
2960 btrfs_put_delayed_ref(ref);
1887be66 2961 cond_resched();
56bec294 2962 goto again;
c46effa6
LB
2963 } else {
2964 WARN_ON(1);
56bec294
CM
2965 }
2966 node = rb_next(node);
2967 }
2968 spin_unlock(&delayed_refs->lock);
d7df2c79 2969 cond_resched();
56bec294 2970 goto again;
5f39d397 2971 }
54aa1f4d 2972out:
edf39272 2973 assert_qgroups_uptodate(trans);
d9a0540a 2974 trans->can_flush_pending_bgs = can_flush_pending_bgs;
a28ec197
CM
2975 return 0;
2976}
2977
5d4f98a2
YZ
2978int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
2979 struct btrfs_root *root,
2980 u64 bytenr, u64 num_bytes, u64 flags,
b1c79e09 2981 int level, int is_data)
5d4f98a2
YZ
2982{
2983 struct btrfs_delayed_extent_op *extent_op;
2984 int ret;
2985
78a6184a 2986 extent_op = btrfs_alloc_delayed_extent_op();
5d4f98a2
YZ
2987 if (!extent_op)
2988 return -ENOMEM;
2989
2990 extent_op->flags_to_set = flags;
2991 extent_op->update_flags = 1;
2992 extent_op->update_key = 0;
2993 extent_op->is_data = is_data ? 1 : 0;
b1c79e09 2994 extent_op->level = level;
5d4f98a2 2995
66d7e7f0
AJ
2996 ret = btrfs_add_delayed_extent_op(root->fs_info, trans, bytenr,
2997 num_bytes, extent_op);
5d4f98a2 2998 if (ret)
78a6184a 2999 btrfs_free_delayed_extent_op(extent_op);
5d4f98a2
YZ
3000 return ret;
3001}
3002
3003static noinline int check_delayed_ref(struct btrfs_trans_handle *trans,
3004 struct btrfs_root *root,
3005 struct btrfs_path *path,
3006 u64 objectid, u64 offset, u64 bytenr)
3007{
3008 struct btrfs_delayed_ref_head *head;
3009 struct btrfs_delayed_ref_node *ref;
3010 struct btrfs_delayed_data_ref *data_ref;
3011 struct btrfs_delayed_ref_root *delayed_refs;
5d4f98a2
YZ
3012 int ret = 0;
3013
5d4f98a2
YZ
3014 delayed_refs = &trans->transaction->delayed_refs;
3015 spin_lock(&delayed_refs->lock);
3016 head = btrfs_find_delayed_ref_head(trans, bytenr);
d7df2c79
JB
3017 if (!head) {
3018 spin_unlock(&delayed_refs->lock);
3019 return 0;
3020 }
5d4f98a2
YZ
3021
3022 if (!mutex_trylock(&head->mutex)) {
3023 atomic_inc(&head->node.refs);
3024 spin_unlock(&delayed_refs->lock);
3025
b3b4aa74 3026 btrfs_release_path(path);
5d4f98a2 3027
8cc33e5c
DS
3028 /*
3029 * Mutex was contended, block until it's released and let
3030 * caller try again
3031 */
5d4f98a2
YZ
3032 mutex_lock(&head->mutex);
3033 mutex_unlock(&head->mutex);
3034 btrfs_put_delayed_ref(&head->node);
3035 return -EAGAIN;
3036 }
d7df2c79 3037 spin_unlock(&delayed_refs->lock);
5d4f98a2 3038
d7df2c79 3039 spin_lock(&head->lock);
c6fc2454 3040 list_for_each_entry(ref, &head->ref_list, list) {
d7df2c79
JB
3041 /* If it's a shared ref we know a cross reference exists */
3042 if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
3043 ret = 1;
3044 break;
3045 }
5d4f98a2 3046
d7df2c79 3047 data_ref = btrfs_delayed_node_to_data_ref(ref);
5d4f98a2 3048
d7df2c79
JB
3049 /*
3050 * If our ref doesn't match the one we're currently looking at
3051 * then we have a cross reference.
3052 */
3053 if (data_ref->root != root->root_key.objectid ||
3054 data_ref->objectid != objectid ||
3055 data_ref->offset != offset) {
3056 ret = 1;
3057 break;
3058 }
5d4f98a2 3059 }
d7df2c79 3060 spin_unlock(&head->lock);
5d4f98a2 3061 mutex_unlock(&head->mutex);
5d4f98a2
YZ
3062 return ret;
3063}
3064
3065static noinline int check_committed_ref(struct btrfs_trans_handle *trans,
3066 struct btrfs_root *root,
3067 struct btrfs_path *path,
3068 u64 objectid, u64 offset, u64 bytenr)
be20aa9d
CM
3069{
3070 struct btrfs_root *extent_root = root->fs_info->extent_root;
f321e491 3071 struct extent_buffer *leaf;
5d4f98a2
YZ
3072 struct btrfs_extent_data_ref *ref;
3073 struct btrfs_extent_inline_ref *iref;
3074 struct btrfs_extent_item *ei;
f321e491 3075 struct btrfs_key key;
5d4f98a2 3076 u32 item_size;
be20aa9d 3077 int ret;
925baedd 3078
be20aa9d 3079 key.objectid = bytenr;
31840ae1 3080 key.offset = (u64)-1;
f321e491 3081 key.type = BTRFS_EXTENT_ITEM_KEY;
be20aa9d 3082
be20aa9d
CM
3083 ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
3084 if (ret < 0)
3085 goto out;
79787eaa 3086 BUG_ON(ret == 0); /* Corruption */
80ff3856
YZ
3087
3088 ret = -ENOENT;
3089 if (path->slots[0] == 0)
31840ae1 3090 goto out;
be20aa9d 3091
31840ae1 3092 path->slots[0]--;
f321e491 3093 leaf = path->nodes[0];
5d4f98a2 3094 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
be20aa9d 3095
5d4f98a2 3096 if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
be20aa9d 3097 goto out;
f321e491 3098
5d4f98a2
YZ
3099 ret = 1;
3100 item_size = btrfs_item_size_nr(leaf, path->slots[0]);
3101#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
3102 if (item_size < sizeof(*ei)) {
3103 WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
3104 goto out;
3105 }
3106#endif
3107 ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
bd09835d 3108
5d4f98a2
YZ
3109 if (item_size != sizeof(*ei) +
3110 btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
3111 goto out;
be20aa9d 3112
5d4f98a2
YZ
3113 if (btrfs_extent_generation(leaf, ei) <=
3114 btrfs_root_last_snapshot(&root->root_item))
3115 goto out;
3116
3117 iref = (struct btrfs_extent_inline_ref *)(ei + 1);
3118 if (btrfs_extent_inline_ref_type(leaf, iref) !=
3119 BTRFS_EXTENT_DATA_REF_KEY)
3120 goto out;
3121
3122 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
3123 if (btrfs_extent_refs(leaf, ei) !=
3124 btrfs_extent_data_ref_count(leaf, ref) ||
3125 btrfs_extent_data_ref_root(leaf, ref) !=
3126 root->root_key.objectid ||
3127 btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
3128 btrfs_extent_data_ref_offset(leaf, ref) != offset)
3129 goto out;
3130
3131 ret = 0;
3132out:
3133 return ret;
3134}
3135
3136int btrfs_cross_ref_exist(struct btrfs_trans_handle *trans,
3137 struct btrfs_root *root,
3138 u64 objectid, u64 offset, u64 bytenr)
3139{
3140 struct btrfs_path *path;
3141 int ret;
3142 int ret2;
3143
3144 path = btrfs_alloc_path();
3145 if (!path)
3146 return -ENOENT;
3147
3148 do {
3149 ret = check_committed_ref(trans, root, path, objectid,
3150 offset, bytenr);
3151 if (ret && ret != -ENOENT)
f321e491 3152 goto out;
80ff3856 3153
5d4f98a2
YZ
3154 ret2 = check_delayed_ref(trans, root, path, objectid,
3155 offset, bytenr);
3156 } while (ret2 == -EAGAIN);
3157
3158 if (ret2 && ret2 != -ENOENT) {
3159 ret = ret2;
3160 goto out;
f321e491 3161 }
5d4f98a2
YZ
3162
3163 if (ret != -ENOENT || ret2 != -ENOENT)
3164 ret = 0;
be20aa9d 3165out:
80ff3856 3166 btrfs_free_path(path);
f0486c68
YZ
3167 if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
3168 WARN_ON(ret > 0);
f321e491 3169 return ret;
be20aa9d 3170}
c5739bba 3171
5d4f98a2 3172static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
b7a9f29f 3173 struct btrfs_root *root,
5d4f98a2 3174 struct extent_buffer *buf,
e339a6b0 3175 int full_backref, int inc)
31840ae1
ZY
3176{
3177 u64 bytenr;
5d4f98a2
YZ
3178 u64 num_bytes;
3179 u64 parent;
31840ae1 3180 u64 ref_root;
31840ae1 3181 u32 nritems;
31840ae1
ZY
3182 struct btrfs_key key;
3183 struct btrfs_file_extent_item *fi;
3184 int i;
3185 int level;
3186 int ret = 0;
31840ae1 3187 int (*process_func)(struct btrfs_trans_handle *, struct btrfs_root *,
b06c4bf5 3188 u64, u64, u64, u64, u64, u64);
31840ae1 3189
fccb84c9
DS
3190
3191 if (btrfs_test_is_dummy_root(root))
faa2dbf0 3192 return 0;
fccb84c9 3193
31840ae1 3194 ref_root = btrfs_header_owner(buf);
31840ae1
ZY
3195 nritems = btrfs_header_nritems(buf);
3196 level = btrfs_header_level(buf);
3197
27cdeb70 3198 if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
5d4f98a2 3199 return 0;
31840ae1 3200
5d4f98a2
YZ
3201 if (inc)
3202 process_func = btrfs_inc_extent_ref;
3203 else
3204 process_func = btrfs_free_extent;
31840ae1 3205
5d4f98a2
YZ
3206 if (full_backref)
3207 parent = buf->start;
3208 else
3209 parent = 0;
3210
3211 for (i = 0; i < nritems; i++) {
31840ae1 3212 if (level == 0) {
5d4f98a2 3213 btrfs_item_key_to_cpu(buf, &key, i);
962a298f 3214 if (key.type != BTRFS_EXTENT_DATA_KEY)
31840ae1 3215 continue;
5d4f98a2 3216 fi = btrfs_item_ptr(buf, i,
31840ae1
ZY
3217 struct btrfs_file_extent_item);
3218 if (btrfs_file_extent_type(buf, fi) ==
3219 BTRFS_FILE_EXTENT_INLINE)
3220 continue;
3221 bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
3222 if (bytenr == 0)
3223 continue;
5d4f98a2
YZ
3224
3225 num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
3226 key.offset -= btrfs_file_extent_offset(buf, fi);
3227 ret = process_func(trans, root, bytenr, num_bytes,
3228 parent, ref_root, key.objectid,
b06c4bf5 3229 key.offset);
31840ae1
ZY
3230 if (ret)
3231 goto fail;
3232 } else {
5d4f98a2 3233 bytenr = btrfs_node_blockptr(buf, i);
707e8a07 3234 num_bytes = root->nodesize;
5d4f98a2 3235 ret = process_func(trans, root, bytenr, num_bytes,
b06c4bf5 3236 parent, ref_root, level - 1, 0);
31840ae1
ZY
3237 if (ret)
3238 goto fail;
3239 }
3240 }
3241 return 0;
3242fail:
5d4f98a2
YZ
3243 return ret;
3244}
3245
3246int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
e339a6b0 3247 struct extent_buffer *buf, int full_backref)
5d4f98a2 3248{
e339a6b0 3249 return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
5d4f98a2
YZ
3250}
3251
3252int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
e339a6b0 3253 struct extent_buffer *buf, int full_backref)
5d4f98a2 3254{
e339a6b0 3255 return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
31840ae1
ZY
3256}
3257
9078a3e1
CM
3258static int write_one_cache_group(struct btrfs_trans_handle *trans,
3259 struct btrfs_root *root,
3260 struct btrfs_path *path,
3261 struct btrfs_block_group_cache *cache)
3262{
3263 int ret;
9078a3e1 3264 struct btrfs_root *extent_root = root->fs_info->extent_root;
5f39d397
CM
3265 unsigned long bi;
3266 struct extent_buffer *leaf;
9078a3e1 3267
9078a3e1 3268 ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
df95e7f0
JB
3269 if (ret) {
3270 if (ret > 0)
3271 ret = -ENOENT;
54aa1f4d 3272 goto fail;
df95e7f0 3273 }
5f39d397
CM
3274
3275 leaf = path->nodes[0];
3276 bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
3277 write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
3278 btrfs_mark_buffer_dirty(leaf);
54aa1f4d 3279fail:
24b89d08 3280 btrfs_release_path(path);
df95e7f0 3281 return ret;
9078a3e1
CM
3282
3283}
3284
4a8c9a62
YZ
3285static struct btrfs_block_group_cache *
3286next_block_group(struct btrfs_root *root,
3287 struct btrfs_block_group_cache *cache)
3288{
3289 struct rb_node *node;
292cbd51 3290
4a8c9a62 3291 spin_lock(&root->fs_info->block_group_cache_lock);
292cbd51
FM
3292
3293 /* If our block group was removed, we need a full search. */
3294 if (RB_EMPTY_NODE(&cache->cache_node)) {
3295 const u64 next_bytenr = cache->key.objectid + cache->key.offset;
3296
3297 spin_unlock(&root->fs_info->block_group_cache_lock);
3298 btrfs_put_block_group(cache);
3299 cache = btrfs_lookup_first_block_group(root->fs_info,
3300 next_bytenr);
3301 return cache;
3302 }
4a8c9a62
YZ
3303 node = rb_next(&cache->cache_node);
3304 btrfs_put_block_group(cache);
3305 if (node) {
3306 cache = rb_entry(node, struct btrfs_block_group_cache,
3307 cache_node);
11dfe35a 3308 btrfs_get_block_group(cache);
4a8c9a62
YZ
3309 } else
3310 cache = NULL;
3311 spin_unlock(&root->fs_info->block_group_cache_lock);
3312 return cache;
3313}
3314
0af3d00b
JB
3315static int cache_save_setup(struct btrfs_block_group_cache *block_group,
3316 struct btrfs_trans_handle *trans,
3317 struct btrfs_path *path)
3318{
3319 struct btrfs_root *root = block_group->fs_info->tree_root;
3320 struct inode *inode = NULL;
3321 u64 alloc_hint = 0;
2b20982e 3322 int dcs = BTRFS_DC_ERROR;
f8c269d7 3323 u64 num_pages = 0;
0af3d00b
JB
3324 int retries = 0;
3325 int ret = 0;
3326
3327 /*
3328 * If this block group is smaller than 100 megs don't bother caching the
3329 * block group.
3330 */
3331 if (block_group->key.offset < (100 * 1024 * 1024)) {
3332 spin_lock(&block_group->lock);
3333 block_group->disk_cache_state = BTRFS_DC_WRITTEN;
3334 spin_unlock(&block_group->lock);
3335 return 0;
3336 }
3337
0c0ef4bc
JB
3338 if (trans->aborted)
3339 return 0;
0af3d00b
JB
3340again:
3341 inode = lookup_free_space_inode(root, block_group, path);
3342 if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
3343 ret = PTR_ERR(inode);
b3b4aa74 3344 btrfs_release_path(path);
0af3d00b
JB
3345 goto out;
3346 }
3347
3348 if (IS_ERR(inode)) {
3349 BUG_ON(retries);
3350 retries++;
3351
3352 if (block_group->ro)
3353 goto out_free;
3354
3355 ret = create_free_space_inode(root, trans, block_group, path);
3356 if (ret)
3357 goto out_free;
3358 goto again;
3359 }
3360
5b0e95bf
JB
3361 /* We've already setup this transaction, go ahead and exit */
3362 if (block_group->cache_generation == trans->transid &&
3363 i_size_read(inode)) {
3364 dcs = BTRFS_DC_SETUP;
3365 goto out_put;
3366 }
3367
0af3d00b
JB
3368 /*
3369 * We want to set the generation to 0, that way if anything goes wrong
3370 * from here on out we know not to trust this cache when we load up next
3371 * time.
3372 */
3373 BTRFS_I(inode)->generation = 0;
3374 ret = btrfs_update_inode(trans, root, inode);
0c0ef4bc
JB
3375 if (ret) {
3376 /*
3377 * So theoretically we could recover from this, simply set the
3378 * super cache generation to 0 so we know to invalidate the
3379 * cache, but then we'd have to keep track of the block groups
3380 * that fail this way so we know we _have_ to reset this cache
3381 * before the next commit or risk reading stale cache. So to
3382 * limit our exposure to horrible edge cases lets just abort the
3383 * transaction, this only happens in really bad situations
3384 * anyway.
3385 */
3386 btrfs_abort_transaction(trans, root, ret);
3387 goto out_put;
3388 }
0af3d00b
JB
3389 WARN_ON(ret);
3390
3391 if (i_size_read(inode) > 0) {
7b61cd92
MX
3392 ret = btrfs_check_trunc_cache_free_space(root,
3393 &root->fs_info->global_block_rsv);
3394 if (ret)
3395 goto out_put;
3396
1bbc621e 3397 ret = btrfs_truncate_free_space_cache(root, trans, NULL, inode);
0af3d00b
JB
3398 if (ret)
3399 goto out_put;
3400 }
3401
3402 spin_lock(&block_group->lock);
cf7c1ef6 3403 if (block_group->cached != BTRFS_CACHE_FINISHED ||
e4c88f00 3404 !btrfs_test_opt(root, SPACE_CACHE)) {
cf7c1ef6
LB
3405 /*
3406 * don't bother trying to write stuff out _if_
3407 * a) we're not cached,
3408 * b) we're with nospace_cache mount option.
3409 */
2b20982e 3410 dcs = BTRFS_DC_WRITTEN;
0af3d00b
JB
3411 spin_unlock(&block_group->lock);
3412 goto out_put;
3413 }
3414 spin_unlock(&block_group->lock);
3415
2968b1f4
JB
3416 /*
3417 * We hit an ENOSPC when setting up the cache in this transaction, just
3418 * skip doing the setup, we've already cleared the cache so we're safe.
3419 */
3420 if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
3421 ret = -ENOSPC;
3422 goto out_put;
3423 }
3424
6fc823b1
JB
3425 /*
3426 * Try to preallocate enough space based on how big the block group is.
3427 * Keep in mind this has to include any pinned space which could end up
3428 * taking up quite a bit since it's not folded into the other space
3429 * cache.
3430 */
f8c269d7 3431 num_pages = div_u64(block_group->key.offset, 256 * 1024 * 1024);
0af3d00b
JB
3432 if (!num_pages)
3433 num_pages = 1;
3434
0af3d00b
JB
3435 num_pages *= 16;
3436 num_pages *= PAGE_CACHE_SIZE;
3437
7cf5b976 3438 ret = btrfs_check_data_free_space(inode, 0, num_pages);
0af3d00b
JB
3439 if (ret)
3440 goto out_put;
3441
3442 ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
3443 num_pages, num_pages,
3444 &alloc_hint);
2968b1f4
JB
3445 /*
3446 * Our cache requires contiguous chunks so that we don't modify a bunch
3447 * of metadata or split extents when writing the cache out, which means
3448 * we can enospc if we are heavily fragmented in addition to just normal
3449 * out of space conditions. So if we hit this just skip setting up any
3450 * other block groups for this transaction, maybe we'll unpin enough
3451 * space the next time around.
3452 */
2b20982e
JB
3453 if (!ret)
3454 dcs = BTRFS_DC_SETUP;
2968b1f4
JB
3455 else if (ret == -ENOSPC)
3456 set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
7cf5b976 3457 btrfs_free_reserved_data_space(inode, 0, num_pages);
c09544e0 3458
0af3d00b
JB
3459out_put:
3460 iput(inode);
3461out_free:
b3b4aa74 3462 btrfs_release_path(path);
0af3d00b
JB
3463out:
3464 spin_lock(&block_group->lock);
e65cbb94 3465 if (!ret && dcs == BTRFS_DC_SETUP)
5b0e95bf 3466 block_group->cache_generation = trans->transid;
2b20982e 3467 block_group->disk_cache_state = dcs;
0af3d00b
JB
3468 spin_unlock(&block_group->lock);
3469
3470 return ret;
3471}
3472
dcdf7f6d
JB
3473int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
3474 struct btrfs_root *root)
3475{
3476 struct btrfs_block_group_cache *cache, *tmp;
3477 struct btrfs_transaction *cur_trans = trans->transaction;
3478 struct btrfs_path *path;
3479
3480 if (list_empty(&cur_trans->dirty_bgs) ||
3481 !btrfs_test_opt(root, SPACE_CACHE))
3482 return 0;
3483
3484 path = btrfs_alloc_path();
3485 if (!path)
3486 return -ENOMEM;
3487
3488 /* Could add new block groups, use _safe just in case */
3489 list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
3490 dirty_list) {
3491 if (cache->disk_cache_state == BTRFS_DC_CLEAR)
3492 cache_save_setup(cache, trans, path);
3493 }
3494
3495 btrfs_free_path(path);
3496 return 0;
3497}
3498
1bbc621e
CM
3499/*
3500 * transaction commit does final block group cache writeback during a
3501 * critical section where nothing is allowed to change the FS. This is
3502 * required in order for the cache to actually match the block group,
3503 * but can introduce a lot of latency into the commit.
3504 *
3505 * So, btrfs_start_dirty_block_groups is here to kick off block group
3506 * cache IO. There's a chance we'll have to redo some of it if the
3507 * block group changes again during the commit, but it greatly reduces
3508 * the commit latency by getting rid of the easy block groups while
3509 * we're still allowing others to join the commit.
3510 */
3511int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
96b5179d 3512 struct btrfs_root *root)
9078a3e1 3513{
4a8c9a62 3514 struct btrfs_block_group_cache *cache;
ce93ec54
JB
3515 struct btrfs_transaction *cur_trans = trans->transaction;
3516 int ret = 0;
c9dc4c65 3517 int should_put;
1bbc621e
CM
3518 struct btrfs_path *path = NULL;
3519 LIST_HEAD(dirty);
3520 struct list_head *io = &cur_trans->io_bgs;
c9dc4c65 3521 int num_started = 0;
1bbc621e
CM
3522 int loops = 0;
3523
3524 spin_lock(&cur_trans->dirty_bgs_lock);
b58d1a9e
FM
3525 if (list_empty(&cur_trans->dirty_bgs)) {
3526 spin_unlock(&cur_trans->dirty_bgs_lock);
3527 return 0;
1bbc621e 3528 }
b58d1a9e 3529 list_splice_init(&cur_trans->dirty_bgs, &dirty);
1bbc621e 3530 spin_unlock(&cur_trans->dirty_bgs_lock);
ce93ec54 3531
1bbc621e 3532again:
1bbc621e
CM
3533 /*
3534 * make sure all the block groups on our dirty list actually
3535 * exist
3536 */
3537 btrfs_create_pending_block_groups(trans, root);
3538
3539 if (!path) {
3540 path = btrfs_alloc_path();
3541 if (!path)
3542 return -ENOMEM;
3543 }
3544
b58d1a9e
FM
3545 /*
3546 * cache_write_mutex is here only to save us from balance or automatic
3547 * removal of empty block groups deleting this block group while we are
3548 * writing out the cache
3549 */
3550 mutex_lock(&trans->transaction->cache_write_mutex);
1bbc621e
CM
3551 while (!list_empty(&dirty)) {
3552 cache = list_first_entry(&dirty,
3553 struct btrfs_block_group_cache,
3554 dirty_list);
1bbc621e
CM
3555 /*
3556 * this can happen if something re-dirties a block
3557 * group that is already under IO. Just wait for it to
3558 * finish and then do it all again
3559 */
3560 if (!list_empty(&cache->io_list)) {
3561 list_del_init(&cache->io_list);
3562 btrfs_wait_cache_io(root, trans, cache,
3563 &cache->io_ctl, path,
3564 cache->key.objectid);
3565 btrfs_put_block_group(cache);
3566 }
3567
3568
3569 /*
3570 * btrfs_wait_cache_io uses the cache->dirty_list to decide
3571 * if it should update the cache_state. Don't delete
3572 * until after we wait.
3573 *
3574 * Since we're not running in the commit critical section
3575 * we need the dirty_bgs_lock to protect from update_block_group
3576 */
3577 spin_lock(&cur_trans->dirty_bgs_lock);
3578 list_del_init(&cache->dirty_list);
3579 spin_unlock(&cur_trans->dirty_bgs_lock);
3580
3581 should_put = 1;
3582
3583 cache_save_setup(cache, trans, path);
3584
3585 if (cache->disk_cache_state == BTRFS_DC_SETUP) {
3586 cache->io_ctl.inode = NULL;
3587 ret = btrfs_write_out_cache(root, trans, cache, path);
3588 if (ret == 0 && cache->io_ctl.inode) {
3589 num_started++;
3590 should_put = 0;
3591
3592 /*
3593 * the cache_write_mutex is protecting
3594 * the io_list
3595 */
3596 list_add_tail(&cache->io_list, io);
3597 } else {
3598 /*
3599 * if we failed to write the cache, the
3600 * generation will be bad and life goes on
3601 */
3602 ret = 0;
3603 }
3604 }
ff1f8250 3605 if (!ret) {
1bbc621e 3606 ret = write_one_cache_group(trans, root, path, cache);
ff1f8250
FM
3607 /*
3608 * Our block group might still be attached to the list
3609 * of new block groups in the transaction handle of some
3610 * other task (struct btrfs_trans_handle->new_bgs). This
3611 * means its block group item isn't yet in the extent
3612 * tree. If this happens ignore the error, as we will
3613 * try again later in the critical section of the
3614 * transaction commit.
3615 */
3616 if (ret == -ENOENT) {
3617 ret = 0;
3618 spin_lock(&cur_trans->dirty_bgs_lock);
3619 if (list_empty(&cache->dirty_list)) {
3620 list_add_tail(&cache->dirty_list,
3621 &cur_trans->dirty_bgs);
3622 btrfs_get_block_group(cache);
3623 }
3624 spin_unlock(&cur_trans->dirty_bgs_lock);
3625 } else if (ret) {
3626 btrfs_abort_transaction(trans, root, ret);
3627 }
3628 }
1bbc621e
CM
3629
3630 /* if its not on the io list, we need to put the block group */
3631 if (should_put)
3632 btrfs_put_block_group(cache);
3633
3634 if (ret)
3635 break;
b58d1a9e
FM
3636
3637 /*
3638 * Avoid blocking other tasks for too long. It might even save
3639 * us from writing caches for block groups that are going to be
3640 * removed.
3641 */
3642 mutex_unlock(&trans->transaction->cache_write_mutex);
3643 mutex_lock(&trans->transaction->cache_write_mutex);
1bbc621e 3644 }
b58d1a9e 3645 mutex_unlock(&trans->transaction->cache_write_mutex);
1bbc621e
CM
3646
3647 /*
3648 * go through delayed refs for all the stuff we've just kicked off
3649 * and then loop back (just once)
3650 */
3651 ret = btrfs_run_delayed_refs(trans, root, 0);
3652 if (!ret && loops == 0) {
3653 loops++;
3654 spin_lock(&cur_trans->dirty_bgs_lock);
3655 list_splice_init(&cur_trans->dirty_bgs, &dirty);
b58d1a9e
FM
3656 /*
3657 * dirty_bgs_lock protects us from concurrent block group
3658 * deletes too (not just cache_write_mutex).
3659 */
3660 if (!list_empty(&dirty)) {
3661 spin_unlock(&cur_trans->dirty_bgs_lock);
3662 goto again;
3663 }
1bbc621e 3664 spin_unlock(&cur_trans->dirty_bgs_lock);
1bbc621e
CM
3665 }
3666
3667 btrfs_free_path(path);
3668 return ret;
3669}
3670
3671int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
3672 struct btrfs_root *root)
3673{
3674 struct btrfs_block_group_cache *cache;
3675 struct btrfs_transaction *cur_trans = trans->transaction;
3676 int ret = 0;
3677 int should_put;
3678 struct btrfs_path *path;
3679 struct list_head *io = &cur_trans->io_bgs;
3680 int num_started = 0;
9078a3e1
CM
3681
3682 path = btrfs_alloc_path();
3683 if (!path)
3684 return -ENOMEM;
3685
ce93ec54
JB
3686 /*
3687 * We don't need the lock here since we are protected by the transaction
3688 * commit. We want to do the cache_save_setup first and then run the
3689 * delayed refs to make sure we have the best chance at doing this all
3690 * in one shot.
3691 */
3692 while (!list_empty(&cur_trans->dirty_bgs)) {
3693 cache = list_first_entry(&cur_trans->dirty_bgs,
3694 struct btrfs_block_group_cache,
3695 dirty_list);
c9dc4c65
CM
3696
3697 /*
3698 * this can happen if cache_save_setup re-dirties a block
3699 * group that is already under IO. Just wait for it to
3700 * finish and then do it all again
3701 */
3702 if (!list_empty(&cache->io_list)) {
3703 list_del_init(&cache->io_list);
3704 btrfs_wait_cache_io(root, trans, cache,
3705 &cache->io_ctl, path,
3706 cache->key.objectid);
3707 btrfs_put_block_group(cache);
c9dc4c65
CM
3708 }
3709
1bbc621e
CM
3710 /*
3711 * don't remove from the dirty list until after we've waited
3712 * on any pending IO
3713 */
ce93ec54 3714 list_del_init(&cache->dirty_list);
c9dc4c65
CM
3715 should_put = 1;
3716
1bbc621e 3717 cache_save_setup(cache, trans, path);
c9dc4c65 3718
ce93ec54 3719 if (!ret)
c9dc4c65
CM
3720 ret = btrfs_run_delayed_refs(trans, root, (unsigned long) -1);
3721
3722 if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
3723 cache->io_ctl.inode = NULL;
3724 ret = btrfs_write_out_cache(root, trans, cache, path);
3725 if (ret == 0 && cache->io_ctl.inode) {
3726 num_started++;
3727 should_put = 0;
1bbc621e 3728 list_add_tail(&cache->io_list, io);
c9dc4c65
CM
3729 } else {
3730 /*
3731 * if we failed to write the cache, the
3732 * generation will be bad and life goes on
3733 */
3734 ret = 0;
3735 }
3736 }
ff1f8250 3737 if (!ret) {
ce93ec54 3738 ret = write_one_cache_group(trans, root, path, cache);
ff1f8250
FM
3739 if (ret)
3740 btrfs_abort_transaction(trans, root, ret);
3741 }
c9dc4c65
CM
3742
3743 /* if its not on the io list, we need to put the block group */
3744 if (should_put)
3745 btrfs_put_block_group(cache);
3746 }
3747
1bbc621e
CM
3748 while (!list_empty(io)) {
3749 cache = list_first_entry(io, struct btrfs_block_group_cache,
c9dc4c65
CM
3750 io_list);
3751 list_del_init(&cache->io_list);
c9dc4c65
CM
3752 btrfs_wait_cache_io(root, trans, cache,
3753 &cache->io_ctl, path, cache->key.objectid);
0cb59c99
JB
3754 btrfs_put_block_group(cache);
3755 }
3756
9078a3e1 3757 btrfs_free_path(path);
ce93ec54 3758 return ret;
9078a3e1
CM
3759}
3760
d2fb3437
YZ
3761int btrfs_extent_readonly(struct btrfs_root *root, u64 bytenr)
3762{
3763 struct btrfs_block_group_cache *block_group;
3764 int readonly = 0;
3765
3766 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
3767 if (!block_group || block_group->ro)
3768 readonly = 1;
3769 if (block_group)
fa9c0d79 3770 btrfs_put_block_group(block_group);
d2fb3437
YZ
3771 return readonly;
3772}
3773
6ab0a202
JM
3774static const char *alloc_name(u64 flags)
3775{
3776 switch (flags) {
3777 case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
3778 return "mixed";
3779 case BTRFS_BLOCK_GROUP_METADATA:
3780 return "metadata";
3781 case BTRFS_BLOCK_GROUP_DATA:
3782 return "data";
3783 case BTRFS_BLOCK_GROUP_SYSTEM:
3784 return "system";
3785 default:
3786 WARN_ON(1);
3787 return "invalid-combination";
3788 };
3789}
3790
593060d7
CM
3791static int update_space_info(struct btrfs_fs_info *info, u64 flags,
3792 u64 total_bytes, u64 bytes_used,
3793 struct btrfs_space_info **space_info)
3794{
3795 struct btrfs_space_info *found;
b742bb82
YZ
3796 int i;
3797 int factor;
b150a4f1 3798 int ret;
b742bb82
YZ
3799
3800 if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
3801 BTRFS_BLOCK_GROUP_RAID10))
3802 factor = 2;
3803 else
3804 factor = 1;
593060d7
CM
3805
3806 found = __find_space_info(info, flags);
3807 if (found) {
25179201 3808 spin_lock(&found->lock);
593060d7 3809 found->total_bytes += total_bytes;
89a55897 3810 found->disk_total += total_bytes * factor;
593060d7 3811 found->bytes_used += bytes_used;
b742bb82 3812 found->disk_used += bytes_used * factor;
2e6e5183
FM
3813 if (total_bytes > 0)
3814 found->full = 0;
25179201 3815 spin_unlock(&found->lock);
593060d7
CM
3816 *space_info = found;
3817 return 0;
3818 }
c146afad 3819 found = kzalloc(sizeof(*found), GFP_NOFS);
593060d7
CM
3820 if (!found)
3821 return -ENOMEM;
3822
908c7f19 3823 ret = percpu_counter_init(&found->total_bytes_pinned, 0, GFP_KERNEL);
b150a4f1
JB
3824 if (ret) {
3825 kfree(found);
3826 return ret;
3827 }
3828
c1895442 3829 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
b742bb82 3830 INIT_LIST_HEAD(&found->block_groups[i]);
80eb234a 3831 init_rwsem(&found->groups_sem);
0f9dd46c 3832 spin_lock_init(&found->lock);
52ba6929 3833 found->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
593060d7 3834 found->total_bytes = total_bytes;
89a55897 3835 found->disk_total = total_bytes * factor;
593060d7 3836 found->bytes_used = bytes_used;
b742bb82 3837 found->disk_used = bytes_used * factor;
593060d7 3838 found->bytes_pinned = 0;
e8569813 3839 found->bytes_reserved = 0;
c146afad 3840 found->bytes_readonly = 0;
f0486c68 3841 found->bytes_may_use = 0;
6af3e3ad 3842 found->full = 0;
4f4db217 3843 found->max_extent_size = 0;
0e4f8f88 3844 found->force_alloc = CHUNK_ALLOC_NO_FORCE;
6d74119f 3845 found->chunk_alloc = 0;
fdb5effd
JB
3846 found->flush = 0;
3847 init_waitqueue_head(&found->wait);
633c0aad 3848 INIT_LIST_HEAD(&found->ro_bgs);
6ab0a202
JM
3849
3850 ret = kobject_init_and_add(&found->kobj, &space_info_ktype,
3851 info->space_info_kobj, "%s",
3852 alloc_name(found->flags));
3853 if (ret) {
3854 kfree(found);
3855 return ret;
3856 }
3857
593060d7 3858 *space_info = found;
4184ea7f 3859 list_add_rcu(&found->list, &info->space_info);
b4d7c3c9
LZ
3860 if (flags & BTRFS_BLOCK_GROUP_DATA)
3861 info->data_sinfo = found;
6ab0a202
JM
3862
3863 return ret;
593060d7
CM
3864}
3865
8790d502
CM
3866static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
3867{
899c81ea
ID
3868 u64 extra_flags = chunk_to_extended(flags) &
3869 BTRFS_EXTENDED_PROFILE_MASK;
a46d11a8 3870
de98ced9 3871 write_seqlock(&fs_info->profiles_lock);
a46d11a8
ID
3872 if (flags & BTRFS_BLOCK_GROUP_DATA)
3873 fs_info->avail_data_alloc_bits |= extra_flags;
3874 if (flags & BTRFS_BLOCK_GROUP_METADATA)
3875 fs_info->avail_metadata_alloc_bits |= extra_flags;
3876 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3877 fs_info->avail_system_alloc_bits |= extra_flags;
de98ced9 3878 write_sequnlock(&fs_info->profiles_lock);
8790d502 3879}
593060d7 3880
fc67c450
ID
3881/*
3882 * returns target flags in extended format or 0 if restripe for this
3883 * chunk_type is not in progress
c6664b42
ID
3884 *
3885 * should be called with either volume_mutex or balance_lock held
fc67c450
ID
3886 */
3887static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
3888{
3889 struct btrfs_balance_control *bctl = fs_info->balance_ctl;
3890 u64 target = 0;
3891
fc67c450
ID
3892 if (!bctl)
3893 return 0;
3894
3895 if (flags & BTRFS_BLOCK_GROUP_DATA &&
3896 bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3897 target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
3898 } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
3899 bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3900 target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
3901 } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
3902 bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
3903 target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
3904 }
3905
3906 return target;
3907}
3908
a46d11a8
ID
3909/*
3910 * @flags: available profiles in extended format (see ctree.h)
3911 *
e4d8ec0f
ID
3912 * Returns reduced profile in chunk format. If profile changing is in
3913 * progress (either running or paused) picks the target profile (if it's
3914 * already available), otherwise falls back to plain reducing.
a46d11a8 3915 */
48a3b636 3916static u64 btrfs_reduce_alloc_profile(struct btrfs_root *root, u64 flags)
ec44a35c 3917{
95669976 3918 u64 num_devices = root->fs_info->fs_devices->rw_devices;
fc67c450 3919 u64 target;
9c170b26
ZL
3920 u64 raid_type;
3921 u64 allowed = 0;
a061fc8d 3922
fc67c450
ID
3923 /*
3924 * see if restripe for this chunk_type is in progress, if so
3925 * try to reduce to the target profile
3926 */
e4d8ec0f 3927 spin_lock(&root->fs_info->balance_lock);
fc67c450
ID
3928 target = get_restripe_target(root->fs_info, flags);
3929 if (target) {
3930 /* pick target profile only if it's already available */
3931 if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
e4d8ec0f 3932 spin_unlock(&root->fs_info->balance_lock);
fc67c450 3933 return extended_to_chunk(target);
e4d8ec0f
ID
3934 }
3935 }
3936 spin_unlock(&root->fs_info->balance_lock);
3937
53b381b3 3938 /* First, mask out the RAID levels which aren't possible */
9c170b26
ZL
3939 for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
3940 if (num_devices >= btrfs_raid_array[raid_type].devs_min)
3941 allowed |= btrfs_raid_group[raid_type];
3942 }
3943 allowed &= flags;
3944
3945 if (allowed & BTRFS_BLOCK_GROUP_RAID6)
3946 allowed = BTRFS_BLOCK_GROUP_RAID6;
3947 else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
3948 allowed = BTRFS_BLOCK_GROUP_RAID5;
3949 else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
3950 allowed = BTRFS_BLOCK_GROUP_RAID10;
3951 else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
3952 allowed = BTRFS_BLOCK_GROUP_RAID1;
3953 else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
3954 allowed = BTRFS_BLOCK_GROUP_RAID0;
3955
3956 flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
3957
3958 return extended_to_chunk(flags | allowed);
ec44a35c
CM
3959}
3960
f8213bdc 3961static u64 get_alloc_profile(struct btrfs_root *root, u64 orig_flags)
6a63209f 3962{
de98ced9 3963 unsigned seq;
f8213bdc 3964 u64 flags;
de98ced9
MX
3965
3966 do {
f8213bdc 3967 flags = orig_flags;
de98ced9
MX
3968 seq = read_seqbegin(&root->fs_info->profiles_lock);
3969
3970 if (flags & BTRFS_BLOCK_GROUP_DATA)
3971 flags |= root->fs_info->avail_data_alloc_bits;
3972 else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
3973 flags |= root->fs_info->avail_system_alloc_bits;
3974 else if (flags & BTRFS_BLOCK_GROUP_METADATA)
3975 flags |= root->fs_info->avail_metadata_alloc_bits;
3976 } while (read_seqretry(&root->fs_info->profiles_lock, seq));
6fef8df1 3977
b742bb82 3978 return btrfs_reduce_alloc_profile(root, flags);
6a63209f
JB
3979}
3980
6d07bcec 3981u64 btrfs_get_alloc_profile(struct btrfs_root *root, int data)
9ed74f2d 3982{
b742bb82 3983 u64 flags;
53b381b3 3984 u64 ret;
9ed74f2d 3985
b742bb82
YZ
3986 if (data)
3987 flags = BTRFS_BLOCK_GROUP_DATA;
3988 else if (root == root->fs_info->chunk_root)
3989 flags = BTRFS_BLOCK_GROUP_SYSTEM;
9ed74f2d 3990 else
b742bb82 3991 flags = BTRFS_BLOCK_GROUP_METADATA;
9ed74f2d 3992
53b381b3
DW
3993 ret = get_alloc_profile(root, flags);
3994 return ret;
6a63209f 3995}
9ed74f2d 3996
4ceff079 3997int btrfs_alloc_data_chunk_ondemand(struct inode *inode, u64 bytes)
6a63209f 3998{
6a63209f 3999 struct btrfs_space_info *data_sinfo;
0ca1f7ce 4000 struct btrfs_root *root = BTRFS_I(inode)->root;
b4d7c3c9 4001 struct btrfs_fs_info *fs_info = root->fs_info;
ab6e2410 4002 u64 used;
94b947b2 4003 int ret = 0;
c99f1b0c
ZL
4004 int need_commit = 2;
4005 int have_pinned_space;
6a63209f 4006
6a63209f 4007 /* make sure bytes are sectorsize aligned */
fda2832f 4008 bytes = ALIGN(bytes, root->sectorsize);
6a63209f 4009
9dced186 4010 if (btrfs_is_free_space_inode(inode)) {
c99f1b0c 4011 need_commit = 0;
9dced186 4012 ASSERT(current->journal_info);
0af3d00b
JB
4013 }
4014
b4d7c3c9 4015 data_sinfo = fs_info->data_sinfo;
33b4d47f
CM
4016 if (!data_sinfo)
4017 goto alloc;
9ed74f2d 4018
6a63209f
JB
4019again:
4020 /* make sure we have enough space to handle the data first */
4021 spin_lock(&data_sinfo->lock);
8929ecfa
YZ
4022 used = data_sinfo->bytes_used + data_sinfo->bytes_reserved +
4023 data_sinfo->bytes_pinned + data_sinfo->bytes_readonly +
4024 data_sinfo->bytes_may_use;
ab6e2410
JB
4025
4026 if (used + bytes > data_sinfo->total_bytes) {
4e06bdd6 4027 struct btrfs_trans_handle *trans;
9ed74f2d 4028
6a63209f
JB
4029 /*
4030 * if we don't have enough free bytes in this space then we need
4031 * to alloc a new chunk.
4032 */
b9fd47cd 4033 if (!data_sinfo->full) {
6a63209f 4034 u64 alloc_target;
9ed74f2d 4035
0e4f8f88 4036 data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
6a63209f 4037 spin_unlock(&data_sinfo->lock);
33b4d47f 4038alloc:
6a63209f 4039 alloc_target = btrfs_get_alloc_profile(root, 1);
9dced186
MX
4040 /*
4041 * It is ugly that we don't call nolock join
4042 * transaction for the free space inode case here.
4043 * But it is safe because we only do the data space
4044 * reservation for the free space cache in the
4045 * transaction context, the common join transaction
4046 * just increase the counter of the current transaction
4047 * handler, doesn't try to acquire the trans_lock of
4048 * the fs.
4049 */
7a7eaa40 4050 trans = btrfs_join_transaction(root);
a22285a6
YZ
4051 if (IS_ERR(trans))
4052 return PTR_ERR(trans);
9ed74f2d 4053
6a63209f 4054 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
0e4f8f88
CM
4055 alloc_target,
4056 CHUNK_ALLOC_NO_FORCE);
6a63209f 4057 btrfs_end_transaction(trans, root);
d52a5b5f
MX
4058 if (ret < 0) {
4059 if (ret != -ENOSPC)
4060 return ret;
c99f1b0c
ZL
4061 else {
4062 have_pinned_space = 1;
d52a5b5f 4063 goto commit_trans;
c99f1b0c 4064 }
d52a5b5f 4065 }
9ed74f2d 4066
b4d7c3c9
LZ
4067 if (!data_sinfo)
4068 data_sinfo = fs_info->data_sinfo;
4069
6a63209f
JB
4070 goto again;
4071 }
f2bb8f5c
JB
4072
4073 /*
b150a4f1 4074 * If we don't have enough pinned space to deal with this
94b947b2
ZL
4075 * allocation, and no removed chunk in current transaction,
4076 * don't bother committing the transaction.
f2bb8f5c 4077 */
c99f1b0c
ZL
4078 have_pinned_space = percpu_counter_compare(
4079 &data_sinfo->total_bytes_pinned,
4080 used + bytes - data_sinfo->total_bytes);
6a63209f 4081 spin_unlock(&data_sinfo->lock);
6a63209f 4082
4e06bdd6 4083 /* commit the current transaction and try again */
d52a5b5f 4084commit_trans:
c99f1b0c 4085 if (need_commit &&
a4abeea4 4086 !atomic_read(&root->fs_info->open_ioctl_trans)) {
c99f1b0c 4087 need_commit--;
b150a4f1 4088
9a4e7276
ZL
4089 if (need_commit > 0)
4090 btrfs_wait_ordered_roots(fs_info, -1);
4091
7a7eaa40 4092 trans = btrfs_join_transaction(root);
a22285a6
YZ
4093 if (IS_ERR(trans))
4094 return PTR_ERR(trans);
c99f1b0c 4095 if (have_pinned_space >= 0 ||
3204d33c
JB
4096 test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
4097 &trans->transaction->flags) ||
c99f1b0c 4098 need_commit > 0) {
94b947b2
ZL
4099 ret = btrfs_commit_transaction(trans, root);
4100 if (ret)
4101 return ret;
d7c15171
ZL
4102 /*
4103 * make sure that all running delayed iput are
4104 * done
4105 */
4106 down_write(&root->fs_info->delayed_iput_sem);
4107 up_write(&root->fs_info->delayed_iput_sem);
94b947b2
ZL
4108 goto again;
4109 } else {
4110 btrfs_end_transaction(trans, root);
4111 }
4e06bdd6 4112 }
9ed74f2d 4113
cab45e22
JM
4114 trace_btrfs_space_reservation(root->fs_info,
4115 "space_info:enospc",
4116 data_sinfo->flags, bytes, 1);
6a63209f
JB
4117 return -ENOSPC;
4118 }
4119 data_sinfo->bytes_may_use += bytes;
8c2a3ca2 4120 trace_btrfs_space_reservation(root->fs_info, "space_info",
2bcc0328 4121 data_sinfo->flags, bytes, 1);
6a63209f 4122 spin_unlock(&data_sinfo->lock);
6a63209f 4123
237c0e9f 4124 return ret;
9ed74f2d 4125}
6a63209f 4126
4ceff079
QW
4127/*
4128 * New check_data_free_space() with ability for precious data reservation
4129 * Will replace old btrfs_check_data_free_space(), but for patch split,
4130 * add a new function first and then replace it.
4131 */
7cf5b976 4132int btrfs_check_data_free_space(struct inode *inode, u64 start, u64 len)
4ceff079
QW
4133{
4134 struct btrfs_root *root = BTRFS_I(inode)->root;
4135 int ret;
4136
4137 /* align the range */
4138 len = round_up(start + len, root->sectorsize) -
4139 round_down(start, root->sectorsize);
4140 start = round_down(start, root->sectorsize);
4141
4142 ret = btrfs_alloc_data_chunk_ondemand(inode, len);
4143 if (ret < 0)
4144 return ret;
4145
94ed938a
QW
4146 /*
4147 * Use new btrfs_qgroup_reserve_data to reserve precious data space
4148 *
4149 * TODO: Find a good method to avoid reserve data space for NOCOW
4150 * range, but don't impact performance on quota disable case.
4151 */
4ceff079
QW
4152 ret = btrfs_qgroup_reserve_data(inode, start, len);
4153 return ret;
4154}
4155
4ceff079
QW
4156/*
4157 * Called if we need to clear a data reservation for this inode
4158 * Normally in a error case.
4159 *
51773bec
QW
4160 * This one will *NOT* use accurate qgroup reserved space API, just for case
4161 * which we can't sleep and is sure it won't affect qgroup reserved space.
4162 * Like clear_bit_hook().
4ceff079 4163 */
51773bec
QW
4164void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
4165 u64 len)
4ceff079
QW
4166{
4167 struct btrfs_root *root = BTRFS_I(inode)->root;
4168 struct btrfs_space_info *data_sinfo;
4169
4170 /* Make sure the range is aligned to sectorsize */
4171 len = round_up(start + len, root->sectorsize) -
4172 round_down(start, root->sectorsize);
4173 start = round_down(start, root->sectorsize);
4174
4ceff079
QW
4175 data_sinfo = root->fs_info->data_sinfo;
4176 spin_lock(&data_sinfo->lock);
4177 if (WARN_ON(data_sinfo->bytes_may_use < len))
4178 data_sinfo->bytes_may_use = 0;
4179 else
4180 data_sinfo->bytes_may_use -= len;
4181 trace_btrfs_space_reservation(root->fs_info, "space_info",
4182 data_sinfo->flags, len, 0);
4183 spin_unlock(&data_sinfo->lock);
4184}
4185
51773bec
QW
4186/*
4187 * Called if we need to clear a data reservation for this inode
4188 * Normally in a error case.
4189 *
4190 * This one will handle the per-indoe data rsv map for accurate reserved
4191 * space framework.
4192 */
4193void btrfs_free_reserved_data_space(struct inode *inode, u64 start, u64 len)
4194{
4195 btrfs_free_reserved_data_space_noquota(inode, start, len);
4196 btrfs_qgroup_free_data(inode, start, len);
4197}
4198
97e728d4 4199static void force_metadata_allocation(struct btrfs_fs_info *info)
e3ccfa98 4200{
97e728d4
JB
4201 struct list_head *head = &info->space_info;
4202 struct btrfs_space_info *found;
e3ccfa98 4203
97e728d4
JB
4204 rcu_read_lock();
4205 list_for_each_entry_rcu(found, head, list) {
4206 if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
0e4f8f88 4207 found->force_alloc = CHUNK_ALLOC_FORCE;
e3ccfa98 4208 }
97e728d4 4209 rcu_read_unlock();
e3ccfa98
JB
4210}
4211
3c76cd84
MX
4212static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
4213{
4214 return (global->size << 1);
4215}
4216
e5bc2458 4217static int should_alloc_chunk(struct btrfs_root *root,
698d0082 4218 struct btrfs_space_info *sinfo, int force)
32c00aff 4219{
fb25e914 4220 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
424499db 4221 u64 num_bytes = sinfo->total_bytes - sinfo->bytes_readonly;
0e4f8f88 4222 u64 num_allocated = sinfo->bytes_used + sinfo->bytes_reserved;
e5bc2458 4223 u64 thresh;
e3ccfa98 4224
0e4f8f88
CM
4225 if (force == CHUNK_ALLOC_FORCE)
4226 return 1;
4227
fb25e914
JB
4228 /*
4229 * We need to take into account the global rsv because for all intents
4230 * and purposes it's used space. Don't worry about locking the
4231 * global_rsv, it doesn't change except when the transaction commits.
4232 */
54338b5c 4233 if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
3c76cd84 4234 num_allocated += calc_global_rsv_need_space(global_rsv);
fb25e914 4235
0e4f8f88
CM
4236 /*
4237 * in limited mode, we want to have some free space up to
4238 * about 1% of the FS size.
4239 */
4240 if (force == CHUNK_ALLOC_LIMITED) {
6c41761f 4241 thresh = btrfs_super_total_bytes(root->fs_info->super_copy);
0e4f8f88
CM
4242 thresh = max_t(u64, 64 * 1024 * 1024,
4243 div_factor_fine(thresh, 1));
4244
4245 if (num_bytes - num_allocated < thresh)
4246 return 1;
4247 }
0e4f8f88 4248
698d0082 4249 if (num_allocated + 2 * 1024 * 1024 < div_factor(num_bytes, 8))
14ed0ca6 4250 return 0;
424499db 4251 return 1;
32c00aff
JB
4252}
4253
39c2d7fa 4254static u64 get_profile_num_devs(struct btrfs_root *root, u64 type)
15d1ff81
LB
4255{
4256 u64 num_dev;
4257
53b381b3
DW
4258 if (type & (BTRFS_BLOCK_GROUP_RAID10 |
4259 BTRFS_BLOCK_GROUP_RAID0 |
4260 BTRFS_BLOCK_GROUP_RAID5 |
4261 BTRFS_BLOCK_GROUP_RAID6))
15d1ff81
LB
4262 num_dev = root->fs_info->fs_devices->rw_devices;
4263 else if (type & BTRFS_BLOCK_GROUP_RAID1)
4264 num_dev = 2;
4265 else
4266 num_dev = 1; /* DUP or single */
4267
39c2d7fa 4268 return num_dev;
15d1ff81
LB
4269}
4270
39c2d7fa
FM
4271/*
4272 * If @is_allocation is true, reserve space in the system space info necessary
4273 * for allocating a chunk, otherwise if it's false, reserve space necessary for
4274 * removing a chunk.
4275 */
4276void check_system_chunk(struct btrfs_trans_handle *trans,
4277 struct btrfs_root *root,
4617ea3a 4278 u64 type)
15d1ff81
LB
4279{
4280 struct btrfs_space_info *info;
4281 u64 left;
4282 u64 thresh;
4fbcdf66 4283 int ret = 0;
39c2d7fa 4284 u64 num_devs;
4fbcdf66
FM
4285
4286 /*
4287 * Needed because we can end up allocating a system chunk and for an
4288 * atomic and race free space reservation in the chunk block reserve.
4289 */
4290 ASSERT(mutex_is_locked(&root->fs_info->chunk_mutex));
15d1ff81
LB
4291
4292 info = __find_space_info(root->fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
4293 spin_lock(&info->lock);
4294 left = info->total_bytes - info->bytes_used - info->bytes_pinned -
4fbcdf66
FM
4295 info->bytes_reserved - info->bytes_readonly -
4296 info->bytes_may_use;
15d1ff81
LB
4297 spin_unlock(&info->lock);
4298
39c2d7fa
FM
4299 num_devs = get_profile_num_devs(root, type);
4300
4301 /* num_devs device items to update and 1 chunk item to add or remove */
4617ea3a
FM
4302 thresh = btrfs_calc_trunc_metadata_size(root, num_devs) +
4303 btrfs_calc_trans_metadata_size(root, 1);
39c2d7fa 4304
15d1ff81 4305 if (left < thresh && btrfs_test_opt(root, ENOSPC_DEBUG)) {
c2cf52eb
SK
4306 btrfs_info(root->fs_info, "left=%llu, need=%llu, flags=%llu",
4307 left, thresh, type);
15d1ff81
LB
4308 dump_space_info(info, 0, 0);
4309 }
4310
4311 if (left < thresh) {
4312 u64 flags;
4313
4314 flags = btrfs_get_alloc_profile(root->fs_info->chunk_root, 0);
4fbcdf66
FM
4315 /*
4316 * Ignore failure to create system chunk. We might end up not
4317 * needing it, as we might not need to COW all nodes/leafs from
4318 * the paths we visit in the chunk tree (they were already COWed
4319 * or created in the current transaction for example).
4320 */
4321 ret = btrfs_alloc_chunk(trans, root, flags);
4322 }
4323
4324 if (!ret) {
4325 ret = btrfs_block_rsv_add(root->fs_info->chunk_root,
4326 &root->fs_info->chunk_block_rsv,
4327 thresh, BTRFS_RESERVE_NO_FLUSH);
4328 if (!ret)
4329 trans->chunk_bytes_reserved += thresh;
15d1ff81
LB
4330 }
4331}
4332
6324fbf3 4333static int do_chunk_alloc(struct btrfs_trans_handle *trans,
698d0082 4334 struct btrfs_root *extent_root, u64 flags, int force)
9ed74f2d 4335{
6324fbf3 4336 struct btrfs_space_info *space_info;
97e728d4 4337 struct btrfs_fs_info *fs_info = extent_root->fs_info;
6d74119f 4338 int wait_for_alloc = 0;
9ed74f2d 4339 int ret = 0;
9ed74f2d 4340
c6b305a8
JB
4341 /* Don't re-enter if we're already allocating a chunk */
4342 if (trans->allocating_chunk)
4343 return -ENOSPC;
4344
6324fbf3 4345 space_info = __find_space_info(extent_root->fs_info, flags);
593060d7
CM
4346 if (!space_info) {
4347 ret = update_space_info(extent_root->fs_info, flags,
4348 0, 0, &space_info);
79787eaa 4349 BUG_ON(ret); /* -ENOMEM */
9ed74f2d 4350 }
79787eaa 4351 BUG_ON(!space_info); /* Logic error */
9ed74f2d 4352
6d74119f 4353again:
25179201 4354 spin_lock(&space_info->lock);
9e622d6b 4355 if (force < space_info->force_alloc)
0e4f8f88 4356 force = space_info->force_alloc;
25179201 4357 if (space_info->full) {
09fb99a6
FDBM
4358 if (should_alloc_chunk(extent_root, space_info, force))
4359 ret = -ENOSPC;
4360 else
4361 ret = 0;
25179201 4362 spin_unlock(&space_info->lock);
09fb99a6 4363 return ret;
9ed74f2d
JB
4364 }
4365
698d0082 4366 if (!should_alloc_chunk(extent_root, space_info, force)) {
25179201 4367 spin_unlock(&space_info->lock);
6d74119f
JB
4368 return 0;
4369 } else if (space_info->chunk_alloc) {
4370 wait_for_alloc = 1;
4371 } else {
4372 space_info->chunk_alloc = 1;
9ed74f2d 4373 }
0e4f8f88 4374
25179201 4375 spin_unlock(&space_info->lock);
9ed74f2d 4376
6d74119f
JB
4377 mutex_lock(&fs_info->chunk_mutex);
4378
4379 /*
4380 * The chunk_mutex is held throughout the entirety of a chunk
4381 * allocation, so once we've acquired the chunk_mutex we know that the
4382 * other guy is done and we need to recheck and see if we should
4383 * allocate.
4384 */
4385 if (wait_for_alloc) {
4386 mutex_unlock(&fs_info->chunk_mutex);
4387 wait_for_alloc = 0;
4388 goto again;
4389 }
4390
c6b305a8
JB
4391 trans->allocating_chunk = true;
4392
67377734
JB
4393 /*
4394 * If we have mixed data/metadata chunks we want to make sure we keep
4395 * allocating mixed chunks instead of individual chunks.
4396 */
4397 if (btrfs_mixed_space_info(space_info))
4398 flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
4399
97e728d4
JB
4400 /*
4401 * if we're doing a data chunk, go ahead and make sure that
4402 * we keep a reasonable number of metadata chunks allocated in the
4403 * FS as well.
4404 */
9ed74f2d 4405 if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
97e728d4
JB
4406 fs_info->data_chunk_allocations++;
4407 if (!(fs_info->data_chunk_allocations %
4408 fs_info->metadata_ratio))
4409 force_metadata_allocation(fs_info);
9ed74f2d
JB
4410 }
4411
15d1ff81
LB
4412 /*
4413 * Check if we have enough space in SYSTEM chunk because we may need
4414 * to update devices.
4415 */
4617ea3a 4416 check_system_chunk(trans, extent_root, flags);
15d1ff81 4417
2b82032c 4418 ret = btrfs_alloc_chunk(trans, extent_root, flags);
c6b305a8 4419 trans->allocating_chunk = false;
92b8e897 4420
9ed74f2d 4421 spin_lock(&space_info->lock);
a81cb9a2
AO
4422 if (ret < 0 && ret != -ENOSPC)
4423 goto out;
9ed74f2d 4424 if (ret)
6324fbf3 4425 space_info->full = 1;
424499db
YZ
4426 else
4427 ret = 1;
6d74119f 4428
0e4f8f88 4429 space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
a81cb9a2 4430out:
6d74119f 4431 space_info->chunk_alloc = 0;
9ed74f2d 4432 spin_unlock(&space_info->lock);
a25c75d5 4433 mutex_unlock(&fs_info->chunk_mutex);
00d80e34
FM
4434 /*
4435 * When we allocate a new chunk we reserve space in the chunk block
4436 * reserve to make sure we can COW nodes/leafs in the chunk tree or
4437 * add new nodes/leafs to it if we end up needing to do it when
4438 * inserting the chunk item and updating device items as part of the
4439 * second phase of chunk allocation, performed by
4440 * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
4441 * large number of new block groups to create in our transaction
4442 * handle's new_bgs list to avoid exhausting the chunk block reserve
4443 * in extreme cases - like having a single transaction create many new
4444 * block groups when starting to write out the free space caches of all
4445 * the block groups that were made dirty during the lifetime of the
4446 * transaction.
4447 */
d9a0540a
FM
4448 if (trans->can_flush_pending_bgs &&
4449 trans->chunk_bytes_reserved >= (2 * 1024 * 1024ull)) {
00d80e34
FM
4450 btrfs_create_pending_block_groups(trans, trans->root);
4451 btrfs_trans_release_chunk_metadata(trans);
4452 }
0f9dd46c 4453 return ret;
6324fbf3 4454}
9ed74f2d 4455
a80c8dcf
JB
4456static int can_overcommit(struct btrfs_root *root,
4457 struct btrfs_space_info *space_info, u64 bytes,
08e007d2 4458 enum btrfs_reserve_flush_enum flush)
a80c8dcf 4459{
96f1bb57 4460 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
a80c8dcf 4461 u64 profile = btrfs_get_alloc_profile(root, 0);
3c76cd84 4462 u64 space_size;
a80c8dcf
JB
4463 u64 avail;
4464 u64 used;
4465
4466 used = space_info->bytes_used + space_info->bytes_reserved +
96f1bb57
JB
4467 space_info->bytes_pinned + space_info->bytes_readonly;
4468
96f1bb57
JB
4469 /*
4470 * We only want to allow over committing if we have lots of actual space
4471 * free, but if we don't have enough space to handle the global reserve
4472 * space then we could end up having a real enospc problem when trying
4473 * to allocate a chunk or some other such important allocation.
4474 */
3c76cd84
MX
4475 spin_lock(&global_rsv->lock);
4476 space_size = calc_global_rsv_need_space(global_rsv);
4477 spin_unlock(&global_rsv->lock);
4478 if (used + space_size >= space_info->total_bytes)
96f1bb57
JB
4479 return 0;
4480
4481 used += space_info->bytes_may_use;
a80c8dcf
JB
4482
4483 spin_lock(&root->fs_info->free_chunk_lock);
4484 avail = root->fs_info->free_chunk_space;
4485 spin_unlock(&root->fs_info->free_chunk_lock);
4486
4487 /*
4488 * If we have dup, raid1 or raid10 then only half of the free
53b381b3
DW
4489 * space is actually useable. For raid56, the space info used
4490 * doesn't include the parity drive, so we don't have to
4491 * change the math
a80c8dcf
JB
4492 */
4493 if (profile & (BTRFS_BLOCK_GROUP_DUP |
4494 BTRFS_BLOCK_GROUP_RAID1 |
4495 BTRFS_BLOCK_GROUP_RAID10))
4496 avail >>= 1;
4497
4498 /*
561c294d
MX
4499 * If we aren't flushing all things, let us overcommit up to
4500 * 1/2th of the space. If we can flush, don't let us overcommit
4501 * too much, let it overcommit up to 1/8 of the space.
a80c8dcf 4502 */
08e007d2 4503 if (flush == BTRFS_RESERVE_FLUSH_ALL)
14575aef 4504 avail >>= 3;
a80c8dcf 4505 else
14575aef 4506 avail >>= 1;
a80c8dcf 4507
14575aef 4508 if (used + bytes < space_info->total_bytes + avail)
a80c8dcf
JB
4509 return 1;
4510 return 0;
4511}
4512
48a3b636 4513static void btrfs_writeback_inodes_sb_nr(struct btrfs_root *root,
6c255e67 4514 unsigned long nr_pages, int nr_items)
da633a42
MX
4515{
4516 struct super_block *sb = root->fs_info->sb;
da633a42 4517
925a6efb
JB
4518 if (down_read_trylock(&sb->s_umount)) {
4519 writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
4520 up_read(&sb->s_umount);
4521 } else {
da633a42
MX
4522 /*
4523 * We needn't worry the filesystem going from r/w to r/o though
4524 * we don't acquire ->s_umount mutex, because the filesystem
4525 * should guarantee the delalloc inodes list be empty after
4526 * the filesystem is readonly(all dirty pages are written to
4527 * the disk).
4528 */
6c255e67 4529 btrfs_start_delalloc_roots(root->fs_info, 0, nr_items);
98ad69cf 4530 if (!current->journal_info)
6c255e67 4531 btrfs_wait_ordered_roots(root->fs_info, nr_items);
da633a42
MX
4532 }
4533}
4534
18cd8ea6
MX
4535static inline int calc_reclaim_items_nr(struct btrfs_root *root, u64 to_reclaim)
4536{
4537 u64 bytes;
4538 int nr;
4539
4540 bytes = btrfs_calc_trans_metadata_size(root, 1);
4541 nr = (int)div64_u64(to_reclaim, bytes);
4542 if (!nr)
4543 nr = 1;
4544 return nr;
4545}
4546
c61a16a7
MX
4547#define EXTENT_SIZE_PER_ITEM (256 * 1024)
4548
9ed74f2d 4549/*
5da9d01b 4550 * shrink metadata reservation for delalloc
9ed74f2d 4551 */
f4c738c2
JB
4552static void shrink_delalloc(struct btrfs_root *root, u64 to_reclaim, u64 orig,
4553 bool wait_ordered)
5da9d01b 4554{
0ca1f7ce 4555 struct btrfs_block_rsv *block_rsv;
0019f10d 4556 struct btrfs_space_info *space_info;
663350ac 4557 struct btrfs_trans_handle *trans;
f4c738c2 4558 u64 delalloc_bytes;
5da9d01b 4559 u64 max_reclaim;
b1953bce 4560 long time_left;
d3ee29e3
MX
4561 unsigned long nr_pages;
4562 int loops;
b0244199 4563 int items;
08e007d2 4564 enum btrfs_reserve_flush_enum flush;
5da9d01b 4565
c61a16a7 4566 /* Calc the number of the pages we need flush for space reservation */
b0244199
MX
4567 items = calc_reclaim_items_nr(root, to_reclaim);
4568 to_reclaim = items * EXTENT_SIZE_PER_ITEM;
c61a16a7 4569
663350ac 4570 trans = (struct btrfs_trans_handle *)current->journal_info;
0ca1f7ce 4571 block_rsv = &root->fs_info->delalloc_block_rsv;
0019f10d 4572 space_info = block_rsv->space_info;
bf9022e0 4573
963d678b
MX
4574 delalloc_bytes = percpu_counter_sum_positive(
4575 &root->fs_info->delalloc_bytes);
f4c738c2 4576 if (delalloc_bytes == 0) {
fdb5effd 4577 if (trans)
f4c738c2 4578 return;
38c135af 4579 if (wait_ordered)
b0244199 4580 btrfs_wait_ordered_roots(root->fs_info, items);
f4c738c2 4581 return;
fdb5effd
JB
4582 }
4583
d3ee29e3 4584 loops = 0;
f4c738c2
JB
4585 while (delalloc_bytes && loops < 3) {
4586 max_reclaim = min(delalloc_bytes, to_reclaim);
4587 nr_pages = max_reclaim >> PAGE_CACHE_SHIFT;
6c255e67 4588 btrfs_writeback_inodes_sb_nr(root, nr_pages, items);
dea31f52
JB
4589 /*
4590 * We need to wait for the async pages to actually start before
4591 * we do anything.
4592 */
9f3a074d
MX
4593 max_reclaim = atomic_read(&root->fs_info->async_delalloc_pages);
4594 if (!max_reclaim)
4595 goto skip_async;
4596
4597 if (max_reclaim <= nr_pages)
4598 max_reclaim = 0;
4599 else
4600 max_reclaim -= nr_pages;
dea31f52 4601
9f3a074d
MX
4602 wait_event(root->fs_info->async_submit_wait,
4603 atomic_read(&root->fs_info->async_delalloc_pages) <=
4604 (int)max_reclaim);
4605skip_async:
08e007d2
MX
4606 if (!trans)
4607 flush = BTRFS_RESERVE_FLUSH_ALL;
4608 else
4609 flush = BTRFS_RESERVE_NO_FLUSH;
0019f10d 4610 spin_lock(&space_info->lock);
08e007d2 4611 if (can_overcommit(root, space_info, orig, flush)) {
f4c738c2
JB
4612 spin_unlock(&space_info->lock);
4613 break;
4614 }
0019f10d 4615 spin_unlock(&space_info->lock);
5da9d01b 4616
36e39c40 4617 loops++;
f104d044 4618 if (wait_ordered && !trans) {
b0244199 4619 btrfs_wait_ordered_roots(root->fs_info, items);
f104d044 4620 } else {
f4c738c2 4621 time_left = schedule_timeout_killable(1);
f104d044
JB
4622 if (time_left)
4623 break;
4624 }
963d678b
MX
4625 delalloc_bytes = percpu_counter_sum_positive(
4626 &root->fs_info->delalloc_bytes);
5da9d01b 4627 }
5da9d01b
YZ
4628}
4629
663350ac
JB
4630/**
4631 * maybe_commit_transaction - possibly commit the transaction if its ok to
4632 * @root - the root we're allocating for
4633 * @bytes - the number of bytes we want to reserve
4634 * @force - force the commit
8bb8ab2e 4635 *
663350ac
JB
4636 * This will check to make sure that committing the transaction will actually
4637 * get us somewhere and then commit the transaction if it does. Otherwise it
4638 * will return -ENOSPC.
8bb8ab2e 4639 */
663350ac
JB
4640static int may_commit_transaction(struct btrfs_root *root,
4641 struct btrfs_space_info *space_info,
4642 u64 bytes, int force)
4643{
4644 struct btrfs_block_rsv *delayed_rsv = &root->fs_info->delayed_block_rsv;
4645 struct btrfs_trans_handle *trans;
4646
4647 trans = (struct btrfs_trans_handle *)current->journal_info;
4648 if (trans)
4649 return -EAGAIN;
4650
4651 if (force)
4652 goto commit;
4653
4654 /* See if there is enough pinned space to make this reservation */
b150a4f1 4655 if (percpu_counter_compare(&space_info->total_bytes_pinned,
0424c548 4656 bytes) >= 0)
663350ac 4657 goto commit;
663350ac
JB
4658
4659 /*
4660 * See if there is some space in the delayed insertion reservation for
4661 * this reservation.
4662 */
4663 if (space_info != delayed_rsv->space_info)
4664 return -ENOSPC;
4665
4666 spin_lock(&delayed_rsv->lock);
b150a4f1
JB
4667 if (percpu_counter_compare(&space_info->total_bytes_pinned,
4668 bytes - delayed_rsv->size) >= 0) {
663350ac
JB
4669 spin_unlock(&delayed_rsv->lock);
4670 return -ENOSPC;
4671 }
4672 spin_unlock(&delayed_rsv->lock);
4673
4674commit:
4675 trans = btrfs_join_transaction(root);
4676 if (IS_ERR(trans))
4677 return -ENOSPC;
4678
4679 return btrfs_commit_transaction(trans, root);
4680}
4681
96c3f433 4682enum flush_state {
67b0fd63
JB
4683 FLUSH_DELAYED_ITEMS_NR = 1,
4684 FLUSH_DELAYED_ITEMS = 2,
4685 FLUSH_DELALLOC = 3,
4686 FLUSH_DELALLOC_WAIT = 4,
ea658bad
JB
4687 ALLOC_CHUNK = 5,
4688 COMMIT_TRANS = 6,
96c3f433
JB
4689};
4690
4691static int flush_space(struct btrfs_root *root,
4692 struct btrfs_space_info *space_info, u64 num_bytes,
4693 u64 orig_bytes, int state)
4694{
4695 struct btrfs_trans_handle *trans;
4696 int nr;
f4c738c2 4697 int ret = 0;
96c3f433
JB
4698
4699 switch (state) {
96c3f433
JB
4700 case FLUSH_DELAYED_ITEMS_NR:
4701 case FLUSH_DELAYED_ITEMS:
18cd8ea6
MX
4702 if (state == FLUSH_DELAYED_ITEMS_NR)
4703 nr = calc_reclaim_items_nr(root, num_bytes) * 2;
4704 else
96c3f433 4705 nr = -1;
18cd8ea6 4706
96c3f433
JB
4707 trans = btrfs_join_transaction(root);
4708 if (IS_ERR(trans)) {
4709 ret = PTR_ERR(trans);
4710 break;
4711 }
4712 ret = btrfs_run_delayed_items_nr(trans, root, nr);
4713 btrfs_end_transaction(trans, root);
4714 break;
67b0fd63
JB
4715 case FLUSH_DELALLOC:
4716 case FLUSH_DELALLOC_WAIT:
24af7dd1 4717 shrink_delalloc(root, num_bytes * 2, orig_bytes,
67b0fd63
JB
4718 state == FLUSH_DELALLOC_WAIT);
4719 break;
ea658bad
JB
4720 case ALLOC_CHUNK:
4721 trans = btrfs_join_transaction(root);
4722 if (IS_ERR(trans)) {
4723 ret = PTR_ERR(trans);
4724 break;
4725 }
4726 ret = do_chunk_alloc(trans, root->fs_info->extent_root,
ea658bad
JB
4727 btrfs_get_alloc_profile(root, 0),
4728 CHUNK_ALLOC_NO_FORCE);
4729 btrfs_end_transaction(trans, root);
4730 if (ret == -ENOSPC)
4731 ret = 0;
4732 break;
96c3f433
JB
4733 case COMMIT_TRANS:
4734 ret = may_commit_transaction(root, space_info, orig_bytes, 0);
4735 break;
4736 default:
4737 ret = -ENOSPC;
4738 break;
4739 }
4740
4741 return ret;
4742}
21c7e756
MX
4743
4744static inline u64
4745btrfs_calc_reclaim_metadata_size(struct btrfs_root *root,
4746 struct btrfs_space_info *space_info)
4747{
4748 u64 used;
4749 u64 expected;
4750 u64 to_reclaim;
4751
4752 to_reclaim = min_t(u64, num_online_cpus() * 1024 * 1024,
4753 16 * 1024 * 1024);
4754 spin_lock(&space_info->lock);
4755 if (can_overcommit(root, space_info, to_reclaim,
4756 BTRFS_RESERVE_FLUSH_ALL)) {
4757 to_reclaim = 0;
4758 goto out;
4759 }
4760
4761 used = space_info->bytes_used + space_info->bytes_reserved +
4762 space_info->bytes_pinned + space_info->bytes_readonly +
4763 space_info->bytes_may_use;
4764 if (can_overcommit(root, space_info, 1024 * 1024,
4765 BTRFS_RESERVE_FLUSH_ALL))
4766 expected = div_factor_fine(space_info->total_bytes, 95);
4767 else
4768 expected = div_factor_fine(space_info->total_bytes, 90);
4769
4770 if (used > expected)
4771 to_reclaim = used - expected;
4772 else
4773 to_reclaim = 0;
4774 to_reclaim = min(to_reclaim, space_info->bytes_may_use +
4775 space_info->bytes_reserved);
4776out:
4777 spin_unlock(&space_info->lock);
4778
4779 return to_reclaim;
4780}
4781
4782static inline int need_do_async_reclaim(struct btrfs_space_info *space_info,
4783 struct btrfs_fs_info *fs_info, u64 used)
4784{
365c5313
JB
4785 u64 thresh = div_factor_fine(space_info->total_bytes, 98);
4786
4787 /* If we're just plain full then async reclaim just slows us down. */
4788 if (space_info->bytes_used >= thresh)
4789 return 0;
4790
4791 return (used >= thresh && !btrfs_fs_closing(fs_info) &&
21c7e756
MX
4792 !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
4793}
4794
4795static int btrfs_need_do_async_reclaim(struct btrfs_space_info *space_info,
25ce459c
LB
4796 struct btrfs_fs_info *fs_info,
4797 int flush_state)
21c7e756
MX
4798{
4799 u64 used;
4800
4801 spin_lock(&space_info->lock);
25ce459c
LB
4802 /*
4803 * We run out of space and have not got any free space via flush_space,
4804 * so don't bother doing async reclaim.
4805 */
4806 if (flush_state > COMMIT_TRANS && space_info->full) {
4807 spin_unlock(&space_info->lock);
4808 return 0;
4809 }
4810
21c7e756
MX
4811 used = space_info->bytes_used + space_info->bytes_reserved +
4812 space_info->bytes_pinned + space_info->bytes_readonly +
4813 space_info->bytes_may_use;
4814 if (need_do_async_reclaim(space_info, fs_info, used)) {
4815 spin_unlock(&space_info->lock);
4816 return 1;
4817 }
4818 spin_unlock(&space_info->lock);
4819
4820 return 0;
4821}
4822
4823static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
4824{
4825 struct btrfs_fs_info *fs_info;
4826 struct btrfs_space_info *space_info;
4827 u64 to_reclaim;
4828 int flush_state;
4829
4830 fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
4831 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
4832
4833 to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info->fs_root,
4834 space_info);
4835 if (!to_reclaim)
4836 return;
4837
4838 flush_state = FLUSH_DELAYED_ITEMS_NR;
4839 do {
4840 flush_space(fs_info->fs_root, space_info, to_reclaim,
4841 to_reclaim, flush_state);
4842 flush_state++;
25ce459c
LB
4843 if (!btrfs_need_do_async_reclaim(space_info, fs_info,
4844 flush_state))
21c7e756 4845 return;
365c5313 4846 } while (flush_state < COMMIT_TRANS);
21c7e756
MX
4847}
4848
4849void btrfs_init_async_reclaim_work(struct work_struct *work)
4850{
4851 INIT_WORK(work, btrfs_async_reclaim_metadata_space);
4852}
4853
4a92b1b8
JB
4854/**
4855 * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
4856 * @root - the root we're allocating for
4857 * @block_rsv - the block_rsv we're allocating for
4858 * @orig_bytes - the number of bytes we want
48fc7f7e 4859 * @flush - whether or not we can flush to make our reservation
8bb8ab2e 4860 *
4a92b1b8
JB
4861 * This will reserve orgi_bytes number of bytes from the space info associated
4862 * with the block_rsv. If there is not enough space it will make an attempt to
4863 * flush out space to make room. It will do this by flushing delalloc if
4864 * possible or committing the transaction. If flush is 0 then no attempts to
4865 * regain reservations will be made and this will fail if there is not enough
4866 * space already.
8bb8ab2e 4867 */
4a92b1b8 4868static int reserve_metadata_bytes(struct btrfs_root *root,
8bb8ab2e 4869 struct btrfs_block_rsv *block_rsv,
08e007d2
MX
4870 u64 orig_bytes,
4871 enum btrfs_reserve_flush_enum flush)
9ed74f2d 4872{
f0486c68 4873 struct btrfs_space_info *space_info = block_rsv->space_info;
2bf64758 4874 u64 used;
8bb8ab2e 4875 u64 num_bytes = orig_bytes;
67b0fd63 4876 int flush_state = FLUSH_DELAYED_ITEMS_NR;
8bb8ab2e 4877 int ret = 0;
fdb5effd 4878 bool flushing = false;
9ed74f2d 4879
8bb8ab2e 4880again:
fdb5effd 4881 ret = 0;
8bb8ab2e 4882 spin_lock(&space_info->lock);
fdb5effd 4883 /*
08e007d2
MX
4884 * We only want to wait if somebody other than us is flushing and we
4885 * are actually allowed to flush all things.
fdb5effd 4886 */
08e007d2
MX
4887 while (flush == BTRFS_RESERVE_FLUSH_ALL && !flushing &&
4888 space_info->flush) {
fdb5effd
JB
4889 spin_unlock(&space_info->lock);
4890 /*
4891 * If we have a trans handle we can't wait because the flusher
4892 * may have to commit the transaction, which would mean we would
4893 * deadlock since we are waiting for the flusher to finish, but
4894 * hold the current transaction open.
4895 */
663350ac 4896 if (current->journal_info)
fdb5effd 4897 return -EAGAIN;
b9688bb8
AJ
4898 ret = wait_event_killable(space_info->wait, !space_info->flush);
4899 /* Must have been killed, return */
4900 if (ret)
fdb5effd
JB
4901 return -EINTR;
4902
4903 spin_lock(&space_info->lock);
4904 }
4905
4906 ret = -ENOSPC;
2bf64758
JB
4907 used = space_info->bytes_used + space_info->bytes_reserved +
4908 space_info->bytes_pinned + space_info->bytes_readonly +
4909 space_info->bytes_may_use;
9ed74f2d 4910
8bb8ab2e
JB
4911 /*
4912 * The idea here is that we've not already over-reserved the block group
4913 * then we can go ahead and save our reservation first and then start
4914 * flushing if we need to. Otherwise if we've already overcommitted
4915 * lets start flushing stuff first and then come back and try to make
4916 * our reservation.
4917 */
2bf64758
JB
4918 if (used <= space_info->total_bytes) {
4919 if (used + orig_bytes <= space_info->total_bytes) {
fb25e914 4920 space_info->bytes_may_use += orig_bytes;
8c2a3ca2 4921 trace_btrfs_space_reservation(root->fs_info,
2bcc0328 4922 "space_info", space_info->flags, orig_bytes, 1);
8bb8ab2e
JB
4923 ret = 0;
4924 } else {
4925 /*
4926 * Ok set num_bytes to orig_bytes since we aren't
4927 * overocmmitted, this way we only try and reclaim what
4928 * we need.
4929 */
4930 num_bytes = orig_bytes;
4931 }
4932 } else {
4933 /*
4934 * Ok we're over committed, set num_bytes to the overcommitted
4935 * amount plus the amount of bytes that we need for this
4936 * reservation.
4937 */
2bf64758 4938 num_bytes = used - space_info->total_bytes +
96c3f433 4939 (orig_bytes * 2);
8bb8ab2e 4940 }
9ed74f2d 4941
44734ed1
JB
4942 if (ret && can_overcommit(root, space_info, orig_bytes, flush)) {
4943 space_info->bytes_may_use += orig_bytes;
4944 trace_btrfs_space_reservation(root->fs_info, "space_info",
4945 space_info->flags, orig_bytes,
4946 1);
4947 ret = 0;
2bf64758
JB
4948 }
4949
8bb8ab2e
JB
4950 /*
4951 * Couldn't make our reservation, save our place so while we're trying
4952 * to reclaim space we can actually use it instead of somebody else
4953 * stealing it from us.
08e007d2
MX
4954 *
4955 * We make the other tasks wait for the flush only when we can flush
4956 * all things.
8bb8ab2e 4957 */
72bcd99d 4958 if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
fdb5effd
JB
4959 flushing = true;
4960 space_info->flush = 1;
21c7e756
MX
4961 } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
4962 used += orig_bytes;
f6acfd50
JB
4963 /*
4964 * We will do the space reservation dance during log replay,
4965 * which means we won't have fs_info->fs_root set, so don't do
4966 * the async reclaim as we will panic.
4967 */
4968 if (!root->fs_info->log_root_recovering &&
4969 need_do_async_reclaim(space_info, root->fs_info, used) &&
21c7e756
MX
4970 !work_busy(&root->fs_info->async_reclaim_work))
4971 queue_work(system_unbound_wq,
4972 &root->fs_info->async_reclaim_work);
8bb8ab2e 4973 }
f0486c68 4974 spin_unlock(&space_info->lock);
9ed74f2d 4975
08e007d2 4976 if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
8bb8ab2e 4977 goto out;
f0486c68 4978
96c3f433
JB
4979 ret = flush_space(root, space_info, num_bytes, orig_bytes,
4980 flush_state);
4981 flush_state++;
08e007d2
MX
4982
4983 /*
4984 * If we are FLUSH_LIMIT, we can not flush delalloc, or the deadlock
4985 * would happen. So skip delalloc flush.
4986 */
4987 if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4988 (flush_state == FLUSH_DELALLOC ||
4989 flush_state == FLUSH_DELALLOC_WAIT))
4990 flush_state = ALLOC_CHUNK;
4991
96c3f433 4992 if (!ret)
8bb8ab2e 4993 goto again;
08e007d2
MX
4994 else if (flush == BTRFS_RESERVE_FLUSH_LIMIT &&
4995 flush_state < COMMIT_TRANS)
4996 goto again;
4997 else if (flush == BTRFS_RESERVE_FLUSH_ALL &&
4998 flush_state <= COMMIT_TRANS)
8bb8ab2e
JB
4999 goto again;
5000
5001out:
5d80366e
JB
5002 if (ret == -ENOSPC &&
5003 unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
5004 struct btrfs_block_rsv *global_rsv =
5005 &root->fs_info->global_block_rsv;
5006
5007 if (block_rsv != global_rsv &&
5008 !block_rsv_use_bytes(global_rsv, orig_bytes))
5009 ret = 0;
5010 }
cab45e22
JM
5011 if (ret == -ENOSPC)
5012 trace_btrfs_space_reservation(root->fs_info,
5013 "space_info:enospc",
5014 space_info->flags, orig_bytes, 1);
fdb5effd 5015 if (flushing) {
8bb8ab2e 5016 spin_lock(&space_info->lock);
fdb5effd
JB
5017 space_info->flush = 0;
5018 wake_up_all(&space_info->wait);
8bb8ab2e 5019 spin_unlock(&space_info->lock);
f0486c68 5020 }
f0486c68
YZ
5021 return ret;
5022}
5023
79787eaa
JM
5024static struct btrfs_block_rsv *get_block_rsv(
5025 const struct btrfs_trans_handle *trans,
5026 const struct btrfs_root *root)
f0486c68 5027{
4c13d758
JB
5028 struct btrfs_block_rsv *block_rsv = NULL;
5029
e9cf439f
AM
5030 if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
5031 (root == root->fs_info->csum_root && trans->adding_csums) ||
5032 (root == root->fs_info->uuid_root))
f7a81ea4
SB
5033 block_rsv = trans->block_rsv;
5034
4c13d758 5035 if (!block_rsv)
f0486c68
YZ
5036 block_rsv = root->block_rsv;
5037
5038 if (!block_rsv)
5039 block_rsv = &root->fs_info->empty_block_rsv;
5040
5041 return block_rsv;
5042}
5043
5044static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
5045 u64 num_bytes)
5046{
5047 int ret = -ENOSPC;
5048 spin_lock(&block_rsv->lock);
5049 if (block_rsv->reserved >= num_bytes) {
5050 block_rsv->reserved -= num_bytes;
5051 if (block_rsv->reserved < block_rsv->size)
5052 block_rsv->full = 0;
5053 ret = 0;
5054 }
5055 spin_unlock(&block_rsv->lock);
5056 return ret;
5057}
5058
5059static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
5060 u64 num_bytes, int update_size)
5061{
5062 spin_lock(&block_rsv->lock);
5063 block_rsv->reserved += num_bytes;
5064 if (update_size)
5065 block_rsv->size += num_bytes;
5066 else if (block_rsv->reserved >= block_rsv->size)
5067 block_rsv->full = 1;
5068 spin_unlock(&block_rsv->lock);
5069}
5070
d52be818
JB
5071int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
5072 struct btrfs_block_rsv *dest, u64 num_bytes,
5073 int min_factor)
5074{
5075 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
5076 u64 min_bytes;
5077
5078 if (global_rsv->space_info != dest->space_info)
5079 return -ENOSPC;
5080
5081 spin_lock(&global_rsv->lock);
5082 min_bytes = div_factor(global_rsv->size, min_factor);
5083 if (global_rsv->reserved < min_bytes + num_bytes) {
5084 spin_unlock(&global_rsv->lock);
5085 return -ENOSPC;
5086 }
5087 global_rsv->reserved -= num_bytes;
5088 if (global_rsv->reserved < global_rsv->size)
5089 global_rsv->full = 0;
5090 spin_unlock(&global_rsv->lock);
5091
5092 block_rsv_add_bytes(dest, num_bytes, 1);
5093 return 0;
5094}
5095
8c2a3ca2
JB
5096static void block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
5097 struct btrfs_block_rsv *block_rsv,
62a45b60 5098 struct btrfs_block_rsv *dest, u64 num_bytes)
f0486c68
YZ
5099{
5100 struct btrfs_space_info *space_info = block_rsv->space_info;
5101
5102 spin_lock(&block_rsv->lock);
5103 if (num_bytes == (u64)-1)
5104 num_bytes = block_rsv->size;
5105 block_rsv->size -= num_bytes;
5106 if (block_rsv->reserved >= block_rsv->size) {
5107 num_bytes = block_rsv->reserved - block_rsv->size;
5108 block_rsv->reserved = block_rsv->size;
5109 block_rsv->full = 1;
5110 } else {
5111 num_bytes = 0;
5112 }
5113 spin_unlock(&block_rsv->lock);
5114
5115 if (num_bytes > 0) {
5116 if (dest) {
e9e22899
JB
5117 spin_lock(&dest->lock);
5118 if (!dest->full) {
5119 u64 bytes_to_add;
5120
5121 bytes_to_add = dest->size - dest->reserved;
5122 bytes_to_add = min(num_bytes, bytes_to_add);
5123 dest->reserved += bytes_to_add;
5124 if (dest->reserved >= dest->size)
5125 dest->full = 1;
5126 num_bytes -= bytes_to_add;
5127 }
5128 spin_unlock(&dest->lock);
5129 }
5130 if (num_bytes) {
f0486c68 5131 spin_lock(&space_info->lock);
fb25e914 5132 space_info->bytes_may_use -= num_bytes;
8c2a3ca2 5133 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 5134 space_info->flags, num_bytes, 0);
f0486c68 5135 spin_unlock(&space_info->lock);
4e06bdd6 5136 }
9ed74f2d 5137 }
f0486c68 5138}
4e06bdd6 5139
f0486c68
YZ
5140static int block_rsv_migrate_bytes(struct btrfs_block_rsv *src,
5141 struct btrfs_block_rsv *dst, u64 num_bytes)
5142{
5143 int ret;
9ed74f2d 5144
f0486c68
YZ
5145 ret = block_rsv_use_bytes(src, num_bytes);
5146 if (ret)
5147 return ret;
9ed74f2d 5148
f0486c68 5149 block_rsv_add_bytes(dst, num_bytes, 1);
9ed74f2d
JB
5150 return 0;
5151}
5152
66d8f3dd 5153void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
9ed74f2d 5154{
f0486c68
YZ
5155 memset(rsv, 0, sizeof(*rsv));
5156 spin_lock_init(&rsv->lock);
66d8f3dd 5157 rsv->type = type;
f0486c68
YZ
5158}
5159
66d8f3dd
MX
5160struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_root *root,
5161 unsigned short type)
f0486c68
YZ
5162{
5163 struct btrfs_block_rsv *block_rsv;
5164 struct btrfs_fs_info *fs_info = root->fs_info;
9ed74f2d 5165
f0486c68
YZ
5166 block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
5167 if (!block_rsv)
5168 return NULL;
9ed74f2d 5169
66d8f3dd 5170 btrfs_init_block_rsv(block_rsv, type);
f0486c68
YZ
5171 block_rsv->space_info = __find_space_info(fs_info,
5172 BTRFS_BLOCK_GROUP_METADATA);
f0486c68
YZ
5173 return block_rsv;
5174}
9ed74f2d 5175
f0486c68
YZ
5176void btrfs_free_block_rsv(struct btrfs_root *root,
5177 struct btrfs_block_rsv *rsv)
5178{
2aaa6655
JB
5179 if (!rsv)
5180 return;
dabdb640
JB
5181 btrfs_block_rsv_release(root, rsv, (u64)-1);
5182 kfree(rsv);
9ed74f2d
JB
5183}
5184
cdfb080e
CM
5185void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
5186{
5187 kfree(rsv);
5188}
5189
08e007d2
MX
5190int btrfs_block_rsv_add(struct btrfs_root *root,
5191 struct btrfs_block_rsv *block_rsv, u64 num_bytes,
5192 enum btrfs_reserve_flush_enum flush)
9ed74f2d 5193{
f0486c68 5194 int ret;
9ed74f2d 5195
f0486c68
YZ
5196 if (num_bytes == 0)
5197 return 0;
8bb8ab2e 5198
61b520a9 5199 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
f0486c68
YZ
5200 if (!ret) {
5201 block_rsv_add_bytes(block_rsv, num_bytes, 1);
5202 return 0;
5203 }
9ed74f2d 5204
f0486c68 5205 return ret;
f0486c68 5206}
9ed74f2d 5207
4a92b1b8 5208int btrfs_block_rsv_check(struct btrfs_root *root,
36ba022a 5209 struct btrfs_block_rsv *block_rsv, int min_factor)
f0486c68
YZ
5210{
5211 u64 num_bytes = 0;
f0486c68 5212 int ret = -ENOSPC;
9ed74f2d 5213
f0486c68
YZ
5214 if (!block_rsv)
5215 return 0;
9ed74f2d 5216
f0486c68 5217 spin_lock(&block_rsv->lock);
36ba022a
JB
5218 num_bytes = div_factor(block_rsv->size, min_factor);
5219 if (block_rsv->reserved >= num_bytes)
5220 ret = 0;
5221 spin_unlock(&block_rsv->lock);
9ed74f2d 5222
36ba022a
JB
5223 return ret;
5224}
5225
08e007d2
MX
5226int btrfs_block_rsv_refill(struct btrfs_root *root,
5227 struct btrfs_block_rsv *block_rsv, u64 min_reserved,
5228 enum btrfs_reserve_flush_enum flush)
36ba022a
JB
5229{
5230 u64 num_bytes = 0;
5231 int ret = -ENOSPC;
5232
5233 if (!block_rsv)
5234 return 0;
5235
5236 spin_lock(&block_rsv->lock);
5237 num_bytes = min_reserved;
13553e52 5238 if (block_rsv->reserved >= num_bytes)
f0486c68 5239 ret = 0;
13553e52 5240 else
f0486c68 5241 num_bytes -= block_rsv->reserved;
f0486c68 5242 spin_unlock(&block_rsv->lock);
13553e52 5243
f0486c68
YZ
5244 if (!ret)
5245 return 0;
5246
aa38a711 5247 ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
dabdb640
JB
5248 if (!ret) {
5249 block_rsv_add_bytes(block_rsv, num_bytes, 0);
f0486c68 5250 return 0;
6a63209f 5251 }
9ed74f2d 5252
13553e52 5253 return ret;
f0486c68
YZ
5254}
5255
5256int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src_rsv,
5257 struct btrfs_block_rsv *dst_rsv,
5258 u64 num_bytes)
5259{
5260 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
5261}
5262
5263void btrfs_block_rsv_release(struct btrfs_root *root,
5264 struct btrfs_block_rsv *block_rsv,
5265 u64 num_bytes)
5266{
5267 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
17504584 5268 if (global_rsv == block_rsv ||
f0486c68
YZ
5269 block_rsv->space_info != global_rsv->space_info)
5270 global_rsv = NULL;
8c2a3ca2
JB
5271 block_rsv_release_bytes(root->fs_info, block_rsv, global_rsv,
5272 num_bytes);
6a63209f
JB
5273}
5274
5275/*
8929ecfa
YZ
5276 * helper to calculate size of global block reservation.
5277 * the desired value is sum of space used by extent tree,
5278 * checksum tree and root tree
6a63209f 5279 */
8929ecfa 5280static u64 calc_global_metadata_size(struct btrfs_fs_info *fs_info)
6a63209f 5281{
8929ecfa
YZ
5282 struct btrfs_space_info *sinfo;
5283 u64 num_bytes;
5284 u64 meta_used;
5285 u64 data_used;
6c41761f 5286 int csum_size = btrfs_super_csum_size(fs_info->super_copy);
6a63209f 5287
8929ecfa
YZ
5288 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_DATA);
5289 spin_lock(&sinfo->lock);
5290 data_used = sinfo->bytes_used;
5291 spin_unlock(&sinfo->lock);
33b4d47f 5292
8929ecfa
YZ
5293 sinfo = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
5294 spin_lock(&sinfo->lock);
6d48755d
JB
5295 if (sinfo->flags & BTRFS_BLOCK_GROUP_DATA)
5296 data_used = 0;
8929ecfa
YZ
5297 meta_used = sinfo->bytes_used;
5298 spin_unlock(&sinfo->lock);
ab6e2410 5299
8929ecfa
YZ
5300 num_bytes = (data_used >> fs_info->sb->s_blocksize_bits) *
5301 csum_size * 2;
f8c269d7 5302 num_bytes += div_u64(data_used + meta_used, 50);
4e06bdd6 5303
8929ecfa 5304 if (num_bytes * 3 > meta_used)
f8c269d7 5305 num_bytes = div_u64(meta_used, 3);
ab6e2410 5306
707e8a07 5307 return ALIGN(num_bytes, fs_info->extent_root->nodesize << 10);
8929ecfa 5308}
6a63209f 5309
8929ecfa
YZ
5310static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
5311{
5312 struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
5313 struct btrfs_space_info *sinfo = block_rsv->space_info;
5314 u64 num_bytes;
6a63209f 5315
8929ecfa 5316 num_bytes = calc_global_metadata_size(fs_info);
33b4d47f 5317
8929ecfa 5318 spin_lock(&sinfo->lock);
1f699d38 5319 spin_lock(&block_rsv->lock);
4e06bdd6 5320
fdf30d1c 5321 block_rsv->size = min_t(u64, num_bytes, 512 * 1024 * 1024);
4e06bdd6 5322
8929ecfa 5323 num_bytes = sinfo->bytes_used + sinfo->bytes_pinned +
6d48755d
JB
5324 sinfo->bytes_reserved + sinfo->bytes_readonly +
5325 sinfo->bytes_may_use;
8929ecfa
YZ
5326
5327 if (sinfo->total_bytes > num_bytes) {
5328 num_bytes = sinfo->total_bytes - num_bytes;
5329 block_rsv->reserved += num_bytes;
fb25e914 5330 sinfo->bytes_may_use += num_bytes;
8c2a3ca2 5331 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 5332 sinfo->flags, num_bytes, 1);
6a63209f 5333 }
6a63209f 5334
8929ecfa
YZ
5335 if (block_rsv->reserved >= block_rsv->size) {
5336 num_bytes = block_rsv->reserved - block_rsv->size;
fb25e914 5337 sinfo->bytes_may_use -= num_bytes;
8c2a3ca2 5338 trace_btrfs_space_reservation(fs_info, "space_info",
2bcc0328 5339 sinfo->flags, num_bytes, 0);
8929ecfa
YZ
5340 block_rsv->reserved = block_rsv->size;
5341 block_rsv->full = 1;
5342 }
182608c8 5343
8929ecfa 5344 spin_unlock(&block_rsv->lock);
1f699d38 5345 spin_unlock(&sinfo->lock);
6a63209f
JB
5346}
5347
f0486c68 5348static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
6a63209f 5349{
f0486c68 5350 struct btrfs_space_info *space_info;
6a63209f 5351
f0486c68
YZ
5352 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
5353 fs_info->chunk_block_rsv.space_info = space_info;
6a63209f 5354
f0486c68 5355 space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
8929ecfa 5356 fs_info->global_block_rsv.space_info = space_info;
8929ecfa 5357 fs_info->delalloc_block_rsv.space_info = space_info;
f0486c68
YZ
5358 fs_info->trans_block_rsv.space_info = space_info;
5359 fs_info->empty_block_rsv.space_info = space_info;
6d668dda 5360 fs_info->delayed_block_rsv.space_info = space_info;
f0486c68 5361
8929ecfa
YZ
5362 fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
5363 fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
5364 fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
5365 fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
3a6cad90
SB
5366 if (fs_info->quota_root)
5367 fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
f0486c68 5368 fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
8929ecfa 5369
8929ecfa 5370 update_global_block_rsv(fs_info);
6a63209f
JB
5371}
5372
8929ecfa 5373static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
6a63209f 5374{
8c2a3ca2
JB
5375 block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
5376 (u64)-1);
8929ecfa
YZ
5377 WARN_ON(fs_info->delalloc_block_rsv.size > 0);
5378 WARN_ON(fs_info->delalloc_block_rsv.reserved > 0);
5379 WARN_ON(fs_info->trans_block_rsv.size > 0);
5380 WARN_ON(fs_info->trans_block_rsv.reserved > 0);
5381 WARN_ON(fs_info->chunk_block_rsv.size > 0);
5382 WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
6d668dda
JB
5383 WARN_ON(fs_info->delayed_block_rsv.size > 0);
5384 WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
fcb80c2a
JB
5385}
5386
a22285a6
YZ
5387void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
5388 struct btrfs_root *root)
6a63209f 5389{
0e721106
JB
5390 if (!trans->block_rsv)
5391 return;
5392
a22285a6
YZ
5393 if (!trans->bytes_reserved)
5394 return;
6a63209f 5395
e77266e4 5396 trace_btrfs_space_reservation(root->fs_info, "transaction",
2bcc0328 5397 trans->transid, trans->bytes_reserved, 0);
b24e03db 5398 btrfs_block_rsv_release(root, trans->block_rsv, trans->bytes_reserved);
a22285a6
YZ
5399 trans->bytes_reserved = 0;
5400}
6a63209f 5401
4fbcdf66
FM
5402/*
5403 * To be called after all the new block groups attached to the transaction
5404 * handle have been created (btrfs_create_pending_block_groups()).
5405 */
5406void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
5407{
5408 struct btrfs_fs_info *fs_info = trans->root->fs_info;
5409
5410 if (!trans->chunk_bytes_reserved)
5411 return;
5412
5413 WARN_ON_ONCE(!list_empty(&trans->new_bgs));
5414
5415 block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
5416 trans->chunk_bytes_reserved);
5417 trans->chunk_bytes_reserved = 0;
5418}
5419
79787eaa 5420/* Can only return 0 or -ENOSPC */
d68fc57b
YZ
5421int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
5422 struct inode *inode)
5423{
5424 struct btrfs_root *root = BTRFS_I(inode)->root;
5425 struct btrfs_block_rsv *src_rsv = get_block_rsv(trans, root);
5426 struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
5427
5428 /*
fcb80c2a
JB
5429 * We need to hold space in order to delete our orphan item once we've
5430 * added it, so this takes the reservation so we can release it later
5431 * when we are truly done with the orphan item.
d68fc57b 5432 */
ff5714cc 5433 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
8c2a3ca2
JB
5434 trace_btrfs_space_reservation(root->fs_info, "orphan",
5435 btrfs_ino(inode), num_bytes, 1);
d68fc57b 5436 return block_rsv_migrate_bytes(src_rsv, dst_rsv, num_bytes);
6a63209f
JB
5437}
5438
d68fc57b 5439void btrfs_orphan_release_metadata(struct inode *inode)
97e728d4 5440{
d68fc57b 5441 struct btrfs_root *root = BTRFS_I(inode)->root;
ff5714cc 5442 u64 num_bytes = btrfs_calc_trans_metadata_size(root, 1);
8c2a3ca2
JB
5443 trace_btrfs_space_reservation(root->fs_info, "orphan",
5444 btrfs_ino(inode), num_bytes, 0);
d68fc57b
YZ
5445 btrfs_block_rsv_release(root, root->orphan_block_rsv, num_bytes);
5446}
97e728d4 5447
d5c12070
MX
5448/*
5449 * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
5450 * root: the root of the parent directory
5451 * rsv: block reservation
5452 * items: the number of items that we need do reservation
5453 * qgroup_reserved: used to return the reserved size in qgroup
5454 *
5455 * This function is used to reserve the space for snapshot/subvolume
5456 * creation and deletion. Those operations are different with the
5457 * common file/directory operations, they change two fs/file trees
5458 * and root tree, the number of items that the qgroup reserves is
5459 * different with the free space reservation. So we can not use
5460 * the space reseravtion mechanism in start_transaction().
5461 */
5462int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
5463 struct btrfs_block_rsv *rsv,
5464 int items,
ee3441b4
JM
5465 u64 *qgroup_reserved,
5466 bool use_global_rsv)
a22285a6 5467{
d5c12070
MX
5468 u64 num_bytes;
5469 int ret;
ee3441b4 5470 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
d5c12070
MX
5471
5472 if (root->fs_info->quota_enabled) {
5473 /* One for parent inode, two for dir entries */
707e8a07 5474 num_bytes = 3 * root->nodesize;
7174109c 5475 ret = btrfs_qgroup_reserve_meta(root, num_bytes);
d5c12070
MX
5476 if (ret)
5477 return ret;
5478 } else {
5479 num_bytes = 0;
5480 }
5481
5482 *qgroup_reserved = num_bytes;
5483
5484 num_bytes = btrfs_calc_trans_metadata_size(root, items);
5485 rsv->space_info = __find_space_info(root->fs_info,
5486 BTRFS_BLOCK_GROUP_METADATA);
5487 ret = btrfs_block_rsv_add(root, rsv, num_bytes,
5488 BTRFS_RESERVE_FLUSH_ALL);
ee3441b4
JM
5489
5490 if (ret == -ENOSPC && use_global_rsv)
5491 ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes);
5492
7174109c
QW
5493 if (ret && *qgroup_reserved)
5494 btrfs_qgroup_free_meta(root, *qgroup_reserved);
d5c12070
MX
5495
5496 return ret;
5497}
5498
5499void btrfs_subvolume_release_metadata(struct btrfs_root *root,
5500 struct btrfs_block_rsv *rsv,
5501 u64 qgroup_reserved)
5502{
5503 btrfs_block_rsv_release(root, rsv, (u64)-1);
97e728d4
JB
5504}
5505
7709cde3
JB
5506/**
5507 * drop_outstanding_extent - drop an outstanding extent
5508 * @inode: the inode we're dropping the extent for
dcab6a3b 5509 * @num_bytes: the number of bytes we're relaseing.
7709cde3
JB
5510 *
5511 * This is called when we are freeing up an outstanding extent, either called
5512 * after an error or after an extent is written. This will return the number of
5513 * reserved extents that need to be freed. This must be called with
5514 * BTRFS_I(inode)->lock held.
5515 */
dcab6a3b 5516static unsigned drop_outstanding_extent(struct inode *inode, u64 num_bytes)
9e0baf60 5517{
7fd2ae21 5518 unsigned drop_inode_space = 0;
9e0baf60 5519 unsigned dropped_extents = 0;
dcab6a3b 5520 unsigned num_extents = 0;
9e0baf60 5521
dcab6a3b
JB
5522 num_extents = (unsigned)div64_u64(num_bytes +
5523 BTRFS_MAX_EXTENT_SIZE - 1,
5524 BTRFS_MAX_EXTENT_SIZE);
5525 ASSERT(num_extents);
5526 ASSERT(BTRFS_I(inode)->outstanding_extents >= num_extents);
5527 BTRFS_I(inode)->outstanding_extents -= num_extents;
9e0baf60 5528
7fd2ae21 5529 if (BTRFS_I(inode)->outstanding_extents == 0 &&
72ac3c0d
JB
5530 test_and_clear_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5531 &BTRFS_I(inode)->runtime_flags))
7fd2ae21 5532 drop_inode_space = 1;
7fd2ae21 5533
9e0baf60
JB
5534 /*
5535 * If we have more or the same amount of outsanding extents than we have
5536 * reserved then we need to leave the reserved extents count alone.
5537 */
5538 if (BTRFS_I(inode)->outstanding_extents >=
5539 BTRFS_I(inode)->reserved_extents)
7fd2ae21 5540 return drop_inode_space;
9e0baf60
JB
5541
5542 dropped_extents = BTRFS_I(inode)->reserved_extents -
5543 BTRFS_I(inode)->outstanding_extents;
5544 BTRFS_I(inode)->reserved_extents -= dropped_extents;
7fd2ae21 5545 return dropped_extents + drop_inode_space;
9e0baf60
JB
5546}
5547
7709cde3
JB
5548/**
5549 * calc_csum_metadata_size - return the amount of metada space that must be
5550 * reserved/free'd for the given bytes.
5551 * @inode: the inode we're manipulating
5552 * @num_bytes: the number of bytes in question
5553 * @reserve: 1 if we are reserving space, 0 if we are freeing space
5554 *
5555 * This adjusts the number of csum_bytes in the inode and then returns the
5556 * correct amount of metadata that must either be reserved or freed. We
5557 * calculate how many checksums we can fit into one leaf and then divide the
5558 * number of bytes that will need to be checksumed by this value to figure out
5559 * how many checksums will be required. If we are adding bytes then the number
5560 * may go up and we will return the number of additional bytes that must be
5561 * reserved. If it is going down we will return the number of bytes that must
5562 * be freed.
5563 *
5564 * This must be called with BTRFS_I(inode)->lock held.
5565 */
5566static u64 calc_csum_metadata_size(struct inode *inode, u64 num_bytes,
5567 int reserve)
6324fbf3 5568{
7709cde3 5569 struct btrfs_root *root = BTRFS_I(inode)->root;
1262133b 5570 u64 old_csums, num_csums;
7709cde3
JB
5571
5572 if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM &&
5573 BTRFS_I(inode)->csum_bytes == 0)
5574 return 0;
5575
28f75a0e 5576 old_csums = btrfs_csum_bytes_to_leaves(root, BTRFS_I(inode)->csum_bytes);
7709cde3
JB
5577 if (reserve)
5578 BTRFS_I(inode)->csum_bytes += num_bytes;
5579 else
5580 BTRFS_I(inode)->csum_bytes -= num_bytes;
28f75a0e 5581 num_csums = btrfs_csum_bytes_to_leaves(root, BTRFS_I(inode)->csum_bytes);
7709cde3
JB
5582
5583 /* No change, no need to reserve more */
5584 if (old_csums == num_csums)
5585 return 0;
5586
5587 if (reserve)
5588 return btrfs_calc_trans_metadata_size(root,
5589 num_csums - old_csums);
5590
5591 return btrfs_calc_trans_metadata_size(root, old_csums - num_csums);
0ca1f7ce 5592}
c146afad 5593
0ca1f7ce
YZ
5594int btrfs_delalloc_reserve_metadata(struct inode *inode, u64 num_bytes)
5595{
5596 struct btrfs_root *root = BTRFS_I(inode)->root;
5597 struct btrfs_block_rsv *block_rsv = &root->fs_info->delalloc_block_rsv;
9e0baf60 5598 u64 to_reserve = 0;
660d3f6c 5599 u64 csum_bytes;
9e0baf60 5600 unsigned nr_extents = 0;
660d3f6c 5601 int extra_reserve = 0;
08e007d2 5602 enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
eb6b88d9 5603 int ret = 0;
c64c2bd8 5604 bool delalloc_lock = true;
88e081bf
WS
5605 u64 to_free = 0;
5606 unsigned dropped;
6324fbf3 5607
c64c2bd8
JB
5608 /* If we are a free space inode we need to not flush since we will be in
5609 * the middle of a transaction commit. We also don't need the delalloc
5610 * mutex since we won't race with anybody. We need this mostly to make
5611 * lockdep shut its filthy mouth.
5612 */
5613 if (btrfs_is_free_space_inode(inode)) {
08e007d2 5614 flush = BTRFS_RESERVE_NO_FLUSH;
c64c2bd8
JB
5615 delalloc_lock = false;
5616 }
c09544e0 5617
08e007d2
MX
5618 if (flush != BTRFS_RESERVE_NO_FLUSH &&
5619 btrfs_transaction_in_commit(root->fs_info))
0ca1f7ce 5620 schedule_timeout(1);
ec44a35c 5621
c64c2bd8
JB
5622 if (delalloc_lock)
5623 mutex_lock(&BTRFS_I(inode)->delalloc_mutex);
5624
0ca1f7ce 5625 num_bytes = ALIGN(num_bytes, root->sectorsize);
8bb8ab2e 5626
9e0baf60 5627 spin_lock(&BTRFS_I(inode)->lock);
6a41dd09
JB
5628 nr_extents = (unsigned)div64_u64(num_bytes +
5629 BTRFS_MAX_EXTENT_SIZE - 1,
5630 BTRFS_MAX_EXTENT_SIZE);
5631 BTRFS_I(inode)->outstanding_extents += nr_extents;
5632 nr_extents = 0;
9e0baf60
JB
5633
5634 if (BTRFS_I(inode)->outstanding_extents >
660d3f6c 5635 BTRFS_I(inode)->reserved_extents)
9e0baf60
JB
5636 nr_extents = BTRFS_I(inode)->outstanding_extents -
5637 BTRFS_I(inode)->reserved_extents;
57a45ced 5638
7fd2ae21
JB
5639 /*
5640 * Add an item to reserve for updating the inode when we complete the
5641 * delalloc io.
5642 */
72ac3c0d
JB
5643 if (!test_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5644 &BTRFS_I(inode)->runtime_flags)) {
7fd2ae21 5645 nr_extents++;
660d3f6c 5646 extra_reserve = 1;
593060d7 5647 }
7fd2ae21
JB
5648
5649 to_reserve = btrfs_calc_trans_metadata_size(root, nr_extents);
7709cde3 5650 to_reserve += calc_csum_metadata_size(inode, num_bytes, 1);
660d3f6c 5651 csum_bytes = BTRFS_I(inode)->csum_bytes;
9e0baf60 5652 spin_unlock(&BTRFS_I(inode)->lock);
57a45ced 5653
88e081bf 5654 if (root->fs_info->quota_enabled) {
7174109c
QW
5655 ret = btrfs_qgroup_reserve_meta(root,
5656 nr_extents * root->nodesize);
88e081bf
WS
5657 if (ret)
5658 goto out_fail;
5659 }
c5567237 5660
88e081bf
WS
5661 ret = reserve_metadata_bytes(root, block_rsv, to_reserve, flush);
5662 if (unlikely(ret)) {
7174109c 5663 btrfs_qgroup_free_meta(root, nr_extents * root->nodesize);
88e081bf 5664 goto out_fail;
9e0baf60 5665 }
25179201 5666
660d3f6c
JB
5667 spin_lock(&BTRFS_I(inode)->lock);
5668 if (extra_reserve) {
72ac3c0d
JB
5669 set_bit(BTRFS_INODE_DELALLOC_META_RESERVED,
5670 &BTRFS_I(inode)->runtime_flags);
660d3f6c
JB
5671 nr_extents--;
5672 }
5673 BTRFS_I(inode)->reserved_extents += nr_extents;
5674 spin_unlock(&BTRFS_I(inode)->lock);
c64c2bd8
JB
5675
5676 if (delalloc_lock)
5677 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
660d3f6c 5678
8c2a3ca2 5679 if (to_reserve)
67871254 5680 trace_btrfs_space_reservation(root->fs_info, "delalloc",
8c2a3ca2 5681 btrfs_ino(inode), to_reserve, 1);
0ca1f7ce
YZ
5682 block_rsv_add_bytes(block_rsv, to_reserve, 1);
5683
0ca1f7ce 5684 return 0;
88e081bf
WS
5685
5686out_fail:
5687 spin_lock(&BTRFS_I(inode)->lock);
dcab6a3b 5688 dropped = drop_outstanding_extent(inode, num_bytes);
88e081bf
WS
5689 /*
5690 * If the inodes csum_bytes is the same as the original
5691 * csum_bytes then we know we haven't raced with any free()ers
5692 * so we can just reduce our inodes csum bytes and carry on.
88e081bf 5693 */
f4881bc7 5694 if (BTRFS_I(inode)->csum_bytes == csum_bytes) {
88e081bf 5695 calc_csum_metadata_size(inode, num_bytes, 0);
f4881bc7
JB
5696 } else {
5697 u64 orig_csum_bytes = BTRFS_I(inode)->csum_bytes;
5698 u64 bytes;
5699
5700 /*
5701 * This is tricky, but first we need to figure out how much we
5702 * free'd from any free-ers that occured during this
5703 * reservation, so we reset ->csum_bytes to the csum_bytes
5704 * before we dropped our lock, and then call the free for the
5705 * number of bytes that were freed while we were trying our
5706 * reservation.
5707 */
5708 bytes = csum_bytes - BTRFS_I(inode)->csum_bytes;
5709 BTRFS_I(inode)->csum_bytes = csum_bytes;
5710 to_free = calc_csum_metadata_size(inode, bytes, 0);
5711
5712
5713 /*
5714 * Now we need to see how much we would have freed had we not
5715 * been making this reservation and our ->csum_bytes were not
5716 * artificially inflated.
5717 */
5718 BTRFS_I(inode)->csum_bytes = csum_bytes - num_bytes;
5719 bytes = csum_bytes - orig_csum_bytes;
5720 bytes = calc_csum_metadata_size(inode, bytes, 0);
5721
5722 /*
5723 * Now reset ->csum_bytes to what it should be. If bytes is
5724 * more than to_free then we would have free'd more space had we
5725 * not had an artificially high ->csum_bytes, so we need to free
5726 * the remainder. If bytes is the same or less then we don't
5727 * need to do anything, the other free-ers did the correct
5728 * thing.
5729 */
5730 BTRFS_I(inode)->csum_bytes = orig_csum_bytes - num_bytes;
5731 if (bytes > to_free)
5732 to_free = bytes - to_free;
5733 else
5734 to_free = 0;
5735 }
88e081bf 5736 spin_unlock(&BTRFS_I(inode)->lock);
e2d1f923 5737 if (dropped)
88e081bf
WS
5738 to_free += btrfs_calc_trans_metadata_size(root, dropped);
5739
5740 if (to_free) {
5741 btrfs_block_rsv_release(root, block_rsv, to_free);
5742 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5743 btrfs_ino(inode), to_free, 0);
5744 }
5745 if (delalloc_lock)
5746 mutex_unlock(&BTRFS_I(inode)->delalloc_mutex);
5747 return ret;
0ca1f7ce
YZ
5748}
5749
7709cde3
JB
5750/**
5751 * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
5752 * @inode: the inode to release the reservation for
5753 * @num_bytes: the number of bytes we're releasing
5754 *
5755 * This will release the metadata reservation for an inode. This can be called
5756 * once we complete IO for a given set of bytes to release their metadata
5757 * reservations.
5758 */
0ca1f7ce
YZ
5759void btrfs_delalloc_release_metadata(struct inode *inode, u64 num_bytes)
5760{
5761 struct btrfs_root *root = BTRFS_I(inode)->root;
9e0baf60
JB
5762 u64 to_free = 0;
5763 unsigned dropped;
0ca1f7ce
YZ
5764
5765 num_bytes = ALIGN(num_bytes, root->sectorsize);
7709cde3 5766 spin_lock(&BTRFS_I(inode)->lock);
dcab6a3b 5767 dropped = drop_outstanding_extent(inode, num_bytes);
97e728d4 5768
0934856d
MX
5769 if (num_bytes)
5770 to_free = calc_csum_metadata_size(inode, num_bytes, 0);
7709cde3 5771 spin_unlock(&BTRFS_I(inode)->lock);
9e0baf60
JB
5772 if (dropped > 0)
5773 to_free += btrfs_calc_trans_metadata_size(root, dropped);
0ca1f7ce 5774
6a3891c5
JB
5775 if (btrfs_test_is_dummy_root(root))
5776 return;
5777
8c2a3ca2
JB
5778 trace_btrfs_space_reservation(root->fs_info, "delalloc",
5779 btrfs_ino(inode), to_free, 0);
c5567237 5780
0ca1f7ce
YZ
5781 btrfs_block_rsv_release(root, &root->fs_info->delalloc_block_rsv,
5782 to_free);
5783}
5784
1ada3a62 5785/**
7cf5b976 5786 * btrfs_delalloc_reserve_space - reserve data and metadata space for
1ada3a62
QW
5787 * delalloc
5788 * @inode: inode we're writing to
5789 * @start: start range we are writing to
5790 * @len: how long the range we are writing to
5791 *
5792 * TODO: This function will finally replace old btrfs_delalloc_reserve_space()
5793 *
5794 * This will do the following things
5795 *
5796 * o reserve space in data space info for num bytes
5797 * and reserve precious corresponding qgroup space
5798 * (Done in check_data_free_space)
5799 *
5800 * o reserve space for metadata space, based on the number of outstanding
5801 * extents and how much csums will be needed
5802 * also reserve metadata space in a per root over-reserve method.
5803 * o add to the inodes->delalloc_bytes
5804 * o add it to the fs_info's delalloc inodes list.
5805 * (Above 3 all done in delalloc_reserve_metadata)
5806 *
5807 * Return 0 for success
5808 * Return <0 for error(-ENOSPC or -EQUOT)
5809 */
7cf5b976 5810int btrfs_delalloc_reserve_space(struct inode *inode, u64 start, u64 len)
1ada3a62
QW
5811{
5812 int ret;
5813
7cf5b976 5814 ret = btrfs_check_data_free_space(inode, start, len);
1ada3a62
QW
5815 if (ret < 0)
5816 return ret;
5817 ret = btrfs_delalloc_reserve_metadata(inode, len);
5818 if (ret < 0)
7cf5b976 5819 btrfs_free_reserved_data_space(inode, start, len);
1ada3a62
QW
5820 return ret;
5821}
5822
7709cde3 5823/**
7cf5b976 5824 * btrfs_delalloc_release_space - release data and metadata space for delalloc
1ada3a62
QW
5825 * @inode: inode we're releasing space for
5826 * @start: start position of the space already reserved
5827 * @len: the len of the space already reserved
5828 *
5829 * This must be matched with a call to btrfs_delalloc_reserve_space. This is
5830 * called in the case that we don't need the metadata AND data reservations
5831 * anymore. So if there is an error or we insert an inline extent.
5832 *
5833 * This function will release the metadata space that was not used and will
5834 * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
5835 * list if there are no delalloc bytes left.
5836 * Also it will handle the qgroup reserved space.
5837 */
7cf5b976 5838void btrfs_delalloc_release_space(struct inode *inode, u64 start, u64 len)
1ada3a62
QW
5839{
5840 btrfs_delalloc_release_metadata(inode, len);
7cf5b976 5841 btrfs_free_reserved_data_space(inode, start, len);
6324fbf3
CM
5842}
5843
ce93ec54
JB
5844static int update_block_group(struct btrfs_trans_handle *trans,
5845 struct btrfs_root *root, u64 bytenr,
5846 u64 num_bytes, int alloc)
9078a3e1 5847{
0af3d00b 5848 struct btrfs_block_group_cache *cache = NULL;
9078a3e1 5849 struct btrfs_fs_info *info = root->fs_info;
db94535d 5850 u64 total = num_bytes;
9078a3e1 5851 u64 old_val;
db94535d 5852 u64 byte_in_group;
0af3d00b 5853 int factor;
3e1ad54f 5854
5d4f98a2 5855 /* block accounting for super block */
eb73c1b7 5856 spin_lock(&info->delalloc_root_lock);
6c41761f 5857 old_val = btrfs_super_bytes_used(info->super_copy);
5d4f98a2
YZ
5858 if (alloc)
5859 old_val += num_bytes;
5860 else
5861 old_val -= num_bytes;
6c41761f 5862 btrfs_set_super_bytes_used(info->super_copy, old_val);
eb73c1b7 5863 spin_unlock(&info->delalloc_root_lock);
5d4f98a2 5864
d397712b 5865 while (total) {
db94535d 5866 cache = btrfs_lookup_block_group(info, bytenr);
f3465ca4 5867 if (!cache)
79787eaa 5868 return -ENOENT;
b742bb82
YZ
5869 if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
5870 BTRFS_BLOCK_GROUP_RAID1 |
5871 BTRFS_BLOCK_GROUP_RAID10))
5872 factor = 2;
5873 else
5874 factor = 1;
9d66e233
JB
5875 /*
5876 * If this block group has free space cache written out, we
5877 * need to make sure to load it if we are removing space. This
5878 * is because we need the unpinning stage to actually add the
5879 * space back to the block group, otherwise we will leak space.
5880 */
5881 if (!alloc && cache->cached == BTRFS_CACHE_NO)
f6373bf3 5882 cache_block_group(cache, 1);
0af3d00b 5883
db94535d
CM
5884 byte_in_group = bytenr - cache->key.objectid;
5885 WARN_ON(byte_in_group > cache->key.offset);
9078a3e1 5886
25179201 5887 spin_lock(&cache->space_info->lock);
c286ac48 5888 spin_lock(&cache->lock);
0af3d00b 5889
73bc1876 5890 if (btrfs_test_opt(root, SPACE_CACHE) &&
0af3d00b
JB
5891 cache->disk_cache_state < BTRFS_DC_CLEAR)
5892 cache->disk_cache_state = BTRFS_DC_CLEAR;
5893
9078a3e1 5894 old_val = btrfs_block_group_used(&cache->item);
db94535d 5895 num_bytes = min(total, cache->key.offset - byte_in_group);
cd1bc465 5896 if (alloc) {
db94535d 5897 old_val += num_bytes;
11833d66
YZ
5898 btrfs_set_block_group_used(&cache->item, old_val);
5899 cache->reserved -= num_bytes;
11833d66 5900 cache->space_info->bytes_reserved -= num_bytes;
b742bb82
YZ
5901 cache->space_info->bytes_used += num_bytes;
5902 cache->space_info->disk_used += num_bytes * factor;
c286ac48 5903 spin_unlock(&cache->lock);
25179201 5904 spin_unlock(&cache->space_info->lock);
cd1bc465 5905 } else {
db94535d 5906 old_val -= num_bytes;
ae0ab003
FM
5907 btrfs_set_block_group_used(&cache->item, old_val);
5908 cache->pinned += num_bytes;
5909 cache->space_info->bytes_pinned += num_bytes;
5910 cache->space_info->bytes_used -= num_bytes;
5911 cache->space_info->disk_used -= num_bytes * factor;
5912 spin_unlock(&cache->lock);
5913 spin_unlock(&cache->space_info->lock);
47ab2a6c 5914
ae0ab003
FM
5915 set_extent_dirty(info->pinned_extents,
5916 bytenr, bytenr + num_bytes - 1,
5917 GFP_NOFS | __GFP_NOFAIL);
47ab2a6c
JB
5918 /*
5919 * No longer have used bytes in this block group, queue
5920 * it for deletion.
5921 */
5922 if (old_val == 0) {
5923 spin_lock(&info->unused_bgs_lock);
5924 if (list_empty(&cache->bg_list)) {
5925 btrfs_get_block_group(cache);
5926 list_add_tail(&cache->bg_list,
5927 &info->unused_bgs);
5928 }
5929 spin_unlock(&info->unused_bgs_lock);
5930 }
cd1bc465 5931 }
1bbc621e
CM
5932
5933 spin_lock(&trans->transaction->dirty_bgs_lock);
5934 if (list_empty(&cache->dirty_list)) {
5935 list_add_tail(&cache->dirty_list,
5936 &trans->transaction->dirty_bgs);
5937 trans->transaction->num_dirty_bgs++;
5938 btrfs_get_block_group(cache);
5939 }
5940 spin_unlock(&trans->transaction->dirty_bgs_lock);
5941
fa9c0d79 5942 btrfs_put_block_group(cache);
db94535d
CM
5943 total -= num_bytes;
5944 bytenr += num_bytes;
9078a3e1
CM
5945 }
5946 return 0;
5947}
6324fbf3 5948
a061fc8d
CM
5949static u64 first_logical_byte(struct btrfs_root *root, u64 search_start)
5950{
0f9dd46c 5951 struct btrfs_block_group_cache *cache;
d2fb3437 5952 u64 bytenr;
0f9dd46c 5953
a1897fdd
LB
5954 spin_lock(&root->fs_info->block_group_cache_lock);
5955 bytenr = root->fs_info->first_logical_byte;
5956 spin_unlock(&root->fs_info->block_group_cache_lock);
5957
5958 if (bytenr < (u64)-1)
5959 return bytenr;
5960
0f9dd46c
JB
5961 cache = btrfs_lookup_first_block_group(root->fs_info, search_start);
5962 if (!cache)
a061fc8d 5963 return 0;
0f9dd46c 5964
d2fb3437 5965 bytenr = cache->key.objectid;
fa9c0d79 5966 btrfs_put_block_group(cache);
d2fb3437
YZ
5967
5968 return bytenr;
a061fc8d
CM
5969}
5970
f0486c68
YZ
5971static int pin_down_extent(struct btrfs_root *root,
5972 struct btrfs_block_group_cache *cache,
5973 u64 bytenr, u64 num_bytes, int reserved)
324ae4df 5974{
11833d66
YZ
5975 spin_lock(&cache->space_info->lock);
5976 spin_lock(&cache->lock);
5977 cache->pinned += num_bytes;
5978 cache->space_info->bytes_pinned += num_bytes;
5979 if (reserved) {
5980 cache->reserved -= num_bytes;
5981 cache->space_info->bytes_reserved -= num_bytes;
5982 }
5983 spin_unlock(&cache->lock);
5984 spin_unlock(&cache->space_info->lock);
68b38550 5985
f0486c68
YZ
5986 set_extent_dirty(root->fs_info->pinned_extents, bytenr,
5987 bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
e2d1f923 5988 if (reserved)
0be5dc67 5989 trace_btrfs_reserved_extent_free(root, bytenr, num_bytes);
f0486c68
YZ
5990 return 0;
5991}
68b38550 5992
f0486c68
YZ
5993/*
5994 * this function must be called within transaction
5995 */
5996int btrfs_pin_extent(struct btrfs_root *root,
5997 u64 bytenr, u64 num_bytes, int reserved)
5998{
5999 struct btrfs_block_group_cache *cache;
68b38550 6000
f0486c68 6001 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
79787eaa 6002 BUG_ON(!cache); /* Logic error */
f0486c68
YZ
6003
6004 pin_down_extent(root, cache, bytenr, num_bytes, reserved);
6005
6006 btrfs_put_block_group(cache);
11833d66
YZ
6007 return 0;
6008}
6009
f0486c68 6010/*
e688b725
CM
6011 * this function must be called within transaction
6012 */
dcfac415 6013int btrfs_pin_extent_for_log_replay(struct btrfs_root *root,
e688b725
CM
6014 u64 bytenr, u64 num_bytes)
6015{
6016 struct btrfs_block_group_cache *cache;
b50c6e25 6017 int ret;
e688b725
CM
6018
6019 cache = btrfs_lookup_block_group(root->fs_info, bytenr);
b50c6e25
JB
6020 if (!cache)
6021 return -EINVAL;
e688b725
CM
6022
6023 /*
6024 * pull in the free space cache (if any) so that our pin
6025 * removes the free space from the cache. We have load_only set
6026 * to one because the slow code to read in the free extents does check
6027 * the pinned extents.
6028 */
f6373bf3 6029 cache_block_group(cache, 1);
e688b725
CM
6030
6031 pin_down_extent(root, cache, bytenr, num_bytes, 0);
6032
6033 /* remove us from the free space cache (if we're there at all) */
b50c6e25 6034 ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
e688b725 6035 btrfs_put_block_group(cache);
b50c6e25 6036 return ret;
e688b725
CM
6037}
6038
8c2a1a30
JB
6039static int __exclude_logged_extent(struct btrfs_root *root, u64 start, u64 num_bytes)
6040{
6041 int ret;
6042 struct btrfs_block_group_cache *block_group;
6043 struct btrfs_caching_control *caching_ctl;
6044
6045 block_group = btrfs_lookup_block_group(root->fs_info, start);
6046 if (!block_group)
6047 return -EINVAL;
6048
6049 cache_block_group(block_group, 0);
6050 caching_ctl = get_caching_control(block_group);
6051
6052 if (!caching_ctl) {
6053 /* Logic error */
6054 BUG_ON(!block_group_cache_done(block_group));
6055 ret = btrfs_remove_free_space(block_group, start, num_bytes);
6056 } else {
6057 mutex_lock(&caching_ctl->mutex);
6058
6059 if (start >= caching_ctl->progress) {
6060 ret = add_excluded_extent(root, start, num_bytes);
6061 } else if (start + num_bytes <= caching_ctl->progress) {
6062 ret = btrfs_remove_free_space(block_group,
6063 start, num_bytes);
6064 } else {
6065 num_bytes = caching_ctl->progress - start;
6066 ret = btrfs_remove_free_space(block_group,
6067 start, num_bytes);
6068 if (ret)
6069 goto out_lock;
6070
6071 num_bytes = (start + num_bytes) -
6072 caching_ctl->progress;
6073 start = caching_ctl->progress;
6074 ret = add_excluded_extent(root, start, num_bytes);
6075 }
6076out_lock:
6077 mutex_unlock(&caching_ctl->mutex);
6078 put_caching_control(caching_ctl);
6079 }
6080 btrfs_put_block_group(block_group);
6081 return ret;
6082}
6083
6084int btrfs_exclude_logged_extents(struct btrfs_root *log,
6085 struct extent_buffer *eb)
6086{
6087 struct btrfs_file_extent_item *item;
6088 struct btrfs_key key;
6089 int found_type;
6090 int i;
6091
6092 if (!btrfs_fs_incompat(log->fs_info, MIXED_GROUPS))
6093 return 0;
6094
6095 for (i = 0; i < btrfs_header_nritems(eb); i++) {
6096 btrfs_item_key_to_cpu(eb, &key, i);
6097 if (key.type != BTRFS_EXTENT_DATA_KEY)
6098 continue;
6099 item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
6100 found_type = btrfs_file_extent_type(eb, item);
6101 if (found_type == BTRFS_FILE_EXTENT_INLINE)
6102 continue;
6103 if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
6104 continue;
6105 key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
6106 key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
6107 __exclude_logged_extent(log, key.objectid, key.offset);
6108 }
6109
6110 return 0;
6111}
6112
fb25e914
JB
6113/**
6114 * btrfs_update_reserved_bytes - update the block_group and space info counters
6115 * @cache: The cache we are manipulating
6116 * @num_bytes: The number of bytes in question
6117 * @reserve: One of the reservation enums
e570fd27 6118 * @delalloc: The blocks are allocated for the delalloc write
fb25e914
JB
6119 *
6120 * This is called by the allocator when it reserves space, or by somebody who is
6121 * freeing space that was never actually used on disk. For example if you
6122 * reserve some space for a new leaf in transaction A and before transaction A
6123 * commits you free that leaf, you call this with reserve set to 0 in order to
6124 * clear the reservation.
6125 *
6126 * Metadata reservations should be called with RESERVE_ALLOC so we do the proper
6127 * ENOSPC accounting. For data we handle the reservation through clearing the
6128 * delalloc bits in the io_tree. We have to do this since we could end up
6129 * allocating less disk space for the amount of data we have reserved in the
6130 * case of compression.
6131 *
6132 * If this is a reservation and the block group has become read only we cannot
6133 * make the reservation and return -EAGAIN, otherwise this function always
6134 * succeeds.
f0486c68 6135 */
fb25e914 6136static int btrfs_update_reserved_bytes(struct btrfs_block_group_cache *cache,
e570fd27 6137 u64 num_bytes, int reserve, int delalloc)
11833d66 6138{
fb25e914 6139 struct btrfs_space_info *space_info = cache->space_info;
f0486c68 6140 int ret = 0;
79787eaa 6141
fb25e914
JB
6142 spin_lock(&space_info->lock);
6143 spin_lock(&cache->lock);
6144 if (reserve != RESERVE_FREE) {
f0486c68
YZ
6145 if (cache->ro) {
6146 ret = -EAGAIN;
6147 } else {
fb25e914
JB
6148 cache->reserved += num_bytes;
6149 space_info->bytes_reserved += num_bytes;
6150 if (reserve == RESERVE_ALLOC) {
8c2a3ca2 6151 trace_btrfs_space_reservation(cache->fs_info,
2bcc0328
LB
6152 "space_info", space_info->flags,
6153 num_bytes, 0);
fb25e914
JB
6154 space_info->bytes_may_use -= num_bytes;
6155 }
e570fd27
MX
6156
6157 if (delalloc)
6158 cache->delalloc_bytes += num_bytes;
f0486c68 6159 }
fb25e914
JB
6160 } else {
6161 if (cache->ro)
6162 space_info->bytes_readonly += num_bytes;
6163 cache->reserved -= num_bytes;
6164 space_info->bytes_reserved -= num_bytes;
e570fd27
MX
6165
6166 if (delalloc)
6167 cache->delalloc_bytes -= num_bytes;
324ae4df 6168 }
fb25e914
JB
6169 spin_unlock(&cache->lock);
6170 spin_unlock(&space_info->lock);
f0486c68 6171 return ret;
324ae4df 6172}
9078a3e1 6173
143bede5 6174void btrfs_prepare_extent_commit(struct btrfs_trans_handle *trans,
11833d66 6175 struct btrfs_root *root)
e8569813 6176{
e8569813 6177 struct btrfs_fs_info *fs_info = root->fs_info;
11833d66
YZ
6178 struct btrfs_caching_control *next;
6179 struct btrfs_caching_control *caching_ctl;
6180 struct btrfs_block_group_cache *cache;
e8569813 6181
9e351cc8 6182 down_write(&fs_info->commit_root_sem);
25179201 6183
11833d66
YZ
6184 list_for_each_entry_safe(caching_ctl, next,
6185 &fs_info->caching_block_groups, list) {
6186 cache = caching_ctl->block_group;
6187 if (block_group_cache_done(cache)) {
6188 cache->last_byte_to_unpin = (u64)-1;
6189 list_del_init(&caching_ctl->list);
6190 put_caching_control(caching_ctl);
e8569813 6191 } else {
11833d66 6192 cache->last_byte_to_unpin = caching_ctl->progress;
e8569813 6193 }
e8569813 6194 }
11833d66
YZ
6195
6196 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6197 fs_info->pinned_extents = &fs_info->freed_extents[1];
6198 else
6199 fs_info->pinned_extents = &fs_info->freed_extents[0];
6200
9e351cc8 6201 up_write(&fs_info->commit_root_sem);
8929ecfa
YZ
6202
6203 update_global_block_rsv(fs_info);
e8569813
ZY
6204}
6205
c759c4e1
JB
6206/*
6207 * Returns the free cluster for the given space info and sets empty_cluster to
6208 * what it should be based on the mount options.
6209 */
6210static struct btrfs_free_cluster *
6211fetch_cluster_info(struct btrfs_root *root, struct btrfs_space_info *space_info,
6212 u64 *empty_cluster)
6213{
6214 struct btrfs_free_cluster *ret = NULL;
6215 bool ssd = btrfs_test_opt(root, SSD);
6216
6217 *empty_cluster = 0;
6218 if (btrfs_mixed_space_info(space_info))
6219 return ret;
6220
6221 if (ssd)
6222 *empty_cluster = 2 * 1024 * 1024;
6223 if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
6224 ret = &root->fs_info->meta_alloc_cluster;
6225 if (!ssd)
6226 *empty_cluster = 64 * 1024;
6227 } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) && ssd) {
6228 ret = &root->fs_info->data_alloc_cluster;
6229 }
6230
6231 return ret;
6232}
6233
678886bd
FM
6234static int unpin_extent_range(struct btrfs_root *root, u64 start, u64 end,
6235 const bool return_free_space)
ccd467d6 6236{
11833d66
YZ
6237 struct btrfs_fs_info *fs_info = root->fs_info;
6238 struct btrfs_block_group_cache *cache = NULL;
7b398f8e
JB
6239 struct btrfs_space_info *space_info;
6240 struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
c759c4e1 6241 struct btrfs_free_cluster *cluster = NULL;
11833d66 6242 u64 len;
c759c4e1
JB
6243 u64 total_unpinned = 0;
6244 u64 empty_cluster = 0;
7b398f8e 6245 bool readonly;
ccd467d6 6246
11833d66 6247 while (start <= end) {
7b398f8e 6248 readonly = false;
11833d66
YZ
6249 if (!cache ||
6250 start >= cache->key.objectid + cache->key.offset) {
6251 if (cache)
6252 btrfs_put_block_group(cache);
c759c4e1 6253 total_unpinned = 0;
11833d66 6254 cache = btrfs_lookup_block_group(fs_info, start);
79787eaa 6255 BUG_ON(!cache); /* Logic error */
c759c4e1
JB
6256
6257 cluster = fetch_cluster_info(root,
6258 cache->space_info,
6259 &empty_cluster);
6260 empty_cluster <<= 1;
11833d66
YZ
6261 }
6262
6263 len = cache->key.objectid + cache->key.offset - start;
6264 len = min(len, end + 1 - start);
6265
6266 if (start < cache->last_byte_to_unpin) {
6267 len = min(len, cache->last_byte_to_unpin - start);
678886bd
FM
6268 if (return_free_space)
6269 btrfs_add_free_space(cache, start, len);
11833d66
YZ
6270 }
6271
f0486c68 6272 start += len;
c759c4e1 6273 total_unpinned += len;
7b398f8e 6274 space_info = cache->space_info;
f0486c68 6275
c759c4e1
JB
6276 /*
6277 * If this space cluster has been marked as fragmented and we've
6278 * unpinned enough in this block group to potentially allow a
6279 * cluster to be created inside of it go ahead and clear the
6280 * fragmented check.
6281 */
6282 if (cluster && cluster->fragmented &&
6283 total_unpinned > empty_cluster) {
6284 spin_lock(&cluster->lock);
6285 cluster->fragmented = 0;
6286 spin_unlock(&cluster->lock);
6287 }
6288
7b398f8e 6289 spin_lock(&space_info->lock);
11833d66
YZ
6290 spin_lock(&cache->lock);
6291 cache->pinned -= len;
7b398f8e 6292 space_info->bytes_pinned -= len;
4f4db217 6293 space_info->max_extent_size = 0;
d288db5d 6294 percpu_counter_add(&space_info->total_bytes_pinned, -len);
7b398f8e
JB
6295 if (cache->ro) {
6296 space_info->bytes_readonly += len;
6297 readonly = true;
6298 }
11833d66 6299 spin_unlock(&cache->lock);
7b398f8e
JB
6300 if (!readonly && global_rsv->space_info == space_info) {
6301 spin_lock(&global_rsv->lock);
6302 if (!global_rsv->full) {
6303 len = min(len, global_rsv->size -
6304 global_rsv->reserved);
6305 global_rsv->reserved += len;
6306 space_info->bytes_may_use += len;
6307 if (global_rsv->reserved >= global_rsv->size)
6308 global_rsv->full = 1;
6309 }
6310 spin_unlock(&global_rsv->lock);
6311 }
6312 spin_unlock(&space_info->lock);
ccd467d6 6313 }
11833d66
YZ
6314
6315 if (cache)
6316 btrfs_put_block_group(cache);
ccd467d6
CM
6317 return 0;
6318}
6319
6320int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
11833d66 6321 struct btrfs_root *root)
a28ec197 6322{
11833d66 6323 struct btrfs_fs_info *fs_info = root->fs_info;
e33e17ee
JM
6324 struct btrfs_block_group_cache *block_group, *tmp;
6325 struct list_head *deleted_bgs;
11833d66 6326 struct extent_io_tree *unpin;
1a5bc167
CM
6327 u64 start;
6328 u64 end;
a28ec197 6329 int ret;
a28ec197 6330
11833d66
YZ
6331 if (fs_info->pinned_extents == &fs_info->freed_extents[0])
6332 unpin = &fs_info->freed_extents[1];
6333 else
6334 unpin = &fs_info->freed_extents[0];
6335
e33e17ee 6336 while (!trans->aborted) {
d4b450cd 6337 mutex_lock(&fs_info->unused_bg_unpin_mutex);
1a5bc167 6338 ret = find_first_extent_bit(unpin, 0, &start, &end,
e6138876 6339 EXTENT_DIRTY, NULL);
d4b450cd
FM
6340 if (ret) {
6341 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
a28ec197 6342 break;
d4b450cd 6343 }
1f3c79a2 6344
5378e607
LD
6345 if (btrfs_test_opt(root, DISCARD))
6346 ret = btrfs_discard_extent(root, start,
6347 end + 1 - start, NULL);
1f3c79a2 6348
1a5bc167 6349 clear_extent_dirty(unpin, start, end, GFP_NOFS);
678886bd 6350 unpin_extent_range(root, start, end, true);
d4b450cd 6351 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
b9473439 6352 cond_resched();
a28ec197 6353 }
817d52f8 6354
e33e17ee
JM
6355 /*
6356 * Transaction is finished. We don't need the lock anymore. We
6357 * do need to clean up the block groups in case of a transaction
6358 * abort.
6359 */
6360 deleted_bgs = &trans->transaction->deleted_bgs;
6361 list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
6362 u64 trimmed = 0;
6363
6364 ret = -EROFS;
6365 if (!trans->aborted)
6366 ret = btrfs_discard_extent(root,
6367 block_group->key.objectid,
6368 block_group->key.offset,
6369 &trimmed);
6370
6371 list_del_init(&block_group->bg_list);
6372 btrfs_put_block_group_trimming(block_group);
6373 btrfs_put_block_group(block_group);
6374
6375 if (ret) {
6376 const char *errstr = btrfs_decode_error(ret);
6377 btrfs_warn(fs_info,
6378 "Discard failed while removing blockgroup: errno=%d %s\n",
6379 ret, errstr);
6380 }
6381 }
6382
e20d96d6
CM
6383 return 0;
6384}
6385
b150a4f1
JB
6386static void add_pinned_bytes(struct btrfs_fs_info *fs_info, u64 num_bytes,
6387 u64 owner, u64 root_objectid)
6388{
6389 struct btrfs_space_info *space_info;
6390 u64 flags;
6391
6392 if (owner < BTRFS_FIRST_FREE_OBJECTID) {
6393 if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
6394 flags = BTRFS_BLOCK_GROUP_SYSTEM;
6395 else
6396 flags = BTRFS_BLOCK_GROUP_METADATA;
6397 } else {
6398 flags = BTRFS_BLOCK_GROUP_DATA;
6399 }
6400
6401 space_info = __find_space_info(fs_info, flags);
6402 BUG_ON(!space_info); /* Logic bug */
6403 percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
6404}
6405
6406
5d4f98a2
YZ
6407static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
6408 struct btrfs_root *root,
c682f9b3 6409 struct btrfs_delayed_ref_node *node, u64 parent,
5d4f98a2
YZ
6410 u64 root_objectid, u64 owner_objectid,
6411 u64 owner_offset, int refs_to_drop,
c682f9b3 6412 struct btrfs_delayed_extent_op *extent_op)
a28ec197 6413{
e2fa7227 6414 struct btrfs_key key;
5d4f98a2 6415 struct btrfs_path *path;
1261ec42
CM
6416 struct btrfs_fs_info *info = root->fs_info;
6417 struct btrfs_root *extent_root = info->extent_root;
5f39d397 6418 struct extent_buffer *leaf;
5d4f98a2
YZ
6419 struct btrfs_extent_item *ei;
6420 struct btrfs_extent_inline_ref *iref;
a28ec197 6421 int ret;
5d4f98a2 6422 int is_data;
952fccac
CM
6423 int extent_slot = 0;
6424 int found_extent = 0;
6425 int num_to_del = 1;
5d4f98a2
YZ
6426 u32 item_size;
6427 u64 refs;
c682f9b3
QW
6428 u64 bytenr = node->bytenr;
6429 u64 num_bytes = node->num_bytes;
fcebe456 6430 int last_ref = 0;
3173a18f
JB
6431 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
6432 SKINNY_METADATA);
037e6390 6433
5caf2a00 6434 path = btrfs_alloc_path();
54aa1f4d
CM
6435 if (!path)
6436 return -ENOMEM;
5f26f772 6437
3c12ac72 6438 path->reada = 1;
b9473439 6439 path->leave_spinning = 1;
5d4f98a2
YZ
6440
6441 is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
6442 BUG_ON(!is_data && refs_to_drop != 1);
6443
3173a18f
JB
6444 if (is_data)
6445 skinny_metadata = 0;
6446
5d4f98a2
YZ
6447 ret = lookup_extent_backref(trans, extent_root, path, &iref,
6448 bytenr, num_bytes, parent,
6449 root_objectid, owner_objectid,
6450 owner_offset);
7bb86316 6451 if (ret == 0) {
952fccac 6452 extent_slot = path->slots[0];
5d4f98a2
YZ
6453 while (extent_slot >= 0) {
6454 btrfs_item_key_to_cpu(path->nodes[0], &key,
952fccac 6455 extent_slot);
5d4f98a2 6456 if (key.objectid != bytenr)
952fccac 6457 break;
5d4f98a2
YZ
6458 if (key.type == BTRFS_EXTENT_ITEM_KEY &&
6459 key.offset == num_bytes) {
952fccac
CM
6460 found_extent = 1;
6461 break;
6462 }
3173a18f
JB
6463 if (key.type == BTRFS_METADATA_ITEM_KEY &&
6464 key.offset == owner_objectid) {
6465 found_extent = 1;
6466 break;
6467 }
952fccac
CM
6468 if (path->slots[0] - extent_slot > 5)
6469 break;
5d4f98a2 6470 extent_slot--;
952fccac 6471 }
5d4f98a2
YZ
6472#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6473 item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
6474 if (found_extent && item_size < sizeof(*ei))
6475 found_extent = 0;
6476#endif
31840ae1 6477 if (!found_extent) {
5d4f98a2 6478 BUG_ON(iref);
56bec294 6479 ret = remove_extent_backref(trans, extent_root, path,
5d4f98a2 6480 NULL, refs_to_drop,
fcebe456 6481 is_data, &last_ref);
005d6427
DS
6482 if (ret) {
6483 btrfs_abort_transaction(trans, extent_root, ret);
6484 goto out;
6485 }
b3b4aa74 6486 btrfs_release_path(path);
b9473439 6487 path->leave_spinning = 1;
5d4f98a2
YZ
6488
6489 key.objectid = bytenr;
6490 key.type = BTRFS_EXTENT_ITEM_KEY;
6491 key.offset = num_bytes;
6492
3173a18f
JB
6493 if (!is_data && skinny_metadata) {
6494 key.type = BTRFS_METADATA_ITEM_KEY;
6495 key.offset = owner_objectid;
6496 }
6497
31840ae1
ZY
6498 ret = btrfs_search_slot(trans, extent_root,
6499 &key, path, -1, 1);
3173a18f
JB
6500 if (ret > 0 && skinny_metadata && path->slots[0]) {
6501 /*
6502 * Couldn't find our skinny metadata item,
6503 * see if we have ye olde extent item.
6504 */
6505 path->slots[0]--;
6506 btrfs_item_key_to_cpu(path->nodes[0], &key,
6507 path->slots[0]);
6508 if (key.objectid == bytenr &&
6509 key.type == BTRFS_EXTENT_ITEM_KEY &&
6510 key.offset == num_bytes)
6511 ret = 0;
6512 }
6513
6514 if (ret > 0 && skinny_metadata) {
6515 skinny_metadata = false;
9ce49a0b 6516 key.objectid = bytenr;
3173a18f
JB
6517 key.type = BTRFS_EXTENT_ITEM_KEY;
6518 key.offset = num_bytes;
6519 btrfs_release_path(path);
6520 ret = btrfs_search_slot(trans, extent_root,
6521 &key, path, -1, 1);
6522 }
6523
f3465ca4 6524 if (ret) {
c2cf52eb 6525 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
c1c9ff7c 6526 ret, bytenr);
b783e62d
JB
6527 if (ret > 0)
6528 btrfs_print_leaf(extent_root,
6529 path->nodes[0]);
f3465ca4 6530 }
005d6427
DS
6531 if (ret < 0) {
6532 btrfs_abort_transaction(trans, extent_root, ret);
6533 goto out;
6534 }
31840ae1
ZY
6535 extent_slot = path->slots[0];
6536 }
fae7f21c 6537 } else if (WARN_ON(ret == -ENOENT)) {
7bb86316 6538 btrfs_print_leaf(extent_root, path->nodes[0]);
c2cf52eb
SK
6539 btrfs_err(info,
6540 "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
c1c9ff7c
GU
6541 bytenr, parent, root_objectid, owner_objectid,
6542 owner_offset);
c4a050bb
JB
6543 btrfs_abort_transaction(trans, extent_root, ret);
6544 goto out;
79787eaa 6545 } else {
005d6427
DS
6546 btrfs_abort_transaction(trans, extent_root, ret);
6547 goto out;
7bb86316 6548 }
5f39d397
CM
6549
6550 leaf = path->nodes[0];
5d4f98a2
YZ
6551 item_size = btrfs_item_size_nr(leaf, extent_slot);
6552#ifdef BTRFS_COMPAT_EXTENT_TREE_V0
6553 if (item_size < sizeof(*ei)) {
6554 BUG_ON(found_extent || extent_slot != path->slots[0]);
6555 ret = convert_extent_item_v0(trans, extent_root, path,
6556 owner_objectid, 0);
005d6427
DS
6557 if (ret < 0) {
6558 btrfs_abort_transaction(trans, extent_root, ret);
6559 goto out;
6560 }
5d4f98a2 6561
b3b4aa74 6562 btrfs_release_path(path);
5d4f98a2
YZ
6563 path->leave_spinning = 1;
6564
6565 key.objectid = bytenr;
6566 key.type = BTRFS_EXTENT_ITEM_KEY;
6567 key.offset = num_bytes;
6568
6569 ret = btrfs_search_slot(trans, extent_root, &key, path,
6570 -1, 1);
6571 if (ret) {
c2cf52eb 6572 btrfs_err(info, "umm, got %d back from search, was looking for %llu",
c1c9ff7c 6573 ret, bytenr);
5d4f98a2
YZ
6574 btrfs_print_leaf(extent_root, path->nodes[0]);
6575 }
005d6427
DS
6576 if (ret < 0) {
6577 btrfs_abort_transaction(trans, extent_root, ret);
6578 goto out;
6579 }
6580
5d4f98a2
YZ
6581 extent_slot = path->slots[0];
6582 leaf = path->nodes[0];
6583 item_size = btrfs_item_size_nr(leaf, extent_slot);
6584 }
6585#endif
6586 BUG_ON(item_size < sizeof(*ei));
952fccac 6587 ei = btrfs_item_ptr(leaf, extent_slot,
123abc88 6588 struct btrfs_extent_item);
3173a18f
JB
6589 if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
6590 key.type == BTRFS_EXTENT_ITEM_KEY) {
5d4f98a2
YZ
6591 struct btrfs_tree_block_info *bi;
6592 BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
6593 bi = (struct btrfs_tree_block_info *)(ei + 1);
6594 WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
6595 }
56bec294 6596
5d4f98a2 6597 refs = btrfs_extent_refs(leaf, ei);
32b02538
JB
6598 if (refs < refs_to_drop) {
6599 btrfs_err(info, "trying to drop %d refs but we only have %Lu "
351fd353 6600 "for bytenr %Lu", refs_to_drop, refs, bytenr);
32b02538
JB
6601 ret = -EINVAL;
6602 btrfs_abort_transaction(trans, extent_root, ret);
6603 goto out;
6604 }
56bec294 6605 refs -= refs_to_drop;
5f39d397 6606
5d4f98a2
YZ
6607 if (refs > 0) {
6608 if (extent_op)
6609 __run_delayed_extent_op(extent_op, leaf, ei);
6610 /*
6611 * In the case of inline back ref, reference count will
6612 * be updated by remove_extent_backref
952fccac 6613 */
5d4f98a2
YZ
6614 if (iref) {
6615 BUG_ON(!found_extent);
6616 } else {
6617 btrfs_set_extent_refs(leaf, ei, refs);
6618 btrfs_mark_buffer_dirty(leaf);
6619 }
6620 if (found_extent) {
6621 ret = remove_extent_backref(trans, extent_root, path,
6622 iref, refs_to_drop,
fcebe456 6623 is_data, &last_ref);
005d6427
DS
6624 if (ret) {
6625 btrfs_abort_transaction(trans, extent_root, ret);
6626 goto out;
6627 }
952fccac 6628 }
b150a4f1
JB
6629 add_pinned_bytes(root->fs_info, -num_bytes, owner_objectid,
6630 root_objectid);
5d4f98a2 6631 } else {
5d4f98a2
YZ
6632 if (found_extent) {
6633 BUG_ON(is_data && refs_to_drop !=
9ed0dea0 6634 extent_data_ref_count(path, iref));
5d4f98a2
YZ
6635 if (iref) {
6636 BUG_ON(path->slots[0] != extent_slot);
6637 } else {
6638 BUG_ON(path->slots[0] != extent_slot + 1);
6639 path->slots[0] = extent_slot;
6640 num_to_del = 2;
6641 }
78fae27e 6642 }
b9473439 6643
fcebe456 6644 last_ref = 1;
952fccac
CM
6645 ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
6646 num_to_del);
005d6427
DS
6647 if (ret) {
6648 btrfs_abort_transaction(trans, extent_root, ret);
6649 goto out;
6650 }
b3b4aa74 6651 btrfs_release_path(path);
21af804c 6652
5d4f98a2 6653 if (is_data) {
459931ec 6654 ret = btrfs_del_csums(trans, root, bytenr, num_bytes);
005d6427
DS
6655 if (ret) {
6656 btrfs_abort_transaction(trans, extent_root, ret);
6657 goto out;
6658 }
459931ec
CM
6659 }
6660
ce93ec54 6661 ret = update_block_group(trans, root, bytenr, num_bytes, 0);
005d6427
DS
6662 if (ret) {
6663 btrfs_abort_transaction(trans, extent_root, ret);
6664 goto out;
6665 }
a28ec197 6666 }
fcebe456
JB
6667 btrfs_release_path(path);
6668
79787eaa 6669out:
5caf2a00 6670 btrfs_free_path(path);
a28ec197
CM
6671 return ret;
6672}
6673
1887be66 6674/*
f0486c68 6675 * when we free an block, it is possible (and likely) that we free the last
1887be66
CM
6676 * delayed ref for that extent as well. This searches the delayed ref tree for
6677 * a given extent, and if there are no other delayed refs to be processed, it
6678 * removes it from the tree.
6679 */
6680static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
6681 struct btrfs_root *root, u64 bytenr)
6682{
6683 struct btrfs_delayed_ref_head *head;
6684 struct btrfs_delayed_ref_root *delayed_refs;
f0486c68 6685 int ret = 0;
1887be66
CM
6686
6687 delayed_refs = &trans->transaction->delayed_refs;
6688 spin_lock(&delayed_refs->lock);
6689 head = btrfs_find_delayed_ref_head(trans, bytenr);
6690 if (!head)
cf93da7b 6691 goto out_delayed_unlock;
1887be66 6692
d7df2c79 6693 spin_lock(&head->lock);
c6fc2454 6694 if (!list_empty(&head->ref_list))
1887be66
CM
6695 goto out;
6696
5d4f98a2
YZ
6697 if (head->extent_op) {
6698 if (!head->must_insert_reserved)
6699 goto out;
78a6184a 6700 btrfs_free_delayed_extent_op(head->extent_op);
5d4f98a2
YZ
6701 head->extent_op = NULL;
6702 }
6703
1887be66
CM
6704 /*
6705 * waiting for the lock here would deadlock. If someone else has it
6706 * locked they are already in the process of dropping it anyway
6707 */
6708 if (!mutex_trylock(&head->mutex))
6709 goto out;
6710
6711 /*
6712 * at this point we have a head with no other entries. Go
6713 * ahead and process it.
6714 */
6715 head->node.in_tree = 0;
c46effa6 6716 rb_erase(&head->href_node, &delayed_refs->href_root);
c3e69d58 6717
d7df2c79 6718 atomic_dec(&delayed_refs->num_entries);
1887be66
CM
6719
6720 /*
6721 * we don't take a ref on the node because we're removing it from the
6722 * tree, so we just steal the ref the tree was holding.
6723 */
c3e69d58 6724 delayed_refs->num_heads--;
d7df2c79 6725 if (head->processing == 0)
c3e69d58 6726 delayed_refs->num_heads_ready--;
d7df2c79
JB
6727 head->processing = 0;
6728 spin_unlock(&head->lock);
1887be66
CM
6729 spin_unlock(&delayed_refs->lock);
6730
f0486c68
YZ
6731 BUG_ON(head->extent_op);
6732 if (head->must_insert_reserved)
6733 ret = 1;
6734
6735 mutex_unlock(&head->mutex);
1887be66 6736 btrfs_put_delayed_ref(&head->node);
f0486c68 6737 return ret;
1887be66 6738out:
d7df2c79 6739 spin_unlock(&head->lock);
cf93da7b
CM
6740
6741out_delayed_unlock:
1887be66
CM
6742 spin_unlock(&delayed_refs->lock);
6743 return 0;
6744}
6745
f0486c68
YZ
6746void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
6747 struct btrfs_root *root,
6748 struct extent_buffer *buf,
5581a51a 6749 u64 parent, int last_ref)
f0486c68 6750{
b150a4f1 6751 int pin = 1;
f0486c68
YZ
6752 int ret;
6753
6754 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
66d7e7f0
AJ
6755 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
6756 buf->start, buf->len,
6757 parent, root->root_key.objectid,
6758 btrfs_header_level(buf),
b06c4bf5 6759 BTRFS_DROP_DELAYED_REF, NULL);
79787eaa 6760 BUG_ON(ret); /* -ENOMEM */
f0486c68
YZ
6761 }
6762
6763 if (!last_ref)
6764 return;
6765
f0486c68 6766 if (btrfs_header_generation(buf) == trans->transid) {
6219872d
FM
6767 struct btrfs_block_group_cache *cache;
6768
f0486c68
YZ
6769 if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
6770 ret = check_ref_cleanup(trans, root, buf->start);
6771 if (!ret)
37be25bc 6772 goto out;
f0486c68
YZ
6773 }
6774
6219872d
FM
6775 cache = btrfs_lookup_block_group(root->fs_info, buf->start);
6776
f0486c68
YZ
6777 if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
6778 pin_down_extent(root, cache, buf->start, buf->len, 1);
6219872d 6779 btrfs_put_block_group(cache);
37be25bc 6780 goto out;
f0486c68
YZ
6781 }
6782
6783 WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
6784
6785 btrfs_add_free_space(cache, buf->start, buf->len);
e570fd27 6786 btrfs_update_reserved_bytes(cache, buf->len, RESERVE_FREE, 0);
6219872d 6787 btrfs_put_block_group(cache);
0be5dc67 6788 trace_btrfs_reserved_extent_free(root, buf->start, buf->len);
b150a4f1 6789 pin = 0;
f0486c68
YZ
6790 }
6791out:
b150a4f1
JB
6792 if (pin)
6793 add_pinned_bytes(root->fs_info, buf->len,
6794 btrfs_header_level(buf),
6795 root->root_key.objectid);
6796
a826d6dc
JB
6797 /*
6798 * Deleting the buffer, clear the corrupt flag since it doesn't matter
6799 * anymore.
6800 */
6801 clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
f0486c68
YZ
6802}
6803
79787eaa 6804/* Can return -ENOMEM */
66d7e7f0
AJ
6805int btrfs_free_extent(struct btrfs_trans_handle *trans, struct btrfs_root *root,
6806 u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
b06c4bf5 6807 u64 owner, u64 offset)
925baedd
CM
6808{
6809 int ret;
66d7e7f0 6810 struct btrfs_fs_info *fs_info = root->fs_info;
925baedd 6811
fccb84c9 6812 if (btrfs_test_is_dummy_root(root))
faa2dbf0 6813 return 0;
fccb84c9 6814
b150a4f1
JB
6815 add_pinned_bytes(root->fs_info, num_bytes, owner, root_objectid);
6816
56bec294
CM
6817 /*
6818 * tree log blocks never actually go into the extent allocation
6819 * tree, just update pinning info and exit early.
56bec294 6820 */
5d4f98a2
YZ
6821 if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
6822 WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
b9473439 6823 /* unlocks the pinned mutex */
11833d66 6824 btrfs_pin_extent(root, bytenr, num_bytes, 1);
56bec294 6825 ret = 0;
5d4f98a2 6826 } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
66d7e7f0
AJ
6827 ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
6828 num_bytes,
5d4f98a2 6829 parent, root_objectid, (int)owner,
b06c4bf5 6830 BTRFS_DROP_DELAYED_REF, NULL);
5d4f98a2 6831 } else {
66d7e7f0
AJ
6832 ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
6833 num_bytes,
6834 parent, root_objectid, owner,
5846a3c2
QW
6835 offset, 0,
6836 BTRFS_DROP_DELAYED_REF, NULL);
56bec294 6837 }
925baedd
CM
6838 return ret;
6839}
6840
817d52f8
JB
6841/*
6842 * when we wait for progress in the block group caching, its because
6843 * our allocation attempt failed at least once. So, we must sleep
6844 * and let some progress happen before we try again.
6845 *
6846 * This function will sleep at least once waiting for new free space to
6847 * show up, and then it will check the block group free space numbers
6848 * for our min num_bytes. Another option is to have it go ahead
6849 * and look in the rbtree for a free extent of a given size, but this
6850 * is a good start.
36cce922
JB
6851 *
6852 * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
6853 * any of the information in this block group.
817d52f8 6854 */
36cce922 6855static noinline void
817d52f8
JB
6856wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
6857 u64 num_bytes)
6858{
11833d66 6859 struct btrfs_caching_control *caching_ctl;
817d52f8 6860
11833d66
YZ
6861 caching_ctl = get_caching_control(cache);
6862 if (!caching_ctl)
36cce922 6863 return;
817d52f8 6864
11833d66 6865 wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
34d52cb6 6866 (cache->free_space_ctl->free_space >= num_bytes));
11833d66
YZ
6867
6868 put_caching_control(caching_ctl);
11833d66
YZ
6869}
6870
6871static noinline int
6872wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
6873{
6874 struct btrfs_caching_control *caching_ctl;
36cce922 6875 int ret = 0;
11833d66
YZ
6876
6877 caching_ctl = get_caching_control(cache);
6878 if (!caching_ctl)
36cce922 6879 return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
11833d66
YZ
6880
6881 wait_event(caching_ctl->wait, block_group_cache_done(cache));
36cce922
JB
6882 if (cache->cached == BTRFS_CACHE_ERROR)
6883 ret = -EIO;
11833d66 6884 put_caching_control(caching_ctl);
36cce922 6885 return ret;
817d52f8
JB
6886}
6887
31e50229 6888int __get_raid_index(u64 flags)
b742bb82 6889{
7738a53a 6890 if (flags & BTRFS_BLOCK_GROUP_RAID10)
e6ec716f 6891 return BTRFS_RAID_RAID10;
7738a53a 6892 else if (flags & BTRFS_BLOCK_GROUP_RAID1)
e6ec716f 6893 return BTRFS_RAID_RAID1;
7738a53a 6894 else if (flags & BTRFS_BLOCK_GROUP_DUP)
e6ec716f 6895 return BTRFS_RAID_DUP;
7738a53a 6896 else if (flags & BTRFS_BLOCK_GROUP_RAID0)
e6ec716f 6897 return BTRFS_RAID_RAID0;
53b381b3 6898 else if (flags & BTRFS_BLOCK_GROUP_RAID5)
e942f883 6899 return BTRFS_RAID_RAID5;
53b381b3 6900 else if (flags & BTRFS_BLOCK_GROUP_RAID6)
e942f883 6901 return BTRFS_RAID_RAID6;
7738a53a 6902
e942f883 6903 return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
b742bb82
YZ
6904}
6905
6ab0a202 6906int get_block_group_index(struct btrfs_block_group_cache *cache)
7738a53a 6907{
31e50229 6908 return __get_raid_index(cache->flags);
7738a53a
ID
6909}
6910
6ab0a202
JM
6911static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
6912 [BTRFS_RAID_RAID10] = "raid10",
6913 [BTRFS_RAID_RAID1] = "raid1",
6914 [BTRFS_RAID_DUP] = "dup",
6915 [BTRFS_RAID_RAID0] = "raid0",
6916 [BTRFS_RAID_SINGLE] = "single",
6917 [BTRFS_RAID_RAID5] = "raid5",
6918 [BTRFS_RAID_RAID6] = "raid6",
6919};
6920
1b8e5df6 6921static const char *get_raid_name(enum btrfs_raid_types type)
6ab0a202
JM
6922{
6923 if (type >= BTRFS_NR_RAID_TYPES)
6924 return NULL;
6925
6926 return btrfs_raid_type_names[type];
6927}
6928
817d52f8 6929enum btrfs_loop_type {
285ff5af
JB
6930 LOOP_CACHING_NOWAIT = 0,
6931 LOOP_CACHING_WAIT = 1,
6932 LOOP_ALLOC_CHUNK = 2,
6933 LOOP_NO_EMPTY_SIZE = 3,
817d52f8
JB
6934};
6935
e570fd27
MX
6936static inline void
6937btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
6938 int delalloc)
6939{
6940 if (delalloc)
6941 down_read(&cache->data_rwsem);
6942}
6943
6944static inline void
6945btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
6946 int delalloc)
6947{
6948 btrfs_get_block_group(cache);
6949 if (delalloc)
6950 down_read(&cache->data_rwsem);
6951}
6952
6953static struct btrfs_block_group_cache *
6954btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
6955 struct btrfs_free_cluster *cluster,
6956 int delalloc)
6957{
6958 struct btrfs_block_group_cache *used_bg;
6959 bool locked = false;
6960again:
6961 spin_lock(&cluster->refill_lock);
6962 if (locked) {
6963 if (used_bg == cluster->block_group)
6964 return used_bg;
6965
6966 up_read(&used_bg->data_rwsem);
6967 btrfs_put_block_group(used_bg);
6968 }
6969
6970 used_bg = cluster->block_group;
6971 if (!used_bg)
6972 return NULL;
6973
6974 if (used_bg == block_group)
6975 return used_bg;
6976
6977 btrfs_get_block_group(used_bg);
6978
6979 if (!delalloc)
6980 return used_bg;
6981
6982 if (down_read_trylock(&used_bg->data_rwsem))
6983 return used_bg;
6984
6985 spin_unlock(&cluster->refill_lock);
6986 down_read(&used_bg->data_rwsem);
6987 locked = true;
6988 goto again;
6989}
6990
6991static inline void
6992btrfs_release_block_group(struct btrfs_block_group_cache *cache,
6993 int delalloc)
6994{
6995 if (delalloc)
6996 up_read(&cache->data_rwsem);
6997 btrfs_put_block_group(cache);
6998}
6999
fec577fb
CM
7000/*
7001 * walks the btree of allocated extents and find a hole of a given size.
7002 * The key ins is changed to record the hole:
a4820398 7003 * ins->objectid == start position
62e2749e 7004 * ins->flags = BTRFS_EXTENT_ITEM_KEY
a4820398 7005 * ins->offset == the size of the hole.
fec577fb 7006 * Any available blocks before search_start are skipped.
a4820398
MX
7007 *
7008 * If there is no suitable free space, we will record the max size of
7009 * the free space extent currently.
fec577fb 7010 */
00361589 7011static noinline int find_free_extent(struct btrfs_root *orig_root,
98ed5174 7012 u64 num_bytes, u64 empty_size,
98ed5174 7013 u64 hint_byte, struct btrfs_key *ins,
e570fd27 7014 u64 flags, int delalloc)
fec577fb 7015{
80eb234a 7016 int ret = 0;
d397712b 7017 struct btrfs_root *root = orig_root->fs_info->extent_root;
fa9c0d79 7018 struct btrfs_free_cluster *last_ptr = NULL;
80eb234a 7019 struct btrfs_block_group_cache *block_group = NULL;
81c9ad23 7020 u64 search_start = 0;
a4820398 7021 u64 max_extent_size = 0;
c759c4e1 7022 u64 empty_cluster = 0;
80eb234a 7023 struct btrfs_space_info *space_info;
fa9c0d79 7024 int loop = 0;
b6919a58
DS
7025 int index = __get_raid_index(flags);
7026 int alloc_type = (flags & BTRFS_BLOCK_GROUP_DATA) ?
fb25e914 7027 RESERVE_ALLOC_NO_ACCOUNT : RESERVE_ALLOC;
0a24325e 7028 bool failed_cluster_refill = false;
1cdda9b8 7029 bool failed_alloc = false;
67377734 7030 bool use_cluster = true;
60d2adbb 7031 bool have_caching_bg = false;
a5e681d9 7032 bool full_search = false;
fec577fb 7033
db94535d 7034 WARN_ON(num_bytes < root->sectorsize);
962a298f 7035 ins->type = BTRFS_EXTENT_ITEM_KEY;
80eb234a
JB
7036 ins->objectid = 0;
7037 ins->offset = 0;
b1a4d965 7038
b6919a58 7039 trace_find_free_extent(orig_root, num_bytes, empty_size, flags);
3f7de037 7040
b6919a58 7041 space_info = __find_space_info(root->fs_info, flags);
1b1d1f66 7042 if (!space_info) {
b6919a58 7043 btrfs_err(root->fs_info, "No space info for %llu", flags);
1b1d1f66
JB
7044 return -ENOSPC;
7045 }
2552d17e 7046
67377734 7047 /*
4f4db217
JB
7048 * If our free space is heavily fragmented we may not be able to make
7049 * big contiguous allocations, so instead of doing the expensive search
7050 * for free space, simply return ENOSPC with our max_extent_size so we
7051 * can go ahead and search for a more manageable chunk.
7052 *
7053 * If our max_extent_size is large enough for our allocation simply
7054 * disable clustering since we will likely not be able to find enough
7055 * space to create a cluster and induce latency trying.
67377734 7056 */
4f4db217
JB
7057 if (unlikely(space_info->max_extent_size)) {
7058 spin_lock(&space_info->lock);
7059 if (space_info->max_extent_size &&
7060 num_bytes > space_info->max_extent_size) {
7061 ins->offset = space_info->max_extent_size;
7062 spin_unlock(&space_info->lock);
7063 return -ENOSPC;
7064 } else if (space_info->max_extent_size) {
7065 use_cluster = false;
7066 }
7067 spin_unlock(&space_info->lock);
fa9c0d79 7068 }
0f9dd46c 7069
c759c4e1 7070 last_ptr = fetch_cluster_info(orig_root, space_info, &empty_cluster);
239b14b3 7071 if (last_ptr) {
fa9c0d79
CM
7072 spin_lock(&last_ptr->lock);
7073 if (last_ptr->block_group)
7074 hint_byte = last_ptr->window_start;
c759c4e1
JB
7075 if (last_ptr->fragmented) {
7076 /*
7077 * We still set window_start so we can keep track of the
7078 * last place we found an allocation to try and save
7079 * some time.
7080 */
7081 hint_byte = last_ptr->window_start;
7082 use_cluster = false;
7083 }
fa9c0d79 7084 spin_unlock(&last_ptr->lock);
239b14b3 7085 }
fa9c0d79 7086
a061fc8d 7087 search_start = max(search_start, first_logical_byte(root, 0));
239b14b3 7088 search_start = max(search_start, hint_byte);
2552d17e 7089 if (search_start == hint_byte) {
2552d17e
JB
7090 block_group = btrfs_lookup_block_group(root->fs_info,
7091 search_start);
817d52f8
JB
7092 /*
7093 * we don't want to use the block group if it doesn't match our
7094 * allocation bits, or if its not cached.
ccf0e725
JB
7095 *
7096 * However if we are re-searching with an ideal block group
7097 * picked out then we don't care that the block group is cached.
817d52f8 7098 */
b6919a58 7099 if (block_group && block_group_bits(block_group, flags) &&
285ff5af 7100 block_group->cached != BTRFS_CACHE_NO) {
2552d17e 7101 down_read(&space_info->groups_sem);
44fb5511
CM
7102 if (list_empty(&block_group->list) ||
7103 block_group->ro) {
7104 /*
7105 * someone is removing this block group,
7106 * we can't jump into the have_block_group
7107 * target because our list pointers are not
7108 * valid
7109 */
7110 btrfs_put_block_group(block_group);
7111 up_read(&space_info->groups_sem);
ccf0e725 7112 } else {
b742bb82 7113 index = get_block_group_index(block_group);
e570fd27 7114 btrfs_lock_block_group(block_group, delalloc);
44fb5511 7115 goto have_block_group;
ccf0e725 7116 }
2552d17e 7117 } else if (block_group) {
fa9c0d79 7118 btrfs_put_block_group(block_group);
2552d17e 7119 }
42e70e7a 7120 }
2552d17e 7121search:
60d2adbb 7122 have_caching_bg = false;
a5e681d9
JB
7123 if (index == 0 || index == __get_raid_index(flags))
7124 full_search = true;
80eb234a 7125 down_read(&space_info->groups_sem);
b742bb82
YZ
7126 list_for_each_entry(block_group, &space_info->block_groups[index],
7127 list) {
6226cb0a 7128 u64 offset;
817d52f8 7129 int cached;
8a1413a2 7130
e570fd27 7131 btrfs_grab_block_group(block_group, delalloc);
2552d17e 7132 search_start = block_group->key.objectid;
42e70e7a 7133
83a50de9
CM
7134 /*
7135 * this can happen if we end up cycling through all the
7136 * raid types, but we want to make sure we only allocate
7137 * for the proper type.
7138 */
b6919a58 7139 if (!block_group_bits(block_group, flags)) {
83a50de9
CM
7140 u64 extra = BTRFS_BLOCK_GROUP_DUP |
7141 BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
7142 BTRFS_BLOCK_GROUP_RAID5 |
7143 BTRFS_BLOCK_GROUP_RAID6 |
83a50de9
CM
7144 BTRFS_BLOCK_GROUP_RAID10;
7145
7146 /*
7147 * if they asked for extra copies and this block group
7148 * doesn't provide them, bail. This does allow us to
7149 * fill raid0 from raid1.
7150 */
b6919a58 7151 if ((flags & extra) && !(block_group->flags & extra))
83a50de9
CM
7152 goto loop;
7153 }
7154
2552d17e 7155have_block_group:
291c7d2f
JB
7156 cached = block_group_cache_done(block_group);
7157 if (unlikely(!cached)) {
a5e681d9 7158 have_caching_bg = true;
f6373bf3 7159 ret = cache_block_group(block_group, 0);
1d4284bd
CM
7160 BUG_ON(ret < 0);
7161 ret = 0;
817d52f8
JB
7162 }
7163
36cce922
JB
7164 if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
7165 goto loop;
ea6a478e 7166 if (unlikely(block_group->ro))
2552d17e 7167 goto loop;
0f9dd46c 7168
0a24325e 7169 /*
062c05c4
AO
7170 * Ok we want to try and use the cluster allocator, so
7171 * lets look there
0a24325e 7172 */
c759c4e1 7173 if (last_ptr && use_cluster) {
215a63d1 7174 struct btrfs_block_group_cache *used_block_group;
8de972b4 7175 unsigned long aligned_cluster;
fa9c0d79
CM
7176 /*
7177 * the refill lock keeps out other
7178 * people trying to start a new cluster
7179 */
e570fd27
MX
7180 used_block_group = btrfs_lock_cluster(block_group,
7181 last_ptr,
7182 delalloc);
7183 if (!used_block_group)
44fb5511 7184 goto refill_cluster;
274bd4fb 7185
e570fd27
MX
7186 if (used_block_group != block_group &&
7187 (used_block_group->ro ||
7188 !block_group_bits(used_block_group, flags)))
7189 goto release_cluster;
44fb5511 7190
274bd4fb 7191 offset = btrfs_alloc_from_cluster(used_block_group,
a4820398
MX
7192 last_ptr,
7193 num_bytes,
7194 used_block_group->key.objectid,
7195 &max_extent_size);
fa9c0d79
CM
7196 if (offset) {
7197 /* we have a block, we're done */
7198 spin_unlock(&last_ptr->refill_lock);
3f7de037 7199 trace_btrfs_reserve_extent_cluster(root,
89d4346a
MX
7200 used_block_group,
7201 search_start, num_bytes);
215a63d1 7202 if (used_block_group != block_group) {
e570fd27
MX
7203 btrfs_release_block_group(block_group,
7204 delalloc);
215a63d1
MX
7205 block_group = used_block_group;
7206 }
fa9c0d79
CM
7207 goto checks;
7208 }
7209
274bd4fb 7210 WARN_ON(last_ptr->block_group != used_block_group);
e570fd27 7211release_cluster:
062c05c4
AO
7212 /* If we are on LOOP_NO_EMPTY_SIZE, we can't
7213 * set up a new clusters, so lets just skip it
7214 * and let the allocator find whatever block
7215 * it can find. If we reach this point, we
7216 * will have tried the cluster allocator
7217 * plenty of times and not have found
7218 * anything, so we are likely way too
7219 * fragmented for the clustering stuff to find
a5f6f719
AO
7220 * anything.
7221 *
7222 * However, if the cluster is taken from the
7223 * current block group, release the cluster
7224 * first, so that we stand a better chance of
7225 * succeeding in the unclustered
7226 * allocation. */
7227 if (loop >= LOOP_NO_EMPTY_SIZE &&
e570fd27 7228 used_block_group != block_group) {
062c05c4 7229 spin_unlock(&last_ptr->refill_lock);
e570fd27
MX
7230 btrfs_release_block_group(used_block_group,
7231 delalloc);
062c05c4
AO
7232 goto unclustered_alloc;
7233 }
7234
fa9c0d79
CM
7235 /*
7236 * this cluster didn't work out, free it and
7237 * start over
7238 */
7239 btrfs_return_cluster_to_free_space(NULL, last_ptr);
7240
e570fd27
MX
7241 if (used_block_group != block_group)
7242 btrfs_release_block_group(used_block_group,
7243 delalloc);
7244refill_cluster:
a5f6f719
AO
7245 if (loop >= LOOP_NO_EMPTY_SIZE) {
7246 spin_unlock(&last_ptr->refill_lock);
7247 goto unclustered_alloc;
7248 }
7249
8de972b4
CM
7250 aligned_cluster = max_t(unsigned long,
7251 empty_cluster + empty_size,
7252 block_group->full_stripe_len);
7253
fa9c0d79 7254 /* allocate a cluster in this block group */
00361589
JB
7255 ret = btrfs_find_space_cluster(root, block_group,
7256 last_ptr, search_start,
7257 num_bytes,
7258 aligned_cluster);
fa9c0d79
CM
7259 if (ret == 0) {
7260 /*
7261 * now pull our allocation out of this
7262 * cluster
7263 */
7264 offset = btrfs_alloc_from_cluster(block_group,
a4820398
MX
7265 last_ptr,
7266 num_bytes,
7267 search_start,
7268 &max_extent_size);
fa9c0d79
CM
7269 if (offset) {
7270 /* we found one, proceed */
7271 spin_unlock(&last_ptr->refill_lock);
3f7de037
JB
7272 trace_btrfs_reserve_extent_cluster(root,
7273 block_group, search_start,
7274 num_bytes);
fa9c0d79
CM
7275 goto checks;
7276 }
0a24325e
JB
7277 } else if (!cached && loop > LOOP_CACHING_NOWAIT
7278 && !failed_cluster_refill) {
817d52f8
JB
7279 spin_unlock(&last_ptr->refill_lock);
7280
0a24325e 7281 failed_cluster_refill = true;
817d52f8
JB
7282 wait_block_group_cache_progress(block_group,
7283 num_bytes + empty_cluster + empty_size);
7284 goto have_block_group;
fa9c0d79 7285 }
817d52f8 7286
fa9c0d79
CM
7287 /*
7288 * at this point we either didn't find a cluster
7289 * or we weren't able to allocate a block from our
7290 * cluster. Free the cluster we've been trying
7291 * to use, and go to the next block group
7292 */
0a24325e 7293 btrfs_return_cluster_to_free_space(NULL, last_ptr);
fa9c0d79 7294 spin_unlock(&last_ptr->refill_lock);
0a24325e 7295 goto loop;
fa9c0d79
CM
7296 }
7297
062c05c4 7298unclustered_alloc:
c759c4e1
JB
7299 /*
7300 * We are doing an unclustered alloc, set the fragmented flag so
7301 * we don't bother trying to setup a cluster again until we get
7302 * more space.
7303 */
7304 if (unlikely(last_ptr)) {
7305 spin_lock(&last_ptr->lock);
7306 last_ptr->fragmented = 1;
7307 spin_unlock(&last_ptr->lock);
7308 }
a5f6f719
AO
7309 spin_lock(&block_group->free_space_ctl->tree_lock);
7310 if (cached &&
7311 block_group->free_space_ctl->free_space <
7312 num_bytes + empty_cluster + empty_size) {
a4820398
MX
7313 if (block_group->free_space_ctl->free_space >
7314 max_extent_size)
7315 max_extent_size =
7316 block_group->free_space_ctl->free_space;
a5f6f719
AO
7317 spin_unlock(&block_group->free_space_ctl->tree_lock);
7318 goto loop;
7319 }
7320 spin_unlock(&block_group->free_space_ctl->tree_lock);
7321
6226cb0a 7322 offset = btrfs_find_space_for_alloc(block_group, search_start,
a4820398
MX
7323 num_bytes, empty_size,
7324 &max_extent_size);
1cdda9b8
JB
7325 /*
7326 * If we didn't find a chunk, and we haven't failed on this
7327 * block group before, and this block group is in the middle of
7328 * caching and we are ok with waiting, then go ahead and wait
7329 * for progress to be made, and set failed_alloc to true.
7330 *
7331 * If failed_alloc is true then we've already waited on this
7332 * block group once and should move on to the next block group.
7333 */
7334 if (!offset && !failed_alloc && !cached &&
7335 loop > LOOP_CACHING_NOWAIT) {
817d52f8 7336 wait_block_group_cache_progress(block_group,
1cdda9b8
JB
7337 num_bytes + empty_size);
7338 failed_alloc = true;
817d52f8 7339 goto have_block_group;
1cdda9b8
JB
7340 } else if (!offset) {
7341 goto loop;
817d52f8 7342 }
fa9c0d79 7343checks:
4e54b17a 7344 search_start = ALIGN(offset, root->stripesize);
25179201 7345
2552d17e
JB
7346 /* move on to the next group */
7347 if (search_start + num_bytes >
215a63d1
MX
7348 block_group->key.objectid + block_group->key.offset) {
7349 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e 7350 goto loop;
6226cb0a 7351 }
f5a31e16 7352
f0486c68 7353 if (offset < search_start)
215a63d1 7354 btrfs_add_free_space(block_group, offset,
f0486c68
YZ
7355 search_start - offset);
7356 BUG_ON(offset > search_start);
2552d17e 7357
215a63d1 7358 ret = btrfs_update_reserved_bytes(block_group, num_bytes,
e570fd27 7359 alloc_type, delalloc);
f0486c68 7360 if (ret == -EAGAIN) {
215a63d1 7361 btrfs_add_free_space(block_group, offset, num_bytes);
2552d17e 7362 goto loop;
0f9dd46c 7363 }
0b86a832 7364
f0486c68 7365 /* we are all good, lets return */
2552d17e
JB
7366 ins->objectid = search_start;
7367 ins->offset = num_bytes;
d2fb3437 7368
3f7de037
JB
7369 trace_btrfs_reserve_extent(orig_root, block_group,
7370 search_start, num_bytes);
e570fd27 7371 btrfs_release_block_group(block_group, delalloc);
2552d17e
JB
7372 break;
7373loop:
0a24325e 7374 failed_cluster_refill = false;
1cdda9b8 7375 failed_alloc = false;
b742bb82 7376 BUG_ON(index != get_block_group_index(block_group));
e570fd27 7377 btrfs_release_block_group(block_group, delalloc);
2552d17e
JB
7378 }
7379 up_read(&space_info->groups_sem);
7380
60d2adbb
MX
7381 if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
7382 goto search;
7383
b742bb82
YZ
7384 if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
7385 goto search;
7386
285ff5af 7387 /*
ccf0e725
JB
7388 * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
7389 * caching kthreads as we move along
817d52f8
JB
7390 * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
7391 * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
7392 * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
7393 * again
fa9c0d79 7394 */
723bda20 7395 if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
b742bb82 7396 index = 0;
a5e681d9
JB
7397 if (loop == LOOP_CACHING_NOWAIT) {
7398 /*
7399 * We want to skip the LOOP_CACHING_WAIT step if we
7400 * don't have any unached bgs and we've alrelady done a
7401 * full search through.
7402 */
7403 if (have_caching_bg || !full_search)
7404 loop = LOOP_CACHING_WAIT;
7405 else
7406 loop = LOOP_ALLOC_CHUNK;
7407 } else {
7408 loop++;
7409 }
7410
817d52f8 7411 if (loop == LOOP_ALLOC_CHUNK) {
00361589 7412 struct btrfs_trans_handle *trans;
f017f15f
WS
7413 int exist = 0;
7414
7415 trans = current->journal_info;
7416 if (trans)
7417 exist = 1;
7418 else
7419 trans = btrfs_join_transaction(root);
00361589 7420
00361589
JB
7421 if (IS_ERR(trans)) {
7422 ret = PTR_ERR(trans);
7423 goto out;
7424 }
7425
b6919a58 7426 ret = do_chunk_alloc(trans, root, flags,
ea658bad 7427 CHUNK_ALLOC_FORCE);
a5e681d9
JB
7428
7429 /*
7430 * If we can't allocate a new chunk we've already looped
7431 * through at least once, move on to the NO_EMPTY_SIZE
7432 * case.
7433 */
7434 if (ret == -ENOSPC)
7435 loop = LOOP_NO_EMPTY_SIZE;
7436
ea658bad
JB
7437 /*
7438 * Do not bail out on ENOSPC since we
7439 * can do more things.
7440 */
00361589 7441 if (ret < 0 && ret != -ENOSPC)
ea658bad
JB
7442 btrfs_abort_transaction(trans,
7443 root, ret);
00361589
JB
7444 else
7445 ret = 0;
f017f15f
WS
7446 if (!exist)
7447 btrfs_end_transaction(trans, root);
00361589 7448 if (ret)
ea658bad 7449 goto out;
2552d17e
JB
7450 }
7451
723bda20 7452 if (loop == LOOP_NO_EMPTY_SIZE) {
a5e681d9
JB
7453 /*
7454 * Don't loop again if we already have no empty_size and
7455 * no empty_cluster.
7456 */
7457 if (empty_size == 0 &&
7458 empty_cluster == 0) {
7459 ret = -ENOSPC;
7460 goto out;
7461 }
723bda20
JB
7462 empty_size = 0;
7463 empty_cluster = 0;
fa9c0d79 7464 }
723bda20
JB
7465
7466 goto search;
2552d17e
JB
7467 } else if (!ins->objectid) {
7468 ret = -ENOSPC;
d82a6f1d 7469 } else if (ins->objectid) {
c759c4e1
JB
7470 if (!use_cluster && last_ptr) {
7471 spin_lock(&last_ptr->lock);
7472 last_ptr->window_start = ins->objectid;
7473 spin_unlock(&last_ptr->lock);
7474 }
80eb234a 7475 ret = 0;
be744175 7476 }
79787eaa 7477out:
4f4db217
JB
7478 if (ret == -ENOSPC) {
7479 spin_lock(&space_info->lock);
7480 space_info->max_extent_size = max_extent_size;
7481 spin_unlock(&space_info->lock);
a4820398 7482 ins->offset = max_extent_size;
4f4db217 7483 }
0f70abe2 7484 return ret;
fec577fb 7485}
ec44a35c 7486
9ed74f2d
JB
7487static void dump_space_info(struct btrfs_space_info *info, u64 bytes,
7488 int dump_block_groups)
0f9dd46c
JB
7489{
7490 struct btrfs_block_group_cache *cache;
b742bb82 7491 int index = 0;
0f9dd46c 7492
9ed74f2d 7493 spin_lock(&info->lock);
efe120a0 7494 printk(KERN_INFO "BTRFS: space_info %llu has %llu free, is %sfull\n",
c1c9ff7c
GU
7495 info->flags,
7496 info->total_bytes - info->bytes_used - info->bytes_pinned -
7497 info->bytes_reserved - info->bytes_readonly,
d397712b 7498 (info->full) ? "" : "not ");
efe120a0 7499 printk(KERN_INFO "BTRFS: space_info total=%llu, used=%llu, pinned=%llu, "
8929ecfa 7500 "reserved=%llu, may_use=%llu, readonly=%llu\n",
c1c9ff7c
GU
7501 info->total_bytes, info->bytes_used, info->bytes_pinned,
7502 info->bytes_reserved, info->bytes_may_use,
7503 info->bytes_readonly);
9ed74f2d
JB
7504 spin_unlock(&info->lock);
7505
7506 if (!dump_block_groups)
7507 return;
0f9dd46c 7508
80eb234a 7509 down_read(&info->groups_sem);
b742bb82
YZ
7510again:
7511 list_for_each_entry(cache, &info->block_groups[index], list) {
0f9dd46c 7512 spin_lock(&cache->lock);
efe120a0
FH
7513 printk(KERN_INFO "BTRFS: "
7514 "block group %llu has %llu bytes, "
7515 "%llu used %llu pinned %llu reserved %s\n",
c1c9ff7c
GU
7516 cache->key.objectid, cache->key.offset,
7517 btrfs_block_group_used(&cache->item), cache->pinned,
7518 cache->reserved, cache->ro ? "[readonly]" : "");
0f9dd46c
JB
7519 btrfs_dump_free_space(cache, bytes);
7520 spin_unlock(&cache->lock);
7521 }
b742bb82
YZ
7522 if (++index < BTRFS_NR_RAID_TYPES)
7523 goto again;
80eb234a 7524 up_read(&info->groups_sem);
0f9dd46c 7525}
e8569813 7526
00361589 7527int btrfs_reserve_extent(struct btrfs_root *root,
11833d66
YZ
7528 u64 num_bytes, u64 min_alloc_size,
7529 u64 empty_size, u64 hint_byte,
e570fd27 7530 struct btrfs_key *ins, int is_data, int delalloc)
fec577fb 7531{
36af4e07 7532 bool final_tried = num_bytes == min_alloc_size;
b6919a58 7533 u64 flags;
fec577fb 7534 int ret;
925baedd 7535
b6919a58 7536 flags = btrfs_get_alloc_profile(root, is_data);
98d20f67 7537again:
db94535d 7538 WARN_ON(num_bytes < root->sectorsize);
00361589 7539 ret = find_free_extent(root, num_bytes, empty_size, hint_byte, ins,
e570fd27 7540 flags, delalloc);
3b951516 7541
9e622d6b 7542 if (ret == -ENOSPC) {
a4820398
MX
7543 if (!final_tried && ins->offset) {
7544 num_bytes = min(num_bytes >> 1, ins->offset);
24542bf7 7545 num_bytes = round_down(num_bytes, root->sectorsize);
9e622d6b 7546 num_bytes = max(num_bytes, min_alloc_size);
9e622d6b
MX
7547 if (num_bytes == min_alloc_size)
7548 final_tried = true;
7549 goto again;
7550 } else if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
7551 struct btrfs_space_info *sinfo;
7552
b6919a58 7553 sinfo = __find_space_info(root->fs_info, flags);
c2cf52eb 7554 btrfs_err(root->fs_info, "allocation failed flags %llu, wanted %llu",
c1c9ff7c 7555 flags, num_bytes);
53804280
JM
7556 if (sinfo)
7557 dump_space_info(sinfo, num_bytes, 1);
9e622d6b 7558 }
925baedd 7559 }
0f9dd46c
JB
7560
7561 return ret;
e6dcd2dc
CM
7562}
7563
e688b725 7564static int __btrfs_free_reserved_extent(struct btrfs_root *root,
e570fd27
MX
7565 u64 start, u64 len,
7566 int pin, int delalloc)
65b51a00 7567{
0f9dd46c 7568 struct btrfs_block_group_cache *cache;
1f3c79a2 7569 int ret = 0;
0f9dd46c 7570
0f9dd46c
JB
7571 cache = btrfs_lookup_block_group(root->fs_info, start);
7572 if (!cache) {
c2cf52eb 7573 btrfs_err(root->fs_info, "Unable to find block group for %llu",
c1c9ff7c 7574 start);
0f9dd46c
JB
7575 return -ENOSPC;
7576 }
1f3c79a2 7577
e688b725
CM
7578 if (pin)
7579 pin_down_extent(root, cache, start, len, 1);
7580 else {
dcc82f47
FM
7581 if (btrfs_test_opt(root, DISCARD))
7582 ret = btrfs_discard_extent(root, start, len, NULL);
e688b725 7583 btrfs_add_free_space(cache, start, len);
e570fd27 7584 btrfs_update_reserved_bytes(cache, len, RESERVE_FREE, delalloc);
e688b725 7585 }
31193213 7586
fa9c0d79 7587 btrfs_put_block_group(cache);
817d52f8 7588
1abe9b8a 7589 trace_btrfs_reserved_extent_free(root, start, len);
7590
e6dcd2dc
CM
7591 return ret;
7592}
7593
e688b725 7594int btrfs_free_reserved_extent(struct btrfs_root *root,
e570fd27 7595 u64 start, u64 len, int delalloc)
e688b725 7596{
e570fd27 7597 return __btrfs_free_reserved_extent(root, start, len, 0, delalloc);
e688b725
CM
7598}
7599
7600int btrfs_free_and_pin_reserved_extent(struct btrfs_root *root,
7601 u64 start, u64 len)
7602{
e570fd27 7603 return __btrfs_free_reserved_extent(root, start, len, 1, 0);
e688b725
CM
7604}
7605
5d4f98a2
YZ
7606static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7607 struct btrfs_root *root,
7608 u64 parent, u64 root_objectid,
7609 u64 flags, u64 owner, u64 offset,
7610 struct btrfs_key *ins, int ref_mod)
e6dcd2dc
CM
7611{
7612 int ret;
5d4f98a2 7613 struct btrfs_fs_info *fs_info = root->fs_info;
e6dcd2dc 7614 struct btrfs_extent_item *extent_item;
5d4f98a2 7615 struct btrfs_extent_inline_ref *iref;
e6dcd2dc 7616 struct btrfs_path *path;
5d4f98a2
YZ
7617 struct extent_buffer *leaf;
7618 int type;
7619 u32 size;
26b8003f 7620
5d4f98a2
YZ
7621 if (parent > 0)
7622 type = BTRFS_SHARED_DATA_REF_KEY;
7623 else
7624 type = BTRFS_EXTENT_DATA_REF_KEY;
58176a96 7625
5d4f98a2 7626 size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
7bb86316
CM
7627
7628 path = btrfs_alloc_path();
db5b493a
TI
7629 if (!path)
7630 return -ENOMEM;
47e4bb98 7631
b9473439 7632 path->leave_spinning = 1;
5d4f98a2
YZ
7633 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7634 ins, size);
79787eaa
JM
7635 if (ret) {
7636 btrfs_free_path(path);
7637 return ret;
7638 }
0f9dd46c 7639
5d4f98a2
YZ
7640 leaf = path->nodes[0];
7641 extent_item = btrfs_item_ptr(leaf, path->slots[0],
47e4bb98 7642 struct btrfs_extent_item);
5d4f98a2
YZ
7643 btrfs_set_extent_refs(leaf, extent_item, ref_mod);
7644 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7645 btrfs_set_extent_flags(leaf, extent_item,
7646 flags | BTRFS_EXTENT_FLAG_DATA);
7647
7648 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
7649 btrfs_set_extent_inline_ref_type(leaf, iref, type);
7650 if (parent > 0) {
7651 struct btrfs_shared_data_ref *ref;
7652 ref = (struct btrfs_shared_data_ref *)(iref + 1);
7653 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
7654 btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
7655 } else {
7656 struct btrfs_extent_data_ref *ref;
7657 ref = (struct btrfs_extent_data_ref *)(&iref->offset);
7658 btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
7659 btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
7660 btrfs_set_extent_data_ref_offset(leaf, ref, offset);
7661 btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
7662 }
47e4bb98
CM
7663
7664 btrfs_mark_buffer_dirty(path->nodes[0]);
7bb86316 7665 btrfs_free_path(path);
f510cfec 7666
ce93ec54 7667 ret = update_block_group(trans, root, ins->objectid, ins->offset, 1);
79787eaa 7668 if (ret) { /* -ENOENT, logic error */
c2cf52eb 7669 btrfs_err(fs_info, "update block group failed for %llu %llu",
c1c9ff7c 7670 ins->objectid, ins->offset);
f5947066
CM
7671 BUG();
7672 }
0be5dc67 7673 trace_btrfs_reserved_extent_alloc(root, ins->objectid, ins->offset);
e6dcd2dc
CM
7674 return ret;
7675}
7676
5d4f98a2
YZ
7677static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
7678 struct btrfs_root *root,
7679 u64 parent, u64 root_objectid,
7680 u64 flags, struct btrfs_disk_key *key,
b06c4bf5 7681 int level, struct btrfs_key *ins)
e6dcd2dc
CM
7682{
7683 int ret;
5d4f98a2
YZ
7684 struct btrfs_fs_info *fs_info = root->fs_info;
7685 struct btrfs_extent_item *extent_item;
7686 struct btrfs_tree_block_info *block_info;
7687 struct btrfs_extent_inline_ref *iref;
7688 struct btrfs_path *path;
7689 struct extent_buffer *leaf;
3173a18f 7690 u32 size = sizeof(*extent_item) + sizeof(*iref);
fcebe456 7691 u64 num_bytes = ins->offset;
3173a18f
JB
7692 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
7693 SKINNY_METADATA);
7694
7695 if (!skinny_metadata)
7696 size += sizeof(*block_info);
1c2308f8 7697
5d4f98a2 7698 path = btrfs_alloc_path();
857cc2fc
JB
7699 if (!path) {
7700 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
707e8a07 7701 root->nodesize);
d8926bb3 7702 return -ENOMEM;
857cc2fc 7703 }
56bec294 7704
5d4f98a2
YZ
7705 path->leave_spinning = 1;
7706 ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
7707 ins, size);
79787eaa 7708 if (ret) {
dd825259 7709 btrfs_free_path(path);
857cc2fc 7710 btrfs_free_and_pin_reserved_extent(root, ins->objectid,
707e8a07 7711 root->nodesize);
79787eaa
JM
7712 return ret;
7713 }
5d4f98a2
YZ
7714
7715 leaf = path->nodes[0];
7716 extent_item = btrfs_item_ptr(leaf, path->slots[0],
7717 struct btrfs_extent_item);
7718 btrfs_set_extent_refs(leaf, extent_item, 1);
7719 btrfs_set_extent_generation(leaf, extent_item, trans->transid);
7720 btrfs_set_extent_flags(leaf, extent_item,
7721 flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
5d4f98a2 7722
3173a18f
JB
7723 if (skinny_metadata) {
7724 iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
707e8a07 7725 num_bytes = root->nodesize;
3173a18f
JB
7726 } else {
7727 block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
7728 btrfs_set_tree_block_key(leaf, block_info, key);
7729 btrfs_set_tree_block_level(leaf, block_info, level);
7730 iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
7731 }
5d4f98a2 7732
5d4f98a2
YZ
7733 if (parent > 0) {
7734 BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
7735 btrfs_set_extent_inline_ref_type(leaf, iref,
7736 BTRFS_SHARED_BLOCK_REF_KEY);
7737 btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
7738 } else {
7739 btrfs_set_extent_inline_ref_type(leaf, iref,
7740 BTRFS_TREE_BLOCK_REF_KEY);
7741 btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
7742 }
7743
7744 btrfs_mark_buffer_dirty(leaf);
7745 btrfs_free_path(path);
7746
ce93ec54
JB
7747 ret = update_block_group(trans, root, ins->objectid, root->nodesize,
7748 1);
79787eaa 7749 if (ret) { /* -ENOENT, logic error */
c2cf52eb 7750 btrfs_err(fs_info, "update block group failed for %llu %llu",
c1c9ff7c 7751 ins->objectid, ins->offset);
5d4f98a2
YZ
7752 BUG();
7753 }
0be5dc67 7754
707e8a07 7755 trace_btrfs_reserved_extent_alloc(root, ins->objectid, root->nodesize);
5d4f98a2
YZ
7756 return ret;
7757}
7758
7759int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
7760 struct btrfs_root *root,
7761 u64 root_objectid, u64 owner,
5846a3c2
QW
7762 u64 offset, u64 ram_bytes,
7763 struct btrfs_key *ins)
5d4f98a2
YZ
7764{
7765 int ret;
7766
7767 BUG_ON(root_objectid == BTRFS_TREE_LOG_OBJECTID);
7768
66d7e7f0
AJ
7769 ret = btrfs_add_delayed_data_ref(root->fs_info, trans, ins->objectid,
7770 ins->offset, 0,
7771 root_objectid, owner, offset,
5846a3c2
QW
7772 ram_bytes, BTRFS_ADD_DELAYED_EXTENT,
7773 NULL);
e6dcd2dc
CM
7774 return ret;
7775}
e02119d5
CM
7776
7777/*
7778 * this is used by the tree logging recovery code. It records that
7779 * an extent has been allocated and makes sure to clear the free
7780 * space cache bits as well
7781 */
5d4f98a2
YZ
7782int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
7783 struct btrfs_root *root,
7784 u64 root_objectid, u64 owner, u64 offset,
7785 struct btrfs_key *ins)
e02119d5
CM
7786{
7787 int ret;
7788 struct btrfs_block_group_cache *block_group;
11833d66 7789
8c2a1a30
JB
7790 /*
7791 * Mixed block groups will exclude before processing the log so we only
7792 * need to do the exlude dance if this fs isn't mixed.
7793 */
7794 if (!btrfs_fs_incompat(root->fs_info, MIXED_GROUPS)) {
7795 ret = __exclude_logged_extent(root, ins->objectid, ins->offset);
b50c6e25 7796 if (ret)
8c2a1a30 7797 return ret;
11833d66
YZ
7798 }
7799
8c2a1a30
JB
7800 block_group = btrfs_lookup_block_group(root->fs_info, ins->objectid);
7801 if (!block_group)
7802 return -EINVAL;
7803
fb25e914 7804 ret = btrfs_update_reserved_bytes(block_group, ins->offset,
e570fd27 7805 RESERVE_ALLOC_NO_ACCOUNT, 0);
79787eaa 7806 BUG_ON(ret); /* logic error */
5d4f98a2
YZ
7807 ret = alloc_reserved_file_extent(trans, root, 0, root_objectid,
7808 0, owner, offset, ins, 1);
b50c6e25 7809 btrfs_put_block_group(block_group);
e02119d5
CM
7810 return ret;
7811}
7812
48a3b636
ES
7813static struct extent_buffer *
7814btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
fe864576 7815 u64 bytenr, int level)
65b51a00
CM
7816{
7817 struct extent_buffer *buf;
7818
a83fffb7 7819 buf = btrfs_find_create_tree_block(root, bytenr);
65b51a00
CM
7820 if (!buf)
7821 return ERR_PTR(-ENOMEM);
7822 btrfs_set_header_generation(buf, trans->transid);
85d4e461 7823 btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
65b51a00 7824 btrfs_tree_lock(buf);
01d58472 7825 clean_tree_block(trans, root->fs_info, buf);
3083ee2e 7826 clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
b4ce94de
CM
7827
7828 btrfs_set_lock_blocking(buf);
65b51a00 7829 btrfs_set_buffer_uptodate(buf);
b4ce94de 7830
d0c803c4 7831 if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
656f30db 7832 buf->log_index = root->log_transid % 2;
8cef4e16
YZ
7833 /*
7834 * we allow two log transactions at a time, use different
7835 * EXENT bit to differentiate dirty pages.
7836 */
656f30db 7837 if (buf->log_index == 0)
8cef4e16
YZ
7838 set_extent_dirty(&root->dirty_log_pages, buf->start,
7839 buf->start + buf->len - 1, GFP_NOFS);
7840 else
7841 set_extent_new(&root->dirty_log_pages, buf->start,
7842 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4 7843 } else {
656f30db 7844 buf->log_index = -1;
d0c803c4 7845 set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
65b51a00 7846 buf->start + buf->len - 1, GFP_NOFS);
d0c803c4 7847 }
65b51a00 7848 trans->blocks_used++;
b4ce94de 7849 /* this returns a buffer locked for blocking */
65b51a00
CM
7850 return buf;
7851}
7852
f0486c68
YZ
7853static struct btrfs_block_rsv *
7854use_block_rsv(struct btrfs_trans_handle *trans,
7855 struct btrfs_root *root, u32 blocksize)
7856{
7857 struct btrfs_block_rsv *block_rsv;
68a82277 7858 struct btrfs_block_rsv *global_rsv = &root->fs_info->global_block_rsv;
f0486c68 7859 int ret;
d88033db 7860 bool global_updated = false;
f0486c68
YZ
7861
7862 block_rsv = get_block_rsv(trans, root);
7863
b586b323
MX
7864 if (unlikely(block_rsv->size == 0))
7865 goto try_reserve;
d88033db 7866again:
f0486c68
YZ
7867 ret = block_rsv_use_bytes(block_rsv, blocksize);
7868 if (!ret)
7869 return block_rsv;
7870
b586b323
MX
7871 if (block_rsv->failfast)
7872 return ERR_PTR(ret);
7873
d88033db
MX
7874 if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
7875 global_updated = true;
7876 update_global_block_rsv(root->fs_info);
7877 goto again;
7878 }
7879
b586b323
MX
7880 if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
7881 static DEFINE_RATELIMIT_STATE(_rs,
7882 DEFAULT_RATELIMIT_INTERVAL * 10,
7883 /*DEFAULT_RATELIMIT_BURST*/ 1);
7884 if (__ratelimit(&_rs))
7885 WARN(1, KERN_DEBUG
efe120a0 7886 "BTRFS: block rsv returned %d\n", ret);
b586b323
MX
7887 }
7888try_reserve:
7889 ret = reserve_metadata_bytes(root, block_rsv, blocksize,
7890 BTRFS_RESERVE_NO_FLUSH);
7891 if (!ret)
7892 return block_rsv;
7893 /*
7894 * If we couldn't reserve metadata bytes try and use some from
5881cfc9
MX
7895 * the global reserve if its space type is the same as the global
7896 * reservation.
b586b323 7897 */
5881cfc9
MX
7898 if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
7899 block_rsv->space_info == global_rsv->space_info) {
b586b323
MX
7900 ret = block_rsv_use_bytes(global_rsv, blocksize);
7901 if (!ret)
7902 return global_rsv;
7903 }
7904 return ERR_PTR(ret);
f0486c68
YZ
7905}
7906
8c2a3ca2
JB
7907static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
7908 struct btrfs_block_rsv *block_rsv, u32 blocksize)
f0486c68
YZ
7909{
7910 block_rsv_add_bytes(block_rsv, blocksize, 0);
8c2a3ca2 7911 block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
f0486c68
YZ
7912}
7913
fec577fb 7914/*
f0486c68 7915 * finds a free extent and does all the dirty work required for allocation
67b7859e 7916 * returns the tree buffer or an ERR_PTR on error.
fec577fb 7917 */
4d75f8a9
DS
7918struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
7919 struct btrfs_root *root,
5d4f98a2
YZ
7920 u64 parent, u64 root_objectid,
7921 struct btrfs_disk_key *key, int level,
5581a51a 7922 u64 hint, u64 empty_size)
fec577fb 7923{
e2fa7227 7924 struct btrfs_key ins;
f0486c68 7925 struct btrfs_block_rsv *block_rsv;
5f39d397 7926 struct extent_buffer *buf;
67b7859e 7927 struct btrfs_delayed_extent_op *extent_op;
f0486c68
YZ
7928 u64 flags = 0;
7929 int ret;
4d75f8a9 7930 u32 blocksize = root->nodesize;
3173a18f
JB
7931 bool skinny_metadata = btrfs_fs_incompat(root->fs_info,
7932 SKINNY_METADATA);
fec577fb 7933
fccb84c9 7934 if (btrfs_test_is_dummy_root(root)) {
faa2dbf0 7935 buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
fe864576 7936 level);
faa2dbf0
JB
7937 if (!IS_ERR(buf))
7938 root->alloc_bytenr += blocksize;
7939 return buf;
7940 }
fccb84c9 7941
f0486c68
YZ
7942 block_rsv = use_block_rsv(trans, root, blocksize);
7943 if (IS_ERR(block_rsv))
7944 return ERR_CAST(block_rsv);
7945
00361589 7946 ret = btrfs_reserve_extent(root, blocksize, blocksize,
e570fd27 7947 empty_size, hint, &ins, 0, 0);
67b7859e
OS
7948 if (ret)
7949 goto out_unuse;
55c69072 7950
fe864576 7951 buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
67b7859e
OS
7952 if (IS_ERR(buf)) {
7953 ret = PTR_ERR(buf);
7954 goto out_free_reserved;
7955 }
f0486c68
YZ
7956
7957 if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
7958 if (parent == 0)
7959 parent = ins.objectid;
7960 flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
7961 } else
7962 BUG_ON(parent > 0);
7963
7964 if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
78a6184a 7965 extent_op = btrfs_alloc_delayed_extent_op();
67b7859e
OS
7966 if (!extent_op) {
7967 ret = -ENOMEM;
7968 goto out_free_buf;
7969 }
f0486c68
YZ
7970 if (key)
7971 memcpy(&extent_op->key, key, sizeof(extent_op->key));
7972 else
7973 memset(&extent_op->key, 0, sizeof(extent_op->key));
7974 extent_op->flags_to_set = flags;
3173a18f
JB
7975 if (skinny_metadata)
7976 extent_op->update_key = 0;
7977 else
7978 extent_op->update_key = 1;
f0486c68
YZ
7979 extent_op->update_flags = 1;
7980 extent_op->is_data = 0;
b1c79e09 7981 extent_op->level = level;
f0486c68 7982
66d7e7f0 7983 ret = btrfs_add_delayed_tree_ref(root->fs_info, trans,
67b7859e
OS
7984 ins.objectid, ins.offset,
7985 parent, root_objectid, level,
7986 BTRFS_ADD_DELAYED_EXTENT,
b06c4bf5 7987 extent_op);
67b7859e
OS
7988 if (ret)
7989 goto out_free_delayed;
f0486c68 7990 }
fec577fb 7991 return buf;
67b7859e
OS
7992
7993out_free_delayed:
7994 btrfs_free_delayed_extent_op(extent_op);
7995out_free_buf:
7996 free_extent_buffer(buf);
7997out_free_reserved:
7998 btrfs_free_reserved_extent(root, ins.objectid, ins.offset, 0);
7999out_unuse:
8000 unuse_block_rsv(root->fs_info, block_rsv, blocksize);
8001 return ERR_PTR(ret);
fec577fb 8002}
a28ec197 8003
2c47e605
YZ
8004struct walk_control {
8005 u64 refs[BTRFS_MAX_LEVEL];
8006 u64 flags[BTRFS_MAX_LEVEL];
8007 struct btrfs_key update_progress;
8008 int stage;
8009 int level;
8010 int shared_level;
8011 int update_ref;
8012 int keep_locks;
1c4850e2
YZ
8013 int reada_slot;
8014 int reada_count;
66d7e7f0 8015 int for_reloc;
2c47e605
YZ
8016};
8017
8018#define DROP_REFERENCE 1
8019#define UPDATE_BACKREF 2
8020
1c4850e2
YZ
8021static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
8022 struct btrfs_root *root,
8023 struct walk_control *wc,
8024 struct btrfs_path *path)
6407bf6d 8025{
1c4850e2
YZ
8026 u64 bytenr;
8027 u64 generation;
8028 u64 refs;
94fcca9f 8029 u64 flags;
5d4f98a2 8030 u32 nritems;
1c4850e2
YZ
8031 u32 blocksize;
8032 struct btrfs_key key;
8033 struct extent_buffer *eb;
6407bf6d 8034 int ret;
1c4850e2
YZ
8035 int slot;
8036 int nread = 0;
6407bf6d 8037
1c4850e2
YZ
8038 if (path->slots[wc->level] < wc->reada_slot) {
8039 wc->reada_count = wc->reada_count * 2 / 3;
8040 wc->reada_count = max(wc->reada_count, 2);
8041 } else {
8042 wc->reada_count = wc->reada_count * 3 / 2;
8043 wc->reada_count = min_t(int, wc->reada_count,
8044 BTRFS_NODEPTRS_PER_BLOCK(root));
8045 }
7bb86316 8046
1c4850e2
YZ
8047 eb = path->nodes[wc->level];
8048 nritems = btrfs_header_nritems(eb);
707e8a07 8049 blocksize = root->nodesize;
bd56b302 8050
1c4850e2
YZ
8051 for (slot = path->slots[wc->level]; slot < nritems; slot++) {
8052 if (nread >= wc->reada_count)
8053 break;
bd56b302 8054
2dd3e67b 8055 cond_resched();
1c4850e2
YZ
8056 bytenr = btrfs_node_blockptr(eb, slot);
8057 generation = btrfs_node_ptr_generation(eb, slot);
2dd3e67b 8058
1c4850e2
YZ
8059 if (slot == path->slots[wc->level])
8060 goto reada;
5d4f98a2 8061
1c4850e2
YZ
8062 if (wc->stage == UPDATE_BACKREF &&
8063 generation <= root->root_key.offset)
bd56b302
CM
8064 continue;
8065
94fcca9f 8066 /* We don't lock the tree block, it's OK to be racy here */
3173a18f
JB
8067 ret = btrfs_lookup_extent_info(trans, root, bytenr,
8068 wc->level - 1, 1, &refs,
8069 &flags);
79787eaa
JM
8070 /* We don't care about errors in readahead. */
8071 if (ret < 0)
8072 continue;
94fcca9f
YZ
8073 BUG_ON(refs == 0);
8074
1c4850e2 8075 if (wc->stage == DROP_REFERENCE) {
1c4850e2
YZ
8076 if (refs == 1)
8077 goto reada;
bd56b302 8078
94fcca9f
YZ
8079 if (wc->level == 1 &&
8080 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8081 continue;
1c4850e2
YZ
8082 if (!wc->update_ref ||
8083 generation <= root->root_key.offset)
8084 continue;
8085 btrfs_node_key_to_cpu(eb, &key, slot);
8086 ret = btrfs_comp_cpu_keys(&key,
8087 &wc->update_progress);
8088 if (ret < 0)
8089 continue;
94fcca9f
YZ
8090 } else {
8091 if (wc->level == 1 &&
8092 (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8093 continue;
6407bf6d 8094 }
1c4850e2 8095reada:
d3e46fea 8096 readahead_tree_block(root, bytenr);
1c4850e2 8097 nread++;
20524f02 8098 }
1c4850e2 8099 wc->reada_slot = slot;
20524f02 8100}
2c47e605 8101
0ed4792a
QW
8102/*
8103 * TODO: Modify related function to add related node/leaf to dirty_extent_root,
8104 * for later qgroup accounting.
8105 *
8106 * Current, this function does nothing.
8107 */
1152651a
MF
8108static int account_leaf_items(struct btrfs_trans_handle *trans,
8109 struct btrfs_root *root,
8110 struct extent_buffer *eb)
8111{
8112 int nr = btrfs_header_nritems(eb);
0ed4792a 8113 int i, extent_type;
1152651a
MF
8114 struct btrfs_key key;
8115 struct btrfs_file_extent_item *fi;
8116 u64 bytenr, num_bytes;
8117
8118 for (i = 0; i < nr; i++) {
8119 btrfs_item_key_to_cpu(eb, &key, i);
8120
8121 if (key.type != BTRFS_EXTENT_DATA_KEY)
8122 continue;
8123
8124 fi = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
8125 /* filter out non qgroup-accountable extents */
8126 extent_type = btrfs_file_extent_type(eb, fi);
8127
8128 if (extent_type == BTRFS_FILE_EXTENT_INLINE)
8129 continue;
8130
8131 bytenr = btrfs_file_extent_disk_bytenr(eb, fi);
8132 if (!bytenr)
8133 continue;
8134
8135 num_bytes = btrfs_file_extent_disk_num_bytes(eb, fi);
1152651a
MF
8136 }
8137 return 0;
8138}
8139
8140/*
8141 * Walk up the tree from the bottom, freeing leaves and any interior
8142 * nodes which have had all slots visited. If a node (leaf or
8143 * interior) is freed, the node above it will have it's slot
8144 * incremented. The root node will never be freed.
8145 *
8146 * At the end of this function, we should have a path which has all
8147 * slots incremented to the next position for a search. If we need to
8148 * read a new node it will be NULL and the node above it will have the
8149 * correct slot selected for a later read.
8150 *
8151 * If we increment the root nodes slot counter past the number of
8152 * elements, 1 is returned to signal completion of the search.
8153 */
8154static int adjust_slots_upwards(struct btrfs_root *root,
8155 struct btrfs_path *path, int root_level)
8156{
8157 int level = 0;
8158 int nr, slot;
8159 struct extent_buffer *eb;
8160
8161 if (root_level == 0)
8162 return 1;
8163
8164 while (level <= root_level) {
8165 eb = path->nodes[level];
8166 nr = btrfs_header_nritems(eb);
8167 path->slots[level]++;
8168 slot = path->slots[level];
8169 if (slot >= nr || level == 0) {
8170 /*
8171 * Don't free the root - we will detect this
8172 * condition after our loop and return a
8173 * positive value for caller to stop walking the tree.
8174 */
8175 if (level != root_level) {
8176 btrfs_tree_unlock_rw(eb, path->locks[level]);
8177 path->locks[level] = 0;
8178
8179 free_extent_buffer(eb);
8180 path->nodes[level] = NULL;
8181 path->slots[level] = 0;
8182 }
8183 } else {
8184 /*
8185 * We have a valid slot to walk back down
8186 * from. Stop here so caller can process these
8187 * new nodes.
8188 */
8189 break;
8190 }
8191
8192 level++;
8193 }
8194
8195 eb = path->nodes[root_level];
8196 if (path->slots[root_level] >= btrfs_header_nritems(eb))
8197 return 1;
8198
8199 return 0;
8200}
8201
8202/*
8203 * root_eb is the subtree root and is locked before this function is called.
0ed4792a
QW
8204 * TODO: Modify this function to mark all (including complete shared node)
8205 * to dirty_extent_root to allow it get accounted in qgroup.
1152651a
MF
8206 */
8207static int account_shared_subtree(struct btrfs_trans_handle *trans,
8208 struct btrfs_root *root,
8209 struct extent_buffer *root_eb,
8210 u64 root_gen,
8211 int root_level)
8212{
8213 int ret = 0;
8214 int level;
8215 struct extent_buffer *eb = root_eb;
8216 struct btrfs_path *path = NULL;
8217
8218 BUG_ON(root_level < 0 || root_level > BTRFS_MAX_LEVEL);
8219 BUG_ON(root_eb == NULL);
8220
8221 if (!root->fs_info->quota_enabled)
8222 return 0;
8223
8224 if (!extent_buffer_uptodate(root_eb)) {
8225 ret = btrfs_read_buffer(root_eb, root_gen);
8226 if (ret)
8227 goto out;
8228 }
8229
8230 if (root_level == 0) {
8231 ret = account_leaf_items(trans, root, root_eb);
8232 goto out;
8233 }
8234
8235 path = btrfs_alloc_path();
8236 if (!path)
8237 return -ENOMEM;
8238
8239 /*
8240 * Walk down the tree. Missing extent blocks are filled in as
8241 * we go. Metadata is accounted every time we read a new
8242 * extent block.
8243 *
8244 * When we reach a leaf, we account for file extent items in it,
8245 * walk back up the tree (adjusting slot pointers as we go)
8246 * and restart the search process.
8247 */
8248 extent_buffer_get(root_eb); /* For path */
8249 path->nodes[root_level] = root_eb;
8250 path->slots[root_level] = 0;
8251 path->locks[root_level] = 0; /* so release_path doesn't try to unlock */
8252walk_down:
8253 level = root_level;
8254 while (level >= 0) {
8255 if (path->nodes[level] == NULL) {
1152651a
MF
8256 int parent_slot;
8257 u64 child_gen;
8258 u64 child_bytenr;
8259
8260 /* We need to get child blockptr/gen from
8261 * parent before we can read it. */
8262 eb = path->nodes[level + 1];
8263 parent_slot = path->slots[level + 1];
8264 child_bytenr = btrfs_node_blockptr(eb, parent_slot);
8265 child_gen = btrfs_node_ptr_generation(eb, parent_slot);
8266
ce86cd59 8267 eb = read_tree_block(root, child_bytenr, child_gen);
64c043de
LB
8268 if (IS_ERR(eb)) {
8269 ret = PTR_ERR(eb);
8270 goto out;
8271 } else if (!extent_buffer_uptodate(eb)) {
8635eda9 8272 free_extent_buffer(eb);
64c043de 8273 ret = -EIO;
1152651a
MF
8274 goto out;
8275 }
8276
8277 path->nodes[level] = eb;
8278 path->slots[level] = 0;
8279
8280 btrfs_tree_read_lock(eb);
8281 btrfs_set_lock_blocking_rw(eb, BTRFS_READ_LOCK);
8282 path->locks[level] = BTRFS_READ_LOCK_BLOCKING;
1152651a
MF
8283 }
8284
8285 if (level == 0) {
8286 ret = account_leaf_items(trans, root, path->nodes[level]);
8287 if (ret)
8288 goto out;
8289
8290 /* Nonzero return here means we completed our search */
8291 ret = adjust_slots_upwards(root, path, root_level);
8292 if (ret)
8293 break;
8294
8295 /* Restart search with new slots */
8296 goto walk_down;
8297 }
8298
8299 level--;
8300 }
8301
8302 ret = 0;
8303out:
8304 btrfs_free_path(path);
8305
8306 return ret;
8307}
8308
f82d02d9 8309/*
2c016dc2 8310 * helper to process tree block while walking down the tree.
2c47e605 8311 *
2c47e605
YZ
8312 * when wc->stage == UPDATE_BACKREF, this function updates
8313 * back refs for pointers in the block.
8314 *
8315 * NOTE: return value 1 means we should stop walking down.
f82d02d9 8316 */
2c47e605 8317static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
5d4f98a2 8318 struct btrfs_root *root,
2c47e605 8319 struct btrfs_path *path,
94fcca9f 8320 struct walk_control *wc, int lookup_info)
f82d02d9 8321{
2c47e605
YZ
8322 int level = wc->level;
8323 struct extent_buffer *eb = path->nodes[level];
2c47e605 8324 u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
f82d02d9
YZ
8325 int ret;
8326
2c47e605
YZ
8327 if (wc->stage == UPDATE_BACKREF &&
8328 btrfs_header_owner(eb) != root->root_key.objectid)
8329 return 1;
f82d02d9 8330
2c47e605
YZ
8331 /*
8332 * when reference count of tree block is 1, it won't increase
8333 * again. once full backref flag is set, we never clear it.
8334 */
94fcca9f
YZ
8335 if (lookup_info &&
8336 ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
8337 (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
2c47e605
YZ
8338 BUG_ON(!path->locks[level]);
8339 ret = btrfs_lookup_extent_info(trans, root,
3173a18f 8340 eb->start, level, 1,
2c47e605
YZ
8341 &wc->refs[level],
8342 &wc->flags[level]);
79787eaa
JM
8343 BUG_ON(ret == -ENOMEM);
8344 if (ret)
8345 return ret;
2c47e605
YZ
8346 BUG_ON(wc->refs[level] == 0);
8347 }
5d4f98a2 8348
2c47e605
YZ
8349 if (wc->stage == DROP_REFERENCE) {
8350 if (wc->refs[level] > 1)
8351 return 1;
f82d02d9 8352
2c47e605 8353 if (path->locks[level] && !wc->keep_locks) {
bd681513 8354 btrfs_tree_unlock_rw(eb, path->locks[level]);
2c47e605
YZ
8355 path->locks[level] = 0;
8356 }
8357 return 0;
8358 }
f82d02d9 8359
2c47e605
YZ
8360 /* wc->stage == UPDATE_BACKREF */
8361 if (!(wc->flags[level] & flag)) {
8362 BUG_ON(!path->locks[level]);
e339a6b0 8363 ret = btrfs_inc_ref(trans, root, eb, 1);
79787eaa 8364 BUG_ON(ret); /* -ENOMEM */
e339a6b0 8365 ret = btrfs_dec_ref(trans, root, eb, 0);
79787eaa 8366 BUG_ON(ret); /* -ENOMEM */
2c47e605 8367 ret = btrfs_set_disk_extent_flags(trans, root, eb->start,
b1c79e09
JB
8368 eb->len, flag,
8369 btrfs_header_level(eb), 0);
79787eaa 8370 BUG_ON(ret); /* -ENOMEM */
2c47e605
YZ
8371 wc->flags[level] |= flag;
8372 }
8373
8374 /*
8375 * the block is shared by multiple trees, so it's not good to
8376 * keep the tree lock
8377 */
8378 if (path->locks[level] && level > 0) {
bd681513 8379 btrfs_tree_unlock_rw(eb, path->locks[level]);
2c47e605
YZ
8380 path->locks[level] = 0;
8381 }
8382 return 0;
8383}
8384
1c4850e2 8385/*
2c016dc2 8386 * helper to process tree block pointer.
1c4850e2
YZ
8387 *
8388 * when wc->stage == DROP_REFERENCE, this function checks
8389 * reference count of the block pointed to. if the block
8390 * is shared and we need update back refs for the subtree
8391 * rooted at the block, this function changes wc->stage to
8392 * UPDATE_BACKREF. if the block is shared and there is no
8393 * need to update back, this function drops the reference
8394 * to the block.
8395 *
8396 * NOTE: return value 1 means we should stop walking down.
8397 */
8398static noinline int do_walk_down(struct btrfs_trans_handle *trans,
8399 struct btrfs_root *root,
8400 struct btrfs_path *path,
94fcca9f 8401 struct walk_control *wc, int *lookup_info)
1c4850e2
YZ
8402{
8403 u64 bytenr;
8404 u64 generation;
8405 u64 parent;
8406 u32 blocksize;
8407 struct btrfs_key key;
8408 struct extent_buffer *next;
8409 int level = wc->level;
8410 int reada = 0;
8411 int ret = 0;
1152651a 8412 bool need_account = false;
1c4850e2
YZ
8413
8414 generation = btrfs_node_ptr_generation(path->nodes[level],
8415 path->slots[level]);
8416 /*
8417 * if the lower level block was created before the snapshot
8418 * was created, we know there is no need to update back refs
8419 * for the subtree
8420 */
8421 if (wc->stage == UPDATE_BACKREF &&
94fcca9f
YZ
8422 generation <= root->root_key.offset) {
8423 *lookup_info = 1;
1c4850e2 8424 return 1;
94fcca9f 8425 }
1c4850e2
YZ
8426
8427 bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
707e8a07 8428 blocksize = root->nodesize;
1c4850e2 8429
01d58472 8430 next = btrfs_find_tree_block(root->fs_info, bytenr);
1c4850e2 8431 if (!next) {
a83fffb7 8432 next = btrfs_find_create_tree_block(root, bytenr);
90d2c51d
MX
8433 if (!next)
8434 return -ENOMEM;
b2aaaa3b
JB
8435 btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
8436 level - 1);
1c4850e2
YZ
8437 reada = 1;
8438 }
8439 btrfs_tree_lock(next);
8440 btrfs_set_lock_blocking(next);
8441
3173a18f 8442 ret = btrfs_lookup_extent_info(trans, root, bytenr, level - 1, 1,
94fcca9f
YZ
8443 &wc->refs[level - 1],
8444 &wc->flags[level - 1]);
79787eaa
JM
8445 if (ret < 0) {
8446 btrfs_tree_unlock(next);
8447 return ret;
8448 }
8449
c2cf52eb
SK
8450 if (unlikely(wc->refs[level - 1] == 0)) {
8451 btrfs_err(root->fs_info, "Missing references.");
8452 BUG();
8453 }
94fcca9f 8454 *lookup_info = 0;
1c4850e2 8455
94fcca9f 8456 if (wc->stage == DROP_REFERENCE) {
1c4850e2 8457 if (wc->refs[level - 1] > 1) {
1152651a 8458 need_account = true;
94fcca9f
YZ
8459 if (level == 1 &&
8460 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8461 goto skip;
8462
1c4850e2
YZ
8463 if (!wc->update_ref ||
8464 generation <= root->root_key.offset)
8465 goto skip;
8466
8467 btrfs_node_key_to_cpu(path->nodes[level], &key,
8468 path->slots[level]);
8469 ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
8470 if (ret < 0)
8471 goto skip;
8472
8473 wc->stage = UPDATE_BACKREF;
8474 wc->shared_level = level - 1;
8475 }
94fcca9f
YZ
8476 } else {
8477 if (level == 1 &&
8478 (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
8479 goto skip;
1c4850e2
YZ
8480 }
8481
b9fab919 8482 if (!btrfs_buffer_uptodate(next, generation, 0)) {
1c4850e2
YZ
8483 btrfs_tree_unlock(next);
8484 free_extent_buffer(next);
8485 next = NULL;
94fcca9f 8486 *lookup_info = 1;
1c4850e2
YZ
8487 }
8488
8489 if (!next) {
8490 if (reada && level == 1)
8491 reada_walk_down(trans, root, wc, path);
ce86cd59 8492 next = read_tree_block(root, bytenr, generation);
64c043de
LB
8493 if (IS_ERR(next)) {
8494 return PTR_ERR(next);
8495 } else if (!extent_buffer_uptodate(next)) {
416bc658 8496 free_extent_buffer(next);
97d9a8a4 8497 return -EIO;
416bc658 8498 }
1c4850e2
YZ
8499 btrfs_tree_lock(next);
8500 btrfs_set_lock_blocking(next);
8501 }
8502
8503 level--;
8504 BUG_ON(level != btrfs_header_level(next));
8505 path->nodes[level] = next;
8506 path->slots[level] = 0;
bd681513 8507 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
1c4850e2
YZ
8508 wc->level = level;
8509 if (wc->level == 1)
8510 wc->reada_slot = 0;
8511 return 0;
8512skip:
8513 wc->refs[level - 1] = 0;
8514 wc->flags[level - 1] = 0;
94fcca9f
YZ
8515 if (wc->stage == DROP_REFERENCE) {
8516 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
8517 parent = path->nodes[level]->start;
8518 } else {
8519 BUG_ON(root->root_key.objectid !=
8520 btrfs_header_owner(path->nodes[level]));
8521 parent = 0;
8522 }
1c4850e2 8523
1152651a
MF
8524 if (need_account) {
8525 ret = account_shared_subtree(trans, root, next,
8526 generation, level - 1);
8527 if (ret) {
94647322
DS
8528 btrfs_err_rl(root->fs_info,
8529 "Error "
1152651a 8530 "%d accounting shared subtree. Quota "
94647322
DS
8531 "is out of sync, rescan required.",
8532 ret);
1152651a
MF
8533 }
8534 }
94fcca9f 8535 ret = btrfs_free_extent(trans, root, bytenr, blocksize, parent,
b06c4bf5 8536 root->root_key.objectid, level - 1, 0);
79787eaa 8537 BUG_ON(ret); /* -ENOMEM */
1c4850e2 8538 }
1c4850e2
YZ
8539 btrfs_tree_unlock(next);
8540 free_extent_buffer(next);
94fcca9f 8541 *lookup_info = 1;
1c4850e2
YZ
8542 return 1;
8543}
8544
2c47e605 8545/*
2c016dc2 8546 * helper to process tree block while walking up the tree.
2c47e605
YZ
8547 *
8548 * when wc->stage == DROP_REFERENCE, this function drops
8549 * reference count on the block.
8550 *
8551 * when wc->stage == UPDATE_BACKREF, this function changes
8552 * wc->stage back to DROP_REFERENCE if we changed wc->stage
8553 * to UPDATE_BACKREF previously while processing the block.
8554 *
8555 * NOTE: return value 1 means we should stop walking up.
8556 */
8557static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
8558 struct btrfs_root *root,
8559 struct btrfs_path *path,
8560 struct walk_control *wc)
8561{
f0486c68 8562 int ret;
2c47e605
YZ
8563 int level = wc->level;
8564 struct extent_buffer *eb = path->nodes[level];
8565 u64 parent = 0;
8566
8567 if (wc->stage == UPDATE_BACKREF) {
8568 BUG_ON(wc->shared_level < level);
8569 if (level < wc->shared_level)
8570 goto out;
8571
2c47e605
YZ
8572 ret = find_next_key(path, level + 1, &wc->update_progress);
8573 if (ret > 0)
8574 wc->update_ref = 0;
8575
8576 wc->stage = DROP_REFERENCE;
8577 wc->shared_level = -1;
8578 path->slots[level] = 0;
8579
8580 /*
8581 * check reference count again if the block isn't locked.
8582 * we should start walking down the tree again if reference
8583 * count is one.
8584 */
8585 if (!path->locks[level]) {
8586 BUG_ON(level == 0);
8587 btrfs_tree_lock(eb);
8588 btrfs_set_lock_blocking(eb);
bd681513 8589 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
8590
8591 ret = btrfs_lookup_extent_info(trans, root,
3173a18f 8592 eb->start, level, 1,
2c47e605
YZ
8593 &wc->refs[level],
8594 &wc->flags[level]);
79787eaa
JM
8595 if (ret < 0) {
8596 btrfs_tree_unlock_rw(eb, path->locks[level]);
3268a246 8597 path->locks[level] = 0;
79787eaa
JM
8598 return ret;
8599 }
2c47e605
YZ
8600 BUG_ON(wc->refs[level] == 0);
8601 if (wc->refs[level] == 1) {
bd681513 8602 btrfs_tree_unlock_rw(eb, path->locks[level]);
3268a246 8603 path->locks[level] = 0;
2c47e605
YZ
8604 return 1;
8605 }
f82d02d9 8606 }
2c47e605 8607 }
f82d02d9 8608
2c47e605
YZ
8609 /* wc->stage == DROP_REFERENCE */
8610 BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
5d4f98a2 8611
2c47e605
YZ
8612 if (wc->refs[level] == 1) {
8613 if (level == 0) {
8614 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
e339a6b0 8615 ret = btrfs_dec_ref(trans, root, eb, 1);
2c47e605 8616 else
e339a6b0 8617 ret = btrfs_dec_ref(trans, root, eb, 0);
79787eaa 8618 BUG_ON(ret); /* -ENOMEM */
1152651a
MF
8619 ret = account_leaf_items(trans, root, eb);
8620 if (ret) {
94647322
DS
8621 btrfs_err_rl(root->fs_info,
8622 "error "
1152651a 8623 "%d accounting leaf items. Quota "
94647322
DS
8624 "is out of sync, rescan required.",
8625 ret);
1152651a 8626 }
2c47e605
YZ
8627 }
8628 /* make block locked assertion in clean_tree_block happy */
8629 if (!path->locks[level] &&
8630 btrfs_header_generation(eb) == trans->transid) {
8631 btrfs_tree_lock(eb);
8632 btrfs_set_lock_blocking(eb);
bd681513 8633 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605 8634 }
01d58472 8635 clean_tree_block(trans, root->fs_info, eb);
2c47e605
YZ
8636 }
8637
8638 if (eb == root->node) {
8639 if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8640 parent = eb->start;
8641 else
8642 BUG_ON(root->root_key.objectid !=
8643 btrfs_header_owner(eb));
8644 } else {
8645 if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
8646 parent = path->nodes[level + 1]->start;
8647 else
8648 BUG_ON(root->root_key.objectid !=
8649 btrfs_header_owner(path->nodes[level + 1]));
f82d02d9 8650 }
f82d02d9 8651
5581a51a 8652 btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
2c47e605
YZ
8653out:
8654 wc->refs[level] = 0;
8655 wc->flags[level] = 0;
f0486c68 8656 return 0;
2c47e605
YZ
8657}
8658
8659static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
8660 struct btrfs_root *root,
8661 struct btrfs_path *path,
8662 struct walk_control *wc)
8663{
2c47e605 8664 int level = wc->level;
94fcca9f 8665 int lookup_info = 1;
2c47e605
YZ
8666 int ret;
8667
8668 while (level >= 0) {
94fcca9f 8669 ret = walk_down_proc(trans, root, path, wc, lookup_info);
2c47e605
YZ
8670 if (ret > 0)
8671 break;
8672
8673 if (level == 0)
8674 break;
8675
7a7965f8
YZ
8676 if (path->slots[level] >=
8677 btrfs_header_nritems(path->nodes[level]))
8678 break;
8679
94fcca9f 8680 ret = do_walk_down(trans, root, path, wc, &lookup_info);
1c4850e2
YZ
8681 if (ret > 0) {
8682 path->slots[level]++;
8683 continue;
90d2c51d
MX
8684 } else if (ret < 0)
8685 return ret;
1c4850e2 8686 level = wc->level;
f82d02d9 8687 }
f82d02d9
YZ
8688 return 0;
8689}
8690
d397712b 8691static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
98ed5174 8692 struct btrfs_root *root,
f82d02d9 8693 struct btrfs_path *path,
2c47e605 8694 struct walk_control *wc, int max_level)
20524f02 8695{
2c47e605 8696 int level = wc->level;
20524f02 8697 int ret;
9f3a7427 8698
2c47e605
YZ
8699 path->slots[level] = btrfs_header_nritems(path->nodes[level]);
8700 while (level < max_level && path->nodes[level]) {
8701 wc->level = level;
8702 if (path->slots[level] + 1 <
8703 btrfs_header_nritems(path->nodes[level])) {
8704 path->slots[level]++;
20524f02
CM
8705 return 0;
8706 } else {
2c47e605
YZ
8707 ret = walk_up_proc(trans, root, path, wc);
8708 if (ret > 0)
8709 return 0;
bd56b302 8710
2c47e605 8711 if (path->locks[level]) {
bd681513
CM
8712 btrfs_tree_unlock_rw(path->nodes[level],
8713 path->locks[level]);
2c47e605 8714 path->locks[level] = 0;
f82d02d9 8715 }
2c47e605
YZ
8716 free_extent_buffer(path->nodes[level]);
8717 path->nodes[level] = NULL;
8718 level++;
20524f02
CM
8719 }
8720 }
8721 return 1;
8722}
8723
9aca1d51 8724/*
2c47e605
YZ
8725 * drop a subvolume tree.
8726 *
8727 * this function traverses the tree freeing any blocks that only
8728 * referenced by the tree.
8729 *
8730 * when a shared tree block is found. this function decreases its
8731 * reference count by one. if update_ref is true, this function
8732 * also make sure backrefs for the shared block and all lower level
8733 * blocks are properly updated.
9d1a2a3a
DS
8734 *
8735 * If called with for_reloc == 0, may exit early with -EAGAIN
9aca1d51 8736 */
2c536799 8737int btrfs_drop_snapshot(struct btrfs_root *root,
66d7e7f0
AJ
8738 struct btrfs_block_rsv *block_rsv, int update_ref,
8739 int for_reloc)
20524f02 8740{
5caf2a00 8741 struct btrfs_path *path;
2c47e605
YZ
8742 struct btrfs_trans_handle *trans;
8743 struct btrfs_root *tree_root = root->fs_info->tree_root;
9f3a7427 8744 struct btrfs_root_item *root_item = &root->root_item;
2c47e605
YZ
8745 struct walk_control *wc;
8746 struct btrfs_key key;
8747 int err = 0;
8748 int ret;
8749 int level;
d29a9f62 8750 bool root_dropped = false;
20524f02 8751
1152651a
MF
8752 btrfs_debug(root->fs_info, "Drop subvolume %llu", root->objectid);
8753
5caf2a00 8754 path = btrfs_alloc_path();
cb1b69f4
TI
8755 if (!path) {
8756 err = -ENOMEM;
8757 goto out;
8758 }
20524f02 8759
2c47e605 8760 wc = kzalloc(sizeof(*wc), GFP_NOFS);
38a1a919
MF
8761 if (!wc) {
8762 btrfs_free_path(path);
cb1b69f4
TI
8763 err = -ENOMEM;
8764 goto out;
38a1a919 8765 }
2c47e605 8766
a22285a6 8767 trans = btrfs_start_transaction(tree_root, 0);
79787eaa
JM
8768 if (IS_ERR(trans)) {
8769 err = PTR_ERR(trans);
8770 goto out_free;
8771 }
98d5dc13 8772
3fd0a558
YZ
8773 if (block_rsv)
8774 trans->block_rsv = block_rsv;
2c47e605 8775
9f3a7427 8776 if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
2c47e605 8777 level = btrfs_header_level(root->node);
5d4f98a2
YZ
8778 path->nodes[level] = btrfs_lock_root_node(root);
8779 btrfs_set_lock_blocking(path->nodes[level]);
9f3a7427 8780 path->slots[level] = 0;
bd681513 8781 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
8782 memset(&wc->update_progress, 0,
8783 sizeof(wc->update_progress));
9f3a7427 8784 } else {
9f3a7427 8785 btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
2c47e605
YZ
8786 memcpy(&wc->update_progress, &key,
8787 sizeof(wc->update_progress));
8788
6702ed49 8789 level = root_item->drop_level;
2c47e605 8790 BUG_ON(level == 0);
6702ed49 8791 path->lowest_level = level;
2c47e605
YZ
8792 ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
8793 path->lowest_level = 0;
8794 if (ret < 0) {
8795 err = ret;
79787eaa 8796 goto out_end_trans;
9f3a7427 8797 }
1c4850e2 8798 WARN_ON(ret > 0);
2c47e605 8799
7d9eb12c
CM
8800 /*
8801 * unlock our path, this is safe because only this
8802 * function is allowed to delete this snapshot
8803 */
5d4f98a2 8804 btrfs_unlock_up_safe(path, 0);
2c47e605
YZ
8805
8806 level = btrfs_header_level(root->node);
8807 while (1) {
8808 btrfs_tree_lock(path->nodes[level]);
8809 btrfs_set_lock_blocking(path->nodes[level]);
fec386ac 8810 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
8811
8812 ret = btrfs_lookup_extent_info(trans, root,
8813 path->nodes[level]->start,
3173a18f 8814 level, 1, &wc->refs[level],
2c47e605 8815 &wc->flags[level]);
79787eaa
JM
8816 if (ret < 0) {
8817 err = ret;
8818 goto out_end_trans;
8819 }
2c47e605
YZ
8820 BUG_ON(wc->refs[level] == 0);
8821
8822 if (level == root_item->drop_level)
8823 break;
8824
8825 btrfs_tree_unlock(path->nodes[level]);
fec386ac 8826 path->locks[level] = 0;
2c47e605
YZ
8827 WARN_ON(wc->refs[level] != 1);
8828 level--;
8829 }
9f3a7427 8830 }
2c47e605
YZ
8831
8832 wc->level = level;
8833 wc->shared_level = -1;
8834 wc->stage = DROP_REFERENCE;
8835 wc->update_ref = update_ref;
8836 wc->keep_locks = 0;
66d7e7f0 8837 wc->for_reloc = for_reloc;
1c4850e2 8838 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
2c47e605 8839
d397712b 8840 while (1) {
9d1a2a3a 8841
2c47e605
YZ
8842 ret = walk_down_tree(trans, root, path, wc);
8843 if (ret < 0) {
8844 err = ret;
20524f02 8845 break;
2c47e605 8846 }
9aca1d51 8847
2c47e605
YZ
8848 ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
8849 if (ret < 0) {
8850 err = ret;
20524f02 8851 break;
2c47e605
YZ
8852 }
8853
8854 if (ret > 0) {
8855 BUG_ON(wc->stage != DROP_REFERENCE);
e7a84565
CM
8856 break;
8857 }
2c47e605
YZ
8858
8859 if (wc->stage == DROP_REFERENCE) {
8860 level = wc->level;
8861 btrfs_node_key(path->nodes[level],
8862 &root_item->drop_progress,
8863 path->slots[level]);
8864 root_item->drop_level = level;
8865 }
8866
8867 BUG_ON(wc->level == 0);
3c8f2422
JB
8868 if (btrfs_should_end_transaction(trans, tree_root) ||
8869 (!for_reloc && btrfs_need_cleaner_sleep(root))) {
2c47e605
YZ
8870 ret = btrfs_update_root(trans, tree_root,
8871 &root->root_key,
8872 root_item);
79787eaa
JM
8873 if (ret) {
8874 btrfs_abort_transaction(trans, tree_root, ret);
8875 err = ret;
8876 goto out_end_trans;
8877 }
2c47e605 8878
3fd0a558 8879 btrfs_end_transaction_throttle(trans, tree_root);
3c8f2422 8880 if (!for_reloc && btrfs_need_cleaner_sleep(root)) {
efe120a0 8881 pr_debug("BTRFS: drop snapshot early exit\n");
3c8f2422
JB
8882 err = -EAGAIN;
8883 goto out_free;
8884 }
8885
a22285a6 8886 trans = btrfs_start_transaction(tree_root, 0);
79787eaa
JM
8887 if (IS_ERR(trans)) {
8888 err = PTR_ERR(trans);
8889 goto out_free;
8890 }
3fd0a558
YZ
8891 if (block_rsv)
8892 trans->block_rsv = block_rsv;
c3e69d58 8893 }
20524f02 8894 }
b3b4aa74 8895 btrfs_release_path(path);
79787eaa
JM
8896 if (err)
8897 goto out_end_trans;
2c47e605
YZ
8898
8899 ret = btrfs_del_root(trans, tree_root, &root->root_key);
79787eaa
JM
8900 if (ret) {
8901 btrfs_abort_transaction(trans, tree_root, ret);
8902 goto out_end_trans;
8903 }
2c47e605 8904
76dda93c 8905 if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
cb517eab
MX
8906 ret = btrfs_find_root(tree_root, &root->root_key, path,
8907 NULL, NULL);
79787eaa
JM
8908 if (ret < 0) {
8909 btrfs_abort_transaction(trans, tree_root, ret);
8910 err = ret;
8911 goto out_end_trans;
8912 } else if (ret > 0) {
84cd948c
JB
8913 /* if we fail to delete the orphan item this time
8914 * around, it'll get picked up the next time.
8915 *
8916 * The most common failure here is just -ENOENT.
8917 */
8918 btrfs_del_orphan_item(trans, tree_root,
8919 root->root_key.objectid);
76dda93c
YZ
8920 }
8921 }
8922
27cdeb70 8923 if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
2b9dbef2 8924 btrfs_add_dropped_root(trans, root);
76dda93c
YZ
8925 } else {
8926 free_extent_buffer(root->node);
8927 free_extent_buffer(root->commit_root);
b0feb9d9 8928 btrfs_put_fs_root(root);
76dda93c 8929 }
d29a9f62 8930 root_dropped = true;
79787eaa 8931out_end_trans:
3fd0a558 8932 btrfs_end_transaction_throttle(trans, tree_root);
79787eaa 8933out_free:
2c47e605 8934 kfree(wc);
5caf2a00 8935 btrfs_free_path(path);
cb1b69f4 8936out:
d29a9f62
JB
8937 /*
8938 * So if we need to stop dropping the snapshot for whatever reason we
8939 * need to make sure to add it back to the dead root list so that we
8940 * keep trying to do the work later. This also cleans up roots if we
8941 * don't have it in the radix (like when we recover after a power fail
8942 * or unmount) so we don't leak memory.
8943 */
b37b39cd 8944 if (!for_reloc && root_dropped == false)
d29a9f62 8945 btrfs_add_dead_root(root);
90515e7f 8946 if (err && err != -EAGAIN)
a4553fef 8947 btrfs_std_error(root->fs_info, err, NULL);
2c536799 8948 return err;
20524f02 8949}
9078a3e1 8950
2c47e605
YZ
8951/*
8952 * drop subtree rooted at tree block 'node'.
8953 *
8954 * NOTE: this function will unlock and release tree block 'node'
66d7e7f0 8955 * only used by relocation code
2c47e605 8956 */
f82d02d9
YZ
8957int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
8958 struct btrfs_root *root,
8959 struct extent_buffer *node,
8960 struct extent_buffer *parent)
8961{
8962 struct btrfs_path *path;
2c47e605 8963 struct walk_control *wc;
f82d02d9
YZ
8964 int level;
8965 int parent_level;
8966 int ret = 0;
8967 int wret;
8968
2c47e605
YZ
8969 BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
8970
f82d02d9 8971 path = btrfs_alloc_path();
db5b493a
TI
8972 if (!path)
8973 return -ENOMEM;
f82d02d9 8974
2c47e605 8975 wc = kzalloc(sizeof(*wc), GFP_NOFS);
db5b493a
TI
8976 if (!wc) {
8977 btrfs_free_path(path);
8978 return -ENOMEM;
8979 }
2c47e605 8980
b9447ef8 8981 btrfs_assert_tree_locked(parent);
f82d02d9
YZ
8982 parent_level = btrfs_header_level(parent);
8983 extent_buffer_get(parent);
8984 path->nodes[parent_level] = parent;
8985 path->slots[parent_level] = btrfs_header_nritems(parent);
8986
b9447ef8 8987 btrfs_assert_tree_locked(node);
f82d02d9 8988 level = btrfs_header_level(node);
f82d02d9
YZ
8989 path->nodes[level] = node;
8990 path->slots[level] = 0;
bd681513 8991 path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
2c47e605
YZ
8992
8993 wc->refs[parent_level] = 1;
8994 wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
8995 wc->level = level;
8996 wc->shared_level = -1;
8997 wc->stage = DROP_REFERENCE;
8998 wc->update_ref = 0;
8999 wc->keep_locks = 1;
66d7e7f0 9000 wc->for_reloc = 1;
1c4850e2 9001 wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(root);
f82d02d9
YZ
9002
9003 while (1) {
2c47e605
YZ
9004 wret = walk_down_tree(trans, root, path, wc);
9005 if (wret < 0) {
f82d02d9 9006 ret = wret;
f82d02d9 9007 break;
2c47e605 9008 }
f82d02d9 9009
2c47e605 9010 wret = walk_up_tree(trans, root, path, wc, parent_level);
f82d02d9
YZ
9011 if (wret < 0)
9012 ret = wret;
9013 if (wret != 0)
9014 break;
9015 }
9016
2c47e605 9017 kfree(wc);
f82d02d9
YZ
9018 btrfs_free_path(path);
9019 return ret;
9020}
9021
ec44a35c
CM
9022static u64 update_block_group_flags(struct btrfs_root *root, u64 flags)
9023{
9024 u64 num_devices;
fc67c450 9025 u64 stripped;
e4d8ec0f 9026
fc67c450
ID
9027 /*
9028 * if restripe for this chunk_type is on pick target profile and
9029 * return, otherwise do the usual balance
9030 */
9031 stripped = get_restripe_target(root->fs_info, flags);
9032 if (stripped)
9033 return extended_to_chunk(stripped);
e4d8ec0f 9034
95669976 9035 num_devices = root->fs_info->fs_devices->rw_devices;
cd02dca5 9036
fc67c450 9037 stripped = BTRFS_BLOCK_GROUP_RAID0 |
53b381b3 9038 BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
fc67c450
ID
9039 BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
9040
ec44a35c
CM
9041 if (num_devices == 1) {
9042 stripped |= BTRFS_BLOCK_GROUP_DUP;
9043 stripped = flags & ~stripped;
9044
9045 /* turn raid0 into single device chunks */
9046 if (flags & BTRFS_BLOCK_GROUP_RAID0)
9047 return stripped;
9048
9049 /* turn mirroring into duplication */
9050 if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
9051 BTRFS_BLOCK_GROUP_RAID10))
9052 return stripped | BTRFS_BLOCK_GROUP_DUP;
ec44a35c
CM
9053 } else {
9054 /* they already had raid on here, just return */
ec44a35c
CM
9055 if (flags & stripped)
9056 return flags;
9057
9058 stripped |= BTRFS_BLOCK_GROUP_DUP;
9059 stripped = flags & ~stripped;
9060
9061 /* switch duplicated blocks with raid1 */
9062 if (flags & BTRFS_BLOCK_GROUP_DUP)
9063 return stripped | BTRFS_BLOCK_GROUP_RAID1;
9064
e3176ca2 9065 /* this is drive concat, leave it alone */
ec44a35c 9066 }
e3176ca2 9067
ec44a35c
CM
9068 return flags;
9069}
9070
868f401a 9071static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
0ef3e66b 9072{
f0486c68
YZ
9073 struct btrfs_space_info *sinfo = cache->space_info;
9074 u64 num_bytes;
199c36ea 9075 u64 min_allocable_bytes;
f0486c68 9076 int ret = -ENOSPC;
0ef3e66b 9077
199c36ea
MX
9078 /*
9079 * We need some metadata space and system metadata space for
9080 * allocating chunks in some corner cases until we force to set
9081 * it to be readonly.
9082 */
9083 if ((sinfo->flags &
9084 (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
9085 !force)
9086 min_allocable_bytes = 1 * 1024 * 1024;
9087 else
9088 min_allocable_bytes = 0;
9089
f0486c68
YZ
9090 spin_lock(&sinfo->lock);
9091 spin_lock(&cache->lock);
61cfea9b
W
9092
9093 if (cache->ro) {
868f401a 9094 cache->ro++;
61cfea9b
W
9095 ret = 0;
9096 goto out;
9097 }
9098
f0486c68
YZ
9099 num_bytes = cache->key.offset - cache->reserved - cache->pinned -
9100 cache->bytes_super - btrfs_block_group_used(&cache->item);
9101
9102 if (sinfo->bytes_used + sinfo->bytes_reserved + sinfo->bytes_pinned +
37be25bc
JB
9103 sinfo->bytes_may_use + sinfo->bytes_readonly + num_bytes +
9104 min_allocable_bytes <= sinfo->total_bytes) {
f0486c68 9105 sinfo->bytes_readonly += num_bytes;
868f401a 9106 cache->ro++;
633c0aad 9107 list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
f0486c68
YZ
9108 ret = 0;
9109 }
61cfea9b 9110out:
f0486c68
YZ
9111 spin_unlock(&cache->lock);
9112 spin_unlock(&sinfo->lock);
9113 return ret;
9114}
7d9eb12c 9115
868f401a 9116int btrfs_inc_block_group_ro(struct btrfs_root *root,
f0486c68 9117 struct btrfs_block_group_cache *cache)
c286ac48 9118
f0486c68
YZ
9119{
9120 struct btrfs_trans_handle *trans;
9121 u64 alloc_flags;
9122 int ret;
7d9eb12c 9123
1bbc621e 9124again:
ff5714cc 9125 trans = btrfs_join_transaction(root);
79787eaa
JM
9126 if (IS_ERR(trans))
9127 return PTR_ERR(trans);
5d4f98a2 9128
1bbc621e
CM
9129 /*
9130 * we're not allowed to set block groups readonly after the dirty
9131 * block groups cache has started writing. If it already started,
9132 * back off and let this transaction commit
9133 */
9134 mutex_lock(&root->fs_info->ro_block_group_mutex);
3204d33c 9135 if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
1bbc621e
CM
9136 u64 transid = trans->transid;
9137
9138 mutex_unlock(&root->fs_info->ro_block_group_mutex);
9139 btrfs_end_transaction(trans, root);
9140
9141 ret = btrfs_wait_for_commit(root, transid);
9142 if (ret)
9143 return ret;
9144 goto again;
9145 }
9146
153c35b6
CM
9147 /*
9148 * if we are changing raid levels, try to allocate a corresponding
9149 * block group with the new raid level.
9150 */
9151 alloc_flags = update_block_group_flags(root, cache->flags);
9152 if (alloc_flags != cache->flags) {
9153 ret = do_chunk_alloc(trans, root, alloc_flags,
9154 CHUNK_ALLOC_FORCE);
9155 /*
9156 * ENOSPC is allowed here, we may have enough space
9157 * already allocated at the new raid level to
9158 * carry on
9159 */
9160 if (ret == -ENOSPC)
9161 ret = 0;
9162 if (ret < 0)
9163 goto out;
9164 }
1bbc621e 9165
868f401a 9166 ret = inc_block_group_ro(cache, 0);
f0486c68
YZ
9167 if (!ret)
9168 goto out;
9169 alloc_flags = get_alloc_profile(root, cache->space_info->flags);
698d0082 9170 ret = do_chunk_alloc(trans, root, alloc_flags,
0e4f8f88 9171 CHUNK_ALLOC_FORCE);
f0486c68
YZ
9172 if (ret < 0)
9173 goto out;
868f401a 9174 ret = inc_block_group_ro(cache, 0);
f0486c68 9175out:
2f081088
SL
9176 if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
9177 alloc_flags = update_block_group_flags(root, cache->flags);
a9629596 9178 lock_chunks(root->fs_info->chunk_root);
4617ea3a 9179 check_system_chunk(trans, root, alloc_flags);
a9629596 9180 unlock_chunks(root->fs_info->chunk_root);
2f081088 9181 }
1bbc621e 9182 mutex_unlock(&root->fs_info->ro_block_group_mutex);
2f081088 9183
f0486c68
YZ
9184 btrfs_end_transaction(trans, root);
9185 return ret;
9186}
5d4f98a2 9187
c87f08ca
CM
9188int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
9189 struct btrfs_root *root, u64 type)
9190{
9191 u64 alloc_flags = get_alloc_profile(root, type);
698d0082 9192 return do_chunk_alloc(trans, root, alloc_flags,
0e4f8f88 9193 CHUNK_ALLOC_FORCE);
c87f08ca
CM
9194}
9195
6d07bcec
MX
9196/*
9197 * helper to account the unused space of all the readonly block group in the
633c0aad 9198 * space_info. takes mirrors into account.
6d07bcec 9199 */
633c0aad 9200u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
6d07bcec
MX
9201{
9202 struct btrfs_block_group_cache *block_group;
9203 u64 free_bytes = 0;
9204 int factor;
9205
633c0aad
JB
9206 /* It's df, we don't care if it's racey */
9207 if (list_empty(&sinfo->ro_bgs))
9208 return 0;
9209
9210 spin_lock(&sinfo->lock);
9211 list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
6d07bcec
MX
9212 spin_lock(&block_group->lock);
9213
9214 if (!block_group->ro) {
9215 spin_unlock(&block_group->lock);
9216 continue;
9217 }
9218
9219 if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
9220 BTRFS_BLOCK_GROUP_RAID10 |
9221 BTRFS_BLOCK_GROUP_DUP))
9222 factor = 2;
9223 else
9224 factor = 1;
9225
9226 free_bytes += (block_group->key.offset -
9227 btrfs_block_group_used(&block_group->item)) *
9228 factor;
9229
9230 spin_unlock(&block_group->lock);
9231 }
6d07bcec
MX
9232 spin_unlock(&sinfo->lock);
9233
9234 return free_bytes;
9235}
9236
868f401a 9237void btrfs_dec_block_group_ro(struct btrfs_root *root,
f0486c68 9238 struct btrfs_block_group_cache *cache)
5d4f98a2 9239{
f0486c68
YZ
9240 struct btrfs_space_info *sinfo = cache->space_info;
9241 u64 num_bytes;
9242
9243 BUG_ON(!cache->ro);
9244
9245 spin_lock(&sinfo->lock);
9246 spin_lock(&cache->lock);
868f401a
Z
9247 if (!--cache->ro) {
9248 num_bytes = cache->key.offset - cache->reserved -
9249 cache->pinned - cache->bytes_super -
9250 btrfs_block_group_used(&cache->item);
9251 sinfo->bytes_readonly -= num_bytes;
9252 list_del_init(&cache->ro_list);
9253 }
f0486c68
YZ
9254 spin_unlock(&cache->lock);
9255 spin_unlock(&sinfo->lock);
5d4f98a2
YZ
9256}
9257
ba1bf481
JB
9258/*
9259 * checks to see if its even possible to relocate this block group.
9260 *
9261 * @return - -1 if it's not a good idea to relocate this block group, 0 if its
9262 * ok to go ahead and try.
9263 */
9264int btrfs_can_relocate(struct btrfs_root *root, u64 bytenr)
1a40e23b 9265{
ba1bf481
JB
9266 struct btrfs_block_group_cache *block_group;
9267 struct btrfs_space_info *space_info;
9268 struct btrfs_fs_devices *fs_devices = root->fs_info->fs_devices;
9269 struct btrfs_device *device;
6df9a95e 9270 struct btrfs_trans_handle *trans;
cdcb725c 9271 u64 min_free;
6719db6a
JB
9272 u64 dev_min = 1;
9273 u64 dev_nr = 0;
4a5e98f5 9274 u64 target;
cdcb725c 9275 int index;
ba1bf481
JB
9276 int full = 0;
9277 int ret = 0;
1a40e23b 9278
ba1bf481 9279 block_group = btrfs_lookup_block_group(root->fs_info, bytenr);
1a40e23b 9280
ba1bf481
JB
9281 /* odd, couldn't find the block group, leave it alone */
9282 if (!block_group)
9283 return -1;
1a40e23b 9284
cdcb725c 9285 min_free = btrfs_block_group_used(&block_group->item);
9286
ba1bf481 9287 /* no bytes used, we're good */
cdcb725c 9288 if (!min_free)
1a40e23b
ZY
9289 goto out;
9290
ba1bf481
JB
9291 space_info = block_group->space_info;
9292 spin_lock(&space_info->lock);
17d217fe 9293
ba1bf481 9294 full = space_info->full;
17d217fe 9295
ba1bf481
JB
9296 /*
9297 * if this is the last block group we have in this space, we can't
7ce618db
CM
9298 * relocate it unless we're able to allocate a new chunk below.
9299 *
9300 * Otherwise, we need to make sure we have room in the space to handle
9301 * all of the extents from this block group. If we can, we're good
ba1bf481 9302 */
7ce618db 9303 if ((space_info->total_bytes != block_group->key.offset) &&
cdcb725c 9304 (space_info->bytes_used + space_info->bytes_reserved +
9305 space_info->bytes_pinned + space_info->bytes_readonly +
9306 min_free < space_info->total_bytes)) {
ba1bf481
JB
9307 spin_unlock(&space_info->lock);
9308 goto out;
17d217fe 9309 }
ba1bf481 9310 spin_unlock(&space_info->lock);
ea8c2819 9311
ba1bf481
JB
9312 /*
9313 * ok we don't have enough space, but maybe we have free space on our
9314 * devices to allocate new chunks for relocation, so loop through our
4a5e98f5
ID
9315 * alloc devices and guess if we have enough space. if this block
9316 * group is going to be restriped, run checks against the target
9317 * profile instead of the current one.
ba1bf481
JB
9318 */
9319 ret = -1;
ea8c2819 9320
cdcb725c 9321 /*
9322 * index:
9323 * 0: raid10
9324 * 1: raid1
9325 * 2: dup
9326 * 3: raid0
9327 * 4: single
9328 */
4a5e98f5
ID
9329 target = get_restripe_target(root->fs_info, block_group->flags);
9330 if (target) {
31e50229 9331 index = __get_raid_index(extended_to_chunk(target));
4a5e98f5
ID
9332 } else {
9333 /*
9334 * this is just a balance, so if we were marked as full
9335 * we know there is no space for a new chunk
9336 */
9337 if (full)
9338 goto out;
9339
9340 index = get_block_group_index(block_group);
9341 }
9342
e6ec716f 9343 if (index == BTRFS_RAID_RAID10) {
cdcb725c 9344 dev_min = 4;
6719db6a
JB
9345 /* Divide by 2 */
9346 min_free >>= 1;
e6ec716f 9347 } else if (index == BTRFS_RAID_RAID1) {
cdcb725c 9348 dev_min = 2;
e6ec716f 9349 } else if (index == BTRFS_RAID_DUP) {
6719db6a
JB
9350 /* Multiply by 2 */
9351 min_free <<= 1;
e6ec716f 9352 } else if (index == BTRFS_RAID_RAID0) {
cdcb725c 9353 dev_min = fs_devices->rw_devices;
47c5713f 9354 min_free = div64_u64(min_free, dev_min);
cdcb725c 9355 }
9356
6df9a95e
JB
9357 /* We need to do this so that we can look at pending chunks */
9358 trans = btrfs_join_transaction(root);
9359 if (IS_ERR(trans)) {
9360 ret = PTR_ERR(trans);
9361 goto out;
9362 }
9363
ba1bf481
JB
9364 mutex_lock(&root->fs_info->chunk_mutex);
9365 list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
7bfc837d 9366 u64 dev_offset;
56bec294 9367
ba1bf481
JB
9368 /*
9369 * check to make sure we can actually find a chunk with enough
9370 * space to fit our block group in.
9371 */
63a212ab
SB
9372 if (device->total_bytes > device->bytes_used + min_free &&
9373 !device->is_tgtdev_for_dev_replace) {
6df9a95e 9374 ret = find_free_dev_extent(trans, device, min_free,
7bfc837d 9375 &dev_offset, NULL);
ba1bf481 9376 if (!ret)
cdcb725c 9377 dev_nr++;
9378
9379 if (dev_nr >= dev_min)
73e48b27 9380 break;
cdcb725c 9381
ba1bf481 9382 ret = -1;
725c8463 9383 }
edbd8d4e 9384 }
ba1bf481 9385 mutex_unlock(&root->fs_info->chunk_mutex);
6df9a95e 9386 btrfs_end_transaction(trans, root);
edbd8d4e 9387out:
ba1bf481 9388 btrfs_put_block_group(block_group);
edbd8d4e
CM
9389 return ret;
9390}
9391
b2950863
CH
9392static int find_first_block_group(struct btrfs_root *root,
9393 struct btrfs_path *path, struct btrfs_key *key)
0b86a832 9394{
925baedd 9395 int ret = 0;
0b86a832
CM
9396 struct btrfs_key found_key;
9397 struct extent_buffer *leaf;
9398 int slot;
edbd8d4e 9399
0b86a832
CM
9400 ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
9401 if (ret < 0)
925baedd
CM
9402 goto out;
9403
d397712b 9404 while (1) {
0b86a832 9405 slot = path->slots[0];
edbd8d4e 9406 leaf = path->nodes[0];
0b86a832
CM
9407 if (slot >= btrfs_header_nritems(leaf)) {
9408 ret = btrfs_next_leaf(root, path);
9409 if (ret == 0)
9410 continue;
9411 if (ret < 0)
925baedd 9412 goto out;
0b86a832 9413 break;
edbd8d4e 9414 }
0b86a832 9415 btrfs_item_key_to_cpu(leaf, &found_key, slot);
edbd8d4e 9416
0b86a832 9417 if (found_key.objectid >= key->objectid &&
925baedd
CM
9418 found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
9419 ret = 0;
9420 goto out;
9421 }
0b86a832 9422 path->slots[0]++;
edbd8d4e 9423 }
925baedd 9424out:
0b86a832 9425 return ret;
edbd8d4e
CM
9426}
9427
0af3d00b
JB
9428void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
9429{
9430 struct btrfs_block_group_cache *block_group;
9431 u64 last = 0;
9432
9433 while (1) {
9434 struct inode *inode;
9435
9436 block_group = btrfs_lookup_first_block_group(info, last);
9437 while (block_group) {
9438 spin_lock(&block_group->lock);
9439 if (block_group->iref)
9440 break;
9441 spin_unlock(&block_group->lock);
9442 block_group = next_block_group(info->tree_root,
9443 block_group);
9444 }
9445 if (!block_group) {
9446 if (last == 0)
9447 break;
9448 last = 0;
9449 continue;
9450 }
9451
9452 inode = block_group->inode;
9453 block_group->iref = 0;
9454 block_group->inode = NULL;
9455 spin_unlock(&block_group->lock);
9456 iput(inode);
9457 last = block_group->key.objectid + block_group->key.offset;
9458 btrfs_put_block_group(block_group);
9459 }
9460}
9461
1a40e23b
ZY
9462int btrfs_free_block_groups(struct btrfs_fs_info *info)
9463{
9464 struct btrfs_block_group_cache *block_group;
4184ea7f 9465 struct btrfs_space_info *space_info;
11833d66 9466 struct btrfs_caching_control *caching_ctl;
1a40e23b
ZY
9467 struct rb_node *n;
9468
9e351cc8 9469 down_write(&info->commit_root_sem);
11833d66
YZ
9470 while (!list_empty(&info->caching_block_groups)) {
9471 caching_ctl = list_entry(info->caching_block_groups.next,
9472 struct btrfs_caching_control, list);
9473 list_del(&caching_ctl->list);
9474 put_caching_control(caching_ctl);
9475 }
9e351cc8 9476 up_write(&info->commit_root_sem);
11833d66 9477
47ab2a6c
JB
9478 spin_lock(&info->unused_bgs_lock);
9479 while (!list_empty(&info->unused_bgs)) {
9480 block_group = list_first_entry(&info->unused_bgs,
9481 struct btrfs_block_group_cache,
9482 bg_list);
9483 list_del_init(&block_group->bg_list);
9484 btrfs_put_block_group(block_group);
9485 }
9486 spin_unlock(&info->unused_bgs_lock);
9487
1a40e23b
ZY
9488 spin_lock(&info->block_group_cache_lock);
9489 while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
9490 block_group = rb_entry(n, struct btrfs_block_group_cache,
9491 cache_node);
1a40e23b
ZY
9492 rb_erase(&block_group->cache_node,
9493 &info->block_group_cache_tree);
01eacb27 9494 RB_CLEAR_NODE(&block_group->cache_node);
d899e052
YZ
9495 spin_unlock(&info->block_group_cache_lock);
9496
80eb234a 9497 down_write(&block_group->space_info->groups_sem);
1a40e23b 9498 list_del(&block_group->list);
80eb234a 9499 up_write(&block_group->space_info->groups_sem);
d2fb3437 9500
817d52f8 9501 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 9502 wait_block_group_cache_done(block_group);
817d52f8 9503
3c14874a
JB
9504 /*
9505 * We haven't cached this block group, which means we could
9506 * possibly have excluded extents on this block group.
9507 */
36cce922
JB
9508 if (block_group->cached == BTRFS_CACHE_NO ||
9509 block_group->cached == BTRFS_CACHE_ERROR)
3c14874a
JB
9510 free_excluded_extents(info->extent_root, block_group);
9511
817d52f8 9512 btrfs_remove_free_space_cache(block_group);
11dfe35a 9513 btrfs_put_block_group(block_group);
d899e052
YZ
9514
9515 spin_lock(&info->block_group_cache_lock);
1a40e23b
ZY
9516 }
9517 spin_unlock(&info->block_group_cache_lock);
4184ea7f
CM
9518
9519 /* now that all the block groups are freed, go through and
9520 * free all the space_info structs. This is only called during
9521 * the final stages of unmount, and so we know nobody is
9522 * using them. We call synchronize_rcu() once before we start,
9523 * just to be on the safe side.
9524 */
9525 synchronize_rcu();
9526
8929ecfa
YZ
9527 release_global_block_rsv(info);
9528
67871254 9529 while (!list_empty(&info->space_info)) {
6ab0a202
JM
9530 int i;
9531
4184ea7f
CM
9532 space_info = list_entry(info->space_info.next,
9533 struct btrfs_space_info,
9534 list);
b069e0c3 9535 if (btrfs_test_opt(info->tree_root, ENOSPC_DEBUG)) {
fae7f21c 9536 if (WARN_ON(space_info->bytes_pinned > 0 ||
b069e0c3 9537 space_info->bytes_reserved > 0 ||
fae7f21c 9538 space_info->bytes_may_use > 0)) {
b069e0c3
DS
9539 dump_space_info(space_info, 0, 0);
9540 }
f0486c68 9541 }
4184ea7f 9542 list_del(&space_info->list);
6ab0a202
JM
9543 for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
9544 struct kobject *kobj;
c1895442
JM
9545 kobj = space_info->block_group_kobjs[i];
9546 space_info->block_group_kobjs[i] = NULL;
9547 if (kobj) {
6ab0a202
JM
9548 kobject_del(kobj);
9549 kobject_put(kobj);
9550 }
9551 }
9552 kobject_del(&space_info->kobj);
9553 kobject_put(&space_info->kobj);
4184ea7f 9554 }
1a40e23b
ZY
9555 return 0;
9556}
9557
b742bb82
YZ
9558static void __link_block_group(struct btrfs_space_info *space_info,
9559 struct btrfs_block_group_cache *cache)
9560{
9561 int index = get_block_group_index(cache);
ed55b6ac 9562 bool first = false;
b742bb82
YZ
9563
9564 down_write(&space_info->groups_sem);
ed55b6ac
JM
9565 if (list_empty(&space_info->block_groups[index]))
9566 first = true;
9567 list_add_tail(&cache->list, &space_info->block_groups[index]);
9568 up_write(&space_info->groups_sem);
9569
9570 if (first) {
c1895442 9571 struct raid_kobject *rkobj;
6ab0a202
JM
9572 int ret;
9573
c1895442
JM
9574 rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
9575 if (!rkobj)
9576 goto out_err;
9577 rkobj->raid_type = index;
9578 kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
9579 ret = kobject_add(&rkobj->kobj, &space_info->kobj,
9580 "%s", get_raid_name(index));
6ab0a202 9581 if (ret) {
c1895442
JM
9582 kobject_put(&rkobj->kobj);
9583 goto out_err;
6ab0a202 9584 }
c1895442 9585 space_info->block_group_kobjs[index] = &rkobj->kobj;
6ab0a202 9586 }
c1895442
JM
9587
9588 return;
9589out_err:
9590 pr_warn("BTRFS: failed to add kobject for block cache. ignoring.\n");
b742bb82
YZ
9591}
9592
920e4a58
MX
9593static struct btrfs_block_group_cache *
9594btrfs_create_block_group_cache(struct btrfs_root *root, u64 start, u64 size)
9595{
9596 struct btrfs_block_group_cache *cache;
9597
9598 cache = kzalloc(sizeof(*cache), GFP_NOFS);
9599 if (!cache)
9600 return NULL;
9601
9602 cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
9603 GFP_NOFS);
9604 if (!cache->free_space_ctl) {
9605 kfree(cache);
9606 return NULL;
9607 }
9608
9609 cache->key.objectid = start;
9610 cache->key.offset = size;
9611 cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9612
9613 cache->sectorsize = root->sectorsize;
9614 cache->fs_info = root->fs_info;
9615 cache->full_stripe_len = btrfs_full_stripe_len(root,
9616 &root->fs_info->mapping_tree,
9617 start);
9618 atomic_set(&cache->count, 1);
9619 spin_lock_init(&cache->lock);
e570fd27 9620 init_rwsem(&cache->data_rwsem);
920e4a58
MX
9621 INIT_LIST_HEAD(&cache->list);
9622 INIT_LIST_HEAD(&cache->cluster_list);
47ab2a6c 9623 INIT_LIST_HEAD(&cache->bg_list);
633c0aad 9624 INIT_LIST_HEAD(&cache->ro_list);
ce93ec54 9625 INIT_LIST_HEAD(&cache->dirty_list);
c9dc4c65 9626 INIT_LIST_HEAD(&cache->io_list);
920e4a58 9627 btrfs_init_free_space_ctl(cache);
04216820 9628 atomic_set(&cache->trimming, 0);
920e4a58
MX
9629
9630 return cache;
9631}
9632
9078a3e1
CM
9633int btrfs_read_block_groups(struct btrfs_root *root)
9634{
9635 struct btrfs_path *path;
9636 int ret;
9078a3e1 9637 struct btrfs_block_group_cache *cache;
be744175 9638 struct btrfs_fs_info *info = root->fs_info;
6324fbf3 9639 struct btrfs_space_info *space_info;
9078a3e1
CM
9640 struct btrfs_key key;
9641 struct btrfs_key found_key;
5f39d397 9642 struct extent_buffer *leaf;
0af3d00b
JB
9643 int need_clear = 0;
9644 u64 cache_gen;
96b5179d 9645
be744175 9646 root = info->extent_root;
9078a3e1 9647 key.objectid = 0;
0b86a832 9648 key.offset = 0;
962a298f 9649 key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
9078a3e1
CM
9650 path = btrfs_alloc_path();
9651 if (!path)
9652 return -ENOMEM;
026fd317 9653 path->reada = 1;
9078a3e1 9654
6c41761f 9655 cache_gen = btrfs_super_cache_generation(root->fs_info->super_copy);
73bc1876 9656 if (btrfs_test_opt(root, SPACE_CACHE) &&
6c41761f 9657 btrfs_super_generation(root->fs_info->super_copy) != cache_gen)
0af3d00b 9658 need_clear = 1;
88c2ba3b
JB
9659 if (btrfs_test_opt(root, CLEAR_CACHE))
9660 need_clear = 1;
0af3d00b 9661
d397712b 9662 while (1) {
0b86a832 9663 ret = find_first_block_group(root, path, &key);
b742bb82
YZ
9664 if (ret > 0)
9665 break;
0b86a832
CM
9666 if (ret != 0)
9667 goto error;
920e4a58 9668
5f39d397
CM
9669 leaf = path->nodes[0];
9670 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
920e4a58
MX
9671
9672 cache = btrfs_create_block_group_cache(root, found_key.objectid,
9673 found_key.offset);
9078a3e1 9674 if (!cache) {
0b86a832 9675 ret = -ENOMEM;
f0486c68 9676 goto error;
9078a3e1 9677 }
96303081 9678
cf7c1ef6
LB
9679 if (need_clear) {
9680 /*
9681 * When we mount with old space cache, we need to
9682 * set BTRFS_DC_CLEAR and set dirty flag.
9683 *
9684 * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
9685 * truncate the old free space cache inode and
9686 * setup a new one.
9687 * b) Setting 'dirty flag' makes sure that we flush
9688 * the new space cache info onto disk.
9689 */
cf7c1ef6 9690 if (btrfs_test_opt(root, SPACE_CACHE))
ce93ec54 9691 cache->disk_cache_state = BTRFS_DC_CLEAR;
cf7c1ef6 9692 }
0af3d00b 9693
5f39d397
CM
9694 read_extent_buffer(leaf, &cache->item,
9695 btrfs_item_ptr_offset(leaf, path->slots[0]),
9696 sizeof(cache->item));
920e4a58 9697 cache->flags = btrfs_block_group_flags(&cache->item);
0b86a832 9698
9078a3e1 9699 key.objectid = found_key.objectid + found_key.offset;
b3b4aa74 9700 btrfs_release_path(path);
34d52cb6 9701
3c14874a
JB
9702 /*
9703 * We need to exclude the super stripes now so that the space
9704 * info has super bytes accounted for, otherwise we'll think
9705 * we have more space than we actually do.
9706 */
835d974f
JB
9707 ret = exclude_super_stripes(root, cache);
9708 if (ret) {
9709 /*
9710 * We may have excluded something, so call this just in
9711 * case.
9712 */
9713 free_excluded_extents(root, cache);
920e4a58 9714 btrfs_put_block_group(cache);
835d974f
JB
9715 goto error;
9716 }
3c14874a 9717
817d52f8
JB
9718 /*
9719 * check for two cases, either we are full, and therefore
9720 * don't need to bother with the caching work since we won't
9721 * find any space, or we are empty, and we can just add all
9722 * the space in and be done with it. This saves us _alot_ of
9723 * time, particularly in the full case.
9724 */
9725 if (found_key.offset == btrfs_block_group_used(&cache->item)) {
11833d66 9726 cache->last_byte_to_unpin = (u64)-1;
817d52f8 9727 cache->cached = BTRFS_CACHE_FINISHED;
1b2da372 9728 free_excluded_extents(root, cache);
817d52f8 9729 } else if (btrfs_block_group_used(&cache->item) == 0) {
11833d66 9730 cache->last_byte_to_unpin = (u64)-1;
817d52f8
JB
9731 cache->cached = BTRFS_CACHE_FINISHED;
9732 add_new_free_space(cache, root->fs_info,
9733 found_key.objectid,
9734 found_key.objectid +
9735 found_key.offset);
11833d66 9736 free_excluded_extents(root, cache);
817d52f8 9737 }
96b5179d 9738
8c579fe7
JB
9739 ret = btrfs_add_block_group_cache(root->fs_info, cache);
9740 if (ret) {
9741 btrfs_remove_free_space_cache(cache);
9742 btrfs_put_block_group(cache);
9743 goto error;
9744 }
9745
6324fbf3
CM
9746 ret = update_space_info(info, cache->flags, found_key.offset,
9747 btrfs_block_group_used(&cache->item),
9748 &space_info);
8c579fe7
JB
9749 if (ret) {
9750 btrfs_remove_free_space_cache(cache);
9751 spin_lock(&info->block_group_cache_lock);
9752 rb_erase(&cache->cache_node,
9753 &info->block_group_cache_tree);
01eacb27 9754 RB_CLEAR_NODE(&cache->cache_node);
8c579fe7
JB
9755 spin_unlock(&info->block_group_cache_lock);
9756 btrfs_put_block_group(cache);
9757 goto error;
9758 }
9759
6324fbf3 9760 cache->space_info = space_info;
1b2da372 9761 spin_lock(&cache->space_info->lock);
f0486c68 9762 cache->space_info->bytes_readonly += cache->bytes_super;
1b2da372
JB
9763 spin_unlock(&cache->space_info->lock);
9764
b742bb82 9765 __link_block_group(space_info, cache);
0f9dd46c 9766
75ccf47d 9767 set_avail_alloc_bits(root->fs_info, cache->flags);
47ab2a6c 9768 if (btrfs_chunk_readonly(root, cache->key.objectid)) {
868f401a 9769 inc_block_group_ro(cache, 1);
47ab2a6c
JB
9770 } else if (btrfs_block_group_used(&cache->item) == 0) {
9771 spin_lock(&info->unused_bgs_lock);
9772 /* Should always be true but just in case. */
9773 if (list_empty(&cache->bg_list)) {
9774 btrfs_get_block_group(cache);
9775 list_add_tail(&cache->bg_list,
9776 &info->unused_bgs);
9777 }
9778 spin_unlock(&info->unused_bgs_lock);
9779 }
9078a3e1 9780 }
b742bb82
YZ
9781
9782 list_for_each_entry_rcu(space_info, &root->fs_info->space_info, list) {
9783 if (!(get_alloc_profile(root, space_info->flags) &
9784 (BTRFS_BLOCK_GROUP_RAID10 |
9785 BTRFS_BLOCK_GROUP_RAID1 |
53b381b3
DW
9786 BTRFS_BLOCK_GROUP_RAID5 |
9787 BTRFS_BLOCK_GROUP_RAID6 |
b742bb82
YZ
9788 BTRFS_BLOCK_GROUP_DUP)))
9789 continue;
9790 /*
9791 * avoid allocating from un-mirrored block group if there are
9792 * mirrored block groups.
9793 */
1095cc0d 9794 list_for_each_entry(cache,
9795 &space_info->block_groups[BTRFS_RAID_RAID0],
9796 list)
868f401a 9797 inc_block_group_ro(cache, 1);
1095cc0d 9798 list_for_each_entry(cache,
9799 &space_info->block_groups[BTRFS_RAID_SINGLE],
9800 list)
868f401a 9801 inc_block_group_ro(cache, 1);
9078a3e1 9802 }
f0486c68
YZ
9803
9804 init_global_block_rsv(info);
0b86a832
CM
9805 ret = 0;
9806error:
9078a3e1 9807 btrfs_free_path(path);
0b86a832 9808 return ret;
9078a3e1 9809}
6324fbf3 9810
ea658bad
JB
9811void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
9812 struct btrfs_root *root)
9813{
9814 struct btrfs_block_group_cache *block_group, *tmp;
9815 struct btrfs_root *extent_root = root->fs_info->extent_root;
9816 struct btrfs_block_group_item item;
9817 struct btrfs_key key;
9818 int ret = 0;
d9a0540a 9819 bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
ea658bad 9820
d9a0540a 9821 trans->can_flush_pending_bgs = false;
47ab2a6c 9822 list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
ea658bad 9823 if (ret)
c92f6be3 9824 goto next;
ea658bad
JB
9825
9826 spin_lock(&block_group->lock);
9827 memcpy(&item, &block_group->item, sizeof(item));
9828 memcpy(&key, &block_group->key, sizeof(key));
9829 spin_unlock(&block_group->lock);
9830
9831 ret = btrfs_insert_item(trans, extent_root, &key, &item,
9832 sizeof(item));
9833 if (ret)
9834 btrfs_abort_transaction(trans, extent_root, ret);
6df9a95e
JB
9835 ret = btrfs_finish_chunk_alloc(trans, extent_root,
9836 key.objectid, key.offset);
9837 if (ret)
9838 btrfs_abort_transaction(trans, extent_root, ret);
c92f6be3
FM
9839next:
9840 list_del_init(&block_group->bg_list);
ea658bad 9841 }
d9a0540a 9842 trans->can_flush_pending_bgs = can_flush_pending_bgs;
ea658bad
JB
9843}
9844
6324fbf3
CM
9845int btrfs_make_block_group(struct btrfs_trans_handle *trans,
9846 struct btrfs_root *root, u64 bytes_used,
e17cade2 9847 u64 type, u64 chunk_objectid, u64 chunk_offset,
6324fbf3
CM
9848 u64 size)
9849{
9850 int ret;
6324fbf3
CM
9851 struct btrfs_root *extent_root;
9852 struct btrfs_block_group_cache *cache;
6324fbf3
CM
9853
9854 extent_root = root->fs_info->extent_root;
6324fbf3 9855
995946dd 9856 btrfs_set_log_full_commit(root->fs_info, trans);
e02119d5 9857
920e4a58 9858 cache = btrfs_create_block_group_cache(root, chunk_offset, size);
0f9dd46c
JB
9859 if (!cache)
9860 return -ENOMEM;
34d52cb6 9861
6324fbf3 9862 btrfs_set_block_group_used(&cache->item, bytes_used);
6324fbf3 9863 btrfs_set_block_group_chunk_objectid(&cache->item, chunk_objectid);
6324fbf3
CM
9864 btrfs_set_block_group_flags(&cache->item, type);
9865
920e4a58 9866 cache->flags = type;
11833d66 9867 cache->last_byte_to_unpin = (u64)-1;
817d52f8 9868 cache->cached = BTRFS_CACHE_FINISHED;
835d974f
JB
9869 ret = exclude_super_stripes(root, cache);
9870 if (ret) {
9871 /*
9872 * We may have excluded something, so call this just in
9873 * case.
9874 */
9875 free_excluded_extents(root, cache);
920e4a58 9876 btrfs_put_block_group(cache);
835d974f
JB
9877 return ret;
9878 }
96303081 9879
817d52f8
JB
9880 add_new_free_space(cache, root->fs_info, chunk_offset,
9881 chunk_offset + size);
9882
11833d66
YZ
9883 free_excluded_extents(root, cache);
9884
d0bd4560
JB
9885#ifdef CONFIG_BTRFS_DEBUG
9886 if (btrfs_should_fragment_free_space(root, cache)) {
9887 u64 new_bytes_used = size - bytes_used;
9888
9889 bytes_used += new_bytes_used >> 1;
9890 fragment_free_space(root, cache);
9891 }
9892#endif
2e6e5183
FM
9893 /*
9894 * Call to ensure the corresponding space_info object is created and
9895 * assigned to our block group, but don't update its counters just yet.
9896 * We want our bg to be added to the rbtree with its ->space_info set.
9897 */
9898 ret = update_space_info(root->fs_info, cache->flags, 0, 0,
9899 &cache->space_info);
9900 if (ret) {
9901 btrfs_remove_free_space_cache(cache);
9902 btrfs_put_block_group(cache);
9903 return ret;
9904 }
9905
8c579fe7
JB
9906 ret = btrfs_add_block_group_cache(root->fs_info, cache);
9907 if (ret) {
9908 btrfs_remove_free_space_cache(cache);
9909 btrfs_put_block_group(cache);
9910 return ret;
9911 }
9912
2e6e5183
FM
9913 /*
9914 * Now that our block group has its ->space_info set and is inserted in
9915 * the rbtree, update the space info's counters.
9916 */
6324fbf3
CM
9917 ret = update_space_info(root->fs_info, cache->flags, size, bytes_used,
9918 &cache->space_info);
8c579fe7
JB
9919 if (ret) {
9920 btrfs_remove_free_space_cache(cache);
9921 spin_lock(&root->fs_info->block_group_cache_lock);
9922 rb_erase(&cache->cache_node,
9923 &root->fs_info->block_group_cache_tree);
01eacb27 9924 RB_CLEAR_NODE(&cache->cache_node);
8c579fe7
JB
9925 spin_unlock(&root->fs_info->block_group_cache_lock);
9926 btrfs_put_block_group(cache);
9927 return ret;
9928 }
c7c144db 9929 update_global_block_rsv(root->fs_info);
1b2da372
JB
9930
9931 spin_lock(&cache->space_info->lock);
f0486c68 9932 cache->space_info->bytes_readonly += cache->bytes_super;
1b2da372
JB
9933 spin_unlock(&cache->space_info->lock);
9934
b742bb82 9935 __link_block_group(cache->space_info, cache);
6324fbf3 9936
47ab2a6c 9937 list_add_tail(&cache->bg_list, &trans->new_bgs);
6324fbf3 9938
d18a2c44 9939 set_avail_alloc_bits(extent_root->fs_info, type);
925baedd 9940
6324fbf3
CM
9941 return 0;
9942}
1a40e23b 9943
10ea00f5
ID
9944static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
9945{
899c81ea
ID
9946 u64 extra_flags = chunk_to_extended(flags) &
9947 BTRFS_EXTENDED_PROFILE_MASK;
10ea00f5 9948
de98ced9 9949 write_seqlock(&fs_info->profiles_lock);
10ea00f5
ID
9950 if (flags & BTRFS_BLOCK_GROUP_DATA)
9951 fs_info->avail_data_alloc_bits &= ~extra_flags;
9952 if (flags & BTRFS_BLOCK_GROUP_METADATA)
9953 fs_info->avail_metadata_alloc_bits &= ~extra_flags;
9954 if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
9955 fs_info->avail_system_alloc_bits &= ~extra_flags;
de98ced9 9956 write_sequnlock(&fs_info->profiles_lock);
10ea00f5
ID
9957}
9958
1a40e23b 9959int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
04216820
FM
9960 struct btrfs_root *root, u64 group_start,
9961 struct extent_map *em)
1a40e23b
ZY
9962{
9963 struct btrfs_path *path;
9964 struct btrfs_block_group_cache *block_group;
44fb5511 9965 struct btrfs_free_cluster *cluster;
0af3d00b 9966 struct btrfs_root *tree_root = root->fs_info->tree_root;
1a40e23b 9967 struct btrfs_key key;
0af3d00b 9968 struct inode *inode;
c1895442 9969 struct kobject *kobj = NULL;
1a40e23b 9970 int ret;
10ea00f5 9971 int index;
89a55897 9972 int factor;
4f69cb98 9973 struct btrfs_caching_control *caching_ctl = NULL;
04216820 9974 bool remove_em;
1a40e23b 9975
1a40e23b
ZY
9976 root = root->fs_info->extent_root;
9977
9978 block_group = btrfs_lookup_block_group(root->fs_info, group_start);
9979 BUG_ON(!block_group);
c146afad 9980 BUG_ON(!block_group->ro);
1a40e23b 9981
9f7c43c9 9982 /*
9983 * Free the reserved super bytes from this block group before
9984 * remove it.
9985 */
9986 free_excluded_extents(root, block_group);
9987
1a40e23b 9988 memcpy(&key, &block_group->key, sizeof(key));
10ea00f5 9989 index = get_block_group_index(block_group);
89a55897
JB
9990 if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
9991 BTRFS_BLOCK_GROUP_RAID1 |
9992 BTRFS_BLOCK_GROUP_RAID10))
9993 factor = 2;
9994 else
9995 factor = 1;
1a40e23b 9996
44fb5511
CM
9997 /* make sure this block group isn't part of an allocation cluster */
9998 cluster = &root->fs_info->data_alloc_cluster;
9999 spin_lock(&cluster->refill_lock);
10000 btrfs_return_cluster_to_free_space(block_group, cluster);
10001 spin_unlock(&cluster->refill_lock);
10002
10003 /*
10004 * make sure this block group isn't part of a metadata
10005 * allocation cluster
10006 */
10007 cluster = &root->fs_info->meta_alloc_cluster;
10008 spin_lock(&cluster->refill_lock);
10009 btrfs_return_cluster_to_free_space(block_group, cluster);
10010 spin_unlock(&cluster->refill_lock);
10011
1a40e23b 10012 path = btrfs_alloc_path();
d8926bb3
MF
10013 if (!path) {
10014 ret = -ENOMEM;
10015 goto out;
10016 }
1a40e23b 10017
1bbc621e
CM
10018 /*
10019 * get the inode first so any iput calls done for the io_list
10020 * aren't the final iput (no unlinks allowed now)
10021 */
10b2f34d 10022 inode = lookup_free_space_inode(tree_root, block_group, path);
1bbc621e
CM
10023
10024 mutex_lock(&trans->transaction->cache_write_mutex);
10025 /*
10026 * make sure our free spache cache IO is done before remove the
10027 * free space inode
10028 */
10029 spin_lock(&trans->transaction->dirty_bgs_lock);
10030 if (!list_empty(&block_group->io_list)) {
10031 list_del_init(&block_group->io_list);
10032
10033 WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
10034
10035 spin_unlock(&trans->transaction->dirty_bgs_lock);
10036 btrfs_wait_cache_io(root, trans, block_group,
10037 &block_group->io_ctl, path,
10038 block_group->key.objectid);
10039 btrfs_put_block_group(block_group);
10040 spin_lock(&trans->transaction->dirty_bgs_lock);
10041 }
10042
10043 if (!list_empty(&block_group->dirty_list)) {
10044 list_del_init(&block_group->dirty_list);
10045 btrfs_put_block_group(block_group);
10046 }
10047 spin_unlock(&trans->transaction->dirty_bgs_lock);
10048 mutex_unlock(&trans->transaction->cache_write_mutex);
10049
0af3d00b 10050 if (!IS_ERR(inode)) {
b532402e 10051 ret = btrfs_orphan_add(trans, inode);
79787eaa
JM
10052 if (ret) {
10053 btrfs_add_delayed_iput(inode);
10054 goto out;
10055 }
0af3d00b
JB
10056 clear_nlink(inode);
10057 /* One for the block groups ref */
10058 spin_lock(&block_group->lock);
10059 if (block_group->iref) {
10060 block_group->iref = 0;
10061 block_group->inode = NULL;
10062 spin_unlock(&block_group->lock);
10063 iput(inode);
10064 } else {
10065 spin_unlock(&block_group->lock);
10066 }
10067 /* One for our lookup ref */
455757c3 10068 btrfs_add_delayed_iput(inode);
0af3d00b
JB
10069 }
10070
10071 key.objectid = BTRFS_FREE_SPACE_OBJECTID;
10072 key.offset = block_group->key.objectid;
10073 key.type = 0;
10074
10075 ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
10076 if (ret < 0)
10077 goto out;
10078 if (ret > 0)
b3b4aa74 10079 btrfs_release_path(path);
0af3d00b
JB
10080 if (ret == 0) {
10081 ret = btrfs_del_item(trans, tree_root, path);
10082 if (ret)
10083 goto out;
b3b4aa74 10084 btrfs_release_path(path);
0af3d00b
JB
10085 }
10086
3dfdb934 10087 spin_lock(&root->fs_info->block_group_cache_lock);
1a40e23b
ZY
10088 rb_erase(&block_group->cache_node,
10089 &root->fs_info->block_group_cache_tree);
292cbd51 10090 RB_CLEAR_NODE(&block_group->cache_node);
a1897fdd
LB
10091
10092 if (root->fs_info->first_logical_byte == block_group->key.objectid)
10093 root->fs_info->first_logical_byte = (u64)-1;
3dfdb934 10094 spin_unlock(&root->fs_info->block_group_cache_lock);
817d52f8 10095
80eb234a 10096 down_write(&block_group->space_info->groups_sem);
44fb5511
CM
10097 /*
10098 * we must use list_del_init so people can check to see if they
10099 * are still on the list after taking the semaphore
10100 */
10101 list_del_init(&block_group->list);
6ab0a202 10102 if (list_empty(&block_group->space_info->block_groups[index])) {
c1895442
JM
10103 kobj = block_group->space_info->block_group_kobjs[index];
10104 block_group->space_info->block_group_kobjs[index] = NULL;
10ea00f5 10105 clear_avail_alloc_bits(root->fs_info, block_group->flags);
6ab0a202 10106 }
80eb234a 10107 up_write(&block_group->space_info->groups_sem);
c1895442
JM
10108 if (kobj) {
10109 kobject_del(kobj);
10110 kobject_put(kobj);
10111 }
1a40e23b 10112
4f69cb98
FM
10113 if (block_group->has_caching_ctl)
10114 caching_ctl = get_caching_control(block_group);
817d52f8 10115 if (block_group->cached == BTRFS_CACHE_STARTED)
11833d66 10116 wait_block_group_cache_done(block_group);
4f69cb98
FM
10117 if (block_group->has_caching_ctl) {
10118 down_write(&root->fs_info->commit_root_sem);
10119 if (!caching_ctl) {
10120 struct btrfs_caching_control *ctl;
10121
10122 list_for_each_entry(ctl,
10123 &root->fs_info->caching_block_groups, list)
10124 if (ctl->block_group == block_group) {
10125 caching_ctl = ctl;
10126 atomic_inc(&caching_ctl->count);
10127 break;
10128 }
10129 }
10130 if (caching_ctl)
10131 list_del_init(&caching_ctl->list);
10132 up_write(&root->fs_info->commit_root_sem);
10133 if (caching_ctl) {
10134 /* Once for the caching bgs list and once for us. */
10135 put_caching_control(caching_ctl);
10136 put_caching_control(caching_ctl);
10137 }
10138 }
817d52f8 10139
ce93ec54
JB
10140 spin_lock(&trans->transaction->dirty_bgs_lock);
10141 if (!list_empty(&block_group->dirty_list)) {
1bbc621e
CM
10142 WARN_ON(1);
10143 }
10144 if (!list_empty(&block_group->io_list)) {
10145 WARN_ON(1);
ce93ec54
JB
10146 }
10147 spin_unlock(&trans->transaction->dirty_bgs_lock);
817d52f8
JB
10148 btrfs_remove_free_space_cache(block_group);
10149
c146afad 10150 spin_lock(&block_group->space_info->lock);
75c68e9f 10151 list_del_init(&block_group->ro_list);
18d018ad
ZL
10152
10153 if (btrfs_test_opt(root, ENOSPC_DEBUG)) {
10154 WARN_ON(block_group->space_info->total_bytes
10155 < block_group->key.offset);
10156 WARN_ON(block_group->space_info->bytes_readonly
10157 < block_group->key.offset);
10158 WARN_ON(block_group->space_info->disk_total
10159 < block_group->key.offset * factor);
10160 }
c146afad
YZ
10161 block_group->space_info->total_bytes -= block_group->key.offset;
10162 block_group->space_info->bytes_readonly -= block_group->key.offset;
89a55897 10163 block_group->space_info->disk_total -= block_group->key.offset * factor;
18d018ad 10164
c146afad 10165 spin_unlock(&block_group->space_info->lock);
283bb197 10166
0af3d00b
JB
10167 memcpy(&key, &block_group->key, sizeof(key));
10168
04216820 10169 lock_chunks(root);
495e64f4
FM
10170 if (!list_empty(&em->list)) {
10171 /* We're in the transaction->pending_chunks list. */
10172 free_extent_map(em);
10173 }
04216820
FM
10174 spin_lock(&block_group->lock);
10175 block_group->removed = 1;
10176 /*
10177 * At this point trimming can't start on this block group, because we
10178 * removed the block group from the tree fs_info->block_group_cache_tree
10179 * so no one can't find it anymore and even if someone already got this
10180 * block group before we removed it from the rbtree, they have already
10181 * incremented block_group->trimming - if they didn't, they won't find
10182 * any free space entries because we already removed them all when we
10183 * called btrfs_remove_free_space_cache().
10184 *
10185 * And we must not remove the extent map from the fs_info->mapping_tree
10186 * to prevent the same logical address range and physical device space
10187 * ranges from being reused for a new block group. This is because our
10188 * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
10189 * completely transactionless, so while it is trimming a range the
10190 * currently running transaction might finish and a new one start,
10191 * allowing for new block groups to be created that can reuse the same
10192 * physical device locations unless we take this special care.
e33e17ee
JM
10193 *
10194 * There may also be an implicit trim operation if the file system
10195 * is mounted with -odiscard. The same protections must remain
10196 * in place until the extents have been discarded completely when
10197 * the transaction commit has completed.
04216820
FM
10198 */
10199 remove_em = (atomic_read(&block_group->trimming) == 0);
10200 /*
10201 * Make sure a trimmer task always sees the em in the pinned_chunks list
10202 * if it sees block_group->removed == 1 (needs to lock block_group->lock
10203 * before checking block_group->removed).
10204 */
10205 if (!remove_em) {
10206 /*
10207 * Our em might be in trans->transaction->pending_chunks which
10208 * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
10209 * and so is the fs_info->pinned_chunks list.
10210 *
10211 * So at this point we must be holding the chunk_mutex to avoid
10212 * any races with chunk allocation (more specifically at
10213 * volumes.c:contains_pending_extent()), to ensure it always
10214 * sees the em, either in the pending_chunks list or in the
10215 * pinned_chunks list.
10216 */
10217 list_move_tail(&em->list, &root->fs_info->pinned_chunks);
10218 }
10219 spin_unlock(&block_group->lock);
04216820
FM
10220
10221 if (remove_em) {
10222 struct extent_map_tree *em_tree;
10223
10224 em_tree = &root->fs_info->mapping_tree.map_tree;
10225 write_lock(&em_tree->lock);
8dbcd10f
FM
10226 /*
10227 * The em might be in the pending_chunks list, so make sure the
10228 * chunk mutex is locked, since remove_extent_mapping() will
10229 * delete us from that list.
10230 */
04216820
FM
10231 remove_extent_mapping(em_tree, em);
10232 write_unlock(&em_tree->lock);
10233 /* once for the tree */
10234 free_extent_map(em);
10235 }
10236
8dbcd10f
FM
10237 unlock_chunks(root);
10238
fa9c0d79
CM
10239 btrfs_put_block_group(block_group);
10240 btrfs_put_block_group(block_group);
1a40e23b
ZY
10241
10242 ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
10243 if (ret > 0)
10244 ret = -EIO;
10245 if (ret < 0)
10246 goto out;
10247
10248 ret = btrfs_del_item(trans, root, path);
10249out:
10250 btrfs_free_path(path);
10251 return ret;
10252}
acce952b 10253
47ab2a6c
JB
10254/*
10255 * Process the unused_bgs list and remove any that don't have any allocated
10256 * space inside of them.
10257 */
10258void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
10259{
10260 struct btrfs_block_group_cache *block_group;
10261 struct btrfs_space_info *space_info;
10262 struct btrfs_root *root = fs_info->extent_root;
10263 struct btrfs_trans_handle *trans;
10264 int ret = 0;
10265
10266 if (!fs_info->open)
10267 return;
10268
10269 spin_lock(&fs_info->unused_bgs_lock);
10270 while (!list_empty(&fs_info->unused_bgs)) {
10271 u64 start, end;
e33e17ee 10272 int trimming;
47ab2a6c
JB
10273
10274 block_group = list_first_entry(&fs_info->unused_bgs,
10275 struct btrfs_block_group_cache,
10276 bg_list);
10277 space_info = block_group->space_info;
10278 list_del_init(&block_group->bg_list);
10279 if (ret || btrfs_mixed_space_info(space_info)) {
10280 btrfs_put_block_group(block_group);
10281 continue;
10282 }
10283 spin_unlock(&fs_info->unused_bgs_lock);
10284
67c5e7d4
FM
10285 mutex_lock(&root->fs_info->delete_unused_bgs_mutex);
10286
47ab2a6c
JB
10287 /* Don't want to race with allocators so take the groups_sem */
10288 down_write(&space_info->groups_sem);
10289 spin_lock(&block_group->lock);
10290 if (block_group->reserved ||
10291 btrfs_block_group_used(&block_group->item) ||
10292 block_group->ro) {
10293 /*
10294 * We want to bail if we made new allocations or have
10295 * outstanding allocations in this block group. We do
10296 * the ro check in case balance is currently acting on
10297 * this block group.
10298 */
10299 spin_unlock(&block_group->lock);
10300 up_write(&space_info->groups_sem);
10301 goto next;
10302 }
10303 spin_unlock(&block_group->lock);
10304
10305 /* We don't want to force the issue, only flip if it's ok. */
868f401a 10306 ret = inc_block_group_ro(block_group, 0);
47ab2a6c
JB
10307 up_write(&space_info->groups_sem);
10308 if (ret < 0) {
10309 ret = 0;
10310 goto next;
10311 }
10312
10313 /*
10314 * Want to do this before we do anything else so we can recover
10315 * properly if we fail to join the transaction.
10316 */
3d84be79
FL
10317 /* 1 for btrfs_orphan_reserve_metadata() */
10318 trans = btrfs_start_transaction(root, 1);
47ab2a6c 10319 if (IS_ERR(trans)) {
868f401a 10320 btrfs_dec_block_group_ro(root, block_group);
47ab2a6c
JB
10321 ret = PTR_ERR(trans);
10322 goto next;
10323 }
10324
10325 /*
10326 * We could have pending pinned extents for this block group,
10327 * just delete them, we don't care about them anymore.
10328 */
10329 start = block_group->key.objectid;
10330 end = start + block_group->key.offset - 1;
d4b450cd
FM
10331 /*
10332 * Hold the unused_bg_unpin_mutex lock to avoid racing with
10333 * btrfs_finish_extent_commit(). If we are at transaction N,
10334 * another task might be running finish_extent_commit() for the
10335 * previous transaction N - 1, and have seen a range belonging
10336 * to the block group in freed_extents[] before we were able to
10337 * clear the whole block group range from freed_extents[]. This
10338 * means that task can lookup for the block group after we
10339 * unpinned it from freed_extents[] and removed it, leading to
10340 * a BUG_ON() at btrfs_unpin_extent_range().
10341 */
10342 mutex_lock(&fs_info->unused_bg_unpin_mutex);
758eb51e 10343 ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
47ab2a6c 10344 EXTENT_DIRTY, GFP_NOFS);
758eb51e 10345 if (ret) {
d4b450cd 10346 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
868f401a 10347 btrfs_dec_block_group_ro(root, block_group);
758eb51e
FM
10348 goto end_trans;
10349 }
10350 ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
47ab2a6c 10351 EXTENT_DIRTY, GFP_NOFS);
758eb51e 10352 if (ret) {
d4b450cd 10353 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
868f401a 10354 btrfs_dec_block_group_ro(root, block_group);
758eb51e
FM
10355 goto end_trans;
10356 }
d4b450cd 10357 mutex_unlock(&fs_info->unused_bg_unpin_mutex);
47ab2a6c
JB
10358
10359 /* Reset pinned so btrfs_put_block_group doesn't complain */
c30666d4
ZL
10360 spin_lock(&space_info->lock);
10361 spin_lock(&block_group->lock);
10362
10363 space_info->bytes_pinned -= block_group->pinned;
10364 space_info->bytes_readonly += block_group->pinned;
10365 percpu_counter_add(&space_info->total_bytes_pinned,
10366 -block_group->pinned);
47ab2a6c
JB
10367 block_group->pinned = 0;
10368
c30666d4
ZL
10369 spin_unlock(&block_group->lock);
10370 spin_unlock(&space_info->lock);
10371
e33e17ee
JM
10372 /* DISCARD can flip during remount */
10373 trimming = btrfs_test_opt(root, DISCARD);
10374
10375 /* Implicit trim during transaction commit. */
10376 if (trimming)
10377 btrfs_get_block_group_trimming(block_group);
10378
47ab2a6c
JB
10379 /*
10380 * Btrfs_remove_chunk will abort the transaction if things go
10381 * horribly wrong.
10382 */
10383 ret = btrfs_remove_chunk(trans, root,
10384 block_group->key.objectid);
e33e17ee
JM
10385
10386 if (ret) {
10387 if (trimming)
10388 btrfs_put_block_group_trimming(block_group);
10389 goto end_trans;
10390 }
10391
10392 /*
10393 * If we're not mounted with -odiscard, we can just forget
10394 * about this block group. Otherwise we'll need to wait
10395 * until transaction commit to do the actual discard.
10396 */
10397 if (trimming) {
10398 WARN_ON(!list_empty(&block_group->bg_list));
10399 spin_lock(&trans->transaction->deleted_bgs_lock);
10400 list_move(&block_group->bg_list,
10401 &trans->transaction->deleted_bgs);
10402 spin_unlock(&trans->transaction->deleted_bgs_lock);
10403 btrfs_get_block_group(block_group);
10404 }
758eb51e 10405end_trans:
47ab2a6c
JB
10406 btrfs_end_transaction(trans, root);
10407next:
67c5e7d4 10408 mutex_unlock(&root->fs_info->delete_unused_bgs_mutex);
47ab2a6c
JB
10409 btrfs_put_block_group(block_group);
10410 spin_lock(&fs_info->unused_bgs_lock);
10411 }
10412 spin_unlock(&fs_info->unused_bgs_lock);
10413}
10414
c59021f8 10415int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
10416{
10417 struct btrfs_space_info *space_info;
1aba86d6 10418 struct btrfs_super_block *disk_super;
10419 u64 features;
10420 u64 flags;
10421 int mixed = 0;
c59021f8 10422 int ret;
10423
6c41761f 10424 disk_super = fs_info->super_copy;
1aba86d6 10425 if (!btrfs_super_root(disk_super))
10426 return 1;
c59021f8 10427
1aba86d6 10428 features = btrfs_super_incompat_flags(disk_super);
10429 if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
10430 mixed = 1;
c59021f8 10431
1aba86d6 10432 flags = BTRFS_BLOCK_GROUP_SYSTEM;
10433 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
c59021f8 10434 if (ret)
1aba86d6 10435 goto out;
c59021f8 10436
1aba86d6 10437 if (mixed) {
10438 flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
10439 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
10440 } else {
10441 flags = BTRFS_BLOCK_GROUP_METADATA;
10442 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
10443 if (ret)
10444 goto out;
10445
10446 flags = BTRFS_BLOCK_GROUP_DATA;
10447 ret = update_space_info(fs_info, flags, 0, 0, &space_info);
10448 }
10449out:
c59021f8 10450 return ret;
10451}
10452
acce952b 10453int btrfs_error_unpin_extent_range(struct btrfs_root *root, u64 start, u64 end)
10454{
678886bd 10455 return unpin_extent_range(root, start, end, false);
acce952b 10456}
10457
499f377f
JM
10458/*
10459 * It used to be that old block groups would be left around forever.
10460 * Iterating over them would be enough to trim unused space. Since we
10461 * now automatically remove them, we also need to iterate over unallocated
10462 * space.
10463 *
10464 * We don't want a transaction for this since the discard may take a
10465 * substantial amount of time. We don't require that a transaction be
10466 * running, but we do need to take a running transaction into account
10467 * to ensure that we're not discarding chunks that were released in
10468 * the current transaction.
10469 *
10470 * Holding the chunks lock will prevent other threads from allocating
10471 * or releasing chunks, but it won't prevent a running transaction
10472 * from committing and releasing the memory that the pending chunks
10473 * list head uses. For that, we need to take a reference to the
10474 * transaction.
10475 */
10476static int btrfs_trim_free_extents(struct btrfs_device *device,
10477 u64 minlen, u64 *trimmed)
10478{
10479 u64 start = 0, len = 0;
10480 int ret;
10481
10482 *trimmed = 0;
10483
10484 /* Not writeable = nothing to do. */
10485 if (!device->writeable)
10486 return 0;
10487
10488 /* No free space = nothing to do. */
10489 if (device->total_bytes <= device->bytes_used)
10490 return 0;
10491
10492 ret = 0;
10493
10494 while (1) {
10495 struct btrfs_fs_info *fs_info = device->dev_root->fs_info;
10496 struct btrfs_transaction *trans;
10497 u64 bytes;
10498
10499 ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
10500 if (ret)
10501 return ret;
10502
10503 down_read(&fs_info->commit_root_sem);
10504
10505 spin_lock(&fs_info->trans_lock);
10506 trans = fs_info->running_transaction;
10507 if (trans)
10508 atomic_inc(&trans->use_count);
10509 spin_unlock(&fs_info->trans_lock);
10510
10511 ret = find_free_dev_extent_start(trans, device, minlen, start,
10512 &start, &len);
10513 if (trans)
10514 btrfs_put_transaction(trans);
10515
10516 if (ret) {
10517 up_read(&fs_info->commit_root_sem);
10518 mutex_unlock(&fs_info->chunk_mutex);
10519 if (ret == -ENOSPC)
10520 ret = 0;
10521 break;
10522 }
10523
10524 ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
10525 up_read(&fs_info->commit_root_sem);
10526 mutex_unlock(&fs_info->chunk_mutex);
10527
10528 if (ret)
10529 break;
10530
10531 start += len;
10532 *trimmed += bytes;
10533
10534 if (fatal_signal_pending(current)) {
10535 ret = -ERESTARTSYS;
10536 break;
10537 }
10538
10539 cond_resched();
10540 }
10541
10542 return ret;
10543}
10544
f7039b1d
LD
10545int btrfs_trim_fs(struct btrfs_root *root, struct fstrim_range *range)
10546{
10547 struct btrfs_fs_info *fs_info = root->fs_info;
10548 struct btrfs_block_group_cache *cache = NULL;
499f377f
JM
10549 struct btrfs_device *device;
10550 struct list_head *devices;
f7039b1d
LD
10551 u64 group_trimmed;
10552 u64 start;
10553 u64 end;
10554 u64 trimmed = 0;
2cac13e4 10555 u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
f7039b1d
LD
10556 int ret = 0;
10557
2cac13e4
LB
10558 /*
10559 * try to trim all FS space, our block group may start from non-zero.
10560 */
10561 if (range->len == total_bytes)
10562 cache = btrfs_lookup_first_block_group(fs_info, range->start);
10563 else
10564 cache = btrfs_lookup_block_group(fs_info, range->start);
f7039b1d
LD
10565
10566 while (cache) {
10567 if (cache->key.objectid >= (range->start + range->len)) {
10568 btrfs_put_block_group(cache);
10569 break;
10570 }
10571
10572 start = max(range->start, cache->key.objectid);
10573 end = min(range->start + range->len,
10574 cache->key.objectid + cache->key.offset);
10575
10576 if (end - start >= range->minlen) {
10577 if (!block_group_cache_done(cache)) {
f6373bf3 10578 ret = cache_block_group(cache, 0);
1be41b78
JB
10579 if (ret) {
10580 btrfs_put_block_group(cache);
10581 break;
10582 }
10583 ret = wait_block_group_cache_done(cache);
10584 if (ret) {
10585 btrfs_put_block_group(cache);
10586 break;
10587 }
f7039b1d
LD
10588 }
10589 ret = btrfs_trim_block_group(cache,
10590 &group_trimmed,
10591 start,
10592 end,
10593 range->minlen);
10594
10595 trimmed += group_trimmed;
10596 if (ret) {
10597 btrfs_put_block_group(cache);
10598 break;
10599 }
10600 }
10601
10602 cache = next_block_group(fs_info->tree_root, cache);
10603 }
10604
499f377f
JM
10605 mutex_lock(&root->fs_info->fs_devices->device_list_mutex);
10606 devices = &root->fs_info->fs_devices->alloc_list;
10607 list_for_each_entry(device, devices, dev_alloc_list) {
10608 ret = btrfs_trim_free_extents(device, range->minlen,
10609 &group_trimmed);
10610 if (ret)
10611 break;
10612
10613 trimmed += group_trimmed;
10614 }
10615 mutex_unlock(&root->fs_info->fs_devices->device_list_mutex);
10616
f7039b1d
LD
10617 range->len = trimmed;
10618 return ret;
10619}
8257b2dc
MX
10620
10621/*
9ea24bbe
FM
10622 * btrfs_{start,end}_write_no_snapshoting() are similar to
10623 * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
10624 * data into the page cache through nocow before the subvolume is snapshoted,
10625 * but flush the data into disk after the snapshot creation, or to prevent
10626 * operations while snapshoting is ongoing and that cause the snapshot to be
10627 * inconsistent (writes followed by expanding truncates for example).
8257b2dc 10628 */
9ea24bbe 10629void btrfs_end_write_no_snapshoting(struct btrfs_root *root)
8257b2dc
MX
10630{
10631 percpu_counter_dec(&root->subv_writers->counter);
10632 /*
a83342aa 10633 * Make sure counter is updated before we wake up waiters.
8257b2dc
MX
10634 */
10635 smp_mb();
10636 if (waitqueue_active(&root->subv_writers->wait))
10637 wake_up(&root->subv_writers->wait);
10638}
10639
9ea24bbe 10640int btrfs_start_write_no_snapshoting(struct btrfs_root *root)
8257b2dc 10641{
ee39b432 10642 if (atomic_read(&root->will_be_snapshoted))
8257b2dc
MX
10643 return 0;
10644
10645 percpu_counter_inc(&root->subv_writers->counter);
10646 /*
10647 * Make sure counter is updated before we check for snapshot creation.
10648 */
10649 smp_mb();
ee39b432 10650 if (atomic_read(&root->will_be_snapshoted)) {
9ea24bbe 10651 btrfs_end_write_no_snapshoting(root);
8257b2dc
MX
10652 return 0;
10653 }
10654 return 1;
10655}
This page took 1.463221 seconds and 5 git commands to generate.