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
81 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
85 * \fn void Threads_Init(void)
86 * \brief Initialse the thread list
88 void Threads_Init(void)
92 // Create Initial Task
93 gActiveThreads = &gThreadZero;
94 gAllThreads = &gThreadZero;
95 //giFreeTickets = gThreadZero.NumTickets; // Not needed, as ThreadZero is scheduled
96 giNumActiveThreads = 1;
102 * \fn void Threads_SetName(char *NewName)
103 * \brief Sets the current thread's name
104 * \param NewName New name for the thread
105 * \return Boolean Failure
107 int Threads_SetName(char *NewName)
109 tThread *cur = Proc_GetCurThread();
110 char *oldname = cur->ThreadName;
112 // NOTE: There is a possibility of non-thread safety here
113 // A thread could read the current name pointer before it is zeroed
115 cur->ThreadName = NULL;
117 if( IsHeap(oldname) ) free( oldname );
119 cur->ThreadName = strdup(NewName);
124 * \fn char *Threads_GetName(int ID)
125 * \brief Gets a thread's name
126 * \param ID Thread ID (-1 indicates current thread)
127 * \return Pointer to name
128 * \retval NULL Failure
130 char *Threads_GetName(tTID ID)
133 return Proc_GetCurThread()->ThreadName;
135 return Threads_GetThread(ID)->ThreadName;
139 * \fn void Threads_SetTickets(tThread *Thread, int Num)
140 * \brief Sets the 'priority' of a task
141 * \param Thread Thread to update ticket count (NULL means current thread)
142 * \param Num New ticket count (must be >= 0, clipped to \a MAX_TICKETS)
144 void Threads_SetTickets(tThread *Thread, int Num)
146 // Get current thread
147 if(Thread == NULL) Thread = Proc_GetCurThread();
150 if(Num > MAX_TICKETS) Num = MAX_TICKETS;
152 // If this isn't the current thread, we need to lock
153 if( Thread != Proc_GetCurThread() ) {
154 SHORTLOCK( &glThreadListLock );
155 giFreeTickets -= Thread->NumTickets - Num;
156 Thread->NumTickets = Num;
157 #if DEBUG_TRACE_TICKETS
158 Log("Threads_SetTickets: new giFreeTickets = %i", giFreeTickets);
160 SHORTREL( &glThreadListLock );
163 Thread->NumTickets = Num;
167 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
168 * \brief Clone the TCB of the current thread
169 * \param Err Error pointer
170 * \param Flags Flags for something... (What is this for?)
172 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
176 cur = Proc_GetCurThread();
178 // Allocate and duplicate
179 new = malloc(sizeof(tThread));
184 memcpy(new, cur, sizeof(tThread));
188 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
189 new->Status = THREAD_STAT_PREINIT;
193 new->TID = giNextTID++;
197 new->ThreadName = strdup(cur->ThreadName);
199 // Set Thread Group ID (PID)
201 new->TGID = new->TID;
203 new->TGID = cur->TGID;
205 // Messages are not inherited
206 new->Messages = NULL;
207 new->LastMessage = NULL;
210 new->Remaining = new->Quantum = cur->Quantum;
211 new->NumTickets = cur->NumTickets;
213 // Set Signal Handlers
214 new->CurFaultNum = 0;
215 new->FaultHandler = cur->FaultHandler;
217 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
219 switch(cCONFIG_TYPES[i])
222 new->Config[i] = cur->Config[i];
226 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
233 // Maintain a global list of threads
234 SHORTLOCK( &glThreadListLock );
235 new->GlobalPrev = NULL; // Protect against bugs
236 new->GlobalNext = gAllThreads;
238 SHORTREL( &glThreadListLock );
244 * \brief Get a configuration pointer from the Per-Thread data area
245 * \param ID Config slot ID
246 * \return Pointer at ID
248 Uint *Threads_GetCfgPtr(int ID)
250 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
251 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
255 return &Proc_GetCurThread()->Config[ID];
259 * \brief Wait for a task to change state
260 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
261 * \param Status Thread return status
262 * \return TID of child that changed state
264 tTID Threads_WaitTID(int TID, int *Status)
268 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
272 // Any peer/child thread
274 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
280 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
286 tThread *t = Threads_GetThread(TID);
287 int initStatus = t->Status;
290 // Wait for the thread to die!
291 if(initStatus != THREAD_STAT_ZOMBIE) {
292 // TODO: Handle child also being suspended if wanted
293 while(t->Status != THREAD_STAT_ZOMBIE) {
295 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
296 Threads_GetTID(), t->TID, t->Status);
301 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
302 Threads_GetTID(), t->TID, t->Status);
306 case THREAD_STAT_ZOMBIE:
308 t->Status = THREAD_STAT_DEAD;
309 // TODO: Child return value?
310 if(Status) *Status = t->RetStatus;
311 // add to delete queue
312 Threads_AddToDelete( t );
315 if(Status) *Status = -1;
325 * \brief Gets a thread given its TID
326 * \param TID Thread ID
327 * \return Thread pointer
329 tThread *Threads_GetThread(Uint TID)
333 // Search global list
334 for(thread = gAllThreads;
336 thread = thread->GlobalNext)
338 if(thread->TID == TID)
342 Log("Unable to find TID %i on main list\n", TID);
348 * \brief Adds a thread to the delete queue
349 * \param Thread Thread to delete
351 void Threads_AddToDelete(tThread *Thread)
353 // Add to delete queue
354 // TODO: Is locking needed?
356 Thread->Next = gDeleteThreads;
357 gDeleteThreads = Thread;
360 gDeleteThreads = Thread;
365 * \brief Gets the previous entry in a thead linked list
366 * \param List Pointer to the list head
367 * \param Thread Thread to find
368 * \return Thread before \a Thread on \a List
369 * \note This uses a massive hack of assuming that the first field in the
370 * structure is the .Next pointer. By doing this, we can return \a List
371 * as a (tThread*) and simplify other code.
373 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread)
377 if(*List == Thread) {
378 return (tThread*)List;
383 ret->Next && ret->Next != Thread;
386 // Error if the thread is not on the list
387 if(!ret->Next || ret->Next != Thread) {
395 * \brief Exit the current process (or another?)
396 * \param TID Thread ID to kill
397 * \param Status Exit status
399 void Threads_Exit(int TID, int Status)
402 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
404 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
406 // Halt forever, just in case
411 * \fn void Threads_Kill(tThread *Thread, int Status)
412 * \brief Kill a thread
413 * \param Thread Thread to kill
414 * \param Status Status code to return to the parent
416 void Threads_Kill(tThread *Thread, int Status)
421 // TODO: Kill all children
425 // TODO: I should keep a .Parent pointer, and a .Children list
426 for(child = gActiveThreads;
430 if(child->PTID == Thread->TID)
431 Threads_Kill(child, -1);
436 ///\note Double lock is needed due to overlap of lock areas
438 // Lock thread (stop us recieving messages)
439 SHORTLOCK( &Thread->IsLocked );
441 // Clear Message Queue
442 while( Thread->Messages )
444 msg = Thread->Messages->Next;
445 free( Thread->Messages );
446 Thread->Messages = msg;
450 SHORTLOCK( &glThreadListLock );
452 // Get previous thread on list
453 prev = Threads_int_GetPrev( &gActiveThreads, Thread );
455 Warning("Proc_Exit - Current thread is not on the active queue");
456 SHORTREL( &glThreadListLock );
457 SHORTREL( &Thread->IsLocked );
461 // Ensure that we are not rescheduled
462 Thread->Remaining = 0; // Clear Remaining Quantum
463 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
464 prev->Next = Thread->Next; // Remove from active
466 // Update bookkeeping
467 giNumActiveThreads --;
468 if( Thread != Proc_GetCurThread() )
469 giFreeTickets -= Thread->NumTickets;
472 Thread->RetStatus = Status;
474 // Don't Zombie if we are being killed because our parent is
477 Thread->Status = THREAD_STAT_DEAD;
478 Threads_AddToDelete( Thread );
480 Thread->Status = THREAD_STAT_ZOMBIE;
482 Threads_Wake( Thread->Parent );
485 Log("Thread %i went *hurk* (%i)", Thread->TID, Thread->Status);
488 SHORTREL( &glThreadListLock );
489 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
499 * \brief Yield remainder of the current thread's timeslice
501 void Threads_Yield(void)
503 tThread *thread = Proc_GetCurThread();
504 thread->Remaining = 0;
505 //while(thread->Remaining == 0)
510 * \fn void Threads_Sleep(void)
511 * \brief Take the current process off the run queue
513 void Threads_Sleep(void)
515 tThread *cur = Proc_GetCurThread();
518 SHORTLOCK( &glThreadListLock );
520 // Don't sleep if there is a message waiting
521 if( cur->Messages ) {
522 SHORTREL( &glThreadListLock );
526 // Remove us from running queue
528 // Mark thread as sleeping
529 cur->Status = THREAD_STAT_SLEEPING;
531 // Add to Sleeping List (at the top)
532 cur->Next = gSleepingThreads;
533 gSleepingThreads = cur;
536 #if DEBUG_TRACE_STATE
537 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
541 SHORTREL( &glThreadListLock );
543 while(cur->Status != THREAD_STAT_ACTIVE) HALT();
548 * \fn int Threads_Wake( tThread *Thread )
549 * \brief Wakes a sleeping/waiting thread up
550 * \param Thread Thread to wake
551 * \return Boolean Failure (Returns ERRNO)
552 * \warning This should ONLY be called with task switches disabled
554 int Threads_Wake(tThread *Thread)
561 switch(Thread->Status)
563 case THREAD_STAT_ACTIVE:
564 Log("Thread_Wake: Waking awake thread (%i)", Thread->TID);
567 case THREAD_STAT_SLEEPING:
568 SHORTLOCK( &glThreadListLock );
569 // Remove from sleeping queue
570 prev = Threads_int_GetPrev(&gSleepingThreads, Thread);
571 prev->Next = Thread->Next;
573 Threads_AddActive( Thread );
575 #if DEBUG_TRACE_STATE
576 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
578 SHORTREL( &glThreadListLock );
581 case THREAD_STAT_WAITING:
582 Warning("Thread_Wake - Waiting threads are not currently supported");
585 case THREAD_STAT_DEAD:
586 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
590 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
596 * \brief Wake a thread given the TID
597 * \param TID Thread ID to wake
598 * \return Boolean Faulure (errno)
600 int Threads_WakeTID(tTID TID)
602 tThread *thread = Threads_GetThread(TID);
606 ret = Threads_Wake( thread );
607 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
612 * \brief Adds a thread to the active queue
614 void Threads_AddActive(tThread *Thread)
616 SHORTLOCK( &glThreadListLock );
621 for( t = gActiveThreads; t; t = t->Next )
624 Panic("Threads_AddActive: Attempting a double add of TID %i (0x%x)",
625 Thread->TID, __builtin_return_address(0));
628 if(t->Status != THREAD_STAT_ACTIVE) {
629 Panic("Threads_AddActive: TID %i status != THREAD_STAT_ACTIVE",
636 // Add to active list
637 Thread->Next = gActiveThreads;
638 gActiveThreads = Thread;
640 Thread->Status = THREAD_STAT_ACTIVE;
643 // Update bookkeeping
644 giNumActiveThreads ++;
645 giFreeTickets += Thread->NumTickets;
647 #if DEBUG_TRACE_TICKETS
648 Log("Threads_AddActive: %p %i (%s) added, new giFreeTickets = %i",
649 Thread, Thread->TID, Thread->ThreadName, giFreeTickets);
651 SHORTREL( &glThreadListLock );
655 * \brief Removes the current thread from the active queue
656 * \warning This should ONLY be called with task switches disabled
657 * \return Current thread pointer
659 tThread *Threads_RemActive(void)
661 tThread *ret = Proc_GetCurThread();
664 SHORTLOCK( &glThreadListLock );
666 prev = Threads_int_GetPrev(&gActiveThreads, ret);
668 SHORTREL( &glThreadListLock );
675 prev->Next = ret->Next;
676 giNumActiveThreads --;
677 // no need to decrement tickets, scheduler did it for us
679 #if DEBUG_TRACE_TICKETS
680 Log("Threads_RemActive: %p %i (%s) removed, giFreeTickets = %i",
681 ret, ret->TID, ret->ThreadName, giFreeTickets);
684 SHORTREL( &glThreadListLock );
690 * \fn void Threads_SetFaultHandler(Uint Handler)
691 * \brief Sets the signal handler for a signal
693 void Threads_SetFaultHandler(Uint Handler)
695 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
696 Proc_GetCurThread()->FaultHandler = Handler;
700 * \fn void Threads_Fault(int Num)
701 * \brief Calls a fault handler
703 void Threads_Fault(int Num)
705 tThread *thread = Proc_GetCurThread();
707 Log_Log("Threads", "Threads_Fault: thread = %p", thread);
711 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
713 switch(thread->FaultHandler)
716 Threads_Kill(thread, -1);
719 case 1: // Dump Core?
720 Threads_Kill(thread, -1);
725 // Double Fault? Oh, F**k
726 if(thread->CurFaultNum != 0) {
727 Threads_Kill(thread, -1); // For now, just kill
731 thread->CurFaultNum = Num;
733 Proc_CallFaultHandler(thread);
736 // --- Process Structure Access Functions ---
737 tPID Threads_GetPID(void)
739 return Proc_GetCurThread()->TGID;
741 tTID Threads_GetTID(void)
743 return Proc_GetCurThread()->TID;
745 tUID Threads_GetUID(void)
747 return Proc_GetCurThread()->UID;
749 tGID Threads_GetGID(void)
751 return Proc_GetCurThread()->GID;
754 int Threads_SetUID(Uint *Errno, tUID ID)
756 tThread *t = Proc_GetCurThread();
761 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
766 int Threads_SetGID(Uint *Errno, tGID ID)
768 tThread *t = Proc_GetCurThread();
773 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
779 * \fn void Threads_Dump(void)
780 * \brief Dumps a list of currently running threads
782 void Threads_Dump(void)
786 Log("--- Thread Dump ---");
787 Log("Active Threads: (%i reported)", giNumActiveThreads);
788 for(thread=gActiveThreads;thread;thread=thread->Next)
790 Log(" %i (%i) - %s (CPU %i)",
791 thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
792 if(thread->Status != THREAD_STAT_ACTIVE)
793 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
794 Log(" %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
795 Log(" KStack 0x%x", thread->KernelStack);
799 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
801 Log(" %i (%i) - %s (CPU %i)",
802 thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
803 Log(" State %i", thread->Status);
804 Log(" %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
805 Log(" KStack 0x%x", thread->KernelStack);
809 * \fn void Threads_Dump(void)
811 void Threads_DumpActive(void)
815 Log("Active Threads:");
816 for(thread=gActiveThreads;thread;thread=thread->Next)
818 Log(" %i (%i) - %s (CPU %i)",
819 thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
820 if(thread->Status != THREAD_STAT_ACTIVE)
821 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
822 Log(" %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
823 Log(" KStack 0x%x", thread->KernelStack);
828 * \brief Gets the next thread to run
829 * \param CPU Current CPU
830 * \param Last The thread the CPU was running
832 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
838 // If this CPU has the lock, we must let it complete
839 if( CPU_HAS_LOCK( &glThreadListLock ) )
842 // Same if the current CPU has any lock
843 if( gaThreads_NoTaskSwitch[CPU] )
848 SHORTLOCK( &glThreadListLock );
850 // Clear Delete Queue
851 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
852 while(gDeleteThreads)
854 thread = gDeleteThreads->Next;
855 if( IS_LOCKED(&gDeleteThreads->IsLocked) ) { // Only free if structure is unused
857 gDeleteThreads->Status = THREAD_STAT_DEAD;
859 if( IsHeap(gDeleteThreads->ThreadName) )
860 free(gDeleteThreads->ThreadName);
861 // Remove from global list
862 if( gDeleteThreads == gAllThreads )
863 gAllThreads = gDeleteThreads->GlobalNext;
865 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
866 free( gDeleteThreads );
868 gDeleteThreads = thread;
871 // No active threads, just take a nap
872 if(giNumActiveThreads == 0) {
873 SHORTREL( &glThreadListLock );
874 #if DEBUG_TRACE_TICKETS
875 Log("No active threads");
880 // Special case: 1 thread
881 if(giNumActiveThreads == 1) {
882 if( gActiveThreads->CurCPU == -1 )
883 gActiveThreads->CurCPU = CPU;
885 SHORTREL( &glThreadListLock );
887 if( gActiveThreads->CurCPU == CPU )
888 return gActiveThreads;
890 return NULL; // CPU has nothing to do
893 // Allow the old thread to be scheduled again
895 if( Last->Status == THREAD_STAT_ACTIVE ) {
896 giFreeTickets += Last->NumTickets;
897 #if DEBUG_TRACE_TICKETS
898 LogF(" CPU %i released %p (%i %s) into the pool (%i tickets in pool)\n",
899 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets);
902 #if DEBUG_TRACE_TICKETS
904 LogF(" CPU %i released %p (%s)->Status = %i (Released)\n",
905 CPU, Last, Last->ThreadName, Last->Status);
910 #if DEBUG_TRACE_TICKETS
911 //Threads_DumpActive();
916 for(thread = gActiveThreads; thread; thread = thread->Next) {
917 if(thread->CurCPU >= 0) continue;
918 if(thread->Status != THREAD_STAT_ACTIVE)
919 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
920 thread, thread->TID, thread->ThreadName, thread->Status);
921 if(thread->Next == thread) {
922 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
923 thread, thread->TID, thread->ThreadName, thread->Status);
925 number += thread->NumTickets;
927 if(number != giFreeTickets) {
928 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
929 giFreeTickets, number, CPU);
933 // No free tickets (all tasks delegated to cores)
934 if( giFreeTickets == 0 ) {
935 SHORTREL(&glThreadListLock);
939 // Get the ticket number
940 ticket = number = rand() % giFreeTickets;
942 // Find the next thread
943 for(thread=gActiveThreads;thread;thread=thread->Next)
945 if(thread->CurCPU >= 0) continue;
946 if(thread->NumTickets > number) break;
947 number -= thread->NumTickets;
953 for(thread=gActiveThreads;thread;thread=thread->Next) {
954 if(thread->CurCPU >= 0) continue;
955 number += thread->NumTickets;
957 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
958 giFreeTickets, number);
960 #if DEBUG_TRACE_TICKETS
961 LogF(" CPU%i giFreeTickets = %i\n", CPU, giFreeTickets);
964 // Make the new thread non-schedulable
965 giFreeTickets -= thread->NumTickets;
966 thread->CurCPU = CPU;
969 #if DEBUG_TRACE_TICKETS
970 LogF(" CPU%i giFreeTickets = %i, giving %p (%i %s CPU=%i)\n",
971 CPU, giFreeTickets, thread, thread->TID, thread->ThreadName, thread->CurCPU);
974 SHORTREL( &glThreadListLock );
980 * \fn void Threads_SegFault(tVAddr Addr)
981 * \brief Called when a Segment Fault occurs
983 void Threads_SegFault(tVAddr Addr)
985 Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
987 //Threads_Exit( 0, -1 );
991 * \brief Acquire a heavy mutex
992 * \param Mutex Mutex to acquire
994 * This type of mutex checks if the mutex is avaliable, and acquires it
995 * if it is. Otherwise, the current thread is added to the mutex's wait
996 * queue and the thread suspends. When the holder of the mutex completes,
997 * the oldest thread (top thread) on the queue is given the lock and
1000 void Mutex_Acquire(tMutex *Mutex)
1002 tThread *us = Proc_GetCurThread();
1005 SHORTLOCK( &Mutex->Protector );
1007 //Log("Mutex_Acquire: (%p)", Mutex);
1009 // Check if the lock is already held
1010 if( Mutex->Owner ) {
1011 SHORTLOCK( &glThreadListLock );
1012 // - Remove from active list
1013 Threads_RemActive();
1014 // - Mark as sleeping
1015 us->Status = THREAD_STAT_OFFSLEEP;
1018 if(Mutex->LastWaiting) {
1019 Mutex->LastWaiting->Next = us;
1020 Mutex->LastWaiting = us;
1023 Mutex->Waiting = us;
1024 Mutex->LastWaiting = us;
1026 SHORTREL( &glThreadListLock );
1027 SHORTREL( &Mutex->Protector );
1028 while(us->Status == THREAD_STAT_OFFSLEEP) Threads_Yield();
1029 // We're only woken when we get the lock
1031 // Ooh, let's take it!
1034 SHORTREL( &Mutex->Protector );
1039 * \brief Release a held mutex
1040 * \param Mutex Mutex to release
1042 void Mutex_Release(tMutex *Mutex)
1044 SHORTLOCK( &Mutex->Protector );
1045 //Log("Mutex_Release: (%p)", Mutex);
1046 if( Mutex->Waiting ) {
1047 Mutex->Owner = Mutex->Waiting; // Set owner
1048 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1051 SHORTLOCK( &glThreadListLock );
1052 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1053 Threads_AddActive(Mutex->Owner);
1054 SHORTREL( &glThreadListLock );
1057 Mutex->Owner = NULL;
1059 SHORTREL( &Mutex->Protector );
1063 * \brief Is this mutex locked?
1064 * \param Mutex Mutex pointer
1066 int Mutex_IsLocked(tMutex *Mutex)
1068 return Mutex->Owner != NULL;
1072 EXPORT(Threads_GetUID);
1073 EXPORT(Mutex_Acquire);
1074 EXPORT(Mutex_Release);
1075 EXPORT(Mutex_IsLocked);