Make it commit ready
[kugel-rb.git] / firmware / target / hosted / sdl / thread-sdl.c
blobfbe2621d404261f2f4fed20e67cfd2745d8b6442
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2006 Dan Everton
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation; either version 2
15 * of the License, or (at your option) any later version.
17 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
18 * KIND, either express or implied.
20 ****************************************************************************/
22 #include <stdbool.h>
23 #include <time.h>
24 #include <SDL.h>
25 #include <SDL_thread.h>
26 #include <stdlib.h>
27 #include <memory.h>
28 #include <setjmp.h>
29 #include "system-sdl.h"
30 #include "thread-sdl.h"
31 #include "system.h"
32 #include "kernel.h"
33 #include "thread.h"
34 #include "debug.h"
36 /* Define this as 1 to show informational messages that are not errors. */
37 #define THREAD_SDL_DEBUGF_ENABLED 0
39 #if THREAD_SDL_DEBUGF_ENABLED
40 #define THREAD_SDL_DEBUGF(...) DEBUGF(__VA_ARGS__)
41 static char __name[32];
42 #define THREAD_SDL_GET_NAME(thread) \
43 ({ thread_get_name(__name, ARRAYLEN(__name), thread); __name; })
44 #else
45 #define THREAD_SDL_DEBUGF(...)
46 #define THREAD_SDL_GET_NAME(thread)
47 #endif
49 #define THREAD_PANICF(str...) \
50 ({ fprintf(stderr, str); exit(-1); })
52 /* Thread/core entries as in rockbox core */
53 static struct core_entry cores[NUM_CORES];
54 struct thread_entry threads[MAXTHREADS];
55 /* Jump buffers for graceful exit - kernel threads don't stay neatly
56 * in their start routines responding to messages so this is the only
57 * way to get them back in there so they may exit */
58 static jmp_buf thread_jmpbufs[MAXTHREADS];
59 /* this mutex locks out other Rockbox threads while one runs,
60 * that enables us to simulate a cooperative environment even if
61 * the host is preemptive */
62 static SDL_mutex *m;
63 static volatile bool threads_exit = false;
65 extern long start_tick;
67 void sim_thread_shutdown(void)
69 int i;
71 /* Tell all threads jump back to their start routines, unlock and exit
72 gracefully - we'll check each one in turn for it's status. Threads
73 _could_ terminate via remove_thread or multiple threads could exit
74 on each unlock but that is safe. */
76 /* Do this before trying to acquire lock */
77 threads_exit = true;
79 /* Take control */
80 SDL_LockMutex(m);
82 for (i = 0; i < MAXTHREADS; i++)
84 struct thread_entry *thread = &threads[i];
85 /* exit all current threads, except the main one */
86 if (thread->context.t != NULL)
88 /* Signal thread on delay or block */
89 SDL_Thread *t = thread->context.t;
90 SDL_SemPost(thread->context.s);
91 SDL_UnlockMutex(m);
92 /* Wait for it to finish */
93 SDL_WaitThread(t, NULL);
94 /* Relock for next thread signal */
95 SDL_LockMutex(m);
99 SDL_UnlockMutex(m);
100 SDL_DestroyMutex(m);
103 static void new_thread_id(unsigned int slot_num,
104 struct thread_entry *thread)
106 unsigned int version =
107 (thread->id + (1u << THREAD_ID_VERSION_SHIFT))
108 & THREAD_ID_VERSION_MASK;
110 if (version == 0)
111 version = 1u << THREAD_ID_VERSION_SHIFT;
113 thread->id = version | (slot_num & THREAD_ID_SLOT_MASK);
116 static struct thread_entry * find_empty_thread_slot(void)
118 struct thread_entry *thread = NULL;
119 int n;
121 for (n = 0; n < MAXTHREADS; n++)
123 int state = threads[n].state;
125 if (state == STATE_KILLED)
127 thread = &threads[n];
128 break;
132 return thread;
136 /* Initialize SDL threading */
137 void init_threads(void)
139 struct thread_entry *thread;
140 int n;
142 memset(cores, 0, sizeof(cores));
143 memset(threads, 0, sizeof(threads));
145 m = SDL_CreateMutex();
147 if (SDL_LockMutex(m) == -1)
149 fprintf(stderr, "Couldn't lock mutex\n");
150 return;
153 /* Initialize all IDs */
154 for (n = 0; n < MAXTHREADS; n++)
155 threads[n].id = THREAD_ID_INIT(n);
157 /* Slot 0 is reserved for the main thread - initialize it here and
158 then create the SDL thread - it is possible to have a quick, early
159 shutdown try to access the structure. */
160 thread = &threads[0];
161 thread->stack = (uintptr_t *)" ";
162 thread->stack_size = 8;
163 thread->name = "main";
164 thread->state = STATE_RUNNING;
165 thread->context.s = SDL_CreateSemaphore(0);
166 thread->context.t = NULL; /* NULL for the implicit main thread */
167 cores[CURRENT_CORE].running = thread;
169 if (thread->context.s == NULL)
171 fprintf(stderr, "Failed to create main semaphore\n");
172 return;
175 THREAD_SDL_DEBUGF("Main thread: %p\n", thread);
177 return;
180 void sim_thread_exception_wait(void)
182 while (1)
184 SDL_Delay(HZ/10);
185 if (threads_exit)
186 thread_exit();
190 /* A way to yield and leave the threading system for extended periods */
191 void sim_thread_lock(void *me)
193 SDL_LockMutex(m);
194 cores[CURRENT_CORE].running = (struct thread_entry *)me;
196 if (threads_exit)
197 thread_exit();
200 void * sim_thread_unlock(void)
202 struct thread_entry *current = cores[CURRENT_CORE].running;
203 SDL_UnlockMutex(m);
204 return current;
207 struct thread_entry * thread_id_entry(unsigned int thread_id)
209 return (thread_id == THREAD_ID_CURRENT) ?
210 cores[CURRENT_CORE].running :
211 &threads[thread_id & THREAD_ID_SLOT_MASK];
214 static void add_to_list_l(struct thread_entry **list,
215 struct thread_entry *thread)
217 if (*list == NULL)
219 /* Insert into unoccupied list */
220 thread->l.next = thread;
221 thread->l.prev = thread;
222 *list = thread;
224 else
226 /* Insert last */
227 thread->l.next = *list;
228 thread->l.prev = (*list)->l.prev;
229 thread->l.prev->l.next = thread;
230 (*list)->l.prev = thread;
234 static void remove_from_list_l(struct thread_entry **list,
235 struct thread_entry *thread)
237 if (thread == thread->l.next)
239 /* The only item */
240 *list = NULL;
241 return;
244 if (thread == *list)
246 /* List becomes next item */
247 *list = thread->l.next;
250 /* Fix links to jump over the removed entry. */
251 thread->l.prev->l.next = thread->l.next;
252 thread->l.next->l.prev = thread->l.prev;
255 unsigned int thread_get_current(void)
257 return cores[CURRENT_CORE].running->id;
260 void switch_thread(void)
262 struct thread_entry *current = cores[CURRENT_CORE].running;
264 enable_irq();
266 switch (current->state)
268 case STATE_RUNNING:
270 SDL_UnlockMutex(m);
271 /* Any other thread waiting already will get it first */
272 SDL_LockMutex(m);
273 break;
274 } /* STATE_RUNNING: */
276 case STATE_BLOCKED:
278 int oldlevel;
280 SDL_UnlockMutex(m);
281 SDL_SemWait(current->context.s);
282 SDL_LockMutex(m);
284 oldlevel = disable_irq_save();
285 current->state = STATE_RUNNING;
286 restore_irq(oldlevel);
287 break;
288 } /* STATE_BLOCKED: */
290 case STATE_BLOCKED_W_TMO:
292 int result, oldlevel;
294 SDL_UnlockMutex(m);
295 result = SDL_SemWaitTimeout(current->context.s, current->tmo_tick);
296 SDL_LockMutex(m);
298 oldlevel = disable_irq_save();
300 if (current->state == STATE_BLOCKED_W_TMO)
302 /* Timed out */
303 remove_from_list_l(current->bqp, current);
305 #ifdef HAVE_WAKEUP_EXT_CB
306 if (current->wakeup_ext_cb != NULL)
307 current->wakeup_ext_cb(current);
308 #endif
309 current->state = STATE_RUNNING;
312 if (result == SDL_MUTEX_TIMEDOUT)
314 /* Other signals from an explicit wake could have been made before
315 * arriving here if we timed out waiting for the semaphore. Make
316 * sure the count is reset. */
317 while (SDL_SemValue(current->context.s) > 0)
318 SDL_SemTryWait(current->context.s);
321 restore_irq(oldlevel);
322 break;
323 } /* STATE_BLOCKED_W_TMO: */
325 case STATE_SLEEPING:
327 SDL_UnlockMutex(m);
328 SDL_SemWaitTimeout(current->context.s, current->tmo_tick);
329 SDL_LockMutex(m);
330 current->state = STATE_RUNNING;
331 break;
332 } /* STATE_SLEEPING: */
335 cores[CURRENT_CORE].running = current;
337 if (threads_exit)
338 thread_exit();
341 void sleep_thread(int ticks)
343 struct thread_entry *current = cores[CURRENT_CORE].running;
344 int rem;
346 current->state = STATE_SLEEPING;
348 rem = (SDL_GetTicks() - start_tick) % (1000/HZ);
349 if (rem < 0)
350 rem = 0;
352 current->tmo_tick = (1000/HZ) * ticks + ((1000/HZ)-1) - rem;
355 void block_thread(struct thread_entry *current)
357 current->state = STATE_BLOCKED;
358 add_to_list_l(current->bqp, current);
361 void block_thread_w_tmo(struct thread_entry *current, int ticks)
363 current->state = STATE_BLOCKED_W_TMO;
364 current->tmo_tick = (1000/HZ)*ticks;
365 add_to_list_l(current->bqp, current);
368 unsigned int wakeup_thread(struct thread_entry **list)
370 struct thread_entry *thread = *list;
372 if (thread != NULL)
374 switch (thread->state)
376 case STATE_BLOCKED:
377 case STATE_BLOCKED_W_TMO:
378 remove_from_list_l(list, thread);
379 thread->state = STATE_RUNNING;
380 SDL_SemPost(thread->context.s);
381 return THREAD_OK;
385 return THREAD_NONE;
388 unsigned int thread_queue_wake(struct thread_entry **list)
390 unsigned int result = THREAD_NONE;
392 for (;;)
394 unsigned int rc = wakeup_thread(list);
396 if (rc == THREAD_NONE)
397 break;
399 result |= rc;
402 return result;
405 void thread_thaw(unsigned int thread_id)
407 struct thread_entry *thread = thread_id_entry(thread_id);
409 if (thread->id == thread_id && thread->state == STATE_FROZEN)
411 thread->state = STATE_RUNNING;
412 SDL_SemPost(thread->context.s);
416 int runthread(void *data)
418 struct thread_entry *current;
419 jmp_buf *current_jmpbuf;
421 /* Cannot access thread variables before locking the mutex as the
422 data structures may not be filled-in yet. */
423 SDL_LockMutex(m);
424 cores[CURRENT_CORE].running = (struct thread_entry *)data;
425 current = cores[CURRENT_CORE].running;
426 current_jmpbuf = &thread_jmpbufs[current - threads];
428 /* Setup jump for exit */
429 if (setjmp(*current_jmpbuf) == 0)
431 /* Run the thread routine */
432 if (current->state == STATE_FROZEN)
434 SDL_UnlockMutex(m);
435 SDL_SemWait(current->context.s);
436 SDL_LockMutex(m);
437 cores[CURRENT_CORE].running = current;
440 if (!threads_exit)
442 current->context.start();
443 THREAD_SDL_DEBUGF("Thread Done: %d (%s)\n",
444 current - threads, THREAD_SDL_GET_NAME(current));
445 /* Thread routine returned - suicide */
448 thread_exit();
450 else
452 /* Unlock and exit */
453 SDL_UnlockMutex(m);
456 return 0;
459 unsigned int create_thread(void (*function)(void),
460 void* stack, size_t stack_size,
461 unsigned flags, const char *name)
463 struct thread_entry *thread;
464 SDL_Thread* t;
465 SDL_sem *s;
467 THREAD_SDL_DEBUGF("Creating thread: (%s)\n", name ? name : "");
469 thread = find_empty_thread_slot();
470 if (thread == NULL)
472 DEBUGF("Failed to find thread slot\n");
473 return 0;
476 s = SDL_CreateSemaphore(0);
477 if (s == NULL)
479 DEBUGF("Failed to create semaphore\n");
480 return 0;
483 t = SDL_CreateThread(runthread, thread);
484 if (t == NULL)
486 DEBUGF("Failed to create SDL thread\n");
487 SDL_DestroySemaphore(s);
488 return 0;
491 thread->stack = stack;
492 thread->stack_size = stack_size;
493 thread->name = name;
494 thread->state = (flags & CREATE_THREAD_FROZEN) ?
495 STATE_FROZEN : STATE_RUNNING;
496 thread->context.start = function;
497 thread->context.t = t;
498 thread->context.s = s;
500 THREAD_SDL_DEBUGF("New Thread: %d (%s)\n",
501 thread - threads, THREAD_SDL_GET_NAME(thread));
503 return thread->id;
506 #ifndef ALLOW_REMOVE_THREAD
507 static void remove_thread(unsigned int thread_id)
508 #else
509 void remove_thread(unsigned int thread_id)
510 #endif
512 struct thread_entry *current = cores[CURRENT_CORE].running;
513 struct thread_entry *thread = thread_id_entry(thread_id);
515 SDL_Thread *t;
516 SDL_sem *s;
518 if (thread_id != THREAD_ID_CURRENT && thread->id != thread_id)
519 return;
521 int oldlevel = disable_irq_save();
523 t = thread->context.t;
524 s = thread->context.s;
525 thread->context.t = NULL;
527 if (thread != current)
529 switch (thread->state)
531 case STATE_BLOCKED:
532 case STATE_BLOCKED_W_TMO:
533 /* Remove thread from object it's waiting on */
534 remove_from_list_l(thread->bqp, thread);
536 #ifdef HAVE_WAKEUP_EXT_CB
537 if (thread->wakeup_ext_cb != NULL)
538 thread->wakeup_ext_cb(thread);
539 #endif
540 break;
543 SDL_SemPost(s);
546 THREAD_SDL_DEBUGF("Removing thread: %d (%s)\n",
547 thread - threads, THREAD_SDL_GET_NAME(thread));
549 new_thread_id(thread->id, thread);
550 thread->state = STATE_KILLED;
551 thread_queue_wake(&thread->queue);
553 SDL_DestroySemaphore(s);
555 if (thread == current)
557 /* Do a graceful exit - perform the longjmp back into the thread
558 function to return */
559 restore_irq(oldlevel);
560 longjmp(thread_jmpbufs[current - threads], 1);
563 SDL_KillThread(t);
564 restore_irq(oldlevel);
567 void thread_exit(void)
569 remove_thread(THREAD_ID_CURRENT);
572 void thread_wait(unsigned int thread_id)
574 struct thread_entry *current = cores[CURRENT_CORE].running;
575 struct thread_entry *thread = thread_id_entry(thread_id);
577 if (thread_id == THREAD_ID_CURRENT ||
578 (thread->id == thread_id && thread->state != STATE_KILLED))
580 current->bqp = &thread->queue;
581 block_thread(current);
582 switch_thread();
586 int thread_stack_usage(const struct thread_entry *thread)
588 return 50;
589 (void)thread;
592 /* Return name if one or ID if none */
593 void thread_get_name(char *buffer, int size,
594 struct thread_entry *thread)
596 if (size <= 0)
597 return;
599 *buffer = '\0';
601 if (thread)
603 /* Display thread name if one or ID if none */
604 bool named = thread->name && *thread->name;
605 const char *fmt = named ? "%s" : "%08lX";
606 intptr_t name = named ?
607 (intptr_t)thread->name : (intptr_t)thread;
608 snprintf(buffer, size, fmt, name);