Reading position, not mastery.
Reading settings
Line spacing
Text width
Saved only in this browser. Theme and colors are in Appearance.
Explore, understand, practice

Why do we need a kernel?

Understand the problem before the solution

Imagine an editor and an audio player sharing a machine. The editor enters an infinite loop. If audio depends on the editor voluntarily giving up control, a local bug disrupts the whole experience. If the editor can overwrite any memory address or storage block, correct audio-player code is insufficient protection.

In a simple model where one program directly controls the machine, the program owns resource management. This can suit dedicated applications. Independent programs introduce the need to share resources, protect them and communicate under controlled rules. This is a conceptual motivation, not a claim that every historical system followed exactly this sequence. The xv6 organization chapter explores this design problem.

Lesson goals: explain why a protection boundary is needed, draw a syscall path, and distinguish a privilege transition from a process switch. Suggested duration: two hours including exercises. Prerequisites: programs, instructions and memory.

What is the kernel, and what surrounds it?

The kernel is the privileged part of the operating system that manages resources and access to them. A usable operating system also includes user-space tools and services. Terminals, shells and compilers generally execute in user space. User space is neither a separate physical location nor a human user's identity; it describes the restricted execution environment for applications. Being root does not mean application instructions continuously run in kernel mode.

Separate three questions: Who is allowed access? When do they get a turn? What abstraction do they use? Authorization, scheduling and abstraction answer different questions. Files, processes and sockets expose resources. Calling the kernel a manager is only an analogy: instructions, data structures and hardware rules implement the mechanism.

How is the boundary enforced?

CPU privilege restricts permitted operations. Page tables specify memory mappings and access permissions; hardware performs translation and access checks while executing instructions. The kernel configures these mechanisms. Protection therefore does not rely solely on voluntary cooperation by applications.

In xv6 on RISC-V, applications run in U-mode and the kernel mainly runs in S-mode. Linux details depend on the architecture. Learn the relationship between restricted execution and controlled kernel entry rather than memorizing one privilege-level number for every CPU.

Request, controlled kernel entry and return to the application

Figure: arrows show control order, not separate CPUs. During a simple syscall, the same thread can execute kernel code and return to user space.

Worked example: writing three bytes

Consider this user program:

#include <unistd.h>
int main(void) {
    ssize_t n = write(1, "hi\n", 3);
    return n == 3 ? 0 : 1;
}

1 is a file-descriptor number in this process's table, not a permanent name for the screen. Output redirection can make it refer to a file. 3 is the requested byte count; it excludes the string's terminating zero. Production code must handle errors and short writes; this example studies just one call. See the write contract.

  1. Application code calls the library wrapper, still in user space.
  2. The wrapper prepares the syscall number and arguments according to the ABI, the binary agreement between both sides.
  3. An architecture-specific entry instruction transfers control to a kernel-selected entry. The xv6 model uses ecall; do not copy that instruction into x86 code.
  4. Hardware records part of the state; entry code preserves the additional context it needs. The CPU does not automatically save everything.
  5. The kernel dispatches the request. The descriptor and access to the user buffer require checks along the service path. Receiving a pointer does not make it trustworthy.
  6. The destination path accepts data, or an error or wait occurs. On the ordinary return path, the result is recorded and execution returns to user space.

Follow entry mechanics in the xv6 trap chapter and Linux-specific concerns in the Linux entry/exit documentation. This teaching trace does not identify every function in a particular Linux revision.

A successful write to a file alone does not guarantee durability after power loss. With printf, library buffering can change when and how many writes occur. Library calls and syscalls need not have a one-to-one relationship.

A crucial distinction: kernel entry versus a process switch

A mode switch changes the CPU execution privilege. A context switch changes the executing task's context. A syscall can return without another task running. If a request must wait, the scheduler may run a different task. Returning the result then requires the requesting task to resume. Compare this distinction with xv6 scheduling.

An interrupt is an event such as a device requesting attention; an exception is synchronous with an instruction, such as an invalid access; a syscall deliberately requests a service. Terminology has architecture-specific details. A page fault need not be fatal; later lessons cover lazy allocation. Syscalls are not the only occasions when kernel code runs.

Predict, then observe

Run these commands only inside Linux with cc and strace available. If the tools are missing, trace the path on paper for now; installation belongs to the lab lesson. Save the program above as hello.c.

uname -srmo
cc -Wall -Wextra -O0 -g hello.c -o hello
strace -e trace=write ./hello
strace -e trace=write ./hello > out.txt
cat out.txt

Predict first: Will the descriptor number change? Where will hi go? Where will the trace appear? The teaching expectation is a write on descriptor 1 returning 3; exact formatting depends on the environment. In the second experiment hi goes to the file, while strace normally reports to stderr, which > does not redirect. Descriptor 1 can remain the same while its destination changes. This is a prediction from the program and tool contract; this experiment has not been executed on the current system. See the strace manual.

Seeing write in a trace does not prove that data immediately reached disk or that another task ran. Not seeing malloc does not prove that no allocation occurred: malloc is a library API, and each allocation need not require a separate syscall.

Exercises: solve before reading the answers

  1. One trusted program runs on a machine. Does the argument for inter-program protection apply with the same force? What needs remain?
  2. Why cannot a library wrapper alone stop a malicious program?
  3. A hypothetical syscall immediately answers from ready data. Must a context switch have occurred? Explain.
  4. A program calls read(fd, buf, 100) and gets 20. Is that necessarily an error?
  5. Why can stdout's descriptor number stay 1 after output redirection?
  6. Is seeing read in strace enough to claim that execution waited for a device? Suggest additional evidence.
Reveal answers and reasoning

Answers and reasoning

  1. Inter-program protection does not have the same necessity under this assumption. Device setup, abstraction, interrupt handling and real-time requirements can remain. Derive a mechanism's necessity from the problem's assumptions.
  2. The application can bypass the wrapper. An effective boundary needs enforcement outside the application's control.
  3. No. Kernel entry and return can occur in the same task.
  4. No. A read may return fewer bytes than requested. Zero commonly indicates end of input for that source type; source semantics and errors require separate consideration. See the read contract.
  5. A descriptor is a handle in a process table, not a fixed hardware identifier. The same slot can refer to a different destination.
  6. The syscall name does not establish the actual waiting path. Scheduling traces correlated with relevant I/O events and a controlled environment help; even a long syscall duration alone does not establish the cause of waiting.

Completion criterion: draw the write path without notes. Treat privilege, executing task and output destination as three independent variables. Explain which claims the experiment establishes and which remain an explanatory model.

Linked sources checked on 2026-10-16. Diagrams and examples are original course material. Return to the roadmap.

Next: C for reading kernels