← Documents Documentation/admin-guide/mm/userfaultfd.rst GitHub 원문 ↗

Linux 6.18.37 · Administration / Memory Management

Userfaultfd

Userspace page-fault 관리의 생성·협상·등록·해소 API, write-protect와 poison mode, QEMU postcopy 및 외부 manager event를 설명합니다.

Source pathDocumentation/admin-guide/mm/userfaultfd.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

운영 핵심

userfaultfd.rst:1-430

Userfaultfd는 faulting thread를 kernel에서 즉시 해소하지 않고 userspace manager가 page 내용과 mapping 시점을 결정하게 합니다. API와 range별 ioctl bitmask를 먼저 협상하고, fault 종류·memory type·wake 정책을 확인한 뒤 해소해야 합니다.

관점핵심
생성`userfaultfd(2)` 또는 `/dev/userfaultfd` + `USERFAULTFD_IOC_NEW`
협상`UFFDIO_API`로 protocol feature와 generic ioctl bitmask 확인
등록`UFFDIO_REGISTER`의 mode로 missing, minor, WP fault 선택
해소`UFFDIO_COPY`, `UFFDIO_ZEROPAGE`, `UFFDIO_CONTINUE`
외부 관리fork/remap/remove/unmap event와 QEMU postcopy migration 지원

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

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

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

목표

1-14

Userfault는 userspace에서 demand paging을 구현하게 하며, 더 일반적으로는 원래 kernel code만 제어할 수 있던 여러 종류의 memory page fault를 userspace가 제어하게 합니다.

예를 들어 userfault를 사용하면 `PROT_NONE+SIGSEGV` 기법을 더 올바르고 효율적으로 구현할 수 있습니다.

설계

15-49

Userspace는 새 userfaultfd를 만들고 초기화한 뒤 하나 이상의 virtual memory region을 등록합니다. 등록한 region에서 page fault가 발생하면 userfaultfd로 message가 전달되어 userspace에 fault를 알립니다.

구분기능역할
1`read/POLLIN` protocol발생한 fault를 userspace 관리 thread에 알림
2`UFFDIO_*` ioctl등록한 virtual memory range의 fault 해소와 background memory 관리

일반적인 `mremap`/`mprotect` virtual memory 관리와 비교할 때 userfault의 실질적 장점은 모든 동작에서 VMA 같은 무거운 구조를 건드리지 않는다는 점입니다. 실제로 `userfaultfd` runtime load는 write 용도로 `mmap_lock`을 잡지 않습니다. Terabyte 규모의 virtual address space에서 page 또는 hugepage 단위 fault를 추적하려면 너무 많은 VMA가 필요하므로 VMA는 적합하지 않습니다.

만든 `userfaultfd`는 unix domain socket으로 manager process에 전달할 수 있습니다. 따라서 하나의 manager가 여러 process가 내부 동작을 알지 못한 채 발생시키는 userfault를 처리할 수 있습니다. 다만 process가 manager가 이미 추적하는 같은 region에 직접 `userfaultfd`를 사용하려 하면 현재 그 corner case는 `-EBUSY`를 반환합니다.

userfaultfd 생성과 접근 제어

50-82

새 userfaultfd를 만드는 방법은 두 가지이며, kernel page fault를 처리하는 userfaultfd가 역사적으로 kernel exploit에 유용한 수단이었기 때문에 두 경로 모두 접근을 제한할 수 있습니다.

생성 경로필요 권한범위
`userfaultfd(2)` + `UFFD_USER_MODE_ONLY`모든 사용자userspace page fault만 포착
`userfaultfd(2)``CAP_SYS_PTRACE` 또는 `vm.unprivileged_userfaultfd=1`kernel page fault까지 포착
`/dev/userfaultfd` + `USERFAULTFD_IOC_NEW`device의 user/group/mode 권한kernel page fault 포착 가능, sysctl은 고려하지 않음

처음부터 지원된 `userfaultfd(2)` syscall에서는 누구나 `UFFD_USER_MODE_ONLY` flag로 userspace page fault만 포착하는 fd를 만들 수 있습니다. Address space의 kernel page fault까지 포착하려면 process에 `CAP_SYS_PTRACE`가 있거나 `vm.unprivileged_userfaultfd`가 1이어야 하며, 이 sysctl의 기본값은 0입니다.

