The kernel abstraction
On this page
How the kernel runs untrusted code safely: the process abstraction, dual-mode operation, and the three ways into the kernel – interrupts, exceptions and system calls – plus upcalls, the way back out to user programs.
The problem: protection
How do we run code with restricted privileges, either because it is buggy or because it might be malicious? Examples: a script in a web browser, a program downloaded from the internet, or a program you just wrote and haven't tested.
One approach is to run every instruction in a simulator and only perform the permitted ones (the basic model of JavaScript and other interpreted languages). That is slow. To go faster, the unprivileged code should run directly on the CPU, which needs hardware support.
The process abstraction
A process is an instance of a program running with limited rights. It consists of:
- a thread: a sequence of instructions within the process (potentially many per process; one for now), and
- an address space: the set of rights of the process – the memory it can access, and other permissions such as which system calls it can make and which files it can access.
The kernel keeps track of each process in a process control block (PCB).
Dual-mode operation
- Kernel mode
- Execution with the full privileges of the hardware: read and write any memory, access any I/O device, any disk sector, send and read any packet.
- User mode
- Limited privileges, only those granted by the kernel.
On x86 the mode is stored in the EFLAGS register; on MIPS in the status register. Hardware support consists of:
- Privileged instructions, available only in kernel mode. If user code tries one, the processor raises an exception.
- Limits on memory accesses, so user code cannot overwrite the kernel (base and bounds, later virtual addresses; see address translation).
- A timer that periodically interrupts the processor and returns control to the kernel, so it can regain control from a user program stuck in a loop. Only the kernel can set the frequency or defer the interrupt.
- A safe way to switch between user and kernel mode.
Why not let a “Hello world” program write directly to the screen buffer? Because then any program could overwrite anything on the screen; the kernel copies the string from user memory instead.
Mode switches
From user mode to kernel mode
- Interrupts
- Triggered by the timer and I/O devices. Asynchronous: unrelated to the instruction being run.
- Exceptions
- Triggered by unexpected (or malicious) program behaviour: divide by zero, an illegal memory reference, a privileged instruction in user mode.
- System calls
- A request by the program for the kernel to do something on its behalf (a protected procedure call). Only a limited number of very carefully coded entry points.
A trap is the general term for a synchronous transfer from user to kernel mode: system calls and exceptions are caused by the instruction being executed.
From kernel mode to user mode
- Starting a new process or thread: jump to the first instruction.
- Returning from an interrupt, exception or system call: resume the suspended execution.
- A process or thread context switch: resume some other process.
- A user-level upcall (UNIX signal): an asynchronous notification to the user program.
A trap is a synchronous transfer from user to kernel mode (2023 Q6, 2025 Q10). A timer interrupt is not an exception (2023 Q7). Of char buffer[5];, c++;, int x=5; and printf("me\n");, only printf causes a mode switch, because it ends in a write system call (2023 Q8).
Devices and interrupts
Devices run asynchronously from the CPU. With polling the kernel waits until the I/O is done, wasting CPU cycles; with interrupts it can do other work in the meantime. An interrupt is an asynchronous signal to the processor that an external event has occurred.
Devices can move data with programmed I/O (the CPU reads and writes to the device) or direct memory access (DMA), where the device itself reads and writes memory. A buffer descriptor describes a sequence of DMAs, for example a packet header and body; the kernel keeps a queue of them.
Taking interrupts safely
- Interrupt vector
- A table set up by the kernel with pointers to the code to run for each event. This limits the entry points into the kernel.
- Interrupt stack
- Per processor, in kernel memory. A process or thread usually has both a kernel stack and a user stack. The handler can't use the user stack, because the kernel cannot trust its state.
- Atomic transfer of control
- A single instruction changes the program counter, stack pointer, memory protection and mode.
- Transparent restartable execution
- The user program does not know an interrupt occurred.
- Interrupt masking
- The handler runs with interrupts off, re-enabled when it completes. The kernel can also turn interrupts off, for example while choosing the next thread. On x86,
CLIdisables andSTIenables interrupts, only on the current CPU. This is used to implement synchronisation.
Interrupt handlers are non-blocking and run to completion. They do the minimum needed to let the device take the next interrupt, and wake up other threads (in Linux, with a semaphore) to do any real work. The rest of the device driver runs as a kernel thread.
What x86 does on an interrupt
- Save the current stack pointer, program counter and processor status word (condition codes).
- Switch to the kernel stack and push SP, PC and PSW onto it.
- Switch to kernel mode.
- Vector through the interrupt table.
- The handler saves any registers it might clobber.
At the end the handler restores the saved registers, then atomically restores the program counter, the program stack and the processor status word, and switches to user mode. The stack pointer is saved twice on the interrupt stack: once by the hardware (the user SP) and once by the handler (the SP in the kernel).
MIPS does the same with two entry points: the TLB miss handler and everything else. It saves the type (system call, exception, interrupt), the PC, the old mode and interrupt bits, sets kernel mode, disables interrupts and, for memory faults, saves the virtual address.
System calls
A system call goes through a user stub and a kernel stub:
- The program calls
file_open(arg1, arg2)like a normal function. - The user stub pushes the system call number (e.g.
#SYSCALL_OPEN) and executes atrap. - The hardware traps into the kernel's system call handler.
- The kernel stub copies and checks the arguments, calls the real
file_open, and copies the return value into user memory. - The kernel returns from the trap; the user stub returns to the program.
The kernel's system call handler must:
- Locate the arguments, in registers or on the user stack, translating user addresses into kernel addresses.
- Copy the arguments from user memory into kernel memory, to protect the kernel from malicious code changing them after they were checked.
- Validate the arguments, to protect the kernel from errors in user code.
- Copy results back into user memory.
The course example syscall_args.c shows the checks in action: read on fd 9999, on the address 0xDEADBEEF, or with a count of −1 returns an error and sets errno instead of crashing the kernel.
Upcalls (signals)
An upcall is user-level event delivery: the kernel notifies a user process of an event that needs handling right away. Uses include timer expiration (real-time UIs, time slices for a user-level thread manager), interrupt delivery to a VM player, and asynchronous I/O completion. In UNIX, upcalls are signals.
Upcalls mirror interrupts:
| Upcall | Interrupt |
|---|---|
| Signal handlers | Interrupt vector |
| Signal stack | Interrupt stack |
| Automatic save and restore of registers | Transparent resume |
| Signal masking: signals disabled while in the handler | Interrupts disabled in the handler |
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void handler(int num)
{
printf("We caught a signal %d\n", num);
}
int main()
{
signal(SIGTERM, handler);
signal(SIGUSR1, handler);
signal(SIGSEGV, handler);
while (1)
{
printf("Sleeping for 5 seconds...\n");
sleep(5);
}
}
In the signals exercise you handle SIGWINCH (window size changed), read the size with ioctl(0, TIOCGWINSZ, &w), and print it in the middle of the terminal using ANSI escape codes. Use pause() instead of sleep to wait for a signal, and fflush(0) to print without a newline.
Virtual machines
A user-level VM player (such as VM Player) needs to catch privileged instructions, interrupts and device I/O. It installs a kernel driver, which requires administrator privileges and modifies the interrupt table: if an interrupt is for the VM, it is delivered by upcall; otherwise the original table is reinstalled and the kernel resumes. So an upcall from the host kernel to the VM player is analogous to an interrupt from a hardware device to the CPU.
Kernel structure
A portable kernel sits between the system call interface (with portable OS libraries above it) and a hardware abstraction layer for x86, ARM, PowerPC and so on, with device drivers for networks, disks and graphics below. A microkernel follows the philosophy “what can be at user level, should be”.
On earlier exams
- 2023, question 3 – Upcalls and virtual machines
- 2023, question 4 – End of the interrupt handler
- 2023, question 5 – Bottom half of the interrupt handler
- 2023, question 6 – Trap
- 2023, question 7 – Processor exceptions
- 2023, question 8 – Mode switch
- 2024, question 8 – Upcall
- 2024, question 9 – Interrupts versus polling
- 2024, question 10 – Kernel philosophy
- 2025, question 3 – Interrupt
- 2025, question 10 – Trap
- 2025, question 17 – Interrupt stack
Practise this topic in the quiz (22 questions)