irq中断子系统

时间:2021-12-16 15:33:32

参考:http://blog.csdn.net/adaptiver/article/details/6834337
1 因为当中断发生的时候系统由中断门 进入时自动关中断(对于x86平台就是将eflags寄存器的if位置为0),在irq_exit中恢复中断
2 貌似在handle_edge_irq中也有对中断关闭和打开的操作
3 两点说明:一是因为linux不支持 中断优先级,因此任何中断都可以抢占其他中断,但是同种类型的中断(即定义使用同一个 中断线的中断)不会发生抢占,他们会在执行本类型中断的时候依次被调用执行。二是所谓 “只要发生中断,就可以抢占内核”这句是有一定限制的,因为当中断发生的时候系统由中断门 进入时自动关中断(对于x86平台就是将eflags寄存器的if位置为0),只有当中断函数被执行 (handle_IRQ_event)的过程中开中断之后才能有抢占。

对于linux系统而言,中断发生过程为:
根据中断号跳转至规定的中断向量表的位置–>保护现场,并且转换模式至SVC32–>根据向量表得指示进一步跳转至处理函数处–>进一步跳转__irq_svc,并保存那些寄存器供中断返回时使用–>irq_handler中断处理–>
进入c语言的asm_do_IRQ–>generic_handle_irq(irq)–> desc->handle_irq(irq, desc)即handle_edge_irq等–>屏蔽同一个中断,清中断,使能本中断–>handle_IRQ_event–>action->handler(irq, action->dev_id)注册的中断处理函数–>中断返回irq_exit–>如果还有软中断没执行则invoke_softirq()–>现场恢复

通过中断产生结合函数来说明中断发生过程:
1、重要结构
/include/linux/irq.h
irq_desc 内核中记录一个irq_desc的数组,数组的每一项对应一个中断或者一组中断使用同一个中断号,一句话irq_desc几乎记录所有中断相关的东西,这个结构是中断的核心。其中包括俩个重要的结构irq_chip 和irqaction 。
这个结构体作用与gpio_desc很像,都是一个数组,然后通过索引找到相应的chip等信息。

struct irq_desc {
        unsigned int            irq;                                              中断号
        struct timer_rand_state *timer_rand_state;
        unsigned int            *kstat_irqs;
#ifdef CONFIG_INTR_REMAP
        struct irq_2_iommu      *irq_2_iommu;
#endif
        irq_flow_handler_t      handle_irq;                                          //中断处理入口函数
        struct irq_chip         *chip;                                               //irq中断子系统接口函数
        struct msi_desc         *msi_desc;
        void                    *handler_data;                                        
        void                    *chip_data;
        struct irqaction        *action;        /* IRQ action list */                 //注册中断时将中断函数挂在这个链表上面
        unsigned int            status;         /* IRQ status */

        unsigned int            depth;          /* nested irq disables */
        unsigned int            wake_depth;     /* nested wake enables */
        unsigned int            irq_count;      /* For detecting broken IRQs */
        unsigned long           last_unhandled; /* Aging timer for unhandled count */
        unsigned int            irqs_unhandled;
        raw_spinlock_t          lock;
#ifdef CONFIG_SMP
        cpumask_var_t           affinity;
        const struct cpumask    *affinity_hint;
        unsigned int            node;
#ifdef CONFIG_GENERIC_PENDING_IRQ
        cpumask_var_t           pending_mask;
#endif
#endif
        atomic_t                threads_active;
        wait_queue_head_t       wait_for_threads;
#ifdef CONFIG_PROC_FS
        struct proc_dir_entry   *dir;
#endif
        const char              *name;
} ____cacheline_internodealigned_in_smp;

接下来看看irq中断子系统接口函数
struct irq_chip {  
    const char  *name;  
    unsigned int    (*startup)(unsigned int irq); 启动中断  
    void        (*shutdown)(unsigned int irq); 关闭中断  
    void        (*enable)(unsigned int irq);   使能中断  
    void        (*disable)(unsigned int irq);  禁止中断  

    void        (*ack)(unsigned int irq);   中断应答函数,就是清除中断标识函数  
    void        (*mask)(unsigned int irq);   中断屏蔽函数  
    void        (*mask_ack)(unsigned int irq); 屏蔽中断应答函数,一般用于电平触发方式,需要先屏蔽再应答  
    void        (*unmask)(unsigned int irq);  开启中断  
    void        (*eoi)(unsigned int irq);  

