Repository navigation
Operating Systems 10 kernel
Relevant source files
The following references were used as context for generating this wiki page:
- Wikipedia: Kernel (operating system)
- Wikipedia: System call
- Wikipedia: Protection ring
- Wikipedia: Microkernel
- Wikipedia: Monolithic kernel
- Wikipedia: Interrupt
- Book: Silberschatz, Galvin and Gagne, Operating System Concepts, chapter 2
The kernel is the part of the OS that runs with full hardware privilege. Programs cannot call it like an ordinary function; they must cross a hardware-enforced boundary using a system call. This page explains how that crossing works, the three ways the CPU enters the kernel, how kernels are structured, and what happens when the machine boots. It finishes with the classic interview trace: "what happens when you type ls and press Enter?"
Assembly and traces on this page are illustrative.
This page covers privilege levels, the system call path, interrupts versus traps versus exceptions, monolithic, micro- and hybrid kernels, loadable modules, the boot sequence, and an end-to-end trace. Device interrupts in detail are on Files and I/O.
| Bank | Computer |
|---|---|
| Customers in the public hall | User-mode programs |
| The vault behind the counter | Kernel memory and hardware |
| Filling in a form and handing it through the window | A system call |
| The teller checks the form before acting | The kernel validates arguments |
| The fire alarm interrupts everyone | A hardware interrupt |
| A customer faints: staff must respond | An exception (fault) |
flowchart TB
subgraph Arm["Arm A-profile exception levels"]
EL0["EL0: applications"]
EL1["EL1: OS kernel"]
EL2["EL2: hypervisor"]
EL3["EL3: secure monitor / firmware"]
end
subgraph X86["x86 protection rings"]
R3["Ring 3: applications"]
R0["Ring 0: kernel"]
end
User code that tries a privileged instruction (change the page table base, disable interrupts) causes an exception, and the kernel usually kills the program.
Sources: Wikipedia: Protection ring
// illustrative: what a program writes
write(1, "hi\n", 3);sequenceDiagram
participant A as Application (user mode)
participant L as libc wrapper
participant C as CPU
participant K as Kernel (kernel mode)
A->>L: write(1, "hi\n", 3)
L->>L: put syscall number and arguments in registers
L->>C: SVC #0 (Arm) / syscall (x86-64)
C->>K: switch to kernel mode, jump to the fixed entry point
K->>K: save user registers, look up syscall table[number]
K->>K: sys_write: check fd, copy data from user memory safely
K-->>C: put return value in a register
C-->>L: return to user mode (ERET / sysret)
L-->>A: return 3 (or -1 and set errno)
// illustrative Arm64 Linux: write(1, msg, 3)
mov x0, #1 // fd
adr x1, msg // buffer
mov x2, #3 // count
mov x8, #64 // syscall number for write on arm64 Linux
svc #0 // trap into the kernel
Key points:
- Entry is only through a fixed, kernel-chosen address; programs can't jump into arbitrary kernel code.
- The kernel must never trust user pointers; it checks them and copies with special routines (
copy_from_user). - A system call costs far more than a function call (mode switch, register saving, cache and TLB effects), so programs batch work (buffered I/O in
stdio).
| Category | Examples |
|---|---|
| Process control |
fork, execve, exit, wait4, kill
|
| Files |
open, read, write, close, lseek, stat
|
| Memory |
mmap, munmap, brk
|
| Communication |
pipe, socket, send, recv
|
| Information |
getpid, clock_gettime
|
Some calls such as clock_gettime are often served in user mode through the vDSO, a small kernel-provided library, without a real mode switch.
Sources: Wikipedia: System call
| Kind | Caused by | Synchronous? | Examples |
|---|---|---|---|
| Interrupt | A device or timer, outside the program | No: can arrive at any time | Timer tick, disk done, network packet |
| Trap (software interrupt) | The program on purpose | Yes | System call (SVC, syscall), breakpoint |
| Exception / fault | The program by accident | Yes | Page fault, divide by zero, illegal instruction |
flowchart TD
U["User code running"] --> I["Interrupt<br/>(device, timer)"]
U --> T["Trap<br/>(system call)"]
U --> F["Fault<br/>(page fault, bad instruction)"]
I --> V["Exception vector table<br/>in the kernel"]
T --> V
F --> V
V --> H["Handler runs in kernel mode"]
H --> R{"Outcome"}
R --> RE["Return to the same program"]
R --> SW["Schedule another thread"]
R --> KI["Kill the program (SIGSEGV, SIGILL)"]
The timer interrupt is what makes preemptive scheduling possible (CPU Scheduling).
Sources: Wikipedia: Interrupt
flowchart TB
subgraph Mono["Monolithic kernel"]
direction TB
MU["Apps"] --> MK["Kernel: scheduler, memory, file systems,<br/>drivers, network stack — all in kernel mode"]
end
subgraph Micro["Microkernel"]
direction TB
UU["Apps"] --> SV["User-mode servers:<br/>file system, drivers, network"]
SV -->|"IPC messages"| UK["Small kernel: scheduling,<br/>address spaces, IPC"]
UU -->|"IPC"| UK
end
| Monolithic | Microkernel | Hybrid | |
|---|---|---|---|
| In kernel mode | Everything | Only the minimum | Most services, some in user space |
| Speed | Fast: direct function calls | Slower: IPC for every service | In between |
| A driver crash | Can crash the whole system | Restart the server; system survives | Depends |
| Examples | Linux, traditional Unix | seL4, QNX, MINIX 3 | Windows NT, macOS XNU |
Linux is monolithic but modular: drivers can be loaded and unloaded at run time as loadable kernel modules (insmod, modprobe), still running in kernel mode.
Sources: Wikipedia: Monolithic kernel, Wikipedia: Microkernel
flowchart LR
P["Power on"] --> R["Boot ROM / firmware<br/>(UEFI or BIOS; on Arm, trusted firmware)"]
R --> B["Bootloader<br/>(GRUB, U-Boot)"]
B --> K["Kernel: set up memory, MMU,<br/>interrupts, drivers"]
K --> M["Mount root file system"]
M --> I["Start init (PID 1)<br/>(systemd)"]
I --> S["Services, login, shell"]
A favourite interview question. A good answer touches most of this wiki:
sequenceDiagram
participant KB as Keyboard
participant K as Kernel
participant SH as Shell
participant LS as ls process
KB->>K: key interrupts; driver buffers characters
K->>SH: Enter pressed: shell's blocked read() returns "ls\n"
SH->>SH: parse command, search PATH for /bin/ls
SH->>K: fork()
K-->>LS: child created (copy-on-write pages)
LS->>K: execve("/bin/ls")
K->>K: load ELF: map code, set up stack, dynamic linker loads libc
LS->>K: openat("."), getdents64(): read directory entries
K->>K: file system reads inodes/blocks (page cache or disk, DMA, interrupt)
LS->>K: write(1, names): terminal driver displays them
LS->>K: exit(0)
K->>SH: SIGCHLD; shell's waitpid() returns
SH->>K: write prompt, read() again (blocks)
| Step | Concept | Page |
|---|---|---|
| Keyboard interrupt, driver buffer | Interrupts | Files and I/O |
Shell blocked in read wakes up |
Process states | Processes |
fork + execve + waitpid
|
Process creation | Processes |
| Child gets the CPU | Scheduling | CPU Scheduling |
| Pages loaded lazily; COW after fork | Virtual memory | Virtual Memory |
| Directory read through inodes | File systems | Files and I/O |
| Every request to the kernel | System calls | this page |
- A system call is not a normal function call; it changes privilege level.
- Interrupts are asynchronous; traps and faults are caused by the current instruction.
- "Monolithic" does not mean "not modular"; Linux has loadable modules.
- The kernel is not a process that runs alongside others; it runs in the context of whichever thread trapped into it (plus its own kernel threads).
- What happens during a system call? The library puts the call number and arguments in registers and executes a trap instruction; the CPU switches to kernel mode at a fixed entry point; the kernel saves state, dispatches through the syscall table, validates arguments, does the work, and returns to user mode with a result.
- Interrupt vs trap vs exception? Interrupt: asynchronous, from hardware. Trap: deliberate, from an instruction (syscall). Exception/fault: accidental, from an instruction (page fault, divide by zero).
- Monolithic vs microkernel? Monolithic runs all services in kernel mode (fast, less isolated); a microkernel keeps only the essentials in the kernel and runs services in user space (more robust, more IPC overhead).
- Why can't user programs just disable interrupts? It is a privileged instruction; allowing it would let one program take over the CPU.
- What is a kernel module? Code (often a driver) loaded into a running kernel, running in kernel mode.
-
What happens when you type
lsand press Enter? See the trace above: interrupt, read returns, fork, exec, file system reads, writes to the terminal, exit, wait.
- Hardware enforces user and kernel modes; programs cross into the kernel only via system calls, interrupts and exceptions.
- System calls go through a fixed entry point and a dispatch table, with careful checking of user arguments.
- Kernels are monolithic, micro or hybrid; Linux is monolithic with loadable modules.
- Computer Architecture Overview
- Fundamentals: CPU, Memory and Instructions
- Pipelining
- Branches and Remedies
- Instruction-Level Parallelism
- Memory and Ordering
- Caches and Coherence
- Multicore
- Multithreading in Hardware
- SIMD and GPUs
- Glossary and Summary
- Hexagon Overview and Processor Properties
- ISA Fundamentals: Packets, Slots and Threads
- Registers
- Instruction Encoding and Mnemonics
- Data, Memory and Control Instructions
- Floating Point, HVX and Alignment
- Caches, MMU and Glossary
- Operating Systems Overview
- Processes
- Threads
- CPU Scheduling
- Synchronization
- Deadlock
- Memory Management
- Virtual Memory
- Files, Storage and I/O
- Kernel and System Calls
- Interview Q&A and Glossary
- C++ for LLVM Development: Overview
- C++ Basics
- Classes and RAII
- Ownership and Move Semantics
- Templates and Lambdas
- LLVM Data Structures (ADT)
- LLVM-Style RTTI: isa, cast, dyn_cast
- Errors, Output and Assertions
- Iterators and Ranges
- Building, Debugging and Exercises
- LLVM IR Overview
- Structure: Modules, Functions, Blocks and Values
- Type System
- Arithmetic, Bitwise and Cast Instructions
- Compare and Select
- Memory: alloca, load, store and getelementptr
- Control Flow: br, switch, ret and call
- SSA and Phi
- Control Flow Graph and Loops
- Dominance, Dominator Tree and Dominance Frontier
- Data-flow Analysis
- Writing an IR Pass
- Common Passes
- Exercises, Tooling and Glossary
- SelectionDAG Overview
- Pipeline, Phases and Traversal Orders
- Core Data Structures
- DAG Construction
- DAG Combiner
- Legalization
- Type Legalization
- Operation and Vector Legalization
- Instruction Selection
- TableGen Pattern Language
- Matcher Interpreter and Folding
- AArch64 Instruction Selection
- Scheduling and MIR Emission
- PHI Node Resolution
- AArch64 Walkthroughs
- Arithmetic and Data Movement
- Memory Instructions
- Control Flow and Calls
- End-to-End Example
- Tooling, Debugging and Extending
- Selector Comparison and Glossary
- Assignments: Build the Toy Backend
- Stage 1: Build Setup
- Stage 2: Target Registration
- Stage 3: TableGen Skeleton
- Stage 4: MC Layer for Assembly Output
- Stage 5: TargetMachine and Subtarget
- Stage 6: TargetLowering, Arguments and Returns
- Stage 7: Instruction Selection and the First Function
- Stage 8: Registers, Copies and Spills
- Stage 9: Frame Lowering
- Stage 10: Memory, Globals and Control Flow
- Stage 11: Calls
- Stage 12: Scheduling Model
- Stage 13: Object Files
- Stage 14: Capstone, a Complete Toy Backend
- Target Bring-up Overview
- Directory Layout, CMake and Registration
- The Target .td File
- TargetMachine and Subtarget
- TargetLowering Setup
- Calling Conventions
- Instructions and Instruction Selection
- Registers and Allocation Hooks
- Frame Lowering
- AsmPrinter and the MC Layer
- Scheduling
- A Minimal Toy Target
- Bring-up Checklist and AArch64 File Map
- Tooling and Glossary
- Calling Conventions Overview
- The CallingConv.td Language
- CCState and CCValAssign
- LowerFormalArguments
- LowerCall
- LowerReturn and CanLowerReturn
- Varargs, byval, sret and swifterror
- Tail Calls and Sibling Calls
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- Frame Lowering Overview
- MachineFrameInfo
- TargetFrameLowering Hooks
- The PEI Pass
- Callee-Saved Registers and Stack Layout
- Frame Index Elimination and the Register Scavenger
- Shrink Wrapping
- CFI and Unwind Information
- Custom Backend Guide and Checklist
- AArch64 Walkthroughs
- Tooling and Glossary
- MC Layer Overview
- Core Data Structures
- Streamers
- Assembler and Layout
- Fixups and Relocations
- Writing an MC Layer for a Custom Backend
- MCAsmInfo and the Instruction Printer
- Code Emitter
- AsmBackend and Object Writer
- Assembly Parser and Disassembler
- Bring-up Checklist and Common Failures
- Tooling and Glossary
- Register Allocation Overview
- The Register Allocation Pipeline
- Registers, Virtual Registers and Register Classes
- Liveness: Slot Indexes and Live Intervals
- Preparing Code for Allocation
- PHI Elimination and Two-Address Lowering
- Register Coalescer
- Allocation Framework
- The Register Allocators
- Fast Register Allocator
- Basic Register Allocator
- Greedy Register Allocator
- PBQP Register Allocator
- Spilling and Splitting
- Spill Weights and Copy Hints
- The Inline Spiller
- Live Range Splitting
- Rewriting and Post-RA Passes
- Writing Register Allocation Support for a Custom Backend
- Register Definitions in TableGen
- TargetRegisterInfo Hooks
- TargetInstrInfo Hooks
- Pass Pipeline Hooks
- Bring-up Checklist and Common Failures
- AArch64 Walkthroughs
- Tooling and Debugging
- Glossary and Where Do I Look