initial ramdisk,它是一种将临时的根文件系统载入内存的方案,主要用于 Linux 的启动过程。也叫 early user space (早期用户空间),在 Linux kernel 2.5.46 引入。从出现至今存在以下两种方案:
initrd 在 Linux 引导过程中的作用
从根本上说:
其他次要的因素:
存储:initrd 镜像必须存储在 Linux bootloader 或引导固件可访问的位置,包括根文件系统本身、光盘上的引导镜像、本机磁盘上的小分区 (引导分区,一般为 ext2 或 FAT 文件系统) 等。
载入:bootloader 将载入内核和 initrd 镜像到内存,然后启动内核,并传递镜像的内存地址,内核检测镜像的格式,要么是 initrd,要么是 initramfs 方案。
initrd 通过特殊的块设备 (/dev/ram) 进行挂载,有些使用 ext2 文件系统镜像,有些使用 cramfs 镜像 (Debian)。内核执行其中的 /linuxrc 作为第一个进程,退出后执行 /sbin/init 开始正常的引导过程。
initramfs 镜像是 cpio 存档 (为节省空间可压缩),该存档由内核解包到特殊的 tmpfs 上。相比 initrd 的优势,不需要将中间文件系统或块驱动编译到内核中。内核执行 /init 作为第一个进程。
挂载准备:Debian 生成定制的 initrd 镜像,只包含必要的 ATA、SCSI、文件系统内核模块。Fedora、Ubuntu 生成更通用的 initrd 镜像。
mkdir --parents /usr/src/initramfs/{bin,dev,etc,lib,lib64,mnt/root,proc,root,sbin,sys}
cp --archive /dev/{null,console,tty,sda1} /usr/src/initramfs/dev/ # 设备节点
应用程序:拷贝想要在引导时执行的二进制程序及库,可用 busybox 替代。
编写 init 脚本:
#!/bin/busybox sh
# Mount the /proc and /sys filesystems.
mount -t proc none /proc
mount -t sysfs none /sys
# Do your stuff here.
echo "This script just mounts and boots the rootfs, nothing else!"
# Mount the root filesystem.
mount -o ro /dev/sda1 /mnt/root
# Clean up.
umount /proc
umount /sys
# Boot the real thing.
exec switch_root /mnt/root /sbin/init
find . -print0 | cpio --null --create --verbose --format=newc | gzip --best > /boot/custom-initramfs.cpio.gz
配置 GRUB:
initrd custom-initramfs.cpio.gz # /boot/grub/grub.cfg