interrupt.rs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. use super::mem::handle_kernel_page_fault;
  2. use super::timer::timer_interrupt;
  3. use crate::kernel::constants::EINVAL;
  4. use crate::prelude::*;
  5. use alloc::sync::Arc;
  6. use eonix_hal::traits::fault::Fault;
  7. use eonix_hal::traits::trap::{RawTrapContext, TrapType};
  8. use eonix_hal::trap::TrapContext;
  9. use eonix_mm::address::{Addr as _, VAddr};
  10. use eonix_sync::SpinIrq as _;
  11. static IRQ_HANDLERS: Spin<[Vec<Arc<dyn Fn() + Send + Sync>>; 16]> =
  12. Spin::new([const { Vec::new() }; 16]);
  13. pub fn default_irq_handler(irqno: usize) {
  14. assert!(irqno < 16);
  15. {
  16. let handlers = IRQ_HANDLERS.lock();
  17. for handler in handlers[irqno].iter() {
  18. handler();
  19. }
  20. }
  21. }
  22. pub fn default_fault_handler(fault_type: Fault, trap_ctx: &mut TrapContext) {
  23. if trap_ctx.is_user_mode() {
  24. unimplemented!("Unhandled user space fault");
  25. }
  26. match fault_type {
  27. Fault::PageFault {
  28. error_code,
  29. address: vaddr,
  30. } => {
  31. let fault_pc = VAddr::from(trap_ctx.get_program_counter());
  32. if let Some(new_pc) = handle_kernel_page_fault(fault_pc, vaddr, error_code) {
  33. trap_ctx.set_program_counter(new_pc.addr());
  34. }
  35. }
  36. fault => panic!("Unhandled kernel space fault: {fault:?}"),
  37. }
  38. }
  39. #[eonix_hal::default_trap_handler]
  40. pub fn interrupt_handler(trap_ctx: &mut TrapContext) {
  41. match trap_ctx.trap_type() {
  42. TrapType::Syscall { no, .. } => unreachable!("Syscall {} in kernel space.", no),
  43. TrapType::Breakpoint => unreachable!("Breakpoint in kernel space."),
  44. TrapType::Fault(fault) => default_fault_handler(fault, trap_ctx),
  45. TrapType::Irq { callback } => callback(default_irq_handler),
  46. TrapType::Timer { callback } => callback(timer_interrupt),
  47. }
  48. }
  49. pub fn register_irq_handler<F>(irqno: i32, handler: F) -> Result<(), u32>
  50. where
  51. F: Fn() + Send + Sync + 'static,
  52. {
  53. if irqno < 0 || irqno >= 16 {
  54. return Err(EINVAL);
  55. }
  56. IRQ_HANDLERS.lock_irq()[irqno as usize].push(Arc::new(handler));
  57. Ok(())
  58. }