Module Name:    src
Committed By:   maxv
Date:           Sun Dec 13 15:53:06 UTC 2015

Modified Files:
        src/sys/arch/amd64/amd64: trap.c
        src/sys/arch/x86/x86: cpu.c

Log Message:
Implement amd64 support for SMEP - Supervisor Mode Execution Protection.

Now, on CPUs that support this feature, if the kernel tries to execute
an instruction located in userland, the CPU will trigger a page fault.

Tested on amd64 (Intel Core i5).


To generate a diff of this commit:
cvs rdiff -u -r1.82 -r1.83 src/sys/arch/amd64/amd64/trap.c
cvs rdiff -u -r1.117 -r1.118 src/sys/arch/x86/x86/cpu.c

Please note that diffs are not public domain; they are subject to the
copyright notices on the relevant files.

Modified files:

Index: src/sys/arch/amd64/amd64/trap.c
diff -u src/sys/arch/amd64/amd64/trap.c:1.82 src/sys/arch/amd64/amd64/trap.c:1.83
--- src/sys/arch/amd64/amd64/trap.c:1.82	Sat Nov 28 15:06:55 2015
+++ src/sys/arch/amd64/amd64/trap.c	Sun Dec 13 15:53:05 2015
@@ -1,4 +1,4 @@
-/*	$NetBSD: trap.c,v 1.82 2015/11/28 15:06:55 dholland Exp $	*/
+/*	$NetBSD: trap.c,v 1.83 2015/12/13 15:53:05 maxv Exp $	*/
 
 /*-
  * Copyright (c) 1998, 2000 The NetBSD Foundation, Inc.
@@ -68,7 +68,7 @@
  */
 
 #include <sys/cdefs.h>
-__KERNEL_RCSID(0, "$NetBSD: trap.c,v 1.82 2015/11/28 15:06:55 dholland Exp $");
+__KERNEL_RCSID(0, "$NetBSD: trap.c,v 1.83 2015/12/13 15:53:05 maxv Exp $");
 
 #include "opt_ddb.h"
 #include "opt_kgdb.h"
@@ -515,6 +515,14 @@ kernelfault:
 		}
 
 		cr2 = rcr2();
+
+		if (frame->tf_err & PGEX_X) {
+			/* SMEP might have brought us here */
+			if (cr2 > VM_MIN_ADDRESS && cr2 <= VM_MAXUSER_ADDRESS)
+				panic("prevented execution of %p (SMEP)",
+				    (void *)cr2);
+		}
+
 		goto faultcommon;
 
 	case T_PAGEFLT|T_USER: {	/* page fault */

Index: src/sys/arch/x86/x86/cpu.c
diff -u src/sys/arch/x86/x86/cpu.c:1.117 src/sys/arch/x86/x86/cpu.c:1.118
--- src/sys/arch/x86/x86/cpu.c:1.117	Sun Dec 13 15:02:19 2015
+++ src/sys/arch/x86/x86/cpu.c	Sun Dec 13 15:53:06 2015
@@ -1,4 +1,4 @@
-/*	$NetBSD: cpu.c,v 1.117 2015/12/13 15:02:19 maxv Exp $	*/
+/*	$NetBSD: cpu.c,v 1.118 2015/12/13 15:53:06 maxv Exp $	*/
 
 /*-
  * Copyright (c) 2000-2012 NetBSD Foundation, Inc.
@@ -62,7 +62,7 @@
  */
 
 #include <sys/cdefs.h>
-__KERNEL_RCSID(0, "$NetBSD: cpu.c,v 1.117 2015/12/13 15:02:19 maxv Exp $");
+__KERNEL_RCSID(0, "$NetBSD: cpu.c,v 1.118 2015/12/13 15:53:06 maxv Exp $");
 
 #include "opt_ddb.h"
 #include "opt_mpbios.h"		/* for MPDEBUG */
@@ -581,6 +581,12 @@ cpu_init(struct cpu_info *ci)
 	if (cpu_feature[1] & CPUID2_XSAVE)
 		cr4 |= CR4_OSXSAVE;
 
+#ifdef __x86_64__
+	/* If SMEP is supported, enable it */
+	if (cpu_feature[5] & CPUID_SEF_SMEP)
+		cr4 |= CR4_SMEP;
+#endif
+
 	if (cr4) {
 		cr4 |= rcr4();
 		lcr4(cr4);

Reply via email to