Tuesday, January 31, 2023

How does Linux load rootfs

  • To load rootfs, you need a basic set of tools. How does the kernel bring them in? Initramfs
  • Initramfs is a RAM based FS that brings support for the basic things.  Command line to setup the kernel at start: vmlinuz initrd=initramfs.img root=/dev/sdaX
  • Moving from initramfs to rootfs: Initramfs does a pivot and switch to rootfs. (1) Move initramfs mountpoints to new rootfs mountpoints, (2) This initramfs contains the essential tools required to create and launch the rootfs. Final switch is done by: switch_root /newroot /bin/bash. Finally once the switch_root is done, run the init from the new rootfs.
Labels: switch_root, Linux, Kernel, rootfs, initramfs, build, systems, TLDR, summary

Code Snippet:
# First, find and mount the new filesystem.      mkdir /newroot    mount /dev/whatever /newroot      # Unmount everything else you've attached to rootfs.  (Moving the filesystems    # into newroot is something useful to do with them.)      mount --move /sys /newroot/sys    mount --move /proc /newroot/proc    mount --move /dev /newroot/dev      # Now switch to the new filesystem, and run /sbin/init out of it.  Don't    # forget the "exec" here, because you want the new init program to inherit    # PID 1.      exec switch_root /newroot /sbin/init