1 /*
2  * Copyright (c) 2020 Intel Corporation.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys_clock.h>
9 #include <zephyr/timing/timing.h>
10 #include "altera_avalon_timer_regs.h"
11 
12 #define NIOS2_SUBTRACT_CLOCK_CYCLES(val)                                       \
13 	((IORD_ALTERA_AVALON_TIMER_PERIODH(TIMER_0_BASE) << 16 |               \
14 	  (IORD_ALTERA_AVALON_TIMER_PERIODL(TIMER_0_BASE))) -                  \
15 	 ((uint32_t)val))
16 
17 #define TIMING_INFO_OS_GET_TIME()                                              \
18 	(NIOS2_SUBTRACT_CLOCK_CYCLES(                                          \
19 		((uint32_t)IORD_ALTERA_AVALON_TIMER_SNAPH(TIMER_0_BASE)        \
20 		 << 16) |                                                      \
21 		((uint32_t)IORD_ALTERA_AVALON_TIMER_SNAPL(TIMER_0_BASE))))
22 
arch_timing_init(void)23 void arch_timing_init(void)
24 {
25 }
26 
arch_timing_start(void)27 void arch_timing_start(void)
28 {
29 }
30 
arch_timing_stop(void)31 void arch_timing_stop(void)
32 {
33 }
34 
arch_timing_counter_get(void)35 timing_t arch_timing_counter_get(void)
36 {
37 	IOWR_ALTERA_AVALON_TIMER_SNAPL(TIMER_0_BASE, 10);
38 	return TIMING_INFO_OS_GET_TIME();
39 }
40 
arch_timing_cycles_get(volatile timing_t * const start,volatile timing_t * const end)41 uint64_t arch_timing_cycles_get(volatile timing_t *const start,
42 				volatile timing_t *const end)
43 {
44 	return (*end - *start);
45 }
46 
arch_timing_freq_get(void)47 uint64_t arch_timing_freq_get(void)
48 {
49 	return sys_clock_hw_cycles_per_sec();
50 }
51 
arch_timing_cycles_to_ns(uint64_t cycles)52 uint64_t arch_timing_cycles_to_ns(uint64_t cycles)
53 {
54 	return k_cyc_to_ns_floor64(cycles);
55 }
56 
arch_timing_cycles_to_ns_avg(uint64_t cycles,uint32_t count)57 uint64_t arch_timing_cycles_to_ns_avg(uint64_t cycles, uint32_t count)
58 {
59 	return arch_timing_cycles_to_ns(cycles) / count;
60 }
61 
arch_timing_freq_get_mhz(void)62 uint32_t arch_timing_freq_get_mhz(void)
63 {
64 	return (uint32_t)(arch_timing_freq_get() / 1000000U);
65 }
66