1bacd691cSlogin use core::{ 2bacd691cSlogin fmt::Debug, 3bacd691cSlogin intrinsics::unlikely, 4bacd691cSlogin mem::{self, MaybeUninit}, 5bacd691cSlogin ptr::null_mut, 60d6cf65aSLoGin sync::atomic::{compiler_fence, AtomicI16, Ordering}, 7bacd691cSlogin }; 862e46139SGou Ngai 90d6cf65aSLoGin use alloc::{boxed::Box, sync::Arc, vec::Vec}; 10bacd691cSlogin use num_traits::FromPrimitive; 1191e9d4abSLoGin use system_error::SystemError; 1262e46139SGou Ngai 1362e46139SGou Ngai use crate::{ 140d6cf65aSLoGin arch::CurrentIrqArch, 150d6cf65aSLoGin exception::InterruptArch, 160d6cf65aSLoGin kdebug, kinfo, 170d6cf65aSLoGin libs::rwlock::RwLock, 180d6cf65aSLoGin mm::percpu::{PerCpu, PerCpuVar}, 190d6cf65aSLoGin process::ProcessManager, 20*e2841179SLoGin smp::{core::smp_get_processor_id, cpu::ProcessorId}, 2191e9d4abSLoGin time::timer::clock, 2262e46139SGou Ngai }; 2362e46139SGou Ngai 2462e46139SGou Ngai const MAX_SOFTIRQ_NUM: u64 = 64; 25bacd691cSlogin const MAX_SOFTIRQ_RESTART: i32 = 20; 26bacd691cSlogin 27*e2841179SLoGin static mut __CPU_PENDING: Option<Box<[VecStatus; PerCpu::MAX_CPU_NUM as usize]>> = None; 28bacd691cSlogin static mut __SORTIRQ_VECTORS: *mut Softirq = null_mut(); 29bacd691cSlogin 30bacd691cSlogin #[no_mangle] 31bacd691cSlogin pub extern "C" fn rs_softirq_init() { 32bacd691cSlogin softirq_init().expect("softirq_init failed"); 33bacd691cSlogin } 34bacd691cSlogin 355b59005fSLoGin #[inline(never)] 36bacd691cSlogin pub fn softirq_init() -> Result<(), SystemError> { 37bacd691cSlogin kinfo!("Initializing softirq..."); 38bacd691cSlogin unsafe { 39bacd691cSlogin __SORTIRQ_VECTORS = Box::leak(Box::new(Softirq::new())); 4046e234aeSLoGin __CPU_PENDING = Some(Box::new( 4146e234aeSLoGin [VecStatus::default(); PerCpu::MAX_CPU_NUM as usize], 4246e234aeSLoGin )); 43bacd691cSlogin let cpu_pending = __CPU_PENDING.as_mut().unwrap(); 4446e234aeSLoGin for i in 0..PerCpu::MAX_CPU_NUM { 45bacd691cSlogin cpu_pending[i as usize] = VecStatus::default(); 46bacd691cSlogin } 47bacd691cSlogin } 4840fe15e0SLoGin kinfo!("Softirq initialized."); 49bacd691cSlogin return Ok(()); 50bacd691cSlogin } 51bacd691cSlogin 52bacd691cSlogin #[inline(always)] 53bacd691cSlogin pub fn softirq_vectors() -> &'static mut Softirq { 54bacd691cSlogin unsafe { 55bacd691cSlogin return __SORTIRQ_VECTORS.as_mut().unwrap(); 56bacd691cSlogin } 57bacd691cSlogin } 58bacd691cSlogin 59bacd691cSlogin #[inline(always)] 60*e2841179SLoGin fn cpu_pending(cpu_id: ProcessorId) -> &'static mut VecStatus { 61bacd691cSlogin unsafe { 62*e2841179SLoGin return &mut __CPU_PENDING.as_mut().unwrap()[cpu_id.data() as usize]; 63bacd691cSlogin } 64bacd691cSlogin } 6562e46139SGou Ngai 6662e46139SGou Ngai /// 软中断向量号码 6762e46139SGou Ngai #[allow(dead_code)] 6862e46139SGou Ngai #[repr(u8)] 69bacd691cSlogin #[derive(FromPrimitive, Copy, Clone, Debug, PartialEq, Eq)] 7062e46139SGou Ngai pub enum SoftirqNumber { 71bacd691cSlogin /// 时钟软中断信号 72bacd691cSlogin TIMER = 0, 7362e46139SGou Ngai VideoRefresh = 1, //帧缓冲区刷新软中断 7462e46139SGou Ngai } 7562e46139SGou Ngai 76bacd691cSlogin impl From<u64> for SoftirqNumber { 77bacd691cSlogin fn from(value: u64) -> Self { 78bacd691cSlogin return <Self as FromPrimitive>::from_u64(value).unwrap(); 7962e46139SGou Ngai } 8062e46139SGou Ngai } 8162e46139SGou Ngai 82bacd691cSlogin bitflags! { 83bacd691cSlogin #[derive(Default)] 84bacd691cSlogin pub struct VecStatus: u64 { 85bacd691cSlogin const TIMER = 1 << 0; 86bacd691cSlogin const VIDEO_REFRESH = 1 << 1; 87bacd691cSlogin } 88bacd691cSlogin } 89bacd691cSlogin 90bacd691cSlogin impl From<SoftirqNumber> for VecStatus { 91bacd691cSlogin fn from(value: SoftirqNumber) -> Self { 92bacd691cSlogin return Self::from_bits_truncate(1 << (value as u64)); 93bacd691cSlogin } 94bacd691cSlogin } 95bacd691cSlogin 96bacd691cSlogin pub trait SoftirqVec: Send + Sync + Debug { 97bacd691cSlogin fn run(&self); 98bacd691cSlogin } 99bacd691cSlogin 100bacd691cSlogin #[derive(Debug)] 10162e46139SGou Ngai pub struct Softirq { 102bacd691cSlogin table: RwLock<[Option<Arc<dyn SoftirqVec>>; MAX_SOFTIRQ_NUM as usize]>, 1030d6cf65aSLoGin /// 软中断嵌套层数(per cpu) 1040d6cf65aSLoGin cpu_running_count: PerCpuVar<AtomicI16>, 10562e46139SGou Ngai } 10662e46139SGou Ngai impl Softirq { 1070d6cf65aSLoGin /// 每个CPU最大嵌套的软中断数量 1080d6cf65aSLoGin const MAX_RUNNING_PER_CPU: i16 = 3; 109bacd691cSlogin fn new() -> Softirq { 110bacd691cSlogin let mut data: [MaybeUninit<Option<Arc<dyn SoftirqVec>>>; MAX_SOFTIRQ_NUM as usize] = 111bacd691cSlogin unsafe { MaybeUninit::uninit().assume_init() }; 112bacd691cSlogin 113bacd691cSlogin for i in 0..MAX_SOFTIRQ_NUM { 114bacd691cSlogin data[i as usize] = MaybeUninit::new(None); 11562e46139SGou Ngai } 11662e46139SGou Ngai 117bacd691cSlogin let data: [Option<Arc<dyn SoftirqVec>>; MAX_SOFTIRQ_NUM as usize] = unsafe { 118bacd691cSlogin mem::transmute::<_, [Option<Arc<dyn SoftirqVec>>; MAX_SOFTIRQ_NUM as usize]>(data) 119bacd691cSlogin }; 12062e46139SGou Ngai 1210d6cf65aSLoGin let mut percpu_count = Vec::with_capacity(PerCpu::MAX_CPU_NUM as usize); 1220d6cf65aSLoGin percpu_count.resize_with(PerCpu::MAX_CPU_NUM as usize, || AtomicI16::new(0)); 1230d6cf65aSLoGin let cpu_running_count = PerCpuVar::new(percpu_count).unwrap(); 1240d6cf65aSLoGin 125bacd691cSlogin return Softirq { 126bacd691cSlogin table: RwLock::new(data), 1270d6cf65aSLoGin cpu_running_count, 128bacd691cSlogin }; 12962e46139SGou Ngai } 13062e46139SGou Ngai 1310d6cf65aSLoGin fn cpu_running_count(&self) -> &PerCpuVar<AtomicI16> { 1320d6cf65aSLoGin return &self.cpu_running_count; 1330d6cf65aSLoGin } 1340d6cf65aSLoGin 13562e46139SGou Ngai /// @brief 注册软中断向量 136bacd691cSlogin /// 137bacd691cSlogin /// @param softirq_num 中断向量号 138bacd691cSlogin /// 139bacd691cSlogin /// @param hanlder 中断函数对应的结构体 14062e46139SGou Ngai pub fn register_softirq( 141bacd691cSlogin &self, 142bacd691cSlogin softirq_num: SoftirqNumber, 143bacd691cSlogin handler: Arc<dyn SoftirqVec>, 144bacd691cSlogin ) -> Result<i32, SystemError> { 145bacd691cSlogin // kdebug!("register_softirq softirq_num = {:?}", softirq_num as u64); 14662e46139SGou Ngai 147bacd691cSlogin // let self = &mut SOFTIRQ_VECTORS.lock(); 148bacd691cSlogin // 判断该软中断向量是否已经被注册 1490d6cf65aSLoGin let mut table_guard = self.table.write_irqsave(); 150bacd691cSlogin if table_guard[softirq_num as usize].is_some() { 151bacd691cSlogin // kdebug!("register_softirq failed"); 152bacd691cSlogin 153bacd691cSlogin return Err(SystemError::EINVAL); 15462e46139SGou Ngai } 155bacd691cSlogin table_guard[softirq_num as usize] = Some(handler); 156bacd691cSlogin drop(table_guard); 157bacd691cSlogin 158bacd691cSlogin // kdebug!( 159bacd691cSlogin // "register_softirq successfully, softirq_num = {:?}", 160bacd691cSlogin // softirq_num as u64 161bacd691cSlogin // ); 162bacd691cSlogin compiler_fence(Ordering::SeqCst); 163bacd691cSlogin return Ok(0); 16462e46139SGou Ngai } 16562e46139SGou Ngai 16662e46139SGou Ngai /// @brief 解注册软中断向量 167bacd691cSlogin /// 16862e46139SGou Ngai /// @param irq_num 中断向量号码 169*e2841179SLoGin #[allow(dead_code)] 170bacd691cSlogin pub fn unregister_softirq(&self, softirq_num: SoftirqNumber) { 171bacd691cSlogin // kdebug!("unregister_softirq softirq_num = {:?}", softirq_num as u64); 1720d6cf65aSLoGin let mut table_guard = self.table.write_irqsave(); 173bacd691cSlogin // 将软中断向量清空 174bacd691cSlogin table_guard[softirq_num as usize] = None; 175bacd691cSlogin drop(table_guard); 176bacd691cSlogin // 将对应位置的pending和runing都置0 177bacd691cSlogin // self.running.lock().set(VecStatus::from(softirq_num), false); 178bacd691cSlogin // 将对应CPU的pending置0 179bacd691cSlogin compiler_fence(Ordering::SeqCst); 180*e2841179SLoGin cpu_pending(smp_get_processor_id()).set(VecStatus::from(softirq_num), false); 181bacd691cSlogin compiler_fence(Ordering::SeqCst); 18262e46139SGou Ngai } 183bacd691cSlogin 184*e2841179SLoGin #[inline(never)] 185bacd691cSlogin pub fn do_softirq(&self) { 1860d6cf65aSLoGin if self.cpu_running_count().get().load(Ordering::SeqCst) >= Self::MAX_RUNNING_PER_CPU { 1870d6cf65aSLoGin // 当前CPU的软中断嵌套层数已经达到最大值,不再执行 1880d6cf65aSLoGin return; 1890d6cf65aSLoGin } 1900d6cf65aSLoGin // 创建一个RunningCountGuard,当退出作用域时,会自动将cpu_running_count减1 1910d6cf65aSLoGin let _count_guard = RunningCountGuard::new(self.cpu_running_count()); 1920d6cf65aSLoGin 193bacd691cSlogin // TODO pcb的flags未修改 194bacd691cSlogin let end = clock() + 500 * 2; 195bacd691cSlogin let cpu_id = smp_get_processor_id(); 196bacd691cSlogin let mut max_restart = MAX_SOFTIRQ_RESTART; 197bacd691cSlogin loop { 198bacd691cSlogin compiler_fence(Ordering::SeqCst); 199*e2841179SLoGin let pending = cpu_pending(cpu_id).bits; 200*e2841179SLoGin cpu_pending(cpu_id).bits = 0; 201bacd691cSlogin compiler_fence(Ordering::SeqCst); 202bacd691cSlogin 20346e234aeSLoGin unsafe { CurrentIrqArch::interrupt_enable() }; 204bacd691cSlogin if pending != 0 { 205bacd691cSlogin for i in 0..MAX_SOFTIRQ_NUM { 206bacd691cSlogin if pending & (1 << i) == 0 { 20762e46139SGou Ngai continue; 20862e46139SGou Ngai } 209bacd691cSlogin 2100d6cf65aSLoGin let table_guard = self.table.read_irqsave(); 211bacd691cSlogin let softirq_func = table_guard[i as usize].clone(); 212bacd691cSlogin drop(table_guard); 213bacd691cSlogin if softirq_func.is_none() { 214bacd691cSlogin continue; 215bacd691cSlogin } 216bacd691cSlogin 2171496ba7bSLoGin let prev_count: usize = ProcessManager::current_pcb().preempt_count(); 218bacd691cSlogin 219bacd691cSlogin softirq_func.as_ref().unwrap().run(); 2201496ba7bSLoGin if unlikely(prev_count != ProcessManager::current_pcb().preempt_count()) { 221bacd691cSlogin kdebug!( 222bacd691cSlogin "entered softirq {:?} with preempt_count {:?},exited with {:?}", 223bacd691cSlogin i, 224bacd691cSlogin prev_count, 2251496ba7bSLoGin ProcessManager::current_pcb().preempt_count() 226bacd691cSlogin ); 2271496ba7bSLoGin unsafe { ProcessManager::current_pcb().set_preempt_count(prev_count) }; 228bacd691cSlogin } 229bacd691cSlogin } 230bacd691cSlogin } 23146e234aeSLoGin unsafe { CurrentIrqArch::interrupt_disable() }; 232bacd691cSlogin max_restart -= 1; 233bacd691cSlogin compiler_fence(Ordering::SeqCst); 234*e2841179SLoGin if cpu_pending(cpu_id).is_empty() { 235bacd691cSlogin compiler_fence(Ordering::SeqCst); 236bacd691cSlogin if clock() < end && max_restart > 0 { 237bacd691cSlogin continue; 238bacd691cSlogin } else { 239bacd691cSlogin break; 240bacd691cSlogin } 241bacd691cSlogin } else { 242bacd691cSlogin // TODO:当有softirqd时 唤醒它 24362e46139SGou Ngai break; 24462e46139SGou Ngai } 24562e46139SGou Ngai } 24662e46139SGou Ngai } 24762e46139SGou Ngai 248bacd691cSlogin pub fn raise_softirq(&self, softirq_num: SoftirqNumber) { 2499550910aSChiichen let guard = unsafe { CurrentIrqArch::save_and_disable_irq() }; 250*e2841179SLoGin let processor_id = smp_get_processor_id(); 251bacd691cSlogin 252bacd691cSlogin cpu_pending(processor_id).insert(VecStatus::from(softirq_num)); 253bacd691cSlogin 254bacd691cSlogin compiler_fence(Ordering::SeqCst); 255bacd691cSlogin 2569550910aSChiichen drop(guard); 257bacd691cSlogin // kdebug!("raise_softirq exited"); 25862e46139SGou Ngai } 259*e2841179SLoGin 260*e2841179SLoGin #[allow(dead_code)] 2618fd71f27Shoumkh pub unsafe fn clear_softirq_pending(&self, softirq_num: SoftirqNumber) { 262bacd691cSlogin compiler_fence(Ordering::SeqCst); 263*e2841179SLoGin cpu_pending(smp_get_processor_id()).remove(VecStatus::from(softirq_num)); 264bacd691cSlogin compiler_fence(Ordering::SeqCst); 26562e46139SGou Ngai } 26662e46139SGou Ngai } 267bacd691cSlogin 2680d6cf65aSLoGin /// 当前CPU的软中断嵌套层数的计数器守卫 2690d6cf65aSLoGin /// 2700d6cf65aSLoGin /// 当进入作用域时,会自动将cpu_running_count加1, 2710d6cf65aSLoGin /// 当退出作用域时,会自动将cpu_running_count减1 2720d6cf65aSLoGin struct RunningCountGuard<'a> { 2730d6cf65aSLoGin cpu_running_count: &'a PerCpuVar<AtomicI16>, 2740d6cf65aSLoGin } 2750d6cf65aSLoGin 2760d6cf65aSLoGin impl<'a> RunningCountGuard<'a> { 2770d6cf65aSLoGin fn new(cpu_running_count: &'a PerCpuVar<AtomicI16>) -> RunningCountGuard { 2780d6cf65aSLoGin cpu_running_count.get().fetch_add(1, Ordering::SeqCst); 2790d6cf65aSLoGin return RunningCountGuard { cpu_running_count }; 2800d6cf65aSLoGin } 2810d6cf65aSLoGin } 2820d6cf65aSLoGin 2830d6cf65aSLoGin impl<'a> Drop for RunningCountGuard<'a> { 2840d6cf65aSLoGin fn drop(&mut self) { 2850d6cf65aSLoGin self.cpu_running_count.get().fetch_sub(1, Ordering::SeqCst); 2860d6cf65aSLoGin } 2870d6cf65aSLoGin } 2880d6cf65aSLoGin 289*e2841179SLoGin pub fn do_softirq() { 290bacd691cSlogin softirq_vectors().do_softirq(); 291bacd691cSlogin } 292