Skip to main content

Lesson 4 of 26 · 12 min read

Limited direct execution, traps, and context switches

Follow how hardware privilege levels, trap tables, timer interrupts, and register switches let the OS virtualize the CPU at near-native speed without losing control.

Limited Direct Execution sequence: User Ring 3, Trap vector, Kernel switch(), and Return-from-trap.
Hardware privilege rings, timer interrupts, and kernel-stack register switches keep direct execution safe.
Course syllabus · lesson 4 of 26
In this lesson

OSTEP Chapter 6 crux — How to efficiently virtualize the CPU with control. How can the operating system let programs execute directly while retaining control of the processor? The chapter asks how a process can request restricted operations and how the kernel can regain the CPU without the process's cooperation.

Limited direct execution lets most user instructions run at native speed. An arithmetic instruction can retire without an operating system call. Operations that require kernel authority go through protected entry points, and an interrupt can bring the kernel back even if the application never issues a request. The concrete path below uses 32-bit protected-mode x86 xv6. Other architectures use different entry instructions and register layouts.

User mode execution traps on syscall or timer interrupt, hardware pushes user registers onto the kernel stack, kernel calls switch() between Process A and Process B contexts, and return-from-trap resumes user mode.
Open full-size diagram
Limited direct execution pairs user-mode speed with hardware traps and kernel-stack register switches.

Trace a timer trap and context switch

Process A running, Process B ready, Kernel timer armedProcess ArunningProcess BreadyKerneltimer armed

Step 1 of 4

Execute in user mode

A executes directly on the CPU with user-mode permissions. A hardware timer is armed to return control to the kernel.

Entering the kernel through a protected gate

Kernel privilege lets the OS configure interrupts, manage mappings, and talk to devices. User mode constrains what the application can do directly. If a process wants to read a file, it supplies arguments to a system call. The kernel checks the descriptor and the user memory involved before carrying out the operation. Entering the kernel grants authority to execute handler code. The caller's arguments still require validation.

The generic trap table is the interrupt descriptor table, or IDT, in protected-mode x86. The interrupt vector table, or IVT, of real-mode x86 instead records segment and offset pairs. The IDT register carries the table's base address and byte limit. The vector number indexes a gate. Its offset fields identify the entry code, the code-segment selector determines the destination code segment, and the present bit indicates that a gate is available. The gate type distinguishes trap and interrupt gates here. An interrupt gate clears the hardware interrupt-enable flag on entry, while a trap gate leaves it as it was. The descriptor privilege level controls which callers may invoke the gate with a software interrupt instruction. It does not prevent the device interrupt from being delivered while a user program runs.

At initialization xv6 installs kernel-only gates for device vectors and a user-callable trap gate for the syscall vector. It loads the IDT on each CPU. The syscall stub supplies a syscall number in eax and uses an int instruction with the syscall vector. That vector selects the trusted entry stub, while eax selects a service after the kernel is already running. Passing a different number can make the dispatcher reject the request, but does not supply a new entry address. The kernel must set the table up before enabling interrupt delivery or entering user code. xv6 IDT setup and dispatch

Which registers the trap frame holds

For a transition from user to kernel privilege, x86 takes the privileged stack location from the task-state segment. xv6 configures this location for the process it is about to dispatch. On the new stack the CPU records old ss and esp, then eflags, cs, and eip. Some exceptions also push an error code. The vector stub supplies a placeholder code for vectors without one and pushes the vector number. Common entry assembly then saves data segment and general-purpose registers so C code can use them without destroying the interrupted computation.

Read xv6's struct trapframe in groups from the low-address end of the completed frame:

  • edi, esi, ebp, ebx, edx, ecx, and eax hold interrupted general-purpose values. oesp is the stack-pointer slot made by the save-all instruction. Its value comes from the entry stack, and the matching restore skips that slot. The syscall handler can store its result in the saved eax.
  • gs, fs, es, and ds preserve segment selectors used by the interrupted code. Padding keeps the records aligned with the stack slots produced by the assembly.
  • trapno identifies the vector. err holds the exception's error code or the placeholder. The two fields make the handling path uniform across different entry stubs.
  • eip locates the instruction where execution will resume, cs gives the old code selector and helps identify the old privilege, and eflags contains condition flags and the old interrupt-enable state. An expected restart address depends on the kind of event.
  • esp and ss hold the interrupted user stack pointer and selector on a crossing from user privilege. An interrupt that arrives while already in the kernel uses the current kernel stack in this design and has no saved outer-privilege stack pair.

Return assembly restores general and segment registers, removes the vector and error slots, and executes iret. The processor then consumes the architectural return fields. Dropping the wrong number of words before iret would make hardware read the wrong instruction address or selector. This is why the C layout, assembly pushes, and architectural frame must agree. xv6 register layout xv6 entry and return assembly

Taking back the CPU

A cooperative scheduler can switch only after a process enters the kernel at a suitable point, such as yielding or blocking on a system call. A compute loop with no such calls can monopolize a core indefinitely. With a timer programmed by the kernel, the interrupt arrives independently of user instructions. The handler can account for elapsed ticks, acknowledge the interrupt controller, and arrange a scheduling decision. An ordinary user loop cannot disable the timer or mask its interrupts.

