Taking turns
Programs A and B both want to run, but there is one CPU, and a CPU runs one program at a time. To share it, the kernel lets them take turns, switching many times a second, so both seem to run at once.
The CPU keeps a running program's place in its registers, small fast slots inside the chip. PC, the program counter, says where it is. SP points at its stack. R1 holds its counter. Copy these out, and you have saved the program.
A runs directly on the CPU in user mode. Line 2 adds one, so R1 goes from 41 to 42. The kernel is not running at all. So how does it ever get the CPU back from a program that never stops?
The switch
At boot the kernel started a hardware timer. On Linux it ticks 250 times a second by default, once every 4 ms. Each tick is an interrupt: the CPU must stop what it is doing, whatever the program wants.
The interrupt traps into the kernel. In one move the CPU switches to kernel mode and runs the timer handler the kernel chose at boot. A's registers are saved in kernel memory: PC A·L2, SP A, R1 42.
The kernel now has the CPU, so it can choose. Its scheduler sees that A has had its turn and B is ready and waiting. It decides to switch to B. A goes from running to ready.
This is the context switch itself. The kernel copies B's saved registers back into the CPU: PC B·L2, SP B, R1 7. Those are exactly the values B had when it was last stopped.
The kernel runs return-from-trap. The CPU drops to user mode and carries on at PC, which now points into B. B adds one, so R1 goes from 7 to 8. B never notices it was stopped.
Why it works
The next tick runs the same steps the other way: save B's registers (R1 8), load A's. A resumes on line 2 with R1 = 42, untouched, and adds one to make 43. Its count is never lost.
A switch is not free: on Linux one between processes takes about 3 to 4 microseconds. A 4 ms tick is 1000 times longer, so the programs keep almost all the time. Switching far more often would waste it.
Every switch is counted. A C program can ask with getrusage(): ru_nivcsw counts the times the kernel took the CPU away, and ru_nvcsw the times it gave it up itself. On Linux, /proc shows the same counts.
What happens
;; step 1/11 · two-programs program A running (has the CPU) program B ready (waiting for a turn) one CPU core runs one program at a time. the kernel swaps them many times a second so both seem to run together: time sharing.
The figure shows one save area per program. Real kernels save twice: the trap saves the program's user registers on its kernel stack, and the switch routine saves the kernel's own registers in the process structure (OSTEP Figure 6.3; in xv6, the trapframe and p->context). PC is shown as a program and a line (A·L2). In a real CPU it holds the memory address of the next machine instruction, and one line of C is several instructions.