深入 Linux 内核中的中断:从启动早期的 IDT 配置到早期 trap 初始化

原创2026-09-27 11:43:041,842 阅读
文章标签:文档教程操作系统

深入 Linux 内核中的中断:从启动早期的 IDT 配置到早期 trap 初始化

本篇文章是《Linux 内核揭秘》(linux-insides-zh)中断与中断处理系列的第二部分,承接第一部分的中断理论,正式从 Linux 内核源代码角度出发,沿着 x86_64 架构的启动路径,梳理与中断、异常处理相关的早期代码:从保护模式入口处的空 IDT 配置、gs 基址与 per-cpu 中断栈的建立,到 start_kernel 中栈保护与本地中断控制,最后到 setup_arch 中的早期 trap 初始化。读完本篇,你将掌握中断描述符表(IDT)在 Linux 启动各阶段的填充时机、irq_stack_union 与 MSR_GS_BASE 的关联方式、local_irq_disable/enable 的底层实现,以及 set_intr_gate_ist 系列函数如何向 IDT 写入门描述符。

从理论到代码:中断处理源码阅读的起点

在上一章节中,我们学习了中断和异常处理的理论知识:中断向量号范围 0 到 255、IDT 的门结构、可屏蔽/不可屏蔽中断、sti/cli 对 IF 标志的控制等。本篇不再从 Linux 内核启动的[最开始]几行代码读起,而是直接定位与中断、异常处理相关的最早期代码,逐一展开。

在 x86_64 架构下,内核源代码中与中断相关的最早代码出现在 arch/x86/boot/pm.c 文件中,该文件首次配置了中断描述符表(IDT)。对 IDT 的配置在 go_to_protected_mode 函数中完成:该函数首先调用 setup_idt 配置 IDT,然后将处理器工作模式切换为保护模式:

void go_to_protected_mode(void)
{
        ...
        setup_idt();
        ...
}

setup_idt 函数在同一文件中定义,它仅仅用 NULL 填充了中断描述符表:

static void setup_idt(void)
{
        static const struct gdt_ptr null_idt = {0, 0};
        asm volatile("lidtl %0" : : "m" (null_idt));
}

这里 gdt_ptr 表示一个 48-bit 的特殊功能寄存器结构,它保存了全局描述符表(GDT)的基地址:

struct gdt_ptr {
        u16 len;
        u32 ptr;
} __attribute__((packed));

需要指出的是:此处的 gdt_ptr 实际代表的是 IDTR 寄存器而非 GDTR,因为 lidtl 指令加载的是中断描述符表的基址。Linux 内核代码中没有专门的 idt_ptr 结构体,是因为它与 gdt_ptr 结构完全相同、只是名字不同,没有必要重复定义。内核在此阶段并不真正填充 IDT 的表项,因为此刻处理任何中断或异常都为时尚早,所以仅以全 NULL 的 IDT 完成加载——这对应第一部分中提到的"进入保护模式时用 NULL 门加载 IDT"的做法。

进入保护模式与 long mode 的跳转链

设置完 IDT、GDT 等结构之后,内核开始进入保护模式,这部分代码实现在 arch/x86/boot/pmjump.S 中。关于如何进入保护模式的具体细节,可参考引导章节。

进入保护模式的代码入口位于 boot_params.hdr.code32_start。在 arch/x86/boot/pm.c 的末尾,内核将入口函数指针和启动参数 boot_params 传递给了 protected_mode_jump 函数:

protected_mode_jump(boot_params.hdr.code32_start,
                            (u32)&boot_params + (ds() << 4));

定义在 arch/x86/boot/pmjump.S 中的 protected_mode_jump 函数通过 8086 调用约定,用 ax 和 dx 两个寄存器获取参数:

GLOBAL(protected_mode_jump)
        ...
        .byte   0x66, 0xea              # ljmpl opcode
2:      .long   in_pm32                 # offset
        .word   __BOOT_CS               # segment
...
ENDPROC(protected_mode_jump)

其中 in_pm32 包含了对 32-bit 入口的跳转语句:

GLOBAL(in_pm32)
        ...
        jmpl    *%eax // %eax contains address of the `startup_32`
        ...
ENDPROC(in_pm32)

