379. The initramfs
This chapter is for anyone who wants to know exactly what goes into the KDOS initramfs, or who has to add a program or a kernel module to it.
The initramfs (initial RAM filesystem) is the small root the kernel unpacks into memory and runs first. Its one job is to find the real root, on a disk or on the boot medium, and hand over to it.
script/phases/70_image/090_initramfs.sh builds it from the finished root, which is the image stage, or build/fs under KDOS_IMAGE=full. In order, the step:
- lays out a directory tree;
- copies into it the programs early boot runs, with every library they need;
- picks the kernel modules;
- writes the
initscript; - puts the processor microcode in front;
- checks the udev rules and the library closure, and packs the lot into one file.
This chapter goes through the script in that order. The init it writes is long enough to have a chapter of its own.
What the initramfs does at boot, and why each part is there, is described in The initramfs and the sections after it. This chapter is about how the file is made.
Runs in: the chroot, as a script step of 70_image
Reads: the programs, libraries, udev rules and kernel modules installed in the root
Writes: the tree build/initramfs/, the microcode tree build/ucode/ and its archive build/ucode.cpio, the finished build/initramfs.cpio.gz, and /boot/initramfs.modules in the root
The workspace
echo "Building Initramfs..."
# Setup workspace
INITRAMFS=/kdos/build/initramfs
rm -rf $INITRAMFS
mkdir -p $INITRAMFS
cd $INITRAMFS
# Create Directory Structure
mkdir -p bin dev proc sys run mnt/iso newroot etc lib
# Install Basic Config
cp /etc/passwd etc/passwd
cp /etc/group etc/group
script/phases/70_image/090_initramfs.sh, lines 16–29
/kdos is the repository inside the chroot, so the tree is build/initramfs in the checkout. It is deleted and made again on every run, and nothing from an earlier initramfs survives into the next. The directories are the mount points init uses (proc, sys, dev, run, mnt/iso, newroot) and the places the copies below go. etc/passwd and etc/group are the root’s own.
The tree is left in place when the step ends. build/initramfs/init is the generated script as the kernel will run it, and ls build/initramfs/bin build/initramfs/lib shows what was carried.
Proving the reader
# copy_closure DEST SRC: SRC to DEST, then every library its NEEDED entries
# name, and theirs, from /usr/lib or /lib into lib/. NEEDED is read with
# readelf, from the dynamic section, without loading the file. A library that
# is installed nowhere stops the build here, naming the program that wanted it.
#
# THE READER IS PROVEN BEFORE IT IS TRUSTED. A readelf that is absent or
# prints another format fails inside a command substitution, which `set -e`
# does not see: every program would be copied with no libraries and the final
# check below would report nothing. binutils' readelf is first; llvm-readelf
# prints the same NEEDED lines. Either must find libblkid in blkid, which is
# known to link it, or the build stops.
READELF=""
for _r in readelf llvm-readelf; do
command -v $_r >/dev/null 2>&1 || continue
if $_r -d /usr/sbin/blkid 2>/dev/null | grep -q '(NEEDED).*\[libblkid\.so'; then
READELF=$_r
break
fi
done
unset _r
if [ -z "$READELF" ]; then
echo "FATAL: no readelf reads NEEDED from /usr/sbin/blkid; the initramfs" >&2
echo " library closure cannot be measured. binutils provides one." >&2
exit 1
fi
needed_libs() {
$READELF -d "$1" | sed -n 's/.*(NEEDED).*\[\(.*\)\]/\1/p'
}
script/phases/70_image/090_initramfs.sh, lines 31–58
The script does not ask ldd which libraries a program needs. It reads them from the program’s dynamic section instead: readelf -d prints one (NEEDED) line for each library the file was linked against, and needed_libs keeps the name in brackets. Those are the direct needs only; the libraries of a library are found by reading the library in turn, which is what copy_closure does.
Before the script trusts that reader, it tries it on a program whose answer it knows. util-linux’s blkid links libblkid, so a reader that works must print a NEEDED line for it. readelf comes from binutils; llvm-readelf prints the same lines and is the second choice. If neither passes, the step stops. The comment says why the test has to be explicit: needed_libs runs inside $(...), where a failing command does not stop a set -e script, so a missing reader would make every program look as if it needed nothing.
copy_closure
copy_closure() {
local _dest=$1 _src=$2 _lib _dir
cp "$_src" "$_dest"
for _lib in $(needed_libs "$_src"); do
[ -e "lib/$_lib" ] && continue
for _dir in /usr/lib /lib; do
if [ -f "$_dir/$_lib" ]; then
copy_closure "lib/$_lib" "$_dir/$_lib"
break
fi
done
if [ ! -e "lib/$_lib" ]; then
echo "FATAL: $_src needs $_lib, which is installed nowhere." >&2
exit 1
fi
done
}
script/phases/70_image/090_initramfs.sh, lines 60–76
copy_closure DEST SRC copies one program and then, for each library it names, the library itself, by calling itself on it. A library already in lib/ is skipped, so a library that many programs need is copied once and the recursion ends. Libraries are looked for in /usr/lib and then /lib. When one is in neither, the step stops and names the program that wanted it, so a broken closure is a failed build and never a program that cannot start at boot.
cp follows symbolic links, so a library reached through its .so.N link is copied as a regular file under that name, which is the name the program asks the dynamic linker for.
The GNU programs
# GNU coreutils, grep and sed. The first row is what `init` runs; the rest are
# the rescue shell's, for the boot that does not reach a root, and the udev
# rules' (63-md-raid-arrays runs readlink and basename). Each must
# answer --version as GNU's (`dd` alone names its package `coreutils`, without
# the GNU) and is copied with its libraries.
for _n in cat chmod cut ls mkdir mknod seq sleep \
cp mv rm ln rmdir head tail wc stat df dd sync uname readlink touch \
basename sort tr grep sed; do
_p=""
for _d in /usr/bin /usr/sbin; do
if [ -x "$_d/$_n" ]; then
_p=$_d/$_n
break
fi
done
if [ -z "$_p" ]; then
echo "FATAL: the initramfs needs $_n, which is installed nowhere." >&2
exit 1
fi
case "$("$_p" --version 2>/dev/null)" in
*"(GNU "*|*" (coreutils) "*) ;;
*)
echo "FATAL: $_p is not GNU's: its --version names no GNU package." >&2
exit 1
;;
esac
copy_closure bin/$_n "$_p"
done
unset _n _p _d
script/phases/70_image/090_initramfs.sh, lines 90–118
The first row is what init itself runs; the rest are there for the rescue shell and for the udev rules, of which 63-md-raid-arrays.rules runs readlink and basename. Each is looked for in /usr/bin and then /usr/sbin, and each must answer --version with a GNU package name before it is copied: (GNU coreutils), (GNU grep) and so on, or (coreutils) for dd, the one program of the set whose banner leaves out the word GNU. A program that is missing, or that is some other userland’s, stops the step. The programs come from coreutils, grep and sed.
The util-linux programs
# util_linux_only PATH: stop the build unless PATH answers --version as
# util-linux. Each program held to it below is one whose stand-ins from other
# userlands lack what this init relies on, and the boot fails without saying
# why.
util_linux_only() {
case "$("$1" --version 2>/dev/null)" in
*" from util-linux "*) return 0 ;;
esac
echo "FATAL: $1 is not util-linux's: its --version does not name util-linux." >&2
exit 1
}
script/phases/70_image/090_initramfs.sh, lines 78–88
# util-linux's switch_root, mount, umount, losetup, dmesg and setsid.
#
# switch_root MUST MOVE THE NEW ROOT ONTO / (mount(newroot, "/", MS_MOVE))
# before it chroot()s. One that only wipes the initramfs and chroot()s leaves
# every process on the machine chrooted for ever: a process that joins a mount
# namespace via setns() -- podman exec, distrobox enter, nsenter -m -- gets the
# empty initramfs rootfs as "/" and every path is ENOENT, and the kernel
# refuses CLONE_NEWUSER to a chrooted caller, so no user namespace can be
# created by anybody, root included, and no box can start at all. The machine
# boots perfectly either way, which is why the check exists.
#
# mount, umount and losetup are what `init` itself runs: the ISO scan, the
# loop device under system.sfs, the overlay and the --move of every mount into
# the new root. setsid gives the rescue shell tty1 as its controlling
# terminal. dmesg is for the rescue shell.
for _p in /usr/sbin/switch_root /usr/bin/mount /usr/bin/umount \
/usr/sbin/losetup /usr/bin/dmesg /usr/bin/setsid; do
util_linux_only "$_p"
copy_closure bin/${_p##*/} "$_p"
done
unset _p
script/phases/70_image/090_initramfs.sh, lines 120–140
util_linux_only runs the program with --version and accepts it only if the answer contains from util-linux. switch_root, mount, umount, losetup, dmesg and setsid are held to it here and blkid a little further down, all from util-linux. The reason for switch_root is given at length in the comment, and in switch_root: a stand-in boots the machine and leaves every process chrooted, which only shows when something tries to start a box. Each program is copied with copy_closure, under its own name in bin/.
The splash, the C library and bash
# Install the boot splash. Static, so it needs nothing else here, and it keeps
# running across switch_root: its FIFO lives in /dev (devtmpfs is moved into the
# new root, not remounted), so one process spans the initramfs and the real root
# without the screen ever going black between them. It names the release under
# the wordmark from the image's /etc/kdos-release and /etc/os-release, which
# 045_identity.sh stamped before this step, copied beside it: that is what it
# shows before any root is open. An image built with no commit has no record,
# so that copy may fail, and without either file it draws the name alone.
# sp_root_release, below, replaces it with the release of the root it boots.
if [ -x /usr/bin/kdos-splash ]; then
cp /usr/bin/kdos-splash bin/kdos-splash
mkdir -p usr/share/kdos
cp /usr/share/kdos/splash.psf usr/share/kdos/splash.psf
cp /etc/os-release etc/os-release
[ ! -f /etc/kdos-release ] || cp /etc/kdos-release etc/kdos-release
else
echo "Warning: kdos-splash not installed — booting without the splash"
fi
# Install Libc
cp /usr/lib/libc.so lib/libc.so
ln -sf libc.so lib/ld-musl-x86_64.so.1
# Install Bash and Dependencies
cp /usr/bin/bash bin/bash
cp /usr/lib/libreadline.so.8 lib/libreadline.so.8
cp /usr/lib/libhistory.so.8 lib/libhistory.so.8
cp /usr/lib/libncursesw.so.6 lib/libncursesw.so.6
ln -sf bash bin/sh
script/phases/70_image/090_initramfs.sh, lines 142–170
kdos-splash is statically linked, so it is copied alone, with the font it draws in. When it is not installed the step prints a warning and carries on, and the machine boots without a splash; every call to it in init first tests that /bin/kdos-splash exists. The image’s /etc/os-release and, when the build had a commit, its /etc/kdos-release go into the initramfs’s etc/ beside it, stamped by identity before this step: the splash names the release from them while no root is open, until sp_root_release sends the booted root’s (see the splash).
musl’s libc.so is its own dynamic linker, so the link ld-musl-x86_64.so.1, the interpreter every program in the tree names, points at it. bash and the three libraries beside it are listed by hand rather than walked with copy_closure: bash names libreadline, which names libncursesw, and libhistory comes with them. bin/sh is bash under its other name, and init is a bash script. The closure check at the end of the step reads every program in the tree, these included, so a library missing from this list stops the build there.
blkid
# Install util-linux's blkid.
#
# EVERY LOOKUP IN THIS INIT IS `blkid -U <uuid>` — the root filesystem, the
# ESP that holds the A/B state, and the LUKS container an encrypted root
# lives inside. A prober that cannot resolve -U, or cannot name a
# `crypto_LUKS` container, answers nothing to every one of them: an installed
# machine drops to a shell with "Root device not found", A/B selection
# silently never engages, and an encrypted root cannot be unlocked at all,
# with a passphrase prompt that never appears.
util_linux_only /usr/sbin/blkid
copy_closure bin/blkid /usr/sbin/blkid
script/phases/70_image/090_initramfs.sh, lines 172–182
Every lookup init makes by UUID is blkid -U, so this is the one program whose failure would stop every installed machine from finding its root. It is held to util-linux like the programs above. What each lookup is and what a stand-in breaks is listed in blkid.
loadkeys and the keymaps
# Install kbd's loadkeys and every keymap, for the disk passphrase.
#
# THE PASSPHRASE IS TYPED BEFORE ANY ROOT IS OPEN, so /etc/keymap cannot be
# read, and this image is one image for every machine. The machine's map is
# named on its ESP (EFI/kdos/keymap) and loaded from here before the prompt;
# without it the kernel's US map is the only one, and a passphrase set on a
# German layout, or holding any letter US has no key for, is never typed.
# The whole tree, about 1.4 MB: the installer offers every map in it, and a
# map left out here is a prompt that silently types US. The maps are gzipped
# and loadkeys dlopens libz, which no ELF header names: it is the copy the
# udev block below makes for kmod.
copy_closure bin/loadkeys /usr/bin/loadkeys
mkdir -p usr/share && cp -a /usr/share/keymaps usr/share/keymaps
script/phases/70_image/090_initramfs.sh, lines 184–196
The disk passphrase is typed before any root is open, so the machine’s /etc/keymap cannot be read then, and this one image serves every machine. loadkeys from kbd is copied with its closure (libxkbcommon), and the whole of /usr/share/keymaps goes to usr/share/keymaps/, about 1.4 MB. The text installer offers every map in that tree, so a map left out of the image would be one whose prompt silently types with the US map. init loads the map the ESP names in EFI/kdos/keymap before the prompt; see The unlock function.
The maps are gzipped. loadkeys opens libz with dlopen, which no ELF header names and the closure check cannot see; the copy it uses is the one the udev block makes for kmod.
mdadm and e2fsck
# Install mdadm, for a root that lives on a software RAID array. At
# /usr/sbin, the path its udev rules run it from, with the init's bin/mdadm a
# link to it.
if [ -x /usr/sbin/mdadm ]; then
mkdir -p usr/sbin
copy_closure usr/sbin/mdadm /usr/sbin/mdadm
ln -sf ../usr/sbin/mdadm bin/mdadm
else
echo "Note: mdadm not installed — the initramfs cannot assemble an array"
fi
# Install e2fsck, for the check an ext4 root gets before it is mounted. Here
# and nowhere later: the root is mounted read-write below, and a filesystem
# with errors recorded in its superblock would otherwise run until somebody
# checks it by hand from other media. Copied WITH its libraries or not at all,
# the cryptsetup rule — an e2fsck that cannot exec is skipped at boot rather
# than failing it, and a skipped check is exactly the gap this closes.
if [ -x /usr/sbin/e2fsck ]; then
_ok=1
for _l in libext2fs.so.2 libcom_err.so.2 libe2p.so.2; do
[ -f /usr/lib/$_l ] || _ok=0
done
if [ "$_ok" = 1 ]; then
cp /usr/sbin/e2fsck bin/e2fsck
for _l in libext2fs.so.2 libcom_err.so.2 libe2p.so.2; do
cp /usr/lib/$_l lib/$_l
done
else
echo "Note: e2fsck's libraries are missing — an ext4 root is mounted unchecked"
fi
unset _ok
else
echo "Note: e2fsprogs not installed — an ext4 root is mounted unchecked"
fi
script/phases/70_image/090_initramfs.sh, lines 198–231
mdadm is optional: without it the initramfs cannot assemble an array, and init skips the RAID stage. It is copied with its closure (libudev) to usr/sbin/, the path its udev rules run, and bin/mdadm, which init runs, is a link to it.
e2fsck from e2fsprogs checks an ext root before it is mounted. It is copied only when its three e2fsprogs libraries are installed, and then with them; otherwise the step prints a note, init finds no /bin/e2fsck, and an ext root is mounted unchecked. e2fsck also names libblkid and libuuid, which this block does not copy: they reach lib/ with blkid and cryptsetup, and the closure check stops the build if they do not.
udev
# Install eudev and dependencies
cp /sbin/udevd bin/udevd
cp /sbin/udevadm bin/udevadm
cp /usr/lib/libudev.so.1 lib/libudev.so.1
cp /usr/lib/libkmod.so.2 lib/libkmod.so.2
cp /usr/lib/liblzma.so.5 lib/liblzma.so.5
cp /usr/lib/libz.so.1 lib/libz.so.1
cp /usr/lib/libzstd.so.1 lib/libzstd.so.1
script/phases/70_image/090_initramfs.sh, lines 233–240
udevd and udevadm come from eudev. They name libkmod, which names liblzma, libz and libzstd, and libblkid, which blkid has already brought. Neither names libudev; it is copied for the programs built on it: mdadm, lvm2’s programs, pdata_tools and udev helpers such as hid2hci. This list, too, is written out by hand, and the closure check holds it to what the binaries name.
kdos-bootctl
# Install kdos-bootctl, which decides WHICH root to boot when the machine has
# two. Limine cannot count boots — that is a systemd-boot feature — so the
# counting is ours and it has to happen here rather than in rcS: a kernel that
# boots into a wedged userland must still spend an attempt.
#
# /usr/bin/kdos-bootctl IS A SYMLINK TO /usr/sbin/ksvc and cp copies through it,
# so what lands here is the whole tool — linked -lpng for `kdos theme`'s
# wallpaper retint. libpng16 is therefore carried beside it; libz.so.1 is
# already above and musl's libm is inside libc, so those two are the whole
# closure.
#
# COPIED WHOLE OR NOT AT ALL, the cryptsetup rule one block down: a
# kdos-bootctl that cannot exec makes A/B selection silently never run, and the
# machine reads as one whose slot was never marked good rather than one missing
# a library.
BOOTCTL=""
[ -x /usr/bin/kdos-bootctl ] && BOOTCTL=/usr/bin/kdos-bootctl
if [ -z "$BOOTCTL" ]; then
echo "Note: kdos-bootctl not installed — no A/B slot selection at boot"
elif [ ! -f /usr/lib/libpng16.so.16 ]; then
echo "Note: no libpng16 for kdos-bootctl — no A/B slot selection at boot"
else
cp $BOOTCTL bin/kdos-bootctl
cp /usr/lib/libpng16.so.16 lib/libpng16.so.16
fi
script/phases/70_image/090_initramfs.sh, lines 242–266
kdos-bootctl decides which root slot to boot when a machine has two; see A/B slot selection. It is one name of the multi-call ksvc binary from kdos-tools, and cp copies the binary through the link, so the initramfs gets all of it, and with it its libpng16. The script looks only for /usr/bin/kdos-bootctl, the link the port installs. Either the binary and libpng are both copied, or neither is and the step prints a note; with no kdos-bootctl, init skips the BOOT SLOT stage and boots the root= on the command line.
cryptsetup
# Install cryptsetup, for an encrypted root.
#
# Copied WITH its libraries and skipped entirely when it is not installed: an
# initramfs that half-carries a cryptsetup is an initramfs that fails at the
# passphrase prompt instead of at build time. The list is explicit and each
# entry is copied only when /usr/lib has it; a library cryptsetup NEEDs that
# the list misses or /usr/lib lacks is caught by the closure check at the end
# of this step, which stops the build and names it. `init` asks only whether
# /bin/cryptsetup exists, when a cryptdevice= needs it.
if [ -x /usr/sbin/cryptsetup ]; then
cp /usr/sbin/cryptsetup bin/cryptsetup
for _l in libcryptsetup.so.12 libdevmapper.so.1.02 libjson-c.so.5 \
libpopt.so.0 libssl.so.4 libcrypto.so.4 libargon2.so.1 \
libuuid.so.1 libblkid.so.1 libz.so.1; do
[ -f /usr/lib/$_l ] && cp /usr/lib/$_l lib/$_l
done
else
echo "Note: cryptsetup not installed — the initramfs cannot unlock a LUKS root"
fi
script/phases/70_image/090_initramfs.sh, lines 268–286
cryptsetup unlocks an encrypted root. When it is installed it is copied with the libraries in the list; each library is copied when it exists and skipped quietly when it does not, and the closure check at the end of the step then stops the build if cryptsetup names one that was skipped. Nothing later in the build asks whether cryptsetup was carried. When cryptsetup is not installed, init still parses cryptdevice=, and the unlock fails with cryptdevice: this initramfs has no cryptsetup.
lvm2
# Install lvm and dmsetup, for a root on a logical volume.
#
# AT /usr/sbin, THE PATHS lvm2's UDEV RULES NAME, and not in bin/: the rules
# are copied below with the rest of /usr/lib/udev. 95-dm-notify.rules runs
# `/usr/sbin/dmsetup udevcomplete` for every device-mapper change, and every
# program built on libdevmapper -- lvm, and cryptsetup opening a container --
# waits for that call with no timeout. A dmsetup the rule cannot find is a
# boot that hangs at the unlock or the activation, with nothing on screen.
#
# INSTALLED lvm2 MEANS THE INITRAMFS CARRIES BOTH, or the build stops: lvm2
# arrives as a dependency of cryptsetup and parted, so its rules are on every
# image that has them, and a missing binary is a package that did not install
# properly rather than one that was left out.
if [ -f /var/lib/kpkg/db/lvm2 ] || [ -f /usr/lib/udev/rules.d/95-dm-notify.rules ]; then
for _p in /usr/sbin/lvm /usr/sbin/dmsetup; do
if [ ! -x $_p ]; then
echo "FATAL: lvm2 is installed but $_p is not." >&2
echo " Its udev rules run it, and a boot that opens any" >&2
echo " device-mapper device waits for it for ever." >&2
exit 1
fi
done
# The rules take that directory from lvm2's configure (its sbindir), so
# it is read back rather than assumed: a rule naming dmsetup or lvm
# anywhere else is the same silent hang, and stops the build here.
_stray=$(cat /usr/lib/udev/rules.d/*.rules 2>/dev/null | grep -v '^[[:space:]]*#' \
| grep -o '[^ "=]*/\(dmsetup\|lvm\) ' | grep -v '^/usr/sbin/' || true)
if ! grep -q '/usr/sbin/dmsetup udevcomplete' /usr/lib/udev/rules.d/95-dm-notify.rules 2>/dev/null \
|| [ -n "$_stray" ]; then
echo "FATAL: lvm2's udev rules do not run dmsetup and lvm from /usr/sbin," >&2
echo " where the initramfs carries them:" $_stray >&2
exit 1
fi
unset _stray
mkdir -p usr/sbin
copy_closure usr/sbin/lvm /usr/sbin/lvm
copy_closure usr/sbin/dmsetup /usr/sbin/dmsetup
ln -sf ../usr/sbin/lvm bin/lvm
ln -sf ../usr/sbin/dmsetup bin/dmsetup
unset _p
script/phases/70_image/090_initramfs.sh, lines 288–327
The test for lvm2 is its package database entry or its device-mapper udev rule; on any image where either is present, the step either carries LVM or stops. lvm and dmsetup must both exist, and every udev rule that runs one of them must name it under /usr/sbin. The second test reads every rule file, drops comment lines, and collects each path ending in /dmsetup or /lvm that does not start with /usr/sbin/; any such path, or a 95-dm-notify.rules without the udevcomplete call, stops the step and prints what it found. The two programs are then copied with their closures to usr/sbin/, the path the rules name, with links from bin/ so that PATH=/bin finds them too.
# AND thin_check AND cache_check, for a root on a thin or a cached
# volume. lvm runs the one that matches before it activates a thin pool
# or a cache and refuses the volume when it cannot, and 41_system's disk
# list installs thin-provisioning-tools beside lvm2 (it depends on lvm2,
# not the other way round), so a missing one is a broken install and stops
# the build like a missing lvm does. Both names are argv[0] links to one
# binary, pdata_tools, which is copied once with its libraries.
#
# lvm.conf NAMES THEM, and names nothing else: every other setting stays
# the compiled default. The paths are this initramfs's, written here beside
# the copy that makes them true, rather than inherited from wherever
# lvm2's configure pointed.
for _p in /usr/sbin/thin_check /usr/sbin/cache_check; do
if [ ! -x $_p ]; then
echo "FATAL: lvm2 is installed but $_p is not." >&2
echo " A thin or cached root would refuse to activate." >&2
exit 1
fi
done
_pdata=$(readlink -f /usr/sbin/thin_check)
copy_closure "usr/sbin/${_pdata##*/}" "$_pdata"
for _p in thin_check cache_check; do
[ "$_p" = "${_pdata##*/}" ] || ln -sf "${_pdata##*/}" usr/sbin/$_p
done
mkdir -p etc/lvm
cat > etc/lvm/lvm.conf <<'LVMCONF'
# Written by 090_initramfs.sh. Every setting not named here is lvm2's compiled
# default.
global {
thin_check_executable = "/usr/sbin/thin_check"
cache_check_executable = "/usr/sbin/cache_check"
}
LVMCONF
unset _p _pdata
else
echo "Note: lvm2 not installed — the initramfs cannot activate a volume group"
script/phases/70_image/090_initramfs.sh, lines 329–364
thin_check and cache_check are installed by thin-provisioning-tools as links to one program. readlink -f finds it, copy_closure copies it once under its own name, and the two names are made links to it again. On an image with lvm2, a missing thin_check or cache_check stops the step, as a missing lvm does: lvm runs the matching one before it activates a thin pool or a cache, and refuses the volume when it cannot. The generated lvm.conf names those two paths and nothing else. Activation itself is in Activating volume groups.
The udev rules and kmod
# Install udev rules and helpers. Which of them stay is decided once every
# program and library is in the tree; see the udev check before the pack.
mkdir -p lib/udev/rules.d etc/udev/rules.d
cp -r /usr/lib/udev/rules.d/* lib/udev/rules.d/ 2>/dev/null || true
cp -r /etc/udev/rules.d/* etc/udev/rules.d/ 2>/dev/null || true
cp -r /usr/lib/udev/* lib/udev/ 2>/dev/null || true
# udev reads only the compiled hwdb.bin, which this tree does not carry; the
# sources would be carried for nothing.
rm -rf lib/udev/hwdb.d
# THE RULES NAME THE ROOT'S PATHS, so the initramfs answers at them. udevd
# runs a bare helper name from /usr/lib/udev, and the packages' rules run
# /usr/bin, /usr/sbin and /sbin; here the programs are in bin/ and the
# helpers in lib/udev, so each of those paths is a link into the tree. lvm2's
# and mdadm's binaries are in usr/sbin itself.
mkdir -p usr/lib usr/sbin
ln -sfn ../../lib/udev usr/lib/udev
ln -sfn ../bin usr/bin
ln -sfn bin sbin
ln -sf ../../bin/blkid usr/sbin/blkid
# Install kmod and overlay module
cp /usr/bin/kmod bin/kmod
ln -sf kmod bin/modprobe
ln -sf kmod bin/insmod
ln -sf kmod bin/depmod
script/phases/70_image/090_initramfs.sh, lines 367–392
The rules come from both rule directories, and then the whole of /usr/lib/udev is copied, which brings the helper programs the rules call. hwdb.d is removed again: udev reads only the compiled hwdb.bin, and the tree does not carry one. Every 2>/dev/null || true here means that a missing directory is not an error. Which rules and helpers stay is decided at the end of the step, in the udev check.
The rules name the real root’s paths: helpers under /usr/lib/udev (where udevd also runs a bare helper name from), programs under /usr/bin, /usr/sbin and /sbin. The links make each of those paths answer here: usr/lib/udev is lib/udev, usr/bin and sbin are bin, and usr/sbin/blkid is bin/blkid. lvm2’s and mdadm’s programs are in usr/sbin itself.
kmod is one program that behaves as modprobe, insmod and depmod according to the name it is run under, so those three are links to it.
Kernel modules
Finding the kernel
# Detect Kernel Version & Copy necessary modules
KERNEL_VER=$(ls /lib/modules | sort -V | tail -n 1)
if [ -z "$KERNEL_VER" ]; then
echo "Error: No kernel modules found in /lib/modules!"
exit 1
fi
echo "Using Kernel Version: $KERNEL_VER"
MOD_DIR=lib/modules/$KERNEL_VER
mkdir -p $MOD_DIR
# Function to copy module and dependencies recursively
run_depmod() {
if [ ! -f /lib/modules/$KERNEL_VER/modules.dep ]; then
echo "Running depmod..."
depmod -a $KERNEL_VER
fi
}
run_depmod
script/phases/70_image/090_initramfs.sh, lines 394–411
The modules belong to the newest kernel in /lib/modules, taken with sort -V. With none there, the linux port has not been installed and the step stops. depmod -a runs only when that kernel has no modules.dep, the index modinfo uses to turn a module’s name into its file.
copy_module
copy_module() {
local MOD=$1
# Check if builtin
if grep -q -w "$MOD" /lib/modules/$KERNEL_VER/modules.builtin 2>/dev/null; then
echo "Module $MOD is builtin, skipping."
return
fi
local MOD_PATH=$(modinfo -k $KERNEL_VER -n $MOD 2>/dev/null)
# Fallback if modinfo fails (e.g. for .zst or if depmod is stale)
if [ -z "$MOD_PATH" ] || [ "$MOD_PATH" = "(builtin)" ]; then
MOD_PATH=$(find /lib/modules/$KERNEL_VER -name "$MOD.ko*" -print -quit)
fi
if [ -z "$MOD_PATH" ]; then
echo "Warning: Module $MOD not found"
return
fi
# Destination path structure (strip /lib/modules/VER/)
local REL_PATH=${MOD_PATH#*/lib/modules/$KERNEL_VER/}
local DEST=$MOD_DIR/$REL_PATH
# If .zst, update destination to .ko
if [[ "$DEST" == *.zst ]]; then
DEST=${DEST%.zst}
fi
if [ -e "$DEST" ]; then
return
fi
# Create directory
mkdir -p $(dirname $DEST)
# Copy and decompress if needed
if [[ "$MOD_PATH" == *.zst ]]; then
echo "Copying and decompressing $MOD..."
zstd -d -c "$MOD_PATH" > "$DEST"
else
echo "Copying $MOD..."
cp "$MOD_PATH" "$DEST"
fi
# Recursively copy dependencies
local DEPS=$(modinfo -k $KERNEL_VER -F depends "$MOD_PATH" 2>/dev/null | tr ',' ' ')
for DEP in $DEPS; do
copy_module $DEP
done
}
script/phases/70_image/090_initramfs.sh, lines 413–464
copy_module NAME does for one module what copy_closure does for a program:
- A name listed in
modules.builtinis part of the kernel image and has nothing to copy. modinfo -k <version> -nprints the module’s file. Whenmodinfogives nothing, or answers(builtin),findlooks forNAME.ko*instead.- A module not found at all is a warning, and the list goes on.
- The file keeps its path relative to
/lib/modules/<version>. A.ko.zstis decompressed on the way in and stored as.ko; anything else is copied as it is. modinfo -F dependslists the modules it needs, and each is copied by the same function. A module already in the tree ends the recursion.
The module list
# Core Modules for Booting (Storage, FS, Input, etc.)
MODULES="overlay squashfs isofs cdrom sr_mod loop sd_mod ata_piix ahci libahci virtio virtio_blk virtio_pci virtio_scsi xhci-pci xhci-hcd ehci-pci ehci-hcd ohci-pci ohci-hcd usb-storage uas"
# Every disk transport the installer classifies and installs to must be
# reachable before the root mounts, or the installed root is not found on its
# first boot. NVMe behind Intel VMD (RST), eMMC and SD (mmc), Hyper-V, Xen
# and VMware guests' disks, and the MegaRAID and mpt3sas controllers are all
# modules on this kernel; copy_module brings mmc_core, hv_vmbus and the rest
# of each one's dependencies.
MODULES="$MODULES vmd mmc_block sdhci-pci sdhci-acpi cqhci rtsx_pci_sdmmc hv_storvsc xen-blkfront vmw_pvscsi megaraid_sas mpt3sas"
# vfat, so the initramfs can read the boot state off the ESP.
MODULES="$MODULES vfat nls_cp437 nls_iso8859-1"
# Root filesystems the installer can create. EVERY ROW OF ki_filesystems[] NOT
# BUILT INTO THE KERNEL MUST APPEAR HERE: the installer's table offers the
# choice, this makes it bootable, and a root the initramfs cannot mount
# installs perfectly and never boots again. f2fs is CONFIG_F2FS_FS=m; xfs is =y
# and its copy is a no-op, kept so a kernel with xfs as a module still boots.
MODULES="$MODULES xfs f2fs"
# dm-crypt and the ciphers a LUKS2 default header actually uses. Carried
# unconditionally: they are small, and a kernel that has them built in makes
# copy_module a no-op anyway. The generic AES, SHA-256 and SHA-512 code is
# built into this kernel and has no module to name.
MODULES="$MODULES dm-crypt dm-mod aesni-intel xts crypto_null algif_skcipher"
# Software RAID. A root ON an array needs these before anything can be
# assembled, and a machine whose DATA disks are an array needs them before
# udev settles — without md_mod the members are bare disks with a superblock
# nobody reads, which looks like an empty drive rather than a missing module.
# The personalities are listed individually because md_mod loads none of them.
MODULES="$MODULES md_mod raid0 raid1 raid10 raid456 dm-raid"
# The device-mapper targets an LVM root can be built from beyond the linear one
# dm-mod has built in: a thin volume, a cached or write-cached one, and a
# snapshot. A group holding any of them activates only with its target loaded,
# and the init loads these before its first vgchange -- lvm2's own modprobe
# path is whatever its configure found at build time, not one this initramfs
# is known to have.
MODULES="$MODULES dm-snapshot dm-thin-pool dm-cache dm-cache-smq dm-writecache"
for MOD in $MODULES; do
copy_module $MOD
done
script/phases/70_image/090_initramfs.sh, lines 466–505
The list grows in groups: the live medium’s needs (overlay, squashfs, isofs, the CD drive and loop) with the common storage controllers and USB storage, the disk transports the installer can install to, vfat and its two code pages for the ESP, the root filesystems the installer offers beyond ext4 and btrfs (xfs and f2fs), device-mapper and the LUKS ciphers, software RAID, and the device-mapper targets an LVM root can use. This kernel builds ext4, btrfs and xfs in and f2fs as a module, so of the two only f2fs is copied; xfs stays in the list so that a kernel with xfs as a module still boots an xfs root. Why each group is there is in The initramfs.
A name in the list that is built into the kernel costs nothing, so the list names what a boot needs rather than what this kernel happens to build as modules. Two other parts of the tree have to agree with it. Every root filesystem ki_filesystems[] in the installer offers must be in it, and testing/preflight.sh checks that, with ext4 and btrfs exempt; xfs is held to the list although this kernel builds it in. And modprobe in init loads modules by these names, so a module init asks for must be in the list to be in the tree at all.
The list on the image, and the module index
# The same list, kept on the image beside the initramfs it describes. A kernel
# installed later has none of these modules in this initramfs, and the linux
# package's postinstall reads this file to carry the new kernel's copies of
# exactly this set; a second copy of the list there would be the one that
# goes stale.
printf '%s\n' $MODULES > /boot/initramfs.modules
# Copy modules.order and modules.builtin for depmod
cp /lib/modules/$KERNEL_VER/modules.order $MOD_DIR/
cp /lib/modules/$KERNEL_VER/modules.builtin $MOD_DIR/
if [ -f /lib/modules/$KERNEL_VER/modules.builtin.modinfo ]; then
cp /lib/modules/$KERNEL_VER/modules.builtin.modinfo $MOD_DIR/
fi
# Regenerate module dependencies for the initramfs. The symbol map is read
# where the kernel installed it; the initramfs does not carry it.
echo "Generating dependency map..."
if [ -f /boot/System.map-$KERNEL_VER ]; then
depmod -b . -F /boot/System.map-$KERNEL_VER $KERNEL_VER
else
depmod -b . $KERNEL_VER
fi
script/phases/70_image/090_initramfs.sh, lines 507–528
The list is written to /boot/initramfs.modules in the root, one name per line. The linux port’s postinstall.sh reads it when a later kernel is installed and builds that kernel’s initramfs from the same set; see A new kernel.
modules.order and modules.builtin are copied beside the modules, with modules.builtin.modinfo when the kernel has one, and then depmod -b . writes the initramfs’s own modules.dep and indexes, for the modules it holds and nothing else. When /boot/System.map-<version> exists, -F names it, read where the kernel installed it; the tree does not carry the map. depmod’s manual describes the map as what -e checks modules’ symbols against, and this call passes no -e.
The init script
# Create Init Script
cat > init <<EOF
#!/bin/bash
export PATH=/bin
script/phases/70_image/090_initramfs.sh, lines 530–533
init is written by cat from a here-document that ends at the EOF line below. The delimiter is not quoted, so the shell expands $ and backquotes inside it while the step runs. Every $ that belongs to init is therefore written \$, and every backquote \`: \$ROOT_UUID in the step becomes $ROOT_UUID in the file. None is left unescaped, so nothing from the build’s environment reaches the script. The next chapter shows it piece by piece as it stands in the step, backslashes included. build/initramfs/init is the same text with those escapes undone, and with every line that ends in a backslash joined to the next one, which an unquoted here-document also does.
EOF
chmod +x init
script/phases/70_image/090_initramfs.sh, lines 1605–1606
Microcode
# ---------------------------------------------------------------------------
# CPU microcode
# ---------------------------------------------------------------------------
# The early loader runs before the initramfs is decompressed and before any
# filesystem exists: it scans the raw initrd image for the literal paths
# kernel/x86/microcode/{GenuineIntel,AuthenticAMD}.bin. Three consequences,
# and getting any one wrong means the microcode is silently never applied:
#
# - this cpio must NOT be compressed, and the blobs inside it must not be
# either, whatever form linux-firmware ships them in: the early loader
# cannot decompress. A `.bin` is copied as it is and a `.bin.zst` is
# expanded on the way in.
# - it must come FIRST in the file, ahead of the gzipped part.
# - CONFIG_MICROCODE_LATE_LOADING is off, so this is the only path there is.
# /usr/lib/firmware/intel-ucode.bin is never read at runtime.
#
# A vendor whose microcode is installed and yields an empty file stops the
# build. An initramfs without microcode boots with no symptom, so nothing
# later would notice.
UCODE=/kdos/build/ucode
rm -rf $UCODE
mkdir -p $UCODE/kernel/x86/microcode
if [ -f /usr/lib/firmware/intel-ucode.bin ]; then
cp /usr/lib/firmware/intel-ucode.bin \
$UCODE/kernel/x86/microcode/GenuineIntel.bin
if [ ! -s $UCODE/kernel/x86/microcode/GenuineIntel.bin ]; then
echo "FATAL: /usr/lib/firmware/intel-ucode.bin is empty." >&2
exit 1
fi
echo "Microcode: Intel bundle carried"
elif [ -f /var/lib/kpkg/db/intel-ucode ]; then
echo "FATAL: intel-ucode is installed but /usr/lib/firmware/intel-ucode.bin is not." >&2
exit 1
else
echo "Microcode: no intel-ucode.bin — Intel CPUs will run BIOS microcode"
fi
script/phases/70_image/090_initramfs.sh, lines 1608–1644
The processor’s early microcode loader runs before the kernel unpacks anything, and reads two literal paths from the start of the initrd as it is in memory. Those paths are built here in a tree of their own, build/ucode. The Intel file is the bundle the intel-ucode port builds, copied under the name the loader wants. An empty bundle stops the step, and so does an installed intel-ucode package with no bundle; with neither, Intel processors keep the microcode their firmware loaded, and the step says so.
# One AMD container per family, concatenated in the order the shell sorts them;
# the loader walks the containers and matches on the equivalence table.
if [ -d /usr/lib/firmware/amd-ucode ]; then
for BLOB in /usr/lib/firmware/amd-ucode/microcode_amd*.bin \
/usr/lib/firmware/amd-ucode/microcode_amd*.bin.zst; do
[ -f "$BLOB" ] || continue
case "$BLOB" in
*.zst) zstd -d -c "$BLOB" >> $UCODE/kernel/x86/microcode/AuthenticAMD.bin ;;
*) cat "$BLOB" >> $UCODE/kernel/x86/microcode/AuthenticAMD.bin ;;
esac
done
if [ ! -s $UCODE/kernel/x86/microcode/AuthenticAMD.bin ]; then
echo "FATAL: /usr/lib/firmware/amd-ucode/ holds no microcode_amd*.bin or .bin.zst" >&2
echo " container, so AMD CPUs would run BIOS microcode." >&2
exit 1
fi
echo "Microcode: AMD containers carried"
else
echo "Microcode: no amd-ucode/ — AMD CPUs will run BIOS microcode"
fi
UCODE_CPIO=/kdos/build/ucode.cpio
rm -f $UCODE_CPIO
if [ -n "$(ls -A $UCODE/kernel/x86/microcode)" ]; then
( cd $UCODE && find . | LC_ALL=C sort | cpio -o -H newc --reproducible ) \
> $UCODE_CPIO 2>/dev/null
fi
script/phases/70_image/090_initramfs.sh, lines 1646–1672
The AMD containers come from firmware-amd, one per processor family, and are concatenated into one file in the order the shell’s glob sorts them. A .bin.zst is expanded first, because the early loader cannot decompress. A directory that yields an empty file stops the step. The microcode tree is then packed as a cpio archive of its own, uncompressed, and only when at least one vendor’s file is in it. Why the archive must be uncompressed and first is in Microcode.
The udev check
# EVERY UDEV RULE CARRIED HERE CAN RUN WHAT IT NAMES. The rules and helpers
# above are the root's whole set, and a rule whose program is absent makes
# udevd log "failed to execute" for every device it matches. Nothing is lost
# by leaving one out: the root's udev replays every rule once it starts.
#
# A helper first: one that links a library this tree does not carry (libmtp,
# libinput's, libgpod's) exists and fails at every event, so it goes. Then a
# rules file any of whose RUN, PROGRAM or IMPORT{program} keys names a
# program the tree lacks -- an absolute path, or a bare name, which udevd
# runs from /usr/lib/udev -- goes whole: removing lines would leave its
# GOTOs and LABELs unbalanced.
#
# THE RULES THAT ASSEMBLE A ROOT MUST STAY, or the build stops. device-mapper
# (10-dm, 11-dm-lvm, 13-dm-disk, 95-dm-notify) is what LUKS and LVM wait on;
# md's assemble an array; 64-btrfs completes a multi-device btrfs; and
# 60-persistent-storage makes /dev/disk/by-*. Each is required only when the
# root has it, and one that names a missing program is a program this step
# failed to carry.
for _f in lib/udev/*; do
[ -f "$_f" ] && [ ! -L "$_f" ] || continue
for _l in $(needed_libs "$_f" 2>/dev/null); do
if [ ! -e "lib/$_l" ]; then
echo "Note: udev helper ${_f##*/} needs $_l, which the initramfs does not carry — left out"
rm -f "$_f"
break
fi
done
done
_required=" 10-dm 11-dm-lvm 13-dm-disk 95-dm-notify 63-md-raid-arrays 64-md-raid-assembly 64-btrfs 60-persistent-storage "
for _r in lib/udev/rules.d/*.rules etc/udev/rules.d/*.rules; do
[ -f "$_r" ] || continue
for _p in $(grep -v '^[[:space:]]*#' "$_r" \
| grep -oE '(RUN(\{program\})?|PROGRAM|IMPORT\{program\})[+:]?==?"[^"]*"' \
| sed 's/^[^"]*"[[:space:]]*//; s/[[:space:]].*//; s/"$//' | sort -u); do
case "$_p" in
/*) _t=".$_p" ;;
*[!A-Za-z0-9_.-]*) continue ;;
*) _t="lib/udev/$_p" ;;
esac
[ -e "$_t" ] && continue
_b=${_r##*/}
case "$_required" in
*" ${_b%.rules} "*)
echo "FATAL: the udev rule $_r runs $_p, which the initramfs does not carry." >&2
echo " A root that needs this rule could not be assembled." >&2
exit 1
;;
esac
echo "Note: udev rule $_b runs $_p, which the initramfs does not carry — left out"
rm -f "$_r"
break
done
done
for _r in $_required; do
if [ -f /usr/lib/udev/rules.d/$_r.rules ] && [ ! -f lib/udev/rules.d/$_r.rules ]; then
echo "FATAL: the udev rule $_r.rules is on the root and not in the initramfs." >&2
exit 1
fi
done
unset _f _l _r _p _t _b _required
script/phases/70_image/090_initramfs.sh, lines 1674–1733
A rule whose program is absent costs nothing in function, since the root’s /etc/init.d/01_udev.sh replays every rule, but udevd logs failed to execute for every device the rule matches, early in every boot. So the step keeps only what can run:
- A helper in
lib/udevis read with the sameneeded_libsas the closure check below, and goes when a library it names is not inlib/, asmtp-probe(libmtp) and libinput’s and libgpod’s helpers do. - Each rules file’s
RUN,PROGRAMandIMPORT{program}values are cut down to their first word. An absolute path is looked up in the tree through the links above, a bare name inlib/udev, and anything else (a$env{}or a%substitution) is passed over. - The first program that is not there removes the whole rules file, with a
Note:line naming both. The whole file goes, because removing single lines would leave itsGOTOs andLABELs unbalanced.
Eight files in _required are the ones a root’s assembly waits on: the device-mapper rules (10-dm, 11-dm-lvm, 13-dm-disk, 95-dm-notify), md’s two (63-md-raid-arrays, 64-md-raid-assembly), 64-btrfs and 60-persistent-storage. If one of them would be removed, or is on the root and not in the initramfs, the step stops.
The closure check
# EVERY PROGRAM'S LIBRARIES ARE HERE, or the initramfs is not built. NEEDED is
# read with the reader proven above, without loading anything, for each
# program in bin/ and usr/sbin/ and each library in lib/. A file that is not
# ELF -- a script -- names nothing. A missing one is an init that cannot exec -- the kernel
# panics with "Attempted to kill init" -- or a tool that says "not found" at
# the one moment it is needed.
_missing=""
for _f in bin/* usr/sbin/* lib/*.so*; do
[ -f "$_f" ] && [ ! -L "$_f" ] || continue
for _l in $($READELF -d "$_f" 2>/dev/null | sed -n 's/.*(NEEDED).*\[\(.*\)\]/\1/p'); do
[ -e "lib/$_l" ] || _missing="$_missing $_f:$_l"
done
done
if [ -n "$_missing" ]; then
echo "FATAL: the initramfs is missing libraries its programs need:" >&2
for _m in $_missing; do echo " $_m" >&2; done
exit 1
fi
unset _missing _f _l _m
script/phases/70_image/090_initramfs.sh, lines 1735–1753
This is the check every hand-written list above relies on. Every regular file in bin/ and usr/sbin/, and every shared library in lib/, is read with the reader proven at the start, and every library it names must be in lib/. Links are skipped, because their targets are read under their own names; a file that is not an ELF binary, such as a script, prints no NEEDED lines and passes. Any gap stops the step with one line per program and library, in the form bin/cryptsetup:libjson-c.so.5.
Packing
# Pack Initramfs
find . | LC_ALL=C sort | cpio -o -H newc --reproducible | gzip -9 > ../initramfs.gz.part
if [ -s "$UCODE_CPIO" ]; then
cat $UCODE_CPIO ../initramfs.gz.part > ../initramfs.cpio.gz
else
mv ../initramfs.gz.part ../initramfs.cpio.gz
fi
rm -f ../initramfs.gz.part
echo "Initramfs created at $INITRAMFS"
script/phases/70_image/090_initramfs.sh, lines 1755–1763
The tree is listed with find, sorted byte by byte so that the order does not depend on the filesystem, and written by cpio in copy-out mode (-o) in the newc format, the one the kernel unpacks. --reproducible is GNU cpio’s alias for --device-independent: it records no number for the device a file is stored on, numbers the inodes in archive order from 0, and records every directory with a link count of 2, so the archive does not depend on the filesystem the tree sits on. It keeps each file’s modification time. gzip -9 compresses it; reading from a pipe, gzip writes zero in its header’s time field and stores no file name.
The finished build/initramfs.cpio.gz is the microcode archive followed by the gzipped one, or the gzipped one alone when there is no microcode. Despite its name, then, it starts with a plain cpio archive. The kernel unpacks the two one after the other.
Contents of the initramfs
Programs in bin/: bash (and sh), the GNU programs cat, chmod, cut, ls, mkdir, mknod, seq, sleep, cp, mv, rm, ln, rmdir, head, tail, wc, stat, df, dd, sync, uname, readlink, touch, basename, sort, tr, grep and sed; util-linux’s switch_root, mount, umount, losetup, dmesg, setsid and blkid; udevd, udevadm and kmod (as modprobe, insmod and depmod); kbd’s loadkeys; and, each when its package is installed, kdos-splash, e2fsck, kdos-bootctl, cryptsetup, and links to mdadm, lvm and dmsetup.
Programs in usr/sbin/: blkid as a link to bin/blkid; when mdadm is installed, mdadm; when lvm2 is installed, lvm, dmsetup, thin-provisioning-tools’ pdata_tools, and thin_check and cache_check as links to it.
Links: usr/bin and sbin to bin, and usr/lib/udev to lib/udev.
Other files: init; lib/ with musl and every library above; lib/udev/ with the rules and helpers that passed the udev check; lib/modules/<version>/ with the modules and their index; etc/passwd, etc/group, etc/udev/rules.d/ and, with lvm2, etc/lvm/lvm.conf; usr/share/kdos/splash.psf with the splash; usr/share/keymaps/ with kbd’s console maps.
See also
- The initramfs init: the script this chapter writes, stage by stage
- The ISO: where
initramfs.cpio.gzgoes next - The initramfs: what it carries and why
- Microcode: the early loader’s rules
- Tools that must be util-linux’s
- A new kernel: how an installed machine rebuilds it