retrofit the kernel and loader to handle resume

and now the even harder debuggening begins...zomg o_O
This commit is contained in:
bunnie 2021-04-30 01:55:38 +08:00
parent 2d3a643d20
commit 0e2d57c9fb
17 changed files with 435 additions and 471 deletions

View file

@ -17,12 +17,12 @@ pub fn current_pid() -> PID {
PID::new(satp::read().asid() as _).unwrap()
}
pub fn init() {
pub fn init(resume: bool) {
unsafe {
sie::set_ssoft();
sie::set_sext();
}
rand::init();
rand::init(resume);
}
/// Put the core to sleep until an interrupt hits. Returns `true`

View file

@ -7,15 +7,15 @@ use xous_kernel::{MemoryFlags, MemoryType, PID};
pub const TRNG_KERNEL: Trng = Trng {
// the HW device mapping is done in xous-rs/src/lib.rs/init()
// the manually chosen virtuall address has to be in the top 4MiB as it is the only page shared among all processes
base: 0xffce_0000 as *mut usize,
// the manually chosen virtual address has to be in the top 4MiB as it is the only page shared among all processes
base: 0xffce_0000 as *mut usize, // see https://github.com/betrusted-io/xous-core/blob/master/docs/memory.md
};
pub struct Trng {
pub base: *mut usize,
}
pub fn init() {
pub fn init(resume: bool) {
// Map the TRNG so that we can allocate names
// hardware guarantees that:
// - TRNG will automatically power on
@ -23,18 +23,20 @@ pub fn init() {
// - Kernel FIFO will fill with TRNGs such that at least the next 512 calls to get_u32() will succeed without delay
// - The kernel will start a TRNG server
// - All further security decisions and policies are 100% delegated to this new server.
MemoryManager::with_mut(|memory_manager| {
memory_manager
.map_range(
utra::trng_kernel::HW_TRNG_KERNEL_BASE as *mut u8,
((TRNG_KERNEL.base as u32) & !4095) as *mut u8,
4096,
PID::new(1).unwrap(),
MemoryFlags::R | MemoryFlags::W,
MemoryType::Default,
)
.expect("unable to map TRNG")
});
if !resume {
MemoryManager::with_mut(|memory_manager| {
memory_manager
.map_range(
utra::trng_kernel::HW_TRNG_KERNEL_BASE as *mut u8,
((TRNG_KERNEL.base as u32) & !4095) as *mut u8,
4096,
PID::new(1).unwrap(),
MemoryFlags::R | MemoryFlags::W,
MemoryType::Default,
)
.expect("unable to map TRNG")
});
}
let trng_kernel_csr = CSR::new(TRNG_KERNEL.base as *mut u32);
while trng_kernel_csr.rf(utra::trng_kernel::STATUS_AVAIL) == 0 {}

View file

@ -27,7 +27,7 @@ pub fn current_pid() -> PID {
unimplemented!();
}
pub fn init() {}
pub fn init(resume: bool) {}
pub mod syscall {
use crate::arch::Context;

View file

@ -14,7 +14,7 @@ use utralib::generated::*;
))]
pub mod debug_print_hardware {
// the HW device mapping is done in main.rs/init(); the virtual address has to be in the top 4MiB as it is the only page shared among all processes
pub const SUPERVISOR_UART_ADDR: *mut usize = 0xffcf_0000 as *mut usize;
pub const SUPERVISOR_UART_ADDR: *mut usize = 0xffcf_0000 as *mut usize; // see https://github.com/betrusted-io/xous-core/blob/master/docs/memory.md
#[macro_export]
macro_rules! print

View file

@ -39,61 +39,110 @@ fn handle_panic(_arg: &PanicInfo) -> ! {
}
}
use utralib::generated::*;
pub const RESUME_KICKER: ResumeKicker = ResumeKicker {
// the manually chosen virtual address has to be in the top 4MiB as it is the only page shared among all processes
base: 0xffcd_0000 as *mut usize, // see https://github.com/betrusted-io/xous-core/blob/master/docs/memory.md
};
pub struct ResumeKicker {
pub base: *mut usize,
}
#[cfg(baremetal)]
#[no_mangle]
/// This function is called from baremetal startup code to initialize various kernel structures
/// based on arguments passed by the bootloader. It is unused when running under an operating system.
pub extern "C" fn init(arg_offset: *const u32, init_offset: *const u32, rpt_offset: *mut u32) {
unsafe { args::KernelArguments::init(arg_offset) };
let args = args::KernelArguments::get();
// Everything needs memory, so the first thing we should do is initialize the memory manager.
crate::mem::MemoryManager::with_mut(|mm| {
mm.init_from_memory(rpt_offset, &args)
.expect("couldn't initialize memory manager")
});
SystemServices::with_mut(|system_services| {
system_services.init_from_memory(init_offset, &args)
});
pub extern "C" fn init(arg_offset: *const u32, init_offset: *const u32, rpt_offset: *mut u32, resume: bool) {
if !resume {
unsafe { args::KernelArguments::init(arg_offset) };
let args = args::KernelArguments::get();
// Everything needs memory, so the first thing we should do is initialize the memory manager.
crate::mem::MemoryManager::with_mut(|mm| {
mm.init_from_memory(rpt_offset, &args)
.expect("couldn't initialize memory manager")
});
SystemServices::with_mut(|system_services| {
system_services.init_from_memory(init_offset, &args)
});
}
// Now that the memory manager is set up, perform any arch-specific initializations.
arch::init();
// each sub-call will handle things differently depending on the resume state
arch::init(resume);
// Either map memory using a syscall, or if we're debugging the syscall
// handler then directly map it.
#[cfg(any(feature = "debug-print", feature = "print-panics"))]
{
use utralib::generated::*;
// Map the serial port so println!() works as expected.
if !resume {
// Map the serial port so println!() works as expected.
mem::MemoryManager::with_mut(|memory_manager| {
memory_manager
.map_range(
utra::uart::HW_UART_BASE as *mut u8,
((debug::SUPERVISOR_UART_ADDR as u32) & !4095) as *mut u8,
4096,
PID::new(1).unwrap(),
MemoryFlags::R | MemoryFlags::W,
MemoryType::Default,
)
.expect("unable to map serial port")
});
debug::Uart{}.init();
println!("KMAIN (clean boot): Supervisor mode started...");
println!("Claiming IRQ {} via syscall...", utra::uart::UART_IRQ);
xous_kernel::claim_interrupt(utra::uart::UART_IRQ, debug::irq, 0 as *mut usize)
.expect("Couldn't claim debug interrupt");
print!("}} ");
} else {
println!("KMAIN (resume): Loader is instructing us to resume...");
}
if !resume {
// Print the processed kernel arguments
let args = args::KernelArguments::get();
println!("Kernel arguments:");
for arg in args.iter() {
println!(" {}", arg);
}
}
}
if !resume {
// map in the resume kicker to its fixed virtual address for the next time we start with a resume
mem::MemoryManager::with_mut(|memory_manager| {
memory_manager
.map_range(
utra::uart::HW_UART_BASE as *mut u8,
((debug::SUPERVISOR_UART_ADDR as u32) & !4095) as *mut u8,
utra::resumekicker::HW_RESUMEKICKER_BASE as *mut u8,
((RESUME_KICKER.base as u32) & !4095) as *mut u8,
4096,
PID::new(1).unwrap(),
MemoryFlags::R | MemoryFlags::W,
MemoryType::Default,
)
.expect("unable to map serial port")
.expect("unable to map resume kicker for future resume use")
});
debug::Uart{}.init();
println!("KMAIN: Supervisor mode started...");
println!("Claiming IRQ {} via syscall...", utra::uart::UART_IRQ);
xous_kernel::claim_interrupt(utra::uart::UART_IRQ, debug::irq, 0 as *mut usize)
.expect("Couldn't claim debug interrupt");
print!("}} ");
// Print the processed kernel arguments
let args = args::KernelArguments::get();
println!("Kernel arguments:");
for arg in args.iter() {
println!(" {}", arg);
}
}
// pump the random number generator to test it
for _ in 0..100 {
arch::rand::get_u32();
// rand::init() already clears the initial pipe, but pump the TRNG a little more out of no other reason than sheer paranoia
arch::rand::get_u32();
arch::rand::get_u32();
if resume {
// this will reload the SIM from its backing store in RAM
crate::arch::irq::enable_all_irqs();
// we should already have our page mapped from a prior boot
let mut resumekicker = CSR::new(RESUME_KICKER.base as *mut u32);
// this should trigger a pending interrupt immediately
// note that the resumekicker's "kick" signal is a wire-OR into the susres SOFT_INT bit
// and that the loader will have set EV_ENABLE on this before handing control to the kernel
resumekicker.wfo(utra::resumekicker::KICKER_KICK, 1);
// when the handler returns to this closing curly brace,
// the control flow returns to the asm.S loader
// and the very next immediate thing it does is jump to kmain() and schedule the next PID to run!
}
}

View file

@ -15,8 +15,8 @@ rand = "0.7.3"
[features]
debug-print = []
earlyprintk = []
#default = ["debug-print"]
default = []
default = ["debug-print"]
#default = []
[profile.release]
codegen-units = 1 # 1 better optimizations

View file

@ -50,5 +50,8 @@ start_kernel:
// Reposition the stack at the offset passed by $a5
move sp, a5
// copy the clean suspend marker to the fourth argument slot (a3)
move a3, a7
// Issue the return, which will jump to $mepc in Supervisor mode
mret

View file

@ -389,6 +389,7 @@ extern "C" {
entrypoint: usize,
stack: usize,
debug: bool,
resume: bool,
) -> !;
}
@ -1076,8 +1077,10 @@ fn boot_sequence(args: KernelArguments, _signature: u32) -> ! {
let (clean, was_forced_suspend) = check_resume(&mut cfg);
if !clean {
println!("no suspend marker found, doing a cold boot!");
phase_1(&mut cfg);
phase_2(&mut cfg);
println!("done initializing for cold boot.");
} else {
use utralib::generated::*;
// setup for a resume
@ -1092,10 +1095,8 @@ fn boot_sequence(args: KernelArguments, _signature: u32) -> ! {
resume_csr.wfo(utra::susres::STATE_RESUME, 1);
}
resume_csr.wfo(utra::susres::CONTROL_PAUSE, 1); // ensure that the ticktimer is paused before resuming
// set the resume marker for the early kernel init
///////////TODO
resume_csr.wfo(utra::susres::EV_ENABLE_SOFT_INT, 1); // ensure that the soft interrupt is enabled for the kernel to kick
println!("clean suspend marker found, doing a resume!");
// SATP restore is handled by the `start_kernel` assembly pre-amble
}
@ -1130,6 +1131,7 @@ fn boot_sequence(args: KernelArguments, _signature: u32) -> ! {
cfg.processes[0].entrypoint,
cfg.processes[0].sp,
cfg.debug,
clean,
);
}
}

View file

@ -139,14 +139,6 @@ pub(crate) const SERVER_NAME_LLIO: &str = "_Low Level I/O manager_";
//////////////////////////////////// OPCODES
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum Opcode {
/// not tested - reboot
RebootRequest,
RebootSocConfirm, // all peripherals + CPU
RebootCpuConfirm, // just the CPU, peripherals (in particular the USB debug bridge) keep state
/// not tested - reboot address
RebootVector, //(u32),
/// not tested - set CRG parameters
CrgMode, //(ClockMode),

View file

@ -31,7 +31,6 @@ mod implementation {
#[allow(dead_code)]
pub struct Llio {
reboot_csr: utralib::CSR<u32>,
crg_csr: utralib::CSR<u32>,
gpio_csr: utralib::CSR<u32>,
gpio_susres: RegManager::<{utra::gpio::GPIO_NUMREGS}>,
@ -127,13 +126,6 @@ mod implementation {
pub fn get_i2c_base(&self) -> *mut u32 { self.i2c_csr.base }
pub fn new(handler_conn: xous::CID, gpio_base: *mut u32) -> Llio {
let reboot_csr = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::reboot::HW_REBOOT_BASE),
None,
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map Reboot CSR range");
let crg_csr = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::crg::HW_CRG_BASE),
None,
@ -187,7 +179,6 @@ mod implementation {
let ticktimer = ticktimer_server::Ticktimer::new().expect("Couldn't connect to Ticktimer");
let mut xl = Llio {
reboot_csr: CSR::new(reboot_csr.as_mut_ptr() as *mut u32),
crg_csr: CSR::new(crg_csr.as_mut_ptr() as *mut u32),
gpio_csr: CSR::new(gpio_base),
gpio_susres: RegManager::new(gpio_base),
@ -289,16 +280,6 @@ mod implementation {
self.i2c_susres.resume();
}
pub fn reboot(&mut self, reboot_soc: bool) {
if reboot_soc {
self.reboot_csr.wfo(utra::reboot::SOC_RESET_SOC_RESET, 0xAC);
} else {
self.reboot_csr.wfo(utra::reboot::CPU_RESET_CPU_RESET, 1);
}
}
pub fn set_reboot_vector(&mut self, vector: u32) {
self.reboot_csr.wfo(utra::reboot::ADDR_ADDR, vector);
}
pub fn gpio_dout(&mut self, d: u32) {
self.gpio_csr.wfo(utra::gpio::OUTPUT_OUTPUT, d);
}
@ -484,8 +465,6 @@ mod implementation {
pub fn suspend(&self) {}
pub fn resume(&self) {}
pub fn reboot(&self, _reboot_soc: bool) {}
pub fn set_reboot_vector(&self, _vector: u32) {}
pub fn gpio_dout(&self, _d: u32) {}
pub fn gpio_din(&self, ) -> u32 { 0xDEAD_BEEF }
pub fn gpio_drive(&self, _d: u32) {}
@ -588,220 +567,195 @@ fn xmain() -> ! {
let mut gpio_cb_conns: [Option<ScalarCallback>; 32] = [None; 32];
log::trace!("starting main loop");
let mut reboot_requested: bool = false;
loop {
let mut msg = xous::receive_message(llio_sid).unwrap();
log::trace!("Message: {:?}", msg);
if reboot_requested {
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::RebootCpuConfirm) => {
llio.reboot(false);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
llio.suspend();
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
llio.resume();
}),
Some(Opcode::CrgMode) => msg_scalar_unpack!(msg, _mode, _, _, _, {
todo!("CrgMode opcode not yet implemented.");
}),
Some(Opcode::GpioDataOut) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_dout(d as u32);
}),
Some(Opcode::GpioDataIn) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.gpio_din() as usize).expect("couldn't return gpio data in");
}),
Some(Opcode::GpioDataDrive) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_drive(d as u32);
}),
Some(Opcode::GpioIntMask) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_int_mask(d as u32);
}),
Some(Opcode::GpioIntAsFalling) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_int_as_falling(d as u32);
}),
Some(Opcode::GpioIntPending) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.gpio_int_pending() as usize).expect("couldn't return gpio pending vector");
}),
Some(Opcode::GpioIntEna) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_int_ena(d as u32);
}),
Some(Opcode::UartMux) => msg_scalar_unpack!(msg, mux, _, _, _, {
llio.set_uart_mux(mux.into());
}),
Some(Opcode::InfoDna) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (val1, val2) = llio.get_info_dna();
xous::return_scalar2(msg.sender, val1, val2).expect("couldn't return DNA");
}),
Some(Opcode::InfoGit) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (val1, val2) = llio.get_info_git();
xous::return_scalar2(msg.sender, val1, val2).expect("couldn't return Git");
}),
Some(Opcode::InfoPlatform) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (val1, val2) = llio.get_info_platform();
xous::return_scalar2(msg.sender, val1, val2).expect("couldn't return Platform");
}),
Some(Opcode::InfoTarget) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (val1, val2) = llio.get_info_target();
xous::return_scalar2(msg.sender, val1, val2).expect("couldn't return Target");
}),
Some(Opcode::PowerAudio) => msg_scalar_unpack!(msg, power_on, _, _, _, {
if power_on == 0 {
llio.power_audio(false);
} else {
llio.power_audio(true);
}
Some(Opcode::RebootSocConfirm) => {
llio.reboot(true);
}),
Some(Opcode::PowerSelf) => msg_scalar_unpack!(msg, power_on, _, _, _, {
if power_on == 0 {
llio.power_self(false);
} else {
llio.power_self(true);
}
_ => reboot_requested = false,
}),
Some(Opcode::PowerBoostMode) => msg_scalar_unpack!(msg, power_on, _, _, _, {
if power_on == 0 {
llio.power_boost_mode(false);
} else {
llio.power_boost_mode(true);
}
}),
Some(Opcode::EcSnoopAllow) => msg_scalar_unpack!(msg, power_on, _, _, _, {
if power_on == 0 {
llio.ec_snoop_allow(false);
} else {
llio.ec_snoop_allow(true);
}
}),
Some(Opcode::EcReset) => msg_scalar_unpack!(msg, _, _, _, _, {
llio.ec_reset();
}),
Some(Opcode::EcPowerOn) => msg_scalar_unpack!(msg, _, _, _, _, {
llio.ec_power_on();
}),
Some(Opcode::SelfDestruct) => msg_scalar_unpack!(msg, code, _, _, _, {
llio.self_destruct(code as u32);
}),
Some(Opcode::Vibe) => msg_scalar_unpack!(msg, pattern, _, _, _, {
llio.vibe(pattern.into());
}),
Some(Opcode::AdcVbus) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_vbus() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcVccInt) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_vccint() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcVccAux) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_vccaux() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcVccBram) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_vccbram() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcUsbN) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_usbn() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcUsbP) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_usbp() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcTemperature) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_temperature() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcGpio5) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_gpio5() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcGpio2) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_gpio2() as _).expect("couldn't return Xadc");
}),
Some(Opcode::IrqI2cTxrxDone) => msg_scalar_unpack!(msg, _, _, _, _, {
// I2C state machine handler irq received
i2c_machine.handler();
}),
Some(Opcode::I2cTxRx) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let i2c_txrx = buffer.to_original::<llio::api::I2cTransaction, _>().unwrap();
let status = i2c_machine.initiate(i2c_txrx);
buffer.replace(status).unwrap();
}
} else {
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::SuspendResume) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
llio.suspend();
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
llio.resume();
}),
Some(Opcode::RebootRequest) => {
reboot_requested = true;
},
Some(Opcode::RebootCpuConfirm) => {
info!("RebootCpuConfirm, but no prior Request. Ignoring.");
},
Some(Opcode::RebootSocConfirm) => {
info!("RebootSocConfirm, but no prior Request. Ignoring.");
},
Some(Opcode::RebootVector) => msg_scalar_unpack!(msg, vector, _, _, _, {
llio.set_reboot_vector(vector as u32);
}),
Some(Opcode::CrgMode) => msg_scalar_unpack!(msg, _mode, _, _, _, {
todo!("CrgMode opcode not yet implemented.");
}),
Some(Opcode::GpioDataOut) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_dout(d as u32);
}),
Some(Opcode::GpioDataIn) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.gpio_din() as usize).expect("couldn't return gpio data in");
}),
Some(Opcode::GpioDataDrive) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_drive(d as u32);
}),
Some(Opcode::GpioIntMask) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_int_mask(d as u32);
}),
Some(Opcode::GpioIntAsFalling) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_int_as_falling(d as u32);
}),
Some(Opcode::GpioIntPending) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.gpio_int_pending() as usize).expect("couldn't return gpio pending vector");
}),
Some(Opcode::GpioIntEna) => msg_scalar_unpack!(msg, d, _, _, _, {
llio.gpio_int_ena(d as u32);
}),
Some(Opcode::UartMux) => msg_scalar_unpack!(msg, mux, _, _, _, {
llio.set_uart_mux(mux.into());
}),
Some(Opcode::InfoDna) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (val1, val2) = llio.get_info_dna();
xous::return_scalar2(msg.sender, val1, val2).expect("couldn't return DNA");
}),
Some(Opcode::InfoGit) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (val1, val2) = llio.get_info_git();
xous::return_scalar2(msg.sender, val1, val2).expect("couldn't return Git");
}),
Some(Opcode::InfoPlatform) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (val1, val2) = llio.get_info_platform();
xous::return_scalar2(msg.sender, val1, val2).expect("couldn't return Platform");
}),
Some(Opcode::InfoTarget) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let (val1, val2) = llio.get_info_target();
xous::return_scalar2(msg.sender, val1, val2).expect("couldn't return Target");
}),
Some(Opcode::PowerAudio) => msg_scalar_unpack!(msg, power_on, _, _, _, {
if power_on == 0 {
llio.power_audio(false);
} else {
llio.power_audio(true);
}
}),
Some(Opcode::PowerSelf) => msg_scalar_unpack!(msg, power_on, _, _, _, {
if power_on == 0 {
llio.power_self(false);
} else {
llio.power_self(true);
}
}),
Some(Opcode::PowerBoostMode) => msg_scalar_unpack!(msg, power_on, _, _, _, {
if power_on == 0 {
llio.power_boost_mode(false);
} else {
llio.power_boost_mode(true);
}
}),
Some(Opcode::EcSnoopAllow) => msg_scalar_unpack!(msg, power_on, _, _, _, {
if power_on == 0 {
llio.ec_snoop_allow(false);
} else {
llio.ec_snoop_allow(true);
}
}),
Some(Opcode::EcReset) => msg_scalar_unpack!(msg, _, _, _, _, {
llio.ec_reset();
}),
Some(Opcode::EcPowerOn) => msg_scalar_unpack!(msg, _, _, _, _, {
llio.ec_power_on();
}),
Some(Opcode::SelfDestruct) => msg_scalar_unpack!(msg, code, _, _, _, {
llio.self_destruct(code as u32);
}),
Some(Opcode::Vibe) => msg_scalar_unpack!(msg, pattern, _, _, _, {
llio.vibe(pattern.into());
}),
Some(Opcode::AdcVbus) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_vbus() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcVccInt) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_vccint() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcVccAux) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_vccaux() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcVccBram) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_vccbram() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcUsbN) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_usbn() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcUsbP) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_usbp() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcTemperature) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_temperature() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcGpio5) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_gpio5() as _).expect("couldn't return Xadc");
}),
Some(Opcode::AdcGpio2) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
xous::return_scalar(msg.sender, llio.xadc_gpio2() as _).expect("couldn't return Xadc");
}),
Some(Opcode::IrqI2cTxrxDone) => msg_scalar_unpack!(msg, _, _, _, _, {
// I2C state machine handler irq received
i2c_machine.handler();
}),
Some(Opcode::I2cTxRx) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let i2c_txrx = buffer.to_original::<llio::api::I2cTransaction, _>().unwrap();
let status = i2c_machine.initiate(i2c_txrx);
buffer.replace(status).unwrap();
Some(Opcode::I2cIsBusy) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let busy = if i2c_machine.is_busy() {1} else {0};
xous::return_scalar(msg.sender, busy as _).expect("couldn't return I2cIsBusy");
}),
Some(Opcode::EventUsbAttachSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut usb_cb_conns);
}
Some(Opcode::EventComSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut com_cb_conns);
}
Some(Opcode::EventRtcSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut rtc_cb_conns);
}
Some(Opcode::GpioIntSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut gpio_cb_conns);
}
Some(Opcode::EventComEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.com_int_ena(false);
} else {
llio.com_int_ena(true);
}
Some(Opcode::I2cIsBusy) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let busy = if i2c_machine.is_busy() {1} else {0};
xous::return_scalar(msg.sender, busy as _).expect("couldn't return I2cIsBusy");
}),
Some(Opcode::EventUsbAttachSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut usb_cb_conns);
}),
Some(Opcode::EventRtcEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.rtc_int_ena(false);
} else {
llio.rtc_int_ena(true);
}
Some(Opcode::EventComSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut com_cb_conns);
}
Some(Opcode::EventRtcSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut rtc_cb_conns);
}
Some(Opcode::GpioIntSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut gpio_cb_conns);
}
Some(Opcode::EventComEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.com_int_ena(false);
} else {
llio.com_int_ena(true);
}
}),
Some(Opcode::EventRtcEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.rtc_int_ena(false);
} else {
llio.rtc_int_ena(true);
}
}),
Some(Opcode::EventUsbAttachEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.usb_int_ena(false);
} else {
llio.usb_int_ena(true);
}
}),
Some(Opcode::EventComHappened) => {
send_event(&com_cb_conns, 0);
},
Some(Opcode::EventRtcHappened) => {
send_event(&rtc_cb_conns, 0);
},
Some(Opcode::EventUsbHappened) => {
send_event(&usb_cb_conns, 0);
},
Some(Opcode::GpioIntHappened) => msg_scalar_unpack!(msg, channel, _, _, _, {
send_event(&gpio_cb_conns, channel as usize);
}),
None => {
error!("couldn't convert opcode");
break;
}),
Some(Opcode::EventUsbAttachEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.usb_int_ena(false);
} else {
llio.usb_int_ena(true);
}
}),
Some(Opcode::EventComHappened) => {
send_event(&com_cb_conns, 0);
},
Some(Opcode::EventRtcHappened) => {
send_event(&rtc_cb_conns, 0);
},
Some(Opcode::EventUsbHappened) => {
send_event(&usb_cb_conns, 0);
},
Some(Opcode::GpioIntHappened) => msg_scalar_unpack!(msg, channel, _, _, _, {
send_event(&gpio_cb_conns, channel as usize);
}),
None => {
error!("couldn't convert opcode");
break;
}
}
}

