4 * - Common Thread Control
12 #define DEBUG_TRACE_TICKETS 0 // Trace ticket counts
13 #define DEBUG_TRACE_STATE 0 // Trace state changes (sleep/wake)
17 #define SCHED_LOTTERY 1 // Lottery scheduler
18 #define SCHED_RR_SIM 2 // Single Queue Round Robin
19 #define SCHED_RR_PRI 3 // Multi Queue Round Robin
21 #define SCHEDULER_TYPE SCHED_LOTTERY
24 #define DEFAULT_QUANTUM 10
25 #define DEFAULT_PRIORITY 5
26 #define MIN_PRIORITY 10
27 const enum eConfigTypes cCONFIG_TYPES[] = {
28 CFGT_HEAPSTR, // e.g. CFG_VFS_CWD
29 CFGT_INT, // e.g. CFG_VFS_MAXFILES
34 extern void ArchThreads_Init(void);
35 extern void Proc_CallFaultHandler(tThread *Thread);
36 extern void Proc_DumpThreadCPUState(tThread *Thread);
37 extern int GetCPUNum(void);
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_Fault(int Num);
63 void Threads_SegFault(tVAddr Addr);
65 int Threads_GetPID(void);
66 int Threads_GetTID(void);
67 tUID Threads_GetUID(void);
68 tGID Threads_GetGID(void);
69 int Threads_SetUID(Uint *Errno, tUID ID);
70 int Threads_SetGID(Uint *Errno, tUID ID);
72 void Threads_Dump(void);
73 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 // Create Initial Task
126 #if SCHEDULER_TYPE == SCHED_RR_PRI
127 gaActiveThreads[gThreadZero.Priority] = &gThreadZero;
129 gActiveThreads = &gThreadZero;
132 gAllThreads = &gThreadZero;
133 giNumActiveThreads = 1;
139 * \fn void Threads_SetName(const char *NewName)
140 * \brief Sets the current thread's name
141 * \param NewName New name for the thread
142 * \return Boolean Failure
144 int Threads_SetName(const char *NewName)
146 tThread *cur = Proc_GetCurThread();
147 char *oldname = cur->ThreadName;
149 // NOTE: There is a possibility of non-thread safety here
150 // A thread could read the current name pointer before it is zeroed
152 cur->ThreadName = NULL;
154 if( IsHeap(oldname) ) free( oldname );
156 cur->ThreadName = strdup(NewName);
161 * \fn char *Threads_GetName(int ID)
162 * \brief Gets a thread's name
163 * \param ID Thread ID (-1 indicates current thread)
164 * \return Pointer to name
165 * \retval NULL Failure
167 char *Threads_GetName(tTID ID)
170 return Proc_GetCurThread()->ThreadName;
172 return Threads_GetThread(ID)->ThreadName;
176 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
177 * \brief Sets the priority of a task
178 * \param Thread Thread to update ticket count (NULL means current thread)
179 * \param Pri New priority
181 void Threads_SetPriority(tThread *Thread, int Pri)
183 // Get current thread
184 if(Thread == NULL) Thread = Proc_GetCurThread();
186 // - If < 0, set to lowest priority
187 if(Pri < 0) Pri = MIN_PRIORITY;
188 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
190 // Do we actually have to do anything?
191 if( Pri == Thread->Priority ) return;
193 #if SCHEDULER_TYPE == SCHED_RR_PRI
194 SHORTLOCK( &glThreadListLock );
195 // Remove from old priority
196 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
198 Thread->Next = gaActiveThreads[Pri];
199 gaActiveThreads[Pri] = Thread;
200 Thread->Priority = Pri;
201 SHORTREL( &glThreadListLock );
203 // If this isn't the current thread, we need to lock
204 if( Thread != Proc_GetCurThread() )
206 SHORTLOCK( &glThreadListLock );
208 #if SCHEDULER_TYPE == SCHED_LOTTERY
209 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
210 # if DEBUG_TRACE_TICKETS
211 Log("Threads_SetTickets: new giFreeTickets = %i", giFreeTickets);
214 Thread->Priority = Pri;
215 SHORTREL( &glThreadListLock );
218 Thread->Priority = Pri;
223 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
224 * \brief Clone the TCB of the current thread
225 * \param Err Error pointer
226 * \param Flags Flags for something... (What is this for?)
228 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
232 cur = Proc_GetCurThread();
234 // Allocate and duplicate
235 new = malloc(sizeof(tThread));
240 memcpy(new, cur, sizeof(tThread));
244 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
245 new->Status = THREAD_STAT_PREINIT;
249 new->TID = giNextTID++;
253 new->ThreadName = strdup(cur->ThreadName);
255 // Set Thread Group ID (PID)
257 new->TGID = new->TID;
259 new->TGID = cur->TGID;
261 // Messages are not inherited
262 new->Messages = NULL;
263 new->LastMessage = NULL;
266 new->Remaining = new->Quantum = cur->Quantum;
267 new->Priority = cur->Priority;
269 // Set Signal Handlers
270 new->CurFaultNum = 0;
271 new->FaultHandler = cur->FaultHandler;
273 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
275 switch(cCONFIG_TYPES[i])
278 new->Config[i] = cur->Config[i];
282 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
289 // Maintain a global list of threads
290 SHORTLOCK( &glThreadListLock );
291 new->GlobalPrev = NULL; // Protect against bugs
292 new->GlobalNext = gAllThreads;
293 gAllThreads->GlobalPrev = new;
295 SHORTREL( &glThreadListLock );
301 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
302 * \brief Clone the TCB of the current thread
304 tThread *Threads_CloneThreadZero(void)
308 cur = Proc_GetCurThread();
310 // Allocate and duplicate
311 new = malloc(sizeof(tThread));
315 memcpy(new, &gThreadZero, sizeof(tThread));
319 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
320 new->Status = THREAD_STAT_PREINIT;
324 new->TID = giNextTID++;
328 new->ThreadName = NULL;
330 // Messages are not inherited
331 new->Messages = NULL;
332 new->LastMessage = NULL;
335 new->Remaining = new->Quantum = cur->Quantum;
336 new->Priority = cur->Priority;
338 // Set Signal Handlers
339 new->CurFaultNum = 0;
340 new->FaultHandler = cur->FaultHandler;
342 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
344 switch(cCONFIG_TYPES[i])
347 new->Config[i] = cur->Config[i];
351 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
358 // Maintain a global list of threads
359 SHORTLOCK( &glThreadListLock );
360 new->GlobalPrev = NULL; // Protect against bugs
361 new->GlobalNext = gAllThreads;
362 gAllThreads->GlobalPrev = new;
364 SHORTREL( &glThreadListLock );
370 * \brief Get a configuration pointer from the Per-Thread data area
371 * \param ID Config slot ID
372 * \return Pointer at ID
374 Uint *Threads_GetCfgPtr(int ID)
376 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
377 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
381 return &Proc_GetCurThread()->Config[ID];
385 * \brief Wait for a task to change state
386 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
387 * \param Status Thread return status
388 * \return TID of child that changed state
390 tTID Threads_WaitTID(int TID, int *Status)
394 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
398 // Any peer/child thread
400 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
406 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
412 tThread *t = Threads_GetThread(TID);
413 int initStatus = t->Status;
416 // Wait for the thread to die!
417 if(initStatus != THREAD_STAT_ZOMBIE) {
418 // TODO: Handle child also being suspended if wanted
419 while(t->Status != THREAD_STAT_ZOMBIE) {
421 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
422 Threads_GetTID(), t->TID, t->Status);
427 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
428 Threads_GetTID(), t->TID, t->Status);
432 case THREAD_STAT_ZOMBIE:
434 t->Status = THREAD_STAT_DEAD;
435 // TODO: Child return value?
436 if(Status) *Status = t->RetStatus;
437 // add to delete queue
438 Threads_AddToDelete( t );
441 if(Status) *Status = -1;
451 * \brief Gets a thread given its TID
452 * \param TID Thread ID
453 * \return Thread pointer
455 tThread *Threads_GetThread(Uint TID)
459 // Search global list
460 for(thread = gAllThreads;
462 thread = thread->GlobalNext)
464 if(thread->TID == TID)
468 Log("Unable to find TID %i on main list\n", TID);
474 * \brief Adds a thread to the delete queue
475 * \param Thread Thread to delete
477 void Threads_AddToDelete(tThread *Thread)
479 // Add to delete queue
480 // TODO: Is locking needed?
482 Thread->Next = gDeleteThreads;
483 gDeleteThreads = Thread;
486 gDeleteThreads = Thread;
491 * \brief Deletes an entry from a list
492 * \param List Pointer to the list head
493 * \param Thread Thread to find
496 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
498 tThread *ret, *prev = NULL;
501 ret && ret != Thread;
502 prev = ret, ret = ret->Next
505 // Is the thread on the list
507 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
512 *List = Thread->Next;
513 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
516 prev->Next = Thread->Next;
517 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
524 * \brief Exit the current process (or another?)
525 * \param TID Thread ID to kill
526 * \param Status Exit status
528 void Threads_Exit(int TID, int Status)
531 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
533 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
535 // Halt forever, just in case
540 * \fn void Threads_Kill(tThread *Thread, int Status)
541 * \brief Kill a thread
542 * \param Thread Thread to kill
543 * \param Status Status code to return to the parent
545 void Threads_Kill(tThread *Thread, int Status)
548 int isCurThread = Thread == Proc_GetCurThread();
550 // TODO: Kill all children
554 // TODO: I should keep a .Parent pointer, and a .Children list
555 for(child = gAllThreads;
557 child = child->GlobalNext)
559 if(child->Parent == Thread)
560 Threads_Kill(child, -1);
565 ///\note Double lock is needed due to overlap of lock areas
567 // Lock thread (stop us recieving messages)
568 SHORTLOCK( &Thread->IsLocked );
570 // Clear Message Queue
571 while( Thread->Messages )
573 msg = Thread->Messages->Next;
574 free( Thread->Messages );
575 Thread->Messages = msg;
579 SHORTLOCK( &glThreadListLock );
581 switch(Thread->Status)
583 case THREAD_STAT_PREINIT: // Only on main list
586 // Currently active thread
587 case THREAD_STAT_ACTIVE:
588 #if SCHEDULER_TYPE == SCHED_RR_PRI
589 if( Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
591 if( Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
594 // Ensure that we are not rescheduled
595 Thread->Remaining = 0; // Clear Remaining Quantum
596 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
598 // Update bookkeeping
599 giNumActiveThreads --;
600 #if SCHEDULER_TYPE == SCHED_LOTTERY
601 if( Thread != Proc_GetCurThread() )
602 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
607 Log_Warning("Threads",
608 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
609 Thread, Thread->TID, Thread->ThreadName
613 // Kill it while it sleeps!
614 case THREAD_STAT_SLEEPING:
615 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
617 Log_Warning("Threads",
618 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
619 Thread, Thread->TID, Thread->ThreadName
624 // Brains!... You cannot kill
625 case THREAD_STAT_ZOMBIE:
626 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
627 Thread, Thread->TID, Thread->ThreadName);
628 SHORTREL( &glThreadListLock );
629 SHORTREL( &Thread->IsLocked );
633 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
639 Thread->RetStatus = Status;
641 // Don't Zombie if we are being killed because our parent is
644 Thread->Status = THREAD_STAT_DEAD;
645 Threads_AddToDelete( Thread );
647 Thread->Status = THREAD_STAT_ZOMBIE;
649 Threads_Wake( Thread->Parent );
652 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
655 SHORTREL( &glThreadListLock );
656 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
666 * \brief Yield remainder of the current thread's timeslice
668 void Threads_Yield(void)
670 tThread *thread = Proc_GetCurThread();
671 thread->Remaining = 0;
672 //while(thread->Remaining == 0)
677 * \fn void Threads_Sleep(void)
678 * \brief Take the current process off the run queue
680 void Threads_Sleep(void)
682 tThread *cur = Proc_GetCurThread();
685 SHORTLOCK( &glThreadListLock );
687 // Don't sleep if there is a message waiting
688 if( cur->Messages ) {
689 SHORTREL( &glThreadListLock );
693 // Remove us from running queue
695 // Mark thread as sleeping
696 cur->Status = THREAD_STAT_SLEEPING;
698 // Add to Sleeping List (at the top)
699 cur->Next = gSleepingThreads;
700 gSleepingThreads = cur;
703 #if DEBUG_TRACE_STATE
704 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
708 SHORTREL( &glThreadListLock );
710 while(cur->Status != THREAD_STAT_ACTIVE) HALT();
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_WAITING:
746 Warning("Threads_Wake - Waiting threads are not currently supported");
749 case THREAD_STAT_DEAD:
750 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
754 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
760 * \brief Wake a thread given the TID
761 * \param TID Thread ID to wake
762 * \return Boolean Faulure (errno)
764 int Threads_WakeTID(tTID TID)
766 tThread *thread = Threads_GetThread(TID);
770 ret = Threads_Wake( thread );
771 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
776 * \brief Adds a thread to the active queue
778 void Threads_AddActive(tThread *Thread)
780 SHORTLOCK( &glThreadListLock );
782 if( Thread->Status == THREAD_STAT_ACTIVE ) {
783 tThread *cur = Proc_GetCurThread();
784 Warning("WTF, CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
785 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
786 SHORTREL( &glThreadListLock );
791 Thread->Status = THREAD_STAT_ACTIVE;
792 // Add to active list
793 #if SCHEDULER_TYPE == SCHED_RR_PRI
794 Thread->Next = gaActiveThreads[Thread->Priority];
795 gaActiveThreads[Thread->Priority] = Thread;
797 Thread->Next = gActiveThreads;
798 gActiveThreads = Thread;
801 // Update bookkeeping
802 giNumActiveThreads ++;
804 #if SCHEDULER_TYPE == SCHED_LOTTERY
807 // Only change the ticket count if the thread is un-scheduled
808 if(Thread->CurCPU != -1)
811 delta = caiTICKET_COUNTS[ Thread->Priority ];
813 giFreeTickets += delta;
814 # if DEBUG_TRACE_TICKETS
815 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
816 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
823 SHORTREL( &glThreadListLock );
827 * \brief Removes the current thread from the active queue
828 * \warning This should ONLY be called with task switches disabled
829 * \return Current thread pointer
831 tThread *Threads_RemActive(void)
833 tThread *ret = Proc_GetCurThread();
835 SHORTLOCK( &glThreadListLock );
837 // Delete from active queue
838 #if SCHEDULER_TYPE == SCHED_RR_PRI
839 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
841 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
844 SHORTREL( &glThreadListLock );
851 giNumActiveThreads --;
852 // no need to decrement tickets, scheduler did it for us
854 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
855 Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
856 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
859 SHORTREL( &glThreadListLock );
865 * \fn void Threads_SetFaultHandler(Uint Handler)
866 * \brief Sets the signal handler for a signal
868 void Threads_SetFaultHandler(Uint Handler)
870 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
871 Proc_GetCurThread()->FaultHandler = Handler;
875 * \fn void Threads_Fault(int Num)
876 * \brief Calls a fault handler
878 void Threads_Fault(int Num)
880 tThread *thread = Proc_GetCurThread();
882 Log_Log("Threads", "Threads_Fault: thread = %p", thread);
886 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
888 switch(thread->FaultHandler)
891 Threads_Kill(thread, -1);
894 case 1: // Dump Core?
895 Threads_Kill(thread, -1);
900 // Double Fault? Oh, F**k
901 if(thread->CurFaultNum != 0) {
902 Threads_Kill(thread, -1); // For now, just kill
906 thread->CurFaultNum = Num;
908 Proc_CallFaultHandler(thread);
912 * \fn void Threads_SegFault(tVAddr Addr)
913 * \brief Called when a Segment Fault occurs
915 void Threads_SegFault(tVAddr Addr)
917 Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
919 //Threads_Exit( 0, -1 );
922 // --- Process Structure Access Functions ---
923 tPID Threads_GetPID(void)
925 return Proc_GetCurThread()->TGID;
927 tTID Threads_GetTID(void)
929 return Proc_GetCurThread()->TID;
931 tUID Threads_GetUID(void)
933 return Proc_GetCurThread()->UID;
935 tGID Threads_GetGID(void)
937 return Proc_GetCurThread()->GID;
940 int Threads_SetUID(Uint *Errno, tUID ID)
942 tThread *t = Proc_GetCurThread();
947 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
952 int Threads_SetGID(Uint *Errno, tGID ID)
954 tThread *t = Proc_GetCurThread();
959 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
965 * \fn void Threads_Dump(void)
967 void Threads_DumpActive(void)
970 #if SCHEDULER_TYPE == SCHED_RR_PRI
974 Log("Active Threads: (%i reported)", giNumActiveThreads);
976 #if SCHEDULER_TYPE == SCHED_RR_PRI
977 for( i = 0; i < MIN_PRIORITY+1; i++ )
979 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
981 for(thread=gActiveThreads;thread;thread=thread->Next)
984 Log(" %p %i (%i) - %s (CPU %i)",
985 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
986 if(thread->Status != THREAD_STAT_ACTIVE)
987 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
988 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
989 Log(" KStack 0x%x", thread->KernelStack);
990 Proc_DumpThreadCPUState(thread);
993 #if SCHEDULER_TYPE == SCHED_RR_PRI
999 * \fn void Threads_Dump(void)
1000 * \brief Dumps a list of currently running threads
1002 void Threads_Dump(void)
1006 Log("--- Thread Dump ---");
1007 Threads_DumpActive();
1009 Log("All Threads:");
1010 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1012 Log(" %p %i (%i) - %s (CPU %i)",
1013 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1014 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1015 switch(thread->Status)
1017 case THREAD_STAT_MUTEXSLEEP:
1018 Log(" Mutex Pointer: %p", thread->WaitPointer);
1020 case THREAD_STAT_SEMAPHORESLEEP:
1021 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1022 Log(" Semaphore Name: %s:%s",
1023 ((tSemaphore*)thread->WaitPointer)->ModName,
1024 ((tSemaphore*)thread->WaitPointer)->Name
1027 case THREAD_STAT_ZOMBIE:
1028 Log(" Return Status: %i", thread->RetStatus);
1032 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1033 Log(" KStack 0x%x", thread->KernelStack);
1038 * \brief Gets the next thread to run
1039 * \param CPU Current CPU
1040 * \param Last The thread the CPU was running
1042 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1046 // If this CPU has the lock, we must let it complete
1047 if( CPU_HAS_LOCK( &glThreadListLock ) )
1050 // Don't change threads if the current CPU has switches disabled
1051 if( gaThreads_NoTaskSwitch[CPU] )
1056 SHORTLOCK( &glThreadListLock );
1058 // Clear Delete Queue
1059 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
1060 // DEFINITELY - free() can deadlock in this case
1061 while(gDeleteThreads)
1063 thread = gDeleteThreads->Next;
1064 // Only free if structure is unused
1065 if( !IS_LOCKED(&gDeleteThreads->IsLocked) )
1068 gDeleteThreads->Status = THREAD_STAT_BURIED;
1070 if( IsHeap(gDeleteThreads->ThreadName) )
1071 free(gDeleteThreads->ThreadName);
1072 // Remove from global list
1073 if( gDeleteThreads == gAllThreads )
1074 gAllThreads = gDeleteThreads->GlobalNext;
1076 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
1077 free( gDeleteThreads );
1079 gDeleteThreads = thread;
1082 // No active threads, just take a nap
1083 if(giNumActiveThreads == 0) {
1084 SHORTREL( &glThreadListLock );
1085 #if DEBUG_TRACE_TICKETS
1086 Log("No active threads");
1091 #if SCHEDULER_TYPE != SCHED_RR_PRI
1092 // Special case: 1 thread
1093 if(giNumActiveThreads == 1) {
1094 if( gActiveThreads->CurCPU == -1 )
1095 gActiveThreads->CurCPU = CPU;
1097 SHORTREL( &glThreadListLock );
1099 if( gActiveThreads->CurCPU == CPU )
1100 return gActiveThreads;
1102 return NULL; // CPU has nothing to do
1106 // Allow the old thread to be scheduled again
1108 if( Last->Status == THREAD_STAT_ACTIVE ) {
1109 #if SCHEDULER_TYPE == SCHED_LOTTERY
1110 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1111 # if DEBUG_TRACE_TICKETS
1112 LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1113 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1114 caiTICKET_COUNTS[ Last->Priority ]);
1118 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1120 LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released)\n",
1121 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1127 // Lottery Scheduler
1129 #if SCHEDULER_TYPE == SCHED_LOTTERY
1134 for(thread = gActiveThreads; thread; thread = thread->Next) {
1135 if(thread->CurCPU >= 0) continue;
1136 if(thread->Status != THREAD_STAT_ACTIVE)
1137 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1138 thread, thread->TID, thread->ThreadName, thread->Status);
1139 if(thread->Next == thread) {
1140 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1141 thread, thread->TID, thread->ThreadName, thread->Status);
1143 number += caiTICKET_COUNTS[ thread->Priority ];
1145 if(number != giFreeTickets) {
1146 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1147 giFreeTickets, number, CPU);
1151 // No free tickets (all tasks delegated to cores)
1152 if( giFreeTickets == 0 ) {
1153 SHORTREL(&glThreadListLock);
1157 // Get the ticket number
1158 ticket = number = rand() % giFreeTickets;
1160 // Find the next thread
1161 for(thread=gActiveThreads;thread;thread=thread->Next)
1163 if(thread->CurCPU >= 0) continue;
1164 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1165 number -= caiTICKET_COUNTS[ thread->Priority ];
1168 // If we didn't find a thread, something went wrong
1172 for(thread=gActiveThreads;thread;thread=thread->Next) {
1173 if(thread->CurCPU >= 0) continue;
1174 number += caiTICKET_COUNTS[ thread->Priority ];
1176 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1177 giFreeTickets, number);
1180 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1181 # if DEBUG_TRACE_TICKETS
1182 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1183 CPU, thread, thread->TID, thread->ThreadName,
1184 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1189 // Priority based round robin scheduler
1191 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1194 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1196 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1198 if( thread->CurCPU == -1 ) break;
1200 // If we fall onto the same queue again, special handling is
1202 if( i == Last->Priority ) {
1203 tThread *savedThread = thread;
1205 // Find the next unscheduled thread in the list
1206 for( thread = Last->Next; thread; thread = thread->Next )
1208 if( thread->CurCPU == -1 ) break;
1210 // If we don't find anything after, just use the one
1212 if( !thread ) thread = savedThread;
1214 // Found a thread? Schedule it!
1220 SHORTREL(&glThreadListLock);
1224 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1226 // Find the next unscheduled thread in the list
1227 for( thread = Last->Next; thread; thread = thread->Next )
1229 if( thread->CurCPU == -1 ) break;
1231 // If we don't find anything after, search from the beginning
1234 for(thread = gActiveThreads; thread; thread = thread->Next)
1236 if( thread->CurCPU == -1 ) break;
1242 SHORTREL(&glThreadListLock);
1247 # error "Unimplemented scheduling algorithm"
1250 // Make the new thread non-schedulable
1251 thread->CurCPU = CPU;
1253 SHORTREL( &glThreadListLock );
1259 * \brief Acquire a heavy mutex
1260 * \param Mutex Mutex to acquire
1262 * This type of mutex checks if the mutex is avaliable, and acquires it
1263 * if it is. Otherwise, the current thread is added to the mutex's wait
1264 * queue and the thread suspends. When the holder of the mutex completes,
1265 * the oldest thread (top thread) on the queue is given the lock and
1268 int Mutex_Acquire(tMutex *Mutex)
1270 tThread *us = Proc_GetCurThread();
1273 SHORTLOCK( &Mutex->Protector );
1275 //Log("Mutex_Acquire: (%p)", Mutex);
1277 // Check if the lock is already held
1278 if( Mutex->Owner ) {
1279 SHORTLOCK( &glThreadListLock );
1280 // - Remove from active list
1281 us = Threads_RemActive();
1283 // - Mark as sleeping
1284 us->Status = THREAD_STAT_MUTEXSLEEP;
1285 us->WaitPointer = Mutex;
1288 if(Mutex->LastWaiting) {
1289 Mutex->LastWaiting->Next = us;
1290 Mutex->LastWaiting = us;
1293 Mutex->Waiting = us;
1294 Mutex->LastWaiting = us;
1300 for( t = Mutex->Waiting; t; t = t->Next, i++ )
1301 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1302 t, t->TID, t->ThreadName);
1306 SHORTREL( &glThreadListLock );
1307 SHORTREL( &Mutex->Protector );
1308 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1309 // We're only woken when we get the lock
1310 us->WaitPointer = NULL;
1312 // Ooh, let's take it!
1315 SHORTREL( &Mutex->Protector );
1319 extern tMutex glPhysAlloc;
1320 if( Mutex != &glPhysAlloc )
1321 LogF("Mutex %p taken by %i %p\n", Mutex, us->TID, __builtin_return_address(0));
1328 * \brief Release a held mutex
1329 * \param Mutex Mutex to release
1330 * \note Releasing a non-held mutex has no effect
1332 void Mutex_Release(tMutex *Mutex)
1334 SHORTLOCK( &Mutex->Protector );
1335 //Log("Mutex_Release: (%p)", Mutex);
1336 if( Mutex->Waiting ) {
1337 Mutex->Owner = Mutex->Waiting; // Set owner
1338 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1339 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1340 // 2010-10-02 21:50 - Comemerating the death of the longest single
1341 // blocker in the Acess2 history. REMEMBER TO
1342 // FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1343 if( Mutex->LastWaiting == Mutex->Owner )
1344 Mutex->LastWaiting = NULL;
1347 SHORTLOCK( &glThreadListLock );
1348 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1349 Threads_AddActive(Mutex->Owner);
1350 SHORTREL( &glThreadListLock );
1353 Mutex->Owner = NULL;
1355 SHORTREL( &Mutex->Protector );
1358 extern tMutex glPhysAlloc;
1359 if( Mutex != &glPhysAlloc )
1360 LogF("Mutex %p released by %i %p\n", Mutex, Threads_GetTID(), __builtin_return_address(0));
1365 * \brief Is this mutex locked?
1366 * \param Mutex Mutex pointer
1368 int Mutex_IsLocked(tMutex *Mutex)
1370 return Mutex->Owner != NULL;
1374 // Initialise a semaphore
1376 void Semaphore_Init(tSemaphore *Sem, int Value, int MaxValue, const char *Module, const char *Name)
1378 memset(Sem, 0, sizeof(tSemaphore));
1380 Sem->ModName = Module;
1382 Sem->MaxValue = MaxValue;
1385 // Wait for items to be avaliable
1387 int Semaphore_Wait(tSemaphore *Sem, int MaxToTake)
1391 if( MaxToTake < 0 ) {
1392 Log_Warning("Threads", "Semaphore_Wait: User bug - MaxToTake(%i) < 0, Sem=%p(%s)",
1393 MaxToTake, Sem, Sem->Name);
1396 SHORTLOCK( &Sem->Protector );
1398 // Check if there's already items avaliable
1399 if( Sem->Value > 0 ) {
1400 // Take what we need
1401 if( MaxToTake && Sem->Value > MaxToTake )
1405 Sem->Value -= taken;
1406 SHORTREL( &Sem->Protector );
1410 SHORTLOCK( &glThreadListLock );
1412 // - Remove from active list
1413 us = Threads_RemActive();
1415 // - Mark as sleeping
1416 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1417 us->WaitPointer = Sem;
1418 us->RetStatus = MaxToTake; // Use RetStatus as a temp variable
1421 if(Sem->LastWaiting) {
1422 Sem->LastWaiting->Next = us;
1423 Sem->LastWaiting = us;
1427 Sem->LastWaiting = us;
1430 SHORTREL( &glThreadListLock );
1431 SHORTREL( &Sem->Protector );
1432 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1433 // We're only woken when there's something avaliable
1434 us->WaitPointer = NULL;
1436 taken = us->RetStatus;
1438 // Get the lock again
1439 SHORTLOCK( &Sem->Protector );
1442 // While there is space, and there are thread waiting
1443 // wake the first thread and give it what it wants (or what's left)
1444 while( (Sem->MaxValue == 0 || Sem->Value < Sem->MaxValue) && Sem->Signaling )
1447 tThread *toWake = Sem->Signaling;
1449 Sem->Signaling = Sem->Signaling->Next;
1450 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1451 if( Sem->Signaling == NULL )
1452 Sem->LastSignaling = NULL;
1454 // Figure out how much to give
1455 if( toWake->RetStatus && Sem->Value + toWake->RetStatus < Sem->MaxValue )
1456 given = toWake->RetStatus;
1458 given = Sem->MaxValue - Sem->Value;
1459 Sem->Value -= given;
1461 // Save the number we gave to the thread's status
1462 toWake->RetStatus = given;
1465 SHORTLOCK( &glThreadListLock );
1466 if( toWake->Status != THREAD_STAT_ACTIVE )
1467 Threads_AddActive(toWake);
1468 SHORTREL( &glThreadListLock );
1470 SHORTREL( &Sem->Protector );
1476 // Add items to a semaphore
1478 int Semaphore_Signal(tSemaphore *Sem, int AmmountToAdd)
1483 if( AmmountToAdd < 0 ) {
1484 Log_Warning("Threads", "Semaphore_Signal: User bug - AmmountToAdd(%i) < 0, Sem=%p(%s)",
1485 AmmountToAdd, Sem, Sem->Name);
1487 SHORTLOCK( &Sem->Protector );
1489 // Check if we have to block
1490 if( Sem->MaxValue && Sem->Value == Sem->MaxValue )
1494 Log_Debug("Threads", "Semaphore_Signal: IDLE Sem = %s:%s", Sem->ModName, Sem->Name);
1495 Log_Debug("Threads", "Semaphore_Signal: Sem->Value(%i) == Sem->MaxValue(%i)", Sem->Value, Sem->MaxValue);
1498 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 = AmmountToAdd; // Use RetStatus as a temp variable
1508 if(Sem->LastSignaling) {
1509 Sem->LastSignaling->Next = us;
1510 Sem->LastSignaling = us;
1513 Sem->Signaling = us;
1514 Sem->LastSignaling = us;
1517 SHORTREL( &glThreadListLock );
1518 SHORTREL( &Sem->Protector );
1519 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1520 // We're only woken when there's something avaliable
1521 us->WaitPointer = NULL;
1523 added = us->RetStatus;
1525 // Get the lock again
1526 SHORTLOCK( &Sem->Protector );
1531 // Figure out how much we need to take off
1532 if( Sem->MaxValue && Sem->Value + AmmountToAdd > Sem->MaxValue)
1533 added = Sem->MaxValue - Sem->Value;
1535 added = AmmountToAdd;
1536 Sem->Value += added;
1539 // While there are items avaliable, and there are thread waiting
1540 // wake the first thread and give it what it wants (or what's left)
1541 while( Sem->Value && Sem->Waiting )
1543 tThread *toWake = Sem->Waiting;
1545 Sem->Waiting = Sem->Waiting->Next;
1546 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1547 if( Sem->Waiting == NULL )
1548 Sem->LastWaiting = NULL;
1550 // Figure out how much to give
1551 if( toWake->RetStatus && Sem->Value > toWake->RetStatus )
1552 given = toWake->RetStatus;
1555 Sem->Value -= given;
1557 // Save the number we gave to the thread's status
1558 toWake->RetStatus = given;
1561 SHORTLOCK( &glThreadListLock );
1562 if( toWake->Status != THREAD_STAT_ACTIVE )
1563 Threads_AddActive(toWake);
1564 SHORTREL( &glThreadListLock );
1566 SHORTREL( &Sem->Protector );
1572 // Get the current value of a semaphore
1574 int Semaphore_GetValue(tSemaphore *Sem)
1580 EXPORT(Threads_GetUID);
1581 EXPORT(Threads_GetGID);
1582 EXPORT(Mutex_Acquire);
1583 EXPORT(Mutex_Release);
1584 EXPORT(Mutex_IsLocked);
1585 EXPORT(Semaphore_Init);
1586 EXPORT(Semaphore_Wait);
1587 EXPORT(Semaphore_Signal);