1 /*
2  * Copyright (c) 2018 Oticon A/S
3  * Copyright (c) 2023 Nordic Semiconductor ASA
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <stdint.h>
9 #include "nsi_tracing.h"
10 #include "native_rtc.h"
11 #include "nsi_hw_scheduler.h"
12 #include "nsi_timer_model.h"
13 
14 /**
15  * Return the (simulation) time in microseconds
16  * where clock_type is one of RTC_CLOCK_*
17  */
native_rtc_gettime_us(int clock_type)18 uint64_t native_rtc_gettime_us(int clock_type)
19 {
20 	if (clock_type == RTC_CLOCK_BOOT) {
21 		return nsi_hws_get_time();
22 	} else if (clock_type == RTC_CLOCK_REALTIME) { /* RTC_CLOCK_REALTIME */
23 		return hwtimer_get_simu_rtc_time();
24 	} else if (clock_type == RTC_CLOCK_PSEUDOHOSTREALTIME) {
25 		uint32_t nsec;
26 		uint64_t sec;
27 
28 		hwtimer_get_pseudohost_rtc_time(&nsec, &sec);
29 		return sec * 1000000UL + nsec / 1000U;
30 	}
31 
32 	nsi_print_error_and_exit("Unknown clock source %i\n",
33 				   clock_type);
34 	return 0;
35 }
36 
37 /**
38  * Similar to POSIX clock_gettime()
39  * get the simulation time split in nsec and seconds
40  * where clock_type is one of RTC_CLOCK_*
41  */
native_rtc_gettime(int clock_type,uint32_t * nsec,uint64_t * sec)42 void native_rtc_gettime(int clock_type, uint32_t *nsec, uint64_t *sec)
43 {
44 	if (clock_type == RTC_CLOCK_BOOT || clock_type == RTC_CLOCK_REALTIME) {
45 		uint64_t us = native_rtc_gettime_us(clock_type);
46 		*nsec = (us % 1000000UL) * 1000U;
47 		*sec  = us / 1000000UL;
48 	} else { /* RTC_CLOCK_PSEUDOHOSTREALTIME */
49 		hwtimer_get_pseudohost_rtc_time(nsec, sec);
50 	}
51 }
52 
53 /**
54  * Offset the real time clock by a number of microseconds.
55  * Note that this only affects the RTC_CLOCK_REALTIME and
56  * RTC_CLOCK_PSEUDOHOSTREALTIME clocks.
57  */
native_rtc_offset(int64_t delta_us)58 void native_rtc_offset(int64_t delta_us)
59 {
60 	hwtimer_adjust_rtc_offset(delta_us);
61 }
62 
63 /**
64  * Adjust the speed of the clock source by a multiplicative factor
65  */
native_rtc_adjust_clock(double clock_correction)66 void native_rtc_adjust_clock(double clock_correction)
67 {
68 	hwtimer_adjust_rt_ratio(clock_correction);
69 }
70