Skip to content

Instantly share code, notes, and snippets.

@TheArchitectEngineer
Forked from afmiguez/wsl-kvm.sh
Last active May 19, 2024 23:16
Show Gist options
  • Save TheArchitectEngineer/20d06463ee1f3b8a764fb0da1a3955b8 to your computer and use it in GitHub Desktop.
Save TheArchitectEngineer/20d06463ee1f3b8a764fb0da1a3955b8 to your computer and use it in GitHub Desktop.
KVM in WSL2
#!/bin/bash
# Fork & Edited from https://gist.github.com/afmiguez/44c50ea146ea27f94f0696664afc8128
# Fully based on https://boxofcables.dev/kvm-optimized-custom-kernel-wsl2-2022/
if [ -z "$1" ]
then
echo "Must supply your Windows 11 username"
exit
fi
WIN_USERNAME=$1
# Install Build Dependencies
sudo apt update && sudo apt -y upgrade
sudo apt -y install build-essential libncurses-dev bison flex libssl-dev libelf-dev cpu-checker qemu-kvm aria2
# Change to Home Directory
cd $HOME
# Get the Microsoft WSL 2 Kernel Sources
curl -s https://api.github.com/repos/microsoft/WSL2-Linux-Kernel/releases/latest | jq -r '.name' | sed 's/$/.tar.gz/' | sed 's#^#https://github.com/microsoft/WSL2-Linux-Kernel/archive/refs/tags/#' | aria2c -i -
# Extract the Microsoft WSL 2 Kernel Sources
tar -xf *.tar.gz
# Change to the Kernel Directory
cd "$(find -type d -name "WSL2-Linux-Kernel-linux-msft-wsl-*")"
# Copy the default Microsoft Kernel Configuration
cp ./Microsoft/config-wsl .config
# Tweak the Default Microsoft Kernel Configuration for KVM Guests
sed -i 's/# CONFIG_KVM_GUEST is not set/CONFIG_KVM_GUEST=y/g' .config
sed -i 's/# CONFIG_ARCH_CPUIDLE_HALTPOLL is not set/CONFIG_ARCH_CPUIDLE_HALTPOLL=y/g' .config
sed -i 's/# CONFIG_HYPERV_IOMMU is not set/CONFIG_HYPERV_IOMMU=y/g' .config
sed -i '/^# CONFIG_PARAVIRT_TIME_ACCOUNTING is not set/a CONFIG_PARAVIRT_CLOCK=y' .config
sed -i '/^# CONFIG_CPU_IDLE_GOV_TEO is not set/a CONFIG_CPU_IDLE_GOV_HALTPOLL=y' .config
sed -i '/^CONFIG_CPU_IDLE_GOV_HALTPOLL=y/a CONFIG_HALTPOLL_CPUIDLE=y' .config
sed -i 's/CONFIG_HAVE_ARCH_KCSAN=y/CONFIG_HAVE_ARCH_KCSAN=n/g' .config
sed -i '/^CONFIG_HAVE_ARCH_KCSAN=n/a CONFIG_KCSAN=n' .config
# Build the Kernel
make -j 8
# Copy the Built Kernel to your Windows User's Home Folder
powershell.exe /C 'Copy-Item .\arch\x86\boot\bzImage $env:USERPROFILE'
# Point to your custom kernel in .wslconfig
powershell.exe /C 'Write-Output [wsl2]`nkernel=$env:USERPROFILE\bzImage | % {$_.replace("\","\\")} | Out-File $env:USERPROFILE\.wslconfig -encoding ASCII'
# Echo .wslconfig
cat /mnt/c/Users/$WIN_USERNAME/.wslconfig
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment