xref: /freebsd/tools/test/stress2/misc/pkru2.sh (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1#/bin/sh
2
3# Test scenario for Intel userspace protection keys feature on Skylake Xeons
4# Based on tests by kib@
5
6grep -qw PKU /var/run/dmesg.boot || exit 0
7cd /tmp
8
9cat > /tmp/pkru2a.c <<EOF
10#include <sys/types.h>
11#include <sys/mman.h>
12#include <sys/wait.h>
13#include <machine/sysarch.h>
14#include <err.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <time.h>
19#include <unistd.h>
20
21static volatile char *mapping;
22
23#define	OPKEY	1
24
25int
26main(void)
27{
28	time_t start;
29	int error;
30
31	start = time(NULL);
32	while (time(NULL) - start < 60) {
33		mapping = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE,
34		    MAP_PRIVATE | MAP_ANON, -1, 0);
35		if (mapping == MAP_FAILED)
36			err(1, "mmap");
37		error = x86_pkru_protect_range((void *)mapping,
38		    getpagesize(), OPKEY, 0);
39		error = x86_pkru_protect_range((void *)mapping,
40		    getpagesize() * 64, OPKEY, 0);
41		if (error != 0)
42			err(1, "x86_pkru_protect_range");
43		error = x86_pkru_set_perm(OPKEY, 0, 0);
44		if (error != 0)
45			err(1, "x86_pkru_set_perm");
46		if (munmap((void *)mapping, getpagesize()) == -1)
47			err(1, "munmap()");
48	}
49	return (0);
50}
51EOF
52cc -Wall -Wextra -g -O -o pkru2a64 pkru2a.c || exit 1
53cc -Wall -Wextra -g -O -o pkru2a32 -m32 pkru2a.c || exit 1
54rm pkru2a.c
55./pkru2a64
56./pkru2a32
57rm -f pkru2a64 pkru2a32
58
59cat > /tmp/pkru2b.c <<EOF
60#include <sys/types.h>
61#include <sys/mman.h>
62#include <sys/wait.h>
63#include <machine/sysarch.h>
64#include <err.h>
65#include <stdio.h>
66#include <stdlib.h>
67#include <string.h>
68#include <time.h>
69#include <unistd.h>
70
71static volatile char *mapping;
72
73#define	OPKEY	1
74
75int
76main(void)
77{
78	time_t start;
79	int error;
80
81	start = time(NULL);
82	while (time(NULL) - start < 60) {
83		mapping = mmap(NULL, getpagesize(), PROT_READ | PROT_WRITE,
84		    MAP_PRIVATE | MAP_ANON, -1, 0);
85		if (mapping == MAP_FAILED)
86			err(1, "mmap");
87		error = x86_pkru_protect_range((void *)mapping,
88		    getpagesize() * 64, OPKEY, 0);
89		if (error != 0)
90			err(1, "x86_pkru_protect_range");
91		error = x86_pkru_set_perm(OPKEY, 0, 0);
92		if (error != 0)
93			err(1, "x86_pkru_set_perm");
94		if (munmap((void *)mapping, getpagesize()) == -1)
95			err(1, "munmap()");
96	}
97	return (0);
98}
99EOF
100
101cc -Wall -Wextra -g -O -o pkru2b64 pkru2b.c || exit 1
102cc -Wall -Wextra -g -O -o pkru2b32 -m32 pkru2b.c || exit 1
103rm pkru2b.c
104./pkru2b64
105./pkru2b32
106rm -f pkru2b64 pkru2b32
107
108exit
109