GNU Linux-libre 4.9.317-gnu1
[releases.git] / tools / testing / selftests / x86 / protection_keys.c
1 /*
2  * Tests x86 Memory Protection Keys (see Documentation/x86/protection-keys.txt)
3  *
4  * There are examples in here of:
5  *  * how to set protection keys on memory
6  *  * how to set/clear bits in PKRU (the rights register)
7  *  * how to handle SEGV_PKRU signals and extract pkey-relevant
8  *    information from the siginfo
9  *
10  * Things to add:
11  *      make sure KSM and KSM COW breaking works
12  *      prefault pages in at malloc, or not
13  *      protect MPX bounds tables with protection keys?
14  *      make sure VMA splitting/merging is working correctly
15  *      OOMs can destroy mm->mmap (see exit_mmap()), so make sure it is immune to pkeys
16  *      look for pkey "leaks" where it is still set on a VMA but "freed" back to the kernel
17  *      do a plain mprotect() to a mprotect_pkey() area and make sure the pkey sticks
18  *
19  * Compile like this:
20  *      gcc      -o protection_keys    -O2 -g -std=gnu99 -pthread -Wall protection_keys.c -lrt -ldl -lm
21  *      gcc -m32 -o protection_keys_32 -O2 -g -std=gnu99 -pthread -Wall protection_keys.c -lrt -ldl -lm
22  */
23 #define _GNU_SOURCE
24 #include <errno.h>
25 #include <linux/futex.h>
26 #include <time.h>
27 #include <sys/time.h>
28 #include <sys/syscall.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <stdint.h>
32 #include <stdbool.h>
33 #include <signal.h>
34 #include <assert.h>
35 #include <stdlib.h>
36 #include <ucontext.h>
37 #include <sys/mman.h>
38 #include <sys/types.h>
39 #include <sys/wait.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42 #include <unistd.h>
43 #include <sys/ptrace.h>
44 #include <setjmp.h>
45
46 #include "pkey-helpers.h"
47
48 int iteration_nr = 1;
49 int test_nr;
50
51 unsigned int shadow_pkru;
52
53 #define HPAGE_SIZE      (1UL<<21)
54 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x)))
55 #define ALIGN_UP(x, align_to)   (((x) + ((align_to)-1)) & ~((align_to)-1))
56 #define ALIGN_DOWN(x, align_to) ((x) & ~((align_to)-1))
57 #define ALIGN_PTR_UP(p, ptr_align_to)   ((typeof(p))ALIGN_UP((unsigned long)(p),        ptr_align_to))
58 #define ALIGN_PTR_DOWN(p, ptr_align_to) ((typeof(p))ALIGN_DOWN((unsigned long)(p),      ptr_align_to))
59 #define __stringify_1(x...)     #x
60 #define __stringify(x...)       __stringify_1(x)
61
62 #define PTR_ERR_ENOTSUP ((void *)-ENOTSUP)
63
64 int dprint_in_signal;
65 char dprint_in_signal_buffer[DPRINT_IN_SIGNAL_BUF_SIZE];
66
67 extern void abort_hooks(void);
68 #define pkey_assert(condition) do {             \
69         if (!(condition)) {                     \
70                 dprintf0("assert() at %s::%d test_nr: %d iteration: %d\n", \
71                                 __FILE__, __LINE__,     \
72                                 test_nr, iteration_nr); \
73                 dprintf0("errno at assert: %d", errno); \
74                 abort_hooks();                  \
75                 assert(condition);              \
76         }                                       \
77 } while (0)
78 #define raw_assert(cond) assert(cond)
79
80 void cat_into_file(char *str, char *file)
81 {
82         int fd = open(file, O_RDWR);
83         int ret;
84
85         dprintf2("%s(): writing '%s' to '%s'\n", __func__, str, file);
86         /*
87          * these need to be raw because they are called under
88          * pkey_assert()
89          */
90         raw_assert(fd >= 0);
91         ret = write(fd, str, strlen(str));
92         if (ret != strlen(str)) {
93                 perror("write to file failed");
94                 fprintf(stderr, "filename: '%s' str: '%s'\n", file, str);
95                 raw_assert(0);
96         }
97         close(fd);
98 }
99
100 #if CONTROL_TRACING > 0
101 static int warned_tracing;
102 int tracing_root_ok(void)
103 {
104         if (geteuid() != 0) {
105                 if (!warned_tracing)
106                         fprintf(stderr, "WARNING: not run as root, "
107                                         "can not do tracing control\n");
108                 warned_tracing = 1;
109                 return 0;
110         }
111         return 1;
112 }
113 #endif
114
115 void tracing_on(void)
116 {
117 #if CONTROL_TRACING > 0
118 #define TRACEDIR "/sys/kernel/debug/tracing"
119         char pidstr[32];
120
121         if (!tracing_root_ok())
122                 return;
123
124         sprintf(pidstr, "%d", getpid());
125         cat_into_file("0", TRACEDIR "/tracing_on");
126         cat_into_file("\n", TRACEDIR "/trace");
127         if (1) {
128                 cat_into_file("function_graph", TRACEDIR "/current_tracer");
129                 cat_into_file("1", TRACEDIR "/options/funcgraph-proc");
130         } else {
131                 cat_into_file("nop", TRACEDIR "/current_tracer");
132         }
133         cat_into_file(pidstr, TRACEDIR "/set_ftrace_pid");
134         cat_into_file("1", TRACEDIR "/tracing_on");
135         dprintf1("enabled tracing\n");
136 #endif
137 }
138
139 void tracing_off(void)
140 {
141 #if CONTROL_TRACING > 0
142         if (!tracing_root_ok())
143                 return;
144         cat_into_file("0", "/sys/kernel/debug/tracing/tracing_on");
145 #endif
146 }
147
148 void abort_hooks(void)
149 {
150         fprintf(stderr, "running %s()...\n", __func__);
151         tracing_off();
152 #ifdef SLEEP_ON_ABORT
153         sleep(SLEEP_ON_ABORT);
154 #endif
155 }
156
157 static inline void __page_o_noops(void)
158 {
159         /* 8-bytes of instruction * 512 bytes = 1 page */
160         asm(".rept 512 ; nopl 0x7eeeeeee(%eax) ; .endr");
161 }
162
163 /*
164  * This attempts to have roughly a page of instructions followed by a few
165  * instructions that do a write, and another page of instructions.  That
166  * way, we are pretty sure that the write is in the second page of
167  * instructions and has at least a page of padding behind it.
168  *
169  * *That* lets us be sure to madvise() away the write instruction, which
170  * will then fault, which makes sure that the fault code handles
171  * execute-only memory properly.
172  */
173 __attribute__((__aligned__(PAGE_SIZE)))
174 void lots_o_noops_around_write(int *write_to_me)
175 {
176         dprintf3("running %s()\n", __func__);
177         __page_o_noops();
178         /* Assume this happens in the second page of instructions: */
179         *write_to_me = __LINE__;
180         /* pad out by another page: */
181         __page_o_noops();
182         dprintf3("%s() done\n", __func__);
183 }
184
185 /* Define some kernel-like types */
186 #define  u8 uint8_t
187 #define u16 uint16_t
188 #define u32 uint32_t
189 #define u64 uint64_t
190
191 #ifdef __i386__
192
193 #ifndef SYS_mprotect_key
194 # define SYS_mprotect_key 380
195 #endif
196 #ifndef SYS_pkey_alloc
197 # define SYS_pkey_alloc  381
198 # define SYS_pkey_free   382
199 #endif
200 #define REG_IP_IDX REG_EIP
201 #define si_pkey_offset 0x14
202
203 #else
204
205 #ifndef SYS_mprotect_key
206 # define SYS_mprotect_key 329
207 #endif
208 #ifndef SYS_pkey_alloc
209 # define SYS_pkey_alloc  330
210 # define SYS_pkey_free   331
211 #endif
212 #define REG_IP_IDX REG_RIP
213 #define si_pkey_offset 0x20
214
215 #endif
216
217 void dump_mem(void *dumpme, int len_bytes)
218 {
219         char *c = (void *)dumpme;
220         int i;
221
222         for (i = 0; i < len_bytes; i += sizeof(u64)) {
223                 u64 *ptr = (u64 *)(c + i);
224                 dprintf1("dump[%03d][@%p]: %016jx\n", i, ptr, *ptr);
225         }
226 }
227
228 #define SEGV_BNDERR     3  /* failed address bound checks */
229 #define SEGV_PKUERR     4
230
231 static char *si_code_str(int si_code)
232 {
233         if (si_code == SEGV_MAPERR)
234                 return "SEGV_MAPERR";
235         if (si_code == SEGV_ACCERR)
236                 return "SEGV_ACCERR";
237         if (si_code == SEGV_BNDERR)
238                 return "SEGV_BNDERR";
239         if (si_code == SEGV_PKUERR)
240                 return "SEGV_PKUERR";
241         return "UNKNOWN";
242 }
243
244 int pkru_faults;
245 int last_si_pkey = -1;
246 void signal_handler(int signum, siginfo_t *si, void *vucontext)
247 {
248         ucontext_t *uctxt = vucontext;
249         int trapno;
250         unsigned long ip;
251         char *fpregs;
252         u32 *pkru_ptr;
253         u64 siginfo_pkey;
254         u32 *si_pkey_ptr;
255         int pkru_offset;
256         fpregset_t fpregset;
257
258         dprint_in_signal = 1;
259         dprintf1(">>>>===============SIGSEGV============================\n");
260         dprintf1("%s()::%d, pkru: 0x%x shadow: %x\n", __func__, __LINE__,
261                         __rdpkru(), shadow_pkru);
262
263         trapno = uctxt->uc_mcontext.gregs[REG_TRAPNO];
264         ip = uctxt->uc_mcontext.gregs[REG_IP_IDX];
265         fpregset = uctxt->uc_mcontext.fpregs;
266         fpregs = (void *)fpregset;
267
268         dprintf2("%s() trapno: %d ip: 0x%lx info->si_code: %s/%d\n", __func__,
269                         trapno, ip, si_code_str(si->si_code), si->si_code);
270 #ifdef __i386__
271         /*
272          * 32-bit has some extra padding so that userspace can tell whether
273          * the XSTATE header is present in addition to the "legacy" FPU
274          * state.  We just assume that it is here.
275          */
276         fpregs += 0x70;
277 #endif
278         pkru_offset = pkru_xstate_offset();
279         pkru_ptr = (void *)(&fpregs[pkru_offset]);
280
281         dprintf1("siginfo: %p\n", si);
282         dprintf1(" fpregs: %p\n", fpregs);
283         /*
284          * If we got a PKRU fault, we *HAVE* to have at least one bit set in
285          * here.
286          */
287         dprintf1("pkru_xstate_offset: %d\n", pkru_xstate_offset());
288         if (DEBUG_LEVEL > 4)
289                 dump_mem(pkru_ptr - 128, 256);
290         pkey_assert(*pkru_ptr);
291
292         si_pkey_ptr = (u32 *)(((u8 *)si) + si_pkey_offset);
293         dprintf1("si_pkey_ptr: %p\n", si_pkey_ptr);
294         dump_mem(si_pkey_ptr - 8, 24);
295         siginfo_pkey = *si_pkey_ptr;
296         pkey_assert(siginfo_pkey < NR_PKEYS);
297         last_si_pkey = siginfo_pkey;
298
299         if ((si->si_code == SEGV_MAPERR) ||
300             (si->si_code == SEGV_ACCERR) ||
301             (si->si_code == SEGV_BNDERR)) {
302                 printf("non-PK si_code, exiting...\n");
303                 exit(4);
304         }
305
306         dprintf1("signal pkru from xsave: %08x\n", *pkru_ptr);
307         /* need __rdpkru() version so we do not do shadow_pkru checking */
308         dprintf1("signal pkru from  pkru: %08x\n", __rdpkru());
309         dprintf1("pkey from siginfo: %jx\n", siginfo_pkey);
310         *(u64 *)pkru_ptr = 0x00000000;
311         dprintf1("WARNING: set PRKU=0 to allow faulting instruction to continue\n");
312         pkru_faults++;
313         dprintf1("<<<<==================================================\n");
314         return;
315         if (trapno == 14) {
316                 fprintf(stderr,
317                         "ERROR: In signal handler, page fault, trapno = %d, ip = %016lx\n",
318                         trapno, ip);
319                 fprintf(stderr, "si_addr %p\n", si->si_addr);
320                 fprintf(stderr, "REG_ERR: %lx\n",
321                                 (unsigned long)uctxt->uc_mcontext.gregs[REG_ERR]);
322                 exit(1);
323         } else {
324                 fprintf(stderr, "unexpected trap %d! at 0x%lx\n", trapno, ip);
325                 fprintf(stderr, "si_addr %p\n", si->si_addr);
326                 fprintf(stderr, "REG_ERR: %lx\n",
327                                 (unsigned long)uctxt->uc_mcontext.gregs[REG_ERR]);
328                 exit(2);
329         }
330         dprint_in_signal = 0;
331 }
332
333 int wait_all_children(void)
334 {
335         int status;
336         return waitpid(-1, &status, 0);
337 }
338
339 void sig_chld(int x)
340 {
341         dprint_in_signal = 1;
342         dprintf2("[%d] SIGCHLD: %d\n", getpid(), x);
343         dprint_in_signal = 0;
344 }
345
346 void setup_sigsegv_handler(void)
347 {
348         int r, rs;
349         struct sigaction newact;
350         struct sigaction oldact;
351
352         /* #PF is mapped to sigsegv */
353         int signum  = SIGSEGV;
354
355         newact.sa_handler = 0;
356         newact.sa_sigaction = signal_handler;
357
358         /*sigset_t - signals to block while in the handler */
359         /* get the old signal mask. */
360         rs = sigprocmask(SIG_SETMASK, 0, &newact.sa_mask);
361         pkey_assert(rs == 0);
362
363         /* call sa_sigaction, not sa_handler*/
364         newact.sa_flags = SA_SIGINFO;
365
366         newact.sa_restorer = 0;  /* void(*)(), obsolete */
367         r = sigaction(signum, &newact, &oldact);
368         r = sigaction(SIGALRM, &newact, &oldact);
369         pkey_assert(r == 0);
370 }
371
372 void setup_handlers(void)
373 {
374         signal(SIGCHLD, &sig_chld);
375         setup_sigsegv_handler();
376 }
377
378 pid_t fork_lazy_child(void)
379 {
380         pid_t forkret;
381
382         forkret = fork();
383         pkey_assert(forkret >= 0);
384         dprintf3("[%d] fork() ret: %d\n", getpid(), forkret);
385
386         if (!forkret) {
387                 /* in the child */
388                 while (1) {
389                         dprintf1("child sleeping...\n");
390                         sleep(30);
391                 }
392         }
393         return forkret;
394 }
395
396 #define PKEY_DISABLE_ACCESS    0x1
397 #define PKEY_DISABLE_WRITE     0x2
398
399 u32 pkey_get(int pkey, unsigned long flags)
400 {
401         u32 mask = (PKEY_DISABLE_ACCESS|PKEY_DISABLE_WRITE);
402         u32 pkru = __rdpkru();
403         u32 shifted_pkru;
404         u32 masked_pkru;
405
406         dprintf1("%s(pkey=%d, flags=%lx) = %x / %d\n",
407                         __func__, pkey, flags, 0, 0);
408         dprintf2("%s() raw pkru: %x\n", __func__, pkru);
409
410         shifted_pkru = (pkru >> (pkey * PKRU_BITS_PER_PKEY));
411         dprintf2("%s() shifted_pkru: %x\n", __func__, shifted_pkru);
412         masked_pkru = shifted_pkru & mask;
413         dprintf2("%s() masked  pkru: %x\n", __func__, masked_pkru);
414         /*
415          * shift down the relevant bits to the lowest two, then
416          * mask off all the other high bits.
417          */
418         return masked_pkru;
419 }
420
421 int pkey_set(int pkey, unsigned long rights, unsigned long flags)
422 {
423         u32 mask = (PKEY_DISABLE_ACCESS|PKEY_DISABLE_WRITE);
424         u32 old_pkru = __rdpkru();
425         u32 new_pkru;
426
427         /* make sure that 'rights' only contains the bits we expect: */
428         assert(!(rights & ~mask));
429
430         /* copy old pkru */
431         new_pkru = old_pkru;
432         /* mask out bits from pkey in old value: */
433         new_pkru &= ~(mask << (pkey * PKRU_BITS_PER_PKEY));
434         /* OR in new bits for pkey: */
435         new_pkru |= (rights << (pkey * PKRU_BITS_PER_PKEY));
436
437         __wrpkru(new_pkru);
438
439         dprintf3("%s(pkey=%d, rights=%lx, flags=%lx) = %x pkru now: %x old_pkru: %x\n",
440                         __func__, pkey, rights, flags, 0, __rdpkru(), old_pkru);
441         return 0;
442 }
443
444 void pkey_disable_set(int pkey, int flags)
445 {
446         unsigned long syscall_flags = 0;
447         int ret;
448         int pkey_rights;
449         u32 orig_pkru;
450
451         dprintf1("START->%s(%d, 0x%x)\n", __func__,
452                 pkey, flags);
453         pkey_assert(flags & (PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE));
454
455         pkey_rights = pkey_get(pkey, syscall_flags);
456
457         dprintf1("%s(%d) pkey_get(%d): %x\n", __func__,
458                         pkey, pkey, pkey_rights);
459         pkey_assert(pkey_rights >= 0);
460
461         pkey_rights |= flags;
462
463         ret = pkey_set(pkey, pkey_rights, syscall_flags);
464         assert(!ret);
465         /*pkru and flags have the same format */
466         shadow_pkru |= flags << (pkey * 2);
467         dprintf1("%s(%d) shadow: 0x%x\n", __func__, pkey, shadow_pkru);
468
469         pkey_assert(ret >= 0);
470
471         pkey_rights = pkey_get(pkey, syscall_flags);
472         dprintf1("%s(%d) pkey_get(%d): %x\n", __func__,
473                         pkey, pkey, pkey_rights);
474
475         dprintf1("%s(%d) pkru: 0x%x\n", __func__, pkey, rdpkru());
476         if (flags)
477                 pkey_assert(rdpkru() > orig_pkru);
478         dprintf1("END<---%s(%d, 0x%x)\n", __func__,
479                 pkey, flags);
480 }
481
482 void pkey_disable_clear(int pkey, int flags)
483 {
484         unsigned long syscall_flags = 0;
485         int ret;
486         int pkey_rights = pkey_get(pkey, syscall_flags);
487         u32 orig_pkru = rdpkru();
488
489         pkey_assert(flags & (PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE));
490
491         dprintf1("%s(%d) pkey_get(%d): %x\n", __func__,
492                         pkey, pkey, pkey_rights);
493         pkey_assert(pkey_rights >= 0);
494
495         pkey_rights |= flags;
496
497         ret = pkey_set(pkey, pkey_rights, 0);
498         /* pkru and flags have the same format */
499         shadow_pkru &= ~(flags << (pkey * 2));
500         pkey_assert(ret >= 0);
501
502         pkey_rights = pkey_get(pkey, syscall_flags);
503         dprintf1("%s(%d) pkey_get(%d): %x\n", __func__,
504                         pkey, pkey, pkey_rights);
505
506         dprintf1("%s(%d) pkru: 0x%x\n", __func__, pkey, rdpkru());
507         if (flags)
508                 assert(rdpkru() > orig_pkru);
509 }
510
511 void pkey_write_allow(int pkey)
512 {
513         pkey_disable_clear(pkey, PKEY_DISABLE_WRITE);
514 }
515 void pkey_write_deny(int pkey)
516 {
517         pkey_disable_set(pkey, PKEY_DISABLE_WRITE);
518 }
519 void pkey_access_allow(int pkey)
520 {
521         pkey_disable_clear(pkey, PKEY_DISABLE_ACCESS);
522 }
523 void pkey_access_deny(int pkey)
524 {
525         pkey_disable_set(pkey, PKEY_DISABLE_ACCESS);
526 }
527
528 int sys_mprotect_pkey(void *ptr, size_t size, unsigned long orig_prot,
529                 unsigned long pkey)
530 {
531         int sret;
532
533         dprintf2("%s(0x%p, %zx, prot=%lx, pkey=%lx)\n", __func__,
534                         ptr, size, orig_prot, pkey);
535
536         errno = 0;
537         sret = syscall(SYS_mprotect_key, ptr, size, orig_prot, pkey);
538         if (errno) {
539                 dprintf2("SYS_mprotect_key sret: %d\n", sret);
540                 dprintf2("SYS_mprotect_key prot: 0x%lx\n", orig_prot);
541                 dprintf2("SYS_mprotect_key failed, errno: %d\n", errno);
542                 if (DEBUG_LEVEL >= 2)
543                         perror("SYS_mprotect_pkey");
544         }
545         return sret;
546 }
547
548 int sys_pkey_alloc(unsigned long flags, unsigned long init_val)
549 {
550         int ret = syscall(SYS_pkey_alloc, flags, init_val);
551         dprintf1("%s(flags=%lx, init_val=%lx) syscall ret: %d errno: %d\n",
552                         __func__, flags, init_val, ret, errno);
553         return ret;
554 }
555
556 int alloc_pkey(void)
557 {
558         int ret;
559         unsigned long init_val = 0x0;
560
561         dprintf1("alloc_pkey()::%d, pkru: 0x%x shadow: %x\n",
562                         __LINE__, __rdpkru(), shadow_pkru);
563         ret = sys_pkey_alloc(0, init_val);
564         /*
565          * pkey_alloc() sets PKRU, so we need to reflect it in
566          * shadow_pkru:
567          */
568         dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
569                         __LINE__, ret, __rdpkru(), shadow_pkru);
570         if (ret) {
571                 /* clear both the bits: */
572                 shadow_pkru &= ~(0x3      << (ret * 2));
573                 dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
574                                 __LINE__, ret, __rdpkru(), shadow_pkru);
575                 /*
576                  * move the new state in from init_val
577                  * (remember, we cheated and init_val == pkru format)
578                  */
579                 shadow_pkru |=  (init_val << (ret * 2));
580         }
581         dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
582                         __LINE__, ret, __rdpkru(), shadow_pkru);
583         dprintf1("alloc_pkey()::%d errno: %d\n", __LINE__, errno);
584         /* for shadow checking: */
585         rdpkru();
586         dprintf4("alloc_pkey()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n",
587                         __LINE__, ret, __rdpkru(), shadow_pkru);
588         return ret;
589 }
590
591 int sys_pkey_free(unsigned long pkey)
592 {
593         int ret = syscall(SYS_pkey_free, pkey);
594         dprintf1("%s(pkey=%ld) syscall ret: %d\n", __func__, pkey, ret);
595         return ret;
596 }
597
598 /*
599  * I had a bug where pkey bits could be set by mprotect() but
600  * not cleared.  This ensures we get lots of random bit sets
601  * and clears on the vma and pte pkey bits.
602  */
603 int alloc_random_pkey(void)
604 {
605         int max_nr_pkey_allocs;
606         int ret;
607         int i;
608         int alloced_pkeys[NR_PKEYS];
609         int nr_alloced = 0;
610         int random_index;
611         memset(alloced_pkeys, 0, sizeof(alloced_pkeys));
612
613         /* allocate every possible key and make a note of which ones we got */
614         max_nr_pkey_allocs = NR_PKEYS;
615         for (i = 0; i < max_nr_pkey_allocs; i++) {
616                 int new_pkey = alloc_pkey();
617                 if (new_pkey < 0)
618                         break;
619                 alloced_pkeys[nr_alloced++] = new_pkey;
620         }
621
622         pkey_assert(nr_alloced > 0);
623         /* select a random one out of the allocated ones */
624         random_index = rand() % nr_alloced;
625         ret = alloced_pkeys[random_index];
626         /* now zero it out so we don't free it next */
627         alloced_pkeys[random_index] = 0;
628
629         /* go through the allocated ones that we did not want and free them */
630         for (i = 0; i < nr_alloced; i++) {
631                 int free_ret;
632                 if (!alloced_pkeys[i])
633                         continue;
634                 free_ret = sys_pkey_free(alloced_pkeys[i]);
635                 pkey_assert(!free_ret);
636         }
637         dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__,
638                         __LINE__, ret, __rdpkru(), shadow_pkru);
639         return ret;
640 }
641
642 int mprotect_pkey(void *ptr, size_t size, unsigned long orig_prot,
643                 unsigned long pkey)
644 {
645         int nr_iterations = random() % 100;
646         int ret;
647
648         while (0) {
649                 int rpkey = alloc_random_pkey();
650                 ret = sys_mprotect_pkey(ptr, size, orig_prot, pkey);
651                 dprintf1("sys_mprotect_pkey(%p, %zx, prot=0x%lx, pkey=%ld) ret: %d\n",
652                                 ptr, size, orig_prot, pkey, ret);
653                 if (nr_iterations-- < 0)
654                         break;
655
656                 dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__,
657                         __LINE__, ret, __rdpkru(), shadow_pkru);
658                 sys_pkey_free(rpkey);
659                 dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__,
660                         __LINE__, ret, __rdpkru(), shadow_pkru);
661         }
662         pkey_assert(pkey < NR_PKEYS);
663
664         ret = sys_mprotect_pkey(ptr, size, orig_prot, pkey);
665         dprintf1("mprotect_pkey(%p, %zx, prot=0x%lx, pkey=%ld) ret: %d\n",
666                         ptr, size, orig_prot, pkey, ret);
667         pkey_assert(!ret);
668         dprintf1("%s()::%d, ret: %d pkru: 0x%x shadow: 0x%x\n", __func__,
669                         __LINE__, ret, __rdpkru(), shadow_pkru);
670         return ret;
671 }
672
673 struct pkey_malloc_record {
674         void *ptr;
675         long size;
676 };
677 struct pkey_malloc_record *pkey_malloc_records;
678 long nr_pkey_malloc_records;
679 void record_pkey_malloc(void *ptr, long size)
680 {
681         long i;
682         struct pkey_malloc_record *rec = NULL;
683
684         for (i = 0; i < nr_pkey_malloc_records; i++) {
685                 rec = &pkey_malloc_records[i];
686                 /* find a free record */
687                 if (rec)
688                         break;
689         }
690         if (!rec) {
691                 /* every record is full */
692                 size_t old_nr_records = nr_pkey_malloc_records;
693                 size_t new_nr_records = (nr_pkey_malloc_records * 2 + 1);
694                 size_t new_size = new_nr_records * sizeof(struct pkey_malloc_record);
695                 dprintf2("new_nr_records: %zd\n", new_nr_records);
696                 dprintf2("new_size: %zd\n", new_size);
697                 pkey_malloc_records = realloc(pkey_malloc_records, new_size);
698                 pkey_assert(pkey_malloc_records != NULL);
699                 rec = &pkey_malloc_records[nr_pkey_malloc_records];
700                 /*
701                  * realloc() does not initialize memory, so zero it from
702                  * the first new record all the way to the end.
703                  */
704                 for (i = 0; i < new_nr_records - old_nr_records; i++)
705                         memset(rec + i, 0, sizeof(*rec));
706         }
707         dprintf3("filling malloc record[%d/%p]: {%p, %ld}\n",
708                 (int)(rec - pkey_malloc_records), rec, ptr, size);
709         rec->ptr = ptr;
710         rec->size = size;
711         nr_pkey_malloc_records++;
712 }
713
714 void free_pkey_malloc(void *ptr)
715 {
716         long i;
717         int ret;
718         dprintf3("%s(%p)\n", __func__, ptr);
719         for (i = 0; i < nr_pkey_malloc_records; i++) {
720                 struct pkey_malloc_record *rec = &pkey_malloc_records[i];
721                 dprintf4("looking for ptr %p at record[%ld/%p]: {%p, %ld}\n",
722                                 ptr, i, rec, rec->ptr, rec->size);
723                 if ((ptr <  rec->ptr) ||
724                     (ptr >= rec->ptr + rec->size))
725                         continue;
726
727                 dprintf3("found ptr %p at record[%ld/%p]: {%p, %ld}\n",
728                                 ptr, i, rec, rec->ptr, rec->size);
729                 nr_pkey_malloc_records--;
730                 ret = munmap(rec->ptr, rec->size);
731                 dprintf3("munmap ret: %d\n", ret);
732                 pkey_assert(!ret);
733                 dprintf3("clearing rec->ptr, rec: %p\n", rec);
734                 rec->ptr = NULL;
735                 dprintf3("done clearing rec->ptr, rec: %p\n", rec);
736                 return;
737         }
738         pkey_assert(false);
739 }
740
741
742 void *malloc_pkey_with_mprotect(long size, int prot, u16 pkey)
743 {
744         void *ptr;
745         int ret;
746
747         rdpkru();
748         dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
749                         size, prot, pkey);
750         pkey_assert(pkey < NR_PKEYS);
751         ptr = mmap(NULL, size, prot, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
752         pkey_assert(ptr != (void *)-1);
753         ret = mprotect_pkey((void *)ptr, PAGE_SIZE, prot, pkey);
754         pkey_assert(!ret);
755         record_pkey_malloc(ptr, size);
756         rdpkru();
757
758         dprintf1("%s() for pkey %d @ %p\n", __func__, pkey, ptr);
759         return ptr;
760 }
761
762 void *malloc_pkey_anon_huge(long size, int prot, u16 pkey)
763 {
764         int ret;
765         void *ptr;
766
767         dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
768                         size, prot, pkey);
769         /*
770          * Guarantee we can fit at least one huge page in the resulting
771          * allocation by allocating space for 2:
772          */
773         size = ALIGN_UP(size, HPAGE_SIZE * 2);
774         ptr = mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
775         pkey_assert(ptr != (void *)-1);
776         record_pkey_malloc(ptr, size);
777         mprotect_pkey(ptr, size, prot, pkey);
778
779         dprintf1("unaligned ptr: %p\n", ptr);
780         ptr = ALIGN_PTR_UP(ptr, HPAGE_SIZE);
781         dprintf1("  aligned ptr: %p\n", ptr);
782         ret = madvise(ptr, HPAGE_SIZE, MADV_HUGEPAGE);
783         dprintf1("MADV_HUGEPAGE ret: %d\n", ret);
784         ret = madvise(ptr, HPAGE_SIZE, MADV_WILLNEED);
785         dprintf1("MADV_WILLNEED ret: %d\n", ret);
786         memset(ptr, 0, HPAGE_SIZE);
787
788         dprintf1("mmap()'d thp for pkey %d @ %p\n", pkey, ptr);
789         return ptr;
790 }
791
792 int hugetlb_setup_ok;
793 #define GET_NR_HUGE_PAGES 10
794 void setup_hugetlbfs(void)
795 {
796         int err;
797         int fd;
798         int validated_nr_pages;
799         int i;
800         char buf[] = "123";
801
802         if (geteuid() != 0) {
803                 fprintf(stderr, "WARNING: not run as root, can not do hugetlb test\n");
804                 return;
805         }
806
807         cat_into_file(__stringify(GET_NR_HUGE_PAGES), "/proc/sys/vm/nr_hugepages");
808
809         /*
810          * Now go make sure that we got the pages and that they
811          * are 2M pages.  Someone might have made 1G the default.
812          */
813         fd = open("/sys/kernel/mm/hugepages/hugepages-2048kB/nr_hugepages", O_RDONLY);
814         if (fd < 0) {
815                 perror("opening sysfs 2M hugetlb config");
816                 return;
817         }
818
819         /* -1 to guarantee leaving the trailing \0 */
820         err = read(fd, buf, sizeof(buf)-1);
821         close(fd);
822         if (err <= 0) {
823                 perror("reading sysfs 2M hugetlb config");
824                 return;
825         }
826
827         if (atoi(buf) != GET_NR_HUGE_PAGES) {
828                 fprintf(stderr, "could not confirm 2M pages, got: '%s' expected %d\n",
829                         buf, GET_NR_HUGE_PAGES);
830                 return;
831         }
832
833         hugetlb_setup_ok = 1;
834 }
835
836 void *malloc_pkey_hugetlb(long size, int prot, u16 pkey)
837 {
838         void *ptr;
839         int flags = MAP_ANONYMOUS|MAP_PRIVATE|MAP_HUGETLB;
840
841         if (!hugetlb_setup_ok)
842                 return PTR_ERR_ENOTSUP;
843
844         dprintf1("doing %s(%ld, %x, %x)\n", __func__, size, prot, pkey);
845         size = ALIGN_UP(size, HPAGE_SIZE * 2);
846         pkey_assert(pkey < NR_PKEYS);
847         ptr = mmap(NULL, size, PROT_NONE, flags, -1, 0);
848         pkey_assert(ptr != (void *)-1);
849         mprotect_pkey(ptr, size, prot, pkey);
850
851         record_pkey_malloc(ptr, size);
852
853         dprintf1("mmap()'d hugetlbfs for pkey %d @ %p\n", pkey, ptr);
854         return ptr;
855 }
856
857 void *malloc_pkey_mmap_dax(long size, int prot, u16 pkey)
858 {
859         void *ptr;
860         int fd;
861
862         dprintf1("doing %s(size=%ld, prot=0x%x, pkey=%d)\n", __func__,
863                         size, prot, pkey);
864         pkey_assert(pkey < NR_PKEYS);
865         fd = open("/dax/foo", O_RDWR);
866         pkey_assert(fd >= 0);
867
868         ptr = mmap(0, size, prot, MAP_SHARED, fd, 0);
869         pkey_assert(ptr != (void *)-1);
870
871         mprotect_pkey(ptr, size, prot, pkey);
872
873         record_pkey_malloc(ptr, size);
874
875         dprintf1("mmap()'d for pkey %d @ %p\n", pkey, ptr);
876         close(fd);
877         return ptr;
878 }
879
880 void *(*pkey_malloc[])(long size, int prot, u16 pkey) = {
881
882         malloc_pkey_with_mprotect,
883         malloc_pkey_anon_huge,
884         malloc_pkey_hugetlb
885 /* can not do direct with the pkey_mprotect() API:
886         malloc_pkey_mmap_direct,
887         malloc_pkey_mmap_dax,
888 */
889 };
890
891 void *malloc_pkey(long size, int prot, u16 pkey)
892 {
893         void *ret;
894         static int malloc_type;
895         int nr_malloc_types = ARRAY_SIZE(pkey_malloc);
896
897         pkey_assert(pkey < NR_PKEYS);
898
899         while (1) {
900                 pkey_assert(malloc_type < nr_malloc_types);
901
902                 ret = pkey_malloc[malloc_type](size, prot, pkey);
903                 pkey_assert(ret != (void *)-1);
904
905                 malloc_type++;
906                 if (malloc_type >= nr_malloc_types)
907                         malloc_type = (random()%nr_malloc_types);
908
909                 /* try again if the malloc_type we tried is unsupported */
910                 if (ret == PTR_ERR_ENOTSUP)
911                         continue;
912
913                 break;
914         }
915
916         dprintf3("%s(%ld, prot=%x, pkey=%x) returning: %p\n", __func__,
917                         size, prot, pkey, ret);
918         return ret;
919 }
920
921 int last_pkru_faults;
922 void expected_pk_fault(int pkey)
923 {
924         dprintf2("%s(): last_pkru_faults: %d pkru_faults: %d\n",
925                         __func__, last_pkru_faults, pkru_faults);
926         dprintf2("%s(%d): last_si_pkey: %d\n", __func__, pkey, last_si_pkey);
927         pkey_assert(last_pkru_faults + 1 == pkru_faults);
928         pkey_assert(last_si_pkey == pkey);
929         /*
930          * The signal handler shold have cleared out PKRU to let the
931          * test program continue.  We now have to restore it.
932          */
933         if (__rdpkru() != 0)
934                 pkey_assert(0);
935
936         __wrpkru(shadow_pkru);
937         dprintf1("%s() set PKRU=%x to restore state after signal nuked it\n",
938                         __func__, shadow_pkru);
939         last_pkru_faults = pkru_faults;
940         last_si_pkey = -1;
941 }
942
943 void do_not_expect_pk_fault(void)
944 {
945         pkey_assert(last_pkru_faults == pkru_faults);
946 }
947
948 int test_fds[10] = { -1 };
949 int nr_test_fds;
950 void __save_test_fd(int fd)
951 {
952         pkey_assert(fd >= 0);
953         pkey_assert(nr_test_fds < ARRAY_SIZE(test_fds));
954         test_fds[nr_test_fds] = fd;
955         nr_test_fds++;
956 }
957
958 int get_test_read_fd(void)
959 {
960         int test_fd = open("/etc/passwd", O_RDONLY);
961         __save_test_fd(test_fd);
962         return test_fd;
963 }
964
965 void close_test_fds(void)
966 {
967         int i;
968
969         for (i = 0; i < nr_test_fds; i++) {
970                 if (test_fds[i] < 0)
971                         continue;
972                 close(test_fds[i]);
973                 test_fds[i] = -1;
974         }
975         nr_test_fds = 0;
976 }
977
978 #define barrier() __asm__ __volatile__("": : :"memory")
979 __attribute__((noinline)) int read_ptr(int *ptr)
980 {
981         /*
982          * Keep GCC from optimizing this away somehow
983          */
984         barrier();
985         return *ptr;
986 }
987
988 void test_read_of_write_disabled_region(int *ptr, u16 pkey)
989 {
990         int ptr_contents;
991
992         dprintf1("disabling write access to PKEY[1], doing read\n");
993         pkey_write_deny(pkey);
994         ptr_contents = read_ptr(ptr);
995         dprintf1("*ptr: %d\n", ptr_contents);
996         dprintf1("\n");
997 }
998 void test_read_of_access_disabled_region(int *ptr, u16 pkey)
999 {
1000         int ptr_contents;
1001
1002         dprintf1("disabling access to PKEY[%02d], doing read @ %p\n", pkey, ptr);
1003         rdpkru();
1004         pkey_access_deny(pkey);
1005         ptr_contents = read_ptr(ptr);
1006         dprintf1("*ptr: %d\n", ptr_contents);
1007         expected_pk_fault(pkey);
1008 }
1009 void test_write_of_write_disabled_region(int *ptr, u16 pkey)
1010 {
1011         dprintf1("disabling write access to PKEY[%02d], doing write\n", pkey);
1012         pkey_write_deny(pkey);
1013         *ptr = __LINE__;
1014         expected_pk_fault(pkey);
1015 }
1016 void test_write_of_access_disabled_region(int *ptr, u16 pkey)
1017 {
1018         dprintf1("disabling access to PKEY[%02d], doing write\n", pkey);
1019         pkey_access_deny(pkey);
1020         *ptr = __LINE__;
1021         expected_pk_fault(pkey);
1022 }
1023 void test_kernel_write_of_access_disabled_region(int *ptr, u16 pkey)
1024 {
1025         int ret;
1026         int test_fd = get_test_read_fd();
1027
1028         dprintf1("disabling access to PKEY[%02d], "
1029                  "having kernel read() to buffer\n", pkey);
1030         pkey_access_deny(pkey);
1031         ret = read(test_fd, ptr, 1);
1032         dprintf1("read ret: %d\n", ret);
1033         pkey_assert(ret);
1034 }
1035 void test_kernel_write_of_write_disabled_region(int *ptr, u16 pkey)
1036 {
1037         int ret;
1038         int test_fd = get_test_read_fd();
1039
1040         pkey_write_deny(pkey);
1041         ret = read(test_fd, ptr, 100);
1042         dprintf1("read ret: %d\n", ret);
1043         if (ret < 0 && (DEBUG_LEVEL > 0))
1044                 perror("verbose read result (OK for this to be bad)");
1045         pkey_assert(ret);
1046 }
1047
1048 void test_kernel_gup_of_access_disabled_region(int *ptr, u16 pkey)
1049 {
1050         int pipe_ret, vmsplice_ret;
1051         struct iovec iov;
1052         int pipe_fds[2];
1053
1054         pipe_ret = pipe(pipe_fds);
1055
1056         pkey_assert(pipe_ret == 0);
1057         dprintf1("disabling access to PKEY[%02d], "
1058                  "having kernel vmsplice from buffer\n", pkey);
1059         pkey_access_deny(pkey);
1060         iov.iov_base = ptr;
1061         iov.iov_len = PAGE_SIZE;
1062         vmsplice_ret = vmsplice(pipe_fds[1], &iov, 1, SPLICE_F_GIFT);
1063         dprintf1("vmsplice() ret: %d\n", vmsplice_ret);
1064         pkey_assert(vmsplice_ret == -1);
1065
1066         close(pipe_fds[0]);
1067         close(pipe_fds[1]);
1068 }
1069
1070 void test_kernel_gup_write_to_write_disabled_region(int *ptr, u16 pkey)
1071 {
1072         int ignored = 0xdada;
1073         int futex_ret;
1074         int some_int = __LINE__;
1075
1076         dprintf1("disabling write to PKEY[%02d], "
1077                  "doing futex gunk in buffer\n", pkey);
1078         *ptr = some_int;
1079         pkey_write_deny(pkey);
1080         futex_ret = syscall(SYS_futex, ptr, FUTEX_WAIT, some_int-1, NULL,
1081                         &ignored, ignored);
1082         if (DEBUG_LEVEL > 0)
1083                 perror("futex");
1084         dprintf1("futex() ret: %d\n", futex_ret);
1085 }
1086
1087 /* Assumes that all pkeys other than 'pkey' are unallocated */
1088 void test_pkey_syscalls_on_non_allocated_pkey(int *ptr, u16 pkey)
1089 {
1090         int err;
1091         int i;
1092
1093         /* Note: 0 is the default pkey, so don't mess with it */
1094         for (i = 1; i < NR_PKEYS; i++) {
1095                 if (pkey == i)
1096                         continue;
1097
1098                 dprintf1("trying get/set/free to non-allocated pkey: %2d\n", i);
1099                 err = sys_pkey_free(i);
1100                 pkey_assert(err);
1101
1102                 /* not enforced when pkey_get() is not a syscall
1103                 err = pkey_get(i, 0);
1104                 pkey_assert(err < 0);
1105                 */
1106
1107                 err = sys_pkey_free(i);
1108                 pkey_assert(err);
1109
1110                 err = sys_mprotect_pkey(ptr, PAGE_SIZE, PROT_READ, i);
1111                 pkey_assert(err);
1112         }
1113 }
1114
1115 /* Assumes that all pkeys other than 'pkey' are unallocated */
1116 void test_pkey_syscalls_bad_args(int *ptr, u16 pkey)
1117 {
1118         int err;
1119         int bad_flag = (PKEY_DISABLE_ACCESS | PKEY_DISABLE_WRITE) + 1;
1120         int bad_pkey = NR_PKEYS+99;
1121
1122         /* not enforced when pkey_get() is not a syscall
1123         err = pkey_get(bad_pkey, bad_flag);
1124         pkey_assert(err < 0);
1125         */
1126
1127         /* pass a known-invalid pkey in: */
1128         err = sys_mprotect_pkey(ptr, PAGE_SIZE, PROT_READ, bad_pkey);
1129         pkey_assert(err);
1130 }
1131
1132 void become_child(void)
1133 {
1134         pid_t forkret;
1135
1136         forkret = fork();
1137         pkey_assert(forkret >= 0);
1138         dprintf3("[%d] fork() ret: %d\n", getpid(), forkret);
1139
1140         if (!forkret) {
1141                 /* in the child */
1142                 return;
1143         }
1144         exit(0);
1145 }
1146
1147 /* Assumes that all pkeys other than 'pkey' are unallocated */
1148 void test_pkey_alloc_exhaust(int *ptr, u16 pkey)
1149 {
1150         unsigned long flags;
1151         unsigned long init_val;
1152         int err;
1153         int allocated_pkeys[NR_PKEYS] = {0};
1154         int nr_allocated_pkeys = 0;
1155         int i;
1156
1157         for (i = 0; i < NR_PKEYS*3; i++) {
1158                 int new_pkey;
1159                 dprintf1("%s() alloc loop: %d\n", __func__, i);
1160                 new_pkey = alloc_pkey();
1161                 dprintf4("%s()::%d, err: %d pkru: 0x%x shadow: 0x%x\n", __func__,
1162                                 __LINE__, err, __rdpkru(), shadow_pkru);
1163                 rdpkru(); /* for shadow checking */
1164                 dprintf2("%s() errno: %d ENOSPC: %d\n", __func__, errno, ENOSPC);
1165                 if ((new_pkey == -1) && (errno == ENOSPC)) {
1166                         dprintf2("%s() failed to allocate pkey after %d tries\n",
1167                                 __func__, nr_allocated_pkeys);
1168                 } else {
1169                         /*
1170                          * Ensure the number of successes never
1171                          * exceeds the number of keys supported
1172                          * in the hardware.
1173                          */
1174                         pkey_assert(nr_allocated_pkeys < NR_PKEYS);
1175                         allocated_pkeys[nr_allocated_pkeys++] = new_pkey;
1176                 }
1177
1178                 /*
1179                  * Make sure that allocation state is properly
1180                  * preserved across fork().
1181                  */
1182                 if (i == NR_PKEYS*2)
1183                         become_child();
1184         }
1185
1186         dprintf3("%s()::%d\n", __func__, __LINE__);
1187
1188         /*
1189          * There are 16 pkeys supported in hardware.  One is taken
1190          * up for the default (0) and another can be taken up by
1191          * an execute-only mapping.  Ensure that we can allocate
1192          * at least 14 (16-2).
1193          */
1194         pkey_assert(i >= NR_PKEYS-2);
1195
1196         for (i = 0; i < nr_allocated_pkeys; i++) {
1197                 err = sys_pkey_free(allocated_pkeys[i]);
1198                 pkey_assert(!err);
1199                 rdpkru(); /* for shadow checking */
1200         }
1201 }
1202
1203 void test_ptrace_of_child(int *ptr, u16 pkey)
1204 {
1205         __attribute__((__unused__)) int peek_result;
1206         pid_t child_pid;
1207         void *ignored = 0;
1208         long ret;
1209         int status;
1210         /*
1211          * This is the "control" for our little expermient.  Make sure
1212          * we can always access it when ptracing.
1213          */
1214         int *plain_ptr_unaligned = malloc(HPAGE_SIZE);
1215         int *plain_ptr = ALIGN_PTR_UP(plain_ptr_unaligned, PAGE_SIZE);
1216
1217         /*
1218          * Fork a child which is an exact copy of this process, of course.
1219          * That means we can do all of our tests via ptrace() and then plain
1220          * memory access and ensure they work differently.
1221          */
1222         child_pid = fork_lazy_child();
1223         dprintf1("[%d] child pid: %d\n", getpid(), child_pid);
1224
1225         ret = ptrace(PTRACE_ATTACH, child_pid, ignored, ignored);
1226         if (ret)
1227                 perror("attach");
1228         dprintf1("[%d] attach ret: %ld %d\n", getpid(), ret, __LINE__);
1229         pkey_assert(ret != -1);
1230         ret = waitpid(child_pid, &status, WUNTRACED);
1231         if ((ret != child_pid) || !(WIFSTOPPED(status))) {
1232                 fprintf(stderr, "weird waitpid result %ld stat %x\n",
1233                                 ret, status);
1234                 pkey_assert(0);
1235         }
1236         dprintf2("waitpid ret: %ld\n", ret);
1237         dprintf2("waitpid status: %d\n", status);
1238
1239         pkey_access_deny(pkey);
1240         pkey_write_deny(pkey);
1241
1242         /* Write access, untested for now:
1243         ret = ptrace(PTRACE_POKEDATA, child_pid, peek_at, data);
1244         pkey_assert(ret != -1);
1245         dprintf1("poke at %p: %ld\n", peek_at, ret);
1246         */
1247
1248         /*
1249          * Try to access the pkey-protected "ptr" via ptrace:
1250          */
1251         ret = ptrace(PTRACE_PEEKDATA, child_pid, ptr, ignored);
1252         /* expect it to work, without an error: */
1253         pkey_assert(ret != -1);
1254         /* Now access from the current task, and expect an exception: */
1255         peek_result = read_ptr(ptr);
1256         expected_pk_fault(pkey);
1257
1258         /*
1259          * Try to access the NON-pkey-protected "plain_ptr" via ptrace:
1260          */
1261         ret = ptrace(PTRACE_PEEKDATA, child_pid, plain_ptr, ignored);
1262         /* expect it to work, without an error: */
1263         pkey_assert(ret != -1);
1264         /* Now access from the current task, and expect NO exception: */
1265         peek_result = read_ptr(plain_ptr);
1266         do_not_expect_pk_fault();
1267
1268         ret = ptrace(PTRACE_DETACH, child_pid, ignored, 0);
1269         pkey_assert(ret != -1);
1270
1271         ret = kill(child_pid, SIGKILL);
1272         pkey_assert(ret != -1);
1273
1274         wait(&status);
1275
1276         free(plain_ptr_unaligned);
1277 }
1278
1279 void test_executing_on_unreadable_memory(int *ptr, u16 pkey)
1280 {
1281         void *p1;
1282         int scratch;
1283         int ptr_contents;
1284         int ret;
1285
1286         p1 = ALIGN_PTR_UP(&lots_o_noops_around_write, PAGE_SIZE);
1287         dprintf3("&lots_o_noops: %p\n", &lots_o_noops_around_write);
1288         /* lots_o_noops_around_write should be page-aligned already */
1289         assert(p1 == &lots_o_noops_around_write);
1290
1291         /* Point 'p1' at the *second* page of the function: */
1292         p1 += PAGE_SIZE;
1293
1294         madvise(p1, PAGE_SIZE, MADV_DONTNEED);
1295         lots_o_noops_around_write(&scratch);
1296         ptr_contents = read_ptr(p1);
1297         dprintf2("ptr (%p) contents@%d: %x\n", p1, __LINE__, ptr_contents);
1298
1299         ret = mprotect_pkey(p1, PAGE_SIZE, PROT_EXEC, (u64)pkey);
1300         pkey_assert(!ret);
1301         pkey_access_deny(pkey);
1302
1303         dprintf2("pkru: %x\n", rdpkru());
1304
1305         /*
1306          * Make sure this is an *instruction* fault
1307          */
1308         madvise(p1, PAGE_SIZE, MADV_DONTNEED);
1309         lots_o_noops_around_write(&scratch);
1310         do_not_expect_pk_fault();
1311         ptr_contents = read_ptr(p1);
1312         dprintf2("ptr (%p) contents@%d: %x\n", p1, __LINE__, ptr_contents);
1313         expected_pk_fault(pkey);
1314 }
1315
1316 void test_mprotect_pkey_on_unsupported_cpu(int *ptr, u16 pkey)
1317 {
1318         int size = PAGE_SIZE;
1319         int sret;
1320
1321         if (cpu_has_pku()) {
1322                 dprintf1("SKIP: %s: no CPU support\n", __func__);
1323                 return;
1324         }
1325
1326         sret = syscall(SYS_mprotect_key, ptr, size, PROT_READ, pkey);
1327         pkey_assert(sret < 0);
1328 }
1329
1330 void (*pkey_tests[])(int *ptr, u16 pkey) = {
1331         test_read_of_write_disabled_region,
1332         test_read_of_access_disabled_region,
1333         test_write_of_write_disabled_region,
1334         test_write_of_access_disabled_region,
1335         test_kernel_write_of_access_disabled_region,
1336         test_kernel_write_of_write_disabled_region,
1337         test_kernel_gup_of_access_disabled_region,
1338         test_kernel_gup_write_to_write_disabled_region,
1339         test_executing_on_unreadable_memory,
1340         test_ptrace_of_child,
1341         test_pkey_syscalls_on_non_allocated_pkey,
1342         test_pkey_syscalls_bad_args,
1343         test_pkey_alloc_exhaust,
1344 };
1345
1346 void run_tests_once(void)
1347 {
1348         int *ptr;
1349         int prot = PROT_READ|PROT_WRITE;
1350
1351         for (test_nr = 0; test_nr < ARRAY_SIZE(pkey_tests); test_nr++) {
1352                 int pkey;
1353                 int orig_pkru_faults = pkru_faults;
1354
1355                 dprintf1("======================\n");
1356                 dprintf1("test %d preparing...\n", test_nr);
1357
1358                 tracing_on();
1359                 pkey = alloc_random_pkey();
1360                 dprintf1("test %d starting with pkey: %d\n", test_nr, pkey);
1361                 ptr = malloc_pkey(PAGE_SIZE, prot, pkey);
1362                 dprintf1("test %d starting...\n", test_nr);
1363                 pkey_tests[test_nr](ptr, pkey);
1364                 dprintf1("freeing test memory: %p\n", ptr);
1365                 free_pkey_malloc(ptr);
1366                 sys_pkey_free(pkey);
1367
1368                 dprintf1("pkru_faults: %d\n", pkru_faults);
1369                 dprintf1("orig_pkru_faults: %d\n", orig_pkru_faults);
1370
1371                 tracing_off();
1372                 close_test_fds();
1373
1374                 printf("test %2d PASSED (itertation %d)\n", test_nr, iteration_nr);
1375                 dprintf1("======================\n\n");
1376         }
1377         iteration_nr++;
1378 }
1379
1380 void pkey_setup_shadow(void)
1381 {
1382         shadow_pkru = __rdpkru();
1383 }
1384
1385 int main(void)
1386 {
1387         int nr_iterations = 22;
1388
1389         srand((unsigned int)time(NULL));
1390
1391         setup_handlers();
1392
1393         printf("has pku: %d\n", cpu_has_pku());
1394
1395         if (!cpu_has_pku()) {
1396                 int size = PAGE_SIZE;
1397                 int *ptr;
1398
1399                 printf("running PKEY tests for unsupported CPU/OS\n");
1400
1401                 ptr  = mmap(NULL, size, PROT_NONE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
1402                 assert(ptr != (void *)-1);
1403                 test_mprotect_pkey_on_unsupported_cpu(ptr, 1);
1404                 exit(0);
1405         }
1406
1407         pkey_setup_shadow();
1408         printf("startup pkru: %x\n", rdpkru());
1409         setup_hugetlbfs();
1410
1411         while (nr_iterations-- > 0)
1412                 run_tests_once();
1413
1414         printf("done (all tests OK)\n");
1415         return 0;
1416 }