Skip to content

Commit

Permalink
shared/runtime/softtimer: Fix ticks range when computing ticks diff.
Browse files Browse the repository at this point in the history
The previous computation incorrectly assumed that the uint32_t ticks
counter MICROPY_SOFT_TIMER_TICKS_MS was in the range [0,0x80000000) where
its actually [0,0xffffffff].  This means the diff calculation can be
simplified compared to the original implementation copied from
utime_mphal.c, which has to deal with a ticks range constrained by the
small int range.

Signed-off-by: Jim Mussared <jim.mussared@gmail.com>
  • Loading branch information
jimmo authored and dpgeorge committed Feb 17, 2023
1 parent de1f1dd commit b1cdb20
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions shared/runtime/softtimer.c
Expand Up @@ -30,9 +30,6 @@
#include "py/runtime.h"
#include "softtimer.h"

#define TICKS_PERIOD 0x80000000
#define TICKS_DIFF(t1, t0) ((int32_t)(((t1 - t0 + TICKS_PERIOD / 2) & (TICKS_PERIOD - 1)) - TICKS_PERIOD / 2))

extern __IO uint32_t MICROPY_SOFT_TIMER_TICKS_MS;

volatile uint32_t soft_timer_next;
Expand All @@ -42,16 +39,23 @@ volatile uint32_t soft_timer_next;
// and is explicitly GC traced by soft_timer_gc_mark_all().
STATIC soft_timer_entry_t *soft_timer_heap;

static inline int32_t ticks_diff(uint32_t t1, uint32_t t0) {
// t1 is after t0 (i.e. positive result) if there exists a uint32_t X <= INT_MAX
// such that t0 + X = t1. Otherwise t1 is interepreted to be earlier than
// t0 (negative result).
return t1 - t0;
}

STATIC int soft_timer_lt(mp_pairheap_t *n1, mp_pairheap_t *n2) {
soft_timer_entry_t *e1 = (soft_timer_entry_t *)n1;
soft_timer_entry_t *e2 = (soft_timer_entry_t *)n2;
return TICKS_DIFF(e1->expiry_ms, e2->expiry_ms) < 0;
return ticks_diff(e1->expiry_ms, e2->expiry_ms) < 0;
}

STATIC void soft_timer_schedule_systick(uint32_t ticks_ms) {
uint32_t irq_state = disable_irq();
uint32_t uw_tick = MICROPY_SOFT_TIMER_TICKS_MS;
if (TICKS_DIFF(ticks_ms, uw_tick) <= 0) {
if (ticks_diff(ticks_ms, uw_tick) <= 0) {
soft_timer_next = uw_tick + 1;
} else {
soft_timer_next = ticks_ms;
Expand Down Expand Up @@ -79,7 +83,7 @@ void soft_timer_deinit(void) {
void soft_timer_handler(void) {
uint32_t ticks_ms = MICROPY_SOFT_TIMER_TICKS_MS;
soft_timer_entry_t *heap = soft_timer_heap;
while (heap != NULL && TICKS_DIFF(heap->expiry_ms, ticks_ms) <= 0) {
while (heap != NULL && ticks_diff(heap->expiry_ms, ticks_ms) <= 0) {
soft_timer_entry_t *entry = heap;
heap = (soft_timer_entry_t *)mp_pairheap_pop(soft_timer_lt, &heap->pairheap);
if (entry->flags & SOFT_TIMER_FLAG_PY_CALLBACK) {
Expand Down

0 comments on commit b1cdb20

Please sign in to comment.