32-bit 的入口地址位于汇编文件 arch/x86/boot/compressed/head_64.S 中——尽管它的名字包含 _64 后缀。在 arch/x86/boot/compressed 目录下可以看到两个相似的文件:

  • arch/x86/boot/compressed/head_32.S
  • arch/x86/boot/compressed/head_64.S

然而 32-bit 模式的入口位于第二个文件(head_64.S)中,而第一个文件在 x86_64 配置下不参与编译。这可以从 arch/x86/boot/compressed/Makefile 看出:

vmlinux-objs-y := $(obj)/vmlinux.lds $(obj)/head_$(BITS).o $(obj)/misc.o \
...

head_* 取决于 $(BITS) 变量的值,该值由"架构"决定。在 arch/x86/Makefile 中可以找到相关信息:

ifeq ($(CONFIG_X86_32),y)
...
        BITS := 32
else
        BITS := 64
        ...
endif

从 head_64.S 跳入 startup_32 函数后,该函数本身没有与中断处理相关的内容,它只包含进入 long mode 之前的必要准备并直接进入 long mode。long mode 的入口位于 startup_64 函数中,该函数完成内核解压的准备工作(内核解压代码位于 arch/x86/boot/compressed/misc.c 的 decompress_kernel 函数,详见内核解压章节)。

建立 per-cpu 中断栈:gs 基址与 irq_stack_union

内核解压完成后,程序跳入 arch/x86/kernel/head_64.S 中的 startup_64 函数。在这个函数中,内核构建 identity-mapped pages,检查 NX 位,配置 Extended Feature Enable Register,使用 lgdt 更新早期 GDT,然后使用如下代码设置 gs 寄存器:

movl    $MSR_GS_BASE,%ecx
movl    initial_gs(%rip),%eax
movl    initial_gs+4(%rip),%edx
wrmsr

请注意代码最后的 wrmsr 指令:它把 edx:eax 寄存器指定的地址写入到由 ecx 寄存器指定的 model specific register(MSR)中。这里的 ecx 值是 $MSR_GS_BASE,定义在 arch/x86/include/uapi/asm/msr-index.h:

#define MSR_GS_BASE             0xc0000101

MSR_GS_BASE 定义了该 MSR 的编号。由于在 64-bit 模式中 cs、ds、es、ss 不再用于寻址,这些段寄存器的值会被忽略,但内核仍可通过 fs 和 gs 寄存器访问内存空间。MSR 提供了一种"后门"来访问这些段寄存器的基址,让我们可以通过 fs 和 gs 访问 64-bit 的基地址。上面的代码正是把某个地址映射到 GS.base 域。

再看 initial_gs 的定义:

GLOBAL(initial_gs)
        .quad   INIT_PER_CPU_VAR(irq_stack_union)

这段代码将 irq_stack_union 传递给 INIT_PER_CPU_VAR 宏,后者只是给输入参数添加 init_per_cpu__ 前缀,从而得到符号 init_per_cpu__irq_stack_union。再看 arch/x86/kernel/vmlinux.lds.S 链接脚本中的定义:

#define INIT_PER_CPU(x) init_per_cpu__##x = x + __per_cpu_load
INIT_PER_CPU(irq_stack_union);

这告诉我们符号 init_per_cpu__irq_stack_union 的地址是 irq_stack_union + __per_cpu_load。接下来定位 init_per_cpu__irq_stack_union 与 __per_cpu_load 的具体含义。

irq_stack_union 的定义出现在 arch/x86/include/asm/processor.h 中,其中的 DECLARE_INIT_PER_CPU 宏展开后又调用了 init_per_cpu_var 宏:

DECLARE_INIT_PER_CPU(irq_stack_union);

#define DECLARE_INIT_PER_CPU(var) \
       extern typeof(per_cpu_var(var)) init_per_cpu_var(var)

#define init_per_cpu_var(var)  init_per_cpu__##var

将所有宏展开之后可以得到与之前相同的名称 init_per_cpu__irq_stack_union,但此时它不再只是一个符号,而是一个变量。注意表达式 typeof(per_cpu_var(var))——此时 var 是 irq_stack_union,而 per_cpu_var 宏在 arch/x86/include/asm/percpu.h 中定义:

