# -------------------------------------------------------------------
# Authenticator helper functions.
# -------------------------------------------------------------------

# write 32-bit data word to authenticator data input
proc authenticator_write {WDATA} {
  riscv authdata_write $WDATA
}

# read 32-bit data word from authenticator data output
proc authenticator_read {} {
  return [riscv authdata_read]
}

# check if authentication was successful (bit 7 in dmstatus)
proc authenticator_check {} {
  set DMSTATUS [riscv dmi_read 0x11]
  if { [expr {$DMSTATUS & (1<<7)}] } {
    echo "Authentication passed."
  } else {
    echo "AUTHENTICATION FAILED!"
    exit
  }
}

# ---------------------------------------------------------
# Authentication process.
# Adjust this for your custom/non-default authenticator.
# ---------------------------------------------------------
# read challenge
set CHALLENGE [authenticator_read]
# compute response (default authenticator module)
set RESPONSE [expr {$CHALLENGE | 1}]
# send response
authenticator_write $RESPONSE
# success?
authenticator_check
