[教育訓練紀錄] Spinlock in Process-Context Code

jollen 發表於 April 22, 2007 2:21 PM

紀錄 Linux device driver 課程,關於「spinlock」的討論。

Kernel synchronization 的機制中,semaphore 有二種版本可供使用:

- Semaphore: down(), up()

- Spinlock

二種不同的 semaphore 實作的差異在於「P operation」的實作:

- down/up, 採取 sleeping 方式

- spinlock, 採取 busy loop 方式

在 interrupt handler 的實作上,由於 kernel 並非與 process context 做切換(kernel 執行的是 interrupt-context code),無法進行系統的 rescheduling,所以只能使用 spinlock 來進入 critical section。另外,我們提到,在 process-context mode 也常會看到 spinlock 的使用;在一般的 system call 實作函數裡,為什麼用 spinlock 而不是典型的 down/up 呢?道理在於,「如果 P operation 的等待時間相當短暫(semaphore holding 的時間很短),那麼使用 busy-loop 的方式便會比排程 task 為 INTERRUPTIBLE/UNINTERRUPTIBLE 狀態(sleep)來得更有效率」。

Linux 提供了三類的 spinlock API:

- IRQ don't care, 不對 local interrupt 做任何設定

- IRQ disabling, 將 local interrupt 設定為 disable

- IRQ save/restore, 儲存/還原 local interrupt 狀態

狀況一:當我們選擇在 non-interrupt mode 或是 process-context mode 使用 busy-loop 版本的 semaphore 時,若要確保 critical section 為 atomic operation,或是與 interrupt handler 做同步,此時就必須使用 IRQ disabling 的 spinlock,以確保 critical section 不會被 interrupt 打斷,且讓 processor 不會再接受任何的 interrupt。IRQ-disabling spinlock API 如下:

- spin_lock_irq

- spin_unlock_irq

同學可查閱課堂所發的補充資料,觀念上的疑問,可透過 forum 來詢問。

來源: Jollen's Blog

Jollen's Blog 使用 Github issues 與讀者交流討論。請點擊上方的文章專屬 issue,或 open a new issue

您可透過電子郵件 jollen@jollen.org,或是 Linkedin 與我連絡。更歡迎使用微信,請搜尋 WeChat ID:jollentw