Normally when you access unmapped memory the kernel sends you SIGSEGV and you die. That’s the correct behavior most of the time. But there’s a whole class of problems where you want to say: no, hold on, I’ll supply that page myself, just wait a second. Demand paging from a network backend. Post-copy VM live migration where the guest is running before all its RAM has arrived. Checkpoint-restore where memory is hydrated lazily from a snapshot. For all of these, you need the faulting thread to stall while a handler thread fetches or constructs the missing page, then resumes transparently.
That is exactly what userfaultfd(2) does. It’s been in the kernel since 4.3 (2015). CRIU and QEMU both depend on it. Almost nobody writes userspace code that uses it directly, which is a shame, because the API is actually reasonable.
It is not a general-purpose allocator hook. Every fault is a round trip through the kernel to another thread and back, so if you’re thinking of putting it under a hot heap, stop thinking that. It’s for lazy page delivery where the content is remote, compressed, or checkpoint-derived, and the round trip is cheap next to fetching the data.
The model
userfaultfd() returns a file descriptor. You register one or more virtual memory ranges with it using UFFDIO_REGISTER. From that point on, any thread that faults on a missing page in a registered region does not get SIGSEGV. Instead, it stalls in the kernel and a uffd_msg appears on the uffd file descriptor. A dedicated handler thread reads those messages and resolves each fault with UFFDIO_COPY (copy a page from a source buffer) or UFFDIO_ZEROPAGE (zero-fill it). The faulting thread resumes only after the fault is resolved. No signal handlers, no longjmp, no threading acrobatics.
The crucial invariant: the handler thread must not itself fault on the registered region or you deadlock. Keep your handler’s stack and working memory in a separate, unregistered allocation.
When the last fd referring to the uffd is closed, every range registered with it is unregistered and any unread events are flushed. The fd is the registration.
Basic usage
#define _GNU_SOURCE
#include <linux/userfaultfd.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <sys/mman.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
static long page_size;
/* Negotiate the API version and feature set with the kernel. */
static int uffd_api_handshake(int uffd)
{
struct uffdio_api api = {
.api = UFFD_API,
.features = 0,
};
return ioctl(uffd, UFFDIO_API, &api);
}
/* Register a VA range for missing-page fault interception. */
static int uffd_register(int uffd, void *addr, size_t len)
{
struct uffdio_register reg = {
.range = { .start = (uint64_t)(uintptr_t)addr, .len = len },
.mode = UFFDIO_REGISTER_MODE_MISSING,
};
return ioctl(uffd, UFFDIO_REGISTER, ®);
}
/* Resolve a fault by copying one page from 'src' to the faulting address. */
static int uffd_supply_page(int uffd, uint64_t fault_addr, void *src)
{
uint64_t page_start = fault_addr & ~((uint64_t)page_size - 1);
struct uffdio_copy copy = {
.dst = page_start,
.src = (uint64_t)(uintptr_t)src,
.len = (uint64_t)page_size,
.mode = 0,
};
return ioctl(uffd, UFFDIO_COPY, ©);
}
The handler thread runs a poll() loop over the uffd plus an eventfd that main kicks when it wants the handler gone:
typedef struct { int uffd; int stopfd; } HandlerArg;
static void *fault_handler(void *arg)
{
HandlerArg *h = arg;
/* Allocate the page buffer OUTSIDE the registered region. */
char *page = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (page == MAP_FAILED) { perror("mmap"); return NULL; }
struct pollfd pfd[2] = {
{ .fd = h->uffd, .events = POLLIN },
{ .fd = h->stopfd, .events = POLLIN },
};
for (;;) {
if (poll(pfd, 2, -1) < 0) {
if (errno == EINTR) continue;
perror("poll");
break;
}
if (pfd[1].revents & POLLIN) /* main says we're done */
break;
if (!(pfd[0].revents & POLLIN))
continue;
struct uffd_msg msg;
ssize_t n = read(h->uffd, &msg, sizeof(msg));
if (n < 0) {
if (errno == EAGAIN) continue; /* spurious wakeup */
perror("read uffd");
break;
}
if (msg.event != UFFD_EVENT_PAGEFAULT)
continue;
uint64_t addr = msg.arg.pagefault.address;
/* This is where you'd fetch real data: from a file, network, etc.
Here we just fill with a recognizable pattern. */
memset(page, 0xAB, page_size);
if (uffd_supply_page(h->uffd, addr, page) < 0) {
perror("UFFDIO_COPY");
break;
}
}
munmap(page, page_size);
return NULL;
}
int main(void)
{
page_size = sysconf(_SC_PAGE_SIZE);
/* O_CLOEXEC always. O_NONBLOCK because we poll() it -- see below. */
int uffd = (int)syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK);
if (uffd < 0) { perror("userfaultfd"); return 1; }
if (uffd_api_handshake(uffd) < 0) { perror("UFFDIO_API"); return 1; }
/* Allocate a lazy region: MAP_ANONYMOUS but we will supply pages
on demand rather than letting the kernel zero them. Nothing may
be populated yet, or there's no missing fault to catch. */
size_t region_size = 4 * (size_t)page_size;
char *region = mmap(NULL, region_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (region == MAP_FAILED) { perror("mmap"); return 1; }
if (uffd_register(uffd, region, region_size) < 0) {
perror("UFFDIO_REGISTER"); return 1;
}
/* Start the handler thread before anyone touches the region. */
HandlerArg harg = { .uffd = uffd, .stopfd = eventfd(0, EFD_CLOEXEC) };
pthread_t tid;
pthread_create(&tid, NULL, fault_handler, &harg);
/* Now access the region. Each page fault blocks the accessor until
the handler supplies the page. */
for (size_t i = 0; i < region_size; i += page_size) {
printf("region[%zu] = 0x%02x\n", i, (unsigned char)region[i]);
}
uint64_t one = 1;
write(harg.stopfd, &one, sizeof(one));
pthread_join(tid, NULL);
munmap(region, region_size);
close(harg.stopfd);
close(uffd);
return 0;
}
Build with cc -pthread. You get four lines of 0xab, each one having round-tripped through the handler thread. The pattern is identical whether “fetch data” means reading from a local file, a network socket, a custom compressor, or a key-value store.
Why poll() and not a bare blocking read() loop: two reasons, one of them a trap. The trap is that if you open the uffd with O_NONBLOCK and then write the naive for (;;) read() loop, the first read() returns EAGAIN before anyone has faulted, your loop treats that as an error, the handler exits, and the main thread hangs forever on its first touch of the region. Ask me how I know. The other direction doesn’t work either: without O_NONBLOCK, poll() on a uffd always reports POLLERR and select() reports it readable and writable, so you can’t multiplex it. Pick one: blocking fd with a dedicated thread that does nothing but read(), or O_NONBLOCK plus poll()/epoll. The second is what you want in production, because the same loop can also watch a control socket, a signalfd, a shutdown eventfd, whatever.
What UFFDIO_COPY actually does
UFFDIO_COPY atomically copies len bytes from your src buffer (an address in your own process) into the registered range at dst, installs the page, and by default wakes the thread that was waiting on that fault. From the faulting thread’s point of view it went into the kernel and came back with a fully populated page. There is no window where it sees half your memcpy.
The details that bite:
dstandlenmust be multiples of the page size, or you getEINVAL. Hence the round-down inuffd_supply_page(); the fault address you’re handed is wherever the access landed, not the page start.lencan span multiple pages. If you know the accessor is about to walk the next 64 KiB, fill it in one ioctl instead of eating 16 faults.- The struct has an output field,
copy, where the kernel reports how many bytes it actually copied (or a negated errno). If that doesn’t matchlen, the ioctl fails withEAGAIN, and you deal with the remainder. UFFDIO_COPY_MODE_DONTWAKEpopulates without waking anyone. Useful for prefetching pages nobody has faulted on yet.UFFDIO_COPY_MODE_WPinstalls the page read-only, so the next write traps as a write-protect fault. Only meaningful when the range is registered for both missing and WP mode (below).ENOENTmeans the faulting process changed its memory layout while your copy was in flight.ESRCH(since 4.13) means it exited. Neither is a reason to kill the handler.
UFFDIO_ZEROPAGE is the same thing without a src: the kernel fills the range with zeros. Use it when most of a sparse region should read as zero on first touch and you don’t want to keep a page of zeros around just to copy from.
Privileges and the unprivileged sysctl
Since Linux 5.2, userfaultfd() fails with EPERM if the caller lacks CAP_SYS_PTRACE in the initial user namespace and vm.unprivileged_userfaultfd is 0. The reasoning is grimly practical: a handler that never answers can freeze a thread inside the kernel for as long as it likes, and “hold this kernel thread still while I race something else” is exactly what a lot of kernel exploits want.
cat /proc/sys/vm/unprivileged_userfaultfd
# 0 = unprivileged callers restricted
# 1 = any user may call userfaultfd()
sysctl -w vm.unprivileged_userfaultfd=1 # persist it in /etc/sysctl.d/ if you must
Linux 5.11 added UFFD_USER_MODE_ONLY as a flag to userfaultfd(). With it, the uffd only handles faults that originate from user-mode accesses. If the kernel itself faults on the registered range (say, copy_from_user() inside a syscall you passed a pointer into that range), the process gets SIGBUS instead of a stalled kernel thread. That removes the exploit primitive, which is why it’s the sanctioned way to use userfaultfd without privilege when the sysctl is 0. If you’re on 5.11+ and you don’t need kernel-originated faults, use it:
int uffd = (int)syscall(SYS_userfaultfd,
O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY);
Mind the SIGBUS part: if your program read(2)s from a file straight into a lazily populated region, that’s a kernel-mode fault, and with this flag it’s a dead process rather than a handled fault. On older kernels the flag doesn’t exist (EINVAL); check the sysctl or run with the capability.
Write-protect mode: dirty page tracking
UFFDIO_REGISTER_MODE_MISSING intercepts accesses to unmapped pages. UFFDIO_REGISTER_MODE_WP intercepts writes to pages that are present but write-protected. That’s dirty-page tracking: register the range, write-protect it, and every first write tells you which page got dirtied. Some garbage collectors use exactly this for write barriers, so they never have to call mprotect() from inside a SIGSEGV handler.
Versions, because this one is a mess: WP mode landed in Linux 5.7 for anonymous memory only. Shmem and hugetlbfs support came in 5.19, advertised by a separate feature bit, UFFD_FEATURE_WP_HUGETLBFS_SHMEM. The man page dates the anonymous-memory bit, UFFD_FEATURE_PAGEFAULT_FLAG_WP, to 5.10. Don’t parse uname -r and guess. Probe the feature bit.
Probing has a stupid wrinkle. If you ask UFFDIO_API for a feature the kernel doesn’t have, it doesn’t hand you back the supported subset. It zeroes the struct and fails with EINVAL. The documented dance is: create a throwaway uffd, call UFFDIO_API with features = 0, read the returned bitmask, close it, then create the real uffd and request what you actually want. The man page lists the close-and-reopen under BUGS, which is honest of it.
/* Probe: features = 0 returns everything the kernel supports. */
int probe = (int)syscall(SYS_userfaultfd, O_CLOEXEC);
struct uffdio_api api = { .api = UFFD_API, .features = 0 };
ioctl(probe, UFFDIO_API, &api);
close(probe);
if (!(api.features & UFFD_FEATURE_PAGEFAULT_FLAG_WP)) {
fprintf(stderr, "kernel has no WP faults for anon memory\n");
return 1;
}
/* Real fd: now ask for it. */
int uffd = (int)syscall(SYS_userfaultfd, O_CLOEXEC | O_NONBLOCK);
api = (struct uffdio_api){ .api = UFFD_API,
.features = UFFD_FEATURE_PAGEFAULT_FLAG_WP };
ioctl(uffd, UFFDIO_API, &api);
/* Register a region for write-protect fault interception.
The region must already be mapped. */
struct uffdio_register reg = {
.range = { .start = (uint64_t)(uintptr_t)addr, .len = len },
.mode = UFFDIO_REGISTER_MODE_WP,
};
ioctl(uffd, UFFDIO_REGISTER, ®);
/* Then write-protect the whole region to start tracking. */
struct uffdio_writeprotect wp = {
.range = { .start = (uint64_t)(uintptr_t)addr, .len = len },
.mode = UFFDIO_WRITEPROTECT_MODE_WP, /* enable WP */
};
ioctl(uffd, UFFDIO_WRITEPROTECT, &wp);
When a thread writes to a write-protected page, a UFFD_EVENT_PAGEFAULT arrives with msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP set (and UFFD_PAGEFAULT_FLAG_WRITE too, always, since only a write can trip it). The handler records which page was dirtied and then removes WP for that page, which also wakes the writer:
/* In the handler, after recording the dirty address: */
struct uffdio_writeprotect clear = {
.range = {
.start = fault_addr & ~((uint64_t)page_size - 1),
.len = (uint64_t)page_size,
},
.mode = 0, /* clear WP, allow future writes without faulting */
};
ioctl(uffd, UFFDIO_WRITEPROTECT, &clear);
With only WP registered, writing to a missing page generates no notification at all; you only hear about existing pages. You can combine both modes on the same registration, UFFDIO_REGISTER_MODE_MISSING | UFFDIO_REGISTER_MODE_WP: missing faults supply the page, write faults track dirtiness, and UFFDIO_COPY_MODE_WP lets you install a fetched page already write-protected so its first write is also caught. Lazy population plus dirty tracking, one fd.
Other events
The uffd reports more than just page faults, but only the ones you ask for during UFFDIO_API. UFFD_FEATURE_EVENT_FORK gets you UFFD_EVENT_FORK when a forked child inherits a registered VMA. UFFD_FEATURE_EVENT_REMAP gets you UFFD_EVENT_REMAP on mremap(). UFFD_FEATURE_EVENT_REMOVE gets you UFFD_EVENT_REMOVE on madvise() with MADV_DONTNEED or MADV_REMOVE. UFFD_FEATURE_EVENT_UNMAP gets you UFFD_EVENT_UNMAP on munmap(), explicit or implied by mmap()/mremap() over the range. All since 4.11. This is how CRIU tracks memory state across process tree snapshots without stopping every thread simultaneously.
/* Request fork and remap events during API negotiation. */
struct uffdio_api api = {
.api = UFFD_API,
.features = UFFD_FEATURE_EVENT_FORK | UFFD_FEATURE_EVENT_REMAP,
};
ioctl(uffd, UFFDIO_API, &api);
UFFD_FEATURE_EVENT_FORK specifically requires CAP_SYS_PTRACE; without it UFFDIO_API fails with EPERM, sysctl or no sysctl. The child’s uffd in a fork event is in msg.arg.fork.ufd. Your handler has to read from both uffd file descriptors from that point on, which is one more reason the handler should already be a poll() loop.
This is not mprotect with SIGSEGV
The classic userspace-paging trick is mprotect(PROT_NONE) on a range, catch SIGSEGV, fix things up inside the handler, return. It works. People shipped it for decades. It’s also miserable: a signal handler may only call async-signal-safe functions, so no malloc, no stdio, no sane locking, and certainly no blocking on a network socket to fetch the page. Now have eight threads fault concurrently and enjoy your week.
The uffd handler is a normal thread. It can malloc, open files, block on a socket, log to stderr. The faulting thread is parked in the kernel waiting for the ioctl; it isn’t spinning and it isn’t holding any lock the handler needs (unless you wrote the handler that way, in which case that’s on you).
The flip side: if you just want to catch stray accesses to specific ranges for debugging or sanitization, a SIGSEGV handler with sigaction(SA_SIGINFO) that checks si_addr is simpler and needs no handler thread. userfaultfd is specifically for when a fault should stall the accessor, go get data from somewhere, and resume transparently. The stalling is the whole point.
What memory it works on
Up to Linux 4.11, missing mode works only on private anonymous mappings. Since 4.11 it also covers shared memory (shmem, which includes MAP_SHARED | MAP_ANONYMOUS) and hugetlbfs. Ordinary file-backed mappings on a regular filesystem are not on the list. Write-protect mode is anonymous-only until 5.19, as above. Since 5.13 there’s also a minor-fault mode (UFFDIO_REGISTER_MODE_MINOR) for hugetlbfs, and shmem since 5.14, which fires when the page already exists in the page cache but isn’t mapped yet, and is resolved with UFFDIO_CONTINUE. That one’s a post for another day.
Checking support
# Config must be set
zcat /proc/config.gz | grep USERFAULTFD
# CONFIG_USERFAULTFD=y
# Verify the syscall number on your arch
grep userfaultfd /usr/include/x86_64-linux-gnu/asm/unistd_64.h
# #define __NR_userfaultfd 323
# Quick smoke test: does it return an fd, EPERM, or ENOSYS?
python3 -c "
import ctypes, os
libc = ctypes.CDLL(None, use_errno=True)
fd = libc.syscall(323, 0o2000000) # O_CLOEXEC
print('uffd fd:', fd, '/ errno:', os.strerror(ctypes.get_errno()) if fd < 0 else 'ok')
os.close(fd) if fd >= 0 else None
"
EPERM there means the sysctl is 0 and you’re unprivileged; retry with UFFD_USER_MODE_ONLY (value 1) OR’d into the flags.
The memfd_create post covers sealed anonymous file descriptors for immutable IPC. The pidfd post covers stable process handles, and pidfd_getfd() is how a supervisor process can grab another process’s uffd if you want the fault handler to live outside the faulting process. The timerfd/signalfd/eventfd post covers the poll()/epoll event-loop pattern the handler above is a small instance of. The io_uring post shows how to batch async I/O with registered buffers, which pairs well with a uffd-backed demand-paging backend. Kerrisk’s The Linux Programming Interface (Amazon affiliate link; RodHat may earn a commission) has the mmap() and virtual memory chapter that gives the mental model userfaultfd builds on top of. The actual uffd deep dive is in the kernel tree at Documentation/admin-guide/mm/userfaultfd.rst.
