4 * - Common Thread Control
11 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
12 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
16 #define SCHED_LOTTERY 1 // Lottery scheduler
17 #define SCHED_RR_SIM 2 // Single Queue Round Robin
18 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
20 #define SCHEDULER_TYPE SCHED_LOTTERY
23 #define DEFAULT_QUANTUM 10
24 #define DEFAULT_PRIORITY 5
25 #define MIN_PRIORITY 10
26 const enum eConfigTypes cCONFIG_TYPES[] = {
27 CFGT_HEAPSTR, // e.g. CFG_VFS_CWD
28 CFGT_INT, // e.g. CFG_VFS_MAXFILES
33 extern void ArchThreads_Init(void);
34 extern void Proc_Start(void);
35 extern tThread *Proc_GetCurThread(void);
36 extern int Proc_Clone(Uint *Err, Uint Flags);
37 extern void Proc_CallFaultHandler(tThread *Thread);
40 void Threads_Init(void);
41 int Threads_SetName(char *NewName);
42 char *Threads_GetName(int ID);
43 void Threads_SetPriority(tThread *Thread, int Pri);
44 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
45 int Threads_WaitTID(int TID, int *status);
46 tThread *Threads_GetThread(Uint TID);
47 void Threads_AddToDelete(tThread *Thread);
48 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread);
49 void Threads_Exit(int TID, int Status);
50 void Threads_Kill(tThread *Thread, int Status);
51 void Threads_Yield(void);
52 void Threads_Sleep(void);
53 int Threads_Wake(tThread *Thread);
54 void Threads_AddActive(tThread *Thread);
55 tThread *Threads_RemActive(void);
56 int Threads_GetPID(void);
57 int Threads_GetTID(void);
58 tUID Threads_GetUID(void);
59 int Threads_SetUID(Uint *Errno, tUID ID);
60 tGID Threads_GetGID(void);
61 int Threads_SetGID(Uint *Errno, tUID ID);
62 void Threads_Dump(void);
63 void Threads_DumpActive(void);
64 void Mutex_Acquire(tMutex *Mutex);
65 void Mutex_Release(tMutex *Mutex);
66 int Mutex_IsLocked(tMutex *Mutex);
70 // Only used for the core kernel
71 tThread gThreadZero = {
72 Status: THREAD_STAT_ACTIVE, // Status
73 ThreadName: "ThreadZero", // Name
74 Quantum: DEFAULT_QUANTUM, // Default Quantum
75 Remaining: DEFAULT_QUANTUM, // Current Quantum
76 Priority: DEFAULT_PRIORITY // Number of tickets
80 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
81 // --- Current State ---
82 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
83 volatile Uint giNextTID = 1; // Next TID to allocate
84 // --- Thread Lists ---
85 tThread *gAllThreads = NULL; // All allocated threads
86 tThread *gSleepingThreads = NULL; // Sleeping Threads
87 tThread *gDeleteThreads = NULL; // Threads to delete
88 int giNumCPUs = 1; // Number of CPUs
89 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
90 // --- Scheduler Types ---
91 #if SCHEDULER_TYPE == SCHED_LOTTERY
92 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
93 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
94 tThread *gActiveThreads = NULL; // Currently Running Threads
95 #elif SCHEDULER_TYPE == SCHED_RR_SIM
96 tThread *gActiveThreads = NULL; // Currently Running Threads
97 #elif SCHEDULER_TYPE == SCHED_RR_PRI
98 tThread *gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
100 # error "Unkown scheduler type"
105 * \fn void Threads_Init(void)
106 * \brief Initialse the thread list
108 void Threads_Init(void)
112 // Create Initial Task
113 #if SCHEDULER_TYPE == SCHED_RR_PRI
114 gaActiveThreads[gThreadZero.Priority] = &gThreadZero;
116 gActiveThreads = &gThreadZero;
119 gAllThreads = &gThreadZero;
120 giNumActiveThreads = 1;
126 * \fn void Threads_SetName(char *NewName)
127 * \brief Sets the current thread's name
128 * \param NewName New name for the thread
129 * \return Boolean Failure
131 int Threads_SetName(char *NewName)
133 tThread *cur = Proc_GetCurThread();
134 char *oldname = cur->ThreadName;
136 // NOTE: There is a possibility of non-thread safety here
137 // A thread could read the current name pointer before it is zeroed
139 cur->ThreadName = NULL;
141 if( IsHeap(oldname) ) free( oldname );
143 cur->ThreadName = strdup(NewName);
148 * \fn char *Threads_GetName(int ID)
149 * \brief Gets a thread's name
150 * \param ID Thread ID (-1 indicates current thread)
151 * \return Pointer to name
152 * \retval NULL Failure
154 char *Threads_GetName(tTID ID)
157 return Proc_GetCurThread()->ThreadName;
159 return Threads_GetThread(ID)->ThreadName;
163 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
164 * \brief Sets the priority of a task
165 * \param Thread Thread to update ticket count (NULL means current thread)
166 * \param Pri New priority
168 void Threads_SetPriority(tThread *Thread, int Pri)
170 // Get current thread
171 if(Thread == NULL) Thread = Proc_GetCurThread();
173 // - If < 0, set to lowest priority
174 if(Pri < 0) Pri = MIN_PRIORITY;
175 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
177 // Do we actually have to do anything?
178 if( Pri == Thread->Priority ) return;
180 #if SCHEDULER_TYPE == SCHED_RR_PRI
181 SHORTLOCK( &glThreadListLock );
182 // Remove from old priority
183 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
185 Thread->Next = gaActiveThreads[Pri];
186 gaActiveThreads[Pri] = Thread;
187 Thread->Priority = Pri;
188 SHORTREL( &glThreadListLock );
190 // If this isn't the current thread, we need to lock
191 if( Thread != Proc_GetCurThread() )
193 SHORTLOCK( &glThreadListLock );
195 #if SCHEDULER_TYPE == SCHED_LOTTERY
196 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
197 # if DEBUG_TRACE_TICKETS
198 Log("Threads_SetTickets: new giFreeTickets = %i", giFreeTickets);
201 Thread->Priority = Pri;
202 SHORTREL( &glThreadListLock );
205 Thread->Priority = Pri;
210 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
211 * \brief Clone the TCB of the current thread
212 * \param Err Error pointer
213 * \param Flags Flags for something... (What is this for?)
215 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
219 cur = Proc_GetCurThread();
221 // Allocate and duplicate
222 new = malloc(sizeof(tThread));
227 memcpy(new, cur, sizeof(tThread));
231 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
232 new->Status = THREAD_STAT_PREINIT;
236 new->TID = giNextTID++;
240 new->ThreadName = strdup(cur->ThreadName);
242 // Set Thread Group ID (PID)
244 new->TGID = new->TID;
246 new->TGID = cur->TGID;
248 // Messages are not inherited
249 new->Messages = NULL;
250 new->LastMessage = NULL;
253 new->Remaining = new->Quantum = cur->Quantum;
254 new->Priority = cur->Priority;
256 // Set Signal Handlers
257 new->CurFaultNum = 0;
258 new->FaultHandler = cur->FaultHandler;
260 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
262 switch(cCONFIG_TYPES[i])
265 new->Config[i] = cur->Config[i];
269 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
276 // Maintain a global list of threads
277 SHORTLOCK( &glThreadListLock );
278 new->GlobalPrev = NULL; // Protect against bugs
279 new->GlobalNext = gAllThreads;
281 SHORTREL( &glThreadListLock );
287 * \brief Get a configuration pointer from the Per-Thread data area
288 * \param ID Config slot ID
289 * \return Pointer at ID
291 Uint *Threads_GetCfgPtr(int ID)
293 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
294 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
298 return &Proc_GetCurThread()->Config[ID];
302 * \brief Wait for a task to change state
303 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
304 * \param Status Thread return status
305 * \return TID of child that changed state
307 tTID Threads_WaitTID(int TID, int *Status)
311 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
315 // Any peer/child thread
317 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
323 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
329 tThread *t = Threads_GetThread(TID);
330 int initStatus = t->Status;
333 // Wait for the thread to die!
334 if(initStatus != THREAD_STAT_ZOMBIE) {
335 // TODO: Handle child also being suspended if wanted
336 while(t->Status != THREAD_STAT_ZOMBIE) {
338 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
339 Threads_GetTID(), t->TID, t->Status);
344 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
345 Threads_GetTID(), t->TID, t->Status);
349 case THREAD_STAT_ZOMBIE:
351 t->Status = THREAD_STAT_DEAD;
352 // TODO: Child return value?
353 if(Status) *Status = t->RetStatus;
354 // add to delete queue
355 Threads_AddToDelete( t );
358 if(Status) *Status = -1;
368 * \brief Gets a thread given its TID
369 * \param TID Thread ID
370 * \return Thread pointer
372 tThread *Threads_GetThread(Uint TID)
376 // Search global list
377 for(thread = gAllThreads;
379 thread = thread->GlobalNext)
381 if(thread->TID == TID)
385 Log("Unable to find TID %i on main list\n", TID);
391 * \brief Adds a thread to the delete queue
392 * \param Thread Thread to delete
394 void Threads_AddToDelete(tThread *Thread)
396 // Add to delete queue
397 // TODO: Is locking needed?
399 Thread->Next = gDeleteThreads;
400 gDeleteThreads = Thread;
403 gDeleteThreads = Thread;
408 * \brief Deletes an entry from a list
409 * \param List Pointer to the list head
410 * \param Thread Thread to find
413 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
415 tThread *ret, *prev = NULL;
418 ret && ret != Thread;
419 prev = ret, ret = ret->Next
422 // Is the thread on the list
424 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
429 *List = Thread->Next;
430 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
433 prev->Next = Thread->Next;
434 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
441 * \brief Exit the current process (or another?)
442 * \param TID Thread ID to kill
443 * \param Status Exit status
445 void Threads_Exit(int TID, int Status)
448 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
450 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
452 // Halt forever, just in case
457 * \fn void Threads_Kill(tThread *Thread, int Status)
458 * \brief Kill a thread
459 * \param Thread Thread to kill
460 * \param Status Status code to return to the parent
462 void Threads_Kill(tThread *Thread, int Status)
466 // TODO: Kill all children
470 // TODO: I should keep a .Parent pointer, and a .Children list
471 for(child = gActiveThreads;
475 if(child->PTID == Thread->TID)
476 Threads_Kill(child, -1);
481 ///\note Double lock is needed due to overlap of lock areas
483 // Lock thread (stop us recieving messages)
484 SHORTLOCK( &Thread->IsLocked );
486 // Clear Message Queue
487 while( Thread->Messages )
489 msg = Thread->Messages->Next;
490 free( Thread->Messages );
491 Thread->Messages = msg;
495 SHORTLOCK( &glThreadListLock );
497 // Delete from active list
498 #if SCHEDULER_TYPE == SCHED_RR_PRI
499 if( !Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
501 if( !Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
504 Warning("Proc_Exit - Current thread is not on the active queue");
505 SHORTREL( &glThreadListLock );
506 SHORTREL( &Thread->IsLocked );
510 // Ensure that we are not rescheduled
511 Thread->Remaining = 0; // Clear Remaining Quantum
512 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
514 // Update bookkeeping
515 giNumActiveThreads --;
516 #if SCHEDULER_TYPE == SCHED_LOTTERY
517 if( Thread != Proc_GetCurThread() )
518 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
522 Thread->RetStatus = Status;
524 // Don't Zombie if we are being killed because our parent is
527 Thread->Status = THREAD_STAT_DEAD;
528 Threads_AddToDelete( Thread );
530 Thread->Status = THREAD_STAT_ZOMBIE;
532 Threads_Wake( Thread->Parent );
535 Log("Thread %i went *hurk* (%i)", Thread->TID, Thread->Status);
538 SHORTREL( &glThreadListLock );
539 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
549 * \brief Yield remainder of the current thread's timeslice
551 void Threads_Yield(void)
553 tThread *thread = Proc_GetCurThread();
554 thread->Remaining = 0;
555 //while(thread->Remaining == 0)
560 * \fn void Threads_Sleep(void)
561 * \brief Take the current process off the run queue
563 void Threads_Sleep(void)
565 tThread *cur = Proc_GetCurThread();
568 SHORTLOCK( &glThreadListLock );
570 // Don't sleep if there is a message waiting
571 if( cur->Messages ) {
572 SHORTREL( &glThreadListLock );
576 // Remove us from running queue
578 // Mark thread as sleeping
579 cur->Status = THREAD_STAT_SLEEPING;
581 // Add to Sleeping List (at the top)
582 cur->Next = gSleepingThreads;
583 gSleepingThreads = cur;
586 #if DEBUG_TRACE_STATE
587 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
591 SHORTREL( &glThreadListLock );
593 while(cur->Status != THREAD_STAT_ACTIVE) HALT();
598 * \fn int Threads_Wake( tThread *Thread )
599 * \brief Wakes a sleeping/waiting thread up
600 * \param Thread Thread to wake
601 * \return Boolean Failure (Returns ERRNO)
602 * \warning This should ONLY be called with task switches disabled
604 int Threads_Wake(tThread *Thread)
609 switch(Thread->Status)
611 case THREAD_STAT_ACTIVE:
612 Log("Thread_Wake: Waking awake thread (%i)", Thread->TID);
615 case THREAD_STAT_SLEEPING:
616 SHORTLOCK( &glThreadListLock );
617 // Remove from sleeping queue
618 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
620 Threads_AddActive( Thread );
622 #if DEBUG_TRACE_STATE
623 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
625 SHORTREL( &glThreadListLock );
628 case THREAD_STAT_WAITING:
629 Warning("Thread_Wake - Waiting threads are not currently supported");
632 case THREAD_STAT_DEAD:
633 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
637 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
643 * \brief Wake a thread given the TID
644 * \param TID Thread ID to wake
645 * \return Boolean Faulure (errno)
647 int Threads_WakeTID(tTID TID)
649 tThread *thread = Threads_GetThread(TID);
653 ret = Threads_Wake( thread );
654 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
659 * \brief Adds a thread to the active queue
661 void Threads_AddActive(tThread *Thread)
663 SHORTLOCK( &glThreadListLock );
666 Thread->Status = THREAD_STAT_ACTIVE;
668 // Add to active list
669 #if SCHEDULER_TYPE == SCHED_RR_PRI
670 Thread->Next = gaActiveThreads[Thread->Priority];
671 gaActiveThreads[Thread->Priority] = Thread;
673 Thread->Next = gActiveThreads;
674 gActiveThreads = Thread;
677 // Update bookkeeping
678 giNumActiveThreads ++;
680 #if SCHEDULER_TYPE == SCHED_LOTTERY
681 giFreeTickets += caiTICKET_COUNTS[ Thread->Priority ];
682 # if DEBUG_TRACE_TICKETS
683 Log("Threads_AddActive: %p %i (%s) added, new giFreeTickets = %i",
684 Thread, Thread->TID, Thread->ThreadName, giFreeTickets);
688 SHORTREL( &glThreadListLock );
692 * \brief Removes the current thread from the active queue
693 * \warning This should ONLY be called with task switches disabled
694 * \return Current thread pointer
696 tThread *Threads_RemActive(void)
698 tThread *ret = Proc_GetCurThread();
700 SHORTLOCK( &glThreadListLock );
702 // Delete from active queue
703 #if SCHEDULER_TYPE == SCHED_RR_PRI
704 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
706 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
709 SHORTREL( &glThreadListLock );
717 giNumActiveThreads --;
718 // no need to decrement tickets, scheduler did it for us
720 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
721 Log("Threads_RemActive: %p %i (%s) removed, giFreeTickets = %i",
722 ret, ret->TID, ret->ThreadName, giFreeTickets);
725 SHORTREL( &glThreadListLock );
731 * \fn void Threads_SetFaultHandler(Uint Handler)
732 * \brief Sets the signal handler for a signal
734 void Threads_SetFaultHandler(Uint Handler)
736 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
737 Proc_GetCurThread()->FaultHandler = Handler;
741 * \fn void Threads_Fault(int Num)
742 * \brief Calls a fault handler
744 void Threads_Fault(int Num)
746 tThread *thread = Proc_GetCurThread();
748 Log_Log("Threads", "Threads_Fault: thread = %p", thread);
752 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
754 switch(thread->FaultHandler)
757 Threads_Kill(thread, -1);
760 case 1: // Dump Core?
761 Threads_Kill(thread, -1);
766 // Double Fault? Oh, F**k
767 if(thread->CurFaultNum != 0) {
768 Threads_Kill(thread, -1); // For now, just kill
772 thread->CurFaultNum = Num;
774 Proc_CallFaultHandler(thread);
777 // --- Process Structure Access Functions ---
778 tPID Threads_GetPID(void)
780 return Proc_GetCurThread()->TGID;
782 tTID Threads_GetTID(void)
784 return Proc_GetCurThread()->TID;
786 tUID Threads_GetUID(void)
788 return Proc_GetCurThread()->UID;
790 tGID Threads_GetGID(void)
792 return Proc_GetCurThread()->GID;
795 int Threads_SetUID(Uint *Errno, tUID ID)
797 tThread *t = Proc_GetCurThread();
802 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
807 int Threads_SetGID(Uint *Errno, tGID ID)
809 tThread *t = Proc_GetCurThread();
814 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
820 * \fn void Threads_Dump(void)
822 void Threads_DumpActive(void)
825 #if SCHEDULER_TYPE == SCHED_RR_PRI
829 Log("Active Threads: (%i reported)", giNumActiveThreads);
831 #if SCHEDULER_TYPE == SCHED_RR_PRI
832 for( i = 0; i < MIN_PRIORITY+1; i++ )
834 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
836 for(thread=gActiveThreads;thread;thread=thread->Next)
839 Log(" %i (%i) - %s (CPU %i)",
840 thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
841 if(thread->Status != THREAD_STAT_ACTIVE)
842 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
843 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
844 Log(" KStack 0x%x", thread->KernelStack);
847 #if SCHEDULER_TYPE == SCHED_RR_PRI
853 * \fn void Threads_Dump(void)
854 * \brief Dumps a list of currently running threads
856 void Threads_Dump(void)
860 Log("--- Thread Dump ---");
861 Threads_DumpActive();
864 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
866 Log(" %i (%i) - %s (CPU %i)",
867 thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
868 Log(" State %i", thread->Status);
869 switch(thread->Status)
871 case THREAD_STAT_MUTEXSLEEP:
872 Log(" Mutex Pointer: %p", thread->WaitPointer);
874 case THREAD_STAT_ZOMBIE:
875 Log(" Return Status: %i", thread->RetStatus);
879 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
880 Log(" KStack 0x%x", thread->KernelStack);
885 * \brief Gets the next thread to run
886 * \param CPU Current CPU
887 * \param Last The thread the CPU was running
889 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
893 // If this CPU has the lock, we must let it complete
894 if( CPU_HAS_LOCK( &glThreadListLock ) )
897 // Don't change threads if the current CPU has switches disabled
898 if( gaThreads_NoTaskSwitch[CPU] )
903 SHORTLOCK( &glThreadListLock );
905 // Clear Delete Queue
906 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
907 while(gDeleteThreads)
909 thread = gDeleteThreads->Next;
910 if( IS_LOCKED(&gDeleteThreads->IsLocked) ) { // Only free if structure is unused
912 gDeleteThreads->Status = THREAD_STAT_DEAD;
914 if( IsHeap(gDeleteThreads->ThreadName) )
915 free(gDeleteThreads->ThreadName);
916 // Remove from global list
917 if( gDeleteThreads == gAllThreads )
918 gAllThreads = gDeleteThreads->GlobalNext;
920 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
921 free( gDeleteThreads );
923 gDeleteThreads = thread;
926 // No active threads, just take a nap
927 if(giNumActiveThreads == 0) {
928 SHORTREL( &glThreadListLock );
929 #if DEBUG_TRACE_TICKETS
930 Log("No active threads");
935 #if SCHEDULER_TYPE != SCHED_RR_PRI
936 // Special case: 1 thread
937 if(giNumActiveThreads == 1) {
938 if( gActiveThreads->CurCPU == -1 )
939 gActiveThreads->CurCPU = CPU;
941 SHORTREL( &glThreadListLock );
943 if( gActiveThreads->CurCPU == CPU )
944 return gActiveThreads;
946 return NULL; // CPU has nothing to do
950 // Allow the old thread to be scheduled again
952 if( Last->Status == THREAD_STAT_ACTIVE ) {
953 #if SCHEDULER_TYPE == SCHED_LOTTERY
954 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
955 # if DEBUG_TRACE_TICKETS
956 LogF(" CPU %i released %p (%i %s) into the pool (%i tickets in pool)\n",
957 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets);
961 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
963 LogF(" CPU %i released %p (%i %s)->Status = %i (Released)\n",
964 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
972 #if SCHEDULER_TYPE == SCHED_LOTTERY
977 for(thread = gActiveThreads; thread; thread = thread->Next) {
978 if(thread->CurCPU >= 0) continue;
979 if(thread->Status != THREAD_STAT_ACTIVE)
980 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
981 thread, thread->TID, thread->ThreadName, thread->Status);
982 if(thread->Next == thread) {
983 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
984 thread, thread->TID, thread->ThreadName, thread->Status);
986 number += caiTICKET_COUNTS[ thread->Priority ];
988 if(number != giFreeTickets) {
989 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
990 giFreeTickets, number, CPU);
994 // No free tickets (all tasks delegated to cores)
995 if( giFreeTickets == 0 ) {
996 SHORTREL(&glThreadListLock);
1000 // Get the ticket number
1001 ticket = number = rand() % giFreeTickets;
1003 // Find the next thread
1004 for(thread=gActiveThreads;thread;thread=thread->Next)
1006 if(thread->CurCPU >= 0) continue;
1007 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1008 number -= caiTICKET_COUNTS[ thread->Priority ];
1011 // If we didn't find a thread, something went wrong
1015 for(thread=gActiveThreads;thread;thread=thread->Next) {
1016 if(thread->CurCPU >= 0) continue;
1017 number += caiTICKET_COUNTS[ thread->Priority ];
1019 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1020 giFreeTickets, number);
1022 # if DEBUG_TRACE_TICKETS
1023 LogF(" CPU%i giFreeTickets = %i, running %p (%i %s CPU=%i)\n",
1024 CPU, giFreeTickets, thread, thread->TID, thread->ThreadName, thread->CurCPU);
1027 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1031 // Priority based round robin scheduler
1033 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1036 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1038 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1040 if( thread->CurCPU == -1 ) break;
1042 // If we fall onto the same queue again, special handling is
1044 if( i == Last->Priority ) {
1045 tThread *savedThread = thread;
1047 // Find the next unscheduled thread in the list
1048 for( thread = Last->Next; thread; thread = thread->Next )
1050 if( thread->CurCPU == -1 ) break;
1052 // If we don't find anything after, just use the one
1054 if( !thread ) thread = savedThread;
1056 // Found a thread? Schedule it!
1062 SHORTREL(&glThreadListLock);
1066 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1068 // Find the next unscheduled thread in the list
1069 for( thread = Last->Next; thread; thread = thread->Next )
1071 if( thread->CurCPU == -1 ) break;
1073 // If we don't find anything after, search from the beginning
1076 for(thread = gActiveThreads; thread; thread = thread->Next)
1078 if( thread->CurCPU == -1 ) break;
1084 SHORTREL(&glThreadListLock);
1089 # error "Unimplemented scheduling algorithm"
1092 // Make the new thread non-schedulable
1093 thread->CurCPU = CPU;
1095 SHORTREL( &glThreadListLock );
1101 * \fn void Threads_SegFault(tVAddr Addr)
1102 * \brief Called when a Segment Fault occurs
1104 void Threads_SegFault(tVAddr Addr)
1106 Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
1108 //Threads_Exit( 0, -1 );
1112 * \brief Acquire a heavy mutex
1113 * \param Mutex Mutex to acquire
1115 * This type of mutex checks if the mutex is avaliable, and acquires it
1116 * if it is. Otherwise, the current thread is added to the mutex's wait
1117 * queue and the thread suspends. When the holder of the mutex completes,
1118 * the oldest thread (top thread) on the queue is given the lock and
1121 void Mutex_Acquire(tMutex *Mutex)
1123 tThread *us = Proc_GetCurThread();
1126 SHORTLOCK( &Mutex->Protector );
1128 //Log("Mutex_Acquire: (%p)", Mutex);
1130 // Check if the lock is already held
1131 if( Mutex->Owner ) {
1132 SHORTLOCK( &glThreadListLock );
1133 // - Remove from active list
1134 us = Threads_RemActive();
1136 // - Mark as sleeping
1137 us->Status = THREAD_STAT_MUTEXSLEEP;
1138 us->WaitPointer = Mutex;
1141 if(Mutex->LastWaiting) {
1142 Mutex->LastWaiting->Next = us;
1143 Mutex->LastWaiting = us;
1146 Mutex->Waiting = us;
1147 Mutex->LastWaiting = us;
1153 for( t = Mutex->Waiting; t; t = t->Next, i++ )
1154 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1155 t, t->TID, t->ThreadName);
1159 SHORTREL( &glThreadListLock );
1160 SHORTREL( &Mutex->Protector );
1161 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1162 // We're only woken when we get the lock
1163 us->WaitPointer = NULL;
1165 // Ooh, let's take it!
1168 SHORTREL( &Mutex->Protector );
1173 * \brief Release a held mutex
1174 * \param Mutex Mutex to release
1176 void Mutex_Release(tMutex *Mutex)
1178 SHORTLOCK( &Mutex->Protector );
1179 //Log("Mutex_Release: (%p)", Mutex);
1180 if( Mutex->Waiting ) {
1181 Mutex->Owner = Mutex->Waiting; // Set owner
1182 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1183 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1184 // 2010-10-02 21:50 - Comemerating the death of the longest single
1185 // blocker in the Acess2 history. REMEMBER TO
1186 // FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1187 if( Mutex->LastWaiting == Mutex->Owner )
1188 Mutex->LastWaiting = NULL;
1191 SHORTLOCK( &glThreadListLock );
1192 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1193 Threads_AddActive(Mutex->Owner);
1194 SHORTREL( &glThreadListLock );
1197 Mutex->Owner = NULL;
1199 SHORTREL( &Mutex->Protector );
1203 * \brief Is this mutex locked?
1204 * \param Mutex Mutex pointer
1206 int Mutex_IsLocked(tMutex *Mutex)
1208 return Mutex->Owner != NULL;
1212 EXPORT(Threads_GetUID);
1213 EXPORT(Threads_GetGID);
1214 EXPORT(Mutex_Acquire);
1215 EXPORT(Mutex_Release);
1216 EXPORT(Mutex_IsLocked);