This post covers installing Gentoo on a Raspberry Pi 4B.

I recently bought a Raspberry Pi 4B. After two days with the stock OS I still wasn’t used to it, and I wanted Gentoo anyway. I’d installed it on a Pi 3 before, and as a desktop the performance really was poor; this time I’m using it as an arm64 binhost, so desktop performance doesn’t matter much.

There was no other ARM machine at hand and no monitor to connect, so I cross-compiled from my x86_64 workstation.

Crossdev

I had no other ARM machines and no monitor that would work with the Pi, so I went in blind and decided to use the workstation as the cross-compile host for the Pi. The workstation runs Gentoo, which is very well suited to this. First install crossdev:

emerge crossdev

Make sure /etc/portage/package.env is a directory rather than a file. Create the cross-compile toolchain:

crossdev -t aarch64-unknown-linux-gnu

After it finishes, check with gcc-config -l. The output looks like this:

 [1] aarch64-unknown-linux-gnu-10.2.0 *

 [2] x86_64-pc-linux-gnu-8.4.0
 [3] x86_64-pc-linux-gnu-10.2.0 *

That means it’s installed.

QEMU-USER

Besides crossdev, QEMU also needs configuring for the cross-compiles and the chroot later. Add the targets:

echo 'QEMU_SOFTMMU_TARGETS="alpha aarch64 arm i386 mips mips64 mips64el mipsel ppc ppc64 s390x sh4 sh4eb sparc sparc64 x86_64"' >> /etc/portage/make.conf
echo 'QEMU_USER_TARGETS="alpha aarch64 arm armeb i386 mips mipsel ppc ppc64 ppc64abi32 s390x sh4 sh4eb sparc sparc32plus sparc64"' >> /etc/portage/make.conf

Make sure QEMU has the static-user USE flag enabled:

USE=static-user emerge app-emulation/qemu

Or write it into package.use and install:

echo 'app-emulation/qemu static-user' >> /etc/portage/package.use/qemu
emerge -av app-emulation/qemu

Build a binary package of QEMU (needed for the chroot later):

quickpkg app-emulation/qemu

Make sure your kernel has the CONFIG_BINFMT_MISC option enabled (module or built-in). Load binfmt_misc:

[ -d /proc/sys/fs/binfmt_misc ] || modprobe binfmt_misc
[ -f /proc/sys/fs/binfmt_misc/register ] || mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc   

Register the handler (only aarch64 is needed here):

echo ':aarch64:M::\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\xb7:\xff\xff\xff\xff\xff\xff\xff\xfc\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff:/usr/bin/qemu-aarch64:' > /proc/sys/fs/binfmt_misc/register

Start binfmt:

/etc/init.d/qemu-binfmt start

If you use it often, add it to the boot runlevel:

rc-update add qemu-binfmt default

Preparing the Disk

Put the storage card into a reader and plug it into the computer. First confirm the device name (it’s /dev/sdd here; yours may differ):

lsblk

Create two partitions:

Partition Size Purpose
/dev/sdd1 250M /boot, vfat
/dev/sdd2 Rest of the card /, ext4

Format /boot:

mkfs -t vfat -F 32 /dev/sdd1

Format /. -i 8192 makes the inodes denser; Gentoo has a lot of files, inodes run out quickly, and this value can’t be changed once the filesystem is created:

mkfs -i 8192 -t ext4 /dev/sdd2

Mounting the Partitions

Create the mount point:

mkdir -pv /mnt/gentoo

Mount /:

mount /dev/sdd2 /mnt/gentoo

Create the boot mount point:

mkdir -pv /mnt/gentoo/boot

Mount the boot partition:

mount /dev/sdd1 /mnt/gentoo/boot

Configuring the Kernel

Create a working directory:

mkdir $HOME/raspberrypi && cd $HOME/raspberrypi

Clone the firmware:

git clone -b stable --depth=1 https://github.com/raspberrypi/firmware

And the Linux source:

git clone --depth=1 https://github.com/raspberrypi/linux

Configure the Linux kernel (go into the Linux kernel directory first):

cd linux

List the available kernel branches:

git branch -a

When I cloned it, only rpi-5.4.y was there:

git checkout rpi-5.4.y

5.4 is fairly old now; a newer branch such as rpi-6.6.y or the current stable branch is a better choice. Generate the default config:

