main.back.rs 18.34 KiB
// Ref: https://github.com/luojia65/rustsbi/blob/master/platform/k210/src/main.rs
#![no_std]
#![no_main]
#![feature(alloc_error_handler)]
#![feature(global_asm)]
#![feature(llvm_asm)]
#[cfg(not(test))]
use core::alloc::Layout;
#[cfg(not(test))]
use core::panic::PanicInfo;
use k210_hal::{clock::Clocks, fpioa, pac, prelude::*};
use linked_list_allocator::LockedHeap;
use rustsbi::{enter_privileged, print, println};
use riscv::register::{
    mcause::{self, Exception, Interrupt, Trap},
    medeleg, mepc, mhartid, mideleg, mie, mip, misa::{self, MXL},
    mstatus::{self, MPP},
    mtval,
    mtvec::{self, TrapMode},
    satp,
#[global_allocator]
static ALLOCATOR: LockedHeap = LockedHeap::empty();
static mut DEVINTRENTRY: usize = 0;
#[cfg(not(test))]
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    println!("[rustsbi] {}", info);
    loop {}
#[cfg(not(test))]
#[alloc_error_handler]
fn oom(layout: Layout) -> ! {
    println!("[rustsbi] out of memory for layout {:?}", layout);
    loop {}
fn mp_hook() -> bool {
    use riscv::asm::wfi;
    use k210_hal::clint::msip;
    let hartid = mhartid::read();
    if hartid == 0 {
        true
    } else {
        unsafe {
            // Clear IPI
            msip::clear_ipi(hartid);
            // Start listening for software interrupts
            mie::set_msoft();
            loop {
                wfi();
                if mip::read().msoft() {
                    break;
            // Stop listening for software interrupts
            mie::clear_msoft();
            // Clear IPI
            msip::clear_ipi(hartid);
        false
7172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
} #[export_name = "_start"] #[link_section = ".text.entry"] // this is stable fn main() -> ! { unsafe { llvm_asm!( " csrr a2, mhartid lui t0, %hi(_max_hart_id) add t0, t0, %lo(_max_hart_id) bgtu a2, t0, _start_abort la sp, _stack_start lui t0, %hi(_hart_stack_size) add t0, t0, %lo(_hart_stack_size) .ifdef __riscv_mul mul t0, a2, t0 .else beqz a2, 2f // Jump if single-hart mv t1, a2 mv t2, t0 1: add t0, t0, t2 addi t1, t1, -1 bnez t1, 1b 2: .endif sub sp, sp, t0 csrw mscratch, zero j _start_success _start_abort: wfi j _start_abort _start_success: " ) }; if mp_hook() { extern "C" { static mut _ebss: u32; static mut _sbss: u32; static mut _edata: u32; static mut _sdata: u32; static _sidata: u32; } unsafe { r0::zero_bss(&mut _sbss, &mut _ebss); r0::init_data(&mut _sdata, &mut _edata, &_sidata); } } extern "C" { fn _start_trap(); } unsafe { mtvec::write(_start_trap as usize, TrapMode::Direct); } if mhartid::read() == 0 { extern "C" { fn _sheap(); fn _heap_size(); } let sheap = &mut _sheap as *mut _ as usize; let heap_size = &_heap_size as *const _ as usize; unsafe { ALLOCATOR.lock().init(sheap, heap_size); }