Interrupt (中斷)
目錄
何謂中斷
CPU在執行程式過程中,遇到外部或內部的緊急事件(event)須優先處理,因此暫停執行當前的程式,轉而服務突發的事件,直到服務完畢,再回到原先的暫停處(為一記憶體地址)繼續執行原本尚未完成的程式,或是不回到原先暫停處而是直接終止程式。為突發事件服務的程式稱之為中斷服務程式(Interrupt Service Routine, ISR)或Interrupt Handler。中斷有劃分為一般中斷(Interrupt)和異常中斷(Exception),常見的一般中斷有如System Call或硬碟I/O中斷,而異常中斷如除以0或不正確的記憶體存取(Segmentation Fault)。
Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
以上圖為例,在使用者對kernel發出system call運行process時,kernel即開始執行該程序,假如中間有突發的中斷產生,會從原先執行的process中的中斷點暫時跳出,進而對其進行服務,直到完成該中斷服務後再回到中斷點繼續執行原先的程序。
外部中斷
外部中斷源自於硬體,一般是指由硬體發出的中斷請求,外部中斷又分為可以遮蔽的(Maskable)中斷如GPIO中斷、硬碟I/O中斷和不可遮蔽的(Unmaskable)中斷如Watchdog timeout,也就是說可以遮蔽的中斷利用中斷控制器可以遮蔽這些外部裝置的中斷請求。
內部中斷
內部中斷是指因硬體出錯(如突然掉電、奇偶校驗錯、除數為零等)或特殊中斷breakpoint(debugger)或是呼叫System Calls所引起的中斷。內部中斷是不可遮蔽的中斷。
Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
硬體中斷
- GPIO中斷
- 硬碟I/O中斷
- Watchdog timeout
- 除數為零
- Segmentation Fault
Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
軟體中斷
- 單步執行(debugger)
- breakpoint(debugger)
- System Calls
- kill
Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
中斷向量
通常在主記憶體中低斷位置的一塊保留區會存放Interrupt Vector,存放著各種中斷的ID及其服務程式的起始位址,當中斷發生時,會根據此向量表找到對應的中斷服務程式,並跳至指定的起始位址去執行。
巢狀中斷
Image Not Showing
Possible Reasons
- The image was uploaded to a note which you don't have access to
- The note which the image was originally uploaded to has been deleted
Learn More →
就一般情況來看,當中斷發生時,作業系統會透過查找中斷向量表將中斷交給指定的 ISR 處理,這時候如果又有新的中斷產生,就會產生巢狀中斷(nested interrupt)。
在設計 OS Kernel 時要小心的處理 Nested Interrupt,比如說:很多作業系統利用 Timer Interrupt 做到 Task Preemption,但如果在處理 Timer Interrupt 時又產生了新的 Timer Interrupt,我們就要在 ISR 裡面判斷是不是需要做任務切換,最簡單的作法是宣告一個 Counter,每次進入 ISR 時 Counter + 1,離開 ISR 時 Counter - 1,只有在 Counter 為 1 時才做 preemption。
當然,也有部分的處理器架構會在進入中斷時自動屏蔽新的中斷處理(e.g. RISC-V),這種作法也是最簡單暴力的。
本章節練習與反思
延伸閱讀
參考資料
- 中斷與中斷處理
- Interrupts in Linux
- Linux核心設計:中斷處理和現代架構考量
- Philippe Darche, "Interrupt Mechanism," in Microprocessor 4: Core Concepts - Software Aspects , Wiley, 2020, pp.119-162, doi: 10.1002/9781119801979.ch5. keywords: {Hardware;Microprocessors;Software;Context;Standards;NIST;Moon},