Skip to content

Commit 662f37d

Browse files
author
Chris Friedt
committed
tests: posix: clock: ensure overflow is consistent
Add a test to verify previous fixes when calculating time in seconds for `clock_gettime()`. Signed-off-by: Chris Friedt <[email protected]>
1 parent 504b5cf commit 662f37d

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

tests/posix/common/src/clock.c

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,3 +122,67 @@ ZTEST(posix_apis, test_posix_realtime)
122122
zassert_true(rts.tv_nsec >= tv.tv_usec * NSEC_PER_USEC,
123123
"gettimeofday didn't provide correct result");
124124
}
125+
126+
static inline bool ts_gt(const struct timespec *a, const struct timespec *b)
127+
{
128+
__ASSERT_NO_MSG(a->tv_nsec < NSEC_PER_SEC);
129+
__ASSERT_NO_MSG(a->tv_nsec >= 0);
130+
__ASSERT_NO_MSG(b->tv_nsec < NSEC_PER_SEC);
131+
__ASSERT_NO_MSG(b->tv_nsec >= 0);
132+
133+
if (a->tv_sec > b->tv_sec) {
134+
return true;
135+
}
136+
137+
if (a->tv_sec < b->tv_sec) {
138+
return false;
139+
}
140+
141+
if (a->tv_nsec > b->tv_nsec) {
142+
return true;
143+
}
144+
145+
return false;
146+
}
147+
148+
static inline void ts_print(const char *label, const struct timespec *ts)
149+
{
150+
printk("%s: {%" PRIu64 ", %" PRIu64 "}\n", label, (uint64_t)ts->tv_sec,
151+
(uint64_t)ts->tv_nsec);
152+
}
153+
154+
ZTEST(posix_apis, test_clock_gettime_rollover)
155+
{
156+
uint64_t t;
157+
struct timespec ts[3];
158+
const uint64_t rollover_s = UINT64_MAX / CONFIG_SYS_CLOCK_TICKS_PER_SEC;
159+
160+
printk("CONFIG_SYS_CLOCK_TICKS_PER_SEC: %u\n", CONFIG_SYS_CLOCK_TICKS_PER_SEC);
161+
printk("rollover_s: %" PRIu64 "\n", rollover_s);
162+
163+
t = UINT64_MAX - 1;
164+
/* align to tick boundary */
165+
k_sleep(K_TICKS(1));
166+
sys_clock_tick_set(t);
167+
zassert_ok(clock_gettime(CLOCK_MONOTONIC, &ts[0]));
168+
ts_print("t-1", &ts[0]);
169+
zassert_equal(rollover_s, ts[0].tv_sec);
170+
171+
t = UINT64_MAX;
172+
/* align to tick boundary */
173+
k_sleep(K_TICKS(1));
174+
sys_clock_tick_set(t);
175+
zassert_ok(clock_gettime(CLOCK_MONOTONIC, &ts[1]));
176+
ts_print("t+0", &ts[1]);
177+
zassert_equal(rollover_s, ts[1].tv_sec);
178+
zassert_true(ts_gt(&ts[1], &ts[0]));
179+
180+
t = UINT64_MAX + 1;
181+
/* align to tick boundary */
182+
k_sleep(K_TICKS(1));
183+
sys_clock_tick_set(t);
184+
zassert_ok(clock_gettime(CLOCK_MONOTONIC, &ts[2]));
185+
ts_print("t+1", &ts[2]);
186+
zassert_equal(0, ts[2].tv_sec);
187+
zassert_true(ts_gt(&ts[1], &ts[2]));
188+
}

0 commit comments

Comments
 (0)