Config/Compile Linux Kernel for WSL

前言

WSL可以吃customize的Linux Kernel, 所以可以自己config/compile WSL Kernel來用

參考資料

Preparation

packages for config/compile linux kernel

1
root@$> pacman -S base-devel

WSL2-Linux-Kernel

1
2
3
# 這裡假設你要抓6.1.y版,若要其他版本可以參考Github repo的branch name

root@> git clone https://github.com/microsoft/WSL2-Linux-Kernel.git --depth=1 -b linux-msft-wsl-6.1.y

Prepare current Kernel config file

雖然很多都會建議使用WSL2-Linux-Kernel repo內的Microsoft/config-wslconfig檔直接上,但是我自己測試的結果是那個config-wsl基本上是一大堆module定義的
你要就是把M全改成*或是你真的知道你需要哪些Module然後只選那些,不然就會像我一樣高高興興的換上customize kernel後發現沒有wireguard…然後暴死

所以我建議採用以下方式

1
2
3
4
5
root@$> zcat /proc/config.gz > .config(或任何你喜歡的config file name)

or

root@$> cat /proc/config.gz | gunzip > .config(或任何你喜歡的config file name)

用現在跑得好好的Kernel config file去作編輯

Configuration and Compile

Basic of Configuration

如同建議的一樣不要手動去編輯config file, 請用make menuconfig指令來進行

1
2
3
# 若config file name 是 .config的話不需要指定KCONFIG_CONFIG=

root@$> make menuconfig KCONFIG_CONFIG=./<config_file_name>

若有比較過兩種config檔案你會發現zcat來的檔案裡面全部都是*Microsoft/config-wsl裡面的都是M

Add TC/QoS module

基本上我得手動來製作customize kernel的原因,就是因為新的qemu package需要tc/Qos的功能而WSL的Kernel沒有所以才需要自己弄出來,所以加上
基本上就是把Networking support --> Network options --> QoS and/or fair queueing內的全部item都變成*就好了

如同下圖

<img src=“https://raw.githubusercontent.com/Kiwi0093/graph/master/img/螢幕擷取畫面 2025-01-08 112100.png” width=“900”) >

compile

設定好config檔save出來之後
就可以用以下指令compile

1
2
3
4
5
# 這個指令的意思是用所有的CPU去compile
root@$> make -j$(nproc) KCONFIG_CONFIG=<your_kernel_config_file>

# 當然你若知道有有多少核心可以用也可以指定數量,例如指定用16個核心去跑
root@$> make -j 16 KCONFIG_CONFIG=<your_kernel_config_file>

使用Customize Kernel

直接變成預設Kernel

好了之後的檔案會放在arch/x86/boot/bzImage你可以移動到你想要放的位置或是你有Windows administrator的權限也可以改名為kernel放在以下位置

C:\Windows\system32\lxss\tools\

這是WSL預設的Kernel檔名與放置位置,改名放在這裡基本上什麼設定都不用動, 不過得先把WSL shutdown才能放置所以只能在Windows下操作

不過我個人不建議,萬一你自己compile的東西有問題就慘了

使用Customize的設定

C:\Users\<your_username>\.wslconfig

這個檔案的設定要參考Advanced settings configuration in WSL
我自己會用的幾個如下

1
2
3
4
5
6
7
8
# Main WSL Setting Section
[wsl2]
# Nested Virtrualization 可以讓WSL跑hypervisor功能
nestedVirtualization=true
# Customize kernel Windows的\要用\\才會正確
kernel=C:\\Where\\is\\your\\kernel\\bzImage
# WSL的最大RAM使用量單位要用GB/MB
memory=XXGB