分享

Linux中断实现浅析

 langhuayipian 2013-12-28
本文描述内容针对2.6.31+x86平台,不包含硬件相关的细节。
作者:独孤九贱;
版权所有,转载请注明出处。有问题欢迎与我交流讨论。

一、概述

中断,本质上是一个电信号,早期的计算的并没有中断这一概念,这使得CPU与外围设备的交互变得困难,CPU需要不断的轮询,以探测外围设备是否有数据需 要处理。这浪费大量的资源。中断的出现,将CPU从这一任务中解放出来,CPU与外设的处理,变为异步,它可以喝着茶,听着音乐,然后等待外设的报告。

Linux中的中断,除了包含外围设备引发的硬中断外,还有更多宽泛的概念,如CPU引发的同步中断或异常、软中断等。不过本文如未特别注明,都是描述外围设备发出的异步中断。

事实上,外围设备并不能直接发中断给CPU。是的,老大随时来看我轮询一下,浪费他的时间与精力,我也不能想找老大就找老大,得找他的小蜜,外设借助一个 称为“中断控制器”的中间组件来完成请求。这个过程叫IRQ(中断请求),中断控制器在处理完相应的电工任务后,将中断请求转发到CPU的中断输入。例 如,下图展示了一个典型的x86平台的8259A中断控制器:
中断.jpg


二、中断控制器

为了屏蔽各种硬件平台的区别,Linux提供了一个统一抽像的平台来实现中断子系统。irq_chip结构用于描述一个硬件中断控制器,它封装了控制器的名称(如XTPIC或IO-APIC)和控制器相应的操作:
  1. struct irq_chip {
  2.         const char        *name;                                                                        //控制器名称
  3.         unsigned int        (*startup)(unsigned int irq);                //第一次激活时调用,用于第一次初始化IRQ
  4.         void                (*shutdown)(unsigned int irq);                        //对应的关闭操作
  5.         void                (*enable)(unsigned int irq);                        //激活IRQ
  6.         void                (*disable)(unsigned int irq);                        //禁用IRQ

  7.         void                (*ack)(unsigned int irq);                                //显示的中断确认操作
  8.         void                (*mask)(unsigned int irq);                                //屏蔽中断
  9.         void                (*mask_ack)(unsigned int irq);                        //屏幕并确认
  10.         void                (*unmask)(unsigned int irq);                        //屏蔽的反向操作
  11.         void                (*eoi)(unsigned int irq);                                //end of interrupt,提供处理中断时一个到硬件的回调

  12.         void                (*end)(unsigned int irq);                                //end操作表示中断处理在电流层结束
  13.         int                (*set_affinity)(unsigned int irq,                        //设置中断亲和
  14.                                         const struct cpumask *dest);
  15.         int                (*retrigger)(unsigned int irq);
  16.         int                (*set_type)(unsigned int irq, unsigned int flow_type);                //设IRQ电流类型
  17.         int                (*set_wake)(unsigned int irq, unsigned int on);                                //设置唤醒???

  18.         /* Currently used only by UML, might disappear one day.*/
  19. #ifdef CONFIG_IRQ_RELEASE_METHOD
  20.         void                (*release)(unsigned int irq, void *dev_id);
  21. #endif
  22.         /*
  23.          * For compatibility, ->typename is copied into ->name.
  24.          * Will disappear.
  25.          */
  26.         const char        *typename;
  27. };
复制代码
大多数的操作可以根据名称了解一二。该结构考虑到了各种不同的体系结构,所以一个特系结构的使用,通常仅是它的一个子集,甚至是很小的一个子系,仍然以8259A为例:
  1. struct irq_chip i8259A_chip = {
  2.         .name                = "XT-PIC",
  3.         .mask                = disable_8259A_irq,
  4.         .disable        = disable_8259A_irq,
  5.         .unmask                = enable_8259A_irq,
  6.         .mask_ack        = mask_and_ack_8259A,
  7. };
复制代码
三、中断描述符

