Writing an OS Kernel from Scratch – Part 6: First Look at Multitasking — From Single-Core Loops to Process Switching
“A kernel that can only do one thing? That’s a bare-metal program. A real OS must be able to ‘simultaneously’ do multiple things!”
In the previous five posts, we completed kernel boot, entering protected mode, enabling paging, and building the foundation of virtual memory. But so far, our kernel is still single-task: starting from kernel_main, executing straight through, unable to interrupt, unable to switch.
One of the core capabilities of a modern OS is Multitasking — making users feel like multiple programs are running “simultaneously.”
Today, we implement the simplest cooperative multitasking and understand the core principle of process context switching.
Two Types of Multitasking
| Type | Description | Difficulty |
|---|---|---|
| Cooperative | Tasks voluntarily yield CPU (e.g., call yield()) | ⭐ Simple |
| Preemptive | Clock interrupt forces switching (e.g., Linux) | ⭐⭐⭐ Complex |
Today, we first implement cooperative multitasking — its logic is clear and it’s the best starting point for understanding context switching.
Core Concepts: Process and Context
Process: a running program instance with an independent virtual address space and execution state (registers, stack, program counter, etc.)
Context (Context): a complete snapshot of CPU registers, including:
- General purpose registers (EAX, EBX, …)
- Instruction pointer (EIP)
- Stack pointer (ESP)
- Flags register (EFLAGS)
- Segment registers (CS, DS, …)
Context switching = Save current task state + Restore next task state
Process Control Block (PCB)
We need a struct to describe each process. Each process must have an independent kernel stack! Otherwise, stacks would overwrite each other during switching, causing crashes.
Context Switching: Assembly is the Only Choice
C language cannot directly manipulate EIP (program counter), so assembly is required for context save/restore.
The ret instruction pops EIP from the stack top — exactly the “next instruction address” we saved in the task stack!
Comments