# SPDX-License-Identifier: GPL-2.0
#!/bin/bash

export QCOW2_IMG_SZ=2G

_create_qcow2_null_image() {
	local type=$1
	local size=$2
	local my_file=`mktemp -p ${UBLK_TMP_DIR}  ublk_${type}_${size}_XXXXX.qcow2`
	qemu-img create -f qcow2 $my_file $size  > /dev/null 2>&1
	echo $my_file
}

_qcow2_image_alloc_data() {
	local my_dev=`__create_nbd_dev "$1"`
	local my_size=`blockdev --getsz $my_dev`
	local my_count=`expr ${my_size} / 2048`

	dd if=/dev/zero of=$my_dev bs=1M count=${my_count} oflag=direct > /dev/null 2>&1
	__remove_nbd_dev $my_dev
}

_create_qcow2_image() {
	local type=$1
	local size=$2

	local file=`_create_qcow2_null_image $type $size`
	if [ "$type" == "data" ]; then
		local nbd_params="-c /dev/nbd11 -n --aio=native $file"
		_qcow2_image_alloc_data "$nbd_params"
	fi
	echo $file
}

_check_qcow2_image() {
	local my_file=$1
	qemu-img check $my_file > ${UBLK_TMP} 2>&1
	[ $? -ne 0 ] && echo "qcow2 image $my_file is broken" && cat ${UBLK_TMP} && exit
}

_remove_qcow2_image() {
	local file=$1

	if [ -f "$file" ]; then
		_check_qcow2_image $file
		rm -f $file
	fi
}


__remove_nbd_dev() {
	local DEV=$1
	sync $DEV
	qemu-nbd -d $DEV  > /dev/null 2>&1
}

__create_nbd_dev() {
	local nbd_params="$1"
	local DEV=`echo ${nbd_params} | awk '{ for(i=1; i<=NF; ++i) if (substr($i, 1, 8) == "/dev/nbd") printf $i}'`
	modprobe nbd > /dev/null 2>&1
	qemu-nbd -d $DEV > /dev/null 2>&1
	eval qemu-nbd ${nbd_params} > /dev/null 2>&1
	echo "$DEV"
}

__run_nbd_dev_perf()
{
	local JOBS=$1
	local DEV=`__create_nbd_dev "${T_TYPE_PARAMS}"`

	echo -e "\t$T_TYPE $T_TYPE_PARAMS, fio($DEV, libaio, dio, io jobs $JOB)..."
	__run_dev_perf_no_create "nbd" $JOBS $DEV

	__remove_nbd_dev $DEV
}
