@@ -33,6 +33,9 @@ static kcb_t kernel_state = {
3333};
3434kcb_t * kcb = & kernel_state ;
3535
36+ /* Deferred timer work flag to reduce interrupt latency */
37+ static volatile bool timer_work_pending = false;
38+
3639/* Magic number written to both ends of a task's stack for corruption detection.
3740 */
3841#define STACK_CANARY 0x33333333U
@@ -288,7 +291,7 @@ static int32_t noop_rtsched(void)
288291void dispatcher (void )
289292{
290293 kcb -> ticks ++ ;
291- _timer_tick_handler () ;
294+ timer_work_pending = true ;
292295 _dispatch ();
293296}
294297
@@ -327,6 +330,12 @@ void yield(void)
327330 if (unlikely (!kcb || !kcb -> task_current || !kcb -> task_current -> data ))
328331 return ;
329332
333+ /* Process deferred timer work during yield */
334+ if (timer_work_pending ) {
335+ timer_work_pending = false;
336+ _timer_tick_handler ();
337+ }
338+
330339 /* HAL context switching is used for preemptive scheduling. */
331340 if (hal_context_save (((tcb_t * ) kcb -> task_current -> data )-> context ) != 0 )
332341 return ;
@@ -491,6 +500,12 @@ void mo_task_yield(void)
491500
492501void mo_task_delay (uint16_t ticks )
493502{
503+ /* Process deferred timer work before sleeping */
504+ if (timer_work_pending ) {
505+ timer_work_pending = false;
506+ _timer_tick_handler ();
507+ }
508+
494509 if (!ticks )
495510 return ;
496511
@@ -634,6 +649,12 @@ int32_t mo_task_idref(void *task_entry)
634649
635650void mo_task_wfi (void )
636651{
652+ /* Process deferred timer work before waiting */
653+ if (timer_work_pending ) {
654+ timer_work_pending = false;
655+ _timer_tick_handler ();
656+ }
657+
637658 if (!kcb -> preemptive )
638659 return ;
639660
@@ -663,6 +684,12 @@ void _sched_block(queue_t *wait_q)
663684 !kcb -> task_current -> data ))
664685 panic (ERR_SEM_OPERATION );
665686
687+ /* Process deferred timer work before blocking */
688+ if (timer_work_pending ) {
689+ timer_work_pending = false;
690+ _timer_tick_handler ();
691+ }
692+
666693 tcb_t * self = kcb -> task_current -> data ;
667694
668695 if (queue_enqueue (wait_q , self ) != 0 ) {
0 commit comments