Skip to content
systemcoding.dev
Virtualization

Map Guest Memory With KVM_SET_USER_MEMORY_REGION

Register guest RAM, ROM and holes with KVM_SET_USER_MEMORY_REGION, covering slot rules, read-only slots, dirty logging and slot removal, with C code.

8 min read
Summarize in AI
Flat illustration of guest machines running on a hypervisor over hardware, with the QEMU, Linux and C logos.

Every KVM guest sees a physical address space that the hypervisor invents. Parts of it are RAM, parts are ROM, and large parts are empty or reserved for devices. The ioctl that builds that picture is KVM_SET_USER_MEMORY_REGION, and although it looks simple, a surprising number of VMM bugs come from the details: alignment, overlap, how a hole behaves, what read-only really does and how to delete a slot without breaking a running guest. This post covers the structure and its rules, builds a small address space with two RAM regions, a ROM and a gap, shows the exits the gap produces, uses dirty logging to see which pages a guest wrote and ends with deleting and moving slots. It uses Linux 6.12 headers on x86-64 and builds on the API overview in the complete guide to the Linux KVM API and the VMM structure in the minimal hypervisor post.

The structure and the rules

kvm-header.hc
struct kvm_userspace_memory_region {
    __u32 slot;
    __u32 flags;
    __u64 guest_phys_addr;
    __u64 memory_size;
    __u64 userspace_addr;
};

The call maps the host virtual range starting at userspace_addr and spanning memory_size bytes to the guest physical range starting at guest_phys_addr. The kernel enforces these rules, documented in Documentation/virt/kvm/api.rst:

  • guest_phys_addr, memory_size and userspace_addr must all be multiples of the page size (4096 on x86).

  • Slots must not overlap in guest physical space. Two slots may map overlapping host ranges, though that is unusual.

  • The slot number selects the slot to create, change or delete. The low 16 bits are the slot number on x86, and the upper 16 bits are an address-space ID used for SMM, which ordinary VMMs leave as zero.

  • A memory_size of zero deletes the slot.

  • The host range must be mapped in the process, or the kernel returns EINVAL or later EFAULT when the guest touches it.

A failure with EINVAL almost always means one of the alignment or overlap rules. Print all four fields when it happens.

Building an address space

Suppose we want a small PC-like layout: 640 KiB of low RAM, a read-only ROM at the top of the first megabyte and more RAM from 1 MiB. Guest physical addresses between the two RAM regions that do not belong to any slot are a hole. The plan:

RegionGuest physical rangeType
Low RAM0x00000000 to 0x0009ffffRAM, 640 KiB
Hole0x000a0000 to 0x000effffUnmapped, so accesses exit as MMIO
ROM0x000f0000 to 0x000fffffRead-only, 64 KiB
High RAM0x00100000 to 0x004fffffRAM, 4 MiB

The code registers each region. It uses a helper so every call checks its result and prints the arguments on failure:

memslots.cc
#include <errno.h>
#include <fcntl.h>
#include <linux/kvm.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>

static int add_region(int vm, uint32_t slot, uint32_t flags,
                      uint64_t gpa, uint64_t size, void *host)
{
    struct kvm_userspace_memory_region r = {
        .slot = slot,
        .flags = flags,
        .guest_phys_addr = gpa,
        .memory_size = size,
        .userspace_addr = (uint64_t)(uintptr_t)host,
    };

    if (ioctl(vm, KVM_SET_USER_MEMORY_REGION, &r) < 0) {
        fprintf(stderr,
                "slot %u gpa 0x%llx size 0x%llx host %p flags 0x%x: %s\n",
                slot, (unsigned long long)gpa, (unsigned long long)size,
                host, flags, strerror(errno));
        return -1;
    }
    return 0;
}

