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 = calloc( sizeof(struct sProcess), 1 );
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;
786 else if( ListHead ) {
787 us->Next = *ListHead;
794 //if( Proc_ThreadSync(us) )
796 SHORTREL( &glThreadListLock );
799 Threads_int_WaitForStatusEnd(Status);
800 us->WaitPointer = NULL;
801 return us->RetStatus;
805 * \fn void Threads_Sleep(void)
806 * \brief Take the current process off the run queue
808 void Threads_Sleep(void)
810 tThread *cur = Proc_GetCurThread();
813 SHORTLOCK( &glThreadListLock );
815 // Don't sleep if there is a message waiting
816 if( cur->Messages ) {
817 SHORTREL( &glThreadListLock );
821 // Remove us from running queue
823 // Mark thread as sleeping
824 cur->Status = THREAD_STAT_SLEEPING;
826 // Add to Sleeping List (at the top)
827 Threads_int_AddToList( &gSleepingThreads, cur );
829 #if DEBUG_TRACE_STATE
830 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
834 SHORTREL( &glThreadListLock );
835 Threads_int_WaitForStatusEnd(THREAD_STAT_SLEEPING);
840 * \brief Wakes a sleeping/waiting thread up
841 * \param Thread Thread to wake
842 * \return Boolean Failure (Returns ERRNO)
843 * \warning This should ONLY be called with task switches disabled
845 int Threads_Wake(tThread *Thread)
850 switch(Thread->Status)
852 case THREAD_STAT_ACTIVE:
853 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
856 case THREAD_STAT_SLEEPING:
857 // Remove from sleeping queue
858 SHORTLOCK( &glThreadListLock );
859 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
860 SHORTREL( &glThreadListLock );
862 Threads_AddActive( Thread );
864 #if DEBUG_TRACE_STATE
865 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
869 case THREAD_STAT_SEMAPHORESLEEP: {
871 tThread *th, *prev=NULL;
873 sem = Thread->WaitPointer;
875 SHORTLOCK( &sem->Protector );
877 // Remove from sleeping queue
878 for( th = sem->Waiting; th; prev = th, th = th->Next )
879 if( th == Thread ) break;
883 prev->Next = Thread->Next;
885 sem->Waiting = Thread->Next;
886 if(sem->LastWaiting == Thread)
887 sem->LastWaiting = prev;
892 for( th = sem->Signaling; th; prev = th, th = th->Next )
893 if( th == Thread ) break;
895 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
896 Thread, Thread->TID, Thread->ThreadName,
897 sem, sem->ModName, sem->Name);
902 prev->Next = Thread->Next;
904 sem->Signaling = Thread->Next;
905 if(sem->LastSignaling == Thread)
906 sem->LastSignaling = prev;
909 Thread->RetStatus = 0; // It didn't get anything
910 Threads_AddActive( Thread );
912 #if DEBUG_TRACE_STATE
913 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
915 SHORTREL( &sem->Protector );
918 case THREAD_STAT_WAITING:
919 Warning("Threads_Wake - Waiting threads are not currently supported");
922 case THREAD_STAT_DEAD:
923 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
927 Log_Warning("Threads", "Threads_Wake - Unknown process status (%i)", Thread->Status);
933 * \brief Wake a thread given the TID
934 * \param TID Thread ID to wake
935 * \return Boolean Faulure (errno)
937 int Threads_WakeTID(tTID TID)
939 tThread *thread = Threads_GetThread(TID);
943 ret = Threads_Wake( thread );
944 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
948 void Threads_ToggleTrace(int TID)
950 tThread *thread = Threads_GetThread(TID);
952 thread->bInstrTrace = !thread->bInstrTrace;
956 * \brief Adds a thread to the active queue
958 void Threads_AddActive(tThread *Thread)
960 #if DEBUG_TRACE_ACTIVEQUEUE
961 Debug("Threads_AddActive("PRIthread_fmt")", PRIthread_args(Thread));
963 SHORTLOCK( &glThreadListLock );
965 if( Thread->Status == THREAD_STAT_ACTIVE )
967 tThread *cur = Proc_GetCurThread();
968 Log_KernelPanic("Threads",
969 "ret=%p CPU%i "PRIthread_fmt" is adding "PRIthread_fmt" when it is active",
970 __builtin_return_address(0),
971 GetCPUNum(), PRIthread_args(cur), PRIthread_args(Thread));
972 SHORTREL( &glThreadListLock );
977 Thread->Status = THREAD_STAT_ACTIVE;
978 // Add to active list
979 // - Thread can be the current thread if we're interrupted just before
980 // Proc_Reschedule in a sleep state.
981 if( Thread != Proc_GetCurThread() )
983 #if SCHEDULER_TYPE == SCHED_RR_PRI
984 tThreadList *list = &gaActiveThreads[Thread->Priority];
986 tThreadList *list = &gActiveThreads;
988 #if DEBUG_TRACE_ACTIVEQUEUE
989 Debug(" - Head="PRIthread_fmt",Tail="PRIthread_fmt"",
990 PRIthread_args(list->Head),
991 PRIthread_args(list->Tail)
994 Threads_int_AddToList( list, Thread );
997 // Update bookkeeping
998 giNumActiveThreads ++;
1000 #if SCHEDULER_TYPE == SCHED_LOTTERY
1003 // Only change the ticket count if the thread is un-scheduled
1004 if(Thread->CurCPU != -1)
1007 delta = caiTICKET_COUNTS[ Thread->Priority ];
1009 giFreeTickets += delta;
1010 # if DEBUG_TRACE_TICKETS
1011 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
1012 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
1013 giFreeTickets, delta
1019 SHORTREL( &glThreadListLock );
1023 * \brief Removes the current thread from the active queue
1024 * \warning This should ONLY be called with the lock held
1025 * \return Current thread pointer
1027 tThread *Threads_RemActive(void)
1029 tThread *us = Proc_GetCurThread();
1030 #if DEBUG_TRACE_ACTIVEQUEUE
1031 Debug("Threads_RemActive(%p(%i %s))", us, us->TID, us->ThreadName);
1033 giNumActiveThreads --;
1038 * \fn void Threads_SetFaultHandler(Uint Handler)
1039 * \brief Sets the signal handler for a signal
1041 void Threads_SetFaultHandler(Uint Handler)
1043 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
1044 Proc_GetCurThread()->FaultHandler = Handler;
1048 * \fn void Threads_Fault(int Num)
1049 * \brief Calls a fault handler
1051 void Threads_Fault(int Num)
1053 tThread *thread = Proc_GetCurThread();
1055 if(!thread) return ;
1057 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
1059 switch(thread->FaultHandler)
1062 Threads_Kill(thread, -1);
1065 case 1: // Dump Core?
1066 Threads_Kill(thread, -1);
1071 // Double Fault? Oh, F**k
1072 if(thread->CurFaultNum != 0) {
1073 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
1074 Threads_Kill(thread, -1); // For now, just kill
1078 thread->CurFaultNum = Num;
1080 Proc_CallFaultHandler(thread);
1084 * \fn void Threads_SegFault(tVAddr Addr)
1085 * \brief Called when a Segment Fault occurs
1087 void Threads_SegFault(tVAddr Addr)
1089 tThread *cur = Proc_GetCurThread();
1090 cur->bInstrTrace = 0;
1091 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
1092 MM_DumpTables(0, USER_MAX);
1094 //Threads_Exit( 0, -1 );
1098 void Threads_PostSignalTo(tThread *Thread, int SignalNum)
1101 Log_Debug("Threads", "Signalling %i(%s) with %i", Thread->TID, Thread->ThreadName, SignalNum);
1102 Thread->PendingSignal = SignalNum;
1103 Threads_PostEvent(Thread, THREAD_EVENT_SIGNAL);
1105 void Threads_PostSignal(int SignalNum)
1107 Threads_PostSignalTo( Proc_GetCurThread(), SignalNum );
1110 void Threads_SignalGroup(tPGID PGID, int Signal)
1112 for( tProcess *proc = gAllProcesses; proc; proc = proc->Next )
1114 if(proc->PGID == PGID)
1116 Threads_PostSignalTo(proc->FirstThread, Signal);
1123 int Threads_GetPendingSignal(void)
1125 tThread *cur = Proc_GetCurThread();
1127 // Atomic AND with 0 fetches and clears in one operation
1128 int ret = __sync_fetch_and_and( &cur->PendingSignal, 0 );
1131 Log_Debug("Threads", "Thread %i(%s) has signal %i pending",
1132 cur->TID, cur->ThreadName, ret);
1138 * \brief Update the current thread's signal handler
1140 void Threads_SetSignalHandler(int SignalNum, void *Handler)
1142 if( SignalNum <= 0 || SignalNum >= NSIGNALS )
1144 if( !MM_IsUser(Handler) )
1146 Proc_GetCurThread()->Process->SignalHandlers[SignalNum] = Handler;
1150 * \brief Gets the registered (or default, if none set) handler for a signal.
1151 * \return Handler function pointer, OR NULL if no signal to be ignored
1153 void *Threads_GetSignalHandler(int SignalNum)
1156 void *User_Signal_Core = User_Signal_Kill;
1158 if( SignalNum <= 0 || SignalNum >= NSIGNALS )
1160 void *ret = Proc_GetCurThread()->Process->SignalHandlers[SignalNum];
1161 if( !ret || (SignalNum == SIGKILL || SignalNum == SIGSTOP) )
1168 ret = User_Signal_Kill;
1174 ret = User_Signal_Core;
1177 ret = User_Signal_Kill;
1180 ret = User_Signal_Core;
1185 ret = User_Signal_Kill;
1192 Log_Debug("Threads", "Handler %p for signal %i", ret, SignalNum);
1196 // --- Process Structure Access Functions ---
1197 tPGID Threads_GetPGID(void)
1199 return Proc_GetCurThread()->Process->PGID;
1201 tPID Threads_GetPID(void)
1203 return Proc_GetCurThread()->Process->PID;
1205 tTID Threads_GetTID(void)
1207 return Proc_GetCurThread()->TID;
1209 tUID Threads_GetUID(void)
1211 return Proc_GetCurThread()->Process->UID;
1213 tGID Threads_GetGID(void)
1215 return Proc_GetCurThread()->Process->GID;
1218 int Threads_SetUID(tUID ID)
1220 tThread *t = Proc_GetCurThread();
1221 if( t->Process->UID != 0 ) {
1225 Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1226 t->Process->UID = ID;
1230 int Threads_SetGID(tGID ID)
1232 tThread *t = Proc_GetCurThread();
1233 if( t->Process->UID != 0 ) {
1237 Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1238 t->Process->GID = ID;
1242 // --- Per-thread storage ---
1243 int *Threads_GetErrno(void)
1245 return &Proc_GetCurThread()->_errno;
1248 // --- Configuration ---
1249 int *Threads_GetMaxFD(void)
1251 return &Proc_GetCurThread()->Process->MaxFD;
1253 char **Threads_GetChroot(void)
1255 return &Proc_GetCurThread()->Process->RootDir;
1257 char **Threads_GetCWD(void)
1259 return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1263 void Threads_int_DumpThread(tThread *thread)
1266 Log(" %p NULL", thread);
1269 if( !CheckMem(thread, sizeof(tThread)) ) {
1270 Log(" %p INVAL", thread);
1273 tPID pid = (thread->Process ? thread->Process->PID : -1);
1274 const char *statstr = (thread->Status < sizeof(casTHREAD_STAT)/sizeof(casTHREAD_STAT[0])
1275 ? casTHREAD_STAT[thread->Status] : "");
1276 Log(" %p %i (%i) - %s (CPU %i) - %i (%s)",
1277 thread, thread->TID, pid, thread->ThreadName, thread->CurCPU,
1278 thread->Status, statstr
1280 switch(thread->Status)
1282 case THREAD_STAT_MUTEXSLEEP:
1283 Log(" Mutex Pointer: %p", thread->WaitPointer);
1285 case THREAD_STAT_RWLOCKSLEEP:
1286 Log(" Lock Pointer: %p", thread->WaitPointer);
1287 Log(" Lock Name: %s",
1288 ((tRWLock*)thread->WaitPointer)->Name);
1290 case THREAD_STAT_SEMAPHORESLEEP:
1291 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1292 Log(" Semaphore Name: %s:%s",
1293 ((tSemaphore*)thread->WaitPointer)->ModName,
1294 ((tSemaphore*)thread->WaitPointer)->Name
1297 case THREAD_STAT_EVENTSLEEP:
1298 Log(" Event Mask: %x", thread->RetStatus);
1300 case THREAD_STAT_ZOMBIE:
1301 Log(" Return Status: %i", thread->RetStatus);
1305 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1306 Log(" KStack %p", thread->KernelStack);
1307 if( thread->bInstrTrace )
1308 Log(" Tracing Enabled");
1309 Proc_DumpThreadCPUState(thread);
1313 * \fn void Threads_Dump(void)
1315 void Threads_DumpActive(void)
1317 Log("Active Threads: (%i reported)", giNumActiveThreads);
1319 #if SCHEDULER_TYPE == SCHED_RR_PRI
1320 for( int i = 0; i < MIN_PRIORITY+1; i++ )
1322 tThreadList *list = &gaActiveThreads[i];
1324 tThreadList *list = &gActiveThreads;
1326 for(tThread *thread = list->Head; thread; thread = thread->Next)
1328 Threads_int_DumpThread(thread);
1329 if(thread->Status != THREAD_STAT_ACTIVE)
1330 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1331 thread->Status, THREAD_STAT_ACTIVE);
1334 #if SCHEDULER_TYPE == SCHED_RR_PRI
1340 * \fn void Threads_Dump(void)
1341 * \brief Dumps a list of currently running threads
1343 void Threads_Dump(void)
1345 Log("--- Thread Dump ---");
1346 Threads_DumpActive();
1348 Log("All Threads:");
1349 for(tThread *thread = gAllThreads; thread; thread = thread->GlobalNext)
1351 Threads_int_DumpThread(thread);
1355 tThread *Threads_int_GetRunnable(void)
1357 #if SCHEDULER_TYPE == SCHED_LOTTERY
1358 // -----------------------------------
1359 // Lottery Scheduler
1360 // -----------------------------------
1361 #if DEBUG_VALIDATE_TICKET_COUNTS
1363 int total_tickets = 0;
1364 for(const tThread *thread = gActiveThreads.Head; thread; thread = thread->Next)
1366 if(thread->Status != THREAD_STAT_ACTIVE)
1367 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1368 thread, thread->TID, thread->ThreadName, thread->Status);
1369 if(thread->Next == thread) {
1370 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1371 thread, thread->TID, thread->ThreadName, thread->Status);
1373 total_tickets += caiTICKET_COUNTS[ thread->Priority ];
1375 if(total_tickets != giFreeTickets)
1377 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1378 giFreeTickets, total_tickets, CPU);
1383 // No free tickets (all tasks delegated to cores)
1384 if( giFreeTickets == 0 )
1389 // Get the ticket number
1390 int ticket = rand() % giFreeTickets;
1391 int number = ticket;
1393 // Find the next thread
1394 tThread **pnp = &gActiveThreads.Head;
1396 for(thread = gActiveThreads.Head; thread; pnp = &thread->Next, thread = thread->Next )
1398 if( caiTICKET_COUNTS[ thread->Priority ] > number)
1400 number -= caiTICKET_COUNTS[ thread->Priority ];
1403 // If we didn't find a thread, something went wrong
1406 int total_tickets = 0;
1407 for(thread=gActiveThreads;thread;thread=thread->Next) {
1408 if(thread->CurCPU >= 0) continue;
1409 total_tickets += caiTICKET_COUNTS[ thread->Priority ];
1411 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1412 giFreeTickets, total_tickets);
1416 *pnp = thread->Next;
1418 gActiveThreads.Tail = prev;
1420 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1421 # if DEBUG_TRACE_TICKETS
1422 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1423 CPU, thread, thread->TID, thread->ThreadName,
1424 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1428 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1430 // -----------------------------------
1431 // Priority based round robin scheduler
1432 // -----------------------------------
1433 for( int i = 0; i < MIN_PRIORITY + 1; i ++ )
1435 if( gaActiveThreads[i].Head == NULL )
1438 tThread *thread = gaActiveThreads[i].Head;
1440 if( thread->Status != THREAD_STAT_ACTIVE ) {
1441 for( const tThread *t = gaActiveThreads[i].Head; t; t = t->Next )
1442 LogF("- %p(%i %s)\n", t, t->TID, t->ThreadName);
1443 Panic("Thread %p(%i %s) from pqueue %i is active!",
1444 thread, thread->TID, thread->ThreadName, i);
1448 gaActiveThreads[i].Head = thread->Next;
1450 gaActiveThreads[i].Tail = NULL;
1451 thread->Next = NULL;
1456 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1458 // -----------------------------------
1459 // Single-list round-robin
1460 // -----------------------------------
1461 tThread *thread = gActiveThreads.Head;
1464 gActiveThreads.Head = thread->Next;
1466 gaActiveThreads.Tail = NULL;
1467 thread->Next = NULL;
1471 # error "Unimplemented scheduling algorithm"
1477 * \brief Gets the next thread to run
1478 * \param CPU Current CPU
1479 * \param Last The thread the CPU was running
1481 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1483 // If this CPU has the lock, we must let it complete
1484 if( CPU_HAS_LOCK( &glThreadListLock ) )
1487 // Don't change threads if the current CPU has switches disabled
1488 if( gaThreads_NoTaskSwitch[CPU] )
1492 SHORTLOCK( &glThreadListLock );
1494 // Make sure the current (well, old) thread is marked as de-scheduled
1495 if(Last) Last->CurCPU = -1;
1497 // No active threads, just take a nap
1498 if(giNumActiveThreads == 0) {
1499 SHORTREL( &glThreadListLock );
1500 #if DEBUG_TRACE_TICKETS
1501 Log("No active threads");
1506 // Allow the old thread to be scheduled again
1509 if( Last->Status == THREAD_STAT_ACTIVE ) {
1511 #if SCHEDULER_TYPE == SCHED_LOTTERY
1512 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1513 # if DEBUG_TRACE_TICKETS
1514 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1515 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1516 caiTICKET_COUNTS[ Last->Priority ]);
1520 #if SCHEDULER_TYPE == SCHED_RR_PRI
1521 list = &gaActiveThreads[ Last->Priority ];
1523 list = &gActiveThreads;
1525 // Add to end of list
1526 Threads_int_AddToList( list, Last );
1527 #if DEBUG_TRACE_ACTIVEQUEUE > 1
1528 Debug("Threads_GetNextToRun: Append thread %p(%i %s)",
1529 Last, Last->TID, Last->ThreadName);
1532 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1534 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1535 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1540 // Call actual scheduler
1541 tThread *thread = Threads_int_GetRunnable();
1546 if( thread->Status != THREAD_STAT_ACTIVE )
1548 LogF("Thread %p(%i %s) scheduled while not active\n",
1549 thread, thread->TID, thread->ThreadName);
1552 // Make the new thread non-schedulable
1553 thread->CurCPU = CPU;
1554 thread->Remaining = thread->Quantum;
1556 #if DEBUG_TRACE_SCHEDULE
1557 Debug("Scheduled "PRIthread_fmt", next = %p",
1558 PRIthread_args(thread),
1564 // No thread possible, warning condition (idle thread should be runnable)
1565 Warning("No runnable thread for CPU%i", CPU);
1568 SHORTREL( &glThreadListLock );
1574 EXPORT(Threads_GetUID);
1575 EXPORT(Threads_GetGID);