0
votes

Here is my understanding of the process switching (in amd64 Linux).

  1. A hardware interrupt or a software interrupt is triggered.
  2. Context of currently running process is saved to its PCB. This includes program counter, stack pointer, general-purpose registers, etc.
  3. Interrupt routine handler is run. This in turn calls scheduler code. Scheduler loads another process context onto the registers.

I am confused about who actually saves the context of the interrupted process. It cannot be the user program, because it doesn't know when it will be preempted. It cannot be the kernel code, because to run kernel code in the first place, the program counter has to point to the kernel code. If you do that, you are losing the interrupted process' program counter.

1

1 Answers

2
votes

Hardware saves the user-space program-counter on the kernel stack, as part of how exceptions / interrupts work on x86. (Or for the syscall entry point, user-space RIP is in RCX and does have to get stored manually into the PCB).

The rest of user-space context is saved on the kernel stack for that task by software after entering the kernel. Context-switch swaps kernel context including kernel stack pointer to be pointing at the new task's stack, so returning, eventually to user-space, will restore the new task's user-space state.