#!/bin/sh
#
# $NetBSD: smtoff,v 1.1 2019/05/11 19:31:03 maxv Exp $
#
# Public Domain.
#

# PROVIDE: smtoff
# REQUIRE: root bootconf mountcritlocal tty

$_rc_subr_loaded . /etc/rc.subr

name="smtoff"
rcvar=$name

start_cmd="smtoff_start"
stop_cmd="smtoff_stop"

# ------------------------------------------------------------------------------

#
# The format of the output is:
#
#     ...
#     cpu0: SMT ID 1
#     ...
#
# Return the value.
#
GetSmtId() {
	smtid=$(cpuctl identify $1 | grep "SMT ID" | cut -d " " -f 4)
	case $smtid in
		[0-9]*)
			echo "$smtid" ;;
		*)
			echo "error" ;;
	esac
}

#
# The format of the output is:
#
#     hw.ncpu = 80
#
# Return the value.
#
CountCPUs() {
	ncpus=$(sysctl hw.ncpu | cut -d " " -f 3)
	echo "$ncpus"
}

# ------------------------------------------------------------------------------

#
# Disable SMT. We skip cpu0.
#
smtoff_start()
{
	ncpus=$(CountCPUs)
	i=1

	while [ $i -lt $ncpus ]
	do
		smtid=$(GetSmtId "$i")

		# Didn't get the ID? Then maybe no SMT.
		if [ "$smtid" = "error" ]; then
			i=$(($i+1))
			continue
		fi

		# The first thread is never disabled.
		if [ $smtid -eq 0 ]; then
			i=$(($i+1))
			continue
		fi

		cmd="cpuctl offline $i"
		$cmd
		i=$(($i+1))
	done
}

#
# Enable SMT. We basically turn on each CPU.
#
smtoff_stop()
{
	ncpus=$(CountCPUs)
	i=1

	while [ $i -lt $ncpus ]
	do
		cmd="cpuctl online $i"
		$cmd
		i=$(($i+1))
	done
}

load_rc_config $name
run_rc_command "$1"
