#!/bin/bash
# SPDX-License-Identifier: GPL-3.0+
# Copyright (C) 2017 Omar Sandoval
#
# null_blk helper functions.

_have_null_blk() {
	_have_modules null_blk
}

_remove_null_blk_devices() {
	if [[ -d /sys/kernel/config/nullb ]]; then
		find /sys/kernel/config/nullb -mindepth 1 -maxdepth 1 \
		     -type d -delete
	fi
}

_init_null_blk() {
	_remove_null_blk_devices

	local zoned=""
	if (( RUN_FOR_ZONED )); then zoned="zoned=1"; fi

	if ! modprobe -r null_blk || ! modprobe null_blk "$@" "${zoned}" ; then
		return 1
	fi

	udevadm settle
	return 0
}

# Configure one null_blk instance with name $1 and parameters $2..${$#}.
_configure_null_blk() {
	local nullb=/sys/kernel/config/nullb/$1 param val

	shift
	mkdir "$nullb" || return $?
	while [[ $# -gt 0 ]]; do
		param="${1%%=*}"
		val="${1#*=}"
		shift
		echo "$val" > "$nullb/$param" || return $?
	done
}

_exit_null_blk() {
	_remove_null_blk_devices
	udevadm settle
	modprobe -r null_blk
}