每个中断都有一个编号,系统可以根据编号很容易地区分来访者,是鼠标,还是键盘,或者是网卡。只是很可惜,出于很多原因(例如短视或成本考虑),在很多体 系结构上,提供的编号是很少的,例如图1中显示的,两个8259A芯片,总共提供了16个中断槽位。虽然曾经看来,对于个人计算机这已经足够了,只是时过 境迁,又到了改变的时候,例如,多个外设共享一个中断,称之为中断共享,有过PCI驱动编写经验的都接触过,当然,这需要硬件和内核同时支持。

在IA-32 CPU上,为外围设备都供了16个中断号,从32-47,不过如果看一下/proc/interrupts就会发现,外围设备的IRQ编号是从0开始到 15的,这意味着,中断控制器的一个重要任务,就是对IRQ编号和中断号进行映射,在IA-32上,这个映射,就需要加上32即可。

每个中断号的信息使用IRQ描述符struct irq_desc表示:
  1. struct irq_desc {
  2.         unsigned int                irq;
  3.         ……
  4.         irq_flow_handler_t        handle_irq;                //指向上述控制芯片的电流处理程序
  5.         struct irq_chip                *chip;                        //指向上述的控制芯片
  6.         ……
  7.         struct irqaction        *action;        /* IRQ action list */                //指向IRQ的中断action列表
  8.         ……
  9. } ____cacheline_internodealigned_in_smp;
复制代码
IRQ相关信息的管理的关键之处在于,内核引入一个irq_desc 类型的全局数组来记录之,每个数组的项对应一个IRQ编号,数组槽位与中断号一一对应,IRQ0在位置0,诸如此类。

数组irq_desc_ptrs的初始化在kernel/irq/handle.c
  1. struct irq_desc **irq_desc_ptrs __read_mostly;

  2. irq_desc_legacy是一个用于初始化的临时中介:
  3. static struct irq_desc irq_desc_legacy[NR_IRQS_LEGACY] __cacheline_aligned_in_smp = {
  4.         [0 ... NR_IRQS_LEGACY-1] = {
  5.                 .irq            = -1,
  6.                 .status            = IRQ_DISABLED,
  7.                 .chip            = &no_irq_chip,
  8.                 .handle_irq = handle_bad_irq,
  9.                 .depth            = 1,
  10.                 .lock            = __SPIN_LOCK_UNLOCKED(irq_desc_init.lock),
  11.         }
  12. };
复制代码
这里使用了一个gcc扩展,将所有成员irq号都初始化为-1,其handle_irq都指向handle_bad_irq。

irq_to_desc函数可以根据设备中断号取得相应的中断描述符:
  1. struct irq_desc *irq_to_desc(unsigned int irq)
  2. {
  3.         if (irq_desc_ptrs && irq < nr_irqs)
  4.                 return irq_desc_ptrs[irq];

  5.         return NULL;
  6. }
复制代码
中断描述符中,其最后一个成员action指向中断处理程序。这将在后文描述,先来看中断描述符的初始化,这在early_irq_init函数中完成:
  1. int __init early_irq_init(void)
  2. {
  3.         struct irq_desc *desc;
  4.        
  5.         desc = irq_desc_legacy;
  6.        
  7.         //为中断描述符分配槽位
  8.         irq_desc_ptrs = kcalloc(nr_irqs, sizeof(void *), GFP_NOWAIT);
  9.        
  10.         legacy_count = ARRAY_SIZE(irq_desc_legacy);
  11.        
  12.         //初始化之       
  13.         for (i = 0; i < legacy_count; i++) {
  14.                 desc[i].irq = i;
  15.                 desc[i].kstat_irqs = kstat_irqs_legacy + i * nr_cpu_ids;
  16.                 lockdep_set_class(&desc[i].lock, &irq_desc_lock_class);
  17.                 alloc_desc_masks(&desc[i], node, true);
  18.                 init_desc_masks(&desc[i]);
  19.                 irq_desc_ptrs[i] = desc + i;
  20.         }
  21.        
  22.         //初始化余下的
  23.         for (i = legacy_count; i < nr_irqs; i++)
  24.                 irq_desc_ptrs[i] = NULL;               
  25. }
