From d8c129fc476f63822ce6ae430298482631adcc9e Mon Sep 17 00:00:00 2001 From: Kaspar Schleiser Date: Wed, 22 Apr 2020 10:02:17 +0200 Subject: [PATCH] ztimer: periph_rtt: ensure RTT_MAX_VALUE is honored Previously, ztimer would happily set an absolute RTT alarm value that exceeds RTT's maximum value (though not a longer interval), as the `val` was simply added to `rtt_get_counter()`. This commit ensures that the target value wraps around RTT_MAX_VALUE. Fixes #13920. --- sys/ztimer/periph_rtt.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/sys/ztimer/periph_rtt.c b/sys/ztimer/periph_rtt.c index 0d1c79914c..64b5c63398 100644 --- a/sys/ztimer/periph_rtt.c +++ b/sys/ztimer/periph_rtt.c @@ -19,6 +19,7 @@ * * @} */ +#include "assert.h" #include "periph/rtt.h" #include "ztimer/periph_rtt.h" @@ -50,7 +51,16 @@ static void _ztimer_periph_rtt_set(ztimer_clock_t *clock, uint32_t val) } unsigned state = irq_disable(); - rtt_set_alarm(rtt_get_counter() + val, _ztimer_periph_rtt_callback, clock); + + /* ensure RTT_MAX_VALUE is (2^n - 1) */ + static_assert((RTT_MAX_VALUE == UINT32_MAX) || + !((RTT_MAX_VALUE + 1) & (RTT_MAX_VALUE)), + "RTT_MAX_VALUE needs to be (2^n) - 1"); + + rtt_set_alarm( + (rtt_get_counter() + val) & RTT_MAX_VALUE, _ztimer_periph_rtt_callback, + clock); + irq_restore(state); }