GNU Linux-libre 6.1.90-gnu
[releases.git] / Documentation / admin-guide / mm / userfaultfd.rst
1 .. _userfaultfd:
2
3 ===========
4 Userfaultfd
5 ===========
6
7 Objective
8 =========
9
10 Userfaults allow the implementation of on-demand paging from userland
11 and more generally they allow userland to take control of various
12 memory page faults, something otherwise only the kernel code could do.
13
14 For example userfaults allows a proper and more optimal implementation
15 of the ``PROT_NONE+SIGSEGV`` trick.
16
17 Design
18 ======
19
20 Userspace creates a new userfaultfd, initializes it, and registers one or more
21 regions of virtual memory with it. Then, any page faults which occur within the
22 region(s) result in a message being delivered to the userfaultfd, notifying
23 userspace of the fault.
24
25 The ``userfaultfd`` (aside from registering and unregistering virtual
26 memory ranges) provides two primary functionalities:
27
28 1) ``read/POLLIN`` protocol to notify a userland thread of the faults
29    happening
30
31 2) 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
36 The real advantage of userfaults if compared to regular virtual memory
37 management of mremap/mprotect is that the userfaults in all their
38 operations never involve heavyweight structures like vmas (in fact the
39 ``userfaultfd`` runtime load never takes the mmap_lock for writing).
40 Vmas are not suitable for page- (or hugepage) granular fault tracking
41 when dealing with virtual address spaces that could span
42 Terabytes. Too many vmas would be needed for that.
43
44 The ``userfaultfd``, once created, can also be
45 passed using unix domain sockets to a manager process, so the same
46 manager process could handle the userfaults of a multitude of
47 different processes without them being aware about what is going on
48 (well of course unless they later try to use the ``userfaultfd``
49 themselves on the same region the manager is already tracking, which
50 is a corner case that would currently return ``-EBUSY``).
51
52 API
53 ===
54
55 Creating a userfaultfd
56 ----------------------
57
58 There are two ways to create a new userfaultfd, each of which provide ways to
59 restrict access to this functionality (since historically userfaultfds which
60 handle kernel page faults have been a useful tool for exploiting the kernel).
61
62 The first way, supported since userfaultfd was introduced, is the
63 userfaultfd(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
74 The 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
76 yields equivalent userfaultfds to the userfaultfd(2) syscall.
77
78 Unlike userfaultfd(2), access to /dev/userfaultfd is controlled via normal
79 filesystem permissions (user/group/mode), which gives fine grained access to
80 userfaultfd specifically, without also granting other unrelated privileges at
81 the same time (as e.g. granting CAP_SYS_PTRACE would do). Users who have access
82 to /dev/userfaultfd can always create userfaultfds that trap kernel page faults;
83 vm.unprivileged_userfaultfd is not considered.
84
85 Initializing a userfaultfd
86 --------------------------
87
88 When first opened the ``userfaultfd`` must be enabled invoking the
89 ``UFFDIO_API`` ioctl specifying a ``uffdio_api.api`` value set to ``UFFD_API`` (or
90 a later API version) which will specify the ``read/POLLIN`` protocol
91 userland intends to speak on the ``UFFD`` and the ``uffdio_api.features``
92 userland requires. The ``UFFDIO_API`` ioctl if successful (i.e. if the
93 requested ``uffdio_api.api`` is spoken also by the running kernel and the
94 requested features are going to be enabled) will return into
95 ``uffdio_api.features`` and ``uffdio_api.ioctls`` two 64bit bitmasks of
96 respectively all the available features of the read(2) protocol and
97 the generic ioctl available.
98
99 The ``uffdio_api.features`` bitmask returned by the ``UFFDIO_API`` ioctl
100 defines what memory types are supported by the ``userfaultfd`` and what
101 events, 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
118 The userland application should set the feature flags it intends to use
119 when invoking the ``UFFDIO_API`` ioctl, to request that those features be
120 enabled if supported.
121
122 Once the ``userfaultfd`` API has been enabled the ``UFFDIO_REGISTER``
123 ioctl should be invoked (if present in the returned ``uffdio_api.ioctls``
124 bitmask) to register a memory range in the ``userfaultfd`` by setting the
125 uffdio_register structure accordingly. The ``uffdio_register.mode``
126 bitmask will specify to the kernel which kind of faults to track for
127 the range. The ``UFFDIO_REGISTER`` ioctl will return the
128 ``uffdio_register.ioctls`` bitmask of ioctls that are suitable to resolve
129 userfaults on the range registered. Not all ioctls will necessarily be
130 supported for all memory types (e.g. anonymous memory vs. shmem vs.
131 hugetlbfs), or all types of intercepted faults.
132
133 Userland can use the ``uffdio_register.ioctls`` to manage the virtual
134 address space in the background (to add or potentially also remove
135 memory from the ``userfaultfd`` registered range). This means a userfault
136 could be triggering just before userland maps in the background the
137 user-faulted page.
138
139 Resolving Userfaults
140 --------------------
141
142 There 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
151 These operations are atomic in the sense that they guarantee nothing can
152 see a half-populated page, since readers will keep userfaulting until the
153 operation has finished.
154
155 By default, these wake up userfaults blocked on the range in question.
156 They support a ``UFFDIO_*_MODE_DONTWAKE`` ``mode`` flag, which indicates
157 that waking will be done separately at some later time.
158
159 Which ioctl to choose depends on the kind of page fault, and what we'd
160 like 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
174 Notes:
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
194 Write Protect Notifications
195 ---------------------------
196
197 This is equivalent to (but faster than) using mprotect and a SIGSEGV
198 signal handler.
199
200 Firstly you need to register a range with ``UFFDIO_REGISTER_MODE_WP``.
201 Instead of using mprotect(2) you use
202 ``ioctl(uffd, UFFDIO_WRITEPROTECT, struct *uffdio_writeprotect)``
203 while ``mode = UFFDIO_WRITEPROTECT_MODE_WP``
204 in the struct passed in.  The range does not default to and does not
205 have to be identical to the range you registered with.  You can write
206 protect as many ranges as you like (inside the registered range).
207 Then, 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)``
210 again while ``pagefault.mode`` does not have ``UFFDIO_WRITEPROTECT_MODE_WP``
211 set. This wakes up the thread which will continue to run with writes. This
212 allows you to do the bookkeeping about the write in the uffd reading
213 thread before the ioctl.
214
215 If you registered with both ``UFFDIO_REGISTER_MODE_MISSING`` and
216 ``UFFDIO_REGISTER_MODE_WP`` then you need to think about the sequence in
217 which you supply a page and undo write protect.  Note that there is a
218 difference between writes into a WP area and into a !WP area.  The
219 former will have ``UFFD_PAGEFAULT_FLAG_WP`` set, the latter
220 ``UFFD_PAGEFAULT_FLAG_WRITE``.  The latter did not fail on protection but
221 you still need to supply a page when ``UFFDIO_REGISTER_MODE_MISSING`` was
222 used.
223
224 QEMU/KVM
225 ========
226
227 QEMU/KVM is using the ``userfaultfd`` syscall to implement postcopy live
228 migration. Postcopy live migration is one form of memory
229 externalization consisting of a virtual machine running with part or
230 all of its memory residing on a different node in the cloud. The
231 ``userfaultfd`` abstraction is generic enough that not a single line of
232 KVM kernel code had to be modified in order to add postcopy live
233 migration to QEMU.
234
235 Guest async page faults, ``FOLL_NOWAIT`` and all other ``GUP*`` features work
236 just fine in combination with userfaults. Userfaults trigger async
237 page faults in the guest scheduler so those guest processes that
238 aren't waiting for userfaults (i.e. network bound) can keep running in
239 the guest vcpus.
240
241 It is generally beneficial to run one pass of precopy live migration
242 just before starting postcopy live migration, in order to avoid
243 generating userfaults for readonly guest regions.
244
245 The implementation of postcopy live migration currently uses one
246 single bidirectional socket but in the future two different sockets
247 will be used (to reduce the latency of the userfaults to the minimum
248 possible without having to decrease ``/proc/sys/net/ipv4/tcp_wmem``).
249
250 The QEMU in the source node writes all pages that it knows are missing
251 in the destination node, into the socket, and the migration thread of
252 the QEMU running in the destination node runs ``UFFDIO_COPY|ZEROPAGE``
253 ioctls on the ``userfaultfd`` in order to map the received pages into the
254 guest (``UFFDIO_ZEROCOPY`` is used if the source page was a zero page).
255
256 A different postcopy thread in the destination node listens with
257 poll() to the ``userfaultfd`` in parallel. When a ``POLLIN`` event is
258 generated after a userfault triggers, the postcopy thread read() from
259 the ``userfaultfd`` and receives the fault address (or ``-EAGAIN`` in case the
260 userfault was already resolved and waken by a ``UFFDIO_COPY|ZEROPAGE`` run
261 by the parallel QEMU migration thread).
262
263 After the QEMU postcopy thread (running in the destination node) gets
264 the userfault address it writes the information about the missing page
265 into the socket. The QEMU source node receives the information and
266 roughly "seeks" to that page address and continues sending all
267 remaining missing pages from that new page offset. Soon after that
268 (just the time to flush the tcp_wmem queue through the network) the
269 migration thread in the QEMU running in the destination node will
270 receive the page that triggered the userfault and it'll map it as
271 usual with the ``UFFDIO_COPY|ZEROPAGE`` (without actually knowing if it
272 was spontaneously sent by the source or if it was an urgent page
273 requested through a userfault).
274
275 By the time the userfaults start, the QEMU in the destination node
276 doesn't need to keep any per-page state bitmap relative to the live
277 migration around and a single per-page bitmap has to be maintained in
278 the QEMU running in the source node to know which pages are still
279 missing in the destination node. The bitmap in the source node is
280 checked to find which missing pages to send in round robin and we seek
281 over it when receiving incoming userfaults. After sending each page of
282 course the bitmap is updated accordingly. It's also useful to avoid
283 sending the same page twice (in case the userfault is read by the
284 postcopy thread just before ``UFFDIO_COPY|ZEROPAGE`` runs in the migration
285 thread).
286
287 Non-cooperative userfaultfd
288 ===========================
289
290 When the ``userfaultfd`` is monitored by an external manager, the manager
291 must be able to track changes in the process virtual memory
292 layout. Userfaultfd can notify the manager about such changes using
293 the same read(2) protocol as for the page fault notifications. The
294 manager has to explicitly enable these events by setting appropriate
295 bits 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
322 Although the ``UFFD_FEATURE_EVENT_REMOVE`` and ``UFFD_FEATURE_EVENT_UNMAP``
323 are pretty similar, they quite differ in the action expected from the
324 ``userfaultfd`` manager. In the former case, the virtual memory is
325 removed, 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
327 delivered to the manager. The proper resolution for such page fault is
328 to zeromap the faulting address. However, in the latter case, when an
329 area is unmapped, either explicitly (with munmap() system call), or
330 implicitly (e.g. during mremap()), the area is removed and in turn the
331 ``userfaultfd`` context for such area disappears too and the manager will
332 not get further userland page faults from the removed area. Still, the
333 notification is required in order to prevent manager from using
334 ``UFFDIO_COPY`` on the unmapped area.
335
336 Unlike userland page faults which have to be synchronous and require
337 explicit or implicit wakeup, all the events are delivered
338 asynchronously and the non-cooperative process resumes execution as
339 soon as manager executes read(). The ``userfaultfd`` manager should
340 carefully synchronize calls to ``UFFDIO_COPY`` with the events
341 processing. To aid the synchronization, the ``UFFDIO_COPY`` ioctl will
342 return ``-ENOSPC`` when the monitored process exits at the time of
343 ``UFFDIO_COPY``, and ``-ENOENT``, when the non-cooperative process has changed
344 its virtual memory layout simultaneously with outstanding ``UFFDIO_COPY``
345 operation.
346
347 The current asynchronous model of the event delivery is optimal for
348 single threaded non-cooperative ``userfaultfd`` manager implementations. A
349 synchronous event delivery model can be added later as a new
350 ``userfaultfd`` feature to facilitate multithreading enhancements of the
351 non cooperative manager, for example to allow ``UFFDIO_COPY`` ioctls to
352 run in parallel to the event reception. Single threaded
353 implementations should continue to use the current async event
354 delivery model instead.