drivers/timers: Fix non-atomic clock read in up_timer_gettime.

up_timer_gettime() computed tv_sec and tv_nsec from two separate calls
to current_usec(), which returns a free-running microsecond counter.
The counter advances between the two calls, so a read that straddles a
second boundary yields an inconsistent (possibly backwards) timespec.

Read current_usec() once into a local variable and derive both fields
from that single snapshot.

Signed-off-by: yushuailong <yyyusl@qq.com>
This commit is contained in:
yushuailong
2026-06-17 17:12:04 +08:00
committed by Xiang Xiao
parent a6c2cd73b5
commit fb4ffa4ae7
+5 -2
View File
@@ -309,11 +309,14 @@ int weak_function up_timer_gettick(FAR clock_t *ticks)
int weak_function up_timer_gettime(struct timespec *ts)
{
int ret = -EAGAIN;
uint64_t usec;
if (g_timer.lower != NULL)
{
ts->tv_sec = current_usec() / USEC_PER_SEC;
ts->tv_nsec = (current_usec() % USEC_PER_SEC) * NSEC_PER_USEC;
usec = current_usec();
ts->tv_sec = usec / USEC_PER_SEC;
ts->tv_nsec = (usec % USEC_PER_SEC) * NSEC_PER_USEC;
ret = OK;
}