复制代码
这样,每个irq_desc_ptrs的槽位的初始化工作就完成了。值得注意的是,这里并没有初始化中断描述符的电流处理句柄handle_irq成员。这是留到具体的控制器中去完成的,还是以8259A为例:
  1. void make_8259A_irq(unsigned int irq)
  2. {
  3.         disable_irq_nosync(irq);
  4.         io_apic_irqs &= ~(1<<irq);
  5.         set_irq_chip_and_handler_name(irq, &i8259A_chip, handle_level_irq,
  6.                                       "XT");
  7.         enable_irq(irq);
  8. }
复制代码
set_irq_chip_and_handler_name函数是内核提供的处理注册irq_chip和设置电流处理程序的API之一:
  1. void
  2. set_irq_chip_and_handler_name(unsigned int irq, struct irq_chip *chip,
  3.                               irq_flow_handler_t handle, const char *name)
  4. {
  5.         //取得IRQ对应的中断描述符,设置其chip成员
  6.         set_irq_chip(irq, chip);
  7.         //设置IRQ对应的中断描述符的handle_irq成员
  8.         __set_irq_handler(irq, handle, 0, name);
  9. }
复制代码
这样,i8259A_chip控制器的电流处理程序被注册为handle_level_irq,即为电平触发中断,对应的,边沿触发中断的处理程序是handle_edge_irq。
  1. void
  2. handle_level_irq(unsigned int irq, struct irq_desc *desc)
  3. {
  4.         struct irqaction *action;
  5.         irqreturn_t action_ret;

  6.         spin_lock(&desc->lock);
  7.         mask_ack_irq(desc, irq);

  8.         //后面的代码在应答的中断后,会调置IRQ_INPROGRESS标志,这里做一个简单检查
  9.         if (unlikely(desc->status & IRQ_INPROGRESS))
  10.                 goto out_unlock;
  11.         //清除IRQ_REPLAY | IRQ_WAITING标志位
  12.         desc->status &= ~(IRQ_REPLAY | IRQ_WAITING);
  13.         //统计
  14.         kstat_incr_irqs_this_cpu(irq, desc);

  15.         /*
  16.          * If its disabled or no action available
  17.          * keep it masked and get out of here
  18.          */
  19.         //从中断描述符中取得action
  20.         action = desc->action;
  21.         //如果没有action,或者是中断被关闭,退出
  22.         if (unlikely(!action || (desc->status & IRQ_DISABLED)))
  23.                 goto out_unlock;

  24.         //设置IRQ_INPROGRESS,表示正在处理
  25.         desc->status |= IRQ_INPROGRESS;
  26.         spin_unlock(&desc->lock);

  27.         //调用高层的中断处理程序handle_IRQ_event进一步处理
  28.         action_ret = handle_IRQ_event(irq, action);
  29.         if (!noirqdebug)
  30.                 note_interrupt(irq, desc, action_ret);

  31.         spin_lock(&desc->lock);
  32.         //处理完毕,清除正在处理标志
  33.         desc->status &= ~IRQ_INPROGRESS;
  34.         //如果IRQ没有被禁用,调用chip的unmask
  35.         if (!(desc->status & IRQ_DISABLED) && desc->chip->unmask)
  36.                 desc->chip->unmask(irq);
  37. out_unlock:
  38.         spin_unlock(&desc->lock);
  39. }
复制代码
略过一些硬件的细节差异,handle_edge_irq处理过程类似,它最终也会调用高层的中断处理程序handle_IRQ_event。

四、中断处理程序函数

每个中断处理程序函数都由结构struct irqaction表示,也就是上述中断描述符的最后一个成员:
  1. struct irqaction {
  2.         irq_handler_t handler;
  3.         unsigned long flags;
  4.         cpumask_t mask;
  5.         const char *name;
  6.         void *dev_id;
  7.         struct irqaction *next;
  8.         int irq;
  9.         struct proc_dir_entry *dir;
  10.         irq_handler_t thread_fn;
  11.         struct task_struct *thread;
  12.         unsigned long thread_flags;
  13. };
