Linux 2.6.11 的軟中斷線程 ksoftirqd 是一段很值得細讀的程式碼,它在「一次處理更多」與「不要讓別人餓死」之間的取捨,幾乎寫在每一行裡。
schedule() 切出,並因為狀態已設為 TASK_INTERRUPTIBLE 而被移出執行佇列。cond_resched() 主動切出,避免其他線程餓死。此時狀態仍是 TASK_RUNNING,所以不會被移出佇列——活還沒幹完,得趕快回來,而且切出前關閉了核心搶佔,很快就會被重新排到。TASK_INTERRUPTIBLE,為下一輪「沒事就切出並移出佇列」做準備。舉個例子:一次來了 8 個軟中斷,期間可能多次主動切出;若剛好處理完最後一個時又碰上 cond_resched() 判定時間片用完而切出,等切回來發現空檔期間又來了新的軟中斷,那就繼續處理。
static int ksoftirqd (void * __bind_cpu)
{
set_user_nice(current, 19); /* 以最低優先級運行 */
current->flags |= PF_NOFREEZE;
set_current_state(TASK_INTERRUPTIBLE); /* 進主循環前先設為可中斷睡眠 */
while (!kthread_should_stop()) {
if (!local_softirq_pending()) /* 沒事做:切出並移出佇列 */
schedule();
__set_current_state(TASK_RUNNING); /* 有活:恢復為可運行 */
while (local_softirq_pending()) { /* 干活的主循環 */
preempt_disable(); /* 關搶佔,確保能連續處理完 */
if (cpu_is_offline((long)__bind_cpu))
goto wait_to_die;
do_softirq(); /* 處理軟中斷 */
preempt_enable();
cond_resched(); /* 跑太久主動切出,狀態仍是 RUNNING */
}
set_current_state(TASK_INTERRUPTIBLE); /* 為下一輪切出做準備 */
}
__set_current_state(TASK_RUNNING);
return 0;
wait_to_die: /* 只有出錯才會走到這裡 */
preempt_enable();
set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop()) {
schedule();
set_current_state(TASK_INTERRUPTIBLE);
}
__set_current_state(TASK_RUNNING);
return 0;
}
再看 cond_resched() 與它的判斷依據:
int __sched cond_resched (void)
{
if (need_resched()) {
__cond_resched();
return 1;
}
return 0;
}
static inline void __cond_resched (void)
{
do {
add_preempt_count(PREEMPT_ACTIVE); /* 搶佔計數++,讓本線程切出後盡快切回 */
schedule();
sub_preempt_count(PREEMPT_ACTIVE);
} while (need_resched());
}
static inline int need_resched (void)
{
return unlikely(test_thread_flag(TIF_NEED_RESCHED));
}
TIF_NEED_RESCHED 主要由時鐘中斷裡的 scheduler_tick() 設定,用來標記本線程時間片是否用完。因為此時關著核心搶佔,若不主動讓出,其他線程真的會被餓著。
這套「沒事就睡、有事就幹、幹太久就讓一讓」的骨架,可以直接套用到任何類似的核心線程:
static int kmythread (...)
{
...
set_current_state(TASK_INTERRUPTIBLE);
while (!kthread_should_stop()) {
__set_current_state(TASK_RUNNING);
while (/* 自己的佇列裡還有資料要處理 */) {
preempt_disable();
/* 干活... */
preempt_enable();
cond_resched();
}
set_current_state(TASK_INTERRUPTIBLE);
}
__set_current_state(TASK_RUNNING);
return 0;
}
關鍵就在三個狀態轉換的時機,以及 preempt_disable() 與 cond_resched() 的配對:前者保證批次處理的完整性,後者保證系統整體的公平性。