4 * - Common Thread Control
10 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
11 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
14 #define DEFAULT_QUANTUM 10
15 #define DEFAULT_TICKETS 5
16 #define MAX_TICKETS 10
17 const enum eConfigTypes cCONFIG_TYPES[] = {
18 CFGT_HEAPSTR, // e.g. CFG_VFS_CWD
19 CFGT_INT, // e.g. CFG_VFS_MAXFILES
24 extern void ArchThreads_Init(void);
25 extern void Proc_Start(void);
26 extern tThread *Proc_GetCurThread(void);
27 extern int Proc_Clone(Uint *Err, Uint Flags);
28 extern void Proc_CallFaultHandler(tThread *Thread);
31 void Threads_Init(void);
32 int Threads_SetName(char *NewName);
33 char *Threads_GetName(int ID);
34 void Threads_SetTickets(tThread *Thread, int Num);
35 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
36 int Threads_WaitTID(int TID, int *status);
37 tThread *Threads_GetThread(Uint TID);
38 void Threads_AddToDelete(tThread *Thread);
39 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread);
40 void Threads_Exit(int TID, int Status);
41 void Threads_Kill(tThread *Thread, int Status);
42 void Threads_Yield(void);
43 void Threads_Sleep(void);
44 int Threads_Wake(tThread *Thread);
45 void Threads_AddActive(tThread *Thread);
46 tThread *Threads_RemActive(void);
47 int Threads_GetPID(void);
48 int Threads_GetTID(void);
49 tUID Threads_GetUID(void);
50 int Threads_SetUID(Uint *Errno, tUID ID);
51 tGID Threads_GetGID(void);
52 int Threads_SetGID(Uint *Errno, tUID ID);
53 void Threads_Dump(void);
54 void Mutex_Acquire(tMutex *Mutex);
55 void Mutex_Release(tMutex *Mutex);
56 int Mutex_IsLocked(tMutex *Mutex);
60 // Only used for the core kernel
61 tThread gThreadZero = {
62 Status: THREAD_STAT_ACTIVE, // Status
63 ThreadName: "ThreadZero", // Name
64 Quantum: DEFAULT_QUANTUM, // Default Quantum
65 Remaining: DEFAULT_QUANTUM, // Current Quantum
66 NumTickets: DEFAULT_TICKETS // Number of tickets
70 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
71 // --- Current State ---
72 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
73 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
74 volatile Uint giNextTID = 1; // Next TID to allocate
75 // --- Thread Lists ---
76 tThread *gAllThreads = NULL; // All allocated threads
77 tThread *gActiveThreads = NULL; // Currently Running Threads
78 tThread *gSleepingThreads = NULL; // Sleeping Threads
79 tThread *gDeleteThreads = NULL; // Threads to delete
80 int giNumCPUs = 1; // Number of CPUs
84 * \fn void Threads_Init(void)
85 * \brief Initialse the thread list
87 void Threads_Init(void)
91 // Create Initial Task
92 gActiveThreads = &gThreadZero;
93 gAllThreads = &gThreadZero;
94 //giFreeTickets = gThreadZero.NumTickets; // Not needed, as ThreadZero is scheduled
95 giNumActiveThreads = 1;
101 * \fn void Threads_SetName(char *NewName)
102 * \brief Sets the current thread's name
103 * \param NewName New name for the thread
104 * \return Boolean Failure
106 int Threads_SetName(char *NewName)
108 tThread *cur = Proc_GetCurThread();
109 char *oldname = cur->ThreadName;
111 // NOTE: There is a possibility of non-thread safety here
112 // A thread could read the current name pointer before it is zeroed
114 cur->ThreadName = NULL;
116 if( IsHeap(oldname) ) free( oldname );
118 cur->ThreadName = strdup(NewName);
123 * \fn char *Threads_GetName(int ID)
124 * \brief Gets a thread's name
125 * \param ID Thread ID (-1 indicates current thread)
126 * \return Pointer to name
127 * \retval NULL Failure
129 char *Threads_GetName(tTID ID)
132 return Proc_GetCurThread()->ThreadName;
134 return Threads_GetThread(ID)->ThreadName;
138 * \fn void Threads_SetTickets(tThread *Thread, int Num)
139 * \brief Sets the 'priority' of a task
140 * \param Thread Thread to update ticket count (NULL means current thread)
141 * \param Num New ticket count (must be >= 0, clipped to \a MAX_TICKETS)
143 void Threads_SetTickets(tThread *Thread, int Num)
145 // Get current thread
146 if(Thread == NULL) Thread = Proc_GetCurThread();
149 if(Num > MAX_TICKETS) Num = MAX_TICKETS;
151 // If this isn't the current thread, we need to lock
152 if( Thread != Proc_GetCurThread() ) {
153 SHORTLOCK( &glThreadListLock );
154 giFreeTickets -= Thread->NumTickets - Num;
155 Thread->NumTickets = Num;
156 #if DEBUG_TRACE_TICKETS
157 Log("Threads_SetTickets: new giFreeTickets = %i", giFreeTickets);
159 SHORTREL( &glThreadListLock );
162 Thread->NumTickets = Num;
166 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
167 * \brief Clone the TCB of the current thread
168 * \param Err Error pointer
169 * \param Flags Flags for something... (What is this for?)
171 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
175 cur = Proc_GetCurThread();
177 // Allocate and duplicate
178 new = malloc(sizeof(tThread));
183 memcpy(new, cur, sizeof(tThread));
187 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
188 new->Status = THREAD_STAT_PREINIT;
192 new->TID = giNextTID++;
196 new->ThreadName = strdup(cur->ThreadName);
198 // Set Thread Group ID (PID)
200 new->TGID = new->TID;
202 new->TGID = cur->TGID;
204 // Messages are not inherited
205 new->Messages = NULL;
206 new->LastMessage = NULL;
209 new->Remaining = new->Quantum = cur->Quantum;
210 new->NumTickets = cur->NumTickets;
212 // Set Signal Handlers
213 new->CurFaultNum = 0;
214 new->FaultHandler = cur->FaultHandler;
216 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
218 switch(cCONFIG_TYPES[i])
221 new->Config[i] = cur->Config[i];
225 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
232 // Maintain a global list of threads
233 SHORTLOCK( &glThreadListLock );
234 new->GlobalPrev = NULL; // Protect against bugs
235 new->GlobalNext = gAllThreads;
237 SHORTREL( &glThreadListLock );
243 * \brief Get a configuration pointer from the Per-Thread data area
244 * \param ID Config slot ID
245 * \return Pointer at ID
247 Uint *Threads_GetCfgPtr(int ID)
249 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
250 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
254 return &Proc_GetCurThread()->Config[ID];
258 * \brief Wait for a task to change state
259 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
260 * \param Status Thread return status
261 * \return TID of child that changed state
263 tTID Threads_WaitTID(int TID, int *Status)
267 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
271 // Any peer/child thread
273 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
279 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
285 tThread *t = Threads_GetThread(TID);
286 int initStatus = t->Status;
289 // Wait for the thread to die!
290 if(initStatus != THREAD_STAT_ZOMBIE) {
291 // TODO: Handle child also being suspended if wanted
292 while(t->Status != THREAD_STAT_ZOMBIE) {
294 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
295 Threads_GetTID(), t->TID, t->Status);
300 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
301 Threads_GetTID(), t->TID, t->Status);
305 case THREAD_STAT_ZOMBIE:
307 t->Status = THREAD_STAT_DEAD;
308 // TODO: Child return value?
309 if(Status) *Status = t->RetStatus;
310 // add to delete queue
311 Threads_AddToDelete( t );
314 if(Status) *Status = -1;
324 * \brief Gets a thread given its TID
325 * \param TID Thread ID
326 * \return Thread pointer
328 tThread *Threads_GetThread(Uint TID)
332 // Search global list
333 for(thread = gAllThreads;
335 thread = thread->GlobalNext)
337 if(thread->TID == TID)
341 Log("Unable to find TID %i on main list\n", TID);
347 * \brief Adds a thread to the delete queue
348 * \param Thread Thread to delete
350 void Threads_AddToDelete(tThread *Thread)
352 // Add to delete queue
353 // TODO: Is locking needed?
355 Thread->Next = gDeleteThreads;
356 gDeleteThreads = Thread;
359 gDeleteThreads = Thread;
364 * \brief Gets the previous entry in a thead linked list
365 * \param List Pointer to the list head
366 * \param Thread Thread to find
367 * \return Thread before \a Thread on \a List
368 * \note This uses a massive hack of assuming that the first field in the
369 * structure is the .Next pointer. By doing this, we can return \a List
370 * as a (tThread*) and simplify other code.
372 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread)
376 if(*List == Thread) {
377 return (tThread*)List;
382 ret->Next && ret->Next != Thread;
385 // Error if the thread is not on the list
386 if(!ret->Next || ret->Next != Thread) {
394 * \brief Exit the current process (or another?)
395 * \param TID Thread ID to kill
396 * \param Status Exit status
398 void Threads_Exit(int TID, int Status)
401 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
403 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
405 // Halt forever, just in case
410 * \fn void Threads_Kill(tThread *Thread, int Status)
411 * \brief Kill a thread
412 * \param Thread Thread to kill
413 * \param Status Status code to return to the parent
415 void Threads_Kill(tThread *Thread, int Status)
420 // TODO: Kill all children
424 // TODO: I should keep a .Parent pointer, and a .Children list
425 for(child = gActiveThreads;
429 if(child->PTID == Thread->TID)
430 Threads_Kill(child, -1);
435 ///\note Double lock is needed due to overlap of lock areas
437 // Lock thread (stop us recieving messages)
438 SHORTLOCK( &Thread->IsLocked );
440 // Clear Message Queue
441 while( Thread->Messages )
443 msg = Thread->Messages->Next;
444 free( Thread->Messages );
445 Thread->Messages = msg;
449 SHORTLOCK( &glThreadListLock );
451 // Get previous thread on list
452 prev = Threads_int_GetPrev( &gActiveThreads, Thread );
454 Warning("Proc_Exit - Current thread is not on the active queue");
455 SHORTREL( &glThreadListLock );
456 SHORTREL( &Thread->IsLocked );
460 // Ensure that we are not rescheduled
461 Thread->Remaining = 0; // Clear Remaining Quantum
462 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
463 prev->Next = Thread->Next; // Remove from active
465 // Update bookkeeping
466 giNumActiveThreads --;
467 if( Thread != Proc_GetCurThread() )
468 giFreeTickets -= Thread->NumTickets;
471 Thread->RetStatus = Status;
473 // Don't Zombie if we are being killed because our parent is
476 Thread->Status = THREAD_STAT_DEAD;
477 Threads_AddToDelete( Thread );
479 Thread->Status = THREAD_STAT_ZOMBIE;
481 Threads_Wake( Thread->Parent );
484 Log("Thread %i went *hurk* (%i)", Thread->TID, Thread->Status);
487 SHORTREL( &glThreadListLock );
488 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
498 * \brief Yield remainder of the current thread's timeslice
500 void Threads_Yield(void)
502 tThread *thread = Proc_GetCurThread();
503 thread->Remaining = 0;
504 //while(thread->Remaining == 0)
509 * \fn void Threads_Sleep(void)
510 * \brief Take the current process off the run queue
512 void Threads_Sleep(void)
514 tThread *cur = Proc_GetCurThread();
517 SHORTLOCK( &glThreadListLock );
519 // Don't sleep if there is a message waiting
520 if( cur->Messages ) {
521 SHORTREL( &glThreadListLock );
525 // Remove us from running queue
527 // Mark thread as sleeping
528 cur->Status = THREAD_STAT_SLEEPING;
530 // Add to Sleeping List (at the top)
531 cur->Next = gSleepingThreads;
532 gSleepingThreads = cur;
535 #if DEBUG_TRACE_STATE
536 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
540 SHORTREL( &glThreadListLock );
542 while(cur->Status != THREAD_STAT_ACTIVE) HALT();
547 * \fn int Threads_Wake( tThread *Thread )
548 * \brief Wakes a sleeping/waiting thread up
549 * \param Thread Thread to wake
550 * \return Boolean Failure (Returns ERRNO)
551 * \warning This should ONLY be called with task switches disabled
553 int Threads_Wake(tThread *Thread)
560 switch(Thread->Status)
562 case THREAD_STAT_ACTIVE:
563 Log("Thread_Wake: Waking awake thread (%i)", Thread->TID);
566 case THREAD_STAT_SLEEPING:
567 SHORTLOCK( &glThreadListLock );
568 // Remove from sleeping queue
569 prev = Threads_int_GetPrev(&gSleepingThreads, Thread);
570 prev->Next = Thread->Next;
572 Threads_AddActive( Thread );
574 #if DEBUG_TRACE_STATE
575 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
577 SHORTREL( &glThreadListLock );
580 case THREAD_STAT_WAITING:
581 Warning("Thread_Wake - Waiting threads are not currently supported");
584 case THREAD_STAT_DEAD:
585 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
589 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
595 * \brief Wake a thread given the TID
596 * \param TID Thread ID to wake
597 * \return Boolean Faulure (errno)
599 int Threads_WakeTID(tTID TID)
601 tThread *thread = Threads_GetThread(TID);
605 ret = Threads_Wake( thread );
606 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
611 * \brief Adds a thread to the active queue
613 void Threads_AddActive(tThread *Thread)
615 SHORTLOCK( &glThreadListLock );
620 for( t = gActiveThreads; t; t = t->Next )
623 Panic("Threads_AddActive: Attempting a double add of TID %i (0x%x)",
624 Thread->TID, __builtin_return_address(0));
627 if(t->Status != THREAD_STAT_ACTIVE) {
628 Panic("Threads_AddActive: TID %i status != THREAD_STAT_ACTIVE",
635 // Add to active list
636 Thread->Next = gActiveThreads;
637 gActiveThreads = Thread;
639 Thread->Status = THREAD_STAT_ACTIVE;
642 // Update bookkeeping
643 giNumActiveThreads ++;
644 giFreeTickets += Thread->NumTickets;
646 #if DEBUG_TRACE_TICKETS
647 Log("Threads_AddActive: %p %i (%s) added, new giFreeTickets = %i",
648 Thread, Thread->TID, Thread->ThreadName, giFreeTickets);
650 SHORTREL( &glThreadListLock );
654 * \brief Removes the current thread from the active queue
655 * \warning This should ONLY be called with task switches disabled
656 * \return Current thread pointer
658 tThread *Threads_RemActive(void)
660 tThread *ret = Proc_GetCurThread();
663 SHORTLOCK( &glThreadListLock );
665 prev = Threads_int_GetPrev(&gActiveThreads, ret);
667 SHORTREL( &glThreadListLock );
674 prev->Next = ret->Next;
675 giNumActiveThreads --;
676 // no need to decrement tickets, scheduler did it for us
678 #if DEBUG_TRACE_TICKETS
679 Log("Threads_RemActive: %p %i (%s) removed, giFreeTickets = %i",
680 ret, ret->TID, ret->ThreadName, giFreeTickets);
683 SHORTREL( &glThreadListLock );
689 * \fn void Threads_SetFaultHandler(Uint Handler)
690 * \brief Sets the signal handler for a signal
692 void Threads_SetFaultHandler(Uint Handler)
694 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
695 Proc_GetCurThread()->FaultHandler = Handler;
699 * \fn void Threads_Fault(int Num)
700 * \brief Calls a fault handler
702 void Threads_Fault(int Num)
704 tThread *thread = Proc_GetCurThread();
706 Log_Log("Threads", "Threads_Fault: thread = %p", thread);
710 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
712 switch(thread->FaultHandler)
715 Threads_Kill(thread, -1);
718 case 1: // Dump Core?
719 Threads_Kill(thread, -1);
724 // Double Fault? Oh, F**k
725 if(thread->CurFaultNum != 0) {
726 Threads_Kill(thread, -1); // For now, just kill
730 thread->CurFaultNum = Num;
732 Proc_CallFaultHandler(thread);
735 // --- Process Structure Access Functions ---
736 tPID Threads_GetPID(void)
738 return Proc_GetCurThread()->TGID;
740 tTID Threads_GetTID(void)
742 return Proc_GetCurThread()->TID;
744 tUID Threads_GetUID(void)
746 return Proc_GetCurThread()->UID;
748 tGID Threads_GetGID(void)
750 return Proc_GetCurThread()->GID;
753 int Threads_SetUID(Uint *Errno, tUID ID)
755 tThread *t = Proc_GetCurThread();
760 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
765 int Threads_SetGID(Uint *Errno, tGID ID)
767 tThread *t = Proc_GetCurThread();
772 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
778 * \fn void Threads_Dump(void)
779 * \brief Dumps a list of currently running threads
781 void Threads_Dump(void)
785 Log("--- Thread Dump ---");
786 Log("Active Threads: (%i reported)", giNumActiveThreads);
787 for(thread=gActiveThreads;thread;thread=thread->Next)
789 Log(" %i (%i) - %s (CPU %i)",
790 thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
791 if(thread->Status != THREAD_STAT_ACTIVE)
792 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
793 Log(" %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
794 Log(" KStack 0x%x", thread->KernelStack);
798 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
800 Log(" %i (%i) - %s (CPU %i)",
801 thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
802 Log(" State %i", thread->Status);
803 Log(" %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
804 Log(" KStack 0x%x", thread->KernelStack);
808 * \fn void Threads_Dump(void)
810 void Threads_DumpActive(void)
814 Log("Active Threads:");
815 for(thread=gActiveThreads;thread;thread=thread->Next)
817 Log(" %i (%i) - %s (CPU %i)",
818 thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
819 if(thread->Status != THREAD_STAT_ACTIVE)
820 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
821 Log(" %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
822 Log(" KStack 0x%x", thread->KernelStack);
827 * \brief Gets the next thread to run
828 * \param CPU Current CPU
829 * \param Last The thread the CPU was running
831 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
837 // If this CPU has the lock, we must let it complete
838 if( CPU_HAS_LOCK( &glThreadListLock ) )
842 SHORTLOCK( &glThreadListLock );
844 // Clear Delete Queue
845 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
846 while(gDeleteThreads)
848 thread = gDeleteThreads->Next;
849 if( IS_LOCKED(&gDeleteThreads->IsLocked) ) { // Only free if structure is unused
851 gDeleteThreads->Status = THREAD_STAT_DEAD;
853 if( IsHeap(gDeleteThreads->ThreadName) )
854 free(gDeleteThreads->ThreadName);
855 // Remove from global list
856 if( gDeleteThreads == gAllThreads )
857 gAllThreads = gDeleteThreads->GlobalNext;
859 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
860 free( gDeleteThreads );
862 gDeleteThreads = thread;
865 // No active threads, just take a nap
866 if(giNumActiveThreads == 0) {
867 SHORTREL( &glThreadListLock );
868 #if DEBUG_TRACE_TICKETS
869 Log("No active threads");
874 // Special case: 1 thread
875 if(giNumActiveThreads == 1) {
876 if( gActiveThreads->CurCPU == -1 )
877 gActiveThreads->CurCPU = CPU;
879 SHORTREL( &glThreadListLock );
881 if( gActiveThreads->CurCPU == CPU )
882 return gActiveThreads;
884 return NULL; // CPU has nothing to do
887 // Allow the old thread to be scheduled again
889 if( Last->Status == THREAD_STAT_ACTIVE ) {
890 giFreeTickets += Last->NumTickets;
891 #if DEBUG_TRACE_TICKETS
892 LogF(" CPU %i released %p (%i %s) into the pool (%i tickets in pool)\n",
893 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets);
896 #if DEBUG_TRACE_TICKETS
898 LogF(" CPU %i released %p (%s)->Status = %i (Released)\n",
899 CPU, Last, Last->ThreadName, Last->Status);
904 #if DEBUG_TRACE_TICKETS
905 //Threads_DumpActive();
910 for(thread = gActiveThreads; thread; thread = thread->Next) {
911 if(thread->CurCPU >= 0) continue;
912 if(thread->Status != THREAD_STAT_ACTIVE)
913 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
914 thread, thread->TID, thread->ThreadName, thread->Status);
915 if(thread->Next == thread) {
916 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
917 thread, thread->TID, thread->ThreadName, thread->Status);
919 number += thread->NumTickets;
921 if(number != giFreeTickets) {
922 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
923 giFreeTickets, number, CPU);
927 // No free tickets (all tasks delegated to cores)
928 if( giFreeTickets == 0 ) {
929 SHORTREL(&glThreadListLock);
933 // Get the ticket number
934 ticket = number = rand() % giFreeTickets;
936 // Find the next thread
937 for(thread=gActiveThreads;thread;thread=thread->Next)
939 if(thread->CurCPU >= 0) continue;
940 if(thread->NumTickets > number) break;
941 number -= thread->NumTickets;
947 for(thread=gActiveThreads;thread;thread=thread->Next) {
948 if(thread->CurCPU >= 0) continue;
949 number += thread->NumTickets;
951 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
952 giFreeTickets, number);
954 #if DEBUG_TRACE_TICKETS
955 LogF(" CPU%i giFreeTickets = %i\n", CPU, giFreeTickets);
958 // Make the new thread non-schedulable
959 giFreeTickets -= thread->NumTickets;
960 thread->CurCPU = CPU;
963 #if DEBUG_TRACE_TICKETS
964 LogF(" CPU%i giFreeTickets = %i, giving %p (%i %s CPU=%i)\n",
965 CPU, giFreeTickets, thread, thread->TID, thread->ThreadName, thread->CurCPU);
968 SHORTREL( &glThreadListLock );
974 * \fn void Threads_SegFault(tVAddr Addr)
975 * \brief Called when a Segment Fault occurs
977 void Threads_SegFault(tVAddr Addr)
979 Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
981 //Threads_Exit( 0, -1 );
985 * \brief Acquire a heavy mutex
986 * \param Mutex Mutex to acquire
988 * This type of mutex checks if the mutex is avaliable, and acquires it
989 * if it is. Otherwise, the current thread is added to the mutex's wait
990 * queue and the thread suspends. When the holder of the mutex completes,
991 * the oldest thread (top thread) on the queue is given the lock and
994 void Mutex_Acquire(tMutex *Mutex)
996 tThread *us = Proc_GetCurThread();
999 SHORTLOCK( &Mutex->Protector );
1001 //Log("Mutex_Acquire: (%p)", Mutex);
1003 // Check if the lock is already held
1004 if( Mutex->Owner ) {
1005 SHORTLOCK( &glThreadListLock );
1006 // - Remove from active list
1007 Threads_RemActive();
1008 // - Mark as sleeping
1009 us->Status = THREAD_STAT_OFFSLEEP;
1012 if(Mutex->LastWaiting) {
1013 Mutex->LastWaiting->Next = us;
1014 Mutex->LastWaiting = us;
1017 Mutex->Waiting = us;
1018 Mutex->LastWaiting = us;
1020 SHORTREL( &glThreadListLock );
1021 SHORTREL( &Mutex->Protector );
1022 while(us->Status == THREAD_STAT_OFFSLEEP) Threads_Yield();
1023 // We're only woken when we get the lock
1025 // Ooh, let's take it!
1028 SHORTREL( &Mutex->Protector );
1033 * \brief Release a held mutex
1034 * \param Mutex Mutex to release
1036 void Mutex_Release(tMutex *Mutex)
1038 SHORTLOCK( &Mutex->Protector );
1039 //Log("Mutex_Release: (%p)", Mutex);
1040 if( Mutex->Waiting ) {
1041 Mutex->Owner = Mutex->Waiting; // Set owner
1042 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1045 SHORTLOCK( &glThreadListLock );
1046 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1047 Threads_AddActive(Mutex->Owner);
1048 SHORTREL( &glThreadListLock );
1051 Mutex->Owner = NULL;
1053 SHORTREL( &Mutex->Protector );
1057 * \brief Is this mutex locked?
1058 * \param Mutex Mutex pointer
1060 int Mutex_IsLocked(tMutex *Mutex)
1062 return Mutex->Owner != NULL;
1066 EXPORT(Threads_GetUID);
1067 EXPORT(Mutex_Acquire);
1068 EXPORT(Mutex_Release);
1069 EXPORT(Mutex_IsLocked);