From e7c23bb381b51f6faf9643ece081fa5f69db4eb2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 28 Sep 2026 14:47:49 -0600 Subject: [PATCH 1/6] Don't run wait callback hooks for a thread that isn't waiting A thread whose wait ends without a context switch (for example when a callback run from the wait satisfies it) keeps its old waitType. If it later ran a callback, from sceUmdWaitDriveStatCB with the drive already ready for instance, the stale wait's begin/end hooks ran, couldn't find the paused wait, and resumed the thread with SCE_KERNEL_ERROR_WAIT_DELETE, overwriting the HLE call's return value. Should fix "sceUmdWaitDriveStatCB: error 0x800201b5" dialog in Maru Goukaku TOEIC Test Portable (#7576). Co-Authored-By: Claude Opus 5.5 (1M context) --- Core/HLE/sceKernelThread.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 8bafc3b1cc..e84201af14 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -3090,8 +3090,9 @@ void __KernelCallAddress(PSPThread *thread, u32 entryPoint, PSPAction *afterActi afterAction = after; if (thread->nt.waitType != WAITTYPE_NONE) { - // If it's a callback, tell the wait to stop. - if (cbId > 0) { + // If it's a callback, tell the wait to stop. A thread that already returned from its + // wait keeps a stale waitType until it's switched out, so check that it's waiting. + if (cbId > 0 && (thread->nt.status & THREADSTATUS_WAIT) != 0) { if (waitTypeFuncs[thread->nt.waitType].beginFunc != NULL) { waitTypeFuncs[thread->nt.waitType].beginFunc(after->threadID, thread->currentCallbackId); } else { @@ -3250,7 +3251,7 @@ void __KernelReturnFromMipsCall() { } currentCallbackThreadID = 0; - if (cur->nt.waitType != WAITTYPE_NONE && call->cbId > 0) { + if (cur->nt.waitType != WAITTYPE_NONE && (cur->nt.status & THREADSTATUS_WAIT) != 0 && call->cbId > 0) { if (waitTypeFuncs[cur->nt.waitType].endFunc != NULL) waitTypeFuncs[cur->nt.waitType].endFunc(cur->GetUID(), cur->currentCallbackId); else From 3bf8b5b5c9451558c1200afdd7e8d1ac798f4116 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 28 Sep 2026 14:47:56 -0600 Subject: [PATCH 2/6] Callbacks: Run nested callbacks from CB waits, match hardware ordering Verified against new pspautotests threads/callbacks/afterwait and nested: - A thread inside a callback runs its own pending callbacks (even the same one again) nested, when it enters a CB wait. Waits paused by a nested callback are keyed by the outer callback's id. - sceKernelCheckCallback inside a callback returns ILLEGAL_CONTEXT without running anything. - sceKernelSleepThreadCB with a queued wakeup runs pending callbacks before consuming it. - A thread whose wait ended during a callback keeps the CPU, instead of queueing behind threads of the same priority. threads/callbacks/notify now passes too. Co-Authored-By: Claude Opus 5.5 (1M context) --- Core/HLE/sceKernelThread.cpp | 60 +++++++++++++++++++++++++++++++----- pspautotests | 2 +- test.py | 4 ++- 3 files changed, 56 insertions(+), 10 deletions(-) diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index e84201af14..6a4f885295 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -2559,7 +2559,13 @@ static int __KernelSleepThread(bool doCallbacks) { return hleNoLog(-1); } - if (thread->nt.wakeupCount > 0) { + if (doCallbacks && thread->nt.wakeupCount > 0 && __KernelCurHasReadyCallbacks()) { + // Pending callbacks run first, then the sleep end callback consumes the wakeup. + // Log first, the callback starts running right away. + (void)hleLogDebug(Log::sceKernel, 0, "running callbacks before wakeup"); + __KernelWaitCallbacksCurThread(WAITTYPE_SLEEP, 0, 0, 0); + return 0; + } else if (thread->nt.wakeupCount > 0) { thread->nt.wakeupCount--; return hleLogDebug(Log::sceKernel, 0, "wakeupCount decremented to %i", thread->nt.wakeupCount); } else { @@ -3064,8 +3070,18 @@ const char *ThreadStatusToString(ThreadStatus status) { return "(unk)"; } +// Set while a returning mipscall's after-action runs, which may queue the next callback. +static bool g_inMipsCallReturn = false; + +static bool __KernelIsInCallbackOnThread(const PSPThread *thread) { + return g_inCbCount > 0 && thread && thread->GetUID() == currentCallbackThreadID; +} + static bool __CanExecuteCallbackNow(PSPThread *thread) { - return currentCallbackThreadID == 0 && g_inCbCount == 0; + if (currentCallbackThreadID == 0 && g_inCbCount == 0) + return true; + // A thread inside a callback runs its own pending callbacks nested, from a CB wait. + return !g_inMipsCallReturn && __KernelIsInCallbackOnThread(thread); } // Takes ownership of afterAction. @@ -3104,6 +3120,10 @@ void __KernelCallAddress(PSPThread *thread, u32 entryPoint, PSPAction *afterActi thread->nt.waitType = WAITTYPE_NONE; } + // A wait paused by a callback nested in this one is keyed by this callback's id. + if (cbId > 0) + thread->currentCallbackId = cbId; + __KernelChangeThreadState(thread, THREADSTATUS_READY); } @@ -3152,7 +3172,7 @@ bool __KernelExecuteMipsCallOnCurrentThread(u32 callId, bool reschedAfter) return false; } - if (g_inCbCount > 0) { + if (g_inCbCount > 0 && !__KernelIsInCallbackOnThread(cur)) { WARN_LOG_REPORT(Log::sceKernel, "__KernelExecuteMipsCallOnCurrentThread(): Already in a callback!"); } DEBUG_LOG(Log::sceKernel, "Executing mipscall %i", callId); @@ -3216,7 +3236,9 @@ void __KernelReturnFromMipsCall() { // TODO: Should also save/restore wait state here? if (call->doAfter) { + g_inMipsCallReturn = true; call->doAfter->run(*call); + g_inMipsCallReturn = false; delete call->doAfter; call->doAfter = nullptr; } @@ -3249,7 +3271,8 @@ void __KernelReturnFromMipsCall() { if (call->cbId != 0 && g_inCbCount > 0) { g_inCbCount--; } - currentCallbackThreadID = 0; + // Returning from a nested callback leaves us inside the outer one. + currentCallbackThreadID = g_inCbCount > 0 ? cur->GetUID() : 0; if (cur->nt.waitType != WAITTYPE_NONE && (cur->nt.status & THREADSTATUS_WAIT) != 0 && call->cbId > 0) { if (waitTypeFuncs[cur->nt.waitType].endFunc != NULL) @@ -3258,6 +3281,12 @@ void __KernelReturnFromMipsCall() { ERROR_LOG_REPORT(Log::HLE, "Missing begin/restore funcs for wait type %d", cur->nt.waitType); } + // If the wait ended (or there was none), the thread never gave up the CPU, so it shouldn't + // queue behind threads of the same priority. + if (cur->isReady()) { + __KernelChangeThreadState(cur, THREADSTATUS_RUNNING); + } + // yeah! back in the real world, let's keep going. Should we process more callbacks? if (!__KernelExecutePendingMipsCalls(cur, call->reschedAfter)) { // Sometimes, we want to stay on the thread. @@ -3395,10 +3424,16 @@ bool __KernelCheckCallbacks() { if (readyCallbacksCount < 0) { ERROR_LOG_REPORT(Log::sceKernel, "readyCallbacksCount became negative: %i", readyCallbacksCount); } - if (__IsInInterrupt() || !__KernelIsDispatchEnabled() || __KernelInCallback()) { - // TODO: Technically, other callbacks can run when a thread within a callback is waiting. - // However, callbacks that were pending before the current callback started won't be run. - // This is pretty uncommon, and not yet handled correctly. + if (__IsInInterrupt() || !__KernelIsDispatchEnabled()) { + return false; + } + if (__KernelInCallback()) { + // A thread inside a callback runs its own callbacks nested, from a CB wait. + // TODO: Technically, other threads' callbacks can also run when a thread within a callback is waiting. + PSPThread *thread = __GetCurrentThread(); + if (__KernelIsInCallbackOnThread(thread) && thread->isWaiting() && __KernelCheckThreadCallbacks(thread, false)) { + return __KernelExecutePendingMipsCalls(thread, true); + } return false; } @@ -3445,6 +3480,15 @@ bool __KernelForceCallbacks() { // Not wrapped because it has special return logic. void sceKernelCheckCallback() { + // Unlike CB waits, this refuses to run callbacks from inside one. + if (__KernelIsInCallbackOnThread(__GetCurrentThread())) { + DEBUG_LOG(Log::sceKernel, "sceKernelCheckCallback() - in a callback, refused."); + RETURN(SCE_KERNEL_ERROR_ILLEGAL_CONTEXT); + hleEatCycles(230); + hleNoLogVoid(); + return; + } + // Start with yes. RETURN(1); diff --git a/pspautotests b/pspautotests index 31dd9ac3c5..3f41a30b6c 160000 --- a/pspautotests +++ b/pspautotests @@ -1 +1 @@ -Subproject commit 31dd9ac3c5584fb096baa52d64397f0e6942145e +Subproject commit 3f41a30b6c4ac52c9357b0a27de2b9ce6666c37f diff --git a/test.py b/test.py index ffd5dafbf7..6917c04b5e 100755 --- a/test.py +++ b/test.py @@ -309,11 +309,14 @@ tests_good = [ "threads/alarm/cancel/cancel", "threads/alarm/refer/refer", "threads/alarm/set/set", + "threads/callbacks/afterwait", "threads/callbacks/callbacks", "threads/callbacks/check", "threads/callbacks/create", "threads/callbacks/delete", "threads/callbacks/exit", + "threads/callbacks/nested", + "threads/callbacks/notify", "threads/callbacks/refer", "threads/events/events", "threads/events/cancel/cancel", @@ -580,7 +583,6 @@ tests_next = [ "sysmem/partition", "threads/callbacks/cancel", "threads/callbacks/count", - "threads/callbacks/notify", # These two mbx tests only appeared to work because they papered over bugs From acd2738b7a2599a3d9d5a77f4f0dab95b98b0c96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 28 Sep 2026 14:52:45 -0600 Subject: [PATCH 3/6] Callbacks: Deliver to other threads by priority, fix sceKernelCancelCallback Verified against pspautotests threads/callbacks/delivery: - Notifying the callback of a better priority thread in a CB wait runs it right away. Callbacks of other waiting threads stay pending until those threads would get to run, rather than being taken at any reschedule, so they can still be counted or canceled. - sceKernelCancelCallback clears the notify count, not just the arg. threads/callbacks/cancel, count and umd/wait/wait now pass. Co-Authored-By: Claude Opus 5.5 (1M context) --- Core/HLE/sceKernelThread.cpp | 18 ++++++++++++++++++ pspautotests | 2 +- test.py | 7 ++++--- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 6a4f885295..0a7636494b 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -2774,6 +2774,11 @@ int sceKernelNotifyCallback(SceUID cbId, int notifyArg) { PSPCallback *cb = kernelObjects.Get(cbId, error); if (cb) { __KernelNotifyCallback(cbId, notifyArg); + // A better priority thread in a CB wait runs the callback right away. + PSPThread *t = kernelObjects.Get(cb->nc.threadId, error); + if (t && t->GetUID() != currentThread && t->isWaiting() && t->isProcessingCallbacks) { + hleReSchedule("callback notified"); + } return hleLogDebug(Log::sceKernel, 0); } else { return hleLogError(Log::sceKernel, error, "bad cbId"); @@ -2785,6 +2790,10 @@ int sceKernelCancelCallback(SceUID cbId) { PSPCallback *cb = kernelObjects.Get(cbId, error); if (cb) { // This just resets the notify count. + if (cb->nc.notifyCount != 0) { + readyCallbacksCount--; + } + cb->nc.notifyCount = 0; cb->nc.notifyArg = 0; return hleLogDebug(Log::sceKernel, 0); } else { @@ -3439,9 +3448,18 @@ bool __KernelCheckCallbacks() { bool processed = false; + // A waiting thread takes its callbacks when it would get to run. While the current thread + // keeps running, that's only threads of better priority; the rest stay pending (and can + // still be counted or canceled.) + PSPThread *cur = __GetCurrentThread(); + const bool curRunning = cur && cur->isRunning(); + u32 error; for (auto iter = threadqueue.begin(); iter != threadqueue.end(); ++iter) { PSPThread *thread = kernelObjects.Get(*iter, error); + if (thread && curRunning && thread != cur && thread->nt.currentPriority >= cur->nt.currentPriority) { + continue; + } if (thread && __KernelCheckThreadCallbacks(thread, false)) { processed = true; } diff --git a/pspautotests b/pspautotests index 3f41a30b6c..2a58a15610 160000 --- a/pspautotests +++ b/pspautotests @@ -1 +1 @@ -Subproject commit 3f41a30b6c4ac52c9357b0a27de2b9ce6666c37f +Subproject commit 2a58a15610739ee7d0cf95044f9888c399d79d5e diff --git a/test.py b/test.py index 6917c04b5e..b0f26916f4 100755 --- a/test.py +++ b/test.py @@ -311,9 +311,12 @@ tests_good = [ "threads/alarm/set/set", "threads/callbacks/afterwait", "threads/callbacks/callbacks", + "threads/callbacks/cancel", "threads/callbacks/check", + "threads/callbacks/count", "threads/callbacks/create", "threads/callbacks/delete", + "threads/callbacks/delivery", "threads/callbacks/exit", "threads/callbacks/nested", "threads/callbacks/notify", @@ -441,6 +444,7 @@ tests_good = [ "utility/savedata/makedata", "utility/systemparam/systemparam", "umd/callbacks/umd", + "umd/wait/wait", "umd/register", "video/mpeg/ringbuffer/avail", "video/mpeg/ringbuffer/construct", @@ -581,8 +585,6 @@ tests_next = [ "net/primary/ether", "power/freq", "sysmem/partition", - "threads/callbacks/cancel", - "threads/callbacks/count", # These two mbx tests only appeared to work because they papered over bugs @@ -594,7 +596,6 @@ tests_next = [ "threads/vpl/create", "umd/io/umd_io", "umd/raw_access/raw_access", - "umd/wait/wait", "utility/msgdialog/dialog", "utility/savedata/idlist", # These tests appear to be broken and just hang. From 24b41d3f23697c7338191205441f917d88df838e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 28 Sep 2026 15:10:50 -0600 Subject: [PATCH 4/6] Kernel waits: Fix VPL/FPL and msgpipe waits around callbacks, report timeout left Verified against pspautotests threads/callbacks/waittypes: - __KernelThreadingInit() cleared the wait type callback table after __KernelMemoryInit() had registered VPL and FPL in it, so a VPL or FPL wait interrupted by a callback was never paused or resumed, and could hang forever. - A msgpipe deleted during a callback left its waiter waiting, instead of waking it with WAIT_DELETE. - A wait that got its object during a callback reported no time left; put the timer back before trying to unlock, so the unlock writes what remains. Co-Authored-By: Claude Opus 5.5 (1M context) --- Core/HLE/KernelWaitHelpers.h | 22 ++++++++++++++-------- Core/HLE/sceKernelMsgPipe.cpp | 6 +++++- Core/HLE/sceKernelThread.cpp | 3 ++- 3 files changed, 21 insertions(+), 10 deletions(-) diff --git a/Core/HLE/KernelWaitHelpers.h b/Core/HLE/KernelWaitHelpers.h index 9aed035147..196ee10060 100644 --- a/Core/HLE/KernelWaitHelpers.h +++ b/Core/HLE/KernelWaitHelpers.h @@ -150,8 +150,8 @@ template WaitBeginEndCallbackResult WaitBeginCallback(SceUID threadID, SceUID prevCallbackId, int waitTimer, std::vector &waitingThreads, std::map &pausedWaits, bool doTimeout = true) { SceUID pauseKey = prevCallbackId == 0 ? threadID : prevCallbackId; - // This means two callbacks in a row. PSP crashes if the same callback waits inside itself (may need more testing.) - // TODO: Handle this better? + // Shouldn't happen: each nesting level pauses under its own key, and on hardware a callback can + // nest only one level (a CB wait that would go deeper never returns.) if (pausedWaits.find(pauseKey) != pausedWaits.end()) { return WAIT_CB_SUCCESS; } @@ -222,6 +222,14 @@ WaitBeginEndCallbackResult WaitEndCallback(SceUID threadID, SceUID prevCallbackI // TODO: Don't wake up if __KernelCurHasReadyCallbacks()? + // The timeout kept running during the callback. Put the timer back first, so that an unlock + // reports the time that's left. + s64 cyclesLeft = waitDeadline - CoreTiming::GetTicks(currentMIPS); + const bool hasTimer = timeoutPtr != 0 && waitTimer != -1 && waitDeadline != 0; + if (hasTimer) { + CoreTiming::ScheduleEvent(cyclesLeft < 0 ? 0 : cyclesLeft, waitTimer, threadID); + } + bool wokeThreads; // Attempt to unlock. if (TryUnlock(ko, waitData, error, 0, wokeThreads)) { @@ -229,20 +237,18 @@ WaitBeginEndCallbackResult WaitEndCallback(SceUID threadID, SceUID prevCallbackI } // We only check if it timed out if it couldn't unlock. - s64 cyclesLeft = waitDeadline - CoreTiming::GetTicks(currentMIPS); if (cyclesLeft < 0 && waitDeadline != 0) { + if (hasTimer) { + CoreTiming::UnscheduleEvent(waitTimer, threadID); + } if (timeoutPtr != 0 && waitTimer != -1) { Memory::WriteOrException_U32(0, timeoutPtr); } __KernelResumeThreadFromWait(threadID, SCE_KERNEL_ERROR_WAIT_TIMEOUT); return WAIT_CB_TIMED_OUT; - } else { - if (timeoutPtr != 0 && waitTimer != -1) { - CoreTiming::ScheduleEvent(cyclesLeft, waitTimer, __KernelGetCurThread()); - } - return WAIT_CB_RESUMED_WAIT; } + return WAIT_CB_RESUMED_WAIT; } // Meant to be called in a registered end callback function for a wait type. diff --git a/Core/HLE/sceKernelMsgPipe.cpp b/Core/HLE/sceKernelMsgPipe.cpp index 47110b2752..82a2f2108d 100644 --- a/Core/HLE/sceKernelMsgPipe.cpp +++ b/Core/HLE/sceKernelMsgPipe.cpp @@ -566,7 +566,11 @@ static void __KernelMsgPipeEndCallback(SceUID threadID, SceUID prevCallbackId) { MsgPipe *ko = uid == 0 ? NULL : kernelObjects.Get(uid, error); if (ko == NULL) { - ERROR_LOG_REPORT(Log::sceKernel, "__KernelMsgPipeEndCallback: Invalid object"); + // Deleted during the callback. + u32 timeoutPtr = __KernelGetWaitTimeoutPtr(threadID, error); + if (timeoutPtr != 0 && waitTimer != -1) + Memory::WriteOrException_U32(0, timeoutPtr); + __KernelResumeThreadFromWait(threadID, SCE_KERNEL_ERROR_WAIT_DELETE); return; } diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 0a7636494b..895774e174 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -782,7 +782,8 @@ void __KernelThreadingInit() { u32 blockSize = sizeof(idleThreadCode) + ARRAY_SIZE(threadHacks) * 2 * 4; // The thread code above plus 8 bytes per "hack" dispatchEnabled = true; - memset(waitTypeFuncs, 0, sizeof(waitTypeFuncs)); + // Don't clear waitTypeFuncs here: __KernelMemoryInit() registers VPL and FPL before this runs. + // Every entry is set again by its module's init anyway. __SetCurrentThread(NULL, 0, NULL); g_inCbCount = 0; From eda92c4ef2585d6efaacce8b27e0a47663e01950 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 28 Sep 2026 15:10:50 -0600 Subject: [PATCH 5/6] Callbacks: Track callback nesting per thread, one level deep Replaces the global in-callback counter with each thread's own mipscall chain, so several threads can be inside callbacks at once, and other threads' callbacks (better priority ones right away) run while one is. Verified against pspautotests threads/callbacks/otherthread, recursion and intrnotify: - A callback nests only one level: a CB wait that would go deeper never returns on hardware, so the callback is left pending instead. - A non-CB wait inside a callback no longer runs callbacks because of the CB wait the callback interrupted. - Callbacks for a waiting thread are only taken when it beats both the running thread and every ready one. After an interrupt (which runs on the idle thread) that's the thread about to resume, not idle. Co-Authored-By: Claude Opus 5.5 (1M context) --- Core/HLE/sceDisplay.cpp | 4 +- Core/HLE/sceKernelThread.cpp | 99 ++++++++++++++++++++---------------- Core/HLE/sceUmd.cpp | 4 +- pspautotests | 2 +- test.py | 5 ++ 5 files changed, 64 insertions(+), 50 deletions(-) diff --git a/Core/HLE/sceDisplay.cpp b/Core/HLE/sceDisplay.cpp index 4f81dd093d..d657610979 100644 --- a/Core/HLE/sceDisplay.cpp +++ b/Core/HLE/sceDisplay.cpp @@ -319,8 +319,8 @@ void __DisplayShutdown() { void __DisplayVblankBeginCallback(SceUID threadID, SceUID prevCallbackId) { SceUID pauseKey = prevCallbackId == 0 ? threadID : prevCallbackId; - // This means two callbacks in a row. PSP crashes if the same callback waits inside itself (may need more testing.) - // TODO: Handle this better? + // Shouldn't happen: each nesting level pauses under its own key, and on hardware a callback can + // nest only one level (a CB wait that would go deeper never returns.) if (vblankPausedWaits.find(pauseKey) != vblankPausedWaits.end()) { return; } diff --git a/Core/HLE/sceKernelThread.cpp b/Core/HLE/sceKernelThread.cpp index 895774e174..b4132b0f9a 100644 --- a/Core/HLE/sceKernelThread.cpp +++ b/Core/HLE/sceKernelThread.cpp @@ -480,8 +480,8 @@ bool __KernelCheckThreadCallbacks(PSPThread *thread, bool force); ////////////////////////////////////////////////////////////////////////// //STATE BEGIN ////////////////////////////////////////////////////////////////////////// +// No longer used (callback nesting is tracked per thread), only kept for savestates. static int g_inCbCount = 0; -// Normally, the same as currentThread. In an interrupt, remembers the callback's thread id. static SceUID currentCallbackThreadID = 0; static int readyCallbacksCount = 0; static SceUID currentThread; @@ -1539,11 +1539,6 @@ u32 __KernelDeleteThread(SceUID threadID, int exitStatus, const char *reason) if (currentThread == threadID) __SetCurrentThread(NULL, 0, NULL); - if (currentCallbackThreadID == threadID) - { - currentCallbackThreadID = 0; - g_inCbCount = 0; - } u32 error; PSPThread *t = kernelObjects.Get(threadID, error); @@ -2120,8 +2115,6 @@ int sceKernelExitDeleteThread(int exitStatus) { uint32_t thread_attr = thread->nt.attr; uint32_t uid = thread->GetUID(); __KernelDeleteThread(currentThread, exitStatus, "thread exited with delete"); - // Temporary hack since we don't reschedule within callbacks. - g_inCbCount = 0; hleReSchedule("thread exited with delete"); @@ -3083,15 +3076,39 @@ const char *ThreadStatusToString(ThreadStatus status) { // Set while a returning mipscall's after-action runs, which may queue the next callback. static bool g_inMipsCallReturn = false; +// How many callbacks the thread is running, nested in each other (on hardware, at most two.) +static int __KernelCallbackDepth(const PSPThread *thread) { + int depth = 0; + u32 id = thread ? thread->currentMipscallId : 0; + while (id != 0 && id != (u32)-1) { + MipsCall *call = mipsCalls.get(id); + if (!call) + break; + if (call->cbId > 0) + depth++; + id = call->savedId; + } + return depth; +} + static bool __KernelIsInCallbackOnThread(const PSPThread *thread) { - return g_inCbCount > 0 && thread && thread->GetUID() == currentCallbackThreadID; + return __KernelCallbackDepth(thread) > 0; } static bool __CanExecuteCallbackNow(PSPThread *thread) { - if (currentCallbackThreadID == 0 && g_inCbCount == 0) + if (g_inMipsCallReturn) + return false; + if (!thread) + thread = __GetCurrentThread(); + if (!thread) return true; - // A thread inside a callback runs its own pending callbacks nested, from a CB wait. - return !g_inMipsCallReturn && __KernelIsInCallbackOnThread(thread); + int depth = __KernelCallbackDepth(thread); + // Not in the middle of some other mipscall. + if (depth == 0) + return thread->currentMipscallId == 0 || thread->currentMipscallId == (u32)-1; + // A thread inside a callback runs its own pending callbacks nested, from a CB wait, but only + // one level deep: going deeper hangs the thread on hardware. + return depth == 1; } // Takes ownership of afterAction. @@ -3130,9 +3147,12 @@ void __KernelCallAddress(PSPThread *thread, u32 entryPoint, PSPAction *afterActi thread->nt.waitType = WAITTYPE_NONE; } - // A wait paused by a callback nested in this one is keyed by this callback's id. - if (cbId > 0) + if (cbId > 0) { + // A wait paused by a callback nested in this one is keyed by this callback's id. thread->currentCallbackId = cbId; + // Only a CB wait inside the callback processes callbacks, not the one it interrupted. + thread->isProcessingCallbacks = false; + } __KernelChangeThreadState(thread, THREADSTATUS_READY); } @@ -3182,8 +3202,8 @@ bool __KernelExecuteMipsCallOnCurrentThread(u32 callId, bool reschedAfter) return false; } - if (g_inCbCount > 0 && !__KernelIsInCallbackOnThread(cur)) { - WARN_LOG_REPORT(Log::sceKernel, "__KernelExecuteMipsCallOnCurrentThread(): Already in a callback!"); + if (__KernelCallbackDepth(cur) > 1) { + WARN_LOG_REPORT(Log::sceKernel, "__KernelExecuteMipsCallOnCurrentThread(): Already two callbacks deep!"); } DEBUG_LOG(Log::sceKernel, "Executing mipscall %i", callId); MipsCall *call = mipsCalls.get(callId); @@ -3221,10 +3241,6 @@ bool __KernelExecuteMipsCallOnCurrentThread(u32 callId, bool reschedAfter) currentMIPS->r[MIPS_REG_A0 + i] = call->args[i]; } - if (call->cbId != 0) - g_inCbCount++; - currentCallbackThreadID = currentThread; - return true; } @@ -3277,13 +3293,6 @@ void __KernelReturnFromMipsCall() { currentMIPS->r[MIPS_REG_V1] = call->savedV1; cur->currentMipscallId = call->savedId; - // If the thread called ExitDelete, we might've already decreased g_inCbCount. - if (call->cbId != 0 && g_inCbCount > 0) { - g_inCbCount--; - } - // Returning from a nested callback leaves us inside the outer one. - currentCallbackThreadID = g_inCbCount > 0 ? cur->GetUID() : 0; - if (cur->nt.waitType != WAITTYPE_NONE && (cur->nt.status & THREADSTATUS_WAIT) != 0 && call->cbId > 0) { if (waitTypeFuncs[cur->nt.waitType].endFunc != NULL) waitTypeFuncs[cur->nt.waitType].endFunc(cur->GetUID(), cur->currentCallbackId); @@ -3437,31 +3446,31 @@ bool __KernelCheckCallbacks() { if (__IsInInterrupt() || !__KernelIsDispatchEnabled()) { return false; } - if (__KernelInCallback()) { - // A thread inside a callback runs its own callbacks nested, from a CB wait. - // TODO: Technically, other threads' callbacks can also run when a thread within a callback is waiting. - PSPThread *thread = __GetCurrentThread(); - if (__KernelIsInCallbackOnThread(thread) && thread->isWaiting() && __KernelCheckThreadCallbacks(thread, false)) { - return __KernelExecutePendingMipsCalls(thread, true); - } - return false; - } bool processed = false; - // A waiting thread takes its callbacks when it would get to run. While the current thread - // keeps running, that's only threads of better priority; the rest stay pending (and can - // still be counted or canceled.) + // A waiting thread takes its callbacks when it would get to run: only if its priority beats + // the running thread and every ready one. The rest stay pending (and can still be counted or + // canceled.) PSPThread *cur = __GetCurrentThread(); - const bool curRunning = cur && cur->isRunning(); - u32 error; + u32 bestPriority = 0xFFFFFFFF; + if (cur && cur->isRunning()) + bestPriority = cur->nt.currentPriority; + SceUID bestReady = threadReadyQueue.peek_first(); + PSPThread *bestReadyThread = bestReady != 0 ? kernelObjects.Get(bestReady, error) : nullptr; + if (bestReadyThread && bestReadyThread->nt.currentPriority < bestPriority) + bestPriority = bestReadyThread->nt.currentPriority; + for (auto iter = threadqueue.begin(); iter != threadqueue.end(); ++iter) { PSPThread *thread = kernelObjects.Get(*iter, error); - if (thread && curRunning && thread != cur && thread->nt.currentPriority >= cur->nt.currentPriority) { + if (!thread || !thread->isWaiting()) continue; - } - if (thread && __KernelCheckThreadCallbacks(thread, false)) { + if (thread != cur && thread->nt.currentPriority >= bestPriority) + continue; + if (!__CanExecuteCallbackNow(thread)) + continue; + if (__KernelCheckThreadCallbacks(thread, false)) { processed = true; } } @@ -3525,7 +3534,7 @@ void sceKernelCheckCallback() { bool __KernelInCallback() { - return (g_inCbCount != 0); + return __KernelIsInCallbackOnThread(__GetCurrentThread()); } void __KernelNotifyCallback(SceUID cbId, int notifyArg) diff --git a/Core/HLE/sceUmd.cpp b/Core/HLE/sceUmd.cpp index 40b67d3852..d9fc257606 100644 --- a/Core/HLE/sceUmd.cpp +++ b/Core/HLE/sceUmd.cpp @@ -201,8 +201,8 @@ static void __UmdBeginCallback(SceUID threadID, SceUID prevCallbackId) if (HLEKernel::VerifyWait(threadID, WAITTYPE_UMD, 1)) { - // This means two callbacks in a row. PSP crashes if the same callback runs inside itself. - // TODO: Handle this better? + // Shouldn't happen: each nesting level pauses under its own key, and on hardware a callback can + // nest only one level (a CB wait that would go deeper never returns.) if (umdPausedWaits.find(pauseKey) != umdPausedWaits.end()) return; diff --git a/pspautotests b/pspautotests index 2a58a15610..d2097ed7d8 160000 --- a/pspautotests +++ b/pspautotests @@ -1 +1 @@ -Subproject commit 2a58a15610739ee7d0cf95044f9888c399d79d5e +Subproject commit d2097ed7d840d39dddf37433726790cd2a446a1d diff --git a/test.py b/test.py index b0f26916f4..7515cbd36b 100755 --- a/test.py +++ b/test.py @@ -312,15 +312,20 @@ tests_good = [ "threads/callbacks/afterwait", "threads/callbacks/callbacks", "threads/callbacks/cancel", + "threads/callbacks/cbtimeout", "threads/callbacks/check", "threads/callbacks/count", "threads/callbacks/create", "threads/callbacks/delete", "threads/callbacks/delivery", "threads/callbacks/exit", + "threads/callbacks/intrnotify", "threads/callbacks/nested", "threads/callbacks/notify", + "threads/callbacks/otherthread", + "threads/callbacks/recursion", "threads/callbacks/refer", + "threads/callbacks/waittypes", "threads/events/events", "threads/events/cancel/cancel", "threads/events/clear/clear", From c11e46aeeacc876f5cab8982db18e9f045222e65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Henrik=20Rydg=C3=A5rd?= Date: Mon, 28 Sep 2026 15:16:31 -0600 Subject: [PATCH 6/6] LwMutex: Take the lock after a callback if it was released during it The end callback checked the kernel object's lockThread, which for an lwmutex is only refreshed by sceKernelReferLwMutexStatus. The lock state lives in the workarea, so an unlock during the callback left the waiter waiting forever. Verified against pspautotests threads/lwmutex/callbacks. Co-Authored-By: Claude Opus 5.5 (1M context) --- Core/HLE/sceKernelMutex.cpp | 3 ++- pspautotests | 2 +- test.py | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Core/HLE/sceKernelMutex.cpp b/Core/HLE/sceKernelMutex.cpp index 2044c88c06..da149aebba 100644 --- a/Core/HLE/sceKernelMutex.cpp +++ b/Core/HLE/sceKernelMutex.cpp @@ -826,7 +826,8 @@ static void __KernelWaitLwMutex(LwMutex *mutex, u32 timeoutPtr) { static bool __KernelUnlockLwMutexForThreadCheck(LwMutex *mutex, SceUID threadID, u32 &error, int result, bool &wokeThreads) { - if (mutex->nm.lockThread == -1 && __KernelUnlockLwMutexForThread(mutex, mutex->nm.workarea, threadID, error, 0)) + // The lock state lives in the workarea, nm.lockThread is only refreshed when referred. + if (mutex->nm.workarea->lockLevel == 0 && __KernelUnlockLwMutexForThread(mutex, mutex->nm.workarea, threadID, error, 0)) return true; return false; } diff --git a/pspautotests b/pspautotests index d2097ed7d8..33e59e29f2 160000 --- a/pspautotests +++ b/pspautotests @@ -1 +1 @@ -Subproject commit d2097ed7d840d39dddf37433726790cd2a446a1d +Subproject commit 33e59e29f2aad3c7440e5b1afeab1715268d72dc diff --git a/test.py b/test.py index 7515cbd36b..61af594c53 100755 --- a/test.py +++ b/test.py @@ -345,6 +345,7 @@ tests_good = [ "threads/fpl/refer", "threads/fpl/tryallocate", "threads/k0/k0", + "threads/lwmutex/callbacks", "threads/lwmutex/create", "threads/lwmutex/delete", "threads/lwmutex/lock",