Linux的中断处理是驱动中比较重要的一部分内容,要清楚具体的实现才能更好的理解而不是靠记住别人理解后总结的规律,所以今天就打算从从源码来学习一下Linux内核对于中断处理过程,设计中断子系统的初始化的内容比较少,后续有空了在去深入的看看。通过追踪Linux中断的响应过程就能知道中断的具体处理细节。

中断响应过程

网上总结中断的执行过程的大致流程是:

  1. 保存中断发生时CPSR寄存器内容到SPSR_irq寄存器中
  2. 修改CPSR寄存器,让CPU进入处理器模式(processor mode)中的IRQ模式,即修改CPSR寄存器中的M域设置为IRQ Mode。
  3. 硬件自动关闭中断IRQ或FIQ,即CPSR中的IRQ位或FIQ位置1。
  4. 保存返回地址到LR_irq寄存器中。
  5. 硬件自动调转到中断向量表的IRQ向量。,从此处开始进入软件领

Linux的源码中定义了一段代码如下,就是其中断向量表,然后通过连接脚本和处理并在启动过程中将其放到内存的特定地址上去并通过CP13寄存器指示。

  1. .section .vectors, "ax", %progbits__vectors_start:
  2. W(b) vector_rst
  3. W(b) vector_und
  4. W(ldr) pc, __vectors_start + 0x1000
  5. W(b) vector_pabt
  6. W(b) vector_dabt
  7. W(b) vector_addrexcptn
  8. W(b) vector_irq
  9. W(b) vector_fiq
  10.  
  11. /*
  12. * Interrupt dispatcher
  13. */
  14. @------------------------------------------------vector_stub宏定义了vector_irq
  15. vector_stub irq, IRQ_MODE, 4
  16.  
  17. .long __irq_usr @ 0 (USR_26 / USR_32)
  18. .long __irq_invalid @ 1 (FIQ_26 / FIQ_32)
  19. .long __irq_invalid @ 2 (IRQ_26 / IRQ_32)
  20. @----------------------------svc模式数值是0b10011,与上0xf后就是3
  21. .long __irq_svc @ 3 (SVC_26 / SVC_32)
  22. .long __irq_invalid @ 4
  23. .long __irq_invalid @ 5
  24. .long __irq_invalid @ 6
  25. .long __irq_invalid @ 7
  26. .long __irq_invalid @ 8
  27. .long __irq_invalid @ 9
  28. .long __irq_invalid @ a
  29. .long __irq_invalid @ b
  30. .long __irq_invalid @ c
  31. .long __irq_invalid @ d
  32. .long __irq_invalid @ e
  33. .long __irq_invalid @ f   
  34.  
  35. @------------------------------------vector_stub宏定义
  36. .macro vector_stub, name, mode, correction=0
  37. .align 5
  38. vector_\name:
  39. .if \correction
  40. sub lr, lr, #\correction
  41. .endif
  42.  
  43. @
  44. @ Save r0, lr_<exception> (parent PC) and spsr_<exception>
  45. @ (parent CPSR)
  46. @
  47. stmia sp, {r0, lr} @ save r0, lr
  48. mrs lr, spsr
  49. str lr, [sp, #8] @ save spsr
  50.  
  51. @
  52. @ Prepare for SVC32 mode. IRQs remain disabled.
  53. @
  54. mrs r0, cpsr
  55. @修改CPSR寄存器的控制域为SVC模式,为了使中断处理在SVC模式下执行。
  56. eor r0, r0, #(\mode ^ SVC_MODE | PSR_ISETSTATE)
  57. msr spsr_cxsf, r0
  58.  
  59. @
  60. @ the branch table must immediately follow this code
  61. @
  62. @低4位反映了进入中断前CPU的运行模式,9USR3SVC模式。
  63. and lr, lr, #0x0f
  64. THUMB( adr r0, 1f )
  65. @根据中断发生点所在的模式,给lr寄存器赋值,__irq_usr或者__irq_svc标签处。
  66. THUMB( ldr lr, [r0, lr, lsl #2] )
  67. mov r0, spk
  68. @得到的lr就是".long __irq_svc"
  69. ARM( ldr lr, [pc, lr, lsl #2] )
  70. @把lr的值赋给pc指针,跳转到__irq_usr或者__irq_svc
  71. movs pc, lr @ branch to handler in SVC mode
  72. ENDPROC(vector_\name)

这里注意汇编宏的展开操作,理解了这一部分就能明白,24行处就是定义了vector_irq这个中断服务函数这个函数内读取了一些寄存器,然后根据进入中断前的CPU状态跳转到__irq_usr或者 __irq_svc。这里暂时分析在内核态时的情况所以是跳转到__irq_svc这个函数这一部分是中断上下文直接调用的所以他也就还在中断上下文中执行,接着看__irq_svc。

  1. __irq_svc:
  2. svc_entry
  3. irq_handler
  4. @中断处理结束后,发生抢占的地方
  5. #ifdef CONFIG_PREEMPT
  6. get_thread_info tsk
  7. @获取thread_info->preempt_cpunt变量;preempt_count0,说明可以抢占进程;preempt_count大于0,表示不能抢占。
  8. ldr r8, [tsk, #TI_PREEMPT] @ get preempt count
  9. ldr r0, [tsk, #TI_FLAGS] @ get flags
  10. teq r8, #0 @ if preempt count != 0
  11. movne r0, #0 @ force flags to 0
  12. @判断是否设置了_TIF_NEED_RESCHED标志位
  13. tst r0, #_TIF_NEED_RESCHED
  14. blne svc_preempt
  15. #endif
  16.  
  17. svc_exit r5, irq = 1 @ return from exception
  18. UNWIND(.fnend )
  19. ENDPROC(__irq_svc)

__irq_svc处理发生在内核空间的中断,主要svc_entry保护中断现场;irq_handler执行中断处理,如果打开抢占功能后续还要检查是否可以抢占这里暂时不看;最后svc_exit执行中断退出处理。到irq_handler就会调用C代码部分的通用中断子系统处理过程。直接上源码

  1. .macro irq_handler
  2. #ifdef CONFIG_MULTI_IRQ_HANDLER
  3. ldr r1, =handle_arch_irq
  4. mov r0, sp
  5. @设置返回地址
  6. adr lr, BSYM(9997f)
  7. @调用handle_arch_irq 保存的处理接口,这里使用的是ldr所以不会覆盖LR寄存器从而保证了正常返回
  8. ldr pc, [r1]
  9. #else
  10. arch_irq_handler_default
  11. #endif
  12. 9997:
  13. .endm

其中handle_arch_irq的是在中断子系统初始化过程中绑定的,在gic控制器的环境下为gic_handle_irq的,其中的处理分中断后大于15和小于等于的两种情况见源码。

  1. static void __exception_irq_entry gic_handle_irq(struct pt_regs *regs)
  2. {
  3. u32 irqstat, irqnr;
  4. struct gic_chip_data *gic = &gic_data[0];
  5. void __iomem *cpu_base = gic_data_cpu_base(gic);
  6.  
  7. do {
  8. @读取IAR寄存器
  9. irqstat = readl_relaxed(cpu_base + GIC_CPU_INTACK);
  10. @GICC_IAR_INT_ID_MASK0x3ff,即低10位,所以中断最多从0~1023
  11. irqnr = irqstat & GICC_IAR_INT_ID_MASK;
  12.  
  13. if (likely(irqnr > 15 && irqnr < 1021)) {
  14. handle_domain_irq(gic->domain, irqnr, regs);
  15. continue;
  16. }
  17. @SGI类型的中断是CPU核间通信所用,只有定义了CONFIG_SMP才有意义。
  18. if (irqnr < 16) {
  19. @直接写EOI寄存器,表示结束中断。
  20. writel_relaxed(irqstat, cpu_base + GIC_CPU_EOI);
  21. #ifdef CONFIG_SMP
  22. handle_IPI(irqnr, regs);
  23. #endif
  24. continue;
  25. }
  26. break;
  27. } while (1);
  28. }

通过以个循环处理所有的硬件中断,根据GIC中断控制器的原理小于16的中断是用于SMP系统的核间通讯的所以,只在SMP架构下起作用。所以常用中断处理流程走的是irqnr > 15 && irqnr < 1021 这个分支调用---> handle_domain_irq(gic->domain, irqnr, regs)//irqnr 是硬件中断号;reg是svc_entry保存的中断现场;domain是中断子系统初始化时根据中断控制器的不同初始化的一个中断操作接口。由源码可以看到中断处理最重要的是通过调用__handle_domain_irq接口,并且在lookp中传入了ture。

这里再来看__handle_domain_irq 的处理流程:

  1. int __handle_domain_irq(struct irq_domain *domain, unsigned int hwirq,
  2. bool lookup, struct pt_regs *regs)
  3. {
  4. struct pt_regs *old_regs = set_irq_regs(regs);
  5. unsigned int irq = hwirq;
  6. int ret = 0;
  7.  
  8. @通过显式增加hardirq域计数,通知Linux进入中断上下文
  9. irq_enter();
  10.  
  11. #ifdef CONFIG_IRQ_DOMAIN
  12. if (lookup)
  13. @根据硬件中断号找到对应的软件中断号
  14. irq = irq_find_mapping(domain, hwirq);
  15. #endif
  16.  
  17. /*
  18. * Some hardware gives randomly wrong interrupts. Rather
  19. * than crashing, do something sensible.
  20. */
  21. if (unlikely(!irq || irq >= nr_irqs)) {
  22. ack_bad_irq(irq);
  23. ret = -EINVAL;
  24. } else {
  25. @开始具体某一个中断的处理,此处irq已经是Linux中断号。
  26. generic_handle_irq(irq);
  27. }
  28.  
  29. irq_exit();
  30. @退出中断上下文
  31. set_irq_regs(old_regs);
  32. return ret;
  33. }

其中处理中断的接口是generic_handle_irq,进入到generic_handle_irq参数是irq号,irq_to_desc()根据irq号找到对应的struct irq_desc。然后调用generic_handle_irq_desc(irq,desc)进一步调用调用irq_desc->handle_irq处理对应的中断。

  1. int generic_handle_irq(unsigned int irq)
  2. {
  3. struct irq_desc *desc = irq_to_desc(irq);
  4.  
  5. if (!desc)
  6. return -EINVAL;
  7. generic_handle_irq_desc(irq, desc);
  8. return 0;
  9. }

static inline void generic_handle_irq_desc(unsigned int irq, struct irq_desc *desc)
{
   desc->handle_irq(irq, desc);
}

这里需要明白中断描述符中的handle_irq接口的初始化也是分情况的。每个中断描述符注册的时候,由gic_irq_domain_map根据hwirq号决定。在gic_irq_domain_map的时候根据hw号决定handle,hw硬件中断号小于32指向handle_percpu_devid_irq,其他情况指向handle_fasteoi_irq。驱动编程通常情况都是使外部中断而非内部异常所以中断号>32,所以handle_irq = handle_fasteoi_irq。

  1. void handle_fasteoi_irq(unsigned int irq, struct irq_desc *desc)
  2. {
  3. @chip 中封装了中断控制器的ARCH层操作
  4. struct irq_chip *chip = desc->irq_data.chip;
  5.  
  6. raw_spin_lock(&desc->lock);
  7.  
  8. if (!irq_may_run(desc))
  9. goto out;
  10.  
  11. desc->istate &= ~(IRQS_REPLAY | IRQS_WAITING);
  12. kstat_incr_irqs_this_cpu(irq, desc);
  13.  
  14. /*
  15. * If its disabled or no action available
  16. * then mask it and get out of here:
  17. */
  18. @如果该中断没有指定action描述符或该中断被关闭了IRQD_IRQ_DISABLED,设置该中断状态为IRQS_PENDING,且mask_irq()屏蔽该中断。
  19. if (unlikely(!desc->action || irqd_irq_disabled(&desc->irq_data))) {
  20. desc->istate |= IRQS_PENDING;
  21. mask_irq(desc);
  22. goto out;
  23. }
  24. @如果中断是IRQS_ONESHOT,不支持中断嵌套,那么应该调用mask_irq()来屏蔽该中断源。
  25. if (desc->istate & IRQS_ONESHOT)
  26. mask_irq(desc);
  27.  
  28. preflow_handler(desc);
  29. @实际的中断处理接口
  30. handle_irq_event(desc);
  31. 根据不同条件执行unmask_irq()解除中断屏蔽,或者执行irq_chip->irq_eoi发送EOI信号,通知GIC中断处理完毕。
  32. cond_unmask_eoi_irq(desc, chip);
  33.  
  34. raw_spin_unlock(&desc->lock);
  35. return;
  36. out:
  37. if (!(chip->flags & IRQCHIP_EOI_IF_HANDLED))
  38. chip->irq_eoi(&desc->irq_data);
  39. raw_spin_unlock(&desc->lock);
  40. }

handle_irq_event调用handle_irq_event_percpu,执行action->handler(),如有需要唤醒内核中断线程执行action->thread_fn见源码如下:

  1. irqreturn_t handle_irq_event(struct irq_desc *desc)
  2. {
  3. struct irqaction *action = desc->action;
  4. irqreturn_t ret;
  5. @清除IRQS_PENDING标志位
  6. desc->istate &= ~IRQS_PENDING;
  7. @设置IRQD_IRQ_INPROGRESS标志位,表示正在处理硬件中断。
  8. irqd_set(&desc->irq_data, IRQD_IRQ_INPROGRESS);
  9. raw_spin_unlock(&desc->lock);
  10.  
  11. ret = handle_irq_event_percpu(desc, action);
  12.  
  13. raw_spin_lock(&desc->lock);
  14. @清除IRQD_IRQ_INPROGRESS标志位,表示中断处理结束。
  15. irqd_clear(&desc->irq_data, IRQD_IRQ_INPROGRESS);
  16. return ret;
  17. }

handle_irq_event_percpu,以此处理每个CPU上的中断的每个action(share):

  1. irqreturn_t handle_irq_event_percpu(struct irq_desc *desc, struct irqaction *action)
  2. {
  3. irqreturn_t retval = IRQ_NONE;
  4. unsigned int flags = 0, irq = desc->irq_data.irq;
  5. @遍历中断描述符中的action链表,依次执行每个action元素中的primary handler回调函数action->handler
  6. do {
  7. irqreturn_t res;
  8.  
  9. trace_irq_handler_entry(irq, action);
  10. @执行struct irqactionhandler函数。这就是申请注册中断接口时指定的中断服务函数
  11. res = action->handler(irq, action->dev_id);
  12. trace_irq_handler_exit(irq, action, res);
  13.  
  14. if (WARN_ONCE(!irqs_disabled(),"irq %u handler %pF enabled interrupts\n",
  15. irq, action->handler))
  16. local_irq_disable();
  17. @根据中断服务函数的返回值执行操作
  18. switch (res) {
  19. @需要唤醒内核中断线程,去唤醒内核中断线程
  20. case IRQ_WAKE_THREAD:
  21. /*
  22. * Catch drivers which return WAKE_THREAD but
  23. * did not set up a thread function
  24. */
  25. if (unlikely(!action->thread_fn)) {
  26. @输出一个打印表示没有中断处理函数
  27. warn_no_thread(irq, action);
  28. break;
  29. }
  30. @唤醒此中断对应的内核线程
  31. __irq_wake_thread(desc, action);
  32.  
  33. /* Fall through to add to randomness */
  34. case IRQ_HANDLED:
  35. @已经处理完毕,可以结束。
  36. flags |= action->flags;
  37. break;
  38.  
  39. default:
  40. break;
  41. }
  42.  
  43. retval |= res;
  44. action = action->next;
  45. } while (action);
  46.  
  47. add_interrupt_randomness(irq, flags);
  48.  
  49. if (!noirqdebug)
  50. note_interrupt(irq, desc, retval);
  51. return retval;
  52. }

到这里应该大部分处理流程都清楚了,中断发生后通过以部分arch层相关的代码处理后得到Linux中断子系统的中断号进而找到对应的中断,而驱动在编程过程中已经通过request_irq接口注册好action接口函数到对应的中断。中断执行过程中直接找到对应的接口进行调用就完成了中断的响应处理,然后在根据中断handler处理的返回值如果是IRQ_WAKE_THREAD则唤醒中断注册时候创建的线程,这个线程的具体内容后面中断注册内容部分再具体学习。这里说明request_irq 申请注册的中断服务函数的执行时在中断上下文中的,但是实际上内核为例提高实时性进行了一部分优化通过强制中断服务接口线程化,这个后面学习。  先来看上面提到的区分中断号小于32的处理接口handle_percpu_devid_irq()。

  1. void handle_percpu_devid_irq(unsigned int irq, struct irq_desc *desc)
  2. {
  3. struct irq_chip *chip = irq_desc_get_chip(desc);
  4. struct irqaction *action = desc->action;
  5. void *dev_id = raw_cpu_ptr(action->percpu_dev_id);
  6. irqreturn_t res;
  7.  
  8. kstat_incr_irqs_this_cpu(irq, desc);
  9.  
  10. if (chip->irq_ack)
  11. chip->irq_ack(&desc->irq_data);
  12.  
  13. trace_irq_handler_entry(irq, action);
  14. res = action->handler(irq, dev_id);
  15. trace_irq_handler_exit(irq, action, res);
  16.  
  17. if (chip->irq_eoi)
  18. #调用gic_eoi_irq()函数
  19. chip->irq_eoi(&desc->irq_data);
  20. }

首先响应IAR,然后执行handler这里的接口是内核注册的接口不是驱动开发过程使用(暂时这么理解),最后发送EOI基本上。它的处理流程不同于handle_fasteoi_irq。

中断注册流程

  内核驱动的开发过程常用申请中断的接口是request_irq,他实际上是对另一个接口的调用封转如下,所以进一步查看request_threaded_irq的处理过程

  1. static inline int __must_check
  2. request_irq(unsigned int irq, irq_handler_t handler, unsigned long flags,
  3. const char *name, void *dev)
  4. {
  5. return request_threaded_irq(irq, handler, NULL, flags, name, dev);
  6. }

request_threaded_irq的处理过程才是正真的中断注册接口,而request_irq是一个将thread_fn设置为NULL的封装。这做其实是和他的实现有关系的继续往下看就明白了。

  1. int request_threaded_irq(unsigned int irq, irq_handler_t handler,
  2. irq_handler_t thread_fn, unsigned long irqflags,
  3. const char *devname, void *dev_id)
  4. {
  5. struct irqaction *action;
  6. struct irq_desc *desc;
  7. int retval;
  8.  
  9. /*
  10. * Sanity-check: shared interrupts must pass in a real dev-ID,
  11. * otherwise we'll have trouble later trying to figure out
  12. * which interrupt is which (messes up the interrupt freeing
  13. * logic etc).
  14. */
  15. if ((irqflags & IRQF_SHARED) && !dev_id)
  16. return -EINVAL;
  17.  
  18. desc = irq_to_desc(irq);
  19. if (!desc)
  20. return -EINVAL;
  21.  
  22. if (!irq_settings_can_request(desc) ||
  23. WARN_ON(irq_settings_is_per_cpu_devid(desc)))
  24. return -EINVAL;
  25. //如果中断没有任何响应接口肯定是不行,但是是可以没有handler
  26. if (!handler) {
  27. if (!thread_fn)
  28. return -EINVAL;
  29. handler = irq_default_primary_handler;
  30. }
  31.   //申请一个action结构,这个会在后面绑定到中断描述符中去以便中断发生时能找到这个接口
  32. action = kzalloc(sizeof(struct irqaction), GFP_KERNEL);
  33. if (!action)
  34. return -ENOMEM;
  35. //初始化构造的action
  36. action->handler = handler;
  37. action->thread_fn = thread_fn;
  38. action->flags = irqflags;
  39. action->name = devname;
  40. action->dev_id = dev_id;
  41.   //接下来的调用是重点,完成了中断注册的主要部分
  42. chip_bus_lock(desc);
  43. retval = __setup_irq(irq, desc, action);
  44. chip_bus_sync_unlock(desc);
  45.  
  46. if (retval)
  47. kfree(action);
  48.  
  49. #ifdef CONFIG_DEBUG_SHIRQ_FIXME
  50. if (!retval && (irqflags & IRQF_SHARED)) {
  51. /*
  52. * It's a shared IRQ -- the driver ought to be prepared for it
  53. * to happen immediately, so let's make sure....
  54. * We disable the irq to make sure that a 'real' IRQ doesn't
  55. * run in parallel with our fake.
  56. */
  57. unsigned long flags;
  58.  
  59. disable_irq(irq);
  60. local_irq_save(flags);
  61.  
  62. handler(irq, dev_id);
  63.  
  64. local_irq_restore(flags);
  65. enable_irq(irq);
  66. }
  67. #endif
  68. return retval;
  69. }

下面这个接口是中断注册的关键也是能说明现在Linux内核对于中断的处理的正真实现机制,这里也就是前面说到的内核对实时性优化的中断处理机制。

  1. /*
  2. * Internal function to register an irqaction - typically used to
  3. * allocate special interrupts that are part of the architecture.
  4. */
  5. static int
  6. __setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new)
  7. {
  8. struct irqaction *old, **old_ptr;
  9. unsigned long flags, thread_mask = 0;
  10. int ret, nested, shared = 0;
  11. cpumask_var_t mask;
  12.  
  13. if (!desc)
  14. return -EINVAL;
  15.  
  16. if (desc->irq_data.chip == &no_irq_chip)
  17. return -ENOSYS;
  18. if (!try_module_get(desc->owner))
  19. return -ENODEV;
  20.  
  21. /*
  22. * Check whether the interrupt nests into another interrupt
  23. * thread.
  24. */
  25. //对于设置了_IRQ_NESTED_THREAD嵌套类型的中断描述符,必须指定thread_fn。
  26. nested = irq_settings_is_nested_thread(desc);
  27. if (nested) {
  28. if (!new->thread_fn) {
  29. ret = -EINVAL;
  30. goto out_mput;
  31. }
  32. /*
  33. * Replace the primary handler which was provided from
  34. * the driver for non nested interrupt handling by the
  35. * dummy function which warns when called.
  36. */
  37. //嵌套类型的中断的线程函数由这个替换,这个在前面设置过,所以这里是将原来指定的handler
  38. //接口丢弃了,替换成现在的接口只是输出一个警告,所以说明不支持IRQ_NESTED_THREAD的handler
  39. new->handler = irq_nested_primary_handler;
  40. } else {
  41. //强制线程化了中断的服务接口,只要中断没有用使用IRQF_NO_THREAD强制不能线程化都会线程化它
  42. if (irq_settings_can_thread(desc))
  43. irq_setup_forced_threading(new);
  44. }
  45.  
  46. /*
  47. * Create a handler thread when a thread function is supplied
  48. * and the interrupt does not nest into another interrupt
  49. * thread.
  50. */
  51. //线程化中断设置之后的的线程创建
  52. if (new->thread_fn && !nested) {
  53. struct task_struct *t;
  54. static const struct sched_param param = {
  55. .sched_priority = MAX_USER_RT_PRIO/2,
  56. };
  57.  
  58. t = kthread_create(irq_thread, new, "irq/%d-%s", irq,
  59. new->name);
  60. if (IS_ERR(t)) {
  61. ret = PTR_ERR(t);
  62. goto out_mput;
  63. }
  64. //设置调度方式为FIFO
  65. sched_setscheduler_nocheck(t, SCHED_FIFO, &param);
  66.  
  67. /*
  68. * We keep the reference to the task struct even if
  69. * the thread dies to avoid that the interrupt code
  70. * references an already freed task_struct.
  71. */
  72. get_task_struct(t);
  73. new->thread = t;
  74. /*
  75. * Tell the thread to set its affinity. This is
  76. * important for shared interrupt handlers as we do
  77. * not invoke setup_affinity() for the secondary
  78. * handlers as everything is already set up. Even for
  79. * interrupts marked with IRQF_NO_BALANCE this is
  80. * correct as we want the thread to move to the cpu(s)
  81. * on which the requesting code placed the interrupt.
  82. */
  83. //设置CPU亲和性
  84. set_bit(IRQTF_AFFINITY, &new->thread_flags);
  85. }
  86.  
  87. if (!alloc_cpumask_var(&mask, GFP_KERNEL)) {
  88. ret = -ENOMEM;
  89. goto out_thread;
  90. }
  91.  
  92. /*
  93. * Drivers are often written to work w/o knowledge about the
  94. * underlying irq chip implementation, so a request for a
  95. * threaded irq without a primary hard irq context handler
  96. * requires the ONESHOT flag to be set. Some irq chips like
  97. * MSI based interrupts are per se one shot safe. Check the
  98. * chip flags, so we can avoid the unmask dance at the end of
  99. * the threaded handler for those.
  100. */
  101. if (desc->irq_data.chip->flags & IRQCHIP_ONESHOT_SAFE)
  102. new->flags &= ~IRQF_ONESHOT;
  103.  
  104. /*
  105. * The following block of code has to be executed atomically
  106. */
  107. //共享中断可能会有多个Action,这里吧它全部加进去形成链表
  108. raw_spin_lock_irqsave(&desc->lock, flags);
  109. old_ptr = &desc->action;
  110. old = *old_ptr;
  111. if (old) {
  112. /*
  113. * Can't share interrupts unless both agree to and are
  114. * the same type (level, edge, polarity). So both flag
  115. * fields must have IRQF_SHARED set and the bits which
  116. * set the trigger type must match. Also all must
  117. * agree on ONESHOT.
  118. */
  119. if (!((old->flags & new->flags) & IRQF_SHARED) ||
  120. ((old->flags ^ new->flags) & IRQF_TRIGGER_MASK) ||
  121. ((old->flags ^ new->flags) & IRQF_ONESHOT))
  122. goto mismatch;
  123.  
  124. /* All handlers must agree on per-cpuness */
  125. if ((old->flags & IRQF_PERCPU) !=
  126. (new->flags & IRQF_PERCPU))
  127. goto mismatch;
  128.  
  129. /* add new interrupt at end of irq queue */
  130. do {
  131. /*
  132. * Or all existing action->thread_mask bits,
  133. * so we can find the next zero bit for this
  134. * new action.
  135. */
  136. thread_mask |= old->thread_mask;
  137. old_ptr = &old->next;
  138. old = *old_ptr;
  139. } while (old);
  140. shared = 1;
  141. }
  142.  
  143. /*
  144. * Setup the thread mask for this irqaction for ONESHOT. For
  145. * !ONESHOT irqs the thread mask is 0 so we can avoid a
  146. * conditional in irq_wake_thread().
  147. */
  148. //RQF_ONESHOT类型中断 的中断掩蔽代码
  149. if (new->flags & IRQF_ONESHOT) {
  150. /*
  151. * Unlikely to have 32 resp 64 irqs sharing one line,
  152. * but who knows.
  153. */
  154. if (thread_mask == ~0UL) {
  155. ret = -EBUSY;
  156. goto out_mask;
  157. }
  158. /*
  159. * The thread_mask for the action is or'ed to
  160. * desc->thread_active to indicate that the
  161. * IRQF_ONESHOT thread handler has been woken, but not
  162. * yet finished. The bit is cleared when a thread
  163. * completes. When all threads of a shared interrupt
  164. * line have completed desc->threads_active becomes
  165. * zero and the interrupt line is unmasked. See
  166. * handle.c:irq_wake_thread() for further information.
  167. *
  168. * If no thread is woken by primary (hard irq context)
  169. * interrupt handlers, then desc->threads_active is
  170. * also checked for zero to unmask the irq line in the
  171. * affected hard irq flow handlers
  172. * (handle_[fasteoi|level]_irq).
  173. *
  174. * The new action gets the first zero bit of
  175. * thread_mask assigned. See the loop above which or's
  176. * all existing action->thread_mask bits.
  177. */
  178. new->thread_mask = 1 << ffz(thread_mask);
  179.  
  180. /*handler使用默认irq_default_primary_handler(),如果中断触发类型是LEVEL,
  181. *如果中断出发后不清中断容易引发中断风暴。提醒驱动开发者,没有primary handler
  182. */且中断控制器不支持硬件oneshot,必须显式指定IRQF_ONESHOT表示位。
  183.  
  184. } else if (new->handler == irq_default_primary_handler &&
  185. !(desc->irq_data.chip->flags & IRQCHIP_ONESHOT_SAFE)) {
  186. /*
  187. * The interrupt was requested with handler = NULL, so
  188. * we use the default primary handler for it. But it
  189. * does not have the oneshot flag set. In combination
  190. * with level interrupts this is deadly, because the
  191. * default primary handler just wakes the thread, then
  192. * the irq lines is reenabled, but the device still
  193. * has the level irq asserted. Rinse and repeat....
  194. *
  195. * While this works for edge type interrupts, we play
  196. * it safe and reject unconditionally because we can't
  197. * say for sure which type this interrupt really
  198. * has. The type flags are unreliable as the
  199. * underlying chip implementation can override them.
  200. */
  201. pr_err("Threaded irq requested with handler=NULL and !ONESHOT for irq %d\n",
  202. irq);
  203. ret = -EINVAL;
  204. goto out_mask;
  205. }
  206. //非共享中断情况
  207. if (!shared) {
  208. ret = irq_request_resources(desc);
  209. if (ret) {
  210. pr_err("Failed to request resources for %s (irq %d) on irqchip %s\n",
  211. new->name, irq, desc->irq_data.chip->name);
  212. goto out_mask;
  213. }
  214. //初始化阻塞队列
  215. init_waitqueue_head(&desc->wait_for_threads);
  216. //设置中断触发方式
  217. /* Setup the type (level, edge polarity) if configured: */
  218. if (new->flags & IRQF_TRIGGER_MASK) {
  219. ret = __irq_set_trigger(desc, irq,
  220. new->flags & IRQF_TRIGGER_MASK);
  221.  
  222. if (ret)
  223. goto out_mask;
  224. }
  225. //清楚状态标志
  226. desc->istate &= ~(IRQS_AUTODETECT | IRQS_SPURIOUS_DISABLED | \
  227. IRQS_ONESHOT | IRQS_WAITING);
  228. irqd_clear(&desc->irq_data, IRQD_IRQ_INPROGRESS);
  229.  
  230. if (new->flags & IRQF_PERCPU) {
  231. irqd_set(&desc->irq_data, IRQD_PER_CPU);
  232. irq_settings_set_per_cpu(desc);
  233. }
  234.  
  235. if (new->flags & IRQF_ONESHOT)
  236. desc->istate |= IRQS_ONESHOT;
  237. //如果可以直接启动则直接使能,默认不设置就是自动的
  238. if (irq_settings_can_autoenable(desc))
  239. irq_startup(desc, true);
  240. else
  241. /* Undo nested disables: */
  242. desc->depth = 1;
  243.  
  244. /* Exclude IRQ from balancing if requested */
  245. if (new->flags & IRQF_NOBALANCING) {
  246. irq_settings_set_no_balancing(desc);
  247. irqd_set(&desc->irq_data, IRQD_NO_BALANCING);
  248. }
  249.  
  250. /* Set default affinity mask once everything is setup */
  251. setup_affinity(irq, desc, mask);
  252.  
  253. } else if (new->flags & IRQF_TRIGGER_MASK) {
  254. unsigned int nmsk = new->flags & IRQF_TRIGGER_MASK;
  255. unsigned int omsk = irq_settings_get_trigger_mask(desc);
  256.  
  257. if (nmsk != omsk)
  258. /* hope the handler works with current trigger mode */
  259. pr_warning("irq %d uses trigger mode %u; requested %u\n",
  260. irq, nmsk, omsk);
  261. }
  262.  
  263. new->irq = irq;
  264. *old_ptr = new;
  265.  
  266. irq_pm_install_action(desc, new);
  267.  
  268. /* Reset broken irq detection when installing new handler */
  269. desc->irq_count = 0;
  270. desc->irqs_unhandled = 0;
  271.  
  272. /*
  273. * Check whether we disabled the irq via the spurious handler
  274. * before. Reenable it and give it another chance.
  275. */
  276. if (shared && (desc->istate & IRQS_SPURIOUS_DISABLED)) {
  277. desc->istate &= ~IRQS_SPURIOUS_DISABLED;
  278. __enable_irq(desc, irq);
  279. }
  280.  
  281. raw_spin_unlock_irqrestore(&desc->lock, flags);
  282.  
  283. /*
  284. * Strictly no need to wake it up, but hung_task complains
  285. * when no hard interrupt wakes the thread up.
  286. */
  287. //唤醒中断进程,就会阻塞在等来中断发生的位置
  288. if (new->thread)
  289. wake_up_process(new->thread);
  290. //创建文件系统接口部分的内容
  291. register_irq_proc(irq, desc);
  292. new->dir = NULL;
  293. register_handler_proc(irq, new);
  294. free_cpumask_var(mask);
  295.  
  296. return 0;
  297.  
  298. mismatch:
  299. if (!(new->flags & IRQF_PROBE_SHARED)) {
  300. pr_err("Flags mismatch irq %d. %08x (%s) vs. %08x (%s)\n",
  301. irq, new->flags, new->name, old->flags, old->name);
  302. #ifdef CONFIG_DEBUG_SHIRQ
  303. dump_stack();
  304. #endif
  305. }
  306. ret = -EBUSY;
  307.  
  308. out_mask:
  309. raw_spin_unlock_irqrestore(&desc->lock, flags);
  310. free_cpumask_var(mask);
  311.  
  312. out_thread:
  313. if (new->thread) {
  314. struct task_struct *t = new->thread;
  315.  
  316. new->thread = NULL;
  317. kthread_stop(t);
  318. put_task_struct(t);
  319. }
  320. out_mput:
  321. module_put(desc->owner);
  322. return ret;
  323. }

这个函数的接口的整个执行流程就是,如果当前接口是要支持嵌套的则直接修改handler接口为irq_nested_primary_handler这个接口后面说明,如果不支持嵌套且没有强制指定为不可以线程化的时候都是进行线程化中断服务接口的通过irq_setup_forced_threading()同样是后面详细说明,线程化中断服务接口后就会为这个中断创建对应的线程并配置调度方式为FIFO和CPU亲和性。之后就是中断抽象数据的配置和中断使能和文件系统接口的问的创建在/proc目录下。到这里处理流程就算结束了,接下来在完善上面接口的详细内容的探究。

irq_setup_forced_threading

  1. static void irq_setup_forced_threading(struct irqaction *new)
  2. {
  3. if (!force_irqthreads)
  4. return;
  5. if (new->flags & (IRQF_NO_THREAD | IRQF_PERCPU | IRQF_ONESHOT))
  6. return;
  7.  
  8. new->flags |= IRQF_ONESHOT;
  9.  
  10. if (!new->thread_fn) {
  11. set_bit(IRQTF_FORCED_THREAD, &new->thread_flags);
  12. new->thread_fn = new->handler;
  13. new->handler = irq_default_primary_handler;
  14. }
  15. }

通过源码可以清楚的看明白,进行的操作就是检查中断是否能线程化,然后再判断 thread_fn是否为未设置只有这个接口未设置才能强制线程化,原因就很简单,不能丢弃驱动层注册的接口内容要不然不就成BUG了吗。所以线程化的方式就是给未设置thread_fn的中断类型接口直接绑定了一个内建的线程irq_thread,然后在将原有接口的中断服务函数作为线程的接口函数绑定到线程中,再把原来的handler 替换为irq_default_primary_handler,这个接口和前面的irq_nested_primary_handler很相似,只是前面的接口会返回唤醒中断而第二个则直接答应了一个警告信息返回了NONE如下:

  1. /*
  2. * Default primary interrupt handler for threaded interrupts. Is
  3. * assigned as primary handler when request_threaded_irq is called
  4. * with handler == NULL. Useful for oneshot interrupts.
  5. */
  6. static irqreturn_t irq_default_primary_handler(int irq, void *dev_id)
  7. {
  8. return IRQ_WAKE_THREAD;
  9. }
  10.  
  11. /*
  12. * Primary handler for nested threaded interrupts. Should never be
  13. * called.
  14. */
  15. static irqreturn_t irq_nested_primary_handler(int irq, void *dev_id)
  16. {
  17. WARN(1, "Primary handler called for nested irq %d\n", irq);
  18. return IRQ_NONE;
  19. }

所以到这里就应该明白通过request_irq接口注册的中断服务接口在内核是会有可能被线程化的所以,这个接口注册的中断服务函数在指定不可以线程化的标志后是运行在中断上下文的,而其他情况是运行在进程上下文的。这也是我一开始想来研究硬中断到底运行在哪个上下文的,因为并发的一些接口是需要区别中断上下文还是进程上下文的。最后再来看一下内核将中断服务进程线程化的线程是怎样执行的。

  1. static int irq_thread(void *data)
  2. {
  3. struct callback_head on_exit_work;
  4. struct irqaction *action = data;
  5. struct irq_desc *desc = irq_to_desc(action->irq);
  6. irqreturn_t (*handler_fn)(struct irq_desc *desc,
  7. struct irqaction *action);
  8.  
  9. if (force_irqthreads && test_bit(IRQTF_FORCED_THREAD,
  10. &action->thread_flags))
  11. handler_fn = irq_forced_thread_fn;
  12. else
  13. handler_fn = irq_thread_fn;
  14.  
  15. init_task_work(&on_exit_work, irq_thread_dtor);
  16. task_work_add(current, &on_exit_work, false);
  17.  
  18. irq_thread_check_affinity(desc, action);
  19.  
  20. while (!irq_wait_for_interrupt(action)) {
  21. irqreturn_t action_ret;
  22.  
  23. irq_thread_check_affinity(desc, action);
  24. //执行中断内核线程函数
  25. action_ret = handler_fn(desc, action);
  26. if (action_ret == IRQ_HANDLED)
  27. //增加threads_handled计数
  28. atomic_inc(&desc->threads_handled);
  29. //唤醒wait_for_threads等待队列
  30. wake_threads_waitq(desc);
  31. }
  32.  
  33. /*
  34. * This is the regular exit path. __free_irq() is stopping the
  35. * thread via kthread_stop() after calling
  36. * synchronize_irq(). So neither IRQTF_RUNTHREAD nor the
  37. * oneshot mask bit can be set. We cannot verify that as we
  38. * cannot touch the oneshot mask at this point anymore as
  39. * __setup_irq() might have given out currents thread_mask
  40. * again.
  41. */
  42. task_work_cancel(current, irq_thread_dtor);
  43. return 0;
  44. }

这和线程接受一个struct irqaction作为参数,运行起来后会在irq_wait_for_interrupt()下阻塞挂起直到中断上下文执行线程唤醒时才会继续运行。就在中断执行为完handler后判断其返回值是否是IRQ_WAKE_THREAD,进而 调用__irq_wake_thread(desc, action);唤醒中断服务程序线程。而线程化则是将handler直接绑定到一个返回IRQ_WAKE_THREAD的接口上从而保证进程一定会被唤醒,以上就是我对于硬中断的全部理解了。

参考博客:

https://www.cnblogs.com/sky-heaven/p/11096462.html

https://www.cnblogs.com/arnoldlu/p/8659981.html

Linux内核实现透视---硬中断的更多相关文章

  1. [Linux内核]软中断与硬中断

    转自:http://blog.csdn.net/zhangskd/article/details/21992933 本文主要内容:硬中断 / 软中断的原理和实现 内核版本:2.6.37 Author: ...

  2. 向linux内核中添加外部中断驱动模块

    本文主要介绍外部中断驱动模块的编写,包括:1.linux模块的框架及混杂设备的注册.卸载.操作函数集.2.中断的申请及释放.3.等待队列的使用.4.工作队列的使用.5.定时器的使用.6.向linux内 ...

  3. Linux内核实现透视---软中断&Tasklet

    软中断 首先明确一个概念软中断(不是软件中断int n).总来来说软中断就是内核在启动时为每一个内核创建了一个特殊的进程,这个进程会不停的poll检查是否有软中断需要执行,如果需要执行则调用注册的接口 ...

  4. Linux内核设计笔记7——中断

    中断与中断处理 何为中断? 一种由设备发向处理器的电信号 中断不与处理器时钟同步,随时可以发生,内核随时可能因为中断到来而被打断. 每一个中断都有唯一一个数字标志,称之为中断线(IRQ) 异常是由软件 ...

  5. Linux内核实现透视---工作队列

    作为Linux中断低半部的另一种实现机制的基础,工作队列的出现更多的是为了解决软中断和Tasklet对于用户进程的时间片的不良影响问题的.工作队列本身是可以使用内核线程来替代的,但是使用线程来实现复杂 ...

  6. (笔记)Linux内核学习(五)之中断推后处理机制

    一 中断 硬件通过中断与操作系统进行通信,通过对硬件驱动程序处注册中断处理程序,快速响应硬件的中断. 硬件中断优先级很高,打断当前正在执行的程序.有两种情况: 硬件中断在中断处理程序中处理 硬件中断延 ...

  7. Linux内核源代码情景分析-中断半

    一.中断初始化 1.中断向量表IDT初始化 void __init init_IRQ(void) { int i; #ifndef CONFIG_X86_VISWS_APIC init_ISA_irq ...

  8. linux内核学习-

    我的博客:www.while0.com 1.端口地址的设置主要有统一编址和独立编址.  cat /proc/ioports 可以查询linux主机的设备端口. 2.数据传输控制方式有循环查询,中断和D ...

  9. Linux内核中断和异常分析(下)

    这节,我们继续上,中(以前的日志有)篇目进行分析,结合一个真实的驱动案例来描述linux内核中驱动的中断机制,首先我们先了解一下linux内核中提供的中断接口. 这个接口我们需要包含一个头文件:#in ...

随机推荐

  1. Vue的核心思想

    Vue的核心思想主要分为两部分: 1.数据驱动  2.组件系统 1.数据驱动 在传统的前端交互中,我们是通过Ajax向服务器请求数据,然后手动的去操作DOM元素,进行数据的渲染,每当前端数据交互变化时 ...

  2. HTML5与CSS3知识点总结

    好好学习,天天向上 本文已收录至我的Github仓库DayDayUP:github.com/RobodLee/DayDayUP,欢迎Star 原文链接:https://blog.csdn.net/we ...

  3. 在QML 中用javascritpt 将中文转换拼音,可以在音标

    项目需要, 今天整理了一下.在QML调用javascrit将中文汉字转换成拼音. 感觉执行效率低.下面是主要代码. 具体代码请参考QMLPinyin 代码 ```import "./piny ...

  4. Maven 中央仓库

    概述 当你建立一个 Maven 的项目,Maven 会检查你的 pom.xml 文件,以确定哪些依赖下载.首先,Maven 将从本地资源库获得 Maven 的本地资源库依赖资源,如果没有找到,然后把它 ...

  5. 【练习】goroutine chan 通道 总结

    1. fatal error: all goroutines are asleep - deadlock! 所有的协程都休眠了 - 死锁! package mainimport("fmt&q ...

  6. 最全面的图卷积网络GCN的理解和详细推导,都在这里了!

    目录 目录 1. 为什么会出现图卷积神经网络? 2. 图卷积网络的两种理解方式 2.1 vertex domain(spatial domain):顶点域(空间域) 2.2 spectral doma ...

  7. 通过Portainer统一管理不同服务器的Docker

    通过Portainer统一管理不同服务器的Docker 一.可视化管理工具Portainer的安装 二.跨服务器管理Docker 2.1开启2375监听端口 2.2Portainer配置远程管理 一. ...

  8. centos7 快速搭建redis集群环境

    本文主要是记录一下快速搭建redis集群环境的方式. 环境简介:centos 7  + redis-3.2.4 本次用两个服务6个节点来搭建:192.168.116.120  和  192.168.1 ...

  9. 802.1X

    1.简介 IEEE802 LAN/WAN委员会为解决无线局域网网络安全问题,提出了802.1X协议.后来,802.1X协议作为局域网端口的一个普通接入控制机制在以太网中被广泛应用,主要解决以太网内认证 ...

  10. spring源码学习笔记之容器的基本实现(一)

    前言 最近学习了<<Spring源码深度解析>>受益匪浅,本博客是对学习内容的一个总结.分享,方便日后自己复习或与一同学习的小伙伴一起探讨之用. 建议与源码配合使用,效果更嘉, ...