1
$\begingroup$

This is a really short question and a straightforward one for anyone who knows the subject well. But its also super specific, so I can't find the answer online.

I know a program counter is saved when a context switch occurs. I can't seem to make sense of how this could happen in software. In order for the CPU to run the process that saves the program counter, it must load that program counter into the program counter register. So isn't the program counter that's suppose to be save now lost?

$\endgroup$

2 Answers 2

2
$\begingroup$

Good question! The answer is: this is implemented in hardware. When an interrupt occurs, the processor saves the program counter in a known place (typically, by pushing it onto the stack), then transfers control to the interrupt handler code (overwriting the prior program counter).

$\endgroup$
2
$\begingroup$

On x86-64, the OS sets up an interrupt descriptor table (IDT). For each device there is connected to the computer, there is one interrupt number that is reserved. This is especially true since the advent of the mandatory MSI-X capability of PCI-Express devices. Everything is PCI today. Since most devices on your computer are PCI and probably even PCI-Express, they throw interrupts using MSI-X or MSI.

MSI-X/MSI interrupts bypass the IOAPIC and throw an inter-processor interrupt. The local APIC of the CPU is programmed with memory mapped registers that are mapped into RAM to trigger a certain handler. For example, you could have an MSI-X interrupt that is mapped to interrupt number 48. When that interrupt handler runs, the OS is aware that a certain device was set to throw that interrupt so it can assume that, when this interrupt runs, it is that device which triggered the interrupt.

The scheduler mostly runs on interrupt on modern systems. The CPU pushes the RIP register (and sometimes other things) on the stack on interrupt so it allows the OS to find out what was the RIP register before the interrupt.

What is missing here is the timer. A timer can be programmed to trigger an interrupt after some time has elapsed. The OS can thus know the time slice of a process has finished and can thus call the scheduler to determine what other process will come next. The scheduler can also be called at different moments like on IO completion.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.