View file

@ -19,6 +19,14 @@ pub(crate) enum Opcode {
/// from the timeout thread
SuspendTimeout,
/// not tested - reboot
RebootRequest,
RebootSocConfirm, // all peripherals + CPU
RebootCpuConfirm, // just the CPU, peripherals (in particular the USB debug bridge) keep state
/// not tested - reboot address
RebootVector, //(u32),
/// exit the server
Quit,
}
@ -206,106 +214,3 @@ impl<const N: usize> SuspendResume for ManagedMem<N> {
}
}
}
/*
// "suspend/resume u32"
struct SrU32 {
/// offset of the register
offset: crate::Register,
/// the saved value of the register
value: u32,
/// the order in which this register should be written. If none, it's written at any convenient time.
resume_order: Option<u8>,
/// if this register should be in the suspend/resume set
do_sr: bool,
}
/* sketching some structs for suspend/resume */
struct TicktimerSusres {
csr: utralib::CSR<u32>, // new(csr_base) will allocate this register, from the virtual CSR base given to us by the owning server
pub control: Option<u32>,
pub time1: Option<u32>,
pub time0: Option<u32>,
pub resume_time1: Option<u32>,
pub resume_time0: Option<u32>,
pub status: Option<u32>,
pub msleep_target1: Option<u32>,
pub msleep_target0: Option<u32>,
pub ev_status: Option<u32>,
pub ev_pending: Option<u32>,
pub ev_enable: Option<u32>,
pub ticktimer_irq: Option<bool>, // whether to enable or not after resume
pub wait_suspend: Option<fn(timeout: u32) -> bool>, // function to call to check if a block can suspend
}
pub trait SuspendResume {
pub fn suspend(&mut self) {
/*
go through each item of the structure, and if the item is Some(item), access the corresponding
register and save it into the register
*/
}
pub fn resume(&mut self) {
/*
go through each item of the stucture, and if the item is Some(item), unwrap the value and
poke it into the register
*/
}
}
enum TickttimerReg {
Control = 0,
Time1 = 1,
Time0 = 2,
MSleepTarget1 = 3,
//...
}
//enum TickttimerInterrupt {
// Alarm = 0,
//}
struct ManagedReg {
offset: TickttimerReg,
mask: usize, // mask of data to store
value: u32,
}
//struct ManagedInterrupt {
// irq: usize,
//}
struct ManagedMem {
offset: usize, // the starting offset of the volatile memory block
mem: [u32; MEMLEN], // backup copy of the memory
}
// this can operate on the above three structure
pub trait SusResOps {
fn save();
fn restore();
}
/*
Interrupts need no suspend/resume setup:
- the hooks and callback locations are all stored in non-volatile SRAM
- the SIM register, which contains the mask of interrupts that are enabled, will be restored
by the loader on boot
Between these two facts, all of the interrupt mechanism are transparently handled by the kernel
*/
struct SusResManager {
csr: utralib::CSR<u32>,
pub registers: [Option<ManagedReg>; 12], // max number is set by the utra2svd generator
//pub interrupts: [Option<usize>; 1], // if in this list, this interrupt should be enabled
// i think maybe these go in the library, not in the auto-generated manager structure
pub suspend_cb: fn(),
pub resume_cb: fn(),
}
pub trait SusResBlockOps {
fn append(reg: ManagedReg); // adds a register to the managed suspend list
fn suspend(); // iterates through the list of registers and performs the suspend operation
fn resume(); // iterates through the list of registers and performs the resume operation
}
*/

