# \[PATCH\] userfaultfd: fix a race between writeprotect and exit\_mmap()

- Subsystems: FILESYSTEMS (VFS and infrastructure), THE REST
- Maintainers: Alexander Viro, Christian Brauner, Linus Torvalds
- Status: LANDED (cb185d5f1ebf · 2021-10-19 06:22)
- Landed in mainline as cb185d5f1ebf on 2021-10-19.
- List: stable
- 2 messages, 2 authors
- Page: https://ratatoskr.run/stable/2021/09/214721/t

## \[PATCH\] userfaultfd: fix a race between writeprotect and exit\_mmap()

- From: Nadav Amit \<hidden\>
- Date: 2021-09-22 03:33:40 
- Message: https://ratatoskr.run/stable/2021/09/214721.md

```text
From: Nadav Amit <redacted>

A race is possible when a process exits, its VMAs are removed
by exit_mmap() and at the same time userfaultfd_writeprotect() is
called.

The race was detected by KASAN on a development kernel, but it appears
to be possible on vanilla kernels as well.

Use mmget_not_zero() to prevent the race as done in other userfaultfd
operations.

Cc: Peter Xu <peterx@redhat.com>
Cc: Andrea Arcangeli <redacted>
Cc: <redacted>
Fixes: 63b2d4174c4ad ("userfaultfd: wp: add the writeprotect API to userfaultfd ioctl")
Signed-off-by: Nadav Amit <redacted>
---
 fs/userfaultfd.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)

diff --git a/fs/userfaultfd.c b/fs/userfaultfd.c
index 003f0d31743e..22bf14ab2d16 100644
--- a/fs/userfaultfd.c
+++ b/fs/userfaultfd.c
@@ -1827,9 +1827,15 @@ static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
 	if (mode_wp && mode_dontwake)
 		return -EINVAL;
 
-	ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
-				  uffdio_wp.range.len, mode_wp,
-				  &ctx->mmap_changing);
+	if (mmget_not_zero(ctx->mm)) {
+		ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
+					  uffdio_wp.range.len, mode_wp,
+					  &ctx->mmap_changing);
+		mmput(ctx->mm);
+	} else {
+		return -ESRCH;
+	}
+
 	if (ret)
 		return ret;
 
-- 
2.25.1

```

## Re: \[PATCH\] userfaultfd: fix a race between writeprotect and exit\_mmap()

- From: Peter Xu \<peterx@redhat.com\>
- Date: 2021-09-22 14:31:00 
- Message: https://ratatoskr.run/stable/2021/09/214750.md

```text
On Tue, Sep 21, 2021 at 01:02:47PM -0700, Nadav Amit wrote:
> From: Nadav Amit <redacted>
> 
> A race is possible when a process exits, its VMAs are removed
> by exit_mmap() and at the same time userfaultfd_writeprotect() is
> called.
> 
> The race was detected by KASAN on a development kernel, but it appears
> to be possible on vanilla kernels as well.
> 
> Use mmget_not_zero() to prevent the race as done in other userfaultfd
> operations.
> 
> Cc: Peter Xu <peterx@redhat.com>
> Cc: Andrea Arcangeli <redacted>
> Cc: <redacted>
> Fixes: 63b2d4174c4ad ("userfaultfd: wp: add the writeprotect API to userfaultfd ioctl")
> Signed-off-by: Nadav Amit <redacted>

Reviewed-by: Peter Xu <peterx@redhat.com>

Thanks!

-- 
Peter Xu

```
