git: 422ba9ac8373 - stable/13 - sched_4bsd: Fix a racy thread state modification

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Sat, 01 Oct 2022 16:13:27 UTC
The branch stable/13 has been updated by markj:

URL: https://cgit.FreeBSD.org/src/commit/?id=422ba9ac83731615083ef15d52d30f3418da8fef

commit 422ba9ac83731615083ef15d52d30f3418da8fef
Author:     Mark Johnston <markj@FreeBSD.org>
AuthorDate: 2022-09-23 23:41:30 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2022-10-01 15:35:32 +0000

    sched_4bsd: Fix a racy thread state modification
    
    When a thread switching off-CPU is migrating to a remote CPU,
    sched_switch() may trigger a rescheduling of the thread currently
    running on that CPU.  When doing so, it must ensure that that thread is
    locked before modifying thread state.  If the thread's lock is not the
    scheduler lock, then the thread is in the process of switching off-CPU
    and no extra effort is needed, and the initiator does not hold the
    thread's lock and thus should not modify any thread state.
    
    Reported and tested by: Steve Kargl
    
    (cherry picked from commit c2d27b0ec7000d28b4f31148005ccfe371f47db3)
---
 sys/kern/sched_4bsd.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/sys/kern/sched_4bsd.c b/sys/kern/sched_4bsd.c
index 27621b79d4b7..87d317d4f586 100644
--- a/sys/kern/sched_4bsd.c
+++ b/sys/kern/sched_4bsd.c
@@ -1248,9 +1248,10 @@ kick_other_cpu(int pri, int cpuid)
 	}
 #endif /* defined(IPI_PREEMPTION) && defined(PREEMPTION) */
 
-	pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
-	ipi_cpu(cpuid, IPI_AST);
-	return;
+	if (pcpu->pc_curthread->td_lock == &sched_lock) {
+		pcpu->pc_curthread->td_flags |= TDF_NEEDRESCHED;
+		ipi_cpu(cpuid, IPI_AST);
+	}
 }
 #endif /* SMP */