#! /bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2014 Fujitsu.  All Rights Reserved.
#
# FS QA Test No. btrfs/049
#
# Regression test for btrfs inode caching vs tree log which was
# addressed by the following kernel patch.
#
# Btrfs: fix inode caching vs tree log
#
. ./common/preamble
_begin_fstest auto quick

# Override the default cleanup function.
_cleanup()
{
	_cleanup_flakey
	rm -rf $tmp
}

# Import common functions.
. ./common/filter
. ./common/dmflakey

# real QA test starts here
_supported_fs btrfs
_require_scratch
_require_dm_target flakey

_scratch_mkfs >> $seqres.full 2>&1

SAVE_MOUNT_OPTIONS="$MOUNT_OPTIONS"
MOUNT_OPTIONS="$MOUNT_OPTIONS -o inode_cache,commit=100"

# create a basic flakey device that will never error out
_init_flakey
_mount_flakey

_get_inode_id()
{
	local inode_id
	inode_id=`stat $1 | grep Inode: | $AWK_PROG '{print $4}'`
	echo $inode_id
}

$XFS_IO_PROG -f -c "pwrite 0 10M" -c "fsync" \
	$SCRATCH_MNT/data >& /dev/null

inode_id=`_get_inode_id "$SCRATCH_MNT/data"`
rm -f $SCRATCH_MNT/data

for i in `seq 1 5`;
do
	mkdir $SCRATCH_MNT/dir_$i
	new_inode_id=`_get_inode_id $SCRATCH_MNT/dir_$i`
	if [ $new_inode_id -eq $inode_id ]
	then
		$XFS_IO_PROG -f -c "pwrite 0 1M" -c "fsync" \
			$SCRATCH_MNT/dir_$i/data1 >& /dev/null
		_load_flakey_table 1
		_unmount_flakey
		need_umount=1
		break
	fi
	sleep 1
done

# restore previous mount options
export MOUNT_OPTIONS="$SAVE_MOUNT_OPTIONS"

# ok mount so that any recovery that needs to happen is done
if [ $new_inode_id -eq $inode_id ];then
	_load_flakey_table $FLAKEY_ALLOW_WRITES
	_mount_flakey
	_unmount_flakey
fi

# make sure we got a valid fs after replay
_check_scratch_fs $FLAKEY_DEV

status=0
exit
