Skip to contentSkip to conversation

mm/memfd: handle GUP references reliably when write-sealing

PATCH Applied David Hildenbrand (Arm) 4 participants 9 messages Nov 3 – Nov 8

Subsystems (5)
lore
Share & tools
lore

David Hildenbrand (Arm)

author maintainer
#0 lore raw

cover mm/memfd: handle GUP references reliably when write-sealing

I spent way too much time on this, looking for better options. I think patch #1 fixes the most immediate issues but something like patch #2 is needed.

Long story short: someone can trigger a race such that we don't detect GUP references when write-sealing, allowing to modify content later.

Patch #1 handles pins reliably for folios with a pincount. Patch #2 handles the remaining references, but can reject write-sealing with populated file mappings. vm.memfd_write_seal_mapped allows restoring the legacy behavior if needed.

All alternatives to patch #2 I tried ended up too complicated and nasty in corner cases. We should never have allowed write-sealing with existing file mappings.

Plenty of details in patch #2.

Did some testing on x86-64 without any surprises.

---
David Hildenbrand (Arm) (2):
mm/memfd: handle GUP pins more reliably when write-sealing mm/memfd: handle GUP references reliably when write-sealing

 Documentation/admin-guide/sysctl/vm.rst | 21 +++++++++++++++
 mm/memfd.c                              | 45 ++++++++++++++++++++++++++++++++-
 2 files changed, 65 insertions(+), 1 deletion(-)

---

base-commit: 462595652740dc45f2392dc59d9609e509ee60af

change-id: 20261102-fixes_core_2-39e59afda919

--

Cheers,

David

author maintainer
#1 lore raw

PATCH 1/2 mm/memfd: handle GUP pins more reliably when write-sealing

memfd_wait_for_pins() detects GUP references by comparing a folio's actual refcount with its expected refcount. As spelled out by folio_expected_ref_count(), obtaining the expected refcount when there can be concurrent folio (un)mapping is racy.

So it is possible that a changing folio mapcount can race with our check for GUP references, and F_SEAL_WRITE might succeed even if there are some, allowing file contents to be modified after sealing.

For folios with a reliable pincount, detect FOLL_PIN references using folio_maybe_dma_pinned() before falling back to the refcount comparison. For small folios without that, the 1024 pinning BIAS makes it very hard (although not impossible) to misguide the refcount comparison.

This improves FOLL_PIN detection for folios with a pincount. Handling FOLL_GET and small folios requires a more fundamental change.

Fortunately, most interfaces that allow for GUP'ing such pages use FOLL_PIN, in particular interfaces using FOLL_LONGTERM. However, we still have some FOLL_GET leftovers ...

Fixes 05f65b5c7090 ("shm: wait for pins to be released when sealing")
Cc Chris Mason <[email protected]>
---
 mm/memfd.c | 7 +++++++
 1 file changed, 7 insertions(+)
mm/memfd.c +7 -0
index 0f6fff004f5e4..9eda4c3eeaca5 100644
@@ -32,6 +32,13 @@
 
 static bool memfd_folio_has_extra_refs(struct folio *folio)
 {
+	/*
+	 * Use the precise pincount where available to avoid racy refcount
+	 * comparisons.
+	 */
+	if (folio_has_pincount(folio) && folio_maybe_dma_pinned(folio))
+		return true;
+
 	return folio_ref_count(folio) != folio_expected_ref_count(folio);
 }
 
Signature · 1 line
2.43.0
reviewer Reviewed-by on v1 1/2
#2 lore raw

Re: [PATCH 1/2] mm/memfd: handle GUP pins more reliably when write-sealing

Quoted 17 lines · David Hildenbrand (Arm)

memfd_wait_for_pins() detects GUP references by comparing a folio's actual refcount with its expected refcount. As spelled out by folio_expected_ref_count(), obtaining the expected refcount when there can be concurrent folio (un)mapping is racy.

So it is possible that a changing folio mapcount can race with our check for GUP references, and F_SEAL_WRITE might succeed even if there are some, allowing file contents to be modified after sealing.

For folios with a reliable pincount, detect FOLL_PIN references using folio_maybe_dma_pinned() before falling back to the refcount comparison. For small folios without that, the 1024 pinning BIAS makes it very hard (although not impossible) to misguide the refcount comparison.

