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

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


The following commit(s) were added to refs/heads/master by this push:
     new ab195942333 arch/x86_64/intel64: Fix the precision and the SMP step of 
the TSC RTC.
ab195942333 is described below

commit ab195942333886ce5e8c21463acca5d2e75b3951
Author: Marco Casaroli <[email protected]>
AuthorDate: Tue Nov 17 14:03:34 2026 +0100

    arch/x86_64/intel64: Fix the precision and the SMP step of the TSC RTC.
    
    rtc_read() converted TSC cycles to nanoseconds with
    (tsc / (freq / 1000000)) * 1000.  freq / 1000000 drops the part of the
    frequency below 1 MHz, so the clock runs fast, and the result has a step
    of 1 us.  Calculate the seconds and the remainder separately, as
    up_perf_convert() does.
    
    When the TSC value was smaller than the last value, rtc_read() added
    0xffffffffffffffff - last to it, for a wrap that the 64-bit TSC does not
    do.  On SMP a CPU with a TSC that is a little behind gets there, and the
    time then goes forward by about 2^64 cycles.  Keep the last value
    instead, so that the time does not go back.
    
    Assisted-by: Claude Code:claude-opus-5-5
    Signed-off-by: Marco Casaroli <[email protected]>
---
 arch/x86_64/src/intel64/intel64_rtc.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/arch/x86_64/src/intel64/intel64_rtc.c 
b/arch/x86_64/src/intel64/intel64_rtc.c
index 8d01d648a9e..52ace1fbad7 100644
--- a/arch/x86_64/src/intel64/intel64_rtc.c
+++ b/arch/x86_64/src/intel64/intel64_rtc.c
@@ -100,17 +100,21 @@ static unsigned long rtc_read(void)
   uint64_t  tmr = rdtscp();
   irqstate_t flags;
 
+  /* The 64-bit TSC does not wrap.  A smaller value comes from a CPU whose
+   * TSC is behind the TSC of the CPU that read last: keep the last value.
+   */
+
   flags = spin_lock_irqsave(&g_rtc_lock);
   if (tmr < rtc_last)
     {
-      tmr += (0xffffffffffffffffull - rtc_last);
+      tmr = rtc_last;
     }
 
   rtc_last = tmr;
   spin_unlock_irqrestore(&g_rtc_lock, flags);
-  tmr = (tmr / (g_x86_64_timer_freq / 1000000ul)) * 1000l;
 
-  return tmr;
+  return tmr / g_x86_64_timer_freq * NS_PER_SEC +
+         tmr % g_x86_64_timer_freq * NS_PER_SEC / g_x86_64_timer_freq;
 }
 
 /****************************************************************************

Reply via email to