all repos — mgba @ 1cc0bdeec140cbe411020b8239f3dd47852a9e2f

mGBA Game Boy Advance Emulator

src/core/thread.c (view raw)

  1/* Copyright (c) 2013-2016 Jeffrey Pfau
  2 *
  3 * This Source Code Form is subject to the terms of the Mozilla Public
  4 * License, v. 2.0. If a copy of the MPL was not distributed with this
  5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  6#include "thread.h"
  7
  8#include "core/core.h"
  9#include "util/patch.h"
 10#include "util/vfs.h"
 11
 12#include "platform/commandline.h"
 13
 14#include <signal.h>
 15
 16#ifndef DISABLE_THREADING
 17
 18static const float _defaultFPSTarget = 60.f;
 19
 20#ifdef USE_PTHREADS
 21static pthread_key_t _contextKey;
 22static pthread_once_t _contextOnce = PTHREAD_ONCE_INIT;
 23
 24static void _createTLS(void) {
 25	pthread_key_create(&_contextKey, 0);
 26}
 27#elif _WIN32
 28static DWORD _contextKey;
 29static INIT_ONCE _contextOnce = INIT_ONCE_STATIC_INIT;
 30
 31static BOOL CALLBACK _createTLS(PINIT_ONCE once, PVOID param, PVOID* context) {
 32	UNUSED(once);
 33	UNUSED(param);
 34	UNUSED(context);
 35	_contextKey = TlsAlloc();
 36	return TRUE;
 37}
 38#endif
 39
 40static void _changeState(struct mCoreThread* threadContext, enum mCoreThreadState newState, bool broadcast) {
 41	MutexLock(&threadContext->stateMutex);
 42	threadContext->state = newState;
 43	if (broadcast) {
 44		ConditionWake(&threadContext->stateCond);
 45	}
 46	MutexUnlock(&threadContext->stateMutex);
 47}
 48
 49static void _waitOnInterrupt(struct mCoreThread* threadContext) {
 50	while (threadContext->state == THREAD_INTERRUPTED) {
 51		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
 52	}
 53}
 54
 55static void _waitUntilNotState(struct mCoreThread* threadContext, enum mCoreThreadState oldState) {
 56	MutexLock(&threadContext->sync.videoFrameMutex);
 57	bool videoFrameWait = threadContext->sync.videoFrameWait;
 58	threadContext->sync.videoFrameWait = false;
 59	MutexUnlock(&threadContext->sync.videoFrameMutex);
 60
 61	while (threadContext->state == oldState) {
 62		MutexUnlock(&threadContext->stateMutex);
 63
 64		if (!MutexTryLock(&threadContext->sync.videoFrameMutex)) {
 65			ConditionWake(&threadContext->sync.videoFrameRequiredCond);
 66			MutexUnlock(&threadContext->sync.videoFrameMutex);
 67		}
 68
 69		if (!MutexTryLock(&threadContext->sync.audioBufferMutex)) {
 70			ConditionWake(&threadContext->sync.audioRequiredCond);
 71			MutexUnlock(&threadContext->sync.audioBufferMutex);
 72		}
 73
 74		MutexLock(&threadContext->stateMutex);
 75		ConditionWake(&threadContext->stateCond);
 76	}
 77
 78	MutexLock(&threadContext->sync.videoFrameMutex);
 79	threadContext->sync.videoFrameWait = videoFrameWait;
 80	MutexUnlock(&threadContext->sync.videoFrameMutex);
 81}
 82
 83static void _pauseThread(struct mCoreThread* threadContext, bool onThread) {
 84	threadContext->state = THREAD_PAUSING;
 85	if (!onThread) {
 86		_waitUntilNotState(threadContext, THREAD_PAUSING);
 87	}
 88}
 89
 90static THREAD_ENTRY _mCoreThreadRun(void* context) {
 91	struct mCoreThread* threadContext = context;
 92#ifdef USE_PTHREADS
 93	pthread_once(&_contextOnce, _createTLS);
 94	pthread_setspecific(_contextKey, threadContext);
 95#elif _WIN32
 96	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
 97	TlsSetValue(_contextKey, threadContext);
 98#endif
 99
100	ThreadSetName("CPU Thread");
101
102#if !defined(_WIN32) && defined(USE_PTHREADS)
103	sigset_t signals;
104	sigemptyset(&signals);
105	pthread_sigmask(SIG_SETMASK, &signals, 0);
106#endif
107
108	struct mCore* core = threadContext->core;
109	core->setSync(core, &threadContext->sync);
110	core->reset(core);
111
112	if (threadContext->startCallback) {
113		threadContext->startCallback(threadContext);
114	}
115
116	_changeState(threadContext, THREAD_RUNNING, true);
117
118	while (threadContext->state < THREAD_EXITING) {
119		struct mDebugger* debugger = core->debugger;
120		if (debugger) {
121			mDebuggerRun(debugger);
122			if (debugger->state == DEBUGGER_SHUTDOWN) {
123				_changeState(threadContext, THREAD_EXITING, false);
124			}
125		} else {
126			while (threadContext->state == THREAD_RUNNING) {
127				core->runLoop(core);
128			}
129		}
130
131		int resetScheduled = 0;
132		MutexLock(&threadContext->stateMutex);
133		while (threadContext->state > THREAD_RUNNING && threadContext->state < THREAD_EXITING) {
134			if (threadContext->state == THREAD_PAUSING) {
135				threadContext->state = THREAD_PAUSED;
136				ConditionWake(&threadContext->stateCond);
137			}
138			if (threadContext->state == THREAD_INTERRUPTING) {
139				threadContext->state = THREAD_INTERRUPTED;
140				ConditionWake(&threadContext->stateCond);
141			}
142			if (threadContext->state == THREAD_RUN_ON) {
143				if (threadContext->run) {
144					threadContext->run(threadContext);
145				}
146				threadContext->state = threadContext->savedState;
147				ConditionWake(&threadContext->stateCond);
148			}
149			if (threadContext->state == THREAD_RESETING) {
150				threadContext->state = THREAD_RUNNING;
151				resetScheduled = 1;
152			}
153			while (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_INTERRUPTED) {
154				ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
155			}
156		}
157		MutexUnlock(&threadContext->stateMutex);
158		if (resetScheduled) {
159			core->reset(core);
160		}
161	}
162
163	while (threadContext->state < THREAD_SHUTDOWN) {
164		_changeState(threadContext, THREAD_SHUTDOWN, false);
165	}
166
167	if (threadContext->cleanCallback) {
168		threadContext->cleanCallback(threadContext);
169	}
170
171	return 0;
172}
173
174bool mCoreThreadStart(struct mCoreThread* threadContext) {
175	threadContext->state = THREAD_INITIALIZED;
176	threadContext->logger.p = threadContext;
177	threadContext->logLevel = threadContext->core->opts.logLevel;
178
179	if (!threadContext->sync.fpsTarget) {
180		threadContext->sync.fpsTarget = _defaultFPSTarget;
181	}
182
183	MutexInit(&threadContext->stateMutex);
184	ConditionInit(&threadContext->stateCond);
185
186	MutexInit(&threadContext->sync.videoFrameMutex);
187	ConditionInit(&threadContext->sync.videoFrameAvailableCond);
188	ConditionInit(&threadContext->sync.videoFrameRequiredCond);
189	MutexInit(&threadContext->sync.audioBufferMutex);
190	ConditionInit(&threadContext->sync.audioRequiredCond);
191
192	threadContext->interruptDepth = 0;
193
194#ifdef USE_PTHREADS
195	sigset_t signals;
196	sigemptyset(&signals);
197	sigaddset(&signals, SIGINT);
198	sigaddset(&signals, SIGTRAP);
199	pthread_sigmask(SIG_BLOCK, &signals, 0);
200#endif
201
202	threadContext->sync.audioWait = threadContext->core->opts.audioSync;
203	threadContext->sync.videoFrameWait = threadContext->core->opts.videoSync;
204	threadContext->sync.fpsTarget = threadContext->core->opts.fpsTarget;
205
206	MutexLock(&threadContext->stateMutex);
207	ThreadCreate(&threadContext->thread, _mCoreThreadRun, threadContext);
208	while (threadContext->state < THREAD_RUNNING) {
209		ConditionWait(&threadContext->stateCond, &threadContext->stateMutex);
210	}
211	MutexUnlock(&threadContext->stateMutex);
212
213	return true;
214}
215
216bool mCoreThreadHasStarted(struct mCoreThread* threadContext) {
217	bool hasStarted;
218	MutexLock(&threadContext->stateMutex);
219	hasStarted = threadContext->state > THREAD_INITIALIZED;
220	MutexUnlock(&threadContext->stateMutex);
221	return hasStarted;
222}
223
224bool mCoreThreadHasExited(struct mCoreThread* threadContext) {
225	bool hasExited;
226	MutexLock(&threadContext->stateMutex);
227	hasExited = threadContext->state > THREAD_EXITING;
228	MutexUnlock(&threadContext->stateMutex);
229	return hasExited;
230}
231
232bool mCoreThreadHasCrashed(struct mCoreThread* threadContext) {
233	bool hasExited;
234	MutexLock(&threadContext->stateMutex);
235	hasExited = threadContext->state == THREAD_CRASHED;
236	MutexUnlock(&threadContext->stateMutex);
237	return hasExited;
238}
239
240void mCoreThreadEnd(struct mCoreThread* threadContext) {
241	MutexLock(&threadContext->stateMutex);
242	_waitOnInterrupt(threadContext);
243	threadContext->state = THREAD_EXITING;
244	ConditionWake(&threadContext->stateCond);
245	MutexUnlock(&threadContext->stateMutex);
246	MutexLock(&threadContext->sync.audioBufferMutex);
247	threadContext->sync.audioWait = 0;
248	ConditionWake(&threadContext->sync.audioRequiredCond);
249	MutexUnlock(&threadContext->sync.audioBufferMutex);
250
251	MutexLock(&threadContext->sync.videoFrameMutex);
252	threadContext->sync.videoFrameWait = false;
253	threadContext->sync.videoFrameOn = false;
254	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
255	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
256	MutexUnlock(&threadContext->sync.videoFrameMutex);
257}
258
259void mCoreThreadReset(struct mCoreThread* threadContext) {
260	MutexLock(&threadContext->stateMutex);
261	_waitOnInterrupt(threadContext);
262	threadContext->state = THREAD_RESETING;
263	ConditionWake(&threadContext->stateCond);
264	MutexUnlock(&threadContext->stateMutex);
265}
266
267void mCoreThreadJoin(struct mCoreThread* threadContext) {
268	ThreadJoin(threadContext->thread);
269
270	MutexDeinit(&threadContext->stateMutex);
271	ConditionDeinit(&threadContext->stateCond);
272
273	MutexDeinit(&threadContext->sync.videoFrameMutex);
274	ConditionWake(&threadContext->sync.videoFrameAvailableCond);
275	ConditionDeinit(&threadContext->sync.videoFrameAvailableCond);
276	ConditionWake(&threadContext->sync.videoFrameRequiredCond);
277	ConditionDeinit(&threadContext->sync.videoFrameRequiredCond);
278
279	ConditionWake(&threadContext->sync.audioRequiredCond);
280	ConditionDeinit(&threadContext->sync.audioRequiredCond);
281	MutexDeinit(&threadContext->sync.audioBufferMutex);
282}
283
284bool mCoreThreadIsActive(struct mCoreThread* threadContext) {
285	return threadContext->state >= THREAD_RUNNING && threadContext->state < THREAD_EXITING;
286}
287
288void mCoreThreadInterrupt(struct mCoreThread* threadContext) {
289	if (!threadContext) {
290		return;
291	}
292	MutexLock(&threadContext->stateMutex);
293	++threadContext->interruptDepth;
294	if (threadContext->interruptDepth > 1 || !mCoreThreadIsActive(threadContext)) {
295		MutexUnlock(&threadContext->stateMutex);
296		return;
297	}
298	threadContext->savedState = threadContext->state;
299	_waitOnInterrupt(threadContext);
300	threadContext->state = THREAD_INTERRUPTING;
301	ConditionWake(&threadContext->stateCond);
302	_waitUntilNotState(threadContext, THREAD_INTERRUPTING);
303	MutexUnlock(&threadContext->stateMutex);
304}
305
306void mCoreThreadContinue(struct mCoreThread* threadContext) {
307	if (!threadContext) {
308		return;
309	}
310	MutexLock(&threadContext->stateMutex);
311	--threadContext->interruptDepth;
312	if (threadContext->interruptDepth < 1 && mCoreThreadIsActive(threadContext)) {
313		threadContext->state = threadContext->savedState;
314		ConditionWake(&threadContext->stateCond);
315	}
316	MutexUnlock(&threadContext->stateMutex);
317}
318
319void mCoreThreadRunFunction(struct mCoreThread* threadContext, void (*run)(struct mCoreThread*)) {
320	MutexLock(&threadContext->stateMutex);
321	threadContext->run = run;
322	_waitOnInterrupt(threadContext);
323	threadContext->savedState = threadContext->state;
324	threadContext->state = THREAD_RUN_ON;
325	ConditionWake(&threadContext->stateCond);
326	_waitUntilNotState(threadContext, THREAD_RUN_ON);
327	MutexUnlock(&threadContext->stateMutex);
328}
329
330void mCoreThreadPause(struct mCoreThread* threadContext) {
331	bool frameOn = threadContext->sync.videoFrameOn;
332	MutexLock(&threadContext->stateMutex);
333	_waitOnInterrupt(threadContext);
334	if (threadContext->state == THREAD_RUNNING) {
335		_pauseThread(threadContext, false);
336		threadContext->frameWasOn = frameOn;
337		frameOn = false;
338	}
339	MutexUnlock(&threadContext->stateMutex);
340
341	mCoreSyncSetVideoSync(&threadContext->sync, frameOn);
342}
343
344void mCoreThreadUnpause(struct mCoreThread* threadContext) {
345	bool frameOn = threadContext->sync.videoFrameOn;
346	MutexLock(&threadContext->stateMutex);
347	_waitOnInterrupt(threadContext);
348	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
349		threadContext->state = THREAD_RUNNING;
350		ConditionWake(&threadContext->stateCond);
351		frameOn = threadContext->frameWasOn;
352	}
353	MutexUnlock(&threadContext->stateMutex);
354
355	mCoreSyncSetVideoSync(&threadContext->sync, frameOn);
356}
357
358bool mCoreThreadIsPaused(struct mCoreThread* threadContext) {
359	bool isPaused;
360	MutexLock(&threadContext->stateMutex);
361	_waitOnInterrupt(threadContext);
362	isPaused = threadContext->state == THREAD_PAUSED;
363	MutexUnlock(&threadContext->stateMutex);
364	return isPaused;
365}
366
367void mCoreThreadTogglePause(struct mCoreThread* threadContext) {
368	bool frameOn = threadContext->sync.videoFrameOn;
369	MutexLock(&threadContext->stateMutex);
370	_waitOnInterrupt(threadContext);
371	if (threadContext->state == THREAD_PAUSED || threadContext->state == THREAD_PAUSING) {
372		threadContext->state = THREAD_RUNNING;
373		ConditionWake(&threadContext->stateCond);
374		frameOn = threadContext->frameWasOn;
375	} else if (threadContext->state == THREAD_RUNNING) {
376		_pauseThread(threadContext, false);
377		threadContext->frameWasOn = frameOn;
378		frameOn = false;
379	}
380	MutexUnlock(&threadContext->stateMutex);
381
382	mCoreSyncSetVideoSync(&threadContext->sync, frameOn);
383}
384
385void mCoreThreadPauseFromThread(struct mCoreThread* threadContext) {
386	bool frameOn = true;
387	MutexLock(&threadContext->stateMutex);
388	_waitOnInterrupt(threadContext);
389	if (threadContext->state == THREAD_RUNNING) {
390		_pauseThread(threadContext, true);
391		frameOn = false;
392	}
393	MutexUnlock(&threadContext->stateMutex);
394
395	mCoreSyncSetVideoSync(&threadContext->sync, frameOn);
396}
397
398#ifdef USE_PTHREADS
399struct mCoreThread* mCoreThreadGet(void) {
400	pthread_once(&_contextOnce, _createTLS);
401	return pthread_getspecific(_contextKey);
402}
403#elif _WIN32
404struct mCoreThread* mCoreThreadGet(void) {
405	InitOnceExecuteOnce(&_contextOnce, _createTLS, NULL, 0);
406	return TlsGetValue(_contextKey);
407}
408#else
409struct mCoreThread* mCoreThreadGet(void) {
410	return NULL;
411}
412#endif
413
414#else
415struct mCoreThread* mCoreThreadGet(void) {
416	return NULL;
417}
418#endif
419
420static void _mCoreLog(struct mLogger* logger, int category, enum mLogLevel level, const char* format, va_list args) {
421	UNUSED(logger);
422	struct mCoreThread* thread = mCoreThreadGet();
423	if (thread && !(thread->logLevel & level)) {
424		return;
425	}
426	printf("%s: ", mLogCategoryName(category));
427	vprintf(format, args);
428	printf("\n");
429}
430
431struct mLogger* mCoreThreadLogger(void) {
432	struct mCoreThread* thread = mCoreThreadGet();
433	if (thread) {
434		if (!thread->logger.d.log) {
435			thread->logger.d.log = _mCoreLog;
436		}
437		return &thread->logger.d;
438	}
439	return NULL;
440}
441