---
# System prepended metadata

title: Timers and Time Management

---

# Timers and Time Management



# Timer Implementation

kernel 用 Bottom half-- softirq的方法實作timer
* timer interrupt戳進來後，timer interrupt handler runs update_process_times(), which calls run_local_timers():

![](https://i.imgur.com/LF5tCr4.png)

![](https://i.imgur.com/60LYvNH.png)

![](https://i.imgur.com/UNXH6IL.png)

![](https://i.imgur.com/jBB88sA.png)

local_softirq_pending()會跟 1UL |後根據傳下來的softirq enum值看要往左shift多少來判斷是哪種softirq
![](https://i.imgur.com/3aOzsRh.png)

多CPU環境下需要取得目前是在哪顆CPU上
![](https://i.imgur.com/AI2cErW.png)

最好把softirq拉成pending等待處理



# Delaying Execution

Often, kernel code (especially drivers) needs a way to delay execution for some time without using **timers** or a **bottom-half** mechanism.This is usually to enable hardware time to complete a given task

**Busy Looping**

爛方法，不要用
![](https://i.imgur.com/tkjWcOf.png)

**等待時schedule給其他人**

![](https://i.imgur.com/w8rQyT5.png)

jiffies 不能保證在迴圈裡他的值一直保持不變，因為這個值is incremented elsewhere, 系統需要保證每次存取他都是正確的值，所以要使用volatile.

volatile

The volatile keyword instructs the compiler to reload the variable on each access from main memory and never alias the variable’s value in a register, guaranteeing that the previous loop completes as expected.


# Small Delays

Sometimes, kernel code (again, usually drivers) requires short (smaller than a clock tick) and rather precise delays.This is often to synchronize with hardware, which again usually lists some minimum time for an activity to complete—often less than a millisecond.

* 用jiffies-based delays會太不準
* timer interrupt 
    * 100Hz, clock tick rate = 10 millisecond
    * 1000Hz = 1 millisecond
* Kernel 提供3種更精確的delay，不用jiffies的
    * void udelay(unsigned long usecs)
    * void ndelay(unsigned long nsecs)
    * void mdelay(unsigned long msecs)

![](https://i.imgur.com/9FLNZW4.png)
![](https://i.imgur.com/X25O4IU.png)
