4 * - Common Thread Control
8 #include <threads_int.h>
10 #include <semaphore.h>
13 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
14 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
15 #define SEMAPHORE_DEBUG 0
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_LOTTERY
26 #define DEFAULT_QUANTUM 10
27 #define DEFAULT_PRIORITY 5
28 #define MIN_PRIORITY 10
29 const enum eConfigTypes cCONFIG_TYPES[] = {
30 CFGT_HEAPSTR, // e.g. CFG_VFS_CWD
31 CFGT_INT, // e.g. CFG_VFS_MAXFILES
36 extern void ArchThreads_Init(void);
37 extern void Proc_CallFaultHandler(tThread *Thread);
38 extern void Proc_DumpThreadCPUState(tThread *Thread);
39 extern int GetCPUNum(void);
42 void Threads_Init(void);
44 int Threads_SetName(const char *NewName);
46 char *Threads_GetName(int ID);
48 void Threads_SetPriority(tThread *Thread, int Pri);
49 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
50 int Threads_WaitTID(int TID, int *status);
51 tThread *Threads_GetThread(Uint TID);
53 void Threads_AddToDelete(tThread *Thread);
54 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread);
56 void Threads_Exit(int TID, int Status);
57 void Threads_Kill(tThread *Thread, int Status);
58 void Threads_Yield(void);
59 void Threads_Sleep(void);
60 int Threads_Wake(tThread *Thread);
61 void Threads_AddActive(tThread *Thread);
62 tThread *Threads_RemActive(void);
64 void Threads_ToggleTrace(int TID);
65 void Threads_Fault(int Num);
66 void Threads_SegFault(tVAddr Addr);
68 int Threads_GetPID(void);
69 int Threads_GetTID(void);
70 tUID Threads_GetUID(void);
71 tGID Threads_GetGID(void);
72 int Threads_SetUID(Uint *Errno, tUID ID);
73 int Threads_SetGID(Uint *Errno, tUID ID);
75 void Threads_Dump(void);
76 void Threads_DumpActive(void);
78 int Mutex_Acquire(tMutex *Mutex);
79 void Mutex_Release(tMutex *Mutex);
80 int Mutex_IsLocked(tMutex *Mutex);
85 // Only used for the core kernel
86 tThread gThreadZero = {
87 .Status = THREAD_STAT_ACTIVE, // Status
88 .ThreadName = (char*)"ThreadZero", // Name
89 .Quantum = DEFAULT_QUANTUM, // Default Quantum
90 .Remaining = DEFAULT_QUANTUM, // Current Quantum
91 .Priority = DEFAULT_PRIORITY // Number of tickets
95 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
96 // --- Current State ---
97 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
98 volatile Uint giNextTID = 1; // Next TID to allocate
99 // --- Thread Lists ---
100 tThread *gAllThreads = NULL; // All allocated threads
101 tThread *gSleepingThreads = NULL; // Sleeping Threads
102 tThread *gDeleteThreads = NULL; // Threads to delete
103 int giNumCPUs = 1; // Number of CPUs
104 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
105 // --- Scheduler Types ---
106 #if SCHEDULER_TYPE == SCHED_LOTTERY
107 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
108 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
109 tThread *gActiveThreads = NULL; // Currently Running Threads
110 #elif SCHEDULER_TYPE == SCHED_RR_SIM
111 tThread *gActiveThreads = NULL; // Currently Running Threads
112 #elif SCHEDULER_TYPE == SCHED_RR_PRI
113 tThread *gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
115 # error "Unkown scheduler type"
120 * \fn void Threads_Init(void)
121 * \brief Initialse the thread list
123 void Threads_Init(void)
127 Log_Debug("Threads", "Offsets of tThread");
128 Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
130 // Create Initial Task
131 #if SCHEDULER_TYPE == SCHED_RR_PRI
132 gaActiveThreads[gThreadZero.Priority] = &gThreadZero;
134 gActiveThreads = &gThreadZero;
137 gAllThreads = &gThreadZero;
138 giNumActiveThreads = 1;
144 * \fn void Threads_SetName(const char *NewName)
145 * \brief Sets the current thread's name
146 * \param NewName New name for the thread
147 * \return Boolean Failure
149 int Threads_SetName(const char *NewName)
151 tThread *cur = Proc_GetCurThread();
152 char *oldname = cur->ThreadName;
154 // NOTE: There is a possibility of non-thread safety here
155 // A thread could read the current name pointer before it is zeroed
157 cur->ThreadName = NULL;
159 if( IsHeap(oldname) ) free( oldname );
161 cur->ThreadName = strdup(NewName);
166 * \fn char *Threads_GetName(int ID)
167 * \brief Gets a thread's name
168 * \param ID Thread ID (-1 indicates current thread)
169 * \return Pointer to name
170 * \retval NULL Failure
172 char *Threads_GetName(tTID ID)
175 return Proc_GetCurThread()->ThreadName;
177 return Threads_GetThread(ID)->ThreadName;
181 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
182 * \brief Sets the priority of a task
183 * \param Thread Thread to update ticket count (NULL means current thread)
184 * \param Pri New priority
186 void Threads_SetPriority(tThread *Thread, int Pri)
188 // Get current thread
189 if(Thread == NULL) Thread = Proc_GetCurThread();
191 // - If < 0, set to lowest priority
192 // - Minumum priority is actualy a high number, 0 is highest
193 if(Pri < 0) Pri = MIN_PRIORITY;
194 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
196 // Do we actually have to do anything?
197 if( Pri == Thread->Priority ) return;
199 #if SCHEDULER_TYPE == SCHED_RR_PRI
200 SHORTLOCK( &glThreadListLock );
201 // Remove from old priority
202 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
204 Thread->Next = gaActiveThreads[Pri];
205 gaActiveThreads[Pri] = Thread;
206 Thread->Priority = Pri;
207 SHORTREL( &glThreadListLock );
209 // If this isn't the current thread, we need to lock
210 if( Thread != Proc_GetCurThread() )
212 SHORTLOCK( &glThreadListLock );
214 #if SCHEDULER_TYPE == SCHED_LOTTERY
215 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
216 # if DEBUG_TRACE_TICKETS
217 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
219 caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
222 Thread->Priority = Pri;
223 SHORTREL( &glThreadListLock );
226 Thread->Priority = Pri;
229 #if DEBUG_TRACE_STATE
230 Log("Threads_SetPriority: %p(%i %s) pri set %i",
231 Thread, Thread->TID, Thread->ThreadName,
237 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
238 * \brief Clone the TCB of the current thread
239 * \param Err Error pointer
240 * \param Flags Flags for something... (What is this for?)
242 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
246 cur = Proc_GetCurThread();
248 // Allocate and duplicate
249 new = malloc(sizeof(tThread));
250 if(new == NULL) { *Err = -ENOMEM; return NULL; }
251 memcpy(new, cur, sizeof(tThread));
255 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
256 new->Status = THREAD_STAT_PREINIT;
260 new->TID = giNextTID++;
262 new->bInstrTrace = 0;
265 new->ThreadName = strdup(cur->ThreadName);
267 // Set Thread Group ID (PID)
269 new->TGID = new->TID;
271 new->TGID = cur->TGID;
273 // Messages are not inherited
274 new->Messages = NULL;
275 new->LastMessage = NULL;
278 new->Remaining = new->Quantum = cur->Quantum;
279 new->Priority = cur->Priority;
281 // Set Signal Handlers
282 new->CurFaultNum = 0;
283 new->FaultHandler = cur->FaultHandler;
285 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
287 switch(cCONFIG_TYPES[i])
290 new->Config[i] = cur->Config[i];
294 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
301 // Maintain a global list of threads
302 SHORTLOCK( &glThreadListLock );
303 new->GlobalPrev = NULL; // Protect against bugs
304 new->GlobalNext = gAllThreads;
305 gAllThreads->GlobalPrev = new;
307 SHORTREL( &glThreadListLock );
313 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
314 * \brief Clone the TCB of the current thread
316 tThread *Threads_CloneThreadZero(void)
320 cur = Proc_GetCurThread();
322 // Allocate and duplicate
323 new = malloc(sizeof(tThread));
327 memcpy(new, &gThreadZero, sizeof(tThread));
331 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
332 new->Status = THREAD_STAT_PREINIT;
336 new->TID = giNextTID++;
340 new->ThreadName = NULL;
342 // Messages are not inherited
343 new->Messages = NULL;
344 new->LastMessage = NULL;
347 new->Remaining = new->Quantum = cur->Quantum;
348 new->Priority = cur->Priority;
349 new->bInstrTrace = 0;
351 // Set Signal Handlers
352 new->CurFaultNum = 0;
353 new->FaultHandler = cur->FaultHandler;
355 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
357 switch(cCONFIG_TYPES[i])
360 new->Config[i] = cur->Config[i];
364 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
371 // Maintain a global list of threads
372 SHORTLOCK( &glThreadListLock );
373 new->GlobalPrev = NULL; // Protect against bugs
374 new->GlobalNext = gAllThreads;
375 gAllThreads->GlobalPrev = new;
377 SHORTREL( &glThreadListLock );
383 * \brief Get a configuration pointer from the Per-Thread data area
384 * \param ID Config slot ID
385 * \return Pointer at ID
387 Uint *Threads_GetCfgPtr(int ID)
389 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
390 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
394 return &Proc_GetCurThread()->Config[ID];
398 * \brief Wait for a task to change state
399 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
400 * \param Status Thread return status
401 * \return TID of child that changed state
403 tTID Threads_WaitTID(int TID, int *Status)
407 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
411 // Any peer/child thread
413 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
419 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
425 tThread *t = Threads_GetThread(TID);
426 int initStatus = t->Status;
429 // Wait for the thread to die!
430 if(initStatus != THREAD_STAT_ZOMBIE) {
431 // TODO: Handle child also being suspended if wanted
432 while(t->Status != THREAD_STAT_ZOMBIE) {
434 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
435 Threads_GetTID(), t->TID, t->Status);
440 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
441 Threads_GetTID(), t->TID, t->Status);
445 case THREAD_STAT_ZOMBIE:
447 t->Status = THREAD_STAT_DEAD;
448 // TODO: Child return value?
449 if(Status) *Status = t->RetStatus;
450 // add to delete queue
451 Threads_AddToDelete( t );
454 if(Status) *Status = -1;
464 * \brief Gets a thread given its TID
465 * \param TID Thread ID
466 * \return Thread pointer
468 tThread *Threads_GetThread(Uint TID)
472 // Search global list
473 for(thread = gAllThreads;
475 thread = thread->GlobalNext)
477 if(thread->TID == TID)
481 Log("Unable to find TID %i on main list\n", TID);
487 * \brief Adds a thread to the delete queue
488 * \param Thread Thread to delete
490 void Threads_AddToDelete(tThread *Thread)
492 // Add to delete queue
493 // TODO: Is locking needed?
495 Thread->Next = gDeleteThreads;
496 gDeleteThreads = Thread;
499 gDeleteThreads = Thread;
504 * \brief Deletes an entry from a list
505 * \param List Pointer to the list head
506 * \param Thread Thread to find
509 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
511 tThread *ret, *prev = NULL;
514 ret && ret != Thread;
515 prev = ret, ret = ret->Next
518 // Is the thread on the list
520 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
525 *List = Thread->Next;
526 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
529 prev->Next = Thread->Next;
530 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
537 * \brief Exit the current process (or another?)
538 * \param TID Thread ID to kill
539 * \param Status Exit status
541 void Threads_Exit(int TID, int Status)
544 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
546 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
548 // Halt forever, just in case
553 * \fn void Threads_Kill(tThread *Thread, int Status)
554 * \brief Kill a thread
555 * \param Thread Thread to kill
556 * \param Status Status code to return to the parent
558 void Threads_Kill(tThread *Thread, int Status)
561 int isCurThread = Thread == Proc_GetCurThread();
563 // TODO: Kill all children
567 // TODO: I should keep a .Parent pointer, and a .Children list
568 for(child = gAllThreads;
570 child = child->GlobalNext)
572 if(child->Parent == Thread)
573 Threads_Kill(child, -1);
578 ///\note Double lock is needed due to overlap of lock areas
580 // Lock thread (stop us recieving messages)
581 SHORTLOCK( &Thread->IsLocked );
583 // Clear Message Queue
584 while( Thread->Messages )
586 msg = Thread->Messages->Next;
587 free( Thread->Messages );
588 Thread->Messages = msg;
592 SHORTLOCK( &glThreadListLock );
594 switch(Thread->Status)
596 case THREAD_STAT_PREINIT: // Only on main list
599 // Currently active thread
600 case THREAD_STAT_ACTIVE:
601 #if SCHEDULER_TYPE == SCHED_RR_PRI
602 if( Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
604 if( Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
607 // Ensure that we are not rescheduled
608 Thread->Remaining = 0; // Clear Remaining Quantum
609 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
611 // Update bookkeeping
612 giNumActiveThreads --;
613 #if SCHEDULER_TYPE == SCHED_LOTTERY
614 if( Thread != Proc_GetCurThread() )
615 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
620 Log_Warning("Threads",
621 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
622 Thread, Thread->TID, Thread->ThreadName
626 // Kill it while it sleeps!
627 case THREAD_STAT_SLEEPING:
628 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
630 Log_Warning("Threads",
631 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
632 Thread, Thread->TID, Thread->ThreadName
637 // Brains!... You cannot kill
638 case THREAD_STAT_ZOMBIE:
639 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
640 Thread, Thread->TID, Thread->ThreadName);
641 SHORTREL( &glThreadListLock );
642 SHORTREL( &Thread->IsLocked );
646 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
652 Thread->RetStatus = Status;
654 // Don't Zombie if we are being killed because our parent is
657 Thread->Status = THREAD_STAT_DEAD;
658 Threads_AddToDelete( Thread );
660 Thread->Status = THREAD_STAT_ZOMBIE;
662 Threads_Wake( Thread->Parent );
665 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
668 SHORTREL( &glThreadListLock );
669 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)
683 tThread *thread = Proc_GetCurThread();
684 thread->Remaining = 0;
685 //while(thread->Remaining == 0)
690 * \fn void Threads_Sleep(void)
691 * \brief Take the current process off the run queue
693 void Threads_Sleep(void)
695 tThread *cur = Proc_GetCurThread();
698 SHORTLOCK( &glThreadListLock );
700 // Don't sleep if there is a message waiting
701 if( cur->Messages ) {
702 SHORTREL( &glThreadListLock );
706 // Remove us from running queue
708 // Mark thread as sleeping
709 cur->Status = THREAD_STAT_SLEEPING;
711 // Add to Sleeping List (at the top)
712 cur->Next = gSleepingThreads;
713 gSleepingThreads = cur;
716 #if DEBUG_TRACE_STATE
717 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
721 SHORTREL( &glThreadListLock );
723 while(cur->Status != THREAD_STAT_ACTIVE) HALT();
728 * \fn int Threads_Wake( tThread *Thread )
729 * \brief Wakes a sleeping/waiting thread up
730 * \param Thread Thread to wake
731 * \return Boolean Failure (Returns ERRNO)
732 * \warning This should ONLY be called with task switches disabled
734 int Threads_Wake(tThread *Thread)
739 switch(Thread->Status)
741 case THREAD_STAT_ACTIVE:
742 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
745 case THREAD_STAT_SLEEPING:
746 SHORTLOCK( &glThreadListLock );
747 // Remove from sleeping queue
748 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
750 Threads_AddActive( Thread );
752 #if DEBUG_TRACE_STATE
753 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
755 SHORTREL( &glThreadListLock );
758 case THREAD_STAT_WAITING:
759 Warning("Threads_Wake - Waiting threads are not currently supported");
762 case THREAD_STAT_DEAD:
763 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
767 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
773 * \brief Wake a thread given the TID
774 * \param TID Thread ID to wake
775 * \return Boolean Faulure (errno)
777 int Threads_WakeTID(tTID TID)
779 tThread *thread = Threads_GetThread(TID);
783 ret = Threads_Wake( thread );
784 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
788 void Threads_ToggleTrace(int TID)
790 tThread *thread = Threads_GetThread(TID);
792 thread->bInstrTrace = !thread->bInstrTrace;
796 * \brief Adds a thread to the active queue
798 void Threads_AddActive(tThread *Thread)
800 SHORTLOCK( &glThreadListLock );
802 if( Thread->Status == THREAD_STAT_ACTIVE ) {
803 tThread *cur = Proc_GetCurThread();
804 Warning("WTF, CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
805 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
806 SHORTREL( &glThreadListLock );
811 Thread->Status = THREAD_STAT_ACTIVE;
812 // Thread->CurCPU = -1;
813 // Add to active list
814 #if SCHEDULER_TYPE == SCHED_RR_PRI
815 Thread->Next = gaActiveThreads[Thread->Priority];
816 gaActiveThreads[Thread->Priority] = Thread;
818 Thread->Next = gActiveThreads;
819 gActiveThreads = Thread;
822 // Update bookkeeping
823 giNumActiveThreads ++;
825 #if SCHEDULER_TYPE == SCHED_LOTTERY
828 // Only change the ticket count if the thread is un-scheduled
829 if(Thread->CurCPU != -1)
832 delta = caiTICKET_COUNTS[ Thread->Priority ];
834 giFreeTickets += delta;
835 # if DEBUG_TRACE_TICKETS
836 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
837 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
844 SHORTREL( &glThreadListLock );
848 * \brief Removes the current thread from the active queue
849 * \warning This should ONLY be called with task switches disabled
850 * \return Current thread pointer
852 tThread *Threads_RemActive(void)
854 tThread *ret = Proc_GetCurThread();
856 SHORTLOCK( &glThreadListLock );
858 // Delete from active queue
859 #if SCHEDULER_TYPE == SCHED_RR_PRI
860 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
862 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
865 SHORTREL( &glThreadListLock );
872 giNumActiveThreads --;
873 // no need to decrement tickets, scheduler did it for us
875 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
876 Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
877 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
880 SHORTREL( &glThreadListLock );
886 * \fn void Threads_SetFaultHandler(Uint Handler)
887 * \brief Sets the signal handler for a signal
889 void Threads_SetFaultHandler(Uint Handler)
891 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
892 Proc_GetCurThread()->FaultHandler = Handler;
896 * \fn void Threads_Fault(int Num)
897 * \brief Calls a fault handler
899 void Threads_Fault(int Num)
901 tThread *thread = Proc_GetCurThread();
903 Log_Log("Threads", "Threads_Fault: thread = %p", thread);
907 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
909 switch(thread->FaultHandler)
912 Threads_Kill(thread, -1);
915 case 1: // Dump Core?
916 Threads_Kill(thread, -1);
921 // Double Fault? Oh, F**k
922 if(thread->CurFaultNum != 0) {
923 Threads_Kill(thread, -1); // For now, just kill
927 thread->CurFaultNum = Num;
929 Proc_CallFaultHandler(thread);
933 * \fn void Threads_SegFault(tVAddr Addr)
934 * \brief Called when a Segment Fault occurs
936 void Threads_SegFault(tVAddr Addr)
938 Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
940 //Threads_Exit( 0, -1 );
943 // --- Process Structure Access Functions ---
944 tPID Threads_GetPID(void)
946 return Proc_GetCurThread()->TGID;
948 tTID Threads_GetTID(void)
950 return Proc_GetCurThread()->TID;
952 tUID Threads_GetUID(void)
954 return Proc_GetCurThread()->UID;
956 tGID Threads_GetGID(void)
958 return Proc_GetCurThread()->GID;
961 int Threads_SetUID(Uint *Errno, tUID ID)
963 tThread *t = Proc_GetCurThread();
968 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
973 int Threads_SetGID(Uint *Errno, tGID ID)
975 tThread *t = Proc_GetCurThread();
980 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
986 * \fn void Threads_Dump(void)
988 void Threads_DumpActive(void)
991 #if SCHEDULER_TYPE == SCHED_RR_PRI
995 Log("Active Threads: (%i reported)", giNumActiveThreads);
997 #if SCHEDULER_TYPE == SCHED_RR_PRI
998 for( i = 0; i < MIN_PRIORITY+1; i++ )
1000 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
1002 for(thread=gActiveThreads;thread;thread=thread->Next)
1005 Log(" %p %i (%i) - %s (CPU %i)",
1006 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1007 if(thread->Status != THREAD_STAT_ACTIVE)
1008 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
1009 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1010 Log(" KStack 0x%x", thread->KernelStack);
1011 if( thread->bInstrTrace )
1012 Log(" Tracing Enabled");
1013 Proc_DumpThreadCPUState(thread);
1016 #if SCHEDULER_TYPE == SCHED_RR_PRI
1022 * \fn void Threads_Dump(void)
1023 * \brief Dumps a list of currently running threads
1025 void Threads_Dump(void)
1029 Log("--- Thread Dump ---");
1030 Threads_DumpActive();
1032 Log("All Threads:");
1033 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1035 Log(" %p %i (%i) - %s (CPU %i)",
1036 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1037 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1038 switch(thread->Status)
1040 case THREAD_STAT_MUTEXSLEEP:
1041 Log(" Mutex Pointer: %p", thread->WaitPointer);
1043 case THREAD_STAT_SEMAPHORESLEEP:
1044 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1045 Log(" Semaphore Name: %s:%s",
1046 ((tSemaphore*)thread->WaitPointer)->ModName,
1047 ((tSemaphore*)thread->WaitPointer)->Name
1050 case THREAD_STAT_ZOMBIE:
1051 Log(" Return Status: %i", thread->RetStatus);
1055 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1056 Log(" KStack 0x%x", thread->KernelStack);
1057 if( thread->bInstrTrace )
1058 Log(" Tracing Enabled");
1059 Proc_DumpThreadCPUState(thread);
1064 * \brief Gets the next thread to run
1065 * \param CPU Current CPU
1066 * \param Last The thread the CPU was running
1068 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1072 // If this CPU has the lock, we must let it complete
1073 if( CPU_HAS_LOCK( &glThreadListLock ) )
1076 // Don't change threads if the current CPU has switches disabled
1077 if( gaThreads_NoTaskSwitch[CPU] )
1082 SHORTLOCK( &glThreadListLock );
1084 // Clear Delete Queue
1085 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
1086 // DEFINITELY - free() can deadlock in this case
1087 // I'll do it when it becomes an issue
1088 while(gDeleteThreads)
1090 thread = gDeleteThreads->Next;
1091 // Only free if structure is unused
1092 if( !IS_LOCKED(&gDeleteThreads->IsLocked) )
1095 gDeleteThreads->Status = THREAD_STAT_BURIED;
1097 if( IsHeap(gDeleteThreads->ThreadName) )
1098 free(gDeleteThreads->ThreadName);
1099 // Remove from global list
1100 if( gDeleteThreads == gAllThreads )
1101 gAllThreads = gDeleteThreads->GlobalNext;
1103 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
1104 free( gDeleteThreads );
1106 gDeleteThreads = thread;
1109 // Make sure the current (well, old) thread is marked as de-scheduled
1110 if(Last) Last->CurCPU = -1;
1112 // No active threads, just take a nap
1113 if(giNumActiveThreads == 0) {
1114 SHORTREL( &glThreadListLock );
1115 #if DEBUG_TRACE_TICKETS
1116 Log("No active threads");
1121 #if SCHEDULER_TYPE != SCHED_RR_PRI
1122 // Special case: 1 thread
1123 if(giNumActiveThreads == 1) {
1124 if( gActiveThreads->CurCPU == -1 )
1125 gActiveThreads->CurCPU = CPU;
1127 SHORTREL( &glThreadListLock );
1129 if( gActiveThreads->CurCPU == CPU )
1130 return gActiveThreads;
1132 return NULL; // CPU has nothing to do
1136 // Allow the old thread to be scheduled again
1138 if( Last->Status == THREAD_STAT_ACTIVE ) {
1139 #if SCHEDULER_TYPE == SCHED_LOTTERY
1140 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1141 # if DEBUG_TRACE_TICKETS
1142 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1143 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1144 caiTICKET_COUNTS[ Last->Priority ]);
1148 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1150 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1151 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1157 // Lottery Scheduler
1159 #if SCHEDULER_TYPE == SCHED_LOTTERY
1164 for(thread = gActiveThreads; thread; thread = thread->Next) {
1165 if(thread->CurCPU >= 0) continue;
1166 if(thread->Status != THREAD_STAT_ACTIVE)
1167 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1168 thread, thread->TID, thread->ThreadName, thread->Status);
1169 if(thread->Next == thread) {
1170 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1171 thread, thread->TID, thread->ThreadName, thread->Status);
1173 number += caiTICKET_COUNTS[ thread->Priority ];
1175 if(number != giFreeTickets) {
1176 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1177 giFreeTickets, number, CPU);
1181 // No free tickets (all tasks delegated to cores)
1182 if( giFreeTickets == 0 ) {
1183 SHORTREL(&glThreadListLock);
1187 // Get the ticket number
1188 ticket = number = rand() % giFreeTickets;
1190 // Find the next thread
1191 for(thread=gActiveThreads;thread;thread=thread->Next)
1193 if(thread->CurCPU >= 0) continue;
1194 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1195 number -= caiTICKET_COUNTS[ thread->Priority ];
1198 // If we didn't find a thread, something went wrong
1202 for(thread=gActiveThreads;thread;thread=thread->Next) {
1203 if(thread->CurCPU >= 0) continue;
1204 number += caiTICKET_COUNTS[ thread->Priority ];
1206 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1207 giFreeTickets, number);
1210 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1211 # if DEBUG_TRACE_TICKETS
1212 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1213 CPU, thread, thread->TID, thread->ThreadName,
1214 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1219 // Priority based round robin scheduler
1221 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1224 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1226 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1228 if( thread->CurCPU == -1 ) break;
1230 // If we fall onto the same queue again, special handling is
1232 if( i == Last->Priority ) {
1233 tThread *savedThread = thread;
1235 // Find the next unscheduled thread in the list
1236 for( thread = Last->Next; thread; thread = thread->Next )
1238 if( thread->CurCPU == -1 ) break;
1240 // If we don't find anything after, just use the one
1242 if( !thread ) thread = savedThread;
1244 // Found a thread? Schedule it!
1250 SHORTREL(&glThreadListLock);
1254 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1256 // Find the next unscheduled thread in the list
1257 for( thread = Last->Next; thread; thread = thread->Next )
1259 if( thread->CurCPU == -1 ) break;
1261 // If we don't find anything after, search from the beginning
1264 for(thread = gActiveThreads; thread; thread = thread->Next)
1266 if( thread->CurCPU == -1 ) break;
1272 SHORTREL(&glThreadListLock);
1277 # error "Unimplemented scheduling algorithm"
1280 // Make the new thread non-schedulable
1281 thread->CurCPU = CPU;
1283 SHORTREL( &glThreadListLock );
1288 // Acquire mutex (see mutex.h for documentation)
1289 int Mutex_Acquire(tMutex *Mutex)
1291 tThread *us = Proc_GetCurThread();
1294 SHORTLOCK( &Mutex->Protector );
1296 //Log("Mutex_Acquire: (%p)", Mutex);
1298 // Check if the lock is already held
1299 if( Mutex->Owner ) {
1300 SHORTLOCK( &glThreadListLock );
1301 // - Remove from active list
1302 us = Threads_RemActive();
1304 // - Mark as sleeping
1305 us->Status = THREAD_STAT_MUTEXSLEEP;
1306 us->WaitPointer = Mutex;
1309 if(Mutex->LastWaiting) {
1310 Mutex->LastWaiting->Next = us;
1311 Mutex->LastWaiting = us;
1314 Mutex->Waiting = us;
1315 Mutex->LastWaiting = us;
1318 #if DEBUG_TRACE_STATE
1319 Log("%p (%i %s) waiting on mutex %p",
1320 us, us->TID, us->ThreadName, Mutex);
1327 for( t = Mutex->Waiting; t; t = t->Next, i++ )
1328 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1329 t, t->TID, t->ThreadName);
1333 SHORTREL( &glThreadListLock );
1334 SHORTREL( &Mutex->Protector );
1335 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1336 // We're only woken when we get the lock
1337 us->WaitPointer = NULL;
1339 // Ooh, let's take it!
1342 SHORTREL( &Mutex->Protector );
1346 extern tMutex glPhysAlloc;
1347 if( Mutex != &glPhysAlloc )
1348 LogF("Mutex %p taken by %i %p\n", Mutex, us->TID, __builtin_return_address(0));
1355 void Mutex_Release(tMutex *Mutex)
1357 SHORTLOCK( &Mutex->Protector );
1358 //Log("Mutex_Release: (%p)", Mutex);
1359 if( Mutex->Waiting ) {
1360 Mutex->Owner = Mutex->Waiting; // Set owner
1361 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1362 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1363 // 2010-10-02 21:50 - Comemerating the death of the longest single
1364 // blocker in the Acess2 history. REMEMBER TO
1365 // FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1366 if( Mutex->LastWaiting == Mutex->Owner )
1367 Mutex->LastWaiting = NULL;
1370 SHORTLOCK( &glThreadListLock );
1371 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1372 Threads_AddActive(Mutex->Owner);
1373 SHORTREL( &glThreadListLock );
1376 Mutex->Owner = NULL;
1378 SHORTREL( &Mutex->Protector );
1381 extern tMutex glPhysAlloc;
1382 if( Mutex != &glPhysAlloc )
1383 LogF("Mutex %p released by %i %p\n", Mutex, Threads_GetTID(), __builtin_return_address(0));
1387 // Check if a mutex is locked
1388 int Mutex_IsLocked(tMutex *Mutex)
1390 return Mutex->Owner != NULL;
1394 // Initialise a semaphore
1396 void Semaphore_Init(tSemaphore *Sem, int Value, int MaxValue, const char *Module, const char *Name)
1398 memset(Sem, 0, sizeof(tSemaphore));
1400 Sem->ModName = Module;
1402 Sem->MaxValue = MaxValue;
1405 // Wait for items to be avaliable
1407 int Semaphore_Wait(tSemaphore *Sem, int MaxToTake)
1411 if( MaxToTake < 0 ) {
1412 Log_Warning("Threads", "Semaphore_Wait: User bug - MaxToTake(%i) < 0, Sem=%p(%s)",
1413 MaxToTake, Sem, Sem->Name);
1416 SHORTLOCK( &Sem->Protector );
1418 // Check if there's already items avaliable
1419 if( Sem->Value > 0 ) {
1420 // Take what we need
1421 if( MaxToTake && Sem->Value > MaxToTake )
1425 Sem->Value -= taken;
1426 SHORTREL( &Sem->Protector );
1430 SHORTLOCK( &glThreadListLock );
1432 // - Remove from active list
1433 us = Threads_RemActive();
1435 // - Mark as sleeping
1436 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1437 us->WaitPointer = Sem;
1438 us->RetStatus = MaxToTake; // Use RetStatus as a temp variable
1441 if(Sem->LastWaiting) {
1442 Sem->LastWaiting->Next = us;
1443 Sem->LastWaiting = us;
1447 Sem->LastWaiting = us;
1450 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1451 Log("%p (%i %s) waiting on semaphore %p %s:%s",
1452 us, us->TID, us->ThreadName,
1453 Sem, Sem->ModName, Sem->Name);
1456 SHORTREL( &Sem->Protector ); // Release first to make sure it is released
1457 SHORTREL( &glThreadListLock );
1458 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1459 // We're only woken when there's something avaliable
1460 us->WaitPointer = NULL;
1462 taken = us->RetStatus;
1464 // Get the lock again
1465 SHORTLOCK( &Sem->Protector );
1468 // While there is space, and there are thread waiting
1469 // wake the first thread and give it what it wants (or what's left)
1470 while( (Sem->MaxValue == 0 || Sem->Value < Sem->MaxValue) && Sem->Signaling )
1473 tThread *toWake = Sem->Signaling;
1475 Sem->Signaling = Sem->Signaling->Next;
1476 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1477 if( Sem->Signaling == NULL )
1478 Sem->LastSignaling = NULL;
1480 // Figure out how much to give
1481 if( toWake->RetStatus && Sem->Value + toWake->RetStatus < Sem->MaxValue )
1482 given = toWake->RetStatus;
1484 given = Sem->MaxValue - Sem->Value;
1485 Sem->Value -= given;
1488 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1489 Log("%p (%i %s) woken by wait on %p %s:%s",
1490 toWake, toWake->TID, toWake->ThreadName,
1491 Sem, Sem->ModName, Sem->Name);
1494 // Save the number we gave to the thread's status
1495 toWake->RetStatus = given;
1498 SHORTLOCK( &glThreadListLock );
1499 if( toWake->Status != THREAD_STAT_ACTIVE )
1500 Threads_AddActive(toWake);
1501 SHORTREL( &glThreadListLock );
1503 SHORTREL( &Sem->Protector );
1509 // Add items to a semaphore
1511 int Semaphore_Signal(tSemaphore *Sem, int AmmountToAdd)
1516 if( AmmountToAdd < 0 ) {
1517 Log_Warning("Threads", "Semaphore_Signal: User bug - AmmountToAdd(%i) < 0, Sem=%p(%s)",
1518 AmmountToAdd, Sem, Sem->Name);
1520 SHORTLOCK( &Sem->Protector );
1522 // Check if we have to block
1523 if( Sem->MaxValue && Sem->Value == Sem->MaxValue )
1527 Log_Debug("Threads", "Semaphore_Signal: IDLE Sem = %s:%s", Sem->ModName, Sem->Name);
1528 Log_Debug("Threads", "Semaphore_Signal: Sem->Value(%i) == Sem->MaxValue(%i)", Sem->Value, Sem->MaxValue);
1531 SHORTLOCK( &glThreadListLock );
1532 // - Remove from active list
1533 us = Threads_RemActive();
1535 // - Mark as sleeping
1536 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1537 us->WaitPointer = Sem;
1538 us->RetStatus = AmmountToAdd; // Use RetStatus as a temp variable
1541 if(Sem->LastSignaling) {
1542 Sem->LastSignaling->Next = us;
1543 Sem->LastSignaling = us;
1546 Sem->Signaling = us;
1547 Sem->LastSignaling = us;
1550 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1551 Log("%p (%i %s) signaling semaphore %p %s:%s",
1552 us, us->TID, us->ThreadName,
1553 Sem, Sem->ModName, Sem->Name);
1556 SHORTREL( &glThreadListLock );
1557 SHORTREL( &Sem->Protector );
1558 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1559 // We're only woken when there's something avaliable
1560 us->WaitPointer = NULL;
1562 added = us->RetStatus;
1564 // Get the lock again
1565 SHORTLOCK( &Sem->Protector );
1570 // Figure out how much we need to take off
1571 if( Sem->MaxValue && Sem->Value + AmmountToAdd > Sem->MaxValue)
1572 added = Sem->MaxValue - Sem->Value;
1574 added = AmmountToAdd;
1575 Sem->Value += added;
1578 // While there are items avaliable, and there are thread waiting
1579 // wake the first thread and give it what it wants (or what's left)
1580 while( Sem->Value && Sem->Waiting )
1582 tThread *toWake = Sem->Waiting;
1584 // Remove thread from list (double ended, so clear LastWaiting if needed)
1585 Sem->Waiting = Sem->Waiting->Next;
1586 if( Sem->Waiting == NULL )
1587 Sem->LastWaiting = NULL;
1589 // Figure out how much to give to woken thread
1590 // - Requested count is stored in ->RetStatus
1591 if( toWake->RetStatus && Sem->Value > toWake->RetStatus )
1592 given = toWake->RetStatus;
1595 Sem->Value -= given;
1597 // Save the number we gave to the thread's status
1598 toWake->RetStatus = given;
1600 if(toWake->bInstrTrace)
1601 Log("%s(%i) given %i from %p", toWake->ThreadName, toWake->TID, given, Sem);
1602 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1603 Log("%p (%i %s) woken by signal on %p %s:%s",
1604 toWake, toWake->TID, toWake->ThreadName,
1605 Sem, Sem->ModName, Sem->Name);
1609 SHORTLOCK( &glThreadListLock );
1610 if( toWake->Status != THREAD_STAT_ACTIVE )
1611 Threads_AddActive(toWake);
1613 Warning("Thread %p (%i %s) is already awake", toWake, toWake->TID, toWake->ThreadName);
1614 SHORTREL( &glThreadListLock );
1616 SHORTREL( &Sem->Protector );
1622 // Get the current value of a semaphore
1624 int Semaphore_GetValue(tSemaphore *Sem)
1630 EXPORT(Threads_GetUID);
1631 EXPORT(Threads_GetGID);
1632 EXPORT(Mutex_Acquire);
1633 EXPORT(Mutex_Release);
1634 EXPORT(Mutex_IsLocked);
1635 EXPORT(Semaphore_Init);
1636 EXPORT(Semaphore_Wait);
1637 EXPORT(Semaphore_Signal);