btrfs-progs: lowmem check: Fix regression which screws up extent allocator
authorQu Wenruo <wqu@suse.com>
Wed, 22 Nov 2017 09:03:15 +0000 (17:03 +0800)
committerDavid Sterba <dsterba@suse.com>
Wed, 3 Jan 2018 16:09:07 +0000 (17:09 +0100)
commitbeb06b63cc9a54f0d33dae43c3c6ff956ccc885a
treee557180c59560f0ff67478989258534cce498d4d
parent86fe5fb2c15aa49e4b98ad83c071d5d63895a0be
btrfs-progs: lowmem check: Fix regression which screws up extent allocator

[BUG]
Commit 723427d7e6b7 ("btrfs-progs: check: change the way lowmem mode
traverses metadata") introduces a regression which could make some fsck
self test case to fail.

For fsck test case 004-no-dir-item, btrfs check --mode=lowmem --repair
can cause BUG_ON() with ret = -17 (-EEXIST) when committing transaction.

The problem happens with the following backtrace:

./btrfs(+0x22045)[0x555d0dade045]
./btrfs(+0x2216f)[0x555d0dade16f]
./btrfs(+0x29df1)[0x555d0dae5df1]
./btrfs(+0x2a142)[0x555d0dae6142]
./btrfs(btrfs_alloc_free_block+0x78)[0x555d0dae6202]
./btrfs(__btrfs_cow_block+0x177)[0x555d0dad00a2]
./btrfs(btrfs_cow_block+0x116)[0x555d0dad05a8]
./btrfs(commit_tree_roots+0x91)[0x555d0db1fd4f]
./btrfs(btrfs_commit_transaction+0x18c)[0x555d0db20100]
./btrfs(btrfs_fix_super_size+0x190)[0x555d0db005a4]
./btrfs(btrfs_fix_device_and_super_size+0x177)[0x555d0db00771]
./btrfs(cmd_check+0x1757)[0x555d0db4f6ab]
./btrfs(main+0x138)[0x555d0dace5dd]
/usr/lib/libc.so.6(__libc_start_main+0xea)[0x7fa5e4613f6a]
./btrfs(_start+0x2a)[0x555d0dacddda]

The bug is triggered by that, extent allocator considers range
[2936012829376512) as free and allocates it.  However when inserting
EXTENT_ITEM, btrfs finds there is already one tree block (fs tree root),
returning -EEXIST and causing the later BUG_ON().

[CAUSE]
The cause is in repair mode, lowmem check always pins all metadata
blocks.  However pinned metadata blocks will be unpined when transaction
commits, and will be marked as *FREE* space.

So later extent allocator will consider such range free and allocates
them incorrectly.

[FIX]
Don't pin metadata blocks without valid reason or preparation (like
discard all free space cache to re-calculate free space on next write).

Fixes: 723427d7e6b7 ("btrfs-progs: check: change the way lowmem mode traverses metadata")
Signed-off-by: Qu Wenruo <wqu@suse.com>
Signed-off-by: David Sterba <dsterba@suse.com>
cmds-check.c