Skip to the text
KDOS
Menu
kdos.dev KDOS from Scratch KDOS 0.2 · 4dd4a10 · 2026-11-30 Contents Index

380. The initramfs init

This chapter is for anyone who needs to know what happens between the boot menu and the login screen: to debug a machine that drops to the rescue shell, or to change how KDOS finds its root.

init is the first program the kernel runs, as process 1, out of the initramfs the previous chapter builds. It is a bash script that 090_initramfs.sh writes from a here-document. This chapter walks through it in the order it runs:

  1. the early mounts and the splash;
  2. the rescue shell every failure ends in;
  3. the device manager, RAID and the filesystem modules;
  4. the kernel command line;
  5. the A/B slot, LVM and the unlock;
  6. one of the two ways to a root: an installed disk, or the live medium.

For each stage it says what the script does when the stage fails.

Why the stages are in this order, and what each protects against, is in Boot and init, from The initramfs to Tools that must be util-linux’s. This chapter does not repeat that; it shows the code those sections describe.

Reading the excerpts

The excerpts are quoted from the step script, so every $ that belongs to init appears as \$ and every backquote as \`; The init script explains why. Read \$ROOT_UUID as $ROOT_UUID. After a build, build/initramfs/init holds the script as the kernel runs it.

testing/selftest.sh extracts the here-document the same way, undoing the escapes, and checks it with bash -n. It then runs six of its functions against stub programs: esp_keymap, unlock_root, activate_lvm, find_persist (with the uptime_cs and usb_scan it calls), persist_dev and rescue. The variables PASS_TTY, CRYPT_MAPPER_DIR, LVM_BIN and USB_DEVICES below exist so that it can; persist_dev and rescue have none, and the test points its copies of them at a fake /sys and fake terminals.

The stages at a glance

Each stage is announced on the splash with kdos-splash step and closed with ok or fail. The total the splash’s progress bar counts to is added up as the script learns which stages it will run. Each section below is named after the stage it covers, the label in the table’s first column.

Stage Runs when When it fails
DEVICE MANAGER always nothing is checked; the stage closes as passed
RAID /bin/mdadm is carried ignored: assembling nothing is the ordinary case
FILESYSTEM MODULES always a line per module that would not load; the boot goes on
BOOT SLOT the command line has bootstate=UUID= and /bin/kdos-bootctl is carried the root= of the command line is kept; the stage closes as passed
VOLUME GROUPS root=UUID= or cryptdevice= is given, lvm is carried, and blkid reports physical volumes not yet activated the stage is marked failed and the boot goes on
UNLOCKING cryptdevice= is set rescue shell: Failed to unlock …
ROOT DEVICE root=UUID= is set rescue shell: Disk boot failed: no root at UUID=… with /sbin/init on it
MOUNTING ROOT the root was found the same rescue shell, when /sbin/init is not on what was mounted
BOOT MEDIA there is no root=UUID= rescue shell: Failed to find the KDOS live medium.
SYSTEM IMAGE the medium was found rescue shell: Failed to set up a loop device for system.sfs or Failed to mount system.sfs
OVERLAY ROOT system.sfs is mounted a broken persistence store falls back to a session in memory; rescue shell only if /newroot is not a directory
SWITCHING ROOT the last stage on both paths live medium: rescue shell, Error: /sbin/init not found in new root!

The early mounts

#!/bin/bash
export PATH=/bin

# Redirect stdout/stderr to console
exec >/dev/console 2>&1

echo "KDOS Init Starting..."

mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev
mkdir -p /dev/pts
# This mount is the root's too: it is moved there, and nothing remounts it.
# gid=5 (tty) and mode 620 are what a new terminal is created with, so write
# and wall can reach it; ptmxmode=666 lets every user open /dev/pts/ptmx.
# The kernel's defaults are the opener's group, 600 and 000.
mount -t devpts -o gid=5,mode=620,ptmxmode=666 devpts /dev/pts
mkdir -p /dev/shm
mount -t tmpfs -o nosuid,nodev tmpfs /dev/shm

script/phases/70_image/090_initramfs.sh, lines 532–550

PATH is /bin alone, the directory the step filled. Everything the script prints goes to /dev/console, which is the last console= on the kernel command line: the serial port on the live medium’s entries, the first virtual terminal on an installed machine’s (see Command-line parameters KDOS reads). Then the kernel’s filesystems are mounted: /proc, /sys, /dev as devtmpfs, /dev/pts and a /dev/shm with nosuid,nodev. None of the mounts is checked. devpts gets gid=5,mode=620,ptmxmode=666: a new terminal belongs to the tty group with mode 620, so write and wall reach it, and /dev/pts/ptmx is open to every user. The mount moves into the real root with /dev and nothing mounts it again, so these are the booted system’s options; the kernel’s own are the opener’s group, 600 and 000.

The splash

# fbcon defers taking the framebuffer until a glyph is printed on a virtual
# terminal. /dev/console is the last console=: ttyS0 on the quiet live entries,
# so none of these messages reach the screen; tty0 on the live verbose entry and
# on an installed machine, where the echo above has ended the deferral. A
# drawing splash puts the VT in graphics mode, so on a quiet boot the messages
# go to the VT's buffer and not over the picture. \`kdos-splash run\` draws
# only on a command line with \`quiet\`: without it it exits at once, every
# call below is a no-op, and the messages are the whole of what the screen
# shows.
if [ -x /bin/kdos-splash ]; then
    /bin/kdos-splash run </dev/null >/dev/null 2>&1 &
fi
sp_step() { [ -x /bin/kdos-splash ] && /bin/kdos-splash step "\$1" 2>/dev/null; return 0; }
sp_ok()   { [ -x /bin/kdos-splash ] && /bin/kdos-splash ok 2>/dev/null; return 0; }
sp_fail() { [ -x /bin/kdos-splash ] && /bin/kdos-splash fail 2>/dev/null; return 0; }
sp_total() { [ -x /bin/kdos-splash ] && /bin/kdos-splash total "\$1" 2>/dev/null; return 0; }
# THE SPLASH NAMES THE ROOT IT BOOTS, not the image that built this
# initramfs: an installed machine keeps one initramfs across every update that
# is not a slot image, so its copy of /etc/kdos-release can be a release
# behind. The client reads /newroot's record (os-release when it has none) and
# the running splash takes it. Sent before /dev moves, like everything else.
sp_root_release() {
    [ -x /bin/kdos-splash ] && KDOS_SPLASH_ROOT=/newroot /bin/kdos-splash release 2>/dev/null
    return 0
}
# Called before /dev moves into the new root: the splash's FIFO is
# /dev/.kdos-splash, and once /dev has moved no command sent from here reaches
# it. \`emergency\` makes init run sulogin before rcS, the one thing that stops
# the splash on a normal boot, so a splash still drawing then covers the prompt
# on the screen and leaves the keyboard's console showing a frozen bar; the
# prompt would be reachable only over the serial line. \`quit\` leaves the
# console in text mode with its cursor shown.
sp_release() {
    [ "\$INIT_ARG" = emergency ] && [ -x /bin/kdos-splash ] && /bin/kdos-splash quit 2>/dev/null
    return 0
}

script/phases/70_image/090_initramfs.sh, lines 552–587

The splash is started in the background, with its own input and output thrown away, and the helpers send it commands. Each helper does nothing when the splash is not carried, and returns 0 whatever happens, so a splash that fails can never stop the boot. sp_root_release runs KDOS_SPLASH_ROOT=/newroot kdos-splash release, which reads the mounted root’s /etc/kdos-release (its /etc/os-release when it has none) and has the splash name that release in place of the initramfs’s copy, which an installed machine keeps across every update that is not a slot image. It and sp_release are called on both paths before /dev moves into the new root: the commands travel through the FIFO /dev/.kdos-splash, and once /dev has moved no helper can reach it. On an emergency boot sp_release runs kdos-splash quit: init then runs sulogin before rcS, the one thing that stops the splash on a normal boot, so a splash still drawing would hide the prompt and keep the keyboard’s console showing a frozen bar. On every other boot it does nothing and the splash survives the switch. The commands are listed in The splash.

On an installed machine /dev/console is the screen, so the script’s first line, KDOS Init Starting..., has already ended the console’s deferred takeover of the framebuffer before the splash starts. A drawing splash puts the terminal into graphics mode, so on a quiet boot the later lines go into the terminal’s buffer rather than over the picture. The live entries print on the serial line and leave the splash alone.

The rescue shell

# EVERY FAILURE ENDS HERE, AND SAYS WHY WHERE SOMEBODY IS LOOKING. /dev/console
# is the last console= on the command line, which on the quiet live entries is
# the serial port: a shell there alone leaves a laptop showing the splash's fail
# state and nothing else. The reason goes to the splash as a detail line, held
# on the screen for RESCUE_HOLD seconds before the splash fades out (a quit
# straight after the detail shows it only during the fade, too dark to read),
# and then to tty1, where fbcon takes the framebuffer over at the first write
# and the keyboard is. An optional second argument is a hint printed under the
# reason on the screens, never on the splash, which has one detail line. Both
# screens say that Ctrl+Alt+Del restarts: the kernel reboots on it at once
# until init disables it, and nothing here does. That restart is immediate and
# syncs nothing, and a failure after the root is mounted (a missing /sbin/init,
# a persistent live upper) leaves a disk mounted read-write, so the boot's own
# writes are synced before the shell opens and the screens tell whoever
# changes a disk to run sync first. On tty1 under a serial /dev/console the
# screen names the menu's verbose entry, the one way to see the boot log
# there, and under the reason and hint tty1 lists RESCUE_TRIED, the devices
# a failed medium scan tried and why each was passed over: the scan's own
# line about them went to the serial console only. tty1 gets a shell loop of
# its own, in a process setsid -f detaches from this one: each shell is a
# setsid -c session with tty1 as its controlling terminal, and tty1 is
# released when that session ends, so the next shell can claim it and an exit
# there opens a fresh one. It is never a background job of this shell, which
# runs without job control: bash starts an asynchronous command with SIGINT
# and SIGQUIT ignored, every shell the loop opened would inherit that, and
# Ctrl+C would reach nothing it runs. This process runs a shell on /dev/console
# in a loop, so the serial line keeps its shell and the log it has been reading,
# and an exit there, or an input that ends the shell, opens a fresh one. When
# /dev/console is itself a virtual terminal there is one screen and one shell,
# and the reason is printed on it once: an echo before the branch and the printf
# in it would both land on that one screen. That shell is opened on the terminal
# itself, never on /dev/console, which cannot be a controlling terminal: a shell
# there has no job control, says so in two lines of noise, and lets Ctrl+C reach
# nothing it runs. setsid -c makes the terminal the shell's controlling terminal
# and -w waits for it, in a loop, so an exit opens a fresh shell. Every shell,
# whatever its exit status, is followed by a second's wait before the next: a
# shell that cannot start, or one that reads end-of-file at once from a hung-up
# line and exits 0, would otherwise spin the loop and flood the console with
# prompts. PID 1 must never return from here, on either branch: a shell that
# exits as PID 1, or a return from this function, panics the kernel with
# "Attempted to kill init".
#
# EVERY FIXED LINE AND EVERY HINT IS 80 COLUMNS OR FEWER. They are printed
# before fbcon's deferred takeover has widened the console, while the VT is 80
# columns, and a longer line wraps a lone word onto a line of its own.
RESCUE_HOLD=4
RESCUE_TRIED=""
RESCUE_RESTART="Ctrl+Alt+Del restarts at once; run sync first if you changed a disk."
RESCUE_VERBOSE="The boot menu's '(verbose)' entry shows the boot log on this screen."
rescue() {
    local con
    if [ -x /bin/kdos-splash ]; then
        /bin/kdos-splash detail "\$1" 2>/dev/null
        [ -n "\$SPLASH_QUIET" ] && sleep "\$RESCUE_HOLD"
        /bin/kdos-splash quit 2>/dev/null
    fi
    sync
    con=\$(cat /sys/class/tty/console/active 2>/dev/null)
    con=\${con##* }
    case "\$con" in
    tty[0-9]*)
        printf '\n%s\n' "\$1"
        [ -n "\$2" ] && printf '%s\n' "\$2"
        echo "KDOS cannot boot. This is a rescue shell."
        echo "\$RESCUE_RESTART"
        while :; do
            setsid -c -w /bin/sh -i < "/dev/\$con" > "/dev/\$con" 2>&1; sleep 1
        done
        ;;
    esac
    echo "\$1"
    [ -n "\$2" ] && echo "\$2"
    {
        printf '\n%s\n' "\$1"
        [ -n "\$2" ] && printf '%s\n' "\$2"
        [ -n "\$RESCUE_TRIED" ] && printf 'Devices tried:\n%s\n' "\$RESCUE_TRIED"
        echo "KDOS cannot boot. This is a rescue shell."
        echo "\$RESCUE_VERBOSE"
        echo "\$RESCUE_RESTART"
    } > /dev/tty1 2>/dev/null
    setsid -f /bin/sh -c 'while :; do setsid -c -w /bin/sh -i < /dev/tty1 > /dev/tty1 2>&1; sleep 1; done' < /dev/null > /dev/null 2>&1
    echo "A rescue shell is also open on tty1."
    while :; do
        /bin/sh; sleep 1
    done
}

script/phases/70_image/090_initramfs.sh, lines 589–674

rescue MESSAGE [HINT] is the end of every path that cannot boot. It first does three things:

  1. It shows the message on the splash as a detail line and, on a quiet boot, holds it there for RESCUE_HOLD, four seconds, so it can be read before the fade. Then it quits the splash, which hands the screen back.
  2. It runs sync. A failure after the root was mounted leaves a disk mounted read-write, and Ctrl+Alt+Del, which the kernel answers with an immediate restart until init takes it over, syncs nothing.
  3. It reads the active consoles from /sys/class/tty/console/active; the last name there is the one /dev/console is.

What follows depends on that console.

When /dev/console is a virtual terminal (tty0, tty1 and so on), there is one screen, and the message is printed on it once, followed by:

The script then opens an interactive shell on that terminal with setsid -c -w, which makes the terminal the shell’s controlling terminal (/dev/console can never be one, and a shell there has no job control), and waits for it. It does so in a loop, so an exit opens a fresh shell. Every shell, whatever its exit status, is followed by a second’s wait before the next, so a shell that cannot start, or one that reads end-of-file at once from a hung-up line, does not spin the loop.

When /dev/console is a serial line, the message and the hint are printed there. They also go to tty1, with:

setsid -f detaches a process that runs setsid -c -w /bin/sh -i on tty1 in a loop, so each shell there is a session with tty1 as its controlling terminal, and an exit opens a fresh one. It is not a background job of the init’s shell, which has no job control: bash would start such a job with SIGINT ignored, and Ctrl+C on tty1 would reach nothing. The script itself runs a shell on /dev/console in the same kind of loop, so an exit on the serial line, or an input that ends the shell, opens a fresh one.

Every fixed line and every hint is 80 columns or fewer: they are printed before fbcon’s deferred takeover has widened the console, and a longer line wraps.

Process 1 never returns from rescue on either branch, because its exit panics the kernel with Attempted to kill init. There is no reboot program in the initramfs, so Ctrl+Alt+Del is the restart; see The rescue shell for how to restart from it, and The initramfs for the programs it has.

Device manager

# The two stages every boot path runs; each path adds its own share below.
sp_total 2

# Populate /dev
echo "Populating /dev..."
sp_step "DEVICE MANAGER"
udevd --daemon
echo "Triggering udev events..."
udevadm trigger --type=subsystems --action=add
udevadm trigger --type=devices --action=add
udevadm settle
sp_ok

# THIS udevd ENDS BEFORE switch_root, ON EVERY PATH THAT TAKES IT. Left
# running it survives the switch with the initramfs's /bin/udevd and libraries
# deleted under it, so the root's 01_udev starts a second one beside it and
# \`kdos restarts\` reports it on every boot as running replaced code from
# packages nobody updated. It is called before /dev moves: settle drains the
# events still queued, and --exit waits for udevd to answer on its control
# socket in /run.
udev_release() {
    udevadm settle 2>/dev/null || true
    udevadm control --exit 2>/dev/null || true
}

script/phases/70_image/090_initramfs.sh, lines 676–699

sp_total 2 counts this stage and FILESYSTEM MODULES, the two every boot runs. udevd --daemon starts the device manager; the two udevadm trigger calls ask the kernel to replay the add event of every subsystem and then of every device present since boot, which nobody was listening for; and udevadm settle waits until udev has handled them all. After this, /dev holds a node for every disk the kernel has found, and the modules udev loads for the hardware are in.

udev_release is the end of this udevd, called on every path just before /dev moves into the new root: udevadm settle drains what is still queued and udevadm control --exit stops the daemon. One left running survives switch_root with its program and libraries deleted under it, the root’s /etc/init.d/01_udev.sh starts a second beside it, and kdos restarts names it on every boot as a process running replaced code.

RAID

#
# ASSEMBLE ANY SOFTWARE RAID BEFORE ANYTHING LOOKS FOR A ROOT. An array's
# members are bare partitions carrying a superblock until mdadm brings them
# together; the filesystem UUID the boot is hunting for lives INSIDE the
# array and does not exist on the disk, so a blkid run before this finds the
# members and not the root.
#
# \`--scan\` AND NOT A CONFIG. Nothing here knows which arrays this machine
# has; each member's own superblock does, which is also what makes a machine
# whose disks were reordered still boot.
#
# SILENT WHEN THERE IS NO ARRAY: mdadm exits non-zero when it assembles
# nothing, which is the ordinary case on the overwhelming majority of
# machines and must not read as a failure.
if [ -x /bin/mdadm ]; then
    # The total is additive and only this branch knows it is going to run —
    # the rule the unlock and the slot blocks already keep.
    sp_total 1
    sp_step "RAID"
    mdadm --assemble --scan >/dev/null 2>&1 || true
    udevadm settle
    sp_ok
fi

script/phases/70_image/090_initramfs.sh, lines 701–723

mdadm --assemble --scan reads the RAID superblock on each device and assembles every array it finds, with no configuration file. Its exit status is thrown away, because a machine with no array makes it fail. udevadm settle then waits for the arrays’ own devices. This runs before anything looks for a root, so a root on an array is visible to every lookup that follows.

Filesystem modules

echo "Loading essential filesystem modules..."
sp_step "FILESYSTEM MODULES"
modprobe -v loop || echo "Modprobe loop failed"
modprobe -v isofs || echo "Modprobe isofs failed"
modprobe -v squashfs || echo "Modprobe squashfs failed"
modprobe -v overlay || echo "Modprobe overlay failed"
sp_ok

# Check for loop device (create if missing)
if [ ! -e /dev/loop0 ]; then
    mknod /dev/loop0 b 7 0
fi

echo "Welcome to KDOS"

script/phases/70_image/090_initramfs.sh, lines 725–738

loop, isofs, squashfs and overlay are what the live path needs. A module that will not load prints a line and the boot goes on; one that is built into the kernel loads as a no-op. When there is no /dev/loop0, it is made by hand, block device major 7, minor 0.

The kernel command line

# Parse Boot Parameters. INIT_ARG starts empty: the kernel hands init every
# unrecognised name=value on its command line as an environment variable.
INIT_ARG=""
SPLASH_QUIET=""
for i in \$(cat /proc/cmdline); do
    case "\$i" in
        root=UUID=*)
            ROOT_UUID="\${i#root=UUID=}"
            ;;
        cryptdevice=*)
            CRYPTDEV="\${i#cryptdevice=}"
            ;;
        bootstate=UUID=*)
            BOOTSTATE_UUID="\${i#bootstate=UUID=}"
            ;;
        kdos_slot=*)
            BOOT_SLOT="\${i#kdos_slot=}"
            ;;
        # Handed on to init: \`single\` runs rcS and then sulogin, with no
        # consoles and no desktop; \`emergency\` runs sulogin before rcS.
        single|emergency)
            INIT_ARG="\$i"
            ;;
        # The splash draws only on a boot with \`quiet\`; without it nothing
        # is on the screen to carry the passphrase prompt.
        quiet)
            SPLASH_QUIET=1
            ;;
    esac
done

script/phases/70_image/090_initramfs.sh, lines 740–769

The script reads /proc/cmdline word by word and keeps five things: root=UUID=, cryptdevice=, bootstate=UUID=, kdos_slot=, and single or emergency, which are handed to the real init at the end. The live medium’s entries pass root=/dev/ram0, which matches none of the patterns, so ROOT_UUID stays empty there, and an empty ROOT_UUID is what sends the script down the live path. INIT_ARG is cleared first because the kernel passes every name=value it does not recognise to init as an environment variable, so a stray INIT_ARG= on the command line would otherwise arrive set.

The unlock function

#
# An encrypted root, unlocked before anything looks for the filesystem inside
# it. The syntax is Arch's, because it is the one already in people's heads:
#
#     cryptdevice=UUID=<luks-uuid>:<name>   root=UUID=<filesystem-uuid>
#
# The two UUIDs are DIFFERENT things and the distinction is the whole trap: the
# first is the LUKS container's, the second belongs to the filesystem that only
# exists once the container is open. kinstall writes both.
#
# On a boot with \`quiet\` the prompt goes through the SPLASH, not to
# /dev/console, which is the last console=: tty0 under the splash on an
# installed machine, ttyS0 on the quiet live entries, where a plain \`read -p\`
# prompts a serial port nobody is looking at while the screen shows a splash
# that appears to have frozen. On a boot without \`quiet\` (the verbose and
# single-user entries) no splash draws, and the prompt and its outcome are
# printed on PASS_TTY instead. Never both: tty1 under a drawing splash is in
# graphics mode, so a prompt written there is not seen until the splash has
# quit. The keystrokes are read from /dev/tty1, which is where the keyboard
# actually is.
#
# The prompt says DISK PASSPHRASE and never the mapper name, which is an
# internal device name nobody chose. A cryptdevice= that cannot be used returns
# 1; three wrong passphrases return 2, which the caller tells apart so the
# rescue screen can say a restart gives three more tries.
#
# There is no per-keystroke feedback: the splash owns the framebuffer and bash
# owns the terminal, and a passphrase field that echoed dots would mean moving
# the read into the splash. Stated rather than hidden.
#
# THE PROMPT TYPES WITH THE MACHINE'S CONSOLE MAP, loaded on tty1 once before
# the first read. KEYMAP is the name the A/B block below read off the ESP
# (EFI/kdos/keymap, which the installer and kdos-settingsd write from
# /etc/keymap); with none the kernel's US map stays, which is every machine
# whose ESP holds no keymap file. A layout whose console map has no letter
# for a character cannot type that character here.
#
# Three knobs, each defaulted to the real thing. The keyboard is on tty1
# whatever console= names, the mapper directory is where the kernel puts an
# opened container, and LOADKEYS is kbd's. They are variables so
# \`testing/selftest.sh\` can exercise this function without a LUKS volume, a
# console or root — the same trick \`kdos stutter --fixture\` uses for /proc.
: "\${PASS_TTY:=/dev/tty1}"
: "\${CRYPT_MAPPER_DIR:=/dev/mapper}"
: "\${LOADKEYS:=/bin/loadkeys}"
KEYMAP=""

script/phases/70_image/090_initramfs.sh, lines 771–816

The comment sets out the cryptdevice= syntax and the two different UUIDs it involves. The three : "${VAR:=default}" lines give PASS_TTY, CRYPT_MAPPER_DIR and LOADKEYS their real values (/dev/tty1, /dev/mapper and /bin/loadkeys) unless the environment already set them, which only the self-test does. KEYMAP starts empty.

# esp_keymap <esp>: KEYMAP from <esp>/EFI/kdos/keymap. One line, a kbd map
# NAME and never a path or an option: a file on the ESP is a file anybody
# with the disk can edit, and loadkeys reads a path as readily as a name.
esp_keymap() {
    local k=""
    [ -r "\$1/EFI/kdos/keymap" ] && read -r k < "\$1/EFI/kdos/keymap"
    case "\$k" in
        ''|[.-]*|*[!A-Za-z0-9_.+-]*) return 0 ;;
    esac
    KEYMAP="\$k"
}

script/phases/70_image/090_initramfs.sh, lines 818–828

esp_keymap sets KEYMAP from the first line of EFI/kdos/keymap under the ESP it is given. It takes the line only when it is a map name: not empty, not starting with . or -, and made only of letters, digits and _ . + -. Anything else, or a missing file, leaves KEYMAP empty. The file is on a FAT partition anybody holding the disk can edit, and loadkeys would read a path or an option as readily as a name. The installer and kdos-settingsd write the file; the Boot slot block below calls this function.

unlock_root() {
    local spec="\$1" luks_uuid name dev tries tty_say=1
    [ -n "\$SPLASH_QUIET" ] && [ -x /bin/kdos-splash ] && tty_say=

    case "\$spec" in
        UUID=*:*)  luks_uuid="\${spec#UUID=}"; luks_uuid="\${luks_uuid%%:*}"
                   name="\${spec##*:}" ;;
        /dev/*:*)  dev="\${spec%%:*}"; name="\${spec##*:}" ;;
        *)         echo "cryptdevice: cannot parse '\$spec'"; return 1 ;;
    esac
    [ -n "\$name" ] || name=kdosroot

    if [ -z "\$dev" ]; then
        for i in \$(seq 1 10); do
            dev=\$(blkid -U "\$luks_uuid")
            [ -n "\$dev" ] && break
            sleep 1
        done
    fi
    if [ -z "\$dev" ] || [ ! -e "\$dev" ]; then
        echo "cryptdevice: no device for \$spec"
        return 1
    fi
    if [ ! -x /bin/cryptsetup ]; then
        echo "cryptdevice: this initramfs has no cryptsetup"
        return 1
    fi

    modprobe -q dm-crypt 2>/dev/null

    # -u: the passphrase was set in a UTF-8 session, so ü is its UTF-8 bytes.
    # A map that fails to load leaves the US map, and the prompt still runs.
    [ -n "\$KEYMAP" ] && "\$LOADKEYS" -q -u -C "\$PASS_TTY" "\$KEYMAP" \
        </dev/null >/dev/null 2>&1

    tries=0
    while [ \$tries -lt 3 ]; do
        tries=\$((tries + 1))
        [ -x /bin/kdos-splash ] && /bin/kdos-splash msg \
            "DISK PASSPHRASE (attempt \$tries of 3)" 2>/dev/null
        [ -n "\$tty_say" ] && printf 'Disk passphrase (attempt %d of 3): ' \
            "\$tries" >>"\$PASS_TTY" 2>/dev/null
        # -s: never echo the passphrase. Read from tty1 because the keyboard
        # is there, whatever /dev/console is.
        PASS=""
        read -r -s PASS < "\$PASS_TTY" || true
        # Fed on STDIN, never as an argument: /proc/<pid>/cmdline is readable
        # by every process on the machine for as long as the process lives.
        printf '%s' "\$PASS" | cryptsetup open --key-file=- "\$dev" "\$name"
        rc=\$?
        PASS=""
        if [ \$rc -eq 0 ] && [ -e "\$CRYPT_MAPPER_DIR/\$name" ]; then
            [ -x /bin/kdos-splash ] && /bin/kdos-splash msg "UNLOCKED" 2>/dev/null
            [ -n "\$tty_say" ] && printf '\nUnlocked.\n' >>"\$PASS_TTY" 2>/dev/null
            return 0
        fi
        [ -x /bin/kdos-splash ] && /bin/kdos-splash msg \
            "WRONG PASSPHRASE" 2>/dev/null
        [ -n "\$tty_say" ] && printf '\nWrong passphrase.\n' >>"\$PASS_TTY" 2>/dev/null
    done
    return 2
}

script/phases/70_image/090_initramfs.sh, lines 830–891

unlock_root accepts UUID=<luks-uuid>:<name> or /dev/<node>:<name>, and anything else is an error. An empty name becomes kdosroot. Given a UUID, it asks blkid -U once a second, for up to ten seconds, for the device holding that container. It fails when no device turns up, or when the initramfs carries no cryptsetup.

Before the first try, when KEYMAP is set, it runs $LOADKEYS -q -u -C $PASS_TTY $KEYMAP once, so the passphrase is typed with the machine’s console map. -u loads the map in Unicode mode, because the passphrase was set in a UTF-8 session. A map that fails to load leaves the kernel’s US map, and the prompt runs anyway. With no KEYMAP the US map is the only one.

Then it allows three tries. Each one shows DISK PASSPHRASE (attempt N of 3) on the splash, or Disk passphrase (attempt N of 3): on PASS_TTY when no splash draws, never the mapper name, reads a line from tty1 with read -r -s, which does not echo, and feeds the passphrase to cryptsetup open --key-file=- on its standard input. An attempt succeeds only when cryptsetup exits 0 and the mapped device exists under /dev/mapper. The variable is cleared after every attempt. A cryptdevice= that cannot be used returns 1, and the third wrong passphrase returns 2, so that its caller can tell the two apart in the rescue shell’s reason. The design of the prompt is in Unlocking an encrypted root.

The function is only defined here. It runs in the UNLOCKING stage, after the slot selection below, which may change the container it is given.

Boot slot

#
# A/B slots: the boot state lives on the ESP because it must be readable and
# WRITABLE before any root filesystem is mounted — including the one that turns
# out not to work. \`select\` prints the UUID to boot and spends an attempt in the
# same breath, so a kernel that hangs after this point has still been counted.
#
# Failing to read it is not fatal: \`root=\` on the command line is what a machine
# without A/B uses anyway, and it stays the fallback.
#
# AND THE SLOT'S OWN CONTAINER COMES WITH IT. \`select\` yields a FILESYSTEM
# identifier; on an encrypted machine that filesystem is inside a LUKS
# container, and the command line can name exactly one \`cryptdevice=\`. Two
# slots inside two containers cannot both be named there, so each slot records
# its own and \`crypt\` is asked for the one that belongs to the filesystem
# \`select\` just chose. A slot that names none leaves \`CRYPTDEV\` exactly as the
# command line set it, which is every machine installed without encryption and
# every machine whose two slots share one container.
#
# THE ORDER IS LOAD-BEARING: this block runs BEFORE the unlock below, because
# the unlock is what has to happen to the container this block names. Moving
# the unlock above it would unlock whichever container the command line
# mentions and then look for the other slot's filesystem inside it.
#
if [ -n "\$BOOTSTATE_UUID" ] && [ -x /bin/kdos-bootctl ]; then
    sp_total 1
    sp_step "BOOT SLOT"
    modprobe -q vfat 2>/dev/null
    mkdir -p /esp
    ESP_DEV=""
    for i in \$(seq 1 10); do
        ESP_DEV=\$(blkid -U "\$BOOTSTATE_UUID")
        [ -n "\$ESP_DEV" ] && break
        sleep 1
    done
    if [ -n "\$ESP_DEV" ] && mount -t vfat "\$ESP_DEV" /esp 2>/dev/null; then
        # \`kdos_slot=\` is the slot whose ESP directory this kernel came
        # from, and it is handed to \`select\`: that slot's modules are the
        # only ones this kernel can load, so a hand-picked entry boots its
        # own slot and nothing else. Absent on a menu whose entries share
        # one kernel, where \`select\` decides alone. \`select\` also rewrites
        # the menu on the ESP when its decision moves the next boot.
        # KDOS_CMDLINE names /proc/cmdline outright: a state file away from
        # /boot/efi reads no command line without it, and \`select\` reads
        # \`kdos_menu=trial\` there to tell a confirmed entry picked from a
        # trial menu from a firmware fallback.
        SEL=\$(KDOS_BOOTSTATE=/esp/EFI/kdos/bootstate \
               KDOS_CMDLINE=/proc/cmdline \
               /bin/kdos-bootctl select \${BOOT_SLOT:+"\$BOOT_SLOT"} \
               2>/dev/console)
        # BOTH READS HAPPEN WHILE IT IS MOUNTED. \`crypt\` reads the same file
        # \`select\` just wrote, so asking after the umount below reads nothing
        # and silently drops the container — an encrypted second slot would
        # then be unlocked with the first slot's container and fail to mount,
        # which reads as a corrupt filesystem rather than as a missing lookup.
        # It spends no attempt: \`select\` is the only verb that counts.
        SLOT_CRYPT=""
        [ -n "\$SEL" ] && SLOT_CRYPT=\$(KDOS_BOOTSTATE=/esp/EFI/kdos/bootstate \
               /bin/kdos-bootctl crypt "\$SEL" 2>/dev/null)
        # The console map the passphrase prompt loads is read here too, for
        # the same reason: the ESP is not mounted again before the unlock.
        esp_keymap /esp
        # Unmounted immediately: the root filesystem mounts it again at
        # /boot/efi, and two mounts of one FAT filesystem is how a state file
        # gets written twice and read once.
        umount /esp 2>/dev/null
        if [ -n "\$SEL" ]; then
            echo "Boot slot selected: \$SEL"
            ROOT_UUID="\$SEL"
            if [ -n "\$SLOT_CRYPT" ]; then
                # The mapper name is this initramfs's own and not the state
                # file's: only one container is ever open at a time here, so
                # there is nothing for a per-slot name to disambiguate, and a
                # name read out of a file on the ESP is a name somebody can
                # edit into a path.
                CRYPTDEV="UUID=\$SLOT_CRYPT:kdosroot"
                echo "Slot container: \$SLOT_CRYPT"
            fi
            sp_ok
        else
            echo "No usable boot state; keeping root=\$ROOT_UUID"
            sp_ok
        fi
    else
        echo "Cannot read the boot state; keeping root=\$ROOT_UUID"
        sp_ok
    fi
fi

script/phases/70_image/090_initramfs.sh, lines 893–979

On a machine with A/B slots, the command line names the ESP that holds the state file. The script loads vfat, waits up to ten seconds for that ESP, and mounts it at /esp. Two questions are put to kdos-bootctl, both against /esp/EFI/kdos/bootstate:

  1. select, given the entry’s kdos_slot= when it has one, prints the filesystem UUID to boot and counts the attempt in the state file. When its decision moves the next boot, it also rewrites the boot menu on the ESP. Its messages go to the console. It is told to read /proc/cmdline (KDOS_CMDLINE), because a state file away from /boot/efi reads no command line otherwise, and the kdos_menu=trial there is how it tells a confirmed entry picked from a trial menu from a firmware fallback.
  2. crypt <uuid> prints the LUKS container that filesystem is inside, if it is in one.

While the ESP is still mounted, esp_keymap /esp reads EFI/kdos/keymap into KEYMAP for the unlock: the ESP is not mounted again before the passphrase prompt. Then the ESP is unmounted. A UUID from select replaces ROOT_UUID, and a container from crypt replaces CRYPTDEV, always under the mapper name kdosroot. When there is no ESP, no state file or no answer, the script prints which, keeps the command line’s root= and closes the stage as passed: a machine whose slot state cannot be read still boots the root its menu entry names. The verbs and the state file are in A/B slot selection and A slot knows its own container.

Volume groups

#
# VOLUME GROUPS ARE ACTIVATED BEFORE ANYTHING LOOKS FOR THE ROOT, for the
# reason the RAID block gives: a filesystem on a logical volume has no device
# node until its group is active, and \`blkid -U\` finds nothing.
#
# ON EACH SIDE OF THE UNLOCK, because LVM and LUKS stack both ways: a group
# inside a container exists only after the unlock, and a container on a
# logical volume has to be active before it. Each call runs lvm only when
# blkid reports a set of physical volumes it has not already activated, so a
# disk boot with no LVM costs one blkid per call and never starts lvm, and a
# live boot -- no root=, no cryptdevice= -- makes no call at all; 03_lvm.sh
# activates the groups of a live session.
#
# --sysinit is no dmeventd monitoring, no background polling and no locking
# failure: the three things an initramfs cannot provide. The lvm.conf carried
# here names thin_check and cache_check and nothing else, so every other
# setting is the compiled default and every group is activated. The groups
# stay active across switch_root.
#
# THE THIN, CACHE AND SNAPSHOT TARGETS ARE LOADED FIRST, on the first call
# that finds a physical volume: a group holding one of those volumes activates
# only with its target present, and lvm's own modprobe is a path its configure
# chose. A kernel with them built in makes this a no-op.
: "\${LVM_BIN:=/usr/sbin/lvm}"
LVM_PVS=""
activate_lvm() {
    local pvs
    [ -x "\$LVM_BIN" ] || return 0
    pvs=\$(blkid -t TYPE=LVM2_member -o device 2>/dev/null)
    [ -n "\$pvs" ] && [ "\$pvs" != "\$LVM_PVS" ] || return 0
    if [ -z "\$LVM_PVS" ]; then
        modprobe -q -a dm-snapshot dm-thin-pool dm-cache dm-cache-smq \
            dm-writecache 2>/dev/null || true
    fi
    LVM_PVS="\$pvs"
    sp_total 1
    sp_step "VOLUME GROUPS"
    if "\$LVM_BIN" vgchange -aay --sysinit; then
        udevadm settle 2>/dev/null || true
        sp_ok
    else
        # Not a stop: a group that is partly missing need not hold the root,
        # and the root lookup below says so when it does.
        sp_fail
    fi
}
[ -n "\$ROOT_UUID\$CRYPTDEV" ] && activate_lvm

script/phases/70_image/090_initramfs.sh, lines 981–1027

activate_lvm is called from three places: here, after the unlock, and on each pass of the wait for the root. Each call asks blkid -t TYPE=LVM2_member -o device for the physical volumes and returns at once when there are none, or when the list is the one the last call activated. The first call that finds any loads the snapshot, thin, cache and write-cache targets with modprobe -q -a. Each call that goes on adds a VOLUME GROUPS stage and runs lvm vgchange -aay --sysinit, which activates every logical volume set to activate automatically; --sysinit leaves out the monitoring daemon and background polling, and does not fail on locking, three things an initramfs cannot provide. A failure marks the stage failed and nothing more; if the root was on that group, the root lookup reports it missing.

The line after the function makes the first call only when root=UUID= or cryptdevice= is set, so the live medium never runs lvm here. See Activating volume groups.

Unlocking

if [ -n "\$CRYPTDEV" ]; then
    # One extra stage on the progress bar, added here rather than up front:
    # the total is additive, and only this branch knows there is an unlock.
    sp_total 1
    sp_step "UNLOCKING"
    unlock_root "\$CRYPTDEV"
    UNLOCK_RC=\$?
    if [ \$UNLOCK_RC -eq 0 ]; then
        sp_ok
        # The filesystem inside the container has only just appeared, so the
        # udev pass that ran before the unlock never saw it.
        udevadm settle 2>/dev/null || true
        activate_lvm
    elif [ \$UNLOCK_RC -eq 2 ]; then
        sp_fail
        rescue "Wrong passphrase three times. Ctrl+Alt+Del restarts and asks again."
    else
        sp_fail
        rescue "Failed to unlock \$CRYPTDEV"
    fi
fi

script/phases/70_image/090_initramfs.sh, lines 1029–1049

When CRYPTDEV is set, by the command line or by the slot, unlock_root runs in a stage of its own. Once it succeeds, udev is given time to settle, because the filesystem inside the container has only just appeared, and activate_lvm runs again for a volume group inside the container. A failed unlock is the first stage that opens the rescue shell: three wrong passphrases with the reason Wrong passphrase three times. Ctrl+Alt+Del restarts and asks again., and a container that cannot be opened at all with Failed to unlock <cryptdevice>.

The installed root

Root device

if [ -n "\$ROOT_UUID" ]; then
    # Disk Boot Mode
    echo "Waiting for root device \$ROOT_UUID..."
    sp_total 3
    sp_step "ROOT DEVICE"

    # Wait for device to appear (timeout 10s). A disk that enumerates late
    # may carry the root's physical volume, so each pass activates any group
    # that has appeared since; with no new PV that is one blkid and no lvm.
    for i in \$(seq 1 10); do
        activate_lvm
        ROOT_DEV=\$(blkid -U "\$ROOT_UUID")
        if [ -n "\$ROOT_DEV" ]; then
            break
        fi
        sleep 1
    done

    if [ -n "\$ROOT_DEV" ]; then
        echo "Found root device: \$ROOT_DEV"
        sp_ok

script/phases/70_image/090_initramfs.sh, lines 1051–1071

With ROOT_UUID set, this is a disk boot. The path adds its three stages and asks blkid -U for the root once a second for up to ten seconds, running activate_lvm before each try so that a volume group on a disk that appears late is activated in time. The first try is made at once: udev has settled already, and on most machines it succeeds.

Mounting and switching root

        sp_step "MOUNTING ROOT"
        # An ext4 root is checked before it is mounted, which is the only
        # point at which it is not in use. -p repairs what is safe to repair
        # unattended. 1 and 2 are "repaired", and the root is not mounted so
        # there is nothing to reboot for; 4 and above left errors behind, and
        # the boot goes on and says so rather than stopping at a shell nobody
        # can see behind the splash. btrfs, xfs and f2fs check themselves at
        # mount time.
        ROOT_TYPE=\$(blkid -o value -s TYPE "\$ROOT_DEV" 2>/dev/null)
        case "\$ROOT_TYPE" in
            ext2|ext3|ext4)
                if [ -x /bin/e2fsck ]; then
                    e2fsck -p "\$ROOT_DEV"
                    FSCK_RC=\$?
                    if [ \$FSCK_RC -ge 4 ]; then
                        echo "e2fsck: \$ROOT_DEV still has errors (exit \$FSCK_RC)"
                        [ -x /bin/kdos-splash ] && /bin/kdos-splash msg \
                            "ROOT FILESYSTEM HAS ERRORS - RUN e2fsck" 2>/dev/null
                    fi
                fi
                ;;
        esac
        mount "\$ROOT_DEV" /newroot

        if [ -x /newroot/sbin/init ]; then
            sp_ok
            # The last step is drawn before /dev moves, as everything sent to
            # the splash must be (see sp_release).
            sp_step "SWITCHING ROOT"
            sp_ok
            sp_root_release
            sp_release
            udev_release
            # Move Mountpoints
            mount --move /dev /newroot/dev
            mount --move /proc /newroot/proc
            mount --move /sys /newroot/sys

            # Switch Root
            echo "Switching root..."
            exec switch_root /newroot /sbin/init \$INIT_ARG
        else
            echo "Error: /sbin/init not found on root device!"
            sp_fail
        fi
    else
        echo "Error: Root device with UUID=\$ROOT_UUID not found!"
        sp_fail
    fi
    
    rescue "Disk boot failed: no root at UUID=\$ROOT_UUID with /sbin/init on it"

script/phases/70_image/090_initramfs.sh, lines 1072–1122

The filesystem type is read with blkid -o value -s TYPE. When the initramfs carries e2fsck, an ext2, ext3 or ext4 root is checked with e2fsck -p, which repairs what is safe to repair without asking. An exit status of 4 or more means errors were left; the script prints the status, shows ROOT FILESYSTEM HAS ERRORS - RUN e2fsck on the splash and mounts the root anyway. The reasons are in Checking the root.

The root is mounted at /newroot with no type and no options, so mount probes the type and mounts it read-write. The mount’s own status is not tested; the test that follows is whether /newroot/sbin/init is executable, which also fails when nothing was mounted. When it is, the splash draws SWITCHING ROOT and marks it done while /dev is still the initramfs’s: its FIFO is in /dev, and nothing this script sends after the move reaches it. sp_root_release has the splash name the release of the root just mounted. udev_release stops this udevd, as on the live path. Then /dev, /proc and /sys are moved into the new root, and switch_root makes /newroot the root and runs /sbin/init there as process 1, with single or emergency if the command line had one. Before /dev moves, on an emergency boot, sp_release stops the splash and leaves the console in text mode; on every other boot the splash survives the switch. exec means no line of this script runs after it. When the root or its /sbin/init is not found, the stage is marked failed and the next line opens the rescue shell.

The live medium

Waiting for USB storage

#
# THE PERSISTENCE STORE IS LOOKED FOR UNTIL USB STORAGE HAS SETTLED. The
# medium is found the moment its own device answers, and a store on another
# USB stick is still being enumerated then: behind a hub it gets an address a
# few hundred milliseconds later, and usb-storage waits a further delay_use
# (one second) before it scans the disk. A single lookup at that point finds
# nothing and the session runs in RAM with the store attached.
#
# USB IS BUSY while a hub port holds a device that is not yet configured, or
# a mass-storage interface has no block device beneath it. Neither state is
# visible for the moment between a hub being configured and its first port
# reporting a connection (power-good plus debounce, well under a second), so
# while a hub other than a root hub is present the lookup also waits until
# the set of USB devices has stood still for one second. With nothing busy
# and no such hub, a boot with no store pays one blkid and no wait. The bound
# is 10 seconds, the bound the medium and the root device get: a device that
# never finishes costs that much and no more, and the boot goes on in RAM.
#
# A NEW DISK GETS ONE MORE LOOKUP. Its block device appears in sysfs before
# the kernel has read its partition table, so a blkid that starts then can
# list the disk without the partition holding the store. blkid opens every
# disk it lists, and the open waits for that read, so the lookup after it
# sees the partitions: the wait ends only after a lookup whose scan counted
# the same USB disks as the scan before the previous one. That second lookup
# runs at once, with no sleep.
: "\${USB_DEVICES:=/sys/bus/usb/devices}"
uptime_cs() {
    local u
    read -r u _ < /proc/uptime
    NOW=\$(( 10#\${u%.*}\${u#*.} ))
}
usb_scan() {
    local p s d found
    USB_BUSY=""
    USB_SEEN=""
    USB_DISKS=""
    USB_HUB=0
    for p in "\$USB_DEVICES"/*:*/*-port*/state; do
        [ -r "\$p" ] || continue
        read -r s < "\$p"
        case "\$s" in
        "not attached"|configured|suspended) ;;
        *) USB_BUSY="\$USB_BUSY \${p%/state}" ;;
        esac
    done
    for d in "\$USB_DEVICES"/*; do
        [ -e "\$d" ] || continue
        case "\${d##*/}" in
        *:*)
            [ -r "\$d/bInterfaceClass" ] || continue
            read -r s < "\$d/bInterfaceClass"
            [ "\$s" == "08" ] || continue
            found=0
            for p in "\$d"/host*/target*/*/block/*; do
                [ -e "\$p" ] || continue
                found=1
                USB_DISKS="\$USB_DISKS \${p##*/}"
            done
            [ "\$found" == "1" ] || USB_BUSY="\$USB_BUSY \$d"
            ;;
        usb*)
            USB_SEEN="\$USB_SEEN \${d##*/}"
            ;;
        *)
            USB_SEEN="\$USB_SEEN \${d##*/}"
            [ -r "\$d/bDeviceClass" ] || continue
            read -r s < "\$d/bDeviceClass"
            [ "\$s" == "09" ] && USB_HUB=1
            ;;
        esac
    done
}
find_persist() {
    local deadline quiet last=x disks="" said=0
    PERSIST=""
    uptime_cs
    deadline=\$(( NOW + 1000 ))
    while :; do
        usb_scan
        PERSIST=\$(blkid -L KDOS_PERSIST 2>/dev/null)
        [ -n "\$PERSIST" ] && return 0
        uptime_cs
        if [ "\$USB_SEEN" != "\$last" ]; then
            last="\$USB_SEEN"
            quiet=\$NOW
            [ "\$USB_HUB" == "1" ] && quiet=\$(( NOW + 100 ))
        fi
        if [ -z "\$USB_BUSY" ] && [ "\$NOW" -ge "\$quiet" ]; then
            [ "\$USB_DISKS" == "\$disks" ] && return 1
            disks="\$USB_DISKS"
            continue
        fi
        disks="\$USB_DISKS"
        if [ "\$NOW" -ge "\$deadline" ]; then
            echo "USB storage still settling after 10s; no persistence store found"
            return 1
        fi
        if [ "\$said" == "0" ]; then
            echo "Waiting for USB devices to settle before looking for a persistence store..."
            said=1
        fi
        sleep 0.1
    done
}

script/phases/70_image/090_initramfs.sh, lines 1125–1228

These three functions are defined before the live path and called once, from the overlay stage, to find the persistence store. uptime_cs sets NOW to the uptime in hundredths of a second. usb_scan reads the USB device tree under USB_DEVICES and sets four variables:

find_persist calls usb_scan and then blkid -L KDOS_PERSIST, every tenth of a second. A lookup that answers sets PERSIST and returns 0. Otherwise it returns 1 when USB_BUSY is empty, the quiet time has passed and USB_DISKS is what it was at the scan before, or when 10 seconds have passed since the first call. The quiet time is reset to now whenever USB_SEEN changes, and to one second from now when a hub is present: a hub’s empty ports report nothing between the hub being configured and its first connection being seen. A disk’s block device appears before the kernel has read its partition table, so a lookup started then can miss the partition that holds the store. That lookup opens the disk, and the open waits for the read, so when USB_DISKS has changed the function makes one more lookup at once, without sleeping, before it gives up. A boot from a USB stick therefore makes two lookups. Before its first sleep it prints Waiting for USB devices to settle before looking for a persistence store..., and when the bound is reached USB storage still settling after 10s; no persistence store found.

Boot media

# Live ISO Boot Mode (Fallback)
mkdir -p /mnt/iso
echo "Searching for KDOS boot media..."

# Announce the stage BEFORE the scan: with only the two common steps closed
# the bar would otherwise sit on "done" through the whole scan.
sp_total 4
sp_step "BOOT MEDIA"

# Find the medium by polling, never by waiting a fixed interval first: udev has
# already settled above, so on every machine whose media is enumerated the first
# pass succeeds and costs nothing. The 10-second bound is what covers the slow
# ones — a USB stick, or a device behind a bridge — and it matches the bound the
# disk-boot path gives its root device. Every retry walks EVERY device class
# again: the first node to answer is not always the one holding the medium, and
# a class that has not appeared yet must still get its chance.
#
# /dev/mapper/ventoy COMES FIRST. A Ventoy stick boots the ISO as a file on its
# exFAT partition, and Ventoy's hook in the initrd maps that file to
# /dev/mapper/ventoy; it also swaps the stick's second partition node for the
# same device, but naming the mapping does not depend on that swap. The hook
# builds that mapping over the stick while this scan runs, and the scan reaches
# whichever of the two names exists first: either is the medium. On any other
# machine the name does not exist and costs one test.
#
# NOTHING IS MOUNTED THAT IS NOT ISO 9660. A mount opens its device
# exclusively, and a mount of the Ventoy stick or its exFAT partition while the
# hook builds its mapping makes the mapping fail with EBUSY: the boot is then
# left without a medium. So each node's primary volume descriptor, CD001 at
# byte 32769, is read first through a plain read, which claims nothing, and
# only a node that carries it is mounted.
#
# EACH DEVICE IS NARRATED THE FIRST TIME IT IS SEEN, on whichever pass it
# appears, and what it turned out to be is kept in WHY. A stick that
# enumerates after the first pass is named in the log like one that was
# there at once, and when the bound passes one line lists every device tried
# and why it was not the medium: the line a failed boot is diagnosed from.
# The same list goes into RESCUE_TRIED one device to a line for the rescue's
# tty1 screen, at most eight devices and each line cut to 80 columns, since
# that line is wider than the screen and goes to the serial console alone.
#
# THE MEDIUM IS THE ONE THE ENTRY NAMES. Every live entry of the medium's
# limine.conf carries kdos.medium=<id>, and the medium carries the same id in
# kdos-medium.id beside system.sfs. A device with system.sfs and another id, or
# none, is a second KDOS medium attached to the machine: it is released,
# recorded in WHY as "another KDOS medium (<id>)" and the scan goes on. Taking
# it would pair this kernel's modules with another release's system.sfs and
# make the installer call the wrong device the boot medium. A command line
# without kdos.medium= (a hand-made entry) takes the first medium found.
MEDIA_HINT="Write the whole ISO with dd, Rufus DD mode or Ventoy; copied files cannot boot."
WANT_MEDIUM=""
for i in \$(cat /proc/cmdline); do
    case "\$i" in kdos.medium=*) WANT_MEDIUM="\${i#kdos.medium=}" ;; esac
done
SCAN_UNTIL=\$(( \$(cut -d. -f1 /proc/uptime) + 10 ))
FOUND=0
PASS=0
STUCK=0
CHECKED=" "
SEEN=" "
declare -A WHY
while :; do
    PASS=\$(( PASS + 1 ))
    for dev in /dev/mapper/ventoy /dev/sr* /dev/sd* /dev/vd* /dev/nvme* /dev/mmcblk*; do
        [ -b "\$dev" ] || continue
        # ONE INSPECTION PER DEVICE. A node that mounts as iso9660 and has no
        # system.sfs on it will not grow one, and a disk that is not ISO 9660
        # will not become one, so reading or mounting it again every 100 ms is
        # churn. Only an optical drive is inspected again after a read or a
        # mount that failed: a disc still spinning up answers on a later pass.
        case "\$CHECKED" in *" \$dev "*) continue ;; esac
        case "\$SEEN" in
            *" \$dev "*) first=0 ;;
            *) first=1; SEEN="\$SEEN\$dev "; echo "Checking \$dev..." ;;
        esac
        # A DRIVE WITH NO MEDIUM IN IT IS PASSED OVER. Opening it fails
        # (ENOMEDIUM), so the scan opens before it reads: a mount of it only
        # prints "Can't open blockdev", and its sysfs size is no test, since
        # an empty optical drive reports a guessed size rather than 0. It is
        # not marked checked: a disc still spinning up opens on a later pass.
        if ! { : < "\$dev"; } 2>/dev/null; then
            WHY[\$dev]="no medium"
            continue
        fi
        pvd=\$(dd if="\$dev" bs=1 skip=32769 count=5 2>/dev/null | tr '\000' '?')
        if [ "\$pvd" != CD001 ]; then
            WHY[\$dev]="not ISO 9660"
            case "\$dev" in /dev/sr*) ;; *) CHECKED="\$CHECKED\$dev " ;; esac
            continue
        fi
        # Only a device's first mount prints its error. A hundred retries of
        # the same line would bury the one message that explains a failed
        # boot, and this log is the only thing left to read when one happens.
        if [ "\$first" == "1" ]; then
            mount -t iso9660 "\$dev" /mnt/iso
        else
            mount -t iso9660 "\$dev" /mnt/iso 2>/dev/null
        fi
        if [ \$? -ne 0 ]; then
            WHY[\$dev]="ISO 9660 that does not mount"
            case "\$dev" in /dev/sr*) ;; *) CHECKED="\$CHECKED\$dev " ;; esac
            continue
        fi
        CHECKED="\$CHECKED\$dev "
        if [ -f /mnt/iso/system.sfs ]; then
            have=""
            [ -f /mnt/iso/kdos-medium.id ] && read -r have < /mnt/iso/kdos-medium.id
            if [ -z "\$WANT_MEDIUM" ] || [ "\$have" == "\$WANT_MEDIUM" ]; then
                echo "Found KDOS media on \$dev (medium \${have:-without an id})"
                MEDIUM="\$dev"
                FOUND=1
                break
            fi
            WHY[\$dev]="another KDOS medium (\${have:-none})"
            echo "\$dev is another KDOS medium (\${have:-none}), not \$WANT_MEDIUM"
        else
            WHY[\$dev]="ISO 9660 without system.sfs"
        fi
        # THE UMOUNT IS CHECKED because /mnt/iso is the only mount point the
        # scan has: if it stays busy, the next mount stacks a second
        # filesystem on the same path and every later test reads the wrong
        # one. Nothing further can be inspected, so the scan stops here and
        # the boot goes to the shell with a reason on the console.
        if ! umount /mnt/iso; then
            echo "Cannot release /mnt/iso after \$dev — stopping the scan"
            STUCK=1
            break
        fi
    done
    [ "\$FOUND" == "1" ] && break
    [ "\$STUCK" == "1" ] && break
    [ "\$(cut -d. -f1 /proc/uptime)" -lt "\$SCAN_UNTIL" ] || break
    [ "\$PASS" == "1" ] && echo "No KDOS media yet; retrying until the 10s bound..."
    sleep 0.1
done
if [ "\$FOUND" != "1" ]; then
    tried=""
    tried_n=0
    for dev in \$SEEN; do
        tried="\$tried\${tried:+, }\$dev (\${WHY[\$dev]:-not inspected})"
        tried_n=\$((tried_n + 1))
        if [ "\$tried_n" -le 8 ]; then
            tried_line="  \$dev: \${WHY[\$dev]:-not inspected}"
            RESCUE_TRIED="\$RESCUE_TRIED\${RESCUE_TRIED:+
}\${tried_line:0:80}"
        fi
    done
    echo "No KDOS media; tried: \${tried:-no block device appeared}"
    [ "\$tried_n" -gt 8 ] && RESCUE_TRIED="\$RESCUE_TRIED
  ...and \$((tried_n - 8)) more; the serial line lists every one."
    [ -n "\$RESCUE_TRIED" ] || RESCUE_TRIED="  no block device appeared"
fi

script/phases/70_image/090_initramfs.sh, lines 1254–1405

With no root=UUID=, the script looks for the medium the image was booted from. It tries /dev/mapper/ventoy and then every block node of /dev/sr*, /dev/sd*, /dev/vd*, /dev/nvme* and /dev/mmcblk* in turn, mounting each that carries an ISO9660 descriptor on /mnt/iso and looking for system.sfs at its top. /dev/mapper/ventoy is the device Ventoy’s hook maps over the ISO file on a Ventoy stick; on any other boot it does not exist. It stops at the first that has one and belongs to this boot, and keeps its name in MEDIUM for the persistence store.

Which medium belongs to this boot is read from the command line before the scan starts: kdos.medium=<id>, which every live entry of the medium’s limine.conf carries, goes into WANT_MEDIUM. A node holding system.sfs is taken only when the first line of its kdos-medium.id equals that id; one with another id, or with no kdos-medium.id, is a second KDOS medium attached to the machine, and the scan prints <dev> is another KDOS medium (<id>), not <wanted>, unmounts it and goes on. Taking it would boot this kernel with another release’s system.sfs and its modules, and the installer would then call the wrong device the boot medium. A command line without kdos.medium=, from an entry written by hand, takes the first node that has system.sfs. The Found KDOS media on <dev> (medium <id>) line names the id it matched. The ISO shows where the id comes from.

The scan repeats every tenth of a second until ten seconds of uptime have passed since it started, with these rules:

FOUND=0 at the end, after the time is up or after a stuck unmount, prints one line, No KDOS media; tried: and each node of SEEN with its WHY, and keeps the same list in RESCUE_TRIED one node to a line (<dev>: <WHY>, cut to 80 columns), at most eight lines and then ...and N more; the serial line lists every one., or no block device appeared when SEEN is empty; rescue shows it on tty1 under a serial console. It then opens the rescue shell with Failed to find the KDOS live medium. and the hint MEDIA_HINT, Write the whole ISO with dd, Rufus DD mode or Ventoy; copied files cannot boot. The scan relies on the medium’s ISO9660 filesystem being at the start of the whole-disk node; The ISO shows how the image keeps it there.

System image

if [ "\$FOUND" == "1" ]; then
    echo "Found KDOS Media, Mounting system..."
    sp_ok
    sp_step "SYSTEM IMAGE"
    
    # Mount System SquashFS using explicit loop
    mkdir -p /mnt/system
    
    # Find a free loop device
    LOOPDEV=\$(losetup -f)
    if [ -z "\$LOOPDEV" ]; then
        LOOPDEV=/dev/loop0
        [ -e /dev/loop0 ] || mknod /dev/loop0 b 7 0
    fi
    
    echo "Associating \$LOOPDEV with /mnt/iso/system.sfs..."
    # Force read-only (-r) to avoid "Read-only file system" error
    if losetup -r "\$LOOPDEV" /mnt/iso/system.sfs; then
        echo "Mounting \$LOOPDEV to /mnt/system..."
        if mount -t squashfs -o ro "\$LOOPDEV" /mnt/system; then
             echo "System mounted successfully."
             sp_ok

script/phases/70_image/090_initramfs.sh, lines 1407–1428

losetup -f prints the first unused loop device, with /dev/loop0 as the fallback. losetup -r attaches system.sfs to it read-only, since it sits on a read-only filesystem, and the device is mounted at /mnt/system as squashfs. A failure of either opens the rescue shell, the first with Failed to set up a loop device for system.sfs and the second with Failed to mount system.sfs.

Overlay root

             # Setup OverlayFS
             sp_step "OVERLAY ROOT"
             mkdir -p /newroot
             modprobe overlay

             # THE UPPER IS WHERE A LIVE SESSION'S WRITES LAND, and whether it
             # survives a power-off is the whole of what persistence means. A
             # filesystem labelled KDOS_PERSIST is used as the upper when one
             # is present; with no store the upper is a tmpfs and the session
             # is gone at reboot. \`kdos persist\` makes the store, and
             # find_persist waits for USB storage before it gives up on one.
             #
             # \`nopersist\` ON THE COMMAND LINE FORCES A CLEAN SESSION, and the
             # boot menu carries an entry that passes it. A store holding a
             # change that stops the desktop coming up would otherwise be
             # reachable only by taking the stick to another machine. From
             # that session \`kdos persist reset\` deletes what the store holds.
             #
             # THE STORE MUST CARRY XATTRS, HARDLINKS AND A d_type, so ntfs,
             # iso9660 and squashfs cannot hold one: overlayfs refuses such an
             # upper with EINVAL, which is the same answer it gives for every
             # other bad mount. Refusing them BY NAME here is what makes a
             # hand-made store say what is wrong with it. vfat and exfat stay
             # in the list though neither can carry the 12-character label.
             # \`kdos persist\` reports a store of these types as refused, from
             # its own copy of this list (refused_type in persist.c), which
             # must match this one.
             PERSIST=""
             case " \$(cat /proc/cmdline) " in
             *" nopersist "*)
                 echo "nopersist: this session will not be saved" ;;
             *)
                 find_persist ;;
             esac

             UPPER=""
             if [ -n "\$PERSIST" ]; then
                 PTYPE=\$(blkid -o value -s TYPE "\$PERSIST" 2>/dev/null)
                 case "\$PTYPE" in
                 vfat|exfat|ntfs|iso9660|squashfs)
                     echo "persistence store \$PERSIST is \$PTYPE, which cannot hold an overlay upper"
                     ;;
                 *)
                     mkdir -p /mnt/persist
                     if ! persist_dev "\$PERSIST" "\$MEDIUM"; then
                         echo "persistence store \$PERSIST: no loop device over \$MEDIUM"
                     elif mount "\$PERSIST_DEV" /mnt/persist; then
                         mkdir -p /mnt/persist/upper /mnt/persist/work
                         UPPER="upperdir=/mnt/persist/upper,workdir=/mnt/persist/work"
                         echo "Persistent session on \$PERSIST (\$PTYPE\${PERSIST_LOOP:+, through \$PERSIST_LOOP})"
                     else
                         echo "persistence store \$PERSIST would not mount"
                         [ -n "\$PERSIST_LOOP" ] && losetup -d "\$PERSIST_LOOP"
                     fi
                     ;;
                 esac
             fi

             # A STORE THAT DOES NOT WORK MUST NOT COST THE BOOT. Everything
             # above can fail on a medium somebody else wrote, and a stick that
             # drops to a shell because its persistence is broken is worse than
             # one that quietly forgets. Every failure lands here, and the
             # session comes up exactly as it would with no store at all.
             if [ -n "\$UPPER" ]; then
                 echo "Mounting OverlayFS (persistent)..."
                 mount -t overlay overlay -o lowerdir=/mnt/system,\$UPPER /newroot || UPPER=""
                 if [ -z "\$UPPER" ]; then
                     umount /mnt/persist 2>/dev/null
                     [ -n "\$PERSIST_LOOP" ] && losetup -d "\$PERSIST_LOOP"
                 fi
             fi
             if [ -z "\$UPPER" ]; then
                 echo "Mounting OverlayFS..."
                 mkdir -p /mnt/overlay
                 mount -t tmpfs tmpfs /mnt/overlay
                 mkdir -p /mnt/overlay/upper /mnt/overlay/work
                 mount -t overlay overlay -o lowerdir=/mnt/system,upperdir=/mnt/overlay/upper,workdir=/mnt/overlay/work /newroot
             fi

             # Check if switch root dir is valid
             if [ ! -d "/newroot" ]; then
                sp_fail
                rescue "Error: /newroot is not a directory"
             fi
             sp_ok

script/phases/70_image/090_initramfs.sh, lines 1430–1514

The root of a live session is an overlay: system.sfs as the read-only lower layer, and a writable upper layer where every change lands. The upper layer comes from one of two places.

  1. Unless the command line has nopersist, find_persist looks for a filesystem labelled KDOS_PERSIST, waiting for USB storage as Waiting for USB storage describes. When one exists and is not of a type that cannot hold an upper layer (vfat, exfat, ntfs, iso9660, squashfs), it is mounted at /mnt/persist, and its upper and work directories are used. A store on the disk in MEDIUM is mounted through a loop device that persist_dev sets up at the partition’s offset and length, with direct I/O, because the medium’s whole-disk mount makes the kernel refuse to open any partition on that disk; a store on another disk is mounted directly. If the mount or the overlay over it fails, the store is unmounted, the loop is detached, and the script goes on to the second choice.
  2. Otherwise a tmpfs is mounted at /mnt/overlay and its upper and work directories are used, and the session lasts until the machine is switched off.

Every way the store can fail ends in the second choice and never in the rescue shell. The tmpfs overlay mount is not checked. What the store is and how kdos persist makes one is in The live medium and persistence.

Moving the mounts

            # Create missing mountpoints in newroot
            mkdir -p /newroot/dev /newroot/proc /newroot/sys /newroot/run /newroot/tmp

            # THE SQUASHFS AND THE RAM UPPER ARE DETACHED, and their mount
            # points removed, so nothing is left under /mnt. switch_root
            # deletes the initramfs but never crosses into another filesystem:
            # a mount still on /mnt/system or /mnt/overlay keeps /mnt from
            # being removed, and every live boot prints \`failed to unlink mnt:
            # Directory not empty\`. The overlay took private clones of its
            # layers when it was mounted, so / keeps reading them; the detach
            # only takes away names switch_root would leave unreachable anyway.
            # It runs BEFORE /proc moves: util-linux umount looks its target up
            # in /proc/self/mountinfo and, with no /proc, fails with "No such
            # file or directory" and detaches nothing. It runs only once
            # /sbin/init is known to be there, so a rescue shell for a missing
            # init still finds both mounts.
            #
            # THE LAST STEP IS SETTLED BEFORE /dev MOVES, as everything sent
            # to the splash must be (see sp_release). A missing init fails it
            # and opens the rescue shell here, where /dev and /proc are still
            # the initramfs's and the shell can reach tty1.
            sp_step "SWITCHING ROOT"
            if [ ! -x /newroot/sbin/init ]; then
                ls -l /newroot/sbin/init
                sp_fail
                rescue "Error: /sbin/init not found in new root!"
            fi
            umount -l /mnt/system
            [ -z "\$UPPER" ] && umount -l /mnt/overlay
            rmdir /mnt/system /mnt/overlay 2>/dev/null
            sp_ok
            sp_root_release
            sp_release
            udev_release
            # Move pseudo-filesystems under the new root (standard; Alpine mkinitfs does this)
            mount --move /dev /newroot/dev
            mount --move /proc /newroot/proc
            mount --move /sys /newroot/sys

            # /mnt/iso HAS TO BE MOVED, not detached like the squashfs and the
            # tmpfs are above. Left behind it dies with the initramfs
            # namespace, and everything the booted system reads off the boot
            # medium becomes unreachable BY NAME
            # while the bytes are still on the disk: \`kdos rebuild\` looks in
            # /mnt/iso/sources, and would report a stick empty that is carrying
            # the sources it was built with.
            #
            # Guarded on the mount existing: a boot that found system.sfs some
            # other way must not fail here, and \`mount --move\` on a path that
            # is not a mountpoint is an error rather than a no-op. The test is a
            # shell builtin against the file this branch has already proven is
            # there — nothing on the boot path should need a second binary to
            # answer a question it already knows.
            if [ -e /mnt/iso/system.sfs ]; then
                mkdir -p /newroot/mnt/iso
                mount --move /mnt/iso /newroot/mnt/iso
            fi

            # THE PERSISTENCE STORE MOVES FOR THE SAME REASON AND ONE MORE.
            # Left in the initramfs namespace it is unreachable by name, so
            # \`kdos persist\` could not report how full the store is that the
            # session is writing to. It also has to be a mount the SHUTDOWN can
            # name: /etc/inittab remounts /mnt/persist read-only, and a store
            # not in the new root's table would stay writable at reboot.
            if [ -n "\$UPPER" ]; then
                mkdir -p /newroot/mnt/persist
                mount --move /mnt/persist /newroot/mnt/persist
            fi

script/phases/70_image/090_initramfs.sh, lines 1516–1583

The mount points the real init expects are made in the new root. The splash draws SWITCHING ROOT, and the stage is settled here, before /dev moves, since the FIFO that carries the splash’s commands is in /dev. A missing /sbin/init fails the stage, prints what ls -l can see of it and opens the rescue shell while /dev, /proc and both of the image’s mounts are still where the initramfs left them. Once /sbin/init has been found, umount -l detaches the squashfs at /mnt/system and, on a boot in RAM, the tmpfs at /mnt/overlay, and rmdir removes both mount points. The overlay took private copies of its layers when it was mounted, so the root keeps reading them. The detach comes before /proc moves, because util-linux umount finds its target in /proc/self/mountinfo and without it detaches nothing. The stage is then marked done, sp_root_release has the splash name the release of the overlay root, and udev_release stops this udevd.

/dev, /proc and /sys are then moved into the new root. Two more mounts are moved: /mnt/iso, the medium itself, guarded by a test for system.sfs on it, and /mnt/persist when a store is in use. Both have to be reachable by name from the booted system.

Switching root

            echo "Switching to new root..."
            # Unless sp_release stopped it, the splash runs on: switch_root
            # deletes the old rootfs but not its processes, and the FIFO is
            # on devtmpfs, which has just been moved into the new root.
            exec switch_root /newroot /sbin/init \$INIT_ARG
        else
            sp_fail
            rescue "Failed to mount system.sfs"
        fi
    else
        sp_fail
        rescue "Failed to set up a loop device for system.sfs"
    fi
else
    sp_fail
    rescue "Failed to find the KDOS live medium." "\$MEDIA_HINT"
fi

rescue "Boot failed."
EOF

script/phases/70_image/090_initramfs.sh, lines 1586–1605

switch_root starts the real /sbin/init from the overlay, as on the installed path. Before it does, it deletes the initramfs’s own files to give back their memory, and it never crosses into another mount: one mount still under /mnt would keep /mnt from going, with switch_root: failed to unlink mnt: Directory not empty on the console, which is why the squashfs and the tmpfs were detached above. On an emergency boot sp_release has already stopped the splash, before /dev moved, leaving the console in text mode; on every other boot the splash survives it, as the comment says. The last line of the script is a rescue too, so that init never runs off its end.

See also