ARCH=arm64 CROSS_COMPILE=aarch64-unknown-linux-gnu-  make bcm2711_defconfig

Configure (I’d change the default CPU governor to performance here, otherwise this weak little CPU really is slow):

ARCH=arm64 CROSS_COMPILE=aarch64-unknown-linux-gnu- make menuconfig

Build the kernel:

ARCH=arm64 CROSS_COMPILE=aarch64-unknown-linux-gnu- make -j12

Installing the stage3 Tarball

At this point the stage3 tarball can be downloaded. Get the latest arm64 stage3 from the official site, e.g.:

MIRRORS='https://bouncer.gentoo.org/fetch/root/all/releases/arm64/autobuilds'
ZIPFILENAME=`curl -L $MIRRORS/latest-stage3.txt |grep ^[0-9] |awk -F '[/ ]'  '{if (NR==1) {print $2}}'`
FILENAME=`curl -L $MIRRORS/latest-stage3.txt  2>/dev/null |grep ^[0-9]|awk '{if (NR==1) {print $1}}'`
FILEURL="$MIRRORS/$FILENAME"
wget -O /mnt/gentoo/$ZIPFILENAME $FILEURL > /tmp/download.log

Extract stage3:

cd /mnt/gentoo
tar xpvf stage3-*.tar.xz --xattrs-include='*.*' --numeric-owner

Installing the Kernel

Copy the firmware to boot:

