Polling

Basic Concept

Polling 是 CPU / host 主動反覆檢查 device controller 狀態的一種 I/O coordination 方法。Device controller 會把目前狀態放在 status register 中,例如 busy bit 代表 controller 是否正在工作。Host 如果想送出下一個 command,就一直讀 status register,直到 device 顯示 ready。

它的核心模式是:

CPU repeatedly reads device status → if ready, issue command → repeat

所以 polling 又常被稱為 busy waiting,因為 CPU 在等待期間仍然不斷執行檢查,而不是去做別的工作。

Handshaking Example

Host 和 controller 之間常用一些 bit 來協調 producer-consumer 關係。假設有兩個重要 bit:

  • busy bit:controller 設定;表示 device 是否正在處理前一個 command。
  • command-ready bit:host 設定;表示 host 已經把新 command 準備好。

一個簡化的 write 流程如下:

  1. Host 反覆讀 busy bit,直到 busy bit 被清掉,代表 controller ready。
  2. Host 把 write command 寫到 control register,並把要輸出的 byte 寫到 data-out register。
  3. Host 設定 command-ready bit。
  4. Controller 發現 command-ready bit 被設定,就把 busy bit 設為 1,表示開始處理。
  5. Controller 讀 command register 和 data-out register,執行真正的 device I/O。
  6. Controller 完成後清掉 command-ready bit、error bit、busy bit。

這個流程每傳一個小單位就可能重複一次。

Why Polling Can Be Good

Polling 的好處是簡單、直接,而且單次檢查成本很低。對很快就 ready 的 device,CPU 可能只要花幾個 instruction cycle 就能知道結果,這比進入 interrupt handling 還便宜。

因此在高 throughput、等待時間很短、或 interrupt rate 太高的情境,polling 反而可能比較有效率。例如 network device 在高速收包時,如果每個 packet 都產生 interrupt,interrupt overhead 可能比短暫 polling 更大。

Problem

Polling 的問題是它會消耗 CPU cycle。若 device 很慢或事件很少發生,CPU 可能在 loop 裡讀很多次 status register 卻什麼都沒等到,這些 cycle 本來可以拿去執行其他 process。

因此 polling 的 trade-off 是:

  • 優點:控制流程簡單,ready 時反應快,避免 interrupt overhead。
  • 缺點:若等待時間長,CPU 會浪費在 busy waiting。

Polling vs Interrupt

如果 CPU 不想一直檢查 device,就可以改讓 device 在 ready 時透過 interrupt 通知 CPU。Interrupt 把「誰主動」反過來:polling 是 CPU 問 device「好了嗎?」;interrupt 是 device 主動告訴 CPU「我好了」。

實際系統常常混用兩者:低 I/O rate 時用 interrupt,避免 CPU 空等;高 I/O rate 時改用 polling,避免大量 interrupt 造成 overhead。