1.实验简介
Linux 是一个多任务操作系统,它能支持多任务同时运行。CPU通过进程调度器把 CPU 资源按时间片分配给就绪队列中的多个进程,这个分配过程中就需要进行进程之间的切换。进程切换的时候就需要将当前进程的上下文信息保存下来,随后加载被调度进程的上下文信息,这就是上下文切换。这里所说的上下文信息,既包括虚拟内存、栈、全局变量等用户态的资源,也包括内核堆栈、寄存器等内核态的资源。
2.进程切换代码分析
进程上下文切换主要涉及两个部分:进程地址空间切换以及内核堆栈和硬件上下文切换。其代码调用过程如下。
__schedule // kernel/sched/core.c
->context_switch
->switch_mm_irqs_off //进程地址空间切换
->switch_to //内核堆栈和硬件上下文切换
__schedule通过调度算法确定下一个需要调度的进程,之后调用context_switch完成进程的切换。
static void __sched notrace __schedule(bool preempt)
{
struct task_struct *prev, *next;
......
next = pick_next_task(rq, prev, &rf);
......
if (likely(prev != next)) {
......
rq = context_switch(rq, prev, next, &rf);
} else {
......
}
balance_callback(rq);
}
函数context_switch完成进程地址空间的切换
static __always_inline struct rq *
context_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next, struct rq_flags *rf)
{
......
if (!next->mm) {
enter_lazy_tlb(prev->active_mm, next);
next->active_mm = prev->active_mm;
if (prev->mm)
mmgrab(prev->active_mm);
else
prev->active_mm = NULL;
} else {
membarrier_switch_mm(rq, prev->active_mm, next->mm);
switch_mm_irqs_off(prev->active_mm, next->mm, next);
if (!prev->mm) {
rq->prev_mm = prev->active_mm;
prev->active_mm = NULL;
}
}
......
switch_to(prev, next, prev);
......
}
具体的内核堆栈和硬件上下文切换代码
ENTRY(cpu_switch_to)
mov x10, #THREAD_CPU_CONTEXT // 寄存器x10存放thread.cpu_context偏移,与进程task_struct地址相加后即可获得该进程的cpu_context
add x8, x0, x10 // x0与偏移量相加后存入x8,获取旧进程cpu_context的地址
mov x9, sp // 将栈顶sp存入x9,以备后续保存
// 保存x19~x28寄存器的值,每条指令执行完毕后x8的值会自动+16,以便保存后续寄存器值
stp x19, x20, [x8], #16
stp x21, x22, [x8], #16
stp x23, x24, [x8], #16
stp x25, x26, [x8], #16
stp x27, x28, [x8], #16
stp x29, x9, [x8], #16 // 保存x29(栈基址)与x9(栈顶sp)
str lr, [x8] // 保存寄存器LR,该寄存器存放了cpu_switch_to函数的返回地址
add x8, x1, x10 // x1与偏移量相加后存入x8,获取新进程cpu_context的地址
// 恢复x19~x28寄存器的值
ldp x19, x20, [x8], #16
ldp x21, x22, [x8], #16
ldp x23, x24, [x8], #16
ldp x25, x26, [x8], #16
ldp x27, x28, [x8], #16
ldp x29, x9, [x8], #16 // 恢复x29(栈基址)与x9(栈顶sp)
ldr lr, [x8] // 恢复寄存器LR,这样函数cpu_switch_to返回后就会从新进程上次被中断的位置处继续执行
mov sp, x9 // 从x9处恢复sp的值
msr sp_el0, x1 // 将新进程进程task_struct地址放入sp_el0
ret
ENDPROC(cpu_switch_to)
NOKPROBE(cpu_switch_to)