1 /*
2  * Copyright (c) 2018 Intel Corporation
3  * Copyright (c) 2023, Meta
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 #include <sys/time.h>
8 #include <time.h>
9 #include <unistd.h>
10 
11 #include <zephyr/ztest.h>
12 #include <zephyr/logging/log.h>
13 
ts_to_ns(const struct timespec * ts)14 static inline int64_t ts_to_ns(const struct timespec *ts)
15 {
16 	return ts->tv_sec * NSEC_PER_SEC + ts->tv_nsec;
17 }
18 
tv_to_ts(const struct timeval * tv,struct timespec * ts)19 static inline void tv_to_ts(const struct timeval *tv, struct timespec *ts)
20 {
21 	ts->tv_sec = tv->tv_sec;
22 	ts->tv_nsec = tv->tv_usec * NSEC_PER_USEC;
23 }
24 
25 #define _tp_op(_a, _b, _op) (ts_to_ns(_a) _op ts_to_ns(_b))
26 
27 #define _decl_op(_type, _name, _op)                                                                \
28 	static inline _type _name(const struct timespec *_a, const struct timespec *_b)            \
29 	{                                                                                          \
30 		return _tp_op(_a, _b, _op);                                                        \
31 	}
32 
33 _decl_op(bool, tp_ge, >=); /* a >= b */
34 
ZTEST(clock,test_gettimeofday)35 ZTEST(clock, test_gettimeofday)
36 {
37 	struct timeval tv;
38 	struct timespec ts;
39 	struct timespec rts;
40 
41 	if (false) {
42 		/* undefined behaviour */
43 		errno = 0;
44 		zassert_equal(gettimeofday(NULL, NULL), -1);
45 		zassert_equal(errno, EINVAL);
46 	}
47 
48 	/* Validate gettimeofday API */
49 	zassert_ok(gettimeofday(&tv, NULL));
50 	zassert_ok(clock_gettime(CLOCK_REALTIME, &rts));
51 
52 	/* TESTPOINT: Check if time obtained from
53 	 * gettimeofday is same or more than obtained
54 	 * from clock_gettime
55 	 */
56 	tv_to_ts(&tv, &ts);
57 	zassert_true(tp_ge(&rts, &ts));
58 }
59 
60 ZTEST_SUITE(clock, NULL, NULL, NULL, NULL, NULL);
61