This improves FOLL_PIN detection for folios with a pincount. Handling FOLL_GET and small folios requires a more fundamental change.

Quoted 8 lines

Fortunately, most interfaces that allow for GUP'ing such pages use FOLL_PIN, in particular interfaces using FOLL_LONGTERM. However, we still have some FOLL_GET leftovers ...

Fixes 05f65b5c7090 ("shm: wait for pins to be released when sealing")
Cc Chris Mason <[email protected]>

All very delicate stuff, I wonder if we could somehow make the logic here generalised in a follow-up?

Anyway seems reasonable to me so:

Quoted 24 lines
---
 mm/memfd.c | 7 +++++++
 1 file changed, 7 insertions(+)
mm/memfd.c +7 -1
index 0f6fff004f5e4..9eda4c3eeaca5 100644
@@ -32,6 +32,13 @@
 
 static bool memfd_folio_has_extra_refs(struct folio *folio)
 {
+	/*
+	 * Use the precise pincount where available to avoid racy refcount
+	 * comparisons.
+	 */
+	if (folio_has_pincount(folio) && folio_maybe_dma_pinned(folio))
+		return true;
+
 	return folio_ref_count(folio) != folio_expected_ref_count(folio);
 }
 
 
--
Quoted 2 lines

2.43.0

--
Cheers, Lorenzo

author maintainer Applied
#3 lore raw

Re: [PATCH 1/2] mm/memfd: handle GUP pins more reliably when write-sealing

In reply to David Hildenbrand (Arm)
Quoted 10 lines · David Hildenbrand (Arm)

memfd_wait_for_pins() detects GUP references by comparing a folio's actual refcount with its expected refcount. As spelled out by folio_expected_ref_count(), obtaining the expected refcount when there can be concurrent folio (un)mapping is racy.

So it is possible that a changing folio mapcount can race with our check for GUP references, and F_SEAL_WRITE might succeed even if there are some, allowing file contents to be modified after sealing.

[...]

I'm applying the first patch for now, as that is an obvious improvement for many GUP users (esp. iouring fixed buffers etc).

tree: mm/core.git
branch: for-next-fixes

Applied patches will appear soon in mm-next, followed by linux-next.

Please report any outstanding bugs that were missed during review, so we can either drop the patch series or decide how to fix it up.

It is encouraged to provide Acked-bys, Reviewed-bys, and Tested-bys even though the patches have already been applied. If possible, patch trailers will be updated.

Note that commit hashes shown below are subject to change due to rebase, trailer updates or similar. Further, this is not a guarantee that the patches will go upstream. If in doubt, please check the listed branch.

[1/2] mm/memfd: handle GUP pins more reliably when write-sealing

      https://git.kernel.org/mm/core/c/42990cfe
Signature · 3 lines
Cheers,

David
Reviewed-by on v1 1/2
#4 lore raw

Re: [PATCH 1/2] mm/memfd: handle GUP pins more reliably when write-sealing

In reply to David Hildenbrand (Arm)
Quoted 21 lines · David Hildenbrand (Arm)

memfd_wait_for_pins() detects GUP references by comparing a folio's actual refcount with its expected refcount. As spelled out by folio_expected_ref_count(), obtaining the expected refcount when there can be concurrent folio (un)mapping is racy.

So it is possible that a changing folio mapcount can race with our check for GUP references, and F_SEAL_WRITE might succeed even if there are some, allowing file contents to be modified after sealing.

For folios with a reliable pincount, detect FOLL_PIN references using folio_maybe_dma_pinned() before falling back to the refcount comparison. For small folios without that, the 1024 pinning BIAS makes it very hard (although not impossible) to misguide the refcount comparison.

This improves FOLL_PIN detection for folios with a pincount. Handling FOLL_GET and small folios requires a more fundamental change.

Fortunately, most interfaces that allow for GUP'ing such pages use FOLL_PIN, in particular interfaces using FOLL_LONGTERM. However, we still have some FOLL_GET leftovers ...

Quoted 5 lines
Fixes 05f65b5c7090 ("shm: wait for pins to be released when sealing")
Cc Chris Mason <[email protected]>

