3 * - By John Hodge (thePowersGang)
5 * - Common Thread Control
9 #include <threads_int.h>
12 #include <semaphore.h>
14 #include <vfs_threads.h> // VFS Handle maintainence
16 #include <debug_hooks.h>
19 #define DEBUG_TRACE_ACTIVEQUEUE 0 // Trace adds/removals from the active queue
20 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
21 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
22 #define DEBUG_TRACE_SCHEDULE 0 // Trace scheduling
26 #define SCHED_LOTTERY 1 // Lottery scheduler
27 #define SCHED_RR_SIM 2 // Single Queue Round Robin
28 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
30 #define SCHEDULER_TYPE SCHED_RR_PRI
33 #define DEFAULT_QUANTUM 5
34 #define DEFAULT_PRIORITY 5
35 #define MIN_PRIORITY 10
37 #define PRIthread_fmt "%p(%i %s)"
38 #define PRIthread_args(t) (t), ((t)?(t)->TID:-1), ((t)?(t)->ThreadName:"-")
41 extern void User_Signal_Kill(int SigNum);
51 void Threads_Init(void);
53 void Threads_Delete(tThread *Thread);
54 int Threads_SetName(const char *NewName);
56 char *Threads_GetName(tTID ID);
58 void Threads_SetPriority(tThread *Thread, int Pri);
59 tThread *Threads_CloneTCB(Uint Flags);
60 int Threads_WaitTID(int TID, int *status);
61 tThread *Threads_GetThread(Uint TID);
63 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread);
64 void Threads_int_AddToList(tThreadList *List, tThread *Thread);
66 void Threads_Exit(int TID, int Status);
67 void Threads_Kill(tThread *Thread, int Status);
68 void Threads_Yield(void);
69 int Threads_int_Sleep(enum eThreadStatus Status, void *Ptr, int Num, tThread **ListHead, tThread **ListTail, tShortSpinlock *Lock);
70 void Threads_Sleep(void);
71 int Threads_Wake(tThread *Thread);
72 void Threads_AddActive(tThread *Thread);
73 tThread *Threads_RemActive(void);
74 void Threads_ToggleTrace(int TID);
76 void Threads_Fault(int Num);
77 void Threads_SegFault(tVAddr Addr);
78 void Threads_PostSignalTo(tThread *Thread, int SignalNum);
80 void Threads_PostSignal(int SignalNum);
81 void Threads_SignalGroup(tPGID PGID, int SignalNum);
83 int Threads_GetPendingSignal(void);
84 void Threads_SetSignalHandler(int SignalNum, void *Handler);
85 void *Threads_GetSignalHandler(int SignalNum);
87 int Threads_GetPID(void);
88 int Threads_GetTID(void);
89 tUID Threads_GetUID(void);
90 tGID Threads_GetGID(void);
91 int Threads_SetUID(Uint *Errno, tUID ID);
92 int Threads_SetGID(Uint *Errno, tUID ID);
94 void Threads_int_DumpThread(tThread *thread);
96 void Threads_Dump(void);
98 void Threads_DumpActive(void);
99 tThread *Threads_int_GetRunnable(void);
103 tProcess gProcessZero = {
105 // Only used for the core kernel
106 tThread gThreadZero = {
107 .Status = THREAD_STAT_ACTIVE, // Status
108 .ThreadName = (char*)"ThreadZero", // Name
109 .Quantum = DEFAULT_QUANTUM, // Default Quantum
110 .Remaining = DEFAULT_QUANTUM, // Current Quantum
111 .Priority = DEFAULT_PRIORITY // Number of tickets
114 tProcess *gAllProcesses = &gProcessZero;
116 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
117 // --- Current State ---
118 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
119 volatile Uint giNextTID = 1; // Next TID to allocate
120 // --- Thread Lists ---
121 tThread *gAllThreads = NULL; // All allocated threads
122 tThreadList gSleepingThreads; // Sleeping Threads
123 int giNumCPUs = 1; // Number of CPUs
124 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
125 // --- Scheduler Types ---
126 #if SCHEDULER_TYPE == SCHED_LOTTERY
127 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
128 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
129 tThreadList gActiveThreads; // Currently Running Threads
130 #elif SCHEDULER_TYPE == SCHED_RR_SIM
131 tThreadList gActiveThreads; // Currently Running Threads
132 #elif SCHEDULER_TYPE == SCHED_RR_PRI
133 tThreadList gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
135 # error "Unkown scheduler type"
140 * \fn void Threads_Init(void)
141 * \brief Initialse the thread list
143 void Threads_Init(void)
147 Log_Debug("Threads", "Offsets of tThread");
148 Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
149 Log_Debug("Threads", ".KernelStack = %i", offsetof(tThread, KernelStack));
151 // Create Initial Task
152 gAllThreads = &gThreadZero;
153 giNumActiveThreads = 1;
154 gThreadZero.Process = &gProcessZero;
159 void Threads_Delete(tThread *Thread)
162 Thread->Status = THREAD_STAT_BURIED;
164 // Clear out process state
165 Proc_ClearThread(Thread);
167 Thread->Process->nThreads --;
169 if( Thread->Process->FirstThread == Thread )
171 Thread->Process->FirstThread = Thread->ProcessNext;
175 tThread *prev = Thread->Process->FirstThread;
176 while(prev && prev->ProcessNext != Thread)
177 prev = prev->ProcessNext;
179 Log_Error("Threads", "Thread %p(%i %s) is not on the process's list",
180 Thread, Thread->TID, Thread->ThreadName
183 prev->ProcessNext = Thread->ProcessNext;
186 // If the final thread is being terminated, clean up the process
187 if( Thread->Process->nThreads == 0 )
189 tProcess *proc = Thread->Process;
191 // Remove from global process list
194 proc->Prev->Next = proc->Next;
196 gAllProcesses = proc->Next;
198 proc->Next->Prev = proc->Prev;
201 VFS_CloseAllUserHandles();
202 // Architecture cleanup
203 Proc_ClearProcess( proc );
204 // VFS Configuration strings
205 if( proc->CurrentWorkingDir)
206 free( proc->CurrentWorkingDir );
208 free( proc->RootDir );
209 // Process descriptor
214 if( IsHeap(Thread->ThreadName) )
215 free(Thread->ThreadName);
217 // Remove from global list
218 // TODO: Lock this too
219 if( Thread == gAllThreads )
220 gAllThreads = Thread->GlobalNext;
222 Thread->GlobalPrev->GlobalNext = Thread->GlobalNext;
228 * \fn void Threads_SetName(const char *NewName)
229 * \brief Sets the current thread's name
230 * \param NewName New name for the thread
231 * \return Boolean Failure
233 int Threads_SetName(const char *NewName)
235 tThread *cur = Proc_GetCurThread();
236 char *oldname = cur->ThreadName;
238 // NOTE: There is a possibility of non-thread safety here
239 // A thread could read the current name pointer before it is zeroed
241 cur->ThreadName = NULL;
243 if( IsHeap(oldname) ) free( oldname );
244 cur->ThreadName = strdup(NewName);
246 Log_Debug("Threads", "Thread renamed to '%s'", NewName);
252 * \fn char *Threads_GetName(int ID)
253 * \brief Gets a thread's name
254 * \param ID Thread ID (-1 indicates current thread)
255 * \return Pointer to name
256 * \retval NULL Failure
258 char *Threads_GetName(tTID ID)
261 return Proc_GetCurThread()->ThreadName;
263 return Threads_GetThread(ID)->ThreadName;
267 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
268 * \brief Sets the priority of a task
269 * \param Thread Thread to update ticket count (NULL means current thread)
270 * \param Pri New priority
272 void Threads_SetPriority(tThread *Thread, int Pri)
274 // Get current thread
275 if(Thread == NULL) Thread = Proc_GetCurThread();
277 // - If < 0, set to lowest priority
278 // - Minumum priority is actualy a high number, 0 is highest
279 if(Pri < 0) Pri = MIN_PRIORITY;
280 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
282 // Do we actually have to do anything?
283 if( Pri == Thread->Priority ) return;
285 #if SCHEDULER_TYPE == SCHED_RR_PRI
286 if( Thread != Proc_GetCurThread() )
288 SHORTLOCK( &glThreadListLock );
289 // Remove from old priority
290 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
292 Threads_int_AddToList( &gaActiveThreads[Pri], Thread );
293 Thread->Priority = Pri;
294 SHORTREL( &glThreadListLock );
297 Thread->Priority = Pri;
299 // If this isn't the current thread, we need to lock
300 if( Thread != Proc_GetCurThread() )
302 SHORTLOCK( &glThreadListLock );
304 #if SCHEDULER_TYPE == SCHED_LOTTERY
305 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
306 # if DEBUG_TRACE_TICKETS
307 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
309 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
312 Thread->Priority = Pri;
313 SHORTREL( &glThreadListLock );
316 Thread->Priority = Pri;
319 #if DEBUG_TRACE_STATE
320 Log("Threads_SetPriority: %p(%i %s) pri set %i",
321 Thread, Thread->TID, Thread->ThreadName,
327 * \brief Clone the TCB of the current thread
328 * \param Flags Flags for something... (What is this for?)
330 tThread *Threads_CloneTCB(Uint Flags)
333 cur = Proc_GetCurThread();
335 // Allocate and duplicate
336 new = malloc(sizeof(tThread));
337 if(new == NULL) { errno = -ENOMEM; return NULL; }
338 memcpy(new, cur, sizeof(tThread));
342 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
343 new->Status = THREAD_STAT_PREINIT;
347 new->TID = giNextTID++;
349 new->bInstrTrace = 0;
352 new->ThreadName = strdup(cur->ThreadName);
354 // Set Thread Group ID (PID)
355 if(Flags & CLONE_VM) {
356 tProcess *newproc, *oldproc;
357 oldproc = cur->Process;
358 new->Process = malloc( sizeof(struct sProcess) );
359 newproc = new->Process;
360 newproc->PID = new->TID;
361 if( Flags & CLONE_PGID )
362 newproc->PGID = oldproc->PGID;
364 newproc->PGID = newproc->PID;
365 newproc->UID = oldproc->UID;
366 newproc->GID = oldproc->GID;
367 newproc->MaxFD = oldproc->MaxFD;
368 newproc->CurrentWorkingDir = oldproc->CurrentWorkingDir ? strdup( oldproc->CurrentWorkingDir ) : NULL;
369 newproc->RootDir = oldproc->RootDir ? strdup( oldproc->RootDir ) : NULL;
370 newproc->nThreads = 1;
371 // Reference all handles in the VFS
372 VFS_ReferenceUserHandles();
374 // Add to global list
375 newproc->Prev = NULL;
377 newproc->Next = gAllProcesses;
378 gAllProcesses = newproc;
380 newproc->FirstThread = new;
381 new->ProcessNext = NULL;
384 new->Process->nThreads ++;
385 new->Process = cur->Process;
387 new->ProcessNext = new->Process->FirstThread;
388 new->Process->FirstThread = new;
391 // Messages are not inherited
392 new->Messages = NULL;
393 new->LastMessage = NULL;
396 new->Remaining = new->Quantum = cur->Quantum;
397 new->Priority = cur->Priority;
400 // Set Signal Handlers
401 new->CurFaultNum = 0;
402 new->FaultHandler = cur->FaultHandler;
404 // Maintain a global list of threads
405 SHORTLOCK( &glThreadListLock );
406 new->GlobalPrev = NULL; // Protect against bugs
407 new->GlobalNext = gAllThreads;
408 gAllThreads->GlobalPrev = new;
410 SHORTREL( &glThreadListLock );
416 * \brief Clone the TCB of the kernel thread
418 tThread *Threads_CloneThreadZero(void)
422 // Allocate and duplicate
423 new = malloc(sizeof(tThread));
427 memcpy(new, &gThreadZero, sizeof(tThread));
429 new->Process->nThreads ++;
433 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
434 new->Status = THREAD_STAT_PREINIT;
438 new->TID = giNextTID++;
442 new->ThreadName = NULL;
444 // Messages are not inherited
445 new->Messages = NULL;
446 new->LastMessage = NULL;
449 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
450 new->Priority = DEFAULT_PRIORITY;
451 new->bInstrTrace = 0;
453 // Set Signal Handlers
454 new->CurFaultNum = 0;
455 new->FaultHandler = 0;
457 // Maintain a global list of threads
458 SHORTLOCK( &glThreadListLock );
459 new->GlobalPrev = NULL; // Protect against bugs
460 new->GlobalNext = gAllThreads;
461 gAllThreads->GlobalPrev = new;
463 SHORTREL( &glThreadListLock );
469 * \brief Wait for a task to change state
470 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
471 * \param Status Thread return status
472 * \return TID of child that changed state
474 tTID Threads_WaitTID(int TID, int *Status)
479 Uint32 ev = Threads_WaitEvents(THREAD_EVENT_DEADCHILD);
481 if( ev & THREAD_EVENT_DEADCHILD )
483 // A child died, get the TID
484 tThread *us = Proc_GetCurThread();
485 ASSERT(us->LastDeadChild);
486 ret = us->LastDeadChild->TID;
487 // - Mark as dead (as opposed to undead)
488 ASSERT(us->LastDeadChild->Status == THREAD_STAT_ZOMBIE);
489 us->LastDeadChild->Status = THREAD_STAT_DEAD;
490 // - Set return status
492 *Status = us->LastDeadChild->RetStatus;
493 us->LastDeadChild = NULL;
494 Mutex_Release(&us->DeadChildLock);
498 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
503 // Any peer/child thread
505 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
511 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
518 // TODO: Register on thread to be poked when it dies
520 // NOTE: Race condition - Other child dies, desired child dies, first death is 'lost'
521 while( (ret = Threads_WaitTID(-1, Status)) != TID )
533 * \brief Gets a thread given its TID
534 * \param TID Thread ID
535 * \return Thread pointer
537 tThread *Threads_GetThread(Uint TID)
541 // Search global list
542 for( thread = gAllThreads; thread; thread = thread->GlobalNext )
544 if(thread->TID == TID)
548 Log_Notice("Threads", "Unable to find TID %i on main list\n", TID);
554 * \brief Deletes an entry from a list
555 * \param List Pointer to the list head
556 * \param Thread Thread to find
559 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
561 tThread *ret, *prev = NULL;
563 for(ret = List->Head;
564 ret && ret != Thread;
565 prev = ret, ret = ret->Next
568 // Is the thread on the list
570 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
575 List->Head = Thread->Next;
576 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
579 prev->Next = Thread->Next;
580 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
582 if( Thread->Next == NULL )
588 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
591 List->Tail->Next = Thread;
599 * \brief Exit the current process (or another?)
600 * \param TID Thread ID to kill
601 * \param Status Exit status
603 void Threads_Exit(int TID, int Status)
606 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
608 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
610 // Halt forever, just in case
615 * \fn void Threads_Kill(tThread *Thread, int Status)
616 * \brief Kill a thread
617 * \param Thread Thread to kill
618 * \param Status Status code to return to the parent
620 void Threads_Kill(tThread *Thread, int Status)
623 int isCurThread = Thread == Proc_GetCurThread();
625 // TODO: Disown all children?
629 // TODO: I should keep a .Children list
630 for(child = gAllThreads;
632 child = child->GlobalNext)
634 if(child->Parent == Thread)
635 child->Parent = &gThreadZero;
640 ///\note Double lock is needed due to overlap of lock areas
642 // Lock thread (stop us recieving messages)
643 SHORTLOCK( &Thread->IsLocked );
645 // Clear Message Queue
646 while( Thread->Messages )
648 msg = Thread->Messages->Next;
649 free( Thread->Messages );
650 Thread->Messages = msg;
654 SHORTLOCK( &glThreadListLock );
656 switch(Thread->Status)
658 case THREAD_STAT_PREINIT: // Only on main list
661 // Currently active thread
662 case THREAD_STAT_ACTIVE:
663 if( Thread != Proc_GetCurThread() )
665 #if SCHEDULER_TYPE == SCHED_RR_PRI
666 tThreadList *list = &gaActiveThreads[Thread->Priority];
668 tThreadList *list = &gActiveThreads;
670 if( Threads_int_DelFromQueue( list, Thread ) )
675 Log_Warning("Threads",
676 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
677 Thread, Thread->TID, Thread->ThreadName
680 #if SCHEDULER_TYPE == SCHED_LOTTERY
681 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
684 // Ensure that we are not rescheduled
685 Thread->Remaining = 0; // Clear Remaining Quantum
686 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
688 // Update bookkeeping
689 giNumActiveThreads --;
691 // Kill it while it sleeps!
692 case THREAD_STAT_SLEEPING:
693 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
695 Log_Warning("Threads",
696 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
697 Thread, Thread->TID, Thread->ThreadName
702 // Brains!... You cannot kill something that is already dead
703 case THREAD_STAT_ZOMBIE:
704 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
705 Thread, Thread->TID, Thread->ThreadName);
706 SHORTREL( &glThreadListLock );
707 SHORTREL( &Thread->IsLocked );
711 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
717 Thread->RetStatus = Status;
719 SHORTREL( &Thread->IsLocked );
721 Thread->Status = THREAD_STAT_ZOMBIE;
722 SHORTREL( &glThreadListLock );
723 // TODO: It's possible that we could be timer-preempted here, should disable that... somehow
724 Mutex_Acquire( &Thread->Parent->DeadChildLock ); // released by parent
725 Thread->Parent->LastDeadChild = Thread;
726 Threads_PostEvent( Thread->Parent, THREAD_EVENT_DEADCHILD );
728 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
739 * \brief Yield remainder of the current thread's timeslice
741 void Threads_Yield(void)
743 // Log("Threads_Yield: by %p", __builtin_return_address(0));
748 * \breif Wait for the thread status to not be a specified value
750 void Threads_int_WaitForStatusEnd(enum eThreadStatus Status)
752 tThread *us = Proc_GetCurThread();
753 ASSERT(Status != THREAD_STAT_ACTIVE);
754 ASSERT(Status != THREAD_STAT_DEAD);
755 while( us->Status == Status )
758 if( us->Status == Status )
759 Debug("Thread %p(%i %s) rescheduled while in %s state for %p",
760 us, us->TID, us->ThreadName,
761 casTHREAD_STAT[Status],
762 __builtin_return_address(0));
766 int Threads_int_Sleep(enum eThreadStatus Status, void *Ptr, int Num, tThread **ListHead, tThread **ListTail, tShortSpinlock *Lock)
768 SHORTLOCK( &glThreadListLock );
769 tThread *us = Threads_RemActive();
771 // - Mark as sleeping
773 us->WaitPointer = Ptr;
774 us->RetStatus = Num; // Use RetStatus as a temp variable
779 (*ListTail)->Next = us;
790 //if( Proc_ThreadSync(us) )
792 SHORTREL( &glThreadListLock );
795 Threads_int_WaitForStatusEnd(Status);
796 us->WaitPointer = NULL;
797 return us->RetStatus;
801 * \fn void Threads_Sleep(void)
802 * \brief Take the current process off the run queue
804 void Threads_Sleep(void)
806 tThread *cur = Proc_GetCurThread();
809 SHORTLOCK( &glThreadListLock );
811 // Don't sleep if there is a message waiting
812 if( cur->Messages ) {
813 SHORTREL( &glThreadListLock );
817 // Remove us from running queue
819 // Mark thread as sleeping
820 cur->Status = THREAD_STAT_SLEEPING;
822 // Add to Sleeping List (at the top)
823 Threads_int_AddToList( &gSleepingThreads, cur );
825 #if DEBUG_TRACE_STATE
826 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
830 SHORTREL( &glThreadListLock );
831 Threads_int_WaitForStatusEnd(THREAD_STAT_SLEEPING);
836 * \brief Wakes a sleeping/waiting thread up
837 * \param Thread Thread to wake
838 * \return Boolean Failure (Returns ERRNO)
839 * \warning This should ONLY be called with task switches disabled
841 int Threads_Wake(tThread *Thread)
846 switch(Thread->Status)
848 case THREAD_STAT_ACTIVE:
849 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
852 case THREAD_STAT_SLEEPING:
853 // Remove from sleeping queue
854 SHORTLOCK( &glThreadListLock );
855 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
856 SHORTREL( &glThreadListLock );
858 Threads_AddActive( Thread );
860 #if DEBUG_TRACE_STATE
861 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
865 case THREAD_STAT_SEMAPHORESLEEP: {
867 tThread *th, *prev=NULL;
869 sem = Thread->WaitPointer;
871 SHORTLOCK( &sem->Protector );
873 // Remove from sleeping queue
874 for( th = sem->Waiting; th; prev = th, th = th->Next )
875 if( th == Thread ) break;
879 prev->Next = Thread->Next;
881 sem->Waiting = Thread->Next;
882 if(sem->LastWaiting == Thread)
883 sem->LastWaiting = prev;
888 for( th = sem->Signaling; th; prev = th, th = th->Next )
889 if( th == Thread ) break;
891 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
892 Thread, Thread->TID, Thread->ThreadName,
893 sem, sem->ModName, sem->Name);
898 prev->Next = Thread->Next;
900 sem->Signaling = Thread->Next;
901 if(sem->LastSignaling == Thread)
902 sem->LastSignaling = prev;
905 Thread->RetStatus = 0; // It didn't get anything
906 Threads_AddActive( Thread );
908 #if DEBUG_TRACE_STATE
909 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
911 SHORTREL( &sem->Protector );
914 case THREAD_STAT_WAITING:
915 Warning("Threads_Wake - Waiting threads are not currently supported");
918 case THREAD_STAT_DEAD:
919 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
923 Log_Warning("Threads", "Threads_Wake - Unknown process status (%i)", Thread->Status);
929 * \brief Wake a thread given the TID
930 * \param TID Thread ID to wake
931 * \return Boolean Faulure (errno)
933 int Threads_WakeTID(tTID TID)
935 tThread *thread = Threads_GetThread(TID);
939 ret = Threads_Wake( thread );
940 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
944 void Threads_ToggleTrace(int TID)
946 tThread *thread = Threads_GetThread(TID);
948 thread->bInstrTrace = !thread->bInstrTrace;
952 * \brief Adds a thread to the active queue
954 void Threads_AddActive(tThread *Thread)
956 #if DEBUG_TRACE_ACTIVEQUEUE
957 Debug("Threads_AddActive("PRIthread_fmt")", PRIthread_args(Thread));
959 SHORTLOCK( &glThreadListLock );
961 if( Thread->Status == THREAD_STAT_ACTIVE )
963 tThread *cur = Proc_GetCurThread();
964 Log_KernelPanic("Threads",
965 "ret=%p CPU%i "PRIthread_fmt" is adding "PRIthread_fmt" when it is active",
966 __builtin_return_address(0),
967 GetCPUNum(), PRIthread_args(cur), PRIthread_args(Thread));
968 SHORTREL( &glThreadListLock );
973 Thread->Status = THREAD_STAT_ACTIVE;
974 // Add to active list
975 // - Thread can be the current thread if we're interrupted just before
976 // Proc_Reschedule in a sleep state.
977 if( Thread != Proc_GetCurThread() )
979 #if SCHEDULER_TYPE == SCHED_RR_PRI
980 tThreadList *list = &gaActiveThreads[Thread->Priority];
982 tThreadList *list = &gActiveThreads;
984 #if DEBUG_TRACE_ACTIVEQUEUE
985 Debug(" - Head="PRIthread_fmt",Tail="PRIthread_fmt"",
986 PRIthread_args(list->Head),
987 PRIthread_args(list->Tail)
990 Threads_int_AddToList( list, Thread );
993 // Update bookkeeping
994 giNumActiveThreads ++;
996 #if SCHEDULER_TYPE == SCHED_LOTTERY
999 // Only change the ticket count if the thread is un-scheduled
1000 if(Thread->CurCPU != -1)
1003 delta = caiTICKET_COUNTS[ Thread->Priority ];
1005 giFreeTickets += delta;
1006 # if DEBUG_TRACE_TICKETS
1007 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
1008 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
1009 giFreeTickets, delta
1015 SHORTREL( &glThreadListLock );
1019 * \brief Removes the current thread from the active queue
1020 * \warning This should ONLY be called with the lock held
1021 * \return Current thread pointer
1023 tThread *Threads_RemActive(void)
1025 tThread *us = Proc_GetCurThread();
1026 #if DEBUG_TRACE_ACTIVEQUEUE
1027 Debug("Threads_RemActive(%p(%i %s))", us, us->TID, us->ThreadName);
1029 giNumActiveThreads --;
1034 * \fn void Threads_SetFaultHandler(Uint Handler)
1035 * \brief Sets the signal handler for a signal
1037 void Threads_SetFaultHandler(Uint Handler)
1039 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
1040 Proc_GetCurThread()->FaultHandler = Handler;
1044 * \fn void Threads_Fault(int Num)
1045 * \brief Calls a fault handler
1047 void Threads_Fault(int Num)
1049 tThread *thread = Proc_GetCurThread();
1051 if(!thread) return ;
1053 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
1055 switch(thread->FaultHandler)
1058 Threads_Kill(thread, -1);
1061 case 1: // Dump Core?
1062 Threads_Kill(thread, -1);
1067 // Double Fault? Oh, F**k
1068 if(thread->CurFaultNum != 0) {
1069 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
1070 Threads_Kill(thread, -1); // For now, just kill
1074 thread->CurFaultNum = Num;
1076 Proc_CallFaultHandler(thread);
1080 * \fn void Threads_SegFault(tVAddr Addr)
1081 * \brief Called when a Segment Fault occurs
1083 void Threads_SegFault(tVAddr Addr)
1085 tThread *cur = Proc_GetCurThread();
1086 cur->bInstrTrace = 0;
1087 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
1088 MM_DumpTables(0, USER_MAX);
1090 //Threads_Exit( 0, -1 );
1094 void Threads_PostSignalTo(tThread *Thread, int SignalNum)
1097 Log_Debug("Threads", "Signalling %i(%s) with %i", Thread->TID, Thread->ThreadName, SignalNum);
1098 Thread->PendingSignal = SignalNum;
1099 Threads_PostEvent(Thread, THREAD_EVENT_SIGNAL);
1101 void Threads_PostSignal(int SignalNum)
1103 Threads_PostSignalTo( Proc_GetCurThread(), SignalNum );
1106 void Threads_SignalGroup(tPGID PGID, int Signal)
1108 for( tProcess *proc = gAllProcesses; proc; proc = proc->Next )
1110 if(proc->PGID == PGID)
1112 Threads_PostSignalTo(proc->FirstThread, Signal);
1119 int Threads_GetPendingSignal(void)
1121 tThread *cur = Proc_GetCurThread();
1123 // Atomic AND with 0 fetches and clears in one operation
1124 int ret = __sync_fetch_and_and( &cur->PendingSignal, 0 );
1127 Log_Debug("Threads", "Thread %i(%s) has signal %i pending",
1128 cur->TID, cur->ThreadName, ret);
1134 * \brief Update the current thread's signal handler
1136 void Threads_SetSignalHandler(int SignalNum, void *Handler)
1138 if( SignalNum <= 0 || SignalNum >= NSIGNALS )
1140 if( !MM_IsUser(Handler) )
1142 Proc_GetCurThread()->Process->SignalHandlers[SignalNum] = Handler;
1146 * \brief Gets the registered (or default, if none set) handler for a signal.
1147 * \return Handler function pointer, OR NULL if no signal to be ignored
1149 void *Threads_GetSignalHandler(int SignalNum)
1152 void *User_Signal_Core = User_Signal_Kill;
1154 if( SignalNum <= 0 || SignalNum >= NSIGNALS )
1156 void *ret = Proc_GetCurThread()->Process->SignalHandlers[SignalNum];
1157 if( !ret || (SignalNum == SIGKILL || SignalNum == SIGSTOP) )
1164 ret = User_Signal_Kill;
1170 ret = User_Signal_Core;
1173 ret = User_Signal_Kill;
1176 ret = User_Signal_Core;
1181 ret = User_Signal_Kill;
1188 Log_Debug("Threads", "Handler %p for signal %i", ret, SignalNum);
1192 // --- Process Structure Access Functions ---
1193 tPGID Threads_GetPGID(void)
1195 return Proc_GetCurThread()->Process->PGID;
1197 tPID Threads_GetPID(void)
1199 return Proc_GetCurThread()->Process->PID;
1201 tTID Threads_GetTID(void)
1203 return Proc_GetCurThread()->TID;
1205 tUID Threads_GetUID(void)
1207 return Proc_GetCurThread()->Process->UID;
1209 tGID Threads_GetGID(void)
1211 return Proc_GetCurThread()->Process->GID;
1214 int Threads_SetUID(tUID ID)
1216 tThread *t = Proc_GetCurThread();
1217 if( t->Process->UID != 0 ) {
1221 Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1222 t->Process->UID = ID;
1226 int Threads_SetGID(tGID ID)
1228 tThread *t = Proc_GetCurThread();
1229 if( t->Process->UID != 0 ) {
1233 Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1234 t->Process->GID = ID;
1238 // --- Per-thread storage ---
1239 int *Threads_GetErrno(void)
1241 return &Proc_GetCurThread()->_errno;
1244 // --- Configuration ---
1245 int *Threads_GetMaxFD(void)
1247 return &Proc_GetCurThread()->Process->MaxFD;
1249 char **Threads_GetChroot(void)
1251 return &Proc_GetCurThread()->Process->RootDir;
1253 char **Threads_GetCWD(void)
1255 return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1259 void Threads_int_DumpThread(tThread *thread)
1262 Log(" %p NULL", thread);
1265 if( !CheckMem(thread, sizeof(tThread)) ) {
1266 Log(" %p INVAL", thread);
1269 tPID pid = (thread->Process ? thread->Process->PID : -1);
1270 const char *statstr = (thread->Status < sizeof(casTHREAD_STAT)/sizeof(casTHREAD_STAT[0])
1271 ? casTHREAD_STAT[thread->Status] : "");
1272 Log(" %p %i (%i) - %s (CPU %i) - %i (%s)",
1273 thread, thread->TID, pid, thread->ThreadName, thread->CurCPU,
1274 thread->Status, statstr
1276 switch(thread->Status)
1278 case THREAD_STAT_MUTEXSLEEP:
1279 Log(" Mutex Pointer: %p", thread->WaitPointer);
1281 case THREAD_STAT_RWLOCKSLEEP:
1282 Log(" Lock Pointer: %p", thread->WaitPointer);
1283 Log(" Lock Name: %s",
1284 ((tRWLock*)thread->WaitPointer)->Name);
1286 case THREAD_STAT_SEMAPHORESLEEP:
1287 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1288 Log(" Semaphore Name: %s:%s",
1289 ((tSemaphore*)thread->WaitPointer)->ModName,
1290 ((tSemaphore*)thread->WaitPointer)->Name
1293 case THREAD_STAT_EVENTSLEEP:
1294 Log(" Event Mask: %x", thread->RetStatus);
1296 case THREAD_STAT_ZOMBIE:
1297 Log(" Return Status: %i", thread->RetStatus);
1301 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1302 Log(" KStack %p", thread->KernelStack);
1303 if( thread->bInstrTrace )
1304 Log(" Tracing Enabled");
1305 Proc_DumpThreadCPUState(thread);
1309 * \fn void Threads_Dump(void)
1311 void Threads_DumpActive(void)
1315 #if SCHEDULER_TYPE == SCHED_RR_PRI
1319 Log("Active Threads: (%i reported)", giNumActiveThreads);
1321 #if SCHEDULER_TYPE == SCHED_RR_PRI
1322 for( i = 0; i < MIN_PRIORITY+1; i++ )
1324 list = &gaActiveThreads[i];
1326 list = &gActiveThreads;
1328 for(thread=list->Head;thread;thread=thread->Next)
1330 Threads_int_DumpThread(thread);
1331 if(thread->Status != THREAD_STAT_ACTIVE)
1332 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1333 thread->Status, THREAD_STAT_ACTIVE);
1336 #if SCHEDULER_TYPE == SCHED_RR_PRI
1342 * \fn void Threads_Dump(void)
1343 * \brief Dumps a list of currently running threads
1345 void Threads_Dump(void)
1347 Log("--- Thread Dump ---");
1348 Threads_DumpActive();
1350 Log("All Threads:");
1351 for(tThread *thread = gAllThreads; thread; thread = thread->GlobalNext)
1353 Threads_int_DumpThread(thread);
1357 tThread *Threads_int_GetRunnable(void)
1359 #if SCHEDULER_TYPE == SCHED_LOTTERY
1360 // -----------------------------------
1361 // Lottery Scheduler
1362 // -----------------------------------
1363 #if DEBUG_VALIDATE_TICKET_COUNTS
1365 int total_tickets = 0;
1366 for(const tThread *thread = gActiveThreads.Head; thread; thread = thread->Next)
1368 if(thread->Status != THREAD_STAT_ACTIVE)
1369 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1370 thread, thread->TID, thread->ThreadName, thread->Status);
1371 if(thread->Next == thread) {
1372 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1373 thread, thread->TID, thread->ThreadName, thread->Status);
1375 total_tickets += caiTICKET_COUNTS[ thread->Priority ];
1377 if(total_tickets != giFreeTickets)
1379 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1380 giFreeTickets, total_tickets, CPU);
1385 // No free tickets (all tasks delegated to cores)
1386 if( giFreeTickets == 0 )
1391 // Get the ticket number
1392 int ticket = rand() % giFreeTickets;
1393 int number = ticket;
1395 // Find the next thread
1396 tThread **pnp = &gActiveThreads.Head;
1398 for(thread = gActiveThreads.Head; thread; pnp = &thread->Next, thread = thread->Next )
1400 if( caiTICKET_COUNTS[ thread->Priority ] > number)
1402 number -= caiTICKET_COUNTS[ thread->Priority ];
1405 // If we didn't find a thread, something went wrong
1408 int total_tickets = 0;
1409 for(thread=gActiveThreads;thread;thread=thread->Next) {
1410 if(thread->CurCPU >= 0) continue;
1411 total_tickets += caiTICKET_COUNTS[ thread->Priority ];
1413 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1414 giFreeTickets, total_tickets);
1418 *pnp = thread->Next;
1420 gActiveThreads.Tail = prev;
1422 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1423 # if DEBUG_TRACE_TICKETS
1424 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1425 CPU, thread, thread->TID, thread->ThreadName,
1426 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1430 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1432 // -----------------------------------
1433 // Priority based round robin scheduler
1434 // -----------------------------------
1435 for( int i = 0; i < MIN_PRIORITY + 1; i ++ )
1437 if( gaActiveThreads[i].Head == NULL )
1440 tThread *thread = gaActiveThreads[i].Head;
1442 if( thread->Status != THREAD_STAT_ACTIVE ) {
1443 for( const tThread *t = gaActiveThreads[i].Head; t; t = t->Next )
1444 LogF("- %p(%i %s)\n", t, t->TID, t->ThreadName);
1445 Panic("Thread %p(%i %s) from pqueue %i is active!",
1446 thread, thread->TID, thread->ThreadName, i);
1450 gaActiveThreads[i].Head = thread->Next;
1452 gaActiveThreads[i].Tail = NULL;
1453 thread->Next = NULL;
1458 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1460 // -----------------------------------
1461 // Single-list round-robin
1462 // -----------------------------------
1463 tThread *thread = gActiveThreads.Head;
1466 gActiveThreads.Head = thread->Next;
1468 gaActiveThreads.Tail = NULL;
1469 thread->Next = NULL;
1473 # error "Unimplemented scheduling algorithm"
1479 * \brief Gets the next thread to run
1480 * \param CPU Current CPU
1481 * \param Last The thread the CPU was running
1483 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1485 // If this CPU has the lock, we must let it complete
1486 if( CPU_HAS_LOCK( &glThreadListLock ) )
1489 // Don't change threads if the current CPU has switches disabled
1490 if( gaThreads_NoTaskSwitch[CPU] )
1494 SHORTLOCK( &glThreadListLock );
1496 // Make sure the current (well, old) thread is marked as de-scheduled
1497 if(Last) Last->CurCPU = -1;
1499 // No active threads, just take a nap
1500 if(giNumActiveThreads == 0) {
1501 SHORTREL( &glThreadListLock );
1502 #if DEBUG_TRACE_TICKETS
1503 Log("No active threads");
1508 // Allow the old thread to be scheduled again
1511 if( Last->Status == THREAD_STAT_ACTIVE ) {
1513 #if SCHEDULER_TYPE == SCHED_LOTTERY
1514 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1515 # if DEBUG_TRACE_TICKETS
1516 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1517 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1518 caiTICKET_COUNTS[ Last->Priority ]);
1522 #if SCHEDULER_TYPE == SCHED_RR_PRI
1523 list = &gaActiveThreads[ Last->Priority ];
1525 list = &gActiveThreads;
1527 // Add to end of list
1528 Threads_int_AddToList( list, Last );
1529 #if DEBUG_TRACE_ACTIVEQUEUE > 1
1530 Debug("Threads_GetNextToRun: Append thread %p(%i %s)",
1531 Last, Last->TID, Last->ThreadName);
1534 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1536 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1537 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1542 // Call actual scheduler
1543 tThread *thread = Threads_int_GetRunnable();
1548 if( thread->Status != THREAD_STAT_ACTIVE )
1550 LogF("Thread %p(%i %s) scheduled while not active\n",
1551 thread, thread->TID, thread->ThreadName);
1554 // Make the new thread non-schedulable
1555 thread->CurCPU = CPU;
1556 thread->Remaining = thread->Quantum;
1558 #if DEBUG_TRACE_SCHEDULE
1559 Debug("Scheduled "PRIthread_fmt", next = %p",
1560 PRIthread_args(thread),
1566 // No thread possible, warning condition (idle thread should be runnable)
1567 Warning("No runnable thread for CPU%i", CPU);
1570 SHORTREL( &glThreadListLock );
1576 EXPORT(Threads_GetUID);
1577 EXPORT(Threads_GetGID);