#!/bin/bash
# SPDX-License-Identifier: GPL-3.0+
# Copyright (C) 2018 Omar Sandoval
#
# Test the iostats counters for time spent doing I/O.

. tests/block/rc
. common/null_blk

DESCRIPTION="do I/O and check iostats times"
QUICK=1

requires() {
	_have_null_blk
}

init_times() {
	init_read_ms="$(awk '{ print $4 }' /sys/block/nullb1/stat)"
	init_write_ms="$(awk '{ print $8 }' /sys/block/nullb1/stat)"
}

show_times() {
	read_ms="$(awk '{ print $4 }' /sys/block/nullb1/stat)"
	write_ms="$(awk '{ print $8 }' /sys/block/nullb1/stat)"

	# Print rounded to the nearest second
	printf 'read %d s\n' $(((read_ms - init_read_ms + 500) / 1000))
	printf 'write %d s\n' $(((write_ms - init_write_ms + 500) / 1000))
}

test() {
	local init_read_ms init_write_ms read_ms write_ms

	echo "Running ${TEST_NAME}"

	if ! _configure_null_blk nullb1 irqmode=2 completion_nsec=1000000000 \
			power=1; then
		return 1
	fi

	init_times
	show_times

	dd if=/dev/nullb1 of=/dev/null bs=4096 iflag=direct count=1 status=none
	show_times

	dd if=/dev/zero of=/dev/nullb1 bs=4096 oflag=direct count=1 status=none
	show_times

	dd if=/dev/nullb1 of=/dev/null bs=4096 iflag=direct count=1 status=none &
	dd if=/dev/zero of=/dev/nullb1 bs=4096 oflag=direct count=1 status=none &
	dd if=/dev/zero of=/dev/nullb1 bs=4096 oflag=direct count=1 status=none &
	wait
	show_times

	_exit_null_blk

	unset init_read_ms init_write_ms read_ms write_ms

	echo "Test complete"
}
