@@ -79,39 +79,36 @@ uint32_t supervisor_ticks_ms32() {
7979extern void run_background_tasks (void );
8080
8181void PLACE_IN_ITCM (supervisor_run_background_tasks_if_tick )() {
82- uint8_t subticks ;
83- uint64_t now = port_get_raw_ticks (& subticks );
84-
85- if (now == background_ticks && (subticks & 0x3 ) != 0 ) {
86- return ;
87- }
88- background_ticks = now ;
89-
82+ // TODO: Add a global that can be set by anyone to indicate we should run background tasks. That
83+ // way we can short circuit the background tasks early. We used to do it based on time but it
84+ // breaks cases where we wake up for a short period and then sleep. If we skipped the last
85+ // background task or more before sleeping we may end up starving a task like USB.
9086 run_background_tasks ();
9187}
9288
93- void supervisor_fake_tick () {
94- uint32_t now = port_get_raw_ticks (NULL );
95- background_ticks = (now - 1 );
96- }
97-
9889void mp_hal_delay_ms (mp_uint_t delay ) {
9990 uint64_t start_tick = port_get_raw_ticks (NULL );
10091 // Adjust the delay to ticks vs ms.
10192 delay = delay * 1024 / 1000 ;
102- uint64_t duration = 0 ;
103- port_interrupt_after_ticks ( delay ) ;
104- while (duration < delay ) {
93+ uint64_t end_tick = start_tick + delay ;
94+ int64_t remaining = delay ;
95+ while (remaining > 0 ) {
10596 RUN_BACKGROUND_TASKS ;
10697 // Check to see if we've been CTRL-Ced by autoreload or the user.
10798 if (MP_STATE_VM (mp_pending_exception ) == MP_OBJ_FROM_PTR (& MP_STATE_VM (mp_kbd_exception )) ||
10899 MP_STATE_VM (mp_pending_exception ) == MP_OBJ_FROM_PTR (& MP_STATE_VM (mp_reload_exception ))) {
109100 break ;
110101 }
102+ remaining = end_tick - port_get_raw_ticks (NULL );
103+ // We break a bit early so we don't risk setting the alarm before the time when we call
104+ // sleep.
105+ if (remaining < 1 ) {
106+ break ;
107+ }
108+ port_interrupt_after_ticks (remaining );
111109 // Sleep until an interrupt happens.
112110 port_sleep_until_interrupt ();
113- duration = (port_get_raw_ticks (NULL ) - start_tick );
114- port_interrupt_after_ticks (duration );
111+ remaining = end_tick - port_get_raw_ticks (NULL );
115112 }
116113}
117114
0 commit comments