深入理解进程切换

inux 中进程切换涉及到一个调用链:

schedule() –> context_switch() –> switch_to –> __switch_to()

先是 switch_to 

#define switch_to(prev,next,last) do {
unsigned long esi,edi;
asm volatile("pushflnt"
"pushl %%ebpnt"
"movl %%esp,%0nt"
"movl %5,%%espnt"
"movl $1f,%1nt"
"pushl %6nt"
"jmp __switch_ton"
"1:t"
"popl %%ebpnt"
"popfl"
:"=m" (prev->thread.esp),"=m" (prev->thread.eip),
"=a" (last),"=S" (esi),"=D" (edi)
:"m" (next->thread.esp),"m" (next->thread.eip),
"2" (prev), "d" (next));
} while (0)

由于 switch_to 宏使用了内联汇编,为了便于理解,将其转换成可读性较强的汇编形式(语法上会有些许差别)。下面逐句分析:pushfl将 eflags 寄存器压到 prev 进程的内核栈中。pushl %ebp由于 switch_to 是 context_switch() 中的一个宏替换,所以这一步是将 context_switch() 的栈桢起始位置压到 prev 进程的内核栈中。movl %esp, [prev->thread.esp]保存栈定位置。

movl [next->thread.esp], %esp将 next->thread.esp 恢复到当前 CPU 的 esp 寄存器中,此时已经切换到了 next 进程的内核栈。

movl $1f, [prev->thread.eip]
1:
popl %ebp
popfl

这是为了以后恢复 prev 作下铺垫,下面将会看到它在 next 中起到的作用。

pushl [next->thread.eip]

将 1: 处的指令地址压入 next 的内核栈的栈顶。到这里已经完成了内核栈的切换,下面的工作就是在 __switch_to() 中对 next 进程进行一些设置。

执行 jmp __switch_to 跳转

struct task_struct fastcall *
__switch_to(struct task_struct *prev_p, struct task_struct *next_p)
{
struct thread_struct *prev = &prev_p->thread,
*next = &next_p->thread;
int cpu = smp_processor_id();
struct tss_struct *tss = &per_cpu(init_tss, cpu);
__unlazy_fpu(prev_p);
load_esp0(tss, next);
load_TLS(next, cpu);
asm volatile("movl %%fs,%0":"=m" (*(int *)&prev->fs));
asm volatile("movl %%gs,%0":"=m" (*(int *)&prev->gs));
if (unlikely(prev->fs | prev->gs | next->fs | next->gs)) {
loadsegment(fs, next->fs);
loadsegment(gs, next->gs);
}
if (unlikely(next->debugreg[7])) {
loaddebug(next, 0);
loaddebug(next, 1);
loaddebug(next, 2);
loaddebug(next, 3);
loaddebug(next, 6);
loaddebug(next, 7);
}
if (unlikely(prev->io_bitmap_ptr || next->io_bitmap_ptr))
handle_io_bitmap(next, tss);
return prev_p;
}

这个函数运行在 next 的内核栈上。因为现在 CPU 已经切换到了 next 进程,所以需要重新设置 CPU 的一些数据。例如 TSS:load_esp0(tss, next);load_TLS(next, cpu);最后执行 return prev_p 将栈顶(prev->thread.eip)恢复到 eip 中。执行:

1:
popl %ebp
popfl

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值