---

author maintainer
#5 lore raw

PATCH 2/2 mm/memfd: handle GUP references reliably when write-sealing

In reply to David Hildenbrand (Arm)

memfd_wait_for_pins() detects GUP references by comparing a folio's actual refcount with its expected refcount. As spelled out by folio_expected_ref_count(), obtaining the expected refcount when there can be concurrent folio (un)mapping is racy.

So it is possible that a changing folio mapcount can race with our check for GUP references, and F_SEAL_WRITE might succeed even if there are some, allowing file contents to be modified after sealing.

We made a big mistake when introducing write-sealing: we should have disallowed *any* file mappings while we are write-sealing. Write-sealing is usually done by a producer that wants to hand-off some data to a consumer. Having the producer have a read-only mapping (private or read-only shared) of the memfd while sealing is rather odd: it couldn't have been used to fill the memfd in the first place.

Most identified public users don't do anything like that: they either never map the memfd before write-sealing (using write() instead), or munmap() before write-sealing:

- systemd's journal writes, fwupd, Flatpak, runc, crun and containers/storage write to the memfd without mmap'ing it, before sealing it [1,2,3,4,5,6]. The FD consumer will not access the memfd before sealing.

- dbus-broker, Mutter, Chromium's Android linker, KWin, Weston and glycin map the memfd file, but unmap it before sealing [7,8,9,10,11,12]. glycin retries sealing while waiting for the loader to unmap.

- go-memfd exposes a shared writable mapping before F_SEAL_WRITE and a private read-only mapping afterwards. Its API explicitly requires unmapping the writable mapping before sealing [13].

One exception is CRIU: it restores mappings before applying the saved seals [14,15]. Unfortunately, we cannot simply disallow file mappings without breaking that use case.

The preceding change handles FOLL_PIN by checking folio_maybe_dma_pinned() if our folio has a reliable pincount. For small folios without that, the 1024 pinning BIAS makes it very hard (although not impossible) to misguide the refcount comparison.

Handling FOLL_GET is, however, more problematic, and we still have some users in the tree that use FOLL_GET for writing although they should be using FOLL_PIN; and they are harder to fix, so we have to handle them for now.

To detect any GUP references reliably, we need a stable expected refcount. To achieve that with folio_expected_ref_count() we'd have to unmap all folios and handle/detect concurrent faults, which opens up various cans of worms, including dropping mlock accounting when zapping shmem folios, shaky hugetlb mapping removal and properly handling concurrent page faults.

So let's make our life easier and only allow page-cache references when checking folios. Compare against folio_nr_pages() instead. Concurrent faults can cause false positives, but cannot hide GUP references. This allows CRIU to restore mappings that have no file folios mapped yet.

Populated file-backed mappings, for example due to mlock(), can still fail with -EBUSY now. CRIU preserves MAP_LOCKED when restoring mappings [16], but whether any users actually restore write-sealed memfds with mlocked file folios is hard to say.

To handle these cases that likely don't matter in practice once they pop up, let's do the same thing we did with vm.unprivileged_userfaultfd: give admins a way to keep such software working. Add vm.memfd_write_seal_mapped, defaulting to 0. Setting it to 1 restores the legacy behavior, including its racy reference-count comparison.

[1] https://github.com/systemd/systemd/blob/main/src/libsystemd/sd-journal/journal-send.c
[2] https://github.com/fwupd/fwupd/blob/main/libfwupd/fwupd-common.c
[3] https://github.com/flatpak/flatpak/blob/main/common/flatpak-utils.c
[4] https://github.com/opencontainers/runc/blob/main/libcontainer/exeseal/cloned_binary_linux.go
[5] https://github.com/containers/crun/blob/main/src/libcrun/cloned_binary.c
[6] https://github.com/containers/storage/blob/main/pkg/unshare/unshare.c
[7] https://github.com/bus1/dbus-broker/blob/main/src/util/log.c
[8] https://github.com/GNOME/mutter/blob/main/mtk/mtk/mtk-anonymous-file.c
[9] https://chromium.googlesource.com/chromium/src/+/e06bed6b494928199ae2fb4ec1fa9b03d0f4ef3b/base/android/linker/modern_linker_jni.cc
[10] https://github.com/KDE/kwin/blob/master/src/utils/ramfile.cpp
[11] https://gitlab.freedesktop.org/wayland/weston/-/blob/main/shared/os-compatibility.c
[12] https://github.com/GNOME/glycin/blob/main/glycin-utils/src/memory/shared.rs
[13] https://github.com/justincormack/go-memfd/blob/master/memfd.go
[14] https://github.com/checkpoint-restore/criu/blob/criu-dev/criu/memfd.c
[15] https://github.com/checkpoint-restore/criu/blob/criu-dev/criu/cr-restore.c
[16] https://github.com/checkpoint-restore/criu/blob/criu-dev/criu/pie/restorer.c

