陳鐵+ 原創作品轉載請註明出處 + 《Linux內核分析》MOOC課程http://mooc.study.163.com/course/USTC-1000029000
對於現代操作系統,多任務是必備的,在linux系統下,進程會不斷的被內核調度,從X進程切換爲Y進程,以實現用戶所見到的多任務狀態,下面我們就看一看這樣的過程,分析一下內核如何對進程調度,以及進程間如何切換。
內核使用schedule()函數實現進程的調度,而通常的用戶進程要無法主動調度這個函數,只能通過中斷處理過程(包括時鐘中斷、I/O中斷、系統調用和異常)在某個合適的時機點被動調度;對於現代操作系統,還有內核線程,而內核線程是可以直接調度schedule函數的,只有內核態,當然也可以象用戶態進程一樣在中斷處理過程中被動調度。
爲了控制進程的執行,內核必須有能力掛起正在CPU上執行的進程,並恢復以前掛起的某個進程的執行,這叫做進程切換、任務切換、上下文切換;掛起正在CPU上執行的進程,與中斷時保存現場不同的,中斷前後是在同一個進程上下文中,只是由用戶態轉向內核態執行;而進程切換是在兩個進程之間進行轉換,切換前後的上下文是在不同的進程空間。進程上下文包含了進程執行需要的所有信息:用戶地址空間:包括程序代碼,數據,用戶堆棧等;控制信息:進程描述符,內核堆棧等;硬件上下文。
下面將進程切換的關鍵代碼摘錄如下:
1、schedule函數
asmlinkage __visible void __sched schedule(void) { struct task_struct *tsk = current; sched_submit_work(tsk); __schedule(); }
2、__schedule()函數
2770static void __sched __schedule(void) 2771{ 2772 struct task_struct *prev, *next; 2773 unsigned long *switch_count; 2774 struct rq *rq; 2775 int cpu; 2776 2777need_resched: 2778 preempt_disable(); 2779 cpu = smp_processor_id(); 2780 rq = cpu_rq(cpu); 2781 rcu_note_context_switch(cpu); 2782 prev = rq->curr; 2783 2784 schedule_debug(prev); 2785 2786 if (sched_feat(HRTICK)) 2787 hrtick_clear(rq); 2788 2789 /* 2790 * Make sure that signal_pending_state()->signal_pending() below 2791 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE) 2792 * done by the caller to avoid the race with signal_wake_up(). 2793 */ 2794 smp_mb__before_spinlock(); 2795 raw_spin_lock_irq(&rq->lock); 2796 2797 switch_count = &prev->nivcsw; 2798 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) { 2799 if (unlikely(signal_pending_state(prev->state, prev))) { 2800 prev->state = TASK_RUNNING; 2801 } else { 2802 deactivate_task(rq, prev, DEQUEUE_SLEEP); 2803 prev->on_rq = 0; 2804 2805 /* 2806 * If a worker went to sleep, notify and ask workqueue 2807 * whether it wants to wake up a task to maintain 2808 * concurrency. 2809 */ 2810 if (prev->flags & PF_WQ_WORKER) { 2811 struct task_struct *to_wakeup; 2812 2813 to_wakeup = wq_worker_sleeping(prev, cpu); 2814 if (to_wakeup) 2815 try_to_wake_up_local(to_wakeup); 2816 } 2817 } 2818 switch_count = &prev->nvcsw; 2819 } 2820 2821 if (task_on_rq_queued(prev) || rq->skip_clock_update < 0) 2822 update_rq_clock(rq); 2823 2824 next = pick_next_task(rq, prev); 2825 clear_tsk_need_resched(prev); 2826 clear_preempt_need_resched(); 2827 rq->skip_clock_update = 0; 2828 2829 if (likely(prev != next)) { 2830 rq->nr_switches++; 2831 rq->curr = next; 2832 ++*switch_count; 2833 2834 context_switch(rq, prev, next); /* unlocks the rq */ 2835 /* 2836 * The context switch have flipped the stack from under us 2837 * and restored the local variables which were saved when 2838 * this task called schedule() in the past. prev == current 2839 * is still correct, but it can be moved to another cpu/rq. 2840 */ 2841 cpu = smp_processor_id(); 2842 rq = cpu_rq(cpu); 2843 } else 2844 raw_spin_unlock_irq(&rq->lock); 2845 2846 post_schedule(rq); 2847 2848 sched_preempt_enable_no_resched(); 2849 if (need_resched()) 2850 goto need_resched; 2851}
其中關鍵語句:
struct task_struct *prev, *next; next = pick_next_task(rq, prev); //進程調度算法 context_switch(rq, prev, next); /* unlocks the rq */ //進程上下文切換
3、context_switch函數
2332 * context_switch - switch to the new MM and the new 2333 * thread's register state. 2334 */ 2335static inline void 2336context_switch(struct rq *rq, struct task_struct *prev, 2337 struct task_struct *next) 2338{ 2339 struct mm_struct *mm, *oldmm; 2340 2341 prepare_task_switch(rq, prev, next); 2342 2343 mm = next->mm; 2344 oldmm = prev->active_mm; 2345 /* 2346 * For paravirt, this is coupled with an exit in switch_to to 2347 * combine the page table reload and the switch backend into 2348 * one hypercall. 2349 */ 2350 arch_start_context_switch(prev); 2351 2352 if (!mm) { 2353 next->active_mm = oldmm; 2354 atomic_inc(&oldmm->mm_count); 2355 enter_lazy_tlb(oldmm, next); 2356 } else 2357 switch_mm(oldmm, mm, next); 2358 2359 if (!prev->mm) { 2360 prev->active_mm = NULL; 2361 rq->prev_mm = oldmm; 2362 } 2363 /* 2364 * Since the runqueue lock will be released by the next 2365 * task (which is an invalid locking op but in the case 2366 * of the scheduler it's an obvious special-case), so we 2367 * do an early lockdep release here: 2368 */ 2369 spin_release(&rq->lock.dep_map, 1, _THIS_IP_); 2370 2371 context_tracking_task_switch(prev, next); 2372 /* Here we just switch the register state and the stack. */ 2373 switch_to(prev, next, prev); 2374 2375 barrier(); 2376 /* 2377 * this_rq must be evaluated again because prev may have moved 2378 * CPUs since it called schedule(), thus the 'rq' on its stack 2379 * frame will be invalid. 2380 */ 2381 finish_task_switch(this_rq(), prev); 2382}
4、switch_to宏定義了一段內聯彙編代碼
31#define switch_to(prev, next, last) \ 32do { \ 33 /* \ 34 * Context-switching clobbers all registers, so we clobber \ 35 * them explicitly, via unused output variables. \ 36 * (EAX and EBP is not listed because EBP is saved/restored \ 37 * explicitly for wchan access and EAX is the return value of \ 38 * __switch_to()) \ 39 */ \ 40 unsigned long ebx, ecx, edx, esi, edi; \ 41 \ 42 asm volatile("pushfl\n\t" /* save flags */ \ 43 "pushl %%ebp\n\t" /* save EBP */ \ 44 "movl %%esp,%[prev_sp]\n\t" /* save ESP */ \ 45 "movl %[next_sp],%%esp\n\t" /* restore ESP */ \ 46 "movl $1f,%[prev_ip]\n\t" /* save EIP */ \ 47 "pushl %[next_ip]\n\t" /* restore EIP */ \ 48 __switch_canary \ 49 "jmp __switch_to\n" /* regparm call */ \ 50 "1:\t" \ 51 "popl %%ebp\n\t" /* restore EBP */ \ 52 "popfl\n" /* restore flags */ \ 53 \ 54 /* output parameters */ \ 55 : [prev_sp] "=m" (prev->thread.sp), \ 56 [prev_ip] "=m" (prev->thread.ip), \ 57 "=a" (last), \ 58 \ 59 /* clobbered output registers: */ \ 60 "=b" (ebx), "=c" (ecx), "=d" (edx), \ 61 "=S" (esi), "=D" (edi) \ 62 \ 63 __switch_canary_oparam \ 64 \ 65 /* input parameters: */ \ 66 : [next_sp] "m" (next->thread.sp), \ 67 [next_ip] "m" (next->thread.ip), \ 68 \ 69 /* regparm parameters for __switch_to(): */ \ 70 [prev] "a" (prev), \ 71 [next] "d" (next) \ 72 \ 73 __switch_canary_iparam \ 74 \ 75 : /* reloaded segment registers */ \ 76 "memory"); \ 77} while (0)
通過以上代碼,我們可以看到,當cpu由正在運行的X進程切換到Y進程的大致步驟,其中X,Y是哪一個進程是由調度算法決定的。
進程X正在中運行->發生中斷->進行中斷處理(保存當前的eflag,eip,esp;加載內核中特定的eflag,eip,esp)->執行SAVE ALL->中斷處理過程中或中斷返回前調用了schedule(),switch_to實現關鍵的進程上下文切換->開始從標號1之後運行用戶態進程Y->restore all->iret從內核堆棧中返回eflag,eip,esp->繼續執行Y進程。對於前面提到的內核線程,以及系統中的特殊調用fork和execve會有些特殊,但大致原則是相同的。