더 최근에 추가된 방법은 `/dev/userfaultfd`를 열고 `USERFAULTFD_IOC_NEW` ioctl을 호출하는 것입니다. 결과 fd는 `userfaultfd(2)`가 만드는 것과 동등합니다. 접근은 일반 filesystem user/group/mode 권한으로 제어되므로 `CAP_SYS_PTRACE`처럼 관련 없는 권한까지 부여하지 않고 userfaultfd만 세밀하게 허용할 수 있습니다. Device 접근 권한이 있는 사용자는 kernel page fault를 포착하는 fd를 항상 만들 수 있으며 `vm.unprivileged_userfaultfd`는 고려되지 않습니다.

API 초기화와 feature 협상

83-122

처음 연 `userfaultfd`는 `uffdio_api.api`를 `UFFD_API` 또는 이후 API version으로 설정해 `UFFDIO_API` ioctl을 호출함으로써 활성화해야 합니다. 이 값은 userspace가 UFFD에서 사용할 `read/POLLIN` protocol을 정하고, `uffdio_api.features`는 필요한 기능을 지정합니다.

실행 중인 kernel이 요청 API를 지원하고 요청 feature를 활성화할 수 있으면 `UFFDIO_API`는 성공합니다. 그리고 `uffdio_api.features`와 `uffdio_api.ioctls`에 각각 read(2) protocol의 가용 feature와 generic ioctl을 나타내는 64-bit bitmask를 돌려줍니다.

feature의미
`UFFD_FEATURE_EVENT_*`page fault 외 fork/remap/remove/unmap event 지원
`UFFD_FEATURE_MISSING_HUGETLBFS`hugetlbfs에서 `UFFDIO_REGISTER_MODE_MISSING` 지원
`UFFD_FEATURE_MISSING_SHMEM`tmpfs, `IPCSHM`, `/dev/zero`, `MAP_SHARED`, `memfd_create` 등 shmem에서 missing mode 지원
`UFFD_FEATURE_MINOR_HUGETLBFS`hugetlbfs에서 `UFFDIO_REGISTER_MODE_MINOR` 지원
`UFFD_FEATURE_MINOR_SHMEM`shmem virtual memory area에서 minor mode 지원
`UFFD_FEATURE_MOVE`기존 page 내용을 userspace에서 이동

`uffdio_api.features`는 userfaultfd가 지원하는 memory type과 page fault notification 외에 생성할 수 있는 event를 정의합니다. Application은 사용할 feature flag를 `UFFDIO_API` 호출 전에 설정해, 지원되는 경우 해당 기능을 활성화하도록 요청해야 합니다.

Memory range 등록

123-139

API를 활성화한 뒤 반환된 `uffdio_api.ioctls` bitmask에 `UFFDIO_REGISTER`가 있으면 `uffdio_register` 구조체를 채워 memory range를 등록합니다. `uffdio_register.mode` bitmask는 kernel이 그 range에서 추적할 fault 종류를 지정합니다.

`UFFDIO_REGISTER`는 등록 range의 userfault를 해소하는 데 적합한 ioctl을 `uffdio_register.ioctls` bitmask로 반환합니다. Anonymous memory, shmem, hugetlbfs 같은 memory type과 포착한 fault 종류에 따라 모든 ioctl이 지원되는 것은 아닙니다.

Userspace는 이 range별 ioctl 집합으로 background에서 virtual address space에 memory를 추가하거나 제거할 수 있습니다. 따라서 userspace가 background에서 fault page를 mapping하기 직전에 userfault가 발생하는 경쟁도 고려해야 합니다.

Userfault 해소

140-194
ioctl동작주요 fault
`UFFDIO_COPY`userspace의 기존 page 내용을 새 page로 atomic copy주로 missing fault
`UFFDIO_ZEROPAGE`새 page를 atomic하게 zero-fillmissing fault
`UFFDIO_CONTINUE`이미 populate된 page를 mappingminor fault

