2202 lines · 55.7 KB · C
RawDownload
// SPDX-License-Identifier: GPL-2.0-only/* *  fs/userfaultfd.c * *  Copyright (C) 2007  Davide Libenzi <davidel@xmailserver.org> *  Copyright (C) 2008-2009 Red Hat, Inc. *  Copyright (C) 2015  Red Hat, Inc. * *  Some part derived from fs/eventfd.c (anon inode setup) and *  mm/ksm.c (mm hashing). */ #include <linux/list.h>#include <linux/hashtable.h>#include <linux/sched/signal.h>#include <linux/sched/mm.h>#include <linux/mm.h>#include <linux/mm_inline.h>#include <linux/mmu_notifier.h>#include <linux/poll.h>#include <linux/slab.h>#include <linux/seq_file.h>#include <linux/file.h>#include <linux/bug.h>#include <linux/anon_inodes.h>#include <linux/syscalls.h>#include <linux/userfaultfd_k.h>#include <linux/mempolicy.h>#include <linux/ioctl.h>#include <linux/security.h>#include <linux/hugetlb.h>#include <linux/swapops.h>#include <linux/miscdevice.h>#include <linux/uio.h> static int sysctl_unprivileged_userfaultfd __read_mostly; #ifdef CONFIG_SYSCTLstatic struct ctl_table vm_userfaultfd_table[] = {	{		.procname	= "unprivileged_userfaultfd",		.data		= &sysctl_unprivileged_userfaultfd,		.maxlen		= sizeof(sysctl_unprivileged_userfaultfd),		.mode		= 0644,		.proc_handler	= proc_dointvec_minmax,		.extra1		= SYSCTL_ZERO,		.extra2		= SYSCTL_ONE,	},};#endif static struct kmem_cache *userfaultfd_ctx_cachep __ro_after_init; struct userfaultfd_fork_ctx {	struct userfaultfd_ctx *orig;	struct userfaultfd_ctx *new;	struct list_head list;}; struct userfaultfd_unmap_ctx {	struct userfaultfd_ctx *ctx;	unsigned long start;	unsigned long end;	struct list_head list;}; struct userfaultfd_wait_queue {	struct uffd_msg msg;	wait_queue_entry_t wq;	struct userfaultfd_ctx *ctx;	bool waken;}; struct userfaultfd_wake_range {	unsigned long start;	unsigned long len;}; /* internal indication that UFFD_API ioctl was successfully executed */#define UFFD_FEATURE_INITIALIZED		(1u << 31) static bool userfaultfd_is_initialized(struct userfaultfd_ctx *ctx){	return ctx->features & UFFD_FEATURE_INITIALIZED;} static bool userfaultfd_wp_async_ctx(struct userfaultfd_ctx *ctx){	return ctx && (ctx->features & UFFD_FEATURE_WP_ASYNC);} /* * Whether WP_UNPOPULATED is enabled on the uffd context.  It is only * meaningful when userfaultfd_wp()==true on the vma and when it's * anonymous. */bool userfaultfd_wp_unpopulated(struct vm_area_struct *vma){	struct userfaultfd_ctx *ctx = vma->vm_userfaultfd_ctx.ctx; 	if (!ctx)		return false; 	return ctx->features & UFFD_FEATURE_WP_UNPOPULATED;} static int userfaultfd_wake_function(wait_queue_entry_t *wq, unsigned mode,				     int wake_flags, void *key){	struct userfaultfd_wake_range *range = key;	int ret;	struct userfaultfd_wait_queue *uwq;	unsigned long start, len; 	uwq = container_of(wq, struct userfaultfd_wait_queue, wq);	ret = 0;	/* len == 0 means wake all */	start = range->start;	len = range->len;	if (len && (start > uwq->msg.arg.pagefault.address ||		    start + len <= uwq->msg.arg.pagefault.address))		goto out;	WRITE_ONCE(uwq->waken, true);	/*	 * The Program-Order guarantees provided by the scheduler	 * ensure uwq->waken is visible before the task is woken.	 */	ret = wake_up_state(wq->private, mode);	if (ret) {		/*		 * Wake only once, autoremove behavior.		 *		 * After the effect of list_del_init is visible to the other		 * CPUs, the waitqueue may disappear from under us, see the		 * !list_empty_careful() in handle_userfault().		 *		 * try_to_wake_up() has an implicit smp_mb(), and the		 * wq->private is read before calling the extern function		 * "wake_up_state" (which in turns calls try_to_wake_up).		 */		list_del_init(&wq->entry);	}out:	return ret;} /** * userfaultfd_ctx_get - Acquires a reference to the internal userfaultfd * context. * @ctx: [in] Pointer to the userfaultfd context. */static void userfaultfd_ctx_get(struct userfaultfd_ctx *ctx){	refcount_inc(&ctx->refcount);} /** * userfaultfd_ctx_put - Releases a reference to the internal userfaultfd * context. * @ctx: [in] Pointer to userfaultfd context. * * The userfaultfd context reference must have been previously acquired either * with userfaultfd_ctx_get() or userfaultfd_ctx_fdget(). */static void userfaultfd_ctx_put(struct userfaultfd_ctx *ctx){	if (refcount_dec_and_test(&ctx->refcount)) {		VM_BUG_ON(spin_is_locked(&ctx->fault_pending_wqh.lock));		VM_BUG_ON(waitqueue_active(&ctx->fault_pending_wqh));		VM_BUG_ON(spin_is_locked(&ctx->fault_wqh.lock));		VM_BUG_ON(waitqueue_active(&ctx->fault_wqh));		VM_BUG_ON(spin_is_locked(&ctx->event_wqh.lock));		VM_BUG_ON(waitqueue_active(&ctx->event_wqh));		VM_BUG_ON(spin_is_locked(&ctx->fd_wqh.lock));		VM_BUG_ON(waitqueue_active(&ctx->fd_wqh));		mmdrop(ctx->mm);		kmem_cache_free(userfaultfd_ctx_cachep, ctx);	}} static inline void msg_init(struct uffd_msg *msg){	BUILD_BUG_ON(sizeof(struct uffd_msg) != 32);	/*	 * Must use memset to zero out the paddings or kernel data is	 * leaked to userland.	 */	memset(msg, 0, sizeof(struct uffd_msg));} static inline struct uffd_msg userfault_msg(unsigned long address,					    unsigned long real_address,					    unsigned int flags,					    unsigned long reason,					    unsigned int features){	struct uffd_msg msg; 	msg_init(&msg);	msg.event = UFFD_EVENT_PAGEFAULT; 	msg.arg.pagefault.address = (features & UFFD_FEATURE_EXACT_ADDRESS) ?				    real_address : address; 	/*	 * These flags indicate why the userfault occurred:	 * - UFFD_PAGEFAULT_FLAG_WP indicates a write protect fault.	 * - UFFD_PAGEFAULT_FLAG_MINOR indicates a minor fault.	 * - Neither of these flags being set indicates a MISSING fault.	 *	 * Separately, UFFD_PAGEFAULT_FLAG_WRITE indicates it was a write	 * fault. Otherwise, it was a read fault.	 */	if (flags & FAULT_FLAG_WRITE)		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WRITE;	if (reason & VM_UFFD_WP)		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_WP;	if (reason & VM_UFFD_MINOR)		msg.arg.pagefault.flags |= UFFD_PAGEFAULT_FLAG_MINOR;	if (features & UFFD_FEATURE_THREAD_ID)		msg.arg.pagefault.feat.ptid = task_pid_vnr(current);	return msg;} #ifdef CONFIG_HUGETLB_PAGE/* * Same functionality as userfaultfd_must_wait below with modifications for * hugepmd ranges. */static inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,					      struct vm_fault *vmf,					      unsigned long reason){	struct vm_area_struct *vma = vmf->vma;	pte_t *ptep, pte;	bool ret = true; 	assert_fault_locked(vmf); 	ptep = hugetlb_walk(vma, vmf->address, vma_mmu_pagesize(vma));	if (!ptep)		goto out; 	ret = false;	pte = huge_ptep_get(vma->vm_mm, vmf->address, ptep); 	/*	 * Lockless access: we're in a wait_event so it's ok if it	 * changes under us.  PTE markers should be handled the same as none	 * ptes here.	 */	if (huge_pte_none_mostly(pte))		ret = true;	if (!huge_pte_write(pte) && (reason & VM_UFFD_WP))		ret = true;out:	return ret;}#elsestatic inline bool userfaultfd_huge_must_wait(struct userfaultfd_ctx *ctx,					      struct vm_fault *vmf,					      unsigned long reason){	return false;	/* should never get here */}#endif /* CONFIG_HUGETLB_PAGE */ /* * Verify the pagetables are still not ok after having reigstered into * the fault_pending_wqh to avoid userland having to UFFDIO_WAKE any * userfault that has already been resolved, if userfaultfd_read_iter and * UFFDIO_COPY|ZEROPAGE are being run simultaneously on two different * threads. */static inline bool userfaultfd_must_wait(struct userfaultfd_ctx *ctx,					 struct vm_fault *vmf,					 unsigned long reason){	struct mm_struct *mm = ctx->mm;	unsigned long address = vmf->address;	pgd_t *pgd;	p4d_t *p4d;	pud_t *pud;	pmd_t *pmd, _pmd;	pte_t *pte;	pte_t ptent;	bool ret = true; 	assert_fault_locked(vmf); 	pgd = pgd_offset(mm, address);	if (!pgd_present(*pgd))		goto out;	p4d = p4d_offset(pgd, address);	if (!p4d_present(*p4d))		goto out;	pud = pud_offset(p4d, address);	if (!pud_present(*pud))		goto out;	pmd = pmd_offset(pud, address);again:	_pmd = pmdp_get_lockless(pmd);	if (pmd_none(_pmd))		goto out; 	ret = false;	if (!pmd_present(_pmd) || pmd_devmap(_pmd))		goto out; 	if (pmd_trans_huge(_pmd)) {		if (!pmd_write(_pmd) && (reason & VM_UFFD_WP))			ret = true;		goto out;	} 	pte = pte_offset_map(pmd, address);	if (!pte) {		ret = true;		goto again;	}	/*	 * Lockless access: we're in a wait_event so it's ok if it	 * changes under us.  PTE markers should be handled the same as none	 * ptes here.	 */	ptent = ptep_get(pte);	if (pte_none_mostly(ptent))		ret = true;	if (!pte_write(ptent) && (reason & VM_UFFD_WP))		ret = true;	pte_unmap(pte); out:	return ret;} static inline unsigned int userfaultfd_get_blocking_state(unsigned int flags){	if (flags & FAULT_FLAG_INTERRUPTIBLE)		return TASK_INTERRUPTIBLE; 	if (flags & FAULT_FLAG_KILLABLE)		return TASK_KILLABLE; 	return TASK_UNINTERRUPTIBLE;} /* * The locking rules involved in returning VM_FAULT_RETRY depending on * FAULT_FLAG_ALLOW_RETRY, FAULT_FLAG_RETRY_NOWAIT and * FAULT_FLAG_KILLABLE are not straightforward. The "Caution" * recommendation in __lock_page_or_retry is not an understatement. * * If FAULT_FLAG_ALLOW_RETRY is set, the mmap_lock must be released * before returning VM_FAULT_RETRY only if FAULT_FLAG_RETRY_NOWAIT is * not set. * * If FAULT_FLAG_ALLOW_RETRY is set but FAULT_FLAG_KILLABLE is not * set, VM_FAULT_RETRY can still be returned if and only if there are * fatal_signal_pending()s, and the mmap_lock must be released before * returning it. */vm_fault_t handle_userfault(struct vm_fault *vmf, unsigned long reason){	struct vm_area_struct *vma = vmf->vma;	struct mm_struct *mm = vma->vm_mm;	struct userfaultfd_ctx *ctx;	struct userfaultfd_wait_queue uwq;	vm_fault_t ret = VM_FAULT_SIGBUS;	bool must_wait;	unsigned int blocking_state; 	/*	 * We don't do userfault handling for the final child pid update	 * and when coredumping (faults triggered by get_dump_page()).	 */	if (current->flags & (PF_EXITING|PF_DUMPCORE))		goto out; 	assert_fault_locked(vmf); 	ctx = vma->vm_userfaultfd_ctx.ctx;	if (!ctx)		goto out; 	BUG_ON(ctx->mm != mm); 	/* Any unrecognized flag is a bug. */	VM_BUG_ON(reason & ~__VM_UFFD_FLAGS);	/* 0 or > 1 flags set is a bug; we expect exactly 1. */	VM_BUG_ON(!reason || (reason & (reason - 1))); 	if (ctx->features & UFFD_FEATURE_SIGBUS)		goto out;	if (!(vmf->flags & FAULT_FLAG_USER) && (ctx->flags & UFFD_USER_MODE_ONLY))		goto out; 	/*	 * If it's already released don't get it. This avoids to loop	 * in __get_user_pages if userfaultfd_release waits on the	 * caller of handle_userfault to release the mmap_lock.	 */	if (unlikely(READ_ONCE(ctx->released))) {		/*		 * Don't return VM_FAULT_SIGBUS in this case, so a non		 * cooperative manager can close the uffd after the		 * last UFFDIO_COPY, without risking to trigger an		 * involuntary SIGBUS if the process was starting the		 * userfaultfd while the userfaultfd was still armed		 * (but after the last UFFDIO_COPY). If the uffd		 * wasn't already closed when the userfault reached		 * this point, that would normally be solved by		 * userfaultfd_must_wait returning 'false'.		 *		 * If we were to return VM_FAULT_SIGBUS here, the non		 * cooperative manager would be instead forced to		 * always call UFFDIO_UNREGISTER before it can safely		 * close the uffd.		 */		ret = VM_FAULT_NOPAGE;		goto out;	} 	/*	 * Check that we can return VM_FAULT_RETRY.	 *	 * NOTE: it should become possible to return VM_FAULT_RETRY	 * even if FAULT_FLAG_TRIED is set without leading to gup()	 * -EBUSY failures, if the userfaultfd is to be extended for	 * VM_UFFD_WP tracking and we intend to arm the userfault	 * without first stopping userland access to the memory. For	 * VM_UFFD_MISSING userfaults this is enough for now.	 */	if (unlikely(!(vmf->flags & FAULT_FLAG_ALLOW_RETRY))) {		/*		 * Validate the invariant that nowait must allow retry		 * to be sure not to return SIGBUS erroneously on		 * nowait invocations.		 */		BUG_ON(vmf->flags & FAULT_FLAG_RETRY_NOWAIT);#ifdef CONFIG_DEBUG_VM		if (printk_ratelimit()) {			printk(KERN_WARNING			       "FAULT_FLAG_ALLOW_RETRY missing %x\n",			       vmf->flags);			dump_stack();		}#endif		goto out;	} 	/*	 * Handle nowait, not much to do other than tell it to retry	 * and wait.	 */	ret = VM_FAULT_RETRY;	if (vmf->flags & FAULT_FLAG_RETRY_NOWAIT)		goto out; 	/* take the reference before dropping the mmap_lock */	userfaultfd_ctx_get(ctx); 	init_waitqueue_func_entry(&uwq.wq, userfaultfd_wake_function);	uwq.wq.private = current;	uwq.msg = userfault_msg(vmf->address, vmf->real_address, vmf->flags,				reason, ctx->features);	uwq.ctx = ctx;	uwq.waken = false; 	blocking_state = userfaultfd_get_blocking_state(vmf->flags);         /*         * Take the vma lock now, in order to safely call         * userfaultfd_huge_must_wait() later. Since acquiring the         * (sleepable) vma lock can modify the current task state, that         * must be before explicitly calling set_current_state().         */	if (is_vm_hugetlb_page(vma))		hugetlb_vma_lock_read(vma); 	spin_lock_irq(&ctx->fault_pending_wqh.lock);	/*	 * After the __add_wait_queue the uwq is visible to userland	 * through poll/read().	 */	__add_wait_queue(&ctx->fault_pending_wqh, &uwq.wq);	/*	 * The smp_mb() after __set_current_state prevents the reads	 * following the spin_unlock to happen before the list_add in	 * __add_wait_queue.	 */	set_current_state(blocking_state);	spin_unlock_irq(&ctx->fault_pending_wqh.lock); 	if (!is_vm_hugetlb_page(vma))		must_wait = userfaultfd_must_wait(ctx, vmf, reason);	else		must_wait = userfaultfd_huge_must_wait(ctx, vmf, reason);	if (is_vm_hugetlb_page(vma))		hugetlb_vma_unlock_read(vma);

Lines 1–500 of 2202.