userfaultfd.rst 21 KB

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