# Cross-Compiling For The Raspberry Pi
## On The Pi
1. Load the existing configuration
```bash
sudo modprobe configs
```
2. Copy the configuration into a config
```bash
zcat /proc/config.gz > raspi.config
```
## On Host (Compiling) Machine
1. Download the kernel and toolchain in /home/$USER
```bash
git clone --depth 1 --single-branch --branch "rpi-5.4.y" https://github.com/raspberrypi/linux.git
git clone git://github.com/raspberrypi/tools.git
```
2. Verify the correct version
```bash
cd linux
head Makefile
```
3. Download the RT patch
```bash
wget https://www.kernel.org/pub/linux/kernel/projects/rt/5.4/patch-5.4.70-rt40.patch.gz
```
4. Apply the patch
```bash
zcat patch-5.4.70-rt40.patch.gz | patch -p1 > /home/evan/patch.log 2>&1
```
4. Copy raspi.config from the Pi to /home/$USER/linux on the host machine.
5. Build the kernel
```
./build_pi_kernel.sh
```
`build_pi_kernel.sh:`
```bash
#!/bin/bash
KERNEL_SRC=/home/$USER/linux
TOOL_SRC=/home/$USER/tools
export KERNEL_SRC
CCPREFIX=$TOOL_SRC/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/bin/arm-linux-gnueabihf-
# For 32-bit hosts:
# CCPREFIX=/home/$USER/tools/arm-bcm2708/arm-bcm2708hardfp-linux-gnueabi/bin/arm-bcm2708hardfp-linux-gnueabi-
export CCPREFIX
cd $KERNEL_SRC
make mrproper
cp $KERNEL_SRC/raspi.config .config
make ARCH=arm CROSS_COMPILE=${CCPREFIX} oldconfig
# this should be -jn where n is less than the number of
# threads your CPU is capable of (typically twice the
# number of cores)
make ARCH=arm CROSS_COMPILE=${CCPREFIX} -j8
make ARCH=arm CROSS_COMPILE=${CCPREFIX} modules -j8
make ARCH=arm CROSS_COMPILE=${CCPREFIX} INSTALL_MOD_PATH=~/pimodules modules_install
```
6. Copy the kernel to the Pi
> I recommend doing this by mounting the SD card on your host machine, alternatively you can use scp to copy the files and relocate them on the Pi.
**_BACK UP YOUR `/boot` PARTION PRIOR TO THIS STEP_**
```bash
#!/bin/bash
KERNEL_SRC="/home/$USER/linux"
# Verify these are the correct mountpoints on your machine!
BOOT_PARTION="/run/media/$USER/boot/"
ROOT_PARTION="/run/media/$USER/rootfs"
cd $BOOT_PARTION
cp "$KERNEL_SRC/arch/arm/boot/dts/*.dtb" ./
cp "$KERNEL_SRC/arch/arm/boot/dts/overlays/*.dtb*" ./overlays
cp "$KERNEL_SRC/arch/arm/boot/dts/overlays/README" ./overlays/
sudo cp -r '/home/$USER/pimodules/lib/modules/5.4.72-rt40-v7l+' "$ROOT_PARTION/lib/modules"
```