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
17 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
18 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
22 #define SCHED_LOTTERY 1 // Lottery scheduler
23 #define SCHED_RR_SIM 2 // Single Queue Round Robin
24 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
26 #define SCHEDULER_TYPE SCHED_RR_PRI
29 #define DEFAULT_QUANTUM 5
30 #define DEFAULT_PRIORITY 5
31 #define MIN_PRIORITY 10
43 void Threads_Init(void);
45 void Threads_Delete(tThread *Thread);
46 int Threads_SetName(const char *NewName);
48 char *Threads_GetName(tTID ID);
50 void Threads_SetPriority(tThread *Thread, int Pri);
51 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
52 int Threads_WaitTID(int TID, int *status);
53 tThread *Threads_GetThread(Uint TID);
55 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread);
56 void Threads_int_AddToList(tThreadList *List, tThread *Thread);
58 void Threads_Exit(int TID, int Status);
59 void Threads_Kill(tThread *Thread, int Status);
60 void Threads_Yield(void);
61 void Threads_Sleep(void);
62 int Threads_Wake(tThread *Thread);
63 void Threads_AddActive(tThread *Thread);
64 tThread *Threads_RemActive(void);
66 void Threads_ToggleTrace(int TID);
67 void Threads_Fault(int Num);
68 void Threads_SegFault(tVAddr Addr);
70 int Threads_GetPID(void);
71 int Threads_GetTID(void);
72 tUID Threads_GetUID(void);
73 tGID Threads_GetGID(void);
74 int Threads_SetUID(Uint *Errno, tUID ID);
75 int Threads_SetGID(Uint *Errno, tUID ID);
77 void Threads_int_DumpThread(tThread *thread);
78 void Threads_Dump(void);
79 void Threads_DumpActive(void);
83 struct sProcess gProcessZero = {
85 // Only used for the core kernel
86 tThread gThreadZero = {
87 .Status = THREAD_STAT_ACTIVE, // Status
88 .ThreadName = (char*)"ThreadZero", // Name
89 .Quantum = DEFAULT_QUANTUM, // Default Quantum
90 .Remaining = DEFAULT_QUANTUM, // Current Quantum
91 .Priority = DEFAULT_PRIORITY // Number of tickets
95 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
96 // --- Current State ---
97 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
98 volatile Uint giNextTID = 1; // Next TID to allocate
99 // --- Thread Lists ---
100 tThread *gAllThreads = NULL; // All allocated threads
101 tThreadList gSleepingThreads; // Sleeping Threads
102 int giNumCPUs = 1; // Number of CPUs
103 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
104 // --- Scheduler Types ---
105 #if SCHEDULER_TYPE == SCHED_LOTTERY
106 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
107 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
108 tThreadList gActiveThreads; // Currently Running Threads
109 #elif SCHEDULER_TYPE == SCHED_RR_SIM
110 tThreadList gActiveThreads; // Currently Running Threads
111 #elif SCHEDULER_TYPE == SCHED_RR_PRI
112 tThreadList gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
114 # error "Unkown scheduler type"
119 * \fn void Threads_Init(void)
120 * \brief Initialse the thread list
122 void Threads_Init(void)
126 Log_Debug("Threads", "Offsets of tThread");
127 Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
128 Log_Debug("Threads", ".KernelStack = %i", offsetof(tThread, KernelStack));
130 // Create Initial Task
131 gAllThreads = &gThreadZero;
132 giNumActiveThreads = 1;
133 gThreadZero.Process = &gProcessZero;
138 void Threads_Delete(tThread *Thread)
141 Thread->Status = THREAD_STAT_BURIED;
143 // Clear out process state
144 Proc_ClearThread(Thread);
146 Thread->Process->nThreads --;
148 if( Thread->Process->FirstThread == Thread )
150 Thread->Process->FirstThread = Thread->ProcessNext;
154 tThread *prev = Thread->Process->FirstThread;
155 while(prev && prev->ProcessNext != Thread)
156 prev = prev->ProcessNext;
158 Log_Error("Threads", "Thread %p(%i %s) is not on the process's list",
159 Thread, Thread->TID, Thread->ThreadName
162 prev->ProcessNext = Thread->ProcessNext;
165 // If the final thread is being terminated, clean up the process
166 if( Thread->Process->nThreads == 0 )
168 tProcess *proc = Thread->Process;
170 VFS_CloseAllUserHandles();
171 // Architecture cleanup
172 Proc_ClearProcess( proc );
173 // VFS Configuration strings
174 if( proc->CurrentWorkingDir)
175 free( proc->CurrentWorkingDir );
177 free( proc->RootDir );
178 // Process descriptor
183 if( IsHeap(Thread->ThreadName) )
184 free(Thread->ThreadName);
186 // Remove from global list
187 // TODO: Lock this too
188 if( Thread == gAllThreads )
189 gAllThreads = Thread->GlobalNext;
191 Thread->GlobalPrev->GlobalNext = Thread->GlobalNext;
197 * \fn void Threads_SetName(const char *NewName)
198 * \brief Sets the current thread's name
199 * \param NewName New name for the thread
200 * \return Boolean Failure
202 int Threads_SetName(const char *NewName)
204 tThread *cur = Proc_GetCurThread();
205 char *oldname = cur->ThreadName;
207 // NOTE: There is a possibility of non-thread safety here
208 // A thread could read the current name pointer before it is zeroed
210 cur->ThreadName = NULL;
212 if( IsHeap(oldname) ) free( oldname );
213 cur->ThreadName = strdup(NewName);
215 // Log_Debug("Threads", "Thread renamed to '%s'", NewName);
221 * \fn char *Threads_GetName(int ID)
222 * \brief Gets a thread's name
223 * \param ID Thread ID (-1 indicates current thread)
224 * \return Pointer to name
225 * \retval NULL Failure
227 char *Threads_GetName(tTID ID)
230 return Proc_GetCurThread()->ThreadName;
232 return Threads_GetThread(ID)->ThreadName;
236 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
237 * \brief Sets the priority of a task
238 * \param Thread Thread to update ticket count (NULL means current thread)
239 * \param Pri New priority
241 void Threads_SetPriority(tThread *Thread, int Pri)
243 // Get current thread
244 if(Thread == NULL) Thread = Proc_GetCurThread();
246 // - If < 0, set to lowest priority
247 // - Minumum priority is actualy a high number, 0 is highest
248 if(Pri < 0) Pri = MIN_PRIORITY;
249 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
251 // Do we actually have to do anything?
252 if( Pri == Thread->Priority ) return;
254 #if SCHEDULER_TYPE == SCHED_RR_PRI
255 if( Thread != Proc_GetCurThread() )
257 SHORTLOCK( &glThreadListLock );
258 // Remove from old priority
259 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
261 Threads_int_AddToList( &gaActiveThreads[Pri], Thread );
262 Thread->Priority = Pri;
263 SHORTREL( &glThreadListLock );
266 Thread->Priority = Pri;
268 // If this isn't the current thread, we need to lock
269 if( Thread != Proc_GetCurThread() )
271 SHORTLOCK( &glThreadListLock );
273 #if SCHEDULER_TYPE == SCHED_LOTTERY
274 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
275 # if DEBUG_TRACE_TICKETS
276 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
278 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
281 Thread->Priority = Pri;
282 SHORTREL( &glThreadListLock );
285 Thread->Priority = Pri;
288 #if DEBUG_TRACE_STATE
289 Log("Threads_SetPriority: %p(%i %s) pri set %i",
290 Thread, Thread->TID, Thread->ThreadName,
296 * \brief Clone the TCB of the current thread
297 * \param Flags Flags for something... (What is this for?)
299 tThread *Threads_CloneTCB(Uint Flags)
302 cur = Proc_GetCurThread();
304 // Allocate and duplicate
305 new = malloc(sizeof(tThread));
306 if(new == NULL) { errno = -ENOMEM; return NULL; }
307 memcpy(new, cur, sizeof(tThread));
311 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
312 new->Status = THREAD_STAT_PREINIT;
316 new->TID = giNextTID++;
318 new->bInstrTrace = 0;
321 new->ThreadName = strdup(cur->ThreadName);
323 // Set Thread Group ID (PID)
324 if(Flags & CLONE_VM) {
325 tProcess *newproc, *oldproc;
326 oldproc = cur->Process;
327 new->Process = malloc( sizeof(struct sProcess) );
328 newproc = new->Process;
329 newproc->PID = new->TID;
330 if( Flags & CLONE_PGID )
331 newproc->PGID = oldproc->PGID;
333 newproc->PGID = newproc->PID;
334 newproc->UID = oldproc->UID;
335 newproc->GID = oldproc->GID;
336 newproc->MaxFD = oldproc->MaxFD;
337 if( oldproc->CurrentWorkingDir )
338 newproc->CurrentWorkingDir = strdup( oldproc->CurrentWorkingDir );
340 newproc->CurrentWorkingDir = NULL;
341 if( oldproc->RootDir )
342 newproc->RootDir = strdup( oldproc->RootDir );
344 newproc->RootDir = NULL;
345 newproc->nThreads = 1;
346 // Reference all handles in the VFS
347 VFS_ReferenceUserHandles();
349 newproc->FirstThread = new;
350 new->ProcessNext = NULL;
353 new->Process->nThreads ++;
354 new->Process = cur->Process;
356 new->ProcessNext = new->Process->FirstThread;
357 new->Process->FirstThread = new;
360 // Messages are not inherited
361 new->Messages = NULL;
362 new->LastMessage = NULL;
365 new->Remaining = new->Quantum = cur->Quantum;
366 new->Priority = cur->Priority;
369 // Set Signal Handlers
370 new->CurFaultNum = 0;
371 new->FaultHandler = cur->FaultHandler;
373 // Maintain a global list of threads
374 SHORTLOCK( &glThreadListLock );
375 new->GlobalPrev = NULL; // Protect against bugs
376 new->GlobalNext = gAllThreads;
377 gAllThreads->GlobalPrev = new;
379 SHORTREL( &glThreadListLock );
385 * \brief Clone the TCB of the kernel thread
387 tThread *Threads_CloneThreadZero(void)
391 // Allocate and duplicate
392 new = malloc(sizeof(tThread));
396 memcpy(new, &gThreadZero, sizeof(tThread));
398 new->Process->nThreads ++;
402 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
403 new->Status = THREAD_STAT_PREINIT;
407 new->TID = giNextTID++;
411 new->ThreadName = NULL;
413 // Messages are not inherited
414 new->Messages = NULL;
415 new->LastMessage = NULL;
418 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
419 new->Priority = DEFAULT_PRIORITY;
420 new->bInstrTrace = 0;
422 // Set Signal Handlers
423 new->CurFaultNum = 0;
424 new->FaultHandler = 0;
426 // Maintain a global list of threads
427 SHORTLOCK( &glThreadListLock );
428 new->GlobalPrev = NULL; // Protect against bugs
429 new->GlobalNext = gAllThreads;
430 gAllThreads->GlobalPrev = new;
432 SHORTREL( &glThreadListLock );
438 * \brief Wait for a task to change state
439 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
440 * \param Status Thread return status
441 * \return TID of child that changed state
443 tTID Threads_WaitTID(int TID, int *Status)
448 Uint32 ev = Threads_WaitEvents(THREAD_EVENT_DEADCHILD);
450 if( ev & THREAD_EVENT_DEADCHILD )
452 // A child died, get the TID
453 tThread *us = Proc_GetCurThread();
454 ASSERT(us->LastDeadChild);
455 ret = us->LastDeadChild->TID;
456 // - Mark as dead (as opposed to undead)
457 ASSERT(us->LastDeadChild->Status == THREAD_STAT_ZOMBIE);
458 us->LastDeadChild->Status = THREAD_STAT_DEAD;
459 // - Set return status
461 *Status = us->LastDeadChild->RetStatus;
462 us->LastDeadChild = NULL;
463 Mutex_Release(&us->DeadChildLock);
467 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
472 // Any peer/child thread
474 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
480 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
488 // NOTE: Race condition - Other child dies, desired child dies, first death is 'lost'
489 while( (ret = Threads_WaitTID(-1, Status)) != TID )
501 * \brief Gets a thread given its TID
502 * \param TID Thread ID
503 * \return Thread pointer
505 tThread *Threads_GetThread(Uint TID)
509 // Search global list
510 for( thread = gAllThreads; thread; thread = thread->GlobalNext )
512 if(thread->TID == TID)
516 Log_Notice("Threads", "Unable to find TID %i on main list\n", TID);
522 * \brief Deletes an entry from a list
523 * \param List Pointer to the list head
524 * \param Thread Thread to find
527 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
529 tThread *ret, *prev = NULL;
531 for(ret = List->Head;
532 ret && ret != Thread;
533 prev = ret, ret = ret->Next
536 // Is the thread on the list
538 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
543 List->Head = Thread->Next;
544 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
547 prev->Next = Thread->Next;
548 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
550 if( Thread->Next == NULL )
556 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
559 List->Tail->Next = Thread;
567 * \brief Exit the current process (or another?)
568 * \param TID Thread ID to kill
569 * \param Status Exit status
571 void Threads_Exit(int TID, int Status)
574 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
576 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
578 // Halt forever, just in case
583 * \fn void Threads_Kill(tThread *Thread, int Status)
584 * \brief Kill a thread
585 * \param Thread Thread to kill
586 * \param Status Status code to return to the parent
588 void Threads_Kill(tThread *Thread, int Status)
591 int isCurThread = Thread == Proc_GetCurThread();
593 // TODO: Disown all children?
597 // TODO: I should keep a .Children list
598 for(child = gAllThreads;
600 child = child->GlobalNext)
602 if(child->Parent == Thread)
603 child->Parent = &gThreadZero;
608 ///\note Double lock is needed due to overlap of lock areas
610 // Lock thread (stop us recieving messages)
611 SHORTLOCK( &Thread->IsLocked );
613 // Clear Message Queue
614 while( Thread->Messages )
616 msg = Thread->Messages->Next;
617 free( Thread->Messages );
618 Thread->Messages = msg;
622 SHORTLOCK( &glThreadListLock );
624 switch(Thread->Status)
626 case THREAD_STAT_PREINIT: // Only on main list
629 // Currently active thread
630 case THREAD_STAT_ACTIVE:
631 if( Thread != Proc_GetCurThread() )
633 #if SCHEDULER_TYPE == SCHED_RR_PRI
634 tThreadList *list = &gaActiveThreads[Thread->Priority];
636 tThreadList *list = &gActiveThreads;
638 if( Threads_int_DelFromQueue( list, Thread ) )
643 Log_Warning("Threads",
644 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
645 Thread, Thread->TID, Thread->ThreadName
648 #if SCHEDULER_TYPE == SCHED_LOTTERY
649 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
652 // Ensure that we are not rescheduled
653 Thread->Remaining = 0; // Clear Remaining Quantum
654 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
656 // Update bookkeeping
657 giNumActiveThreads --;
659 // Kill it while it sleeps!
660 case THREAD_STAT_SLEEPING:
661 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
663 Log_Warning("Threads",
664 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
665 Thread, Thread->TID, Thread->ThreadName
670 // Brains!... You cannot kill something that is already dead
671 case THREAD_STAT_ZOMBIE:
672 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
673 Thread, Thread->TID, Thread->ThreadName);
674 SHORTREL( &glThreadListLock );
675 SHORTREL( &Thread->IsLocked );
679 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
685 Thread->RetStatus = Status;
687 SHORTREL( &Thread->IsLocked );
689 Thread->Status = THREAD_STAT_ZOMBIE;
690 SHORTREL( &glThreadListLock );
691 // TODO: It's possible that we could be timer-preempted here, should disable that... somehow
692 Mutex_Acquire( &Thread->Parent->DeadChildLock ); // released by parent
693 Thread->Parent->LastDeadChild = Thread;
694 Threads_PostEvent( Thread->Parent, THREAD_EVENT_DEADCHILD );
696 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
707 * \brief Yield remainder of the current thread's timeslice
709 void Threads_Yield(void)
711 // Log("Threads_Yield: by %p", __builtin_return_address(0));
716 * \breif Wait for the thread status to not be a specified value
718 void Threads_int_WaitForStatusEnd(enum eThreadStatus Status)
720 tThread *us = Proc_GetCurThread();
721 ASSERT(Status != THREAD_STAT_ACTIVE);
722 ASSERT(Status != THREAD_STAT_DEAD);
723 while( us->Status == Status )
726 if( us->Status == Status )
727 Debug("Thread %p(%i %s) rescheduled while in %s state", casTHREAD_STAT[Status]);
732 * \fn void Threads_Sleep(void)
733 * \brief Take the current process off the run queue
735 void Threads_Sleep(void)
737 tThread *cur = Proc_GetCurThread();
740 SHORTLOCK( &glThreadListLock );
742 // Don't sleep if there is a message waiting
743 if( cur->Messages ) {
744 SHORTREL( &glThreadListLock );
748 // Remove us from running queue
750 // Mark thread as sleeping
751 cur->Status = THREAD_STAT_SLEEPING;
753 // Add to Sleeping List (at the top)
754 Threads_int_AddToList( &gSleepingThreads, cur );
756 #if DEBUG_TRACE_STATE
757 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
761 SHORTREL( &glThreadListLock );
762 Threads_int_WaitForStatusEnd(THREAD_STAT_SLEEPING);
767 * \brief Wakes a sleeping/waiting thread up
768 * \param Thread Thread to wake
769 * \return Boolean Failure (Returns ERRNO)
770 * \warning This should ONLY be called with task switches disabled
772 int Threads_Wake(tThread *Thread)
777 switch(Thread->Status)
779 case THREAD_STAT_ACTIVE:
780 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
783 case THREAD_STAT_SLEEPING:
784 // Remove from sleeping queue
785 SHORTLOCK( &glThreadListLock );
786 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
787 SHORTREL( &glThreadListLock );
789 Threads_AddActive( Thread );
791 #if DEBUG_TRACE_STATE
792 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
796 case THREAD_STAT_SEMAPHORESLEEP: {
798 tThread *th, *prev=NULL;
800 sem = Thread->WaitPointer;
802 SHORTLOCK( &sem->Protector );
804 // Remove from sleeping queue
805 for( th = sem->Waiting; th; prev = th, th = th->Next )
806 if( th == Thread ) break;
810 prev->Next = Thread->Next;
812 sem->Waiting = Thread->Next;
813 if(sem->LastWaiting == Thread)
814 sem->LastWaiting = prev;
819 for( th = sem->Signaling; th; prev = th, th = th->Next )
820 if( th == Thread ) break;
822 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
823 Thread, Thread->TID, Thread->ThreadName,
824 sem, sem->ModName, sem->Name);
829 prev->Next = Thread->Next;
831 sem->Signaling = Thread->Next;
832 if(sem->LastSignaling == Thread)
833 sem->LastSignaling = prev;
836 Thread->RetStatus = 0; // It didn't get anything
837 Threads_AddActive( Thread );
839 #if DEBUG_TRACE_STATE
840 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
842 SHORTREL( &sem->Protector );
845 case THREAD_STAT_WAITING:
846 Warning("Threads_Wake - Waiting threads are not currently supported");
849 case THREAD_STAT_DEAD:
850 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
854 Log_Warning("Threads", "Threads_Wake - Unknown process status (%i)", Thread->Status);
860 * \brief Wake a thread given the TID
861 * \param TID Thread ID to wake
862 * \return Boolean Faulure (errno)
864 int Threads_WakeTID(tTID TID)
866 tThread *thread = Threads_GetThread(TID);
870 ret = Threads_Wake( thread );
871 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
875 void Threads_ToggleTrace(int TID)
877 tThread *thread = Threads_GetThread(TID);
879 thread->bInstrTrace = !thread->bInstrTrace;
883 * \brief Adds a thread to the active queue
885 void Threads_AddActive(tThread *Thread)
887 SHORTLOCK( &glThreadListLock );
889 if( Thread->Status == THREAD_STAT_ACTIVE ) {
890 tThread *cur = Proc_GetCurThread();
891 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
892 __builtin_return_address(0),
893 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
894 SHORTREL( &glThreadListLock );
899 Thread->Status = THREAD_STAT_ACTIVE;
900 // Thread->CurCPU = -1;
901 // Add to active list
903 #if SCHEDULER_TYPE == SCHED_RR_PRI
904 tThreadList *list = &gaActiveThreads[Thread->Priority];
906 tThreadList *list = &gActiveThreads;
908 Threads_int_AddToList( list, Thread );
911 // Update bookkeeping
912 giNumActiveThreads ++;
914 #if SCHEDULER_TYPE == SCHED_LOTTERY
917 // Only change the ticket count if the thread is un-scheduled
918 if(Thread->CurCPU != -1)
921 delta = caiTICKET_COUNTS[ Thread->Priority ];
923 giFreeTickets += delta;
924 # if DEBUG_TRACE_TICKETS
925 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
926 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
933 SHORTREL( &glThreadListLock );
937 * \brief Removes the current thread from the active queue
938 * \warning This should ONLY be called with the lock held
939 * \return Current thread pointer
941 tThread *Threads_RemActive(void)
943 giNumActiveThreads --;
944 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;
1074 void Threads_int_DumpThread(tThread *thread)
1076 Log(" %p %i (%i) - %s (CPU %i) - %i (%s)",
1077 thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU,
1078 thread->Status, casTHREAD_STAT[thread->Status]
1080 switch(thread->Status)
1082 case THREAD_STAT_MUTEXSLEEP:
1083 Log(" Mutex Pointer: %p", thread->WaitPointer);
1085 case THREAD_STAT_SEMAPHORESLEEP:
1086 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1087 Log(" Semaphore Name: %s:%s",
1088 ((tSemaphore*)thread->WaitPointer)->ModName,
1089 ((tSemaphore*)thread->WaitPointer)->Name
1092 case THREAD_STAT_ZOMBIE:
1093 Log(" Return Status: %i", thread->RetStatus);
1097 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1098 Log(" KStack %p", thread->KernelStack);
1099 if( thread->bInstrTrace )
1100 Log(" Tracing Enabled");
1101 Proc_DumpThreadCPUState(thread);
1105 * \fn void Threads_Dump(void)
1107 void Threads_DumpActive(void)
1111 #if SCHEDULER_TYPE == SCHED_RR_PRI
1115 Log("Active Threads: (%i reported)", giNumActiveThreads);
1117 #if SCHEDULER_TYPE == SCHED_RR_PRI
1118 for( i = 0; i < MIN_PRIORITY+1; i++ )
1120 list = &gaActiveThreads[i];
1122 list = &gActiveThreads;
1124 for(thread=list->Head;thread;thread=thread->Next)
1126 Threads_int_DumpThread(thread);
1127 if(thread->Status != THREAD_STAT_ACTIVE)
1128 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1129 thread->Status, THREAD_STAT_ACTIVE);
1132 #if SCHEDULER_TYPE == SCHED_RR_PRI
1138 * \fn void Threads_Dump(void)
1139 * \brief Dumps a list of currently running threads
1141 void Threads_Dump(void)
1145 Log("--- Thread Dump ---");
1146 Threads_DumpActive();
1148 Log("All Threads:");
1149 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1151 Threads_int_DumpThread(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);