#! /bin/bash
# SPDX-License-Identifier: GPL-2.0
# Copyright (c) 2026 Christoph Hellwig
#
# FS QA Test No. 803
#
# Basic FSX sanity check when using T10 protection information
#
. ./common/preamble
_begin_fstest auto rw pi dangerous

_cleanup()
{
	cd /
	rm -r -f $tmp.*
	[ -d "$SCSI_DEBUG_MNT" ] && _unmount $SCSI_DEBUG_MNT 2>/dev/null
	_put_scsi_debug_dev
}

. ./common/scsi_debug

_require_debugfs
_require_scsi_debug
# If TEST_DEV is block device, make sure current fs is a localfs which can be
# written on scsi_debug device
_require_test
_require_block_device $TEST_DEV
_require_odirect

_fixed_by_kernel_commit 8a8685b32c07 \
	"iomap: don't free integrity payload that doesn't exist"

size=$(_small_fs_size_mb 256)

# like run_fsx(), but using a custom path
fsx_run()
{
	_run_fsx_on_file $SCSI_DEBUG_MNT/junk $@ || _exit 1
}

test_dif()
{
	local pi_type=$1
	local pi_enable="$2"

	scsi_debug_pi_opts="write_same_length=0 dif=${pi_type} dix=1"
	SCSI_DEBUG_DEV=`_get_scsi_debug_dev 512 512 0 $size $scsi_debug_pi_opts`

	local integrity_path="$(_sysfs_block_integrity_path $SCSI_DEBUG_DEV)"
	if [ ! -d "$integrity_path" ]; then
		_notrun "DIF not supported by running kernel"
	fi

	SCSI_DEBUG_MNT="$TEST_DIR/scsi_debug_$seq"
	rm -rf $SCSI_DEBUG_MNT
	mkdir $SCSI_DEBUG_MNT

	_mkfs_dev $SCSI_DEBUG_DEV || \
		_fail "Can't make $FSTYP on DIF-enabled scsi_debug device"
	run_check _mount $SCSI_DEBUG_DEV $SCSI_DEBUG_MNT

	echo $pi_enable > $integrity_path/read_verify
	echo $pi_enable > $integrity_path/write_generate

	# fsx load similar to generic/091
	echo "Testing direct I/O for DIF type $pi_type (enabled: $pi_enable)"
	bsize=$($here/src/min_dio_alignment $SCSI_DEBUG_MNT $SCSI_DEBUG_DEV)
	fsx_run -N 10000            -l 500000 -r BSIZE -w BSIZE -Z -R -W
	fsx_run -N 10000  -o 8192   -l 500000 -r BSIZE -w BSIZE -Z -R -W
	fsx_run -N 10000  -o 32768  -l 500000 -r BSIZE -w BSIZE -Z -R -W
	fsx_run -N 10000  -o 8192   -l 500000 -r BSIZE -w BSIZE -Z -R -W
	fsx_run -N 10000  -o 32768  -l 500000 -r BSIZE -w BSIZE -Z -R -W
	fsx_run -N 10000  -o 128000 -l 500000 -r BSIZE -w BSIZE -Z -W

	# fsx load similar to generic/091 but using buffered I/O
	echo "Testing buffered I/O for DIF type $pi_type (enabled: $pi_enable)"
	fsx_run -N 10000            -l 500000
	fsx_run -N 10000  -o 8192   -l 500000
	fsx_run -N 10000  -o 32768  -l 500000
	fsx_run -N 10000  -o 128000 -l 500000

	[ -d "$SCSI_DEBUG_MNT" ] && _unmount $SCSI_DEBUG_MNT 2>/dev/null
	_put_scsi_debug_dev
}

# Test with PI fully enabled
test_dif 1 1
test_dif 2 1
test_dif 3 1

# Test with strip / insert in the HBA
test_dif 1 0
test_dif 2 0
test_dif 3 0

# success, all done
_exit 0
