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
34 extern void User_Signal_Kill(int SigNum);
44 void Threads_Init(void);
46 void Threads_Delete(tThread *Thread);
47 int Threads_SetName(const char *NewName);
49 char *Threads_GetName(tTID ID);
51 void Threads_SetPriority(tThread *Thread, int Pri);
52 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
53 int Threads_WaitTID(int TID, int *status);
54 tThread *Threads_GetThread(Uint TID);
56 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread);
57 void Threads_int_AddToList(tThreadList *List, tThread *Thread);
59 void Threads_Exit(int TID, int Status);
60 void Threads_Kill(tThread *Thread, int Status);
61 void Threads_Yield(void);
63 void Threads_int_Sleep(enum eThreadStatus Status, void *Ptr, int Num, tThread **ListHead, tThread **ListTail, tShortSpinlock *Lock);
65 void Threads_Sleep(void);
66 int Threads_Wake(tThread *Thread);
67 void Threads_AddActive(tThread *Thread);
68 tThread *Threads_RemActive(void);
70 void Threads_ToggleTrace(int TID);
71 void Threads_Fault(int Num);
72 void Threads_SegFault(tVAddr Addr);
73 void Threads_PostSignalTo(tThread *Thread, int SignalNum);
75 void Threads_PostSignal(int SignalNum);
76 void Threads_SignalGroup(tPGID PGID, int SignalNum);
78 int Threads_GetPendingSignal(void);
79 void Threads_SetSignalHandler(int SignalNum, void *Handler);
80 void *Threads_GetSignalHandler(int SignalNum);
82 int Threads_GetPID(void);
83 int Threads_GetTID(void);
84 tUID Threads_GetUID(void);
85 tGID Threads_GetGID(void);
86 int Threads_SetUID(Uint *Errno, tUID ID);
87 int Threads_SetGID(Uint *Errno, tUID ID);
89 void Threads_int_DumpThread(tThread *thread);
90 void Threads_Dump(void);
91 void Threads_DumpActive(void);
95 tProcess gProcessZero = {
97 // Only used for the core kernel
98 tThread gThreadZero = {
99 .Status = THREAD_STAT_ACTIVE, // Status
100 .ThreadName = (char*)"ThreadZero", // Name
101 .Quantum = DEFAULT_QUANTUM, // Default Quantum
102 .Remaining = DEFAULT_QUANTUM, // Current Quantum
103 .Priority = DEFAULT_PRIORITY // Number of tickets
106 tProcess *gAllProcesses = &gProcessZero;
108 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
109 // --- Current State ---
110 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
111 volatile Uint giNextTID = 1; // Next TID to allocate
112 // --- Thread Lists ---
113 tThread *gAllThreads = NULL; // All allocated threads
114 tThreadList gSleepingThreads; // Sleeping Threads
115 int giNumCPUs = 1; // Number of CPUs
116 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
117 // --- Scheduler Types ---
118 #if SCHEDULER_TYPE == SCHED_LOTTERY
119 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
120 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
121 tThreadList gActiveThreads; // Currently Running Threads
122 #elif SCHEDULER_TYPE == SCHED_RR_SIM
123 tThreadList gActiveThreads; // Currently Running Threads
124 #elif SCHEDULER_TYPE == SCHED_RR_PRI
125 tThreadList gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
127 # error "Unkown scheduler type"
132 * \fn void Threads_Init(void)
133 * \brief Initialse the thread list
135 void Threads_Init(void)
139 Log_Debug("Threads", "Offsets of tThread");
140 Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
141 Log_Debug("Threads", ".KernelStack = %i", offsetof(tThread, KernelStack));
143 // Create Initial Task
144 gAllThreads = &gThreadZero;
145 giNumActiveThreads = 1;
146 gThreadZero.Process = &gProcessZero;
151 void Threads_Delete(tThread *Thread)
154 Thread->Status = THREAD_STAT_BURIED;
156 // Clear out process state
157 Proc_ClearThread(Thread);
159 Thread->Process->nThreads --;
161 if( Thread->Process->FirstThread == Thread )
163 Thread->Process->FirstThread = Thread->ProcessNext;
167 tThread *prev = Thread->Process->FirstThread;
168 while(prev && prev->ProcessNext != Thread)
169 prev = prev->ProcessNext;
171 Log_Error("Threads", "Thread %p(%i %s) is not on the process's list",
172 Thread, Thread->TID, Thread->ThreadName
175 prev->ProcessNext = Thread->ProcessNext;
178 // If the final thread is being terminated, clean up the process
179 if( Thread->Process->nThreads == 0 )
181 tProcess *proc = Thread->Process;
183 // Remove from global process list
186 proc->Prev->Next = proc->Next;
188 gAllProcesses = proc->Next;
190 proc->Next->Prev = proc->Prev;
193 VFS_CloseAllUserHandles();
194 // Architecture cleanup
195 Proc_ClearProcess( proc );
196 // VFS Configuration strings
197 if( proc->CurrentWorkingDir)
198 free( proc->CurrentWorkingDir );
200 free( proc->RootDir );
201 // Process descriptor
206 if( IsHeap(Thread->ThreadName) )
207 free(Thread->ThreadName);
209 // Remove from global list
210 // TODO: Lock this too
211 if( Thread == gAllThreads )
212 gAllThreads = Thread->GlobalNext;
214 Thread->GlobalPrev->GlobalNext = Thread->GlobalNext;
220 * \fn void Threads_SetName(const char *NewName)
221 * \brief Sets the current thread's name
222 * \param NewName New name for the thread
223 * \return Boolean Failure
225 int Threads_SetName(const char *NewName)
227 tThread *cur = Proc_GetCurThread();
228 char *oldname = cur->ThreadName;
230 // NOTE: There is a possibility of non-thread safety here
231 // A thread could read the current name pointer before it is zeroed
233 cur->ThreadName = NULL;
235 if( IsHeap(oldname) ) free( oldname );
236 cur->ThreadName = strdup(NewName);
238 Log_Debug("Threads", "Thread renamed to '%s'", NewName);
244 * \fn char *Threads_GetName(int ID)
245 * \brief Gets a thread's name
246 * \param ID Thread ID (-1 indicates current thread)
247 * \return Pointer to name
248 * \retval NULL Failure
250 char *Threads_GetName(tTID ID)
253 return Proc_GetCurThread()->ThreadName;
255 return Threads_GetThread(ID)->ThreadName;
259 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
260 * \brief Sets the priority of a task
261 * \param Thread Thread to update ticket count (NULL means current thread)
262 * \param Pri New priority
264 void Threads_SetPriority(tThread *Thread, int Pri)
266 // Get current thread
267 if(Thread == NULL) Thread = Proc_GetCurThread();
269 // - If < 0, set to lowest priority
270 // - Minumum priority is actualy a high number, 0 is highest
271 if(Pri < 0) Pri = MIN_PRIORITY;
272 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
274 // Do we actually have to do anything?
275 if( Pri == Thread->Priority ) return;
277 #if SCHEDULER_TYPE == SCHED_RR_PRI
278 if( Thread != Proc_GetCurThread() )
280 SHORTLOCK( &glThreadListLock );
281 // Remove from old priority
282 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
284 Threads_int_AddToList( &gaActiveThreads[Pri], Thread );
285 Thread->Priority = Pri;
286 SHORTREL( &glThreadListLock );
289 Thread->Priority = Pri;
291 // If this isn't the current thread, we need to lock
292 if( Thread != Proc_GetCurThread() )
294 SHORTLOCK( &glThreadListLock );
296 #if SCHEDULER_TYPE == SCHED_LOTTERY
297 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
298 # if DEBUG_TRACE_TICKETS
299 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
301 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
304 Thread->Priority = Pri;
305 SHORTREL( &glThreadListLock );
308 Thread->Priority = Pri;
311 #if DEBUG_TRACE_STATE
312 Log("Threads_SetPriority: %p(%i %s) pri set %i",
313 Thread, Thread->TID, Thread->ThreadName,
319 * \brief Clone the TCB of the current thread
320 * \param Flags Flags for something... (What is this for?)
322 tThread *Threads_CloneTCB(Uint Flags)
325 cur = Proc_GetCurThread();
327 // Allocate and duplicate
328 new = malloc(sizeof(tThread));
329 if(new == NULL) { errno = -ENOMEM; return NULL; }
330 memcpy(new, cur, sizeof(tThread));
334 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
335 new->Status = THREAD_STAT_PREINIT;
339 new->TID = giNextTID++;
341 new->bInstrTrace = 0;
344 new->ThreadName = strdup(cur->ThreadName);
346 // Set Thread Group ID (PID)
347 if(Flags & CLONE_VM) {
348 tProcess *newproc, *oldproc;
349 oldproc = cur->Process;
350 new->Process = malloc( sizeof(struct sProcess) );
351 newproc = new->Process;
352 newproc->PID = new->TID;
353 if( Flags & CLONE_PGID )
354 newproc->PGID = oldproc->PGID;
356 newproc->PGID = newproc->PID;
357 newproc->UID = oldproc->UID;
358 newproc->GID = oldproc->GID;
359 newproc->MaxFD = oldproc->MaxFD;
360 newproc->CurrentWorkingDir = oldproc->CurrentWorkingDir ? strdup( oldproc->CurrentWorkingDir ) : NULL;
361 newproc->RootDir = oldproc->RootDir ? strdup( oldproc->RootDir ) : NULL;
362 newproc->nThreads = 1;
363 // Reference all handles in the VFS
364 VFS_ReferenceUserHandles();
366 // Add to global list
367 newproc->Prev = NULL;
369 newproc->Next = gAllProcesses;
370 gAllProcesses = newproc;
372 newproc->FirstThread = new;
373 new->ProcessNext = NULL;
376 new->Process->nThreads ++;
377 new->Process = cur->Process;
379 new->ProcessNext = new->Process->FirstThread;
380 new->Process->FirstThread = new;
383 // Messages are not inherited
384 new->Messages = NULL;
385 new->LastMessage = NULL;
388 new->Remaining = new->Quantum = cur->Quantum;
389 new->Priority = cur->Priority;
392 // Set Signal Handlers
393 new->CurFaultNum = 0;
394 new->FaultHandler = cur->FaultHandler;
396 // Maintain a global list of threads
397 SHORTLOCK( &glThreadListLock );
398 new->GlobalPrev = NULL; // Protect against bugs
399 new->GlobalNext = gAllThreads;
400 gAllThreads->GlobalPrev = new;
402 SHORTREL( &glThreadListLock );
408 * \brief Clone the TCB of the kernel thread
410 tThread *Threads_CloneThreadZero(void)
414 // Allocate and duplicate
415 new = malloc(sizeof(tThread));
419 memcpy(new, &gThreadZero, sizeof(tThread));
421 new->Process->nThreads ++;
425 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
426 new->Status = THREAD_STAT_PREINIT;
430 new->TID = giNextTID++;
434 new->ThreadName = NULL;
436 // Messages are not inherited
437 new->Messages = NULL;
438 new->LastMessage = NULL;
441 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
442 new->Priority = DEFAULT_PRIORITY;
443 new->bInstrTrace = 0;
445 // Set Signal Handlers
446 new->CurFaultNum = 0;
447 new->FaultHandler = 0;
449 // Maintain a global list of threads
450 SHORTLOCK( &glThreadListLock );
451 new->GlobalPrev = NULL; // Protect against bugs
452 new->GlobalNext = gAllThreads;
453 gAllThreads->GlobalPrev = new;
455 SHORTREL( &glThreadListLock );
461 * \brief Wait for a task to change state
462 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
463 * \param Status Thread return status
464 * \return TID of child that changed state
466 tTID Threads_WaitTID(int TID, int *Status)
471 Uint32 ev = Threads_WaitEvents(THREAD_EVENT_DEADCHILD);
473 if( ev & THREAD_EVENT_DEADCHILD )
475 // A child died, get the TID
476 tThread *us = Proc_GetCurThread();
477 ASSERT(us->LastDeadChild);
478 ret = us->LastDeadChild->TID;
479 // - Mark as dead (as opposed to undead)
480 ASSERT(us->LastDeadChild->Status == THREAD_STAT_ZOMBIE);
481 us->LastDeadChild->Status = THREAD_STAT_DEAD;
482 // - Set return status
484 *Status = us->LastDeadChild->RetStatus;
485 us->LastDeadChild = NULL;
486 Mutex_Release(&us->DeadChildLock);
490 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
495 // Any peer/child thread
497 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
503 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
511 // NOTE: Race condition - Other child dies, desired child dies, first death is 'lost'
512 while( (ret = Threads_WaitTID(-1, Status)) != TID )
524 * \brief Gets a thread given its TID
525 * \param TID Thread ID
526 * \return Thread pointer
528 tThread *Threads_GetThread(Uint TID)
532 // Search global list
533 for( thread = gAllThreads; thread; thread = thread->GlobalNext )
535 if(thread->TID == TID)
539 Log_Notice("Threads", "Unable to find TID %i on main list\n", TID);
545 * \brief Deletes an entry from a list
546 * \param List Pointer to the list head
547 * \param Thread Thread to find
550 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
552 tThread *ret, *prev = NULL;
554 for(ret = List->Head;
555 ret && ret != Thread;
556 prev = ret, ret = ret->Next
559 // Is the thread on the list
561 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
566 List->Head = Thread->Next;
567 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
570 prev->Next = Thread->Next;
571 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
573 if( Thread->Next == NULL )
579 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
582 List->Tail->Next = Thread;
590 * \brief Exit the current process (or another?)
591 * \param TID Thread ID to kill
592 * \param Status Exit status
594 void Threads_Exit(int TID, int Status)
597 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
599 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
601 // Halt forever, just in case
606 * \fn void Threads_Kill(tThread *Thread, int Status)
607 * \brief Kill a thread
608 * \param Thread Thread to kill
609 * \param Status Status code to return to the parent
611 void Threads_Kill(tThread *Thread, int Status)
614 int isCurThread = Thread == Proc_GetCurThread();
616 // TODO: Disown all children?
620 // TODO: I should keep a .Children list
621 for(child = gAllThreads;
623 child = child->GlobalNext)
625 if(child->Parent == Thread)
626 child->Parent = &gThreadZero;
631 ///\note Double lock is needed due to overlap of lock areas
633 // Lock thread (stop us recieving messages)
634 SHORTLOCK( &Thread->IsLocked );
636 // Clear Message Queue
637 while( Thread->Messages )
639 msg = Thread->Messages->Next;
640 free( Thread->Messages );
641 Thread->Messages = msg;
645 SHORTLOCK( &glThreadListLock );
647 switch(Thread->Status)
649 case THREAD_STAT_PREINIT: // Only on main list
652 // Currently active thread
653 case THREAD_STAT_ACTIVE:
654 if( Thread != Proc_GetCurThread() )
656 #if SCHEDULER_TYPE == SCHED_RR_PRI
657 tThreadList *list = &gaActiveThreads[Thread->Priority];
659 tThreadList *list = &gActiveThreads;
661 if( Threads_int_DelFromQueue( list, Thread ) )
666 Log_Warning("Threads",
667 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
668 Thread, Thread->TID, Thread->ThreadName
671 #if SCHEDULER_TYPE == SCHED_LOTTERY
672 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
675 // Ensure that we are not rescheduled
676 Thread->Remaining = 0; // Clear Remaining Quantum
677 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
679 // Update bookkeeping
680 giNumActiveThreads --;
682 // Kill it while it sleeps!
683 case THREAD_STAT_SLEEPING:
684 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
686 Log_Warning("Threads",
687 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
688 Thread, Thread->TID, Thread->ThreadName
693 // Brains!... You cannot kill something that is already dead
694 case THREAD_STAT_ZOMBIE:
695 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
696 Thread, Thread->TID, Thread->ThreadName);
697 SHORTREL( &glThreadListLock );
698 SHORTREL( &Thread->IsLocked );
702 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
708 Thread->RetStatus = Status;
710 SHORTREL( &Thread->IsLocked );
712 Thread->Status = THREAD_STAT_ZOMBIE;
713 SHORTREL( &glThreadListLock );
714 // TODO: It's possible that we could be timer-preempted here, should disable that... somehow
715 Mutex_Acquire( &Thread->Parent->DeadChildLock ); // released by parent
716 Thread->Parent->LastDeadChild = Thread;
717 Threads_PostEvent( Thread->Parent, THREAD_EVENT_DEADCHILD );
719 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
730 * \brief Yield remainder of the current thread's timeslice
732 void Threads_Yield(void)
734 // Log("Threads_Yield: by %p", __builtin_return_address(0));
739 * \breif Wait for the thread status to not be a specified value
741 void Threads_int_WaitForStatusEnd(enum eThreadStatus Status)
743 tThread *us = Proc_GetCurThread();
744 ASSERT(Status != THREAD_STAT_ACTIVE);
745 ASSERT(Status != THREAD_STAT_DEAD);
746 while( us->Status == Status )
749 if( us->Status == Status )
750 Debug("Thread %p(%i %s) rescheduled while in %s state for %p",
751 us, us->TID, us->ThreadName,
752 casTHREAD_STAT[Status],
753 __builtin_return_address(0));
757 void Threads_int_Sleep(enum eThreadStatus Status, void *Ptr, int Num, tThread **ListHead, tThread **ListTail, tShortSpinlock *Lock)
759 SHORTLOCK( &glThreadListLock );
760 tThread *us = Threads_RemActive();
762 // - Mark as sleeping
764 us->WaitPointer = Ptr;
765 us->RetStatus = Num; // Use RetStatus as a temp variable
770 (*ListTail)->Next = us;
782 //if( Proc_ThreadSync(us) )
784 SHORTREL( &glThreadListLock );
787 Threads_int_WaitForStatusEnd(Status);
791 * \fn void Threads_Sleep(void)
792 * \brief Take the current process off the run queue
794 void Threads_Sleep(void)
796 tThread *cur = Proc_GetCurThread();
799 SHORTLOCK( &glThreadListLock );
801 // Don't sleep if there is a message waiting
802 if( cur->Messages ) {
803 SHORTREL( &glThreadListLock );
807 // Remove us from running queue
809 // Mark thread as sleeping
810 cur->Status = THREAD_STAT_SLEEPING;
812 // Add to Sleeping List (at the top)
813 Threads_int_AddToList( &gSleepingThreads, cur );
815 #if DEBUG_TRACE_STATE
816 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
820 SHORTREL( &glThreadListLock );
821 Threads_int_WaitForStatusEnd(THREAD_STAT_SLEEPING);
826 * \brief Wakes a sleeping/waiting thread up
827 * \param Thread Thread to wake
828 * \return Boolean Failure (Returns ERRNO)
829 * \warning This should ONLY be called with task switches disabled
831 int Threads_Wake(tThread *Thread)
836 switch(Thread->Status)
838 case THREAD_STAT_ACTIVE:
839 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
842 case THREAD_STAT_SLEEPING:
843 // Remove from sleeping queue
844 SHORTLOCK( &glThreadListLock );
845 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
846 SHORTREL( &glThreadListLock );
848 Threads_AddActive( Thread );
850 #if DEBUG_TRACE_STATE
851 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
855 case THREAD_STAT_SEMAPHORESLEEP: {
857 tThread *th, *prev=NULL;
859 sem = Thread->WaitPointer;
861 SHORTLOCK( &sem->Protector );
863 // Remove from sleeping queue
864 for( th = sem->Waiting; th; prev = th, th = th->Next )
865 if( th == Thread ) break;
869 prev->Next = Thread->Next;
871 sem->Waiting = Thread->Next;
872 if(sem->LastWaiting == Thread)
873 sem->LastWaiting = prev;
878 for( th = sem->Signaling; th; prev = th, th = th->Next )
879 if( th == Thread ) break;
881 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
882 Thread, Thread->TID, Thread->ThreadName,
883 sem, sem->ModName, sem->Name);
888 prev->Next = Thread->Next;
890 sem->Signaling = Thread->Next;
891 if(sem->LastSignaling == Thread)
892 sem->LastSignaling = prev;
895 Thread->RetStatus = 0; // It didn't get anything
896 Threads_AddActive( Thread );
898 #if DEBUG_TRACE_STATE
899 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
901 SHORTREL( &sem->Protector );
904 case THREAD_STAT_WAITING:
905 Warning("Threads_Wake - Waiting threads are not currently supported");
908 case THREAD_STAT_DEAD:
909 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
913 Log_Warning("Threads", "Threads_Wake - Unknown process status (%i)", Thread->Status);
919 * \brief Wake a thread given the TID
920 * \param TID Thread ID to wake
921 * \return Boolean Faulure (errno)
923 int Threads_WakeTID(tTID TID)
925 tThread *thread = Threads_GetThread(TID);
929 ret = Threads_Wake( thread );
930 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
934 void Threads_ToggleTrace(int TID)
936 tThread *thread = Threads_GetThread(TID);
938 thread->bInstrTrace = !thread->bInstrTrace;
942 * \brief Adds a thread to the active queue
944 void Threads_AddActive(tThread *Thread)
946 SHORTLOCK( &glThreadListLock );
948 if( Thread->Status == THREAD_STAT_ACTIVE ) {
949 tThread *cur = Proc_GetCurThread();
950 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
951 __builtin_return_address(0),
952 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
953 SHORTREL( &glThreadListLock );
958 Thread->Status = THREAD_STAT_ACTIVE;
959 // Thread->CurCPU = -1;
960 // Add to active list
962 #if SCHEDULER_TYPE == SCHED_RR_PRI
963 tThreadList *list = &gaActiveThreads[Thread->Priority];
965 tThreadList *list = &gActiveThreads;
967 Threads_int_AddToList( list, Thread );
970 // Update bookkeeping
971 giNumActiveThreads ++;
973 #if SCHEDULER_TYPE == SCHED_LOTTERY
976 // Only change the ticket count if the thread is un-scheduled
977 if(Thread->CurCPU != -1)
980 delta = caiTICKET_COUNTS[ Thread->Priority ];
982 giFreeTickets += delta;
983 # if DEBUG_TRACE_TICKETS
984 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
985 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
992 SHORTREL( &glThreadListLock );
996 * \brief Removes the current thread from the active queue
997 * \warning This should ONLY be called with the lock held
998 * \return Current thread pointer
1000 tThread *Threads_RemActive(void)
1002 giNumActiveThreads --;
1003 return Proc_GetCurThread();
1007 * \fn void Threads_SetFaultHandler(Uint Handler)
1008 * \brief Sets the signal handler for a signal
1010 void Threads_SetFaultHandler(Uint Handler)
1012 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
1013 Proc_GetCurThread()->FaultHandler = Handler;
1017 * \fn void Threads_Fault(int Num)
1018 * \brief Calls a fault handler
1020 void Threads_Fault(int Num)
1022 tThread *thread = Proc_GetCurThread();
1024 if(!thread) return ;
1026 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
1028 switch(thread->FaultHandler)
1031 Threads_Kill(thread, -1);
1034 case 1: // Dump Core?
1035 Threads_Kill(thread, -1);
1040 // Double Fault? Oh, F**k
1041 if(thread->CurFaultNum != 0) {
1042 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
1043 Threads_Kill(thread, -1); // For now, just kill
1047 thread->CurFaultNum = Num;
1049 Proc_CallFaultHandler(thread);
1053 * \fn void Threads_SegFault(tVAddr Addr)
1054 * \brief Called when a Segment Fault occurs
1056 void Threads_SegFault(tVAddr Addr)
1058 tThread *cur = Proc_GetCurThread();
1059 cur->bInstrTrace = 0;
1060 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
1061 MM_DumpTables(0, USER_MAX);
1063 //Threads_Exit( 0, -1 );
1067 void Threads_PostSignalTo(tThread *Thread, int SignalNum)
1070 Log_Debug("Threads", "Signalling %i(%s) with %i", Thread->TID, Thread->ThreadName, SignalNum);
1071 Thread->PendingSignal = SignalNum;
1072 Threads_PostEvent(Thread, THREAD_EVENT_SIGNAL);
1074 void Threads_PostSignal(int SignalNum)
1076 Threads_PostSignalTo( Proc_GetCurThread(), SignalNum );
1079 void Threads_SignalGroup(tPGID PGID, int Signal)
1081 for( tProcess *proc = gAllProcesses; proc; proc = proc->Next )
1083 if(proc->PGID == PGID)
1085 Threads_PostSignalTo(proc->FirstThread, Signal);
1092 int Threads_GetPendingSignal(void)
1094 tThread *cur = Proc_GetCurThread();
1096 // Atomic AND with 0 fetches and clears in one operation
1097 int ret = __sync_fetch_and_and( &cur->PendingSignal, 0 );
1100 Log_Debug("Threads", "Thread %i(%s) has signal %i pending",
1101 cur->TID, cur->ThreadName, ret);
1107 * \brief Update the current thread's signal handler
1109 void Threads_SetSignalHandler(int SignalNum, void *Handler)
1111 if( SignalNum <= 0 || SignalNum >= NSIGNALS )
1113 if( !MM_IsUser(Handler) )
1115 Proc_GetCurThread()->Process->SignalHandlers[SignalNum] = Handler;
1119 * \brief Gets the registered (or default, if none set) handler for a signal.
1120 * \return Handler function pointer, OR NULL if no signal to be ignored
1122 void *Threads_GetSignalHandler(int SignalNum)
1125 void *User_Signal_Core = User_Signal_Kill;
1127 if( SignalNum <= 0 || SignalNum >= NSIGNALS )
1129 void *ret = Proc_GetCurThread()->Process->SignalHandlers[SignalNum];
1130 if( !ret || (SignalNum == SIGKILL || SignalNum == SIGSTOP) )
1137 ret = User_Signal_Kill;
1143 ret = User_Signal_Core;
1146 ret = User_Signal_Kill;
1149 ret = User_Signal_Core;
1154 ret = User_Signal_Kill;
1161 Log_Debug("Threads", "Handler %p for signal %i", ret, SignalNum);
1165 // --- Process Structure Access Functions ---
1166 tPGID Threads_GetPGID(void)
1168 return Proc_GetCurThread()->Process->PGID;
1170 tPID Threads_GetPID(void)
1172 return Proc_GetCurThread()->Process->PID;
1174 tTID Threads_GetTID(void)
1176 return Proc_GetCurThread()->TID;
1178 tUID Threads_GetUID(void)
1180 return Proc_GetCurThread()->Process->UID;
1182 tGID Threads_GetGID(void)
1184 return Proc_GetCurThread()->Process->GID;
1187 int Threads_SetUID(tUID ID)
1189 tThread *t = Proc_GetCurThread();
1190 if( t->Process->UID != 0 ) {
1194 Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1195 t->Process->UID = ID;
1199 int Threads_SetGID(tGID ID)
1201 tThread *t = Proc_GetCurThread();
1202 if( t->Process->UID != 0 ) {
1206 Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1207 t->Process->GID = ID;
1211 // --- Per-thread storage ---
1212 int *Threads_GetErrno(void)
1214 return &Proc_GetCurThread()->_errno;
1217 // --- Configuration ---
1218 int *Threads_GetMaxFD(void)
1220 return &Proc_GetCurThread()->Process->MaxFD;
1222 char **Threads_GetChroot(void)
1224 return &Proc_GetCurThread()->Process->RootDir;
1226 char **Threads_GetCWD(void)
1228 return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1232 void Threads_int_DumpThread(tThread *thread)
1235 Log(" %p NULL", thread);
1238 if( !CheckMem(thread, sizeof(tThread)) ) {
1239 Log(" %p INVAL", thread);
1242 tPID pid = (thread->Process ? thread->Process->PID : -1);
1243 const char *statstr = (thread->Status < sizeof(casTHREAD_STAT)/sizeof(casTHREAD_STAT[0])
1244 ? casTHREAD_STAT[thread->Status] : "");
1245 Log(" %p %i (%i) - %s (CPU %i) - %i (%s)",
1246 thread, thread->TID, pid, thread->ThreadName, thread->CurCPU,
1247 thread->Status, statstr
1249 switch(thread->Status)
1251 case THREAD_STAT_MUTEXSLEEP:
1252 Log(" Mutex Pointer: %p", thread->WaitPointer);
1254 case THREAD_STAT_SEMAPHORESLEEP:
1255 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1256 Log(" Semaphore Name: %s:%s",
1257 ((tSemaphore*)thread->WaitPointer)->ModName,
1258 ((tSemaphore*)thread->WaitPointer)->Name
1261 case THREAD_STAT_EVENTSLEEP:
1264 case THREAD_STAT_ZOMBIE:
1265 Log(" Return Status: %i", thread->RetStatus);
1269 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1270 Log(" KStack %p", thread->KernelStack);
1271 if( thread->bInstrTrace )
1272 Log(" Tracing Enabled");
1273 Proc_DumpThreadCPUState(thread);
1277 * \fn void Threads_Dump(void)
1279 void Threads_DumpActive(void)
1283 #if SCHEDULER_TYPE == SCHED_RR_PRI
1287 Log("Active Threads: (%i reported)", giNumActiveThreads);
1289 #if SCHEDULER_TYPE == SCHED_RR_PRI
1290 for( i = 0; i < MIN_PRIORITY+1; i++ )
1292 list = &gaActiveThreads[i];
1294 list = &gActiveThreads;
1296 for(thread=list->Head;thread;thread=thread->Next)
1298 Threads_int_DumpThread(thread);
1299 if(thread->Status != THREAD_STAT_ACTIVE)
1300 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1301 thread->Status, THREAD_STAT_ACTIVE);
1304 #if SCHEDULER_TYPE == SCHED_RR_PRI
1310 * \fn void Threads_Dump(void)
1311 * \brief Dumps a list of currently running threads
1313 void Threads_Dump(void)
1315 Log("--- Thread Dump ---");
1316 Threads_DumpActive();
1318 Log("All Threads:");
1319 for(tThread *thread = gAllThreads; thread; thread = thread->GlobalNext)
1321 Threads_int_DumpThread(thread);
1326 * \brief Gets the next thread to run
1327 * \param CPU Current CPU
1328 * \param Last The thread the CPU was running
1330 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1334 // If this CPU has the lock, we must let it complete
1335 if( CPU_HAS_LOCK( &glThreadListLock ) )
1338 // Don't change threads if the current CPU has switches disabled
1339 if( gaThreads_NoTaskSwitch[CPU] )
1343 SHORTLOCK( &glThreadListLock );
1345 // Make sure the current (well, old) thread is marked as de-scheduled
1346 if(Last) Last->CurCPU = -1;
1348 // No active threads, just take a nap
1349 if(giNumActiveThreads == 0) {
1350 SHORTREL( &glThreadListLock );
1351 #if DEBUG_TRACE_TICKETS
1352 Log("No active threads");
1358 #if SCHEDULER_TYPE != SCHED_RR_PRI
1359 // Special case: 1 thread
1360 if(giNumActiveThreads == 1) {
1361 if( gActiveThreads.Head->CurCPU == -1 )
1362 gActiveThreads.Head->CurCPU = CPU;
1364 SHORTREL( &glThreadListLock );
1366 if( gActiveThreads.Head->CurCPU == CPU )
1367 return gActiveThreads.Head;
1369 return NULL; // CPU has nothing to do
1374 // Allow the old thread to be scheduled again
1376 if( Last->Status == THREAD_STAT_ACTIVE ) {
1378 #if SCHEDULER_TYPE == SCHED_LOTTERY
1379 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1380 # if DEBUG_TRACE_TICKETS
1381 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1382 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1383 caiTICKET_COUNTS[ Last->Priority ]);
1387 #if SCHEDULER_TYPE == SCHED_RR_PRI
1388 list = &gaActiveThreads[ Last->Priority ];
1390 list = &gActiveThreads;
1392 // Add to end of list
1393 Threads_int_AddToList( list, Last );
1395 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1397 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1398 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1404 // Lottery Scheduler
1406 #if SCHEDULER_TYPE == SCHED_LOTTERY
1411 for(thread = gActiveThreads.Head; thread; thread = thread->Next)
1413 if(thread->Status != THREAD_STAT_ACTIVE)
1414 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1415 thread, thread->TID, thread->ThreadName, thread->Status);
1416 if(thread->Next == thread) {
1417 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1418 thread, thread->TID, thread->ThreadName, thread->Status);
1420 number += caiTICKET_COUNTS[ thread->Priority ];
1422 if(number != giFreeTickets) {
1423 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1424 giFreeTickets, number, CPU);
1428 // No free tickets (all tasks delegated to cores)
1429 if( giFreeTickets == 0 ) {
1430 SHORTREL(&glThreadListLock);
1434 // Get the ticket number
1435 ticket = number = rand() % giFreeTickets;
1437 // Find the next thread
1438 for(thread = gActiveThreads.Head; thread; prev = thread, thread = thread->Next )
1440 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1441 number -= caiTICKET_COUNTS[ thread->Priority ];
1444 // If we didn't find a thread, something went wrong
1448 for(thread=gActiveThreads;thread;thread=thread->Next) {
1449 if(thread->CurCPU >= 0) continue;
1450 number += caiTICKET_COUNTS[ thread->Priority ];
1452 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1453 giFreeTickets, number);
1458 prev->Next = thread->Next;
1460 gActiveThreads.Head = thread->Next;
1462 gActiveThreads.Tail = prev;
1464 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1465 # if DEBUG_TRACE_TICKETS
1466 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1467 CPU, thread, thread->TID, thread->ThreadName,
1468 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1473 // Priority based round robin scheduler
1475 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1479 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1481 if( !gaActiveThreads[i].Head )
1484 thread = gaActiveThreads[i].Head;
1487 gaActiveThreads[i].Head = thread->Next;
1489 gaActiveThreads[i].Tail = NULL;
1490 thread->Next = NULL;
1496 SHORTREL(&glThreadListLock);
1499 if( thread->Status != THREAD_STAT_ACTIVE ) {
1500 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1503 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1505 // Get the next thread off the list
1506 thread = gActiveThreads.Head;
1507 gActiveThreads.Head = thread->Next;
1509 gaActiveThreads.Tail = NULL;
1510 thread->Next = NULL;
1514 SHORTREL(&glThreadListLock);
1519 # error "Unimplemented scheduling algorithm"
1522 // Make the new thread non-schedulable
1523 thread->CurCPU = CPU;
1524 thread->Remaining = thread->Quantum;
1526 SHORTREL( &glThreadListLock );
1532 EXPORT(Threads_GetUID);
1533 EXPORT(Threads_GetGID);