1.. _userfaultfd: 2 3=========== 4Userfaultfd 5=========== 6 7Objective 8========= 9 10Userfaults allow the implementation of on-demand paging from userland 11and more generally they allow userland to take control of various 12memory page faults, something otherwise only the kernel code could do. 13 14For example userfaults allows a proper and more optimal implementation 15of the ``PROT_NONE+SIGSEGV`` trick. 16 17Design 18====== 19 20Userspace creates a new userfaultfd, initializes it, and registers one or more 21regions of virtual memory with it. Then, any page faults which occur within the 22region(s) result in a message being delivered to the userfaultfd, notifying 23userspace of the fault. 24 25The ``userfaultfd`` (aside from registering and unregistering virtual 26memory ranges) provides two primary functionalities: 27 281) ``read/POLLIN`` protocol to notify a userland thread of the faults 29 happening 30 312) various ``UFFDIO_*`` ioctls that can manage the virtual memory regions 32 registered in the ``userfaultfd`` that allows userland to efficiently 33 resolve the userfaults it receives via 1) or to manage the virtual 34 memory in the background 35 36The real advantage of userfaults if compared to regular virtual memory 37management of mremap/mprotect is that the userfaults in all their 38operations never involve heavyweight structures like vmas (in fact the 39``userfaultfd`` runtime load never takes the mmap_lock for writing). 40Vmas are not suitable for page- (or hugepage) granular fault tracking 41when dealing with virtual address spaces that could span 42Terabytes. Too many vmas would be needed for that. 43 44The ``userfaultfd``, once created, can also be 45passed using unix domain sockets to a manager process, so the same 46manager process could handle the userfaults of a multitude of 47different processes without them being aware about what is going on 48(well of course unless they later try to use the ``userfaultfd`` 49themselves on the same region the manager is already tracking, which 50is a corner case that would currently return ``-EBUSY``). 51 52API 53=== 54 55Creating a userfaultfd 56---------------------- 57 58There are two ways to create a new userfaultfd, each of which provide ways to 59restrict access to this functionality (since historically userfaultfds which 60handle kernel page faults have been a useful tool for exploiting the kernel). 61 62The first way, supported since userfaultfd was introduced, is the 63userfaultfd(2) syscall. Access to this is controlled in several ways: 64 65- Any user can always create a userfaultfd which traps userspace page faults 66 only. Such a userfaultfd can be created using the userfaultfd(2) syscall 67 with the flag UFFD_USER_MODE_ONLY. 68 69- In order to also trap kernel page faults for the address space, either the 70 process needs the CAP_SYS_PTRACE capability, or the system must have 71 vm.unprivileged_userfaultfd set to 1. By default, vm.unprivileged_userfaultfd 72 is set to 0. 73 74The second way, added to the kernel more recently, is by opening 75/dev/userfaultfd and issuing a USERFAULTFD_IOC_NEW ioctl to it. This method 76yields equivalent userfaultfds to the userfaultfd(2) syscall. 77 78Unlike userfaultfd(2), access to /dev/userfaultfd is controlled via normal 79filesystem permissions (user/group/mode), which gives fine grained access to 80userfaultfd specifically, without also granting other unrelated privileges at 81the same time (as e.g. granting CAP_SYS_PTRACE would do). Users who have access 82to /dev/userfaultfd can always create userfaultfds that trap kernel page faults; 83vm.unprivileged_userfaultfd is not considered. 84 85Initializing a userfaultfd 86-------------------------- 87 88When first opened the ``userfaultfd`` must be enabled invoking the 89``UFFDIO_API`` ioctl specifying a ``uffdio_api.api`` value set to ``UFFD_API`` (or 90a later API version) which will specify the ``read/POLLIN`` protocol 91userland intends to speak on the ``UFFD`` and the ``uffdio_api.features`` 92userland requires. The ``UFFDIO_API`` ioctl if successful (i.e. if the 93requested ``uffdio_api.api`` is spoken also by the running kernel and the 94requested features are going to be enabled) will return into 95``uffdio_api.features`` and ``uffdio_api.ioctls`` two 64bit bitmasks of 96respectively all the available features of the read(2) protocol and 97the generic ioctl available. 98 99The ``uffdio_api.features`` bitmask returned by the ``UFFDIO_API`` ioctl 100defines what memory types are supported by the ``userfaultfd`` and what 101events, except page fault notifications, may be generated: 102 103- The ``UFFD_FEATURE_EVENT_*`` flags indicate that various other events 104 other than page faults are supported. These events are described in more 105 detail below in the `Non-cooperative userfaultfd`_ section. 106 107- ``UFFD_FEATURE_MISSING_HUGETLBFS`` and ``UFFD_FEATURE_MISSING_SHMEM`` 108 indicate that the kernel supports ``UFFDIO_REGISTER_MODE_MISSING`` 109 registrations for hugetlbfs and shared memory (covering all shmem APIs, 110 i.e. tmpfs, ``IPCSHM``, ``/dev/zero``, ``MAP_SHARED``, ``memfd_create``, 111 etc) virtual memory areas, respectively. 112 113- ``UFFD_FEATURE_MINOR_HUGETLBFS`` indicates that the kernel supports 114 ``UFFDIO_REGISTER_MODE_MINOR`` registration for hugetlbfs virtual memory 115 areas. ``UFFD_FEATURE_MINOR_SHMEM`` is the analogous feature indicating 116 support for shmem virtual memory areas. 117 118The userland application should set the feature flags it intends to use 119when invoking the ``UFFDIO_API`` ioctl, to request that those features be 120enabled if supported. 121 122Once the ``userfaultfd`` API has been enabled the ``UFFDIO_REGISTER`` 123ioctl should be invoked (if present in the returned ``uffdio_api.ioctls`` 124bitmask) to register a memory range in the ``userfaultfd`` by setting the 125uffdio_register structure accordingly. The ``uffdio_register.mode`` 126bitmask will specify to the kernel which kind of faults to track for 127the range. The ``UFFDIO_REGISTER`` ioctl will return the 128``uffdio_register.ioctls`` bitmask of ioctls that are suitable to resolve 129userfaults on the range registered. Not all ioctls will necessarily be 130supported for all memory types (e.g. anonymous memory vs. shmem vs. 131hugetlbfs), or all types of intercepted faults. 132 133Userland can use the ``uffdio_register.ioctls`` to manage the virtual 134address space in the background (to add or potentially also remove 135memory from the ``userfaultfd`` registered range). This means a userfault 136could be triggering just before userland maps in the background the 137user-faulted page. 138 139Resolving Userfaults 140-------------------- 141 142There are three basic ways to resolve userfaults: 143 144- ``UFFDIO_COPY`` atomically copies some existing page contents from 145 userspace. 146 147- ``UFFDIO_ZEROPAGE`` atomically zeros the new page. 148 149- ``UFFDIO_CONTINUE`` maps an existing, previously-populated page. 150 151These operations are atomic in the sense that they guarantee nothing can 152see a half-populated page, since readers will keep userfaulting until the 153operation has finished. 154 155By default, these wake up userfaults blocked on the range in question. 156They support a ``UFFDIO_*_MODE_DONTWAKE`` ``mode`` flag, which indicates 157that waking will be done separately at some later time. 158 159Which ioctl to choose depends on the kind of page fault, and what we'd 160like to do to resolve it: 161 162- For ``UFFDIO_REGISTER_MODE_MISSING`` faults, the fault needs to be 163 resolved by either providing a new page (``UFFDIO_COPY``), or mapping 164 the zero page (``UFFDIO_ZEROPAGE``). By default, the kernel would map 165 the zero page for a missing fault. With userfaultfd, userspace can 166 decide what content to provide before the faulting thread continues. 167 168- For ``UFFDIO_REGISTER_MODE_MINOR`` faults, there is an existing page (in 169 the page cache). Userspace has the option of modifying the page's 170 contents before resolving the fault. Once the contents are correct 171 (modified or not), userspace asks the kernel to map the page and let the 172 faulting thread continue with ``UFFDIO_CONTINUE``. 173 174Notes: 175 176- You can tell which kind of fault occurred by examining 177 ``pagefault.flags`` within the ``uffd_msg``, checking for the 178 ``UFFD_PAGEFAULT_FLAG_*`` flags. 179 180- None of the page-delivering ioctls default to the range that you 181 registered with. You must fill in all fields for the appropriate 182 ioctl struct including the range. 183 184- You get the address of the access that triggered the missing page 185 event out of a struct uffd_msg that you read in the thread from the 186 uffd. You can supply as many pages as you want with these IOCTLs. 187 Keep in mind that unless you used DONTWAKE then the first of any of 188 those IOCTLs wakes up the faulting thread. 189 190- Be sure to test for all errors including 191 (``pollfd[0].revents & POLLERR``). This can happen, e.g. when ranges 192 supplied were incorrect. 193 194Write Protect Notifications 195--------------------------- 196 197This is equivalent to (but faster than) using mprotect and a SIGSEGV 198signal handler. 199 200Firstly you need to register a range with ``UFFDIO_REGISTER_MODE_WP``. 201Instead of using mprotect(2) you use 202``ioctl(uffd, UFFDIO_WRITEPROTECT, struct *uffdio_writeprotect)`` 203while ``mode = UFFDIO_WRITEPROTECT_MODE_WP`` 204in the struct passed in. The range does not default to and does not 205have to be identical to the range you registered with. You can write 206protect as many ranges as you like (inside the registered range). 207Then, in the thread reading from uffd the struct will have 208``msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP`` set. Now you send 209``ioctl(uffd, UFFDIO_WRITEPROTECT, struct *uffdio_writeprotect)`` 210again while ``pagefault.mode`` does not have ``UFFDIO_WRITEPROTECT_MODE_WP`` 211set. This wakes up the thread which will continue to run with writes. This 212allows you to do the bookkeeping about the write in the uffd reading 213thread before the ioctl. 214 215If you registered with both ``UFFDIO_REGISTER_MODE_MISSING`` and 216``UFFDIO_REGISTER_MODE_WP`` then you need to think about the sequence in 217which you supply a page and undo write protect. Note that there is a 218difference between writes into a WP area and into a !WP area. The 219former will have ``UFFD_PAGEFAULT_FLAG_WP`` set, the latter 220``UFFD_PAGEFAULT_FLAG_WRITE``. The latter did not fail on protection but 221you still need to supply a page when ``UFFDIO_REGISTER_MODE_MISSING`` was 222used. 223 224QEMU/KVM 225======== 226 227QEMU/KVM is using the ``userfaultfd`` syscall to implement postcopy live 228migration. Postcopy live migration is one form of memory 229externalization consisting of a virtual machine running with part or 230all of its memory residing on a different node in the cloud. The 231``userfaultfd`` abstraction is generic enough that not a single line of 232KVM kernel code had to be modified in order to add postcopy live 233migration to QEMU. 234 235Guest async page faults, ``FOLL_NOWAIT`` and all other ``GUP*`` features work 236just fine in combination with userfaults. Userfaults trigger async 237page faults in the guest scheduler so those guest processes that 238aren't waiting for userfaults (i.e. network bound) can keep running in 239the guest vcpus. 240 241It is generally beneficial to run one pass of precopy live migration 242just before starting postcopy live migration, in order to avoid 243generating userfaults for readonly guest regions. 244 245The implementation of postcopy live migration currently uses one 246single bidirectional socket but in the future two different sockets 247will be used (to reduce the latency of the userfaults to the minimum 248possible without having to decrease ``/proc/sys/net/ipv4/tcp_wmem``). 249 250The QEMU in the source node writes all pages that it knows are missing 251in the destination node, into the socket, and the migration thread of 252the QEMU running in the destination node runs ``UFFDIO_COPY|ZEROPAGE`` 253ioctls on the ``userfaultfd`` in order to map the received pages into the 254guest (``UFFDIO_ZEROCOPY`` is used if the source page was a zero page). 255 256A different postcopy thread in the destination node listens with 257poll() to the ``userfaultfd`` in parallel. When a ``POLLIN`` event is 258generated after a userfault triggers, the postcopy thread read() from 259the ``userfaultfd`` and receives the fault address (or ``-EAGAIN`` in case the 260userfault was already resolved and waken by a ``UFFDIO_COPY|ZEROPAGE`` run 261by the parallel QEMU migration thread). 262 263After the QEMU postcopy thread (running in the destination node) gets 264the userfault address it writes the information about the missing page 265into the socket. The QEMU source node receives the information and 266roughly "seeks" to that page address and continues sending all 267remaining missing pages from that new page offset. Soon after that 268(just the time to flush the tcp_wmem queue through the network) the 269migration thread in the QEMU running in the destination node will 270receive the page that triggered the userfault and it'll map it as 271usual with the ``UFFDIO_COPY|ZEROPAGE`` (without actually knowing if it 272was spontaneously sent by the source or if it was an urgent page 273requested through a userfault). 274 275By the time the userfaults start, the QEMU in the destination node 276doesn't need to keep any per-page state bitmap relative to the live 277migration around and a single per-page bitmap has to be maintained in 278the QEMU running in the source node to know which pages are still 279missing in the destination node. The bitmap in the source node is 280checked to find which missing pages to send in round robin and we seek 281over it when receiving incoming userfaults. After sending each page of 282course the bitmap is updated accordingly. It's also useful to avoid 283sending the same page twice (in case the userfault is read by the 284postcopy thread just before ``UFFDIO_COPY|ZEROPAGE`` runs in the migration 285thread). 286 287Non-cooperative userfaultfd 288=========================== 289 290When the ``userfaultfd`` is monitored by an external manager, the manager 291must be able to track changes in the process virtual memory 292layout. Userfaultfd can notify the manager about such changes using 293the same read(2) protocol as for the page fault notifications. The 294manager has to explicitly enable these events by setting appropriate 295bits in ``uffdio_api.features`` passed to ``UFFDIO_API`` ioctl: 296 297``UFFD_FEATURE_EVENT_FORK`` 298 enable ``userfaultfd`` hooks for fork(). When this feature is 299 enabled, the ``userfaultfd`` context of the parent process is 300 duplicated into the newly created process. The manager 301 receives ``UFFD_EVENT_FORK`` with file descriptor of the new 302 ``userfaultfd`` context in the ``uffd_msg.fork``. 303 304``UFFD_FEATURE_EVENT_REMAP`` 305 enable notifications about mremap() calls. When the 306 non-cooperative process moves a virtual memory area to a 307 different location, the manager will receive 308 ``UFFD_EVENT_REMAP``. The ``uffd_msg.remap`` will contain the old and 309 new addresses of the area and its original length. 310 311``UFFD_FEATURE_EVENT_REMOVE`` 312 enable notifications about madvise(MADV_REMOVE) and 313 madvise(MADV_DONTNEED) calls. The event ``UFFD_EVENT_REMOVE`` will 314 be generated upon these calls to madvise(). The ``uffd_msg.remove`` 315 will contain start and end addresses of the removed area. 316 317``UFFD_FEATURE_EVENT_UNMAP`` 318 enable notifications about memory unmapping. The manager will 319 get ``UFFD_EVENT_UNMAP`` with ``uffd_msg.remove`` containing start and 320 end addresses of the unmapped area. 321 322Although the ``UFFD_FEATURE_EVENT_REMOVE`` and ``UFFD_FEATURE_EVENT_UNMAP`` 323are pretty similar, they quite differ in the action expected from the 324``userfaultfd`` manager. In the former case, the virtual memory is 325removed, but the area is not, the area remains monitored by the 326``userfaultfd``, and if a page fault occurs in that area it will be 327delivered to the manager. The proper resolution for such page fault is 328to zeromap the faulting address. However, in the latter case, when an 329area is unmapped, either explicitly (with munmap() system call), or 330implicitly (e.g. during mremap()), the area is removed and in turn the 331``userfaultfd`` context for such area disappears too and the manager will 332not get further userland page faults from the removed area. Still, the 333notification is required in order to prevent manager from using 334``UFFDIO_COPY`` on the unmapped area. 335 336Unlike userland page faults which have to be synchronous and require 337explicit or implicit wakeup, all the events are delivered 338asynchronously and the non-cooperative process resumes execution as 339soon as manager executes read(). The ``userfaultfd`` manager should 340carefully synchronize calls to ``UFFDIO_COPY`` with the events 341processing. To aid the synchronization, the ``UFFDIO_COPY`` ioctl will 342return ``-ENOSPC`` when the monitored process exits at the time of 343``UFFDIO_COPY``, and ``-ENOENT``, when the non-cooperative process has changed 344its virtual memory layout simultaneously with outstanding ``UFFDIO_COPY`` 345operation. 346 347The current asynchronous model of the event delivery is optimal for 348single threaded non-cooperative ``userfaultfd`` manager implementations. A 349synchronous event delivery model can be added later as a new 350``userfaultfd`` feature to facilitate multithreading enhancements of the 351non cooperative manager, for example to allow ``UFFDIO_COPY`` ioctls to 352run in parallel to the event reception. Single threaded 353implementations should continue to use the current async event 354delivery model instead. 355