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