#define PER_CPU_VAR(var)        %__percpu_seg:var

其中:

#ifdef CONFIG_X86_64
    #define __percpu_seg gs
#endif

因此,内核实际访问的是 gs:irq_stack_union,它的类型是 irq_union。至此,我们定义了第一个 per-cpu 变量并知道了它的地址。

再看第二个符号 __per_cpu_load,该符号定义在 include/asm-generic/sections.h,它代表一系列 per-cpu 变量的数据区域的基地址:

extern char __per_cpu_load[], __per_cpu_start[], __per_cpu_end[];

于是我们知道了 irq_stack_union 与 __per_cpu_load 的地址,并且确认变量 init_per_cpu__irq_stack_union 位于 __per_cpu_load。从 System.map 中可以印证:

ffffffff819ed000 D __init_begin
ffffffff819ed000 D __per_cpu_load
ffffffff819ed000 A init_per_cpu__irq_stack_union

回到之前的汇编代码:

movl    $MSR_GS_BASE,%ecx
movl    initial_gs(%rip),%eax
movl    initial_gs+4(%rip),%edx
wrmsr

此时通过 MSR_GS_BASE 指定平台相关寄存器,将 initial_gs 的 64-bit 地址放入 edx:eax,然后执行 wrmsr,把 init_per_cpu__irq_stack_union 的基地址写入 gs 寄存器——这个地址正是 per-cpu 中断栈的栈底。关于 per-cpu 变量的分配机制(.data..percpu 段、setup_per_cpu_areas、per_cpu_ptr 偏移计算),可参阅Per-cpu 变量章节;而 irq_stack_union 联合体中 gs_base[40] 与 stack_canary 的布局设计,在第一部分中已有详细说明。

早期 IDT 的填充:early_idt_handler_array

设置完 gs 基址后,内核进入 arch/x86/kernel/head64.c 中 x86_64_start_kernel 函数的 C 代码,完成最后的准备工作后进入与平台无关的通用内核代码。如果你读过早期中断和异常处理章节,应该记得其中一项工作就是把中断服务程序入口地址填入早期 IDT:

for (i = 0; i < NUM_EXCEPTION_VECTORS; i++)
        set_intr_gate(i, early_idt_handlers[i]);

load_idt((const struct desc_ptr *)&idt_descr);

上游内核演进中,该数组名称由 early_idt_handlers 更名为 early_idt_handler_array(相关改动已合入主线),现在的代码为:

for (i = 0; i < NUM_EXCEPTION_VECTORS; i++)
        set_intr_gate(i, early_idt_handler_array[i]);

load_idt((const struct desc_ptr *)&idt_descr);

如你所见,唯一区别在于中断服务程序入口点数组的名称改为 early_idt_handler_array:

extern const char early_idt_handler_array[NUM_EXCEPTION_VECTORS][EARLY_IDT_HANDLER_SIZE];

其中:

#define NUM_EXCEPTION_VECTORS 32
#define EARLY_IDT_HANDLER_SIZE 9

因此,数组 early_idt_handler_array 存放着中断服务程序入口,每个入口占据 9 个字节:其中 2 字节用于向栈中压入默认错误码(当异常本身没有提供错误码时)、2 字节用于压入向量号、剩余 5 字节用于跳转到公共异常处理程序。early_idt_handler_array 定义在 arch/x86/kernel/head_64.S 中,使用 .rept NUM_EXCEPTION_VECTORS 批量生成前 32 个异常处理程序入口,其中也包含 early_make_pgtable 的缺页中断服务函数入口(其实现详见早期中断和异常控制):

ENTRY(early_idt_handler_array)
...
ENDPROC(early_idt_handler_common)

至此,x86_64 平台相关代码告一段落,接下来进入通用内核代码。当然,之后还会在 setup_arch 函数中重新回到平台相关代码,但这已是 x86_64 平台早期代码的最后部分。

为中断栈设置 Stack Canary

按照内核初始化过程章节的阅读路径,arch/x86/kernel/head_64.S 之后进入 init/main.c 中函数体最大的函数 start_kernel。这个函数将完成内核以 pid 为 1 运行第一个 init 进程之前的所有初始化工作。其中,与中断和异常处理相关的第一件事是调用 boot_init_stack_canary 函数——它通过设置 canary 值来防止中断栈溢出。

该函数实现在 arch/x86/include/asm/stackprotector.h,其行为取决于内核配置选项 CONFIG_CC_STACKPROTECTOR。如果该选项没有置位,函数将是一个空函数:

#ifdef CONFIG_CC_STACKPROTECTOR
...
#else
static inline void boot_init_stack_canary(void)
{
}
#endif

如果设置了 CONFIG_CC_STACKPROTECTOR,boot_init_stack_canary 一开始将检查联合体 irq_stack_union 的状态。这个联合体代表了 per-cpu 中断栈,其 stack_canary 成员与栈底之间有 40 个字节的偏移:

#ifdef CONFIG_X86_64
        BUILD_BUG_ON(offsetof(union irq_stack_union, stack_canary) != 40);
#endif

irq_stack_union 联合体的定义如下(位于 arch/x86/include/asm/processor.h):

union irq_stack_union {
        char irq_stack[IRQ_STACK_SIZE];

    struct {
                char gs_base[40];
                unsigned long stack_canary;
        };
};

C 语言中的联合体是一种多个数据结构共用一片内存的描述。第一个数据域 gs_base 大小为 40 字节,代表 irq_stack 的栈底。因此,BUILD_BUG_ON 对偏移的检查应能成功通过(BUILD_BUG_ON 宏的详细信息可参见内核初始化过程章节)。

紧接着,内核使用随机数和时戳计数器(TSC)计算新的 canary 值:

get_random_bytes(&canary, sizeof(canary));
tsc = __native_read_tsc();
canary += tsc + (tsc << 32UL);

并通过 this_cpu_write 宏将 canary 值写入 irq_stack_union 中:

this_cpu_write(irq_stack_union.stack_canary, canary);

this_cpu_* 系列宏提供了免抢占的 per-cpu 访问方式,其语义与 get_cpu_var/put_cpu_var 系列一致,区别在于 this_cpu_* 假定代码已处于不可抢占的上下文中。

禁用/使能本地中断:local_irq_disable 与 local_irq_enable

在 init/main.c 中,设置 canary 之后与中断处理相关的下一步是调用 local_irq_disable 宏。这个宏定义在 include/linux/irqflags.h,宏如其名,调用它将禁用本地 CPU 的中断。它的实现首先依赖于内核配置选项 CONFIG_TRACE_IRQFLAGS_SUPPORT:

#ifdef CONFIG_TRACE_IRQFLAGS_SUPPORT
...
#define local_irq_disable() \
         do { raw_local_irq_disable(); trace_hardirqs_off(); } while (0)
...
#else
...
#define local_irq_disable()     do { raw_local_irq_disable(); } while (0)
...
#endif

两者的唯一区别在于:当 CONFIG_TRACE_IRQFLAGS_SUPPORT 使能时,local_irq_disable 还会调用 trace_hardirqs_off 函数。在 Linux 死锁检测模块 lockdep 中有一项 irq-flags tracing 功能,可以追踪 hardirq 和 softirq 的状态,从而提供系统中硬/软中断开/关事件的统计信息。

trace_hardirqs_off 函数定义在 kernel/locking/lockdep.c:

void trace_hardirqs_off(void)
{
         trace_hardirqs_off_caller(CALLER_ADDR0);
}
EXPORT_SYMBOL(trace_hardirqs_off);

它只是调用了 trace_hardirqs_off_caller。该函数检查当前进程的 hardirqs_enabled 域:如果本次 local_irq_disable 调用是冗余的,就使 redundant_hardirqs_off 域增长,否则使 hardirqs_off_events 域增加。这些域以及其他与 lockdep 统计相关的域,定义在 kernel/locking/lockdep_insides.h 的 lockdep_stats 结构体中:

struct lockdep_stats {
...
int     softirqs_off_events;
int     redundant_softirqs_off;
...
}

如果使能了 CONFIG_DEBUG_LOCKDEP 内核配置选项,lockdep_stats_debug_show 函数会将所有调试信息写入 /proc/lockdep:

