杨怡泽 原创作品转载请注明出处《Linux内核分析》MOOC课程http://mooc.study.163.com/course/USTC-1000029000
首先在内核代码中搜索schedule,发现以下结果
在core.c文件中是
实验
设置断点
跟踪schedule的进程
可以看到
struct task_struct *tsk = current;
sched_submit_work(tsk);
将一个task_struct的指针赋值给了当前进程,之后调用了sched_submit_work。
继续执行,进入后面的__schedule()函数
可以看到切换进程的大部分代码都在__schedule()函数中
执行完毕
分析
进程调度的时机
• 中断处理过程中,直接调用schedule(),或者返回用户态时根据need_resched标记调用schedule()。
• 内核线程可以直接调用schedule()进行进程切换,也可以在中断处理过程中进行调度,也就是说内核线程作为一类的特殊的进程可以主动调度,也可以被动调度。
• 用户态进程无法实现主动调度,仅能通过陷入内核态后的某个时机点进行调度,即在中断处理过程中进行调度。
switch_to的分析
switch_to宏有三个参数,它们是prev,next和last。prev表示替换进程,next表示新进程描述符放入赋值在内存中的位置。最后一个参数的输入参数,它表示宏把进程C的描述符地址写在内存的位置。
在进程切换之前,宏吧第一个输入参数prev表示的变量的内容存入CPU的寄存器,在完成进程切换,A已经恢复执行,宏把CPU的eax的寄存器的内容写入由第三个输入参数(last所示的A在内存中的位置)。因为CPU的eax寄存器不会在切换点发生变化,所以C得描述符地址也存在内存的位置。在schedule()执行过程中。参数last指向A的局部变量prev,所以prev被C的地址覆盖。
__schedule()的分析
static 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;
// 选择一个高优先级的任务加入队列
2824 next = pick_next_task(rq, prev);
//并把这个任务的需要加入的标志need_resched去掉
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}
2852
2853static inline void sched_submit_work(struct task_struct *tsk)
2854{
2855 if (!tsk->state || tsk_is_pi_blocked(tsk))
2856 return;
2857 /*
2858 * If we are going to sleep and we have plugged IO queued,
2859 * make sure to submit it to avoid deadlocks.
2860 */
2861 if (blk_needs_flush_plug(tsk))
2862 blk_schedule_flush_plug(tsk);
2863}
总结
Linux系统的一般执行过程是首先有正在运行的用户态进程X然后在停止前发生中断,使用SAVE_ALL保存现场。并且中断处理过程中或中断返回前调用了schedule(),其中的switch_to做了关键的进程上下文切换。最后,标号1之后开始运行用户态进程Y(这里Y曾经通过以上步骤被切换出去过因此可以从标号1继续执行)。
完成调度恢复现场,之后继续运行用户态进程Y。