    void        (*end)(unsigned int irq);  
    int     (*set_affinity)(unsigned int irq,  
                    const struct cpumask *dest);  
    int     (*retrigger)(unsigned int irq);  
    int     (*set_type)(unsigned int irq, unsigned int flow_type); 设置中断类型,其中包括设置GPIO口为中断输入  
    int     (*set_wake)(unsigned int irq, unsigned int on);  

    void        (*bus_lock)(unsigned int irq);  上锁函数  
    void        (*bus_sync_unlock)(unsigned int irq); 解锁  

    /* Currently used only by UML, might disappear one day.*/  
#ifdef CONFIG_IRQ_RELEASE_METHOD 
    void        (*release)(unsigned int irq, void *dev_id);  
#endif 
    /* * For compatibility, ->typename is copied into ->name. * Will disappear. */  
    const char  *typename;  
};  

我们可以看到这里实现的是一个框架,需要我们进一步的填充里面的函数。我们在分析另一个结构irqaction
include/linux/interrupt.h

struct irqaction {  
    irq_handler_t handler;  用户注册的中断处理函数  
    unsigned long flags;    中断标识  
    const char *name;       用户注册的中断名字,cat/proc/interrupts时可以看到  
    void *dev_id;           可以是用户传递的参数或者用来区分共享中断  
    struct irqaction *next; irqaction结构链,一个共享中断可以有多个中断处理函数  
    int irq;                中断号  
    struct proc_dir_entry *dir;  
    irq_handler_t thread_fn;  
    struct task_struct *thread;  
    unsigned long thread_flags;  
};  

一步一步分析request_irq
request_irq(unsigned int irq, irq_handler_t handler, unsigned long flags,
            const char *name, void *dev)
{
        return request_threaded_irq(irq, handler, NULL, flags, name, dev);
}

int request_threaded_irq(unsigned int irq, irq_handler_t handler,
                         irq_handler_t thread_fn, unsigned long irqflags,
                         const char *devname, void *dev_id)
{
        struct irqaction *action;
        struct irq_desc *desc;                                   
        int retval;

        /* * Sanity-check: shared interrupts must pass in a real dev-ID, * otherwise we'll have trouble later trying to figure out * which interrupt is which (messes up the interrupt freeing * logic etc). */
        if ((irqflags & IRQF_SHARED) && !dev_id)
                return -EINVAL;

        desc = irq_to_desc(irq);                                            根据irq找到初始化的irq_desc结构体,后面有这个结构体的初始化程序讲解
        if (!desc)
                return -EINVAL;

        if (desc->status & IRQ_NOREQUEST)                                  如果不能被请求了
                return -EINVAL;

        if (!handler) {                                                        如果没有定义中断处理函数
                if (!thread_fn)                                                                     
                        return -EINVAL;
                handler = irq_default_primary_handler;                          则给一个默认的函数给handler
        }

        action = kzalloc(sizeof(struct irqaction), GFP_KERNEL);                 申请一个action结构体
        if (!action)
                return -ENOMEM;

        action->handler = handler;                                              以下对结构体的各个成员进行赋值
        action->thread_fn = thread_fn;
        action->flags = irqflags;
        action->name = devname;
        action->dev_id = dev_id;

        chip_bus_lock(irq, desc);
        retval = __setup_irq(irq, desc, action);                               见下讲解
        chip_bus_sync_unlock(irq, desc);

        if (retval)
                kfree(action);
        return retval;
}
EXPORT_SYMBOL(request_threaded_irq);



