iT邦幫忙

2026 iThome 鐵人賽

DAY 26
0
Software Development

猴子都寫得出來的 RISC-V OoO CPU系列 第 28 篇

嵌入式系統三大不可思議: Interrupt, Exception, Trap

  • 分享至 

  • xImage
  •  

小時候學的時候都是靠老招:背下來
但實際上為什麼他是 synchronous,為什麼是 asynchronous 沒有太多直觀的認識
這件事的本質原因是 ISA 是一個抽象層
讓使用的人不需要理解背後在做什麼
但反過來也會讓沒寫過的人很難理解背後是什麼
就像 C 語言,使用 printf 的時候根本不會知道系統做了哪些事一樣
我們就可以透過神秘的介面來操作 CPU 資源,得到對應的結果

先分兩部分

  • exception(synchornous): 會在指令內觸發的行為
    例如 branch 跳到一個不能用的 target,這邊的實作會到 retire 階段處理
  • interrupt(asynchronous): cpu 外部的周邊裝置發出來跟 CPU 互動的訊號
    例如 timer 時間到了,就 set irq_external,這邊的實作 cpu 在下一個 cycle 就會把所有指令 flush

在 x86 定義下,exception 裡面有一個分支是 trap,是 software 預期的 exception
例如 ECALL, EBREAK 就數於這種,但每家 CPU 的寫法和定義其實都不一樣
在 riscv spec 有描述 trap 是指把流程轉交給 handler 的行為,不限定是由 exception 觸發
1.6. Exceptions, Traps, and Interrupts:

We use the term exception to refer to an unusual condition occurring at run time associated with an
instruction in the current RISC-V hart. We use the term interrupt to refer to an external asynchronous
event that may cause a RISC-V hart to experience an unexpected transfer of control. We use the term trap
to refer to the transfer of control to a trap handler caused by either an exception or an interrupt.

其他的 exception 則可以依照能不能在 handler 修復分成兩種

  • recoverable: 以在 handler 處理修復的類型
    例如 page fault 就可以在 handler 處理, mret 再跳回同一到指令執行一次
  • non-recoverable: handler 恢復到可安全繼續執行原指令的狀態,後續行為看系統怎麼設計
    例如 access fault 就會送 segmentation fault signal 給 linux process

題外話:
exception 其實不一定是在哪個階段發生
可能在 retire 或者其他可以辨識出來 exception 的階段處理
真實的行為是什麼都是看實作

甚至發生的時間點也沒辦法完整保留對應的 arch register status
如果有學過初版的 Tomasulo's Algorithm 演算法就會知道 ROB 不是一開始就被包含進去
當初是為了加速浮點數運算設計出來的演算法,執行的 instruction 會直接更新 architecture register
這個情況就會有 non-precise exception 難以 debug 的問題
當初是只有在 floating point 單元上採用(IBM System/360 Model 91)
後來加入 ROB 之後才有 pricise exception 的能力


上一篇
Exception!
系列文
猴子都寫得出來的 RISC-V OoO CPU 共 28 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言