Replacing the WSL Kernel

Backstory

I had a dual boot Windows/Fedora machine, and I wanted to be able to run the Fedora install as a VM inside WSL.  To do this, I needed the physical disk accessible from the WSL kernel.  Since the WSL kernel has no access to physical hardware like that, I wanted to try using a nbd server on Windows and a nbd client on Linux.

Does the default WSL kernel support nbd?

$ zgrep NBD /proc/config.gz
# CONFIG_BLK_DEV_NBD is not set

The answer is no, it does not.  You can, however, use your own kernel.

Prep work

Use git to check out this repo: https://github.com/microsoft/WSL2-Linux-Kernel

I'm using the linux-msft-4.19.128 tag, but it looks like there's a 5.4.x branch as well. That repo has a file README-Microsoft.WSL2 with details on what packages are needed. They have their default config in Microsoft/config-wsl, which I turned on NBD support.

gcc version

I had tried compiling 4.19.121 on a system with gcc 10.2.1, and that got me a kernel that wouldn't boot.  Looks like 4.19.124 has some fixes for gcc 10.  Building with gcc 9.3.0 worked.

Building the kernel

make -j4 KCONFIG_CONFIG=Microsoft/config-wsl

This will produce the kernel (we need the vmlinux file) and modules.  You can change the 4 to match the number of cores you have.

Installing the kernel

I put the kernel on my Windows partition:

mkdir /mnt/c/Users/myuser/kernel
cp vmlinux /mnt/c/Users/myuser/kernel/vmlinux-4.19.128

And then I set the wsl config file to use it:

c:\Users\myuser\.wslconfig

[wsl2]
kernel=C:\\users\\myuser\\kernel\\vmlinux-4.19.128

The kernel path does need double \\

Running the kernel

I shutdown my WSL VMs with "wsl --shutdown", and then started them with the new kernel.

C:\Users\myuser>wsl cat /proc/version
Linux version 4.19.128-microsoft-standard+ (myuser@wsl) (gcc version 9.3.0 (Ubuntu 9.3.0-10ubuntu2)) #3 SMP Fri Aug 28 01:10:03 CDT 2020

And now it has nbd support!

$ zgrep NBD /proc/config.gz
CONFIG_BLK_DEV_NBD=y

Final thoughts

I had hoped to use cygwin to run nbd-server on Windows, but cygwin's pread does not work against physical drives, only files.

If you make your own kernel, remember to keep it up to date.