多源中断优先级路由与Claim/Complete机制
PLIC(Platform-Level Interrupt Controller)是RISC-V的标准中断控制器,管理来自外部设备的中断:
| 概念 | 说明 | 默认值 |
|---|---|---|
| 优先级 | 每个中断源可设置0-7级 | 0=禁用 |
| 阈值 | 每个Hart可设优先级阈值 | 0=全部通过 |
| 使能 | 每个Hart可独立使能/禁用中断 | 全部禁用 |
| Claim | 获取当前最高优先级中断ID | - |
| Complete | 通知PLIC中断处理完毕 | - |
// Lesson 07: PLIC — Platform-Level Interrupt Controller
module plic(
input wire clk, rst_n,
input wire [7:0] irq_src,
input wire [2:0] irq_priority_0, irq_priority_1, irq_priority_2, irq_priority_3,
input wire [2:0] irq_priority_4, irq_priority_5, irq_priority_6, irq_priority_7,
input wire [7:0] irq_enable,
input wire [2:0] threshold,
input wire claim_req,
output reg [2:0] claim_id,
output reg claim_valid,
input wire complete_req,
input wire [2:0] complete_id
);
reg [2:0] priorities [0:7];
always @(*) begin
priorities[0]=irq_priority_0; priorities[1]=irq_priority_1;
priorities[2]=irq_priority_2; priorities[3]=irq_priority_3;
priorities[4]=irq_priority_4; priorities[5]=irq_priority_5;
priorities[6]=irq_priority_6; priorities[7]=irq_priority_7;
end
reg [2:0] best_id, best_priority; reg best_pending;
integer i;
always @(*) begin
best_id=0; best_priority=0; best_pending=0;
for (i=0; i<8; i=i+1)
if (irq_src[i] && irq_enable[i] && priorities[i]>threshold)
if (!best_pending || priorities[i]>best_priority ||
(priorities[i]==best_priority && i<best_id))
begin best_id=i[2:0]; best_priority=priorities[i]; best_pending=1; end
end
reg [7:0] in_flight;
always @(posedge clk or negedge rst_n) begin
if (!rst_n) begin claim_valid<=0; claim_id<=0; in_flight<=0; end
else begin
if (claim_req && best_pending && !in_flight[best_id])
begin claim_id<=best_id; claim_valid<=1; in_flight[best_id]<=1; end
else claim_valid<=0;
if (complete_req) in_flight[complete_id]<=0;
end
end
endmodule
QEMU virt平台是RISC-V开发的标准环境,其PLIC配置如下:
| 资料 | 内容 | 链接 |
|---|---|---|
| RISC-V特权规范 | CSR、Trap、中断完整定义 | riscv.org/specifications |
| RISC-V手册 | 中文版免费教材 | crva.ict.ac.cn |
| OpenSBI源码 | M-mode固件参考实现 | github.com/riscv/opensbi |
| Linux RISC-V | 内核移植与驱动 | kernel.org |
| BOOM处理器 | UC Berkeley开源OoO核心 | github.com/riscv-boom/riscv-boom |
| 香山处理器 | 中科院开源高性能核心 | github.com/OpenXiangShan |
| 课程范围 | 课程号 | 主题 |
|---|---|---|
| 特权架构 | 01-06 | 特权级→CSR→ecall→mret→trap→中断 |
| 内存系统 | 07-12 | PLIC→CLINT→SV39→TLB→直接映射→组相联 |
| 算术单元 | 13-14 | Booth乘法器→恢复余数除法 |
| 乱序执行 | 15-19 | OoO→ROB→寄存器重命名→记分牌→Tomasulo |
| 分支预测 | 20-21 | 2位预测器→BTB |
| RISC-V扩展 | 22-26 | RVC→RVM→RVA→RVF→RVD |
| 系统集成 | 27-30 | PMP→解码器→SoC→启动流程 |
建议使用以下环境进行实验:
| 特性 | PLIC | APLIC | IMSIC |
|---|---|---|---|
| 最大中断源 | 1023 | 4095 | ~200(Hart×ID) |
| 优先级级别 | 0-7 | 0-255 | 按ID排序 |
| 触发方式 | 电平/边沿 | 电平/边沿 | MSI写入 |
| 多Hart路由 | 支持 | 支持 | 每Hart独立 |
| 虚拟化 | 无 | 部分 | 完整 |
| MSI支持 | 无 | 支持 | 原生 |
PLIC是RISC-V的"基础版"中断控制器,适用于大多数嵌入式场景。APLIC和IMSIC是"高级版",适用于服务器和虚拟化场景。