static int
__setup_irq(unsigned int irq, struct irq_desc *desc, struct irqaction *new)
{
        struct irqaction *old, **old_ptr;
        const char *old_name = NULL;
        unsigned long flags;
        int nested, shared = 0;
        int ret;

        if (!desc)                                                             
                return -EINVAL;

        if (desc->chip == &no_irq_chip)                                       判断是否使用no_irq_chip接口函数
                return -ENOSYS;
        /* * Some drivers like serial.c use request_irq() heavily, * so we have to be careful not to interfere with a * running system. */
        if (new->flags & IRQF_SAMPLE_RANDOM) {                                  有时供串口驱动使用标志
                /* * This function might sleep, we want to call it first, * outside of the atomic block. * Yes, this might clear the entropy pool if the wrong * driver is attempted to be loaded, without actually * installing a new handler, but is this really a problem, * only the sysadmin is able to do this. */
                rand_initialize_irq(irq);
        }

        /* Oneshot interrupts are not allowed with shared */
        if ((new->flags & IRQF_ONESHOT) && (new->flags & IRQF_SHARED))        Oneshot不允许共享中断   
                return -EINVAL;

        /* * Check whether the interrupt nests into another interrupt * thread. */
        nested = desc->status & IRQ_NESTED_THREAD;                               是否定义了嵌套标志,显然不执行
        if (nested) {
                if (!new->thread_fn)
                        return -EINVAL;
                /* * Replace the primary handler which was provided from * the driver for non nested interrupt handling by the * dummy function which warns when called. */
                new->handler = irq_nested_primary_handler;
        }
        if (new->thread_fn && !nested) {                                          是否有线程函数定义 //不执行
                struct task_struct *t;

                t = kthread_create(irq_thread, new, "irq/%d-%s", irq,                开启线程
                                   new->name);
                if (IS_ERR(t))
                        return PTR_ERR(t);
                /* * We keep the reference to the task struct even if * the thread dies to avoid that the interrupt code * references an already freed task_struct. */
                get_task_struct(t);
                new->thread = t;
        }

        /* * The following block of code has to be executed atomically */
        raw_spin_lock_irqsave(&desc->lock, flags);
        old_ptr = &desc->action;                                                    从旧的desc结构体中取出原来的action
        old = *old_ptr;
        if (old) {                                                                   如果有则是共享中断
                /* * Can't share interrupts unless both agree to and are * the same type (level, edge, polarity). So both flag * fields must have IRQF_SHARED set and the bits which * set the trigger type must match. */
                if (!((old->flags & new->flags) & IRQF_SHARED) ||                     判断是否都是共享,或者触发方式一样
                    ((old->flags ^ new->flags) & IRQF_TRIGGER_MASK)) {
                        old_name = old->name;
                        goto mismatch;
                }

#if defined(CONFIG_IRQ_PER_CPU)
                /* All handlers must agree on per-cpuness */
                if ((old->flags & IRQF_PERCPU) !=
                    (new->flags & IRQF_PERCPU))
                        goto mismatch;
#endif

                /* add new interrupt at end of irq queue */
                do {
                        old_ptr = &old->next;                                      在已经挂载action链表末尾还没最后为空的位置,供新的action来挂载
                        old = *old_ptr;
                } while (old);
                shared = 1;
        }

        if (!shared) {
                irq_chip_set_defaults(desc->chip);                                     如果个别没有设置的chip接口设置默认的函数

                init_waitqueue_head(&desc->wait_for_threads);

                /* Setup the type (level, edge polarity) if configured: */
                if (new->flags & IRQF_TRIGGER_MASK) {
                        ret = __irq_set_trigger(desc, irq,                                设置触发方式 
                                        new->flags & IRQF_TRIGGER_MASK);

                        if (ret)
                                goto out_thread;
                } else
                        compat_irq_chip_set_default_handler(desc);        
#if defined(CONFIG_IRQ_PER_CPU)
                if (new->flags & IRQF_PERCPU)
                        desc->status |= IRQ_PER_CPU;
#endif

                desc->status &= ~(IRQ_AUTODETECT | IRQ_WAITING | IRQ_ONESHOT |
                                  IRQ_INPROGRESS | IRQ_SPURIOUS_DISABLED);

                if (new->flags & IRQF_ONESHOT)
                        desc->status |= IRQ_ONESHOT;

                if (!(desc->status & IRQ_NOAUTOEN)) {
                        desc->depth = 0;
                        desc->status &= ~IRQ_DISABLED;                             设置状态
                        desc->chip->startup(irq);                                   开启中断
                } else
                        /* Undo nested disables: */
                        desc->depth = 1;

                /* Exclude IRQ from balancing if requested */
                if (new->flags & IRQF_NOBALANCING)
                        desc->status |= IRQ_NO_BALANCING;

                /* Set default affinity mask once everything is setup */
                setup_affinity(irq, desc);

        } else if ((new->flags & IRQF_TRIGGER_MASK)
                        && (new->flags & IRQF_TRIGGER_MASK)
                                != (desc->status & IRQ_TYPE_SENSE_MASK)) {
                /* hope the handler works with the actual trigger mode... */
                pr_warning("IRQ %d uses trigger mode %d; requested %d\n",
                                irq, (int)(desc->status & IRQ_TYPE_SENSE_MASK),
                                (int)(new->flags & IRQF_TRIGGER_MASK));
        }

        new->irq = irq;                                                             
        *old_ptr = new;                                                            在irq所属的desc结构体将新的action 挂到链表中

        /* Reset broken irq detection when installing new handler */
        desc->irq_count = 0;
        desc->irqs_unhandled = 0;

         */
        if (shared && (desc->status & IRQ_SPURIOUS_DISABLED)) {
                desc->status &= ~IRQ_SPURIOUS_DISABLED;
                __enable_irq(desc, irq, false);
        }

        raw_spin_unlock_irqrestore(&desc->lock, flags);

        /* * Strictly no need to wake it up, but hung_task complains * when no hard interrupt wakes the thread up. */
        if (new->thread)
                wake_up_process(new->thread);

        register_irq_proc(irq, desc);                                            在proc下创建irq文件节点         
        new->dir = NULL;
        register_handler_proc(irq, new);                                           在proc下创建handler文件节点

        return 0;

mismatch:
#ifdef CONFIG_DEBUG_SHIRQ
        if (!(new->flags & IRQF_PROBE_SHARED)) {
                printk(KERN_ERR "IRQ handler type mismatch for IRQ %d\n", irq);
                if (old_name)
                        printk(KERN_ERR "current handler: %s\n", old_name);
                dump_stack();
        }
#endif
        ret = -EBUSY;

out_thread:
        raw_spin_unlock_irqrestore(&desc->lock, flags);
        if (new->thread) {
                struct task_struct *t = new->thread;

                new->thread = NULL;
                if (likely(!test_bit(IRQTF_DIED, &new->thread_flags)))
                        kthread_stop(t);
                put_task_struct(t);
        }
        return ret;
}