static void lockdep_stats_debug_show(struct seq_file *m)
{
#ifdef CONFIG_DEBUG_LOCKDEP
    unsigned long long hi1 = debug_atomic_read(hardirqs_on_events),
        hi2 = debug_atomic_read(hardirqs_off_events),
        hr1 = debug_atomic_read(redundant_hardirqs_on),
        ...
    seq_printf(m, " hardirq on events:             %11llu\n", hi1);
    seq_printf(m, " hardirq off events:            %11llu\n", hi2);
    seq_printf(m, " redundant hardirq ons:         %11llu\n", hr1);
#endif
}

可以通过如下命令查看其内容:

$ sudo cat /proc/lockdep
 hardirq on events:             12838248974
 hardirq off events:            12838248979
 redundant hardirq ons:               67792
 redundant hardirq offs:         3836339146
 softirq on events:                38002159
 softirq off events:               38002187
 redundant softirq ons:                   0
 redundant softirq offs:                  0

local_irq_disable 宏的实现中都包含 raw_local_irq_disable,它定义在 arch/x86/include/asm/irqflags.h,展开后是:

static inline void native_irq_disable(void)
{
        asm volatile("cli": : :"memory");
}

cli 指令清除 IF(Interrupt Flag)标志位,该标志控制处理器是否响应中断或异常。与之相对的是 local_irq_enable 宏,实现与 local_irq_disable 相似、具有相同的调试机制,区别在于使用 sti 指令使能中断:

static inline void native_irq_enable(void)
{
        asm volatile("sti": : :"memory");
}

为什么叫"本地"中断?早期版本的内核提供了一个叫 cli 的函数来禁用所有处理器的中断,该函数已被移除,取而代之的 local_irq_{enable,disable} 宏只作用于当前处理器。调用 local_irq_disable 禁用中断之后,内核接着设置变量值:

early_boot_irqs_disabled = true;

变量 early_boot_irqs_disabled 定义在 include/linux/kernel.h:

extern bool early_boot_irqs_disabled;

它会在其他地方被使用。例如在 kernel/smp.c 的 smp_call_function_many 函数中,通过该变量检查当前是否由于中断禁用而处于死锁状态:

WARN_ON_ONCE(cpu_online(this_cpu) && irqs_disabled()
                     && !oops_in_progress && !early_boot_irqs_disabled);

内核初始化过程中的早期 trap 初始化

在 local_irq_disable 之后执行的是 boot_cpu_init 和 page_address_init,这两个函数与中断和异常处理无关(更多信息参见内核初始化章节)。接下来是 setup_arch 函数,它定义在 arch/x86/kernel/setup.c,完成很多架构相关的初始化工作(详见体系架构初始化章节)。

在 setup_arch 中与中断相关的第一个函数是 early_trap_init,定义于 arch/x86/kernel/traps.c,它用若干处理程序入口填充 IDT:

void __init early_trap_init(void)
{
        set_intr_gate_ist(X86_TRAP_DB, &debug, DEBUG_STACK);
        set_system_intr_gate_ist(X86_TRAP_BP, &int3, DEBUG_STACK);
#ifdef CONFIG_X86_32
        set_intr_gate(X86_TRAP_PF, page_fault);
#endif
        load_idt(&idt_descr);
}

这里出现了三个不同的函数调用:

  • set_intr_gate_ist
  • set_system_intr_gate_ist
  • set_intr_gate

这些函数都定义在 arch/x86/include/asm/desc.h 中,做的事情也差不多。第一个函数 set_intr_gate_ist 将一个新的中断门插入到 IDT,实现如下:

static inline void set_intr_gate_ist(int n, void *addr, unsigned ist)
{
        BUG_ON((unsigned)n > 0xFF);
        _set_gate(n, GATE_INTERRUPT, addr, 0, ist, __KERNEL_CS);
}

该函数首先检查参数 n(中断向量编号)不大于 0xff(即 255)。如第一部分所述,中断向量号必须处于 0 到 255 的闭区间。然后调用 _set_gate 函数将中断门设置到 IDT:

static inline void _set_gate(int gate, unsigned type, void *addr,
                             unsigned dpl, unsigned ist, unsigned seg)
{
        gate_desc s;

        pack_gate(&s, type, (unsigned long)addr, dpl, ist, seg);
        write_idt_entry(idt_table, gate, &s);
        write_trace_idt_entry(gate, &s);
}

