3 * - By John Hodge (thePowersGang)
5 * - Common Thread Control
9 #include <threads_int.h>
12 #include <semaphore.h>
13 #include <vfs_threads.h> // VFS Handle maintainence
16 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
17 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
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
42 void Threads_Init(void);
44 void Threads_Delete(tThread *Thread);
45 int Threads_SetName(const char *NewName);
47 char *Threads_GetName(tTID ID);
49 void Threads_SetPriority(tThread *Thread, int Pri);
50 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
51 int Threads_WaitTID(int TID, int *status);
52 tThread *Threads_GetThread(Uint TID);
54 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread);
55 void Threads_int_AddToList(tThreadList *List, tThread *Thread);
57 void Threads_Exit(int TID, int Status);
58 void Threads_Kill(tThread *Thread, int Status);
59 void Threads_Yield(void);
60 void Threads_Sleep(void);
61 int Threads_Wake(tThread *Thread);
62 void Threads_AddActive(tThread *Thread);
63 tThread *Threads_RemActive(void);
65 void Threads_ToggleTrace(int TID);
66 void Threads_Fault(int Num);
67 void Threads_SegFault(tVAddr Addr);
69 int Threads_GetPID(void);
70 int Threads_GetTID(void);
71 tUID Threads_GetUID(void);
72 tGID Threads_GetGID(void);
73 int Threads_SetUID(Uint *Errno, tUID ID);
74 int Threads_SetGID(Uint *Errno, tUID ID);
76 void Threads_int_DumpThread(tThread *thread);
77 void Threads_Dump(void);
78 void Threads_DumpActive(void);
82 struct sProcess gProcessZero = {
84 // Only used for the core kernel
85 tThread gThreadZero = {
86 .Status = THREAD_STAT_ACTIVE, // Status
87 .ThreadName = (char*)"ThreadZero", // Name
88 .Quantum = DEFAULT_QUANTUM, // Default Quantum
89 .Remaining = DEFAULT_QUANTUM, // Current Quantum
90 .Priority = DEFAULT_PRIORITY // Number of tickets
94 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
95 // --- Current State ---
96 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
97 volatile Uint giNextTID = 1; // Next TID to allocate
98 // --- Thread Lists ---
99 tThread *gAllThreads = NULL; // All allocated threads
100 tThreadList gSleepingThreads; // Sleeping Threads
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 tThreadList gActiveThreads; // Currently Running Threads
108 #elif SCHEDULER_TYPE == SCHED_RR_SIM
109 tThreadList gActiveThreads; // Currently Running Threads
110 #elif SCHEDULER_TYPE == SCHED_RR_PRI
111 tThreadList 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));
127 Log_Debug("Threads", ".KernelStack = %i", offsetof(tThread, KernelStack));
129 // Create Initial Task
130 gAllThreads = &gThreadZero;
131 giNumActiveThreads = 1;
132 gThreadZero.Process = &gProcessZero;
137 void Threads_Delete(tThread *Thread)
140 Thread->Status = THREAD_STAT_BURIED;
142 // Clear out process state
143 Proc_ClearThread(Thread);
145 Thread->Process->nThreads --;
147 if( Thread->Process->FirstThread == Thread )
149 Thread->Process->FirstThread = Thread->ProcessNext;
153 tThread *prev = Thread->Process->FirstThread;
154 while(prev && prev->ProcessNext != Thread)
155 prev = prev->ProcessNext;
157 Log_Error("Threads", "Thread %p(%i %s) is not on the process's list",
158 Thread, Thread->TID, Thread->ThreadName
161 prev->ProcessNext = Thread->ProcessNext;
164 // If the final thread is being terminated, clean up the process
165 if( Thread->Process->nThreads == 0 )
167 tProcess *proc = Thread->Process;
169 VFS_CloseAllUserHandles();
170 // Architecture cleanup
171 Proc_ClearProcess( proc );
172 // VFS Configuration strings
173 if( proc->CurrentWorkingDir)
174 free( proc->CurrentWorkingDir );
176 free( proc->RootDir );
177 // Process descriptor
182 if( IsHeap(Thread->ThreadName) )
183 free(Thread->ThreadName);
185 // Remove from global list
186 // TODO: Lock this too
187 if( Thread == gAllThreads )
188 gAllThreads = Thread->GlobalNext;
190 Thread->GlobalPrev->GlobalNext = Thread->GlobalNext;
196 * \fn void Threads_SetName(const char *NewName)
197 * \brief Sets the current thread's name
198 * \param NewName New name for the thread
199 * \return Boolean Failure
201 int Threads_SetName(const char *NewName)
203 tThread *cur = Proc_GetCurThread();
204 char *oldname = cur->ThreadName;
206 // NOTE: There is a possibility of non-thread safety here
207 // A thread could read the current name pointer before it is zeroed
209 cur->ThreadName = NULL;
211 if( IsHeap(oldname) ) free( oldname );
212 cur->ThreadName = strdup(NewName);
214 // Log_Debug("Threads", "Thread renamed to '%s'", NewName);
220 * \fn char *Threads_GetName(int ID)
221 * \brief Gets a thread's name
222 * \param ID Thread ID (-1 indicates current thread)
223 * \return Pointer to name
224 * \retval NULL Failure
226 char *Threads_GetName(tTID ID)
229 return Proc_GetCurThread()->ThreadName;
231 return Threads_GetThread(ID)->ThreadName;
235 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
236 * \brief Sets the priority of a task
237 * \param Thread Thread to update ticket count (NULL means current thread)
238 * \param Pri New priority
240 void Threads_SetPriority(tThread *Thread, int Pri)
242 // Get current thread
243 if(Thread == NULL) Thread = Proc_GetCurThread();
245 // - If < 0, set to lowest priority
246 // - Minumum priority is actualy a high number, 0 is highest
247 if(Pri < 0) Pri = MIN_PRIORITY;
248 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
250 // Do we actually have to do anything?
251 if( Pri == Thread->Priority ) return;
253 #if SCHEDULER_TYPE == SCHED_RR_PRI
254 if( Thread != Proc_GetCurThread() )
256 SHORTLOCK( &glThreadListLock );
257 // Remove from old priority
258 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
260 Threads_int_AddToList( &gaActiveThreads[Pri], Thread );
261 Thread->Priority = Pri;
262 SHORTREL( &glThreadListLock );
265 Thread->Priority = Pri;
267 // If this isn't the current thread, we need to lock
268 if( Thread != Proc_GetCurThread() )
270 SHORTLOCK( &glThreadListLock );
272 #if SCHEDULER_TYPE == SCHED_LOTTERY
273 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
274 # if DEBUG_TRACE_TICKETS
275 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
277 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
280 Thread->Priority = Pri;
281 SHORTREL( &glThreadListLock );
284 Thread->Priority = Pri;
287 #if DEBUG_TRACE_STATE
288 Log("Threads_SetPriority: %p(%i %s) pri set %i",
289 Thread, Thread->TID, Thread->ThreadName,
295 * \brief Clone the TCB of the current thread
296 * \param Flags Flags for something... (What is this for?)
298 tThread *Threads_CloneTCB(Uint Flags)
301 cur = Proc_GetCurThread();
303 // Allocate and duplicate
304 new = malloc(sizeof(tThread));
305 if(new == NULL) { errno = -ENOMEM; return NULL; }
306 memcpy(new, cur, sizeof(tThread));
310 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
311 new->Status = THREAD_STAT_PREINIT;
315 new->TID = giNextTID++;
317 new->bInstrTrace = 0;
320 new->ThreadName = strdup(cur->ThreadName);
322 // Set Thread Group ID (PID)
323 if(Flags & CLONE_VM) {
324 tProcess *newproc, *oldproc;
325 oldproc = cur->Process;
326 new->Process = malloc( sizeof(struct sProcess) );
327 newproc = new->Process;
328 newproc->PID = new->TID;
329 if( Flags & CLONE_PGID )
330 newproc->PGID = oldproc->PGID;
332 newproc->PGID = newproc->PID;
333 newproc->UID = oldproc->UID;
334 newproc->GID = oldproc->GID;
335 newproc->MaxFD = oldproc->MaxFD;
336 if( oldproc->CurrentWorkingDir )
337 newproc->CurrentWorkingDir = strdup( oldproc->CurrentWorkingDir );
339 newproc->CurrentWorkingDir = NULL;
340 if( oldproc->RootDir )
341 newproc->RootDir = strdup( oldproc->RootDir );
343 newproc->RootDir = NULL;
344 newproc->nThreads = 1;
345 // Reference all handles in the VFS
346 VFS_ReferenceUserHandles();
348 newproc->FirstThread = new;
349 new->ProcessNext = NULL;
352 new->Process->nThreads ++;
353 new->Process = cur->Process;
355 new->ProcessNext = new->Process->FirstThread;
356 new->Process->FirstThread = new;
359 // Messages are not inherited
360 new->Messages = NULL;
361 new->LastMessage = NULL;
364 new->Remaining = new->Quantum = cur->Quantum;
365 new->Priority = cur->Priority;
368 // Set Signal Handlers
369 new->CurFaultNum = 0;
370 new->FaultHandler = cur->FaultHandler;
372 // Maintain a global list of threads
373 SHORTLOCK( &glThreadListLock );
374 new->GlobalPrev = NULL; // Protect against bugs
375 new->GlobalNext = gAllThreads;
376 gAllThreads->GlobalPrev = new;
378 SHORTREL( &glThreadListLock );
384 * \brief Clone the TCB of the kernel thread
386 tThread *Threads_CloneThreadZero(void)
390 // Allocate and duplicate
391 new = malloc(sizeof(tThread));
395 memcpy(new, &gThreadZero, sizeof(tThread));
397 new->Process->nThreads ++;
401 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
402 new->Status = THREAD_STAT_PREINIT;
406 new->TID = giNextTID++;
410 new->ThreadName = NULL;
412 // Messages are not inherited
413 new->Messages = NULL;
414 new->LastMessage = NULL;
417 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
418 new->Priority = DEFAULT_PRIORITY;
419 new->bInstrTrace = 0;
421 // Set Signal Handlers
422 new->CurFaultNum = 0;
423 new->FaultHandler = 0;
425 // Maintain a global list of threads
426 SHORTLOCK( &glThreadListLock );
427 new->GlobalPrev = NULL; // Protect against bugs
428 new->GlobalNext = gAllThreads;
429 gAllThreads->GlobalPrev = new;
431 SHORTREL( &glThreadListLock );
437 * \brief Wait for a task to change state
438 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
439 * \param Status Thread return status
440 * \return TID of child that changed state
442 tTID Threads_WaitTID(int TID, int *Status)
446 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
450 // Any peer/child thread
452 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
458 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
464 tThread *t = Threads_GetThread(TID);
467 // Wait for the thread to die!
468 // TODO: Handle child also being suspended if wanted
469 while(t->Status != THREAD_STAT_ZOMBIE) {
471 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
472 Threads_GetTID(), t->TID, t->Status);
479 case THREAD_STAT_ZOMBIE:
481 t->Status = THREAD_STAT_DEAD;
482 // TODO: Child return value?
483 if(Status) *Status = t->RetStatus;
484 // add to delete queue
488 if(Status) *Status = -1;
498 * \brief Gets a thread given its TID
499 * \param TID Thread ID
500 * \return Thread pointer
502 tThread *Threads_GetThread(Uint TID)
506 // Search global list
507 for(thread = gAllThreads;
509 thread = thread->GlobalNext)
511 if(thread->TID == TID)
515 Log("Unable to find TID %i on main list\n", TID);
521 * \brief Deletes an entry from a list
522 * \param List Pointer to the list head
523 * \param Thread Thread to find
526 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
528 tThread *ret, *prev = NULL;
530 for(ret = List->Head;
531 ret && ret != Thread;
532 prev = ret, ret = ret->Next
535 // Is the thread on the list
537 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
542 List->Head = Thread->Next;
543 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
546 prev->Next = Thread->Next;
547 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
549 if( Thread->Next == NULL )
555 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
558 List->Tail->Next = Thread;
566 * \brief Exit the current process (or another?)
567 * \param TID Thread ID to kill
568 * \param Status Exit status
570 void Threads_Exit(int TID, int Status)
573 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
575 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
577 // Halt forever, just in case
582 * \fn void Threads_Kill(tThread *Thread, int Status)
583 * \brief Kill a thread
584 * \param Thread Thread to kill
585 * \param Status Status code to return to the parent
587 void Threads_Kill(tThread *Thread, int Status)
590 int isCurThread = Thread == Proc_GetCurThread();
592 // TODO: Disown all children?
596 // TODO: I should keep a .Children list
597 for(child = gAllThreads;
599 child = child->GlobalNext)
601 if(child->Parent == Thread)
602 child->Parent = &gThreadZero;
607 ///\note Double lock is needed due to overlap of lock areas
609 // Lock thread (stop us recieving messages)
610 SHORTLOCK( &Thread->IsLocked );
612 // Clear Message Queue
613 while( Thread->Messages )
615 msg = Thread->Messages->Next;
616 free( Thread->Messages );
617 Thread->Messages = msg;
621 SHORTLOCK( &glThreadListLock );
623 switch(Thread->Status)
625 case THREAD_STAT_PREINIT: // Only on main list
628 // Currently active thread
629 case THREAD_STAT_ACTIVE:
630 if( Thread != Proc_GetCurThread() )
632 #if SCHEDULER_TYPE == SCHED_RR_PRI
633 tThreadList *list = &gaActiveThreads[Thread->Priority];
635 tThreadList *list = &gActiveThreads;
637 if( Threads_int_DelFromQueue( list, Thread ) )
642 Log_Warning("Threads",
643 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
644 Thread, Thread->TID, Thread->ThreadName
647 #if SCHEDULER_TYPE == SCHED_LOTTERY
648 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
651 // Ensure that we are not rescheduled
652 Thread->Remaining = 0; // Clear Remaining Quantum
653 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
655 // Update bookkeeping
656 giNumActiveThreads --;
658 // Kill it while it sleeps!
659 case THREAD_STAT_SLEEPING:
660 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
662 Log_Warning("Threads",
663 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
664 Thread, Thread->TID, Thread->ThreadName
669 // Brains!... You cannot kill something that is already dead
670 case THREAD_STAT_ZOMBIE:
671 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
672 Thread, Thread->TID, Thread->ThreadName);
673 SHORTREL( &glThreadListLock );
674 SHORTREL( &Thread->IsLocked );
678 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
684 Thread->RetStatus = Status;
686 SHORTREL( &Thread->IsLocked );
688 Thread->Status = THREAD_STAT_ZOMBIE;
689 SHORTREL( &glThreadListLock );
690 // TODO: Send something like SIGCHLD
691 Threads_Wake( Thread->Parent );
693 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
704 * \brief Yield remainder of the current thread's timeslice
706 void Threads_Yield(void)
708 // Log("Threads_Yield: by %p", __builtin_return_address(0));
713 * \fn void Threads_Sleep(void)
714 * \brief Take the current process off the run queue
716 void Threads_Sleep(void)
718 tThread *cur = Proc_GetCurThread();
721 SHORTLOCK( &glThreadListLock );
723 // Don't sleep if there is a message waiting
724 if( cur->Messages ) {
725 SHORTREL( &glThreadListLock );
729 // Remove us from running queue
731 // Mark thread as sleeping
732 cur->Status = THREAD_STAT_SLEEPING;
734 // Add to Sleeping List (at the top)
735 Threads_int_AddToList( &gSleepingThreads, cur );
737 #if DEBUG_TRACE_STATE
738 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
742 SHORTREL( &glThreadListLock );
744 while(cur->Status != THREAD_STAT_ACTIVE) {
746 if( cur->Status != THREAD_STAT_ACTIVE )
747 Log("%i - Huh? why am I up? zzzz...", cur->TID);
753 * \brief Wakes a sleeping/waiting thread up
754 * \param Thread Thread to wake
755 * \return Boolean Failure (Returns ERRNO)
756 * \warning This should ONLY be called with task switches disabled
758 int Threads_Wake(tThread *Thread)
763 switch(Thread->Status)
765 case THREAD_STAT_ACTIVE:
766 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
769 case THREAD_STAT_SLEEPING:
770 SHORTLOCK( &glThreadListLock );
771 // Remove from sleeping queue
772 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
774 SHORTREL( &glThreadListLock );
775 Threads_AddActive( Thread );
777 #if DEBUG_TRACE_STATE
778 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
782 case THREAD_STAT_SEMAPHORESLEEP: {
784 tThread *th, *prev=NULL;
786 sem = Thread->WaitPointer;
788 SHORTLOCK( &sem->Protector );
790 // Remove from sleeping queue
791 for( th = sem->Waiting; th; prev = th, th = th->Next )
792 if( th == Thread ) break;
796 prev->Next = Thread->Next;
798 sem->Waiting = Thread->Next;
799 if(sem->LastWaiting == Thread)
800 sem->LastWaiting = prev;
805 for( th = sem->Signaling; th; prev = th, th = th->Next )
806 if( th == Thread ) break;
808 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
809 Thread, Thread->TID, Thread->ThreadName,
810 sem, sem->ModName, sem->Name);
815 prev->Next = Thread->Next;
817 sem->Signaling = Thread->Next;
818 if(sem->LastSignaling == Thread)
819 sem->LastSignaling = prev;
822 Thread->RetStatus = 0; // It didn't get anything
823 Threads_AddActive( Thread );
825 #if DEBUG_TRACE_STATE
826 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
828 SHORTREL( &sem->Protector );
831 case THREAD_STAT_WAITING:
832 Warning("Threads_Wake - Waiting threads are not currently supported");
835 case THREAD_STAT_DEAD:
836 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
840 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
846 * \brief Wake a thread given the TID
847 * \param TID Thread ID to wake
848 * \return Boolean Faulure (errno)
850 int Threads_WakeTID(tTID TID)
852 tThread *thread = Threads_GetThread(TID);
856 ret = Threads_Wake( thread );
857 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
861 void Threads_ToggleTrace(int TID)
863 tThread *thread = Threads_GetThread(TID);
865 thread->bInstrTrace = !thread->bInstrTrace;
869 * \brief Adds a thread to the active queue
871 void Threads_AddActive(tThread *Thread)
873 SHORTLOCK( &glThreadListLock );
875 if( Thread->Status == THREAD_STAT_ACTIVE ) {
876 tThread *cur = Proc_GetCurThread();
877 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
878 __builtin_return_address(0),
879 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
880 SHORTREL( &glThreadListLock );
885 Thread->Status = THREAD_STAT_ACTIVE;
886 // Thread->CurCPU = -1;
887 // Add to active list
889 #if SCHEDULER_TYPE == SCHED_RR_PRI
890 tThreadList *list = &gaActiveThreads[Thread->Priority];
892 tThreadList *list = &gActiveThreads;
894 Threads_int_AddToList( list, Thread );
897 // Update bookkeeping
898 giNumActiveThreads ++;
900 #if SCHEDULER_TYPE == SCHED_LOTTERY
903 // Only change the ticket count if the thread is un-scheduled
904 if(Thread->CurCPU != -1)
907 delta = caiTICKET_COUNTS[ Thread->Priority ];
909 giFreeTickets += delta;
910 # if DEBUG_TRACE_TICKETS
911 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
912 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
919 SHORTREL( &glThreadListLock );
923 * \brief Removes the current thread from the active queue
924 * \warning This should ONLY be called with the lock held
925 * \return Current thread pointer
927 tThread *Threads_RemActive(void)
929 giNumActiveThreads --;
930 return Proc_GetCurThread();
934 * \fn void Threads_SetFaultHandler(Uint Handler)
935 * \brief Sets the signal handler for a signal
937 void Threads_SetFaultHandler(Uint Handler)
939 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
940 Proc_GetCurThread()->FaultHandler = Handler;
944 * \fn void Threads_Fault(int Num)
945 * \brief Calls a fault handler
947 void Threads_Fault(int Num)
949 tThread *thread = Proc_GetCurThread();
953 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
955 switch(thread->FaultHandler)
958 Threads_Kill(thread, -1);
961 case 1: // Dump Core?
962 Threads_Kill(thread, -1);
967 // Double Fault? Oh, F**k
968 if(thread->CurFaultNum != 0) {
969 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
970 Threads_Kill(thread, -1); // For now, just kill
974 thread->CurFaultNum = Num;
976 Proc_CallFaultHandler(thread);
980 * \fn void Threads_SegFault(tVAddr Addr)
981 * \brief Called when a Segment Fault occurs
983 void Threads_SegFault(tVAddr Addr)
985 tThread *cur = Proc_GetCurThread();
986 cur->bInstrTrace = 0;
987 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
988 MM_DumpTables(0, USER_MAX);
990 //Threads_Exit( 0, -1 );
993 // --- Process Structure Access Functions ---
994 tPGID Threads_GetPGID(void)
996 return Proc_GetCurThread()->Process->PGID;
998 tPID Threads_GetPID(void)
1000 return Proc_GetCurThread()->Process->PID;
1002 tTID Threads_GetTID(void)
1004 return Proc_GetCurThread()->TID;
1006 tUID Threads_GetUID(void)
1008 return Proc_GetCurThread()->Process->UID;
1010 tGID Threads_GetGID(void)
1012 return Proc_GetCurThread()->Process->GID;
1015 int Threads_SetUID(tUID ID)
1017 tThread *t = Proc_GetCurThread();
1018 if( t->Process->UID != 0 ) {
1022 Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1023 t->Process->UID = ID;
1027 int Threads_SetGID(tGID ID)
1029 tThread *t = Proc_GetCurThread();
1030 if( t->Process->UID != 0 ) {
1034 Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1035 t->Process->GID = ID;
1039 // --- Per-thread storage ---
1040 int *Threads_GetErrno(void)
1042 return &Proc_GetCurThread()->_errno;
1045 // --- Configuration ---
1046 int *Threads_GetMaxFD(void)
1048 return &Proc_GetCurThread()->Process->MaxFD;
1050 char **Threads_GetChroot(void)
1052 return &Proc_GetCurThread()->Process->RootDir;
1054 char **Threads_GetCWD(void)
1056 return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1060 void Threads_int_DumpThread(tThread *thread)
1062 Log(" %p %i (%i) - %s (CPU %i) - %i (%s)",
1063 thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU,
1064 thread->Status, casTHREAD_STAT[thread->Status]
1066 switch(thread->Status)
1068 case THREAD_STAT_MUTEXSLEEP:
1069 Log(" Mutex Pointer: %p", thread->WaitPointer);
1071 case THREAD_STAT_SEMAPHORESLEEP:
1072 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1073 Log(" Semaphore Name: %s:%s",
1074 ((tSemaphore*)thread->WaitPointer)->ModName,
1075 ((tSemaphore*)thread->WaitPointer)->Name
1078 case THREAD_STAT_ZOMBIE:
1079 Log(" Return Status: %i", thread->RetStatus);
1083 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1084 Log(" KStack 0x%x", thread->KernelStack);
1085 if( thread->bInstrTrace )
1086 Log(" Tracing Enabled");
1087 Proc_DumpThreadCPUState(thread);
1091 * \fn void Threads_Dump(void)
1093 void Threads_DumpActive(void)
1097 #if SCHEDULER_TYPE == SCHED_RR_PRI
1101 Log("Active Threads: (%i reported)", giNumActiveThreads);
1103 #if SCHEDULER_TYPE == SCHED_RR_PRI
1104 for( i = 0; i < MIN_PRIORITY+1; i++ )
1106 list = &gaActiveThreads[i];
1108 list = &gActiveThreads;
1110 for(thread=list->Head;thread;thread=thread->Next)
1112 Threads_int_DumpThread(thread);
1113 if(thread->Status != THREAD_STAT_ACTIVE)
1114 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1115 thread->Status, THREAD_STAT_ACTIVE);
1118 #if SCHEDULER_TYPE == SCHED_RR_PRI
1124 * \fn void Threads_Dump(void)
1125 * \brief Dumps a list of currently running threads
1127 void Threads_Dump(void)
1131 Log("--- Thread Dump ---");
1132 Threads_DumpActive();
1134 Log("All Threads:");
1135 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1137 Threads_int_DumpThread(thread);
1142 * \brief Gets the next thread to run
1143 * \param CPU Current CPU
1144 * \param Last The thread the CPU was running
1146 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1150 // If this CPU has the lock, we must let it complete
1151 if( CPU_HAS_LOCK( &glThreadListLock ) )
1154 // Don't change threads if the current CPU has switches disabled
1155 if( gaThreads_NoTaskSwitch[CPU] )
1159 SHORTLOCK( &glThreadListLock );
1161 // Make sure the current (well, old) thread is marked as de-scheduled
1162 if(Last) Last->CurCPU = -1;
1164 // No active threads, just take a nap
1165 if(giNumActiveThreads == 0) {
1166 SHORTREL( &glThreadListLock );
1167 #if DEBUG_TRACE_TICKETS
1168 Log("No active threads");
1174 #if SCHEDULER_TYPE != SCHED_RR_PRI
1175 // Special case: 1 thread
1176 if(giNumActiveThreads == 1) {
1177 if( gActiveThreads.Head->CurCPU == -1 )
1178 gActiveThreads.Head->CurCPU = CPU;
1180 SHORTREL( &glThreadListLock );
1182 if( gActiveThreads.Head->CurCPU == CPU )
1183 return gActiveThreads.Head;
1185 return NULL; // CPU has nothing to do
1190 // Allow the old thread to be scheduled again
1192 if( Last->Status == THREAD_STAT_ACTIVE ) {
1194 #if SCHEDULER_TYPE == SCHED_LOTTERY
1195 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1196 # if DEBUG_TRACE_TICKETS
1197 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1198 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1199 caiTICKET_COUNTS[ Last->Priority ]);
1203 #if SCHEDULER_TYPE == SCHED_RR_PRI
1204 list = &gaActiveThreads[ Last->Priority ];
1206 list = &gActiveThreads;
1208 // Add to end of list
1209 Threads_int_AddToList( list, Last );
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.Head; thread; thread = thread->Next)
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.Head; thread; prev = thread, thread = thread->Next )
1256 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1257 number -= caiTICKET_COUNTS[ thread->Priority ];
1260 // If we didn't find a thread, something went wrong
1264 for(thread=gActiveThreads;thread;thread=thread->Next) {
1265 if(thread->CurCPU >= 0) continue;
1266 number += caiTICKET_COUNTS[ thread->Priority ];
1268 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1269 giFreeTickets, number);
1274 prev->Next = thread->Next;
1276 gActiveThreads.Head = thread->Next;
1278 gActiveThreads.Tail = prev;
1280 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1281 # if DEBUG_TRACE_TICKETS
1282 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1283 CPU, thread, thread->TID, thread->ThreadName,
1284 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1289 // Priority based round robin scheduler
1291 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1295 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1297 if( !gaActiveThreads[i].Head )
1300 thread = gaActiveThreads[i].Head;
1303 gaActiveThreads[i].Head = thread->Next;
1305 gaActiveThreads[i].Tail = NULL;
1306 thread->Next = NULL;
1312 SHORTREL(&glThreadListLock);
1315 if( thread->Status != THREAD_STAT_ACTIVE ) {
1316 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1319 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1321 // Get the next thread off the list
1322 thread = gActiveThreads.Head;
1323 gActiveThreads.Head = thread->Next;
1325 gaActiveThreads.Tail = NULL;
1326 thread->Next = NULL;
1330 SHORTREL(&glThreadListLock);
1335 # error "Unimplemented scheduling algorithm"
1338 // Make the new thread non-schedulable
1339 thread->CurCPU = CPU;
1340 thread->Remaining = thread->Quantum;
1342 SHORTREL( &glThreadListLock );
1348 EXPORT(Threads_GetUID);
1349 EXPORT(Threads_GetGID);