xref: /openbmc/linux/fs/userfaultfd.c (revision b8da2e466000b232a6b67072bbef375061142daa)
120c8ccb1SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
286039bd3SAndrea Arcangeli /*
386039bd3SAndrea Arcangeli  *  fs/userfaultfd.c
486039bd3SAndrea Arcangeli  *
586039bd3SAndrea Arcangeli  *  Copyright (C) 2007  Davide Libenzi <davidel@xmailserver.org>
686039bd3SAndrea Arcangeli  *  Copyright (C) 2008-2009 Red Hat, Inc.
786039bd3SAndrea Arcangeli  *  Copyright (C) 2015  Red Hat, Inc.
886039bd3SAndrea Arcangeli  *
986039bd3SAndrea Arcangeli  *  Some part derived from fs/eventfd.c (anon inode setup) and
1086039bd3SAndrea Arcangeli  *  mm/ksm.c (mm hashing).
1186039bd3SAndrea Arcangeli  */
1286039bd3SAndrea Arcangeli 
139cd75c3cSPavel Emelyanov #include <linux/list.h>
1486039bd3SAndrea Arcangeli #include <linux/hashtable.h>
15174cd4b1SIngo Molnar #include <linux/sched/signal.h>
166e84f315SIngo Molnar #include <linux/sched/mm.h>
1786039bd3SAndrea Arcangeli #include <linux/mm.h>
1817fca131SArnd Bergmann #include <linux/mm_inline.h>
196dfeaff9SPeter Xu #include <linux/mmu_notifier.h>
2086039bd3SAndrea Arcangeli #include <linux/poll.h>
2186039bd3SAndrea Arcangeli #include <linux/slab.h>
2286039bd3SAndrea Arcangeli #include <linux/seq_file.h>
2386039bd3SAndrea Arcangeli #include <linux/file.h>
2486039bd3SAndrea Arcangeli #include <linux/bug.h>
2586039bd3SAndrea Arcangeli #include <linux/anon_inodes.h>
2686039bd3SAndrea Arcangeli #include <linux/syscalls.h>
2786039bd3SAndrea Arcangeli #include <linux/userfaultfd_k.h>
2886039bd3SAndrea Arcangeli #include <linux/mempolicy.h>
2986039bd3SAndrea Arcangeli #include <linux/ioctl.h>
3086039bd3SAndrea Arcangeli #include <linux/security.h>
31cab350afSMike Kravetz #include <linux/hugetlb.h>
325c041f5dSPeter Xu #include <linux/swapops.h>
332d5de004SAxel Rasmussen #include <linux/miscdevice.h>
3486039bd3SAndrea Arcangeli 
35d0d4730aSLokesh Gidra int sysctl_unprivileged_userfaultfd __read_mostly;
36cefdca0aSPeter Xu 
373004ec9cSAndrea Arcangeli static struct kmem_cache *userfaultfd_ctx_cachep __read_mostly;
383004ec9cSAndrea Arcangeli 
393004ec9cSAndrea Arcangeli /*
403004ec9cSAndrea Arcangeli  * Start with fault_pending_wqh and fault_wqh so they're more likely
413004ec9cSAndrea Arcangeli  * to be in the same cacheline.
42cbcfa130SEric Biggers  *
43cbcfa130SEric Biggers  * Locking order:
44cbcfa130SEric Biggers  *	fd_wqh.lock
45cbcfa130SEric Biggers  *		fault_pending_wqh.lock
46cbcfa130SEric Biggers  *			fault_wqh.lock
47cbcfa130SEric Biggers  *		event_wqh.lock
48cbcfa130SEric Biggers  *
49cbcfa130SEric Biggers  * To avoid deadlocks, IRQs must be disabled when taking any of the above locks,
50cbcfa130SEric Biggers  * since fd_wqh.lock is taken by aio_poll() while it's holding a lock that's
51cbcfa130SEric Biggers  * also taken in IRQ context.
523004ec9cSAndrea Arcangeli  */
5386039bd3SAndrea Arcangeli struct userfaultfd_ctx {
5415b726efSAndrea Arcangeli 	/* waitqueue head for the pending (i.e. not read) userfaults */
5515b726efSAndrea Arcangeli 	wait_queue_head_t fault_pending_wqh;
5615b726efSAndrea Arcangeli 	/* waitqueue head for the userfaults */
5786039bd3SAndrea Arcangeli 	wait_queue_head_t fault_wqh;
5886039bd3SAndrea Arcangeli 	/* waitqueue head for the pseudo fd to wakeup poll/read */
5986039bd3SAndrea Arcangeli 	wait_queue_head_t fd_wqh;
609cd75c3cSPavel Emelyanov 	/* waitqueue head for events */
619cd75c3cSPavel Emelyanov 	wait_queue_head_t event_wqh;
622c5b7e1bSAndrea Arcangeli 	/* a refile sequence protected by fault_pending_wqh lock */
632ca97ac8SAhmed S. Darwish 	seqcount_spinlock_t refile_seq;
643004ec9cSAndrea Arcangeli 	/* pseudo fd refcounting */
65ca880420SEric Biggers 	refcount_t refcount;
6686039bd3SAndrea Arcangeli 	/* userfaultfd syscall flags */
6786039bd3SAndrea Arcangeli 	unsigned int flags;
689cd75c3cSPavel Emelyanov 	/* features requested from the userspace */
699cd75c3cSPavel Emelyanov 	unsigned int features;
7086039bd3SAndrea Arcangeli 	/* released */
7186039bd3SAndrea Arcangeli 	bool released;
72df2cc96eSMike Rapoport 	/* memory mappings are changing because of non-cooperative event */
73a759a909SNadav Amit 	atomic_t mmap_changing;
7486039bd3SAndrea Arcangeli 	/* mm with one ore more vmas attached to this userfaultfd_ctx */
7586039bd3SAndrea Arcangeli 	struct mm_struct *mm;
7686039bd3SAndrea Arcangeli };
7786039bd3SAndrea Arcangeli 
78893e26e6SPavel Emelyanov struct userfaultfd_fork_ctx {
79893e26e6SPavel Emelyanov 	struct userfaultfd_ctx *orig;
80893e26e6SPavel Emelyanov 	struct userfaultfd_ctx *new;
81893e26e6SPavel Emelyanov 	struct list_head list;
82893e26e6SPavel Emelyanov };
83893e26e6SPavel Emelyanov 
84897ab3e0SMike Rapoport struct userfaultfd_unmap_ctx {
85897ab3e0SMike Rapoport 	struct userfaultfd_ctx *ctx;
86897ab3e0SMike Rapoport 	unsigned long start;
87897ab3e0SMike Rapoport 	unsigned long end;
88897ab3e0SMike Rapoport 	struct list_head list;
89897ab3e0SMike Rapoport };
90897ab3e0SMike Rapoport 
9186039bd3SAndrea Arcangeli struct userfaultfd_wait_queue {
92a9b85f94SAndrea Arcangeli 	struct uffd_msg msg;
93ac6424b9SIngo Molnar 	wait_queue_entry_t wq;
9486039bd3SAndrea Arcangeli 	struct userfaultfd_ctx *ctx;
9515a77c6fSAndrea Arcangeli 	bool waken;
9686039bd3SAndrea Arcangeli };
9786039bd3SAndrea Arcangeli 
9886039bd3SAndrea Arcangeli struct userfaultfd_wake_range {
9986039bd3SAndrea Arcangeli 	unsigned long start;
10086039bd3SAndrea Arcangeli 	unsigned long len;
10186039bd3SAndrea Arcangeli };
10286039bd3SAndrea Arcangeli 
10322e5fe2aSNadav Amit /* internal indication that UFFD_API ioctl was successfully executed */
10422e5fe2aSNadav Amit #define UFFD_FEATURE_INITIALIZED		(1u << 31)
10522e5fe2aSNadav Amit 
10622e5fe2aSNadav Amit static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx)
10722e5fe2aSNadav Amit {
10822e5fe2aSNadav Amit 	return ctx->features & UFFD_FEATURE_INITIALIZED;
10922e5fe2aSNadav Amit }
11022e5fe2aSNadav Amit 
11151d3d5ebSDavid Hildenbrand static void userfaultfd_set_vm_flags(struct vm_area_struct *vma,
11251d3d5ebSDavid Hildenbrand 				     vm_flags_t flags)
11351d3d5ebSDavid Hildenbrand {
11451d3d5ebSDavid Hildenbrand 	const bool uffd_wp_changed = (vma->vm_flags ^ flags) & VM_UFFD_WP;
11551d3d5ebSDavid Hildenbrand 
11651d3d5ebSDavid Hildenbrand 	vma->vm_flags = flags;
11751d3d5ebSDavid Hildenbrand 	/*
11851d3d5ebSDavid Hildenbrand 	 * For shared mappings, we want to enable writenotify while
11951d3d5ebSDavid Hildenbrand 	 * userfaultfd-wp is enabled (see vma_wants_writenotify()). We'll simply
12051d3d5ebSDavid Hildenbrand 	 * recalculate vma->vm_page_prot whenever userfaultfd-wp changes.
12151d3d5ebSDavid Hildenbrand 	 */
12251d3d5ebSDavid Hildenbrand 	if ((vma->vm_flags & VM_SHARED) && uffd_wp_changed)
12351d3d5ebSDavid Hildenbrand 		vma_set_page_prot(vma);
12451d3d5ebSDavid Hildenbrand }
12551d3d5ebSDavid Hildenbrand 
126ac6424b9SIngo Molnar static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,
12786039bd3SAndrea Arcangeli 				     int wake_flags, void *key)
12886039bd3SAndrea Arcangeli {
12986039bd3SAndrea Arcangeli 	struct userfaultfd_wake_range *range = key;
13086039bd3SAndrea Arcangeli 	int ret;
13186039bd3SAndrea Arcangeli 	struct userfaultfd_wait_queue *uwq;
13286039bd3SAndrea Arcangeli 	unsigned long start, len;
13386039bd3SAndrea Arcangeli 
13486039bd3SAndrea Arcangeli 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
13586039bd3SAndrea Arcangeli 	ret = 0;
13686039bd3SAndrea Arcangeli 	/* len == 0 means wake all */
13786039bd3SAndrea Arcangeli 	start = range->start;
13886039bd3SAndrea Arcangeli 	len = range->len;
139a9b85f94SAndrea Arcangeli 	if (len && (start > uwq->msg.arg.pagefault.address ||
140a9b85f94SAndrea Arcangeli 		    start + len <= uwq->msg.arg.pagefault.address))
14186039bd3SAndrea Arcangeli 		goto out;
14215a77c6fSAndrea Arcangeli 	WRITE_ONCE(uwq->waken, true);
14315a77c6fSAndrea Arcangeli 	/*
144a9668cd6SPeter Zijlstra 	 * The Program-Order guarantees provided by the scheduler
145a9668cd6SPeter Zijlstra 	 * ensure uwq->waken is visible before the task is woken.
14615a77c6fSAndrea Arcangeli 	 */
14786039bd3SAndrea Arcangeli 	ret = wake_up_state(wq->private, mode);
148a9668cd6SPeter Zijlstra 	if (ret) {
14986039bd3SAndrea Arcangeli 		/*
15086039bd3SAndrea Arcangeli 		 * Wake only once, autoremove behavior.
15186039bd3SAndrea Arcangeli 		 *
152a9668cd6SPeter Zijlstra 		 * After the effect of list_del_init is visible to the other
153a9668cd6SPeter Zijlstra 		 * CPUs, the waitqueue may disappear from under us, see the
154a9668cd6SPeter Zijlstra 		 * !list_empty_careful() in handle_userfault().
155a9668cd6SPeter Zijlstra 		 *
156a9668cd6SPeter Zijlstra 		 * try_to_wake_up() has an implicit smp_mb(), and the
157a9668cd6SPeter Zijlstra 		 * wq->private is read before calling the extern function
158a9668cd6SPeter Zijlstra 		 * "wake_up_state" (which in turns calls try_to_wake_up).
15986039bd3SAndrea Arcangeli 		 */
1602055da97SIngo Molnar 		list_del_init(&wq->entry);
161a9668cd6SPeter Zijlstra 	}
16286039bd3SAndrea Arcangeli out:
16386039bd3SAndrea Arcangeli 	return ret;
16486039bd3SAndrea Arcangeli }
16586039bd3SAndrea Arcangeli 
16686039bd3SAndrea Arcangeli /**
16786039bd3SAndrea Arcangeli  * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd
16886039bd3SAndrea Arcangeli  * context.
16986039bd3SAndrea Arcangeli  * @ctx: [in] Pointer to the userfaultfd context.
17086039bd3SAndrea Arcangeli  */
17186039bd3SAndrea Arcangeli static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx)
17286039bd3SAndrea Arcangeli {
173ca880420SEric Biggers 	refcount_inc(&ctx->refcount);
17486039bd3SAndrea Arcangeli }
17586039bd3SAndrea Arcangeli 
17686039bd3SAndrea Arcangeli /**
17786039bd3SAndrea Arcangeli  * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd
17886039bd3SAndrea Arcangeli  * context.
17986039bd3SAndrea Arcangeli  * @ctx: [in] Pointer to userfaultfd context.
18086039bd3SAndrea Arcangeli  *
18186039bd3SAndrea Arcangeli  * The userfaultfd context reference must have been previously acquired either
18286039bd3SAndrea Arcangeli  * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget().
18386039bd3SAndrea Arcangeli  */
18486039bd3SAndrea Arcangeli static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx)
18586039bd3SAndrea Arcangeli {
186ca880420SEric Biggers 	if (refcount_dec_and_test(&ctx->refcount)) {
18786039bd3SAndrea Arcangeli 		VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));
18886039bd3SAndrea Arcangeli 		VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));
18986039bd3SAndrea Arcangeli 		VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));
19086039bd3SAndrea Arcangeli 		VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));
1919cd75c3cSPavel Emelyanov 		VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));
1929cd75c3cSPavel Emelyanov 		VM_BUG_ON(waitqueue_active(&ctx->event_wqh));
19386039bd3SAndrea Arcangeli 		VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));
19486039bd3SAndrea Arcangeli 		VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));
195d2005e3fSOleg Nesterov 		mmdrop(ctx->mm);
1963004ec9cSAndrea Arcangeli 		kmem_cache_free(userfaultfd_ctx_cachep, ctx);
19786039bd3SAndrea Arcangeli 	}
19886039bd3SAndrea Arcangeli }
19986039bd3SAndrea Arcangeli 
200a9b85f94SAndrea Arcangeli static inline void msg_init(struct uffd_msg *msg)
201a9b85f94SAndrea Arcangeli {
202a9b85f94SAndrea Arcangeli 	BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);
203a9b85f94SAndrea Arcangeli 	/*
204a9b85f94SAndrea Arcangeli 	 * Must use memset to zero out the paddings or kernel data is
205a9b85f94SAndrea Arcangeli 	 * leaked to userland.
206a9b85f94SAndrea Arcangeli 	 */
207a9b85f94SAndrea Arcangeli 	memset(msg, 0, sizeof(struct uffd_msg));
208a9b85f94SAndrea Arcangeli }
209a9b85f94SAndrea Arcangeli 
210a9b85f94SAndrea Arcangeli static inline struct uffd_msg userfault_msg(unsigned long address,
211d172b1a3SNadav Amit 					    unsigned long real_address,
21286039bd3SAndrea Arcangeli 					    unsigned int flags,
2139d4ac934SAlexey Perevalov 					    unsigned long reason,
2149d4ac934SAlexey Perevalov 					    unsigned int features)
21586039bd3SAndrea Arcangeli {
216a9b85f94SAndrea Arcangeli 	struct uffd_msg msg;
217d172b1a3SNadav Amit 
218a9b85f94SAndrea Arcangeli 	msg_init(&msg);
219a9b85f94SAndrea Arcangeli 	msg.event = UFFD_EVENT_PAGEFAULT;
220824ddc60SNadav Amit 
221d172b1a3SNadav Amit 	msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?
222d172b1a3SNadav Amit 				    real_address : address;
223d172b1a3SNadav Amit 
22486039bd3SAndrea Arcangeli 	/*
2257677f7fdSAxel Rasmussen 	 * These flags indicate why the userfault occurred:
2267677f7fdSAxel Rasmussen 	 * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.
2277677f7fdSAxel Rasmussen 	 * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.
2287677f7fdSAxel Rasmussen 	 * - Neither of these flags being set indicates a MISSING fault.
2297677f7fdSAxel Rasmussen 	 *
2307677f7fdSAxel Rasmussen 	 * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write
2317677f7fdSAxel Rasmussen 	 * fault. Otherwise, it was a read fault.
23286039bd3SAndrea Arcangeli 	 */
2337677f7fdSAxel Rasmussen 	if (flags & FAULT_FLAG_WRITE)
234a9b85f94SAndrea Arcangeli 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;
23586039bd3SAndrea Arcangeli 	if (reason & VM_UFFD_WP)
236a9b85f94SAndrea Arcangeli 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;
2377677f7fdSAxel Rasmussen 	if (reason & VM_UFFD_MINOR)
2387677f7fdSAxel Rasmussen 		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;
2399d4ac934SAlexey Perevalov 	if (features & UFFD_FEATURE_THREAD_ID)
240a36985d3SAndrea Arcangeli 		msg.arg.pagefault.feat.ptid = task_pid_vnr(current);
241a9b85f94SAndrea Arcangeli 	return msg;
24286039bd3SAndrea Arcangeli }
24386039bd3SAndrea Arcangeli 
244369cd212SMike Kravetz #ifdef CONFIG_HUGETLB_PAGE
245369cd212SMike Kravetz /*
246369cd212SMike Kravetz  * Same functionality as userfaultfd_must_wait below with modifications for
247369cd212SMike Kravetz  * hugepmd ranges.
248369cd212SMike Kravetz  */
249369cd212SMike Kravetz static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
2507868a208SPunit Agrawal 					 struct vm_area_struct *vma,
251369cd212SMike Kravetz 					 unsigned long address,
252369cd212SMike Kravetz 					 unsigned long flags,
253369cd212SMike Kravetz 					 unsigned long reason)
254369cd212SMike Kravetz {
255369cd212SMike Kravetz 	struct mm_struct *mm = ctx->mm;
2561e2c0436SJanosch Frank 	pte_t *ptep, pte;
257369cd212SMike Kravetz 	bool ret = true;
258369cd212SMike Kravetz 
25942fc5414SMichel Lespinasse 	mmap_assert_locked(mm);
260369cd212SMike Kravetz 
2611e2c0436SJanosch Frank 	ptep = huge_pte_offset(mm, address, vma_mmu_pagesize(vma));
2621e2c0436SJanosch Frank 
2631e2c0436SJanosch Frank 	if (!ptep)
264369cd212SMike Kravetz 		goto out;
265369cd212SMike Kravetz 
266369cd212SMike Kravetz 	ret = false;
2671e2c0436SJanosch Frank 	pte = huge_ptep_get(ptep);
268369cd212SMike Kravetz 
269369cd212SMike Kravetz 	/*
270369cd212SMike Kravetz 	 * Lockless access: we're in a wait_event so it's ok if it
2715c041f5dSPeter Xu 	 * changes under us.  PTE markers should be handled the same as none
2725c041f5dSPeter Xu 	 * ptes here.
273369cd212SMike Kravetz 	 */
2745c041f5dSPeter Xu 	if (huge_pte_none_mostly(pte))
275369cd212SMike Kravetz 		ret = true;
2761e2c0436SJanosch Frank 	if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))
277369cd212SMike Kravetz 		ret = true;
278369cd212SMike Kravetz out:
279369cd212SMike Kravetz 	return ret;
280369cd212SMike Kravetz }
281369cd212SMike Kravetz #else
282369cd212SMike Kravetz static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,
2837868a208SPunit Agrawal 					 struct vm_area_struct *vma,
284369cd212SMike Kravetz 					 unsigned long address,
285369cd212SMike Kravetz 					 unsigned long flags,
286369cd212SMike Kravetz 					 unsigned long reason)
287369cd212SMike Kravetz {
288369cd212SMike Kravetz 	return false;	/* should never get here */
289369cd212SMike Kravetz }
290369cd212SMike Kravetz #endif /* CONFIG_HUGETLB_PAGE */
291369cd212SMike Kravetz 
29286039bd3SAndrea Arcangeli /*
2938d2afd96SAndrea Arcangeli  * Verify the pagetables are still not ok after having reigstered into
2948d2afd96SAndrea Arcangeli  * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any
2958d2afd96SAndrea Arcangeli  * userfault that has already been resolved, if userfaultfd_read and
2968d2afd96SAndrea Arcangeli  * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different
2978d2afd96SAndrea Arcangeli  * threads.
2988d2afd96SAndrea Arcangeli  */
2998d2afd96SAndrea Arcangeli static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,
3008d2afd96SAndrea Arcangeli 					 unsigned long address,
3018d2afd96SAndrea Arcangeli 					 unsigned long flags,
3028d2afd96SAndrea Arcangeli 					 unsigned long reason)
3038d2afd96SAndrea Arcangeli {
3048d2afd96SAndrea Arcangeli 	struct mm_struct *mm = ctx->mm;
3058d2afd96SAndrea Arcangeli 	pgd_t *pgd;
306c2febafcSKirill A. Shutemov 	p4d_t *p4d;
3078d2afd96SAndrea Arcangeli 	pud_t *pud;
3088d2afd96SAndrea Arcangeli 	pmd_t *pmd, _pmd;
3098d2afd96SAndrea Arcangeli 	pte_t *pte;
3108d2afd96SAndrea Arcangeli 	bool ret = true;
3118d2afd96SAndrea Arcangeli 
31242fc5414SMichel Lespinasse 	mmap_assert_locked(mm);
3138d2afd96SAndrea Arcangeli 
3148d2afd96SAndrea Arcangeli 	pgd = pgd_offset(mm, address);
3158d2afd96SAndrea Arcangeli 	if (!pgd_present(*pgd))
3168d2afd96SAndrea Arcangeli 		goto out;
317c2febafcSKirill A. Shutemov 	p4d = p4d_offset(pgd, address);
318c2febafcSKirill A. Shutemov 	if (!p4d_present(*p4d))
319c2febafcSKirill A. Shutemov 		goto out;
320c2febafcSKirill A. Shutemov 	pud = pud_offset(p4d, address);
3218d2afd96SAndrea Arcangeli 	if (!pud_present(*pud))
3228d2afd96SAndrea Arcangeli 		goto out;
3238d2afd96SAndrea Arcangeli 	pmd = pmd_offset(pud, address);
3248d2afd96SAndrea Arcangeli 	/*
3258d2afd96SAndrea Arcangeli 	 * READ_ONCE must function as a barrier with narrower scope
3268d2afd96SAndrea Arcangeli 	 * and it must be equivalent to:
3278d2afd96SAndrea Arcangeli 	 *	_pmd = *pmd; barrier();
3288d2afd96SAndrea Arcangeli 	 *
3298d2afd96SAndrea Arcangeli 	 * This is to deal with the instability (as in
3308d2afd96SAndrea Arcangeli 	 * pmd_trans_unstable) of the pmd.
3318d2afd96SAndrea Arcangeli 	 */
3328d2afd96SAndrea Arcangeli 	_pmd = READ_ONCE(*pmd);
333a365ac09SHuang Ying 	if (pmd_none(_pmd))
3348d2afd96SAndrea Arcangeli 		goto out;
3358d2afd96SAndrea Arcangeli 
3368d2afd96SAndrea Arcangeli 	ret = false;
337a365ac09SHuang Ying 	if (!pmd_present(_pmd))
338a365ac09SHuang Ying 		goto out;
339a365ac09SHuang Ying 
34063b2d417SAndrea Arcangeli 	if (pmd_trans_huge(_pmd)) {
34163b2d417SAndrea Arcangeli 		if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))
34263b2d417SAndrea Arcangeli 			ret = true;
3438d2afd96SAndrea Arcangeli 		goto out;
34463b2d417SAndrea Arcangeli 	}
3458d2afd96SAndrea Arcangeli 
3468d2afd96SAndrea Arcangeli 	/*
3478d2afd96SAndrea Arcangeli 	 * the pmd is stable (as in !pmd_trans_unstable) so we can re-read it
3488d2afd96SAndrea Arcangeli 	 * and use the standard pte_offset_map() instead of parsing _pmd.
3498d2afd96SAndrea Arcangeli 	 */
3508d2afd96SAndrea Arcangeli 	pte = pte_offset_map(pmd, address);
3518d2afd96SAndrea Arcangeli 	/*
3528d2afd96SAndrea Arcangeli 	 * Lockless access: we're in a wait_event so it's ok if it
3535c041f5dSPeter Xu 	 * changes under us.  PTE markers should be handled the same as none
3545c041f5dSPeter Xu 	 * ptes here.
3558d2afd96SAndrea Arcangeli 	 */
3565c041f5dSPeter Xu 	if (pte_none_mostly(*pte))
3578d2afd96SAndrea Arcangeli 		ret = true;
35863b2d417SAndrea Arcangeli 	if (!pte_write(*pte) && (reason & VM_UFFD_WP))
35963b2d417SAndrea Arcangeli 		ret = true;
3608d2afd96SAndrea Arcangeli 	pte_unmap(pte);
3618d2afd96SAndrea Arcangeli 
3628d2afd96SAndrea Arcangeli out:
3638d2afd96SAndrea Arcangeli 	return ret;
3648d2afd96SAndrea Arcangeli }
3658d2afd96SAndrea Arcangeli 
3662f064a59SPeter Zijlstra static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags)
3673e69ad08SPeter Xu {
3683e69ad08SPeter Xu 	if (flags & FAULT_FLAG_INTERRUPTIBLE)
3693e69ad08SPeter Xu 		return TASK_INTERRUPTIBLE;
3703e69ad08SPeter Xu 
3713e69ad08SPeter Xu 	if (flags & FAULT_FLAG_KILLABLE)
3723e69ad08SPeter Xu 		return TASK_KILLABLE;
3733e69ad08SPeter Xu 
3743e69ad08SPeter Xu 	return TASK_UNINTERRUPTIBLE;
3753e69ad08SPeter Xu }
3763e69ad08SPeter Xu 
3778d2afd96SAndrea Arcangeli /*
37886039bd3SAndrea Arcangeli  * The locking rules involved in returning VM_FAULT_RETRY depending on
37986039bd3SAndrea Arcangeli  * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and
38086039bd3SAndrea Arcangeli  * FAULT_FLAG_KILLABLE are not straightforward. The "Caution"
38186039bd3SAndrea Arcangeli  * recommendation in __lock_page_or_retry is not an understatement.
38286039bd3SAndrea Arcangeli  *
383c1e8d7c6SMichel Lespinasse  * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released
38486039bd3SAndrea Arcangeli  * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is
38586039bd3SAndrea Arcangeli  * not set.
38686039bd3SAndrea Arcangeli  *
38786039bd3SAndrea Arcangeli  * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not
38886039bd3SAndrea Arcangeli  * set, VM_FAULT_RETRY can still be returned if and only if there are
389c1e8d7c6SMichel Lespinasse  * fatal_signal_pending()s, and the mmap_lock must be released before
39086039bd3SAndrea Arcangeli  * returning it.
39186039bd3SAndrea Arcangeli  */
3922b740303SSouptick Joarder vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason)
39386039bd3SAndrea Arcangeli {
394*b8da2e46SPeter Xu 	struct vm_area_struct *vma = vmf->vma;
395*b8da2e46SPeter Xu 	struct mm_struct *mm = vma->vm_mm;
39686039bd3SAndrea Arcangeli 	struct userfaultfd_ctx *ctx;
39786039bd3SAndrea Arcangeli 	struct userfaultfd_wait_queue uwq;
3982b740303SSouptick Joarder 	vm_fault_t ret = VM_FAULT_SIGBUS;
3993e69ad08SPeter Xu 	bool must_wait;
4002f064a59SPeter Zijlstra 	unsigned int blocking_state;
40186039bd3SAndrea Arcangeli 
40264c2b203SAndrea Arcangeli 	/*
40364c2b203SAndrea Arcangeli 	 * We don't do userfault handling for the final child pid update.
40464c2b203SAndrea Arcangeli 	 *
40564c2b203SAndrea Arcangeli 	 * We also don't do userfault handling during
40664c2b203SAndrea Arcangeli 	 * coredumping. hugetlbfs has the special
40764c2b203SAndrea Arcangeli 	 * follow_hugetlb_page() to skip missing pages in the
40864c2b203SAndrea Arcangeli 	 * FOLL_DUMP case, anon memory also checks for FOLL_DUMP with
40964c2b203SAndrea Arcangeli 	 * the no_page_table() helper in follow_page_mask(), but the
41064c2b203SAndrea Arcangeli 	 * shmem_vm_ops->fault method is invoked even during
411c1e8d7c6SMichel Lespinasse 	 * coredumping without mmap_lock and it ends up here.
41264c2b203SAndrea Arcangeli 	 */
41364c2b203SAndrea Arcangeli 	if (current->flags & (PF_EXITING|PF_DUMPCORE))
41464c2b203SAndrea Arcangeli 		goto out;
41564c2b203SAndrea Arcangeli 
41664c2b203SAndrea Arcangeli 	/*
417c1e8d7c6SMichel Lespinasse 	 * Coredumping runs without mmap_lock so we can only check that
418c1e8d7c6SMichel Lespinasse 	 * the mmap_lock is held, if PF_DUMPCORE was not set.
41964c2b203SAndrea Arcangeli 	 */
42042fc5414SMichel Lespinasse 	mmap_assert_locked(mm);
42164c2b203SAndrea Arcangeli 
422*b8da2e46SPeter Xu 	ctx = vma->vm_userfaultfd_ctx.ctx;
42386039bd3SAndrea Arcangeli 	if (!ctx)
424ba85c702SAndrea Arcangeli 		goto out;
42586039bd3SAndrea Arcangeli 
42686039bd3SAndrea Arcangeli 	BUG_ON(ctx->mm != mm);
42786039bd3SAndrea Arcangeli 
4287677f7fdSAxel Rasmussen 	/* Any unrecognized flag is a bug. */
4297677f7fdSAxel Rasmussen 	VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);
4307677f7fdSAxel Rasmussen 	/* 0 or > 1 flags set is a bug; we expect exactly 1. */
4317677f7fdSAxel Rasmussen 	VM_BUG_ON(!reason || (reason & (reason - 1)));
43286039bd3SAndrea Arcangeli 
4332d6d6f5aSPrakash Sangappa 	if (ctx->features & UFFD_FEATURE_SIGBUS)
4342d6d6f5aSPrakash Sangappa 		goto out;
4352d5de004SAxel Rasmussen 	if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))
43637cd0575SLokesh Gidra 		goto out;
4372d6d6f5aSPrakash Sangappa 
43886039bd3SAndrea Arcangeli 	/*
43986039bd3SAndrea Arcangeli 	 * If it's already released don't get it. This avoids to loop
44086039bd3SAndrea Arcangeli 	 * in __get_user_pages if userfaultfd_release waits on the
441c1e8d7c6SMichel Lespinasse 	 * caller of handle_userfault to release the mmap_lock.
44286039bd3SAndrea Arcangeli 	 */
4436aa7de05SMark Rutland 	if (unlikely(READ_ONCE(ctx->released))) {
444656710a6SAndrea Arcangeli 		/*
445656710a6SAndrea Arcangeli 		 * Don't return VM_FAULT_SIGBUS in this case, so a non
446656710a6SAndrea Arcangeli 		 * cooperative manager can close the uffd after the
447656710a6SAndrea Arcangeli 		 * last UFFDIO_COPY, without risking to trigger an
448656710a6SAndrea Arcangeli 		 * involuntary SIGBUS if the process was starting the
449656710a6SAndrea Arcangeli 		 * userfaultfd while the userfaultfd was still armed
450656710a6SAndrea Arcangeli 		 * (but after the last UFFDIO_COPY). If the uffd
451656710a6SAndrea Arcangeli 		 * wasn't already closed when the userfault reached
452656710a6SAndrea Arcangeli 		 * this point, that would normally be solved by
453656710a6SAndrea Arcangeli 		 * userfaultfd_must_wait returning 'false'.
454656710a6SAndrea Arcangeli 		 *
455656710a6SAndrea Arcangeli 		 * If we were to return VM_FAULT_SIGBUS here, the non
456656710a6SAndrea Arcangeli 		 * cooperative manager would be instead forced to
457656710a6SAndrea Arcangeli 		 * always call UFFDIO_UNREGISTER before it can safely
458656710a6SAndrea Arcangeli 		 * close the uffd.
459656710a6SAndrea Arcangeli 		 */
460656710a6SAndrea Arcangeli 		ret = VM_FAULT_NOPAGE;
461ba85c702SAndrea Arcangeli 		goto out;
462656710a6SAndrea Arcangeli 	}
46386039bd3SAndrea Arcangeli 
46486039bd3SAndrea Arcangeli 	/*
46586039bd3SAndrea Arcangeli 	 * Check that we can return VM_FAULT_RETRY.
46686039bd3SAndrea Arcangeli 	 *
46786039bd3SAndrea Arcangeli 	 * NOTE: it should become possible to return VM_FAULT_RETRY
46886039bd3SAndrea Arcangeli 	 * even if FAULT_FLAG_TRIED is set without leading to gup()
46986039bd3SAndrea Arcangeli 	 * -EBUSY failures, if the userfaultfd is to be extended for
47086039bd3SAndrea Arcangeli 	 * VM_UFFD_WP tracking and we intend to arm the userfault
47186039bd3SAndrea Arcangeli 	 * without first stopping userland access to the memory. For
47286039bd3SAndrea Arcangeli 	 * VM_UFFD_MISSING userfaults this is enough for now.
47386039bd3SAndrea Arcangeli 	 */
47482b0f8c3SJan Kara 	if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {
47586039bd3SAndrea Arcangeli 		/*
47686039bd3SAndrea Arcangeli 		 * Validate the invariant that nowait must allow retry
47786039bd3SAndrea Arcangeli 		 * to be sure not to return SIGBUS erroneously on
47886039bd3SAndrea Arcangeli 		 * nowait invocations.
47986039bd3SAndrea Arcangeli 		 */
48082b0f8c3SJan Kara 		BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);
48186039bd3SAndrea Arcangeli #ifdef CONFIG_DEBUG_VM
48286039bd3SAndrea Arcangeli 		if (printk_ratelimit()) {
48386039bd3SAndrea Arcangeli 			printk(KERN_WARNING
48482b0f8c3SJan Kara 			       "FAULT_FLAG_ALLOW_RETRY missing %x\n",
48582b0f8c3SJan Kara 			       vmf->flags);
48686039bd3SAndrea Arcangeli 			dump_stack();
48786039bd3SAndrea Arcangeli 		}
48886039bd3SAndrea Arcangeli #endif
489ba85c702SAndrea Arcangeli 		goto out;
49086039bd3SAndrea Arcangeli 	}
49186039bd3SAndrea Arcangeli 
49286039bd3SAndrea Arcangeli 	/*
49386039bd3SAndrea Arcangeli 	 * Handle nowait, not much to do other than tell it to retry
49486039bd3SAndrea Arcangeli 	 * and wait.
49586039bd3SAndrea Arcangeli 	 */
496ba85c702SAndrea Arcangeli 	ret = VM_FAULT_RETRY;
49782b0f8c3SJan Kara 	if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)
498ba85c702SAndrea Arcangeli 		goto out;
49986039bd3SAndrea Arcangeli 
500c1e8d7c6SMichel Lespinasse 	/* take the reference before dropping the mmap_lock */
50186039bd3SAndrea Arcangeli 	userfaultfd_ctx_get(ctx);
50286039bd3SAndrea Arcangeli 
50386039bd3SAndrea Arcangeli 	init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);
50486039bd3SAndrea Arcangeli 	uwq.wq.private = current;
505d172b1a3SNadav Amit 	uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,
506d172b1a3SNadav Amit 				reason, ctx->features);
50786039bd3SAndrea Arcangeli 	uwq.ctx = ctx;
50815a77c6fSAndrea Arcangeli 	uwq.waken = false;
50986039bd3SAndrea Arcangeli 
5103e69ad08SPeter Xu 	blocking_state = userfaultfd_get_blocking_state(vmf->flags);
511dfa37dc3SAndrea Arcangeli 
512*b8da2e46SPeter Xu         /*
513*b8da2e46SPeter Xu          * Take the vma lock now, in order to safely call
514*b8da2e46SPeter Xu          * userfaultfd_huge_must_wait() later. Since acquiring the
515*b8da2e46SPeter Xu          * (sleepable) vma lock can modify the current task state, that
516*b8da2e46SPeter Xu          * must be before explicitly calling set_current_state().
517*b8da2e46SPeter Xu          */
518*b8da2e46SPeter Xu 	if (is_vm_hugetlb_page(vma))
519*b8da2e46SPeter Xu 		hugetlb_vma_lock_read(vma);
520*b8da2e46SPeter Xu 
521cbcfa130SEric Biggers 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
52286039bd3SAndrea Arcangeli 	/*
52386039bd3SAndrea Arcangeli 	 * After the __add_wait_queue the uwq is visible to userland
52486039bd3SAndrea Arcangeli 	 * through poll/read().
52586039bd3SAndrea Arcangeli 	 */
52615b726efSAndrea Arcangeli 	__add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);
52715b726efSAndrea Arcangeli 	/*
52815b726efSAndrea Arcangeli 	 * The smp_mb() after __set_current_state prevents the reads
52915b726efSAndrea Arcangeli 	 * following the spin_unlock to happen before the list_add in
53015b726efSAndrea Arcangeli 	 * __add_wait_queue.
53115b726efSAndrea Arcangeli 	 */
53215a77c6fSAndrea Arcangeli 	set_current_state(blocking_state);
533cbcfa130SEric Biggers 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
53486039bd3SAndrea Arcangeli 
535*b8da2e46SPeter Xu 	if (!is_vm_hugetlb_page(vma))
53682b0f8c3SJan Kara 		must_wait = userfaultfd_must_wait(ctx, vmf->address, vmf->flags,
53782b0f8c3SJan Kara 						  reason);
538369cd212SMike Kravetz 	else
539*b8da2e46SPeter Xu 		must_wait = userfaultfd_huge_must_wait(ctx, vma,
5407868a208SPunit Agrawal 						       vmf->address,
541369cd212SMike Kravetz 						       vmf->flags, reason);
542*b8da2e46SPeter Xu 	if (is_vm_hugetlb_page(vma))
543*b8da2e46SPeter Xu 		hugetlb_vma_unlock_read(vma);
544d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
5458d2afd96SAndrea Arcangeli 
546f9bf3522SLinus Torvalds 	if (likely(must_wait && !READ_ONCE(ctx->released))) {
547a9a08845SLinus Torvalds 		wake_up_poll(&ctx->fd_wqh, EPOLLIN);
54886039bd3SAndrea Arcangeli 		schedule();
54986039bd3SAndrea Arcangeli 	}
550ba85c702SAndrea Arcangeli 
55186039bd3SAndrea Arcangeli 	__set_current_state(TASK_RUNNING);
55215b726efSAndrea Arcangeli 
55315b726efSAndrea Arcangeli 	/*
55415b726efSAndrea Arcangeli 	 * Here we race with the list_del; list_add in
55515b726efSAndrea Arcangeli 	 * userfaultfd_ctx_read(), however because we don't ever run
55615b726efSAndrea Arcangeli 	 * list_del_init() to refile across the two lists, the prev
55715b726efSAndrea Arcangeli 	 * and next pointers will never point to self. list_add also
55815b726efSAndrea Arcangeli 	 * would never let any of the two pointers to point to
55915b726efSAndrea Arcangeli 	 * self. So list_empty_careful won't risk to see both pointers
56015b726efSAndrea Arcangeli 	 * pointing to self at any time during the list refile. The
56115b726efSAndrea Arcangeli 	 * only case where list_del_init() is called is the full
56215b726efSAndrea Arcangeli 	 * removal in the wake function and there we don't re-list_add
56315b726efSAndrea Arcangeli 	 * and it's fine not to block on the spinlock. The uwq on this
56415b726efSAndrea Arcangeli 	 * kernel stack can be released after the list_del_init.
56515b726efSAndrea Arcangeli 	 */
5662055da97SIngo Molnar 	if (!list_empty_careful(&uwq.wq.entry)) {
567cbcfa130SEric Biggers 		spin_lock_irq(&ctx->fault_pending_wqh.lock);
56815b726efSAndrea Arcangeli 		/*
56915b726efSAndrea Arcangeli 		 * No need of list_del_init(), the uwq on the stack
57015b726efSAndrea Arcangeli 		 * will be freed shortly anyway.
57115b726efSAndrea Arcangeli 		 */
5722055da97SIngo Molnar 		list_del(&uwq.wq.entry);
573cbcfa130SEric Biggers 		spin_unlock_irq(&ctx->fault_pending_wqh.lock);
574ba85c702SAndrea Arcangeli 	}
57586039bd3SAndrea Arcangeli 
57686039bd3SAndrea Arcangeli 	/*
57786039bd3SAndrea Arcangeli 	 * ctx may go away after this if the userfault pseudo fd is
57886039bd3SAndrea Arcangeli 	 * already released.
57986039bd3SAndrea Arcangeli 	 */
58086039bd3SAndrea Arcangeli 	userfaultfd_ctx_put(ctx);
58186039bd3SAndrea Arcangeli 
582ba85c702SAndrea Arcangeli out:
583ba85c702SAndrea Arcangeli 	return ret;
58486039bd3SAndrea Arcangeli }
58586039bd3SAndrea Arcangeli 
5868c9e7bb7SAndrea Arcangeli static void userfaultfd_event_wait_completion(struct userfaultfd_ctx *ctx,
5879cd75c3cSPavel Emelyanov 					      struct userfaultfd_wait_queue *ewq)
5889cd75c3cSPavel Emelyanov {
5890cbb4b4fSAndrea Arcangeli 	struct userfaultfd_ctx *release_new_ctx;
5900cbb4b4fSAndrea Arcangeli 
5919a69a829SAndrea Arcangeli 	if (WARN_ON_ONCE(current->flags & PF_EXITING))
5929a69a829SAndrea Arcangeli 		goto out;
5939a69a829SAndrea Arcangeli 
5949cd75c3cSPavel Emelyanov 	ewq->ctx = ctx;
5959cd75c3cSPavel Emelyanov 	init_waitqueue_entry(&ewq->wq, current);
5960cbb4b4fSAndrea Arcangeli 	release_new_ctx = NULL;
5979cd75c3cSPavel Emelyanov 
598cbcfa130SEric Biggers 	spin_lock_irq(&ctx->event_wqh.lock);
5999cd75c3cSPavel Emelyanov 	/*
6009cd75c3cSPavel Emelyanov 	 * After the __add_wait_queue the uwq is visible to userland
6019cd75c3cSPavel Emelyanov 	 * through poll/read().
6029cd75c3cSPavel Emelyanov 	 */
6039cd75c3cSPavel Emelyanov 	__add_wait_queue(&ctx->event_wqh, &ewq->wq);
6049cd75c3cSPavel Emelyanov 	for (;;) {
6059cd75c3cSPavel Emelyanov 		set_current_state(TASK_KILLABLE);
6069cd75c3cSPavel Emelyanov 		if (ewq->msg.event == 0)
6079cd75c3cSPavel Emelyanov 			break;
6086aa7de05SMark Rutland 		if (READ_ONCE(ctx->released) ||
6099cd75c3cSPavel Emelyanov 		    fatal_signal_pending(current)) {
610384632e6SAndrea Arcangeli 			/*
611384632e6SAndrea Arcangeli 			 * &ewq->wq may be queued in fork_event, but
612384632e6SAndrea Arcangeli 			 * __remove_wait_queue ignores the head
613384632e6SAndrea Arcangeli 			 * parameter. It would be a problem if it
614384632e6SAndrea Arcangeli 			 * didn't.
615384632e6SAndrea Arcangeli 			 */
6169cd75c3cSPavel Emelyanov 			__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
6177eb76d45SMike Rapoport 			if (ewq->msg.event == UFFD_EVENT_FORK) {
6187eb76d45SMike Rapoport 				struct userfaultfd_ctx *new;
6197eb76d45SMike Rapoport 
6207eb76d45SMike Rapoport 				new = (struct userfaultfd_ctx *)
6217eb76d45SMike Rapoport 					(unsigned long)
6227eb76d45SMike Rapoport 					ewq->msg.arg.reserved.reserved1;
6230cbb4b4fSAndrea Arcangeli 				release_new_ctx = new;
6247eb76d45SMike Rapoport 			}
6259cd75c3cSPavel Emelyanov 			break;
6269cd75c3cSPavel Emelyanov 		}
6279cd75c3cSPavel Emelyanov 
628cbcfa130SEric Biggers 		spin_unlock_irq(&ctx->event_wqh.lock);
6299cd75c3cSPavel Emelyanov 
630a9a08845SLinus Torvalds 		wake_up_poll(&ctx->fd_wqh, EPOLLIN);
6319cd75c3cSPavel Emelyanov 		schedule();
6329cd75c3cSPavel Emelyanov 
633cbcfa130SEric Biggers 		spin_lock_irq(&ctx->event_wqh.lock);
6349cd75c3cSPavel Emelyanov 	}
6359cd75c3cSPavel Emelyanov 	__set_current_state(TASK_RUNNING);
636cbcfa130SEric Biggers 	spin_unlock_irq(&ctx->event_wqh.lock);
6379cd75c3cSPavel Emelyanov 
6380cbb4b4fSAndrea Arcangeli 	if (release_new_ctx) {
6390cbb4b4fSAndrea Arcangeli 		struct vm_area_struct *vma;
6400cbb4b4fSAndrea Arcangeli 		struct mm_struct *mm = release_new_ctx->mm;
64169dbe6daSLiam R. Howlett 		VMA_ITERATOR(vmi, mm, 0);
6420cbb4b4fSAndrea Arcangeli 
6430cbb4b4fSAndrea Arcangeli 		/* the various vma->vm_userfaultfd_ctx still points to it */
644d8ed45c5SMichel Lespinasse 		mmap_write_lock(mm);
64569dbe6daSLiam R. Howlett 		for_each_vma(vmi, vma) {
64631e810aaSMike Rapoport 			if (vma->vm_userfaultfd_ctx.ctx == release_new_ctx) {
6470cbb4b4fSAndrea Arcangeli 				vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
64851d3d5ebSDavid Hildenbrand 				userfaultfd_set_vm_flags(vma,
64951d3d5ebSDavid Hildenbrand 							 vma->vm_flags & ~__VM_UFFD_FLAGS);
65031e810aaSMike Rapoport 			}
65169dbe6daSLiam R. Howlett 		}
652d8ed45c5SMichel Lespinasse 		mmap_write_unlock(mm);
6530cbb4b4fSAndrea Arcangeli 
6540cbb4b4fSAndrea Arcangeli 		userfaultfd_ctx_put(release_new_ctx);
6550cbb4b4fSAndrea Arcangeli 	}
6560cbb4b4fSAndrea Arcangeli 
6579cd75c3cSPavel Emelyanov 	/*
6589cd75c3cSPavel Emelyanov 	 * ctx may go away after this if the userfault pseudo fd is
6599cd75c3cSPavel Emelyanov 	 * already released.
6609cd75c3cSPavel Emelyanov 	 */
6619a69a829SAndrea Arcangeli out:
662a759a909SNadav Amit 	atomic_dec(&ctx->mmap_changing);
663a759a909SNadav Amit 	VM_BUG_ON(atomic_read(&ctx->mmap_changing) < 0);
6649cd75c3cSPavel Emelyanov 	userfaultfd_ctx_put(ctx);
6659cd75c3cSPavel Emelyanov }
6669cd75c3cSPavel Emelyanov 
6679cd75c3cSPavel Emelyanov static void userfaultfd_event_complete(struct userfaultfd_ctx *ctx,
6689cd75c3cSPavel Emelyanov 				       struct userfaultfd_wait_queue *ewq)
6699cd75c3cSPavel Emelyanov {
6709cd75c3cSPavel Emelyanov 	ewq->msg.event = 0;
6719cd75c3cSPavel Emelyanov 	wake_up_locked(&ctx->event_wqh);
6729cd75c3cSPavel Emelyanov 	__remove_wait_queue(&ctx->event_wqh, &ewq->wq);
6739cd75c3cSPavel Emelyanov }
6749cd75c3cSPavel Emelyanov 
675893e26e6SPavel Emelyanov int dup_userfaultfd(struct vm_area_struct *vma, struct list_head *fcs)
676893e26e6SPavel Emelyanov {
677893e26e6SPavel Emelyanov 	struct userfaultfd_ctx *ctx = NULL, *octx;
678893e26e6SPavel Emelyanov 	struct userfaultfd_fork_ctx *fctx;
679893e26e6SPavel Emelyanov 
680893e26e6SPavel Emelyanov 	octx = vma->vm_userfaultfd_ctx.ctx;
681893e26e6SPavel Emelyanov 	if (!octx || !(octx->features & UFFD_FEATURE_EVENT_FORK)) {
682893e26e6SPavel Emelyanov 		vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
68351d3d5ebSDavid Hildenbrand 		userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
684893e26e6SPavel Emelyanov 		return 0;
685893e26e6SPavel Emelyanov 	}
686893e26e6SPavel Emelyanov 
687893e26e6SPavel Emelyanov 	list_for_each_entry(fctx, fcs, list)
688893e26e6SPavel Emelyanov 		if (fctx->orig == octx) {
689893e26e6SPavel Emelyanov 			ctx = fctx->new;
690893e26e6SPavel Emelyanov 			break;
691893e26e6SPavel Emelyanov 		}
692893e26e6SPavel Emelyanov 
693893e26e6SPavel Emelyanov 	if (!ctx) {
694893e26e6SPavel Emelyanov 		fctx = kmalloc(sizeof(*fctx), GFP_KERNEL);
695893e26e6SPavel Emelyanov 		if (!fctx)
696893e26e6SPavel Emelyanov 			return -ENOMEM;
697893e26e6SPavel Emelyanov 
698893e26e6SPavel Emelyanov 		ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
699893e26e6SPavel Emelyanov 		if (!ctx) {
700893e26e6SPavel Emelyanov 			kfree(fctx);
701893e26e6SPavel Emelyanov 			return -ENOMEM;
702893e26e6SPavel Emelyanov 		}
703893e26e6SPavel Emelyanov 
704ca880420SEric Biggers 		refcount_set(&ctx->refcount, 1);
705893e26e6SPavel Emelyanov 		ctx->flags = octx->flags;
706893e26e6SPavel Emelyanov 		ctx->features = octx->features;
707893e26e6SPavel Emelyanov 		ctx->released = false;
708a759a909SNadav Amit 		atomic_set(&ctx->mmap_changing, 0);
709893e26e6SPavel Emelyanov 		ctx->mm = vma->vm_mm;
71000bb31faSMike Rapoport 		mmgrab(ctx->mm);
711893e26e6SPavel Emelyanov 
712893e26e6SPavel Emelyanov 		userfaultfd_ctx_get(octx);
713a759a909SNadav Amit 		atomic_inc(&octx->mmap_changing);
714893e26e6SPavel Emelyanov 		fctx->orig = octx;
715893e26e6SPavel Emelyanov 		fctx->new = ctx;
716893e26e6SPavel Emelyanov 		list_add_tail(&fctx->list, fcs);
717893e26e6SPavel Emelyanov 	}
718893e26e6SPavel Emelyanov 
719893e26e6SPavel Emelyanov 	vma->vm_userfaultfd_ctx.ctx = ctx;
720893e26e6SPavel Emelyanov 	return 0;
721893e26e6SPavel Emelyanov }
722893e26e6SPavel Emelyanov 
7238c9e7bb7SAndrea Arcangeli static void dup_fctx(struct userfaultfd_fork_ctx *fctx)
724893e26e6SPavel Emelyanov {
725893e26e6SPavel Emelyanov 	struct userfaultfd_ctx *ctx = fctx->orig;
726893e26e6SPavel Emelyanov 	struct userfaultfd_wait_queue ewq;
727893e26e6SPavel Emelyanov 
728893e26e6SPavel Emelyanov 	msg_init(&ewq.msg);
729893e26e6SPavel Emelyanov 
730893e26e6SPavel Emelyanov 	ewq.msg.event = UFFD_EVENT_FORK;
731893e26e6SPavel Emelyanov 	ewq.msg.arg.reserved.reserved1 = (unsigned long)fctx->new;
732893e26e6SPavel Emelyanov 
7338c9e7bb7SAndrea Arcangeli 	userfaultfd_event_wait_completion(ctx, &ewq);
734893e26e6SPavel Emelyanov }
735893e26e6SPavel Emelyanov 
736893e26e6SPavel Emelyanov void dup_userfaultfd_complete(struct list_head *fcs)
737893e26e6SPavel Emelyanov {
738893e26e6SPavel Emelyanov 	struct userfaultfd_fork_ctx *fctx, *n;
739893e26e6SPavel Emelyanov 
740893e26e6SPavel Emelyanov 	list_for_each_entry_safe(fctx, n, fcs, list) {
7418c9e7bb7SAndrea Arcangeli 		dup_fctx(fctx);
742893e26e6SPavel Emelyanov 		list_del(&fctx->list);
743893e26e6SPavel Emelyanov 		kfree(fctx);
744893e26e6SPavel Emelyanov 	}
745893e26e6SPavel Emelyanov }
746893e26e6SPavel Emelyanov 
74772f87654SPavel Emelyanov void mremap_userfaultfd_prep(struct vm_area_struct *vma,
74872f87654SPavel Emelyanov 			     struct vm_userfaultfd_ctx *vm_ctx)
74972f87654SPavel Emelyanov {
75072f87654SPavel Emelyanov 	struct userfaultfd_ctx *ctx;
75172f87654SPavel Emelyanov 
75272f87654SPavel Emelyanov 	ctx = vma->vm_userfaultfd_ctx.ctx;
7533cfd22beSPeter Xu 
7543cfd22beSPeter Xu 	if (!ctx)
7553cfd22beSPeter Xu 		return;
7563cfd22beSPeter Xu 
7573cfd22beSPeter Xu 	if (ctx->features & UFFD_FEATURE_EVENT_REMAP) {
75872f87654SPavel Emelyanov 		vm_ctx->ctx = ctx;
75972f87654SPavel Emelyanov 		userfaultfd_ctx_get(ctx);
760a759a909SNadav Amit 		atomic_inc(&ctx->mmap_changing);
7613cfd22beSPeter Xu 	} else {
7623cfd22beSPeter Xu 		/* Drop uffd context if remap feature not enabled */
7633cfd22beSPeter Xu 		vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
76451d3d5ebSDavid Hildenbrand 		userfaultfd_set_vm_flags(vma, vma->vm_flags & ~__VM_UFFD_FLAGS);
76572f87654SPavel Emelyanov 	}
76672f87654SPavel Emelyanov }
76772f87654SPavel Emelyanov 
76890794bf1SAndrea Arcangeli void mremap_userfaultfd_complete(struct vm_userfaultfd_ctx *vm_ctx,
76972f87654SPavel Emelyanov 				 unsigned long from, unsigned long to,
77072f87654SPavel Emelyanov 				 unsigned long len)
77172f87654SPavel Emelyanov {
77290794bf1SAndrea Arcangeli 	struct userfaultfd_ctx *ctx = vm_ctx->ctx;
77372f87654SPavel Emelyanov 	struct userfaultfd_wait_queue ewq;
77472f87654SPavel Emelyanov 
77572f87654SPavel Emelyanov 	if (!ctx)
77672f87654SPavel Emelyanov 		return;
77772f87654SPavel Emelyanov 
77872f87654SPavel Emelyanov 	if (to & ~PAGE_MASK) {
77972f87654SPavel Emelyanov 		userfaultfd_ctx_put(ctx);
78072f87654SPavel Emelyanov 		return;
78172f87654SPavel Emelyanov 	}
78272f87654SPavel Emelyanov 
78372f87654SPavel Emelyanov 	msg_init(&ewq.msg);
78472f87654SPavel Emelyanov 
78572f87654SPavel Emelyanov 	ewq.msg.event = UFFD_EVENT_REMAP;
78672f87654SPavel Emelyanov 	ewq.msg.arg.remap.from = from;
78772f87654SPavel Emelyanov 	ewq.msg.arg.remap.to = to;
78872f87654SPavel Emelyanov 	ewq.msg.arg.remap.len = len;
78972f87654SPavel Emelyanov 
79072f87654SPavel Emelyanov 	userfaultfd_event_wait_completion(ctx, &ewq);
79172f87654SPavel Emelyanov }
79272f87654SPavel Emelyanov 
79370ccb92fSAndrea Arcangeli bool userfaultfd_remove(struct vm_area_struct *vma,
79405ce7724SPavel Emelyanov 			unsigned long start, unsigned long end)
79505ce7724SPavel Emelyanov {
79605ce7724SPavel Emelyanov 	struct mm_struct *mm = vma->vm_mm;
79705ce7724SPavel Emelyanov 	struct userfaultfd_ctx *ctx;
79805ce7724SPavel Emelyanov 	struct userfaultfd_wait_queue ewq;
79905ce7724SPavel Emelyanov 
80005ce7724SPavel Emelyanov 	ctx = vma->vm_userfaultfd_ctx.ctx;
801d811914dSMike Rapoport 	if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_REMOVE))
80270ccb92fSAndrea Arcangeli 		return true;
80305ce7724SPavel Emelyanov 
80405ce7724SPavel Emelyanov 	userfaultfd_ctx_get(ctx);
805a759a909SNadav Amit 	atomic_inc(&ctx->mmap_changing);
806d8ed45c5SMichel Lespinasse 	mmap_read_unlock(mm);
80705ce7724SPavel Emelyanov 
80805ce7724SPavel Emelyanov 	msg_init(&ewq.msg);
80905ce7724SPavel Emelyanov 
810d811914dSMike Rapoport 	ewq.msg.event = UFFD_EVENT_REMOVE;
811d811914dSMike Rapoport 	ewq.msg.arg.remove.start = start;
812d811914dSMike Rapoport 	ewq.msg.arg.remove.end = end;
81305ce7724SPavel Emelyanov 
81405ce7724SPavel Emelyanov 	userfaultfd_event_wait_completion(ctx, &ewq);
81505ce7724SPavel Emelyanov 
81670ccb92fSAndrea Arcangeli 	return false;
81705ce7724SPavel Emelyanov }
81805ce7724SPavel Emelyanov 
819897ab3e0SMike Rapoport static bool has_unmap_ctx(struct userfaultfd_ctx *ctx, struct list_head *unmaps,
820897ab3e0SMike Rapoport 			  unsigned long start, unsigned long end)
821897ab3e0SMike Rapoport {
822897ab3e0SMike Rapoport 	struct userfaultfd_unmap_ctx *unmap_ctx;
823897ab3e0SMike Rapoport 
824897ab3e0SMike Rapoport 	list_for_each_entry(unmap_ctx, unmaps, list)
825897ab3e0SMike Rapoport 		if (unmap_ctx->ctx == ctx && unmap_ctx->start == start &&
826897ab3e0SMike Rapoport 		    unmap_ctx->end == end)
827897ab3e0SMike Rapoport 			return true;
828897ab3e0SMike Rapoport 
829897ab3e0SMike Rapoport 	return false;
830897ab3e0SMike Rapoport }
831897ab3e0SMike Rapoport 
83269dbe6daSLiam R. Howlett int userfaultfd_unmap_prep(struct mm_struct *mm, unsigned long start,
83369dbe6daSLiam R. Howlett 			   unsigned long end, struct list_head *unmaps)
834897ab3e0SMike Rapoport {
83569dbe6daSLiam R. Howlett 	VMA_ITERATOR(vmi, mm, start);
83669dbe6daSLiam R. Howlett 	struct vm_area_struct *vma;
83769dbe6daSLiam R. Howlett 
83869dbe6daSLiam R. Howlett 	for_each_vma_range(vmi, vma, end) {
839897ab3e0SMike Rapoport 		struct userfaultfd_unmap_ctx *unmap_ctx;
840897ab3e0SMike Rapoport 		struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx;
841897ab3e0SMike Rapoport 
842897ab3e0SMike Rapoport 		if (!ctx || !(ctx->features & UFFD_FEATURE_EVENT_UNMAP) ||
843897ab3e0SMike Rapoport 		    has_unmap_ctx(ctx, unmaps, start, end))
844897ab3e0SMike Rapoport 			continue;
845897ab3e0SMike Rapoport 
846897ab3e0SMike Rapoport 		unmap_ctx = kzalloc(sizeof(*unmap_ctx), GFP_KERNEL);
847897ab3e0SMike Rapoport 		if (!unmap_ctx)
848897ab3e0SMike Rapoport 			return -ENOMEM;
849897ab3e0SMike Rapoport 
850897ab3e0SMike Rapoport 		userfaultfd_ctx_get(ctx);
851a759a909SNadav Amit 		atomic_inc(&ctx->mmap_changing);
852897ab3e0SMike Rapoport 		unmap_ctx->ctx = ctx;
853897ab3e0SMike Rapoport 		unmap_ctx->start = start;
854897ab3e0SMike Rapoport 		unmap_ctx->end = end;
855897ab3e0SMike Rapoport 		list_add_tail(&unmap_ctx->list, unmaps);
856897ab3e0SMike Rapoport 	}
857897ab3e0SMike Rapoport 
858897ab3e0SMike Rapoport 	return 0;
859897ab3e0SMike Rapoport }
860897ab3e0SMike Rapoport 
861897ab3e0SMike Rapoport void userfaultfd_unmap_complete(struct mm_struct *mm, struct list_head *uf)
862897ab3e0SMike Rapoport {
863897ab3e0SMike Rapoport 	struct userfaultfd_unmap_ctx *ctx, *n;
864897ab3e0SMike Rapoport 	struct userfaultfd_wait_queue ewq;
865897ab3e0SMike Rapoport 
866897ab3e0SMike Rapoport 	list_for_each_entry_safe(ctx, n, uf, list) {
867897ab3e0SMike Rapoport 		msg_init(&ewq.msg);
868897ab3e0SMike Rapoport 
869897ab3e0SMike Rapoport 		ewq.msg.event = UFFD_EVENT_UNMAP;
870897ab3e0SMike Rapoport 		ewq.msg.arg.remove.start = ctx->start;
871897ab3e0SMike Rapoport 		ewq.msg.arg.remove.end = ctx->end;
872897ab3e0SMike Rapoport 
873897ab3e0SMike Rapoport 		userfaultfd_event_wait_completion(ctx->ctx, &ewq);
874897ab3e0SMike Rapoport 
875897ab3e0SMike Rapoport 		list_del(&ctx->list);
876897ab3e0SMike Rapoport 		kfree(ctx);
877897ab3e0SMike Rapoport 	}
878897ab3e0SMike Rapoport }
879897ab3e0SMike Rapoport 
88086039bd3SAndrea Arcangeli static int userfaultfd_release(struct inode *inode, struct file *file)
88186039bd3SAndrea Arcangeli {
88286039bd3SAndrea Arcangeli 	struct userfaultfd_ctx *ctx = file->private_data;
88386039bd3SAndrea Arcangeli 	struct mm_struct *mm = ctx->mm;
88486039bd3SAndrea Arcangeli 	struct vm_area_struct *vma, *prev;
88586039bd3SAndrea Arcangeli 	/* len == 0 means wake all */
88686039bd3SAndrea Arcangeli 	struct userfaultfd_wake_range range = { .len = 0, };
88786039bd3SAndrea Arcangeli 	unsigned long new_flags;
88869dbe6daSLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
88986039bd3SAndrea Arcangeli 
8906aa7de05SMark Rutland 	WRITE_ONCE(ctx->released, true);
89186039bd3SAndrea Arcangeli 
892d2005e3fSOleg Nesterov 	if (!mmget_not_zero(mm))
893d2005e3fSOleg Nesterov 		goto wakeup;
894d2005e3fSOleg Nesterov 
89586039bd3SAndrea Arcangeli 	/*
89686039bd3SAndrea Arcangeli 	 * Flush page faults out of all CPUs. NOTE: all page faults
89786039bd3SAndrea Arcangeli 	 * must be retried without returning VM_FAULT_SIGBUS if
89886039bd3SAndrea Arcangeli 	 * userfaultfd_ctx_get() succeeds but vma->vma_userfault_ctx
899c1e8d7c6SMichel Lespinasse 	 * changes while handle_userfault released the mmap_lock. So
90086039bd3SAndrea Arcangeli 	 * it's critical that released is set to true (above), before
901c1e8d7c6SMichel Lespinasse 	 * taking the mmap_lock for writing.
90286039bd3SAndrea Arcangeli 	 */
903d8ed45c5SMichel Lespinasse 	mmap_write_lock(mm);
90486039bd3SAndrea Arcangeli 	prev = NULL;
90569dbe6daSLiam R. Howlett 	mas_for_each(&mas, vma, ULONG_MAX) {
90686039bd3SAndrea Arcangeli 		cond_resched();
90786039bd3SAndrea Arcangeli 		BUG_ON(!!vma->vm_userfaultfd_ctx.ctx ^
9087677f7fdSAxel Rasmussen 		       !!(vma->vm_flags & __VM_UFFD_FLAGS));
90986039bd3SAndrea Arcangeli 		if (vma->vm_userfaultfd_ctx.ctx != ctx) {
91086039bd3SAndrea Arcangeli 			prev = vma;
91186039bd3SAndrea Arcangeli 			continue;
91286039bd3SAndrea Arcangeli 		}
9137677f7fdSAxel Rasmussen 		new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
91486039bd3SAndrea Arcangeli 		prev = vma_merge(mm, prev, vma->vm_start, vma->vm_end,
91586039bd3SAndrea Arcangeli 				 new_flags, vma->anon_vma,
91686039bd3SAndrea Arcangeli 				 vma->vm_file, vma->vm_pgoff,
91786039bd3SAndrea Arcangeli 				 vma_policy(vma),
9185c26f6acSSuren Baghdasaryan 				 NULL_VM_UFFD_CTX, anon_vma_name(vma));
91969dbe6daSLiam R. Howlett 		if (prev) {
92069dbe6daSLiam R. Howlett 			mas_pause(&mas);
92186039bd3SAndrea Arcangeli 			vma = prev;
92269dbe6daSLiam R. Howlett 		} else {
92386039bd3SAndrea Arcangeli 			prev = vma;
92469dbe6daSLiam R. Howlett 		}
92569dbe6daSLiam R. Howlett 
92651d3d5ebSDavid Hildenbrand 		userfaultfd_set_vm_flags(vma, new_flags);
92786039bd3SAndrea Arcangeli 		vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
92886039bd3SAndrea Arcangeli 	}
929d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
930d2005e3fSOleg Nesterov 	mmput(mm);
931d2005e3fSOleg Nesterov wakeup:
93286039bd3SAndrea Arcangeli 	/*
93315b726efSAndrea Arcangeli 	 * After no new page faults can wait on this fault_*wqh, flush
93486039bd3SAndrea Arcangeli 	 * the last page faults that may have been already waiting on
93515b726efSAndrea Arcangeli 	 * the fault_*wqh.
93686039bd3SAndrea Arcangeli 	 */
937cbcfa130SEric Biggers 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
938ac5be6b4SAndrea Arcangeli 	__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL, &range);
939c430d1e8SMatthew Wilcox 	__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, &range);
940cbcfa130SEric Biggers 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
94186039bd3SAndrea Arcangeli 
9425a18b64eSMike Rapoport 	/* Flush pending events that may still wait on event_wqh */
9435a18b64eSMike Rapoport 	wake_up_all(&ctx->event_wqh);
9445a18b64eSMike Rapoport 
945a9a08845SLinus Torvalds 	wake_up_poll(&ctx->fd_wqh, EPOLLHUP);
94686039bd3SAndrea Arcangeli 	userfaultfd_ctx_put(ctx);
94786039bd3SAndrea Arcangeli 	return 0;
94886039bd3SAndrea Arcangeli }
94986039bd3SAndrea Arcangeli 
95015b726efSAndrea Arcangeli /* fault_pending_wqh.lock must be hold by the caller */
9516dcc27fdSPavel Emelyanov static inline struct userfaultfd_wait_queue *find_userfault_in(
9526dcc27fdSPavel Emelyanov 		wait_queue_head_t *wqh)
95386039bd3SAndrea Arcangeli {
954ac6424b9SIngo Molnar 	wait_queue_entry_t *wq;
95515b726efSAndrea Arcangeli 	struct userfaultfd_wait_queue *uwq;
95686039bd3SAndrea Arcangeli 
957456a7378SLance Roy 	lockdep_assert_held(&wqh->lock);
95886039bd3SAndrea Arcangeli 
95915b726efSAndrea Arcangeli 	uwq = NULL;
9606dcc27fdSPavel Emelyanov 	if (!waitqueue_active(wqh))
96115b726efSAndrea Arcangeli 		goto out;
96215b726efSAndrea Arcangeli 	/* walk in reverse to provide FIFO behavior to read userfaults */
9632055da97SIngo Molnar 	wq = list_last_entry(&wqh->head, typeof(*wq), entry);
96415b726efSAndrea Arcangeli 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);
96515b726efSAndrea Arcangeli out:
96615b726efSAndrea Arcangeli 	return uwq;
96786039bd3SAndrea Arcangeli }
96886039bd3SAndrea Arcangeli 
9696dcc27fdSPavel Emelyanov static inline struct userfaultfd_wait_queue *find_userfault(
9706dcc27fdSPavel Emelyanov 		struct userfaultfd_ctx *ctx)
9716dcc27fdSPavel Emelyanov {
9726dcc27fdSPavel Emelyanov 	return find_userfault_in(&ctx->fault_pending_wqh);
9736dcc27fdSPavel Emelyanov }
9746dcc27fdSPavel Emelyanov 
9759cd75c3cSPavel Emelyanov static inline struct userfaultfd_wait_queue *find_userfault_evt(
9769cd75c3cSPavel Emelyanov 		struct userfaultfd_ctx *ctx)
9779cd75c3cSPavel Emelyanov {
9789cd75c3cSPavel Emelyanov 	return find_userfault_in(&ctx->event_wqh);
9799cd75c3cSPavel Emelyanov }
9809cd75c3cSPavel Emelyanov 
981076ccb76SAl Viro static __poll_t userfaultfd_poll(struct file *file, poll_table *wait)
98286039bd3SAndrea Arcangeli {
98386039bd3SAndrea Arcangeli 	struct userfaultfd_ctx *ctx = file->private_data;
984076ccb76SAl Viro 	__poll_t ret;
98586039bd3SAndrea Arcangeli 
98686039bd3SAndrea Arcangeli 	poll_wait(file, &ctx->fd_wqh, wait);
98786039bd3SAndrea Arcangeli 
98822e5fe2aSNadav Amit 	if (!userfaultfd_is_initialized(ctx))
989a9a08845SLinus Torvalds 		return EPOLLERR;
99022e5fe2aSNadav Amit 
991ba85c702SAndrea Arcangeli 	/*
992ba85c702SAndrea Arcangeli 	 * poll() never guarantees that read won't block.
993ba85c702SAndrea Arcangeli 	 * userfaults can be waken before they're read().
994ba85c702SAndrea Arcangeli 	 */
995ba85c702SAndrea Arcangeli 	if (unlikely(!(file->f_flags & O_NONBLOCK)))
996a9a08845SLinus Torvalds 		return EPOLLERR;
99715b726efSAndrea Arcangeli 	/*
99815b726efSAndrea Arcangeli 	 * lockless access to see if there are pending faults
99915b726efSAndrea Arcangeli 	 * __pollwait last action is the add_wait_queue but
100015b726efSAndrea Arcangeli 	 * the spin_unlock would allow the waitqueue_active to
100115b726efSAndrea Arcangeli 	 * pass above the actual list_add inside
100215b726efSAndrea Arcangeli 	 * add_wait_queue critical section. So use a full
100315b726efSAndrea Arcangeli 	 * memory barrier to serialize the list_add write of
100415b726efSAndrea Arcangeli 	 * add_wait_queue() with the waitqueue_active read
100515b726efSAndrea Arcangeli 	 * below.
100615b726efSAndrea Arcangeli 	 */
100715b726efSAndrea Arcangeli 	ret = 0;
100815b726efSAndrea Arcangeli 	smp_mb();
100915b726efSAndrea Arcangeli 	if (waitqueue_active(&ctx->fault_pending_wqh))
1010a9a08845SLinus Torvalds 		ret = EPOLLIN;
10119cd75c3cSPavel Emelyanov 	else if (waitqueue_active(&ctx->event_wqh))
1012a9a08845SLinus Torvalds 		ret = EPOLLIN;
10139cd75c3cSPavel Emelyanov 
101486039bd3SAndrea Arcangeli 	return ret;
101586039bd3SAndrea Arcangeli }
101686039bd3SAndrea Arcangeli 
1017893e26e6SPavel Emelyanov static const struct file_operations userfaultfd_fops;
1018893e26e6SPavel Emelyanov 
1019b537900fSDaniel Colascione static int resolve_userfault_fork(struct userfaultfd_ctx *new,
1020b537900fSDaniel Colascione 				  struct inode *inode,
1021893e26e6SPavel Emelyanov 				  struct uffd_msg *msg)
1022893e26e6SPavel Emelyanov {
1023893e26e6SPavel Emelyanov 	int fd;
1024893e26e6SPavel Emelyanov 
1025b537900fSDaniel Colascione 	fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, new,
1026abec3d01SOndrej Mosnacek 			O_RDONLY | (new->flags & UFFD_SHARED_FCNTL_FLAGS), inode);
1027893e26e6SPavel Emelyanov 	if (fd < 0)
1028893e26e6SPavel Emelyanov 		return fd;
1029893e26e6SPavel Emelyanov 
1030893e26e6SPavel Emelyanov 	msg->arg.reserved.reserved1 = 0;
1031893e26e6SPavel Emelyanov 	msg->arg.fork.ufd = fd;
1032893e26e6SPavel Emelyanov 	return 0;
1033893e26e6SPavel Emelyanov }
1034893e26e6SPavel Emelyanov 
103586039bd3SAndrea Arcangeli static ssize_t userfaultfd_ctx_read(struct userfaultfd_ctx *ctx, int no_wait,
1036b537900fSDaniel Colascione 				    struct uffd_msg *msg, struct inode *inode)
103786039bd3SAndrea Arcangeli {
103886039bd3SAndrea Arcangeli 	ssize_t ret;
103986039bd3SAndrea Arcangeli 	DECLARE_WAITQUEUE(wait, current);
104015b726efSAndrea Arcangeli 	struct userfaultfd_wait_queue *uwq;
1041893e26e6SPavel Emelyanov 	/*
1042893e26e6SPavel Emelyanov 	 * Handling fork event requires sleeping operations, so
1043893e26e6SPavel Emelyanov 	 * we drop the event_wqh lock, then do these ops, then
1044893e26e6SPavel Emelyanov 	 * lock it back and wake up the waiter. While the lock is
1045893e26e6SPavel Emelyanov 	 * dropped the ewq may go away so we keep track of it
1046893e26e6SPavel Emelyanov 	 * carefully.
1047893e26e6SPavel Emelyanov 	 */
1048893e26e6SPavel Emelyanov 	LIST_HEAD(fork_event);
1049893e26e6SPavel Emelyanov 	struct userfaultfd_ctx *fork_nctx = NULL;
105086039bd3SAndrea Arcangeli 
105115b726efSAndrea Arcangeli 	/* always take the fd_wqh lock before the fault_pending_wqh lock */
1052ae62c16eSChristoph Hellwig 	spin_lock_irq(&ctx->fd_wqh.lock);
105386039bd3SAndrea Arcangeli 	__add_wait_queue(&ctx->fd_wqh, &wait);
105486039bd3SAndrea Arcangeli 	for (;;) {
105586039bd3SAndrea Arcangeli 		set_current_state(TASK_INTERRUPTIBLE);
105615b726efSAndrea Arcangeli 		spin_lock(&ctx->fault_pending_wqh.lock);
105715b726efSAndrea Arcangeli 		uwq = find_userfault(ctx);
105815b726efSAndrea Arcangeli 		if (uwq) {
105986039bd3SAndrea Arcangeli 			/*
10602c5b7e1bSAndrea Arcangeli 			 * Use a seqcount to repeat the lockless check
10612c5b7e1bSAndrea Arcangeli 			 * in wake_userfault() to avoid missing
10622c5b7e1bSAndrea Arcangeli 			 * wakeups because during the refile both
10632c5b7e1bSAndrea Arcangeli 			 * waitqueue could become empty if this is the
10642c5b7e1bSAndrea Arcangeli 			 * only userfault.
10652c5b7e1bSAndrea Arcangeli 			 */
10662c5b7e1bSAndrea Arcangeli 			write_seqcount_begin(&ctx->refile_seq);
10672c5b7e1bSAndrea Arcangeli 
10682c5b7e1bSAndrea Arcangeli 			/*
106915b726efSAndrea Arcangeli 			 * The fault_pending_wqh.lock prevents the uwq
107015b726efSAndrea Arcangeli 			 * to disappear from under us.
107115b726efSAndrea Arcangeli 			 *
107215b726efSAndrea Arcangeli 			 * Refile this userfault from
107315b726efSAndrea Arcangeli 			 * fault_pending_wqh to fault_wqh, it's not
107415b726efSAndrea Arcangeli 			 * pending anymore after we read it.
107515b726efSAndrea Arcangeli 			 *
107615b726efSAndrea Arcangeli 			 * Use list_del() by hand (as
107715b726efSAndrea Arcangeli 			 * userfaultfd_wake_function also uses
107815b726efSAndrea Arcangeli 			 * list_del_init() by hand) to be sure nobody
107915b726efSAndrea Arcangeli 			 * changes __remove_wait_queue() to use
108015b726efSAndrea Arcangeli 			 * list_del_init() in turn breaking the
108115b726efSAndrea Arcangeli 			 * !list_empty_careful() check in
10822055da97SIngo Molnar 			 * handle_userfault(). The uwq->wq.head list
108315b726efSAndrea Arcangeli 			 * must never be empty at any time during the
108415b726efSAndrea Arcangeli 			 * refile, or the waitqueue could disappear
108515b726efSAndrea Arcangeli 			 * from under us. The "wait_queue_head_t"
108615b726efSAndrea Arcangeli 			 * parameter of __remove_wait_queue() is unused
108715b726efSAndrea Arcangeli 			 * anyway.
108886039bd3SAndrea Arcangeli 			 */
10892055da97SIngo Molnar 			list_del(&uwq->wq.entry);
1090c430d1e8SMatthew Wilcox 			add_wait_queue(&ctx->fault_wqh, &uwq->wq);
109115b726efSAndrea Arcangeli 
10922c5b7e1bSAndrea Arcangeli 			write_seqcount_end(&ctx->refile_seq);
10932c5b7e1bSAndrea Arcangeli 
1094a9b85f94SAndrea Arcangeli 			/* careful to always initialize msg if ret == 0 */
1095a9b85f94SAndrea Arcangeli 			*msg = uwq->msg;
109615b726efSAndrea Arcangeli 			spin_unlock(&ctx->fault_pending_wqh.lock);
109786039bd3SAndrea Arcangeli 			ret = 0;
109886039bd3SAndrea Arcangeli 			break;
109986039bd3SAndrea Arcangeli 		}
110015b726efSAndrea Arcangeli 		spin_unlock(&ctx->fault_pending_wqh.lock);
11019cd75c3cSPavel Emelyanov 
11029cd75c3cSPavel Emelyanov 		spin_lock(&ctx->event_wqh.lock);
11039cd75c3cSPavel Emelyanov 		uwq = find_userfault_evt(ctx);
11049cd75c3cSPavel Emelyanov 		if (uwq) {
11059cd75c3cSPavel Emelyanov 			*msg = uwq->msg;
11069cd75c3cSPavel Emelyanov 
1107893e26e6SPavel Emelyanov 			if (uwq->msg.event == UFFD_EVENT_FORK) {
1108893e26e6SPavel Emelyanov 				fork_nctx = (struct userfaultfd_ctx *)
1109893e26e6SPavel Emelyanov 					(unsigned long)
1110893e26e6SPavel Emelyanov 					uwq->msg.arg.reserved.reserved1;
11112055da97SIngo Molnar 				list_move(&uwq->wq.entry, &fork_event);
1112384632e6SAndrea Arcangeli 				/*
1113384632e6SAndrea Arcangeli 				 * fork_nctx can be freed as soon as
1114384632e6SAndrea Arcangeli 				 * we drop the lock, unless we take a
1115384632e6SAndrea Arcangeli 				 * reference on it.
1116384632e6SAndrea Arcangeli 				 */
1117384632e6SAndrea Arcangeli 				userfaultfd_ctx_get(fork_nctx);
1118893e26e6SPavel Emelyanov 				spin_unlock(&ctx->event_wqh.lock);
1119893e26e6SPavel Emelyanov 				ret = 0;
1120893e26e6SPavel Emelyanov 				break;
1121893e26e6SPavel Emelyanov 			}
1122893e26e6SPavel Emelyanov 
11239cd75c3cSPavel Emelyanov 			userfaultfd_event_complete(ctx, uwq);
11249cd75c3cSPavel Emelyanov 			spin_unlock(&ctx->event_wqh.lock);
11259cd75c3cSPavel Emelyanov 			ret = 0;
11269cd75c3cSPavel Emelyanov 			break;
11279cd75c3cSPavel Emelyanov 		}
11289cd75c3cSPavel Emelyanov 		spin_unlock(&ctx->event_wqh.lock);
11299cd75c3cSPavel Emelyanov 
113086039bd3SAndrea Arcangeli 		if (signal_pending(current)) {
113186039bd3SAndrea Arcangeli 			ret = -ERESTARTSYS;
113286039bd3SAndrea Arcangeli 			break;
113386039bd3SAndrea Arcangeli 		}
113486039bd3SAndrea Arcangeli 		if (no_wait) {
113586039bd3SAndrea Arcangeli 			ret = -EAGAIN;
113686039bd3SAndrea Arcangeli 			break;
113786039bd3SAndrea Arcangeli 		}
1138ae62c16eSChristoph Hellwig 		spin_unlock_irq(&ctx->fd_wqh.lock);
113986039bd3SAndrea Arcangeli 		schedule();
1140ae62c16eSChristoph Hellwig 		spin_lock_irq(&ctx->fd_wqh.lock);
114186039bd3SAndrea Arcangeli 	}
114286039bd3SAndrea Arcangeli 	__remove_wait_queue(&ctx->fd_wqh, &wait);
114386039bd3SAndrea Arcangeli 	__set_current_state(TASK_RUNNING);
1144ae62c16eSChristoph Hellwig 	spin_unlock_irq(&ctx->fd_wqh.lock);
114586039bd3SAndrea Arcangeli 
1146893e26e6SPavel Emelyanov 	if (!ret && msg->event == UFFD_EVENT_FORK) {
1147b537900fSDaniel Colascione 		ret = resolve_userfault_fork(fork_nctx, inode, msg);
1148cbcfa130SEric Biggers 		spin_lock_irq(&ctx->event_wqh.lock);
1149893e26e6SPavel Emelyanov 		if (!list_empty(&fork_event)) {
1150384632e6SAndrea Arcangeli 			/*
1151384632e6SAndrea Arcangeli 			 * The fork thread didn't abort, so we can
1152384632e6SAndrea Arcangeli 			 * drop the temporary refcount.
1153384632e6SAndrea Arcangeli 			 */
1154384632e6SAndrea Arcangeli 			userfaultfd_ctx_put(fork_nctx);
1155384632e6SAndrea Arcangeli 
1156893e26e6SPavel Emelyanov 			uwq = list_first_entry(&fork_event,
1157893e26e6SPavel Emelyanov 					       typeof(*uwq),
11582055da97SIngo Molnar 					       wq.entry);
1159384632e6SAndrea Arcangeli 			/*
1160384632e6SAndrea Arcangeli 			 * If fork_event list wasn't empty and in turn
1161384632e6SAndrea Arcangeli 			 * the event wasn't already released by fork
1162384632e6SAndrea Arcangeli 			 * (the event is allocated on fork kernel
1163384632e6SAndrea Arcangeli 			 * stack), put the event back to its place in
1164384632e6SAndrea Arcangeli 			 * the event_wq. fork_event head will be freed
1165384632e6SAndrea Arcangeli 			 * as soon as we return so the event cannot
1166384632e6SAndrea Arcangeli 			 * stay queued there no matter the current
1167384632e6SAndrea Arcangeli 			 * "ret" value.
1168384632e6SAndrea Arcangeli 			 */
11692055da97SIngo Molnar 			list_del(&uwq->wq.entry);
1170893e26e6SPavel Emelyanov 			__add_wait_queue(&ctx->event_wqh, &uwq->wq);
1171384632e6SAndrea Arcangeli 
1172384632e6SAndrea Arcangeli 			/*
1173384632e6SAndrea Arcangeli 			 * Leave the event in the waitqueue and report
1174384632e6SAndrea Arcangeli 			 * error to userland if we failed to resolve
1175384632e6SAndrea Arcangeli 			 * the userfault fork.
1176384632e6SAndrea Arcangeli 			 */
1177384632e6SAndrea Arcangeli 			if (likely(!ret))
1178893e26e6SPavel Emelyanov 				userfaultfd_event_complete(ctx, uwq);
1179384632e6SAndrea Arcangeli 		} else {
1180384632e6SAndrea Arcangeli 			/*
1181384632e6SAndrea Arcangeli 			 * Here the fork thread aborted and the
1182384632e6SAndrea Arcangeli 			 * refcount from the fork thread on fork_nctx
1183384632e6SAndrea Arcangeli 			 * has already been released. We still hold
1184384632e6SAndrea Arcangeli 			 * the reference we took before releasing the
1185384632e6SAndrea Arcangeli 			 * lock above. If resolve_userfault_fork
1186384632e6SAndrea Arcangeli 			 * failed we've to drop it because the
1187384632e6SAndrea Arcangeli 			 * fork_nctx has to be freed in such case. If
1188384632e6SAndrea Arcangeli 			 * it succeeded we'll hold it because the new
1189384632e6SAndrea Arcangeli 			 * uffd references it.
1190384632e6SAndrea Arcangeli 			 */
1191384632e6SAndrea Arcangeli 			if (ret)
1192384632e6SAndrea Arcangeli 				userfaultfd_ctx_put(fork_nctx);
1193893e26e6SPavel Emelyanov 		}
1194cbcfa130SEric Biggers 		spin_unlock_irq(&ctx->event_wqh.lock);
1195893e26e6SPavel Emelyanov 	}
1196893e26e6SPavel Emelyanov 
119786039bd3SAndrea Arcangeli 	return ret;
119886039bd3SAndrea Arcangeli }
119986039bd3SAndrea Arcangeli 
120086039bd3SAndrea Arcangeli static ssize_t userfaultfd_read(struct file *file, char __user *buf,
120186039bd3SAndrea Arcangeli 				size_t count, loff_t *ppos)
120286039bd3SAndrea Arcangeli {
120386039bd3SAndrea Arcangeli 	struct userfaultfd_ctx *ctx = file->private_data;
120486039bd3SAndrea Arcangeli 	ssize_t _ret, ret = 0;
1205a9b85f94SAndrea Arcangeli 	struct uffd_msg msg;
120686039bd3SAndrea Arcangeli 	int no_wait = file->f_flags & O_NONBLOCK;
1207b537900fSDaniel Colascione 	struct inode *inode = file_inode(file);
120886039bd3SAndrea Arcangeli 
120922e5fe2aSNadav Amit 	if (!userfaultfd_is_initialized(ctx))
121086039bd3SAndrea Arcangeli 		return -EINVAL;
121186039bd3SAndrea Arcangeli 
121286039bd3SAndrea Arcangeli 	for (;;) {
1213a9b85f94SAndrea Arcangeli 		if (count < sizeof(msg))
121486039bd3SAndrea Arcangeli 			return ret ? ret : -EINVAL;
1215b537900fSDaniel Colascione 		_ret = userfaultfd_ctx_read(ctx, no_wait, &msg, inode);
121686039bd3SAndrea Arcangeli 		if (_ret < 0)
121786039bd3SAndrea Arcangeli 			return ret ? ret : _ret;
1218a9b85f94SAndrea Arcangeli 		if (copy_to_user((__u64 __user *) buf, &msg, sizeof(msg)))
121986039bd3SAndrea Arcangeli 			return ret ? ret : -EFAULT;
1220a9b85f94SAndrea Arcangeli 		ret += sizeof(msg);
1221a9b85f94SAndrea Arcangeli 		buf += sizeof(msg);
1222a9b85f94SAndrea Arcangeli 		count -= sizeof(msg);
122386039bd3SAndrea Arcangeli 		/*
122486039bd3SAndrea Arcangeli 		 * Allow to read more than one fault at time but only
122586039bd3SAndrea Arcangeli 		 * block if waiting for the very first one.
122686039bd3SAndrea Arcangeli 		 */
122786039bd3SAndrea Arcangeli 		no_wait = O_NONBLOCK;
122886039bd3SAndrea Arcangeli 	}
122986039bd3SAndrea Arcangeli }
123086039bd3SAndrea Arcangeli 
123186039bd3SAndrea Arcangeli static void __wake_userfault(struct userfaultfd_ctx *ctx,
123286039bd3SAndrea Arcangeli 			     struct userfaultfd_wake_range *range)
123386039bd3SAndrea Arcangeli {
1234cbcfa130SEric Biggers 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
123586039bd3SAndrea Arcangeli 	/* wake all in the range and autoremove */
123615b726efSAndrea Arcangeli 	if (waitqueue_active(&ctx->fault_pending_wqh))
1237ac5be6b4SAndrea Arcangeli 		__wake_up_locked_key(&ctx->fault_pending_wqh, TASK_NORMAL,
123815b726efSAndrea Arcangeli 				     range);
123915b726efSAndrea Arcangeli 	if (waitqueue_active(&ctx->fault_wqh))
1240c430d1e8SMatthew Wilcox 		__wake_up(&ctx->fault_wqh, TASK_NORMAL, 1, range);
1241cbcfa130SEric Biggers 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
124286039bd3SAndrea Arcangeli }
124386039bd3SAndrea Arcangeli 
124486039bd3SAndrea Arcangeli static __always_inline void wake_userfault(struct userfaultfd_ctx *ctx,
124586039bd3SAndrea Arcangeli 					   struct userfaultfd_wake_range *range)
124686039bd3SAndrea Arcangeli {
12472c5b7e1bSAndrea Arcangeli 	unsigned seq;
12482c5b7e1bSAndrea Arcangeli 	bool need_wakeup;
12492c5b7e1bSAndrea Arcangeli 
125086039bd3SAndrea Arcangeli 	/*
125186039bd3SAndrea Arcangeli 	 * To be sure waitqueue_active() is not reordered by the CPU
125286039bd3SAndrea Arcangeli 	 * before the pagetable update, use an explicit SMP memory
12533e4e28c5SMichel Lespinasse 	 * barrier here. PT lock release or mmap_read_unlock(mm) still
125486039bd3SAndrea Arcangeli 	 * have release semantics that can allow the
125586039bd3SAndrea Arcangeli 	 * waitqueue_active() to be reordered before the pte update.
125686039bd3SAndrea Arcangeli 	 */
125786039bd3SAndrea Arcangeli 	smp_mb();
125886039bd3SAndrea Arcangeli 
125986039bd3SAndrea Arcangeli 	/*
126086039bd3SAndrea Arcangeli 	 * Use waitqueue_active because it's very frequent to
126186039bd3SAndrea Arcangeli 	 * change the address space atomically even if there are no
126286039bd3SAndrea Arcangeli 	 * userfaults yet. So we take the spinlock only when we're
126386039bd3SAndrea Arcangeli 	 * sure we've userfaults to wake.
126486039bd3SAndrea Arcangeli 	 */
12652c5b7e1bSAndrea Arcangeli 	do {
12662c5b7e1bSAndrea Arcangeli 		seq = read_seqcount_begin(&ctx->refile_seq);
12672c5b7e1bSAndrea Arcangeli 		need_wakeup = waitqueue_active(&ctx->fault_pending_wqh) ||
12682c5b7e1bSAndrea Arcangeli 			waitqueue_active(&ctx->fault_wqh);
12692c5b7e1bSAndrea Arcangeli 		cond_resched();
12702c5b7e1bSAndrea Arcangeli 	} while (read_seqcount_retry(&ctx->refile_seq, seq));
12712c5b7e1bSAndrea Arcangeli 	if (need_wakeup)
127286039bd3SAndrea Arcangeli 		__wake_userfault(ctx, range);
127386039bd3SAndrea Arcangeli }
127486039bd3SAndrea Arcangeli 
127586039bd3SAndrea Arcangeli static __always_inline int validate_range(struct mm_struct *mm,
1276e71e2aceSPeter Collingbourne 					  __u64 start, __u64 len)
127786039bd3SAndrea Arcangeli {
127886039bd3SAndrea Arcangeli 	__u64 task_size = mm->task_size;
127986039bd3SAndrea Arcangeli 
1280e71e2aceSPeter Collingbourne 	if (start & ~PAGE_MASK)
128186039bd3SAndrea Arcangeli 		return -EINVAL;
128286039bd3SAndrea Arcangeli 	if (len & ~PAGE_MASK)
128386039bd3SAndrea Arcangeli 		return -EINVAL;
128486039bd3SAndrea Arcangeli 	if (!len)
128586039bd3SAndrea Arcangeli 		return -EINVAL;
1286e71e2aceSPeter Collingbourne 	if (start < mmap_min_addr)
128786039bd3SAndrea Arcangeli 		return -EINVAL;
1288e71e2aceSPeter Collingbourne 	if (start >= task_size)
128986039bd3SAndrea Arcangeli 		return -EINVAL;
1290e71e2aceSPeter Collingbourne 	if (len > task_size - start)
129186039bd3SAndrea Arcangeli 		return -EINVAL;
129286039bd3SAndrea Arcangeli 	return 0;
129386039bd3SAndrea Arcangeli }
129486039bd3SAndrea Arcangeli 
129586039bd3SAndrea Arcangeli static int userfaultfd_register(struct userfaultfd_ctx *ctx,
129686039bd3SAndrea Arcangeli 				unsigned long arg)
129786039bd3SAndrea Arcangeli {
129886039bd3SAndrea Arcangeli 	struct mm_struct *mm = ctx->mm;
129986039bd3SAndrea Arcangeli 	struct vm_area_struct *vma, *prev, *cur;
130086039bd3SAndrea Arcangeli 	int ret;
130186039bd3SAndrea Arcangeli 	struct uffdio_register uffdio_register;
130286039bd3SAndrea Arcangeli 	struct uffdio_register __user *user_uffdio_register;
130386039bd3SAndrea Arcangeli 	unsigned long vm_flags, new_flags;
130486039bd3SAndrea Arcangeli 	bool found;
1305ce53e8e6SMike Rapoport 	bool basic_ioctls;
130686039bd3SAndrea Arcangeli 	unsigned long start, end, vma_end;
130769dbe6daSLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
130886039bd3SAndrea Arcangeli 
130986039bd3SAndrea Arcangeli 	user_uffdio_register = (struct uffdio_register __user *) arg;
131086039bd3SAndrea Arcangeli 
131186039bd3SAndrea Arcangeli 	ret = -EFAULT;
131286039bd3SAndrea Arcangeli 	if (copy_from_user(&uffdio_register, user_uffdio_register,
131386039bd3SAndrea Arcangeli 			   sizeof(uffdio_register)-sizeof(__u64)))
131486039bd3SAndrea Arcangeli 		goto out;
131586039bd3SAndrea Arcangeli 
131686039bd3SAndrea Arcangeli 	ret = -EINVAL;
131786039bd3SAndrea Arcangeli 	if (!uffdio_register.mode)
131886039bd3SAndrea Arcangeli 		goto out;
13197677f7fdSAxel Rasmussen 	if (uffdio_register.mode & ~UFFD_API_REGISTER_MODES)
132086039bd3SAndrea Arcangeli 		goto out;
132186039bd3SAndrea Arcangeli 	vm_flags = 0;
132286039bd3SAndrea Arcangeli 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MISSING)
132386039bd3SAndrea Arcangeli 		vm_flags |= VM_UFFD_MISSING;
132400b151f2SPeter Xu 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_WP) {
132500b151f2SPeter Xu #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
132600b151f2SPeter Xu 		goto out;
132700b151f2SPeter Xu #endif
132886039bd3SAndrea Arcangeli 		vm_flags |= VM_UFFD_WP;
132900b151f2SPeter Xu 	}
13307677f7fdSAxel Rasmussen 	if (uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR) {
13317677f7fdSAxel Rasmussen #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
13327677f7fdSAxel Rasmussen 		goto out;
13337677f7fdSAxel Rasmussen #endif
13347677f7fdSAxel Rasmussen 		vm_flags |= VM_UFFD_MINOR;
13357677f7fdSAxel Rasmussen 	}
133686039bd3SAndrea Arcangeli 
1337e71e2aceSPeter Collingbourne 	ret = validate_range(mm, uffdio_register.range.start,
133886039bd3SAndrea Arcangeli 			     uffdio_register.range.len);
133986039bd3SAndrea Arcangeli 	if (ret)
134086039bd3SAndrea Arcangeli 		goto out;
134186039bd3SAndrea Arcangeli 
134286039bd3SAndrea Arcangeli 	start = uffdio_register.range.start;
134386039bd3SAndrea Arcangeli 	end = start + uffdio_register.range.len;
134486039bd3SAndrea Arcangeli 
1345d2005e3fSOleg Nesterov 	ret = -ENOMEM;
1346d2005e3fSOleg Nesterov 	if (!mmget_not_zero(mm))
1347d2005e3fSOleg Nesterov 		goto out;
1348d2005e3fSOleg Nesterov 
1349d8ed45c5SMichel Lespinasse 	mmap_write_lock(mm);
135069dbe6daSLiam R. Howlett 	mas_set(&mas, start);
135169dbe6daSLiam R. Howlett 	vma = mas_find(&mas, ULONG_MAX);
135286039bd3SAndrea Arcangeli 	if (!vma)
135386039bd3SAndrea Arcangeli 		goto out_unlock;
135486039bd3SAndrea Arcangeli 
135586039bd3SAndrea Arcangeli 	/* check that there's at least one vma in the range */
135686039bd3SAndrea Arcangeli 	ret = -EINVAL;
135786039bd3SAndrea Arcangeli 	if (vma->vm_start >= end)
135886039bd3SAndrea Arcangeli 		goto out_unlock;
135986039bd3SAndrea Arcangeli 
136086039bd3SAndrea Arcangeli 	/*
1361cab350afSMike Kravetz 	 * If the first vma contains huge pages, make sure start address
1362cab350afSMike Kravetz 	 * is aligned to huge page size.
1363cab350afSMike Kravetz 	 */
1364cab350afSMike Kravetz 	if (is_vm_hugetlb_page(vma)) {
1365cab350afSMike Kravetz 		unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1366cab350afSMike Kravetz 
1367cab350afSMike Kravetz 		if (start & (vma_hpagesize - 1))
1368cab350afSMike Kravetz 			goto out_unlock;
1369cab350afSMike Kravetz 	}
1370cab350afSMike Kravetz 
1371cab350afSMike Kravetz 	/*
137286039bd3SAndrea Arcangeli 	 * Search for not compatible vmas.
137386039bd3SAndrea Arcangeli 	 */
137486039bd3SAndrea Arcangeli 	found = false;
1375ce53e8e6SMike Rapoport 	basic_ioctls = false;
137669dbe6daSLiam R. Howlett 	for (cur = vma; cur; cur = mas_next(&mas, end - 1)) {
137786039bd3SAndrea Arcangeli 		cond_resched();
137886039bd3SAndrea Arcangeli 
137986039bd3SAndrea Arcangeli 		BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
13807677f7fdSAxel Rasmussen 		       !!(cur->vm_flags & __VM_UFFD_FLAGS));
138186039bd3SAndrea Arcangeli 
138286039bd3SAndrea Arcangeli 		/* check not compatible vmas */
138386039bd3SAndrea Arcangeli 		ret = -EINVAL;
138463b2d417SAndrea Arcangeli 		if (!vma_can_userfault(cur, vm_flags))
138586039bd3SAndrea Arcangeli 			goto out_unlock;
138629ec9066SAndrea Arcangeli 
138729ec9066SAndrea Arcangeli 		/*
138829ec9066SAndrea Arcangeli 		 * UFFDIO_COPY will fill file holes even without
138929ec9066SAndrea Arcangeli 		 * PROT_WRITE. This check enforces that if this is a
139029ec9066SAndrea Arcangeli 		 * MAP_SHARED, the process has write permission to the backing
139129ec9066SAndrea Arcangeli 		 * file. If VM_MAYWRITE is set it also enforces that on a
139229ec9066SAndrea Arcangeli 		 * MAP_SHARED vma: there is no F_WRITE_SEAL and no further
139329ec9066SAndrea Arcangeli 		 * F_WRITE_SEAL can be taken until the vma is destroyed.
139429ec9066SAndrea Arcangeli 		 */
139529ec9066SAndrea Arcangeli 		ret = -EPERM;
139629ec9066SAndrea Arcangeli 		if (unlikely(!(cur->vm_flags & VM_MAYWRITE)))
139729ec9066SAndrea Arcangeli 			goto out_unlock;
139829ec9066SAndrea Arcangeli 
1399cab350afSMike Kravetz 		/*
1400cab350afSMike Kravetz 		 * If this vma contains ending address, and huge pages
1401cab350afSMike Kravetz 		 * check alignment.
1402cab350afSMike Kravetz 		 */
1403cab350afSMike Kravetz 		if (is_vm_hugetlb_page(cur) && end <= cur->vm_end &&
1404cab350afSMike Kravetz 		    end > cur->vm_start) {
1405cab350afSMike Kravetz 			unsigned long vma_hpagesize = vma_kernel_pagesize(cur);
1406cab350afSMike Kravetz 
1407cab350afSMike Kravetz 			ret = -EINVAL;
1408cab350afSMike Kravetz 
1409cab350afSMike Kravetz 			if (end & (vma_hpagesize - 1))
1410cab350afSMike Kravetz 				goto out_unlock;
1411cab350afSMike Kravetz 		}
141263b2d417SAndrea Arcangeli 		if ((vm_flags & VM_UFFD_WP) && !(cur->vm_flags & VM_MAYWRITE))
141363b2d417SAndrea Arcangeli 			goto out_unlock;
141486039bd3SAndrea Arcangeli 
141586039bd3SAndrea Arcangeli 		/*
141686039bd3SAndrea Arcangeli 		 * Check that this vma isn't already owned by a
141786039bd3SAndrea Arcangeli 		 * different userfaultfd. We can't allow more than one
141886039bd3SAndrea Arcangeli 		 * userfaultfd to own a single vma simultaneously or we
141986039bd3SAndrea Arcangeli 		 * wouldn't know which one to deliver the userfaults to.
142086039bd3SAndrea Arcangeli 		 */
142186039bd3SAndrea Arcangeli 		ret = -EBUSY;
142286039bd3SAndrea Arcangeli 		if (cur->vm_userfaultfd_ctx.ctx &&
142386039bd3SAndrea Arcangeli 		    cur->vm_userfaultfd_ctx.ctx != ctx)
142486039bd3SAndrea Arcangeli 			goto out_unlock;
142586039bd3SAndrea Arcangeli 
1426cab350afSMike Kravetz 		/*
1427cab350afSMike Kravetz 		 * Note vmas containing huge pages
1428cab350afSMike Kravetz 		 */
1429ce53e8e6SMike Rapoport 		if (is_vm_hugetlb_page(cur))
1430ce53e8e6SMike Rapoport 			basic_ioctls = true;
1431cab350afSMike Kravetz 
143286039bd3SAndrea Arcangeli 		found = true;
143386039bd3SAndrea Arcangeli 	}
143486039bd3SAndrea Arcangeli 	BUG_ON(!found);
143586039bd3SAndrea Arcangeli 
143669dbe6daSLiam R. Howlett 	mas_set(&mas, start);
143769dbe6daSLiam R. Howlett 	prev = mas_prev(&mas, 0);
143869dbe6daSLiam R. Howlett 	if (prev != vma)
143969dbe6daSLiam R. Howlett 		mas_next(&mas, ULONG_MAX);
144086039bd3SAndrea Arcangeli 
144186039bd3SAndrea Arcangeli 	ret = 0;
144286039bd3SAndrea Arcangeli 	do {
144386039bd3SAndrea Arcangeli 		cond_resched();
144486039bd3SAndrea Arcangeli 
144563b2d417SAndrea Arcangeli 		BUG_ON(!vma_can_userfault(vma, vm_flags));
144686039bd3SAndrea Arcangeli 		BUG_ON(vma->vm_userfaultfd_ctx.ctx &&
144786039bd3SAndrea Arcangeli 		       vma->vm_userfaultfd_ctx.ctx != ctx);
144829ec9066SAndrea Arcangeli 		WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
144986039bd3SAndrea Arcangeli 
145086039bd3SAndrea Arcangeli 		/*
145186039bd3SAndrea Arcangeli 		 * Nothing to do: this vma is already registered into this
145286039bd3SAndrea Arcangeli 		 * userfaultfd and with the right tracking mode too.
145386039bd3SAndrea Arcangeli 		 */
145486039bd3SAndrea Arcangeli 		if (vma->vm_userfaultfd_ctx.ctx == ctx &&
145586039bd3SAndrea Arcangeli 		    (vma->vm_flags & vm_flags) == vm_flags)
145686039bd3SAndrea Arcangeli 			goto skip;
145786039bd3SAndrea Arcangeli 
145886039bd3SAndrea Arcangeli 		if (vma->vm_start > start)
145986039bd3SAndrea Arcangeli 			start = vma->vm_start;
146086039bd3SAndrea Arcangeli 		vma_end = min(end, vma->vm_end);
146186039bd3SAndrea Arcangeli 
14627677f7fdSAxel Rasmussen 		new_flags = (vma->vm_flags & ~__VM_UFFD_FLAGS) | vm_flags;
146386039bd3SAndrea Arcangeli 		prev = vma_merge(mm, prev, start, vma_end, new_flags,
146486039bd3SAndrea Arcangeli 				 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
146586039bd3SAndrea Arcangeli 				 vma_policy(vma),
14669a10064fSColin Cross 				 ((struct vm_userfaultfd_ctx){ ctx }),
14675c26f6acSSuren Baghdasaryan 				 anon_vma_name(vma));
146886039bd3SAndrea Arcangeli 		if (prev) {
146969dbe6daSLiam R. Howlett 			/* vma_merge() invalidated the mas */
147069dbe6daSLiam R. Howlett 			mas_pause(&mas);
147186039bd3SAndrea Arcangeli 			vma = prev;
147286039bd3SAndrea Arcangeli 			goto next;
147386039bd3SAndrea Arcangeli 		}
147486039bd3SAndrea Arcangeli 		if (vma->vm_start < start) {
147586039bd3SAndrea Arcangeli 			ret = split_vma(mm, vma, start, 1);
147686039bd3SAndrea Arcangeli 			if (ret)
147786039bd3SAndrea Arcangeli 				break;
147869dbe6daSLiam R. Howlett 			/* split_vma() invalidated the mas */
147969dbe6daSLiam R. Howlett 			mas_pause(&mas);
148086039bd3SAndrea Arcangeli 		}
148186039bd3SAndrea Arcangeli 		if (vma->vm_end > end) {
148286039bd3SAndrea Arcangeli 			ret = split_vma(mm, vma, end, 0);
148386039bd3SAndrea Arcangeli 			if (ret)
148486039bd3SAndrea Arcangeli 				break;
148569dbe6daSLiam R. Howlett 			/* split_vma() invalidated the mas */
148669dbe6daSLiam R. Howlett 			mas_pause(&mas);
148786039bd3SAndrea Arcangeli 		}
148886039bd3SAndrea Arcangeli 	next:
148986039bd3SAndrea Arcangeli 		/*
149086039bd3SAndrea Arcangeli 		 * In the vma_merge() successful mprotect-like case 8:
149186039bd3SAndrea Arcangeli 		 * the next vma was merged into the current one and
149286039bd3SAndrea Arcangeli 		 * the current one has not been updated yet.
149386039bd3SAndrea Arcangeli 		 */
149451d3d5ebSDavid Hildenbrand 		userfaultfd_set_vm_flags(vma, new_flags);
149586039bd3SAndrea Arcangeli 		vma->vm_userfaultfd_ctx.ctx = ctx;
149686039bd3SAndrea Arcangeli 
14976dfeaff9SPeter Xu 		if (is_vm_hugetlb_page(vma) && uffd_disable_huge_pmd_share(vma))
14986dfeaff9SPeter Xu 			hugetlb_unshare_all_pmds(vma);
14996dfeaff9SPeter Xu 
150086039bd3SAndrea Arcangeli 	skip:
150186039bd3SAndrea Arcangeli 		prev = vma;
150286039bd3SAndrea Arcangeli 		start = vma->vm_end;
150369dbe6daSLiam R. Howlett 		vma = mas_next(&mas, end - 1);
150469dbe6daSLiam R. Howlett 	} while (vma);
150586039bd3SAndrea Arcangeli out_unlock:
1506d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
1507d2005e3fSOleg Nesterov 	mmput(mm);
150886039bd3SAndrea Arcangeli 	if (!ret) {
150914819305SPeter Xu 		__u64 ioctls_out;
151014819305SPeter Xu 
151114819305SPeter Xu 		ioctls_out = basic_ioctls ? UFFD_API_RANGE_IOCTLS_BASIC :
151214819305SPeter Xu 		    UFFD_API_RANGE_IOCTLS;
151314819305SPeter Xu 
151414819305SPeter Xu 		/*
151514819305SPeter Xu 		 * Declare the WP ioctl only if the WP mode is
151614819305SPeter Xu 		 * specified and all checks passed with the range
151714819305SPeter Xu 		 */
151814819305SPeter Xu 		if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_WP))
151914819305SPeter Xu 			ioctls_out &= ~((__u64)1 << _UFFDIO_WRITEPROTECT);
152014819305SPeter Xu 
1521f6191471SAxel Rasmussen 		/* CONTINUE ioctl is only supported for MINOR ranges. */
1522f6191471SAxel Rasmussen 		if (!(uffdio_register.mode & UFFDIO_REGISTER_MODE_MINOR))
1523f6191471SAxel Rasmussen 			ioctls_out &= ~((__u64)1 << _UFFDIO_CONTINUE);
1524f6191471SAxel Rasmussen 
152586039bd3SAndrea Arcangeli 		/*
152686039bd3SAndrea Arcangeli 		 * Now that we scanned all vmas we can already tell
152786039bd3SAndrea Arcangeli 		 * userland which ioctls methods are guaranteed to
152886039bd3SAndrea Arcangeli 		 * succeed on this range.
152986039bd3SAndrea Arcangeli 		 */
153014819305SPeter Xu 		if (put_user(ioctls_out, &user_uffdio_register->ioctls))
153186039bd3SAndrea Arcangeli 			ret = -EFAULT;
153286039bd3SAndrea Arcangeli 	}
153386039bd3SAndrea Arcangeli out:
153486039bd3SAndrea Arcangeli 	return ret;
153586039bd3SAndrea Arcangeli }
153686039bd3SAndrea Arcangeli 
153786039bd3SAndrea Arcangeli static int userfaultfd_unregister(struct userfaultfd_ctx *ctx,
153886039bd3SAndrea Arcangeli 				  unsigned long arg)
153986039bd3SAndrea Arcangeli {
154086039bd3SAndrea Arcangeli 	struct mm_struct *mm = ctx->mm;
154186039bd3SAndrea Arcangeli 	struct vm_area_struct *vma, *prev, *cur;
154286039bd3SAndrea Arcangeli 	int ret;
154386039bd3SAndrea Arcangeli 	struct uffdio_range uffdio_unregister;
154486039bd3SAndrea Arcangeli 	unsigned long new_flags;
154586039bd3SAndrea Arcangeli 	bool found;
154686039bd3SAndrea Arcangeli 	unsigned long start, end, vma_end;
154786039bd3SAndrea Arcangeli 	const void __user *buf = (void __user *)arg;
154869dbe6daSLiam R. Howlett 	MA_STATE(mas, &mm->mm_mt, 0, 0);
154986039bd3SAndrea Arcangeli 
155086039bd3SAndrea Arcangeli 	ret = -EFAULT;
155186039bd3SAndrea Arcangeli 	if (copy_from_user(&uffdio_unregister, buf, sizeof(uffdio_unregister)))
155286039bd3SAndrea Arcangeli 		goto out;
155386039bd3SAndrea Arcangeli 
1554e71e2aceSPeter Collingbourne 	ret = validate_range(mm, uffdio_unregister.start,
155586039bd3SAndrea Arcangeli 			     uffdio_unregister.len);
155686039bd3SAndrea Arcangeli 	if (ret)
155786039bd3SAndrea Arcangeli 		goto out;
155886039bd3SAndrea Arcangeli 
155986039bd3SAndrea Arcangeli 	start = uffdio_unregister.start;
156086039bd3SAndrea Arcangeli 	end = start + uffdio_unregister.len;
156186039bd3SAndrea Arcangeli 
1562d2005e3fSOleg Nesterov 	ret = -ENOMEM;
1563d2005e3fSOleg Nesterov 	if (!mmget_not_zero(mm))
1564d2005e3fSOleg Nesterov 		goto out;
1565d2005e3fSOleg Nesterov 
1566d8ed45c5SMichel Lespinasse 	mmap_write_lock(mm);
156769dbe6daSLiam R. Howlett 	mas_set(&mas, start);
156869dbe6daSLiam R. Howlett 	vma = mas_find(&mas, ULONG_MAX);
156986039bd3SAndrea Arcangeli 	if (!vma)
157086039bd3SAndrea Arcangeli 		goto out_unlock;
157186039bd3SAndrea Arcangeli 
157286039bd3SAndrea Arcangeli 	/* check that there's at least one vma in the range */
157386039bd3SAndrea Arcangeli 	ret = -EINVAL;
157486039bd3SAndrea Arcangeli 	if (vma->vm_start >= end)
157586039bd3SAndrea Arcangeli 		goto out_unlock;
157686039bd3SAndrea Arcangeli 
157786039bd3SAndrea Arcangeli 	/*
1578cab350afSMike Kravetz 	 * If the first vma contains huge pages, make sure start address
1579cab350afSMike Kravetz 	 * is aligned to huge page size.
1580cab350afSMike Kravetz 	 */
1581cab350afSMike Kravetz 	if (is_vm_hugetlb_page(vma)) {
1582cab350afSMike Kravetz 		unsigned long vma_hpagesize = vma_kernel_pagesize(vma);
1583cab350afSMike Kravetz 
1584cab350afSMike Kravetz 		if (start & (vma_hpagesize - 1))
1585cab350afSMike Kravetz 			goto out_unlock;
1586cab350afSMike Kravetz 	}
1587cab350afSMike Kravetz 
1588cab350afSMike Kravetz 	/*
158986039bd3SAndrea Arcangeli 	 * Search for not compatible vmas.
159086039bd3SAndrea Arcangeli 	 */
159186039bd3SAndrea Arcangeli 	found = false;
159286039bd3SAndrea Arcangeli 	ret = -EINVAL;
159369dbe6daSLiam R. Howlett 	for (cur = vma; cur; cur = mas_next(&mas, end - 1)) {
159486039bd3SAndrea Arcangeli 		cond_resched();
159586039bd3SAndrea Arcangeli 
159686039bd3SAndrea Arcangeli 		BUG_ON(!!cur->vm_userfaultfd_ctx.ctx ^
15977677f7fdSAxel Rasmussen 		       !!(cur->vm_flags & __VM_UFFD_FLAGS));
159886039bd3SAndrea Arcangeli 
159986039bd3SAndrea Arcangeli 		/*
160086039bd3SAndrea Arcangeli 		 * Check not compatible vmas, not strictly required
160186039bd3SAndrea Arcangeli 		 * here as not compatible vmas cannot have an
160286039bd3SAndrea Arcangeli 		 * userfaultfd_ctx registered on them, but this
160386039bd3SAndrea Arcangeli 		 * provides for more strict behavior to notice
160486039bd3SAndrea Arcangeli 		 * unregistration errors.
160586039bd3SAndrea Arcangeli 		 */
160663b2d417SAndrea Arcangeli 		if (!vma_can_userfault(cur, cur->vm_flags))
160786039bd3SAndrea Arcangeli 			goto out_unlock;
160886039bd3SAndrea Arcangeli 
160986039bd3SAndrea Arcangeli 		found = true;
161086039bd3SAndrea Arcangeli 	}
161186039bd3SAndrea Arcangeli 	BUG_ON(!found);
161286039bd3SAndrea Arcangeli 
161369dbe6daSLiam R. Howlett 	mas_set(&mas, start);
161469dbe6daSLiam R. Howlett 	prev = mas_prev(&mas, 0);
161569dbe6daSLiam R. Howlett 	if (prev != vma)
161669dbe6daSLiam R. Howlett 		mas_next(&mas, ULONG_MAX);
161786039bd3SAndrea Arcangeli 
161886039bd3SAndrea Arcangeli 	ret = 0;
161986039bd3SAndrea Arcangeli 	do {
162086039bd3SAndrea Arcangeli 		cond_resched();
162186039bd3SAndrea Arcangeli 
162263b2d417SAndrea Arcangeli 		BUG_ON(!vma_can_userfault(vma, vma->vm_flags));
162386039bd3SAndrea Arcangeli 
162486039bd3SAndrea Arcangeli 		/*
162586039bd3SAndrea Arcangeli 		 * Nothing to do: this vma is already registered into this
162686039bd3SAndrea Arcangeli 		 * userfaultfd and with the right tracking mode too.
162786039bd3SAndrea Arcangeli 		 */
162886039bd3SAndrea Arcangeli 		if (!vma->vm_userfaultfd_ctx.ctx)
162986039bd3SAndrea Arcangeli 			goto skip;
163086039bd3SAndrea Arcangeli 
163101e881f5SAndrea Arcangeli 		WARN_ON(!(vma->vm_flags & VM_MAYWRITE));
163201e881f5SAndrea Arcangeli 
163386039bd3SAndrea Arcangeli 		if (vma->vm_start > start)
163486039bd3SAndrea Arcangeli 			start = vma->vm_start;
163586039bd3SAndrea Arcangeli 		vma_end = min(end, vma->vm_end);
163686039bd3SAndrea Arcangeli 
163709fa5296SAndrea Arcangeli 		if (userfaultfd_missing(vma)) {
163809fa5296SAndrea Arcangeli 			/*
163909fa5296SAndrea Arcangeli 			 * Wake any concurrent pending userfault while
164009fa5296SAndrea Arcangeli 			 * we unregister, so they will not hang
164109fa5296SAndrea Arcangeli 			 * permanently and it avoids userland to call
164209fa5296SAndrea Arcangeli 			 * UFFDIO_WAKE explicitly.
164309fa5296SAndrea Arcangeli 			 */
164409fa5296SAndrea Arcangeli 			struct userfaultfd_wake_range range;
164509fa5296SAndrea Arcangeli 			range.start = start;
164609fa5296SAndrea Arcangeli 			range.len = vma_end - start;
164709fa5296SAndrea Arcangeli 			wake_userfault(vma->vm_userfaultfd_ctx.ctx, &range);
164809fa5296SAndrea Arcangeli 		}
164909fa5296SAndrea Arcangeli 
1650f369b07cSPeter Xu 		/* Reset ptes for the whole vma range if wr-protected */
1651f369b07cSPeter Xu 		if (userfaultfd_wp(vma))
1652f369b07cSPeter Xu 			uffd_wp_range(mm, vma, start, vma_end - start, false);
1653f369b07cSPeter Xu 
16547677f7fdSAxel Rasmussen 		new_flags = vma->vm_flags & ~__VM_UFFD_FLAGS;
165586039bd3SAndrea Arcangeli 		prev = vma_merge(mm, prev, start, vma_end, new_flags,
165686039bd3SAndrea Arcangeli 				 vma->anon_vma, vma->vm_file, vma->vm_pgoff,
165786039bd3SAndrea Arcangeli 				 vma_policy(vma),
16585c26f6acSSuren Baghdasaryan 				 NULL_VM_UFFD_CTX, anon_vma_name(vma));
165986039bd3SAndrea Arcangeli 		if (prev) {
166086039bd3SAndrea Arcangeli 			vma = prev;
166159f2f4b8SLiam Howlett 			mas_pause(&mas);
166286039bd3SAndrea Arcangeli 			goto next;
166386039bd3SAndrea Arcangeli 		}
166486039bd3SAndrea Arcangeli 		if (vma->vm_start < start) {
166586039bd3SAndrea Arcangeli 			ret = split_vma(mm, vma, start, 1);
166686039bd3SAndrea Arcangeli 			if (ret)
166786039bd3SAndrea Arcangeli 				break;
166859f2f4b8SLiam Howlett 			mas_pause(&mas);
166986039bd3SAndrea Arcangeli 		}
167086039bd3SAndrea Arcangeli 		if (vma->vm_end > end) {
167186039bd3SAndrea Arcangeli 			ret = split_vma(mm, vma, end, 0);
167286039bd3SAndrea Arcangeli 			if (ret)
167386039bd3SAndrea Arcangeli 				break;
167459f2f4b8SLiam Howlett 			mas_pause(&mas);
167586039bd3SAndrea Arcangeli 		}
167686039bd3SAndrea Arcangeli 	next:
167786039bd3SAndrea Arcangeli 		/*
167886039bd3SAndrea Arcangeli 		 * In the vma_merge() successful mprotect-like case 8:
167986039bd3SAndrea Arcangeli 		 * the next vma was merged into the current one and
168086039bd3SAndrea Arcangeli 		 * the current one has not been updated yet.
168186039bd3SAndrea Arcangeli 		 */
168251d3d5ebSDavid Hildenbrand 		userfaultfd_set_vm_flags(vma, new_flags);
168386039bd3SAndrea Arcangeli 		vma->vm_userfaultfd_ctx = NULL_VM_UFFD_CTX;
168486039bd3SAndrea Arcangeli 
168586039bd3SAndrea Arcangeli 	skip:
168686039bd3SAndrea Arcangeli 		prev = vma;
168786039bd3SAndrea Arcangeli 		start = vma->vm_end;
168869dbe6daSLiam R. Howlett 		vma = mas_next(&mas, end - 1);
168969dbe6daSLiam R. Howlett 	} while (vma);
169086039bd3SAndrea Arcangeli out_unlock:
1691d8ed45c5SMichel Lespinasse 	mmap_write_unlock(mm);
1692d2005e3fSOleg Nesterov 	mmput(mm);
169386039bd3SAndrea Arcangeli out:
169486039bd3SAndrea Arcangeli 	return ret;
169586039bd3SAndrea Arcangeli }
169686039bd3SAndrea Arcangeli 
169786039bd3SAndrea Arcangeli /*
1698ba85c702SAndrea Arcangeli  * userfaultfd_wake may be used in combination with the
1699ba85c702SAndrea Arcangeli  * UFFDIO_*_MODE_DONTWAKE to wakeup userfaults in batches.
170086039bd3SAndrea Arcangeli  */
170186039bd3SAndrea Arcangeli static int userfaultfd_wake(struct userfaultfd_ctx *ctx,
170286039bd3SAndrea Arcangeli 			    unsigned long arg)
170386039bd3SAndrea Arcangeli {
170486039bd3SAndrea Arcangeli 	int ret;
170586039bd3SAndrea Arcangeli 	struct uffdio_range uffdio_wake;
170686039bd3SAndrea Arcangeli 	struct userfaultfd_wake_range range;
170786039bd3SAndrea Arcangeli 	const void __user *buf = (void __user *)arg;
170886039bd3SAndrea Arcangeli 
170986039bd3SAndrea Arcangeli 	ret = -EFAULT;
171086039bd3SAndrea Arcangeli 	if (copy_from_user(&uffdio_wake, buf, sizeof(uffdio_wake)))
171186039bd3SAndrea Arcangeli 		goto out;
171286039bd3SAndrea Arcangeli 
1713e71e2aceSPeter Collingbourne 	ret = validate_range(ctx->mm, uffdio_wake.start, uffdio_wake.len);
171486039bd3SAndrea Arcangeli 	if (ret)
171586039bd3SAndrea Arcangeli 		goto out;
171686039bd3SAndrea Arcangeli 
171786039bd3SAndrea Arcangeli 	range.start = uffdio_wake.start;
171886039bd3SAndrea Arcangeli 	range.len = uffdio_wake.len;
171986039bd3SAndrea Arcangeli 
172086039bd3SAndrea Arcangeli 	/*
172186039bd3SAndrea Arcangeli 	 * len == 0 means wake all and we don't want to wake all here,
172286039bd3SAndrea Arcangeli 	 * so check it again to be sure.
172386039bd3SAndrea Arcangeli 	 */
172486039bd3SAndrea Arcangeli 	VM_BUG_ON(!range.len);
172586039bd3SAndrea Arcangeli 
172686039bd3SAndrea Arcangeli 	wake_userfault(ctx, &range);
172786039bd3SAndrea Arcangeli 	ret = 0;
172886039bd3SAndrea Arcangeli 
172986039bd3SAndrea Arcangeli out:
173086039bd3SAndrea Arcangeli 	return ret;
173186039bd3SAndrea Arcangeli }
173286039bd3SAndrea Arcangeli 
1733ad465caeSAndrea Arcangeli static int userfaultfd_copy(struct userfaultfd_ctx *ctx,
1734ad465caeSAndrea Arcangeli 			    unsigned long arg)
1735ad465caeSAndrea Arcangeli {
1736ad465caeSAndrea Arcangeli 	__s64 ret;
1737ad465caeSAndrea Arcangeli 	struct uffdio_copy uffdio_copy;
1738ad465caeSAndrea Arcangeli 	struct uffdio_copy __user *user_uffdio_copy;
1739ad465caeSAndrea Arcangeli 	struct userfaultfd_wake_range range;
1740ad465caeSAndrea Arcangeli 
1741ad465caeSAndrea Arcangeli 	user_uffdio_copy = (struct uffdio_copy __user *) arg;
1742ad465caeSAndrea Arcangeli 
1743df2cc96eSMike Rapoport 	ret = -EAGAIN;
1744a759a909SNadav Amit 	if (atomic_read(&ctx->mmap_changing))
1745df2cc96eSMike Rapoport 		goto out;
1746df2cc96eSMike Rapoport 
1747ad465caeSAndrea Arcangeli 	ret = -EFAULT;
1748ad465caeSAndrea Arcangeli 	if (copy_from_user(&uffdio_copy, user_uffdio_copy,
1749ad465caeSAndrea Arcangeli 			   /* don't copy "copy" last field */
1750ad465caeSAndrea Arcangeli 			   sizeof(uffdio_copy)-sizeof(__s64)))
1751ad465caeSAndrea Arcangeli 		goto out;
1752ad465caeSAndrea Arcangeli 
1753e71e2aceSPeter Collingbourne 	ret = validate_range(ctx->mm, uffdio_copy.dst, uffdio_copy.len);
1754ad465caeSAndrea Arcangeli 	if (ret)
1755ad465caeSAndrea Arcangeli 		goto out;
1756ad465caeSAndrea Arcangeli 	/*
1757ad465caeSAndrea Arcangeli 	 * double check for wraparound just in case. copy_from_user()
1758ad465caeSAndrea Arcangeli 	 * will later check uffdio_copy.src + uffdio_copy.len to fit
1759ad465caeSAndrea Arcangeli 	 * in the userland range.
1760ad465caeSAndrea Arcangeli 	 */
1761ad465caeSAndrea Arcangeli 	ret = -EINVAL;
1762ad465caeSAndrea Arcangeli 	if (uffdio_copy.src + uffdio_copy.len <= uffdio_copy.src)
1763ad465caeSAndrea Arcangeli 		goto out;
176472981e0eSAndrea Arcangeli 	if (uffdio_copy.mode & ~(UFFDIO_COPY_MODE_DONTWAKE|UFFDIO_COPY_MODE_WP))
1765ad465caeSAndrea Arcangeli 		goto out;
1766d2005e3fSOleg Nesterov 	if (mmget_not_zero(ctx->mm)) {
1767ad465caeSAndrea Arcangeli 		ret = mcopy_atomic(ctx->mm, uffdio_copy.dst, uffdio_copy.src,
176872981e0eSAndrea Arcangeli 				   uffdio_copy.len, &ctx->mmap_changing,
176972981e0eSAndrea Arcangeli 				   uffdio_copy.mode);
1770d2005e3fSOleg Nesterov 		mmput(ctx->mm);
177196333187SMike Rapoport 	} else {
1772e86b298bSMike Rapoport 		return -ESRCH;
1773d2005e3fSOleg Nesterov 	}
1774ad465caeSAndrea Arcangeli 	if (unlikely(put_user(ret, &user_uffdio_copy->copy)))
1775ad465caeSAndrea Arcangeli 		return -EFAULT;
1776ad465caeSAndrea Arcangeli 	if (ret < 0)
1777ad465caeSAndrea Arcangeli 		goto out;
1778ad465caeSAndrea Arcangeli 	BUG_ON(!ret);
1779ad465caeSAndrea Arcangeli 	/* len == 0 would wake all */
1780ad465caeSAndrea Arcangeli 	range.len = ret;
1781ad465caeSAndrea Arcangeli 	if (!(uffdio_copy.mode & UFFDIO_COPY_MODE_DONTWAKE)) {
1782ad465caeSAndrea Arcangeli 		range.start = uffdio_copy.dst;
1783ad465caeSAndrea Arcangeli 		wake_userfault(ctx, &range);
1784ad465caeSAndrea Arcangeli 	}
1785ad465caeSAndrea Arcangeli 	ret = range.len == uffdio_copy.len ? 0 : -EAGAIN;
1786ad465caeSAndrea Arcangeli out:
1787ad465caeSAndrea Arcangeli 	return ret;
1788ad465caeSAndrea Arcangeli }
1789ad465caeSAndrea Arcangeli 
1790ad465caeSAndrea Arcangeli static int userfaultfd_zeropage(struct userfaultfd_ctx *ctx,
1791ad465caeSAndrea Arcangeli 				unsigned long arg)
1792ad465caeSAndrea Arcangeli {
1793ad465caeSAndrea Arcangeli 	__s64 ret;
1794ad465caeSAndrea Arcangeli 	struct uffdio_zeropage uffdio_zeropage;
1795ad465caeSAndrea Arcangeli 	struct uffdio_zeropage __user *user_uffdio_zeropage;
1796ad465caeSAndrea Arcangeli 	struct userfaultfd_wake_range range;
1797ad465caeSAndrea Arcangeli 
1798ad465caeSAndrea Arcangeli 	user_uffdio_zeropage = (struct uffdio_zeropage __user *) arg;
1799ad465caeSAndrea Arcangeli 
1800df2cc96eSMike Rapoport 	ret = -EAGAIN;
1801a759a909SNadav Amit 	if (atomic_read(&ctx->mmap_changing))
1802df2cc96eSMike Rapoport 		goto out;
1803df2cc96eSMike Rapoport 
1804ad465caeSAndrea Arcangeli 	ret = -EFAULT;
1805ad465caeSAndrea Arcangeli 	if (copy_from_user(&uffdio_zeropage, user_uffdio_zeropage,
1806ad465caeSAndrea Arcangeli 			   /* don't copy "zeropage" last field */
1807ad465caeSAndrea Arcangeli 			   sizeof(uffdio_zeropage)-sizeof(__s64)))
1808ad465caeSAndrea Arcangeli 		goto out;
1809ad465caeSAndrea Arcangeli 
1810e71e2aceSPeter Collingbourne 	ret = validate_range(ctx->mm, uffdio_zeropage.range.start,
1811ad465caeSAndrea Arcangeli 			     uffdio_zeropage.range.len);
1812ad465caeSAndrea Arcangeli 	if (ret)
1813ad465caeSAndrea Arcangeli 		goto out;
1814ad465caeSAndrea Arcangeli 	ret = -EINVAL;
1815ad465caeSAndrea Arcangeli 	if (uffdio_zeropage.mode & ~UFFDIO_ZEROPAGE_MODE_DONTWAKE)
1816ad465caeSAndrea Arcangeli 		goto out;
1817ad465caeSAndrea Arcangeli 
1818d2005e3fSOleg Nesterov 	if (mmget_not_zero(ctx->mm)) {
1819ad465caeSAndrea Arcangeli 		ret = mfill_zeropage(ctx->mm, uffdio_zeropage.range.start,
1820df2cc96eSMike Rapoport 				     uffdio_zeropage.range.len,
1821df2cc96eSMike Rapoport 				     &ctx->mmap_changing);
1822d2005e3fSOleg Nesterov 		mmput(ctx->mm);
18239d95aa4bSMike Rapoport 	} else {
1824e86b298bSMike Rapoport 		return -ESRCH;
1825d2005e3fSOleg Nesterov 	}
1826ad465caeSAndrea Arcangeli 	if (unlikely(put_user(ret, &user_uffdio_zeropage->zeropage)))
1827ad465caeSAndrea Arcangeli 		return -EFAULT;
1828ad465caeSAndrea Arcangeli 	if (ret < 0)
1829ad465caeSAndrea Arcangeli 		goto out;
1830ad465caeSAndrea Arcangeli 	/* len == 0 would wake all */
1831ad465caeSAndrea Arcangeli 	BUG_ON(!ret);
1832ad465caeSAndrea Arcangeli 	range.len = ret;
1833ad465caeSAndrea Arcangeli 	if (!(uffdio_zeropage.mode & UFFDIO_ZEROPAGE_MODE_DONTWAKE)) {
1834ad465caeSAndrea Arcangeli 		range.start = uffdio_zeropage.range.start;
1835ad465caeSAndrea Arcangeli 		wake_userfault(ctx, &range);
1836ad465caeSAndrea Arcangeli 	}
1837ad465caeSAndrea Arcangeli 	ret = range.len == uffdio_zeropage.range.len ? 0 : -EAGAIN;
1838ad465caeSAndrea Arcangeli out:
1839ad465caeSAndrea Arcangeli 	return ret;
1840ad465caeSAndrea Arcangeli }
1841ad465caeSAndrea Arcangeli 
184263b2d417SAndrea Arcangeli static int userfaultfd_writeprotect(struct userfaultfd_ctx *ctx,
184363b2d417SAndrea Arcangeli 				    unsigned long arg)
184463b2d417SAndrea Arcangeli {
184563b2d417SAndrea Arcangeli 	int ret;
184663b2d417SAndrea Arcangeli 	struct uffdio_writeprotect uffdio_wp;
184763b2d417SAndrea Arcangeli 	struct uffdio_writeprotect __user *user_uffdio_wp;
184863b2d417SAndrea Arcangeli 	struct userfaultfd_wake_range range;
184923080e27SPeter Xu 	bool mode_wp, mode_dontwake;
185063b2d417SAndrea Arcangeli 
1851a759a909SNadav Amit 	if (atomic_read(&ctx->mmap_changing))
185263b2d417SAndrea Arcangeli 		return -EAGAIN;
185363b2d417SAndrea Arcangeli 
185463b2d417SAndrea Arcangeli 	user_uffdio_wp = (struct uffdio_writeprotect __user *) arg;
185563b2d417SAndrea Arcangeli 
185663b2d417SAndrea Arcangeli 	if (copy_from_user(&uffdio_wp, user_uffdio_wp,
185763b2d417SAndrea Arcangeli 			   sizeof(struct uffdio_writeprotect)))
185863b2d417SAndrea Arcangeli 		return -EFAULT;
185963b2d417SAndrea Arcangeli 
1860e71e2aceSPeter Collingbourne 	ret = validate_range(ctx->mm, uffdio_wp.range.start,
186163b2d417SAndrea Arcangeli 			     uffdio_wp.range.len);
186263b2d417SAndrea Arcangeli 	if (ret)
186363b2d417SAndrea Arcangeli 		return ret;
186463b2d417SAndrea Arcangeli 
186563b2d417SAndrea Arcangeli 	if (uffdio_wp.mode & ~(UFFDIO_WRITEPROTECT_MODE_DONTWAKE |
186663b2d417SAndrea Arcangeli 			       UFFDIO_WRITEPROTECT_MODE_WP))
186763b2d417SAndrea Arcangeli 		return -EINVAL;
186823080e27SPeter Xu 
186923080e27SPeter Xu 	mode_wp = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_WP;
187023080e27SPeter Xu 	mode_dontwake = uffdio_wp.mode & UFFDIO_WRITEPROTECT_MODE_DONTWAKE;
187123080e27SPeter Xu 
187223080e27SPeter Xu 	if (mode_wp && mode_dontwake)
187363b2d417SAndrea Arcangeli 		return -EINVAL;
187463b2d417SAndrea Arcangeli 
1875cb185d5fSNadav Amit 	if (mmget_not_zero(ctx->mm)) {
187663b2d417SAndrea Arcangeli 		ret = mwriteprotect_range(ctx->mm, uffdio_wp.range.start,
187723080e27SPeter Xu 					  uffdio_wp.range.len, mode_wp,
187863b2d417SAndrea Arcangeli 					  &ctx->mmap_changing);
1879cb185d5fSNadav Amit 		mmput(ctx->mm);
1880cb185d5fSNadav Amit 	} else {
1881cb185d5fSNadav Amit 		return -ESRCH;
1882cb185d5fSNadav Amit 	}
1883cb185d5fSNadav Amit 
188463b2d417SAndrea Arcangeli 	if (ret)
188563b2d417SAndrea Arcangeli 		return ret;
188663b2d417SAndrea Arcangeli 
188723080e27SPeter Xu 	if (!mode_wp && !mode_dontwake) {
188863b2d417SAndrea Arcangeli 		range.start = uffdio_wp.range.start;
188963b2d417SAndrea Arcangeli 		range.len = uffdio_wp.range.len;
189063b2d417SAndrea Arcangeli 		wake_userfault(ctx, &range);
189163b2d417SAndrea Arcangeli 	}
189263b2d417SAndrea Arcangeli 	return ret;
189363b2d417SAndrea Arcangeli }
189463b2d417SAndrea Arcangeli 
1895f6191471SAxel Rasmussen static int userfaultfd_continue(struct userfaultfd_ctx *ctx, unsigned long arg)
1896f6191471SAxel Rasmussen {
1897f6191471SAxel Rasmussen 	__s64 ret;
1898f6191471SAxel Rasmussen 	struct uffdio_continue uffdio_continue;
1899f6191471SAxel Rasmussen 	struct uffdio_continue __user *user_uffdio_continue;
1900f6191471SAxel Rasmussen 	struct userfaultfd_wake_range range;
1901f6191471SAxel Rasmussen 
1902f6191471SAxel Rasmussen 	user_uffdio_continue = (struct uffdio_continue __user *)arg;
1903f6191471SAxel Rasmussen 
1904f6191471SAxel Rasmussen 	ret = -EAGAIN;
1905a759a909SNadav Amit 	if (atomic_read(&ctx->mmap_changing))
1906f6191471SAxel Rasmussen 		goto out;
1907f6191471SAxel Rasmussen 
1908f6191471SAxel Rasmussen 	ret = -EFAULT;
1909f6191471SAxel Rasmussen 	if (copy_from_user(&uffdio_continue, user_uffdio_continue,
1910f6191471SAxel Rasmussen 			   /* don't copy the output fields */
1911f6191471SAxel Rasmussen 			   sizeof(uffdio_continue) - (sizeof(__s64))))
1912f6191471SAxel Rasmussen 		goto out;
1913f6191471SAxel Rasmussen 
1914e71e2aceSPeter Collingbourne 	ret = validate_range(ctx->mm, uffdio_continue.range.start,
1915f6191471SAxel Rasmussen 			     uffdio_continue.range.len);
1916f6191471SAxel Rasmussen 	if (ret)
1917f6191471SAxel Rasmussen 		goto out;
1918f6191471SAxel Rasmussen 
1919f6191471SAxel Rasmussen 	ret = -EINVAL;
1920f6191471SAxel Rasmussen 	/* double check for wraparound just in case. */
1921f6191471SAxel Rasmussen 	if (uffdio_continue.range.start + uffdio_continue.range.len <=
1922f6191471SAxel Rasmussen 	    uffdio_continue.range.start) {
1923f6191471SAxel Rasmussen 		goto out;
1924f6191471SAxel Rasmussen 	}
1925f6191471SAxel Rasmussen 	if (uffdio_continue.mode & ~UFFDIO_CONTINUE_MODE_DONTWAKE)
1926f6191471SAxel Rasmussen 		goto out;
1927f6191471SAxel Rasmussen 
1928f6191471SAxel Rasmussen 	if (mmget_not_zero(ctx->mm)) {
1929f6191471SAxel Rasmussen 		ret = mcopy_continue(ctx->mm, uffdio_continue.range.start,
1930f6191471SAxel Rasmussen 				     uffdio_continue.range.len,
1931f6191471SAxel Rasmussen 				     &ctx->mmap_changing);
1932f6191471SAxel Rasmussen 		mmput(ctx->mm);
1933f6191471SAxel Rasmussen 	} else {
1934f6191471SAxel Rasmussen 		return -ESRCH;
1935f6191471SAxel Rasmussen 	}
1936f6191471SAxel Rasmussen 
1937f6191471SAxel Rasmussen 	if (unlikely(put_user(ret, &user_uffdio_continue->mapped)))
1938f6191471SAxel Rasmussen 		return -EFAULT;
1939f6191471SAxel Rasmussen 	if (ret < 0)
1940f6191471SAxel Rasmussen 		goto out;
1941f6191471SAxel Rasmussen 
1942f6191471SAxel Rasmussen 	/* len == 0 would wake all */
1943f6191471SAxel Rasmussen 	BUG_ON(!ret);
1944f6191471SAxel Rasmussen 	range.len = ret;
1945f6191471SAxel Rasmussen 	if (!(uffdio_continue.mode & UFFDIO_CONTINUE_MODE_DONTWAKE)) {
1946f6191471SAxel Rasmussen 		range.start = uffdio_continue.range.start;
1947f6191471SAxel Rasmussen 		wake_userfault(ctx, &range);
1948f6191471SAxel Rasmussen 	}
1949f6191471SAxel Rasmussen 	ret = range.len == uffdio_continue.range.len ? 0 : -EAGAIN;
1950f6191471SAxel Rasmussen 
1951f6191471SAxel Rasmussen out:
1952f6191471SAxel Rasmussen 	return ret;
1953f6191471SAxel Rasmussen }
1954f6191471SAxel Rasmussen 
19559cd75c3cSPavel Emelyanov static inline unsigned int uffd_ctx_features(__u64 user_features)
19569cd75c3cSPavel Emelyanov {
19579cd75c3cSPavel Emelyanov 	/*
195822e5fe2aSNadav Amit 	 * For the current set of features the bits just coincide. Set
195922e5fe2aSNadav Amit 	 * UFFD_FEATURE_INITIALIZED to mark the features as enabled.
19609cd75c3cSPavel Emelyanov 	 */
196122e5fe2aSNadav Amit 	return (unsigned int)user_features | UFFD_FEATURE_INITIALIZED;
19629cd75c3cSPavel Emelyanov }
19639cd75c3cSPavel Emelyanov 
196486039bd3SAndrea Arcangeli /*
196586039bd3SAndrea Arcangeli  * userland asks for a certain API version and we return which bits
196686039bd3SAndrea Arcangeli  * and ioctl commands are implemented in this kernel for such API
196786039bd3SAndrea Arcangeli  * version or -EINVAL if unknown.
196886039bd3SAndrea Arcangeli  */
196986039bd3SAndrea Arcangeli static int userfaultfd_api(struct userfaultfd_ctx *ctx,
197086039bd3SAndrea Arcangeli 			   unsigned long arg)
197186039bd3SAndrea Arcangeli {
197286039bd3SAndrea Arcangeli 	struct uffdio_api uffdio_api;
197386039bd3SAndrea Arcangeli 	void __user *buf = (void __user *)arg;
197422e5fe2aSNadav Amit 	unsigned int ctx_features;
197586039bd3SAndrea Arcangeli 	int ret;
197665603144SAndrea Arcangeli 	__u64 features;
197786039bd3SAndrea Arcangeli 
197886039bd3SAndrea Arcangeli 	ret = -EFAULT;
1979a9b85f94SAndrea Arcangeli 	if (copy_from_user(&uffdio_api, buf, sizeof(uffdio_api)))
198086039bd3SAndrea Arcangeli 		goto out;
1981914eedcbSAxel Rasmussen 	/* Ignore unsupported features (userspace built against newer kernel) */
1982914eedcbSAxel Rasmussen 	features = uffdio_api.features & UFFD_API_FEATURES;
19833c1c24d9SMike Rapoport 	ret = -EPERM;
19843c1c24d9SMike Rapoport 	if ((features & UFFD_FEATURE_EVENT_FORK) && !capable(CAP_SYS_PTRACE))
19853c1c24d9SMike Rapoport 		goto err_out;
198665603144SAndrea Arcangeli 	/* report all available features and ioctls to userland */
198765603144SAndrea Arcangeli 	uffdio_api.features = UFFD_API_FEATURES;
19887677f7fdSAxel Rasmussen #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_MINOR
1989964ab004SAxel Rasmussen 	uffdio_api.features &=
1990964ab004SAxel Rasmussen 		~(UFFD_FEATURE_MINOR_HUGETLBFS | UFFD_FEATURE_MINOR_SHMEM);
19917677f7fdSAxel Rasmussen #endif
199200b151f2SPeter Xu #ifndef CONFIG_HAVE_ARCH_USERFAULTFD_WP
199300b151f2SPeter Xu 	uffdio_api.features &= ~UFFD_FEATURE_PAGEFAULT_FLAG_WP;
199486039bd3SAndrea Arcangeli #endif
1995b1f9e876SPeter Xu #ifndef CONFIG_PTE_MARKER_UFFD_WP
1996b1f9e876SPeter Xu 	uffdio_api.features &= ~UFFD_FEATURE_WP_HUGETLBFS_SHMEM;
1997b1f9e876SPeter Xu #endif
199886039bd3SAndrea Arcangeli 	uffdio_api.ioctls = UFFD_API_IOCTLS;
199986039bd3SAndrea Arcangeli 	ret = -EFAULT;
200086039bd3SAndrea Arcangeli 	if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
200186039bd3SAndrea Arcangeli 		goto out;
200222e5fe2aSNadav Amit 
200386039bd3SAndrea Arcangeli 	/* only enable the requested features for this uffd context */
200422e5fe2aSNadav Amit 	ctx_features = uffd_ctx_features(features);
200522e5fe2aSNadav Amit 	ret = -EINVAL;
200622e5fe2aSNadav Amit 	if (cmpxchg(&ctx->features, 0, ctx_features) != 0)
200722e5fe2aSNadav Amit 		goto err_out;
200822e5fe2aSNadav Amit 
200986039bd3SAndrea Arcangeli 	ret = 0;
201086039bd3SAndrea Arcangeli out:
201186039bd3SAndrea Arcangeli 	return ret;
201286039bd3SAndrea Arcangeli err_out:
201386039bd3SAndrea Arcangeli 	memset(&uffdio_api, 0, sizeof(uffdio_api));
201486039bd3SAndrea Arcangeli 	if (copy_to_user(buf, &uffdio_api, sizeof(uffdio_api)))
201586039bd3SAndrea Arcangeli 		ret = -EFAULT;
201686039bd3SAndrea Arcangeli 	goto out;
201786039bd3SAndrea Arcangeli }
201886039bd3SAndrea Arcangeli 
201986039bd3SAndrea Arcangeli static long userfaultfd_ioctl(struct file *file, unsigned cmd,
2020e6485a47SAndrea Arcangeli 			      unsigned long arg)
2021e6485a47SAndrea Arcangeli {
2022e6485a47SAndrea Arcangeli 	int ret = -EINVAL;
202386039bd3SAndrea Arcangeli 	struct userfaultfd_ctx *ctx = file->private_data;
202486039bd3SAndrea Arcangeli 
202522e5fe2aSNadav Amit 	if (cmd != UFFDIO_API && !userfaultfd_is_initialized(ctx))
202686039bd3SAndrea Arcangeli 		return -EINVAL;
202786039bd3SAndrea Arcangeli 
202886039bd3SAndrea Arcangeli 	switch(cmd) {
202986039bd3SAndrea Arcangeli 	case UFFDIO_API:
203086039bd3SAndrea Arcangeli 		ret = userfaultfd_api(ctx, arg);
203186039bd3SAndrea Arcangeli 		break;
203286039bd3SAndrea Arcangeli 	case UFFDIO_REGISTER:
203386039bd3SAndrea Arcangeli 		ret = userfaultfd_register(ctx, arg);
203486039bd3SAndrea Arcangeli 		break;
203586039bd3SAndrea Arcangeli 	case UFFDIO_UNREGISTER:
203686039bd3SAndrea Arcangeli 		ret = userfaultfd_unregister(ctx, arg);
203786039bd3SAndrea Arcangeli 		break;
203886039bd3SAndrea Arcangeli 	case UFFDIO_WAKE:
2039ad465caeSAndrea Arcangeli 		ret = userfaultfd_wake(ctx, arg);
2040ad465caeSAndrea Arcangeli 		break;
2041ad465caeSAndrea Arcangeli 	case UFFDIO_COPY:
2042ad465caeSAndrea Arcangeli 		ret = userfaultfd_copy(ctx, arg);
2043ad465caeSAndrea Arcangeli 		break;
2044ad465caeSAndrea Arcangeli 	case UFFDIO_ZEROPAGE:
204586039bd3SAndrea Arcangeli 		ret = userfaultfd_zeropage(ctx, arg);
204686039bd3SAndrea Arcangeli 		break;
204763b2d417SAndrea Arcangeli 	case UFFDIO_WRITEPROTECT:
204863b2d417SAndrea Arcangeli 		ret = userfaultfd_writeprotect(ctx, arg);
204963b2d417SAndrea Arcangeli 		break;
2050f6191471SAxel Rasmussen 	case UFFDIO_CONTINUE:
2051f6191471SAxel Rasmussen 		ret = userfaultfd_continue(ctx, arg);
2052f6191471SAxel Rasmussen 		break;
205386039bd3SAndrea Arcangeli 	}
205486039bd3SAndrea Arcangeli 	return ret;
205586039bd3SAndrea Arcangeli }
205686039bd3SAndrea Arcangeli 
205786039bd3SAndrea Arcangeli #ifdef CONFIG_PROC_FS
205886039bd3SAndrea Arcangeli static void userfaultfd_show_fdinfo(struct seq_file *m, struct file *f)
205986039bd3SAndrea Arcangeli {
206086039bd3SAndrea Arcangeli 	struct userfaultfd_ctx *ctx = f->private_data;
2061ac6424b9SIngo Molnar 	wait_queue_entry_t *wq;
206286039bd3SAndrea Arcangeli 	unsigned long pending = 0, total = 0;
206386039bd3SAndrea Arcangeli 
2064cbcfa130SEric Biggers 	spin_lock_irq(&ctx->fault_pending_wqh.lock);
20652055da97SIngo Molnar 	list_for_each_entry(wq, &ctx->fault_pending_wqh.head, entry) {
206686039bd3SAndrea Arcangeli 		pending++;
206786039bd3SAndrea Arcangeli 		total++;
206886039bd3SAndrea Arcangeli 	}
20692055da97SIngo Molnar 	list_for_each_entry(wq, &ctx->fault_wqh.head, entry) {
207015b726efSAndrea Arcangeli 		total++;
207115b726efSAndrea Arcangeli 	}
2072cbcfa130SEric Biggers 	spin_unlock_irq(&ctx->fault_pending_wqh.lock);
207386039bd3SAndrea Arcangeli 
207486039bd3SAndrea Arcangeli 	/*
207586039bd3SAndrea Arcangeli 	 * If more protocols will be added, there will be all shown
207686039bd3SAndrea Arcangeli 	 * separated by a space. Like this:
207786039bd3SAndrea Arcangeli 	 *	protocols: aa:... bb:...
207886039bd3SAndrea Arcangeli 	 */
207986039bd3SAndrea Arcangeli 	seq_printf(m, "pending:\t%lu\ntotal:\t%lu\nAPI:\t%Lx:%x:%Lx\n",
2080045098e9SMike Rapoport 		   pending, total, UFFD_API, ctx->features,
208186039bd3SAndrea Arcangeli 		   UFFD_API_IOCTLS|UFFD_API_RANGE_IOCTLS);
208286039bd3SAndrea Arcangeli }
208386039bd3SAndrea Arcangeli #endif
208486039bd3SAndrea Arcangeli 
208586039bd3SAndrea Arcangeli static const struct file_operations userfaultfd_fops = {
208686039bd3SAndrea Arcangeli #ifdef CONFIG_PROC_FS
208786039bd3SAndrea Arcangeli 	.show_fdinfo	= userfaultfd_show_fdinfo,
208886039bd3SAndrea Arcangeli #endif
208986039bd3SAndrea Arcangeli 	.release	= userfaultfd_release,
209086039bd3SAndrea Arcangeli 	.poll		= userfaultfd_poll,
209186039bd3SAndrea Arcangeli 	.read		= userfaultfd_read,
209286039bd3SAndrea Arcangeli 	.unlocked_ioctl = userfaultfd_ioctl,
20931832f2d8SArnd Bergmann 	.compat_ioctl	= compat_ptr_ioctl,
209486039bd3SAndrea Arcangeli 	.llseek		= noop_llseek,
209586039bd3SAndrea Arcangeli };
209686039bd3SAndrea Arcangeli 
20973004ec9cSAndrea Arcangeli static void init_once_userfaultfd_ctx(void *mem)
20983004ec9cSAndrea Arcangeli {
20993004ec9cSAndrea Arcangeli 	struct userfaultfd_ctx *ctx = (struct userfaultfd_ctx *) mem;
21003004ec9cSAndrea Arcangeli 
21013004ec9cSAndrea Arcangeli 	init_waitqueue_head(&ctx->fault_pending_wqh);
21023004ec9cSAndrea Arcangeli 	init_waitqueue_head(&ctx->fault_wqh);
21039cd75c3cSPavel Emelyanov 	init_waitqueue_head(&ctx->event_wqh);
21043004ec9cSAndrea Arcangeli 	init_waitqueue_head(&ctx->fd_wqh);
21052ca97ac8SAhmed S. Darwish 	seqcount_spinlock_init(&ctx->refile_seq, &ctx->fault_pending_wqh.lock);
21063004ec9cSAndrea Arcangeli }
21073004ec9cSAndrea Arcangeli 
21082d5de004SAxel Rasmussen static int new_userfaultfd(int flags)
210986039bd3SAndrea Arcangeli {
211086039bd3SAndrea Arcangeli 	struct userfaultfd_ctx *ctx;
2111284cd241SEric Biggers 	int fd;
211286039bd3SAndrea Arcangeli 
211386039bd3SAndrea Arcangeli 	BUG_ON(!current->mm);
211486039bd3SAndrea Arcangeli 
211586039bd3SAndrea Arcangeli 	/* Check the UFFD_* constants for consistency.  */
211637cd0575SLokesh Gidra 	BUILD_BUG_ON(UFFD_USER_MODE_ONLY & UFFD_SHARED_FCNTL_FLAGS);
211786039bd3SAndrea Arcangeli 	BUILD_BUG_ON(UFFD_CLOEXEC != O_CLOEXEC);
211886039bd3SAndrea Arcangeli 	BUILD_BUG_ON(UFFD_NONBLOCK != O_NONBLOCK);
211986039bd3SAndrea Arcangeli 
212037cd0575SLokesh Gidra 	if (flags & ~(UFFD_SHARED_FCNTL_FLAGS | UFFD_USER_MODE_ONLY))
2121284cd241SEric Biggers 		return -EINVAL;
212286039bd3SAndrea Arcangeli 
21233004ec9cSAndrea Arcangeli 	ctx = kmem_cache_alloc(userfaultfd_ctx_cachep, GFP_KERNEL);
212486039bd3SAndrea Arcangeli 	if (!ctx)
2125284cd241SEric Biggers 		return -ENOMEM;
212686039bd3SAndrea Arcangeli 
2127ca880420SEric Biggers 	refcount_set(&ctx->refcount, 1);
212886039bd3SAndrea Arcangeli 	ctx->flags = flags;
21299cd75c3cSPavel Emelyanov 	ctx->features = 0;
213086039bd3SAndrea Arcangeli 	ctx->released = false;
2131a759a909SNadav Amit 	atomic_set(&ctx->mmap_changing, 0);
213286039bd3SAndrea Arcangeli 	ctx->mm = current->mm;
213386039bd3SAndrea Arcangeli 	/* prevent the mm struct to be freed */
2134f1f10076SVegard Nossum 	mmgrab(ctx->mm);
213586039bd3SAndrea Arcangeli 
2136b537900fSDaniel Colascione 	fd = anon_inode_getfd_secure("[userfaultfd]", &userfaultfd_fops, ctx,
2137abec3d01SOndrej Mosnacek 			O_RDONLY | (flags & UFFD_SHARED_FCNTL_FLAGS), NULL);
2138284cd241SEric Biggers 	if (fd < 0) {
2139d2005e3fSOleg Nesterov 		mmdrop(ctx->mm);
21403004ec9cSAndrea Arcangeli 		kmem_cache_free(userfaultfd_ctx_cachep, ctx);
2141c03e946fSEric Biggers 	}
214286039bd3SAndrea Arcangeli 	return fd;
214386039bd3SAndrea Arcangeli }
21443004ec9cSAndrea Arcangeli 
21452d5de004SAxel Rasmussen static inline bool userfaultfd_syscall_allowed(int flags)
21462d5de004SAxel Rasmussen {
21472d5de004SAxel Rasmussen 	/* Userspace-only page faults are always allowed */
21482d5de004SAxel Rasmussen 	if (flags & UFFD_USER_MODE_ONLY)
21492d5de004SAxel Rasmussen 		return true;
21502d5de004SAxel Rasmussen 
21512d5de004SAxel Rasmussen 	/*
21522d5de004SAxel Rasmussen 	 * The user is requesting a userfaultfd which can handle kernel faults.
21532d5de004SAxel Rasmussen 	 * Privileged users are always allowed to do this.
21542d5de004SAxel Rasmussen 	 */
21552d5de004SAxel Rasmussen 	if (capable(CAP_SYS_PTRACE))
21562d5de004SAxel Rasmussen 		return true;
21572d5de004SAxel Rasmussen 
21582d5de004SAxel Rasmussen 	/* Otherwise, access to kernel fault handling is sysctl controlled. */
21592d5de004SAxel Rasmussen 	return sysctl_unprivileged_userfaultfd;
21602d5de004SAxel Rasmussen }
21612d5de004SAxel Rasmussen 
21622d5de004SAxel Rasmussen SYSCALL_DEFINE1(userfaultfd, int, flags)
21632d5de004SAxel Rasmussen {
21642d5de004SAxel Rasmussen 	if (!userfaultfd_syscall_allowed(flags))
21652d5de004SAxel Rasmussen 		return -EPERM;
21662d5de004SAxel Rasmussen 
21672d5de004SAxel Rasmussen 	return new_userfaultfd(flags);
21682d5de004SAxel Rasmussen }
21692d5de004SAxel Rasmussen 
21702d5de004SAxel Rasmussen static long userfaultfd_dev_ioctl(struct file *file, unsigned int cmd, unsigned long flags)
21712d5de004SAxel Rasmussen {
21722d5de004SAxel Rasmussen 	if (cmd != USERFAULTFD_IOC_NEW)
21732d5de004SAxel Rasmussen 		return -EINVAL;
21742d5de004SAxel Rasmussen 
21752d5de004SAxel Rasmussen 	return new_userfaultfd(flags);
21762d5de004SAxel Rasmussen }
21772d5de004SAxel Rasmussen 
21782d5de004SAxel Rasmussen static const struct file_operations userfaultfd_dev_fops = {
21792d5de004SAxel Rasmussen 	.unlocked_ioctl = userfaultfd_dev_ioctl,
21802d5de004SAxel Rasmussen 	.compat_ioctl = userfaultfd_dev_ioctl,
21812d5de004SAxel Rasmussen 	.owner = THIS_MODULE,
21822d5de004SAxel Rasmussen 	.llseek = noop_llseek,
21832d5de004SAxel Rasmussen };
21842d5de004SAxel Rasmussen 
21852d5de004SAxel Rasmussen static struct miscdevice userfaultfd_misc = {
21862d5de004SAxel Rasmussen 	.minor = MISC_DYNAMIC_MINOR,
21872d5de004SAxel Rasmussen 	.name = "userfaultfd",
21882d5de004SAxel Rasmussen 	.fops = &userfaultfd_dev_fops
21892d5de004SAxel Rasmussen };
21902d5de004SAxel Rasmussen 
21913004ec9cSAndrea Arcangeli static int __init userfaultfd_init(void)
21923004ec9cSAndrea Arcangeli {
21932d5de004SAxel Rasmussen 	int ret;
21942d5de004SAxel Rasmussen 
21952d5de004SAxel Rasmussen 	ret = misc_register(&userfaultfd_misc);
21962d5de004SAxel Rasmussen 	if (ret)
21972d5de004SAxel Rasmussen 		return ret;
21982d5de004SAxel Rasmussen 
21993004ec9cSAndrea Arcangeli 	userfaultfd_ctx_cachep = kmem_cache_create("userfaultfd_ctx_cache",
22003004ec9cSAndrea Arcangeli 						sizeof(struct userfaultfd_ctx),
22013004ec9cSAndrea Arcangeli 						0,
22023004ec9cSAndrea Arcangeli 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
22033004ec9cSAndrea Arcangeli 						init_once_userfaultfd_ctx);
22043004ec9cSAndrea Arcangeli 	return 0;
22053004ec9cSAndrea Arcangeli }
22063004ec9cSAndrea Arcangeli __initcall(userfaultfd_init);
2207