세 동작은 reader가 완료될 때까지 계속 userfault를 발생시키므로 절반만 populate된 page를 누구도 볼 수 없다는 의미에서 atomic합니다. 기본적으로 대상 range에서 block된 userfault를 깨우며, 나중에 별도로 깨우려면 `UFFDIO_*_MODE_DONTWAKE` mode flag를 사용합니다.

등록 mode상태해소
`UFFDIO_REGISTER_MODE_MISSING`mapping할 page가 없음`UFFDIO_COPY` 또는 `UFFDIO_ZEROPAGE`
`UFFDIO_REGISTER_MODE_MINOR`page cache에 page가 이미 있음필요하면 내용을 수정한 뒤 `UFFDIO_CONTINUE`

Missing fault에서는 kernel 기본 zero-page mapping 대신 userspace가 faulting thread를 재개하기 전에 제공할 내용을 결정할 수 있습니다. Minor fault에는 page cache의 기존 page가 있으므로 userspace가 내용을 수정하거나 그대로 둔 뒤 `UFFDIO_CONTINUE`로 mapping을 요청합니다.

주의점요구 사항
fault 종류`uffd_msg.pagefault.flags`의 `UFFD_PAGEFAULT_FLAG_*` 검사
rangepage 전달 ioctl은 등록 range를 기본값으로 쓰지 않으므로 struct의 모든 range field를 채움
wake`UFFDIO_*_MODE_DONTWAKE`가 없으면 첫 해소 ioctl이 faulting thread를 깨움
오류`pollfd[0].revents & POLLERR`를 포함해 잘못된 range 등의 모든 error를 검사

`uffd_msg`에서 실제 access address를 얻고 한 번에 여러 page를 공급할 수 있지만, `DONTWAKE`를 쓰지 않았다면 첫 해소 ioctl이 faulting thread를 깨운다는 점을 순서 설계에 반영해야 합니다.

Userfault 처리 순서
단계Faulting threaduserfaultfd manager
01 1등록 range 접근 후 block`read/POLLIN`으로 `uffd_msg` 수신
02 2대기`pagefault.flags`와 address 판독
03 3대기`COPY`, `ZEROPAGE`, `CONTINUE` 중 해소 동작 선택
04 4wake 후 재실행필요하면 `DONTWAKE` 뒤 별도 wake

Faulting thread는 manager가 atomic 해소 ioctl을 끝낼 때까지 대기합니다.

Write-protect notification

195-224

Write-protect notification은 `mprotect`와 `SIGSEGV` signal handler를 조합한 방식과 동등하지만 더 빠릅니다.

단계interface결과
등록`UFFDIO_REGISTER_MODE_WP`write-protect fault 추적 활성화
보호`UFFDIO_WRITEPROTECT_MODE_WP` 설정 후 `UFFDIO_WRITEPROTECT`등록 range 내부의 임의 하위 range를 보호
통지`msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP`관리 thread가 write 시도를 식별
해제`UFFDIO_WRITEPROTECT_MODE_WP` 없이 `UFFDIO_WRITEPROTECT`bookkeeping 후 faulting thread를 깨워 write 재개

먼저 `UFFDIO_REGISTER_MODE_WP`로 range를 등록합니다. `mprotect(2)` 대신 `mode = UFFDIO_WRITEPROTECT_MODE_WP`인 `ioctl(uffd, UFFDIO_WRITEPROTECT, struct *uffdio_writeprotect)`를 사용합니다. 보호 range는 등록 range와 같을 필요가 없고 그 내부에서 여러 range를 보호할 수 있습니다.

UFFD reader thread는 `msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP`로 보호 위반을 확인합니다. Bookkeeping을 마친 뒤 WP mode bit 없이 `UFFDIO_WRITEPROTECT`를 다시 호출하면 thread가 깨어나 write를 계속합니다.

`UFFDIO_REGISTER_MODE_MISSING`과 `UFFDIO_REGISTER_MODE_WP`를 함께 등록했다면 page 공급과 WP 해제 순서를 고려해야 합니다. WP area write에는 `UFFD_PAGEFAULT_FLAG_WP`가, 비-WP area write에는 `UFFD_PAGEFAULT_FLAG_WRITE`가 설정됩니다. 후자는 protection 실패가 아니지만 missing mode를 썼다면 여전히 page를 공급해야 합니다.

