1 /*
2  * Copyright (c) 2020 Intel Corporation.
3  * Copyright (c) 2021 Microchip Technology Inc.
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/arch/arm/arch.h>
9 #include <zephyr/kernel.h>
10 #include <zephyr/sys_clock.h>
11 #include <zephyr/timing/timing.h>
12 #include <soc.h>
13 
14 /*
15  * This code is conditionally built please refer to the SoC cmake file and
16  * is not built normally. If this is is not built then timer5 is available
17  * for other uses.
18  */
19 #define BTMR_XEC_REG_BASE						\
20 	((struct btmr_regs *)(DT_REG_ADDR(DT_NODELABEL(timer5))))
21 
soc_timing_init(void)22 void soc_timing_init(void)
23 {
24 	struct btmr_regs *regs = BTMR_XEC_REG_BASE;
25 
26 	/* Setup counter */
27 	regs->CTRL = MCHP_BTMR_CTRL_ENABLE | MCHP_BTMR_CTRL_AUTO_RESTART |
28 		     MCHP_BTMR_CTRL_COUNT_UP;
29 
30 	regs->PRLD = 0; /* Preload */
31 	regs->CNT = 0; /* Counter value */
32 
33 	regs->IEN = 0; /* Disable interrupt */
34 	regs->STS = 1; /* Clear interrupt */
35 }
36 
soc_timing_start(void)37 void soc_timing_start(void)
38 {
39 	regs->CTRL |= MCHP_BTMR_CTRL_START;
40 }
41 
soc_timing_stop(void)42 void soc_timing_stop(void)
43 {
44 	regs->CTRL &= ~MCHP_BTMR_CTRL_START;
45 }
46 
soc_timing_counter_get(void)47 timing_t soc_timing_counter_get(void)
48 {
49 	return regs->CNT;
50 }
51 
soc_timing_cycles_get(volatile timing_t * const start,volatile timing_t * const end)52 uint64_t soc_timing_cycles_get(volatile timing_t *const start,
53 			       volatile timing_t *const end)
54 {
55 	return *end - *start;
56 }
57 
soc_timing_freq_get(void)58 uint64_t soc_timing_freq_get(void)
59 {
60 	return CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC;
61 }
62 
soc_timing_cycles_to_ns(uint64_t cycles)63 uint64_t soc_timing_cycles_to_ns(uint64_t cycles)
64 {
65 	return cycles * NSEC_PER_SEC / CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC;
66 }
67 
soc_timing_cycles_to_ns_avg(uint64_t cycles,uint32_t count)68 uint64_t soc_timing_cycles_to_ns_avg(uint64_t cycles, uint32_t count)
69 {
70 	return (uint32_t)soc_timing_cycles_to_ns(cycles) / count;
71 }
72 
soc_timing_freq_get_mhz(void)73 uint32_t soc_timing_freq_get_mhz(void)
74 {
75 	return (uint32_t)(soc_timing_freq_get() / 1000000);
76 }
77