4 * - Common Thread Control
8 #include <threads_int.h>
11 #include <semaphore.h>
12 #include <vfs_threads.h> // VFS Handle maintainence
15 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
16 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
20 #define SCHED_LOTTERY 1 // Lottery scheduler
21 #define SCHED_RR_SIM 2 // Single Queue Round Robin
22 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
24 #define SCHEDULER_TYPE SCHED_RR_PRI
27 #define DEFAULT_QUANTUM 5
28 #define DEFAULT_PRIORITY 5
29 #define MIN_PRIORITY 10
41 void Threads_Init(void);
43 void Threads_Delete(tThread *Thread);
44 int Threads_SetName(const char *NewName);
46 char *Threads_GetName(tTID ID);
48 void Threads_SetPriority(tThread *Thread, int Pri);
49 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
50 int Threads_WaitTID(int TID, int *status);
51 tThread *Threads_GetThread(Uint TID);
53 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread);
54 void Threads_int_AddToList(tThreadList *List, tThread *Thread);
56 void Threads_Exit(int TID, int Status);
57 void Threads_Kill(tThread *Thread, int Status);
58 void Threads_Yield(void);
59 void Threads_Sleep(void);
60 int Threads_Wake(tThread *Thread);
61 void Threads_AddActive(tThread *Thread);
62 tThread *Threads_RemActive(void);
64 void Threads_ToggleTrace(int TID);
65 void Threads_Fault(int Num);
66 void Threads_SegFault(tVAddr Addr);
68 int Threads_GetPID(void);
69 int Threads_GetTID(void);
70 tUID Threads_GetUID(void);
71 tGID Threads_GetGID(void);
72 int Threads_SetUID(Uint *Errno, tUID ID);
73 int Threads_SetGID(Uint *Errno, tUID ID);
75 void Threads_Dump(void);
76 void Threads_DumpActive(void);
80 struct sProcess gProcessZero = {
82 // Only used for the core kernel
83 tThread gThreadZero = {
84 .Status = THREAD_STAT_ACTIVE, // Status
85 .ThreadName = (char*)"ThreadZero", // Name
86 .Quantum = DEFAULT_QUANTUM, // Default Quantum
87 .Remaining = DEFAULT_QUANTUM, // Current Quantum
88 .Priority = DEFAULT_PRIORITY // Number of tickets
92 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
93 // --- Current State ---
94 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
95 volatile Uint giNextTID = 1; // Next TID to allocate
96 // --- Thread Lists ---
97 tThread *gAllThreads = NULL; // All allocated threads
98 tThreadList gSleepingThreads; // Sleeping Threads
99 int giNumCPUs = 1; // Number of CPUs
100 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
101 // --- Scheduler Types ---
102 #if SCHEDULER_TYPE == SCHED_LOTTERY
103 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
104 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
105 tThreadList gActiveThreads; // Currently Running Threads
106 #elif SCHEDULER_TYPE == SCHED_RR_SIM
107 tThreadList gActiveThreads; // Currently Running Threads
108 #elif SCHEDULER_TYPE == SCHED_RR_PRI
109 tThreadList gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
111 # error "Unkown scheduler type"
116 * \fn void Threads_Init(void)
117 * \brief Initialse the thread list
119 void Threads_Init(void)
123 Log_Debug("Threads", "Offsets of tThread");
124 Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
125 Log_Debug("Threads", ".KernelStack = %i", offsetof(tThread, KernelStack));
127 // Create Initial Task
128 // #if SCHEDULER_TYPE == SCHED_RR_PRI
129 // gaActiveThreads[gThreadZero.Priority].Head = &gThreadZero;
130 // gaActiveThreads[gThreadZero.Priority].Tail = &gThreadZero;
132 // gActiveThreads.Head = &gThreadZero;
133 // gActiveThreads.Tail = &gThreadZero;
136 gAllThreads = &gThreadZero;
137 giNumActiveThreads = 1;
138 gThreadZero.Process = &gProcessZero;
143 void Threads_Delete(tThread *Thread)
146 Thread->Status = THREAD_STAT_BURIED;
148 // Clear out process state
149 Proc_ClearThread(Thread);
151 Thread->Process->nThreads --;
152 if( Thread->Process->nThreads == 0 )
154 tProcess *proc = Thread->Process;
156 VFS_CloseAllUserHandles();
157 // Architecture cleanup
158 Proc_ClearProcess( proc );
159 // VFS Configuration strings
160 if( proc->CurrentWorkingDir)
161 free( proc->CurrentWorkingDir );
163 free( proc->RootDir );
164 // Process descriptor
169 if( IsHeap(Thread->ThreadName) )
170 free(Thread->ThreadName);
172 // Remove from global list
173 // TODO: Lock this too
174 if( Thread == gAllThreads )
175 gAllThreads = Thread->GlobalNext;
177 Thread->GlobalPrev->GlobalNext = Thread->GlobalNext;
183 * \fn void Threads_SetName(const char *NewName)
184 * \brief Sets the current thread's name
185 * \param NewName New name for the thread
186 * \return Boolean Failure
188 int Threads_SetName(const char *NewName)
190 tThread *cur = Proc_GetCurThread();
191 char *oldname = cur->ThreadName;
193 // NOTE: There is a possibility of non-thread safety here
194 // A thread could read the current name pointer before it is zeroed
196 cur->ThreadName = NULL;
198 if( IsHeap(oldname) ) free( oldname );
199 cur->ThreadName = strdup(NewName);
201 Log_Debug("Threads", "Thread renamed to '%s'", NewName);
207 * \fn char *Threads_GetName(int ID)
208 * \brief Gets a thread's name
209 * \param ID Thread ID (-1 indicates current thread)
210 * \return Pointer to name
211 * \retval NULL Failure
213 char *Threads_GetName(tTID ID)
216 return Proc_GetCurThread()->ThreadName;
218 return Threads_GetThread(ID)->ThreadName;
222 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
223 * \brief Sets the priority of a task
224 * \param Thread Thread to update ticket count (NULL means current thread)
225 * \param Pri New priority
227 void Threads_SetPriority(tThread *Thread, int Pri)
229 // Get current thread
230 if(Thread == NULL) Thread = Proc_GetCurThread();
232 // - If < 0, set to lowest priority
233 // - Minumum priority is actualy a high number, 0 is highest
234 if(Pri < 0) Pri = MIN_PRIORITY;
235 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
237 // Do we actually have to do anything?
238 if( Pri == Thread->Priority ) return;
240 #if SCHEDULER_TYPE == SCHED_RR_PRI
241 if( Thread != Proc_GetCurThread() )
243 SHORTLOCK( &glThreadListLock );
244 // Remove from old priority
245 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
247 Threads_int_AddToList( &gaActiveThreads[Pri], Thread );
248 Thread->Priority = Pri;
249 SHORTREL( &glThreadListLock );
252 Thread->Priority = Pri;
254 // If this isn't the current thread, we need to lock
255 if( Thread != Proc_GetCurThread() )
257 SHORTLOCK( &glThreadListLock );
259 #if SCHEDULER_TYPE == SCHED_LOTTERY
260 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
261 # if DEBUG_TRACE_TICKETS
262 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
264 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
267 Thread->Priority = Pri;
268 SHORTREL( &glThreadListLock );
271 Thread->Priority = Pri;
274 #if DEBUG_TRACE_STATE
275 Log("Threads_SetPriority: %p(%i %s) pri set %i",
276 Thread, Thread->TID, Thread->ThreadName,
282 * \brief Clone the TCB of the current thread
283 * \param Flags Flags for something... (What is this for?)
285 tThread *Threads_CloneTCB(Uint Flags)
288 cur = Proc_GetCurThread();
290 // Allocate and duplicate
291 new = malloc(sizeof(tThread));
292 if(new == NULL) { errno = -ENOMEM; return NULL; }
293 memcpy(new, cur, sizeof(tThread));
297 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
298 new->Status = THREAD_STAT_PREINIT;
302 new->TID = giNextTID++;
304 new->bInstrTrace = 0;
307 new->ThreadName = strdup(cur->ThreadName);
309 // Set Thread Group ID (PID)
310 if(Flags & CLONE_VM) {
311 tProcess *newproc, *oldproc;
312 oldproc = cur->Process;
313 new->Process = malloc( sizeof(struct sProcess) );
314 newproc = new->Process;
315 newproc->PID = new->TID;
316 newproc->UID = oldproc->UID;
317 newproc->GID = oldproc->GID;
318 newproc->MaxFD = oldproc->MaxFD;
319 if( oldproc->CurrentWorkingDir )
320 newproc->CurrentWorkingDir = strdup( oldproc->CurrentWorkingDir );
322 newproc->CurrentWorkingDir = NULL;
323 if( oldproc->RootDir )
324 newproc->RootDir = strdup( oldproc->RootDir );
326 newproc->RootDir = NULL;
327 newproc->nThreads = 1;
328 // Reference all handles in the VFS
329 VFS_ReferenceUserHandles();
332 new->Process->nThreads ++;
335 // Messages are not inherited
336 new->Messages = NULL;
337 new->LastMessage = NULL;
340 new->Remaining = new->Quantum = cur->Quantum;
341 new->Priority = cur->Priority;
344 // Set Signal Handlers
345 new->CurFaultNum = 0;
346 new->FaultHandler = cur->FaultHandler;
348 // Maintain a global list of threads
349 SHORTLOCK( &glThreadListLock );
350 new->GlobalPrev = NULL; // Protect against bugs
351 new->GlobalNext = gAllThreads;
352 gAllThreads->GlobalPrev = new;
354 SHORTREL( &glThreadListLock );
360 * \brief Clone the TCB of the kernel thread
362 tThread *Threads_CloneThreadZero(void)
366 // Allocate and duplicate
367 new = malloc(sizeof(tThread));
371 memcpy(new, &gThreadZero, sizeof(tThread));
373 new->Process->nThreads ++;
377 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
378 new->Status = THREAD_STAT_PREINIT;
382 new->TID = giNextTID++;
386 new->ThreadName = NULL;
388 // Messages are not inherited
389 new->Messages = NULL;
390 new->LastMessage = NULL;
393 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
394 new->Priority = DEFAULT_PRIORITY;
395 new->bInstrTrace = 0;
397 // Set Signal Handlers
398 new->CurFaultNum = 0;
399 new->FaultHandler = 0;
401 // Maintain a global list of threads
402 SHORTLOCK( &glThreadListLock );
403 new->GlobalPrev = NULL; // Protect against bugs
404 new->GlobalNext = gAllThreads;
405 gAllThreads->GlobalPrev = new;
407 SHORTREL( &glThreadListLock );
413 * \brief Wait for a task to change state
414 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
415 * \param Status Thread return status
416 * \return TID of child that changed state
418 tTID Threads_WaitTID(int TID, int *Status)
422 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
426 // Any peer/child thread
428 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
434 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
440 tThread *t = Threads_GetThread(TID);
443 // Wait for the thread to die!
444 // TODO: Handle child also being suspended if wanted
445 while(t->Status != THREAD_STAT_ZOMBIE) {
447 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
448 Threads_GetTID(), t->TID, t->Status);
455 case THREAD_STAT_ZOMBIE:
457 t->Status = THREAD_STAT_DEAD;
458 // TODO: Child return value?
459 if(Status) *Status = t->RetStatus;
460 // add to delete queue
464 if(Status) *Status = -1;
474 * \brief Gets a thread given its TID
475 * \param TID Thread ID
476 * \return Thread pointer
478 tThread *Threads_GetThread(Uint TID)
482 // Search global list
483 for(thread = gAllThreads;
485 thread = thread->GlobalNext)
487 if(thread->TID == TID)
491 Log("Unable to find TID %i on main list\n", TID);
497 * \brief Deletes an entry from a list
498 * \param List Pointer to the list head
499 * \param Thread Thread to find
502 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
504 tThread *ret, *prev = NULL;
506 for(ret = List->Head;
507 ret && ret != Thread;
508 prev = ret, ret = ret->Next
511 // Is the thread on the list
513 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
518 List->Head = Thread->Next;
519 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
522 prev->Next = Thread->Next;
523 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
525 if( Thread->Next == NULL )
531 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
534 List->Tail->Next = Thread;
542 * \brief Exit the current process (or another?)
543 * \param TID Thread ID to kill
544 * \param Status Exit status
546 void Threads_Exit(int TID, int Status)
549 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
551 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
553 // Halt forever, just in case
558 * \fn void Threads_Kill(tThread *Thread, int Status)
559 * \brief Kill a thread
560 * \param Thread Thread to kill
561 * \param Status Status code to return to the parent
563 void Threads_Kill(tThread *Thread, int Status)
566 int isCurThread = Thread == Proc_GetCurThread();
568 // TODO: Disown all children?
572 // TODO: I should keep a .Children list
573 for(child = gAllThreads;
575 child = child->GlobalNext)
577 if(child->Parent == Thread)
578 child->Parent = &gThreadZero;
583 ///\note Double lock is needed due to overlap of lock areas
585 // Lock thread (stop us recieving messages)
586 SHORTLOCK( &Thread->IsLocked );
588 // Clear Message Queue
589 while( Thread->Messages )
591 msg = Thread->Messages->Next;
592 free( Thread->Messages );
593 Thread->Messages = msg;
597 SHORTLOCK( &glThreadListLock );
599 switch(Thread->Status)
601 case THREAD_STAT_PREINIT: // Only on main list
604 // Currently active thread
605 case THREAD_STAT_ACTIVE:
606 if( Thread != Proc_GetCurThread() )
608 #if SCHEDULER_TYPE == SCHED_RR_PRI
609 tThreadList *list = &gaActiveThreads[Thread->Priority];
611 tThreadList *list = &gActiveThreads;
613 if( Threads_int_DelFromQueue( list, Thread ) )
618 Log_Warning("Threads",
619 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
620 Thread, Thread->TID, Thread->ThreadName
623 #if SCHEDULER_TYPE == SCHED_LOTTERY
624 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
627 // Ensure that we are not rescheduled
628 Thread->Remaining = 0; // Clear Remaining Quantum
629 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
631 // Update bookkeeping
632 giNumActiveThreads --;
634 // Kill it while it sleeps!
635 case THREAD_STAT_SLEEPING:
636 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
638 Log_Warning("Threads",
639 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
640 Thread, Thread->TID, Thread->ThreadName
645 // Brains!... You cannot kill something that is already dead
646 case THREAD_STAT_ZOMBIE:
647 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
648 Thread, Thread->TID, Thread->ThreadName);
649 SHORTREL( &glThreadListLock );
650 SHORTREL( &Thread->IsLocked );
654 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
660 Thread->RetStatus = Status;
662 SHORTREL( &Thread->IsLocked );
664 Thread->Status = THREAD_STAT_ZOMBIE;
665 SHORTREL( &glThreadListLock );
666 // TODO: Send something like SIGCHLD
667 Threads_Wake( Thread->Parent );
669 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
680 * \brief Yield remainder of the current thread's timeslice
682 void Threads_Yield(void)
684 // Log("Threads_Yield: by %p", __builtin_return_address(0));
689 * \fn void Threads_Sleep(void)
690 * \brief Take the current process off the run queue
692 void Threads_Sleep(void)
694 tThread *cur = Proc_GetCurThread();
697 SHORTLOCK( &glThreadListLock );
699 // Don't sleep if there is a message waiting
700 if( cur->Messages ) {
701 SHORTREL( &glThreadListLock );
705 // Remove us from running queue
707 // Mark thread as sleeping
708 cur->Status = THREAD_STAT_SLEEPING;
710 // Add to Sleeping List (at the top)
711 Threads_int_AddToList( &gSleepingThreads, cur );
713 #if DEBUG_TRACE_STATE
714 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
718 SHORTREL( &glThreadListLock );
720 while(cur->Status != THREAD_STAT_ACTIVE) {
722 if( cur->Status != THREAD_STAT_ACTIVE )
723 Log("%i - Huh? why am I up? zzzz...", cur->TID);
729 * \brief Wakes a sleeping/waiting thread up
730 * \param Thread Thread to wake
731 * \return Boolean Failure (Returns ERRNO)
732 * \warning This should ONLY be called with task switches disabled
734 int Threads_Wake(tThread *Thread)
739 switch(Thread->Status)
741 case THREAD_STAT_ACTIVE:
742 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
745 case THREAD_STAT_SLEEPING:
746 SHORTLOCK( &glThreadListLock );
747 // Remove from sleeping queue
748 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
750 SHORTREL( &glThreadListLock );
751 Threads_AddActive( Thread );
753 #if DEBUG_TRACE_STATE
754 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
758 case THREAD_STAT_SEMAPHORESLEEP: {
760 tThread *th, *prev=NULL;
762 sem = Thread->WaitPointer;
764 SHORTLOCK( &sem->Protector );
766 // Remove from sleeping queue
767 for( th = sem->Waiting; th; prev = th, th = th->Next )
768 if( th == Thread ) break;
772 prev->Next = Thread->Next;
774 sem->Waiting = Thread->Next;
775 if(sem->LastWaiting == Thread)
776 sem->LastWaiting = prev;
781 for( th = sem->Signaling; th; prev = th, th = th->Next )
782 if( th == Thread ) break;
784 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
785 Thread, Thread->TID, Thread->ThreadName,
786 sem, sem->ModName, sem->Name);
791 prev->Next = Thread->Next;
793 sem->Signaling = Thread->Next;
794 if(sem->LastSignaling == Thread)
795 sem->LastSignaling = prev;
798 Thread->RetStatus = 0; // It didn't get anything
799 Threads_AddActive( Thread );
801 #if DEBUG_TRACE_STATE
802 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
804 SHORTREL( &sem->Protector );
807 case THREAD_STAT_WAITING:
808 Warning("Threads_Wake - Waiting threads are not currently supported");
811 case THREAD_STAT_DEAD:
812 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
816 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
822 * \brief Wake a thread given the TID
823 * \param TID Thread ID to wake
824 * \return Boolean Faulure (errno)
826 int Threads_WakeTID(tTID TID)
828 tThread *thread = Threads_GetThread(TID);
832 ret = Threads_Wake( thread );
833 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
837 void Threads_ToggleTrace(int TID)
839 tThread *thread = Threads_GetThread(TID);
841 thread->bInstrTrace = !thread->bInstrTrace;
845 * \brief Adds a thread to the active queue
847 void Threads_AddActive(tThread *Thread)
849 SHORTLOCK( &glThreadListLock );
851 if( Thread->Status == THREAD_STAT_ACTIVE ) {
852 tThread *cur = Proc_GetCurThread();
853 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
854 __builtin_return_address(0),
855 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
856 SHORTREL( &glThreadListLock );
861 Thread->Status = THREAD_STAT_ACTIVE;
862 // Thread->CurCPU = -1;
863 // Add to active list
865 #if SCHEDULER_TYPE == SCHED_RR_PRI
866 tThreadList *list = &gaActiveThreads[Thread->Priority];
868 tThreadList *list = &gActiveThreads;
870 Threads_int_AddToList( list, Thread );
873 // Update bookkeeping
874 giNumActiveThreads ++;
876 #if SCHEDULER_TYPE == SCHED_LOTTERY
879 // Only change the ticket count if the thread is un-scheduled
880 if(Thread->CurCPU != -1)
883 delta = caiTICKET_COUNTS[ Thread->Priority ];
885 giFreeTickets += delta;
886 # if DEBUG_TRACE_TICKETS
887 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
888 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
895 SHORTREL( &glThreadListLock );
899 * \brief Removes the current thread from the active queue
900 * \warning This should ONLY be called with the lock held
901 * \return Current thread pointer
903 tThread *Threads_RemActive(void)
906 tThread *ret = Proc_GetCurThread();
908 if( !IS_LOCKED(&glThreadListLock) ) {
909 Log_KernelPanic("Threads", "Threads_RemActive called without lock held");
913 // Delete from active queue
914 #if SCHEDULER_TYPE == SCHED_RR_PRI
915 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
917 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
920 Log_Warning("Threads", "Current thread %p(%i %s) is not on active queue",
921 ret, ret->TID, ret->ThreadName
929 // no need to decrement tickets, scheduler did it for us
931 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
932 Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
933 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
938 giNumActiveThreads --;
939 return Proc_GetCurThread();
944 * \fn void Threads_SetFaultHandler(Uint Handler)
945 * \brief Sets the signal handler for a signal
947 void Threads_SetFaultHandler(Uint Handler)
949 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
950 Proc_GetCurThread()->FaultHandler = Handler;
954 * \fn void Threads_Fault(int Num)
955 * \brief Calls a fault handler
957 void Threads_Fault(int Num)
959 tThread *thread = Proc_GetCurThread();
963 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
965 switch(thread->FaultHandler)
968 Threads_Kill(thread, -1);
971 case 1: // Dump Core?
972 Threads_Kill(thread, -1);
977 // Double Fault? Oh, F**k
978 if(thread->CurFaultNum != 0) {
979 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
980 Threads_Kill(thread, -1); // For now, just kill
984 thread->CurFaultNum = Num;
986 Proc_CallFaultHandler(thread);
990 * \fn void Threads_SegFault(tVAddr Addr)
991 * \brief Called when a Segment Fault occurs
993 void Threads_SegFault(tVAddr Addr)
995 tThread *cur = Proc_GetCurThread();
996 cur->bInstrTrace = 0;
997 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
998 MM_DumpTables(0, USER_MAX);
1000 //Threads_Exit( 0, -1 );
1003 // --- Process Structure Access Functions ---
1004 tPID Threads_GetPID(void)
1006 return Proc_GetCurThread()->Process->PID;
1008 tTID Threads_GetTID(void)
1010 return Proc_GetCurThread()->TID;
1012 tUID Threads_GetUID(void)
1014 return Proc_GetCurThread()->Process->UID;
1016 tGID Threads_GetGID(void)
1018 return Proc_GetCurThread()->Process->GID;
1021 int Threads_SetUID(tUID ID)
1023 tThread *t = Proc_GetCurThread();
1024 if( t->Process->UID != 0 ) {
1028 Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1029 t->Process->UID = ID;
1033 int Threads_SetGID(tGID ID)
1035 tThread *t = Proc_GetCurThread();
1036 if( t->Process->UID != 0 ) {
1040 Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1041 t->Process->GID = ID;
1045 // --- Per-thread storage ---
1046 int *Threads_GetErrno(void)
1048 return &Proc_GetCurThread()->_errno;
1051 // --- Configuration ---
1052 int *Threads_GetMaxFD(void)
1054 return &Proc_GetCurThread()->Process->MaxFD;
1056 char **Threads_GetChroot(void)
1058 return &Proc_GetCurThread()->Process->RootDir;
1060 char **Threads_GetCWD(void)
1062 return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1067 * \fn void Threads_Dump(void)
1069 void Threads_DumpActive(void)
1073 #if SCHEDULER_TYPE == SCHED_RR_PRI
1077 Log("Active Threads: (%i reported)", giNumActiveThreads);
1079 #if SCHEDULER_TYPE == SCHED_RR_PRI
1080 for( i = 0; i < MIN_PRIORITY+1; i++ )
1082 list = &gaActiveThreads[i];
1084 list = &gActiveThreads;
1086 for(thread=list->Head;thread;thread=thread->Next)
1088 Log(" %p %i (%i) - %s (CPU %i)",
1089 thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU);
1090 if(thread->Status != THREAD_STAT_ACTIVE)
1091 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1092 thread->Status, THREAD_STAT_ACTIVE);
1093 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1094 Log(" KStack 0x%x", thread->KernelStack);
1095 if( thread->bInstrTrace )
1096 Log(" Tracing Enabled");
1097 Proc_DumpThreadCPUState(thread);
1100 #if SCHEDULER_TYPE == SCHED_RR_PRI
1106 * \fn void Threads_Dump(void)
1107 * \brief Dumps a list of currently running threads
1109 void Threads_Dump(void)
1113 Log("--- Thread Dump ---");
1114 Threads_DumpActive();
1116 Log("All Threads:");
1117 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1119 Log(" %p %i (%i) - %s (CPU %i)",
1120 thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU);
1121 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1122 switch(thread->Status)
1124 case THREAD_STAT_MUTEXSLEEP:
1125 Log(" Mutex Pointer: %p", thread->WaitPointer);
1127 case THREAD_STAT_SEMAPHORESLEEP:
1128 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1129 Log(" Semaphore Name: %s:%s",
1130 ((tSemaphore*)thread->WaitPointer)->ModName,
1131 ((tSemaphore*)thread->WaitPointer)->Name
1134 case THREAD_STAT_ZOMBIE:
1135 Log(" Return Status: %i", thread->RetStatus);
1139 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1140 Log(" KStack 0x%x", thread->KernelStack);
1141 if( thread->bInstrTrace )
1142 Log(" Tracing Enabled");
1143 Proc_DumpThreadCPUState(thread);
1148 * \brief Gets the next thread to run
1149 * \param CPU Current CPU
1150 * \param Last The thread the CPU was running
1152 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1156 // If this CPU has the lock, we must let it complete
1157 if( CPU_HAS_LOCK( &glThreadListLock ) )
1160 // Don't change threads if the current CPU has switches disabled
1161 if( gaThreads_NoTaskSwitch[CPU] )
1165 SHORTLOCK( &glThreadListLock );
1167 // Make sure the current (well, old) thread is marked as de-scheduled
1168 if(Last) Last->CurCPU = -1;
1170 // No active threads, just take a nap
1171 if(giNumActiveThreads == 0) {
1172 SHORTREL( &glThreadListLock );
1173 #if DEBUG_TRACE_TICKETS
1174 Log("No active threads");
1180 #if SCHEDULER_TYPE != SCHED_RR_PRI
1181 // Special case: 1 thread
1182 if(giNumActiveThreads == 1) {
1183 if( gActiveThreads.Head->CurCPU == -1 )
1184 gActiveThreads.Head->CurCPU = CPU;
1186 SHORTREL( &glThreadListLock );
1188 if( gActiveThreads.Head->CurCPU == CPU )
1189 return gActiveThreads.Head;
1191 return NULL; // CPU has nothing to do
1196 // Allow the old thread to be scheduled again
1198 if( Last->Status == THREAD_STAT_ACTIVE ) {
1200 #if SCHEDULER_TYPE == SCHED_LOTTERY
1201 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1202 # if DEBUG_TRACE_TICKETS
1203 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1204 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1205 caiTICKET_COUNTS[ Last->Priority ]);
1209 #if SCHEDULER_TYPE == SCHED_RR_PRI
1210 list = &gaActiveThreads[ Last->Priority ];
1212 list = &gActiveThreads;
1214 // Add to end of list
1215 Threads_int_AddToList( list, Last );
1217 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1219 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1220 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1226 // Lottery Scheduler
1228 #if SCHEDULER_TYPE == SCHED_LOTTERY
1233 for(thread = gActiveThreads.Head; thread; thread = thread->Next)
1235 if(thread->Status != THREAD_STAT_ACTIVE)
1236 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1237 thread, thread->TID, thread->ThreadName, thread->Status);
1238 if(thread->Next == thread) {
1239 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1240 thread, thread->TID, thread->ThreadName, thread->Status);
1242 number += caiTICKET_COUNTS[ thread->Priority ];
1244 if(number != giFreeTickets) {
1245 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1246 giFreeTickets, number, CPU);
1250 // No free tickets (all tasks delegated to cores)
1251 if( giFreeTickets == 0 ) {
1252 SHORTREL(&glThreadListLock);
1256 // Get the ticket number
1257 ticket = number = rand() % giFreeTickets;
1259 // Find the next thread
1260 for(thread = gActiveThreads.Head; thread; prev = thread, thread = thread->Next )
1262 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1263 number -= caiTICKET_COUNTS[ thread->Priority ];
1266 // If we didn't find a thread, something went wrong
1270 for(thread=gActiveThreads;thread;thread=thread->Next) {
1271 if(thread->CurCPU >= 0) continue;
1272 number += caiTICKET_COUNTS[ thread->Priority ];
1274 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1275 giFreeTickets, number);
1280 prev->Next = thread->Next;
1282 gActiveThreads.Head = thread->Next;
1284 gActiveThreads.Tail = prev;
1286 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1287 # if DEBUG_TRACE_TICKETS
1288 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1289 CPU, thread, thread->TID, thread->ThreadName,
1290 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1295 // Priority based round robin scheduler
1297 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1301 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1303 if( !gaActiveThreads[i].Head )
1306 thread = gaActiveThreads[i].Head;
1309 gaActiveThreads[i].Head = thread->Next;
1311 gaActiveThreads[i].Tail = NULL;
1312 thread->Next = NULL;
1318 SHORTREL(&glThreadListLock);
1321 if( thread->Status != THREAD_STAT_ACTIVE ) {
1322 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1325 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1327 // Get the next thread off the list
1328 thread = gActiveThreads.Head;
1329 gActiveThreads.Head = thread->Next;
1331 gaActiveThreads.Tail = NULL;
1332 thread->Next = NULL;
1336 SHORTREL(&glThreadListLock);
1341 # error "Unimplemented scheduling algorithm"
1344 // Make the new thread non-schedulable
1345 thread->CurCPU = CPU;
1346 thread->Remaining = thread->Quantum;
1348 SHORTREL( &glThreadListLock );
1354 EXPORT(Threads_GetUID);
1355 EXPORT(Threads_GetGID);