None PTE와 결합 mode

225-249

Userfaultfd write-protect mode는 page가 없는 none PTE를 memory type에 따라 다르게 처리합니다.

memory / 방식none PTE 처리결과
anonymous memory기본적으로 none PTE를 무시missing page write가 WP message를 만들지 않음
shmem / hugetlbfsnone PTE도 present PTE처럼 보호미리 보호한 missing page write도 WP message 생성
anonymous 보완`MADV_POPULATE_READ` 또는 `UFFD_FEATURE_WP_UNPOPULATED`none PTE까지 write-protect
missing/minor 해소와 결합`UFFDIO_COPY_MODE_WP` / `UFFDIO_CONTINUE_MODE_WP`새 page 또는 mapping을 보호된 상태로 설치

Anonymous memory에서는 `ioctl(UFFDIO_WRITEPROTECT)`가 기본적으로 populate되지 않은 none PTE를 무시합니다. 반면 shmem과 hugetlbfs 같은 file-backed memory에서는 none PTE도 present PTE처럼 보호하므로, 미리 보호한 range의 missing page에 write하면 userfaultfd write fault message가 발생합니다.

Anonymous none PTE도 보호하려면 `MADV_POPULATE_READ`로 memory를 미리 populate하거나, 새 kernel에서 `UFFD_FEATURE_WP_UNPOPULATED`를 탐지하고 미리 feature bit를 설정합니다.

WP mode를 missing 또는 minor mode와 함께 사용할 때 `UFFDIO_COPY_MODE_WP`나 `UFFDIO_CONTINUE_MODE_WP`를 지정하면 fault를 해소하며 설치하는 새 page 또는 mapping을 즉시 write-protected 상태로 만들어 이후 write도 WP fault를 내게 할 수 있습니다.

비동기 write-protect mode

250-284

Userfaultfd context에 `UFFD_FEATURE_WP_ASYNC` feature bit가 설정되면 write-protection으로 등록된 VMA는 기본 synchronous mode 대신 asynchronous mode로 동작합니다.

Async mode에서는 write 때 message가 생성되지 않고 kernel이 write-protection을 자동으로 해소합니다. 이는 soft-dirty보다 정밀한 추적으로 볼 수 있으며 다음 차이가 있습니다.

관점async uffd-wp 동작
event 전달write message를 만들지 않고 kernel이 보호를 자동 해제
VMA 변화dirty가 PTE에서만 추적되어 VMA merge 등의 영향을 받지 않음
rangepage-aligned memory라면 기본적으로 range operation 지원
PTE 제거shmem THP split 등으로 PTE가 zap돼도 dirty 정보가 사라지지 않음
bit 의미uffd-wp bit 설정은 clean, 해제는 dirty
상태 수집`/proc/pagemap`에서 관심 page의 uffd-wp bit 조회

Uffd-wp bit의 의미는 soft-dirty와 반대입니다. Bit가 설정되면 clean, 해제되면 dirty입니다. 따라서 anonymous memory의 `MADV_DONTNEED`나 file mapping의 `MADV_REMOVE`처럼 PTE를 제거하며 uffd-wp bit를 떨어뜨리는 동작은 memory를 dirty하게 만든 것으로 처리됩니다.

Application은 `/proc/pagemap`에서 관심 page의 uffd-wp bit를 읽어 written/dirty 상태를 수집합니다. Page는 `UFFDIO_WRITEPROTECT_MODE_WP`를 지정한 `ioctl(UFFDIO_WRITEPROTECT)`로 명시적으로 보호한 뒤에야 async 추적 대상이 됩니다. Async mode가 추적한 page fault를 해소하려는 시도는 유효하지 않습니다.

Userfaultfd-wp async mode를 단독으로 사용할 때는 모든 종류의 memory에 적용할 수 있습니다.

메모리 중독 에뮬레이션

285-299
기능동작용도
`UFFDIO_POISON`missing 또는 minor fault의 해소 동작향후 faulting task에 `SIGBUS`, KVM guest에는 hardware poisoning과 같은 MCE
live migrationsource host의 실제 memory error 위치를 destination에서도 poison 상태로 재현guest 관점의 hardware failure 연속성 유지