Fixes 05f65b5c7090 ("shm: wait for pins to be released when sealing")
Cc Chris Mason <[email protected]>
---
 Documentation/admin-guide/sysctl/vm.rst | 21 +++++++++++++++++
 mm/memfd.c                              | 42 ++++++++++++++++++++++++++++++---
 2 files changed, 60 insertions(+), 3 deletions(-)
Documentation/admin-guide/sysctl/vm.rst +21 -0
index 3cb0138e850c1..182db608ee436 100644
@@ -42,6 +42,7 @@ Currently, these files are in /proc/sys/vm:
 - lowmem_reserve_ratio
 - max_map_count
 - mem_profiling         (only if CONFIG_MEM_ALLOC_PROFILING=y)
+- memfd_write_seal_mapped
 - memory_failure_early_kill
 - memory_failure_recovery
 - min_free_kbytes
@@ -492,6 +493,26 @@ warnings produced by allocations made while profiling is disabled and freed
 when it's enabled.
 
 
+memfd_write_seal_mapped
+=======================
+
+Controls whether ``F_SEAL_WRITE`` can be added to a memfd with file pages
+mapped into page tables (legacy).
+
+In the default mode (0), references from page-table mappings can make
+``F_SEAL_WRITE`` fail with ``EBUSY``, just like references from other kernel
+subsystems or DMA. File mappings without populated page tables do not
+prevent write sealing.
+
+Setting this to the legacy mode (1) permits write sealing with page-table
+mappings, but allows for some race conditions that can permit other kernel
+subsystems or DMA to modify file content after write-sealing through page
+references obtained before write-sealing.
+
+Shared mappings that can be made writable always prevent write sealing,
+even without populated page tables.
+
+
 memory_failure_early_kill
 =========================
 
mm/memfd.c +39 -3

68 lines not on this page · raw message

Signature · 1 line
2.43.0
#6 lore raw

Hi David

Quoted 16 lines · David Hildenbrand (Arm)

We made a big mistake when introducing write-sealing: we should have disallowed *any* file mappings while we are write-sealing. Write-sealing is usually done by a producer that wants to hand-off some data to a consumer. Having the producer have a read-only mapping (private or read-only shared) of the memfd while sealing is rather odd: it couldn't have been used to fill the memfd in the first place.

Most identified public users don't do anything like that: they either never map the memfd before write-sealing (using write() instead), or munmap() before write-sealing:

- systemd's journal writes, fwupd, Flatpak, runc, crun and containers/storage write to the memfd without mmap'ing it, before sealing it [1,2,3,4,5,6]. The FD consumer will not access the memfd before sealing.

Quoted 7 lines

- dbus-broker, Mutter, Chromium's Android linker, KWin, Weston and glycin map the memfd file, but unmap it before sealing [7,8,9,10,11,12]. glycin retries sealing while waiting for the loader to unmap.

- go-memfd exposes a shared writable mapping before F_SEAL_WRITE and a private read-only mapping afterwards. Its API explicitly requires unmapping the writable mapping before sealing [13].

When I wrote memfd-sealing, we had this use-case where an application writes a buffer and then shares it both with in-process and out-of-process tasks. Only if out-of-process tasks are actually involved, the buffer is sealed. Otherwise, it is kept unsealed and can be recycled. Hand-off to other processes was optional, rare and asynchronous, so sealing could happen at any time. Yet, we wanted to keep the buffers mapped to avoid costly TLB flushes. Mappings were readonly, but writes were done through syscalls.

