Merge pull request #22377 from hrydgard/callback-test-fixes

PSP kernel: Callback fixes
This commit is contained in:
Henrik Rydgård authored and GitHub committed 2026-09-28 16:24:06 -06:00
commit 0f4bb62fa7
8 files changed
+144 -51

No files matched your search

+14 -8
View File
@@ -150,8 +150,8 @@ template <typename WaitInfoType, typename PauseType>
WaitBeginEndCallbackResult WaitBeginCallback(SceUID threadID, SceUID prevCallbackId, int waitTimer, std::vector<WaitInfoType> &waitingThreads, std::map<SceUID, PauseType> &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.
+2 -2
View File
@@ -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;
}
+5 -1
View File
@@ -566,7 +566,11 @@ static void __KernelMsgPipeEndCallback(SceUID threadID, SceUID prevCallbackId) {
MsgPipe *ko = uid == 0 ? NULL : kernelObjects.Get<MsgPipe>(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;
}
+2 -1
View File
@@ -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;
}
+105 -32
View File
@@ -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;
@@ -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;
@@ -1538,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<PSPThread>(threadID, error);
@@ -2119,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");
@@ -2559,7 +2553,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 {
@@ -2768,6 +2768,11 @@ int sceKernelNotifyCallback(SceUID cbId, int notifyArg) {
PSPCallback *cb = kernelObjects.Get<PSPCallback>(cbId, error);
if (cb) {
__KernelNotifyCallback(cbId, notifyArg);
// A better priority thread in a CB wait runs the callback right away.
PSPThread *t = kernelObjects.Get<PSPThread>(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");
@@ -2779,6 +2784,10 @@ int sceKernelCancelCallback(SceUID cbId) {
PSPCallback *cb = kernelObjects.Get<PSPCallback>(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 {
@@ -3064,8 +3073,42 @@ 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;
// 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 __KernelCallbackDepth(thread) > 0;
}
static bool __CanExecuteCallbackNow(PSPThread *thread) {
return currentCallbackThreadID == 0 && g_inCbCount == 0;
if (g_inMipsCallReturn)
return false;
if (!thread)
thread = __GetCurrentThread();
if (!thread)
return true;
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.
@@ -3090,8 +3133,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 {
@@ -3103,6 +3147,13 @@ void __KernelCallAddress(PSPThread *thread, u32 entryPoint, PSPAction *afterActi
thread->nt.waitType = WAITTYPE_NONE;
}
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);
}
@@ -3151,8 +3202,8 @@ bool __KernelExecuteMipsCallOnCurrentThread(u32 callId, bool reschedAfter)
return false;
}
if (g_inCbCount > 0) {
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);
@@ -3190,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;
}
@@ -3215,7 +3262,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;
}
@@ -3244,19 +3293,19 @@ 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--;
}
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
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.
@@ -3394,19 +3443,34 @@ 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;
}
bool processed = false;
// 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();
u32 error;
u32 bestPriority = 0xFFFFFFFF;
if (cur && cur->isRunning())
bestPriority = cur->nt.currentPriority;
SceUID bestReady = threadReadyQueue.peek_first();
PSPThread *bestReadyThread = bestReady != 0 ? kernelObjects.Get<PSPThread>(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<PSPThread>(*iter, error);
if (thread && __KernelCheckThreadCallbacks(thread, false)) {
if (!thread || !thread->isWaiting())
continue;
if (thread != cur && thread->nt.currentPriority >= bestPriority)
continue;
if (!__CanExecuteCallbackNow(thread))
continue;
if (__KernelCheckThreadCallbacks(thread, false)) {
processed = true;
}
}
@@ -3444,6 +3508,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);
@@ -3461,7 +3534,7 @@ void sceKernelCheckCallback() {
bool __KernelInCallback()
{
return (g_inCbCount != 0);
return __KernelIsInCallbackOnThread(__GetCurrentThread());
}
void __KernelNotifyCallback(SceUID cbId, int notifyArg)
+2 -2
View File
@@ -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;
+13 -4
View File
@@ -309,12 +309,23 @@ tests_good = [
"threads/alarm/cancel/cancel",
"threads/alarm/refer/refer",
"threads/alarm/set/set",
"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",
@@ -334,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",
@@ -438,6 +450,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",
@@ -578,9 +591,6 @@ tests_next = [
"net/primary/ether",
"power/freq",
"sysmem/partition",
"threads/callbacks/cancel",
"threads/callbacks/count",
"threads/callbacks/notify",
# These two mbx tests only appeared to work because they papered over bugs
@@ -592,7 +602,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.