From bf1d3db1d40e7c631d3224c9d5395375c32e589e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andrzej=20G=C5=82=C4=85bek?= Date: Mon, 2 Jan 2023 09:35:58 +0100 Subject: [PATCH] drivers: nrf_rtc_timer: Simplify sys_clock_set_timeout calculations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove unnecessary decreasing of the number of ticks by 1 (it was then increased by 1 when it was converted to the number of cycles) and add a comment that clarifies the way that ticks < 1 are handled. Signed-off-by: Andrzej Głąbek --- drivers/timer/nrf_rtc_timer.c | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/drivers/timer/nrf_rtc_timer.c b/drivers/timer/nrf_rtc_timer.c index b3b2cadeae5..98f5b3874bb 100644 --- a/drivers/timer/nrf_rtc_timer.c +++ b/drivers/timer/nrf_rtc_timer.c @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -592,12 +593,17 @@ void sys_clock_set_timeout(int32_t ticks, bool idle) return; } - ticks = (ticks == K_TICKS_FOREVER) ? MAX_TICKS : ticks; - ticks = CLAMP(ticks - 1, 0, (int32_t)MAX_TICKS); - /* If timeout is set to max we assume that system is idle and timeout - * is set to forever. - */ - sys_busy = (ticks < (MAX_TICKS - 1)); + if (ticks == K_TICKS_FOREVER) { + cyc = MAX_TICKS * CYC_PER_TICK; + sys_busy = false; + } else { + /* Value of ticks can be zero or negative, what means "announce + * the next tick" (the same as ticks equal to 1). + */ + cyc = CLAMP(ticks, 1, (int32_t)MAX_TICKS); + cyc *= CYC_PER_TICK; + sys_busy = true; + } uint32_t unannounced = z_nrf_rtc_timer_read() - last_count; @@ -607,15 +613,14 @@ void sys_clock_set_timeout(int32_t ticks, bool idle) * before the existing one triggers the interrupt. */ if (unannounced >= COUNTER_HALF_SPAN) { - ticks = 0; + cyc = 0; } /* Get the cycles from last_count to the tick boundary after * the requested ticks have passed starting now. */ - cyc = ticks * CYC_PER_TICK + 1 + unannounced; - cyc += (CYC_PER_TICK - 1); - cyc = (cyc / CYC_PER_TICK) * CYC_PER_TICK; + cyc += unannounced; + cyc = ceiling_fraction(cyc, CYC_PER_TICK) * CYC_PER_TICK; /* Due to elapsed time the calculation above might produce a * duration that laps the counter. Don't let it.