We still do this, but I don't think any of the open-source users picked this up. I did not follow the folio changes, so I am quite unsure whether the implementation was racy from the beginning, or whether new infrastructure introduced the races.

Can you elaborate why folio ref-counts are unreliable / unstable?

Thanks
David

author maintainer
#7 lore raw
Quoted 1 line · David Rheinsberg

Hi David

Hi!

Quoted 22 lines · David Hildenbrand (Arm)
Quoted 20 lines

We made a big mistake when introducing write-sealing: we should have disallowed *any* file mappings while we are write-sealing. Write-sealing is usually done by a producer that wants to hand-off some data to a consumer. Having the producer have a read-only mapping (private or read-only shared) of the memfd while sealing is rather odd: it couldn't have been used to fill the memfd in the first place.

Most identified public users don't do anything like that: they either never map the memfd before write-sealing (using write() instead), or munmap() before write-sealing:

- systemd's journal writes, fwupd, Flatpak, runc, crun and containers/storage write to the memfd without mmap'ing it, before sealing it [1,2,3,4,5,6]. The FD consumer will not access the memfd before sealing.

- dbus-broker, Mutter, Chromium's Android linker, KWin, Weston and glycin map the memfd file, but unmap it before sealing [7,8,9,10,11,12]. glycin retries sealing while waiting for the loader to unmap.

Quoted 7 lines
Quoted 3 lines

- go-memfd exposes a shared writable mapping before F_SEAL_WRITE and a private read-only mapping afterwards. Its API explicitly requires unmapping the writable mapping before sealing [13].

When I wrote memfd-sealing, we had this use-case where an application writes a buffer and then shares it both with in-process and out-of-process tasks. Only if out-of-process tasks are actually involved, the buffer is sealed. Otherwise, it is kept unsealed and can be recycled. Hand-off to other processes was optional, rare and asynchronous, so sealing could happen at any time. Yet, we wanted to keep the buffers mapped to avoid costly TLB flushes. Mappings were readonly, but writes were done through syscalls.

We still do this, but I don't think any of the open-source users picked this up.

Ok. So internally you would have to accept the additional insecurity and enable the kernel workaround through the parameter. How much of a problem would such a workaround be in your fleet once you upgrade the kernel?

Not nice, but there is simply not proper way to fix this mess right now in a better way.

Quoted 3 lines

I did not follow the folio changes, so I am quite unsure whether the implementation was racy from the beginning, or whether new infrastructure introduced the races.

Can you elaborate why folio ref-counts are unreliable / unstable?

I'll have to point you at the doc of folio_expected_ref_count() where this is properly documented.

Back when you used page_count() vs. page_mapcount() you probably had no idea that this is completely racy as we didn't have any such helper to spell it out.

Signature · 3 lines
Cheers,

David
author maintainer
#8 lore raw
In reply to David Hildenbrand (Arm)
Quoted 21 lines · David Hildenbrand (Arm)

I spent way too much time on this, looking for better options. I think patch #1 fixes the most immediate issues but something like patch #2 is needed.

Long story short: someone can trigger a race such that we don't detect GUP references when write-sealing, allowing to modify content later.

Patch #1 handles pins reliably for folios with a pincount. Patch #2 handles the remaining references, but can reject write-sealing with populated file mappings. vm.memfd_write_seal_mapped allows restoring the legacy behavior if needed.

All alternatives to patch #2 I tried ended up too complicated and nasty in corner cases. We should never have allowed write-sealing with existing file mappings.

Plenty of details in patch #2.

Did some testing on x86-64 without any surprises.

Quoted 8 lines

---
David Hildenbrand (Arm) (2):
mm/memfd: handle GUP pins more reliably when write-sealing mm/memfd: handle GUP references reliably when write-sealing

 Documentation/admin-guide/sysctl/vm.rst | 21 +++++++++++++++
 mm/memfd.c                              | 45 ++++++++++++++++++++++++++++++++-
 2 files changed, 65 insertions(+), 1 deletion(-)

I think patch #1 is uncontroversial. It would be good to get some options on #2. With the current infrastructure we have, I don't really see a good way to tackle this differently.

I'd assume CRIU+write-sealed-memfd+mlock is rather the corner case ... :)

Signature · 3 lines
Cheers,

David