View file

@ -51,6 +51,9 @@ mod implementation {
timer.wfo(utra::timer0::EV_PENDING_ZERO, 0b1);
}
// this is just for testing, remove for production
static REBOOT_CSR: core::sync::atomic::AtomicU32 = core::sync::atomic::AtomicU32::new(0);
// we do all the suspend/resume coordination in an interrupt context
// the process state is pushed to main memory prior to entering this routine, so it's staged for a resume
// on a clean suspend then resume, the loader will queue up this interrupt to be the first thing to
@ -61,12 +64,17 @@ mod implementation {
sr.csr.wfo(utra::susres::EV_PENDING_SOFT_INT, 1);
// set this to true to do a touch-and-go suspend/resume (no actual power off, but the whole prep cycle in play)
let touch_and_go = true;
let touch_and_go = false;
if touch_and_go {
sr.csr.wfo(utra::susres::STATE_RESUME, 1);
}
if sr.csr.rf(utra::susres::STATE_RESUME) == 0 {
{ // this is just for testing
let mut reboot_csr = CSR::new(REBOOT_CSR.load(Ordering::Relaxed) as *mut u32);
reboot_csr.wfo(utra::reboot::SOC_RESET_SOC_RESET, 0xAC);
}
// power the system down - this should result in an almost immediate loss of power
sr.csr.wfo(utra::susres::POWERDOWN_POWERDOWN, 1);
@ -90,6 +98,8 @@ mod implementation {
stored_time: Option<u64>,
/// so we can access the build seed and detect if the FPGA image was changed on us
seed_csr: utralib::CSR<u32>,
/// we also own the reboot facility
reboot_csr: utralib::CSR<u32>,
}
impl SusResHw {
pub fn new() -> Self {
@ -135,6 +145,14 @@ mod implementation {
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map Seed CSR range");
let reboot_csr = xous::syscall::map_memory(
xous::MemoryAddress::new(utra::reboot::HW_REBOOT_BASE),
None,
4096,
xous::MemoryFlags::R | xous::MemoryFlags::W,
)
.expect("couldn't map Reboot CSR range");
REBOOT_CSR.store(reboot_csr.as_mut_ptr() as u32, Ordering::Relaxed); // for testing only
let mut sr = SusResHw {
csr: CSR::new(csr.as_mut_ptr() as *mut u32),
os_timer: CSR::new(ostimer_csr.as_mut_ptr() as *mut u32),
@ -142,6 +160,7 @@ mod implementation {
marker,
loader_stack,
seed_csr: CSR::new(seed_csr.as_mut_ptr() as *mut u32),
reboot_csr: CSR::new(reboot_csr.as_mut_ptr() as *mut u32),
};
// start the OS timer running
@ -177,6 +196,17 @@ mod implementation {
sr
}
pub fn reboot(&mut self, reboot_soc: bool) {
if reboot_soc {
self.reboot_csr.wfo(utra::reboot::SOC_RESET_SOC_RESET, 0xAC);
} else {
self.reboot_csr.wfo(utra::reboot::CPU_RESET_CPU_RESET, 1);
}
}
pub fn set_reboot_vector(&mut self, vector: u32) {
self.reboot_csr.wfo(utra::reboot::ADDR_ADDR, vector);
}
pub fn setup_timeout_csr(&mut self, cid: xous::CID) -> Result<(), xous::Error> {
xous::send_message(cid,
xous::Message::new_scalar(crate::TimeoutOpcode::SetCsr.to_usize().unwrap(), self.csr.base as usize, 0, 0, 0)
@ -366,6 +396,8 @@ mod implementation {
pub fn new() -> Self {
SusResHw {}
}
pub fn reboot(&self, _reboot_soc: bool) {}
pub fn set_reboot_vector(&self, _vector: u32) {}
pub fn do_suspend(&mut self, _forced: bool) {
}
pub fn do_resume(&mut self) -> bool {
@ -518,105 +550,130 @@ fn xmain() -> ! {
let mut suspend_requested = false;
let mut timeout_pending = false;
let mut reboot_requested: bool = false;
let mut suspend_subscribers: [Option<ScalarCallback>; 32] = [None; 32];
loop {
let msg = xous::receive_message(susres_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::SuspendEventSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut suspend_subscribers);
},
Some(Opcode::SuspendReady) => msg_scalar_unpack!(msg, token, _, _, _, {
log::trace!("suspendready with token {}", token);
if !suspend_requested {
log::error!("received a SuspendReady message when a suspend wasn't pending. Ignoring.");
continue;
if reboot_requested {
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::RebootCpuConfirm) => {
susres_hw.reboot(false);
}
if token >= suspend_subscribers.len() {
panic!("received a SuspendReady token that's out of range");
Some(Opcode::RebootSocConfirm) => {
susres_hw.reboot(true);
}
if let Some(mut scb) = suspend_subscribers[token] {
if scb.ready_to_suspend {
log::error!("received a duplicate SuspendReady token: {} from {:?}", token, scb);
_ => reboot_requested = false,
}
} else {
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::RebootRequest) => {
reboot_requested = true;
},
Some(Opcode::RebootCpuConfirm) => {
log::error!("RebootCpuConfirm, but no prior Request. Ignoring.");
},
Some(Opcode::RebootSocConfirm) => {
log::error!("RebootSocConfirm, but no prior Request. Ignoring.");
},
Some(Opcode::RebootVector) => msg_scalar_unpack!(msg, vector, _, _, _, {
susres_hw.set_reboot_vector(vector as u32);
}),
Some(Opcode::SuspendEventSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut suspend_subscribers);
},
Some(Opcode::SuspendReady) => msg_scalar_unpack!(msg, token, _, _, _, {
log::trace!("suspendready with token {}", token);
if !suspend_requested {
log::error!("received a SuspendReady message when a suspend wasn't pending. Ignoring.");
continue;
}
scb.ready_to_suspend = true;
suspend_subscribers[token] = Some(scb);
if token >= suspend_subscribers.len() {
panic!("received a SuspendReady token that's out of range");
}
if let Some(mut scb) = suspend_subscribers[token] {
if scb.ready_to_suspend {
log::error!("received a duplicate SuspendReady token: {} from {:?}", token, scb);
}
scb.ready_to_suspend = true;
suspend_subscribers[token] = Some(scb);
let mut all_ready = true;
for maybe_sub in suspend_subscribers.iter() {
if let Some(sub) = maybe_sub {
if sub.ready_to_suspend == false {
all_ready = false;
break;
let mut all_ready = true;
for maybe_sub in suspend_subscribers.iter() {
if let Some(sub) = maybe_sub {
if sub.ready_to_suspend == false {
all_ready = false;
break;
}
};
}
if all_ready {
log::trace!("all callbacks reporting in, doing suspend");
timeout_pending = false;
susres_hw.do_suspend(false);
// when do_suspend() returns, it means we've resumed
suspend_requested = false;
if susres_hw.do_resume() {
log::error!("We did a clean shut-down, but bootloader is saying previous suspend was forced. Some peripherals may be in an unclean state!");
}
// this now allows all other threads to commence
log::trace!("low-level resume done, restoring execution");
RESUME_EXEC.store(true, Ordering::Relaxed);
} else {
log::trace!("still waiting on callbacks, returning to main loop");
}
} else {
panic!("received an invalid token that does not map to a registered suspend listener");
}
}),
Some(Opcode::SuspendRequest) => {
suspend_requested = true;
// clear the resume gate
SHOULD_RESUME.store(false, Ordering::Relaxed);
RESUME_EXEC.store(false, Ordering::Relaxed);
// clear the ready to suspend flag
for maybe_sub in suspend_subscribers.iter_mut() {
if let Some(sub) = maybe_sub {
sub.ready_to_suspend = false;
};
}
if all_ready {
log::trace!("all callbacks reporting in, doing suspend");
// do we want to start the timeout before or after sending the notifications? hmm. 🤔
timeout_pending = true;
send_message(timeout_outgoing_conn,
Message::new_scalar(TimeoutOpcode::Run.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate timeout before suspend!");
send_event(&suspend_subscribers);
},
Some(Opcode::SuspendTimeout) => {
if timeout_pending {
log::trace!("suspend call has timed out, forcing a suspend");
timeout_pending = false;
susres_hw.do_suspend(false);
// force a suspend
susres_hw.do_suspend(true);
// when do_suspend() returns, it means we've resumed
suspend_requested = false;
if susres_hw.do_resume() {
log::error!("We did a clean shut-down, but bootloader is saying previous suspend was forced. Some peripherals may be in an unclean state!");
log::error!("We forced a suspend, some peripherals may be in an unclean state!");
} else {
log::error!("We forced a suspend, but the bootloader is claiming we did a clean suspend. Internal state may be inconsistent.");
}
// this now allows all other threads to commence
log::trace!("low-level resume done, restoring execution");
RESUME_EXEC.store(true, Ordering::Relaxed);
} else {
log::trace!("still waiting on callbacks, returning to main loop");
log::trace!("clean suspend timeout received, ignoring");
// this means we did a clean suspend, we've resumed, and the timeout came back after the resume
// just ignore the message.
}
} else {
panic!("received an invalid token that does not map to a registered suspend listener");
}
}),
Some(Opcode::SuspendRequest) => {
suspend_requested = true;
// clear the resume gate
SHOULD_RESUME.store(false, Ordering::Relaxed);
RESUME_EXEC.store(false, Ordering::Relaxed);
// clear the ready to suspend flag
for maybe_sub in suspend_subscribers.iter_mut() {
if let Some(sub) = maybe_sub {
sub.ready_to_suspend = false;
};
Some(Opcode::Quit) => {
break
}
// do we want to start the timeout before or after sending the notifications? hmm. 🤔
timeout_pending = true;
send_message(timeout_outgoing_conn,
Message::new_scalar(TimeoutOpcode::Run.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't initiate timeout before suspend!");
send_event(&suspend_subscribers);
},
Some(Opcode::SuspendTimeout) => {
if timeout_pending {
log::trace!("suspend call has timed out, forcing a suspend");
timeout_pending = false;
// force a suspend
susres_hw.do_suspend(true);
// when do_suspend() returns, it means we've resumed
suspend_requested = false;
if susres_hw.do_resume() {
log::error!("We forced a suspend, some peripherals may be in an unclean state!");
} else {
log::error!("We forced a suspend, but the bootloader is claiming we did a clean suspend. Internal state may be inconsistent.");
}
RESUME_EXEC.store(true, Ordering::Relaxed);
} else {
log::trace!("clean suspend timeout received, ignoring");
// this means we did a clean suspend, we've resumed, and the timeout came back after the resume
// just ignore the message.
None => {
log::error!("couldn't convert opcode");
}
}
Some(Opcode::Quit) => {
break
}
None => {
log::error!("couldn't convert opcode");
}
}
}
// clean up our program