main.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #![feature(naked_functions)]
  2. #![no_std]
  3. #![no_main]
  4. #![allow(static_mut_refs)]
  5. #[macro_use]
  6. extern crate log;
  7. #[macro_use]
  8. mod macros;
  9. mod board;
  10. mod dt;
  11. mod fail;
  12. mod platform;
  13. mod riscv_spec;
  14. mod sbi;
  15. use core::sync::atomic::{AtomicBool, Ordering};
  16. use core::{arch::asm, mem::MaybeUninit};
  17. use sbi::extensions;
  18. use crate::board::{SBI_IMPL, SIFIVECLINT, SIFIVETEST, UART};
  19. use crate::riscv_spec::{current_hartid, menvcfg};
  20. use crate::sbi::console::SbiConsole;
  21. use crate::sbi::extensions::{hart_extension_probe, Extension};
  22. use crate::sbi::hart_context::NextStage;
  23. use crate::sbi::hsm::{local_remote_hsm, SbiHsm};
  24. use crate::sbi::ipi::{self, SbiIpi};
  25. use crate::sbi::logger;
  26. use crate::sbi::reset::SbiReset;
  27. use crate::sbi::rfence::SbiRFence;
  28. use crate::sbi::trap::{self, trap_vec};
  29. use crate::sbi::trap_stack;
  30. use crate::sbi::SBI;
  31. pub const START_ADDRESS: usize = 0x80000000;
  32. pub const R_RISCV_RELATIVE: usize = 3;
  33. #[no_mangle]
  34. extern "C" fn rust_main(_hart_id: usize, opaque: usize, nonstandard_a2: usize) {
  35. // Track whether SBI is initialized and ready.
  36. static SBI_READY: AtomicBool = AtomicBool::new(false);
  37. let boot_hart_info = platform::get_boot_hart(opaque, nonstandard_a2);
  38. // boot hart task entry.
  39. if boot_hart_info.is_boot_hart {
  40. let fdt_addr = boot_hart_info.fdt_address;
  41. // 1. Init FDT
  42. // parse the device tree.
  43. // TODO: shoule remove `fail:device_tree_format`.
  44. let dtb = dt::parse_device_tree(fdt_addr).unwrap_or_else(fail::device_tree_format);
  45. let dtb = dtb.share();
  46. // TODO: should remove `fail:device_tree_deserialize`.
  47. let tree =
  48. serde_device_tree::from_raw_mut(&dtb).unwrap_or_else(fail::device_tree_deserialize);
  49. // 2. Init device
  50. // TODO: The device base address should be find in a better way.
  51. let console_base = tree.soc.serial.unwrap().iter().next().unwrap();
  52. let clint_device = tree.soc.clint.unwrap().iter().next().unwrap();
  53. let cpu_num = tree.cpus.cpu.len();
  54. let console_base_address = console_base.at();
  55. let ipi_base_address = clint_device.at();
  56. // Initialize reset device if present.
  57. if let Some(test) = tree.soc.test {
  58. let reset_device = test.iter().next().unwrap();
  59. let reset_base_address = reset_device.at();
  60. board::reset_dev_init(usize::from_str_radix(reset_base_address, 16).unwrap());
  61. }
  62. // Initialize console and IPI devices.
  63. board::console_dev_init(usize::from_str_radix(console_base_address, 16).unwrap());
  64. board::ipi_dev_init(usize::from_str_radix(ipi_base_address, 16).unwrap());
  65. // 3. Init the SBI implementation
  66. unsafe {
  67. SBI_IMPL = MaybeUninit::new(SBI {
  68. console: Some(SbiConsole::new(&UART)),
  69. ipi: Some(SbiIpi::new(&SIFIVECLINT, cpu_num)),
  70. hsm: Some(SbiHsm),
  71. reset: Some(SbiReset::new(&SIFIVETEST)),
  72. rfence: Some(SbiRFence),
  73. });
  74. }
  75. // Setup trap handling.
  76. trap_stack::prepare_for_trap();
  77. extensions::init(&tree.cpus.cpu);
  78. SBI_READY.swap(true, Ordering::AcqRel);
  79. // 4. Init Logger
  80. logger::Logger::init().unwrap();
  81. info!("RustSBI version {}", rustsbi::VERSION);
  82. rustsbi::LOGO.lines().for_each(|line| info!("{}", line));
  83. info!("Initializing RustSBI machine-mode environment.");
  84. info!("Number of CPU: {}", cpu_num);
  85. if let Some(model) = tree.model {
  86. info!("Model: {}", model.iter().next().unwrap_or("<unspecified>"));
  87. }
  88. info!("Clint device: {}", ipi_base_address);
  89. info!("Console deivce: {}", console_base_address);
  90. info!(
  91. "Chosen stdout item: {}",
  92. tree.chosen
  93. .stdout_path
  94. .iter()
  95. .next()
  96. .unwrap_or("<unspecified>")
  97. );
  98. platform::set_pmp();
  99. // Get boot information and prepare for kernel entry.
  100. let boot_info = platform::get_boot_info(nonstandard_a2);
  101. let (mpp, next_addr) = (boot_info.mpp, boot_info.next_address);
  102. // Start kernel.
  103. local_remote_hsm().start(NextStage {
  104. start_addr: next_addr,
  105. next_mode: mpp,
  106. opaque: fdt_addr,
  107. });
  108. info!(
  109. "Redirecting hart {} to 0x{:0>16x} in {:?} mode.",
  110. current_hartid(),
  111. next_addr,
  112. mpp
  113. );
  114. } else {
  115. // 设置陷入栈
  116. trap_stack::prepare_for_trap();
  117. // Wait for boot hart to complete SBI initialization.
  118. while !SBI_READY.load(Ordering::Relaxed) {
  119. core::hint::spin_loop()
  120. }
  121. platform::set_pmp();
  122. }
  123. // Clear all pending IPIs.
  124. ipi::clear_all();
  125. // Configure CSRs and trap handling.
  126. unsafe {
  127. // Delegate all interrupts and exceptions to supervisor mode.
  128. asm!("csrw mideleg, {}", in(reg) !0);
  129. asm!("csrw medeleg, {}", in(reg) !0);
  130. asm!("csrw mcounteren, {}", in(reg) !0);
  131. use riscv::register::{medeleg, mtvec};
  132. // Keep supervisor environment calls and illegal instructions in M-mode.
  133. medeleg::clear_supervisor_env_call();
  134. medeleg::clear_illegal_instruction();
  135. // Configure environment features based on available extensions.
  136. if hart_extension_probe(current_hartid(), Extension::Sstc) {
  137. menvcfg::set_bits(
  138. menvcfg::STCE | menvcfg::CBIE_INVALIDATE | menvcfg::CBCFE | menvcfg::CBZE,
  139. );
  140. } else {
  141. menvcfg::set_bits(menvcfg::CBIE_INVALIDATE | menvcfg::CBCFE | menvcfg::CBZE);
  142. }
  143. // Set up vectored trap handling.
  144. mtvec::write(trap_vec as _, mtvec::TrapMode::Vectored);
  145. }
  146. }
  147. #[naked]
  148. #[link_section = ".text.entry"]
  149. #[export_name = "_start"]
  150. unsafe extern "C" fn start() -> ! {
  151. core::arch::asm!(
  152. // 1. Turn off interrupt.
  153. " csrw mie, zero",
  154. // 2. Initialize programming langauge runtime.
  155. // only clear bss if hartid matches preferred boot hart id.
  156. " csrr t0, mhartid",
  157. " bne t0, zero, 4f",
  158. " call {relocation_update}",
  159. "1:",
  160. // 3. Hart 0 clear bss segment.
  161. " lla t0, sbss
  162. lla t1, ebss
  163. 2: bgeu t0, t1, 3f
  164. sd zero, 0(t0)
  165. addi t0, t0, 8
  166. j 2b",
  167. "3: ", // Hart 0 set bss ready signal.
  168. " lla t0, 6f
  169. li t1, 1
  170. amoadd.w t0, t1, 0(t0)
  171. j 5f",
  172. "4:", // Other harts are waiting for bss ready signal.
  173. " li t1, 1
  174. lla t0, 6f
  175. lw t0, 0(t0)
  176. bne t0, t1, 4b",
  177. "5:",
  178. // 4. Prepare stack for each hart.
  179. " call {locate_stack}",
  180. " call {main}",
  181. " csrw mscratch, sp",
  182. " j {hart_boot}",
  183. " .balign 4",
  184. "6:", // bss ready signal.
  185. " .word 0",
  186. relocation_update = sym relocation_update,
  187. locate_stack = sym trap_stack::locate,
  188. main = sym rust_main,
  189. hart_boot = sym trap::msoft,
  190. options(noreturn)
  191. )
  192. }
  193. // Handle relocations for position-independent code
  194. #[naked]
  195. unsafe extern "C" fn relocation_update() {
  196. asm!(
  197. // Get load offset.
  198. " li t0, {START_ADDRESS}",
  199. " lla t1, sbi_start",
  200. " sub t2, t1, t0",
  201. // Foreach rela.dyn and update relocation.
  202. " lla t0, __rel_dyn_start",
  203. " lla t1, __rel_dyn_end",
  204. " li t3, {R_RISCV_RELATIVE}",
  205. "1:",
  206. " ld t4, 8(t0)",
  207. " bne t4, t3, 2f",
  208. " ld t4, 0(t0)", // Get offset
  209. " ld t5, 16(t0)", // Get append
  210. " add t4, t4, t2", // Add load offset to offset add append
  211. " add t5, t5, t2",
  212. " sd t5, 0(t4)", // Update address
  213. " addi t0, t0, 24", // Get next rela item
  214. "2:",
  215. " blt t0, t1, 1b",
  216. // Return
  217. " ret",
  218. R_RISCV_RELATIVE = const R_RISCV_RELATIVE,
  219. START_ADDRESS = const START_ADDRESS,
  220. options(noreturn)
  221. )
  222. }
  223. #[panic_handler]
  224. fn panic(info: &core::panic::PanicInfo) -> ! {
  225. use riscv::register::*;
  226. println!(
  227. "[rustsbi-panic] hart {} {info}",
  228. riscv::register::mhartid::read()
  229. );
  230. println!(
  231. "-----------------------------
  232. > mcause: {:?}
  233. > mepc: {:#018x}
  234. > mtval: {:#018x}
  235. -----------------------------",
  236. mcause::read().cause(),
  237. mepc::read(),
  238. mtval::read()
  239. );
  240. println!("[rustsbi-panic] system shutdown scheduled due to RustSBI panic");
  241. loop {}
  242. }