1 // SPDX-License-Identifier: GPL-2.0
9 #include <linux/types.h>
12 #include "tests/tests.h"
15 #include "arch-tests.h"
17 static u64
rdpmc(unsigned int counter
)
19 unsigned int low
, high
;
21 asm volatile("rdpmc" : "=a" (low
), "=d" (high
) : "c" (counter
));
23 return low
| ((u64
)high
) << 32;
26 static u64
rdtsc(void)
28 unsigned int low
, high
;
30 asm volatile("rdtsc" : "=a" (low
), "=d" (high
));
32 return low
| ((u64
)high
) << 32;
35 static u64
mmap_read_self(void *addr
)
37 struct perf_event_mmap_page
*pc
= addr
;
38 u32 seq
, idx
, time_mult
= 0, time_shift
= 0;
39 u64 count
, cyc
= 0, time_offset
= 0, enabled
, running
, delta
;
45 enabled
= pc
->time_enabled
;
46 running
= pc
->time_running
;
48 if (enabled
!= running
) {
50 time_mult
= pc
->time_mult
;
51 time_shift
= pc
->time_shift
;
52 time_offset
= pc
->time_offset
;
58 count
+= rdpmc(idx
- 1);
61 } while (pc
->lock
!= seq
);
63 if (enabled
!= running
) {
66 quot
= (cyc
>> time_shift
);
67 rem
= cyc
& (((u64
)1 << time_shift
) - 1);
68 delta
= time_offset
+ quot
* time_mult
+
69 ((rem
* time_mult
) >> time_shift
);
75 quot
= count
/ running
;
76 rem
= count
% running
;
77 count
= quot
* enabled
+ (rem
* enabled
) / running
;
84 * If the RDPMC instruction faults then signal this back to the test parent task:
86 static void segfault_handler(int sig __maybe_unused
,
87 siginfo_t
*info __maybe_unused
,
88 void *uc __maybe_unused
)
93 static int __test__rdpmc(void)
100 struct perf_event_attr attr
= {
101 .type
= PERF_TYPE_HARDWARE
,
102 .config
= PERF_COUNT_HW_INSTRUCTIONS
,
107 char sbuf
[STRERR_BUFSIZE
];
109 sigfillset(&sa
.sa_mask
);
110 sa
.sa_sigaction
= segfault_handler
;
112 sigaction(SIGSEGV
, &sa
, NULL
);
114 fd
= sys_perf_event_open(&attr
, 0, -1, -1,
115 perf_event_open_cloexec_flag());
117 pr_err("Error: sys_perf_event_open() syscall returned "
118 "with %d (%s)\n", fd
,
119 str_error_r(errno
, sbuf
, sizeof(sbuf
)));
123 addr
= mmap(NULL
, page_size
, PROT_READ
, MAP_SHARED
, fd
, 0);
124 if (addr
== (void *)(-1)) {
125 pr_err("Error: mmap() syscall returned with (%s)\n",
126 str_error_r(errno
, sbuf
, sizeof(sbuf
)));
130 for (n
= 0; n
< 6; n
++) {
131 u64 stamp
, now
, delta
;
133 stamp
= mmap_read_self(addr
);
135 for (i
= 0; i
< loops
; i
++)
138 now
= mmap_read_self(addr
);
142 pr_debug("%14d: %14Lu\n", n
, (long long)delta
);
147 munmap(addr
, page_size
);
158 int test__rdpmc(struct test
*test __maybe_unused
, int subtest __maybe_unused
)
170 ret
= __test__rdpmc();
175 wret
= waitpid(pid
, &status
, 0);
176 if (wret
< 0 || status
)