Userspace는 missing 또는 minor fault에 대한 해소 동작으로 `UFFDIO_POISON`을 발행할 수 있습니다. 이후 faulting task는 `SIGBUS`를 받고, KVM guest는 실제 hardware memory poisoning이 발생한 것처럼 MCE를 받습니다.

이는 hardware memory poisoning을 에뮬레이션하는 데 쓰입니다. 실제 memory error를 겪은 machine의 VM을 다른 physical machine으로 live migration할 때, 새 host의 같은 위치에 오류가 없더라도 guest가 보던 address range를 계속 poisoned 상태로 유지해 migration을 투명하게 만듭니다.

QEMU/KVM postcopy 개요

300-324

QEMU/KVM은 `userfaultfd` syscall로 postcopy live migration을 구현합니다. 이는 VM memory 일부 또는 전부가 cloud의 다른 node에 있는 상태로 VM을 실행하는 memory externalization의 한 형태입니다.

`userfaultfd` abstraction이 충분히 일반적이어서 QEMU에 postcopy live migration을 추가할 때 KVM kernel code는 한 줄도 수정할 필요가 없었습니다.

Guest asynchronous page fault, `FOLL_NOWAIT`, 그 밖의 모든 `GUP*` 기능은 userfault와 함께 정상 동작합니다. Userfault는 guest scheduler에서 async page fault를 유발하므로 network-bound처럼 userfault를 기다리지 않는 guest process는 guest vCPU에서 계속 실행할 수 있습니다.

Readonly guest region의 userfault 생성을 줄이려면 postcopy를 시작하기 직전에 precopy live migration을 한 차례 수행하는 것이 일반적으로 유리합니다.

현재 구현은 하나의 bidirectional socket을 사용합니다. 향후 userfault latency를 최소화하면서 `/proc/sys/net/ipv4/tcp_wmem`을 낮추지 않도록 서로 다른 socket 두 개를 사용할 계획입니다.

QEMU postcopy page 전송 흐름

325-362
단계주체동작
1source QEMUdestination에 missing인 page를 socket으로 전송
2destination migration thread`UFFDIO_COPY|ZEROPAGE`로 받은 page를 guest에 mapping
3destination postcopy thread`poll()`의 `POLLIN` 뒤 `read()`로 urgent fault address 수신
4destination → sourcemissing page address를 socket으로 요청
5source QEMU해당 offset으로 seek해 그 page부터 남은 missing page 전송
6source bitmap전송 완료 page를 갱신하고 round robin 및 중복 전송 방지

Source QEMU는 destination에 없다고 아는 모든 page를 socket에 쓰고, destination QEMU의 migration thread는 받은 page를 `UFFDIO_COPY|ZEROPAGE` ioctl로 guest에 mapping합니다. Source page가 zero page이면 `UFFDIO_ZEROCOPY`를 사용합니다.

동시에 destination의 별도 postcopy thread가 `poll()`로 userfaultfd를 감시합니다. Userfault 뒤 `POLLIN`이 발생하면 `read()`로 fault address를 받습니다. 병렬 migration thread가 먼저 `UFFDIO_COPY|ZEROPAGE`로 fault를 해소하고 깨운 경우에는 `-EAGAIN`을 받을 수 있습니다.

Postcopy thread가 missing address를 source에 보내면 source QEMU는 그 page address로 대략 seek한 뒤 그 offset부터 남은 missing page를 계속 보냅니다. Network가 `tcp_wmem` queue를 비우면 destination migration thread가 urgent page를 받고 평소처럼 mapping합니다. 그 page가 자발적으로 전송됐는지 userfault 요청 때문인지는 migration thread가 알 필요가 없습니다.

Userfault가 시작될 때 destination QEMU에는 migration용 per-page state bitmap이 필요 없습니다. Source QEMU만 destination에 아직 없는 page를 나타내는 bitmap 하나를 유지합니다. 이 bitmap은 round robin 전송 대상 탐색, incoming userfault에 따른 seek, 전송 완료 갱신, 같은 page 중복 전송 방지에 사용됩니다.

