Skip to contentSkip to conversation

userfaultfd21 updates v2

PATCH In review Andrea Arcangeli 2 participants 8 messages Jul 8, 2015 – Aug 28, 2015

Subsystems (4)
lore
Share & tools
lore
#0 lore raw

cover userfaultfd21 updates v2

Hello everyone,

This is an update for userfaultfd to synchronize -mm with the code in the userfaultfd21 git branch.

It includes: two fixes for some minor problem found with the selftest (qemu wouldn't trigger those), one debuggability improvement for gdb, the selftest itself and it adds one check to verify the API was followed in some case.

The wakeone patch is present in the userfault21 branch but it's deferred because it's just a minor optimization and the "require UFFDIO_API before other ioctls" patch has been updated according to upstream review of the previous submit of this update.

Andrea Arcangeli (5):
userfaultfd: require UFFDIO_API before other ioctls
userfaultfd: allow signals to interrupt a userfault
userfaultfd: propagate the full address in THP faults
userfaultfd: avoid missing wakeups during refile in userfaultfd_read
userfaultfd: selftest

 fs/userfaultfd.c                         |  65 +++-
 mm/huge_memory.c                         |  10 +-
 tools/testing/selftests/vm/Makefile      |   3 +
 tools/testing/selftests/vm/run_vmtests   |  11 +
 tools/testing/selftests/vm/userfaultfd.c | 636 +++++++++++++++++++++++++++++++
 5 files changed, 715 insertions(+), 10 deletions(-)
 create mode 100644 tools/testing/selftests/vm/userfaultfd.c

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#1 lore raw

PATCH 1/5 userfaultfd: require UFFDIO_API before other ioctls

UFFDIO_API was already forced before read/poll could work. This makes the code more strict to force it also for all other ioctls.

All users would already have been required to call UFFDIO_API before invoking other ioctls but this makes it more explicit.

This will ensure we can change all ioctls (all but UFFDIO_API/struct uffdio_api) with a bump of uffdio_api.api.

There's no actual plan or need to change the API or the ioctl, the current API already should cover fine even the non cooperative usage, but this is just for the longer term future just in case.

---
 fs/userfaultfd.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/userfaultfd.c +3 -1
index 89067cf..901d52a 100644
@@ -577,7 +577,6 @@ static ssize_t userfaultfd_read(struct file *file, char __user *buf,
 
 	if (ctx->state == UFFD_STATE_WAIT_API)
 		return -EINVAL;
-	BUG_ON(ctx->state != UFFD_STATE_RUNNING);
 
 	for (;;) {
 		if (count < sizeof(msg))
@@ -1115,6 +1114,9 @@ static long userfaultfd_ioctl(struct file *file, unsigned cmd,
 	int ret = -EINVAL;
 	struct userfaultfd_ctx *ctx = file->private_data;
 
+	if (cmd != UFFDIO_API && ctx->state == UFFD_STATE_WAIT_API)
+		return -EINVAL;
+
 	switch(cmd) {
 	case UFFDIO_API:
 		ret = userfaultfd_api(ctx, arg);

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#2 lore raw

PATCH 2/5 userfaultfd: allow signals to interrupt a userfault

In reply to Andrea Arcangeli

This is only simple to achieve if the userfault is going to return to userland (not to the kernel) because we can avoid returning VM_FAULT_RETRY despite we temporarily released the mmap_sem. The fault would just be retried by userland then. This is safe at least on x86 and powerpc (the two archs with the syscall implemented so far).

Hint to verify for which archs this is safe: after handle_mm_fault returns, no access to data structures protected by the mmap_sem must be done by the fault code in arch/*/mm/fault.c until up_read(&mm->mmap_sem) is called.

This has two main benefits: signals can run with lower latency in production (signals aren't blocked by userfaults and userfaults are immediately repeated after signal processing) and gdb can then trivially debug the threads blocked in this kind of userfaults coming directly from userland.

On a side note: while gdb has a need to get signal processed, coredumps always worked perfectly with userfaults, no matter if the userfault is triggered by GUP a kernel copy_user or directly from userland.

---
 fs/userfaultfd.c | 35 ++++++++++++++++++++++++++++++++---
 1 file changed, 32 insertions(+), 3 deletions(-)
fs/userfaultfd.c +32 -3
index 901d52a..851d575 100644
@@ -262,7 +262,7 @@ int handle_userfault(struct vm_area_struct *vma, unsigned long address,
 	struct userfaultfd_ctx *ctx;
 	struct userfaultfd_wait_queue uwq;
 	int ret;
-	bool must_wait;
+	bool must_wait, return_to_userland;
 
 	BUG_ON(!rwsem_is_locked(&mm->mmap_sem));
 
@@ -327,6 +327,9 @@ int handle_userfault(struct vm_area_struct *vma, unsigned long address,
 	uwq.msg = userfault_msg(address, flags, reason);
 	uwq.ctx = ctx;
 
+	return_to_userland = (flags & (FAULT_FLAG_USER|FAULT_FLAG_KILLABLE)) ==
+		(FAULT_FLAG_USER|FAULT_FLAG_KILLABLE);
+
 	spin_lock(&ctx->fault_pending_wqh.lock);
 	/*
 	 * After the __add_wait_queue the uwq is visible to userland
@@ -338,14 +341,16 @@ int handle_userfault(struct vm_area_struct *vma, unsigned long address,
 	 * following the spin_unlock to happen before the list_add in
 	 * __add_wait_queue.
 	 */
-	set_current_state(TASK_KILLABLE);
+	set_current_state(return_to_userland ? TASK_INTERRUPTIBLE :
+			  TASK_KILLABLE);
 	spin_unlock(&ctx->fault_pending_wqh.lock);
 
 	must_wait = userfaultfd_must_wait(ctx, address, flags, reason);
 	up_read(&mm->mmap_sem);
 
 	if (likely(must_wait && !ACCESS_ONCE(ctx->released) &&
-		   !fatal_signal_pending(current))) {
+		   (return_to_userland ? !signal_pending(current) :
+		    !fatal_signal_pending(current)))) {
 		wake_up_poll(&ctx->fd_wqh, POLLIN);
 		schedule();
 		ret |= VM_FAULT_MAJOR;
@@ -353,6 +358,30 @@ int handle_userfault(struct vm_area_struct *vma, unsigned long address,
 
 	__set_current_state(TASK_RUNNING);
 
+	if (return_to_userland) {
+		if (signal_pending(current) &&
+		    !fatal_signal_pending(current)) {
+			/*
+			 * If we got a SIGSTOP or SIGCONT and this is
+			 * a normal userland page fault, just let
+			 * userland return so the signal will be
+			 * handled and gdb debugging works.  The page
+			 * fault code immediately after we return from
+			 * this function is going to release the
+			 * mmap_sem and it's not depending on it
+			 * (unlike gup would if we were not to return
+			 * VM_FAULT_RETRY).
+			 *
+			 * If a fatal signal is pending we still take
+			 * the streamlined VM_FAULT_RETRY failure path
+			 * and there's no need to retake the mmap_sem
+			 * in such case.
+			 */
+			down_read(&mm->mmap_sem);
+			ret = 0;
+		}
+	}
+
 	/*
 	 * Here we race with the list_del; list_add in
 	 * userfaultfd_ctx_read(), however because we don't ever run

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#3 lore raw

PATCH 3/5 userfaultfd: propagate the full address in THP faults

In reply to Andrea Arcangeli

The THP faults were not propagating the original fault address. The latest version of the API with uffd.arg.pagefault.address is supposed to propagate the full address through THP faults.

This was not a kernel crashing bug and it wouldn't risk to corrupt user memory, but it would cause a SIGBUS failure because the wrong page was being copied.

For various reasons this wasn't easily reproducible in the qemu workload, but the strestest exposed the problem immediately.

---
 mm/huge_memory.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)
mm/huge_memory.c +6 -4
index 68fb507..f9f3337 100644
@@ -717,13 +717,14 @@ static inline pmd_t mk_huge_pmd(struct page *page, pgprot_t prot)
 
 static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
 					struct vm_area_struct *vma,
-					unsigned long haddr, pmd_t *pmd,
+					unsigned long address, pmd_t *pmd,
 					struct page *page, gfp_t gfp,
 					unsigned int flags)
 {
 	struct mem_cgroup *memcg;
 	pgtable_t pgtable;
 	spinlock_t *ptl;
+	unsigned long haddr = address & HPAGE_PMD_MASK;
 
 	VM_BUG_ON_PAGE(!PageCompound(page), page);
 
@@ -765,7 +766,7 @@ static int __do_huge_pmd_anonymous_page(struct mm_struct *mm,
 			mem_cgroup_cancel_charge(page, memcg);
 			put_page(page);
 			pte_free(mm, pgtable);
-			ret = handle_userfault(vma, haddr, flags,
+			ret = handle_userfault(vma, address, flags,
 					       VM_UFFD_MISSING);
 			VM_BUG_ON(ret & VM_FAULT_FALLBACK);
 			return ret;
@@ -841,7 +842,7 @@ int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
 		if (pmd_none(*pmd)) {
 			if (userfaultfd_missing(vma)) {
 				spin_unlock(ptl);
-				ret = handle_userfault(vma, haddr, flags,
+				ret = handle_userfault(vma, address, flags,
 						       VM_UFFD_MISSING);
 				VM_BUG_ON(ret & VM_FAULT_FALLBACK);
 			} else {
@@ -865,7 +866,8 @@ int do_huge_pmd_anonymous_page(struct mm_struct *mm, struct vm_area_struct *vma,
 		count_vm_event(THP_FAULT_FALLBACK);
 		return VM_FAULT_FALLBACK;
 	}
-	return __do_huge_pmd_anonymous_page(mm, vma, haddr, pmd, page, gfp, flags);
+	return __do_huge_pmd_anonymous_page(mm, vma, address, pmd, page, gfp,
+					    flags);
 }
 
 int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#4 lore raw

PATCH 4/5 userfaultfd: avoid missing wakeups during refile in userfaultfd_read

In reply to Andrea Arcangeli

During the refile in userfaultfd_read both waitqueues could look empty to the lockless wake_userfault(). Use a seqcount to prevent this false negative that could leave an userfault blocked.

---
 fs/userfaultfd.c | 26 ++++++++++++++++++++++++--
 1 file changed, 24 insertions(+), 2 deletions(-)
fs/userfaultfd.c +24 -2
index 851d575..6a117f8 100644
@@ -45,6 +45,8 @@ struct userfaultfd_ctx {
 	wait_queue_head_t fault_wqh;
 	/* waitqueue head for the pseudo fd to wakeup poll/read */
 	wait_queue_head_t fd_wqh;
+	/* a refile sequence protected by fault_pending_wqh lock */
+	struct seqcount refile_seq;
 	/* pseudo fd refcounting */
 	atomic_t refcount;
 	/* userfaultfd syscall flags */
@@ -547,6 +549,15 @@ static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
 		uwq = find_userfault(ctx);
 		if (uwq) {
 			/*
+			 * Use a seqcount to repeat the lockless check
+			 * in wake_userfault() to avoid missing
+			 * wakeups because during the refile both
+			 * waitqueue could become empty if this is the
+			 * only userfault.
+			 */
+			write_seqcount_begin(&ctx->refile_seq);
+
+			/*
 			 * The fault_pending_wqh.lock prevents the uwq
 			 * to disappear from under us.
 			 *
@@ -570,6 +581,8 @@ static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
 			list_del(&uwq->wq.task_list);
 			__add_wait_queue(&ctx->fault_wqh, &uwq->wq);
 
+			write_seqcount_end(&ctx->refile_seq);
+
 			/* careful to always initialize msg if ret == 0 */
 			*msg = uwq->msg;
 			spin_unlock(&ctx->fault_pending_wqh.lock);
@@ -647,6 +660,9 @@ static void __wake_userfault(struct userfaultfd_ctx *ctx,
 static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
 					   struct userfaultfd_wake_range *range)
 {
+	unsigned seq;
+	bool need_wakeup;
+
 	/*
 	 * To be sure waitqueue_active() is not reordered by the CPU
 	 * before the pagetable update, use an explicit SMP memory
@@ -662,8 +678,13 @@ static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
 	 * userfaults yet. So we take the spinlock only when we're
 	 * sure we've userfaults to wake.
 	 */
-	if (waitqueue_active(&ctx->fault_pending_wqh) ||
-	    waitqueue_active(&ctx->fault_wqh))
+	do {
+		seq = read_seqcount_begin(&ctx->refile_seq);
+		need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
+			waitqueue_active(&ctx->fault_wqh);
+		cond_resched();
+	} while (read_seqcount_retry(&ctx->refile_seq, seq));
+	if (need_wakeup)
 		__wake_userfault(ctx, range);
 }
 
@@ -1219,6 +1240,7 @@ static void init_once_userfaultfd_ctx(void *mem)
 	init_waitqueue_head(&ctx->fault_pending_wqh);
 	init_waitqueue_head(&ctx->fault_wqh);
 	init_waitqueue_head(&ctx->fd_wqh);
+	seqcount_init(&ctx->refile_seq);
 }
 
 /**

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#5 lore raw

PATCH 5/5 userfaultfd: selftest

In reply to Andrea Arcangeli

This test allocates two virtual areas and bounces the physical memory across the two virtual areas using only userfaultfd.

---
 tools/testing/selftests/vm/Makefile      |   3 +
 tools/testing/selftests/vm/run_vmtests   |  11 +
 tools/testing/selftests/vm/userfaultfd.c | 636 +++++++++++++++++++++++++++++++
 3 files changed, 650 insertions(+)
 create mode 100644 tools/testing/selftests/vm/userfaultfd.c
tools/testing/selftests/vm/Makefile +3 -0
index 231b9a0..0d68547 100644
@@ -8,10 +8,13 @@ BINARIES += hugetlbfstest
 BINARIES += map_hugetlb
 BINARIES += thuge-gen
 BINARIES += transhuge-stress
+BINARIES += userfaultfd
 
 all: $(BINARIES)
 %: %.c
 	$(CC) $(CFLAGS) -o $@ $^ -lrt
+userfaultfd: userfaultfd.c
+	$(CC) $(CFLAGS) -O2 -o $@ $^ -lpthread
 
 TEST_PROGS := run_vmtests
 TEST_FILES := $(BINARIES)
tools/testing/selftests/vm/run_vmtests +11 -0
index 49ece11..831adeb 100755
@@ -86,6 +86,17 @@ else
 	echo "[PASS]"
 fi
 
+echo "--------------------"
+echo "running userfaultfd"
+echo "--------------------"
+./userfaultfd 128 32
+if [ $? -ne 0 ]; then
+	echo "[FAIL]"
+	exitcode=1
+else
+	echo "[PASS]"
+fi
+
 #cleanup
 umount $mnt
 rm -rf $mnt
tools/testing/selftests/vm/userfaultfd.c new file +636 -0

636 lines not on this page · raw message

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#6 lore raw
In reply to Andrea Arcangeli

Hi Andrea,

Is there a way you can think of to use userfaultfd without having a separate thread to sit there and be watching the file descriptor? The current model doesn't seem like it would be possible to use with a single-threaded app, for instance.

Is there a reason we couldn't generate a signal and then have the userfaultfd handling done inside the signal handler?

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#7 lore raw

Hi Dave,

Quoted 9 lines · Dave Hansen

Hi Andrea,

Is there a way you can think of to use userfaultfd without having a separate thread to sit there and be watching the file descriptor? The current model doesn't seem like it would be possible to use with a single-threaded app, for instance.

Is there a reason we couldn't generate a signal and then have the userfaultfd handling done inside the signal handler?

Originally it worked precisely like that, much like volatile pages or the regular PROT_NONE+sigsegv would do (it only avoided the vma mangling). However that can't work for syscalls and get_user_pages. I thought of taking care of get_user_pages called by the KVM shadow page fault handler in a special way, but then there's O_DIRECT (or other get_user_pages) that may be invoked by userland on top of the userfault memory, which would also run into a get_user_pages done on a userfault area.

How do you run a single threaded signal when get_user_pages finds that it has been called on a userfault region or when copy-user returns -EFAULT? It's unthinkable to break the syscall API with new retvals and require all apps to change the error checks of the syscalls to use userfaultfd safely. We could try to play tricks with restarting syscalls within glibc but that sigbus would be the same as a real SIGBUS. Even updating qemu alone to accept new retvals of read/write O_DIRECT syscalls, sounds like a bad idea compared to the current userfaultfd API which is entirely transparent to all syscalls and also to the KVM shadow page fault handler.

The old MADV_USERFAULT/NOUSERFAULT madvise I entirely dropped it and it's basically become the UFFDIO_REGISTER/UNREGISTER ioctls. It looked bad idea to start with MADV_USERFAULT and signals, as you may later notice you need to use a syscall and you've to rewrite the code with the userfaultfd... better to start right away with userfaultfd and avoid the risk of wasting time.

Right now copy-user and get_user_pages just blocks in kernel so userfaults are effectively invisible to the single threaded workflow:
get_user_pages API from the caller point of view is totally userfaultfd agnostic, but you need a separate thread to handle the fault.

The fact the kernel in the blocked fault talks with the userland thread directly over the fd should be more efficient too. The only downside is a schedule() call when blocking, but on the plus side we don't have to invoke the signal code at all which also isn't free (even if potentially less costly than schedule when having lots of runnable tasks and CPU overcommit). In addition signal themself can trip on userfaults now, and gdb also will successfully send sigstop to userfault blocked faults if they didn't happen in kernel context (where again signals, not even sigstop/sigcont, can't run).

The only requirement added has been to have VM_FAULT_RETRY set in every fault or get_user_pages that can hit on userfaultfd registered regions, so we can drop the mmap_sem before blocking. We've to drop the mmap_sem or we'd allow an userland thread to indefinitely leave mmap_sem hold, which wouldn't safe (ps may block indefinitely etc..).

If there's a bug and VM_FAULT_RETRY is missing, SIGBUS is raised, O_DIRECT or KVM page fault would return some noticeable error (like if it was a real SIGBUS), and a rate limited printk is printed in the log along with the offending stack trace that must be fixed to pass VM_FAULT_RETRY.

On a side note, I'm about to extend this VM_FAULT_RETRY so that if the userfault is invoked when FAULT_FLAG_TRIED is set (which means VM_FAULT_RETRY was also previously set) we can one still hang and drop the mmap_sem. This is the major not-self-contained change needed to introduce the wrprotect fault tracking to userfaultfd (so that postcopy live snapshotting becomes possible and distributed shared memory with readonly-shared write-exclusive semantics also becomes possible). With wrprotect faults, the pagetable-based vma-less wrprotection can be armed with a UFFDIO_ ioctl while the page fault is for other reason already in the VM_FAULT_RETRY path and it already consumed it, so we may hit an wrprotect userfault in the FAULT_FLAG_TRIED case (that cannot happen with the missing fault mode, so we didn't need to alter the page fault logic yet and the stock VM_FAULT_RETRY sufficed so far).

Thanks,
Andrea

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>