As we add runq_findbit, use it in ast.c ast_check().
There is a race condition in old code:
if (!(myprocessor->first_quantum) && (rq->count > 0)) {
// Here is not under lock, so when other cpu get
// the last thread, it will set low = NRQS and
// queue_empty() will get wrong q.
q = rq->runq + *(volatile int *)&rq->low;
if (queue_empty(q)) {...}
}
So I use a count > 0 check under lock and use runq_findbit to update
low.
>From eb9ef1da6dcfb9ba99b61fd0fc70fb6faa2e868e Mon Sep 17 00:00:00 2001
From: Donjuanplatinum <[email protected]>
Date: Mon, 30 Nov 2026 06:13:28 +0800
Subject: [PATCH] sched: Use runq_findbit in ast_check() and fix race condition
* ast.c (ast_check): Use runq_findbit and fix race condition.
---
kern/ast.c | 42 ++++++++++++++----------------------------
1 file changed, 14 insertions(+), 28 deletions(-)
diff --git a/kern/ast.c b/kern/ast.c
index 75e2ad15..15f638db 100644
--- a/kern/ast.c
+++ b/kern/ast.c
@@ -188,36 +188,22 @@ ast_check(void)
#endif /* MACH_FIXPRI */
rq = &(myprocessor->processor_set->runq);
if (!(myprocessor->first_quantum) && (rq->count > 0)) {
- queue_t q;
- /*
- * This is not the first quantum, and there may
- * be something in the processor_set runq.
- * Check whether low hint is accurate.
- */
- q = rq->runq + *(volatile int *)&rq->low;
- if (queue_empty(q)) {
- int i;
-
- /*
- * Need to recheck and possibly update hint.
- */
- runq_lock(rq);
- q = rq->runq + rq->low;
- if (rq->count > 0) {
- for (i = rq->low; i < NRQS; i++) {
- if(!(queue_empty(q)))
- break;
- q++;
- }
- rq->low = i;
- }
- runq_unlock(rq);
- }
-
+ /*
+ * This is not the first quantum, and there may
+ * be something in the processor_set runq.
+ * Check whether low hint is accurate.
+ */
+ runq_lock(rq);
+ /*
+ * Need to recheck count and possibly update low.
+ */
+ if (rq->count > 0) {
+ runq_findbit(rq->bitmap, &rq->low);
if (rq->low <= thread->sched_pri) {
- ast_on(mycpu, AST_BLOCK);
- break;
+ ast_on(mycpu, AST_BLOCK);
}
+ }
+ runq_unlock(rq);
}
#if MACH_FIXPRI
}
--
2.56.0
--
Donjuanplatinum, Yifei Yao <[email protected]>
GPG: 1C9E EEE5 4C8E D5A8 3039 1C87 A9F6 8632 D259 40E6
满堂兮美人 忽独与余兮目成