simple overlayfs init script

source code

#!/bin/sh

PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PATH

fallback() {
	exec /sbin/init
}

# if your kernel haven't mount devtmpfs at bootup you need uncomment this:
# mount -t devtmpfs devtmpfs /dev
# this program need get cmdline from /proc
# program mount use /proc to detect filesystem type
mount -t proc proc /proc

cmdline() {
	cmdline_list=$(cat /proc/cmdline)
	for i in ${cmdline_list}; do
		key="$(echo "${i}" | cut -d'=' -f1)"
		if [ "${1}" = "${key}" ]; then
			echo "${i}" | cut -d'=' -f2-
		fi
	done
}

timeout=$(cmdline overlay_timeout)
device=$(cmdline overlay_device)

if [ -z "${device}" ]; then
	fallback
fi

if [ -z "${timeout}" ]; then
	timeout=30
fi

while [ "${timeout}" -gt 0 ]
do
	if [ "${timeout}" -eq 0 ]; then
		fallback
	fi
	if mount "${device}" /mnt; then
		break;
	fi
	sleep 1
	timeout=$((timeout - 1))
done

mkdir  /mnt/upper
rm -rf /mnt/work # make directory empty
mkdir  /mnt/work
mkdir  /mnt/new
mount -t overlay overlay \
	-o lowerdir=/,upperdir=/mnt/upper,workdir=/mnt/work /mnt/new || fallback
mount -t devtmpfs devtmpfs /mnt/new/dev || fallback
exec chroot /mnt/new/ /sbin/init || fallback

how to use it

put it into your rootfs, then rename to ’ovinit’, then add execute perm

$EDITOR ovinit
chmod +x ovinit

you need tell kernel use this init script:

example with uboot:

setenv bootargs init=/ovinit root=/dev/mmcblk0p2 overlay_device=/dev/mmclk0p3 overlay_timeout=5
saveenv

Last updated: 2023-06-28