以上一共做了:创建action结构体,从desc结构体中取出原来的daction结构体,将新的action结构体挂载至原来的acton链表中。

__setup_irq内容比较多,主要完成几个方面的工作

1.添加irqaction结构到irq_desc的action链表中,需要判断是否为共享中断,只有共享中断可以添加多个中断处理函数,如果是共享中断,则要检查中断处理函数是否和链表中其他函数的触发方式等是否相同,只有一致才可以添加到链表中。

2.设置一些irq_chip结构中的函数指针指向默认函数

3.设置中断的触发方式和启动中断

<一>中断初始化流程

下面内容转载他人博客,原文地址 http://blog.chinaunix.net/space.php?uid=15193587&do=blog&cuid=2194431
下面我们分析内核中断初始化的过程以及如何调用到一个新平台的irq初始化函数。
这里我们以s3c2410平台为例,他的中断初始化函数定义在:

/* arch/arm/mach-s3c2410/irq.c */
void __init s3c24xx_init_irq(void)
{
……
}

在arch/arm/mach-s3c2410/mach-smdk2410.c内通过MACHINE_START宏将s3c24xx_init_irq赋值给mach_desc结构体的.init_irq成员。

MACHINE_START(SMDK2410,"SMDK2410")/* @TODO: request a new identifier and switch * to SMDK2410 */
 /* Maintainer: Jonas Dietsche */
 .phys_io = S3C2410_PA_UART,
 .io_pg_offst =(((u32)S3C24XX_VA_UART)>> 18)& 0xfffc,
 .boot_params = S3C2410_SDRAM_PA+ 0x100,
 .map_io = smdk2410_map_io,
 .init_irq = s3c24xx_init_irq,
 .init_machine = smdk_machine_init,
 .timer = &s3c24xx_timer,
MACHINE_END

注:MACHINE_START宏的作用是对mach_desc结构体进行初始化。mach_desc里定义了一些关键的体系架构相关的函数。Porting kernel到新平台时,这个结构体是非常关键的。

init_irq这个成员在系统初始化的时候会被赋值给init_arch_irq全局变量,如下:
/* arch/arm/kernel/setup.c */
void __init setup_arch(char**cmdline_p)
{
 ……
 cpu_init();
 /* * Set up various architecture-specific pointers */
 init_arch_irq = mdesc->init_irq;
 system_timer = mdesc->timer;
 init_machine = mdesc->init_machine;
 ……
}

