Clocks and Timers

Basic Concept

Clock 和 timer 是 OS 用來理解「現在時間」與「未來何時要做某件事」的 I/O device。

常見功能有三種:

  1. 取得 current time。
  2. 測量 elapsed time。
  3. 設定 timer,讓系統在時間 T 觸發某個 operation。

這些功能不只 application 會用,OS kernel 自己也大量依賴它們。

Programmable Interval Timer

Programmable interval timer 是可以被 OS 設定的 hardware timer。OS 可以要求它等待一段時間後產生 interrupt,也可以要求它週期性產生 interrupt。

這個機制支撐許多 OS 功能:

  • CPU scheduling:time slice 到期時產生 interrupt,讓 OS preempt 目前 process。
  • Disk subsystem:週期性 flush dirty cache buffer。
  • Network subsystem:偵測 timeout,取消太慢或失敗的 operation。
  • User process timers:讓 application 設定未來某個時間點要收到通知。

Virtual Clocks

硬體 timer 的數量有限,但系統中可能有很多 kernel routine 和 user process 同時要求 timer。OS 因此會模擬 virtual clocks

做法是:

  1. Kernel 維護一個 timer request list,通常依照 earliest deadline 排序。
  2. Hardware timer 只設定成目前最早需要觸發的時間。
  3. Timer interrupt 發生時,kernel 通知對應 requester。
  4. Kernel 從 list 中取出下一個最早的 request,再重新設定 hardware timer。

這讓有限的 hardware timer channel 可以支援大量 logical timer request。

High-Resolution Clock

有些 hardware clock 其實是一個高頻 counter。CPU 或 kernel 可以讀取這個 counter 的值來精準測量時間間隔。這類 high-resolution clock 不一定會產生 interrupt,但很適合用來測量 elapsed time,例如 profiling 或計算 network latency。

Clock Drift

如果 OS 用 timer tick 維護 system time-of-day,實際時間可能慢慢 drift,因為 hardware clock 不是完美的。系統可以透過 NTP 這類 protocol 和外部時間來源校正,降低 drift。

Why This Is I/O

Timer 看起來不像傳統 input/output,但它仍然是 OS 與外部硬體狀態互動的一種方式。Timer device 透過 interrupt 把「時間到了」這個事件送進 CPU,OS 再根據這個 event 做 scheduling、timeout、flush、signal 等工作。