Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nanox/7ff02ee64eba4a0a174e895cf7291525 to your computer and use it in GitHub Desktop.
Save nanox/7ff02ee64eba4a0a174e895cf7291525 to your computer and use it in GitHub Desktop.
Build An Accelerated KVM Guest Custom Kernel for WSL 2

I'm not the author the blog post and this gist is a simply a note on my usage based on the original post, https://boxofcables.dev/kvm-optimized-custom-kernel-wsl2-2022/.

I also changed the code that extract the latest to a concrete linux kernel version.

First start with openSUSE Tumbleweed distro and commands below can be used to build the custom kernel and set it to be used for WSL2 distros.

# prepare build deps
sudo zypper -n up
# original from the post
sudo bash -c "zypper in -y -t pattern devel_basis && zypper in -y bc openssl openssl-devel dwarves rpm-build libelf-devel aria2 jq"
# what I ended up doing instead
sudo zypper install -y aria2 make gcc bison flex bc libelf-devel libopenssl-3-devel dwarves

# download and unpack kernel source code and cd into it
echo 'https://github.com/microsoft/WSL2-Linux-Kernel/archive/refs/tags/linux-msft-wsl-6.1.21.1.tar.gz' | aria2c -i -
tar -xf *.tar.gz
cd WSL2-Linux-Kernel-linux-msft-wsl-6.1.21.1/

# modify config
cp Microsoft/config-wsl .config
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 kernel
make -j 8

# move kernel to Windows host
powershell.exe /C 'Copy-Item .\arch\x86\boot\bzImage $env:USERPROFILE'
# print '$env:USERPROFILE\.wslconfig' just in case it existed before
cat /mnt/c/Users/$(powershell.exe '$env:USERNAME')/.wslconfig
# set kernel file path to '$env:USERPROFILE\.wslconfig'
powershell.exe /C 'Write-Output [wsl2]`nkernel=$env:USERPROFILE\bzImage | % {$_.replace("\","\\")} | Out-File $env:USERPROFILE\.wslconfig -encoding ASCII'
# verify the content
cat /mnt/c/Users/$(powershell.exe '$env:USERNAME')/.wslconfig

And now this built kernel be the kernel for all wsl distros not just for openSUSE one unless the setting gets reversed later.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment