clock: Fix timing error.

This commit resolves a timing error caused by the round-up behavior in clock_time2ticks. In rare cases, this could lead to a two-tick increment within a single tick interval. To fix this, we introduced clock_time2ticks_floor, which guarantees the correct semantics for obtaining current system ticks.

Signed-off-by: ouyangxiangzhen <ouyangxiangzhen@xiaomi.com>
This commit is contained in:
ouyangxiangzhen
2025-05-09 14:55:10 +08:00
committed by Xiang Xiao
parent c67ac63da3
commit 2e8583f759
5 changed files with 11 additions and 7 deletions
+4
View File
@@ -353,6 +353,10 @@ EXTERN volatile clock_t g_system_ticks;
#define clock_time2ticks(ts) \
((clock_t)(ts)->tv_sec * TICK_PER_SEC + NSEC2TICK((uint32_t)(ts)->tv_nsec))
#define clock_time2ticks_floor(ts) \
((clock_t)(ts)->tv_sec * TICK_PER_SEC + \
div_const((uint32_t)(ts)->tv_nsec, NSEC_PER_TICK))
#define clock_usec2time(ts, usec) \
do \
{ \
+1 -1
View File
@@ -395,7 +395,7 @@ int oneshot_tick_current(FAR struct oneshot_lowerhalf_s *lower,
}
ret = lower->ops->current(lower, &ts);
*ticks = clock_time2ticks(&ts);
*ticks = clock_time2ticks_floor(&ts);
return ret;
}
+1 -1
View File
@@ -84,7 +84,7 @@ clock_t clock_systime_ticks(void)
};
clock_systime_timespec(&ts);
return clock_time2ticks(&ts);
return clock_time2ticks_floor(&ts);
#elif defined(CONFIG_ALARM_ARCH) || \
defined(CONFIG_TIMER_ARCH) || \
defined(CONFIG_SCHED_TICKLESS)
+4 -4
View File
@@ -130,7 +130,7 @@ int up_timer_gettick(FAR clock_t *ticks)
struct timespec ts;
int ret;
ret = up_timer_gettime(&ts);
*ticks = clock_time2ticks(&ts);
*ticks = clock_time2ticks_floor(&ts);
return ret;
}
#endif
@@ -149,7 +149,7 @@ int up_alarm_tick_cancel(FAR clock_t *ticks)
struct timespec ts;
int ret;
ret = up_alarm_cancel(&ts);
*ticks = clock_time2ticks(&ts);
*ticks = clock_time2ticks_floor(&ts);
return ret;
}
# else
@@ -165,7 +165,7 @@ int up_timer_tick_cancel(FAR clock_t *ticks)
struct timespec ts;
int ret;
ret = up_timer_cancel(&ts);
*ticks = clock_time2ticks(&ts);
*ticks = clock_time2ticks_floor(&ts);
return ret;
}
# endif
@@ -494,7 +494,7 @@ void nxsched_alarm_expiration(FAR const struct timespec *ts)
DEBUGASSERT(ts);
ticks = clock_time2ticks(ts);
ticks = clock_time2ticks_floor(ts);
nxsched_alarm_tick_expiration(ticks);
}
#endif
+1 -1
View File
@@ -331,7 +331,7 @@ int timer_settime(timer_t timerid, int flags,
timer->pt_expected = clock_systime_ticks() + delay;
}
/* delay+1 is to prevent the insufficient sleep time if we are
/* This is to prevent the insufficient sleep time if we are
* currently near the boundary to the next tick.
* | current_tick | current_tick + 1 | current_tick + 2 | .... |
* | ^ Here we get the current tick