About Kernel Documentation Linux Kernel Contact Linux Resources Linux Blog

Documentation / prctl / disable-tsc-on-off-stress-test.c


Based on kernel version 4.8. Page generated on 2016-10-06 23:18 EST.

1	/*
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	
32	static uint64_t rdtsc(void)
33	{
34	uint32_t lo, hi;
35	/* We cannot use "=A", since this would use %rax on x86_64 */
36	__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
37	return (uint64_t)hi << 32 | lo;
38	}
39	
40	int should_segv = 0;
41	
42	static void sigsegv_cb(int sig)
43	{
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	
59	static void task(void)
60	{
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	
81	int main(void)
82	{
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	}
Hide Line Numbers


About Kernel Documentation Linux Kernel Contact Linux Resources Linux Blog