How to keep atomicity when contex switching in the kernel mode?

kernel, linux, linux-kernel, operating-system, x86

Solution

Atomic operations are implemented in kernels as follows. At a high-level (e.g., from device driver developer's POV), the kernel provides locks that are acquired and released similarly to user-space mutexes. At a lower-level, these locks are implemented using a combination of atomic operations and signaling the kernel scheduler that preemption should not occur.

In the scheduler itself, atomicity is guaranteed by masking interrupts. This is done using a single instruction (cli or sti), so it is atomic by itself. NMI can indeed occur while interrupts are cleared, however, this is a special case. The NMI handler knows that it can be called in a weird context, so it makes sure that it does not change the context.

Problem

There is no doubt that context switching in kernel mode, which is trapped in by hardware interrupt or software interrupt. It is also known that context switching should be kept in atomic, but how do implement atomicity? It is known that interrupt gate disables all the interrupt (I don't know whether NMI is included).Does an interrupt gate itself can be seen as atomic sequence naturally?

Original source