#!/bin/bash
# SPDX-License-Identifier: GPL-3.0+
# Copyright (C) 2018 Western Digital Corporation or its affiliates.
#
# Run a high queue depth direct sequential write fio job to check that
# write requests are not being reordered when the deadline scheduler is
# used. This test allowed to catch a bug fixed with commit 80e02039721
# "block: mq-deadline: Fix write completion handling".

. tests/zbd/rc

DESCRIPTION="write command ordering"
TIMED=1
CAN_BE_ZONED=1

requires() {
	_have_fio_zbd_zonemode
}

fallback_device() {
	_fallback_null_blk_zoned
}

cleanup_fallback_device() {
	_exit_null_blk
}

test_device() {
	local -i zone_idx
	local -i offset
	local -i moaz
	local -a zbdmode=()

	echo "Running ${TEST_NAME}"

	_get_blkzone_report "${TEST_DEV}" || return $?

	zone_idx=$(_find_first_sequential_zone) || return $?
	offset=$((ZONE_STARTS[zone_idx] * 512))
	moaz=$(_test_dev_max_open_active_zones)

	# If the test target zone has smaller zone capacity than zone size,
	# or if the test target device has max open/active zones limit, enable
	# zonemode=zbd and specify the limit to handle the zone restrictions.
	if ((ZONE_CAPS[zone_idx] != ZONE_LENGTHS[zone_idx])) || ((moaz)); then
		zbdmode=("--zonemode=zbd" "--max_open_zones=${moaz}")
	fi

	blkzone reset -o "${ZONE_STARTS[zone_idx]}" "${TEST_DEV}"

	_test_dev_set_scheduler deadline

	: "${TIMEOUT:=30}"
	FIO_PERF_FIELDS=("write io" "write iops")
	_fio_perf --filename="${TEST_DEV}" --name zbdwo --rw=write --direct=1 \
		  --ioengine=libaio --iodepth=128 --bs=256k \
		  --offset="${offset}" "${zbdmode[@]}"

	_put_blkzone_report

	echo "Test complete"
}
