Tuesday, 25 December 2012

What's that /boot/initramfs file?

Have you ever wondered how kernel mounts the root "/" filesystem? When I was learning Linux and Unix a few years ago, this question used to haunt me. Why? In order to load a filesystem, kernel needs to have the filesystem module loaded into memory. You can achieve this in two ways, either you compile in the filesystem module code along with the kernel i.e statically link it. Or, you can load the module dynamically when needed. The problem arises there. How is it possible for the Linux kernel to load many kernel modules even before mounting the root filesystem? (If you see dmesg, "mounting root filesystem" message appears towards the end). FYI, kernel modules are usuaally stored in /lib/modules/`uname -r`/ directory.

To solve this problem, Linux uses initram filesystem. Grub boot loader takes "initrd" argument along with the location of the iniramfs file. Grub has enough knowledge of the filesystems enabling it to find kernel, initramfs and config files from the /boot filesystem. But it does not yet support LVM or software RAID. That's why you don't get to see /boot partition on an LVM or software RAID.

Anyway, so grub takes the initramfs file, uncompresses it, and lays it out on the memory. Initraamfs contains enough modules and binaries to load the root filesystem modules. When control passes to the kernel, it sees the initramfs filesystem as it's root file system. It then executes /init (yes, it's not a typo) script on initramfs, which loads the modules required for mounting the root filesystem i.e modules for LVM/software RAID, filesystem. Once the root filesystem is mounted, the script chroots to it and the control is passed on to the /sbin/init program. From then onwards, you all know what happens.

Are you not feeling excited enough to see the contects of the initramfs filesystem? Yes, you can see the contents of it. Just execute the following commands:

mkdir /tmp/init
cp /boot/initramfs-`uname -r`.img /tmp/init/initramfs.gz
gunzip /tmp/init/initramfs.gz
cd /tmp/init
cpio -iv </tmp/init/initramfs

And explore the miniature root filesystem!! :)

No comments:

Post a Comment