요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
===========
Userfaultfd
===========
Objective
=========
Userfaults allow the implementation of on-demand paging from userland
and more generally they allow userland to take control of various
memory page faults, something otherwise only the kernel code could do.
For example userfaults allows a proper and more optimal implementation
of the ``PROT_NONE+SIGSEGV`` trick.
Design
======
Userspace creates a new userfaultfd, initializes it, and registers one or more
regions of virtual memory with it. Then, any page faults which occur within the
region(s) result in a message being delivered to the userfaultfd, notifying
userspace of the fault.
The ``userfaultfd`` (aside from registering and unregistering virtual
memory ranges) provides two primary functionalities:
1) ``read/POLLIN`` protocol to notify a userland thread of the faults
happening
2) various ``UFFDIO_*`` ioctls that can manage the virtual memory regions
registered in the ``userfaultfd`` that allows userland to efficiently
resolve the userfaults it receives via 1) or to manage the virtual
memory in the background
The real advantage of userfaults if compared to regular virtual memory
management of mremap/mprotect is that the userfaults in all their
operations never involve heavyweight structures like vmas (in fact the
``userfaultfd`` runtime load never takes the mmap_lock for writing).
Vmas are not suitable for page- (or hugepage) granular fault tracking
when dealing with virtual address spaces that could span
Terabytes. Too many vmas would be needed for that.
The ``userfaultfd``, once created, can also be
passed using unix domain sockets to a manager process, so the same
manager process could handle the userfaults of a multitude of
different processes without them being aware about what is going on
(well of course unless they later try to use the ``userfaultfd``
themselves on the same region the manager is already tracking, which
is a corner case that would currently return ``-EBUSY``).
API
===
Creating a userfaultfd
----------------------
There are two ways to create a new userfaultfd, each of which provide ways to
restrict access to this functionality (since historically userfaultfds which
handle kernel page faults have been a useful tool for exploiting the kernel).
The first way, supported since userfaultfd was introduced, is the
userfaultfd(2) syscall. Access to this is controlled in several ways:
- Any user can always create a userfaultfd which traps userspace page faults
only. Such a userfaultfd can be created using the userfaultfd(2) syscall
with the flag UFFD_USER_MODE_ONLY.
- In order to also trap kernel page faults for the address space, either the
process needs the CAP_SYS_PTRACE capability, or the system must have
vm.unprivileged_userfaultfd set to 1. By default, vm.unprivileged_userfaultfd
is set to 0.
The second way, added to the kernel more recently, is by opening
/dev/userfaultfd and issuing a USERFAULTFD_IOC_NEW ioctl to it. This method
yields equivalent userfaultfds to the userfaultfd(2) syscall.
Unlike userfaultfd(2), access to /dev/userfaultfd is controlled via normal
filesystem permissions (user/group/mode), which gives fine grained access to
userfaultfd specifically, without also granting other unrelated privileges at
the same time (as e.g. granting CAP_SYS_PTRACE would do). Users who have access
to /dev/userfaultfd can always create userfaultfds that trap kernel page faults;
vm.unprivileged_userfaultfd is not considered.
Initializing a userfaultfd
--------------------------
When first opened the ``userfaultfd`` must be enabled invoking the
``UFFDIO_API`` ioctl specifying a ``uffdio_api.api`` value set to ``UFFD_API`` (or
a later API version) which will specify the ``read/POLLIN`` protocol
userland intends to speak on the ``UFFD`` and the ``uffdio_api.features``
userland requires. The ``UFFDIO_API`` ioctl if successful (i.e. if the
requested ``uffdio_api.api`` is spoken also by the running kernel and the
requested features are going to be enabled) will return into
``uffdio_api.features`` and ``uffdio_api.ioctls`` two 64bit bitmasks of
respectively all the available features of the read(2) protocol and
the generic ioctl available.
The ``uffdio_api.features`` bitmask returned by the ``UFFDIO_API`` ioctl
defines what memory types are supported by the ``userfaultfd`` and what
events, except page fault notifications, may be generated:
- The ``UFFD_FEATURE_EVENT_*`` flags indicate that various other events
other than page faults are supported. These events are described in more
detail below in the `Non-cooperative userfaultfd`_ section.
- ``UFFD_FEATURE_MISSING_HUGETLBFS`` and ``UFFD_FEATURE_MISSING_SHMEM``
indicate that the kernel supports ``UFFDIO_REGISTER_MODE_MISSING``
registrations for hugetlbfs and shared memory (covering all shmem APIs,
i.e. tmpfs, ``IPCSHM``, ``/dev/zero``, ``MAP_SHARED``, ``memfd_create``,
etc) virtual memory areas, respectively.
- ``UFFD_FEATURE_MINOR_HUGETLBFS`` indicates that the kernel supports
``UFFDIO_REGISTER_MODE_MINOR`` registration for hugetlbfs virtual memory
areas. ``UFFD_FEATURE_MINOR_SHMEM`` is the analogous feature indicating
support for shmem virtual memory areas.
- ``UFFD_FEATURE_MOVE`` indicates that the kernel supports moving an
existing page contents from userspace.
The userland application should set the feature flags it intends to use
when invoking the ``UFFDIO_API`` ioctl, to request that those features be
enabled if supported.
Once the ``userfaultfd`` API has been enabled the ``UFFDIO_REGISTER``
ioctl should be invoked (if present in the returned ``uffdio_api.ioctls``
bitmask) to register a memory range in the ``userfaultfd`` by setting the
uffdio_register structure accordingly. The ``uffdio_register.mode``
bitmask will specify to the kernel which kind of faults to track for
the range. The ``UFFDIO_REGISTER`` ioctl will return the
``uffdio_register.ioctls`` bitmask of ioctls that are suitable to resolve
userfaults on the range registered. Not all ioctls will necessarily be
supported for all memory types (e.g. anonymous memory vs. shmem vs.
hugetlbfs), or all types of intercepted faults.
Userland can use the ``uffdio_register.ioctls`` to manage the virtual
address space in the background (to add or potentially also remove
memory from the ``userfaultfd`` registered range). This means a userfault
could be triggering just before userland maps in the background the
user-faulted page.
Resolving Userfaults
--------------------
There are three basic ways to resolve userfaults:
- ``UFFDIO_COPY`` atomically copies some existing page contents from
userspace.
- ``UFFDIO_ZEROPAGE`` atomically zeros the new page.
- ``UFFDIO_CONTINUE`` maps an existing, previously-populated page.
These operations are atomic in the sense that they guarantee nothing can
see a half-populated page, since readers will keep userfaulting until the
operation has finished.
By default, these wake up userfaults blocked on the range in question.
They support a ``UFFDIO_*_MODE_DONTWAKE`` ``mode`` flag, which indicates
that waking will be done separately at some later time.
Which ioctl to choose depends on the kind of page fault, and what we'd
like to do to resolve it:
- For ``UFFDIO_REGISTER_MODE_MISSING`` faults, the fault needs to be
resolved by either providing a new page (``UFFDIO_COPY``), or mapping
the zero page (``UFFDIO_ZEROPAGE``). By default, the kernel would map
the zero page for a missing fault. With userfaultfd, userspace can
decide what content to provide before the faulting thread continues.
- For ``UFFDIO_REGISTER_MODE_MINOR`` faults, there is an existing page (in
the page cache). Userspace has the option of modifying the page's
contents before resolving the fault. Once the contents are correct
(modified or not), userspace asks the kernel to map the page and let the
faulting thread continue with ``UFFDIO_CONTINUE``.
Notes:
- You can tell which kind of fault occurred by examining
``pagefault.flags`` within the ``uffd_msg``, checking for the
``UFFD_PAGEFAULT_FLAG_*`` flags.
- None of the page-delivering ioctls default to the range that you
registered with. You must fill in all fields for the appropriate
ioctl struct including the range.
- You get the address of the access that triggered the missing page
event out of a struct uffd_msg that you read in the thread from the
uffd. You can supply as many pages as you want with these IOCTLs.
Keep in mind that unless you used DONTWAKE then the first of any of
those IOCTLs wakes up the faulting thread.
- Be sure to test for all errors including
(``pollfd[0].revents & POLLERR``). This can happen, e.g. when ranges
supplied were incorrect.
Write Protect Notifications
---------------------------
This is equivalent to (but faster than) using mprotect and a SIGSEGV
signal handler.
Firstly you need to register a range with ``UFFDIO_REGISTER_MODE_WP``.
Instead of using mprotect(2) you use
``ioctl(uffd, UFFDIO_WRITEPROTECT, struct *uffdio_writeprotect)``
while ``mode = UFFDIO_WRITEPROTECT_MODE_WP``
in the struct passed in. The range does not default to and does not
have to be identical to the range you registered with. You can write
protect as many ranges as you like (inside the registered range).
Then, in the thread reading from uffd the struct will have
``msg.arg.pagefault.flags & UFFD_PAGEFAULT_FLAG_WP`` set. Now you send
``ioctl(uffd, UFFDIO_WRITEPROTECT, struct *uffdio_writeprotect)``
again while ``pagefault.mode`` does not have ``UFFDIO_WRITEPROTECT_MODE_WP``
set. This wakes up the thread which will continue to run with writes. This
allows you to do the bookkeeping about the write in the uffd reading
thread before the ioctl.
If you registered with both ``UFFDIO_REGISTER_MODE_MISSING`` and
``UFFDIO_REGISTER_MODE_WP`` then you need to think about the sequence in
which you supply a page and undo write protect. Note that there is a
difference between writes into a WP area and into a !WP area. The
former will have ``UFFD_PAGEFAULT_FLAG_WP`` set, the latter
``UFFD_PAGEFAULT_FLAG_WRITE``. The latter did not fail on protection but
you still need to supply a page when ``UFFDIO_REGISTER_MODE_MISSING`` was
used.
Userfaultfd write-protect mode currently behave differently on none ptes
(when e.g. page is missing) over different types of memories.
For anonymous memory, ``ioctl(UFFDIO_WRITEPROTECT)`` will ignore none ptes
(e.g. when pages are missing and not populated). For file-backed memories
like shmem and hugetlbfs, none ptes will be write protected just like a
present pte. In other words, there will be a userfaultfd write fault
message generated when writing to a missing page on file typed memories,
as long as the page range was write-protected before. Such a message will
not be generated on anonymous memories by default.
If the application wants to be able to write protect none ptes on anonymous
memory, one can pre-populate the memory with e.g. MADV_POPULATE_READ. On
newer kernels, one can also detect the feature UFFD_FEATURE_WP_UNPOPULATED
and set the feature bit in advance to make sure none ptes will also be
write protected even upon anonymous memory.
When using ``UFFDIO_REGISTER_MODE_WP`` in combination with either
``UFFDIO_REGISTER_MODE_MISSING`` or ``UFFDIO_REGISTER_MODE_MINOR``, when
resolving missing / minor faults with ``UFFDIO_COPY`` or ``UFFDIO_CONTINUE``
respectively, it may be desirable for the new page / mapping to be
write-protected (so future writes will also result in a WP fault). These ioctls
support a mode flag (``UFFDIO_COPY_MODE_WP`` or ``UFFDIO_CONTINUE_MODE_WP``
respectively) to configure the mapping this way.
If the userfaultfd context has ``UFFD_FEATURE_WP_ASYNC`` feature bit set,
any vma registered with write-protection will work in async mode rather
than the default sync mode.
In async mode, there will be no message generated when a write operation
happens, meanwhile the write-protection will be resolved automatically by
the kernel. It can be seen as a more accurate version of soft-dirty
tracking and it can be different in a few ways:
- The dirty result will not be affected by vma changes (e.g. vma
merging) because the dirty is only tracked by the pte.
- It supports range operations by default, so one can enable tracking on
any range of memory as long as page aligned.
- Dirty information will not get lost if the pte was zapped due to
various reasons (e.g. during split of a shmem transparent huge page).
- Due to a reverted meaning of soft-dirty (page clean when uffd-wp bit
set; dirty when uffd-wp bit cleared), it has different semantics on
some of the memory operations. For example: ``MADV_DONTNEED`` on
anonymous (or ``MADV_REMOVE`` on a file mapping) will be treated as
dirtying of memory by dropping uffd-wp bit during the procedure.
The user app can collect the "written/dirty" status by looking up the
uffd-wp bit for the pages being interested in /proc/pagemap.
The page will not be under track of uffd-wp async mode until the page is
explicitly write-protected by ``ioctl(UFFDIO_WRITEPROTECT)`` with the mode
flag ``UFFDIO_WRITEPROTECT_MODE_WP`` set. Trying to resolve a page fault
that was tracked by async mode userfaultfd-wp is invalid.
When userfaultfd-wp async mode is used alone, it can be applied to all
kinds of memory.
Memory Poisioning Emulation
---------------------------
In response to a fault (either missing or minor), an action userspace can
take to "resolve" it is to issue a ``UFFDIO_POISON``. This will cause any
future faulters to either get a SIGBUS, or in KVM's case the guest will
receive an MCE as if there were hardware memory poisoning.
This is used to emulate hardware memory poisoning. Imagine a VM running on a
machine which experiences a real hardware memory error. Later, we live migrate
the VM to another physical machine. Since we want the migration to be
transparent to the guest, we want that same address range to act as if it was
still poisoned, even though it's on a new physical host which ostensibly
doesn't have a memory error in the exact same spot.
QEMU/KVM
========
QEMU/KVM is using the ``userfaultfd`` syscall to implement postcopy live
migration. Postcopy live migration is one form of memory
externalization consisting of a virtual machine running with part or
all of its memory residing on a different node in the cloud. The
``userfaultfd`` abstraction is generic enough that not a single line of
KVM kernel code had to be modified in order to add postcopy live
migration to QEMU.
Guest async page faults, ``FOLL_NOWAIT`` and all other ``GUP*`` features work
just fine in combination with userfaults. Userfaults trigger async
page faults in the guest scheduler so those guest processes that
aren't waiting for userfaults (i.e. network bound) can keep running in
the guest vcpus.
It is generally beneficial to run one pass of precopy live migration
just before starting postcopy live migration, in order to avoid
generating userfaults for readonly guest regions.
The implementation of postcopy live migration currently uses one
single bidirectional socket but in the future two different sockets
will be used (to reduce the latency of the userfaults to the minimum
possible without having to decrease ``/proc/sys/net/ipv4/tcp_wmem``).
The QEMU in the source node writes all pages that it knows are missing
in the destination node, into the socket, and the migration thread of
the QEMU running in the destination node runs ``UFFDIO_COPY|ZEROPAGE``
ioctls on the ``userfaultfd`` in order to map the received pages into the
guest (``UFFDIO_ZEROCOPY`` is used if the source page was a zero page).
A different postcopy thread in the destination node listens with
poll() to the ``userfaultfd`` in parallel. When a ``POLLIN`` event is
generated after a userfault triggers, the postcopy thread read() from
the ``userfaultfd`` and receives the fault address (or ``-EAGAIN`` in case the
userfault was already resolved and waken by a ``UFFDIO_COPY|ZEROPAGE`` run
by the parallel QEMU migration thread).
After the QEMU postcopy thread (running in the destination node) gets
the userfault address it writes the information about the missing page
into the socket. The QEMU source node receives the information and
roughly "seeks" to that page address and continues sending all
remaining missing pages from that new page offset. Soon after that
(just the time to flush the tcp_wmem queue through the network) the
migration thread in the QEMU running in the destination node will
receive the page that triggered the userfault and it'll map it as
usual with the ``UFFDIO_COPY|ZEROPAGE`` (without actually knowing if it
was spontaneously sent by the source or if it was an urgent page
requested through a userfault).
By the time the userfaults start, the QEMU in the destination node
doesn't need to keep any per-page state bitmap relative to the live
migration around and a single per-page bitmap has to be maintained in
the QEMU running in the source node to know which pages are still
missing in the destination node. The bitmap in the source node is
checked to find which missing pages to send in round robin and we seek
over it when receiving incoming userfaults. After sending each page of
course the bitmap is updated accordingly. It's also useful to avoid
sending the same page twice (in case the userfault is read by the
postcopy thread just before ``UFFDIO_COPY|ZEROPAGE`` runs in the migration
thread).
Non-cooperative userfaultfd
===========================
When the ``userfaultfd`` is monitored by an external manager, the manager
must be able to track changes in the process virtual memory
layout. Userfaultfd can notify the manager about such changes using
the same read(2) protocol as for the page fault notifications. The
manager has to explicitly enable these events by setting appropriate
bits in ``uffdio_api.features`` passed to ``UFFDIO_API`` ioctl:
``UFFD_FEATURE_EVENT_FORK``
enable ``userfaultfd`` hooks for fork(). When this feature is
enabled, the ``userfaultfd`` context of the parent process is
duplicated into the newly created process. The manager
receives ``UFFD_EVENT_FORK`` with file descriptor of the new
``userfaultfd`` context in the ``uffd_msg.fork``.
``UFFD_FEATURE_EVENT_REMAP``
enable notifications about mremap() calls. When the
non-cooperative process moves a virtual memory area to a
different location, the manager will receive
``UFFD_EVENT_REMAP``. The ``uffd_msg.remap`` will contain the old and
new addresses of the area and its original length.
``UFFD_FEATURE_EVENT_REMOVE``
enable notifications about madvise(MADV_REMOVE) and
madvise(MADV_DONTNEED) calls. The event ``UFFD_EVENT_REMOVE`` will
be generated upon these calls to madvise(). The ``uffd_msg.remove``
will contain start and end addresses of the removed area.
``UFFD_FEATURE_EVENT_UNMAP``
enable notifications about memory unmapping. The manager will
get ``UFFD_EVENT_UNMAP`` with ``uffd_msg.remove`` containing start and
end addresses of the unmapped area.
Although the ``UFFD_FEATURE_EVENT_REMOVE`` and ``UFFD_FEATURE_EVENT_UNMAP``
are pretty similar, they quite differ in the action expected from the
``userfaultfd`` manager. In the former case, the virtual memory is
removed, but the area is not, the area remains monitored by the
``userfaultfd``, and if a page fault occurs in that area it will be
delivered to the manager. The proper resolution for such page fault is
to zeromap the faulting address. However, in the latter case, when an
area is unmapped, either explicitly (with munmap() system call), or
implicitly (e.g. during mremap()), the area is removed and in turn the
``userfaultfd`` context for such area disappears too and the manager will
not get further userland page faults from the removed area. Still, the
notification is required in order to prevent manager from using
``UFFDIO_COPY`` on the unmapped area.
Unlike userland page faults which have to be synchronous and require
explicit or implicit wakeup, all the events are delivered
asynchronously and the non-cooperative process resumes execution as
soon as manager executes read(). The ``userfaultfd`` manager should
carefully synchronize calls to ``UFFDIO_COPY`` with the events
processing. To aid the synchronization, the ``UFFDIO_COPY`` ioctl will
return ``-ENOSPC`` when the monitored process exits at the time of
``UFFDIO_COPY``, and ``-ENOENT``, when the non-cooperative process has changed
its virtual memory layout simultaneously with outstanding ``UFFDIO_COPY``
operation.
The current asynchronous model of the event delivery is optimal for
single threaded non-cooperative ``userfaultfd`` manager implementations. A
synchronous event delivery model can be added later as a new
``userfaultfd`` feature to facilitate multithreading enhancements of the
non cooperative manager, for example to allow ``UFFDIO_COPY`` ioctls to
run in parallel to the event reception. Single threaded
implementations should continue to use the current async event
delivery model instead.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
목표
1-14Userfault는 userspace에서 demand paging을 구현하게 하며, 더 일반적으로는 원래 kernel code만 제어할 수 있던 여러 종류의 memory page fault를 userspace가 제어하게 합니다.
예를 들어 userfault를 사용하면 `PROT_NONE+SIGSEGV` 기법을 더 올바르고 효율적으로 구현할 수 있습니다.
설계
15-49Userspace는 새 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-139API를 활성화한 뒤 반환된 `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-fill | missing fault |
| `UFFDIO_CONTINUE` | 이미 populate된 page를 mapping | minor 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_*` 검사 |
| range | page 전달 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를 깨운다는 점을 순서 설계에 반영해야 합니다.
Faulting thread는 manager가 atomic 해소 ioctl을 끝낼 때까지 대기합니다.
Write-protect notification
195-224Write-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-249Userfaultfd write-protect mode는 page가 없는 none PTE를 memory type에 따라 다르게 처리합니다.
| memory / 방식 | none PTE 처리 | 결과 |
|---|---|---|
| anonymous memory | 기본적으로 none PTE를 무시 | missing page write가 WP message를 만들지 않음 |
| shmem / hugetlbfs | none 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-284Userfaultfd 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 등의 영향을 받지 않음 |
| range | page-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 migration | source 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-324QEMU/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| 단계 | 주체 | 동작 |
|---|---|---|
| 1 | source QEMU | destination에 missing인 page를 socket으로 전송 |
| 2 | destination migration thread | `UFFDIO_COPY|ZEROPAGE`로 받은 page를 guest에 mapping |
| 3 | destination postcopy thread | `poll()`의 `POLLIN` 뒤 `read()`로 urgent fault address 수신 |
| 4 | destination → source | missing page address를 socket으로 요청 |
| 5 | source QEMU | 해당 offset으로 seek해 그 page부터 남은 missing page 전송 |
| 6 | source 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 중복 전송 방지에 사용됩니다.
정상 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를 명시적으로 설정해야 합니다.
| feature | event | 전달 정보 |
|---|---|---|
| `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| event | area 상태 | manager 동작 |
|---|---|---|
| REMOVE | memory 내용은 제거되지만 area와 userfaultfd 감시는 유지 | 후속 fault를 zero-map |
| UNMAP | area와 해당 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을 사용해야 합니다.
운영 핵심
userfaultfd.rst:1-430Userfaultfd는 faulting thread를 kernel에서 즉시 해소하지 않고 userspace manager가 page 내용과 mapping 시점을 결정하게 합니다. API와 range별 ioctl bitmask를 먼저 협상하고, fault 종류·memory type·wake 정책을 확인한 뒤 해소해야 합니다.