#!/bin/bash
# SPDX-License-Identifier: GPL-3.0+
# Copyright (C) 2017 David Disseldorp
#
# Test read-only state with BLKROSET and BLKROGET ioctls

. tests/block/rc

DESCRIPTION="check that a read-only block device fails writes"
TIMED=1

requires() {
	_have_program xfs_io
}

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

	blockdev --getro "$TEST_DEV"
	xfs_io -c "pwrite -w -S 0xaa -b 2M 0 2M" -d "$TEST_DEV" >>"$FULL"
	dd if="$TEST_DEV" bs=2M count=1 2>>"$FULL" | hexdump
	blockdev --setro "$TEST_DEV"
	# It is valid to set a device that is already read-only to read-only.
	blockdev --setro "$TEST_DEV"
	blockdev --getro "$TEST_DEV"
	# writes should fail while device is read-only
	xfs_io -c "pwrite -w -S 0xbb -b 2M 0 2M" -d "$TEST_DEV" 2>&1 >>"$FULL" \
		| _filter_xfs_io_error
	dd if="$TEST_DEV" bs=2M count=1 2>>"$FULL" | hexdump
	blockdev --setrw "$TEST_DEV"
	blockdev --getro "$TEST_DEV"
	xfs_io -c "pwrite -w -S 0xcc -b 2M 0 2M" -d "$TEST_DEV" >>"$FULL"
	dd if="$TEST_DEV" bs=2M count=1 2>>"$FULL" | hexdump

	echo "Test complete"
}
