1 use core::ops::{BitXor, Deref, DerefMut}; 2 3 use alloc::{string::String, sync::Arc}; 4 5 use system_error::SystemError; 6 7 use crate::{ 8 driver::base::device::DeviceId, 9 exception::{ 10 irqchip::IrqChipSetMaskResult, 11 irqdesc::{irq_desc_manager, InnerIrqDesc, IrqAction}, 12 }, 13 libs::{cpumask::CpuMask, spinlock::SpinLockGuard}, 14 process::{kthread::KernelThreadMechanism, ProcessManager}, 15 smp::cpu::ProcessorId, 16 }; 17 18 use super::{ 19 dummychip::no_irq_chip, 20 irqchip::IrqChipFlags, 21 irqdata::{IrqData, IrqHandlerData, IrqLineStatus, IrqStatus}, 22 irqdesc::{InnerIrqAction, IrqDesc, IrqDescState, IrqHandleFlags, IrqHandler, IrqReturn}, 23 irqdomain::irq_domain_manager, 24 IrqNumber, 25 }; 26 27 lazy_static! { 28 /// 默认的中断亲和性 29 static ref IRQ_DEFAULT_AFFINITY: CpuMask = { 30 let mut mask = CpuMask::new(); 31 // 默认情况下,中断处理程序将在第一个处理器上运行 32 mask.set(ProcessorId::new(0), true); 33 mask 34 }; 35 } 36 37 pub fn irq_manager() -> &'static IrqManager { 38 &IrqManager 39 } 40 41 /// 中断管理器 42 pub struct IrqManager; 43 44 impl IrqManager { 45 pub const IRQ_RESEND: bool = true; 46 #[allow(dead_code)] 47 pub const IRQ_NORESEND: bool = false; 48 #[allow(dead_code)] 49 pub const IRQ_START_FORCE: bool = true; 50 pub const IRQ_START_COND: bool = false; 51 52 /// 在中断线上添加一个处理函数 53 /// 54 /// ## 参数 55 /// 56 /// - irq: 虚拟中断号(中断线号) 57 /// - name: 生成该中断的设备名称 58 /// - handler: 中断处理函数 59 /// - flags: 中断处理标志 60 /// - dev_id: 一个用于标识设备的cookie 61 pub fn request_irq( 62 &self, 63 irq: IrqNumber, 64 name: String, 65 handler: &'static dyn IrqHandler, 66 flags: IrqHandleFlags, 67 dev_id: Option<Arc<DeviceId>>, 68 ) -> Result<(), SystemError> { 69 return self.request_threaded_irq(irq, Some(handler), None, flags, name, dev_id); 70 } 71 72 /// 在中断线上添加一个处理函数(可以是线程化的中断) 73 /// 74 /// ## 参数 75 /// 76 /// - irq: 虚拟中断号 77 /// - handler: 当中断发生时将被调用的函数,是 78 /// 线程化中断的初级处理程序。如果handler为`None`并且thread_fn不为`None`, 79 /// 将安装默认的初级处理程序 80 /// - thread_fn: 在中断处理程序线程中调用的函数. 如果为`None`,则不会创建irq线程 81 /// - flags: 中断处理标志 82 /// - IRQF_SHARED: 中断是共享的 83 /// - IRQF_TRIGGER*: 指定中断触发方式 84 /// - IRQF_ONESHOT: 在thread_fn中运行时,中断线被遮蔽 85 /// - dev_name: 生成该中断的设备名称 86 /// - dev_id: 一个用于标识设备的cookie 87 /// 88 /// ## 说明 89 /// 90 /// 此调用分配中断资源并启用中断线和IRQ处理。 91 /// 从这一点开始,您的处理程序函数可能会被调用。 92 /// 因此,您必须确保首先初始化您的硬件, 93 /// 并确保以正确的顺序设置中断处理程序。 94 /// 95 /// 如果您想为您的设备设置线程化中断处理程序 96 /// 则需要提供@handler和@thread_fn。@handler仍然 97 /// 在硬中断上下文中调用,并且必须检查 98 /// 中断是否来自设备。如果是,它需要禁用设备上的中断 99 /// 并返回IRQ_WAKE_THREAD,这将唤醒处理程序线程并运行 100 /// @thread_fn。这种拆分处理程序设计是为了支持 101 /// 共享中断。 102 /// 103 /// dev_id必须是全局唯一的。通常使用设备数据结构的地址或者uuid 104 /// 作为cookie。由于处理程序接收这个值,因此使用它是有意义的。 105 /// 106 /// 如果您的中断是共享的,您必须传递一个非NULL的dev_id 107 /// 因为当释放中断时需要它。 108 pub fn request_threaded_irq( 109 &self, 110 irq: IrqNumber, 111 mut handler: Option<&'static dyn IrqHandler>, 112 thread_fn: Option<&'static dyn IrqHandler>, 113 flags: IrqHandleFlags, 114 dev_name: String, 115 dev_id: Option<Arc<DeviceId>>, 116 ) -> Result<(), SystemError> { 117 if irq == IrqNumber::IRQ_NOTCONNECTED { 118 return Err(SystemError::ENOTCONN); 119 } 120 121 // 逻辑检查:共享中断必须传入一个真正的设备ID, 122 // 否则后来我们将难以确定哪个中断是哪个(会搞乱中断释放逻辑等)。 123 // 此外,共享中断与禁用自动使能不相符。 共享中断可能在仍然禁用时请求它,然后永远等待中断。 124 // 另外,IRQF_COND_SUSPEND 仅适用于共享中断,并且它不能与 IRQF_NO_SUSPEND 同时设置。 125 126 if ((flags.contains(IrqHandleFlags::IRQF_SHARED)) && dev_id.is_none()) 127 || ((flags.contains(IrqHandleFlags::IRQF_SHARED)) 128 && (flags.contains(IrqHandleFlags::IRQF_NO_AUTOEN))) 129 || (!(flags.contains(IrqHandleFlags::IRQF_SHARED)) 130 && (flags.contains(IrqHandleFlags::IRQF_COND_SUSPEND))) 131 || ((flags.contains(IrqHandleFlags::IRQF_NO_SUSPEND)) 132 && (flags.contains(IrqHandleFlags::IRQF_COND_SUSPEND))) 133 { 134 return Err(SystemError::EINVAL); 135 } 136 let desc = irq_desc_manager().lookup(irq).ok_or(SystemError::EINVAL)?; 137 if !desc.can_request() { 138 kwarn!("desc {} can not request", desc.irq().data()); 139 return Err(SystemError::EINVAL); 140 } 141 142 if handler.is_none() { 143 if thread_fn.is_none() { 144 // 不允许中断处理函数和线程处理函数都为空 145 return Err(SystemError::EINVAL); 146 } 147 148 // 如果中断处理函数为空,线程处理函数不为空,则使用默认的中断处理函数 149 handler = Some(&DefaultPrimaryIrqHandler); 150 } 151 152 let irqaction = IrqAction::new(irq, dev_name, handler, thread_fn); 153 154 let mut action_guard = irqaction.inner(); 155 *action_guard.flags_mut() = flags; 156 *action_guard.dev_id_mut() = dev_id; 157 drop(action_guard); 158 159 return self.inner_setup_irq(irq, irqaction, desc); 160 } 161 162 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/kernel/irq/manage.c?r=&mo=59252&fi=2138#1497 163 #[inline(never)] 164 fn inner_setup_irq( 165 &self, 166 irq: IrqNumber, 167 action: Arc<IrqAction>, 168 desc: Arc<IrqDesc>, 169 ) -> Result<(), SystemError> { 170 // ==== 定义错误处理函数 ==== 171 let err_out_thread = 172 |e: SystemError, mut action_guard: SpinLockGuard<'_, InnerIrqAction>| -> SystemError { 173 if let Some(thread_pcb) = action_guard.thread() { 174 action_guard.set_thread(None); 175 KernelThreadMechanism::stop(&thread_pcb).ok(); 176 } 177 178 if let Some(secondary) = action_guard.secondary() { 179 let mut secondary_guard = secondary.inner(); 180 if let Some(thread_pcb) = secondary_guard.thread() { 181 secondary_guard.set_thread(None); 182 KernelThreadMechanism::stop(&thread_pcb).ok(); 183 } 184 } 185 return e; 186 }; 187 188 let err_out_bus_unlock = |e: SystemError, 189 desc: Arc<IrqDesc>, 190 req_mutex_guard: crate::libs::mutex::MutexGuard<'_, ()>, 191 action_guard: SpinLockGuard<'_, InnerIrqAction>| 192 -> SystemError { 193 desc.chip_bus_sync_unlock(); 194 drop(req_mutex_guard); 195 return err_out_thread(e, action_guard); 196 }; 197 198 let err_out_unlock = |e: SystemError, 199 desc_guard: SpinLockGuard<'_, InnerIrqDesc>, 200 desc: Arc<IrqDesc>, 201 req_mutex_guard: crate::libs::mutex::MutexGuard<'_, ()>, 202 action_guard: SpinLockGuard<'_, InnerIrqAction>| 203 -> SystemError { 204 drop(desc_guard); 205 return err_out_bus_unlock(e, desc, req_mutex_guard, action_guard); 206 }; 207 208 let err_out_mismatch = |old_action_guard: SpinLockGuard<'_, InnerIrqAction>, 209 desc_guard: SpinLockGuard<'_, InnerIrqDesc>, 210 action_guard: SpinLockGuard<'_, InnerIrqAction>, 211 desc: Arc<IrqDesc>, 212 req_mutex_guard: crate::libs::mutex::MutexGuard<'_, ()>| 213 -> SystemError { 214 if !action_guard 215 .flags() 216 .contains(IrqHandleFlags::IRQF_PROBE_SHARED) 217 { 218 kerror!("Flags mismatch for irq {} (name: {}, flags: {:?}). old action name: {}, old flags: {:?}", irq.data(), action_guard.name(), action_guard.flags(), old_action_guard.name(), old_action_guard.flags()); 219 } 220 return err_out_unlock( 221 SystemError::EBUSY, 222 desc_guard, 223 desc, 224 req_mutex_guard, 225 action_guard, 226 ); 227 }; 228 229 // ===== 代码开始 ===== 230 231 if Arc::ptr_eq( 232 &desc.irq_data().chip_info_read_irqsave().chip(), 233 &no_irq_chip(), 234 ) { 235 return Err(SystemError::ENOSYS); 236 } 237 238 let mut action_guard = action.inner(); 239 if !action_guard.flags().trigger_type_specified() { 240 // 如果没有指定触发类型,则使用默认的触发类型 241 action_guard 242 .flags_mut() 243 .insert_trigger_type(desc.irq_data().common_data().trigger_type()) 244 } 245 246 let nested = desc.nested_thread(); 247 248 if nested { 249 if action_guard.thread_fn().is_none() { 250 return Err(SystemError::EINVAL); 251 } 252 253 action_guard.set_handler(Some(&IrqNestedPrimaryHandler)); 254 } else { 255 if desc.can_thread() { 256 self.setup_forced_threading(action_guard.deref_mut())?; 257 } 258 } 259 260 // 如果具有中断线程处理程序,并且中断不是嵌套的,则设置中断线程 261 if action_guard.thread_fn().is_some() && !nested { 262 self.setup_irq_thread(irq, action_guard.deref(), false)?; 263 264 if let Some(secondary) = action_guard.secondary() { 265 let secondary_guard = secondary.inner(); 266 if let Err(e) = self.setup_irq_thread(irq, secondary_guard.deref(), true) { 267 return Err(err_out_thread(e, action_guard)); 268 } 269 } 270 } 271 272 // Drivers are often written to work w/o knowledge about the 273 // underlying irq chip implementation, so a request for a 274 // threaded irq without a primary hard irq context handler 275 // requires the ONESHOT flag to be set. Some irq chips like 276 // MSI based interrupts are per se one shot safe. Check the 277 // chip flags, so we can avoid the unmask dance at the end of 278 // the threaded handler for those. 279 280 if desc 281 .irq_data() 282 .chip_info_read_irqsave() 283 .chip() 284 .flags() 285 .contains(IrqChipFlags::IRQCHIP_ONESHOT_SAFE) 286 { 287 *action_guard.flags_mut() &= !IrqHandleFlags::IRQF_ONESHOT; 288 } 289 290 // Protects against a concurrent __free_irq() call which might wait 291 // for synchronize_hardirq() to complete without holding the optional 292 // chip bus lock and desc->lock. Also protects against handing out 293 // a recycled oneshot thread_mask bit while it's still in use by 294 // its previous owner. 295 let req_mutex_guard = desc.request_mutex_lock(); 296 297 // Acquire bus lock as the irq_request_resources() callback below 298 // might rely on the serialization or the magic power management 299 // functions which are abusing the irq_bus_lock() callback, 300 desc.chip_bus_lock(); 301 302 // 如果当前中断线上还没有irqaction, 则先为中断线申请资源 303 if desc.actions().is_empty() { 304 if let Err(e) = self.irq_request_resources(desc.clone()) { 305 kerror!( 306 "Failed to request resources for {} (irq {}) on irqchip {}, error {:?}", 307 action_guard.name(), 308 irq.data(), 309 desc.irq_data().chip_info_read_irqsave().chip().name(), 310 e 311 ); 312 return Err(err_out_bus_unlock( 313 e, 314 desc.clone(), 315 req_mutex_guard, 316 action_guard, 317 )); 318 } 319 } 320 321 let mut desc_inner_guard: SpinLockGuard<'_, InnerIrqDesc> = desc.inner(); 322 323 // 标记当前irq是否是共享的 324 let mut irq_shared = false; 325 if desc_inner_guard.actions().is_empty() == false { 326 // 除非双方都同意并且是相同类型(级别、边沿、极性),否则不能共享中断。 327 // 因此,两个标志字段都必须设置IRQF_SHARED,并且设置触发类型的位必须匹配。 328 // 另外,所有各方都必须就ONESHOT达成一致。 329 // NMI用途的中断线不能共享。 330 if desc_inner_guard 331 .internal_state() 332 .contains(IrqDescState::IRQS_NMI) 333 { 334 kerror!( 335 "Invalid attempt to share NMI for {} (irq {}) on irqchip {}", 336 action_guard.name(), 337 irq.data(), 338 desc_inner_guard 339 .irq_data() 340 .chip_info_read_irqsave() 341 .chip() 342 .name() 343 ); 344 return Err(err_out_unlock( 345 SystemError::EINVAL, 346 desc_inner_guard, 347 desc.clone(), 348 req_mutex_guard, 349 action_guard, 350 )); 351 } 352 353 let irq_data = desc_inner_guard.irq_data(); 354 355 let old_trigger_type: super::irqdata::IrqLineStatus; 356 let status = irq_data.common_data().status(); 357 if status.trigger_type_was_set() { 358 old_trigger_type = status.trigger_type(); 359 } else { 360 old_trigger_type = action_guard.flags().trigger_type(); 361 irq_data.common_data().set_trigger_type(old_trigger_type); 362 } 363 364 let old = &desc_inner_guard.actions()[0].clone(); 365 let old_guard = old.inner(); 366 367 if ((old_guard 368 .flags() 369 .intersection(*action_guard.flags()) 370 .contains(IrqHandleFlags::IRQF_SHARED)) 371 == false) 372 || (old_trigger_type != (action_guard.flags().trigger_type())) 373 || ((old_guard.flags().bitxor(*action_guard.flags())) 374 .contains(IrqHandleFlags::IRQF_ONESHOT)) 375 { 376 return Err(err_out_mismatch( 377 old_guard, 378 desc_inner_guard, 379 action_guard, 380 desc.clone(), 381 req_mutex_guard, 382 )); 383 } 384 385 // all handlers must agree on per-cpuness 386 if *old_guard.flags() & IrqHandleFlags::IRQF_PERCPU 387 != *action_guard.flags() & IrqHandleFlags::IRQF_PERCPU 388 { 389 return Err(err_out_mismatch( 390 old_guard, 391 desc_inner_guard, 392 action_guard, 393 desc.clone(), 394 req_mutex_guard, 395 )); 396 } 397 398 irq_shared = true; 399 } 400 401 if action_guard.flags().contains(IrqHandleFlags::IRQF_ONESHOT) { 402 // todo: oneshot 403 } else if action_guard.handler().is_some_and(|h| { 404 h.type_id() == (&DefaultPrimaryIrqHandler as &dyn IrqHandler).type_id() 405 }) && desc_inner_guard 406 .irq_data() 407 .chip_info_read_irqsave() 408 .chip() 409 .flags() 410 .contains(IrqChipFlags::IRQCHIP_ONESHOT_SAFE) 411 == false 412 { 413 // 请求中断时 hander = NULL,因此我们为其使用默认的主处理程序。 414 // 但它没有设置ONESHOT标志。与电平触发中断结合时, 415 // 这是致命的,因为默认的主处理程序只是唤醒线程,然后重新启用 irq 线路, 416 // 但设备仍然保持电平中断生效。周而复始.... 417 // 虽然这对于边缘类型中断来说可行,但我们为了安全起见,不加条件地拒绝, 418 // 因为我们不能确定这个中断实际上具有什么类型。 419 // 由于底层芯片实现可能会覆盖它们,所以类型标志并不可靠. 420 421 kerror!( 422 "Requesting irq {} without a handler, and ONESHOT flags not set for irqaction: {}", 423 irq.data(), 424 action_guard.name() 425 ); 426 return Err(err_out_unlock( 427 SystemError::EINVAL, 428 desc_inner_guard, 429 desc.clone(), 430 req_mutex_guard, 431 action_guard, 432 )); 433 } 434 435 // 第一次在当前irqdesc上注册中断处理函数 436 if !irq_shared { 437 // 设置中断触发方式 438 if action_guard.flags().trigger_type_specified() { 439 let trigger_type = action_guard.flags().trigger_type(); 440 if let Err(e) = 441 self.do_set_irq_trigger(desc.clone(), &mut desc_inner_guard, trigger_type) 442 { 443 return Err(err_out_unlock( 444 e, 445 desc_inner_guard, 446 desc.clone(), 447 req_mutex_guard, 448 action_guard, 449 )); 450 } 451 } 452 453 // 激活中断。这种激活必须独立于IRQ_NOAUTOEN进行*desc_inner_guard.internal_state_mut() |= IrqDescState::IRQS_NOREQUEST;uest. 454 if let Err(e) = self.irq_activate(desc.clone(), &mut desc_inner_guard) { 455 return Err(err_out_unlock( 456 e, 457 desc_inner_guard, 458 desc.clone(), 459 req_mutex_guard, 460 action_guard, 461 )); 462 } 463 464 *desc_inner_guard.internal_state_mut() &= !(IrqDescState::IRQS_AUTODETECT 465 | IrqDescState::IRQS_SPURIOUS_DISABLED 466 | IrqDescState::IRQS_ONESHOT 467 | IrqDescState::IRQS_WAITING); 468 desc_inner_guard 469 .common_data() 470 .clear_status(IrqStatus::IRQD_IRQ_INPROGRESS); 471 472 if action_guard.flags().contains(IrqHandleFlags::IRQF_PERCPU) { 473 desc_inner_guard 474 .common_data() 475 .insert_status(IrqStatus::IRQD_PER_CPU); 476 desc_inner_guard.line_status_set_per_cpu(); 477 478 if action_guard.flags().contains(IrqHandleFlags::IRQF_NO_DEBUG) { 479 desc_inner_guard.line_status_set_no_debug(); 480 } 481 } 482 483 if action_guard.flags().contains(IrqHandleFlags::IRQF_ONESHOT) { 484 *desc_inner_guard.internal_state_mut() |= IrqDescState::IRQS_ONESHOT; 485 } 486 487 // 如果有要求的话,则忽略IRQ的均衡。 488 if action_guard 489 .flags() 490 .contains(IrqHandleFlags::IRQF_NOBALANCING) 491 { 492 todo!("IRQF_NO_BALANCING"); 493 } 494 495 if !action_guard 496 .flags() 497 .contains(IrqHandleFlags::IRQF_NO_AUTOEN) 498 && desc_inner_guard.can_autoenable() 499 { 500 // 如果没有设置IRQF_NOAUTOEN,则自动使能中断 501 self.irq_startup( 502 desc.clone(), 503 &mut desc_inner_guard, 504 Self::IRQ_RESEND, 505 Self::IRQ_START_COND, 506 ) 507 .ok(); 508 } else { 509 // 共享中断与禁用自动使能不太兼容。 510 // 共享中断可能在它仍然被禁用时请求它,然后永远等待中断。 511 512 static mut WARNED: bool = false; 513 if action_guard.flags().contains(IrqHandleFlags::IRQF_SHARED) { 514 if unsafe { !WARNED } { 515 kwarn!( 516 "Shared interrupt {} for {} requested but not auto enabled", 517 irq.data(), 518 action_guard.name() 519 ); 520 unsafe { WARNED = true }; 521 } 522 } 523 524 desc_inner_guard.set_depth(1); 525 } 526 } else if action_guard.flags().trigger_type_specified() { 527 let new_trigger_type = action_guard.flags().trigger_type(); 528 let old_trigger_type = desc_inner_guard.common_data().trigger_type(); 529 if new_trigger_type != old_trigger_type { 530 kwarn!("Irq {} uses trigger type: {old_trigger_type:?}, but requested trigger type: {new_trigger_type:?}.", irq.data()); 531 } 532 } 533 534 // 在队列末尾添加新的irqaction 535 desc_inner_guard.add_action(action.clone()); 536 537 // 检查我们是否曾经通过虚构的中断处理程序禁用过irq。重新启用它并再给它一次机会。 538 if irq_shared 539 && desc_inner_guard 540 .internal_state() 541 .contains(IrqDescState::IRQS_SPURIOUS_DISABLED) 542 { 543 desc_inner_guard 544 .internal_state_mut() 545 .remove(IrqDescState::IRQS_SPURIOUS_DISABLED); 546 self.do_enable_irq(desc.clone(), &mut desc_inner_guard).ok(); 547 } 548 549 drop(desc_inner_guard); 550 desc.chip_bus_sync_unlock(); 551 drop(req_mutex_guard); 552 553 drop(action_guard); 554 self.wake_up_and_wait_for_irq_thread_ready(&desc, Some(action.clone())); 555 self.wake_up_and_wait_for_irq_thread_ready(&desc, action.inner().secondary()); 556 return Ok(()); 557 } 558 559 /// 唤醒中断线程并等待中断线程准备好 560 /// 561 /// ## 参数 562 /// 563 /// - desc: 中断描述符 564 /// - action: 要唤醒的中断处理函数 565 /// 566 /// ## 锁 567 /// 568 /// 进入当前函数时,`action`的锁需要被释放 569 fn wake_up_and_wait_for_irq_thread_ready( 570 &self, 571 desc: &Arc<IrqDesc>, 572 action: Option<Arc<IrqAction>>, 573 ) { 574 if action.is_none() { 575 return; 576 } 577 578 let action = action.unwrap(); 579 580 let action_guard = action.inner(); 581 if action_guard.thread().is_none() { 582 return; 583 } 584 585 ProcessManager::wakeup(&action_guard.thread().unwrap()).ok(); 586 drop(action_guard); 587 action 588 .thread_completion() 589 .wait_for_completion() 590 .map_err(|e| { 591 kwarn!( 592 "Failed to wait for irq thread ready for {} (irq {:?}), error {:?}", 593 action.inner().name(), 594 desc.irq_data().irq(), 595 e 596 ); 597 }) 598 .ok(); 599 } 600 601 pub(super) fn irq_activate( 602 &self, 603 _desc: Arc<IrqDesc>, 604 desc_inner_guard: &mut SpinLockGuard<'_, InnerIrqDesc>, 605 ) -> Result<(), SystemError> { 606 let irq_data = desc_inner_guard.irq_data(); 607 608 if !desc_inner_guard.common_data().status().affinity_managed() { 609 return irq_domain_manager().activate_irq(irq_data, false); 610 } 611 612 return Ok(()); 613 } 614 615 /// 设置CPU亲和性并开启中断 616 pub(super) fn irq_startup( 617 &self, 618 desc: Arc<IrqDesc>, 619 desc_inner_guard: &mut SpinLockGuard<'_, InnerIrqDesc>, 620 resend: bool, 621 force: bool, 622 ) -> Result<(), SystemError> { 623 let mut ret = Ok(()); 624 let irq_data = desc_inner_guard.irq_data().clone(); 625 let affinity = desc_inner_guard.common_data().affinity(); 626 desc_inner_guard.set_depth(0); 627 628 if desc_inner_guard.common_data().status().started() { 629 self.irq_enable(desc_inner_guard); 630 } else { 631 match self.__irq_startup_managed(desc_inner_guard, &affinity, force) { 632 IrqStartupResult::Normal => { 633 if irq_data 634 .chip_info_read_irqsave() 635 .chip() 636 .flags() 637 .contains(IrqChipFlags::IRQCHIP_AFFINITY_PRE_STARTUP) 638 { 639 self.irq_setup_affinity(&desc, desc_inner_guard).ok(); 640 } 641 642 ret = self.__irq_startup(desc_inner_guard); 643 644 if !irq_data 645 .chip_info_read_irqsave() 646 .chip() 647 .flags() 648 .contains(IrqChipFlags::IRQCHIP_AFFINITY_PRE_STARTUP) 649 { 650 self.irq_setup_affinity(&desc, desc_inner_guard).ok(); 651 } 652 } 653 IrqStartupResult::Managed => { 654 self.irq_do_set_affinity(&irq_data, &desc_inner_guard, &affinity, false) 655 .ok(); 656 ret = self.__irq_startup(desc_inner_guard); 657 } 658 IrqStartupResult::Abort => { 659 desc_inner_guard 660 .common_data() 661 .insert_status(IrqStatus::IRQD_MANAGED_SHUTDOWN); 662 return Ok(()); 663 } 664 } 665 } 666 667 if resend { 668 if let Err(e) = self.irq_check_and_resend(desc_inner_guard, false) { 669 kerror!( 670 "Failed to check and resend irq {}, error {:?}", 671 irq_data.irq().data(), 672 e 673 ); 674 } 675 } 676 677 return ret; 678 } 679 680 pub fn irq_enable(&self, desc_inner_guard: &SpinLockGuard<'_, InnerIrqDesc>) { 681 let common_data = desc_inner_guard.common_data(); 682 if !common_data.status().disabled() { 683 self.unmask_irq(desc_inner_guard); 684 } else { 685 common_data.clear_disabled(); 686 687 let chip = desc_inner_guard.irq_data().chip_info_read_irqsave().chip(); 688 689 if let Err(e) = chip.irq_enable(&desc_inner_guard.irq_data()) { 690 if e == SystemError::ENOSYS { 691 self.unmask_irq(desc_inner_guard); 692 } 693 kerror!( 694 "Failed to enable irq {} (name: {:?}), error {:?}", 695 desc_inner_guard.irq_data().irq().data(), 696 desc_inner_guard.name(), 697 e 698 ); 699 } else { 700 common_data.clear_masked(); 701 } 702 } 703 } 704 705 /// 自动设置中断的CPU亲和性 706 /// 707 /// 708 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/kernel/irq/manage.c#589 709 pub fn irq_setup_affinity( 710 &self, 711 _desc: &Arc<IrqDesc>, 712 desc_inner_guard: &mut SpinLockGuard<'_, InnerIrqDesc>, 713 ) -> Result<(), SystemError> { 714 let common_data = desc_inner_guard.common_data(); 715 if !desc_inner_guard.can_set_affinity() { 716 return Ok(()); 717 } 718 719 let mut to_set = IRQ_DEFAULT_AFFINITY.clone(); 720 if common_data.status().affinity_managed() 721 || common_data.status().contains(IrqStatus::IRQD_AFFINITY_SET) 722 { 723 // FIXME: 要判断affinity跟已上线的CPU是否有交集 724 725 let irq_aff = common_data.affinity(); 726 if irq_aff.is_empty() { 727 common_data.clear_status(IrqStatus::IRQD_AFFINITY_SET); 728 } else { 729 to_set = irq_aff; 730 } 731 } 732 733 // FIXME: 求to_set和在线CPU的交集 734 735 return self.irq_do_set_affinity( 736 desc_inner_guard.irq_data(), 737 &desc_inner_guard, 738 &to_set, 739 false, 740 ); 741 } 742 743 pub fn irq_do_set_affinity( 744 &self, 745 irq_data: &Arc<IrqData>, 746 desc_inner_guard: &SpinLockGuard<'_, InnerIrqDesc>, 747 cpumask: &CpuMask, 748 force: bool, 749 ) -> Result<(), SystemError> { 750 let chip = irq_data.chip_info_read_irqsave().chip(); 751 if !chip.can_set_affinity() { 752 return Err(SystemError::EINVAL); 753 } 754 755 // todo: 处理CPU中断隔离相关的逻辑 756 757 let common_data = desc_inner_guard.common_data(); 758 let r; 759 if !force && !cpumask.is_empty() { 760 r = chip.irq_set_affinity(irq_data, &cpumask, force); 761 } else if force { 762 r = chip.irq_set_affinity(irq_data, &cpumask, force); 763 } else { 764 return Err(SystemError::EINVAL); 765 } 766 767 let mut ret = Ok(()); 768 if let Ok(rs) = r { 769 match rs { 770 IrqChipSetMaskResult::SetMaskOk | IrqChipSetMaskResult::SetMaskOkDone => { 771 common_data.set_affinity(cpumask.clone()); 772 } 773 IrqChipSetMaskResult::SetMaskOkNoChange => { 774 775 // irq_validate_effective_affinity(data); 776 // irq_set_thread_affinity(desc); 777 } 778 } 779 } else { 780 ret = Err(r.unwrap_err()); 781 } 782 783 return ret; 784 } 785 786 fn __irq_startup( 787 &self, 788 desc_inner_guard: &SpinLockGuard<'_, InnerIrqDesc>, 789 ) -> Result<(), SystemError> { 790 let common_data = desc_inner_guard.common_data(); 791 792 if let Err(e) = desc_inner_guard 793 .irq_data() 794 .chip_info_read_irqsave() 795 .chip() 796 .irq_startup(desc_inner_guard.irq_data()) 797 { 798 if e == SystemError::ENOSYS { 799 self.irq_enable(desc_inner_guard); 800 } else { 801 return Err(e); 802 } 803 } else { 804 common_data.clear_disabled(); 805 common_data.clear_masked(); 806 } 807 808 common_data.set_started(); 809 810 return Ok(()); 811 } 812 813 fn __irq_startup_managed( 814 &self, 815 desc_inner_guard: &SpinLockGuard<'_, InnerIrqDesc>, 816 _affinity: &CpuMask, 817 _force: bool, 818 ) -> IrqStartupResult { 819 let irq_data = desc_inner_guard.irq_data(); 820 let common_data = desc_inner_guard.common_data(); 821 822 if !common_data.status().affinity_managed() { 823 return IrqStartupResult::Normal; 824 } 825 826 common_data.clear_managed_shutdown(); 827 828 /* 829 - 检查Affinity掩码是否包括所有的在线CPU。如果是,这意味着有代码试图在管理的中断上使用enable_irq(), 830 这可能是非法的。在这种情况下,如果force不是真值,函数会返回IRQ_STARTUP_ABORT,表示中断处理应该被放弃。 831 - 如果Affinity掩码中没有任何在线的CPU,那么中断请求是不可用的,因为没有任何CPU可以处理它。 832 在这种情况下,如果force不是真值,函数同样会返回IRQ_STARTUP_ABORT。 833 - 如果以上条件都不满足,尝试激活中断,并将其设置为管理模式。这是通过调用 `irq_domain_manager().activate_irq()` 函数来实现的。 834 如果这个调用失败,表示有保留的资源无法访问,函数会返回IRQ_STARTUP_ABORT。 835 - 如果一切顺利,函数会返回IRQ_STARTUP_MANAGED,表示中断已经被成功管理并激活。 836 */ 837 838 // if (cpumask_any_and(aff, cpu_online_mask) >= nr_cpu_ids) { 839 // /* 840 // * Catch code which fiddles with enable_irq() on a managed 841 // * and potentially shutdown IRQ. Chained interrupt 842 // * installment or irq auto probing should not happen on 843 // * managed irqs either. 844 // */ 845 // if (WARN_ON_ONCE(force)) 846 // return IRQ_STARTUP_ABORT; 847 // /* 848 // * The interrupt was requested, but there is no online CPU 849 // * in it's affinity mask. Put it into managed shutdown 850 // * state and let the cpu hotplug mechanism start it up once 851 // * a CPU in the mask becomes available. 852 // */ 853 // return IRQ_STARTUP_ABORT; 854 // } 855 856 let r = irq_domain_manager().activate_irq(irq_data, false); 857 if r.is_err() { 858 return IrqStartupResult::Abort; 859 } 860 861 return IrqStartupResult::Managed; 862 } 863 864 pub fn do_enable_irq( 865 &self, 866 _desc: Arc<IrqDesc>, 867 _desc_inner_guard: &mut SpinLockGuard<'_, InnerIrqDesc>, 868 ) -> Result<(), SystemError> { 869 // https://code.dragonos.org.cn/xref/linux-6.1.9/kernel/irq/manage.c?r=&mo=59252&fi=2138#776 870 todo!("do_enable_irq") 871 } 872 873 #[inline(never)] 874 pub fn do_set_irq_trigger( 875 &self, 876 _desc: Arc<IrqDesc>, 877 desc_inner_guard: &mut SpinLockGuard<'_, InnerIrqDesc>, 878 mut trigger_type: IrqLineStatus, 879 ) -> Result<(), SystemError> { 880 let chip = desc_inner_guard.irq_data().chip_info_read_irqsave().chip(); 881 let mut to_unmask = false; 882 883 if !chip.can_set_flow_type() { 884 // kdebug!( 885 // "No set_irq_type function for irq {}, chip {}", 886 // desc_inner_guard.irq_data().irq().data(), 887 // chip.name() 888 // ); 889 return Ok(()); 890 } 891 892 if chip.flags().contains(IrqChipFlags::IRQCHIP_SET_TYPE_MASKED) { 893 if desc_inner_guard.common_data().status().masked() == false { 894 self.mask_irq(desc_inner_guard.irq_data()); 895 } 896 if desc_inner_guard.common_data().status().disabled() == false { 897 to_unmask = true; 898 } 899 } 900 901 trigger_type &= IrqLineStatus::IRQ_TYPE_SENSE_MASK; 902 903 let r = chip.irq_set_type(desc_inner_guard.irq_data(), trigger_type); 904 let ret; 905 if let Ok(rs) = r { 906 match rs { 907 IrqChipSetMaskResult::SetMaskOk | IrqChipSetMaskResult::SetMaskOkDone => { 908 let common_data = desc_inner_guard.common_data(); 909 common_data.clear_status(IrqStatus::IRQD_TRIGGER_MASK); 910 let mut irqstatus = IrqStatus::empty(); 911 irqstatus.set_trigger_type(trigger_type); 912 common_data.insert_status(irqstatus); 913 } 914 IrqChipSetMaskResult::SetMaskOkNoChange => { 915 let flags = desc_inner_guard.common_data().trigger_type(); 916 desc_inner_guard.set_trigger_type(flags); 917 desc_inner_guard 918 .common_data() 919 .clear_status(IrqStatus::IRQD_LEVEL); 920 desc_inner_guard.clear_level(); 921 922 if (flags & IrqLineStatus::IRQ_TYPE_LEVEL_MASK).is_empty() == false { 923 desc_inner_guard.set_level(); 924 desc_inner_guard 925 .common_data() 926 .insert_status(IrqStatus::IRQD_LEVEL); 927 } 928 } 929 } 930 931 ret = Ok(()); 932 } else { 933 kerror!( 934 "Failed to set irq {} trigger type to {:?} on irqchip {}, error {:?}", 935 desc_inner_guard.irq_data().irq().data(), 936 trigger_type, 937 chip.name(), 938 r 939 ); 940 941 ret = Err(r.unwrap_err()); 942 } 943 944 if to_unmask { 945 self.unmask_irq(desc_inner_guard); 946 } 947 return ret; 948 } 949 950 fn irq_request_resources(&self, desc: Arc<IrqDesc>) -> Result<(), SystemError> { 951 let irq_data = desc.irq_data(); 952 let irq_chip = irq_data.chip_info_read_irqsave().chip(); 953 irq_chip.irq_request_resources(&irq_data) 954 } 955 956 /// 参考 https://code.dragonos.org.cn/xref/linux-6.1.9/kernel/irq/manage.c?r=&mo=59252&fi=2138#1448 957 fn setup_irq_thread( 958 &self, 959 _irq: IrqNumber, 960 _action: &InnerIrqAction, 961 _secondary: bool, 962 ) -> Result<(), SystemError> { 963 // if secondary { 964 // KernelThreadMechanism::create(func, name) 965 // } 966 967 todo!("setup_irq_thread") 968 } 969 970 fn setup_forced_threading(&self, _action: &mut InnerIrqAction) -> Result<(), SystemError> { 971 // todo: 处理强制线程化的逻辑,参考linux的`irq_setup_forced_threading()` 972 return Ok(()); 973 } 974 975 pub fn irq_clear_status_flags( 976 &self, 977 irq: IrqNumber, 978 status: IrqLineStatus, 979 ) -> Result<(), SystemError> { 980 let desc = irq_desc_manager().lookup(irq).ok_or(SystemError::EINVAL)?; 981 desc.modify_status(status, IrqLineStatus::empty()); 982 return Ok(()); 983 } 984 985 /// 屏蔽中断 986 pub(super) fn mask_irq(&self, irq_data: &Arc<IrqData>) { 987 if irq_data.common_data().status().masked() { 988 return; 989 } 990 991 let chip = irq_data.chip_info_read_irqsave().chip(); 992 let r = chip.irq_mask(irq_data); 993 994 if r.is_ok() { 995 irq_data.common_data().set_masked(); 996 } 997 } 998 999 /// 解除屏蔽中断 1000 pub(super) fn unmask_irq(&self, desc_inner_guard: &SpinLockGuard<'_, InnerIrqDesc>) { 1001 if desc_inner_guard.common_data().status().masked() == false { 1002 return; 1003 } 1004 1005 let r = desc_inner_guard 1006 .irq_data() 1007 .chip_info_read_irqsave() 1008 .chip() 1009 .irq_unmask(&desc_inner_guard.irq_data()); 1010 1011 if let Err(e) = r { 1012 if e != SystemError::ENOSYS { 1013 kerror!( 1014 "Failed to unmask irq {} on irqchip {}, error {:?}", 1015 desc_inner_guard.irq_data().irq().data(), 1016 desc_inner_guard 1017 .irq_data() 1018 .chip_info_read_irqsave() 1019 .chip() 1020 .name(), 1021 e 1022 ); 1023 } 1024 } else { 1025 desc_inner_guard 1026 .common_data() 1027 .clear_status(IrqStatus::IRQD_IRQ_MASKED); 1028 } 1029 } 1030 1031 /// 释放使用request_irq分配的中断 1032 /// 1033 /// ## 参数 1034 /// 1035 /// - irq: 要释放的中断线 1036 /// - dev_id: 要释放的设备身份 1037 /// 1038 /// ## 返回 1039 /// 1040 /// 返回传递给request_irq的devname参数 1041 /// 1042 /// ## 说明 1043 /// 1044 /// 移除一个中断处理程序。处理程序被移除,如果该中断线不再被任何驱动程序使用,则会被禁用。 1045 /// 1046 /// 在共享IRQ的情况下,调用者必须确保在调用此功能之前,它在所驱动的卡上禁用了中断。 1047 /// 1048 /// ## 注意 1049 /// 1050 /// 此函数不可以在中断上下文中调用。 1051 pub fn free_irq(&self, _irq: IrqNumber, _dev_id: Option<Arc<DeviceId>>) { 1052 kwarn!("Unimplemented free_irq"); 1053 } 1054 } 1055 1056 enum IrqStartupResult { 1057 Normal, 1058 Managed, 1059 Abort, 1060 } 1061 /// 默认的初级中断处理函数 1062 /// 1063 /// 该处理函数仅仅返回`WakeThread`,即唤醒中断线程 1064 #[derive(Debug)] 1065 struct DefaultPrimaryIrqHandler; 1066 1067 impl IrqHandler for DefaultPrimaryIrqHandler { 1068 fn handle( 1069 &self, 1070 _irq: IrqNumber, 1071 _static_data: Option<&dyn IrqHandlerData>, 1072 _dynamic_data: Option<Arc<dyn IrqHandlerData>>, 1073 ) -> Result<IrqReturn, SystemError> { 1074 return Ok(IrqReturn::WakeThread); 1075 } 1076 } 1077 1078 /// Primary handler for nested threaded interrupts. 1079 /// Should never be called. 1080 #[derive(Debug)] 1081 struct IrqNestedPrimaryHandler; 1082 1083 impl IrqHandler for IrqNestedPrimaryHandler { 1084 fn handle( 1085 &self, 1086 irq: IrqNumber, 1087 _static_data: Option<&dyn IrqHandlerData>, 1088 _dynamic_data: Option<Arc<dyn IrqHandlerData>>, 1089 ) -> Result<IrqReturn, SystemError> { 1090 kwarn!("Primary handler called for nested irq {}", irq.data()); 1091 return Ok(IrqReturn::NotHandled); 1092 } 1093 } 1094