Linux context switch internals: how does a process goes back to userland after the switch?

こ雲淡風輕ζ 提交于 2019-12-11 15:37:36

问题


I have read a similar answer to question regarding context switching on StackOverflow: How does schedule()+switch_to() functions from linux kernel actually work?

However, i'm still puzzled by the internals and lack the understanding of how a newly switched process (previously preempted) will resume its execution in userland (assuming it was interrupted there) on Linux.

So far, the general flow of the context switch (on v4.20):

  1. a process is executing in userland (lets say firefox)
  2. the CPU clock generates an interrupt
  3. the scheduler is called
  4. __schedule() is called
  5. if the new task (lets say systemd) is different than the current one, context_switch() is called
  6. context_switch calls switch_to()
  7. At this point, the CPU context is switched to the next task, including stack and virtual address space
  8. the previous task is returned by context_switch()

At this point I don't understand what's happening:

-> Is this new task executing ? in the switch_to code, I didn't see any reference to the instruction pointer of the task_struct being used.

-> How does my systemd process continues its execution in userland ?

-> Are we supposed to hit an iret somewhere ? I saw the resume_kernel and resume_userspace symbols in entry_32.S but I don't understand how they are connected to the scheduler.

-> Why is there no instruction pointer field in the task_struct->thread structure ? How the IP is stored and restored ?

-> Does evey context switch involve an interrupt followed by an iret ? And therefore can i rely on this fact to catch a context switch (by catching the CR3 load) and singlestep until I execute an iret ?

Note: I'm asking the question because i'm trying to build a guest-aware, hypervisor-level debugger. Hence, I'm developping a PTRACE_ATTACH like functionality, but by only using the hypervisors-s VMI APIs

Thank you very much for your time and answers ! 🙂

来源:https://stackoverflow.com/questions/54771450/linux-context-switch-internals-how-does-a-process-goes-back-to-userland-after-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!