blob: a06f027e9d1642a0c8b12591dae0bfe05e4ec2da [file] [log] [blame]
Erik Bosmanf1326972008-04-11 18:57:22 +02001/*
2 * Tests for prctl(PR_GET_TSC, ...) / prctl(PR_SET_TSC, ...)
3 *
4 * Tests if the control register is updated correctly
5 * when set with prctl()
6 *
7 * Warning: this test will cause a very high load for a few seconds
8 *
9 */
10
11#include <stdio.h>
12#include <stdlib.h>
13#include <unistd.h>
14#include <signal.h>
15#include <inttypes.h>
16#include <wait.h>
17
18
19#include <sys/prctl.h>
20#include <linux/prctl.h>
21
22/* Get/set the process' ability to use the timestamp counter instruction */
23#ifndef PR_GET_TSC
24#define PR_GET_TSC 25
25#define PR_SET_TSC 26
26# define PR_TSC_ENABLE 1 /* allow the use of the timestamp counter */
27# define PR_TSC_SIGSEGV 2 /* throw a SIGSEGV instead of reading the TSC */
28#endif
29
30/* snippet from wikipedia :-) */
31
Peter Foley0421fc82014-09-25 11:23:15 -070032static uint64_t rdtsc(void)
33{
Erik Bosmanf1326972008-04-11 18:57:22 +020034uint32_t lo, hi;
35/* We cannot use "=A", since this would use %rax on x86_64 */
36__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
37return (uint64_t)hi << 32 | lo;
38}
39
40int should_segv = 0;
41
Peter Foley0421fc82014-09-25 11:23:15 -070042static void sigsegv_cb(int sig)
Erik Bosmanf1326972008-04-11 18:57:22 +020043{
44 if (!should_segv)
45 {
46 fprintf(stderr, "FATAL ERROR, rdtsc() failed while enabled\n");
47 exit(0);
48 }
49 if (prctl(PR_SET_TSC, PR_TSC_ENABLE) < 0)
50 {
51 perror("prctl");
52 exit(0);
53 }
54 should_segv = 0;
55
56 rdtsc();
57}
58
Peter Foley0421fc82014-09-25 11:23:15 -070059static void task(void)
Erik Bosmanf1326972008-04-11 18:57:22 +020060{
61 signal(SIGSEGV, sigsegv_cb);
62 alarm(10);
63 for(;;)
64 {
65 rdtsc();
66 if (should_segv)
67 {
68 fprintf(stderr, "FATAL ERROR, rdtsc() succeeded while disabled\n");
69 exit(0);
70 }
71 if (prctl(PR_SET_TSC, PR_TSC_SIGSEGV) < 0)
72 {
73 perror("prctl");
74 exit(0);
75 }
76 should_segv = 1;
77 }
78}
79
80
Mahesh Khanwalkarf0cd1472016-02-13 19:05:31 -050081int main(void)
Erik Bosmanf1326972008-04-11 18:57:22 +020082{
83 int n_tasks = 100, i;
84
85 fprintf(stderr, "[No further output means we're allright]\n");
86
87 for (i=0; i<n_tasks; i++)
88 if (fork() == 0)
89 task();
90
91 for (i=0; i<n_tasks; i++)
92 wait(NULL);
93
94 exit(0);
95}
96