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 if( Flags & CLONE_PGID )
317 newproc->PGID = oldproc->PGID;
319 newproc->PGID = newproc->PID;
320 newproc->UID = oldproc->UID;
321 newproc->GID = oldproc->GID;
322 newproc->MaxFD = oldproc->MaxFD;
323 if( oldproc->CurrentWorkingDir )
324 newproc->CurrentWorkingDir = strdup( oldproc->CurrentWorkingDir );
326 newproc->CurrentWorkingDir = NULL;
327 if( oldproc->RootDir )
328 newproc->RootDir = strdup( oldproc->RootDir );
330 newproc->RootDir = NULL;
331 newproc->nThreads = 1;
332 // Reference all handles in the VFS
333 VFS_ReferenceUserHandles();
336 new->Process->nThreads ++;
339 // Messages are not inherited
340 new->Messages = NULL;
341 new->LastMessage = NULL;
344 new->Remaining = new->Quantum = cur->Quantum;
345 new->Priority = cur->Priority;
348 // Set Signal Handlers
349 new->CurFaultNum = 0;
350 new->FaultHandler = cur->FaultHandler;
352 // Maintain a global list of threads
353 SHORTLOCK( &glThreadListLock );
354 new->GlobalPrev = NULL; // Protect against bugs
355 new->GlobalNext = gAllThreads;
356 gAllThreads->GlobalPrev = new;
358 SHORTREL( &glThreadListLock );
364 * \brief Clone the TCB of the kernel thread
366 tThread *Threads_CloneThreadZero(void)
370 // Allocate and duplicate
371 new = malloc(sizeof(tThread));
375 memcpy(new, &gThreadZero, sizeof(tThread));
377 new->Process->nThreads ++;
381 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
382 new->Status = THREAD_STAT_PREINIT;
386 new->TID = giNextTID++;
390 new->ThreadName = NULL;
392 // Messages are not inherited
393 new->Messages = NULL;
394 new->LastMessage = NULL;
397 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
398 new->Priority = DEFAULT_PRIORITY;
399 new->bInstrTrace = 0;
401 // Set Signal Handlers
402 new->CurFaultNum = 0;
403 new->FaultHandler = 0;
405 // Maintain a global list of threads
406 SHORTLOCK( &glThreadListLock );
407 new->GlobalPrev = NULL; // Protect against bugs
408 new->GlobalNext = gAllThreads;
409 gAllThreads->GlobalPrev = new;
411 SHORTREL( &glThreadListLock );
417 * \brief Wait for a task to change state
418 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
419 * \param Status Thread return status
420 * \return TID of child that changed state
422 tTID Threads_WaitTID(int TID, int *Status)
426 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
430 // Any peer/child thread
432 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
438 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
444 tThread *t = Threads_GetThread(TID);
447 // Wait for the thread to die!
448 // TODO: Handle child also being suspended if wanted
449 while(t->Status != THREAD_STAT_ZOMBIE) {
451 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
452 Threads_GetTID(), t->TID, t->Status);
459 case THREAD_STAT_ZOMBIE:
461 t->Status = THREAD_STAT_DEAD;
462 // TODO: Child return value?
463 if(Status) *Status = t->RetStatus;
464 // add to delete queue
468 if(Status) *Status = -1;
478 * \brief Gets a thread given its TID
479 * \param TID Thread ID
480 * \return Thread pointer
482 tThread *Threads_GetThread(Uint TID)
486 // Search global list
487 for(thread = gAllThreads;
489 thread = thread->GlobalNext)
491 if(thread->TID == TID)
495 Log("Unable to find TID %i on main list\n", TID);
501 * \brief Deletes an entry from a list
502 * \param List Pointer to the list head
503 * \param Thread Thread to find
506 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
508 tThread *ret, *prev = NULL;
510 for(ret = List->Head;
511 ret && ret != Thread;
512 prev = ret, ret = ret->Next
515 // Is the thread on the list
517 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
522 List->Head = Thread->Next;
523 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
526 prev->Next = Thread->Next;
527 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
529 if( Thread->Next == NULL )
535 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
538 List->Tail->Next = Thread;
546 * \brief Exit the current process (or another?)
547 * \param TID Thread ID to kill
548 * \param Status Exit status
550 void Threads_Exit(int TID, int Status)
553 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
555 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
557 // Halt forever, just in case
562 * \fn void Threads_Kill(tThread *Thread, int Status)
563 * \brief Kill a thread
564 * \param Thread Thread to kill
565 * \param Status Status code to return to the parent
567 void Threads_Kill(tThread *Thread, int Status)
570 int isCurThread = Thread == Proc_GetCurThread();
572 // TODO: Disown all children?
576 // TODO: I should keep a .Children list
577 for(child = gAllThreads;
579 child = child->GlobalNext)
581 if(child->Parent == Thread)
582 child->Parent = &gThreadZero;
587 ///\note Double lock is needed due to overlap of lock areas
589 // Lock thread (stop us recieving messages)
590 SHORTLOCK( &Thread->IsLocked );
592 // Clear Message Queue
593 while( Thread->Messages )
595 msg = Thread->Messages->Next;
596 free( Thread->Messages );
597 Thread->Messages = msg;
601 SHORTLOCK( &glThreadListLock );
603 switch(Thread->Status)
605 case THREAD_STAT_PREINIT: // Only on main list
608 // Currently active thread
609 case THREAD_STAT_ACTIVE:
610 if( Thread != Proc_GetCurThread() )
612 #if SCHEDULER_TYPE == SCHED_RR_PRI
613 tThreadList *list = &gaActiveThreads[Thread->Priority];
615 tThreadList *list = &gActiveThreads;
617 if( Threads_int_DelFromQueue( list, Thread ) )
622 Log_Warning("Threads",
623 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
624 Thread, Thread->TID, Thread->ThreadName
627 #if SCHEDULER_TYPE == SCHED_LOTTERY
628 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
631 // Ensure that we are not rescheduled
632 Thread->Remaining = 0; // Clear Remaining Quantum
633 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
635 // Update bookkeeping
636 giNumActiveThreads --;
638 // Kill it while it sleeps!
639 case THREAD_STAT_SLEEPING:
640 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
642 Log_Warning("Threads",
643 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
644 Thread, Thread->TID, Thread->ThreadName
649 // Brains!... You cannot kill something that is already dead
650 case THREAD_STAT_ZOMBIE:
651 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
652 Thread, Thread->TID, Thread->ThreadName);
653 SHORTREL( &glThreadListLock );
654 SHORTREL( &Thread->IsLocked );
658 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
664 Thread->RetStatus = Status;
666 SHORTREL( &Thread->IsLocked );
668 Thread->Status = THREAD_STAT_ZOMBIE;
669 SHORTREL( &glThreadListLock );
670 // TODO: Send something like SIGCHLD
671 Threads_Wake( Thread->Parent );
673 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
684 * \brief Yield remainder of the current thread's timeslice
686 void Threads_Yield(void)
688 // Log("Threads_Yield: by %p", __builtin_return_address(0));
693 * \fn void Threads_Sleep(void)
694 * \brief Take the current process off the run queue
696 void Threads_Sleep(void)
698 tThread *cur = Proc_GetCurThread();
701 SHORTLOCK( &glThreadListLock );
703 // Don't sleep if there is a message waiting
704 if( cur->Messages ) {
705 SHORTREL( &glThreadListLock );
709 // Remove us from running queue
711 // Mark thread as sleeping
712 cur->Status = THREAD_STAT_SLEEPING;
714 // Add to Sleeping List (at the top)
715 Threads_int_AddToList( &gSleepingThreads, cur );
717 #if DEBUG_TRACE_STATE
718 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
722 SHORTREL( &glThreadListLock );
724 while(cur->Status != THREAD_STAT_ACTIVE) {
726 if( cur->Status != THREAD_STAT_ACTIVE )
727 Log("%i - Huh? why am I up? zzzz...", cur->TID);
733 * \brief Wakes a sleeping/waiting thread up
734 * \param Thread Thread to wake
735 * \return Boolean Failure (Returns ERRNO)
736 * \warning This should ONLY be called with task switches disabled
738 int Threads_Wake(tThread *Thread)
743 switch(Thread->Status)
745 case THREAD_STAT_ACTIVE:
746 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
749 case THREAD_STAT_SLEEPING:
750 SHORTLOCK( &glThreadListLock );
751 // Remove from sleeping queue
752 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
754 SHORTREL( &glThreadListLock );
755 Threads_AddActive( Thread );
757 #if DEBUG_TRACE_STATE
758 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
762 case THREAD_STAT_SEMAPHORESLEEP: {
764 tThread *th, *prev=NULL;
766 sem = Thread->WaitPointer;
768 SHORTLOCK( &sem->Protector );
770 // Remove from sleeping queue
771 for( th = sem->Waiting; th; prev = th, th = th->Next )
772 if( th == Thread ) break;
776 prev->Next = Thread->Next;
778 sem->Waiting = Thread->Next;
779 if(sem->LastWaiting == Thread)
780 sem->LastWaiting = prev;
785 for( th = sem->Signaling; th; prev = th, th = th->Next )
786 if( th == Thread ) break;
788 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
789 Thread, Thread->TID, Thread->ThreadName,
790 sem, sem->ModName, sem->Name);
795 prev->Next = Thread->Next;
797 sem->Signaling = Thread->Next;
798 if(sem->LastSignaling == Thread)
799 sem->LastSignaling = prev;
802 Thread->RetStatus = 0; // It didn't get anything
803 Threads_AddActive( Thread );
805 #if DEBUG_TRACE_STATE
806 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
808 SHORTREL( &sem->Protector );
811 case THREAD_STAT_WAITING:
812 Warning("Threads_Wake - Waiting threads are not currently supported");
815 case THREAD_STAT_DEAD:
816 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
820 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
826 * \brief Wake a thread given the TID
827 * \param TID Thread ID to wake
828 * \return Boolean Faulure (errno)
830 int Threads_WakeTID(tTID TID)
832 tThread *thread = Threads_GetThread(TID);
836 ret = Threads_Wake( thread );
837 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
841 void Threads_ToggleTrace(int TID)
843 tThread *thread = Threads_GetThread(TID);
845 thread->bInstrTrace = !thread->bInstrTrace;
849 * \brief Adds a thread to the active queue
851 void Threads_AddActive(tThread *Thread)
853 SHORTLOCK( &glThreadListLock );
855 if( Thread->Status == THREAD_STAT_ACTIVE ) {
856 tThread *cur = Proc_GetCurThread();
857 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
858 __builtin_return_address(0),
859 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
860 SHORTREL( &glThreadListLock );
865 Thread->Status = THREAD_STAT_ACTIVE;
866 // Thread->CurCPU = -1;
867 // Add to active list
869 #if SCHEDULER_TYPE == SCHED_RR_PRI
870 tThreadList *list = &gaActiveThreads[Thread->Priority];
872 tThreadList *list = &gActiveThreads;
874 Threads_int_AddToList( list, Thread );
877 // Update bookkeeping
878 giNumActiveThreads ++;
880 #if SCHEDULER_TYPE == SCHED_LOTTERY
883 // Only change the ticket count if the thread is un-scheduled
884 if(Thread->CurCPU != -1)
887 delta = caiTICKET_COUNTS[ Thread->Priority ];
889 giFreeTickets += delta;
890 # if DEBUG_TRACE_TICKETS
891 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
892 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
899 SHORTREL( &glThreadListLock );
903 * \brief Removes the current thread from the active queue
904 * \warning This should ONLY be called with the lock held
905 * \return Current thread pointer
907 tThread *Threads_RemActive(void)
910 tThread *ret = Proc_GetCurThread();
912 if( !IS_LOCKED(&glThreadListLock) ) {
913 Log_KernelPanic("Threads", "Threads_RemActive called without lock held");
917 // Delete from active queue
918 #if SCHEDULER_TYPE == SCHED_RR_PRI
919 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
921 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
924 Log_Warning("Threads", "Current thread %p(%i %s) is not on active queue",
925 ret, ret->TID, ret->ThreadName
933 // no need to decrement tickets, scheduler did it for us
935 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
936 Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
937 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
942 giNumActiveThreads --;
943 return Proc_GetCurThread();
948 * \fn void Threads_SetFaultHandler(Uint Handler)
949 * \brief Sets the signal handler for a signal
951 void Threads_SetFaultHandler(Uint Handler)
953 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
954 Proc_GetCurThread()->FaultHandler = Handler;
958 * \fn void Threads_Fault(int Num)
959 * \brief Calls a fault handler
961 void Threads_Fault(int Num)
963 tThread *thread = Proc_GetCurThread();
967 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
969 switch(thread->FaultHandler)
972 Threads_Kill(thread, -1);
975 case 1: // Dump Core?
976 Threads_Kill(thread, -1);
981 // Double Fault? Oh, F**k
982 if(thread->CurFaultNum != 0) {
983 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
984 Threads_Kill(thread, -1); // For now, just kill
988 thread->CurFaultNum = Num;
990 Proc_CallFaultHandler(thread);
994 * \fn void Threads_SegFault(tVAddr Addr)
995 * \brief Called when a Segment Fault occurs
997 void Threads_SegFault(tVAddr Addr)
999 tThread *cur = Proc_GetCurThread();
1000 cur->bInstrTrace = 0;
1001 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
1002 MM_DumpTables(0, USER_MAX);
1004 //Threads_Exit( 0, -1 );
1007 // --- Process Structure Access Functions ---
1008 tPGID Threads_GetPGID(void)
1010 return Proc_GetCurThread()->Process->PGID;
1012 tPID Threads_GetPID(void)
1014 return Proc_GetCurThread()->Process->PID;
1016 tTID Threads_GetTID(void)
1018 return Proc_GetCurThread()->TID;
1020 tUID Threads_GetUID(void)
1022 return Proc_GetCurThread()->Process->UID;
1024 tGID Threads_GetGID(void)
1026 return Proc_GetCurThread()->Process->GID;
1029 int Threads_SetUID(tUID ID)
1031 tThread *t = Proc_GetCurThread();
1032 if( t->Process->UID != 0 ) {
1036 Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1037 t->Process->UID = ID;
1041 int Threads_SetGID(tGID ID)
1043 tThread *t = Proc_GetCurThread();
1044 if( t->Process->UID != 0 ) {
1048 Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1049 t->Process->GID = ID;
1053 // --- Per-thread storage ---
1054 int *Threads_GetErrno(void)
1056 return &Proc_GetCurThread()->_errno;
1059 // --- Configuration ---
1060 int *Threads_GetMaxFD(void)
1062 return &Proc_GetCurThread()->Process->MaxFD;
1064 char **Threads_GetChroot(void)
1066 return &Proc_GetCurThread()->Process->RootDir;
1068 char **Threads_GetCWD(void)
1070 return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1075 * \fn void Threads_Dump(void)
1077 void Threads_DumpActive(void)
1081 #if SCHEDULER_TYPE == SCHED_RR_PRI
1085 Log("Active Threads: (%i reported)", giNumActiveThreads);
1087 #if SCHEDULER_TYPE == SCHED_RR_PRI
1088 for( i = 0; i < MIN_PRIORITY+1; i++ )
1090 list = &gaActiveThreads[i];
1092 list = &gActiveThreads;
1094 for(thread=list->Head;thread;thread=thread->Next)
1096 Log(" %p %i (%i) - %s (CPU %i)",
1097 thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU);
1098 if(thread->Status != THREAD_STAT_ACTIVE)
1099 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1100 thread->Status, THREAD_STAT_ACTIVE);
1101 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1102 Log(" KStack 0x%x", thread->KernelStack);
1103 if( thread->bInstrTrace )
1104 Log(" Tracing Enabled");
1105 Proc_DumpThreadCPUState(thread);
1108 #if SCHEDULER_TYPE == SCHED_RR_PRI
1114 * \fn void Threads_Dump(void)
1115 * \brief Dumps a list of currently running threads
1117 void Threads_Dump(void)
1121 Log("--- Thread Dump ---");
1122 Threads_DumpActive();
1124 Log("All Threads:");
1125 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1127 Log(" %p %i (%i) - %s (CPU %i)",
1128 thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU);
1129 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1130 switch(thread->Status)
1132 case THREAD_STAT_MUTEXSLEEP:
1133 Log(" Mutex Pointer: %p", thread->WaitPointer);
1135 case THREAD_STAT_SEMAPHORESLEEP:
1136 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1137 Log(" Semaphore Name: %s:%s",
1138 ((tSemaphore*)thread->WaitPointer)->ModName,
1139 ((tSemaphore*)thread->WaitPointer)->Name
1142 case THREAD_STAT_ZOMBIE:
1143 Log(" Return Status: %i", thread->RetStatus);
1147 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1148 Log(" KStack 0x%x", thread->KernelStack);
1149 if( thread->bInstrTrace )
1150 Log(" Tracing Enabled");
1151 Proc_DumpThreadCPUState(thread);
1156 * \brief Gets the next thread to run
1157 * \param CPU Current CPU
1158 * \param Last The thread the CPU was running
1160 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1164 // If this CPU has the lock, we must let it complete
1165 if( CPU_HAS_LOCK( &glThreadListLock ) )
1168 // Don't change threads if the current CPU has switches disabled
1169 if( gaThreads_NoTaskSwitch[CPU] )
1173 SHORTLOCK( &glThreadListLock );
1175 // Make sure the current (well, old) thread is marked as de-scheduled
1176 if(Last) Last->CurCPU = -1;
1178 // No active threads, just take a nap
1179 if(giNumActiveThreads == 0) {
1180 SHORTREL( &glThreadListLock );
1181 #if DEBUG_TRACE_TICKETS
1182 Log("No active threads");
1188 #if SCHEDULER_TYPE != SCHED_RR_PRI
1189 // Special case: 1 thread
1190 if(giNumActiveThreads == 1) {
1191 if( gActiveThreads.Head->CurCPU == -1 )
1192 gActiveThreads.Head->CurCPU = CPU;
1194 SHORTREL( &glThreadListLock );
1196 if( gActiveThreads.Head->CurCPU == CPU )
1197 return gActiveThreads.Head;
1199 return NULL; // CPU has nothing to do
1204 // Allow the old thread to be scheduled again
1206 if( Last->Status == THREAD_STAT_ACTIVE ) {
1208 #if SCHEDULER_TYPE == SCHED_LOTTERY
1209 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1210 # if DEBUG_TRACE_TICKETS
1211 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1212 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1213 caiTICKET_COUNTS[ Last->Priority ]);
1217 #if SCHEDULER_TYPE == SCHED_RR_PRI
1218 list = &gaActiveThreads[ Last->Priority ];
1220 list = &gActiveThreads;
1222 // Add to end of list
1223 Threads_int_AddToList( list, Last );
1225 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1227 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1228 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1234 // Lottery Scheduler
1236 #if SCHEDULER_TYPE == SCHED_LOTTERY
1241 for(thread = gActiveThreads.Head; thread; thread = thread->Next)
1243 if(thread->Status != THREAD_STAT_ACTIVE)
1244 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1245 thread, thread->TID, thread->ThreadName, thread->Status);
1246 if(thread->Next == thread) {
1247 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1248 thread, thread->TID, thread->ThreadName, thread->Status);
1250 number += caiTICKET_COUNTS[ thread->Priority ];
1252 if(number != giFreeTickets) {
1253 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1254 giFreeTickets, number, CPU);
1258 // No free tickets (all tasks delegated to cores)
1259 if( giFreeTickets == 0 ) {
1260 SHORTREL(&glThreadListLock);
1264 // Get the ticket number
1265 ticket = number = rand() % giFreeTickets;
1267 // Find the next thread
1268 for(thread = gActiveThreads.Head; thread; prev = thread, thread = thread->Next )
1270 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1271 number -= caiTICKET_COUNTS[ thread->Priority ];
1274 // If we didn't find a thread, something went wrong
1278 for(thread=gActiveThreads;thread;thread=thread->Next) {
1279 if(thread->CurCPU >= 0) continue;
1280 number += caiTICKET_COUNTS[ thread->Priority ];
1282 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1283 giFreeTickets, number);
1288 prev->Next = thread->Next;
1290 gActiveThreads.Head = thread->Next;
1292 gActiveThreads.Tail = prev;
1294 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1295 # if DEBUG_TRACE_TICKETS
1296 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1297 CPU, thread, thread->TID, thread->ThreadName,
1298 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1303 // Priority based round robin scheduler
1305 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1309 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1311 if( !gaActiveThreads[i].Head )
1314 thread = gaActiveThreads[i].Head;
1317 gaActiveThreads[i].Head = thread->Next;
1319 gaActiveThreads[i].Tail = NULL;
1320 thread->Next = NULL;
1326 SHORTREL(&glThreadListLock);
1329 if( thread->Status != THREAD_STAT_ACTIVE ) {
1330 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1333 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1335 // Get the next thread off the list
1336 thread = gActiveThreads.Head;
1337 gActiveThreads.Head = thread->Next;
1339 gaActiveThreads.Tail = NULL;
1340 thread->Next = NULL;
1344 SHORTREL(&glThreadListLock);
1349 # error "Unimplemented scheduling algorithm"
1352 // Make the new thread non-schedulable
1353 thread->CurCPU = CPU;
1354 thread->Remaining = thread->Quantum;
1356 SHORTREL( &glThreadListLock );
1362 EXPORT(Threads_GetUID);
1363 EXPORT(Threads_GetGID);