#!/bin/bash
# SPDX-License-Identifier: GPL-3.0+
# Copyright (C) 2017 Dmitry Monakhov <dmonakhov@openvz.org>
#
# Check page-cache coherency after BLKDISCARD. Regression test for commit
# 351499a172c0 ("block: Invalidate cache on discard v2"). The page cache should
# be dropped after a successful discard.

. tests/block/rc
. common/scsi_debug

DESCRIPTION="check page-cache coherency after BLKDISCARD"

requires() {
	_have_module scsi_debug
	_have_program xfs_io
}

test() {
	echo "Running ${TEST_NAME}"

	rm -f "$FULL"

	# Create virtual device with unmap_zeroes_data support
	if ! _init_scsi_debug dev_size_mb=32 lbpws=1 lbpws10=1; then
		return 1
	fi

	local dev="/dev/${SCSI_DEBUG_DEVICES[0]}"
	# Initialize data with known pattern
	xfs_io -c "pwrite -S 0xaa -b 2M 0 32M -w" -d "$dev" >>"$FULL"

	# Fill page cache with dirty data
	xfs_io -c "pwrite -S 0xbb -b 2M 2M 10M" -f "$dev" >>"$FULL"

	blkdiscard "$dev"
	# After device was fully discarded, read sould return all zeroes
	dd if="$dev" bs=4k  2>>"$FULL" | hexdump
	dd if="$dev" bs=4M iflag=direct 2>>"$FULL" | hexdump

	_exit_scsi_debug

	echo "Test complete"
}
