> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/linux-internals/02.-boot-process-x86-x86_64-bios-and-uefi.md).

# 02. Boot Process (x86/x86\_64: BIOS & UEFI)

***

### 0. What "booting" even means

When you press the power button, the computer's RAM (its fast, temporary "working memory" - see file 00) is **completely empty**. There is no operating system running, no programs loaded, nothing. "Booting" is the step-by-step process of loading small pieces of software, each one loading a slightly bigger and smarter piece, until eventually the full Linux kernel and a usable login screen exist. This bootstrapping-by-stages is literally where the word "boot" comes from ("pulling yourself up by your bootstraps").

```mermaid
flowchart LR
    A["Power OFF<br/>(RAM is empty,<br/>nothing running)"] --> B["Tiny firmware program<br/>(built into the motherboard)<br/>wakes up"]
    B --> C["Firmware loads a slightly<br/>bigger program: the<br/>BOOTLOADER"]
    C --> D["Bootloader loads a much<br/>bigger program:<br/>the LINUX KERNEL"]
    D --> E["Kernel starts the first<br/>user program: INIT / systemd"]
    E --> F["Login prompt appears  - <br/>system is ready to use"]
```

Each stage exists because the *previous* stage was too small/dumb to do the *next* stage's job directly - the firmware can't understand a full filesystem, so it loads a bootloader that can; the bootloader can't manage processes and memory, so it loads a kernel that can; and so on.

***

### 1. The full chain

```mermaid
flowchart LR
    subgraph S1["Stage 1"]
        Firm["Firmware<br/>(BIOS or UEFI)<br/>built into the motherboard"]
    end
    subgraph S2["Stage 2"]
        Boot["Bootloader<br/>(GRUB2)"]
    end
    subgraph S3["Stage 3"]
        Kern["Kernel decompresses<br/>and starts itself"]
    end
    subgraph S4["Stage 4"]
        Init1["initramfs<br/>(early, temporary userspace)"]
    end
    subgraph S5["Stage 5"]
        Kern2["Kernel finishes init,<br/>mounts the REAL disk"]
    end
    subgraph S6["Stage 6"]
        Sysd["init / systemd<br/>(PID 1) starts services"]
    end
    S1 --> S2 --> S3 --> S4 --> S5 --> S6
```

| Stage             | What happens                             | Key detail             |
| ----------------- | ---------------------------------------- | ---------------------- |
| 1. Firmware       | Checks hardware, finds a boot device     | POST, MBR/GPT          |
| 2. Bootloader     | Loads the kernel + initramfs into RAM    | GRUB2 menu             |
| 3. Kernel startup | Kernel decompresses, sets up the CPU     | `vmlinuz`, `head_64.S` |
| 4. initramfs      | Temporary mini-Linux finds the real disk | ramdisk, loads drivers |
| 5. Kernel handoff | Switches to the real, permanent disk     | `switch_root`          |
| 6. Init system    | Starts all background services           | systemd targets        |

***

### 2. Stage 1 - Firmware: BIOS (legacy) vs UEFI (modern)

**Firmware**, recall from file 00, is small, permanent software built into a chip on the motherboard itself (not on your main hard drive) - it's the very first code that runs, before any operating system exists. On a PC, this firmware is either the older **BIOS** or the newer **UEFI**.

#### Legacy BIOS path

```mermaid
flowchart TD
    A["CPU is reset (powered on).<br/>It automatically starts executing<br/>at a fixed hardware address."] --> B["That address is wired to point<br/>into ROM (Read-Only Memory)  - <br/>a chip holding the BIOS firmware"]
    B --> C["BIOS runs POST<br/>(Power-On Self Test):<br/>checks RAM, CPU, keyboard, etc."]
    C --> D["BIOS finds the boot device<br/>and reads its very first<br/>512-byte SECTOR: the MBR"]
    D --> E["MBR contains a tiny 446-byte<br/>bootstrap program<br/>(GRUB 'stage 1')"]
    E --> F["This tiny program loads a<br/>BIGGER second-stage<br/>bootloader from the disk<br/>sectors right after the MBR"]
    F --> G["Bigger bootloader understands<br/>real filesystems, finds and<br/>loads the actual Linux kernel"]
    G --> H["Control passes to the kernel"]
```

Term-by-term:

* **ROM (Read-Only Memory)**: a memory chip whose contents are burned in at the factory (or rarely updated) and survive with no power - this is physically where BIOS firmware code lives.
* **POST (Power-On Self Test)**: the firmware's own self-check routine - verifies the CPU, RAM, and basic devices are working *before* trying to load anything further. (This is why a dead RAM stick often produces beep codes at this stage - the OS never even got a chance to start.)
* **Boot device**: whichever disk (or USB stick, network location, etc.) the firmware is configured to try loading an OS from.
* **Sector**: the smallest unit a disk can be read or written in - for traditional disks, 512 bytes. The very first sector on a disk (sector 0) is special: BIOS unconditionally reads it and treats it as bootable code, *if* it ends with a specific 2-byte signature (below).
* **MBR (Master Boot Record)**: the name for that special first 512-byte sector, when used in the legacy BIOS scheme. It's split into three parts:

```mermaid
flowchart LR
    subgraph MBR["MBR - 512 bytes total"]
        direction LR
        BC["Bootstrap code<br/>446 bytes<br/>(tiny program)"]
        PT["Partition table<br/>64 bytes<br/>(4 entries × 16 bytes)"]
        SIG["Boot signature<br/>2 bytes<br/>0x55AA"]
    end
```

* **Bootstrap code**: the actual tiny executable machine code (see file 00 - raw CPU instructions) living in the MBR's first 446 bytes.
* **Partition table**: a small table describing how the disk is divided into up to 4 separate sections ("partitions"), each of which can hold a different filesystem (e.g. one partition for Linux, one for a separate data drive).
* **Partition**: a logically separate section of a physical disk, treated by software as if it were its own independent disk.
* **Boot signature (`0x55AA`)**: two specific bytes at the very end of the first sector. If a disk's first sector doesn't end in exactly these two bytes (written in hexadecimal - see file 00), BIOS refuses to treat it as bootable at all - this is a basic sanity check.
* **"Stage 1" / "Stage 1.5" / "Stage 2" bootloader**: because 446 bytes is nowhere near enough code to understand a real filesystem (like ext4 - file 05) well enough to find and load a kernel file, GRUB splits itself into progressively bigger pieces: a tiny stage 1 (fits in the MBR) whose *only* job is to load a bigger stage from the disk sectors immediately following the MBR, which in turn is smart enough to read a real filesystem and load GRUB's full, feature-complete core.

#### Modern UEFI path

```mermaid
flowchart TD
    A["CPU is reset (powered on)"] --> B["UEFI firmware starts  - <br/>it's a much more capable,<br/>OS-like environment than BIOS"]
    B --> C["UEFI reads its own saved<br/>list of boot entries<br/>(stored in NVRAM)"]
    C --> D["UEFI understands GPT<br/>partition tables and FAT32<br/>filesystems NATIVELY  - <br/>no MBR bootstrap code needed"]
    D --> E["UEFI directly runs a<br/>.efi executable file from<br/>the ESP partition<br/>(e.g. grubx64.efi)"]
    E --> F{"Secure Boot<br/>enabled?"}
    F -->|Yes| G["Verify cryptographic signature<br/>on each stage before running it"]
    F -->|No| H["Just run it, unverified"]
    G --> I["Bootloader runs,<br/>loads the kernel"]
    H --> I
```

Term-by-term:

* **UEFI (Unified Extensible Firmware Interface)**: the modern replacement for BIOS - richer, understands modern partition/filesystem formats directly, and provides its own driver model (it can talk to more hardware types on its own, before any OS exists).
* **NVRAM (Non-Volatile RAM)**: a small amount of memory on the motherboard that, unlike normal RAM, **keeps its contents even with the power off** (similar in spirit to ROM/disk, but small and rewritable) - UEFI stores its list of configured boot options here.
* **GPT (GUID Partition Table)**: the modern partition table format used with UEFI. Unlike MBR's hard 4-partition limit, GPT supports many more partitions and much larger disks. "GUID" = Globally Unique Identifier, a very-unlikely-to-repeat random ID used to label each partition.
* **ESP (EFI System Partition)**: a small, dedicated partition formatted as **FAT32** (an old, simple, universally-understood filesystem format) that UEFI firmware can read directly - it holds the actual `.efi` bootloader program files.
* **`.efi` executable**: a program file UEFI firmware itself knows how to load and run directly, without any OS present yet.
* **Secure Boot**: an optional UEFI feature that checks a **cryptographic signature** (a mathematical proof that a file hasn't been tampered with and comes from a trusted source) on the bootloader before running it - and the bootloader in turn checks the kernel's signature, and so on. This "chain of trust" means: firmware trusts `shim` → `shim` trusts GRUB/kernel via a **MOK (Machine Owner Key)** or a Microsoft-signed key. If you ever build a custom/unsigned kernel module for research, this is exactly what produces a "module signature verification failed" error unless you disable Secure Boot or enroll your own key.
* **Chain of trust**: the general security concept where each stage verifies the next stage's signature before running it, so that trust in one root (the firmware, permanently trusted "by definition") extends step-by-step to everything that eventually runs.

***

### 3. Stage 2 - Bootloader (GRUB2)

**GRUB2**'s entire job is: find and load two files into RAM - the Linux **kernel image** (`vmlinuz-*`) and the **initramfs** (`initrd.img-*`, explained fully in section 5) - then jump into the kernel and get out of the way.

* **Kernel image (`vmlinuz`)**: the actual compiled Linux kernel, stored as a *compressed* file on disk (much like a `.zip` file) to save space - "vm" historically stood for "virtual memory," and "z" indicates it's gzip-compressed.

Key configuration file: `/boot/grub/grub.cfg` - this is automatically *generated* (you're not meant to hand-edit it) from settings in `/etc/default/grub` and helper scripts in `/etc/grub.d/`.

A single boot menu entry inside that file looks roughly like:

```
linux   /boot/vmlinuz-6.8.0-generic root=UUID=xxxx ro quiet splash
initrd  /boot/initrd.img-6.8.0-generic
```

* **Kernel command line**: the text after `linux` above (`root=...`, `ro`, `quiet`, `splash`) - a list of options passed from the bootloader to the kernel, read by the kernel very early during its own startup. This is where you'd add debugging flags like `nokaslr` (see section 7) or `kgdboc=ttyS0` when doing kernel debugging.
* **`root=UUID=xxxx`**: tells the kernel which disk partition contains the real root filesystem (`/`) - identified by a UUID (Universally Unique Identifier, a long random string) rather than a device name like `/dev/sda1`, because device names can shift between boots but a UUID (stamped onto the filesystem when it was created) never changes.
* **`ro`**: mount the root filesystem read-only initially (it gets remounted read-write later in boot, once it's safe to do so).
* **`quiet` / `splash`**: cosmetic options - suppress most boot messages and show a graphical splash screen instead.

#### CPU mode transitions during this stage

```mermaid
flowchart LR
    A["Real Mode<br/>(16-bit)<br/>BIOS/reset era holdover,<br/>can only address 1MB of RAM"] --> B["Protected Mode<br/>(32-bit)<br/>set up by GRUB,<br/>adds memory protection"]
    B --> C["Long Mode<br/>(64-bit)<br/>set up by the KERNEL ITSELF,<br/>very early in its own code<br/>(head_64.S) - full 64-bit<br/>addressing"]
```

* **Real mode**: the CPU's original, simplest operating mode, dating back to the 1978 Intel 8086 chip - every x86 CPU still powers on in this mode for backward compatibility, even though nothing modern actually wants to stay in it. Extremely limited: only 1 megabyte of memory is addressable at all.
* **Protected mode**: a more capable 32-bit CPU mode introduced later (1982, the 80286/80386 era) that adds memory protection (the beginning of the ring 0/ring 3 concept from file 01) and can address far more memory.
* **Long mode**: the modern, full 64-bit CPU mode that x86\_64 Linux actually runs in day-to-day. The kernel itself (not GRUB) performs this final transition, extremely early in its own startup code.

***

### 4. Stage 3 - Kernel startup

```mermaid
flowchart TD
    A["vmlinuz loaded into RAM<br/>by GRUB (still compressed)"] --> B["A tiny decompression stub<br/>(prepended to the file)<br/>runs and DECOMPRESSES<br/>the real kernel (vmlinux)"]
    B --> C["Architecture-specific setup<br/>(head_64.S, setup.c):<br/>page tables, long mode,<br/>parse command line, GDT/IDT"]
    C --> D["start_kernel()<br/> -  the main, hardware-independent<br/>C entry point"]
    D --> E["Initializes: scheduler,<br/>memory management, IRQ handling,<br/>timers, and every subsystem<br/>via 'initcalls'"]
    E --> F["kernel_init() runs:<br/>mounts initramfs as a<br/>TEMPORARY root filesystem"]
    F --> G["execs /init inside<br/>the initramfs<br/>(Stage 4 begins)"]
```

* **Decompression stub**: a very small, simple program glued onto the front of the `vmlinuz` file whose only job is to unpack the real, compressed kernel code into RAM so it can actually run.
* **`vmlinux`**: the *uncompressed* kernel binary, sitting inside the compressed `vmlinuz` wrapper.
* **Page table**: a data structure the kernel builds (covered in full depth in file 04) that lets the CPU translate the memory addresses a program uses into real physical RAM locations. Setting up the first, most basic page tables is one of the earliest things the kernel does, because long mode (64-bit) can't function without them.
* **GDT (Global Descriptor Table)**: a table, read directly by the CPU's hardware, that defines memory "segments" and which privilege level (ring - see file 01) each one requires. Historically very important; on modern 64-bit Linux its role is much reduced but it's still set up because the CPU architecture requires *some* valid GDT to exist.
* **IDT (Interrupt Descriptor Table)**: a table, also read directly by CPU hardware, mapping each possible **interrupt** or **exception** number to the address of the kernel function that should handle it. An *interrupt* is a hardware signal (e.g. "the keyboard has a keypress ready," "the timer has ticked") that pauses whatever the CPU was doing to run a handler immediately; an *exception* is a similar mechanism triggered by the CPU itself detecting a problem (like the page fault from file 04, or dividing by zero).
* **`start_kernel()`**: the function, written in ordinary, portable C code (not specific to any one CPU architecture), that represents "the real beginning" of the Linux kernel's own logic - everything before this was just architecture-specific plumbing to get the CPU into a state where this portable C code can safely run.
* **Scheduler**: the part of the kernel that decides which process gets to use the CPU at any given moment (full depth in file 03).
* **Buddy allocator**: one of the kernel's internal systems for managing free physical RAM in power-of-two-sized chunks - a low-level building block that other allocators (like SLUB, from file 04) are built on top of.
* **IRQ (Interrupt Request)**: the specific hardware-level signal a device sends to get the CPU's attention (the term "interrupt" and "IRQ" are used almost interchangeably).
* **RCU (Read-Copy-Update)**: an advanced kernel synchronization mechanism allowing many CPUs to read shared data simultaneously without locks, at the cost of more complex update logic - you don't need to understand its internals yet, just recognize the name in boot logs.
* **Timer**: kernel infrastructure for scheduling code to run after a delay or repeatedly at fixed intervals (used constantly, e.g. by the scheduler itself).
* **Workqueue**: a kernel mechanism for deferring work to be run later, in a safer context, instead of doing it immediately (referenced again in file 03's discussion of interrupt handling).
* **`initcall`**: a registration mechanism letting each kernel subsystem and device driver say "run my setup function during boot, in this general phase" - this is why a boot log shows dozens of lines like "usb 1-1: new high-speed device" as each driver's initcall runs and detects hardware.
* **Driver**: code, usually part of the kernel, written specifically to operate one particular kind of hardware device (a specific network card model, a specific disk controller, etc).
* **KASLR (Kernel Address Space Layout Randomization)**: covered in depth in file 04 - the short version is that the kernel deliberately loads itself at a randomized memory address on every boot (instead of always the same one), to make it harder for an attacker to guess where kernel code/data will be.
* **Entropy**: genuinely unpredictable data, used as the raw material for randomization. **RDRAND** and **RDTSC** are two specific x86 CPU instructions used as entropy sources very early in boot - `RDRAND` reads a hardware random-number generator built into the CPU chip; `RDTSC` reads the CPU's internal cycle counter (whose exact value at any given moment is hard to predict), which can be used as a weaker fallback source of randomness.

***

### 5. Stage 4 - initramfs / initrd (early, temporary userspace)

```mermaid
flowchart TD
    A["Kernel execs /init<br/>(inside the initramfs)"] --> B["Loads kernel MODULES needed<br/>to access the real disk<br/>(disk controller drivers,<br/>LVM/RAID/LUKS tooling, etc.)"]
    B --> C["Assembles /dev device files<br/>(via mdev or udev rules)"]
    C --> D["Finds the REAL root device<br/>(by UUID/LABEL, read from<br/>the kernel command line)"]
    D --> E["Mounts that real root device<br/>at a temporary location<br/>(/root or /sysroot)"]
    E --> F["Runs: switch_root /root /sbin/init"]
    F --> G["Old initramfs is DELETED<br/>from RAM (freeing the space);<br/>new filesystem becomes '/';<br/>real /sbin/init (systemd) execs"]
```

* **initramfs (Initial RAM Filesystem)** / **initrd (Initial RAM Disk)**: two closely related terms for the same idea - a small, temporary filesystem, loaded entirely into RAM by GRUB alongside the kernel, that exists purely to bridge the gap between "kernel just started, doesn't know how to reach the real disk yet" and "real disk is mounted and ready." ("initrd" technically referred to an older, slightly different implementation; "initramfs," a compressed **cpio archive**, is what modern systems actually use - the two terms are now used almost interchangeably.)
* **cpio archive**: a simple, old Unix format for bundling many files into one file (conceptually similar to a `.zip` or `.tar` file) - initramfs images are cpio archives, compressed.
* **Kernel module**: a piece of kernel code that can be loaded into a running kernel *on demand*, rather than being permanently built into the main kernel image - lets the kernel stay smaller and only load the specific hardware drivers a given machine actually needs.
* **LVM (Logical Volume Manager)**: a layer of abstraction that lets multiple physical disks be combined and re-divided flexibly into "logical volumes," instead of being stuck with fixed physical partitions.
* **RAID (Redundant Array of Independent Disks)**: a technique for combining multiple physical disks to improve performance and/or survive individual disk failures.
* **LUKS (Linux Unified Key Setup)**: the standard Linux full-disk encryption format - if your root filesystem is encrypted, the initramfs is what prompts you for the decryption password very early in boot.
* **`/dev`**: the directory where Linux represents hardware devices as special "device files" (e.g. `/dev/sda` for a disk) that programs can open and read/write like regular files, even though they're really talking to hardware.
* **`mdev` / `udev`**: two different programs (mdev is a simpler, smaller one often used in minimal initramfs environments; udev is the full-featured one used on regular running systems) responsible for automatically creating and removing `/dev` device files as hardware is detected.
* **UUID / LABEL**: two different ways to give a filesystem a stable, human-independent identity so it can be found reliably, regardless of which physical disk slot or drive letter it happens to be attached to at any given boot.
* **`busybox`**: a single small program that implements simplified versions of dozens of standard Unix command-line tools (`ls`, `cat`, `mount`, etc.) all in one compact binary - the standard way to get a minimal, functional userspace environment inside a tiny initramfs without needing dozens of separate full-sized programs.
* **`switch_root`**: the specific operation that ends the initramfs stage - it deletes everything currently using RAM from the old, temporary initramfs (freeing that memory), makes the newly-mounted real filesystem become the system's actual `/` (root directory), and then runs (`exec`s) the real init program from that real filesystem. The process ID doesn't change - it's still "PID 1" - but the program running as PID 1, and the entire filesystem underneath it, is now the real one.

***

### 6. Stage 5 - PID 1 and userspace init (systemd, mainstream today)

* **PID (Process ID)**: a unique number the kernel assigns to every running process (file 03 covers processes in full).
* **PID 1**: by long-standing Unix convention, the very first userspace process the kernel starts is always assigned process ID 1, and every other process that will ever run is a descendant of it (directly or indirectly). On essentially all modern Linux distributions, this program is **systemd**.
* **init system**: the general term for "whatever program runs as PID 1 and is responsible for starting every other background service." systemd is the dominant one today; older alternatives include **sysvinit** and **OpenRC**.

```mermaid
flowchart TD
    A["systemd starts as PID 1"] --> B["activates sysinit.target"]
    B --> B1["mount remaining filesystems<br/>(from /etc/fstab)"]
    B --> B2["set up swap"]
    B --> B3["udev finishes detecting<br/>all hardware"]
    B1 & B2 & B3 --> C["activates basic.target"]
    C --> C1["sockets, timers, and<br/>paths are ready"]
    C1 --> D["activates default.target<br/>(usually multi-user.target<br/>or graphical.target)"]
    D --> D1["network.target /<br/>NetworkManager starts"]
    D --> D2["sshd.service starts"]
    D --> D3["your application<br/>services start"]
    D --> D4["getty@tty1.service starts<br/>→ LOGIN PROMPT APPEARS"]
```

* **systemd**: the modern Linux init system - beyond just starting services, it also supervises them (restarting crashed services), manages logging (file 08 covers this), and coordinates most system startup.
* **Unit**: systemd's basic building block - a single service, mount point, socket, or timer that systemd knows how to start/stop/monitor (file 08 covers unit files in full depth).
* **Target**: a named *group* of units representing a particular system state or boot milestone (e.g. `multi-user.target` roughly means "normal multi-user command-line system is fully up") - conceptually similar to the older idea of a numbered "runlevel," but based on flexible dependencies instead of a fixed sequence of numbers.
* **Dependency graph**: systemd doesn't start units in one fixed linear order - instead every unit declares what it needs to happen before/after it, and systemd computes a valid order (and parallelizes anything with no dependency on each other) from that graph, which is why modern boot is often much faster than older strictly-sequential init systems.
* **`/etc/fstab`**: a configuration file listing which filesystems should be automatically mounted at boot, and where.
* **Swap**: disk space set aside to act as an overflow area for RAM when physical memory runs low (slower than real RAM, but prevents an out-of-memory crash).
* **`getty`**: the traditional program that manages a login prompt on a terminal - `getty@tty1.service` is what actually displays the text login prompt you see on a fresh boot.

Inspect this yourself later with:

```
systemctl list-units --type=target
systemd-analyze critical-path       # what took longest at boot
systemd-analyze plot > boot.svg     # visualize boot timeline
journalctl -b                       # this boot's log, incl. kernel msgs
dmesg                               # kernel ring buffer (boot msgs)
```

* **`journalctl` / journal**: the tool/log for reading systemd's own structured system log (file 08 covers this).
* **`dmesg`**: shows the **kernel ring buffer** - a fixed-size, in-memory log the kernel itself writes messages into (including everything it printed during boot, before any logging daemon even existed yet).
* **Kernel ring buffer**: a circular (oldest messages get overwritten) memory buffer the kernel uses to record its own log messages.

***

### 7. Why this matters for kernel/exploit dev

* **KASLR seed timing**: the entropy (see section 4) used to randomize the kernel's load address is gathered very early in boot; on virtual machines it can be weaker/more predictable than on physical hardware - directly relevant when trying to make a kernel exploit reliable.
* **initramfs is a great place to stash debug tooling** when building a custom kernel-dev/fuzzing VM image - you often build a minimal initramfs by hand with `busybox` plus your own proof-of-concept binary, for a fast crash-reboot-retry loop.
* **Fuzzing** (mentioned above): an automated testing technique that feeds a program huge amounts of random or semi-random input, looking for crashes that might indicate a security bug - extremely commonly used against the Linux kernel itself (a tool called **syzkaller** is the standard one).
* **Kernel command line flags you'll use constantly**:
  * `nokaslr` - disable KASLR for reliable, repeatable debugging.
  * `nopti` - disable **KPTI** (the Meltdown-mitigation mechanism covered in file 04) for benchmarking or simplifying analysis.
  * `console=ttyS0 earlyprintk=serial` - send early boot output over a **serial console** (a simple, very old-style text communication link) instead of the normal graphics-based screen - essential when debugging a kernel running inside **QEMU** (a common tool for running virtual machines, heavily used for kernel development/research because it can be paused, snapshotted, and attached to with a debugger).
  * `panic=1` - automatically reboot 1 second after a kernel crash (**kernel panic**) instead of hanging forever - handy for automated fuzzing loops that need to recover and keep going.
* **Kernel panic**: the kernel's version of an unrecoverable crash - when the kernel itself hits a fatal, unrecoverable error, it can't just "restart the program" (there's no other program to fall back to, it *is* the foundation everything else runs on), so it halts (or, with `panic=1`, reboots) the entire machine.
* **`/proc/cmdline`**: a special file (part of `procfs`, covered in file 05) that shows you exactly what kernel command line the currently running kernel was actually booted with.
* Understanding GDT/IDT setup here matters later for interrupt handling and exception-based exploitation primitives (referenced again in files 03 and 04).

***

### 8. Key Terms Defined&#x20;

* **Boot device**: whichever storage device firmware is configured to try loading an operating system from.
* **Boot signature (`0x55AA`)**: the specific two bytes ending a legacy MBR sector, confirming to BIOS that it's bootable.
* **Bootstrap code**: the tiny initial machine-code program stored in an MBR's first 446 bytes.
* **Buddy allocator**: a kernel mechanism for managing free physical RAM in power-of-two-sized chunks.
* **`busybox`**: a single compact binary implementing simplified versions of many standard Unix commands, used inside minimal environments like an initramfs.
* **Chain of trust**: a security model where each stage cryptographically verifies the next before running it, extending trust from one fixed starting point.
* **cpio archive**: an old Unix file-bundling format; initramfs images are compressed cpio archives.
* **Cryptographic signature**: a mathematical proof, attached to a file, that it hasn't been altered and originates from a specific trusted source.
* **Decompression stub**: a tiny program prepended to `vmlinuz` whose only job is to unpack the real, compressed kernel into RAM.
* **Dependency graph**: the structure systemd builds from every unit's declared ordering requirements, used to compute a valid (and parallelized) startup order.
* **`/dev`**: the directory holding special files representing hardware devices.
* **`dmesg`**: the command that displays the kernel's own in-memory log (the kernel ring buffer).
* **Driver**: code (usually part of the kernel) written to operate one specific kind of hardware device.
* **Entropy**: genuinely unpredictable data used as raw material for randomization (e.g. for KASLR).
* **ESP (EFI System Partition)**: a FAT32 partition UEFI firmware reads directly, containing `.efi` bootloader executables.
* **Exception**: a CPU-triggered interrupt caused by the CPU itself detecting a problem during execution (e.g. a page fault, divide-by-zero).
* **`/etc/fstab`**: the configuration file listing filesystems to automatically mount at boot.
* **Fuzzing / fuzzer**: automated testing that feeds a program large amounts of random/semi-random input to try to trigger crashes or bugs.
* **GDT (Global Descriptor Table)**: a CPU-read table defining memory segments and their privilege levels (rings).
* **`getty`**: the traditional program managing a login prompt on a terminal.
* **GPT (GUID Partition Table)**: the modern partition table format used with UEFI.
* **GRUB2**: the standard Linux bootloader; loads the kernel image and initramfs into memory and hands off control.
* **GUID (Globally Unique Identifier)**: a very-unlikely-to-repeat random ID used to label things such as GPT partitions.
* **IDT (Interrupt Descriptor Table)**: a CPU-read table mapping interrupt/exception numbers to their handler function addresses.
* **`initcall`**: a kernel mechanism for registering subsystem/driver initialization functions to run in a defined order during boot.
* **initramfs / initrd**: a small, temporary, RAM-loaded filesystem used to bridge the gap between kernel startup and mounting the real root filesystem.
* **Init system**: the general term for whatever program runs as PID 1 and starts every other background service (systemd, sysvinit, OpenRC).
* **Interrupt**: a hardware signal that pauses the CPU's current work to immediately run a specific handler function.
* **IRQ (Interrupt Request)**: the specific hardware-level signal a device sends to get the CPU's attention.
* **journal / `journalctl`**: systemd's structured system log and the tool used to read it.
* **Kernel command line**: the list of boot-time options passed from the bootloader to the kernel.
* **Kernel image (`vmlinuz`)**: the compressed, bootable Linux kernel file.
* **Kernel module**: a piece of kernel code that can be loaded into a running kernel on demand, rather than being permanently built in.
* **Kernel panic**: the kernel's equivalent of an unrecoverable crash, halting or rebooting the entire machine.
* **Kernel ring buffer**: a fixed-size, circular, in-memory log the kernel writes its own messages into.
* **LABEL**: a human-assigned name given to a filesystem for stable identification, similar in purpose to a UUID.
* **Long mode**: the CPU's full 64-bit execution mode.
* **LUKS (Linux Unified Key Setup)**: the standard Linux full-disk encryption format.
* **LVM (Logical Volume Manager)**: a layer of abstraction allowing flexible combination and division of physical disks into logical volumes.
* **`mdev` / `udev`**: programs that automatically create/remove `/dev` device files as hardware is detected (mdev: minimal; udev: full).
* **MBR (Master Boot Record)**: the first 512-byte sector of a legacy BIOS-booted disk, holding bootstrap code, a partition table, and a boot signature.
* **MOK (Machine Owner Key)**: a user-enrolled cryptographic key that lets Secure Boot trust a custom kernel or module.
* **NVRAM (Non-Volatile RAM)**: small motherboard memory that retains its contents without power, used by UEFI to store boot entries.
* **Page table**: a data structure letting the CPU translate program memory addresses into real physical RAM locations (full depth: file 04).
* **Partition**: a logically separate section of a physical disk.
* **Partition table**: a table describing how a disk is divided into partitions.
* **PID (Process ID)**: a unique number the kernel assigns to every running process.
* **PID 1**: the first userspace process started by the kernel; ancestor of every other process.
* **POST (Power-On Self Test)**: firmware's routine that checks CPU, RAM, and basic devices before loading a bootloader.
* **Protected mode**: the CPU's 32-bit mode with memory protection.
* **QEMU**: a widely-used tool for running virtual machines, popular in kernel development because it can be paused, snapshotted, and debugged easily.
* **RAID (Redundant Array of Independent Disks)**: combining multiple disks for performance and/or fault tolerance.
* **RCU (Read-Copy-Update)**: a kernel synchronization mechanism allowing lock-free concurrent reads of shared data.
* **`RDRAND` / `RDTSC`**: x86 CPU instructions used as early sources of randomness (a hardware random-number generator, and the CPU's cycle counter, respectively).
* **Real mode**: the CPU's original 16-bit startup mode, limited to 1MB of addressable memory.
* **`root=UUID=...`**: a kernel command-line option identifying which partition holds the real root filesystem.
* **ROM (Read-Only Memory)**: a memory chip whose contents are fixed and survive without power; where BIOS firmware physically lives.
* **Scheduler**: the kernel component deciding which process runs on the CPU at any given moment (full depth: file 03).
* **Sector**: the smallest unit a disk can be read/written in (traditionally 512 bytes).
* **Secure Boot**: a UEFI feature verifying cryptographic signatures on each boot-chain stage before running it.
* **Serial console**: a simple, old-style text communication link, commonly used to capture early kernel boot output when debugging.
* **`start_kernel()`**: the architecture-independent C function representing the true start of the kernel's own portable logic.
* **`switch_root`**: the operation ending the initramfs stage - discards the temporary root, makes the real filesystem `/`, and execs the real init.
* **swap**: disk space used as overflow when physical RAM runs low.
* **systemd**: the modern Linux init system (PID 1 on most distributions).
* **Target (systemd)**: a named group of units representing a system state or boot milestone.
* **Timer (kernel)**: infrastructure for scheduling code to run after a delay or at repeating intervals.
* **UEFI**: the modern firmware standard replacing BIOS.
* **Unit (systemd)**: the basic building block systemd manages - a service, mount, socket, or timer.
* **UUID (Universally Unique Identifier)**: a long, effectively-unique random string used to stably identify a filesystem or partition.
* **`vmlinux`**: the uncompressed Linux kernel binary.
* **`vmlinuz`**: the compressed, bootable Linux kernel image file.
* **Workqueue**: a kernel mechanism for deferring work to run later in a safer execution context.
* **`.efi` executable**: a program file format UEFI firmware can load and run directly, before any OS is present.

***

### 9. Full chapter mindmap

```mermaid
mindmap
  root((02: BOOT PROCESS))
    Stage 1: Firmware
      BIOS legacy path
        POST
        ROM
        MBR
          bootstrap code 446B
          partition table 64B
          boot signature 0x55AA
        Sector 512 bytes
        Stage 1 to Stage 1.5 to Stage 2
      UEFI modern path
        NVRAM boot entries
        GPT partition table
        ESP FAT32 partition
        .efi executables
        Secure Boot
          cryptographic signature
          chain of trust
          shim
          MOK
    Stage 2: Bootloader GRUB2
      vmlinuz plus initrd loaded
      grub.cfg config file
      kernel command line
        root=UUID
        ro quiet splash
        nokaslr nopti
      CPU mode transitions
        Real mode 16-bit
        Protected mode 32-bit
        Long mode 64-bit
    Stage 3: Kernel startup
      Decompression stub
      vmlinux uncompressed
      head_64.S setup.c
        page tables
        GDT
        IDT
      start_kernel
        scheduler init
        buddy allocator
        SLUB init
        IRQ handling
        RCU timers workqueues
        initcalls
      kernel_init
        mount initramfs temporarily
        exec slash init
      KASLR
        entropy
        RDRAND RDTSC
    Stage 4: initramfs
      cpio archive in RAM
      busybox minimal userland
      loads storage drivers
        LVM
        RAID
        LUKS
      udev mdev populate slash dev
      finds real root by UUID LABEL
      switch_root
        deletes old initramfs
        new fs becomes root
        exec real init
    Stage 5: systemd PID 1
      sysinit.target
        mount fstab filesystems
        swap setup
        udev settle
      basic.target
        sockets timers paths
      default.target
        multi-user or graphical
        network target
        sshd service
        app services
        getty tty1 to login prompt
      units and targets
      dependency graph
      journalctl dmesg
    Why it matters for exploitation
      KASLR seed timing on VMs
      custom initramfs for fuzzing
      syzkaller fuzzing
      debug kernel flags
        nokaslr
        nopti
        earlyprintk serial
        panic=1
      proc cmdline
      GDT IDT relevant to interrupts
```

Next: **03-process-and-scheduling.md** - what happens the moment `systemd` (or any process) calls `fork()`/`execve()`, and how the scheduler decides who runs.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/linux-internals/02.-boot-process-x86-x86_64-bios-and-uefi.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
