1 /*
2  * Copyright (c) 2023, Meta
3  * Copyright (c) 2025 Tenstorrent AI ULC
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #ifndef ZEPHYR_LIB_POSIX_POSIX_CLOCK_H_
9 #define ZEPHYR_LIB_POSIX_POSIX_CLOCK_H_
10 
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include <time.h>
14 
15 #include <zephyr/posix/sys/time.h>
16 #include <zephyr/sys/clock.h>
17 #include <zephyr/sys/timeutil.h>
18 
19 #ifdef __cplusplus
20 extern "C" {
21 #endif
22 
23 /** @cond INTERNAL_HIDDEN */
24 
ts_to_ns(const struct timespec * ts)25 static inline int64_t ts_to_ns(const struct timespec *ts)
26 {
27 	return ts->tv_sec * NSEC_PER_SEC + ts->tv_nsec;
28 }
29 
ts_to_ms(const struct timespec * ts)30 static inline int64_t ts_to_ms(const struct timespec *ts)
31 {
32 	return ts->tv_sec * MSEC_PER_SEC + ts->tv_nsec / NSEC_PER_MSEC;
33 }
34 
tv_to_ts(const struct timeval * tv,struct timespec * ts)35 static inline void tv_to_ts(const struct timeval *tv, struct timespec *ts)
36 {
37 	ts->tv_sec = tv->tv_sec;
38 	ts->tv_nsec = tv->tv_usec * NSEC_PER_USEC;
39 }
40 
tp_ge(const struct timespec * a,const struct timespec * b)41 static inline bool tp_ge(const struct timespec *a, const struct timespec *b)
42 {
43 	return timespec_compare(a, b) >= 0;
44 }
45 
tp_diff(const struct timespec * a,const struct timespec * b)46 static inline int64_t tp_diff(const struct timespec *a, const struct timespec *b)
47 {
48 	return ts_to_ns(a) - ts_to_ns(b);
49 }
50 
51 /* lo <= (a - b) < hi */
tp_diff_in_range_ns(const struct timespec * a,const struct timespec * b,int64_t lo,int64_t hi)52 static inline bool tp_diff_in_range_ns(const struct timespec *a, const struct timespec *b,
53 				       int64_t lo, int64_t hi)
54 {
55 	int64_t diff = tp_diff(a, b);
56 
57 	return diff >= lo && diff < hi;
58 }
59 
60 uint32_t timespec_to_timeoutms(int clock_id, const struct timespec *abstime);
61 
62 /** INTERNAL_HIDDEN @endcond */
63 
64 #ifdef __cplusplus
65 }
66 #endif
67 
68 #endif
69