1 /*
2  * Copyright (C) 2018-2022 Intel Corporation.
3  * SPDX-License-Identifier: BSD-3-Clause
4  */
5 
6 #ifndef _TIMER_H_
7 #define _TIMER_H_
8 
9 #include <time.h>  // for struct itimerspec
10 #include <sys/param.h>
11 
12 struct acrn_timer {
13 	int32_t fd;
14 	int32_t clockid;
15 	struct mevent *mevp;
16 	void (*callback)(void *, uint64_t);
17 	void *callback_param;
18 };
19 
20 int32_t
21 acrn_timer_init(struct acrn_timer *timer, void (*cb)(void *, uint64_t), void *param);
22 void
23 acrn_timer_deinit(struct acrn_timer *timer);
24 int32_t
25 acrn_timer_settime(struct acrn_timer *timer, const struct itimerspec *new_value);
26 int32_t
27 acrn_timer_settime_abs(struct acrn_timer *timer,
28 		const struct itimerspec *new_value);
29 int32_t
30 acrn_timer_gettime(struct acrn_timer *timer, struct itimerspec *cur_value);
31 
32 #define NS_PER_SEC	(1000000000ULL)
33 
34 static inline uint64_t
ts_to_ticks(const uint32_t freq,const struct timespec * const ts)35 ts_to_ticks(const uint32_t freq, const struct timespec *const ts)
36 {
37 	uint64_t tv_sec_ticks, tv_nsec_ticks;
38 
39 	tv_sec_ticks = ts->tv_sec * freq;
40 	tv_nsec_ticks = (ts->tv_nsec * freq) / NS_PER_SEC;
41 
42 	return tv_sec_ticks + tv_nsec_ticks;
43 }
44 
45 static inline void
ticks_to_ts(const uint32_t freq,const uint64_t ticks,struct timespec * const ts)46 ticks_to_ts(const uint32_t freq, const uint64_t ticks,
47 		struct timespec *const ts)
48 {
49 	uint64_t ns;
50 
51 	ns = howmany(ticks * NS_PER_SEC, freq);
52 
53 	ts->tv_sec = ns / NS_PER_SEC;
54 	ts->tv_nsec = ns % NS_PER_SEC;
55 }
56 #endif /* _VTIMER_ */
57