@@ -138,17 +138,9 @@ uint32_t ztimer_set(ztimer_clock_t *clock, ztimer_t *timer, uint32_t val)
138138
139139 unsigned state = irq_disable ();
140140
141- uint32_t now = _ztimer_update_head_offset (clock );
142-
143- bool was_set = false;
144- if (_is_set (clock , timer )) {
145- was_set = _del_entry_from_list (clock , & timer -> base );
146- }
147-
148141#if MODULE_ZTIMER_ONDEMAND
149- /* if the timer wasn't reset on this clock, it acquires the required
150- * ztimer_clock_t. */
151- if (!was_set && _ztimer_acquire (clock ) == true) {
142+ /* warm up our clock ... */
143+ if (_ztimer_acquire (clock ) == true) {
152144 /* compensate delay that turning on the clock has introduced */
153145 if (val > clock -> adjust_clock_start ) {
154146 val -= clock -> adjust_clock_start ;
@@ -159,6 +151,13 @@ uint32_t ztimer_set(ztimer_clock_t *clock, ztimer_t *timer, uint32_t val)
159151 }
160152#endif
161153
154+ uint32_t now = _ztimer_update_head_offset (clock );
155+
156+ bool was_set = false;
157+ if (_is_set (clock , timer )) {
158+ was_set = _del_entry_from_list (clock , & timer -> base );
159+ }
160+
162161 /* optionally subtract a configurable adjustment value */
163162 if (val > clock -> adjust_set ) {
164163 val -= clock -> adjust_set ;
@@ -179,6 +178,19 @@ uint32_t ztimer_set(ztimer_clock_t *clock, ztimer_t *timer, uint32_t val)
179178 clock -> ops -> set (clock , val );
180179 }
181180
181+ /* the clock is armed now
182+ * everthing down below doesn't impact timing */
183+
184+ #if MODULE_ZTIMER_ONDEMAND
185+ if (was_set ) {
186+ /* the given ztimer_t was set in the past
187+ * remove the previously set instance */
188+ _ztimer_release (clock );
189+ }
190+ #else
191+ (void )was_set ;
192+ #endif
193+
182194 irq_restore (state );
183195 return now ;
184196}
@@ -449,6 +461,9 @@ void ztimer_handler(ztimer_clock_t *clock)
449461 entry -> callback (entry -> arg );
450462#if MODULE_ZTIMER_ONDEMAND
451463 no_clock_user_left = _ztimer_release (clock );
464+ if (no_clock_user_left ) {
465+ break ;
466+ }
452467#endif
453468 entry = _now_next (clock );
454469 if (!entry ) {
0 commit comments