A timer entry is a chance to schedule. The kernel may return to the same process, for example when there is no competing ready work. Interrupts can also arrive while the kernel is already serving a request. Kernel code can briefly mask local interrupts around critical transitions and use locks to coordinate with other cores. Masking interrupts on one core leaves the others free to run. Taking a lock that a local interrupt handler also needs, with interrupts still enabled, can deadlock the core if the handler interrupts the holder. Keeping interrupts masked for too long can instead delay scheduling and device service.

Separate the hardware's tick interval from the scheduler's quantum. A timer could interrupt every millisecond while a policy rotates jobs only after four charged ticks. The first three entries save and restore the current user state with no switch between processes. On the fourth, the handler can arrange a yield if another job is ready. If the current job blocks after two ticks, the scheduler can run a different job immediately instead of leaving the core idle for the remaining two. The timer supplies occasions to examine state. The scheduler controls how much service a job receives and what happens at each occasion.

The kernel continuation is a second save

A user trap frame represents execution at the boundary with user mode. A scheduler switch also needs a kernel continuation. The x86 xv6 implementation examined here uses a stack-resident struct context, a revision distinct from the earlier explicit-register context illustrated in Lesson 2. Its fields are edi, esi, ebx, and ebp, followed by the return address eip. The pointer to this record doubles as the saved kernel stack pointer. Caller-saved registers such as eax, ecx, and edx need no additional slots because swtch is called under the normal kernel calling convention. Any live values in those registers are the call site's responsibility.

For a numerical trace, let the kernel call to swtch leave A's return address at 0x8ffc. The switch pushes ebp, ebx, esi, and edi, so the new stack pointer is 0x8fec. In ascending order the slots at 0x8fec, 0x8ff0, 0x8ff4, 0x8ff8, and 0x8ffc hold the four saved registers in reverse push order and the return address. The code writes 0x8fec through the outgoing context pointer. It must do that before loading any incoming stack pointer.

Suppose the target context starts at 0x9fec. After loading that value into esp, the four pops restore the target's registers, moving esp to 0x9ffc. The following ret pops the target address and continues on the target's kernel stack. Saving the old pointer after changing stacks would record the target as the outgoing continuation. Pushing or popping in a different order would load registers from each other's slots. xv6 context definition xv6 switch assembly

In xv6, a process usually switches to a scheduler context on that CPU. The scheduler then switches to the selected process. Here is a schematic dispatch fragment. Assume the scheduler holds the process-table lock and cpu refers to the current CPU.

Code exampleC
cpu->proc = next;
switchuvm(next);
next->state = RUNNING;
swtch(&cpu->scheduler, next->context);
switchkvm();
cpu->proc = 0;

The first assignment identifies the process for kernel bookkeeping. switchuvm chooses its address space and arranges the kernel stack for future user entries. Publishing RUNNING under the lock prevents another scheduler from claiming the process. Moving setup after swtch would delay it until the scheduler's own continuation resumes, after the chosen process has already run. When the process yields, sleeps, or exits, the scheduler regains control and returns to its kernel-only address space before clearing the current-process reference. xv6 scheduler xv6 address-space switch

A newly created process has never called swtch or taken a user trap. To use the same dispatch machinery, xv6 prepares a kernel stack as though the process had already saved a continuation. It sets the first kernel return address to a setup routine and arranges for that routine to return through the trap-return path. A prepared trap frame supplies the user state that the first iret consumes. For a forked child, that frame comes from the parent's saved syscall state, with the child's return value changed to zero. Both first dispatch and later dispatches obey the same stack layout. The origin of the saved words differs. xv6 process initialization

Worked trace

Process A calls read on a block that requires device I/O. B is ready, with both a kernel continuation and a saved user frame from an earlier preemption.

  1. A's syscall stub takes the protected gate. Hardware and entry assembly build A's trap frame on A's kernel stack. The read handler checks its arguments and starts the request.
  2. A records its wait channel and sleeps. swtch saves A's kernel continuation inside the sleep path and resumes the CPU's scheduler continuation. A's user frame stays on A's stack.
  3. The scheduler dispatches B. B's kernel context resumes in its previous kernel path. When that path reaches trap return, it restores B's user frame, then iret resumes B in user mode.
  4. A disk interrupt arrives while B is running. Its handler makes A ready. For this trace, B keeps the core until a later timer entry. That entry builds another B frame, and B yields to the scheduler.
  5. The scheduler dispatches A. A resumes inside the kernel sleep path, checks that the block completed, and finishes the read. The dispatcher puts the byte count into A's saved eax. Trap return delivers that result to A's original user continuation.

Change one input

Suppose the read completes immediately from cache. Which register saves still happen? The syscall entry still builds A's trap frame, and software still fills its return-value slot. A need not sleep or invoke swtch in this path. A subsequent interrupt can still preempt A. The two saves exist for different transitions and neither implies the other.

Next, study CPU scheduling metrics and timelines.

Before you move on

Try it in your workspace

Trace a timer interrupt while user code runs: hardware pushes registers onto the kernel stack, vectors through the trap table, runs the OS handler, calls switch(), and executes return-from-trap.

Keep a short note of what you tried, what passed, and what you still need to check.

Your practice record

0 of 3 checked.

Saved in this browser when storage is available. Uncheck any item to revisit it. This is your own record, not an assessment.