Postcopy urgent page 왕복
순서DestinationSource
01 1Guest access가 userfault를 발생missing bitmap으로 page stream 전송
02 2Postcopy thread가 address를 요청요청 address로 seek
03 3Migration thread가 page 수신urgent page부터 남은 page 전송
04 4`UFFDIO_COPY|ZEROPAGE`로 mappingbitmap 갱신

정상 page stream과 userfault 기반 urgent request가 같은 전송 경로에서 합류합니다.

비협조 userfaultfd event

363-397

외부 manager가 `userfaultfd`를 감시할 때는 대상 process의 virtual memory layout 변경도 추적해야 합니다. Userfaultfd는 page fault notification과 같은 read(2) protocol로 변경을 알릴 수 있으며, manager는 `UFFDIO_API`에 넘기는 `uffdio_api.features`의 해당 bit를 명시적으로 설정해야 합니다.

featureevent전달 정보
`UFFD_FEATURE_EVENT_FORK``UFFD_EVENT_FORK`child에 복제된 새 `userfaultfd`의 fd를 `uffd_msg.fork`로 전달
`UFFD_FEATURE_EVENT_REMAP``UFFD_EVENT_REMAP``uffd_msg.remap`에 old/new address와 원래 length 전달
`UFFD_FEATURE_EVENT_REMOVE``UFFD_EVENT_REMOVE``madvise(MADV_REMOVE)` / `madvise(MADV_DONTNEED)` range 전달
`UFFD_FEATURE_EVENT_UNMAP``UFFD_EVENT_UNMAP`unmap된 range의 start/end를 `uffd_msg.remove`로 전달

`UFFD_FEATURE_EVENT_FORK`는 fork() hook을 켜 parent의 userfaultfd context를 child에 복제하고 새 context의 fd를 전달합니다. REMAP은 mremap()으로 area가 이동할 때 old/new address와 원래 length를 전달합니다.

REMOVE는 `madvise(MADV_REMOVE)`와 `madvise(MADV_DONTNEED)`의 start/end를 알리고, UNMAP은 명시적 또는 암시적으로 unmap된 area의 start/end를 알립니다.

REMOVE·UNMAP 의미와 동기화

398-421
eventarea 상태manager 동작
REMOVEmemory 내용은 제거되지만 area와 userfaultfd 감시는 유지후속 fault를 zero-map
UNMAParea와 해당 userfaultfd context가 함께 사라짐후속 `UFFDIO_COPY`를 막도록 manager state를 제거

`UFFD_FEATURE_EVENT_REMOVE`와 `UFFD_FEATURE_EVENT_UNMAP`은 비슷하지만 manager가 취해야 할 동작은 다릅니다. REMOVE에서는 virtual memory 내용만 제거되고 area는 남아 계속 감시됩니다. 이후 그 area의 page fault도 manager에 전달되며 올바른 해소는 fault address를 zero-map하는 것입니다.

UNMAP에서는 `munmap()` 또는 `mremap()`에 의해 area와 그 userfaultfd context가 사라져 이후 userland page fault가 오지 않습니다. 그래도 manager가 이미 unmap된 area에 `UFFDIO_COPY`를 사용하지 않도록 notification이 필요합니다.

Userland page fault는 synchronous하고 명시적 또는 암시적 wakeup이 필요하지만 event는 asynchronous하게 전달됩니다. Manager가 `read()`를 실행하면 비협조 process는 곧바로 재개하므로 event 처리와 `UFFDIO_COPY`를 신중하게 동기화해야 합니다.

오류경쟁 조건
`-ENOSPC``UFFDIO_COPY` 시점에 monitored process가 exit
`-ENOENT`outstanding `UFFDIO_COPY`와 동시에 process가 virtual memory layout 변경

비동기 event 전달 모델

422-430

현재 asynchronous event delivery model은 single-threaded non-cooperative `userfaultfd` manager에 최적입니다. 앞으로 synchronous event delivery를 새 feature로 추가하면 event 수신과 `UFFDIO_COPY`를 병렬 실행하는 등 manager의 multithreading을 개선할 수 있습니다.

Single-threaded 구현은 계속 현재의 async event delivery model을 사용해야 합니다.