162306a36Sopenharmony_ci/*
262306a36Sopenharmony_ci * User address space access functions.
362306a36Sopenharmony_ci *
462306a36Sopenharmony_ci *  For licencing details see kernel-base/COPYING
562306a36Sopenharmony_ci */
662306a36Sopenharmony_ci
762306a36Sopenharmony_ci#include <linux/uaccess.h>
862306a36Sopenharmony_ci#include <linux/export.h>
962306a36Sopenharmony_ci#include <linux/instrumented.h>
1062306a36Sopenharmony_ci
1162306a36Sopenharmony_ci#include <asm/tlbflush.h>
1262306a36Sopenharmony_ci
1362306a36Sopenharmony_ci/**
1462306a36Sopenharmony_ci * copy_from_user_nmi - NMI safe copy from user
1562306a36Sopenharmony_ci * @to:		Pointer to the destination buffer
1662306a36Sopenharmony_ci * @from:	Pointer to a user space address of the current task
1762306a36Sopenharmony_ci * @n:		Number of bytes to copy
1862306a36Sopenharmony_ci *
1962306a36Sopenharmony_ci * Returns: The number of not copied bytes. 0 is success, i.e. all bytes copied
2062306a36Sopenharmony_ci *
2162306a36Sopenharmony_ci * Contrary to other copy_from_user() variants this function can be called
2262306a36Sopenharmony_ci * from NMI context. Despite the name it is not restricted to be called
2362306a36Sopenharmony_ci * from NMI context. It is safe to be called from any other context as
2462306a36Sopenharmony_ci * well. It disables pagefaults across the copy which means a fault will
2562306a36Sopenharmony_ci * abort the copy.
2662306a36Sopenharmony_ci *
2762306a36Sopenharmony_ci * For NMI context invocations this relies on the nested NMI work to allow
2862306a36Sopenharmony_ci * atomic faults from the NMI path; the nested NMI paths are careful to
2962306a36Sopenharmony_ci * preserve CR2.
3062306a36Sopenharmony_ci */
3162306a36Sopenharmony_ciunsigned long
3262306a36Sopenharmony_cicopy_from_user_nmi(void *to, const void __user *from, unsigned long n)
3362306a36Sopenharmony_ci{
3462306a36Sopenharmony_ci	unsigned long ret;
3562306a36Sopenharmony_ci
3662306a36Sopenharmony_ci	if (!__access_ok(from, n))
3762306a36Sopenharmony_ci		return n;
3862306a36Sopenharmony_ci
3962306a36Sopenharmony_ci	if (!nmi_uaccess_okay())
4062306a36Sopenharmony_ci		return n;
4162306a36Sopenharmony_ci
4262306a36Sopenharmony_ci	/*
4362306a36Sopenharmony_ci	 * Even though this function is typically called from NMI/IRQ context
4462306a36Sopenharmony_ci	 * disable pagefaults so that its behaviour is consistent even when
4562306a36Sopenharmony_ci	 * called from other contexts.
4662306a36Sopenharmony_ci	 */
4762306a36Sopenharmony_ci	pagefault_disable();
4862306a36Sopenharmony_ci	instrument_copy_from_user_before(to, from, n);
4962306a36Sopenharmony_ci	ret = raw_copy_from_user(to, from, n);
5062306a36Sopenharmony_ci	instrument_copy_from_user_after(to, from, n, ret);
5162306a36Sopenharmony_ci	pagefault_enable();
5262306a36Sopenharmony_ci
5362306a36Sopenharmony_ci	return ret;
5462306a36Sopenharmony_ci}
5562306a36Sopenharmony_ciEXPORT_SYMBOL_GPL(copy_from_user_nmi);
56