What is Interrupt?

Introduction

我們可以將 Interrupt 想成 device 版的 signal,signal 是用來讓 OS 通知 Applications 特定事件的到來,而 Interrupt(廣義)是讓 CPU 暫停當前執行流、轉交控制給 OS 的機制;Hardware Interrupt 是其中由外部 device 觸發的那一類

Why we need interrupt?

沒有 interrupt 的話,OS 必須用 busy-waiting 不斷去讀硬體暫存器確認事件是否發生,這會浪費大量 CPU cycle。Interrupt 讓硬體在「真的有事」時才主動通知 OS,CPU 平時可以做其他事


Types of Interrupt

Hardware Interrupt

由外部裝置發出的信號,像是鍵盤按下、計時器到期、網卡收到封包

Asynchronous

CPU 無法預知此種 interrupt 的到來

Maskable vs. Nonmaskable

  • Maskable:CPU 可以暫時將其遮蔽(mask off),通常在執行不能被打斷的關鍵指令序列時使用(e.g. 更新 kernel 資料結構)
  • Nonmaskable (NMI):不能被遮蔽,保留給嚴重事件(e.g. 不可修復的記憶體錯誤),CPU 無論如何都必須立即處理

Exception

CPU 偵測到錯誤或特殊狀況,像是 divide by zero, segmentation fault 之類的

Synchronous

因為這種 Exception 是因為某一條指令而產生

Software Interrupt / Trap

程式碼在 user space 做不到一些事情,這時候就需要執行一條特殊指令(syscall)來讓 CPU 切入 kernel mode (ring 0) 幫你做完後再轉回 user mode 並交還控制權給你


How does Interrupt works?

Prerequisite (boot time): Initialize Interrupt Vector Table (IVT)

OS 在開機時將各個 ISR 所在的記憶體位置寫到 IVT 上,讓 CPU 之後知道去哪裡找 ISR

Step 1: Device Raises an IRQ signal

Device 偵測到 event(像是鍵盤被按下)後會透過 interrupt-request line(一條硬體訊號線)送 IRQ (Interrupt Request) 給 PIC (Programmable Interrupt Controller),他會將對應的優先級和 Interrupt number 送給 CPU

Step 2: CPU detects the interrupt

CPU 會在完成每個 instruction 後檢查有沒有 IRQ

Step 3: CPU saves current state to the kernel stack

CPU 會先將 program counter, registers 資訊存到 kernel stack (per-CPU interrupt stack),這樣之後要回來執行原來的任務才知道之前執行到哪裡

Step 4: CPU queries the IVT for the ISR address

CPU 去 IVT 看看這個 Interrupt number 對應的 ISR 被存在哪裡

Step 5: CPU jumps to the ISR and executes the event

CPU 根據 IVT 記錄的記憶體位置跳到 ISR 存放位置並且執行去 handle event(像是去鍵盤讀取輸入之類的)

Step 6: ISR returns via iret

ISR 處理完事情後會呼叫 iret 這個特殊的 instruction 會將 CPU 在 step 3 儲存的 program state 回復過來並且繼續執行原來的任務