This is an automated email from the ASF dual-hosted git repository.

xiaoxiang781216 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit 1a3185beebf43093ffcc7d4e2caae57ebc2eef44
Author: yushuailong <[email protected]>
AuthorDate: Wed Jun 10 19:21:30 2026 +0800

    arch/risc-v/esp32c3-legacy: Fix non-atomic clock read in up_rtc_rdalarm.
    
    up_rtc_rdalarm() computed tv_sec and tv_nsec from two separate
    evaluations of rt_timer_time_us() + offset + deadline. The RT timer
    advances between the two calls, so a read that straddles a second
    boundary yields an inconsistent timespec.
    
    Compute the microsecond value once into a local variable and derive
    both fields from that single snapshot.
    
    Signed-off-by: yushuailong <[email protected]>
---
 arch/risc-v/src/esp32c3-legacy/esp32c3_rtc.c | 10 ++++++----
 1 file changed, 6 insertions(+), 4 deletions(-)

diff --git a/arch/risc-v/src/esp32c3-legacy/esp32c3_rtc.c 
b/arch/risc-v/src/esp32c3-legacy/esp32c3_rtc.c
index 0db475b59c5..dc71fa86b32 100644
--- a/arch/risc-v/src/esp32c3-legacy/esp32c3_rtc.c
+++ b/arch/risc-v/src/esp32c3-legacy/esp32c3_rtc.c
@@ -3383,6 +3383,7 @@ int up_rtc_rdalarm(struct timespec *tp, uint32_t alarmid)
 {
   irqstate_t flags;
   struct alm_cbinfo_s *cbinfo;
+  uint64_t time_us;
   DEBUGASSERT(tp != NULL);
   DEBUGASSERT((RTC_ALARM0 <= alarmid) &&
               (alarmid < RTC_ALARM_LAST));
@@ -3393,10 +3394,11 @@ int up_rtc_rdalarm(struct timespec *tp, uint32_t 
alarmid)
 
   cbinfo = &g_alarmcb[alarmid];
 
-  tp->tv_sec = (rt_timer_time_us() + g_rtc_save->offset +
-              cbinfo->deadline_us) / USEC_PER_SEC;
-  tp->tv_nsec = ((rt_timer_time_us() + g_rtc_save->offset +
-              cbinfo->deadline_us) % USEC_PER_SEC) * NSEC_PER_USEC;
+  time_us = rt_timer_time_us() + g_rtc_save->offset +
+            cbinfo->deadline_us;
+
+  tp->tv_sec = time_us / USEC_PER_SEC;
+  tp->tv_nsec = (time_us % USEC_PER_SEC) * NSEC_PER_USEC;
 
   spin_unlock_irqrestore(&g_rtc_lock, flags);
 

Reply via email to