Userfaultfd¶
Objective¶
Userfaults allow the implementation of on-demand paging from userlandand more generally they allow userland to take control of variousmemory page faults, something otherwise only the kernel code could do.
For example userfaults allows a proper and more optimal implementationof thePROT_NONE+SIGSEGV trick.
Design¶
Userspace creates a new userfaultfd, initializes it, and registers one or moreregions of virtual memory with it. Then, any page faults which occur within theregion(s) result in a message being delivered to the userfaultfd, notifyinguserspace of the fault.
Theuserfaultfd (aside from registering and unregistering virtualmemory ranges) provides two primary functionalities:
read/POLLINprotocol to notify a userland thread of the faultshappeningvarious
UFFDIO_*ioctls that can manage the virtual memory regionsregistered in theuserfaultfdthat allows userland to efficientlyresolve the userfaults it receives via 1) or to manage the virtualmemory in the background
The real advantage of userfaults if compared to regular virtual memorymanagement of mremap/mprotect is that the userfaults in all theiroperations never involve heavyweight structures like vmas (in fact theuserfaultfd runtime load never takes the mmap_lock for writing).Vmas are not suitable for page- (or hugepage) granular fault trackingwhen dealing with virtual address spaces that could spanTerabytes. Too many vmas would be needed for that.
Theuserfaultfd, once created, can also bepassed using unix domain sockets to a manager process, so the samemanager process could handle the userfaults of a multitude ofdifferent processes without them being aware about what is going on(well of course unless they later try to use theuserfaultfdthemselves on the same region the manager is already tracking, whichis a corner case that would currently return-EBUSY).
API¶
Creating a userfaultfd¶
There are two ways to create a new userfaultfd, each of which provide ways torestrict access to this functionality (since historically userfaultfds whichhandle kernel page faults have been a useful tool for exploiting the kernel).
The first way, supported since userfaultfd was introduced, is theuserfaultfd(2) syscall. Access to this is controlled in several ways:
Any user can always create a userfaultfd which traps userspace page faultsonly. Such a userfaultfd can be created using the userfaultfd(2) syscallwith the flag UFFD_USER_MODE_ONLY.
In order to also trap kernel page faults for the address space, either theprocess needs the CAP_SYS_PTRACE capability, or the system must havevm.unprivileged_userfaultfd set to 1. By default, vm.unprivileged_userfaultfdis set to 0.
The second way, added to the kernel more recently, is by opening/dev/userfaultfd and issuing a USERFAULTFD_IOC_NEW ioctl to it. This methodyields equivalent userfaultfds to the userfaultfd(2) syscall.
Unlike userfaultfd(2), access to /dev/userfaultfd is controlled via normalfilesystem permissions (user/group/mode), which gives fine grained access touserfaultfd specifically, without also granting other unrelated privileges atthe same time (as e.g. granting CAP_SYS_PTRACE would do). Users who have accessto /dev/userfaultfd can always create userfaultfds that trap kernel page faults;vm.unprivileged_userfaultfd is not considered.
Initializing a userfaultfd¶
When first opened theuserfaultfd must be enabled invoking theUFFDIO_API ioctl specifying auffdio_api.api value set toUFFD_API (ora later API version) which will specify theread/POLLIN protocoluserland intends to speak on theUFFD and theuffdio_api.featuresuserland requires. TheUFFDIO_API ioctl if successful (i.e. if therequesteduffdio_api.api is spoken also by the running kernel and therequested features are going to be enabled) will return intouffdio_api.features anduffdio_api.ioctls two 64bit bitmasks ofrespectively all the available features of the read(2) protocol andthe generic ioctl available.
Theuffdio_api.features bitmask returned by theUFFDIO_API ioctldefines what memory types are supported by theuserfaultfd and whatevents, except page fault notifications, may be generated:
The
UFFD_FEATURE_EVENT_*flags indicate that various other eventsother than page faults are supported. These events are described in moredetail below in theNon-cooperative userfaultfd section.UFFD_FEATURE_MISSING_HUGETLBFSandUFFD_FEATURE_MISSING_SHMEMindicate that the kernel supportsUFFDIO_REGISTER_MODE_MISSINGregistrations for hugetlbfs and shared memory (covering all shmem APIs,i.e. tmpfs,IPCSHM,/dev/zero,MAP_SHARED,memfd_create,etc) virtual memory areas, respectively.UFFD_FEATURE_MINOR_HUGETLBFSindicates that the kernel supportsUFFDIO_REGISTER_MODE_MINORregistration for hugetlbfs virtual memoryareas.UFFD_FEATURE_MINOR_SHMEMis the analogous feature indicatingsupport for shmem virtual memory areas.UFFD_FEATURE_MOVEindicates that the kernel supports moving anexisting page contents from userspace.
The userland application should set the feature flags it intends to usewhen invoking theUFFDIO_API ioctl, to request that those features beenabled if supported.
Once theuserfaultfd API has been enabled theUFFDIO_REGISTERioctl should be invoked (if present in the returneduffdio_api.ioctlsbitmask) to register a memory range in theuserfaultfd by setting theuffdio_register structure accordingly. Theuffdio_register.modebitmask will specify to the kernel which kind of faults to track forthe range. TheUFFDIO_REGISTER ioctl will return theuffdio_register.ioctls bitmask of ioctls that are suitable to resolveuserfaults on the range registered. Not all ioctls will necessarily besupported for all memory types (e.g. anonymous memory vs. shmem vs.hugetlbfs), or all types of intercepted faults.
Userland can use theuffdio_register.ioctls to manage the virtualaddress space in the background (to add or potentially also removememory from theuserfaultfd registered range). This means a userfaultcould be triggering just before userland maps in the background theuser-faulted page.
Resolving Userfaults¶
There are three basic ways to resolve userfaults:
UFFDIO_COPYatomically copies some existing page contents fromuserspace.UFFDIO_ZEROPAGEatomically zeros the new page.UFFDIO_CONTINUEmaps an existing, previously-populated page.
These operations are atomic in the sense that they guarantee nothing cansee a half-populated page, since readers will keep userfaulting until theoperation has finished.
By default, these wake up userfaults blocked on the range in question.They support aUFFDIO_*_MODE_DONTWAKEmode flag, which indicatesthat waking will be done separately at some later time.
Which ioctl to choose depends on the kind of page fault, and what we’dlike to do to resolve it:
For
UFFDIO_REGISTER_MODE_MISSINGfaults, the fault needs to beresolved by either providing a new page (UFFDIO_COPY), or mappingthe zero page (UFFDIO_ZEROPAGE). By default, the kernel would mapthe zero page for a missing fault. With userfaultfd, userspace candecide what content to provide before the faulting thread continues.For
UFFDIO_REGISTER_MODE_MINORfaults, there is an existing page (inthe page cache). Userspace has the option of modifying the page’scontents before resolving the fault. Once the contents are correct(modified or not), userspace asks the kernel to map the page and let thefaulting thread continue withUFFDIO_CONTINUE.
Notes:
You can tell which kind of fault occurred by examining
pagefault.flagswithin theuffd_msg, checking for theUFFD_PAGEFAULT_FLAG_*flags.None of the page-delivering ioctls default to the range that youregistered with. You must fill in all fields for the appropriateioctl
structincludingthe range.You get the address of the access that triggered the missing pageevent out of a
structuffd_msgthat you read in the thread from theuffd. You can supply as many pages as you want with these IOCTLs.Keep in mind that unless you used DONTWAKE then the first of any ofthose IOCTLs wakes up the faulting thread.Be sure to test for all errors including(
pollfd[0].revents&POLLERR). This can happen, e.g. when rangessupplied were incorrect.
Write Protect Notifications¶
This is equivalent to (but faster than) using mprotect and a SIGSEGVsignal handler.
Firstly you need to register a range withUFFDIO_REGISTER_MODE_WP.Instead of using mprotect(2) you useioctl(uffd,UFFDIO_WRITEPROTECT,struct*uffdio_writeprotect)whilemode=UFFDIO_WRITEPROTECT_MODE_WPin thestructpassed in. The range does not default to and does nothave to be identical to the range you registered with. You can writeprotect as many ranges as you like (inside the registered range).Then, in the thread reading from uffd thestructwill havemsg.arg.pagefault.flags&UFFD_PAGEFAULT_FLAG_WP set. Now you sendioctl(uffd,UFFDIO_WRITEPROTECT,struct*uffdio_writeprotect)again whilepagefault.mode does not haveUFFDIO_WRITEPROTECT_MODE_WPset. This wakes up the thread which will continue to run with writes. Thisallows you to do the bookkeeping about the write in the uffd readingthread before the ioctl.
If you registered with bothUFFDIO_REGISTER_MODE_MISSING andUFFDIO_REGISTER_MODE_WP then you need to think about the sequence inwhich you supply a page and undo write protect. Note that there is adifference between writes into a WP area and into a !WP area. Theformer will haveUFFD_PAGEFAULT_FLAG_WP set, the latterUFFD_PAGEFAULT_FLAG_WRITE. The latter did not fail on protection butyou still need to supply a page whenUFFDIO_REGISTER_MODE_MISSING wasused.
Userfaultfd write-protect mode currently behave differently on none ptes(when e.g. page is missing) over different types of memories.
For anonymous memory,ioctl(UFFDIO_WRITEPROTECT) will ignore none ptes(e.g. when pages are missing and not populated). For file-backed memorieslike shmem and hugetlbfs, none ptes will be write protected just like apresent pte. In other words, there will be a userfaultfd write faultmessage generated when writing to a missing page on file typed memories,as long as the page range was write-protected before. Such a message willnot be generated on anonymous memories by default.
If the application wants to be able to write protect none ptes on anonymousmemory, one can pre-populate the memory with e.g. MADV_POPULATE_READ. Onnewer kernels, one can also detect the feature UFFD_FEATURE_WP_UNPOPULATEDand set the feature bit in advance to make sure none ptes will also bewrite protected even upon anonymous memory.
When usingUFFDIO_REGISTER_MODE_WP in combination with eitherUFFDIO_REGISTER_MODE_MISSING orUFFDIO_REGISTER_MODE_MINOR, whenresolving missing / minor faults withUFFDIO_COPY orUFFDIO_CONTINUErespectively, it may be desirable for the new page / mapping to bewrite-protected (so future writes will also result in a WP fault). These ioctlssupport a mode flag (UFFDIO_COPY_MODE_WP orUFFDIO_CONTINUE_MODE_WPrespectively) to configure the mapping this way.
If the userfaultfd context hasUFFD_FEATURE_WP_ASYNC feature bit set,any vma registered with write-protection will work in async mode ratherthan the default sync mode.
In async mode, there will be no message generated when a write operationhappens, meanwhile the write-protection will be resolved automatically bythe kernel. It can be seen as a more accurate version of soft-dirtytracking and it can be different in a few ways:
The dirty result will not be affected by vma changes (e.g. vmamerging) because the dirty is only tracked by the pte.
It supports range operations by default, so one can enable tracking onany range of memory as long as page aligned.
Dirty information will not get lost if the pte was zapped due tovarious reasons (e.g. during split of a shmem transparent huge page).
Due to a reverted meaning of soft-dirty (page clean when uffd-wp bitset; dirty when uffd-wp bit cleared), it has different semantics onsome of the memory operations. For example:
MADV_DONTNEEDonanonymous (orMADV_REMOVEon a file mapping) will be treated asdirtying of memory by dropping uffd-wp bit during the procedure.
The user app can collect the “written/dirty” status by looking up theuffd-wp bit for the pages being interested in /proc/pagemap.
The page will not be under track of uffd-wp async mode until the page isexplicitly write-protected byioctl(UFFDIO_WRITEPROTECT) with the modeflagUFFDIO_WRITEPROTECT_MODE_WP set. Trying to resolve a page faultthat was tracked by async mode userfaultfd-wp is invalid.
When userfaultfd-wp async mode is used alone, it can be applied to allkinds of memory.
Memory Poisioning Emulation¶
In response to a fault (either missing or minor), an action userspace cantake to “resolve” it is to issue aUFFDIO_POISON. This will cause anyfuture faulters to either get a SIGBUS, or in KVM’s case the guest willreceive an MCE as if there were hardware memory poisoning.
This is used to emulate hardware memory poisoning. Imagine a VM running on amachine which experiences a real hardware memory error. Later, we live migratethe VM to another physical machine. Since we want the migration to betransparent to the guest, we want that same address range to act as if it wasstill poisoned, even though it’s on a new physical host which ostensiblydoesn’t have a memory error in the exact same spot.
QEMU/KVM¶
QEMU/KVM is using theuserfaultfd syscall to implement postcopy livemigration. Postcopy live migration is one form of memoryexternalization consisting of a virtual machine running with part orall of its memory residing on a different node in the cloud. Theuserfaultfd abstraction is generic enough that not a single line ofKVM kernel code had to be modified in order to add postcopy livemigration to QEMU.
Guest async page faults,FOLL_NOWAIT and all otherGUP* features workjust fine in combination with userfaults. Userfaults trigger asyncpage faults in the guest scheduler so those guest processes thataren’t waiting for userfaults (i.e. network bound) can keep running inthe guest vcpus.
It is generally beneficial to run one pass of precopy live migrationjust before starting postcopy live migration, in order to avoidgenerating userfaults for readonly guest regions.
The implementation of postcopy live migration currently uses onesingle bidirectional socket but in the future two different socketswill be used (to reduce the latency of the userfaults to the minimumpossible without having to decrease/proc/sys/net/ipv4/tcp_wmem).
The QEMU in the source node writes all pages that it knows are missingin the destination node, into the socket, and the migration thread ofthe QEMU running in the destination node runsUFFDIO_COPY|ZEROPAGEioctls on theuserfaultfd in order to map the received pages into theguest (UFFDIO_ZEROCOPY is used if the source page was a zero page).
A different postcopy thread in the destination node listens withpoll() to theuserfaultfd in parallel. When aPOLLIN event isgenerated after a userfault triggers, the postcopy thread read() fromtheuserfaultfd and receives the fault address (or-EAGAIN in case theuserfault was already resolved and waken by aUFFDIO_COPY|ZEROPAGE runby the parallel QEMU migration thread).
After the QEMU postcopy thread (running in the destination node) getsthe userfault address it writes the information about the missing pageinto the socket. The QEMU source node receives the information androughly “seeks” to that page address and continues sending allremaining missing pages from that new page offset. Soon after that(just the time to flush the tcp_wmem queue through the network) themigration thread in the QEMU running in the destination node willreceive the page that triggered the userfault and it’ll map it asusual with theUFFDIO_COPY|ZEROPAGE (without actually knowing if itwas spontaneously sent by the source or if it was an urgent pagerequested through a userfault).
By the time the userfaults start, the QEMU in the destination nodedoesn’t need to keep any per-page state bitmap relative to the livemigration around and a single per-page bitmap has to be maintained inthe QEMU running in the source node to know which pages are stillmissing in the destination node. The bitmap in the source node ischecked to find which missing pages to send in round robin and we seekover it when receiving incoming userfaults. After sending each page ofcourse the bitmap is updated accordingly. It’s also useful to avoidsending the same page twice (in case the userfault is read by thepostcopy thread just beforeUFFDIO_COPY|ZEROPAGE runs in the migrationthread).
Non-cooperative userfaultfd¶
When theuserfaultfd is monitored by an external manager, the managermust be able to track changes in the process virtual memorylayout. Userfaultfd can notify the manager about such changes usingthe same read(2) protocol as for the page fault notifications. Themanager has to explicitly enable these events by setting appropriatebits inuffdio_api.features passed toUFFDIO_API ioctl:
UFFD_FEATURE_EVENT_FORKenable
userfaultfdhooks for fork(). When this feature isenabled, theuserfaultfdcontext of the parent process isduplicated into the newly created process. The managerreceivesUFFD_EVENT_FORKwith file descriptor of the newuserfaultfdcontext in theuffd_msg.fork.UFFD_FEATURE_EVENT_REMAPenable notifications about
mremap()calls. When thenon-cooperative process moves a virtual memory area to adifferent location, the manager will receiveUFFD_EVENT_REMAP. Theuffd_msg.remapwill contain the old andnew addresses of the area and its original length.UFFD_FEATURE_EVENT_REMOVEenable notifications about madvise(MADV_REMOVE) andmadvise(MADV_DONTNEED) calls. The event
UFFD_EVENT_REMOVEwillbe generated upon these calls tomadvise(). Theuffd_msg.removewill contain start and end addresses of the removed area.UFFD_FEATURE_EVENT_UNMAPenable notifications about memory unmapping. The manager willget
UFFD_EVENT_UNMAPwithuffd_msg.removecontaining start andend addresses of the unmapped area.
Although theUFFD_FEATURE_EVENT_REMOVE andUFFD_FEATURE_EVENT_UNMAPare pretty similar, they quite differ in the action expected from theuserfaultfd manager. In the former case, the virtual memory isremoved, but the area is not, the area remains monitored by theuserfaultfd, and if a page fault occurs in that area it will bedelivered to the manager. The proper resolution for such page fault isto zeromap the faulting address. However, in the latter case, when anarea is unmapped, either explicitly (withmunmap() system call), orimplicitly (e.g. duringmremap()), the area is removed and in turn theuserfaultfd context for such area disappears too and the manager willnot get further userland page faults from the removed area. Still, thenotification is required in order to prevent manager from usingUFFDIO_COPY on the unmapped area.
Unlike userland page faults which have to be synchronous and requireexplicit or implicit wakeup, all the events are deliveredasynchronously and the non-cooperative process resumes execution assoon as manager executes read(). Theuserfaultfd manager shouldcarefully synchronize calls toUFFDIO_COPY with the eventsprocessing. To aid the synchronization, theUFFDIO_COPY ioctl willreturn-ENOSPC when the monitored process exits at the time ofUFFDIO_COPY, and-ENOENT, when the non-cooperative process has changedits virtual memory layout simultaneously with outstandingUFFDIO_COPYoperation.
The current asynchronous model of the event delivery is optimal forsingle threaded non-cooperativeuserfaultfd manager implementations. Asynchronous event delivery model can be added later as a newuserfaultfd feature to facilitate multithreading enhancements of thenon cooperative manager, for example to allowUFFDIO_COPY ioctls torun in parallel to the event reception. Single threadedimplementations should continue to use the current async eventdelivery model instead.