cp -rv $HOME/raspberrypi/firmware/boot/* /mnt/gentoo/boot

Some of it isn’t needed and can be deleted by hand. Install the kernel:

cp -v $HOME/raspberrypi/linux/arch/arm64/boot/Image /mnt/gentoo/boot/kernel8.img

Install the kernel modules:

cd $HOME/raspberrypi/linux
ARCH=arm64 CROSS_COMPILE=aarch64-unknown-linux-gnu- make modules_install INSTALL_MOD_PATH=/mnt/gentoo

Entering the chroot

Copy the DNS config and mount the required filesystems:

cp -v -L /etc/resolv.conf /mnt/gentoo/etc/
mount -v -t proc none /mnt/gentoo/proc
mount -v --rbind /sys /mnt/gentoo/sys
mount -v --rbind /dev /mnt/gentoo/dev
mount -v --make-rslave /mnt/gentoo/sys
mount -v --make-rslave /mnt/gentoo/dev

Enter the chroot:

chroot /mnt/gentoo /bin/bash
source /etc/profile
export PS1="(chroot) $PS1"

fstab

Edit /etc/fstab and append the following:

/dev/mmcblk0p1          /boot           vfat            noauto,noatime  1 2
/dev/mmcblk0p2          /               ext4            noatime         0 1

Configuring the System

Edit /boot/config.txt:

# have a properly sized image
disable_overscan=1
arm_64bit=1
enable_gic=1
# VC4 hardware acceleration; older kernels use vc4-fkms-v3d, newer ones use vc4-kms-v3d
# a headless binhost can leave this line out
dtoverlay=vc4-fkms-v3d
# for sound over HDMI
hdmi_drive=2
# Enable audio (loads snd_bcm2835)
dtparam=audio=on
# gpu_mem is for closed-source driver only; since we are only using the
# open-source driver here, set low
gpu_mem=16

Edit /boot/cmdline.txt:

root=/dev/mmcblk0p2 rootfstype=ext4 fsck.repair=yes rootwait

The elevator=deadline from older guides has been removed from the kernel; newer kernels don’t need it. Edit /etc/portage/make.conf with the following contents:

# detailed example.
COMMON_FLAGS="-march=armv8-a+crc+simd -mtune=cortex-a72 -ftree-vectorize -O2 -pipe -fomit-frame-pointer"
CFLAGS="${COMMON_FLAGS}"
CXXFLAGS="${COMMON_FLAGS}"
FCFLAGS="${COMMON_FLAGS}"
FFLAGS="${COMMON_FLAGS}"
MAKEOPTS="-j6"

# per https://wiki.gentoo.org/wiki/Raspberry_Pi_VC4
VIDEO_CARDS="fbdev vc4"
INPUT_DEVICES="evdev synaptics wacom"


PORTAGE_BUILDDIR="/var/tmp/portage"
GENTOO_MIRRORS="https://mirrors.tuna.tsinghua.edu.cn/gentoo"

L10N="en-US zh-CN en zh"
LINGUAS="en_US zh_CN en zh"
#FEATURES="-pid-sandbox"

ACCEPT_LICENSE="*"

ACCEPT_KEYWORDS="~arm64"
# WARNING: Changing your CHOST is not something that should be done lightly.
# Please consult https://wiki.gentoo.org/wiki/Changing_the_CHOST_variable before changing.
CHOST="aarch64-unknown-linux-gnu"

# NOTE: This stage was built with the bindist Use flag enabled
DISTDIR="/var/cache/distfiles"
PKGDIR="/var/cache/binpkgs"

# This sets the language of build output to English.
# Please keep this setting intact when reporting bugs.
LC_MESSAGES=C

ACCEPT_KEYWORDS="~arm64" puts the whole dependency tree on testing. For something steadier, use ACCEPT_KEYWORDS="arm64" and enable testing only for the packages that really need it.

Set the root password:

passwd

Configure the upstream Gentoo repository. First create the repos.conf directory:

mkdir -pv /etc/portage/repos.conf/

Create and edit /etc/portage/repos.conf/gentoo.conf with the following contents:

[DEFAULT]
main-repo = gentoo

[gentoo]
location = /var/db/repos/gentoo
sync-type = git
sync-uri = https://github.com/gentoo-mirror/gentoo.git
auto-sync = yes

Updating the System

First pick a profile. List all the profiles:

eselect profile list
Available profile symlink targets:
  [1]   default/linux/arm64/17.0 (stable) *
  [2]   default/linux/arm64/17.0/desktop (stable)
  [3]   default/linux/arm64/17.0/desktop/gnome (stable)
  [4]   default/linux/arm64/17.0/desktop/gnome/systemd (stable)
  [5]   default/linux/arm64/17.0/desktop/plasma (stable)
  [6]   default/linux/arm64/17.0/desktop/plasma/systemd (stable)
  [7]   default/linux/arm64/17.0/desktop/systemd (stable)
  [8]   default/linux/arm64/17.0/developer (stable)
  [9]   default/linux/arm64/17.0/systemd (stable)
  [10]  default/linux/arm64/17.0/big-endian (exp)
  [11]  default/linux/arm64/17.0/musl (exp)
  [12]  default/linux/arm64/17.0/musl/hardened (exp)

Pick the first one (I’m not a systemd user):

eselect profile set 1

Update the system:

emerge -auvDN @world

This will throw QEMU errors, because QEMU doesn’t support pid-sandbox or network-sandbox. Turn both off for the update:

env FEATURES="-pid-sandbox -network-sandbox" emerge -auvDN @world 

Or add them to make.conf and run without env.

Network

My network setup isn’t complicated - just an Ethernet cable to a switch, no Wi-Fi - so installing a DHCP client is enough:

env FEATURES="-pid-sandbox -network-sandbox" emerge -av dhcpcd

Add it to the boot runlevel:

rc-update add dhcpcd default

User Management

For easier management, create an admin user here:

useradd --create-home --groups "wheel,portage" --shell /bin/bash --comment "chris" chris

Set the password:

passwd chris

If root login is needed, edit /etc/ssh/sshd_config. I’d allow keys only and leave password auth off:

PermitRootLogin prohibit-password

Add sshd to the boot runlevel:

rc-update add sshd default

For the admin user to be of any use, the sudo package is needed as well:

env FEATURES="-pid-sandbox -network-sandbox" emerge -av sudo

Edit /etc/sudoers with visudo and uncomment this line:

%wheel ALL=(ALL:ALL) ALL

Timezone

Set the timezone to Asia/Shanghai:

echo "Asia/Shanghai"  > /etc/timezone
emerge --ask sys-libs/timezone-data

Hostname

To make the Pi easier to find later, give it a hostname. Edit /etc/conf.d/hostname:

hostname="rpi4"

Locale

echo "en_US.UTF-8 UTF-8" > /etc/locale.gen
locale-gen

Wrapping Up

The basic Gentoo system is now installed. Exit the chroot, unmount the storage card, and boot the Pi:

exit

Unmount:

umount -R /mnt/gentoo && sync

Run sync, put the card into the Pi, boot it, and then look for its address in the DHCP leases.

References