KFENCE (Kernel Electric-Fence) is a low-overhead Linux kernel tool that detects memory corruption in kernel code and modules and generates detailed error reports.
Alibaba Cloud Linux 3 enhances KFENCE with dynamic enable/disable, per-slab monitoring, and memory-aware pool sizing for both production and offline use.
When to use KFENCE
KFENCE trades memory for minimal CPU impact and supports two use cases:
Production monitoring: Enable sampling mode across your fleet. Given enough uptime, KFENCE catches bugs in code paths that test workloads rarely exercise. Consumes up to 2 MiB with negligible performance impact.
Offline debugging: Enable full mode to monitor all allocations for a specific slab type. Consumes GiB-level memory but catches every allocation in scope. Ideal for reproducing known issues.
Kernel and module developers can use KFENCE to detect memory corruption in their code. Users experiencing crashes can enable KFENCE to collect crash data for Alibaba Cloud or third-party driver developers.
Prerequisites
KFENCE requires Alibaba Cloud Linux 3 with the following minimum kernel versions:
Architecture | Minimum kernel version |
x86 |
|
Arm |
|
KFENCE vs. Kernel Address Sanitizer (KASAN)
Both are built-in Linux kernel memory corruption detectors. Alibaba Cloud enhanced KFENCE in kernel 5.10.
Dimension | KFENCE | KASAN |
Monitoring scope | Slabs up to 4 KiB (for example, | All slab types, page memory, stack memory, and global memory |
Detection rate | Higher success rate within monitoring range | -- |
Memory overhead | Higher | Lower |
Performance impact | Lower (suitable for production) | Higher (typically used in test environments) |
Do not enable KFENCE and KASAN simultaneously. KFENCE takes over the monitoring objects of KASAN.
Key concepts
Term | Description |
Memory pollution | Unintended modification or corruption of memory during program execution, causing exceptions or crashes. Common causes include programming errors, software vulnerabilities, malware, and hardware failures. |
Slab | A kernel memory allocation mechanism that pre-allocates objects in a cache pool for fast allocation and release, reducing the overhead of frequent memory operations. |
Order-0 page | A 4 KiB page frame—the smallest unit of memory allocation in the Linux kernel. |
Enable KFENCE
Production monitoring
Detect memory corruption in a live environment with minimal overhead.
Scenario 1: Sampling mode via boot parameters
KFENCE samples memory allocations at a fixed interval. Memory consumption is up to 2 MiB with no measurable performance impact.
Add the
kfence.sample_intervalboot parameter. Replace<sample-interval>with the sampling interval in milliseconds. For example,100= every 100 ms.sudo grubby --update-kernel=/boot/vmlinuz-$(uname -r) --args="kfence.sample_interval=<sample-interval>"(Optional) Add the
kfence.booting_maxparameter to cap KFENCE memory based on total system memory. Replace<booting-max>with a segment notation string such as0-128M:0,128M-256M:1M,256M-:2M.sudo grubby --update-kernel=/boot/vmlinuz-$(uname -r) --args="kfence.booting_max=<booting-max>"Restart the operating system for the configuration to take effect. Restart an instance.
Scenario 2: Full mode for specific slabs via script
This mode monitors all allocations for specified slab types. It consumes GiB-level memory. Use with caution on machines with limited memory.
Create a script named
kfence.sh. The script counts active slab objects, sizes the pool, disables monitoring for other slabs and order-0 pages, then enables full-mode monitoring for the specified slabs.NoteKFENCE monitors both slabs and order-0 pages. Slabs are the kernel's optimized allocation mechanism for frequently used objects.
#!/bin/bash # usage: ./kfence.sh kmalloc-64 SLAB_PREFIX=/sys/kernel/slab MODULE_PREFIX=/sys/module/kfence/parameters if [ $# -eq 0 ]; then echo "err: please input slabs" exit 1 fi #check whether slab exists for i in $@; do slab_path=$SLAB_PREFIX/$i if [ ! -d $slab_path ]; then echo "err: slab $i not exist!" exit 1 fi done #calculate num_objects sumobj=0 for i in $@; do objects=($(cat $SLAB_PREFIX/$i/objects)) maxobj=1 for ((j=1; j<${#objects[@]}; j++)); do nodeobj=$(echo ${objects[$j]} | awk -F= '{print $2}') [ $maxobj -lt $nodeobj ] && maxobj=$nodeobj done ((sumobj += maxobj)) done echo "recommend num_objects per node: $sumobj" #check kfence stats if [ $(cat $MODULE_PREFIX/sample_interval) -ne 0 ]; then echo "kfence is running, disable it and wait..." echo 0 > $MODULE_PREFIX/sample_interval sleep 1 fi #disable all slabs catching for file in $SLAB_PREFIX/* do (echo 0 > $file/kfence_enable) 2>/dev/null || echo 1 > $file/skip_kfence done #disable order0 page catching echo 0 > $MODULE_PREFIX/order0_page #enable setting slabs catching for i in $@; do (echo 1 > $SLAB_PREFIX/$i/kfence_enable) 2>/dev/null || echo 0 > $SLAB_PREFIX/$i/skip_kfence done #setting num_objects and node mode echo $sumobj > $MODULE_PREFIX/num_objects echo node > $MODULE_PREFIX/pool_mode #start kfence echo -1 > $MODULE_PREFIX/sample_interval if [ $? -ne 0 ]; then echo "err: kfence enable fail!" exit 1 fi echo "kfence enabled!"Run the script with the slab type to monitor:
sudo bash ./kfence.sh kmalloc-64
Offline debugging
Capture all memory allocations within a broad scope. High memory consumption, maximum detection coverage.
Boot parameters (x86)
Add the following boot parameters.
Parameter
Value in this example
Effect
num_objects1000000Pool can monitor up to 1,000,000 slab objects, consuming up to ceil(1,000,000 / 131,071) = 8 GiB. Set to approximately 10% of available memory.
sample_interval-1Full mode: monitors all memory matching the configured scope.
faultpanicTriggers a kernel panic when an issue is detected, preserving the core dump for analysis.
sudo grubby --update-kernel=/boot/vmlinuz-$(uname -r) --args="kfence.num_objects=1000000" sudo grubby --update-kernel=/boot/vmlinuz-$(uname -r) --args="kfence.sample_interval=-1" sudo grubby --update-kernel=/boot/vmlinuz-$(uname -r) --args="kfence.fault=panic"Restart the operating system. Restart an instance.
Runtime parameters (x86 or Arm)
KFENCE enabled at runtime cannot detect memory corruption during kernel startup.
To change
num_objectsorsample_intervalafter enabling KFENCE, first disable KFENCE. Changes tonum_objectstake effect the next time KFENCE is enabled.
Run the following commands.
sudo sh -c 'echo 1000000 > /sys/module/kfence/parameters/num_objects'
sudo sh -c 'echo -1 > /sys/module/kfence/parameters/sample_interval'
sudo sh -c 'echo panic > /sys/module/kfence/parameters/fault'The parameters take the same values described in the Boot parameters (x86) section above.
If your kernel version is earlier than 5.10.134-16, the fault parameter is not available. The error message when writing to it can be safely ignored.
Check results
After enabling KFENCE, check for detected issues.
View detection statistics
sudo cat /sys/kernel/debug/kfence/statsIf issues have been detected, the total bugs count is greater than zero.
View error details
dmesg | grep -i kfenceFilters kernel messages for KFENCE error reports.
Disable KFENCE
KFENCE is a standard component built into the Alibaba Cloud Linux kernel image (kernel configuration CONFIG_KFENCE=y). It cannot be disabled through a kernel patch (kpatch), a hot update, or a software package. Use the following manual command to disable it.
Stop KFENCE monitoring. KFENCE stops monitoring new allocations. Once all monitored memory in the pool is released, KFENCE returns it to the kernel buddy system in 1 GiB increments.
sudo bash -c 'echo 0 > /sys/module/kfence/parameters/sample_interval'(Optional) If KFENCE was enabled via boot parameters, remove them to prevent KFENCE from starting on the next boot:
sudo grubby --update-kernel=/boot/vmlinuz-$(uname -r) --remove-args="kfence.sample_interval"
Parameter reference
Configure KFENCE through boot arguments or at runtime via /sys/module/kfence/parameters/.
Parameter | Description | Valid values | Default |
| Sampling interval for memory monitoring. |
| -- |
| Maximum number of slab objects the KFENCE pool can monitor. Determines pool size and memory consumption. | Positive integer. Set to approximately 10% of maximum available memory for offline debugging. |
|
| Action when memory corruption is detected. Available in kernel |
|
|
| Memory limit for KFENCE based on total system memory. Available in kernel | Segment notation, e.g., |
|
| Enable or disable monitoring of order-0 pages. |
| -- |
| Pool allocation strategy. |
| -- |
Memory consumption formulas
Maximum memory consumption depends on num_objects:
When
num_objectsis less than or equal to 131,071: (num_objects + 1) x 8 KiBWhen
num_objectsis greater than 131,071: ceil(num_objects / 131,071) GiB
For example, setting num_objects to 1,000,000 results in a maximum consumption of ceil(1,000,000 / 131,071) = 8 GiB.
The booting_max parameter
The kfence.booting_max parameter caps KFENCE memory based on total system memory. Each segment maps a memory range to a KFENCE limit.
Default configuration (kernel 5.10.134-17 or later):
kfence.booting_max=0-2G:0,2G-32G:2M,32G-:32M
Segment | Meaning |
| Total memory below 2 GiB: KFENCE is disabled |
| Total memory between 2 GiB and 32 GiB: KFENCE can consume up to 2 MiB |
| Total memory above 32 GiB: KFENCE can consume up to 32 MiB |
With the default num_objects of 255, KFENCE memory overhead stays below 1 per mille of total memory. With standard 4 KiB pages, maximum consumption is 2 MiB. With 64 KiB huge pages, it is 32 MiB.
The booting_max parameter only constrains num_objects at boot time. Actual memory consumption may be less than the limit. This parameter does not apply when KFENCE is enabled at runtime.
Custom example: 0-128M:0,128M-256M:1M,256M-:2M
Segment | Meaning |
| Total memory below 128 MiB: KFENCE is disabled |
| Total memory between 128 MiB and 256 MiB: KFENCE can consume up to 1 MiB ( |
| Total memory above 256 MiB: KFENCE can consume up to 2 MiB ( |