xref: /linux/tools/testing/selftests/powerpc/pmu/ebb/cycles_with_freeze_test.c (revision a13d7201d7deedcbb6ac6efa94a1a7d34d3d79ec)
1 /*
2  * Copyright 2014, Michael Ellerman, IBM Corp.
3  * Licensed under GPLv2.
4  */
5 
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <stdbool.h>
9 
10 #include "ebb.h"
11 
12 
13 /*
14  * Test of counting cycles while using MMCR0_FC (freeze counters) to only count
15  * parts of the code. This is complicated by the fact that FC is set by the
16  * hardware when the event overflows. We may take the EBB after we have set FC,
17  * so we have to be careful about whether we clear FC at the end of the EBB
18  * handler or not.
19  */
20 
21 static bool counters_frozen = false;
22 static int ebbs_while_frozen = 0;
23 
24 static void ebb_callee(void)
25 {
26 	uint64_t mask, val;
27 
28 	mask = MMCR0_PMAO | MMCR0_FC;
29 
30 	val = mfspr(SPRN_BESCR);
31 	if (!(val & BESCR_PMEO)) {
32 		ebb_state.stats.spurious++;
33 		goto out;
34 	}
35 
36 	ebb_state.stats.ebb_count++;
37 	trace_log_counter(ebb_state.trace, ebb_state.stats.ebb_count);
38 
39 	val = mfspr(SPRN_MMCR0);
40 	trace_log_reg(ebb_state.trace, SPRN_MMCR0, val);
41 
42 	if (counters_frozen) {
43 		trace_log_string(ebb_state.trace, "frozen");
44 		ebbs_while_frozen++;
45 		mask &= ~MMCR0_FC;
46 	}
47 
48 	count_pmc(1, sample_period);
49 out:
50 	reset_ebb_with_clear_mask(mask);
51 }
52 
53 int cycles_with_freeze(void)
54 {
55 	struct event event;
56 	uint64_t val;
57 	bool fc_cleared;
58 
59 	event_init_named(&event, 0x1001e, "cycles");
60 	event_leader_ebb_init(&event);
61 
62 	event.attr.exclude_kernel = 1;
63 	event.attr.exclude_hv = 1;
64 	event.attr.exclude_idle = 1;
65 
66 	FAIL_IF(event_open(&event));
67 
68 	setup_ebb_handler(ebb_callee);
69 	ebb_global_enable();
70 	FAIL_IF(ebb_event_enable(&event));
71 
72 	mtspr(SPRN_PMC1, pmc_sample_period(sample_period));
73 
74 	fc_cleared = false;
75 
76 	/* Make sure we loop until we take at least one EBB */
77 	while ((ebb_state.stats.ebb_count < 20 && !fc_cleared) ||
78 		ebb_state.stats.ebb_count < 1)
79 	{
80 		counters_frozen = false;
81 		mb();
82 		mtspr(SPRN_MMCR0, mfspr(SPRN_MMCR0) & ~MMCR0_FC);
83 
84 		FAIL_IF(core_busy_loop());
85 
86 		counters_frozen = true;
87 		mb();
88 		mtspr(SPRN_MMCR0, mfspr(SPRN_MMCR0) |  MMCR0_FC);
89 
90 		val = mfspr(SPRN_MMCR0);
91 		if (! (val & MMCR0_FC)) {
92 			printf("Outside of loop, FC NOT set MMCR0 0x%lx\n", val);
93 			fc_cleared = true;
94 		}
95 	}
96 
97 	ebb_global_disable();
98 	ebb_freeze_pmcs();
99 
100 	count_pmc(1, sample_period);
101 
102 	dump_ebb_state();
103 
104 	printf("EBBs while frozen %d\n", ebbs_while_frozen);
105 
106 	event_close(&event);
107 
108 	FAIL_IF(ebb_state.stats.ebb_count == 0);
109 	FAIL_IF(fc_cleared);
110 
111 	return 0;
112 }
113 
114 int main(void)
115 {
116 	return test_harness(cycles_with_freeze, "cycles_with_freeze");
117 }
118