February 7, 2014

Linux switch_root vs pivot_root vs chroot

1. pivot_root can/should be used together with chroot
     
       pivot_root new_root put_old
       pivot_root moves the root file system of the current process to the
       directory put_old and makes new_root the new root file system.  

       cd new_root
       pivot_root . old-root
       exec chroot . command
       umount /old-root
Note that chroot must be available under the old root and under the new root, because pivot_root may or may not have implicitly changed the root directory of the shell.

2. switch_root newroot init [arg...]
       switch_root moves already mounted /proc, /dev and /sys to newroot and
       makes newroot the new root filesystem and starts init process. switch_root       is typically used with initramfs

       WARNING: switch_root removes recursively all files and directories on
       the current root filesystem.
     
The following shell script fragment demonstrates how to use switch_root:
  # 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

2 comments:

  1. Is switch_root can user for ubi file system

    ReplyDelete
  2. Thanks for this. The mount --move commands were the one thing I was missing! Now my initramfs boots my system without a hitch. :)

    ReplyDelete