main.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. // 1. Init FDT
  41. // parse the device tree
  42. // TODO: shoule remove `fail:device_tree_format`
  43. let fdt_addr = boot_hart_info.fdt_address;
  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. // TODO: More than one memory node or range?
  67. let memory_reg = tree
  68. .memory
  69. .iter()
  70. .next()
  71. .unwrap()
  72. .deserialize::<dt::Memory>()
  73. .reg;
  74. let memory_range = memory_reg.iter().next().unwrap().0;
  75. // 3. Init SBI
  76. unsafe {
  77. SBI_IMPL = MaybeUninit::new(SBI {
  78. console: Some(SbiConsole::new(&UART)),
  79. ipi: Some(SbiIpi::new(&SIFIVECLINT, cpu_num)),
  80. hsm: Some(SbiHsm),
  81. reset: Some(SbiReset::new(&SIFIVETEST)),
  82. rfence: Some(SbiRFence),
  83. memory_range,
  84. });
  85. }
  86. // Setup trap handling.
  87. trap_stack::prepare_for_trap();
  88. extensions::init(&tree.cpus.cpu);
  89. SBI_READY.swap(true, Ordering::AcqRel);
  90. // 4. Init Logger
  91. logger::Logger::init().unwrap();
  92. info!("RustSBI version {}", rustsbi::VERSION);
  93. rustsbi::LOGO.lines().for_each(|line| info!("{}", line));
  94. info!("Initializing RustSBI machine-mode environment.");
  95. info!("Number of CPU: {}", cpu_num);
  96. if let Some(model) = tree.model {
  97. info!("Model: {}", model.iter().next().unwrap_or("<unspecified>"));
  98. }
  99. info!("Clint device: {}", ipi_base_address);
  100. info!("Console deivce: {}", console_base_address);
  101. info!(
  102. "Chosen stdout item: {}",
  103. tree.chosen
  104. .stdout_path
  105. .iter()
  106. .next()
  107. .unwrap_or("<unspecified>")
  108. );
  109. platform::set_pmp(&unsafe { SBI_IMPL.assume_init_ref() }.memory_range);
  110. // Get boot information and prepare for kernel entry.
  111. let boot_info = platform::get_boot_info(nonstandard_a2);
  112. let (mpp, next_addr) = (boot_info.mpp, boot_info.next_address);
  113. // Start kernel.
  114. local_remote_hsm().start(NextStage {
  115. start_addr: next_addr,
  116. next_mode: mpp,
  117. opaque: fdt_addr,
  118. });
  119. info!(
  120. "Redirecting hart {} to 0x{:0>16x} in {:?} mode.",
  121. current_hartid(),
  122. next_addr,
  123. mpp
  124. );
  125. } else {
  126. // 设置陷入栈
  127. trap_stack::prepare_for_trap();
  128. // Wait for boot hart to complete SBI initialization.
  129. while !SBI_READY.load(Ordering::Relaxed) {
  130. core::hint::spin_loop()
  131. }
  132. platform::set_pmp(&unsafe { SBI_IMPL.assume_init_ref() }.memory_range);
  133. }
  134. // Clear all pending IPIs.
  135. ipi::clear_all();
  136. // Configure CSRs and trap handling.
  137. unsafe {
  138. // Delegate all interrupts and exceptions to supervisor mode.
  139. asm!("csrw mideleg, {}", in(reg) !0);
  140. asm!("csrw medeleg, {}", in(reg) !0);
  141. asm!("csrw mcounteren, {}", in(reg) !0);
  142. use riscv::register::{medeleg, mtvec};
  143. // Keep supervisor environment calls and illegal instructions in M-mode.
  144. medeleg::clear_supervisor_env_call();
  145. medeleg::clear_illegal_instruction();
  146. // Configure environment features based on available extensions.
  147. if hart_extension_probe(current_hartid(), Extension::Sstc) {
  148. menvcfg::set_bits(
  149. menvcfg::STCE | menvcfg::CBIE_INVALIDATE | menvcfg::CBCFE | menvcfg::CBZE,
  150. );
  151. } else {
  152. menvcfg::set_bits(menvcfg::CBIE_INVALIDATE | menvcfg::CBCFE | menvcfg::CBZE);
  153. }
  154. // Set up vectored trap handling.
  155. mtvec::write(trap_vec as _, mtvec::TrapMode::Vectored);
  156. }
  157. }
  158. #[naked]
  159. #[link_section = ".text.entry"]
  160. #[export_name = "_start"]
  161. unsafe extern "C" fn start() -> ! {
  162. core::arch::asm!(
  163. // 1. Turn off interrupt.
  164. " csrw mie, zero",
  165. // 2. Initialize programming langauge runtime.
  166. // only clear bss if hartid matches preferred boot hart id.
  167. " csrr t0, mhartid",
  168. " bne t0, zero, 4f",
  169. " call {relocation_update}",
  170. "1:",
  171. // 3. Hart 0 clear bss segment.
  172. " lla t0, sbss
  173. lla t1, ebss
  174. 2: bgeu t0, t1, 3f
  175. sd zero, 0(t0)
  176. addi t0, t0, 8
  177. j 2b",
  178. "3: ", // Hart 0 set bss ready signal.
  179. " lla t0, 6f
  180. li t1, 1
  181. amoadd.w t0, t1, 0(t0)
  182. j 5f",
  183. "4:", // Other harts are waiting for bss ready signal.
  184. " li t1, 1
  185. lla t0, 6f
  186. lw t0, 0(t0)
  187. bne t0, t1, 4b",
  188. "5:",
  189. // 4. Prepare stack for each hart.
  190. " call {locate_stack}",
  191. " call {main}",
  192. " csrw mscratch, sp",
  193. " j {hart_boot}",
  194. " .balign 4",
  195. "6:", // bss ready signal.
  196. " .word 0",
  197. relocation_update = sym relocation_update,
  198. locate_stack = sym trap_stack::locate,
  199. main = sym rust_main,
  200. hart_boot = sym trap::msoft,
  201. options(noreturn)
  202. )
  203. }
  204. // Handle relocations for position-independent code
  205. #[naked]
  206. unsafe extern "C" fn relocation_update() {
  207. asm!(
  208. // Get load offset.
  209. " li t0, {START_ADDRESS}",
  210. " lla t1, sbi_start",
  211. " sub t2, t1, t0",
  212. // Foreach rela.dyn and update relocation.
  213. " lla t0, __rel_dyn_start",
  214. " lla t1, __rel_dyn_end",
  215. " li t3, {R_RISCV_RELATIVE}",
  216. "1:",
  217. " ld t4, 8(t0)",
  218. " bne t4, t3, 2f",
  219. " ld t4, 0(t0)", // Get offset
  220. " ld t5, 16(t0)", // Get append
  221. " add t4, t4, t2", // Add load offset to offset add append
  222. " add t5, t5, t2",
  223. " sd t5, 0(t4)", // Update address
  224. " addi t0, t0, 24", // Get next rela item
  225. "2:",
  226. " blt t0, t1, 1b",
  227. // Return
  228. " ret",
  229. R_RISCV_RELATIVE = const R_RISCV_RELATIVE,
  230. START_ADDRESS = const START_ADDRESS,
  231. options(noreturn)
  232. )
  233. }
  234. #[panic_handler]
  235. fn panic(info: &core::panic::PanicInfo) -> ! {
  236. use riscv::register::*;
  237. println!(
  238. "[rustsbi-panic] hart {} {info}",
  239. riscv::register::mhartid::read()
  240. );
  241. println!(
  242. "-----------------------------
  243. > mcause: {:?}
  244. > mepc: {:#018x}
  245. > mtval: {:#018x}
  246. -----------------------------",
  247. mcause::read().cause(),
  248. mepc::read(),
  249. mtval::read()
  250. );
  251. println!("[rustsbi-panic] system shutdown scheduled due to RustSBI panic");
  252. loop {}
  253. }