4 * - Common Thread Control
8 #include <threads_int.h>
11 #include <semaphore.h>
14 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
15 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
19 #define SCHED_LOTTERY 1 // Lottery scheduler
20 #define SCHED_RR_SIM 2 // Single Queue Round Robin
21 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
23 #define SCHEDULER_TYPE SCHED_RR_PRI
26 #define DEFAULT_QUANTUM 5
27 #define DEFAULT_PRIORITY 5
28 #define MIN_PRIORITY 10
29 const enum eConfigTypes cCONFIG_TYPES[NUM_CFG_ENTRIES] = {
30 CFGT_HEAPSTR, // e.g. CFG_VFS_CWD
31 CFGT_INT, // e.g. CFG_VFS_MAXFILES
45 void Threads_Init(void);
47 void Threads_Delete(tThread *Thread);
48 int Threads_SetName(const char *NewName);
50 char *Threads_GetName(int ID);
52 void Threads_SetPriority(tThread *Thread, int Pri);
53 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
54 int Threads_WaitTID(int TID, int *status);
55 tThread *Threads_GetThread(Uint TID);
57 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread);
58 void Threads_int_AddToList(tThreadList *List, tThread *Thread);
60 void Threads_Exit(int TID, int Status);
61 void Threads_Kill(tThread *Thread, int Status);
62 void Threads_Yield(void);
63 void Threads_Sleep(void);
64 int Threads_Wake(tThread *Thread);
65 void Threads_AddActive(tThread *Thread);
66 tThread *Threads_RemActive(void);
68 void Threads_ToggleTrace(int TID);
69 void Threads_Fault(int Num);
70 void Threads_SegFault(tVAddr Addr);
72 int Threads_GetPID(void);
73 int Threads_GetTID(void);
74 tUID Threads_GetUID(void);
75 tGID Threads_GetGID(void);
76 int Threads_SetUID(Uint *Errno, tUID ID);
77 int Threads_SetGID(Uint *Errno, tUID ID);
79 void Threads_Dump(void);
80 void Threads_DumpActive(void);
84 // Only used for the core kernel
85 tThread gThreadZero = {
86 .Status = THREAD_STAT_ACTIVE, // Status
87 .ThreadName = (char*)"ThreadZero", // Name
88 .Quantum = DEFAULT_QUANTUM, // Default Quantum
89 .Remaining = DEFAULT_QUANTUM, // Current Quantum
90 .Priority = DEFAULT_PRIORITY // Number of tickets
94 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
95 // --- Current State ---
96 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
97 volatile Uint giNextTID = 1; // Next TID to allocate
98 // --- Thread Lists ---
99 tThread *gAllThreads = NULL; // All allocated threads
100 tThreadList gSleepingThreads; // Sleeping Threads
101 int giNumCPUs = 1; // Number of CPUs
102 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
103 // --- Scheduler Types ---
104 #if SCHEDULER_TYPE == SCHED_LOTTERY
105 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
106 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
107 tThreadList gActiveThreads; // Currently Running Threads
108 #elif SCHEDULER_TYPE == SCHED_RR_SIM
109 tThreadList gActiveThreads; // Currently Running Threads
110 #elif SCHEDULER_TYPE == SCHED_RR_PRI
111 tThreadList gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
113 # error "Unkown scheduler type"
118 * \fn void Threads_Init(void)
119 * \brief Initialse the thread list
121 void Threads_Init(void)
125 Log_Debug("Threads", "Offsets of tThread");
126 Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
127 Log_Debug("Threads", ".KernelStack = %i", offsetof(tThread, KernelStack));
129 // Create Initial Task
130 // #if SCHEDULER_TYPE == SCHED_RR_PRI
131 // gaActiveThreads[gThreadZero.Priority].Head = &gThreadZero;
132 // gaActiveThreads[gThreadZero.Priority].Tail = &gThreadZero;
134 // gActiveThreads.Head = &gThreadZero;
135 // gActiveThreads.Tail = &gThreadZero;
138 gAllThreads = &gThreadZero;
139 giNumActiveThreads = 1;
144 void Threads_Delete(tThread *Thread)
147 Thread->Status = THREAD_STAT_BURIED;
149 // Clear out process state
150 Proc_ClearThread(Thread);
153 if( IsHeap(Thread->ThreadName) )
154 free(Thread->ThreadName);
156 // Remove from global list
157 // TODO: Lock this too
158 if( Thread == gAllThreads )
159 gAllThreads = Thread->GlobalNext;
161 Thread->GlobalPrev->GlobalNext = Thread->GlobalNext;
167 * \fn void Threads_SetName(const char *NewName)
168 * \brief Sets the current thread's name
169 * \param NewName New name for the thread
170 * \return Boolean Failure
172 int Threads_SetName(const char *NewName)
174 tThread *cur = Proc_GetCurThread();
175 char *oldname = cur->ThreadName;
177 // NOTE: There is a possibility of non-thread safety here
178 // A thread could read the current name pointer before it is zeroed
180 cur->ThreadName = NULL;
182 if( IsHeap(oldname) ) free( oldname );
184 cur->ThreadName = strdup(NewName);
189 * \fn char *Threads_GetName(int ID)
190 * \brief Gets a thread's name
191 * \param ID Thread ID (-1 indicates current thread)
192 * \return Pointer to name
193 * \retval NULL Failure
195 char *Threads_GetName(tTID ID)
198 return Proc_GetCurThread()->ThreadName;
200 return Threads_GetThread(ID)->ThreadName;
204 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
205 * \brief Sets the priority of a task
206 * \param Thread Thread to update ticket count (NULL means current thread)
207 * \param Pri New priority
209 void Threads_SetPriority(tThread *Thread, int Pri)
211 // Get current thread
212 if(Thread == NULL) Thread = Proc_GetCurThread();
214 // - If < 0, set to lowest priority
215 // - Minumum priority is actualy a high number, 0 is highest
216 if(Pri < 0) Pri = MIN_PRIORITY;
217 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
219 // Do we actually have to do anything?
220 if( Pri == Thread->Priority ) return;
222 #if SCHEDULER_TYPE == SCHED_RR_PRI
223 if( Thread != Proc_GetCurThread() )
225 SHORTLOCK( &glThreadListLock );
226 // Remove from old priority
227 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
229 Threads_int_AddToList( &gaActiveThreads[Pri], Thread );
230 Thread->Priority = Pri;
231 SHORTREL( &glThreadListLock );
234 Thread->Priority = Pri;
236 // If this isn't the current thread, we need to lock
237 if( Thread != Proc_GetCurThread() )
239 SHORTLOCK( &glThreadListLock );
241 #if SCHEDULER_TYPE == SCHED_LOTTERY
242 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
243 # if DEBUG_TRACE_TICKETS
244 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
246 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
249 Thread->Priority = Pri;
250 SHORTREL( &glThreadListLock );
253 Thread->Priority = Pri;
256 #if DEBUG_TRACE_STATE
257 Log("Threads_SetPriority: %p(%i %s) pri set %i",
258 Thread, Thread->TID, Thread->ThreadName,
264 * \brief Clone the TCB of the current thread
265 * \param Flags Flags for something... (What is this for?)
267 tThread *Threads_CloneTCB(Uint Flags)
271 cur = Proc_GetCurThread();
273 // Allocate and duplicate
274 new = malloc(sizeof(tThread));
275 if(new == NULL) { errno = -ENOMEM; return NULL; }
276 memcpy(new, cur, sizeof(tThread));
280 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
281 new->Status = THREAD_STAT_PREINIT;
285 new->TID = giNextTID++;
287 new->bInstrTrace = 0;
290 new->ThreadName = strdup(cur->ThreadName);
292 // Set Thread Group ID (PID)
294 new->TGID = new->TID;
296 new->TGID = cur->TGID;
298 // Messages are not inherited
299 new->Messages = NULL;
300 new->LastMessage = NULL;
303 new->Remaining = new->Quantum = cur->Quantum;
304 new->Priority = cur->Priority;
306 // Set Signal Handlers
307 new->CurFaultNum = 0;
308 new->FaultHandler = cur->FaultHandler;
310 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
312 switch(cCONFIG_TYPES[i])
315 new->Config[i] = cur->Config[i];
319 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
326 // Maintain a global list of threads
327 SHORTLOCK( &glThreadListLock );
328 new->GlobalPrev = NULL; // Protect against bugs
329 new->GlobalNext = gAllThreads;
330 gAllThreads->GlobalPrev = new;
332 SHORTREL( &glThreadListLock );
338 * \brief Clone the TCB of the kernel thread
340 tThread *Threads_CloneThreadZero(void)
345 // Allocate and duplicate
346 new = malloc(sizeof(tThread));
350 memcpy(new, &gThreadZero, sizeof(tThread));
354 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
355 new->Status = THREAD_STAT_PREINIT;
359 new->TID = giNextTID++;
363 new->ThreadName = NULL;
365 // Messages are not inherited
366 new->Messages = NULL;
367 new->LastMessage = NULL;
370 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
371 new->Priority = DEFAULT_PRIORITY;
372 new->bInstrTrace = 0;
374 // Set Signal Handlers
375 new->CurFaultNum = 0;
376 new->FaultHandler = 0;
378 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
383 // Maintain a global list of threads
384 SHORTLOCK( &glThreadListLock );
385 new->GlobalPrev = NULL; // Protect against bugs
386 new->GlobalNext = gAllThreads;
387 gAllThreads->GlobalPrev = new;
389 SHORTREL( &glThreadListLock );
395 * \brief Get a configuration pointer from the Per-Thread data area
396 * \param ID Config slot ID
397 * \return Pointer at ID
399 Uint *Threads_GetCfgPtr(int ID)
401 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
402 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
406 return &Proc_GetCurThread()->Config[ID];
410 * \brief Wait for a task to change state
411 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
412 * \param Status Thread return status
413 * \return TID of child that changed state
415 tTID Threads_WaitTID(int TID, int *Status)
419 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
423 // Any peer/child thread
425 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
431 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
437 tThread *t = Threads_GetThread(TID);
440 // Wait for the thread to die!
441 // TODO: Handle child also being suspended if wanted
442 while(t->Status != THREAD_STAT_ZOMBIE) {
444 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
445 Threads_GetTID(), t->TID, t->Status);
452 case THREAD_STAT_ZOMBIE:
454 t->Status = THREAD_STAT_DEAD;
455 // TODO: Child return value?
456 if(Status) *Status = t->RetStatus;
457 // add to delete queue
461 if(Status) *Status = -1;
471 * \brief Gets a thread given its TID
472 * \param TID Thread ID
473 * \return Thread pointer
475 tThread *Threads_GetThread(Uint TID)
479 // Search global list
480 for(thread = gAllThreads;
482 thread = thread->GlobalNext)
484 if(thread->TID == TID)
488 Log("Unable to find TID %i on main list\n", TID);
494 * \brief Deletes an entry from a list
495 * \param List Pointer to the list head
496 * \param Thread Thread to find
499 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
501 tThread *ret, *prev = NULL;
503 for(ret = List->Head;
504 ret && ret != Thread;
505 prev = ret, ret = ret->Next
508 // Is the thread on the list
510 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
515 List->Head = Thread->Next;
516 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
519 prev->Next = Thread->Next;
520 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
522 if( Thread->Next == NULL )
528 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
531 List->Tail->Next = Thread;
539 * \brief Exit the current process (or another?)
540 * \param TID Thread ID to kill
541 * \param Status Exit status
543 void Threads_Exit(int TID, int Status)
546 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
548 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
550 // Halt forever, just in case
555 * \fn void Threads_Kill(tThread *Thread, int Status)
556 * \brief Kill a thread
557 * \param Thread Thread to kill
558 * \param Status Status code to return to the parent
560 void Threads_Kill(tThread *Thread, int Status)
563 int isCurThread = Thread == Proc_GetCurThread();
565 // TODO: Disown all children?
569 // TODO: I should keep a .Children list
570 for(child = gAllThreads;
572 child = child->GlobalNext)
574 if(child->Parent == Thread)
575 child->Parent = &gThreadZero;
580 ///\note Double lock is needed due to overlap of lock areas
582 // Lock thread (stop us recieving messages)
583 SHORTLOCK( &Thread->IsLocked );
585 // Clear Message Queue
586 while( Thread->Messages )
588 msg = Thread->Messages->Next;
589 free( Thread->Messages );
590 Thread->Messages = msg;
594 SHORTLOCK( &glThreadListLock );
596 switch(Thread->Status)
598 case THREAD_STAT_PREINIT: // Only on main list
601 // Currently active thread
602 case THREAD_STAT_ACTIVE:
603 if( Thread != Proc_GetCurThread() )
605 #if SCHEDULER_TYPE == SCHED_RR_PRI
606 tThreadList *list = &gaActiveThreads[Thread->Priority];
608 tThreadList *list = &gActiveThreads;
610 if( Threads_int_DelFromQueue( list, Thread ) )
615 Log_Warning("Threads",
616 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
617 Thread, Thread->TID, Thread->ThreadName
620 #if SCHEDULER_TYPE == SCHED_LOTTERY
621 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
624 // Ensure that we are not rescheduled
625 Thread->Remaining = 0; // Clear Remaining Quantum
626 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
628 // Update bookkeeping
629 giNumActiveThreads --;
631 // Kill it while it sleeps!
632 case THREAD_STAT_SLEEPING:
633 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
635 Log_Warning("Threads",
636 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
637 Thread, Thread->TID, Thread->ThreadName
642 // Brains!... You cannot kill something that is already dead
643 case THREAD_STAT_ZOMBIE:
644 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
645 Thread, Thread->TID, Thread->ThreadName);
646 SHORTREL( &glThreadListLock );
647 SHORTREL( &Thread->IsLocked );
651 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
657 Thread->RetStatus = Status;
659 SHORTREL( &Thread->IsLocked );
661 Thread->Status = THREAD_STAT_ZOMBIE;
662 SHORTREL( &glThreadListLock );
663 // TODO: Send something like SIGCHLD
664 Threads_Wake( Thread->Parent );
666 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
677 * \brief Yield remainder of the current thread's timeslice
679 void Threads_Yield(void)
681 // Log("Threads_Yield: by %p", __builtin_return_address(0));
686 * \fn void Threads_Sleep(void)
687 * \brief Take the current process off the run queue
689 void Threads_Sleep(void)
691 tThread *cur = Proc_GetCurThread();
694 SHORTLOCK( &glThreadListLock );
696 // Don't sleep if there is a message waiting
697 if( cur->Messages ) {
698 SHORTREL( &glThreadListLock );
702 // Remove us from running queue
704 // Mark thread as sleeping
705 cur->Status = THREAD_STAT_SLEEPING;
707 // Add to Sleeping List (at the top)
708 Threads_int_AddToList( &gSleepingThreads, cur );
710 #if DEBUG_TRACE_STATE
711 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
715 SHORTREL( &glThreadListLock );
717 while(cur->Status != THREAD_STAT_ACTIVE) {
719 if( cur->Status != THREAD_STAT_ACTIVE )
720 Log("%i - Huh? why am I up? zzzz...", cur->TID);
726 * \brief Wakes a sleeping/waiting thread up
727 * \param Thread Thread to wake
728 * \return Boolean Failure (Returns ERRNO)
729 * \warning This should ONLY be called with task switches disabled
731 int Threads_Wake(tThread *Thread)
736 switch(Thread->Status)
738 case THREAD_STAT_ACTIVE:
739 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
742 case THREAD_STAT_SLEEPING:
743 SHORTLOCK( &glThreadListLock );
744 // Remove from sleeping queue
745 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
747 SHORTREL( &glThreadListLock );
748 Threads_AddActive( Thread );
750 #if DEBUG_TRACE_STATE
751 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
755 case THREAD_STAT_SEMAPHORESLEEP: {
757 tThread *th, *prev=NULL;
759 sem = Thread->WaitPointer;
761 SHORTLOCK( &sem->Protector );
763 // Remove from sleeping queue
764 for( th = sem->Waiting; th; prev = th, th = th->Next )
765 if( th == Thread ) break;
769 prev->Next = Thread->Next;
771 sem->Waiting = Thread->Next;
772 if(sem->LastWaiting == Thread)
773 sem->LastWaiting = prev;
778 for( th = sem->Signaling; th; prev = th, th = th->Next )
779 if( th == Thread ) break;
781 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
782 Thread, Thread->TID, Thread->ThreadName,
783 sem, sem->ModName, sem->Name);
788 prev->Next = Thread->Next;
790 sem->Signaling = Thread->Next;
791 if(sem->LastSignaling == Thread)
792 sem->LastSignaling = prev;
795 Thread->RetStatus = 0; // It didn't get anything
796 Threads_AddActive( Thread );
798 #if DEBUG_TRACE_STATE
799 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
801 SHORTREL( &sem->Protector );
804 case THREAD_STAT_WAITING:
805 Warning("Threads_Wake - Waiting threads are not currently supported");
808 case THREAD_STAT_DEAD:
809 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
813 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
819 * \brief Wake a thread given the TID
820 * \param TID Thread ID to wake
821 * \return Boolean Faulure (errno)
823 int Threads_WakeTID(tTID TID)
825 tThread *thread = Threads_GetThread(TID);
829 ret = Threads_Wake( thread );
830 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
834 void Threads_ToggleTrace(int TID)
836 tThread *thread = Threads_GetThread(TID);
838 thread->bInstrTrace = !thread->bInstrTrace;
842 * \brief Adds a thread to the active queue
844 void Threads_AddActive(tThread *Thread)
846 SHORTLOCK( &glThreadListLock );
848 if( Thread->Status == THREAD_STAT_ACTIVE ) {
849 tThread *cur = Proc_GetCurThread();
850 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
851 __builtin_return_address(0),
852 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
853 SHORTREL( &glThreadListLock );
858 Thread->Status = THREAD_STAT_ACTIVE;
859 // Thread->CurCPU = -1;
860 // Add to active list
862 #if SCHEDULER_TYPE == SCHED_RR_PRI
863 tThreadList *list = &gaActiveThreads[Thread->Priority];
865 tThreadList *list = &gActiveThreads;
867 Threads_int_AddToList( list, Thread );
870 // Update bookkeeping
871 giNumActiveThreads ++;
873 #if SCHEDULER_TYPE == SCHED_LOTTERY
876 // Only change the ticket count if the thread is un-scheduled
877 if(Thread->CurCPU != -1)
880 delta = caiTICKET_COUNTS[ Thread->Priority ];
882 giFreeTickets += delta;
883 # if DEBUG_TRACE_TICKETS
884 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
885 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
892 SHORTREL( &glThreadListLock );
896 * \brief Removes the current thread from the active queue
897 * \warning This should ONLY be called with the lock held
898 * \return Current thread pointer
900 tThread *Threads_RemActive(void)
903 tThread *ret = Proc_GetCurThread();
905 if( !IS_LOCKED(&glThreadListLock) ) {
906 Log_KernelPanic("Threads", "Threads_RemActive called without lock held");
910 // Delete from active queue
911 #if SCHEDULER_TYPE == SCHED_RR_PRI
912 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
914 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
917 Log_Warning("Threads", "Current thread %p(%i %s) is not on active queue",
918 ret, ret->TID, ret->ThreadName
926 giNumActiveThreads --;
927 // no need to decrement tickets, scheduler did it for us
929 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
930 Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
931 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
936 return Proc_GetCurThread();
941 * \fn void Threads_SetFaultHandler(Uint Handler)
942 * \brief Sets the signal handler for a signal
944 void Threads_SetFaultHandler(Uint Handler)
946 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
947 Proc_GetCurThread()->FaultHandler = Handler;
951 * \fn void Threads_Fault(int Num)
952 * \brief Calls a fault handler
954 void Threads_Fault(int Num)
956 tThread *thread = Proc_GetCurThread();
960 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
962 switch(thread->FaultHandler)
965 Threads_Kill(thread, -1);
968 case 1: // Dump Core?
969 Threads_Kill(thread, -1);
974 // Double Fault? Oh, F**k
975 if(thread->CurFaultNum != 0) {
976 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
977 Threads_Kill(thread, -1); // For now, just kill
981 thread->CurFaultNum = Num;
983 Proc_CallFaultHandler(thread);
987 * \fn void Threads_SegFault(tVAddr Addr)
988 * \brief Called when a Segment Fault occurs
990 void Threads_SegFault(tVAddr Addr)
992 tThread *cur = Proc_GetCurThread();
993 cur->bInstrTrace = 0;
994 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
995 MM_DumpTables(0, USER_MAX);
997 //Threads_Exit( 0, -1 );
1000 // --- Process Structure Access Functions ---
1001 tPID Threads_GetPID(void)
1003 return Proc_GetCurThread()->TGID;
1005 tTID Threads_GetTID(void)
1007 return Proc_GetCurThread()->TID;
1009 tUID Threads_GetUID(void)
1011 return Proc_GetCurThread()->UID;
1013 tGID Threads_GetGID(void)
1015 return Proc_GetCurThread()->GID;
1018 int Threads_SetUID(Uint *Errno, tUID ID)
1020 tThread *t = Proc_GetCurThread();
1025 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
1030 int Threads_SetGID(Uint *Errno, tGID ID)
1032 tThread *t = Proc_GetCurThread();
1037 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
1043 * \fn void Threads_Dump(void)
1045 void Threads_DumpActive(void)
1049 #if SCHEDULER_TYPE == SCHED_RR_PRI
1053 Log("Active Threads: (%i reported)", giNumActiveThreads);
1055 #if SCHEDULER_TYPE == SCHED_RR_PRI
1056 for( i = 0; i < MIN_PRIORITY+1; i++ )
1058 list = &gaActiveThreads[i];
1060 list = &gActiveThreads;
1062 for(thread=list->Head;thread;thread=thread->Next)
1064 Log(" %p %i (%i) - %s (CPU %i)",
1065 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1066 if(thread->Status != THREAD_STAT_ACTIVE)
1067 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1068 thread->Status, THREAD_STAT_ACTIVE);
1069 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1070 Log(" KStack 0x%x", thread->KernelStack);
1071 if( thread->bInstrTrace )
1072 Log(" Tracing Enabled");
1073 Proc_DumpThreadCPUState(thread);
1076 #if SCHEDULER_TYPE == SCHED_RR_PRI
1082 * \fn void Threads_Dump(void)
1083 * \brief Dumps a list of currently running threads
1085 void Threads_Dump(void)
1089 Log("--- Thread Dump ---");
1090 Threads_DumpActive();
1092 Log("All Threads:");
1093 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1095 Log(" %p %i (%i) - %s (CPU %i)",
1096 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1097 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1098 switch(thread->Status)
1100 case THREAD_STAT_MUTEXSLEEP:
1101 Log(" Mutex Pointer: %p", thread->WaitPointer);
1103 case THREAD_STAT_SEMAPHORESLEEP:
1104 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1105 Log(" Semaphore Name: %s:%s",
1106 ((tSemaphore*)thread->WaitPointer)->ModName,
1107 ((tSemaphore*)thread->WaitPointer)->Name
1110 case THREAD_STAT_ZOMBIE:
1111 Log(" Return Status: %i", thread->RetStatus);
1115 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1116 Log(" KStack 0x%x", thread->KernelStack);
1117 if( thread->bInstrTrace )
1118 Log(" Tracing Enabled");
1119 Proc_DumpThreadCPUState(thread);
1124 * \brief Gets the next thread to run
1125 * \param CPU Current CPU
1126 * \param Last The thread the CPU was running
1128 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1132 // If this CPU has the lock, we must let it complete
1133 if( CPU_HAS_LOCK( &glThreadListLock ) )
1136 // Don't change threads if the current CPU has switches disabled
1137 if( gaThreads_NoTaskSwitch[CPU] )
1141 SHORTLOCK( &glThreadListLock );
1143 // Make sure the current (well, old) thread is marked as de-scheduled
1144 if(Last) Last->CurCPU = -1;
1146 // No active threads, just take a nap
1147 if(giNumActiveThreads == 0) {
1148 SHORTREL( &glThreadListLock );
1149 #if DEBUG_TRACE_TICKETS
1150 Log("No active threads");
1156 #if SCHEDULER_TYPE != SCHED_RR_PRI
1157 // Special case: 1 thread
1158 if(giNumActiveThreads == 1) {
1159 if( gActiveThreads.Head->CurCPU == -1 )
1160 gActiveThreads.Head->CurCPU = CPU;
1162 SHORTREL( &glThreadListLock );
1164 if( gActiveThreads.Head->CurCPU == CPU )
1165 return gActiveThreads.Head;
1167 return NULL; // CPU has nothing to do
1172 // Allow the old thread to be scheduled again
1174 if( Last->Status == THREAD_STAT_ACTIVE ) {
1176 #if SCHEDULER_TYPE == SCHED_LOTTERY
1177 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1178 # if DEBUG_TRACE_TICKETS
1179 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1180 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1181 caiTICKET_COUNTS[ Last->Priority ]);
1185 #if SCHEDULER_TYPE == SCHED_RR_PRI
1186 list = &gaActiveThreads[ Last->Priority ];
1188 list = &gActiveThreads;
1190 // Add to end of list
1191 Threads_int_AddToList( list, Last );
1193 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1195 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1196 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1202 // Lottery Scheduler
1204 #if SCHEDULER_TYPE == SCHED_LOTTERY
1209 for(thread = gActiveThreads.Head; thread; thread = thread->Next)
1211 if(thread->Status != THREAD_STAT_ACTIVE)
1212 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1213 thread, thread->TID, thread->ThreadName, thread->Status);
1214 if(thread->Next == thread) {
1215 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1216 thread, thread->TID, thread->ThreadName, thread->Status);
1218 number += caiTICKET_COUNTS[ thread->Priority ];
1220 if(number != giFreeTickets) {
1221 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1222 giFreeTickets, number, CPU);
1226 // No free tickets (all tasks delegated to cores)
1227 if( giFreeTickets == 0 ) {
1228 SHORTREL(&glThreadListLock);
1232 // Get the ticket number
1233 ticket = number = rand() % giFreeTickets;
1235 // Find the next thread
1236 for(thread = gActiveThreads.Head; thread; prev = thread, thread = thread->Next )
1238 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1239 number -= caiTICKET_COUNTS[ thread->Priority ];
1242 // If we didn't find a thread, something went wrong
1246 for(thread=gActiveThreads;thread;thread=thread->Next) {
1247 if(thread->CurCPU >= 0) continue;
1248 number += caiTICKET_COUNTS[ thread->Priority ];
1250 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1251 giFreeTickets, number);
1256 prev->Next = thread->Next;
1258 gActiveThreads.Head = thread->Next;
1260 gActiveThreads.Tail = prev;
1262 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1263 # if DEBUG_TRACE_TICKETS
1264 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1265 CPU, thread, thread->TID, thread->ThreadName,
1266 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1271 // Priority based round robin scheduler
1273 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1277 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1279 if( !gaActiveThreads[i].Head )
1282 thread = gaActiveThreads[i].Head;
1285 gaActiveThreads[i].Head = thread->Next;
1287 gaActiveThreads[i].Tail = NULL;
1288 thread->Next = NULL;
1294 SHORTREL(&glThreadListLock);
1297 if( thread->Status != THREAD_STAT_ACTIVE ) {
1298 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1301 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1303 // Get the next thread off the list
1304 thread = gActiveThreads.Head;
1305 gActiveThreads.Head = thread->Next;
1307 gaActiveThreads.Tail = NULL;
1308 thread->Next = NULL;
1312 SHORTREL(&glThreadListLock);
1317 # error "Unimplemented scheduling algorithm"
1320 // Make the new thread non-schedulable
1321 thread->CurCPU = CPU;
1322 thread->Remaining = thread->Quantum;
1324 SHORTREL( &glThreadListLock );
1330 EXPORT(Threads_GetUID);
1331 EXPORT(Threads_GetGID);