From 6717a3742185a8093cbcbb6b4be8eff6ac091389 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Krzysztof=20Chru=C5=9Bci=C5=84ski?= Date: Wed, 15 Jan 2025 11:00:02 +0100 Subject: [PATCH] drivers: timer: nrf_rtc_timer: Optimize z_nrf_rtc_timer_get_ticks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Converting absolute system ticks to RTC ticks is simple. It needs to be multiplied by CYC_PER_TICK (which by default is 1). Complex algorithm was used when driver was not tracking current 64 bit tick and function was returning uint32_t. Signed-off-by: Krzysztof Chruściński --- drivers/timer/nrf_rtc_timer.c | 21 ++++++++------------ include/zephyr/drivers/timer/nrf_rtc_timer.h | 3 +-- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/drivers/timer/nrf_rtc_timer.c b/drivers/timer/nrf_rtc_timer.c index 0fdf951f925..8cd24e17530 100644 --- a/drivers/timer/nrf_rtc_timer.c +++ b/drivers/timer/nrf_rtc_timer.c @@ -197,30 +197,25 @@ uint32_t z_nrf_rtc_timer_compare_read(int32_t chan) uint64_t z_nrf_rtc_timer_get_ticks(k_timeout_t t) { - uint64_t curr_time; - int64_t curr_tick; - int64_t result; int64_t abs_ticks; - do { - curr_time = z_nrf_rtc_timer_read(); - curr_tick = sys_clock_tick_get(); - } while (curr_time != z_nrf_rtc_timer_read()); - abs_ticks = Z_TICK_ABS(t.ticks); if (Z_IS_TIMEOUT_RELATIVE(t)) { return (t.ticks > COUNTER_SPAN) ? - -EINVAL : (curr_time + t.ticks); + -EINVAL : (z_nrf_rtc_timer_read() + t.ticks * CYC_PER_TICK); } /* absolute timeout */ - result = abs_ticks - curr_tick; - - if (result > COUNTER_SPAN) { + /* abs_ticks is int64_t so it has 63 bits. If CYC_PER_TICK is <=2 then + * any abs_ticks will fit in 64 bits after multiplying by CYC_PER_TICK + * but if CYC_PER_TICK is higher then it is possible that abs_ticks cannot + * be converted to RTC ticks and check for overflow is needed. + */ + if ((CYC_PER_TICK > 2) && (abs_ticks > (UINT64_MAX / CYC_PER_TICK))) { return -EINVAL; } - return curr_time + result; + return abs_ticks * CYC_PER_TICK; } /** @brief Function safely sets an alarm. diff --git a/include/zephyr/drivers/timer/nrf_rtc_timer.h b/include/zephyr/drivers/timer/nrf_rtc_timer.h index 57340098c23..55b2bdcd5ae 100644 --- a/include/zephyr/drivers/timer/nrf_rtc_timer.h +++ b/include/zephyr/drivers/timer/nrf_rtc_timer.h @@ -177,8 +177,7 @@ void z_nrf_rtc_timer_abort(int32_t chan); /** @brief Convert system clock time to RTC ticks. * - * @p t can be absolute or relative. @p t cannot be further into the future - * from now than the RTC range (e.g. 512 seconds if RTC is running at 32768 Hz). + * @p t can be absolute or relative. * * @retval Positive value represents @p t in RTC tick value. * @retval -EINVAL if @p t is out of range.