4 * - Common Thread Control
8 #include <threads_int.h>
11 #include <semaphore.h>
15 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
16 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
17 #define SEMAPHORE_DEBUG 0
21 #define SCHED_LOTTERY 1 // Lottery scheduler
22 #define SCHED_RR_SIM 2 // Single Queue Round Robin
23 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
25 #define SCHEDULER_TYPE SCHED_RR_PRI
28 #define DEFAULT_QUANTUM 5
29 #define DEFAULT_PRIORITY 5
30 #define MIN_PRIORITY 10
31 const enum eConfigTypes cCONFIG_TYPES[] = {
32 CFGT_HEAPSTR, // e.g. CFG_VFS_CWD
33 CFGT_INT, // e.g. CFG_VFS_MAXFILES
40 void Threads_Init(void);
42 int Threads_SetName(const char *NewName);
44 char *Threads_GetName(int ID);
46 void Threads_SetPriority(tThread *Thread, int Pri);
47 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
48 int Threads_WaitTID(int TID, int *status);
49 tThread *Threads_GetThread(Uint TID);
51 void Threads_AddToDelete(tThread *Thread);
52 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread);
54 void Threads_Exit(int TID, int Status);
55 void Threads_Kill(tThread *Thread, int Status);
56 void Threads_Yield(void);
57 void Threads_Sleep(void);
58 int Threads_Wake(tThread *Thread);
59 void Threads_AddActive(tThread *Thread);
60 tThread *Threads_RemActive(void);
62 void Threads_ToggleTrace(int TID);
63 void Threads_Fault(int Num);
64 void Threads_SegFault(tVAddr Addr);
66 int Threads_GetPID(void);
67 int Threads_GetTID(void);
68 tUID Threads_GetUID(void);
69 tGID Threads_GetGID(void);
70 int Threads_SetUID(Uint *Errno, tUID ID);
71 int Threads_SetGID(Uint *Errno, tUID ID);
73 void Threads_Dump(void);
74 void Threads_DumpActive(void);
76 int Mutex_Acquire(tMutex *Mutex);
77 void Mutex_Release(tMutex *Mutex);
78 int Mutex_IsLocked(tMutex *Mutex);
83 // Only used for the core kernel
84 tThread gThreadZero = {
85 .Status = THREAD_STAT_ACTIVE, // Status
86 .ThreadName = (char*)"ThreadZero", // Name
87 .Quantum = DEFAULT_QUANTUM, // Default Quantum
88 .Remaining = DEFAULT_QUANTUM, // Current Quantum
89 .Priority = DEFAULT_PRIORITY // Number of tickets
93 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
94 // --- Current State ---
95 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
96 volatile Uint giNextTID = 1; // Next TID to allocate
97 // --- Thread Lists ---
98 tThread *gAllThreads = NULL; // All allocated threads
99 tThread *gSleepingThreads = NULL; // Sleeping Threads
100 tThread *gDeleteThreads = NULL; // Threads to delete
101 int giNumCPUs = 1; // Number of CPUs
102 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
103 // --- Scheduler Types ---
104 #if SCHEDULER_TYPE == SCHED_LOTTERY
105 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
106 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
107 tThread *gActiveThreads = NULL; // Currently Running Threads
108 #elif SCHEDULER_TYPE == SCHED_RR_SIM
109 tThread *gActiveThreads = NULL; // Currently Running Threads
110 #elif SCHEDULER_TYPE == SCHED_RR_PRI
111 tThread *gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
113 # error "Unkown scheduler type"
118 * \fn void Threads_Init(void)
119 * \brief Initialse the thread list
121 void Threads_Init(void)
125 Log_Debug("Threads", "Offsets of tThread");
126 Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
128 // Create Initial Task
129 #if SCHEDULER_TYPE == SCHED_RR_PRI
130 gaActiveThreads[gThreadZero.Priority] = &gThreadZero;
132 gActiveThreads = &gThreadZero;
135 gAllThreads = &gThreadZero;
136 giNumActiveThreads = 1;
142 * \fn void Threads_SetName(const char *NewName)
143 * \brief Sets the current thread's name
144 * \param NewName New name for the thread
145 * \return Boolean Failure
147 int Threads_SetName(const char *NewName)
149 tThread *cur = Proc_GetCurThread();
150 char *oldname = cur->ThreadName;
152 // NOTE: There is a possibility of non-thread safety here
153 // A thread could read the current name pointer before it is zeroed
155 cur->ThreadName = NULL;
157 if( IsHeap(oldname) ) free( oldname );
159 cur->ThreadName = strdup(NewName);
164 * \fn char *Threads_GetName(int ID)
165 * \brief Gets a thread's name
166 * \param ID Thread ID (-1 indicates current thread)
167 * \return Pointer to name
168 * \retval NULL Failure
170 char *Threads_GetName(tTID ID)
173 return Proc_GetCurThread()->ThreadName;
175 return Threads_GetThread(ID)->ThreadName;
179 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
180 * \brief Sets the priority of a task
181 * \param Thread Thread to update ticket count (NULL means current thread)
182 * \param Pri New priority
184 void Threads_SetPriority(tThread *Thread, int Pri)
186 // Get current thread
187 if(Thread == NULL) Thread = Proc_GetCurThread();
189 // - If < 0, set to lowest priority
190 // - Minumum priority is actualy a high number, 0 is highest
191 if(Pri < 0) Pri = MIN_PRIORITY;
192 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
194 // Do we actually have to do anything?
195 if( Pri == Thread->Priority ) return;
197 #if SCHEDULER_TYPE == SCHED_RR_PRI
198 SHORTLOCK( &glThreadListLock );
199 // Remove from old priority
200 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
202 Thread->Next = gaActiveThreads[Pri];
203 gaActiveThreads[Pri] = Thread;
204 Thread->Priority = Pri;
205 SHORTREL( &glThreadListLock );
207 // If this isn't the current thread, we need to lock
208 if( Thread != Proc_GetCurThread() )
210 SHORTLOCK( &glThreadListLock );
212 #if SCHEDULER_TYPE == SCHED_LOTTERY
213 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
214 # if DEBUG_TRACE_TICKETS
215 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
217 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
220 Thread->Priority = Pri;
221 SHORTREL( &glThreadListLock );
224 Thread->Priority = Pri;
227 #if DEBUG_TRACE_STATE
228 Log("Threads_SetPriority: %p(%i %s) pri set %i",
229 Thread, Thread->TID, Thread->ThreadName,
235 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
236 * \brief Clone the TCB of the current thread
237 * \param Err Error pointer
238 * \param Flags Flags for something... (What is this for?)
240 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
244 cur = Proc_GetCurThread();
246 // Allocate and duplicate
247 new = malloc(sizeof(tThread));
248 if(new == NULL) { *Err = -ENOMEM; return NULL; }
249 memcpy(new, cur, sizeof(tThread));
253 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
254 new->Status = THREAD_STAT_PREINIT;
258 new->TID = giNextTID++;
260 new->bInstrTrace = 0;
263 new->ThreadName = strdup(cur->ThreadName);
265 // Set Thread Group ID (PID)
267 new->TGID = new->TID;
269 new->TGID = cur->TGID;
271 // Messages are not inherited
272 new->Messages = NULL;
273 new->LastMessage = NULL;
276 new->Remaining = new->Quantum = cur->Quantum;
277 new->Priority = cur->Priority;
279 // Set Signal Handlers
280 new->CurFaultNum = 0;
281 new->FaultHandler = cur->FaultHandler;
283 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
285 switch(cCONFIG_TYPES[i])
288 new->Config[i] = cur->Config[i];
292 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
299 // Maintain a global list of threads
300 SHORTLOCK( &glThreadListLock );
301 new->GlobalPrev = NULL; // Protect against bugs
302 new->GlobalNext = gAllThreads;
303 gAllThreads->GlobalPrev = new;
305 SHORTREL( &glThreadListLock );
311 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
312 * \brief Clone the TCB of the current thread
314 tThread *Threads_CloneThreadZero(void)
318 cur = Proc_GetCurThread();
320 // Allocate and duplicate
321 new = malloc(sizeof(tThread));
325 memcpy(new, &gThreadZero, sizeof(tThread));
329 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
330 new->Status = THREAD_STAT_PREINIT;
334 new->TID = giNextTID++;
338 new->ThreadName = NULL;
340 // Messages are not inherited
341 new->Messages = NULL;
342 new->LastMessage = NULL;
345 new->Remaining = new->Quantum = cur->Quantum;
346 new->Priority = cur->Priority;
347 new->bInstrTrace = 0;
349 // Set Signal Handlers
350 new->CurFaultNum = 0;
351 new->FaultHandler = cur->FaultHandler;
353 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
355 switch(cCONFIG_TYPES[i])
358 new->Config[i] = cur->Config[i];
362 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
369 // Maintain a global list of threads
370 SHORTLOCK( &glThreadListLock );
371 new->GlobalPrev = NULL; // Protect against bugs
372 new->GlobalNext = gAllThreads;
373 gAllThreads->GlobalPrev = new;
375 SHORTREL( &glThreadListLock );
381 * \brief Get a configuration pointer from the Per-Thread data area
382 * \param ID Config slot ID
383 * \return Pointer at ID
385 Uint *Threads_GetCfgPtr(int ID)
387 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
388 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
392 return &Proc_GetCurThread()->Config[ID];
396 * \brief Wait for a task to change state
397 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
398 * \param Status Thread return status
399 * \return TID of child that changed state
401 tTID Threads_WaitTID(int TID, int *Status)
405 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
409 // Any peer/child thread
411 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
417 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
423 tThread *t = Threads_GetThread(TID);
424 int initStatus = t->Status;
427 // Wait for the thread to die!
428 if(initStatus != THREAD_STAT_ZOMBIE) {
429 // TODO: Handle child also being suspended if wanted
430 while(t->Status != THREAD_STAT_ZOMBIE) {
432 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
433 Threads_GetTID(), t->TID, t->Status);
438 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
439 Threads_GetTID(), t->TID, t->Status);
443 case THREAD_STAT_ZOMBIE:
445 t->Status = THREAD_STAT_DEAD;
446 // TODO: Child return value?
447 if(Status) *Status = t->RetStatus;
448 // add to delete queue
449 Threads_AddToDelete( t );
452 if(Status) *Status = -1;
462 * \brief Gets a thread given its TID
463 * \param TID Thread ID
464 * \return Thread pointer
466 tThread *Threads_GetThread(Uint TID)
470 // Search global list
471 for(thread = gAllThreads;
473 thread = thread->GlobalNext)
475 if(thread->TID == TID)
479 Log("Unable to find TID %i on main list\n", TID);
485 * \brief Adds a thread to the delete queue
486 * \param Thread Thread to delete
488 void Threads_AddToDelete(tThread *Thread)
490 // Add to delete queue
491 // TODO: Is locking needed?
493 Thread->Next = gDeleteThreads;
494 gDeleteThreads = Thread;
497 gDeleteThreads = Thread;
502 * \brief Deletes an entry from a list
503 * \param List Pointer to the list head
504 * \param Thread Thread to find
507 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
509 tThread *ret, *prev = NULL;
512 ret && ret != Thread;
513 prev = ret, ret = ret->Next
516 // Is the thread on the list
518 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
523 *List = Thread->Next;
524 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
527 prev->Next = Thread->Next;
528 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
535 * \brief Exit the current process (or another?)
536 * \param TID Thread ID to kill
537 * \param Status Exit status
539 void Threads_Exit(int TID, int Status)
542 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
544 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
546 // Halt forever, just in case
551 * \fn void Threads_Kill(tThread *Thread, int Status)
552 * \brief Kill a thread
553 * \param Thread Thread to kill
554 * \param Status Status code to return to the parent
556 void Threads_Kill(tThread *Thread, int Status)
559 int isCurThread = Thread == Proc_GetCurThread();
561 // TODO: Kill all children
565 // TODO: I should keep a .Parent pointer, and a .Children list
566 for(child = gAllThreads;
568 child = child->GlobalNext)
570 if(child->Parent == Thread)
571 Threads_Kill(child, -1);
576 ///\note Double lock is needed due to overlap of lock areas
578 // Lock thread (stop us recieving messages)
579 SHORTLOCK( &Thread->IsLocked );
581 // Clear Message Queue
582 while( Thread->Messages )
584 msg = Thread->Messages->Next;
585 free( Thread->Messages );
586 Thread->Messages = msg;
590 SHORTLOCK( &glThreadListLock );
592 switch(Thread->Status)
594 case THREAD_STAT_PREINIT: // Only on main list
597 // Currently active thread
598 case THREAD_STAT_ACTIVE:
599 #if SCHEDULER_TYPE == SCHED_RR_PRI
600 if( Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
602 if( Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
605 // Ensure that we are not rescheduled
606 Thread->Remaining = 0; // Clear Remaining Quantum
607 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
609 // Update bookkeeping
610 giNumActiveThreads --;
611 #if SCHEDULER_TYPE == SCHED_LOTTERY
612 if( Thread != Proc_GetCurThread() )
613 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
618 Log_Warning("Threads",
619 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
620 Thread, Thread->TID, Thread->ThreadName
624 // Kill it while it sleeps!
625 case THREAD_STAT_SLEEPING:
626 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
628 Log_Warning("Threads",
629 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
630 Thread, Thread->TID, Thread->ThreadName
635 // Brains!... You cannot kill
636 case THREAD_STAT_ZOMBIE:
637 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
638 Thread, Thread->TID, Thread->ThreadName);
639 SHORTREL( &glThreadListLock );
640 SHORTREL( &Thread->IsLocked );
644 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
650 Thread->RetStatus = Status;
652 // Don't Zombie if we are being killed because our parent is
655 Thread->Status = THREAD_STAT_DEAD;
656 Threads_AddToDelete( Thread );
658 Thread->Status = THREAD_STAT_ZOMBIE;
660 Threads_Wake( Thread->Parent );
663 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
666 SHORTREL( &glThreadListLock );
667 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
677 * \brief Yield remainder of the current thread's timeslice
679 void Threads_Yield(void)
681 tThread *thread = Proc_GetCurThread();
682 thread->Remaining = 0;
683 //while(thread->Remaining == 0)
688 * \fn void Threads_Sleep(void)
689 * \brief Take the current process off the run queue
691 void Threads_Sleep(void)
693 tThread *cur = Proc_GetCurThread();
696 SHORTLOCK( &glThreadListLock );
698 // Don't sleep if there is a message waiting
699 if( cur->Messages ) {
700 SHORTREL( &glThreadListLock );
704 // Remove us from running queue
706 // Mark thread as sleeping
707 cur->Status = THREAD_STAT_SLEEPING;
709 // Add to Sleeping List (at the top)
710 cur->Next = gSleepingThreads;
711 gSleepingThreads = cur;
714 #if DEBUG_TRACE_STATE
715 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
719 SHORTREL( &glThreadListLock );
721 while(cur->Status != THREAD_STAT_ACTIVE) HALT();
726 * \fn int Threads_Wake( tThread *Thread )
727 * \brief Wakes a sleeping/waiting thread up
728 * \param Thread Thread to wake
729 * \return Boolean Failure (Returns ERRNO)
730 * \warning This should ONLY be called with task switches disabled
732 int Threads_Wake(tThread *Thread)
737 switch(Thread->Status)
739 case THREAD_STAT_ACTIVE:
740 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
743 case THREAD_STAT_SLEEPING:
744 SHORTLOCK( &glThreadListLock );
745 // Remove from sleeping queue
746 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
748 Threads_AddActive( Thread );
750 #if DEBUG_TRACE_STATE
751 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
753 SHORTREL( &glThreadListLock );
756 case THREAD_STAT_SEMAPHORESLEEP: {
758 tThread *th, *prev=NULL;
760 sem = Thread->WaitPointer;
762 SHORTLOCK( &sem->Protector );
764 // Remove from sleeping queue
765 for( th = sem->Waiting; th; prev = th, th = th->Next )
766 if( th == Thread ) break;
770 prev->Next = Thread->Next;
772 sem->Waiting = Thread->Next;
773 if(sem->LastWaiting == Thread)
774 sem->LastWaiting = prev;
779 for( th = sem->Signaling; th; prev = th, th = th->Next )
780 if( th == Thread ) break;
782 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
783 Thread, Thread->TID, Thread->ThreadName,
784 sem, sem->ModName, sem->Name);
789 prev->Next = Thread->Next;
791 sem->Signaling = Thread->Next;
792 if(sem->LastSignaling == Thread)
793 sem->LastSignaling = prev;
796 SHORTLOCK( &glThreadListLock );
797 Threads_AddActive( Thread );
798 SHORTREL( &glThreadListLock );
800 #if DEBUG_TRACE_STATE
801 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
803 SHORTREL( &sem->Protector );
806 case THREAD_STAT_WAITING:
807 Warning("Threads_Wake - Waiting threads are not currently supported");
810 case THREAD_STAT_DEAD:
811 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
815 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
821 * \brief Wake a thread given the TID
822 * \param TID Thread ID to wake
823 * \return Boolean Faulure (errno)
825 int Threads_WakeTID(tTID TID)
827 tThread *thread = Threads_GetThread(TID);
831 ret = Threads_Wake( thread );
832 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
836 void Threads_ToggleTrace(int TID)
838 tThread *thread = Threads_GetThread(TID);
840 thread->bInstrTrace = !thread->bInstrTrace;
844 * \brief Adds a thread to the active queue
846 void Threads_AddActive(tThread *Thread)
848 SHORTLOCK( &glThreadListLock );
850 if( Thread->Status == THREAD_STAT_ACTIVE ) {
851 tThread *cur = Proc_GetCurThread();
852 Log_Warning("Threads", "WTF, CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
853 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
854 SHORTREL( &glThreadListLock );
859 Thread->Status = THREAD_STAT_ACTIVE;
860 // Thread->CurCPU = -1;
861 // Add to active list
863 tThread *tmp, *prev = NULL;
864 #if SCHEDULER_TYPE == SCHED_RR_PRI
865 for( tmp = gaActiveThreads[Thread->Priority]; tmp; prev = tmp, tmp = tmp->Next );
869 gaActiveThreads[Thread->Priority] = Thread;
871 for( tmp = gActiveThreads; tmp; prev = tmp, tmp = tmp->Next );
875 gActiveThreads = Thread;
880 // Update bookkeeping
881 giNumActiveThreads ++;
883 #if SCHEDULER_TYPE == SCHED_LOTTERY
886 // Only change the ticket count if the thread is un-scheduled
887 if(Thread->CurCPU != -1)
890 delta = caiTICKET_COUNTS[ Thread->Priority ];
892 giFreeTickets += delta;
893 # if DEBUG_TRACE_TICKETS
894 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
895 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
902 SHORTREL( &glThreadListLock );
906 * \brief Removes the current thread from the active queue
907 * \warning This should ONLY be called with task switches disabled
908 * \return Current thread pointer
910 tThread *Threads_RemActive(void)
912 tThread *ret = Proc_GetCurThread();
914 SHORTLOCK( &glThreadListLock );
916 // Delete from active queue
917 #if SCHEDULER_TYPE == SCHED_RR_PRI
918 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
920 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
923 SHORTREL( &glThreadListLock );
924 Log_Warning("Threads", "Current thread %p(%i %s) is not on active queue",
925 ret, ret->TID, ret->ThreadName
933 giNumActiveThreads --;
934 // no need to decrement tickets, scheduler did it for us
936 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
937 Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
938 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
941 SHORTREL( &glThreadListLock );
947 * \fn void Threads_SetFaultHandler(Uint Handler)
948 * \brief Sets the signal handler for a signal
950 void Threads_SetFaultHandler(Uint Handler)
952 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
953 Proc_GetCurThread()->FaultHandler = Handler;
957 * \fn void Threads_Fault(int Num)
958 * \brief Calls a fault handler
960 void Threads_Fault(int Num)
962 tThread *thread = Proc_GetCurThread();
966 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
968 switch(thread->FaultHandler)
971 Threads_Kill(thread, -1);
974 case 1: // Dump Core?
975 Threads_Kill(thread, -1);
980 // Double Fault? Oh, F**k
981 if(thread->CurFaultNum != 0) {
982 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
983 Threads_Kill(thread, -1); // For now, just kill
987 thread->CurFaultNum = Num;
989 Proc_CallFaultHandler(thread);
993 * \fn void Threads_SegFault(tVAddr Addr)
994 * \brief Called when a Segment Fault occurs
996 void Threads_SegFault(tVAddr Addr)
998 tThread *cur = Proc_GetCurThread();
999 cur->bInstrTrace = 0;
1000 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
1001 MM_DumpTables(0, KERNEL_BASE);
1003 //Threads_Exit( 0, -1 );
1006 // --- Process Structure Access Functions ---
1007 tPID Threads_GetPID(void)
1009 return Proc_GetCurThread()->TGID;
1011 tTID Threads_GetTID(void)
1013 return Proc_GetCurThread()->TID;
1015 tUID Threads_GetUID(void)
1017 return Proc_GetCurThread()->UID;
1019 tGID Threads_GetGID(void)
1021 return Proc_GetCurThread()->GID;
1024 int Threads_SetUID(Uint *Errno, tUID ID)
1026 tThread *t = Proc_GetCurThread();
1031 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
1036 int Threads_SetGID(Uint *Errno, tGID ID)
1038 tThread *t = Proc_GetCurThread();
1043 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
1049 * \fn void Threads_Dump(void)
1051 void Threads_DumpActive(void)
1054 #if SCHEDULER_TYPE == SCHED_RR_PRI
1058 Log("Active Threads: (%i reported)", giNumActiveThreads);
1060 #if SCHEDULER_TYPE == SCHED_RR_PRI
1061 for( i = 0; i < MIN_PRIORITY+1; i++ )
1063 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
1065 for(thread=gActiveThreads;thread;thread=thread->Next)
1068 Log(" %p %i (%i) - %s (CPU %i)",
1069 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1070 if(thread->Status != THREAD_STAT_ACTIVE)
1071 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
1072 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1073 Log(" KStack 0x%x", thread->KernelStack);
1074 if( thread->bInstrTrace )
1075 Log(" Tracing Enabled");
1076 Proc_DumpThreadCPUState(thread);
1079 #if SCHEDULER_TYPE == SCHED_RR_PRI
1085 * \fn void Threads_Dump(void)
1086 * \brief Dumps a list of currently running threads
1088 void Threads_Dump(void)
1092 Log("--- Thread Dump ---");
1093 Threads_DumpActive();
1095 Log("All Threads:");
1096 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1098 Log(" %p %i (%i) - %s (CPU %i)",
1099 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1100 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1101 switch(thread->Status)
1103 case THREAD_STAT_MUTEXSLEEP:
1104 Log(" Mutex Pointer: %p", thread->WaitPointer);
1106 case THREAD_STAT_SEMAPHORESLEEP:
1107 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1108 Log(" Semaphore Name: %s:%s",
1109 ((tSemaphore*)thread->WaitPointer)->ModName,
1110 ((tSemaphore*)thread->WaitPointer)->Name
1113 case THREAD_STAT_ZOMBIE:
1114 Log(" Return Status: %i", thread->RetStatus);
1118 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1119 Log(" KStack 0x%x", thread->KernelStack);
1120 if( thread->bInstrTrace )
1121 Log(" Tracing Enabled");
1122 Proc_DumpThreadCPUState(thread);
1127 * \brief Gets the next thread to run
1128 * \param CPU Current CPU
1129 * \param Last The thread the CPU was running
1131 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1135 // If this CPU has the lock, we must let it complete
1136 if( CPU_HAS_LOCK( &glThreadListLock ) )
1139 // Don't change threads if the current CPU has switches disabled
1140 if( gaThreads_NoTaskSwitch[CPU] )
1145 SHORTLOCK( &glThreadListLock );
1147 // Clear Delete Queue
1148 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
1149 // DEFINITELY - free() can deadlock in this case
1150 // I'll do it when it becomes an issue
1151 while(gDeleteThreads)
1153 thread = gDeleteThreads->Next;
1154 // Only free if structure is unused
1155 if( !IS_LOCKED(&gDeleteThreads->IsLocked) )
1158 gDeleteThreads->Status = THREAD_STAT_BURIED;
1160 if( IsHeap(gDeleteThreads->ThreadName) )
1161 free(gDeleteThreads->ThreadName);
1162 // Remove from global list
1163 if( gDeleteThreads == gAllThreads )
1164 gAllThreads = gDeleteThreads->GlobalNext;
1166 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
1167 free( gDeleteThreads );
1169 gDeleteThreads = thread;
1172 // Make sure the current (well, old) thread is marked as de-scheduled
1173 if(Last) Last->CurCPU = -1;
1175 // No active threads, just take a nap
1176 if(giNumActiveThreads == 0) {
1177 SHORTREL( &glThreadListLock );
1178 #if DEBUG_TRACE_TICKETS
1179 Log("No active threads");
1184 #if SCHEDULER_TYPE != SCHED_RR_PRI
1185 // Special case: 1 thread
1186 if(giNumActiveThreads == 1) {
1187 if( gActiveThreads->CurCPU == -1 )
1188 gActiveThreads->CurCPU = CPU;
1190 SHORTREL( &glThreadListLock );
1192 if( gActiveThreads->CurCPU == CPU )
1193 return gActiveThreads;
1195 return NULL; // CPU has nothing to do
1199 // Allow the old thread to be scheduled again
1201 if( Last->Status == THREAD_STAT_ACTIVE ) {
1202 #if SCHEDULER_TYPE == SCHED_LOTTERY
1203 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1204 # if DEBUG_TRACE_TICKETS
1205 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1206 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1207 caiTICKET_COUNTS[ Last->Priority ]);
1211 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1213 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1214 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1220 // Lottery Scheduler
1222 #if SCHEDULER_TYPE == SCHED_LOTTERY
1227 for(thread = gActiveThreads; thread; thread = thread->Next) {
1228 if(thread->CurCPU >= 0) continue;
1229 if(thread->Status != THREAD_STAT_ACTIVE)
1230 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1231 thread, thread->TID, thread->ThreadName, thread->Status);
1232 if(thread->Next == thread) {
1233 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1234 thread, thread->TID, thread->ThreadName, thread->Status);
1236 number += caiTICKET_COUNTS[ thread->Priority ];
1238 if(number != giFreeTickets) {
1239 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1240 giFreeTickets, number, CPU);
1244 // No free tickets (all tasks delegated to cores)
1245 if( giFreeTickets == 0 ) {
1246 SHORTREL(&glThreadListLock);
1250 // Get the ticket number
1251 ticket = number = rand() % giFreeTickets;
1253 // Find the next thread
1254 for(thread=gActiveThreads;thread;thread=thread->Next)
1256 if(thread->CurCPU >= 0) continue;
1257 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1258 number -= caiTICKET_COUNTS[ thread->Priority ];
1261 // If we didn't find a thread, something went wrong
1265 for(thread=gActiveThreads;thread;thread=thread->Next) {
1266 if(thread->CurCPU >= 0) continue;
1267 number += caiTICKET_COUNTS[ thread->Priority ];
1269 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1270 giFreeTickets, number);
1273 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1274 # if DEBUG_TRACE_TICKETS
1275 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1276 CPU, thread, thread->TID, thread->ThreadName,
1277 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1282 // Priority based round robin scheduler
1284 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1287 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1289 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1291 if( thread->CurCPU == -1 ) break;
1293 // If we fall onto the same queue again, special handling is
1295 if( Last && i == Last->Priority ) {
1296 tThread *savedThread = thread;
1298 // Find the next unscheduled thread in the list
1299 for( thread = Last->Next; thread; thread = thread->Next )
1301 if( thread->CurCPU == -1 ) break;
1303 // If we don't find anything after, just use the one
1305 if( !thread ) thread = savedThread;
1307 // Found a thread? Schedule it!
1313 SHORTREL(&glThreadListLock);
1317 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1319 // Find the next unscheduled thread in the list
1320 for( thread = Last->Next; thread; thread = thread->Next )
1322 if( thread->CurCPU == -1 ) break;
1324 // If we don't find anything after, search from the beginning
1327 for(thread = gActiveThreads; thread; thread = thread->Next)
1329 if( thread->CurCPU == -1 ) break;
1335 SHORTREL(&glThreadListLock);
1340 # error "Unimplemented scheduling algorithm"
1343 // Make the new thread non-schedulable
1344 thread->CurCPU = CPU;
1346 SHORTREL( &glThreadListLock );
1351 // Acquire mutex (see mutex.h for documentation)
1352 int Mutex_Acquire(tMutex *Mutex)
1354 tThread *us = Proc_GetCurThread();
1357 SHORTLOCK( &Mutex->Protector );
1359 //Log("Mutex_Acquire: (%p)", Mutex);
1361 // Check if the lock is already held
1362 if( Mutex->Owner ) {
1363 SHORTLOCK( &glThreadListLock );
1364 // - Remove from active list
1365 us = Threads_RemActive();
1367 // - Mark as sleeping
1368 us->Status = THREAD_STAT_MUTEXSLEEP;
1369 us->WaitPointer = Mutex;
1372 if(Mutex->LastWaiting) {
1373 Mutex->LastWaiting->Next = us;
1374 Mutex->LastWaiting = us;
1377 Mutex->Waiting = us;
1378 Mutex->LastWaiting = us;
1381 #if DEBUG_TRACE_STATE
1382 Log("%p (%i %s) waiting on mutex %p",
1383 us, us->TID, us->ThreadName, Mutex);
1390 for( t = Mutex->Waiting; t; t = t->Next, i++ )
1391 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1392 t, t->TID, t->ThreadName);
1396 SHORTREL( &glThreadListLock );
1397 SHORTREL( &Mutex->Protector );
1398 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1399 // We're only woken when we get the lock
1400 us->WaitPointer = NULL;
1402 // Ooh, let's take it!
1405 SHORTREL( &Mutex->Protector );
1409 extern tMutex glPhysAlloc;
1410 if( Mutex != &glPhysAlloc )
1411 LogF("Mutex %p taken by %i %p\n", Mutex, us->TID, __builtin_return_address(0));
1418 void Mutex_Release(tMutex *Mutex)
1420 SHORTLOCK( &Mutex->Protector );
1421 //Log("Mutex_Release: (%p)", Mutex);
1422 if( Mutex->Waiting ) {
1423 Mutex->Owner = Mutex->Waiting; // Set owner
1424 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1425 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1426 // 2010-10-02 21:50 - Comemerating the death of the longest single
1427 // blocker in the Acess2 history. REMEMBER TO
1428 // FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1429 if( Mutex->LastWaiting == Mutex->Owner )
1430 Mutex->LastWaiting = NULL;
1433 SHORTLOCK( &glThreadListLock );
1434 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1435 Threads_AddActive(Mutex->Owner);
1436 SHORTREL( &glThreadListLock );
1439 Mutex->Owner = NULL;
1441 SHORTREL( &Mutex->Protector );
1444 extern tMutex glPhysAlloc;
1445 if( Mutex != &glPhysAlloc )
1446 LogF("Mutex %p released by %i %p\n", Mutex, Threads_GetTID(), __builtin_return_address(0));
1450 // Check if a mutex is locked
1451 int Mutex_IsLocked(tMutex *Mutex)
1453 return Mutex->Owner != NULL;
1457 // Initialise a semaphore
1459 void Semaphore_Init(tSemaphore *Sem, int Value, int MaxValue, const char *Module, const char *Name)
1461 memset(Sem, 0, sizeof(tSemaphore));
1463 Sem->ModName = Module;
1465 Sem->MaxValue = MaxValue;
1468 // Wait for items to be avaliable
1470 int Semaphore_Wait(tSemaphore *Sem, int MaxToTake)
1474 if( MaxToTake < 0 ) {
1475 Log_Warning("Threads", "Semaphore_Wait: User bug - MaxToTake(%i) < 0, Sem=%p(%s)",
1476 MaxToTake, Sem, Sem->Name);
1479 SHORTLOCK( &Sem->Protector );
1481 // Check if there's already items avaliable
1482 if( Sem->Value > 0 ) {
1483 // Take what we need
1484 if( MaxToTake && Sem->Value > MaxToTake )
1488 Sem->Value -= taken;
1492 SHORTLOCK( &glThreadListLock );
1494 // - Remove from active list
1495 us = Threads_RemActive();
1497 // - Mark as sleeping
1498 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1499 us->WaitPointer = Sem;
1500 us->RetStatus = MaxToTake; // Use RetStatus as a temp variable
1503 if(Sem->LastWaiting) {
1504 Sem->LastWaiting->Next = us;
1505 Sem->LastWaiting = us;
1509 Sem->LastWaiting = us;
1512 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1513 Log("%p (%i %s) waiting on semaphore %p %s:%s",
1514 us, us->TID, us->ThreadName,
1515 Sem, Sem->ModName, Sem->Name);
1518 SHORTREL( &Sem->Protector ); // Release first to make sure it is released
1519 SHORTREL( &glThreadListLock );
1520 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1521 // We're only woken when there's something avaliable (or a signal arrives)
1522 us->WaitPointer = NULL;
1524 taken = us->RetStatus;
1526 // Get the lock again
1527 SHORTLOCK( &Sem->Protector );
1530 // While there is space, and there are thread waiting
1531 // wake the first thread and give it what it wants (or what's left)
1532 while( (Sem->MaxValue == 0 || Sem->Value < Sem->MaxValue) && Sem->Signaling )
1535 tThread *toWake = Sem->Signaling;
1537 Sem->Signaling = Sem->Signaling->Next;
1538 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1539 if( Sem->Signaling == NULL )
1540 Sem->LastSignaling = NULL;
1542 // Figure out how much to give
1543 if( toWake->RetStatus && Sem->Value + toWake->RetStatus < Sem->MaxValue )
1544 given = toWake->RetStatus;
1546 given = Sem->MaxValue - Sem->Value;
1547 Sem->Value -= given;
1550 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1551 Log("%p (%i %s) woken by wait on %p %s:%s",
1552 toWake, toWake->TID, toWake->ThreadName,
1553 Sem, Sem->ModName, Sem->Name);
1556 // Save the number we gave to the thread's status
1557 toWake->RetStatus = given;
1560 SHORTLOCK( &glThreadListLock );
1561 if( toWake->Status != THREAD_STAT_ACTIVE )
1562 Threads_AddActive(toWake);
1563 SHORTREL( &glThreadListLock );
1565 SHORTREL( &Sem->Protector );
1571 // Add items to a semaphore
1573 int Semaphore_Signal(tSemaphore *Sem, int AmmountToAdd)
1578 if( AmmountToAdd < 0 ) {
1579 Log_Warning("Threads", "Semaphore_Signal: User bug - AmmountToAdd(%i) < 0, Sem=%p(%s)",
1580 AmmountToAdd, Sem, Sem->Name);
1582 SHORTLOCK( &Sem->Protector );
1584 // Check if we have to block
1585 if( Sem->MaxValue && Sem->Value == Sem->MaxValue )
1589 Log_Debug("Threads", "Semaphore_Signal: IDLE Sem = %s:%s", Sem->ModName, Sem->Name);
1590 Log_Debug("Threads", "Semaphore_Signal: Sem->Value(%i) == Sem->MaxValue(%i)", Sem->Value, Sem->MaxValue);
1593 SHORTLOCK( &glThreadListLock );
1594 // - Remove from active list
1595 us = Threads_RemActive();
1597 // - Mark as sleeping
1598 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1599 us->WaitPointer = Sem;
1600 us->RetStatus = AmmountToAdd; // Use RetStatus as a temp variable
1603 if(Sem->LastSignaling) {
1604 Sem->LastSignaling->Next = us;
1605 Sem->LastSignaling = us;
1608 Sem->Signaling = us;
1609 Sem->LastSignaling = us;
1612 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1613 Log("%p (%i %s) signaling semaphore %p %s:%s",
1614 us, us->TID, us->ThreadName,
1615 Sem, Sem->ModName, Sem->Name);
1618 SHORTREL( &glThreadListLock );
1619 SHORTREL( &Sem->Protector );
1620 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1621 // We're only woken when there's something avaliable
1622 us->WaitPointer = NULL;
1624 added = us->RetStatus;
1626 // Get the lock again
1627 SHORTLOCK( &Sem->Protector );
1632 // Figure out how much we need to take off
1633 if( Sem->MaxValue && Sem->Value + AmmountToAdd > Sem->MaxValue)
1634 added = Sem->MaxValue - Sem->Value;
1636 added = AmmountToAdd;
1637 Sem->Value += added;
1640 // While there are items avaliable, and there are thread waiting
1641 // wake the first thread and give it what it wants (or what's left)
1642 while( Sem->Value && Sem->Waiting )
1644 tThread *toWake = Sem->Waiting;
1646 // Remove thread from list (double ended, so clear LastWaiting if needed)
1647 Sem->Waiting = Sem->Waiting->Next;
1648 if( Sem->Waiting == NULL )
1649 Sem->LastWaiting = NULL;
1651 // Figure out how much to give to woken thread
1652 // - Requested count is stored in ->RetStatus
1653 if( toWake->RetStatus && Sem->Value > toWake->RetStatus )
1654 given = toWake->RetStatus;
1657 Sem->Value -= given;
1659 // Save the number we gave to the thread's status
1660 toWake->RetStatus = given;
1662 if(toWake->bInstrTrace)
1663 Log("%s(%i) given %i from %p", toWake->ThreadName, toWake->TID, given, Sem);
1664 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1665 Log("%p (%i %s) woken by signal on %p %s:%s",
1666 toWake, toWake->TID, toWake->ThreadName,
1667 Sem, Sem->ModName, Sem->Name);
1671 SHORTLOCK( &glThreadListLock );
1672 if( toWake->Status != THREAD_STAT_ACTIVE )
1673 Threads_AddActive(toWake);
1675 Warning("Thread %p (%i %s) is already awake", toWake, toWake->TID, toWake->ThreadName);
1676 SHORTREL( &glThreadListLock );
1678 SHORTREL( &Sem->Protector );
1684 // Get the current value of a semaphore
1686 int Semaphore_GetValue(tSemaphore *Sem)
1692 EXPORT(Threads_GetUID);
1693 EXPORT(Threads_GetGID);
1694 EXPORT(Mutex_Acquire);
1695 EXPORT(Mutex_Release);
1696 EXPORT(Mutex_IsLocked);
1697 EXPORT(Semaphore_Init);
1698 EXPORT(Semaphore_Wait);
1699 EXPORT(Semaphore_Signal);