static void *alloc(size_t size)
{
    void *p = mmap(NULL, size, PROT_READ | PROT_WRITE,
                   MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
    if (p == MAP_FAILED) {
        perror("mmap");
        exit(1);
    }
    return p;
}

int main(void)
{
    int kvm = open("/dev/kvm", O_RDWR | O_CLOEXEC);
    int vm = ioctl(kvm, KVM_CREATE_VM, 0);
    if (kvm < 0 || vm < 0) {
        perror("kvm");
        return 1;
    }

    int nslots = ioctl(kvm, KVM_CHECK_EXTENSION, KVM_CAP_NR_MEMSLOTS);
    printf("memory slots available: %d\n", nslots);

    void *low  = alloc(0xa0000);
    void *rom  = alloc(0x10000);
    void *high = alloc(0x400000);

    memset(rom, 0xf4, 0x10000);     /* fill the ROM with HLT opcodes */

    if (add_region(vm, 0, 0, 0x00000000, 0xa0000, low) ||
        add_region(vm, 1, KVM_MEM_READONLY, 0x000f0000, 0x10000, rom) ||
        add_region(vm, 2, 0, 0x00100000, 0x400000, high))
        return 1;

    puts("address space built");

    /* overlap on purpose: this must fail */
    void *extra = alloc(0x10000);
    if (add_region(vm, 3, 0, 0x00100000, 0x10000, extra) < 0)
        puts("overlap rejected as expected");
    return 0;
}
Text
memory slots available: 32764
address space built
slot 3 gpa 0x100000 size 0x10000 host 0x7f1c48000000 flags 0x0: Invalid argument
overlap rejected as expected

The slot count and the host address will differ on your machine. The last line of the error is the one to remember: overlap in guest physical space produces EINVAL, and the message the helper printed has all the fields needed to see why. Note that the hole between 0xa0000 and 0xeffff is absent from the slot list. There is no call to "create a hole".

What a hole does

A guest access to an address no slot covers cannot be satisfied by RAM, so KVM exits to user space with KVM_EXIT_MMIO. This is the mechanism by which emulated devices exist: place a device's registers in a hole and handle the exits. An access to the hole at 0xb8000, the classic text-mode video memory, arrives as:

hole-exit.cc
case KVM_EXIT_MMIO:
    if (run->mmio.is_write)
        fprintf(stderr, "write to hole: gpa 0x%llx len %u\n",
                (unsigned long long)run->mmio.phys_addr, run->mmio.len);
    else
        fprintf(stderr, "read from hole: gpa 0x%llx len %u\n",
                (unsigned long long)run->mmio.phys_addr, run->mmio.len);
    break;
Text
write to hole: gpa 0xb8000 len 2

A real VMM looks up the address in a table of device ranges, and for an address no device owns, it logs and either returns all ones for reads, as a PC does for an unpopulated address, or injects a fault. Doing nothing and looping is the classic way to hang: the guest retries the same access forever. Leaving an unintended hole, for example by forgetting to map the last page of a region whose size was not rounded up, is a common source of mysterious KVM_EXIT_MMIO exits at ordinary RAM addresses.

Read-only slots

KVM_MEM_READONLY makes a slot behave as ROM. The guest can read it at full speed with no exits, since the data is in the EPT. A guest write cannot be applied, so it exits with KVM_EXIT_MMIO and is_write set, exactly as for a hole. The VMM may ignore it, as a real ROM does, or react, as flash does when a guest issues a programming command. The capability must exist: check KVM_CHECK_EXTENSION with KVM_CAP_READONLY_MEM first, since older kernels and some architectures reject the flag.

readonly-check.cc
if (ioctl(vm, KVM_CHECK_EXTENSION, KVM_CAP_READONLY_MEM) <= 0) {
    fprintf(stderr, "read-only memory slots are not supported\n");
    return 1;
}

Because the slot is backed by your process's memory, you fill the ROM before or after registering it with ordinary stores, and the guest sees the contents with no further call. It does not matter whether your own mapping is writable.

Dirty logging

To see which pages the guest has written, set KVM_MEM_LOG_DIRTY_PAGES on the slot, then ask for the log. The flag can be added to an existing slot by calling the ioctl again with the same slot, guest_phys_addr and memory_size and the new flags, which changes the flags in place:

dirty-log.cc
/* enable logging on slot 2, the high RAM region */
add_region(vm, 2, KVM_MEM_LOG_DIRTY_PAGES, 0x00100000, 0x400000, high);

/* later, after the guest has run: fetch and clear the dirty bitmap */
size_t pages = 0x400000 / 4096;
uint64_t *bitmap = calloc((pages + 63) / 64, 8);
struct kvm_dirty_log log = { .slot = 2, .dirty_bitmap = bitmap };

if (ioctl(vm, KVM_GET_DIRTY_LOG, &log) < 0) {
    perror("KVM_GET_DIRTY_LOG");
    return 1;
}
for (size_t i = 0; i < pages; i++)
    if (bitmap[i / 64] & (1ULL << (i % 64)))
        printf("dirty page at gpa 0x%llx\n", 0x00100000ULL + i * 4096);
Text
dirty page at gpa 0x100000
dirty page at gpa 0x102000

The bitmap has one bit per page and must be a multiple of 64 bits, rounded up. Reading it also clears it, and KVM write-protects the pages again so the next write is logged. The cost is that the first write to each page after a fetch takes a short exit, which is why dirty logging slows a guest during migration. Enabling logging when a slot is created is cheaper than adding it later, since the latter write-protects everything at once.

Changing and removing slots

Deleting a slot is registering it with memory_size = 0:

delete-slot.cc
add_region(vm, 2, 0, 0x00100000, 0, high);   /* size 0 deletes slot 2 */

After deletion, the guest range becomes a hole, and guest accesses exit as MMIO. KVM waits for vCPUs to leave any code that used the old slot, using SRCU, before the call returns, so the deletion is synchronized with running vCPUs. Moving a slot, which means changing guest_phys_addr for the same host memory and size, is allowed in place. Changing the size or the userspace_addr of an existing slot is rejected with EINVAL, so delete and create instead. Of the flags, KVM_MEM_LOG_DIRTY_PAGES can be toggled in place, while KVM_MEM_READONLY cannot be flipped on an existing slot, so replacing RAM with ROM means delete and add.

Slots are indexed by number, and the total is capped (the KVM_CAP_NR_MEMSLOTS value, 32764 above on this kernel). A VMM that maps many small regions, as with memory hot-plug, tracks free slot numbers itself.

Newer variants

KVM_SET_USER_MEMORY_REGION2, added in Linux 6.8, takes a larger structure with additional fields, guest_memfd and guest_memfd_offset, and a new KVM_MEM_GUEST_MEMFD flag. It supports guests whose memory is backed by a guest_memfd file descriptor, which the host cannot map into its own address space, as confidential computing requires. For ordinary guests the original call remains valid and is what most code uses. Check KVM_CAP_USER_MEMORY2 before using the new one.

Common mistakes

SymptomCauseFix
EINVAL on registrationUnaligned address or size, or overlapPrint all fields, align to 4096
KVM_EXIT_MMIO at a RAM addressA page was left out of the slotRound sizes up, check for gaps
Guest reads zeros after a writeWrote to the wrong host mappingConfirm userspace_addr is the same pointer you fill
Writes to ROM are lost silentlyNot handling the MMIO exitDecide whether to ignore, log or emulate
Migration copies too muchDirty logging off, or bitmap not clearedEnable the flag at creation, fetch regularly
Memory use grows with guest sizeMemory touched by the guest is realUse MAP_NORESERVE and monitor with smaps
Also inKernels
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.