veer_el2_sim/
main.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4// Copyright (c) 2024 Antmicro <www.antmicro.com>
5
6//! Board file for VeeR EL2 simulation platform.
7
8#![no_std]
9#![no_main]
10
11use capsules_core::virtualizers::virtual_alarm::{MuxAlarm, VirtualMuxAlarm};
12use kernel::capabilities;
13use kernel::component::Component;
14use kernel::hil;
15use kernel::platform::scheduler_timer::VirtualSchedulerTimer;
16use kernel::platform::{KernelResources, SyscallDriverLookup};
17use kernel::process::ProcessArray;
18use kernel::scheduler::cooperative::CooperativeSched;
19use kernel::utilities::registers::interfaces::ReadWriteable;
20use kernel::{create_capability, debug, static_init};
21use rv32i::csr;
22use veer_el2::chip::VeeRDefaultPeripherals;
23
24use veer_el2::machine_timer::Clint;
25use veer_el2::machine_timer::CLINT_BASE;
26
27pub mod io;
28
29pub const NUM_PROCS: usize = 4;
30
31pub type VeeRChip = veer_el2::chip::VeeR<'static, VeeRDefaultPeripherals>;
32
33/// Static variables used by io.rs.
34static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
35// Reference to the chip for panic dumps.
36static mut CHIP: Option<&'static VeeRChip> = None;
37// Static reference to process printer for panic dumps.
38static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
39    None;
40
41// How should the kernel respond when a process faults.
42const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
43    capsules_system::process_policies::PanicFaultPolicy {};
44
45kernel::stack_size! {0x900}
46
47/// A structure representing this platform that holds references to all
48/// capsules for this platform.
49struct VeeR {
50    console: &'static capsules_core::console::Console<'static>,
51    alarm: &'static capsules_core::alarm::AlarmDriver<
52        'static,
53        VirtualMuxAlarm<'static, Clint<'static>>,
54    >,
55    scheduler: &'static CooperativeSched<'static>,
56    scheduler_timer: &'static VirtualSchedulerTimer<VirtualMuxAlarm<'static, Clint<'static>>>,
57}
58
59/// Mapping of integer syscalls to objects that implement syscalls.
60impl SyscallDriverLookup for VeeR {
61    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
62    where
63        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
64    {
65        match driver_num {
66            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
67            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
68            _ => f(None),
69        }
70    }
71}
72
73impl KernelResources<VeeRChip> for VeeR {
74    type SyscallDriverLookup = Self;
75    type SyscallFilter = ();
76    type ProcessFault = ();
77    type Scheduler = CooperativeSched<'static>;
78    type SchedulerTimer = VirtualSchedulerTimer<VirtualMuxAlarm<'static, Clint<'static>>>;
79    type WatchDog = ();
80    type ContextSwitchCallback = ();
81
82    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
83        self
84    }
85    fn syscall_filter(&self) -> &Self::SyscallFilter {
86        &()
87    }
88    fn process_fault(&self) -> &Self::ProcessFault {
89        &()
90    }
91    fn scheduler(&self) -> &Self::Scheduler {
92        self.scheduler
93    }
94    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
95        self.scheduler_timer
96    }
97    fn watchdog(&self) -> &Self::WatchDog {
98        &()
99    }
100    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
101        &()
102    }
103}
104
105/// This is in a separate, inline(never) function so that its stack frame is
106/// removed when this function returns. Otherwise, the stack space used for
107/// these static_inits is wasted.
108#[inline(never)]
109unsafe fn start() -> (&'static kernel::Kernel, VeeR, &'static VeeRChip) {
110    // only machine mode
111    rv32i::configure_trap_handler();
112
113    let peripherals = static_init!(VeeRDefaultPeripherals, VeeRDefaultPeripherals::new());
114    peripherals.init();
115
116    // initialize capabilities
117    let process_mgmt_cap = create_capability!(capabilities::ProcessManagementCapability);
118    let memory_allocation_cap = create_capability!(capabilities::MemoryAllocationCapability);
119
120    // Create an array to hold process references.
121    let processes = components::process_array::ProcessArrayComponent::new()
122        .finalize(components::process_array_component_static!(NUM_PROCS));
123    PROCESSES = Some(processes);
124
125    // Setup space to store the core kernel data structure.
126    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
127
128    // Configure kernel debug gpios as early as possible
129    kernel::debug::assign_gpios(None, None, None);
130
131    // Create a shared UART channel for the console and for kernel debug.
132    let uart_mux = components::console::UartMuxComponent::new(&peripherals.sim_uart, 115200)
133        .finalize(components::uart_mux_component_static!());
134
135    let mtimer = static_init!(Clint, Clint::new(&CLINT_BASE));
136
137    // Create a shared virtualization mux layer on top of a single hardware
138    // alarm.
139    let mux_alarm = static_init!(MuxAlarm<'static, Clint>, MuxAlarm::new(mtimer));
140    hil::time::Alarm::set_alarm_client(mtimer, mux_alarm);
141
142    // Alarm
143    let virtual_alarm_user = static_init!(
144        VirtualMuxAlarm<'static, Clint>,
145        VirtualMuxAlarm::new(mux_alarm)
146    );
147    virtual_alarm_user.setup();
148
149    let systick_virtual_alarm = static_init!(
150        VirtualMuxAlarm<'static, Clint>,
151        VirtualMuxAlarm::new(mux_alarm)
152    );
153    systick_virtual_alarm.setup();
154
155    let alarm = static_init!(
156        capsules_core::alarm::AlarmDriver<'static, VirtualMuxAlarm<'static, Clint>>,
157        capsules_core::alarm::AlarmDriver::new(
158            virtual_alarm_user,
159            board_kernel.create_grant(capsules_core::alarm::DRIVER_NUM, &memory_allocation_cap)
160        )
161    );
162    hil::time::Alarm::set_alarm_client(virtual_alarm_user, alarm);
163
164    let chip = static_init!(VeeRChip, veer_el2::chip::VeeR::new(peripherals, mtimer));
165    CHIP = Some(chip);
166
167    // Create a process printer for panic.
168    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
169        .finalize(components::process_printer_text_component_static!());
170    PROCESS_PRINTER = Some(process_printer);
171
172    let process_console = components::process_console::ProcessConsoleComponent::new(
173        board_kernel,
174        uart_mux,
175        mux_alarm,
176        process_printer,
177        None,
178    )
179    .finalize(components::process_console_component_static!(Clint));
180    let _ = process_console.start();
181
182    // Need to enable all interrupts for Tock Kernel
183    chip.enable_pic_interrupts();
184
185    // enable interrupts globally
186    csr::CSR
187        .mie
188        .modify(csr::mie::mie::mext::SET + csr::mie::mie::msoft::SET + csr::mie::mie::mtimer::SET);
189    csr::CSR.mstatus.modify(csr::mstatus::mstatus::mie::SET);
190
191    // Setup the console.
192    let console = components::console::ConsoleComponent::new(
193        board_kernel,
194        capsules_core::console::DRIVER_NUM,
195        uart_mux,
196    )
197    .finalize(components::console_component_static!());
198    // Create the debugger object that handles calls to `debug!()`.
199    components::debug_writer::DebugWriterComponent::new(
200        uart_mux,
201        create_capability!(capabilities::SetDebugWriterCapability),
202    )
203    .finalize(components::debug_writer_component_static!());
204
205    debug!("VeeR EL2 initialisation complete.");
206    debug!("Entering main loop.");
207
208    // These symbols are defined in the linker script.
209    extern "C" {
210        /// Beginning of the ROM region containing app images.
211        static _sapps: u8;
212        /// End of the ROM region containing app images.
213        static _eapps: u8;
214        /// Beginning of the RAM region for app memory.
215        static mut _sappmem: u8;
216        /// End of the RAM region for app memory.
217        static _eappmem: u8;
218    }
219
220    let scheduler = components::sched::cooperative::CooperativeComponent::new(processes)
221        .finalize(components::cooperative_component_static!(NUM_PROCS));
222
223    let scheduler_timer = static_init!(
224        VirtualSchedulerTimer<VirtualMuxAlarm<'static, Clint<'static>>>,
225        VirtualSchedulerTimer::new(systick_virtual_alarm)
226    );
227
228    let veer = VeeR {
229        console,
230        alarm,
231        scheduler,
232        scheduler_timer,
233    };
234
235    kernel::process::load_processes(
236        board_kernel,
237        chip,
238        core::slice::from_raw_parts(
239            core::ptr::addr_of!(_sapps),
240            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
241        ),
242        core::slice::from_raw_parts_mut(
243            core::ptr::addr_of_mut!(_sappmem),
244            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
245        ),
246        &FAULT_RESPONSE,
247        &process_mgmt_cap,
248    )
249    .unwrap_or_else(|err| {
250        debug!("Error loading processes!");
251        debug!("{:?}", err);
252    });
253
254    (board_kernel, veer, chip)
255}
256
257/// Main function called after RAM initialized.
258///
259/// # Safety
260/// Accesses memory, memory-mapped registers and CSRs.
261#[no_mangle]
262pub unsafe fn main() {
263    let main_loop_cap = create_capability!(capabilities::MainLoopCapability);
264    let (board_kernel, veer, chip) = start();
265    board_kernel.kernel_loop(&veer, chip, None::<&kernel::ipc::IPC<0>>, &main_loop_cap);
266}