#!/bin/sh
#
# $NetBSD: smtoff,v 1.6 2020/09/08 12:52:18 martin Exp $
#
# Public Domain.
#

# PROVIDE: smtoff
# REQUIRE: root bootconf CRITLOCALMOUNTED 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() {
       cpuctl identify "$1" |
       while read cpuN smt id N junk
       do
               test -n "$junk" && continue

               case "${smt} ${id}" in
               'SMT ID')
                       case "$N" in
                       [0-9]|[1-9][0-9]|[1-9][0-9]*[0-9])
                               printf %s "$N"
                               return
                               ;;
                       esac
                       ;;
               esac
       done
}

CountCPUs() {
       sysctl -n hw.ncpu
}

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

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

       while [ "$i" -lt "$ncpus" ]
       do
               smtid=$(GetSmtId "$i" 2>/dev/null)

               case "$smtid" in
               '')                     # Didn't get the ID? Then maybe no SMT.
                       ;;

               0)                      # The first thread is never disabled.
                       ;;

               *)
                       cpuctl offline "$i"
                       ;;
               esac

               i=$(($i+1))
       done
}

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

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

load_rc_config $name
run_rc_command "$1"