Skip to content

Commit aad0525

Browse files
committed
Add spinlock protection for kcb
1 parent 49f9119 commit aad0525

File tree

1 file changed

+35
-5
lines changed

1 file changed

+35
-5
lines changed

kernel/task.c

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,8 @@ void dispatch(void)
515515
/* Cooperative context switch */
516516
void yield(void)
517517
{
518+
uint32_t flag = 0;
519+
518520
if (unlikely(!kcb || !get_task_current() || !get_task_current()->data))
519521
return;
520522

@@ -530,6 +532,8 @@ void yield(void)
530532
#endif
531533

532534
/* In cooperative mode, delays are only processed on an explicit yield. */
535+
spin_lock_irqsave(&kcb->kcb_lock, &flag);
536+
533537
if (!kcb->preemptive)
534538
list_foreach(kcb->tasks, delay_update, NULL);
535539

@@ -824,10 +828,13 @@ uint16_t mo_task_id(void)
824828

825829
int32_t mo_task_idref(void *task_entry)
826830
{
827-
if (!task_entry || !kcb->tasks)
831+
spin_lock_irqsave(&kcb->kcb_lock, &task_flags);
832+
833+
if (!task_entry || !kcb->tasks) {
834+
spin_unlock_irqrestore(&kcb->kcb_lock, task_flags);
828835
return ERR_TASK_NOT_FOUND;
836+
}
829837

830-
spin_lock_irqsave(&kcb->kcb_lock, &task_flags);
831838
list_node_t *node = list_foreach(kcb->tasks, refcmp, task_entry);
832839
spin_unlock_irqrestore(&kcb->kcb_lock, task_flags);
833840

@@ -838,23 +845,46 @@ void mo_task_wfi(void)
838845
{
839846
/* Process deferred timer work before waiting */
840847
process_deferred_timer_work();
848+
uint32_t flag = 0;
841849

842850
if (!kcb->preemptive)
843851
return;
844852

853+
spin_lock_irqsave(&kcb->kcb_lock, &flag);
845854
volatile uint32_t current_ticks = kcb->ticks;
846-
while (current_ticks == kcb->ticks)
855+
spin_unlock_irqrestore(&kcb->kcb_lock, flag);
856+
857+
while (1) {
858+
spin_lock_irqsave(&kcb->kcb_lock, &flag);
859+
if (current_ticks != kcb->ticks) {
860+
spin_unlock_irqrestore(&kcb->kcb_lock, flag);
861+
break;
862+
}
863+
spin_unlock_irqrestore(&kcb->kcb_lock, flag);
847864
hal_cpu_idle();
865+
}
848866
}
849867

850868
uint16_t mo_task_count(void)
851869
{
852-
return kcb->task_count;
870+
uint32_t task_count;
871+
uint32_t flag;
872+
873+
spin_lock_irqsave(&kcb->kcb_lock, &flag);
874+
task_count = kcb->task_count;
875+
spin_unlock_irqrestore(&kcb->kcb_lock, flag);
876+
return task_count;
853877
}
854878

855879
uint32_t mo_ticks(void)
856880
{
857-
return kcb->ticks;
881+
uint32_t ticks;
882+
uint32_t flag;
883+
884+
spin_lock_irqsave(&kcb->kcb_lock, &flag);
885+
ticks = kcb->ticks;
886+
spin_unlock_irqrestore(&kcb->kcb_lock, flag);
887+
return ticks;
858888
}
859889

860890
uint64_t mo_uptime(void)

0 commit comments

Comments
 (0)