复制代码
该结构中,最重要的叫员就是处理函数本身,也就是其第一个成员。
flags包含一些标志信,例如IRQF_SHARED/IRQF_TIMER等。
mask存储其CPU位图掩码;
name和dev_id唯一地标识一个中断处理程序;
next成员用于实现共享的IRQ处理程序,相同irq号的一个或几个irqaction汇聚在一个链表中。

小结一下,上述三个重要数据结构的关系就很清楚了:

irq_desc数组包含若干成员,每个成员都一个chip指针,指向对应的中断控制器结构,action指向,指向中断处理函数结构irqaction,若干个具体相同irq的中断处理函数结构串在一个链表上。

irqaction是中断子系统面向驱动程序界面提供的接口,驱动程序在初始化的时候向内核注册,调用request_irq向中断子系统注册,request_irq函数会构造一个action,并将其关联到相应的中断描述符上。

五、IDT表与中断的触发

中断的触发,或者称之为中断路由,表示一个中断如何达到上述的中断处理函数中。

IDT(Interrupt Descriptor Table)中断描述表,IDT是个有256个入口的线形表,每个中断向量关联了一个中断处理过程。当计算机运行在实模式时,IDT被初始化并由BIOS 使用。然而,一旦真正进入了Linux内核,IDT就被移到内存的另一个区域,并进行进入实模式的初步初始化。内核的初始化流程如下:
  1. start_kernel
  2. ->init_IRQ
  3. ->native_init_IRQ
复制代码
  1. void __init native_init_IRQ(void)
  2. {
  3.         ……
  4.         //更新外部中断(IRQ)的IDT表项
  5.         for (i = FIRST_EXTERNAL_VECTOR; i < NR_VECTORS; i++) {
  6.                 /* IA32_SYSCALL_VECTOR could be used in trap_init already. */
  7.                 //跳过系统调用(trap)使用过的槽位
  8.                 if (!test_bit(i, used_vectors))
  9.                         set_intr_gate(i, interrupt[i-FIRST_EXTERNAL_VECTOR]);
  10.         }
  11. }
复制代码
set_intr_gate在IDT的第i个表项插入一个中断门。门中的段选择符设置为内核代码的段选择符,基偏移量为中断处理程序的地址,
即为第二个参数interrupt[i-FIRST_EXTERNAL_VECTOR]。

interrupt数组在entry_32.S中定义,它本质上都会跳转到common_interrupt:
  1. .section .init.rodata,"a"
  2. ENTRY(interrupt)
  3. .text
  4.         .p2align 5
  5.         .p2align CONFIG_X86_L1_CACHE_SHIFT
  6. ENTRY(irq_entries_start)
  7.         RING0_INT_FRAME
  8. vector=FIRST_EXTERNAL_VECTOR
  9. .rept (NR_VECTORS-FIRST_EXTERNAL_VECTOR+6)/7
  10.         .balign 32
  11.   .rept        7
  12.     .if vector < NR_VECTORS
  13.       .if vector <> FIRST_EXTERNAL_VECTOR
  14.         CFI_ADJUST_CFA_OFFSET -4
  15.       .endif
  16. 1:        pushl $(~vector+0x80)        /* Note: always in signed byte range */
  17.         CFI_ADJUST_CFA_OFFSET 4
  18.       .if ((vector-FIRST_EXTERNAL_VECTOR)%7) <> 6
  19.         jmp 2f
  20.       .endif
  21.       .previous
  22.         .long 1b
  23.       .text
  24. vector=vector+1
  25.     .endif
  26.   .endr
  27. 2:        jmp common_interrupt
  28. .endr
  29. END(irq_entries_start)

  30. .previous
  31. END(interrupt)
  32. .previous
复制代码
common_interrupt是所有外部中断的统一入口:
  1. /*
  2. * the CPU automatically disables interrupts when executing an IRQ vector,
  3. * so IRQ-flags tracing has to follow that:
  4. */
  5.         .p2align CONFIG_X86_L1_CACHE_SHIFT
  6. common_interrupt:
  7.         //将中断向量号减256。内核用负数表示所有的中断
  8.         addl $-0x80,(%esp)        /* Adjust vector into the [-256,-1] range */
  9.         //调用SAVE_ALL宏保存寄存器的值
  10.         SAVE_ALL
  11.         TRACE_IRQS_OFF
  12.         //保存栈顶地址
  13.         movl %esp,%eax
  14.         //调用do_IRQ函数
  15.         call do_IRQ
  16.         //从中断返回
  17.         jmp ret_from_intr
  18. ENDPROC(common_interrupt)
  19.         CFI_ENDPROC
复制代码
这样,就进入了著名的do_IRQ函数了,到这里,基本上有平台相关的汇编代码的处理流程就结束了,相对而言,我还是更喜欢C语言:
  1. /*
  2. * do_IRQ handles all normal device IRQ's (the special
  3. * SMP cross-CPU interrupts have their own specific
  4. * handlers).
  5. */
  6. unsigned int __irq_entry do_IRQ(struct pt_regs *regs)
  7. {
  8.         //取得原来的寄存器
  9.         struct pt_regs *old_regs = set_irq_regs(regs);

  10.         /* high bit used in ret_from_ code  */
  11.         //取得中断向量号
  12.         unsigned vector = ~regs->orig_ax;
  13.         unsigned irq;

  14.         //退出idle进程
  15.         exit_idle();
  16.         //进入中断
  17.         irq_enter();

  18.         //中断线号与设备的中断号之间对应关系,由系统分派,分派表是一个per-cpu变量vector_irq
  19.         irq = __get_cpu_var(vector_irq)[vector];

  20.         //处理之
  21.         if (!handle_irq(irq, regs)) {
  22.                 //应答APIC
  23.                 ack_APIC_irq();

  24.                 if (printk_ratelimit())
  25.                         pr_emerg("%s: %d.%d No irq handler for vector (irq %d)\n",
  26.                                 __func__, smp_processor_id(), vector, irq);
  27.         }

  28.         //结束中断
  29.         irq_exit();

  30.         set_irq_regs(old_regs);
  31.         return 1;
  32. }
复制代码
handle_irq函数根据中断号,查找相应的desc结构,调用其handle_irq:
  1. bool handle_irq(unsigned irq, struct pt_regs *regs)
  2. {
  3.         struct irq_desc *desc;
  4.         int overflow;

  5.         overflow = check_stack_overflow();

  6.         desc = irq_to_desc(irq);  //取得irq对应的中断描述符,irq_to_desc函数一开始就已经分析过了
  7.         if (unlikely(!desc))
  8.                 return false;

  9.         if (!execute_on_irq_stack(overflow, desc, irq)) {
  10.                 if (unlikely(overflow))
  11.                         print_stack_overflow();
  12.                 desc->handle_irq(irq, desc);
  13.         }

  14.         return true;
  15. }
复制代码
如果是在中断栈上调用,则稍微复杂一点,需要先构造一个中断栈,再调用handle_irq。
  1. static inline int
  2. execute_on_irq_stack(int overflow, struct irq_desc *desc, int irq)
  3. {
  4.         union irq_ctx *curctx, *irqctx;
  5.         u32 *isp, arg1, arg2;

  6.         curctx = (union irq_ctx *) current_thread_info();
  7.         irqctx = __get_cpu_var(hardirq_ctx);

  8.         /*
  9.          * this is where we switch to the IRQ stack. However, if we are
  10.          * already using the IRQ stack (because we interrupted a hardirq
  11.          * handler) we can't do that and just have to keep using the
  12.          * current stack (which is the irq stack already after all)
  13.          */
  14.         if (unlikely(curctx == irqctx))
  15.                 return 0;

  16.         /* build the stack frame on the IRQ stack */
  17.         isp = (u32 *) ((char *)irqctx + sizeof(*irqctx));
  18.         irqctx->tinfo.task = curctx->tinfo.task;
  19.         irqctx->tinfo.previous_esp = current_stack_pointer;

  20.         /*
  21.          * Copy the softirq bits in preempt_count so that the
  22.          * softirq checks work in the hardirq context.
  23.          */
  24.         irqctx->tinfo.preempt_count =
  25.                 (irqctx->tinfo.preempt_count & ~SOFTIRQ_MASK) |
  26.                 (curctx->tinfo.preempt_count & SOFTIRQ_MASK);

  27.         if (unlikely(overflow))
  28.                 call_on_stack(print_stack_overflow, isp);

  29.         asm volatile("xchgl        %%ebx,%%esp        \n"
  30.                      "call        *%%edi                \n"
  31.                      "movl        %%ebx,%%esp        \n"
  32.                      : "=a" (arg1), "=d" (arg2), "=b" (isp)
  33.                      :  "0" (irq),   "1" (desc),  "2" (isp),
  34.                         "D" (desc->handle_irq)
  35.                      : "memory", "cc", "ecx");
  36.         return 1;
  37. }
复制代码
中断栈的构造过程,我在《Linux软中断的实现》一文中分析过了,可以在坛子中搜索。

如前所述,handle_irq函数指针,指向了handle_level_irq,或者是handle_edge_irq。不论是哪一种,中断电流处理 函数在会调用handle_IRQ_event进一步处理,handle_IRQ_event函数的本质是遍历中断号上所有的action,调用其 handler。这是在设备驱动初始化时向中断子系统注册的:


/**
* handle_IRQ_event - irq action chain handler
* @irq:        the interrupt number
* @action:        the interrupt action chain for this irq
*
* Handles the action chain of an irq event
*/
irqreturn_t handle_IRQ_event(unsigned int irq, struct irqaction *action)
{
        irqreturn_t ret, retval = IRQ_NONE;
        unsigned int status = 0;

        //因为CPU会禁止中断,这里将其打开,如果没有指定IRQF_DISABLED标志的话,它表示处理程序在中断禁止情况下运行
        if (!(action->flags & IRQF_DISABLED))
                local_irq_enable_in_hardirq();

        //遍历当前irq的action链表中的所有action,调用之
        do {
                //打开中断跟踪
                trace_irq_handler_entry(irq, action);
                //调用中断处理函数
                ret = action->handler(irq, action->dev_id);
                //结束跟踪
                trace_irq_handler_exit(irq, action, ret);

                switch (ret) {
                case IRQ_WAKE_THREAD:
                        /*
                         * Set result to handled so the spurious check
                         * does not trigger.
                         */
                        ret = IRQ_HANDLED;

                        /*
                         * Catch drivers which return WAKE_THREAD but
                         * did not set up a thread function
                         */
                        if (unlikely(!action->thread_fn)) {
                                warn_no_thread(irq, action);
                                break;
                        }

                        /*
                         * Wake up the handler thread for this
                         * action. In case the thread crashed and was
                         * killed we just pretend that we handled the
                         * interrupt. The hardirq handler above has
                         * disabled the device interrupt, so no irq
                         * storm is lurking.
                         */
                        if (likely(!test_bit(IRQTF_DIED,
                                             &action->thread_flags))) {
                                set_bit(IRQTF_RUNTHREAD, &action->thread_flags);
                                wake_up_process(action->thread);
                        }

                        /* Fall through to add to randomness */
                case IRQ_HANDLED:
                        status |= action->flags;
                        break;

                default:
                        break;
                }

                retval |= ret;
                //取得链表中的下一个action,如果有的话
                action = action->next;
        } while (action);

                //如果指定了标志,则使用中断间隔时间为随机数产生器产生熵
        if (status & IRQF_SAMPLE_RANDOM)
                add_interrupt_randomness(irq);
                //关闭中断,do_IRQ进入下一轮循环——等待新的中断到来
        local_irq_disable();

        return retval;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多