content_switch 函数代码如下:
static __always_inline struct rq *
context_switch(struct rq *rq, struct task_struct *prev,
struct task_struct *next, struct rq_flags *rf)
{
prepare_task_switch(rq, prev, next);
/*
* For paravirt, this is coupled with an exit in switch_to to
* combine the page table reload and the switch backend into
* one hypercall.
*/
arch_start_context_switch(prev);
/*
* kernel -> kernel lazy + transfer active
* user -> kernel lazy + mmgrab() active
*
* kernel -> user switch + mmdrop() active
* user -> user switch
*/
if (!next->mm) { // to kernel
enter_lazy_tlb(prev->active_mm, next);
next->active_mm = prev->active_mm;
if (prev->mm) // from user
mmgrab(prev->active_mm);
else
prev->active_mm = NULL;
} else { // to user
membarrier_switch_mm(rq, prev->active_mm, next->mm);
/*
* sys_membarrier() requires an smp_mb() between setting
* rq->curr / membarrier_switch_mm() and returning to userspace.
*
* The below provides this either through switch_mm(), or in
* case 'prev->active_mm == next->mm' through
* finish_task_switch()'s mmdrop().
*/
switch_mm_irqs_off(prev->active_mm, next->mm, next);
if (!prev->mm) { // from kernel
/* will mmdrop() in finish_task_switch(). */
rq->prev_mm = prev->active_mm;
prev->active_mm = NULL;
}
}
rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
prepare_lock_switch(rq, next, rf);
/* Here we just switch the register state and the stack. */
switch_to(prev, next, prev);
barrier();
return finish_task_switch(prev);
}
该代码是一个用于进程切换的函数,它接收三个参数:当前的运行队列rq,当前正在运行的进程prev以及要被调度的下一个进程next。该函数的目的是将当前正在运行的进程prev切换为被调度的下一个进程next。
具体来说,该函数做了以下几个事情:
调用 prepare_task_switch 函数,准备进行进程切换。调用 arch_start_context_switch 函数,通知体系结构相关的模块开始处理进程切换(这一步可能涉及到虚拟化、页表切换等操作)。根据被调度的下一个进程的类型(用户态或内核态),选择不同的执行路径。
如果被调度的下一个进程是内核态进程,调用 enter_lazy_tlb 函数,更新 TLB,并将被调度的下一个进程的 active_mm 字段设为当前进程的 active_mm 字段。如果当前进程是用户态进程,调用 mmgrab 函数,增加当前进程的 active_mm 引用计数。如果被调度的下一个进程是用户态进程,调用 membarrier_switch_mm 函数,执行一些内存障碍操作,并将当前进程的 active_mm 字段设置为 NULL,将被调度的下一个进程的 active_mm 字段设置为其自己的 mm 字段。调用 switch_mm_irqs_off 函数,切换当前进程和被调度的下一个进程的地址空间,并禁止中断。根据当前进程和被调度的下一个进程的类型和状态,执行相应的操作,如更新运行队列、设置进程状态等。调用 switch_to 函数,进行进程切换,实现将当前正在运行的进程prev切换为被调度的下一个进程next。最后调用 finish_task_switch 函数,完成进程切换并返回。