注:可以看到这里不仅初始化了init_arch_irq 全局变量,同时初始化了system_timer,init_machine等全局变量。这是kernel支持多平台的一种机制。当然这里system_timer和init_machine我不多描述,有兴趣的可以大家自己去看。机制和init_arch_irq大同小异。

init_arch_irq函数指针定义在体系架构无关的arch/arm/kernel/irq.c内
/* arch/arm/kernel/irq.c */
void (*init_arch_irq)(void) __initdata = NULL;

并且在init_IRQ函数内会去执行它。

/* arch/arm/kernel/irq.c */
void __init init_IRQ(void)
{
 int irq;
 for (irq = 0; irq < NR_IRQS; irq++)
  irq_desc[irq].status|= IRQ_NOREQUEST| IRQ_DELAYED_DISABLE|                  //desc状态进行标志
   IRQ_NOPROBE;
#ifdef CONFIG_SMP
 bad_irq_desc.affinity = CPU_MASK_ALL;
 bad_irq_desc.cpu = smp_processor_id();
#endif
 init_arch_irq();
}

那init_IRQ在哪里被调用呢? 我们猜想肯定是在系统初始化的时会调用它。
实际结果也正是,init_IRQ会在init/main.c里的start_kernel函数内被调用:

asmlinkage void __init start_kernel(void)
{
 ……
 trap_init();
 rcu_init();
 init_IRQ();
 pidhash_init();
 clockevents_init();
 init_timers();
 ……
}

init_arch_irq 函数指针,说明的是这是个全局的函数指针,跟体系结构相关。我接着上面的继续分析一下s3c24xx_init_irq()这个函数

void __init s3c24xx_init_irq(void)
{
        unsigned long pend;
        unsigned long last;
        int irqno;
        int i;

#ifdef CONFIG_FIQ
        init_FIQ();
#endif

        irqdbf("s3c2410_init_irq: clearing interrupt status flags\n");

        /* first, clear all interrupts pending... */

        last = 0;
        for (i = 0; i < 4; i++) {
                pend = __raw_readl(S3C24XX_EINTPEND);                                     清中断操作

                if (pend == 0 || pend == last)
                        break;

                __raw_writel(pend, S3C24XX_EINTPEND);
                printk("irq: clearing pending ext status %08x\n", (int)pend);
                last = pend;
        }

        last = 0;
        for (i = 0; i < 4; i++) {
                pend = __raw_readl(S3C2410_INTPND);

                if (pend == 0 || pend == last)
                        break;

                __raw_writel(pend, S3C2410_SRCPND);
                __raw_writel(pend, S3C2410_INTPND);
                printk("irq: clearing pending status %08x\n", (int)pend);
                last = pend;
        }

        last = 0;
        for (i = 0; i < 4; i++) {
                pend = __raw_readl(S3C2410_SUBSRCPND);

                if (pend == 0 || pend == last)
                        break;

                printk("irq: clearing subpending status %08x\n", (int)pend);
                __raw_writel(pend, S3C2410_SUBSRCPND);
                last = pend;
        }

        /* register the main interrupts */
        for (irqno = IRQ_EINT0; irqno <= IRQ_EINT3; irqno++) {
                irqdbf("registering irq %d (ext int)\n", irqno);
                set_irq_chip(irqno, &s3c_irq_eint0t4);                          将chip结构体初始化进desc中
                set_irq_handler(irqno, handle_edge_irq);                         将handler函数初始化进desc中
                set_irq_flags(irqno, IRQF_VALID);                                 清除状态标志位IRQ_NOREQUEST
        }
。。。。。
}

1 上面的for循环,循环清除中断标识,而且设置了一个last变量,不知道是不是为了防止一次擦除中断失败。
2 首先是填充irq_chip结构,然后是设置中断的处理函数入口,这个响应中断的时候就通过函数入口调用用户注册的中断处理函数,中断标识设置为可以使用。
以上参考:http://blog.csdn.net/yimu13/article/details/6803957?locationNum=5
接下来看看中断处理过程,即当发生中断时开始一系列过程。
参考:https://wenku.baidu.com/view/6c6e30634b35eefdc9d33300.html