All Products
Search
Document Center

Alibaba Cloud Linux:Detect kernel memory pollution with KFENCE

Last Updated:Sep 08, 2026

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.

Note

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

5.10.84-10

Arm

5.10.134-16

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, kmalloc-4k) and order-0 pages

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)

Note

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.

  1. Add the kfence.sample_interval boot 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>"
  2. (Optional) Add the kfence.booting_max parameter to cap KFENCE memory based on total system memory. Replace <booting-max> with a segment notation string such as 0-128M:0,128M-256M:1M,256M-:2M.

       sudo grubby --update-kernel=/boot/vmlinuz-$(uname -r) --args="kfence.booting_max=<booting-max>"
  3. 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.

  1. 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.

    Note

    KFENCE 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!"
  2. 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)

  1. Add the following boot parameters.

    Parameter

    Value in this example

    Effect

    num_objects

    1000000

    Pool 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

    -1

    Full mode: monitors all memory matching the configured scope.

    fault

    panic

    Triggers 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"
  2. Restart the operating system. Restart an instance.

Runtime parameters (x86 or Arm)

Note
  • KFENCE enabled at runtime cannot detect memory corruption during kernel startup.

  • To change num_objects or sample_interval after enabling KFENCE, first disable KFENCE. Changes to num_objects take 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.

Note

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/stats

If issues have been detected, the total bugs count is greater than zero.

View error details

dmesg | grep -i kfence

Filters 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.

  1. 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'
  2. (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

sample_interval

Sampling interval for memory monitoring.

0 = disabled. Positive integer = interval in ms (for example, 100 = every 100 ms). Negative integer = full mode (monitors all qualifying memory).

--

num_objects

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.

255

fault

Action when memory corruption is detected. Available in kernel 5.10.134-16 or later.

report = log the error. panic = trigger a kernel panic and preserve the core dump.

report

booting_max

Memory limit for KFENCE based on total system memory. Available in kernel 5.10.134-17 or later. Applies only to boot command line configuration.

Segment notation, e.g., 0-2G:0,2G-32G:2M,32G-:32M

0-2G:0,2G-32G:2M,32G-:32M

order0_page

Enable or disable monitoring of order-0 pages.

0 = disabled, 1 = enabled

--

pool_mode

Pool allocation strategy.

node = per-NUMA-node pools

--

Memory consumption formulas

Maximum memory consumption depends on num_objects:

  • When num_objects is less than or equal to 131,071: (num_objects + 1) x 8 KiB

  • When num_objects is 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

0-2G:0

Total memory below 2 GiB: KFENCE is disabled

2G-32G:2M

Total memory between 2 GiB and 32 GiB: KFENCE can consume up to 2 MiB

32G-:32M

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.

Note

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

0-128M:0

Total memory below 128 MiB: KFENCE is disabled

128M-256M:1M

Total memory between 128 MiB and 256 MiB: KFENCE can consume up to 1 MiB (num_objects capped at 127)

256M-:2M

Total memory above 256 MiB: KFENCE can consume up to 2 MiB (num_objects capped at 255)

FAQ

What is the memory and performance impact of KFENCE?

It depends on the mode:

  • Sampling mode (boot parameters with a positive sample_interval): Up to 2 MiB memory consumption. Negligible performance impact. Recommended for production.

  • Full mode on specific slabs (runtime script or sample_interval=-1): GiB-level memory consumption. Acceptable performance impact if monitoring is scoped to specific slab types.

  • Full mode on all slabs (offline debugging): Significant memory consumption and performance impact. Use only for dedicated debugging sessions.

Test incrementally before production deployment to measure the impact on your workload.

Is there a known stability issue?

In kernel 5.10.134-15 and earlier, KFENCE may cause downtime when simultaneously monitoring order-0 pages and slabs in certain scenarios. To prevent this, disable order-0 page monitoring:

sudo grubby --update-kernel=/boot/vmlinuz-$(uname -r) --args="kfence.order0_page=0"

This issue is resolved in kernel 5.10.134-16 and later.