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 * \brief Clone the TCB of the current thread
237 * \param Flags Flags for something... (What is this for?)
239 tThread *Threads_CloneTCB(Uint Flags)
243 cur = Proc_GetCurThread();
245 // Allocate and duplicate
246 new = malloc(sizeof(tThread));
247 if(new == NULL) { errno = -ENOMEM; return NULL; }
248 memcpy(new, cur, sizeof(tThread));
252 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
253 new->Status = THREAD_STAT_PREINIT;
257 new->TID = giNextTID++;
259 new->bInstrTrace = 0;
262 new->ThreadName = strdup(cur->ThreadName);
264 // Set Thread Group ID (PID)
266 new->TGID = new->TID;
268 new->TGID = cur->TGID;
270 // Messages are not inherited
271 new->Messages = NULL;
272 new->LastMessage = NULL;
275 new->Remaining = new->Quantum = cur->Quantum;
276 new->Priority = cur->Priority;
278 // Set Signal Handlers
279 new->CurFaultNum = 0;
280 new->FaultHandler = cur->FaultHandler;
282 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
284 switch(cCONFIG_TYPES[i])
287 new->Config[i] = cur->Config[i];
291 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
298 // Maintain a global list of threads
299 SHORTLOCK( &glThreadListLock );
300 new->GlobalPrev = NULL; // Protect against bugs
301 new->GlobalNext = gAllThreads;
302 gAllThreads->GlobalPrev = new;
304 SHORTREL( &glThreadListLock );
310 * \brief Clone the TCB of the kernel thread
312 tThread *Threads_CloneThreadZero(void)
317 // Allocate and duplicate
318 new = malloc(sizeof(tThread));
322 memcpy(new, &gThreadZero, sizeof(tThread));
326 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
327 new->Status = THREAD_STAT_PREINIT;
331 new->TID = giNextTID++;
335 new->ThreadName = NULL;
337 // Messages are not inherited
338 new->Messages = NULL;
339 new->LastMessage = NULL;
342 new->Remaining = new->Quantum = DEFAULT_QUANTUM;
343 new->Priority = DEFAULT_PRIORITY;
344 new->bInstrTrace = 0;
346 // Set Signal Handlers
347 new->CurFaultNum = 0;
348 new->FaultHandler = 0;
350 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
355 // Maintain a global list of threads
356 SHORTLOCK( &glThreadListLock );
357 new->GlobalPrev = NULL; // Protect against bugs
358 new->GlobalNext = gAllThreads;
359 gAllThreads->GlobalPrev = new;
361 SHORTREL( &glThreadListLock );
367 * \brief Get a configuration pointer from the Per-Thread data area
368 * \param ID Config slot ID
369 * \return Pointer at ID
371 Uint *Threads_GetCfgPtr(int ID)
373 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
374 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
378 return &Proc_GetCurThread()->Config[ID];
382 * \brief Wait for a task to change state
383 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
384 * \param Status Thread return status
385 * \return TID of child that changed state
387 tTID Threads_WaitTID(int TID, int *Status)
391 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
395 // Any peer/child thread
397 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
403 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
409 tThread *t = Threads_GetThread(TID);
410 int initStatus = t->Status;
413 // Wait for the thread to die!
414 if(initStatus != THREAD_STAT_ZOMBIE) {
415 // TODO: Handle child also being suspended if wanted
416 while(t->Status != THREAD_STAT_ZOMBIE) {
418 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
419 Threads_GetTID(), t->TID, t->Status);
424 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
425 Threads_GetTID(), t->TID, t->Status);
429 case THREAD_STAT_ZOMBIE:
431 t->Status = THREAD_STAT_DEAD;
432 // TODO: Child return value?
433 if(Status) *Status = t->RetStatus;
434 // add to delete queue
435 Threads_AddToDelete( t );
438 if(Status) *Status = -1;
448 * \brief Gets a thread given its TID
449 * \param TID Thread ID
450 * \return Thread pointer
452 tThread *Threads_GetThread(Uint TID)
456 // Search global list
457 for(thread = gAllThreads;
459 thread = thread->GlobalNext)
461 if(thread->TID == TID)
465 Log("Unable to find TID %i on main list\n", TID);
471 * \brief Adds a thread to the delete queue
472 * \param Thread Thread to delete
474 void Threads_AddToDelete(tThread *Thread)
476 // Add to delete queue
477 // TODO: Is locking needed?
479 Thread->Next = gDeleteThreads;
480 gDeleteThreads = Thread;
483 gDeleteThreads = Thread;
488 * \brief Deletes an entry from a list
489 * \param List Pointer to the list head
490 * \param Thread Thread to find
493 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
495 tThread *ret, *prev = NULL;
498 ret && ret != Thread;
499 prev = ret, ret = ret->Next
502 // Is the thread on the list
504 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
509 *List = Thread->Next;
510 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
513 prev->Next = Thread->Next;
514 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
521 * \brief Exit the current process (or another?)
522 * \param TID Thread ID to kill
523 * \param Status Exit status
525 void Threads_Exit(int TID, int Status)
528 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
530 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
532 // Halt forever, just in case
537 * \fn void Threads_Kill(tThread *Thread, int Status)
538 * \brief Kill a thread
539 * \param Thread Thread to kill
540 * \param Status Status code to return to the parent
542 void Threads_Kill(tThread *Thread, int Status)
545 int isCurThread = Thread == Proc_GetCurThread();
547 // TODO: Kill all children
551 // TODO: I should keep a .Parent pointer, and a .Children list
552 for(child = gAllThreads;
554 child = child->GlobalNext)
556 if(child->Parent == Thread)
557 Threads_Kill(child, -1);
562 ///\note Double lock is needed due to overlap of lock areas
564 // Lock thread (stop us recieving messages)
565 SHORTLOCK( &Thread->IsLocked );
567 // Clear Message Queue
568 while( Thread->Messages )
570 msg = Thread->Messages->Next;
571 free( Thread->Messages );
572 Thread->Messages = msg;
576 SHORTLOCK( &glThreadListLock );
578 switch(Thread->Status)
580 case THREAD_STAT_PREINIT: // Only on main list
583 // Currently active thread
584 case THREAD_STAT_ACTIVE:
585 #if SCHEDULER_TYPE == SCHED_RR_PRI
586 if( Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
588 if( Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
591 // Ensure that we are not rescheduled
592 Thread->Remaining = 0; // Clear Remaining Quantum
593 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
595 // Update bookkeeping
596 giNumActiveThreads --;
597 #if SCHEDULER_TYPE == SCHED_LOTTERY
598 if( Thread != Proc_GetCurThread() )
599 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
604 Log_Warning("Threads",
605 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
606 Thread, Thread->TID, Thread->ThreadName
610 // Kill it while it sleeps!
611 case THREAD_STAT_SLEEPING:
612 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
614 Log_Warning("Threads",
615 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
616 Thread, Thread->TID, Thread->ThreadName
621 // Brains!... You cannot kill
622 case THREAD_STAT_ZOMBIE:
623 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
624 Thread, Thread->TID, Thread->ThreadName);
625 SHORTREL( &glThreadListLock );
626 SHORTREL( &Thread->IsLocked );
630 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
636 Thread->RetStatus = Status;
638 // Don't Zombie if we are being killed because our parent is
641 Thread->Status = THREAD_STAT_DEAD;
642 Threads_AddToDelete( Thread );
644 Thread->Status = THREAD_STAT_ZOMBIE;
646 Threads_Wake( Thread->Parent );
649 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
652 SHORTREL( &glThreadListLock );
653 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
664 * \brief Yield remainder of the current thread's timeslice
666 void Threads_Yield(void)
668 // Log("Threads_Yield: by %p", __builtin_return_address(0));
673 * \fn void Threads_Sleep(void)
674 * \brief Take the current process off the run queue
676 void Threads_Sleep(void)
678 tThread *cur = Proc_GetCurThread();
681 SHORTLOCK( &glThreadListLock );
683 // Don't sleep if there is a message waiting
684 if( cur->Messages ) {
685 SHORTREL( &glThreadListLock );
689 // Remove us from running queue
691 // Mark thread as sleeping
692 cur->Status = THREAD_STAT_SLEEPING;
694 // Add to Sleeping List (at the top)
695 cur->Next = gSleepingThreads;
696 gSleepingThreads = cur;
699 #if DEBUG_TRACE_STATE
700 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
704 SHORTREL( &glThreadListLock );
706 while(cur->Status != THREAD_STAT_ACTIVE) {
708 if( cur->Status != THREAD_STAT_ACTIVE )
709 Log("%i - Huh? why am I up? zzzz...", cur->TID);
715 * \fn int Threads_Wake( tThread *Thread )
716 * \brief Wakes a sleeping/waiting thread up
717 * \param Thread Thread to wake
718 * \return Boolean Failure (Returns ERRNO)
719 * \warning This should ONLY be called with task switches disabled
721 int Threads_Wake(tThread *Thread)
726 switch(Thread->Status)
728 case THREAD_STAT_ACTIVE:
729 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
732 case THREAD_STAT_SLEEPING:
733 SHORTLOCK( &glThreadListLock );
734 // Remove from sleeping queue
735 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
737 Threads_AddActive( Thread );
739 #if DEBUG_TRACE_STATE
740 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
742 SHORTREL( &glThreadListLock );
745 case THREAD_STAT_SEMAPHORESLEEP: {
747 tThread *th, *prev=NULL;
749 sem = Thread->WaitPointer;
751 SHORTLOCK( &sem->Protector );
753 // Remove from sleeping queue
754 for( th = sem->Waiting; th; prev = th, th = th->Next )
755 if( th == Thread ) break;
759 prev->Next = Thread->Next;
761 sem->Waiting = Thread->Next;
762 if(sem->LastWaiting == Thread)
763 sem->LastWaiting = prev;
768 for( th = sem->Signaling; th; prev = th, th = th->Next )
769 if( th == Thread ) break;
771 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
772 Thread, Thread->TID, Thread->ThreadName,
773 sem, sem->ModName, sem->Name);
778 prev->Next = Thread->Next;
780 sem->Signaling = Thread->Next;
781 if(sem->LastSignaling == Thread)
782 sem->LastSignaling = prev;
785 SHORTLOCK( &glThreadListLock );
786 Threads_AddActive( Thread );
787 SHORTREL( &glThreadListLock );
789 #if DEBUG_TRACE_STATE
790 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
792 SHORTREL( &sem->Protector );
795 case THREAD_STAT_WAITING:
796 Warning("Threads_Wake - Waiting threads are not currently supported");
799 case THREAD_STAT_DEAD:
800 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
804 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
810 * \brief Wake a thread given the TID
811 * \param TID Thread ID to wake
812 * \return Boolean Faulure (errno)
814 int Threads_WakeTID(tTID TID)
816 tThread *thread = Threads_GetThread(TID);
820 ret = Threads_Wake( thread );
821 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
825 void Threads_ToggleTrace(int TID)
827 tThread *thread = Threads_GetThread(TID);
829 thread->bInstrTrace = !thread->bInstrTrace;
833 * \brief Adds a thread to the active queue
835 void Threads_AddActive(tThread *Thread)
837 SHORTLOCK( &glThreadListLock );
839 if( Thread->Status == THREAD_STAT_ACTIVE ) {
840 tThread *cur = Proc_GetCurThread();
841 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
842 __builtin_return_address(0),
843 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
844 SHORTREL( &glThreadListLock );
849 Thread->Status = THREAD_STAT_ACTIVE;
850 // Thread->CurCPU = -1;
851 // Add to active list
853 tThread *tmp, *prev = NULL;
854 #if SCHEDULER_TYPE == SCHED_RR_PRI
855 for( tmp = gaActiveThreads[Thread->Priority]; tmp; prev = tmp, tmp = tmp->Next );
859 gaActiveThreads[Thread->Priority] = Thread;
861 for( tmp = gActiveThreads; tmp; prev = tmp, tmp = tmp->Next );
865 gActiveThreads = 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)
902 tThread *ret = Proc_GetCurThread();
904 if( !IS_LOCKED(&glThreadListLock) ) {
905 Log_KernelPanic("Threads", "Threads_RemActive called without lock held");
909 // Delete from active queue
910 #if SCHEDULER_TYPE == SCHED_RR_PRI
911 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
913 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
916 SHORTREL( &glThreadListLock );
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);
938 * \fn void Threads_SetFaultHandler(Uint Handler)
939 * \brief Sets the signal handler for a signal
941 void Threads_SetFaultHandler(Uint Handler)
943 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
944 Proc_GetCurThread()->FaultHandler = Handler;
948 * \fn void Threads_Fault(int Num)
949 * \brief Calls a fault handler
951 void Threads_Fault(int Num)
953 tThread *thread = Proc_GetCurThread();
957 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
959 switch(thread->FaultHandler)
962 Threads_Kill(thread, -1);
965 case 1: // Dump Core?
966 Threads_Kill(thread, -1);
971 // Double Fault? Oh, F**k
972 if(thread->CurFaultNum != 0) {
973 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
974 Threads_Kill(thread, -1); // For now, just kill
978 thread->CurFaultNum = Num;
980 Proc_CallFaultHandler(thread);
984 * \fn void Threads_SegFault(tVAddr Addr)
985 * \brief Called when a Segment Fault occurs
987 void Threads_SegFault(tVAddr Addr)
989 tThread *cur = Proc_GetCurThread();
990 cur->bInstrTrace = 0;
991 Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
992 MM_DumpTables(0, USER_MAX);
994 //Threads_Exit( 0, -1 );
997 // --- Process Structure Access Functions ---
998 tPID Threads_GetPID(void)
1000 return Proc_GetCurThread()->TGID;
1002 tTID Threads_GetTID(void)
1004 return Proc_GetCurThread()->TID;
1006 tUID Threads_GetUID(void)
1008 return Proc_GetCurThread()->UID;
1010 tGID Threads_GetGID(void)
1012 return Proc_GetCurThread()->GID;
1015 int Threads_SetUID(Uint *Errno, tUID ID)
1017 tThread *t = Proc_GetCurThread();
1022 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
1027 int Threads_SetGID(Uint *Errno, tGID ID)
1029 tThread *t = Proc_GetCurThread();
1034 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
1040 * \fn void Threads_Dump(void)
1042 void Threads_DumpActive(void)
1045 #if SCHEDULER_TYPE == SCHED_RR_PRI
1049 Log("Active Threads: (%i reported)", giNumActiveThreads);
1051 #if SCHEDULER_TYPE == SCHED_RR_PRI
1052 for( i = 0; i < MIN_PRIORITY+1; i++ )
1054 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
1056 for(thread=gActiveThreads;thread;thread=thread->Next)
1059 Log(" %p %i (%i) - %s (CPU %i)",
1060 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1061 if(thread->Status != THREAD_STAT_ACTIVE)
1062 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
1063 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1064 Log(" KStack 0x%x", thread->KernelStack);
1065 if( thread->bInstrTrace )
1066 Log(" Tracing Enabled");
1067 Proc_DumpThreadCPUState(thread);
1070 #if SCHEDULER_TYPE == SCHED_RR_PRI
1076 * \fn void Threads_Dump(void)
1077 * \brief Dumps a list of currently running threads
1079 void Threads_Dump(void)
1083 Log("--- Thread Dump ---");
1084 Threads_DumpActive();
1086 Log("All Threads:");
1087 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1089 Log(" %p %i (%i) - %s (CPU %i)",
1090 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1091 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1092 switch(thread->Status)
1094 case THREAD_STAT_MUTEXSLEEP:
1095 Log(" Mutex Pointer: %p", thread->WaitPointer);
1097 case THREAD_STAT_SEMAPHORESLEEP:
1098 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1099 Log(" Semaphore Name: %s:%s",
1100 ((tSemaphore*)thread->WaitPointer)->ModName,
1101 ((tSemaphore*)thread->WaitPointer)->Name
1104 case THREAD_STAT_ZOMBIE:
1105 Log(" Return Status: %i", thread->RetStatus);
1109 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1110 Log(" KStack 0x%x", thread->KernelStack);
1111 if( thread->bInstrTrace )
1112 Log(" Tracing Enabled");
1113 Proc_DumpThreadCPUState(thread);
1118 * \brief Gets the next thread to run
1119 * \param CPU Current CPU
1120 * \param Last The thread the CPU was running
1122 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1126 // If this CPU has the lock, we must let it complete
1127 if( CPU_HAS_LOCK( &glThreadListLock ) )
1130 // Don't change threads if the current CPU has switches disabled
1131 if( gaThreads_NoTaskSwitch[CPU] )
1135 SHORTLOCK( &glThreadListLock );
1137 // Clear Delete Queue
1138 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
1139 // DEFINITELY - free() can deadlock in this case
1140 // I'll do it when it becomes an issue
1141 while(gDeleteThreads)
1143 thread = gDeleteThreads->Next;
1144 // Only free if structure is unused
1145 if( !IS_LOCKED(&gDeleteThreads->IsLocked) )
1148 gDeleteThreads->Status = THREAD_STAT_BURIED;
1150 if( IsHeap(gDeleteThreads->ThreadName) )
1151 free(gDeleteThreads->ThreadName);
1152 // Remove from global list
1153 if( gDeleteThreads == gAllThreads )
1154 gAllThreads = gDeleteThreads->GlobalNext;
1156 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
1157 free( gDeleteThreads );
1159 gDeleteThreads = thread;
1162 // Make sure the current (well, old) thread is marked as de-scheduled
1163 if(Last) Last->CurCPU = -1;
1165 // No active threads, just take a nap
1166 if(giNumActiveThreads == 0) {
1167 SHORTREL( &glThreadListLock );
1168 #if DEBUG_TRACE_TICKETS
1169 Log("No active threads");
1174 #if SCHEDULER_TYPE != SCHED_RR_PRI
1175 // Special case: 1 thread
1176 if(giNumActiveThreads == 1) {
1177 if( gActiveThreads->CurCPU == -1 )
1178 gActiveThreads->CurCPU = CPU;
1180 SHORTREL( &glThreadListLock );
1182 if( gActiveThreads->CurCPU == CPU )
1183 return gActiveThreads;
1185 return NULL; // CPU has nothing to do
1189 // Allow the old thread to be scheduled again
1191 if( Last->Status == THREAD_STAT_ACTIVE ) {
1192 #if SCHEDULER_TYPE == SCHED_LOTTERY
1193 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1194 # if DEBUG_TRACE_TICKETS
1195 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1196 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1197 caiTICKET_COUNTS[ Last->Priority ]);
1201 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1203 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1204 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1210 // Lottery Scheduler
1212 #if SCHEDULER_TYPE == SCHED_LOTTERY
1217 for(thread = gActiveThreads; thread; thread = thread->Next) {
1218 if(thread->CurCPU >= 0) continue;
1219 if(thread->Status != THREAD_STAT_ACTIVE)
1220 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1221 thread, thread->TID, thread->ThreadName, thread->Status);
1222 if(thread->Next == thread) {
1223 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1224 thread, thread->TID, thread->ThreadName, thread->Status);
1226 number += caiTICKET_COUNTS[ thread->Priority ];
1228 if(number != giFreeTickets) {
1229 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1230 giFreeTickets, number, CPU);
1234 // No free tickets (all tasks delegated to cores)
1235 if( giFreeTickets == 0 ) {
1236 SHORTREL(&glThreadListLock);
1240 // Get the ticket number
1241 ticket = number = rand() % giFreeTickets;
1243 // Find the next thread
1244 for(thread=gActiveThreads;thread;thread=thread->Next)
1246 if(thread->CurCPU >= 0) continue;
1247 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1248 number -= caiTICKET_COUNTS[ thread->Priority ];
1251 // If we didn't find a thread, something went wrong
1255 for(thread=gActiveThreads;thread;thread=thread->Next) {
1256 if(thread->CurCPU >= 0) continue;
1257 number += caiTICKET_COUNTS[ thread->Priority ];
1259 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1260 giFreeTickets, number);
1263 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1264 # if DEBUG_TRACE_TICKETS
1265 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1266 CPU, thread, thread->TID, thread->ThreadName,
1267 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1272 // Priority based round robin scheduler
1274 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1277 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1279 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1281 if( thread->CurCPU == -1 ) break;
1283 // If we fall onto the same queue again, special handling is
1285 if( Last && Last->Status == THREAD_STAT_ACTIVE && i == Last->Priority ) {
1286 tThread *savedThread = thread;
1288 // Find the next unscheduled thread in the list
1289 for( thread = Last->Next; thread; thread = thread->Next )
1291 if( thread->CurCPU == -1 ) break;
1293 // If we don't find anything after, just use the one
1295 if( !thread ) thread = savedThread;
1297 // Found a thread? Schedule it!
1303 SHORTREL(&glThreadListLock);
1306 if( thread->Status != THREAD_STAT_ACTIVE ) {
1307 LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1310 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1312 // Find the next unscheduled thread in the list
1313 for( thread = Last->Next; thread; thread = thread->Next )
1315 if( thread->CurCPU == -1 ) break;
1317 // If we don't find anything after, search from the beginning
1320 for(thread = gActiveThreads; thread; thread = thread->Next)
1322 if( thread->CurCPU == -1 ) break;
1328 SHORTREL(&glThreadListLock);
1333 # error "Unimplemented scheduling algorithm"
1336 // Make the new thread non-schedulable
1337 thread->CurCPU = CPU;
1338 thread->Remaining = thread->Quantum;
1340 SHORTREL( &glThreadListLock );
1345 // Acquire mutex (see mutex.h for documentation)
1346 int Mutex_Acquire(tMutex *Mutex)
1348 tThread *us = Proc_GetCurThread();
1351 SHORTLOCK( &Mutex->Protector );
1353 //Log("Mutex_Acquire: (%p)", Mutex);
1355 // Check if the lock is already held
1356 if( Mutex->Owner ) {
1357 SHORTLOCK( &glThreadListLock );
1358 // - Remove from active list
1359 us = Threads_RemActive();
1361 // - Mark as sleeping
1362 us->Status = THREAD_STAT_MUTEXSLEEP;
1363 us->WaitPointer = Mutex;
1366 if(Mutex->LastWaiting) {
1367 Mutex->LastWaiting->Next = us;
1368 Mutex->LastWaiting = us;
1371 Mutex->Waiting = us;
1372 Mutex->LastWaiting = us;
1375 #if DEBUG_TRACE_STATE
1376 Log("%p (%i %s) waiting on mutex %p",
1377 us, us->TID, us->ThreadName, Mutex);
1384 for( t = Mutex->Waiting; t; t = t->Next, i++ )
1385 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1386 t, t->TID, t->ThreadName);
1390 SHORTREL( &glThreadListLock );
1391 SHORTREL( &Mutex->Protector );
1392 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1393 // We're only woken when we get the lock
1394 us->WaitPointer = NULL;
1396 // Ooh, let's take it!
1399 SHORTREL( &Mutex->Protector );
1403 extern tMutex glPhysAlloc;
1404 if( Mutex != &glPhysAlloc )
1405 LogF("Mutex %p taken by %i %p\n", Mutex, us->TID, __builtin_return_address(0));
1412 void Mutex_Release(tMutex *Mutex)
1414 SHORTLOCK( &Mutex->Protector );
1415 //Log("Mutex_Release: (%p)", Mutex);
1416 if( Mutex->Waiting ) {
1417 Mutex->Owner = Mutex->Waiting; // Set owner
1418 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1419 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1420 // 2010-10-02 21:50 - Comemerating the death of the longest single
1421 // blocker in the Acess2 history. REMEMBER TO
1422 // FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1423 if( Mutex->LastWaiting == Mutex->Owner )
1424 Mutex->LastWaiting = NULL;
1427 SHORTLOCK( &glThreadListLock );
1428 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1429 Threads_AddActive(Mutex->Owner);
1430 SHORTREL( &glThreadListLock );
1433 Mutex->Owner = NULL;
1435 SHORTREL( &Mutex->Protector );
1438 extern tMutex glPhysAlloc;
1439 if( Mutex != &glPhysAlloc )
1440 LogF("Mutex %p released by %i %p\n", Mutex, Threads_GetTID(), __builtin_return_address(0));
1444 // Check if a mutex is locked
1445 int Mutex_IsLocked(tMutex *Mutex)
1447 return Mutex->Owner != NULL;
1451 // Initialise a semaphore
1453 void Semaphore_Init(tSemaphore *Sem, int Value, int MaxValue, const char *Module, const char *Name)
1455 memset(Sem, 0, sizeof(tSemaphore));
1457 Sem->ModName = Module;
1459 Sem->MaxValue = MaxValue;
1462 // Wait for items to be avaliable
1464 int Semaphore_Wait(tSemaphore *Sem, int MaxToTake)
1468 if( MaxToTake < 0 ) {
1469 Log_Warning("Threads", "Semaphore_Wait: User bug - MaxToTake(%i) < 0, Sem=%p(%s)",
1470 MaxToTake, Sem, Sem->Name);
1473 SHORTLOCK( &Sem->Protector );
1475 // Check if there's already items avaliable
1476 if( Sem->Value > 0 ) {
1477 // Take what we need
1478 if( MaxToTake && Sem->Value > MaxToTake )
1482 Sem->Value -= taken;
1486 SHORTLOCK( &glThreadListLock );
1488 // - Remove from active list
1489 us = Threads_RemActive();
1491 // - Mark as sleeping
1492 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1493 us->WaitPointer = Sem;
1494 us->RetStatus = MaxToTake; // Use RetStatus as a temp variable
1497 if(Sem->LastWaiting) {
1498 Sem->LastWaiting->Next = us;
1499 Sem->LastWaiting = us;
1503 Sem->LastWaiting = us;
1506 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1507 Log("%p (%i %s) waiting on semaphore %p %s:%s",
1508 us, us->TID, us->ThreadName,
1509 Sem, Sem->ModName, Sem->Name);
1512 SHORTREL( &Sem->Protector ); // Release first to make sure it is released
1513 SHORTREL( &glThreadListLock );
1514 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1515 // We're only woken when there's something avaliable (or a signal arrives)
1516 us->WaitPointer = NULL;
1518 taken = us->RetStatus;
1520 // Get the lock again
1521 SHORTLOCK( &Sem->Protector );
1524 // While there is space, and there are thread waiting
1525 // wake the first thread and give it what it wants (or what's left)
1526 while( (Sem->MaxValue == 0 || Sem->Value < Sem->MaxValue) && Sem->Signaling )
1529 tThread *toWake = Sem->Signaling;
1531 Sem->Signaling = Sem->Signaling->Next;
1532 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1533 if( Sem->Signaling == NULL )
1534 Sem->LastSignaling = NULL;
1536 // Figure out how much to give
1537 if( toWake->RetStatus && Sem->Value + toWake->RetStatus < Sem->MaxValue )
1538 given = toWake->RetStatus;
1540 given = Sem->MaxValue - Sem->Value;
1541 Sem->Value -= given;
1544 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1545 Log("%p (%i %s) woken by wait on %p %s:%s",
1546 toWake, toWake->TID, toWake->ThreadName,
1547 Sem, Sem->ModName, Sem->Name);
1550 // Save the number we gave to the thread's status
1551 toWake->RetStatus = given;
1554 SHORTLOCK( &glThreadListLock );
1555 if( toWake->Status != THREAD_STAT_ACTIVE )
1556 Threads_AddActive(toWake);
1557 SHORTREL( &glThreadListLock );
1559 SHORTREL( &Sem->Protector );
1565 // Add items to a semaphore
1567 int Semaphore_Signal(tSemaphore *Sem, int AmmountToAdd)
1572 if( AmmountToAdd < 0 ) {
1573 Log_Warning("Threads", "Semaphore_Signal: User bug - AmmountToAdd(%i) < 0, Sem=%p(%s)",
1574 AmmountToAdd, Sem, Sem->Name);
1576 SHORTLOCK( &Sem->Protector );
1578 // Check if we have to block
1579 if( Sem->MaxValue && Sem->Value == Sem->MaxValue )
1583 Log_Debug("Threads", "Semaphore_Signal: IDLE Sem = %s:%s", Sem->ModName, Sem->Name);
1584 Log_Debug("Threads", "Semaphore_Signal: Sem->Value(%i) == Sem->MaxValue(%i)", Sem->Value, Sem->MaxValue);
1587 SHORTLOCK( &glThreadListLock );
1588 // - Remove from active list
1589 us = Threads_RemActive();
1591 // - Mark as sleeping
1592 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1593 us->WaitPointer = Sem;
1594 us->RetStatus = AmmountToAdd; // Use RetStatus as a temp variable
1597 if(Sem->LastSignaling) {
1598 Sem->LastSignaling->Next = us;
1599 Sem->LastSignaling = us;
1602 Sem->Signaling = us;
1603 Sem->LastSignaling = us;
1606 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1607 Log("%p (%i %s) signaling semaphore %p %s:%s",
1608 us, us->TID, us->ThreadName,
1609 Sem, Sem->ModName, Sem->Name);
1612 SHORTREL( &glThreadListLock );
1613 SHORTREL( &Sem->Protector );
1614 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1615 // We're only woken when there's something avaliable
1616 us->WaitPointer = NULL;
1618 added = us->RetStatus;
1620 // Get the lock again
1621 SHORTLOCK( &Sem->Protector );
1626 // Figure out how much we need to take off
1627 if( Sem->MaxValue && Sem->Value + AmmountToAdd > Sem->MaxValue)
1628 added = Sem->MaxValue - Sem->Value;
1630 added = AmmountToAdd;
1631 Sem->Value += added;
1634 // While there are items avaliable, and there are thread waiting
1635 // wake the first thread and give it what it wants (or what's left)
1636 while( Sem->Value && Sem->Waiting )
1638 tThread *toWake = Sem->Waiting;
1640 // Remove thread from list (double ended, so clear LastWaiting if needed)
1641 Sem->Waiting = Sem->Waiting->Next;
1642 if( Sem->Waiting == NULL )
1643 Sem->LastWaiting = NULL;
1645 // Figure out how much to give to woken thread
1646 // - Requested count is stored in ->RetStatus
1647 if( toWake->RetStatus && Sem->Value > toWake->RetStatus )
1648 given = toWake->RetStatus;
1651 Sem->Value -= given;
1653 // Save the number we gave to the thread's status
1654 toWake->RetStatus = given;
1656 if(toWake->bInstrTrace)
1657 Log("%s(%i) given %i from %p", toWake->ThreadName, toWake->TID, given, Sem);
1658 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1659 Log("%p (%i %s) woken by signal on %p %s:%s",
1660 toWake, toWake->TID, toWake->ThreadName,
1661 Sem, Sem->ModName, Sem->Name);
1665 SHORTLOCK( &glThreadListLock );
1666 if( toWake->Status != THREAD_STAT_ACTIVE )
1667 Threads_AddActive(toWake);
1669 Warning("Thread %p (%i %s) is already awake", toWake, toWake->TID, toWake->ThreadName);
1670 SHORTREL( &glThreadListLock );
1672 SHORTREL( &Sem->Protector );
1678 // Get the current value of a semaphore
1680 int Semaphore_GetValue(tSemaphore *Sem)
1686 EXPORT(Threads_GetUID);
1687 EXPORT(Threads_GetGID);
1688 EXPORT(Mutex_Acquire);
1689 EXPORT(Mutex_Release);
1690 EXPORT(Mutex_IsLocked);
1691 EXPORT(Semaphore_Init);
1692 EXPORT(Semaphore_Wait);
1693 EXPORT(Semaphore_Signal);