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