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);
38 extern int GetCPUNum(void);
41 void Threads_Init(void);
42 int Threads_SetName(const char *NewName);
43 char *Threads_GetName(int ID);
44 void Threads_SetPriority(tThread *Thread, int Pri);
45 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
46 int Threads_WaitTID(int TID, int *status);
47 tThread *Threads_GetThread(Uint TID);
48 void Threads_AddToDelete(tThread *Thread);
49 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread);
50 void Threads_Exit(int TID, int Status);
51 void Threads_Kill(tThread *Thread, int Status);
52 void Threads_Yield(void);
53 void Threads_Sleep(void);
54 int Threads_Wake(tThread *Thread);
55 void Threads_AddActive(tThread *Thread);
56 tThread *Threads_RemActive(void);
57 int Threads_GetPID(void);
58 int Threads_GetTID(void);
59 tUID Threads_GetUID(void);
60 int Threads_SetUID(Uint *Errno, tUID ID);
61 tGID Threads_GetGID(void);
62 int Threads_SetGID(Uint *Errno, tUID ID);
63 void Threads_Dump(void);
64 void Threads_DumpActive(void);
66 void Mutex_Acquire(tMutex *Mutex);
67 void Mutex_Release(tMutex *Mutex);
68 int Mutex_IsLocked(tMutex *Mutex);
72 // Only used for the core kernel
73 tThread gThreadZero = {
74 Status: THREAD_STAT_ACTIVE, // Status
75 ThreadName: "ThreadZero", // Name
76 Quantum: DEFAULT_QUANTUM, // Default Quantum
77 Remaining: DEFAULT_QUANTUM, // Current Quantum
78 Priority: DEFAULT_PRIORITY // Number of tickets
82 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
83 // --- Current State ---
84 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
85 volatile Uint giNextTID = 1; // Next TID to allocate
86 // --- Thread Lists ---
87 tThread *gAllThreads = NULL; // All allocated threads
88 tThread *gSleepingThreads = NULL; // Sleeping Threads
89 tThread *gDeleteThreads = NULL; // Threads to delete
90 int giNumCPUs = 1; // Number of CPUs
91 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
92 // --- Scheduler Types ---
93 #if SCHEDULER_TYPE == SCHED_LOTTERY
94 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
95 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
96 tThread *gActiveThreads = NULL; // Currently Running Threads
97 #elif SCHEDULER_TYPE == SCHED_RR_SIM
98 tThread *gActiveThreads = NULL; // Currently Running Threads
99 #elif SCHEDULER_TYPE == SCHED_RR_PRI
100 tThread *gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
102 # error "Unkown scheduler type"
107 * \fn void Threads_Init(void)
108 * \brief Initialse the thread list
110 void Threads_Init(void)
114 // Create Initial Task
115 #if SCHEDULER_TYPE == SCHED_RR_PRI
116 gaActiveThreads[gThreadZero.Priority] = &gThreadZero;
118 gActiveThreads = &gThreadZero;
121 gAllThreads = &gThreadZero;
122 giNumActiveThreads = 1;
128 * \fn void Threads_SetName(const char *NewName)
129 * \brief Sets the current thread's name
130 * \param NewName New name for the thread
131 * \return Boolean Failure
133 int Threads_SetName(const char *NewName)
135 tThread *cur = Proc_GetCurThread();
136 char *oldname = cur->ThreadName;
138 // NOTE: There is a possibility of non-thread safety here
139 // A thread could read the current name pointer before it is zeroed
141 cur->ThreadName = NULL;
143 if( IsHeap(oldname) ) free( oldname );
145 cur->ThreadName = strdup(NewName);
150 * \fn char *Threads_GetName(int ID)
151 * \brief Gets a thread's name
152 * \param ID Thread ID (-1 indicates current thread)
153 * \return Pointer to name
154 * \retval NULL Failure
156 char *Threads_GetName(tTID ID)
159 return Proc_GetCurThread()->ThreadName;
161 return Threads_GetThread(ID)->ThreadName;
165 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
166 * \brief Sets the priority of a task
167 * \param Thread Thread to update ticket count (NULL means current thread)
168 * \param Pri New priority
170 void Threads_SetPriority(tThread *Thread, int Pri)
172 // Get current thread
173 if(Thread == NULL) Thread = Proc_GetCurThread();
175 // - If < 0, set to lowest priority
176 if(Pri < 0) Pri = MIN_PRIORITY;
177 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
179 // Do we actually have to do anything?
180 if( Pri == Thread->Priority ) return;
182 #if SCHEDULER_TYPE == SCHED_RR_PRI
183 SHORTLOCK( &glThreadListLock );
184 // Remove from old priority
185 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
187 Thread->Next = gaActiveThreads[Pri];
188 gaActiveThreads[Pri] = Thread;
189 Thread->Priority = Pri;
190 SHORTREL( &glThreadListLock );
192 // If this isn't the current thread, we need to lock
193 if( Thread != Proc_GetCurThread() )
195 SHORTLOCK( &glThreadListLock );
197 #if SCHEDULER_TYPE == SCHED_LOTTERY
198 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
199 # if DEBUG_TRACE_TICKETS
200 Log("Threads_SetTickets: new giFreeTickets = %i", giFreeTickets);
203 Thread->Priority = Pri;
204 SHORTREL( &glThreadListLock );
207 Thread->Priority = Pri;
212 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
213 * \brief Clone the TCB of the current thread
214 * \param Err Error pointer
215 * \param Flags Flags for something... (What is this for?)
217 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
221 cur = Proc_GetCurThread();
223 // Allocate and duplicate
224 new = malloc(sizeof(tThread));
229 memcpy(new, cur, sizeof(tThread));
233 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
234 new->Status = THREAD_STAT_PREINIT;
238 new->TID = giNextTID++;
242 new->ThreadName = strdup(cur->ThreadName);
244 // Set Thread Group ID (PID)
246 new->TGID = new->TID;
248 new->TGID = cur->TGID;
250 // Messages are not inherited
251 new->Messages = NULL;
252 new->LastMessage = NULL;
255 new->Remaining = new->Quantum = cur->Quantum;
256 new->Priority = cur->Priority;
258 // Set Signal Handlers
259 new->CurFaultNum = 0;
260 new->FaultHandler = cur->FaultHandler;
262 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
264 switch(cCONFIG_TYPES[i])
267 new->Config[i] = cur->Config[i];
271 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
278 // Maintain a global list of threads
279 SHORTLOCK( &glThreadListLock );
280 new->GlobalPrev = NULL; // Protect against bugs
281 new->GlobalNext = gAllThreads;
282 gAllThreads->GlobalPrev = new;
284 SHORTREL( &glThreadListLock );
290 * \brief Get a configuration pointer from the Per-Thread data area
291 * \param ID Config slot ID
292 * \return Pointer at ID
294 Uint *Threads_GetCfgPtr(int ID)
296 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
297 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
301 return &Proc_GetCurThread()->Config[ID];
305 * \brief Wait for a task to change state
306 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
307 * \param Status Thread return status
308 * \return TID of child that changed state
310 tTID Threads_WaitTID(int TID, int *Status)
314 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
318 // Any peer/child thread
320 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
326 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
332 tThread *t = Threads_GetThread(TID);
333 int initStatus = t->Status;
336 // Wait for the thread to die!
337 if(initStatus != THREAD_STAT_ZOMBIE) {
338 // TODO: Handle child also being suspended if wanted
339 while(t->Status != THREAD_STAT_ZOMBIE) {
341 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
342 Threads_GetTID(), t->TID, t->Status);
347 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
348 Threads_GetTID(), t->TID, t->Status);
352 case THREAD_STAT_ZOMBIE:
354 t->Status = THREAD_STAT_DEAD;
355 // TODO: Child return value?
356 if(Status) *Status = t->RetStatus;
357 // add to delete queue
358 Threads_AddToDelete( t );
361 if(Status) *Status = -1;
371 * \brief Gets a thread given its TID
372 * \param TID Thread ID
373 * \return Thread pointer
375 tThread *Threads_GetThread(Uint TID)
379 // Search global list
380 for(thread = gAllThreads;
382 thread = thread->GlobalNext)
384 if(thread->TID == TID)
388 Log("Unable to find TID %i on main list\n", TID);
394 * \brief Adds a thread to the delete queue
395 * \param Thread Thread to delete
397 void Threads_AddToDelete(tThread *Thread)
399 // Add to delete queue
400 // TODO: Is locking needed?
402 Thread->Next = gDeleteThreads;
403 gDeleteThreads = Thread;
406 gDeleteThreads = Thread;
411 * \brief Deletes an entry from a list
412 * \param List Pointer to the list head
413 * \param Thread Thread to find
416 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
418 tThread *ret, *prev = NULL;
421 ret && ret != Thread;
422 prev = ret, ret = ret->Next
425 // Is the thread on the list
427 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
432 *List = Thread->Next;
433 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
436 prev->Next = Thread->Next;
437 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
444 * \brief Exit the current process (or another?)
445 * \param TID Thread ID to kill
446 * \param Status Exit status
448 void Threads_Exit(int TID, int Status)
451 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
453 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
455 // Halt forever, just in case
460 * \fn void Threads_Kill(tThread *Thread, int Status)
461 * \brief Kill a thread
462 * \param Thread Thread to kill
463 * \param Status Status code to return to the parent
465 void Threads_Kill(tThread *Thread, int Status)
469 // TODO: Kill all children
473 // TODO: I should keep a .Parent pointer, and a .Children list
474 for(child = gAllThreads;
476 child = child->GlobalNext)
478 if(child->Parent == Thread)
479 Threads_Kill(child, -1);
484 ///\note Double lock is needed due to overlap of lock areas
486 // Lock thread (stop us recieving messages)
487 SHORTLOCK( &Thread->IsLocked );
489 // Clear Message Queue
490 while( Thread->Messages )
492 msg = Thread->Messages->Next;
493 free( Thread->Messages );
494 Thread->Messages = msg;
498 SHORTLOCK( &glThreadListLock );
500 switch(Thread->Status)
502 case THREAD_STAT_PREINIT: // Only on main list
505 // Currently active thread
506 case THREAD_STAT_ACTIVE:
507 #if SCHEDULER_TYPE == SCHED_RR_PRI
508 if( Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
510 if( Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
513 // Ensure that we are not rescheduled
514 Thread->Remaining = 0; // Clear Remaining Quantum
515 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
517 // Update bookkeeping
518 giNumActiveThreads --;
519 #if SCHEDULER_TYPE == SCHED_LOTTERY
520 if( Thread != Proc_GetCurThread() )
521 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
526 Log_Warning("Threads",
527 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
528 Thread, Thread->TID, Thread->ThreadName
532 case THREAD_STAT_SLEEPING:
533 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
535 Log_Warning("Threads",
536 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
537 Thread, Thread->TID, Thread->ThreadName
542 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
548 Thread->RetStatus = Status;
550 // Don't Zombie if we are being killed because our parent is
553 Thread->Status = THREAD_STAT_DEAD;
554 Threads_AddToDelete( Thread );
556 Thread->Status = THREAD_STAT_ZOMBIE;
558 Threads_Wake( Thread->Parent );
561 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
564 SHORTREL( &glThreadListLock );
565 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
575 * \brief Yield remainder of the current thread's timeslice
577 void Threads_Yield(void)
579 tThread *thread = Proc_GetCurThread();
580 thread->Remaining = 0;
581 //while(thread->Remaining == 0)
586 * \fn void Threads_Sleep(void)
587 * \brief Take the current process off the run queue
589 void Threads_Sleep(void)
591 tThread *cur = Proc_GetCurThread();
594 SHORTLOCK( &glThreadListLock );
596 // Don't sleep if there is a message waiting
597 if( cur->Messages ) {
598 SHORTREL( &glThreadListLock );
602 // Remove us from running queue
604 // Mark thread as sleeping
605 cur->Status = THREAD_STAT_SLEEPING;
607 // Add to Sleeping List (at the top)
608 cur->Next = gSleepingThreads;
609 gSleepingThreads = cur;
612 #if DEBUG_TRACE_STATE
613 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
617 SHORTREL( &glThreadListLock );
619 while(cur->Status != THREAD_STAT_ACTIVE) HALT();
624 * \fn int Threads_Wake( tThread *Thread )
625 * \brief Wakes a sleeping/waiting thread up
626 * \param Thread Thread to wake
627 * \return Boolean Failure (Returns ERRNO)
628 * \warning This should ONLY be called with task switches disabled
630 int Threads_Wake(tThread *Thread)
635 switch(Thread->Status)
637 case THREAD_STAT_ACTIVE:
638 Log("Thread_Wake: Waking awake thread (%i)", Thread->TID);
641 case THREAD_STAT_SLEEPING:
642 SHORTLOCK( &glThreadListLock );
643 // Remove from sleeping queue
644 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
646 Threads_AddActive( Thread );
648 #if DEBUG_TRACE_STATE
649 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
651 SHORTREL( &glThreadListLock );
654 case THREAD_STAT_WAITING:
655 Warning("Thread_Wake - Waiting threads are not currently supported");
658 case THREAD_STAT_DEAD:
659 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
663 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
669 * \brief Wake a thread given the TID
670 * \param TID Thread ID to wake
671 * \return Boolean Faulure (errno)
673 int Threads_WakeTID(tTID TID)
675 tThread *thread = Threads_GetThread(TID);
679 ret = Threads_Wake( thread );
680 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
685 * \brief Adds a thread to the active queue
687 void Threads_AddActive(tThread *Thread)
689 SHORTLOCK( &glThreadListLock );
691 if( Thread->Status == THREAD_STAT_ACTIVE ) {
692 tThread *cur = Proc_GetCurThread();
693 Warning("WTF, CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
694 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
698 Thread->Status = THREAD_STAT_ACTIVE;
700 // Add to active list
701 #if SCHEDULER_TYPE == SCHED_RR_PRI
702 Thread->Next = gaActiveThreads[Thread->Priority];
703 gaActiveThreads[Thread->Priority] = Thread;
705 Thread->Next = gActiveThreads;
706 gActiveThreads = Thread;
709 // Update bookkeeping
710 giNumActiveThreads ++;
712 #if SCHEDULER_TYPE == SCHED_LOTTERY
713 giFreeTickets += caiTICKET_COUNTS[ Thread->Priority ];
714 # if DEBUG_TRACE_TICKETS
715 Log("Threads_AddActive: CPU%i %p %i (%s) added, new giFreeTickets = %i",
716 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName, giFreeTickets);
720 SHORTREL( &glThreadListLock );
724 * \brief Removes the current thread from the active queue
725 * \warning This should ONLY be called with task switches disabled
726 * \return Current thread pointer
728 tThread *Threads_RemActive(void)
730 tThread *ret = Proc_GetCurThread();
732 SHORTLOCK( &glThreadListLock );
734 // Delete from active queue
735 #if SCHEDULER_TYPE == SCHED_RR_PRI
736 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
738 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
741 SHORTREL( &glThreadListLock );
749 giNumActiveThreads --;
750 // no need to decrement tickets, scheduler did it for us
752 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
753 Log("Threads_RemActive: CPU%i %p %i (%s) removed, giFreeTickets = %i",
754 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
757 SHORTREL( &glThreadListLock );
763 * \fn void Threads_SetFaultHandler(Uint Handler)
764 * \brief Sets the signal handler for a signal
766 void Threads_SetFaultHandler(Uint Handler)
768 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
769 Proc_GetCurThread()->FaultHandler = Handler;
773 * \fn void Threads_Fault(int Num)
774 * \brief Calls a fault handler
776 void Threads_Fault(int Num)
778 tThread *thread = Proc_GetCurThread();
780 Log_Log("Threads", "Threads_Fault: thread = %p", thread);
784 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
786 switch(thread->FaultHandler)
789 Threads_Kill(thread, -1);
792 case 1: // Dump Core?
793 Threads_Kill(thread, -1);
798 // Double Fault? Oh, F**k
799 if(thread->CurFaultNum != 0) {
800 Threads_Kill(thread, -1); // For now, just kill
804 thread->CurFaultNum = Num;
806 Proc_CallFaultHandler(thread);
809 // --- Process Structure Access Functions ---
810 tPID Threads_GetPID(void)
812 return Proc_GetCurThread()->TGID;
814 tTID Threads_GetTID(void)
816 return Proc_GetCurThread()->TID;
818 tUID Threads_GetUID(void)
820 return Proc_GetCurThread()->UID;
822 tGID Threads_GetGID(void)
824 return Proc_GetCurThread()->GID;
827 int Threads_SetUID(Uint *Errno, tUID ID)
829 tThread *t = Proc_GetCurThread();
834 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
839 int Threads_SetGID(Uint *Errno, tGID ID)
841 tThread *t = Proc_GetCurThread();
846 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
852 * \fn void Threads_Dump(void)
854 void Threads_DumpActive(void)
857 #if SCHEDULER_TYPE == SCHED_RR_PRI
861 Log("Active Threads: (%i reported)", giNumActiveThreads);
863 #if SCHEDULER_TYPE == SCHED_RR_PRI
864 for( i = 0; i < MIN_PRIORITY+1; i++ )
866 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
868 for(thread=gActiveThreads;thread;thread=thread->Next)
871 Log(" %p %i (%i) - %s (CPU %i)",
872 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
873 if(thread->Status != THREAD_STAT_ACTIVE)
874 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
875 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
876 Log(" KStack 0x%x", thread->KernelStack);
879 #if SCHEDULER_TYPE == SCHED_RR_PRI
885 * \fn void Threads_Dump(void)
886 * \brief Dumps a list of currently running threads
888 void Threads_Dump(void)
892 Log("--- Thread Dump ---");
893 Threads_DumpActive();
896 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
898 Log(" %p %i (%i) - %s (CPU %i)",
899 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
900 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
901 switch(thread->Status)
903 case THREAD_STAT_MUTEXSLEEP:
904 Log(" Mutex Pointer: %p", thread->WaitPointer);
906 case THREAD_STAT_ZOMBIE:
907 Log(" Return Status: %i", thread->RetStatus);
911 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
912 Log(" KStack 0x%x", thread->KernelStack);
917 * \brief Gets the next thread to run
918 * \param CPU Current CPU
919 * \param Last The thread the CPU was running
921 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
925 // If this CPU has the lock, we must let it complete
926 if( CPU_HAS_LOCK( &glThreadListLock ) )
929 // Don't change threads if the current CPU has switches disabled
930 if( gaThreads_NoTaskSwitch[CPU] )
935 SHORTLOCK( &glThreadListLock );
937 // Clear Delete Queue
938 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
939 while(gDeleteThreads)
941 thread = gDeleteThreads->Next;
942 // Only free if structure is unused
943 if( !IS_LOCKED(&gDeleteThreads->IsLocked) )
946 gDeleteThreads->Status = THREAD_STAT_BURIED;
948 if( IsHeap(gDeleteThreads->ThreadName) )
949 free(gDeleteThreads->ThreadName);
950 // Remove from global list
951 if( gDeleteThreads == gAllThreads )
952 gAllThreads = gDeleteThreads->GlobalNext;
954 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
955 free( gDeleteThreads );
957 gDeleteThreads = thread;
960 // No active threads, just take a nap
961 if(giNumActiveThreads == 0) {
962 SHORTREL( &glThreadListLock );
963 #if DEBUG_TRACE_TICKETS
964 Log("No active threads");
969 #if SCHEDULER_TYPE != SCHED_RR_PRI
970 // Special case: 1 thread
971 if(giNumActiveThreads == 1) {
972 if( gActiveThreads->CurCPU == -1 )
973 gActiveThreads->CurCPU = CPU;
975 SHORTREL( &glThreadListLock );
977 if( gActiveThreads->CurCPU == CPU )
978 return gActiveThreads;
980 return NULL; // CPU has nothing to do
984 // Allow the old thread to be scheduled again
986 if( Last->Status == THREAD_STAT_ACTIVE ) {
987 #if SCHEDULER_TYPE == SCHED_LOTTERY
988 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
989 # if DEBUG_TRACE_TICKETS
990 LogF(" CPU %i released %p (%i %s) into the pool (%i tickets in pool)\n",
991 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets);
995 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
997 LogF(" CPU %i released %p (%i %s)->Status = %i (Released)\n",
998 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1004 // Lottery Scheduler
1006 #if SCHEDULER_TYPE == SCHED_LOTTERY
1011 for(thread = gActiveThreads; thread; thread = thread->Next) {
1012 if(thread->CurCPU >= 0) continue;
1013 if(thread->Status != THREAD_STAT_ACTIVE)
1014 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1015 thread, thread->TID, thread->ThreadName, thread->Status);
1016 if(thread->Next == thread) {
1017 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1018 thread, thread->TID, thread->ThreadName, thread->Status);
1020 number += caiTICKET_COUNTS[ thread->Priority ];
1022 if(number != giFreeTickets) {
1023 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1024 giFreeTickets, number, CPU);
1028 // No free tickets (all tasks delegated to cores)
1029 if( giFreeTickets == 0 ) {
1030 SHORTREL(&glThreadListLock);
1034 // Get the ticket number
1035 ticket = number = rand() % giFreeTickets;
1037 // Find the next thread
1038 for(thread=gActiveThreads;thread;thread=thread->Next)
1040 if(thread->CurCPU >= 0) continue;
1041 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1042 number -= caiTICKET_COUNTS[ thread->Priority ];
1045 // If we didn't find a thread, something went wrong
1049 for(thread=gActiveThreads;thread;thread=thread->Next) {
1050 if(thread->CurCPU >= 0) continue;
1051 number += caiTICKET_COUNTS[ thread->Priority ];
1053 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1054 giFreeTickets, number);
1056 # if DEBUG_TRACE_TICKETS
1057 LogF(" CPU%i giFreeTickets = %i, running %p (%i %s CPU=%i)\n",
1058 CPU, giFreeTickets, thread, thread->TID, thread->ThreadName, thread->CurCPU);
1061 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1065 // Priority based round robin scheduler
1067 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1070 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1072 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1074 if( thread->CurCPU == -1 ) break;
1076 // If we fall onto the same queue again, special handling is
1078 if( i == Last->Priority ) {
1079 tThread *savedThread = thread;
1081 // Find the next unscheduled thread in the list
1082 for( thread = Last->Next; thread; thread = thread->Next )
1084 if( thread->CurCPU == -1 ) break;
1086 // If we don't find anything after, just use the one
1088 if( !thread ) thread = savedThread;
1090 // Found a thread? Schedule it!
1096 SHORTREL(&glThreadListLock);
1100 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1102 // Find the next unscheduled thread in the list
1103 for( thread = Last->Next; thread; thread = thread->Next )
1105 if( thread->CurCPU == -1 ) break;
1107 // If we don't find anything after, search from the beginning
1110 for(thread = gActiveThreads; thread; thread = thread->Next)
1112 if( thread->CurCPU == -1 ) break;
1118 SHORTREL(&glThreadListLock);
1123 # error "Unimplemented scheduling algorithm"
1126 // Make the new thread non-schedulable
1127 thread->CurCPU = CPU;
1129 SHORTREL( &glThreadListLock );
1135 * \fn void Threads_SegFault(tVAddr Addr)
1136 * \brief Called when a Segment Fault occurs
1138 void Threads_SegFault(tVAddr Addr)
1140 Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
1142 //Threads_Exit( 0, -1 );
1146 * \brief Acquire a heavy mutex
1147 * \param Mutex Mutex to acquire
1149 * This type of mutex checks if the mutex is avaliable, and acquires it
1150 * if it is. Otherwise, the current thread is added to the mutex's wait
1151 * queue and the thread suspends. When the holder of the mutex completes,
1152 * the oldest thread (top thread) on the queue is given the lock and
1155 void Mutex_Acquire(tMutex *Mutex)
1157 tThread *us = Proc_GetCurThread();
1160 SHORTLOCK( &Mutex->Protector );
1162 //Log("Mutex_Acquire: (%p)", Mutex);
1164 // Check if the lock is already held
1165 if( Mutex->Owner ) {
1166 SHORTLOCK( &glThreadListLock );
1167 // - Remove from active list
1168 us = Threads_RemActive();
1170 // - Mark as sleeping
1171 us->Status = THREAD_STAT_MUTEXSLEEP;
1172 us->WaitPointer = Mutex;
1175 if(Mutex->LastWaiting) {
1176 Mutex->LastWaiting->Next = us;
1177 Mutex->LastWaiting = us;
1180 Mutex->Waiting = us;
1181 Mutex->LastWaiting = us;
1187 for( t = Mutex->Waiting; t; t = t->Next, i++ )
1188 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1189 t, t->TID, t->ThreadName);
1193 SHORTREL( &glThreadListLock );
1194 SHORTREL( &Mutex->Protector );
1195 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1196 // We're only woken when we get the lock
1197 us->WaitPointer = NULL;
1199 // Ooh, let's take it!
1202 SHORTREL( &Mutex->Protector );
1206 extern tMutex glPhysAlloc;
1207 if( Mutex != &glPhysAlloc )
1208 LogF("Mutex %p taken by %i %p\n", Mutex, us->TID, __builtin_return_address(0));
1213 * \brief Release a held mutex
1214 * \param Mutex Mutex to release
1216 void Mutex_Release(tMutex *Mutex)
1218 SHORTLOCK( &Mutex->Protector );
1219 //Log("Mutex_Release: (%p)", Mutex);
1220 if( Mutex->Waiting ) {
1221 Mutex->Owner = Mutex->Waiting; // Set owner
1222 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1223 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1224 // 2010-10-02 21:50 - Comemerating the death of the longest single
1225 // blocker in the Acess2 history. REMEMBER TO
1226 // FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1227 if( Mutex->LastWaiting == Mutex->Owner )
1228 Mutex->LastWaiting = NULL;
1231 SHORTLOCK( &glThreadListLock );
1232 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1233 Threads_AddActive(Mutex->Owner);
1234 SHORTREL( &glThreadListLock );
1237 Mutex->Owner = NULL;
1239 SHORTREL( &Mutex->Protector );
1242 extern tMutex glPhysAlloc;
1243 if( Mutex != &glPhysAlloc )
1244 LogF("Mutex %p released by %i %p\n", Mutex, Threads_GetTID(), __builtin_return_address(0));
1249 * \brief Is this mutex locked?
1250 * \param Mutex Mutex pointer
1252 int Mutex_IsLocked(tMutex *Mutex)
1254 return Mutex->Owner != NULL;
1258 * \brief Initialise the semaphore
1259 * \param Value Initial value of the semaphore
1260 * \param Label Symbolic name
1262 void Semaphore_Init(tSemaphore *Sem, int Value, const char *Label)
1269 * \brief Acquire a "item" from the semaphore
1271 void Semaphore_Wait(tSemaphore *Sem)
1275 SHORTLOCK( &Sem->Protector );
1276 if( Sem->Value > 0 ) {
1278 SHORTREL( &Sem->Protector );
1282 SHORTLOCK( &glThreadListLock );
1284 // - Remove from active list
1285 us = Threads_RemActive();
1287 // - Mark as sleeping
1288 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1289 us->WaitPointer = Sem;
1292 if(Sem->LastWaiting) {
1293 Sem->LastWaiting->Next = us;
1294 Sem->LastWaiting = us;
1298 Sem->LastWaiting = us;
1301 SHORTREL( &glThreadListLock );
1302 SHORTREL( &Sem->Protector );
1303 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1304 // We're only woken when there's something avaliable
1305 us->WaitPointer = NULL;
1309 * \brief Add an "item" to the semaphore
1311 void Semaphore_Signal(tSemaphore *Sem)
1313 SHORTLOCK( &Sem->Protector );
1318 tThread *toWake = Sem->Waiting;
1320 Sem->Waiting = Sem->Waiting->Next; // Next!
1321 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1322 if( Sem->Waiting == NULL )
1323 Sem->LastWaiting = NULL;
1326 SHORTLOCK( &glThreadListLock );
1327 if( toWake->Status != THREAD_STAT_ACTIVE )
1328 Threads_AddActive(toWake);
1329 SHORTREL( &glThreadListLock );
1331 // Decrement (the value is now "owned" by `toWake`)
1334 SHORTREL( &Sem->Protector );
1338 EXPORT(Threads_GetUID);
1339 EXPORT(Threads_GetGID);
1340 EXPORT(Mutex_Acquire);
1341 EXPORT(Mutex_Release);
1342 EXPORT(Mutex_IsLocked);