First of all, please do not restrict OS to Windows :D
Do context switches happen mid instructions? If not, is it true for multi-step instructions (x86) like INC, XADD?
In the software context switching, context switch will happen on a specific interrupt (A hardware timer, or an internal CPU tick counter timer). All of the CPU's architectures (AFAIK) have a register or flag to notify the "Fetch Unit" that there is a pending interrupt. Then, the CPU starts executing ISR by setting the PC
register. Pay attention context switch will be done on an ISR. So, According to the interrupt mechanism, occurring an interrupt during executing an instruction, does not have any conflict. This way the current instruction will execute completely, But the "Fetch Unit" will load the first ISR instruction (After the hardware stack frame operation, in most of the architectures).
Although, some of the recent CPUs architecture have a Hardware Context Switching mechanism. In this way, All of the context switching processes will be done and handled by the CPU's hardware. To trigger a context switch and tell the CPU where to load its new state from, the far version of CALL
and JMP
instructions are used in the Intel CPUs architecture.
On which processor is the code responsible for context switching is run? If it is run on an arbitrary processor, that could modify the registers on that processor, right? So how does the OS manage to save that particular processor's state?
Each processor has its own context switch. In this way, Each processor has a particular scheduler in the kernel and OS (by observing the load balance on processors) will assign each task to one of the processors (at least in Linux).