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; thread; thread = thread->GlobalNext )
509 if(thread->TID == TID)
513 Log_Notice("Threads", "Unable to find TID %i on main list\n", TID);
519 * \brief Deletes an entry from a list
520 * \param List Pointer to the list head
521 * \param Thread Thread to find
524 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
526 tThread *ret, *prev = NULL;
528 for(ret = List->Head;
529 ret && ret != Thread;
530 prev = ret, ret = ret->Next
533 // Is the thread on the list
535 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
540 List->Head = Thread->Next;
541 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
544 prev->Next = Thread->Next;
545 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
547 if( Thread->Next == NULL )
553 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
556 List->Tail->Next = Thread;
564 * \brief Exit the current process (or another?)
565 * \param TID Thread ID to kill
566 * \param Status Exit status
568 void Threads_Exit(int TID, int Status)
571 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
573 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
575 // Halt forever, just in case
580 * \fn void Threads_Kill(tThread *Thread, int Status)
581 * \brief Kill a thread
582 * \param Thread Thread to kill
583 * \param Status Status code to return to the parent
585 void Threads_Kill(tThread *Thread, int Status)
588 int isCurThread = Thread == Proc_GetCurThread();
590 // TODO: Disown all children?
594 // TODO: I should keep a .Children list
595 for(child = gAllThreads;
597 child = child->GlobalNext)
599 if(child->Parent == Thread)
600 child->Parent = &gThreadZero;
605 ///\note Double lock is needed due to overlap of lock areas
607 // Lock thread (stop us recieving messages)
608 SHORTLOCK( &Thread->IsLocked );
610 // Clear Message Queue
611 while( Thread->Messages )
613 msg = Thread->Messages->Next;
614 free( Thread->Messages );
615 Thread->Messages = msg;
619 SHORTLOCK( &glThreadListLock );
621 switch(Thread->Status)
623 case THREAD_STAT_PREINIT: // Only on main list
626 // Currently active thread
627 case THREAD_STAT_ACTIVE:
628 if( Thread != Proc_GetCurThread() )
630 #if SCHEDULER_TYPE == SCHED_RR_PRI
631 tThreadList *list = &gaActiveThreads[Thread->Priority];
633 tThreadList *list = &gActiveThreads;
635 if( Threads_int_DelFromQueue( list, Thread ) )
640 Log_Warning("Threads",
641 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
642 Thread, Thread->TID, Thread->ThreadName
645 #if SCHEDULER_TYPE == SCHED_LOTTERY
646 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
649 // Ensure that we are not rescheduled
650 Thread->Remaining = 0; // Clear Remaining Quantum
651 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
653 // Update bookkeeping
654 giNumActiveThreads --;
656 // Kill it while it sleeps!
657 case THREAD_STAT_SLEEPING:
658 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
660 Log_Warning("Threads",
661 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
662 Thread, Thread->TID, Thread->ThreadName
667 // Brains!... You cannot kill something that is already dead
668 case THREAD_STAT_ZOMBIE:
669 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
670 Thread, Thread->TID, Thread->ThreadName);
671 SHORTREL( &glThreadListLock );
672 SHORTREL( &Thread->IsLocked );
676 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
682 Thread->RetStatus = Status;
684 SHORTREL( &Thread->IsLocked );
686 Thread->Status = THREAD_STAT_ZOMBIE;
687 SHORTREL( &glThreadListLock );
688 // TODO: Send something like SIGCHLD
689 Threads_Wake( Thread->Parent );
691 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
702 * \brief Yield remainder of the current thread's timeslice
704 void Threads_Yield(void)
706 // Log("Threads_Yield: by %p", __builtin_return_address(0));
711 * \fn void Threads_Sleep(void)
712 * \brief Take the current process off the run queue
714 void Threads_Sleep(void)
716 tThread *cur = Proc_GetCurThread();
719 SHORTLOCK( &glThreadListLock );
721 // Don't sleep if there is a message waiting
722 if( cur->Messages ) {
723 SHORTREL( &glThreadListLock );
727 // Remove us from running queue
729 // Mark thread as sleeping
730 cur->Status = THREAD_STAT_SLEEPING;
732 // Add to Sleeping List (at the top)
733 Threads_int_AddToList( &gSleepingThreads, cur );
735 #if DEBUG_TRACE_STATE
736 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
740 SHORTREL( &glThreadListLock );
742 while(cur->Status != THREAD_STAT_ACTIVE) {
744 if( cur->Status != THREAD_STAT_ACTIVE )
745 Log("%i - Huh? why am I up? zzzz...", cur->TID);
751 * \brief Wakes a sleeping/waiting thread up
752 * \param Thread Thread to wake
753 * \return Boolean Failure (Returns ERRNO)
754 * \warning This should ONLY be called with task switches disabled
756 int Threads_Wake(tThread *Thread)
761 switch(Thread->Status)
763 case THREAD_STAT_ACTIVE:
764 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
767 case THREAD_STAT_SLEEPING:
768 SHORTLOCK( &glThreadListLock );
769 // Remove from sleeping queue
770 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
772 SHORTREL( &glThreadListLock );
773 Threads_AddActive( Thread );
775 #if DEBUG_TRACE_STATE
776 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
780 case THREAD_STAT_SEMAPHORESLEEP: {
782 tThread *th, *prev=NULL;
784 sem = Thread->WaitPointer;
786 SHORTLOCK( &sem->Protector );
788 // Remove from sleeping queue
789 for( th = sem->Waiting; th; prev = th, th = th->Next )
790 if( th == Thread ) break;
794 prev->Next = Thread->Next;
796 sem->Waiting = Thread->Next;
797 if(sem->LastWaiting == Thread)
798 sem->LastWaiting = prev;
803 for( th = sem->Signaling; th; prev = th, th = th->Next )
804 if( th == Thread ) break;
806 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
807 Thread, Thread->TID, Thread->ThreadName,
808 sem, sem->ModName, sem->Name);
813 prev->Next = Thread->Next;
815 sem->Signaling = Thread->Next;
816 if(sem->LastSignaling == Thread)
817 sem->LastSignaling = prev;
820 Thread->RetStatus = 0; // It didn't get anything
821 Threads_AddActive( Thread );
823 #if DEBUG_TRACE_STATE
824 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
826 SHORTREL( &sem->Protector );
829 case THREAD_STAT_WAITING:
830 Warning("Threads_Wake - Waiting threads are not currently supported");
833 case THREAD_STAT_DEAD:
834 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
838 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
844 * \brief Wake a thread given the TID
845 * \param TID Thread ID to wake
846 * \return Boolean Faulure (errno)
848 int Threads_WakeTID(tTID TID)
850 tThread *thread = Threads_GetThread(TID);
854 ret = Threads_Wake( thread );
855 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
859 void Threads_ToggleTrace(int TID)
861 tThread *thread = Threads_GetThread(TID);
863 thread->bInstrTrace = !thread->bInstrTrace;
867 * \brief Adds a thread to the active queue
869 void Threads_AddActive(tThread *Thread)
871 SHORTLOCK( &glThreadListLock );
873 if( Thread->Status == THREAD_STAT_ACTIVE ) {
874 tThread *cur = Proc_GetCurThread();
875 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
876 __builtin_return_address(0),
877 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
878 SHORTREL( &glThreadListLock );
883 Thread->Status = THREAD_STAT_ACTIVE;
884 // Thread->CurCPU = -1;
885 // Add to active list
887 #if SCHEDULER_TYPE == SCHED_RR_PRI
888 tThreadList *list = &gaActiveThreads[Thread->Priority];
890 tThreadList *list = &gActiveThreads;
892 Threads_int_AddToList( list, Thread );
895 // Update bookkeeping
896 giNumActiveThreads ++;
898 #if SCHEDULER_TYPE == SCHED_LOTTERY
901 // Only change the ticket count if the thread is un-scheduled
902 if(Thread->CurCPU != -1)
905 delta = caiTICKET_COUNTS[ Thread->Priority ];
907 giFreeTickets += delta;
908 # if DEBUG_TRACE_TICKETS
909 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
910 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
917 SHORTREL( &glThreadListLock );
921 * \brief Removes the current thread from the active queue
922 * \warning This should ONLY be called with the lock held
923 * \return Current thread pointer
925 tThread *Threads_RemActive(void)
927 giNumActiveThreads --;
928 return Proc_GetCurThread();
932 * \fn void Threads_SetFaultHandler(Uint Handler)
933 * \brief Sets the signal handler for a signal
935 void Threads_SetFaultHandler(Uint Handler)
937 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
938 Proc_GetCurThread()->FaultHandler = Handler;
942 * \fn void Threads_Fault(int Num)
943 * \brief Calls a fault handler
945 void Threads_Fault(int Num)
947 tThread *thread = Proc_GetCurThread();
951 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
953 switch(thread->FaultHandler)
956 Threads_Kill(thread, -1);
959 case 1: // Dump Core?
960 Threads_Kill(thread, -1);
965 // Double Fault? Oh, F**k
966 if(thread->CurFaultNum != 0) {
967 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
968 Threads_Kill(thread, -1); // For now, just kill
972 thread->CurFaultNum = Num;
974 Proc_CallFaultHandler(thread);
978 * \fn void Threads_SegFault(tVAddr Addr)
979 * \brief Called when a Segment Fault occurs
981 void Threads_SegFault(tVAddr Addr)
983 tThread *cur = Proc_GetCurThread();
984 cur->bInstrTrace = 0;
985 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
986 MM_DumpTables(0, USER_MAX);
988 //Threads_Exit( 0, -1 );
991 // --- Process Structure Access Functions ---
992 tPGID Threads_GetPGID(void)
994 return Proc_GetCurThread()->Process->PGID;
996 tPID Threads_GetPID(void)
998 return Proc_GetCurThread()->Process->PID;
1000 tTID Threads_GetTID(void)
1002 return Proc_GetCurThread()->TID;
1004 tUID Threads_GetUID(void)
1006 return Proc_GetCurThread()->Process->UID;
1008 tGID Threads_GetGID(void)
1010 return Proc_GetCurThread()->Process->GID;
1013 int Threads_SetUID(tUID ID)
1015 tThread *t = Proc_GetCurThread();
1016 if( t->Process->UID != 0 ) {
1020 Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1021 t->Process->UID = ID;
1025 int Threads_SetGID(tGID ID)
1027 tThread *t = Proc_GetCurThread();
1028 if( t->Process->UID != 0 ) {
1032 Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1033 t->Process->GID = ID;
1037 // --- Per-thread storage ---
1038 int *Threads_GetErrno(void)
1040 return &Proc_GetCurThread()->_errno;
1043 // --- Configuration ---
1044 int *Threads_GetMaxFD(void)
1046 return &Proc_GetCurThread()->Process->MaxFD;
1048 char **Threads_GetChroot(void)
1050 return &Proc_GetCurThread()->Process->RootDir;
1052 char **Threads_GetCWD(void)
1054 return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1058 void Threads_int_DumpThread(tThread *thread)
1060 Log(" %p %i (%i) - %s (CPU %i) - %i (%s)",
1061 thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU,
1062 thread->Status, casTHREAD_STAT[thread->Status]
1064 switch(thread->Status)
1066 case THREAD_STAT_MUTEXSLEEP:
1067 Log(" Mutex Pointer: %p", thread->WaitPointer);
1069 case THREAD_STAT_SEMAPHORESLEEP:
1070 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1071 Log(" Semaphore Name: %s:%s",
1072 ((tSemaphore*)thread->WaitPointer)->ModName,
1073 ((tSemaphore*)thread->WaitPointer)->Name
1076 case THREAD_STAT_ZOMBIE:
1077 Log(" Return Status: %i", thread->RetStatus);
1081 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1082 Log(" KStack %p", thread->KernelStack);
1083 if( thread->bInstrTrace )
1084 Log(" Tracing Enabled");
1085 Proc_DumpThreadCPUState(thread);
1089 * \fn void Threads_Dump(void)
1091 void Threads_DumpActive(void)
1095 #if SCHEDULER_TYPE == SCHED_RR_PRI
1099 Log("Active Threads: (%i reported)", giNumActiveThreads);
1101 #if SCHEDULER_TYPE == SCHED_RR_PRI
1102 for( i = 0; i < MIN_PRIORITY+1; i++ )
1104 list = &gaActiveThreads[i];
1106 list = &gActiveThreads;
1108 for(thread=list->Head;thread;thread=thread->Next)
1110 Threads_int_DumpThread(thread);
1111 if(thread->Status != THREAD_STAT_ACTIVE)
1112 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1113 thread->Status, THREAD_STAT_ACTIVE);
1116 #if SCHEDULER_TYPE == SCHED_RR_PRI
1122 * \fn void Threads_Dump(void)
1123 * \brief Dumps a list of currently running threads
1125 void Threads_Dump(void)
1129 Log("--- Thread Dump ---");
1130 Threads_DumpActive();
1132 Log("All Threads:");
1133 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1135 Threads_int_DumpThread(thread);
1140 * \brief Gets the next thread to run
1141 * \param CPU Current CPU
1142 * \param Last The thread the CPU was running
1144 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1148 // If this CPU has the lock, we must let it complete
1149 if( CPU_HAS_LOCK( &glThreadListLock ) )
1152 // Don't change threads if the current CPU has switches disabled
1153 if( gaThreads_NoTaskSwitch[CPU] )
1157 SHORTLOCK( &glThreadListLock );
1159 // Make sure the current (well, old) thread is marked as de-scheduled
1160 if(Last) Last->CurCPU = -1;
1162 // No active threads, just take a nap
1163 if(giNumActiveThreads == 0) {
1164 SHORTREL( &glThreadListLock );
1165 #if DEBUG_TRACE_TICKETS
1166 Log("No active threads");
1172 #if SCHEDULER_TYPE != SCHED_RR_PRI
1173 // Special case: 1 thread
1174 if(giNumActiveThreads == 1) {
1175 if( gActiveThreads.Head->CurCPU == -1 )
1176 gActiveThreads.Head->CurCPU = CPU;
1178 SHORTREL( &glThreadListLock );
1180 if( gActiveThreads.Head->CurCPU == CPU )
1181 return gActiveThreads.Head;
1183 return NULL; // CPU has nothing to do
1188 // Allow the old thread to be scheduled again
1190 if( Last->Status == THREAD_STAT_ACTIVE ) {
1192 #if SCHEDULER_TYPE == SCHED_LOTTERY
1193 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1194 # if DEBUG_TRACE_TICKETS
1195 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1196 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1197 caiTICKET_COUNTS[ Last->Priority ]);
1201 #if SCHEDULER_TYPE == SCHED_RR_PRI
1202 list = &gaActiveThreads[ Last->Priority ];
1204 list = &gActiveThreads;
1206 // Add to end of list
1207 Threads_int_AddToList( list, Last );
1209 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1211 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1212 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1218 // Lottery Scheduler
1220 #if SCHEDULER_TYPE == SCHED_LOTTERY
1225 for(thread = gActiveThreads.Head; thread; thread = thread->Next)
1227 if(thread->Status != THREAD_STAT_ACTIVE)
1228 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1229 thread, thread->TID, thread->ThreadName, thread->Status);
1230 if(thread->Next == thread) {
1231 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1232 thread, thread->TID, thread->ThreadName, thread->Status);
1234 number += caiTICKET_COUNTS[ thread->Priority ];
1236 if(number != giFreeTickets) {
1237 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1238 giFreeTickets, number, CPU);
1242 // No free tickets (all tasks delegated to cores)
1243 if( giFreeTickets == 0 ) {
1244 SHORTREL(&glThreadListLock);
1248 // Get the ticket number
1249 ticket = number = rand() % giFreeTickets;
1251 // Find the next thread
1252 for(thread = gActiveThreads.Head; thread; prev = thread, thread = thread->Next )
1254 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1255 number -= caiTICKET_COUNTS[ thread->Priority ];
1258 // If we didn't find a thread, something went wrong
1262 for(thread=gActiveThreads;thread;thread=thread->Next) {
1263 if(thread->CurCPU >= 0) continue;
1264 number += caiTICKET_COUNTS[ thread->Priority ];
1266 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1267 giFreeTickets, number);
1272 prev->Next = thread->Next;
1274 gActiveThreads.Head = thread->Next;
1276 gActiveThreads.Tail = prev;
1278 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1279 # if DEBUG_TRACE_TICKETS
1280 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1281 CPU, thread, thread->TID, thread->ThreadName,
1282 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1287 // Priority based round robin scheduler
1289 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1293 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1295 if( !gaActiveThreads[i].Head )
1298 thread = gaActiveThreads[i].Head;
1301 gaActiveThreads[i].Head = thread->Next;
1303 gaActiveThreads[i].Tail = NULL;
1304 thread->Next = NULL;
1310 SHORTREL(&glThreadListLock);
1313 if( thread->Status != THREAD_STAT_ACTIVE ) {
1314 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1317 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1319 // Get the next thread off the list
1320 thread = gActiveThreads.Head;
1321 gActiveThreads.Head = thread->Next;
1323 gaActiveThreads.Tail = NULL;
1324 thread->Next = NULL;
1328 SHORTREL(&glThreadListLock);
1333 # error "Unimplemented scheduling algorithm"
1336 // Make the new thread non-schedulable
1337 thread->CurCPU = CPU;
1338 thread->Remaining = thread->Quantum;
1340 SHORTREL( &glThreadListLock );
1346 EXPORT(Threads_GetUID);
1347 EXPORT(Threads_GetGID);