4 * - Common Thread Control
8 #include <threads_int.h>
11 #include <semaphore.h>
14 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
15 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
19 #define SCHED_LOTTERY 1 // Lottery scheduler
20 #define SCHED_RR_SIM 2 // Single Queue Round Robin
21 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
23 #define SCHEDULER_TYPE SCHED_RR_PRI
26 #define DEFAULT_QUANTUM 5
27 #define DEFAULT_PRIORITY 5
28 #define MIN_PRIORITY 10
29 const enum eConfigTypes cCONFIG_TYPES[NUM_CFG_ENTRIES] = {
30 CFGT_HEAPSTR, // e.g. CFG_VFS_CWD
31 CFGT_INT, // e.g. CFG_VFS_MAXFILES
38 void Threads_Init(void);
40 void Threads_Delete(tThread *Thread);
41 int Threads_SetName(const char *NewName);
43 char *Threads_GetName(int ID);
45 void Threads_SetPriority(tThread *Thread, int Pri);
46 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
47 int Threads_WaitTID(int TID, int *status);
48 tThread *Threads_GetThread(Uint TID);
50 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread);
52 void Threads_Exit(int TID, int Status);
53 void Threads_Kill(tThread *Thread, int Status);
54 void Threads_Yield(void);
55 void Threads_Sleep(void);
56 int Threads_Wake(tThread *Thread);
57 void Threads_AddActive(tThread *Thread);
58 tThread *Threads_RemActive(void);
60 void Threads_ToggleTrace(int TID);
61 void Threads_Fault(int Num);
62 void Threads_SegFault(tVAddr Addr);
64 int Threads_GetPID(void);
65 int Threads_GetTID(void);
66 tUID Threads_GetUID(void);
67 tGID Threads_GetGID(void);
68 int Threads_SetUID(Uint *Errno, tUID ID);
69 int Threads_SetGID(Uint *Errno, tUID ID);
71 void Threads_Dump(void);
72 void Threads_DumpActive(void);
76 // Only used for the core kernel
77 tThread gThreadZero = {
78 .Status = THREAD_STAT_ACTIVE, // Status
79 .ThreadName = (char*)"ThreadZero", // Name
80 .Quantum = DEFAULT_QUANTUM, // Default Quantum
81 .Remaining = DEFAULT_QUANTUM, // Current Quantum
82 .Priority = DEFAULT_PRIORITY // Number of tickets
86 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
87 // --- Current State ---
88 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
89 volatile Uint giNextTID = 1; // Next TID to allocate
90 // --- Thread Lists ---
91 tThread *gAllThreads = NULL; // All allocated threads
92 tThread *gSleepingThreads = NULL; // Sleeping Threads
93 int giNumCPUs = 1; // Number of CPUs
94 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
95 // --- Scheduler Types ---
96 #if SCHEDULER_TYPE == SCHED_LOTTERY
97 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
98 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
99 tThread *gActiveThreads = NULL; // Currently Running Threads
100 #elif SCHEDULER_TYPE == SCHED_RR_SIM
101 tThread *gActiveThreads = NULL; // Currently Running Threads
102 #elif SCHEDULER_TYPE == SCHED_RR_PRI
103 tThread *gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
105 # error "Unkown scheduler type"
110 * \fn void Threads_Init(void)
111 * \brief Initialse the thread list
113 void Threads_Init(void)
117 Log_Debug("Threads", "Offsets of tThread");
118 Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
119 Log_Debug("Threads", ".KernelStack = %i", offsetof(tThread, KernelStack));
121 // Create Initial Task
122 #if SCHEDULER_TYPE == SCHED_RR_PRI
123 gaActiveThreads[gThreadZero.Priority] = &gThreadZero;
125 gActiveThreads = &gThreadZero;
128 gAllThreads = &gThreadZero;
129 giNumActiveThreads = 1;
134 void Threads_Delete(tThread *Thread)
137 Thread->Status = THREAD_STAT_BURIED;
140 if( IsHeap(Thread->ThreadName) )
141 free(Thread->ThreadName);
143 // Remove from global list
144 // TODO: Lock this too
145 if( Thread == gAllThreads )
146 gAllThreads = Thread->GlobalNext;
148 Thread->GlobalPrev->GlobalNext = Thread->GlobalNext;
154 * \fn void Threads_SetName(const char *NewName)
155 * \brief Sets the current thread's name
156 * \param NewName New name for the thread
157 * \return Boolean Failure
159 int Threads_SetName(const char *NewName)
161 tThread *cur = Proc_GetCurThread();
162 char *oldname = cur->ThreadName;
164 // NOTE: There is a possibility of non-thread safety here
165 // A thread could read the current name pointer before it is zeroed
167 cur->ThreadName = NULL;
169 if( IsHeap(oldname) ) free( oldname );
171 cur->ThreadName = strdup(NewName);
176 * \fn char *Threads_GetName(int ID)
177 * \brief Gets a thread's name
178 * \param ID Thread ID (-1 indicates current thread)
179 * \return Pointer to name
180 * \retval NULL Failure
182 char *Threads_GetName(tTID ID)
185 return Proc_GetCurThread()->ThreadName;
187 return Threads_GetThread(ID)->ThreadName;
191 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
192 * \brief Sets the priority of a task
193 * \param Thread Thread to update ticket count (NULL means current thread)
194 * \param Pri New priority
196 void Threads_SetPriority(tThread *Thread, int Pri)
198 // Get current thread
199 if(Thread == NULL) Thread = Proc_GetCurThread();
201 // - If < 0, set to lowest priority
202 // - Minumum priority is actualy a high number, 0 is highest
203 if(Pri < 0) Pri = MIN_PRIORITY;
204 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
206 // Do we actually have to do anything?
207 if( Pri == Thread->Priority ) return;
209 #if SCHEDULER_TYPE == SCHED_RR_PRI
210 SHORTLOCK( &glThreadListLock );
211 // Remove from old priority
212 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
214 Thread->Next = gaActiveThreads[Pri];
215 gaActiveThreads[Pri] = Thread;
216 Thread->Priority = Pri;
217 SHORTREL( &glThreadListLock );
219 // If this isn't the current thread, we need to lock
220 if( Thread != Proc_GetCurThread() )
222 SHORTLOCK( &glThreadListLock );
224 #if SCHEDULER_TYPE == SCHED_LOTTERY
225 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
226 # if DEBUG_TRACE_TICKETS
227 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
229 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
232 Thread->Priority = Pri;
233 SHORTREL( &glThreadListLock );
236 Thread->Priority = Pri;
239 #if DEBUG_TRACE_STATE
240 Log("Threads_SetPriority: %p(%i %s) pri set %i",
241 Thread, Thread->TID, Thread->ThreadName,
247 * \brief Clone the TCB of the current thread
248 * \param Flags Flags for something... (What is this for?)
250 tThread *Threads_CloneTCB(Uint Flags)
254 cur = Proc_GetCurThread();
256 // Allocate and duplicate
257 new = malloc(sizeof(tThread));
258 if(new == NULL) { errno = -ENOMEM; return NULL; }
259 memcpy(new, cur, sizeof(tThread));
263 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
264 new->Status = THREAD_STAT_PREINIT;
268 new->TID = giNextTID++;
270 new->bInstrTrace = 0;
273 new->ThreadName = strdup(cur->ThreadName);
275 // Set Thread Group ID (PID)
277 new->TGID = new->TID;
279 new->TGID = cur->TGID;
281 // Messages are not inherited
282 new->Messages = NULL;
283 new->LastMessage = NULL;
286 new->Remaining = new->Quantum = cur->Quantum;
287 new->Priority = cur->Priority;
289 // Set Signal Handlers
290 new->CurFaultNum = 0;
291 new->FaultHandler = cur->FaultHandler;
293 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
295 switch(cCONFIG_TYPES[i])
298 new->Config[i] = cur->Config[i];
302 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
309 // Maintain a global list of threads
310 SHORTLOCK( &glThreadListLock );
311 new->GlobalPrev = NULL; // Protect against bugs
312 new->GlobalNext = gAllThreads;
313 gAllThreads->GlobalPrev = new;
315 SHORTREL( &glThreadListLock );
321 * \brief Clone the TCB of the kernel thread
323 tThread *Threads_CloneThreadZero(void)
328 // Allocate and duplicate
329 new = malloc(sizeof(tThread));
333 memcpy(new, &gThreadZero, sizeof(tThread));
337 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
338 new->Status = THREAD_STAT_PREINIT;
342 new->TID = giNextTID++;
346 new->ThreadName = NULL;
348 // Messages are not inherited
349 new->Messages = NULL;
350 new->LastMessage = NULL;
353 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
354 new->Priority = DEFAULT_PRIORITY;
355 new->bInstrTrace = 0;
357 // Set Signal Handlers
358 new->CurFaultNum = 0;
359 new->FaultHandler = 0;
361 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
366 // Maintain a global list of threads
367 SHORTLOCK( &glThreadListLock );
368 new->GlobalPrev = NULL; // Protect against bugs
369 new->GlobalNext = gAllThreads;
370 gAllThreads->GlobalPrev = new;
372 SHORTREL( &glThreadListLock );
378 * \brief Get a configuration pointer from the Per-Thread data area
379 * \param ID Config slot ID
380 * \return Pointer at ID
382 Uint *Threads_GetCfgPtr(int ID)
384 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
385 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
389 return &Proc_GetCurThread()->Config[ID];
393 * \brief Wait for a task to change state
394 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
395 * \param Status Thread return status
396 * \return TID of child that changed state
398 tTID Threads_WaitTID(int TID, int *Status)
402 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
406 // Any peer/child thread
408 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
414 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
420 tThread *t = Threads_GetThread(TID);
421 int initStatus = t->Status;
424 // Wait for the thread to die!
425 if(initStatus != THREAD_STAT_ZOMBIE) {
426 // TODO: Handle child also being suspended if wanted
427 while(t->Status != THREAD_STAT_ZOMBIE) {
429 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
430 Threads_GetTID(), t->TID, t->Status);
435 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
436 Threads_GetTID(), t->TID, t->Status);
440 case THREAD_STAT_ZOMBIE:
442 t->Status = THREAD_STAT_DEAD;
443 // TODO: Child return value?
444 if(Status) *Status = t->RetStatus;
445 // add to delete queue
449 if(Status) *Status = -1;
459 * \brief Gets a thread given its TID
460 * \param TID Thread ID
461 * \return Thread pointer
463 tThread *Threads_GetThread(Uint TID)
467 // Search global list
468 for(thread = gAllThreads;
470 thread = thread->GlobalNext)
472 if(thread->TID == TID)
476 Log("Unable to find TID %i on main list\n", TID);
482 * \brief Deletes an entry from a list
483 * \param List Pointer to the list head
484 * \param Thread Thread to find
487 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
489 tThread *ret, *prev = NULL;
492 ret && ret != Thread;
493 prev = ret, ret = ret->Next
496 // Is the thread on the list
498 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
503 *List = Thread->Next;
504 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
507 prev->Next = Thread->Next;
508 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
515 * \brief Exit the current process (or another?)
516 * \param TID Thread ID to kill
517 * \param Status Exit status
519 void Threads_Exit(int TID, int Status)
522 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
524 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
526 // Halt forever, just in case
531 * \fn void Threads_Kill(tThread *Thread, int Status)
532 * \brief Kill a thread
533 * \param Thread Thread to kill
534 * \param Status Status code to return to the parent
536 void Threads_Kill(tThread *Thread, int Status)
539 int isCurThread = Thread == Proc_GetCurThread();
541 // TODO: Disown all children?
545 // TODO: I should keep a .Children list
546 for(child = gAllThreads;
548 child = child->GlobalNext)
550 if(child->Parent == Thread)
551 child->Parent = &gThreadZero;
556 ///\note Double lock is needed due to overlap of lock areas
558 // Lock thread (stop us recieving messages)
559 SHORTLOCK( &Thread->IsLocked );
561 // Clear Message Queue
562 while( Thread->Messages )
564 msg = Thread->Messages->Next;
565 free( Thread->Messages );
566 Thread->Messages = msg;
570 SHORTLOCK( &glThreadListLock );
572 switch(Thread->Status)
574 case THREAD_STAT_PREINIT: // Only on main list
577 // Currently active thread
578 case THREAD_STAT_ACTIVE:
579 #if SCHEDULER_TYPE == SCHED_RR_PRI
580 if( Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
582 if( Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
585 // Ensure that we are not rescheduled
586 Thread->Remaining = 0; // Clear Remaining Quantum
587 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
589 // Update bookkeeping
590 giNumActiveThreads --;
591 #if SCHEDULER_TYPE == SCHED_LOTTERY
592 if( Thread != Proc_GetCurThread() )
593 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
598 Log_Warning("Threads",
599 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
600 Thread, Thread->TID, Thread->ThreadName
604 // Kill it while it sleeps!
605 case THREAD_STAT_SLEEPING:
606 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
608 Log_Warning("Threads",
609 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
610 Thread, Thread->TID, Thread->ThreadName
615 // Brains!... You cannot kill something that is already dead
616 case THREAD_STAT_ZOMBIE:
617 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
618 Thread, Thread->TID, Thread->ThreadName);
619 SHORTREL( &glThreadListLock );
620 SHORTREL( &Thread->IsLocked );
624 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
630 Thread->RetStatus = Status;
632 SHORTREL( &Thread->IsLocked );
633 // Clear out process state
634 Proc_ClearThread(Thread);
636 Thread->Status = THREAD_STAT_ZOMBIE;
637 SHORTREL( &glThreadListLock );
638 // TODO: Send something like SIGCHLD
639 Threads_Wake( Thread->Parent );
641 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
652 * \brief Yield remainder of the current thread's timeslice
654 void Threads_Yield(void)
656 // Log("Threads_Yield: by %p", __builtin_return_address(0));
661 * \fn void Threads_Sleep(void)
662 * \brief Take the current process off the run queue
664 void Threads_Sleep(void)
666 tThread *cur = Proc_GetCurThread();
669 SHORTLOCK( &glThreadListLock );
671 // Don't sleep if there is a message waiting
672 if( cur->Messages ) {
673 SHORTREL( &glThreadListLock );
677 // Remove us from running queue
679 // Mark thread as sleeping
680 cur->Status = THREAD_STAT_SLEEPING;
682 // Add to Sleeping List (at the top)
683 cur->Next = gSleepingThreads;
684 gSleepingThreads = cur;
687 #if DEBUG_TRACE_STATE
688 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
692 SHORTREL( &glThreadListLock );
694 while(cur->Status != THREAD_STAT_ACTIVE) {
696 if( cur->Status != THREAD_STAT_ACTIVE )
697 Log("%i - Huh? why am I up? zzzz...", cur->TID);
703 * \brief Wakes a sleeping/waiting thread up
704 * \param Thread Thread to wake
705 * \return Boolean Failure (Returns ERRNO)
706 * \warning This should ONLY be called with task switches disabled
708 int Threads_Wake(tThread *Thread)
713 switch(Thread->Status)
715 case THREAD_STAT_ACTIVE:
716 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
719 case THREAD_STAT_SLEEPING:
720 SHORTLOCK( &glThreadListLock );
721 // Remove from sleeping queue
722 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
724 SHORTREL( &glThreadListLock );
725 Threads_AddActive( Thread );
727 #if DEBUG_TRACE_STATE
728 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
732 case THREAD_STAT_SEMAPHORESLEEP: {
734 tThread *th, *prev=NULL;
736 sem = Thread->WaitPointer;
738 SHORTLOCK( &sem->Protector );
740 // Remove from sleeping queue
741 for( th = sem->Waiting; th; prev = th, th = th->Next )
742 if( th == Thread ) break;
746 prev->Next = Thread->Next;
748 sem->Waiting = Thread->Next;
749 if(sem->LastWaiting == Thread)
750 sem->LastWaiting = prev;
755 for( th = sem->Signaling; th; prev = th, th = th->Next )
756 if( th == Thread ) break;
758 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
759 Thread, Thread->TID, Thread->ThreadName,
760 sem, sem->ModName, sem->Name);
765 prev->Next = Thread->Next;
767 sem->Signaling = Thread->Next;
768 if(sem->LastSignaling == Thread)
769 sem->LastSignaling = prev;
772 Thread->RetStatus = 0; // It didn't get anything
773 Threads_AddActive( Thread );
775 #if DEBUG_TRACE_STATE
776 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
778 SHORTREL( &sem->Protector );
781 case THREAD_STAT_WAITING:
782 Warning("Threads_Wake - Waiting threads are not currently supported");
785 case THREAD_STAT_DEAD:
786 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
790 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
796 * \brief Wake a thread given the TID
797 * \param TID Thread ID to wake
798 * \return Boolean Faulure (errno)
800 int Threads_WakeTID(tTID TID)
802 tThread *thread = Threads_GetThread(TID);
806 ret = Threads_Wake( thread );
807 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
811 void Threads_ToggleTrace(int TID)
813 tThread *thread = Threads_GetThread(TID);
815 thread->bInstrTrace = !thread->bInstrTrace;
819 * \brief Adds a thread to the active queue
821 void Threads_AddActive(tThread *Thread)
823 SHORTLOCK( &glThreadListLock );
825 if( Thread->Status == THREAD_STAT_ACTIVE ) {
826 tThread *cur = Proc_GetCurThread();
827 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
828 __builtin_return_address(0),
829 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
830 SHORTREL( &glThreadListLock );
835 Thread->Status = THREAD_STAT_ACTIVE;
836 // Thread->CurCPU = -1;
837 // Add to active list
839 tThread *tmp, *prev = NULL;
840 #if SCHEDULER_TYPE == SCHED_RR_PRI
841 for( tmp = gaActiveThreads[Thread->Priority]; tmp; prev = tmp, tmp = tmp->Next );
845 gaActiveThreads[Thread->Priority] = Thread;
847 for( tmp = gActiveThreads; tmp; prev = tmp, tmp = tmp->Next );
851 gActiveThreads = Thread;
856 // Update bookkeeping
857 giNumActiveThreads ++;
859 #if SCHEDULER_TYPE == SCHED_LOTTERY
862 // Only change the ticket count if the thread is un-scheduled
863 if(Thread->CurCPU != -1)
866 delta = caiTICKET_COUNTS[ Thread->Priority ];
868 giFreeTickets += delta;
869 # if DEBUG_TRACE_TICKETS
870 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
871 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
878 SHORTREL( &glThreadListLock );
882 * \brief Removes the current thread from the active queue
883 * \warning This should ONLY be called with the lock held
884 * \return Current thread pointer
886 tThread *Threads_RemActive(void)
888 tThread *ret = Proc_GetCurThread();
890 if( !IS_LOCKED(&glThreadListLock) ) {
891 Log_KernelPanic("Threads", "Threads_RemActive called without lock held");
895 // Delete from active queue
896 #if SCHEDULER_TYPE == SCHED_RR_PRI
897 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
899 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
902 SHORTREL( &glThreadListLock );
903 Log_Warning("Threads", "Current thread %p(%i %s) is not on active queue",
904 ret, ret->TID, ret->ThreadName
912 giNumActiveThreads --;
913 // no need to decrement tickets, scheduler did it for us
915 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
916 Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
917 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
924 * \fn void Threads_SetFaultHandler(Uint Handler)
925 * \brief Sets the signal handler for a signal
927 void Threads_SetFaultHandler(Uint Handler)
929 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
930 Proc_GetCurThread()->FaultHandler = Handler;
934 * \fn void Threads_Fault(int Num)
935 * \brief Calls a fault handler
937 void Threads_Fault(int Num)
939 tThread *thread = Proc_GetCurThread();
943 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
945 switch(thread->FaultHandler)
948 Threads_Kill(thread, -1);
951 case 1: // Dump Core?
952 Threads_Kill(thread, -1);
957 // Double Fault? Oh, F**k
958 if(thread->CurFaultNum != 0) {
959 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
960 Threads_Kill(thread, -1); // For now, just kill
964 thread->CurFaultNum = Num;
966 Proc_CallFaultHandler(thread);
970 * \fn void Threads_SegFault(tVAddr Addr)
971 * \brief Called when a Segment Fault occurs
973 void Threads_SegFault(tVAddr Addr)
975 tThread *cur = Proc_GetCurThread();
976 cur->bInstrTrace = 0;
977 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
978 MM_DumpTables(0, USER_MAX);
980 //Threads_Exit( 0, -1 );
983 // --- Process Structure Access Functions ---
984 tPID Threads_GetPID(void)
986 return Proc_GetCurThread()->TGID;
988 tTID Threads_GetTID(void)
990 return Proc_GetCurThread()->TID;
992 tUID Threads_GetUID(void)
994 return Proc_GetCurThread()->UID;
996 tGID Threads_GetGID(void)
998 return Proc_GetCurThread()->GID;
1001 int Threads_SetUID(Uint *Errno, tUID ID)
1003 tThread *t = Proc_GetCurThread();
1008 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
1013 int Threads_SetGID(Uint *Errno, tGID ID)
1015 tThread *t = Proc_GetCurThread();
1020 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
1026 * \fn void Threads_Dump(void)
1028 void Threads_DumpActive(void)
1031 #if SCHEDULER_TYPE == SCHED_RR_PRI
1035 Log("Active Threads: (%i reported)", giNumActiveThreads);
1037 #if SCHEDULER_TYPE == SCHED_RR_PRI
1038 for( i = 0; i < MIN_PRIORITY+1; i++ )
1040 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
1042 for(thread=gActiveThreads;thread;thread=thread->Next)
1045 Log(" %p %i (%i) - %s (CPU %i)",
1046 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1047 if(thread->Status != THREAD_STAT_ACTIVE)
1048 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
1049 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1050 Log(" KStack 0x%x", thread->KernelStack);
1051 if( thread->bInstrTrace )
1052 Log(" Tracing Enabled");
1053 Proc_DumpThreadCPUState(thread);
1056 #if SCHEDULER_TYPE == SCHED_RR_PRI
1062 * \fn void Threads_Dump(void)
1063 * \brief Dumps a list of currently running threads
1065 void Threads_Dump(void)
1069 Log("--- Thread Dump ---");
1070 Threads_DumpActive();
1072 Log("All Threads:");
1073 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1075 Log(" %p %i (%i) - %s (CPU %i)",
1076 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1077 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1078 switch(thread->Status)
1080 case THREAD_STAT_MUTEXSLEEP:
1081 Log(" Mutex Pointer: %p", thread->WaitPointer);
1083 case THREAD_STAT_SEMAPHORESLEEP:
1084 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1085 Log(" Semaphore Name: %s:%s",
1086 ((tSemaphore*)thread->WaitPointer)->ModName,
1087 ((tSemaphore*)thread->WaitPointer)->Name
1090 case THREAD_STAT_ZOMBIE:
1091 Log(" Return Status: %i", thread->RetStatus);
1095 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1096 Log(" KStack 0x%x", thread->KernelStack);
1097 if( thread->bInstrTrace )
1098 Log(" Tracing Enabled");
1099 Proc_DumpThreadCPUState(thread);
1104 * \brief Gets the next thread to run
1105 * \param CPU Current CPU
1106 * \param Last The thread the CPU was running
1108 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1112 // If this CPU has the lock, we must let it complete
1113 if( CPU_HAS_LOCK( &glThreadListLock ) )
1116 // Don't change threads if the current CPU has switches disabled
1117 if( gaThreads_NoTaskSwitch[CPU] )
1121 SHORTLOCK( &glThreadListLock );
1123 // Make sure the current (well, old) thread is marked as de-scheduled
1124 if(Last) Last->CurCPU = -1;
1126 // No active threads, just take a nap
1127 if(giNumActiveThreads == 0) {
1128 SHORTREL( &glThreadListLock );
1129 #if DEBUG_TRACE_TICKETS
1130 Log("No active threads");
1135 #if SCHEDULER_TYPE != SCHED_RR_PRI
1136 // Special case: 1 thread
1137 if(giNumActiveThreads == 1) {
1138 if( gActiveThreads->CurCPU == -1 )
1139 gActiveThreads->CurCPU = CPU;
1141 SHORTREL( &glThreadListLock );
1143 if( gActiveThreads->CurCPU == CPU )
1144 return gActiveThreads;
1146 return NULL; // CPU has nothing to do
1150 // Allow the old thread to be scheduled again
1152 if( Last->Status == THREAD_STAT_ACTIVE ) {
1153 #if SCHEDULER_TYPE == SCHED_LOTTERY
1154 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1155 # if DEBUG_TRACE_TICKETS
1156 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1157 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1158 caiTICKET_COUNTS[ Last->Priority ]);
1162 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1164 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1165 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1171 // Lottery Scheduler
1173 #if SCHEDULER_TYPE == SCHED_LOTTERY
1178 for(thread = gActiveThreads; thread; thread = thread->Next) {
1179 if(thread->CurCPU >= 0) continue;
1180 if(thread->Status != THREAD_STAT_ACTIVE)
1181 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1182 thread, thread->TID, thread->ThreadName, thread->Status);
1183 if(thread->Next == thread) {
1184 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1185 thread, thread->TID, thread->ThreadName, thread->Status);
1187 number += caiTICKET_COUNTS[ thread->Priority ];
1189 if(number != giFreeTickets) {
1190 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1191 giFreeTickets, number, CPU);
1195 // No free tickets (all tasks delegated to cores)
1196 if( giFreeTickets == 0 ) {
1197 SHORTREL(&glThreadListLock);
1201 // Get the ticket number
1202 ticket = number = rand() % giFreeTickets;
1204 // Find the next thread
1205 for(thread=gActiveThreads;thread;thread=thread->Next)
1207 if(thread->CurCPU >= 0) continue;
1208 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1209 number -= caiTICKET_COUNTS[ thread->Priority ];
1212 // If we didn't find a thread, something went wrong
1216 for(thread=gActiveThreads;thread;thread=thread->Next) {
1217 if(thread->CurCPU >= 0) continue;
1218 number += caiTICKET_COUNTS[ thread->Priority ];
1220 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1221 giFreeTickets, number);
1224 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1225 # if DEBUG_TRACE_TICKETS
1226 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1227 CPU, thread, thread->TID, thread->ThreadName,
1228 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1233 // Priority based round robin scheduler
1235 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1238 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1240 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1242 if( thread->CurCPU == -1 ) break;
1244 // If we fall onto the same queue again, special handling is
1246 if( Last && Last->Status == THREAD_STAT_ACTIVE && i == Last->Priority ) {
1247 tThread *savedThread = thread;
1249 // Find the next unscheduled thread in the list
1250 for( thread = Last->Next; thread; thread = thread->Next )
1252 if( thread->CurCPU == -1 ) break;
1254 // If we don't find anything after, just use the one
1256 if( !thread ) thread = savedThread;
1258 // Found a thread? Schedule it!
1264 SHORTREL(&glThreadListLock);
1267 if( thread->Status != THREAD_STAT_ACTIVE ) {
1268 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1271 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1273 // Find the next unscheduled thread in the list
1274 for( thread = Last->Next; thread; thread = thread->Next )
1276 if( thread->CurCPU == -1 ) break;
1278 // If we don't find anything after, search from the beginning
1281 for(thread = gActiveThreads; thread; thread = thread->Next)
1283 if( thread->CurCPU == -1 ) break;
1289 SHORTREL(&glThreadListLock);
1294 # error "Unimplemented scheduling algorithm"
1297 // Make the new thread non-schedulable
1298 thread->CurCPU = CPU;
1299 thread->Remaining = thread->Quantum;
1301 SHORTREL( &glThreadListLock );
1307 EXPORT(Threads_GetUID);
1308 EXPORT(Threads_GetGID);