#
# Common zoned block device specific functions
#

#
# blkzone report added zone capacity to be printed from v2.37.
# This filter will add an extra column 'cap' with the same value of
# 'len'(zone size) for blkzone version < 2.37
#
# Before: start: 0x000100000, len 0x040000, wptr 0x000000 ..
# After: start: 0x000100000, len 0x040000, cap 0x040000, wptr 0x000000 ..
_filter_blkzone_report()
{
	$AWK_PROG -F "," 'BEGIN{OFS=",";} $3 !~ /cap/ {$2=$2","$2;} {print;}' |\
	sed -e 's/len/cap/2'
}

_require_limited_active_zones() {
    local dev=$1
    local sysfs=$(_sysfs_dev ${dev})
    local attr="${sysfs}/queue/max_active_zones"

    [ -e "${attr}" ] || _notrun "cannot find queue/max_active_zones. Maybe non-zoned device?"
    if [ $(cat "${attr}") == 0 ]; then
	_notrun "this test requires limited active zones"
    fi
}

_zone_capacity() {
    local phy=$1
    local dev=$2

    [ -z "$dev" ] && dev=$SCRATCH_DEV

    size=$($BLKZONE_PROG report -o $phy -l 1 $dev |\
	       _filter_blkzone_report |\
	       grep -Po "cap 0x[[:xdigit:]]+" | cut -d ' ' -f 2)
    echo $((size << 9))
}

_require_zloop()
{
    modprobe zloop >/dev/null 2>&1
    if [ ! -c "/dev/zloop-control" ]; then
	    _notrun "This test requires zoned loopback device support"
    fi
}

_find_next_zloop()
{
    local id=0

    while true; do
        if [[ ! -b "/dev/zloop$id" ]]; then
            break
        fi
        id=$((id + 1))
    done

    echo "$id"
}

# Create a zloop device
# usage: _create_zloop <base_dir> <zone_size> <nr_conv_zones>
_create_zloop()
{
    local id="$(_find_next_zloop)"

    if [ -n "$1" ]; then
        local zloop_base="$1"
    else
        local zloop_base="/var/local/zloop"
    fi

    if [ -n "$2" ]; then
        local zone_size=",zone_size_mb=$2"
    fi

    if [ -n "$3" ]; then
        local conv_zones=",conv_zones=$3"
    fi

    mkdir -p "$zloop_base/$id"

    local zloop_args="add id=$id,base_dir=$zloop_base$zone_size$conv_zones"

    echo "$zloop_args" > /dev/zloop-control || \
        _fail "cannot create zloop device"

    echo "/dev/zloop$id"
}

_destroy_zloop() {
    local zloop="$1"

    test -b "$zloop" || return
    local id=$(echo $zloop | grep -oE '[0-9]+$')

    echo "remove id=$id" > /dev/zloop-control
}
