4 * - Common Thread Control
8 #include <threads_int.h>
11 #include <semaphore.h>
15 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
16 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
17 #define SEMAPHORE_DEBUG 0
21 #define SCHED_LOTTERY 1 // Lottery scheduler
22 #define SCHED_RR_SIM 2 // Single Queue Round Robin
23 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
25 #define SCHEDULER_TYPE SCHED_RR_PRI
28 #define DEFAULT_QUANTUM 5
29 #define DEFAULT_PRIORITY 5
30 #define MIN_PRIORITY 10
31 const enum eConfigTypes cCONFIG_TYPES[] = {
32 CFGT_HEAPSTR, // e.g. CFG_VFS_CWD
33 CFGT_INT, // e.g. CFG_VFS_MAXFILES
40 void Threads_Init(void);
42 int Threads_SetName(const char *NewName);
44 char *Threads_GetName(int ID);
46 void Threads_SetPriority(tThread *Thread, int Pri);
47 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
48 int Threads_WaitTID(int TID, int *status);
49 tThread *Threads_GetThread(Uint TID);
51 void Threads_AddToDelete(tThread *Thread);
52 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread);
54 void Threads_Exit(int TID, int Status);
55 void Threads_Kill(tThread *Thread, int Status);
56 void Threads_Yield(void);
57 void Threads_Sleep(void);
58 int Threads_Wake(tThread *Thread);
59 void Threads_AddActive(tThread *Thread);
60 tThread *Threads_RemActive(void);
62 void Threads_ToggleTrace(int TID);
63 void Threads_Fault(int Num);
64 void Threads_SegFault(tVAddr Addr);
66 int Threads_GetPID(void);
67 int Threads_GetTID(void);
68 tUID Threads_GetUID(void);
69 tGID Threads_GetGID(void);
70 int Threads_SetUID(Uint *Errno, tUID ID);
71 int Threads_SetGID(Uint *Errno, tUID ID);
73 void Threads_Dump(void);
74 void Threads_DumpActive(void);
76 int Mutex_Acquire(tMutex *Mutex);
77 void Mutex_Release(tMutex *Mutex);
78 int Mutex_IsLocked(tMutex *Mutex);
83 // Only used for the core kernel
84 tThread gThreadZero = {
85 .Status = THREAD_STAT_ACTIVE, // Status
86 .ThreadName = (char*)"ThreadZero", // Name
87 .Quantum = DEFAULT_QUANTUM, // Default Quantum
88 .Remaining = DEFAULT_QUANTUM, // Current Quantum
89 .Priority = DEFAULT_PRIORITY // Number of tickets
93 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
94 // --- Current State ---
95 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
96 volatile Uint giNextTID = 1; // Next TID to allocate
97 // --- Thread Lists ---
98 tThread *gAllThreads = NULL; // All allocated threads
99 tThread *gSleepingThreads = NULL; // Sleeping Threads
100 tThread *gDeleteThreads = NULL; // Threads to delete
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 tThread *gActiveThreads = NULL; // Currently Running Threads
108 #elif SCHEDULER_TYPE == SCHED_RR_SIM
109 tThread *gActiveThreads = NULL; // Currently Running Threads
110 #elif SCHEDULER_TYPE == SCHED_RR_PRI
111 tThread *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] = &gThreadZero;
133 gActiveThreads = &gThreadZero;
136 gAllThreads = &gThreadZero;
137 giNumActiveThreads = 1;
143 * \fn void Threads_SetName(const char *NewName)
144 * \brief Sets the current thread's name
145 * \param NewName New name for the thread
146 * \return Boolean Failure
148 int Threads_SetName(const char *NewName)
150 tThread *cur = Proc_GetCurThread();
151 char *oldname = cur->ThreadName;
153 // NOTE: There is a possibility of non-thread safety here
154 // A thread could read the current name pointer before it is zeroed
156 cur->ThreadName = NULL;
158 if( IsHeap(oldname) ) free( oldname );
160 cur->ThreadName = strdup(NewName);
165 * \fn char *Threads_GetName(int ID)
166 * \brief Gets a thread's name
167 * \param ID Thread ID (-1 indicates current thread)
168 * \return Pointer to name
169 * \retval NULL Failure
171 char *Threads_GetName(tTID ID)
174 return Proc_GetCurThread()->ThreadName;
176 return Threads_GetThread(ID)->ThreadName;
180 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
181 * \brief Sets the priority of a task
182 * \param Thread Thread to update ticket count (NULL means current thread)
183 * \param Pri New priority
185 void Threads_SetPriority(tThread *Thread, int Pri)
187 // Get current thread
188 if(Thread == NULL) Thread = Proc_GetCurThread();
190 // - If < 0, set to lowest priority
191 // - Minumum priority is actualy a high number, 0 is highest
192 if(Pri < 0) Pri = MIN_PRIORITY;
193 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
195 // Do we actually have to do anything?
196 if( Pri == Thread->Priority ) return;
198 #if SCHEDULER_TYPE == SCHED_RR_PRI
199 SHORTLOCK( &glThreadListLock );
200 // Remove from old priority
201 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
203 Thread->Next = gaActiveThreads[Pri];
204 gaActiveThreads[Pri] = Thread;
205 Thread->Priority = Pri;
206 SHORTREL( &glThreadListLock );
208 // If this isn't the current thread, we need to lock
209 if( Thread != Proc_GetCurThread() )
211 SHORTLOCK( &glThreadListLock );
213 #if SCHEDULER_TYPE == SCHED_LOTTERY
214 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
215 # if DEBUG_TRACE_TICKETS
216 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
218 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
221 Thread->Priority = Pri;
222 SHORTREL( &glThreadListLock );
225 Thread->Priority = Pri;
228 #if DEBUG_TRACE_STATE
229 Log("Threads_SetPriority: %p(%i %s) pri set %i",
230 Thread, Thread->TID, Thread->ThreadName,
236 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
237 * \brief Clone the TCB of the current thread
238 * \param Err Error pointer
239 * \param Flags Flags for something... (What is this for?)
241 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
245 cur = Proc_GetCurThread();
247 // Allocate and duplicate
248 new = malloc(sizeof(tThread));
249 if(new == NULL) { *Err = -ENOMEM; return NULL; }
250 memcpy(new, cur, sizeof(tThread));
254 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
255 new->Status = THREAD_STAT_PREINIT;
259 new->TID = giNextTID++;
261 new->bInstrTrace = 0;
264 new->ThreadName = strdup(cur->ThreadName);
266 // Set Thread Group ID (PID)
268 new->TGID = new->TID;
270 new->TGID = cur->TGID;
272 // Messages are not inherited
273 new->Messages = NULL;
274 new->LastMessage = NULL;
277 new->Remaining = new->Quantum = cur->Quantum;
278 new->Priority = cur->Priority;
280 // Set Signal Handlers
281 new->CurFaultNum = 0;
282 new->FaultHandler = cur->FaultHandler;
284 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
286 switch(cCONFIG_TYPES[i])
289 new->Config[i] = cur->Config[i];
293 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
300 // Maintain a global list of threads
301 SHORTLOCK( &glThreadListLock );
302 new->GlobalPrev = NULL; // Protect against bugs
303 new->GlobalNext = gAllThreads;
304 gAllThreads->GlobalPrev = new;
306 SHORTREL( &glThreadListLock );
312 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
313 * \brief Clone the TCB of the current thread
315 tThread *Threads_CloneThreadZero(void)
319 cur = Proc_GetCurThread();
321 // Allocate and duplicate
322 new = malloc(sizeof(tThread));
326 memcpy(new, &gThreadZero, sizeof(tThread));
330 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
331 new->Status = THREAD_STAT_PREINIT;
335 new->TID = giNextTID++;
339 new->ThreadName = NULL;
341 // Messages are not inherited
342 new->Messages = NULL;
343 new->LastMessage = NULL;
346 new->Remaining = new->Quantum = cur->Quantum;
347 new->Priority = cur->Priority;
348 new->bInstrTrace = 0;
350 // Set Signal Handlers
351 new->CurFaultNum = 0;
352 new->FaultHandler = cur->FaultHandler;
354 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
356 switch(cCONFIG_TYPES[i])
359 new->Config[i] = cur->Config[i];
363 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
370 // Maintain a global list of threads
371 SHORTLOCK( &glThreadListLock );
372 new->GlobalPrev = NULL; // Protect against bugs
373 new->GlobalNext = gAllThreads;
374 gAllThreads->GlobalPrev = new;
376 SHORTREL( &glThreadListLock );
382 * \brief Get a configuration pointer from the Per-Thread data area
383 * \param ID Config slot ID
384 * \return Pointer at ID
386 Uint *Threads_GetCfgPtr(int ID)
388 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
389 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
393 return &Proc_GetCurThread()->Config[ID];
397 * \brief Wait for a task to change state
398 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
399 * \param Status Thread return status
400 * \return TID of child that changed state
402 tTID Threads_WaitTID(int TID, int *Status)
406 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
410 // Any peer/child thread
412 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
418 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
424 tThread *t = Threads_GetThread(TID);
425 int initStatus = t->Status;
428 // Wait for the thread to die!
429 if(initStatus != THREAD_STAT_ZOMBIE) {
430 // TODO: Handle child also being suspended if wanted
431 while(t->Status != THREAD_STAT_ZOMBIE) {
433 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
434 Threads_GetTID(), t->TID, t->Status);
439 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
440 Threads_GetTID(), t->TID, t->Status);
444 case THREAD_STAT_ZOMBIE:
446 t->Status = THREAD_STAT_DEAD;
447 // TODO: Child return value?
448 if(Status) *Status = t->RetStatus;
449 // add to delete queue
450 Threads_AddToDelete( t );
453 if(Status) *Status = -1;
463 * \brief Gets a thread given its TID
464 * \param TID Thread ID
465 * \return Thread pointer
467 tThread *Threads_GetThread(Uint TID)
471 // Search global list
472 for(thread = gAllThreads;
474 thread = thread->GlobalNext)
476 if(thread->TID == TID)
480 Log("Unable to find TID %i on main list\n", TID);
486 * \brief Adds a thread to the delete queue
487 * \param Thread Thread to delete
489 void Threads_AddToDelete(tThread *Thread)
491 // Add to delete queue
492 // TODO: Is locking needed?
494 Thread->Next = gDeleteThreads;
495 gDeleteThreads = Thread;
498 gDeleteThreads = Thread;
503 * \brief Deletes an entry from a list
504 * \param List Pointer to the list head
505 * \param Thread Thread to find
508 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
510 tThread *ret, *prev = NULL;
513 ret && ret != Thread;
514 prev = ret, ret = ret->Next
517 // Is the thread on the list
519 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
524 *List = Thread->Next;
525 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
528 prev->Next = Thread->Next;
529 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
536 * \brief Exit the current process (or another?)
537 * \param TID Thread ID to kill
538 * \param Status Exit status
540 void Threads_Exit(int TID, int Status)
543 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
545 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
547 // Halt forever, just in case
552 * \fn void Threads_Kill(tThread *Thread, int Status)
553 * \brief Kill a thread
554 * \param Thread Thread to kill
555 * \param Status Status code to return to the parent
557 void Threads_Kill(tThread *Thread, int Status)
560 int isCurThread = Thread == Proc_GetCurThread();
562 // TODO: Kill all children
566 // TODO: I should keep a .Parent pointer, and a .Children list
567 for(child = gAllThreads;
569 child = child->GlobalNext)
571 if(child->Parent == Thread)
572 Threads_Kill(child, -1);
577 ///\note Double lock is needed due to overlap of lock areas
579 // Lock thread (stop us recieving messages)
580 SHORTLOCK( &Thread->IsLocked );
582 // Clear Message Queue
583 while( Thread->Messages )
585 msg = Thread->Messages->Next;
586 free( Thread->Messages );
587 Thread->Messages = msg;
591 SHORTLOCK( &glThreadListLock );
593 switch(Thread->Status)
595 case THREAD_STAT_PREINIT: // Only on main list
598 // Currently active thread
599 case THREAD_STAT_ACTIVE:
600 #if SCHEDULER_TYPE == SCHED_RR_PRI
601 if( Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
603 if( Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
606 // Ensure that we are not rescheduled
607 Thread->Remaining = 0; // Clear Remaining Quantum
608 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
610 // Update bookkeeping
611 giNumActiveThreads --;
612 #if SCHEDULER_TYPE == SCHED_LOTTERY
613 if( Thread != Proc_GetCurThread() )
614 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
619 Log_Warning("Threads",
620 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
621 Thread, Thread->TID, Thread->ThreadName
625 // Kill it while it sleeps!
626 case THREAD_STAT_SLEEPING:
627 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
629 Log_Warning("Threads",
630 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
631 Thread, Thread->TID, Thread->ThreadName
636 // Brains!... You cannot kill
637 case THREAD_STAT_ZOMBIE:
638 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
639 Thread, Thread->TID, Thread->ThreadName);
640 SHORTREL( &glThreadListLock );
641 SHORTREL( &Thread->IsLocked );
645 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
651 Thread->RetStatus = Status;
653 // Don't Zombie if we are being killed because our parent is
656 Thread->Status = THREAD_STAT_DEAD;
657 Threads_AddToDelete( Thread );
659 Thread->Status = THREAD_STAT_ZOMBIE;
661 Threads_Wake( Thread->Parent );
664 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
667 SHORTREL( &glThreadListLock );
668 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
679 * \brief Yield remainder of the current thread's timeslice
681 void Threads_Yield(void)
687 * \fn void Threads_Sleep(void)
688 * \brief Take the current process off the run queue
690 void Threads_Sleep(void)
692 tThread *cur = Proc_GetCurThread();
695 SHORTLOCK( &glThreadListLock );
697 // Don't sleep if there is a message waiting
698 if( cur->Messages ) {
699 SHORTREL( &glThreadListLock );
703 // Remove us from running queue
705 // Mark thread as sleeping
706 cur->Status = THREAD_STAT_SLEEPING;
708 // Add to Sleeping List (at the top)
709 cur->Next = gSleepingThreads;
710 gSleepingThreads = cur;
713 #if DEBUG_TRACE_STATE
714 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
718 SHORTREL( &glThreadListLock );
720 while(cur->Status != THREAD_STAT_ACTIVE)
726 * \fn int Threads_Wake( tThread *Thread )
727 * \brief Wakes a sleeping/waiting thread up
728 * \param Thread Thread to wake
729 * \return Boolean Failure (Returns ERRNO)
730 * \warning This should ONLY be called with task switches disabled
732 int Threads_Wake(tThread *Thread)
737 switch(Thread->Status)
739 case THREAD_STAT_ACTIVE:
740 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
743 case THREAD_STAT_SLEEPING:
744 SHORTLOCK( &glThreadListLock );
745 // Remove from sleeping queue
746 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
748 Threads_AddActive( Thread );
750 #if DEBUG_TRACE_STATE
751 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
753 SHORTREL( &glThreadListLock );
756 case THREAD_STAT_SEMAPHORESLEEP: {
758 tThread *th, *prev=NULL;
760 sem = Thread->WaitPointer;
762 SHORTLOCK( &sem->Protector );
764 // Remove from sleeping queue
765 for( th = sem->Waiting; th; prev = th, th = th->Next )
766 if( th == Thread ) break;
770 prev->Next = Thread->Next;
772 sem->Waiting = Thread->Next;
773 if(sem->LastWaiting == Thread)
774 sem->LastWaiting = prev;
779 for( th = sem->Signaling; th; prev = th, th = th->Next )
780 if( th == Thread ) break;
782 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
783 Thread, Thread->TID, Thread->ThreadName,
784 sem, sem->ModName, sem->Name);
789 prev->Next = Thread->Next;
791 sem->Signaling = Thread->Next;
792 if(sem->LastSignaling == Thread)
793 sem->LastSignaling = prev;
796 SHORTLOCK( &glThreadListLock );
797 Threads_AddActive( Thread );
798 SHORTREL( &glThreadListLock );
800 #if DEBUG_TRACE_STATE
801 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
803 SHORTREL( &sem->Protector );
806 case THREAD_STAT_WAITING:
807 Warning("Threads_Wake - Waiting threads are not currently supported");
810 case THREAD_STAT_DEAD:
811 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
815 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
821 * \brief Wake a thread given the TID
822 * \param TID Thread ID to wake
823 * \return Boolean Faulure (errno)
825 int Threads_WakeTID(tTID TID)
827 tThread *thread = Threads_GetThread(TID);
831 ret = Threads_Wake( thread );
832 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
836 void Threads_ToggleTrace(int TID)
838 tThread *thread = Threads_GetThread(TID);
840 thread->bInstrTrace = !thread->bInstrTrace;
844 * \brief Adds a thread to the active queue
846 void Threads_AddActive(tThread *Thread)
848 SHORTLOCK( &glThreadListLock );
850 if( Thread->Status == THREAD_STAT_ACTIVE ) {
851 tThread *cur = Proc_GetCurThread();
852 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
853 __builtin_return_address(0),
854 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
855 SHORTREL( &glThreadListLock );
860 Thread->Status = THREAD_STAT_ACTIVE;
861 // Thread->CurCPU = -1;
862 // Add to active list
864 tThread *tmp, *prev = NULL;
865 #if SCHEDULER_TYPE == SCHED_RR_PRI
866 for( tmp = gaActiveThreads[Thread->Priority]; tmp; prev = tmp, tmp = tmp->Next );
870 gaActiveThreads[Thread->Priority] = Thread;
872 for( tmp = gActiveThreads; tmp; prev = tmp, tmp = tmp->Next );
876 gActiveThreads = Thread;
881 // Update bookkeeping
882 giNumActiveThreads ++;
884 #if SCHEDULER_TYPE == SCHED_LOTTERY
887 // Only change the ticket count if the thread is un-scheduled
888 if(Thread->CurCPU != -1)
891 delta = caiTICKET_COUNTS[ Thread->Priority ];
893 giFreeTickets += delta;
894 # if DEBUG_TRACE_TICKETS
895 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
896 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
903 SHORTREL( &glThreadListLock );
907 * \brief Removes the current thread from the active queue
908 * \warning This should ONLY be called with the lock held
909 * \return Current thread pointer
911 tThread *Threads_RemActive(void)
913 tThread *ret = Proc_GetCurThread();
915 if( !IS_LOCKED(&glThreadListLock) ) {
916 Log_KernelPanic("Threads", "Threads_RemActive called without lock held");
920 // Delete from active queue
921 #if SCHEDULER_TYPE == SCHED_RR_PRI
922 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
924 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
927 SHORTREL( &glThreadListLock );
928 Log_Warning("Threads", "Current thread %p(%i %s) is not on active queue",
929 ret, ret->TID, ret->ThreadName
937 giNumActiveThreads --;
938 // no need to decrement tickets, scheduler did it for us
940 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
941 Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
942 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
949 * \fn void Threads_SetFaultHandler(Uint Handler)
950 * \brief Sets the signal handler for a signal
952 void Threads_SetFaultHandler(Uint Handler)
954 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
955 Proc_GetCurThread()->FaultHandler = Handler;
959 * \fn void Threads_Fault(int Num)
960 * \brief Calls a fault handler
962 void Threads_Fault(int Num)
964 tThread *thread = Proc_GetCurThread();
968 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
970 switch(thread->FaultHandler)
973 Threads_Kill(thread, -1);
976 case 1: // Dump Core?
977 Threads_Kill(thread, -1);
982 // Double Fault? Oh, F**k
983 if(thread->CurFaultNum != 0) {
984 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
985 Threads_Kill(thread, -1); // For now, just kill
989 thread->CurFaultNum = Num;
991 Proc_CallFaultHandler(thread);
995 * \fn void Threads_SegFault(tVAddr Addr)
996 * \brief Called when a Segment Fault occurs
998 void Threads_SegFault(tVAddr Addr)
1000 tThread *cur = Proc_GetCurThread();
1001 cur->bInstrTrace = 0;
1002 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
1003 MM_DumpTables(0, USER_MAX);
1005 //Threads_Exit( 0, -1 );
1008 // --- Process Structure Access Functions ---
1009 tPID Threads_GetPID(void)
1011 return Proc_GetCurThread()->TGID;
1013 tTID Threads_GetTID(void)
1015 return Proc_GetCurThread()->TID;
1017 tUID Threads_GetUID(void)
1019 return Proc_GetCurThread()->UID;
1021 tGID Threads_GetGID(void)
1023 return Proc_GetCurThread()->GID;
1026 int Threads_SetUID(Uint *Errno, tUID ID)
1028 tThread *t = Proc_GetCurThread();
1033 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
1038 int Threads_SetGID(Uint *Errno, tGID ID)
1040 tThread *t = Proc_GetCurThread();
1045 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
1051 * \fn void Threads_Dump(void)
1053 void Threads_DumpActive(void)
1056 #if SCHEDULER_TYPE == SCHED_RR_PRI
1060 Log("Active Threads: (%i reported)", giNumActiveThreads);
1062 #if SCHEDULER_TYPE == SCHED_RR_PRI
1063 for( i = 0; i < MIN_PRIORITY+1; i++ )
1065 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
1067 for(thread=gActiveThreads;thread;thread=thread->Next)
1070 Log(" %p %i (%i) - %s (CPU %i)",
1071 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1072 if(thread->Status != THREAD_STAT_ACTIVE)
1073 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
1074 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1075 Log(" KStack 0x%x", thread->KernelStack);
1076 if( thread->bInstrTrace )
1077 Log(" Tracing Enabled");
1078 Proc_DumpThreadCPUState(thread);
1081 #if SCHEDULER_TYPE == SCHED_RR_PRI
1087 * \fn void Threads_Dump(void)
1088 * \brief Dumps a list of currently running threads
1090 void Threads_Dump(void)
1094 Log("--- Thread Dump ---");
1095 Threads_DumpActive();
1097 Log("All Threads:");
1098 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1100 Log(" %p %i (%i) - %s (CPU %i)",
1101 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1102 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1103 switch(thread->Status)
1105 case THREAD_STAT_MUTEXSLEEP:
1106 Log(" Mutex Pointer: %p", thread->WaitPointer);
1108 case THREAD_STAT_SEMAPHORESLEEP:
1109 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1110 Log(" Semaphore Name: %s:%s",
1111 ((tSemaphore*)thread->WaitPointer)->ModName,
1112 ((tSemaphore*)thread->WaitPointer)->Name
1115 case THREAD_STAT_ZOMBIE:
1116 Log(" Return Status: %i", thread->RetStatus);
1120 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1121 Log(" KStack 0x%x", thread->KernelStack);
1122 if( thread->bInstrTrace )
1123 Log(" Tracing Enabled");
1124 Proc_DumpThreadCPUState(thread);
1129 * \brief Gets the next thread to run
1130 * \param CPU Current CPU
1131 * \param Last The thread the CPU was running
1133 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1137 // If this CPU has the lock, we must let it complete
1138 if( CPU_HAS_LOCK( &glThreadListLock ) )
1141 // Don't change threads if the current CPU has switches disabled
1142 if( gaThreads_NoTaskSwitch[CPU] )
1146 SHORTLOCK( &glThreadListLock );
1148 // Clear Delete Queue
1149 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
1150 // DEFINITELY - free() can deadlock in this case
1151 // I'll do it when it becomes an issue
1152 while(gDeleteThreads)
1154 thread = gDeleteThreads->Next;
1155 // Only free if structure is unused
1156 if( !IS_LOCKED(&gDeleteThreads->IsLocked) )
1159 gDeleteThreads->Status = THREAD_STAT_BURIED;
1161 if( IsHeap(gDeleteThreads->ThreadName) )
1162 free(gDeleteThreads->ThreadName);
1163 // Remove from global list
1164 if( gDeleteThreads == gAllThreads )
1165 gAllThreads = gDeleteThreads->GlobalNext;
1167 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
1168 free( gDeleteThreads );
1170 gDeleteThreads = thread;
1173 // Make sure the current (well, old) thread is marked as de-scheduled
1174 if(Last) Last->CurCPU = -1;
1176 // No active threads, just take a nap
1177 if(giNumActiveThreads == 0) {
1178 SHORTREL( &glThreadListLock );
1179 #if DEBUG_TRACE_TICKETS
1180 Log("No active threads");
1185 #if SCHEDULER_TYPE != SCHED_RR_PRI
1186 // Special case: 1 thread
1187 if(giNumActiveThreads == 1) {
1188 if( gActiveThreads->CurCPU == -1 )
1189 gActiveThreads->CurCPU = CPU;
1191 SHORTREL( &glThreadListLock );
1193 if( gActiveThreads->CurCPU == CPU )
1194 return gActiveThreads;
1196 return NULL; // CPU has nothing to do
1200 // Allow the old thread to be scheduled again
1202 if( Last->Status == THREAD_STAT_ACTIVE ) {
1203 #if SCHEDULER_TYPE == SCHED_LOTTERY
1204 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1205 # if DEBUG_TRACE_TICKETS
1206 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1207 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1208 caiTICKET_COUNTS[ Last->Priority ]);
1212 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1214 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1215 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1221 // Lottery Scheduler
1223 #if SCHEDULER_TYPE == SCHED_LOTTERY
1228 for(thread = gActiveThreads; thread; thread = thread->Next) {
1229 if(thread->CurCPU >= 0) continue;
1230 if(thread->Status != THREAD_STAT_ACTIVE)
1231 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1232 thread, thread->TID, thread->ThreadName, thread->Status);
1233 if(thread->Next == thread) {
1234 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1235 thread, thread->TID, thread->ThreadName, thread->Status);
1237 number += caiTICKET_COUNTS[ thread->Priority ];
1239 if(number != giFreeTickets) {
1240 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1241 giFreeTickets, number, CPU);
1245 // No free tickets (all tasks delegated to cores)
1246 if( giFreeTickets == 0 ) {
1247 SHORTREL(&glThreadListLock);
1251 // Get the ticket number
1252 ticket = number = rand() % giFreeTickets;
1254 // Find the next thread
1255 for(thread=gActiveThreads;thread;thread=thread->Next)
1257 if(thread->CurCPU >= 0) continue;
1258 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1259 number -= caiTICKET_COUNTS[ thread->Priority ];
1262 // If we didn't find a thread, something went wrong
1266 for(thread=gActiveThreads;thread;thread=thread->Next) {
1267 if(thread->CurCPU >= 0) continue;
1268 number += caiTICKET_COUNTS[ thread->Priority ];
1270 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1271 giFreeTickets, number);
1274 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1275 # if DEBUG_TRACE_TICKETS
1276 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1277 CPU, thread, thread->TID, thread->ThreadName,
1278 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1283 // Priority based round robin scheduler
1285 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1288 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1290 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1292 if( thread->CurCPU == -1 ) break;
1294 // If we fall onto the same queue again, special handling is
1296 if( Last && Last->Status == THREAD_STAT_ACTIVE && i == Last->Priority ) {
1297 tThread *savedThread = thread;
1299 // Find the next unscheduled thread in the list
1300 for( thread = Last->Next; thread; thread = thread->Next )
1302 if( thread->CurCPU == -1 ) break;
1304 // If we don't find anything after, just use the one
1306 if( !thread ) thread = savedThread;
1308 // Found a thread? Schedule it!
1314 SHORTREL(&glThreadListLock);
1317 if( thread->Status != THREAD_STAT_ACTIVE ) {
1318 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1321 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1323 // Find the next unscheduled thread in the list
1324 for( thread = Last->Next; thread; thread = thread->Next )
1326 if( thread->CurCPU == -1 ) break;
1328 // If we don't find anything after, search from the beginning
1331 for(thread = gActiveThreads; thread; thread = thread->Next)
1333 if( thread->CurCPU == -1 ) break;
1339 SHORTREL(&glThreadListLock);
1344 # error "Unimplemented scheduling algorithm"
1347 // Make the new thread non-schedulable
1348 thread->CurCPU = CPU;
1349 thread->Remaining = thread->Quantum;
1351 SHORTREL( &glThreadListLock );
1356 // Acquire mutex (see mutex.h for documentation)
1357 int Mutex_Acquire(tMutex *Mutex)
1359 tThread *us = Proc_GetCurThread();
1362 SHORTLOCK( &Mutex->Protector );
1364 //Log("Mutex_Acquire: (%p)", Mutex);
1366 // Check if the lock is already held
1367 if( Mutex->Owner ) {
1368 SHORTLOCK( &glThreadListLock );
1369 // - Remove from active list
1370 us = Threads_RemActive();
1372 // - Mark as sleeping
1373 us->Status = THREAD_STAT_MUTEXSLEEP;
1374 us->WaitPointer = Mutex;
1377 if(Mutex->LastWaiting) {
1378 Mutex->LastWaiting->Next = us;
1379 Mutex->LastWaiting = us;
1382 Mutex->Waiting = us;
1383 Mutex->LastWaiting = us;
1386 #if DEBUG_TRACE_STATE
1387 Log("%p (%i %s) waiting on mutex %p",
1388 us, us->TID, us->ThreadName, Mutex);
1395 for( t = Mutex->Waiting; t; t = t->Next, i++ )
1396 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1397 t, t->TID, t->ThreadName);
1401 SHORTREL( &glThreadListLock );
1402 SHORTREL( &Mutex->Protector );
1403 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1404 // We're only woken when we get the lock
1405 us->WaitPointer = NULL;
1407 // Ooh, let's take it!
1410 SHORTREL( &Mutex->Protector );
1414 extern tMutex glPhysAlloc;
1415 if( Mutex != &glPhysAlloc )
1416 LogF("Mutex %p taken by %i %p\n", Mutex, us->TID, __builtin_return_address(0));
1423 void Mutex_Release(tMutex *Mutex)
1425 SHORTLOCK( &Mutex->Protector );
1426 //Log("Mutex_Release: (%p)", Mutex);
1427 if( Mutex->Waiting ) {
1428 Mutex->Owner = Mutex->Waiting; // Set owner
1429 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1430 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1431 // 2010-10-02 21:50 - Comemerating the death of the longest single
1432 // blocker in the Acess2 history. REMEMBER TO
1433 // FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1434 if( Mutex->LastWaiting == Mutex->Owner )
1435 Mutex->LastWaiting = NULL;
1438 SHORTLOCK( &glThreadListLock );
1439 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1440 Threads_AddActive(Mutex->Owner);
1441 SHORTREL( &glThreadListLock );
1444 Mutex->Owner = NULL;
1446 SHORTREL( &Mutex->Protector );
1449 extern tMutex glPhysAlloc;
1450 if( Mutex != &glPhysAlloc )
1451 LogF("Mutex %p released by %i %p\n", Mutex, Threads_GetTID(), __builtin_return_address(0));
1455 // Check if a mutex is locked
1456 int Mutex_IsLocked(tMutex *Mutex)
1458 return Mutex->Owner != NULL;
1462 // Initialise a semaphore
1464 void Semaphore_Init(tSemaphore *Sem, int Value, int MaxValue, const char *Module, const char *Name)
1466 memset(Sem, 0, sizeof(tSemaphore));
1468 Sem->ModName = Module;
1470 Sem->MaxValue = MaxValue;
1473 // Wait for items to be avaliable
1475 int Semaphore_Wait(tSemaphore *Sem, int MaxToTake)
1479 if( MaxToTake < 0 ) {
1480 Log_Warning("Threads", "Semaphore_Wait: User bug - MaxToTake(%i) < 0, Sem=%p(%s)",
1481 MaxToTake, Sem, Sem->Name);
1484 SHORTLOCK( &Sem->Protector );
1486 // Check if there's already items avaliable
1487 if( Sem->Value > 0 ) {
1488 // Take what we need
1489 if( MaxToTake && Sem->Value > MaxToTake )
1493 Sem->Value -= taken;
1497 SHORTLOCK( &glThreadListLock );
1499 // - Remove from active list
1500 us = Threads_RemActive();
1502 // - Mark as sleeping
1503 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1504 us->WaitPointer = Sem;
1505 us->RetStatus = MaxToTake; // Use RetStatus as a temp variable
1508 if(Sem->LastWaiting) {
1509 Sem->LastWaiting->Next = us;
1510 Sem->LastWaiting = us;
1514 Sem->LastWaiting = us;
1517 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1518 Log("%p (%i %s) waiting on semaphore %p %s:%s",
1519 us, us->TID, us->ThreadName,
1520 Sem, Sem->ModName, Sem->Name);
1523 SHORTREL( &Sem->Protector ); // Release first to make sure it is released
1524 SHORTREL( &glThreadListLock );
1525 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1526 // We're only woken when there's something avaliable (or a signal arrives)
1527 us->WaitPointer = NULL;
1529 taken = us->RetStatus;
1531 // Get the lock again
1532 SHORTLOCK( &Sem->Protector );
1535 // While there is space, and there are thread waiting
1536 // wake the first thread and give it what it wants (or what's left)
1537 while( (Sem->MaxValue == 0 || Sem->Value < Sem->MaxValue) && Sem->Signaling )
1540 tThread *toWake = Sem->Signaling;
1542 Sem->Signaling = Sem->Signaling->Next;
1543 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1544 if( Sem->Signaling == NULL )
1545 Sem->LastSignaling = NULL;
1547 // Figure out how much to give
1548 if( toWake->RetStatus && Sem->Value + toWake->RetStatus < Sem->MaxValue )
1549 given = toWake->RetStatus;
1551 given = Sem->MaxValue - Sem->Value;
1552 Sem->Value -= given;
1555 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1556 Log("%p (%i %s) woken by wait on %p %s:%s",
1557 toWake, toWake->TID, toWake->ThreadName,
1558 Sem, Sem->ModName, Sem->Name);
1561 // Save the number we gave to the thread's status
1562 toWake->RetStatus = given;
1565 SHORTLOCK( &glThreadListLock );
1566 if( toWake->Status != THREAD_STAT_ACTIVE )
1567 Threads_AddActive(toWake);
1568 SHORTREL( &glThreadListLock );
1570 SHORTREL( &Sem->Protector );
1576 // Add items to a semaphore
1578 int Semaphore_Signal(tSemaphore *Sem, int AmmountToAdd)
1583 if( AmmountToAdd < 0 ) {
1584 Log_Warning("Threads", "Semaphore_Signal: User bug - AmmountToAdd(%i) < 0, Sem=%p(%s)",
1585 AmmountToAdd, Sem, Sem->Name);
1587 SHORTLOCK( &Sem->Protector );
1589 // Check if we have to block
1590 if( Sem->MaxValue && Sem->Value == Sem->MaxValue )
1594 Log_Debug("Threads", "Semaphore_Signal: IDLE Sem = %s:%s", Sem->ModName, Sem->Name);
1595 Log_Debug("Threads", "Semaphore_Signal: Sem->Value(%i) == Sem->MaxValue(%i)", Sem->Value, Sem->MaxValue);
1598 SHORTLOCK( &glThreadListLock );
1599 // - Remove from active list
1600 us = Threads_RemActive();
1602 // - Mark as sleeping
1603 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1604 us->WaitPointer = Sem;
1605 us->RetStatus = AmmountToAdd; // Use RetStatus as a temp variable
1608 if(Sem->LastSignaling) {
1609 Sem->LastSignaling->Next = us;
1610 Sem->LastSignaling = us;
1613 Sem->Signaling = us;
1614 Sem->LastSignaling = us;
1617 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1618 Log("%p (%i %s) signaling semaphore %p %s:%s",
1619 us, us->TID, us->ThreadName,
1620 Sem, Sem->ModName, Sem->Name);
1623 SHORTREL( &glThreadListLock );
1624 SHORTREL( &Sem->Protector );
1625 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1626 // We're only woken when there's something avaliable
1627 us->WaitPointer = NULL;
1629 added = us->RetStatus;
1631 // Get the lock again
1632 SHORTLOCK( &Sem->Protector );
1637 // Figure out how much we need to take off
1638 if( Sem->MaxValue && Sem->Value + AmmountToAdd > Sem->MaxValue)
1639 added = Sem->MaxValue - Sem->Value;
1641 added = AmmountToAdd;
1642 Sem->Value += added;
1645 // While there are items avaliable, and there are thread waiting
1646 // wake the first thread and give it what it wants (or what's left)
1647 while( Sem->Value && Sem->Waiting )
1649 tThread *toWake = Sem->Waiting;
1651 // Remove thread from list (double ended, so clear LastWaiting if needed)
1652 Sem->Waiting = Sem->Waiting->Next;
1653 if( Sem->Waiting == NULL )
1654 Sem->LastWaiting = NULL;
1656 // Figure out how much to give to woken thread
1657 // - Requested count is stored in ->RetStatus
1658 if( toWake->RetStatus && Sem->Value > toWake->RetStatus )
1659 given = toWake->RetStatus;
1662 Sem->Value -= given;
1664 // Save the number we gave to the thread's status
1665 toWake->RetStatus = given;
1667 if(toWake->bInstrTrace)
1668 Log("%s(%i) given %i from %p", toWake->ThreadName, toWake->TID, given, Sem);
1669 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1670 Log("%p (%i %s) woken by signal on %p %s:%s",
1671 toWake, toWake->TID, toWake->ThreadName,
1672 Sem, Sem->ModName, Sem->Name);
1676 SHORTLOCK( &glThreadListLock );
1677 if( toWake->Status != THREAD_STAT_ACTIVE )
1678 Threads_AddActive(toWake);
1680 Warning("Thread %p (%i %s) is already awake", toWake, toWake->TID, toWake->ThreadName);
1681 SHORTREL( &glThreadListLock );
1683 SHORTREL( &Sem->Protector );
1689 // Get the current value of a semaphore
1691 int Semaphore_GetValue(tSemaphore *Sem)
1697 EXPORT(Threads_GetUID);
1698 EXPORT(Threads_GetGID);
1699 EXPORT(Mutex_Acquire);
1700 EXPORT(Mutex_Release);
1701 EXPORT(Mutex_IsLocked);
1702 EXPORT(Semaphore_Init);
1703 EXPORT(Semaphore_Wait);
1704 EXPORT(Semaphore_Signal);