首先通过 pack_gate 函数填充表示 IDT 表项的 gate_desc 结构体,参数包括基地址、段选择子、中断栈表(IST)、特权等级(DPL)和中断类型。中断类型的取值有:

  • GATE_INTERRUPT
  • GATE_TRAP
  • GATE_CALL
  • GATE_TASK

并设置该 IDT 表项的 present 位:

static inline void pack_gate(gate_desc *gate, unsigned type, unsigned long func,
                             unsigned dpl, unsigned ist, unsigned seg)
{
        gate->offset_low        = PTR_LOW(func);
        gate->segment           = __KERNEL_CS;
        gate->ist               = ist;
        gate->p                 = 1;
        gate->dpl               = dpl;
        gate->zero0             = 0;
        gate->zero1             = 0;
        gate->type              = type;
        gate->offset_middle     = PTR_MIDDLE(func);
        gate->offset_high       = PTR_HIGH(func);
}

然后通过 write_idt_entry 宏把中断门写入 IDT。该宏展开后是 native_write_idt_entry,按索引把门描述符拷贝到 idt_table:

#define write_idt_entry(dt, entry, g)           native_write_idt_entry(dt, entry, g)

static inline void native_write_idt_entry(gate_desc *idt, int entry, const gate_desc *gate)
{
        memcpy(&idt[entry], gate, sizeof(*gate));
}

其中 idt_table 是一个 gate_desc 类型的数组:

extern gate_desc idt_table[];

关于 gate_desc 在 x86_64 下的位域布局(offset_low、segment、ist、dpl、p、offset_middle、offset_high),可参见第一部分对 gate_struct64 的完整剖析,也可参考内核数据结构:中断描述符表中对异常向量与错误码格式的说明。

函数 set_system_intr_gate_ist 的实现仅有一处不同:

static inline void set_system_intr_gate_ist(int n, void *addr, unsigned ist)
{
        BUG_ON((unsigned)n > 0xFF);
        _set_gate(n, GATE_INTERRUPT, addr, 0x3, ist, __KERNEL_CS);
}

注意 _set_gate 的第四个参数是 0x3,而在 set_intr_gate_ist 中该值是 0x0——这个参数是 DPL(描述符特权级)。其中 0 代表最高特权等级,3 代表最低特权等级。回到 early_trap_init:

set_intr_gate_ist(X86_TRAP_DB, &debug, DEBUG_STACK);
set_system_intr_gate_ist(X86_TRAP_BP, &int3, DEBUG_STACK);

这里设置了 #DB(调试异常)和 #BP(断点异常,由 int 3 指令触发)两个 IDT 表项,它们使用 DEBUG_STACK 作为中断栈表索引。这两个函数输入相同的参数组:中断向量号、中断处理程序地址、中断栈表索引。为何 #DB 使用 set_intr_gate_ist(DPL=0)而 #BP 使用 set_system_intr_gate_ist(DPL=3)?因为 #BP 异常可以由用户空间执行 int 3 触发,必须允许从特权级 3 进入;而调试寄存器操作只能在特权模式下进行,#DB 异常处理不应开放给低特权级。这两个异常处理程序的完整实现(idtentry 宏、paranoid_entry、error_entry、sync_regs 等)将在异常处理章节深入展开。

总结

本篇是 Linux 内核中断与中断处理系列的第二部分。我们在第一部分了解了中断与异常处理的理论,并在本篇开始深入阅读相关代码:从启动最早期的空 IDT 加载(setup_idt)、保护模式跳转链,到 gs 基址与 per-cpu 中断栈(irq_stack_union)的建立、早期 IDT 的填充(early_idt_handler_array)、中断栈 canary 的设置(boot_init_stack_canary)、本地中断的禁用与使能(local_irq_disable/local_irq_enable),最后到 setup_arch 中的早期 trap 初始化(early_trap_init 与 set_intr_gate_ist 系列函数)。下一部分将继续深入这个主题,分析 #DB/#BP 等异常处理程序的汇编级实现。

延伸阅读

登录后查看全文
linux-insides-zh