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 int GetCPUNum(void);
39 void Threads_Init(void);
41 int Threads_SetName(const char *NewName);
43 char *Threads_GetName(int ID);
45 void Threads_SetPriority(tThread *Thread, int Pri);
46 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
47 int Threads_WaitTID(int TID, int *status);
48 tThread *Threads_GetThread(Uint TID);
50 void Threads_AddToDelete(tThread *Thread);
51 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread);
53 void Threads_Exit(int TID, int Status);
54 void Threads_Kill(tThread *Thread, int Status);
55 void Threads_Yield(void);
56 void Threads_Sleep(void);
57 int Threads_Wake(tThread *Thread);
58 void Threads_AddActive(tThread *Thread);
59 tThread *Threads_RemActive(void);
61 void Threads_Fault(int Num);
62 void Threads_SegFault(tVAddr Addr);
64 int Threads_GetPID(void);
65 int Threads_GetTID(void);
66 tUID Threads_GetUID(void);
67 tGID Threads_GetGID(void);
68 int Threads_SetUID(Uint *Errno, tUID ID);
69 int Threads_SetGID(Uint *Errno, tUID ID);
71 void Threads_Dump(void);
72 void Threads_DumpActive(void);
75 int Mutex_Acquire(tMutex *Mutex);
76 void Mutex_Release(tMutex *Mutex);
77 int Mutex_IsLocked(tMutex *Mutex);
82 // Only used for the core kernel
83 tThread gThreadZero = {
84 Status: THREAD_STAT_ACTIVE, // Status
85 ThreadName: (char*)"ThreadZero", // Name
86 Quantum: DEFAULT_QUANTUM, // Default Quantum
87 Remaining: DEFAULT_QUANTUM, // Current Quantum
88 Priority: DEFAULT_PRIORITY // Number of tickets
92 tShortSpinlock glThreadListLock; ///\note NEVER use a heap function while locked
93 // --- Current State ---
94 volatile int giNumActiveThreads = 0; // Number of threads on the active queue
95 volatile Uint giNextTID = 1; // Next TID to allocate
96 // --- Thread Lists ---
97 tThread *gAllThreads = NULL; // All allocated threads
98 tThread *gSleepingThreads = NULL; // Sleeping Threads
99 tThread *gDeleteThreads = NULL; // Threads to delete
100 int giNumCPUs = 1; // Number of CPUs
101 BOOL gaThreads_NoTaskSwitch[MAX_CPUS]; // Disables task switches for each core (Pseudo-IF)
102 // --- Scheduler Types ---
103 #if SCHEDULER_TYPE == SCHED_LOTTERY
104 const int caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
105 volatile int giFreeTickets = 0; // Number of tickets held by non-scheduled threads
106 tThread *gActiveThreads = NULL; // Currently Running Threads
107 #elif SCHEDULER_TYPE == SCHED_RR_SIM
108 tThread *gActiveThreads = NULL; // Currently Running Threads
109 #elif SCHEDULER_TYPE == SCHED_RR_PRI
110 tThread *gaActiveThreads[MIN_PRIORITY+1]; // Active threads for each priority level
112 # error "Unkown scheduler type"
117 * \fn void Threads_Init(void)
118 * \brief Initialse the thread list
120 void Threads_Init(void)
124 // Create Initial Task
125 #if SCHEDULER_TYPE == SCHED_RR_PRI
126 gaActiveThreads[gThreadZero.Priority] = &gThreadZero;
128 gActiveThreads = &gThreadZero;
131 gAllThreads = &gThreadZero;
132 giNumActiveThreads = 1;
138 * \fn void Threads_SetName(const char *NewName)
139 * \brief Sets the current thread's name
140 * \param NewName New name for the thread
141 * \return Boolean Failure
143 int Threads_SetName(const char *NewName)
145 tThread *cur = Proc_GetCurThread();
146 char *oldname = cur->ThreadName;
148 // NOTE: There is a possibility of non-thread safety here
149 // A thread could read the current name pointer before it is zeroed
151 cur->ThreadName = NULL;
153 if( IsHeap(oldname) ) free( oldname );
155 cur->ThreadName = strdup(NewName);
160 * \fn char *Threads_GetName(int ID)
161 * \brief Gets a thread's name
162 * \param ID Thread ID (-1 indicates current thread)
163 * \return Pointer to name
164 * \retval NULL Failure
166 char *Threads_GetName(tTID ID)
169 return Proc_GetCurThread()->ThreadName;
171 return Threads_GetThread(ID)->ThreadName;
175 * \fn void Threads_SetPriority(tThread *Thread, int Pri)
176 * \brief Sets the priority of a task
177 * \param Thread Thread to update ticket count (NULL means current thread)
178 * \param Pri New priority
180 void Threads_SetPriority(tThread *Thread, int Pri)
182 // Get current thread
183 if(Thread == NULL) Thread = Proc_GetCurThread();
185 // - If < 0, set to lowest priority
186 if(Pri < 0) Pri = MIN_PRIORITY;
187 if(Pri > MIN_PRIORITY) Pri = MIN_PRIORITY;
189 // Do we actually have to do anything?
190 if( Pri == Thread->Priority ) return;
192 #if SCHEDULER_TYPE == SCHED_RR_PRI
193 SHORTLOCK( &glThreadListLock );
194 // Remove from old priority
195 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
197 Thread->Next = gaActiveThreads[Pri];
198 gaActiveThreads[Pri] = Thread;
199 Thread->Priority = Pri;
200 SHORTREL( &glThreadListLock );
202 // If this isn't the current thread, we need to lock
203 if( Thread != Proc_GetCurThread() )
205 SHORTLOCK( &glThreadListLock );
207 #if SCHEDULER_TYPE == SCHED_LOTTERY
208 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
209 # if DEBUG_TRACE_TICKETS
210 Log("Threads_SetTickets: new giFreeTickets = %i", giFreeTickets);
213 Thread->Priority = Pri;
214 SHORTREL( &glThreadListLock );
217 Thread->Priority = Pri;
222 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
223 * \brief Clone the TCB of the current thread
224 * \param Err Error pointer
225 * \param Flags Flags for something... (What is this for?)
227 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
231 cur = Proc_GetCurThread();
233 // Allocate and duplicate
234 new = malloc(sizeof(tThread));
239 memcpy(new, cur, sizeof(tThread));
243 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
244 new->Status = THREAD_STAT_PREINIT;
248 new->TID = giNextTID++;
252 new->ThreadName = strdup(cur->ThreadName);
254 // Set Thread Group ID (PID)
256 new->TGID = new->TID;
258 new->TGID = cur->TGID;
260 // Messages are not inherited
261 new->Messages = NULL;
262 new->LastMessage = NULL;
265 new->Remaining = new->Quantum = cur->Quantum;
266 new->Priority = cur->Priority;
268 // Set Signal Handlers
269 new->CurFaultNum = 0;
270 new->FaultHandler = cur->FaultHandler;
272 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
274 switch(cCONFIG_TYPES[i])
277 new->Config[i] = cur->Config[i];
281 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
288 // Maintain a global list of threads
289 SHORTLOCK( &glThreadListLock );
290 new->GlobalPrev = NULL; // Protect against bugs
291 new->GlobalNext = gAllThreads;
292 gAllThreads->GlobalPrev = new;
294 SHORTREL( &glThreadListLock );
300 * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
301 * \brief Clone the TCB of the current thread
303 tThread *Threads_CloneThreadZero(void)
307 cur = Proc_GetCurThread();
309 // Allocate and duplicate
310 new = malloc(sizeof(tThread));
314 memcpy(new, &gThreadZero, sizeof(tThread));
318 memset( &new->IsLocked, 0, sizeof(new->IsLocked));
319 new->Status = THREAD_STAT_PREINIT;
323 new->TID = giNextTID++;
327 new->ThreadName = NULL;
329 // Messages are not inherited
330 new->Messages = NULL;
331 new->LastMessage = NULL;
334 new->Remaining = new->Quantum = cur->Quantum;
335 new->Priority = cur->Priority;
337 // Set Signal Handlers
338 new->CurFaultNum = 0;
339 new->FaultHandler = cur->FaultHandler;
341 for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
343 switch(cCONFIG_TYPES[i])
346 new->Config[i] = cur->Config[i];
350 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
357 // Maintain a global list of threads
358 SHORTLOCK( &glThreadListLock );
359 new->GlobalPrev = NULL; // Protect against bugs
360 new->GlobalNext = gAllThreads;
361 gAllThreads->GlobalPrev = new;
363 SHORTREL( &glThreadListLock );
369 * \brief Get a configuration pointer from the Per-Thread data area
370 * \param ID Config slot ID
371 * \return Pointer at ID
373 Uint *Threads_GetCfgPtr(int ID)
375 if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
376 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
380 return &Proc_GetCurThread()->Config[ID];
384 * \brief Wait for a task to change state
385 * \param TID Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
386 * \param Status Thread return status
387 * \return TID of child that changed state
389 tTID Threads_WaitTID(int TID, int *Status)
393 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
397 // Any peer/child thread
399 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
405 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
411 tThread *t = Threads_GetThread(TID);
412 int initStatus = t->Status;
415 // Wait for the thread to die!
416 if(initStatus != THREAD_STAT_ZOMBIE) {
417 // TODO: Handle child also being suspended if wanted
418 while(t->Status != THREAD_STAT_ZOMBIE) {
420 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
421 Threads_GetTID(), t->TID, t->Status);
426 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
427 Threads_GetTID(), t->TID, t->Status);
431 case THREAD_STAT_ZOMBIE:
433 t->Status = THREAD_STAT_DEAD;
434 // TODO: Child return value?
435 if(Status) *Status = t->RetStatus;
436 // add to delete queue
437 Threads_AddToDelete( t );
440 if(Status) *Status = -1;
450 * \brief Gets a thread given its TID
451 * \param TID Thread ID
452 * \return Thread pointer
454 tThread *Threads_GetThread(Uint TID)
458 // Search global list
459 for(thread = gAllThreads;
461 thread = thread->GlobalNext)
463 if(thread->TID == TID)
467 Log("Unable to find TID %i on main list\n", TID);
473 * \brief Adds a thread to the delete queue
474 * \param Thread Thread to delete
476 void Threads_AddToDelete(tThread *Thread)
478 // Add to delete queue
479 // TODO: Is locking needed?
481 Thread->Next = gDeleteThreads;
482 gDeleteThreads = Thread;
485 gDeleteThreads = Thread;
490 * \brief Deletes an entry from a list
491 * \param List Pointer to the list head
492 * \param Thread Thread to find
495 tThread *Threads_int_DelFromQueue(tThread **List, tThread *Thread)
497 tThread *ret, *prev = NULL;
500 ret && ret != Thread;
501 prev = ret, ret = ret->Next
504 // Is the thread on the list
506 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
511 *List = Thread->Next;
512 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
515 prev->Next = Thread->Next;
516 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
523 * \brief Exit the current process (or another?)
524 * \param TID Thread ID to kill
525 * \param Status Exit status
527 void Threads_Exit(int TID, int Status)
530 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
532 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
534 // Halt forever, just in case
539 * \fn void Threads_Kill(tThread *Thread, int Status)
540 * \brief Kill a thread
541 * \param Thread Thread to kill
542 * \param Status Status code to return to the parent
544 void Threads_Kill(tThread *Thread, int Status)
547 int isCurThread = Thread == Proc_GetCurThread();
549 // TODO: Kill all children
553 // TODO: I should keep a .Parent pointer, and a .Children list
554 for(child = gAllThreads;
556 child = child->GlobalNext)
558 if(child->Parent == Thread)
559 Threads_Kill(child, -1);
564 ///\note Double lock is needed due to overlap of lock areas
566 // Lock thread (stop us recieving messages)
567 SHORTLOCK( &Thread->IsLocked );
569 // Clear Message Queue
570 while( Thread->Messages )
572 msg = Thread->Messages->Next;
573 free( Thread->Messages );
574 Thread->Messages = msg;
578 SHORTLOCK( &glThreadListLock );
580 switch(Thread->Status)
582 case THREAD_STAT_PREINIT: // Only on main list
585 // Currently active thread
586 case THREAD_STAT_ACTIVE:
587 #if SCHEDULER_TYPE == SCHED_RR_PRI
588 if( Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread ) )
590 if( Threads_int_DelFromQueue( &gActiveThreads, Thread ) )
593 // Ensure that we are not rescheduled
594 Thread->Remaining = 0; // Clear Remaining Quantum
595 Thread->Quantum = 0; // Clear Quantum to indicate dead thread
597 // Update bookkeeping
598 giNumActiveThreads --;
599 #if SCHEDULER_TYPE == SCHED_LOTTERY
600 if( Thread != Proc_GetCurThread() )
601 giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
606 Log_Warning("Threads",
607 "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
608 Thread, Thread->TID, Thread->ThreadName
612 // Kill it while it sleeps!
613 case THREAD_STAT_SLEEPING:
614 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
616 Log_Warning("Threads",
617 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
618 Thread, Thread->TID, Thread->ThreadName
623 // Brains!... You cannot kill
624 case THREAD_STAT_ZOMBIE:
625 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
626 Thread, Thread->TID, Thread->ThreadName);
627 SHORTREL( &glThreadListLock );
628 SHORTREL( &Thread->IsLocked );
632 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
638 Thread->RetStatus = Status;
640 // Don't Zombie if we are being killed because our parent is
643 Thread->Status = THREAD_STAT_DEAD;
644 Threads_AddToDelete( Thread );
646 Thread->Status = THREAD_STAT_ZOMBIE;
648 Threads_Wake( Thread->Parent );
651 Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
654 SHORTREL( &glThreadListLock );
655 SHORTREL( &Thread->IsLocked ); // TODO: We may not actually be released...
665 * \brief Yield remainder of the current thread's timeslice
667 void Threads_Yield(void)
669 tThread *thread = Proc_GetCurThread();
670 thread->Remaining = 0;
671 //while(thread->Remaining == 0)
676 * \fn void Threads_Sleep(void)
677 * \brief Take the current process off the run queue
679 void Threads_Sleep(void)
681 tThread *cur = Proc_GetCurThread();
684 SHORTLOCK( &glThreadListLock );
686 // Don't sleep if there is a message waiting
687 if( cur->Messages ) {
688 SHORTREL( &glThreadListLock );
692 // Remove us from running queue
694 // Mark thread as sleeping
695 cur->Status = THREAD_STAT_SLEEPING;
697 // Add to Sleeping List (at the top)
698 cur->Next = gSleepingThreads;
699 gSleepingThreads = cur;
702 #if DEBUG_TRACE_STATE
703 Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
707 SHORTREL( &glThreadListLock );
709 while(cur->Status != THREAD_STAT_ACTIVE) HALT();
714 * \fn int Threads_Wake( tThread *Thread )
715 * \brief Wakes a sleeping/waiting thread up
716 * \param Thread Thread to wake
717 * \return Boolean Failure (Returns ERRNO)
718 * \warning This should ONLY be called with task switches disabled
720 int Threads_Wake(tThread *Thread)
725 switch(Thread->Status)
727 case THREAD_STAT_ACTIVE:
728 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
731 case THREAD_STAT_SLEEPING:
732 SHORTLOCK( &glThreadListLock );
733 // Remove from sleeping queue
734 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
736 Threads_AddActive( Thread );
738 #if DEBUG_TRACE_STATE
739 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
741 SHORTREL( &glThreadListLock );
744 case THREAD_STAT_WAITING:
745 Warning("Threads_Wake - Waiting threads are not currently supported");
748 case THREAD_STAT_DEAD:
749 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
753 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
759 * \brief Wake a thread given the TID
760 * \param TID Thread ID to wake
761 * \return Boolean Faulure (errno)
763 int Threads_WakeTID(tTID TID)
765 tThread *thread = Threads_GetThread(TID);
769 ret = Threads_Wake( thread );
770 //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
775 * \brief Adds a thread to the active queue
777 void Threads_AddActive(tThread *Thread)
779 SHORTLOCK( &glThreadListLock );
781 if( Thread->Status == THREAD_STAT_ACTIVE ) {
782 tThread *cur = Proc_GetCurThread();
783 Warning("WTF, CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
784 GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
788 Thread->Status = THREAD_STAT_ACTIVE;
790 // Add to active list
791 #if SCHEDULER_TYPE == SCHED_RR_PRI
792 Thread->Next = gaActiveThreads[Thread->Priority];
793 gaActiveThreads[Thread->Priority] = Thread;
795 Thread->Next = gActiveThreads;
796 gActiveThreads = Thread;
799 // Update bookkeeping
800 giNumActiveThreads ++;
802 #if SCHEDULER_TYPE == SCHED_LOTTERY
803 giFreeTickets += caiTICKET_COUNTS[ Thread->Priority ];
804 # if DEBUG_TRACE_TICKETS
805 Log("Threads_AddActive: CPU%i %p %i (%s) added, new giFreeTickets = %i",
806 GetCPUNum(), Thread, Thread->TID, Thread->ThreadName, giFreeTickets);
810 SHORTREL( &glThreadListLock );
814 * \brief Removes the current thread from the active queue
815 * \warning This should ONLY be called with task switches disabled
816 * \return Current thread pointer
818 tThread *Threads_RemActive(void)
820 tThread *ret = Proc_GetCurThread();
822 SHORTLOCK( &glThreadListLock );
824 // Delete from active queue
825 #if SCHEDULER_TYPE == SCHED_RR_PRI
826 if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
828 if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
831 SHORTREL( &glThreadListLock );
839 giNumActiveThreads --;
840 // no need to decrement tickets, scheduler did it for us
842 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
843 Log("Threads_RemActive: CPU%i %p %i (%s) removed, giFreeTickets = %i",
844 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
847 SHORTREL( &glThreadListLock );
853 * \fn void Threads_SetFaultHandler(Uint Handler)
854 * \brief Sets the signal handler for a signal
856 void Threads_SetFaultHandler(Uint Handler)
858 //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
859 Proc_GetCurThread()->FaultHandler = Handler;
863 * \fn void Threads_Fault(int Num)
864 * \brief Calls a fault handler
866 void Threads_Fault(int Num)
868 tThread *thread = Proc_GetCurThread();
870 Log_Log("Threads", "Threads_Fault: thread = %p", thread);
874 Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
876 switch(thread->FaultHandler)
879 Threads_Kill(thread, -1);
882 case 1: // Dump Core?
883 Threads_Kill(thread, -1);
888 // Double Fault? Oh, F**k
889 if(thread->CurFaultNum != 0) {
890 Threads_Kill(thread, -1); // For now, just kill
894 thread->CurFaultNum = Num;
896 Proc_CallFaultHandler(thread);
900 * \fn void Threads_SegFault(tVAddr Addr)
901 * \brief Called when a Segment Fault occurs
903 void Threads_SegFault(tVAddr Addr)
905 Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
907 //Threads_Exit( 0, -1 );
910 // --- Process Structure Access Functions ---
911 tPID Threads_GetPID(void)
913 return Proc_GetCurThread()->TGID;
915 tTID Threads_GetTID(void)
917 return Proc_GetCurThread()->TID;
919 tUID Threads_GetUID(void)
921 return Proc_GetCurThread()->UID;
923 tGID Threads_GetGID(void)
925 return Proc_GetCurThread()->GID;
928 int Threads_SetUID(Uint *Errno, tUID ID)
930 tThread *t = Proc_GetCurThread();
935 Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
940 int Threads_SetGID(Uint *Errno, tGID ID)
942 tThread *t = Proc_GetCurThread();
947 Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
953 * \fn void Threads_Dump(void)
955 void Threads_DumpActive(void)
958 #if SCHEDULER_TYPE == SCHED_RR_PRI
962 Log("Active Threads: (%i reported)", giNumActiveThreads);
964 #if SCHEDULER_TYPE == SCHED_RR_PRI
965 for( i = 0; i < MIN_PRIORITY+1; i++ )
967 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
969 for(thread=gActiveThreads;thread;thread=thread->Next)
972 Log(" %p %i (%i) - %s (CPU %i)",
973 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
974 if(thread->Status != THREAD_STAT_ACTIVE)
975 Log(" ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
976 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
977 Log(" KStack 0x%x", thread->KernelStack);
980 #if SCHEDULER_TYPE == SCHED_RR_PRI
986 * \fn void Threads_Dump(void)
987 * \brief Dumps a list of currently running threads
989 void Threads_Dump(void)
993 Log("--- Thread Dump ---");
994 Threads_DumpActive();
997 for(thread=gAllThreads;thread;thread=thread->GlobalNext)
999 Log(" %p %i (%i) - %s (CPU %i)",
1000 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1001 Log(" State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1002 switch(thread->Status)
1004 case THREAD_STAT_MUTEXSLEEP:
1005 Log(" Mutex Pointer: %p", thread->WaitPointer);
1007 case THREAD_STAT_SEMAPHORESLEEP:
1008 Log(" Semaphore Pointer: %p", thread->WaitPointer);
1009 Log(" Semaphore Name: %s:%s",
1010 ((tSemaphore*)thread->WaitPointer)->ModName,
1011 ((tSemaphore*)thread->WaitPointer)->Name
1014 case THREAD_STAT_ZOMBIE:
1015 Log(" Return Status: %i", thread->RetStatus);
1019 Log(" Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1020 Log(" KStack 0x%x", thread->KernelStack);
1025 * \brief Gets the next thread to run
1026 * \param CPU Current CPU
1027 * \param Last The thread the CPU was running
1029 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1033 // If this CPU has the lock, we must let it complete
1034 if( CPU_HAS_LOCK( &glThreadListLock ) )
1037 // Don't change threads if the current CPU has switches disabled
1038 if( gaThreads_NoTaskSwitch[CPU] )
1043 SHORTLOCK( &glThreadListLock );
1045 // Clear Delete Queue
1046 // - I should probably put this in a worker thread to avoid calling free() in the scheduler
1047 // DEFINITELY - free() can deadlock in this case
1048 while(gDeleteThreads)
1050 thread = gDeleteThreads->Next;
1051 // Only free if structure is unused
1052 if( !IS_LOCKED(&gDeleteThreads->IsLocked) )
1055 gDeleteThreads->Status = THREAD_STAT_BURIED;
1057 if( IsHeap(gDeleteThreads->ThreadName) )
1058 free(gDeleteThreads->ThreadName);
1059 // Remove from global list
1060 if( gDeleteThreads == gAllThreads )
1061 gAllThreads = gDeleteThreads->GlobalNext;
1063 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
1064 free( gDeleteThreads );
1066 gDeleteThreads = thread;
1069 // No active threads, just take a nap
1070 if(giNumActiveThreads == 0) {
1071 SHORTREL( &glThreadListLock );
1072 #if DEBUG_TRACE_TICKETS
1073 Log("No active threads");
1078 #if SCHEDULER_TYPE != SCHED_RR_PRI
1079 // Special case: 1 thread
1080 if(giNumActiveThreads == 1) {
1081 if( gActiveThreads->CurCPU == -1 )
1082 gActiveThreads->CurCPU = CPU;
1084 SHORTREL( &glThreadListLock );
1086 if( gActiveThreads->CurCPU == CPU )
1087 return gActiveThreads;
1089 return NULL; // CPU has nothing to do
1093 // Allow the old thread to be scheduled again
1095 if( Last->Status == THREAD_STAT_ACTIVE ) {
1096 #if SCHEDULER_TYPE == SCHED_LOTTERY
1097 giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1098 # if DEBUG_TRACE_TICKETS
1099 LogF(" CPU %i released %p (%i %s) into the pool (%i tickets in pool)\n",
1100 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets);
1104 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1106 LogF(" CPU %i released %p (%i %s)->Status = %i (Released)\n",
1107 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1113 // Lottery Scheduler
1115 #if SCHEDULER_TYPE == SCHED_LOTTERY
1120 for(thread = gActiveThreads; thread; thread = thread->Next) {
1121 if(thread->CurCPU >= 0) continue;
1122 if(thread->Status != THREAD_STAT_ACTIVE)
1123 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1124 thread, thread->TID, thread->ThreadName, thread->Status);
1125 if(thread->Next == thread) {
1126 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1127 thread, thread->TID, thread->ThreadName, thread->Status);
1129 number += caiTICKET_COUNTS[ thread->Priority ];
1131 if(number != giFreeTickets) {
1132 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1133 giFreeTickets, number, CPU);
1137 // No free tickets (all tasks delegated to cores)
1138 if( giFreeTickets == 0 ) {
1139 SHORTREL(&glThreadListLock);
1143 // Get the ticket number
1144 ticket = number = rand() % giFreeTickets;
1146 // Find the next thread
1147 for(thread=gActiveThreads;thread;thread=thread->Next)
1149 if(thread->CurCPU >= 0) continue;
1150 if( caiTICKET_COUNTS[ thread->Priority ] > number) break;
1151 number -= caiTICKET_COUNTS[ thread->Priority ];
1154 // If we didn't find a thread, something went wrong
1158 for(thread=gActiveThreads;thread;thread=thread->Next) {
1159 if(thread->CurCPU >= 0) continue;
1160 number += caiTICKET_COUNTS[ thread->Priority ];
1162 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1163 giFreeTickets, number);
1165 # if DEBUG_TRACE_TICKETS
1166 LogF(" CPU%i giFreeTickets = %i, running %p (%i %s CPU=%i)\n",
1167 CPU, giFreeTickets, thread, thread->TID, thread->ThreadName, thread->CurCPU);
1170 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1174 // Priority based round robin scheduler
1176 #elif SCHEDULER_TYPE == SCHED_RR_PRI
1179 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1181 for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1183 if( thread->CurCPU == -1 ) break;
1185 // If we fall onto the same queue again, special handling is
1187 if( i == Last->Priority ) {
1188 tThread *savedThread = thread;
1190 // Find the next unscheduled thread in the list
1191 for( thread = Last->Next; thread; thread = thread->Next )
1193 if( thread->CurCPU == -1 ) break;
1195 // If we don't find anything after, just use the one
1197 if( !thread ) thread = savedThread;
1199 // Found a thread? Schedule it!
1205 SHORTREL(&glThreadListLock);
1209 #elif SCHEDULER_TYPE == SCHED_RR_SIM
1211 // Find the next unscheduled thread in the list
1212 for( thread = Last->Next; thread; thread = thread->Next )
1214 if( thread->CurCPU == -1 ) break;
1216 // If we don't find anything after, search from the beginning
1219 for(thread = gActiveThreads; thread; thread = thread->Next)
1221 if( thread->CurCPU == -1 ) break;
1227 SHORTREL(&glThreadListLock);
1232 # error "Unimplemented scheduling algorithm"
1235 // Make the new thread non-schedulable
1236 thread->CurCPU = CPU;
1238 SHORTREL( &glThreadListLock );
1244 * \brief Acquire a heavy mutex
1245 * \param Mutex Mutex to acquire
1247 * This type of mutex checks if the mutex is avaliable, and acquires it
1248 * if it is. Otherwise, the current thread is added to the mutex's wait
1249 * queue and the thread suspends. When the holder of the mutex completes,
1250 * the oldest thread (top thread) on the queue is given the lock and
1253 int Mutex_Acquire(tMutex *Mutex)
1255 tThread *us = Proc_GetCurThread();
1258 SHORTLOCK( &Mutex->Protector );
1260 //Log("Mutex_Acquire: (%p)", Mutex);
1262 // Check if the lock is already held
1263 if( Mutex->Owner ) {
1264 SHORTLOCK( &glThreadListLock );
1265 // - Remove from active list
1266 us = Threads_RemActive();
1268 // - Mark as sleeping
1269 us->Status = THREAD_STAT_MUTEXSLEEP;
1270 us->WaitPointer = Mutex;
1273 if(Mutex->LastWaiting) {
1274 Mutex->LastWaiting->Next = us;
1275 Mutex->LastWaiting = us;
1278 Mutex->Waiting = us;
1279 Mutex->LastWaiting = us;
1285 for( t = Mutex->Waiting; t; t = t->Next, i++ )
1286 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1287 t, t->TID, t->ThreadName);
1291 SHORTREL( &glThreadListLock );
1292 SHORTREL( &Mutex->Protector );
1293 while(us->Status == THREAD_STAT_MUTEXSLEEP) Threads_Yield();
1294 // We're only woken when we get the lock
1295 us->WaitPointer = NULL;
1297 // Ooh, let's take it!
1300 SHORTREL( &Mutex->Protector );
1304 extern tMutex glPhysAlloc;
1305 if( Mutex != &glPhysAlloc )
1306 LogF("Mutex %p taken by %i %p\n", Mutex, us->TID, __builtin_return_address(0));
1313 * \brief Release a held mutex
1314 * \param Mutex Mutex to release
1315 * \note Releasing a non-held mutex has no effect
1317 void Mutex_Release(tMutex *Mutex)
1319 SHORTLOCK( &Mutex->Protector );
1320 //Log("Mutex_Release: (%p)", Mutex);
1321 if( Mutex->Waiting ) {
1322 Mutex->Owner = Mutex->Waiting; // Set owner
1323 Mutex->Waiting = Mutex->Waiting->Next; // Next!
1324 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1325 // 2010-10-02 21:50 - Comemerating the death of the longest single
1326 // blocker in the Acess2 history. REMEMBER TO
1327 // FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1328 if( Mutex->LastWaiting == Mutex->Owner )
1329 Mutex->LastWaiting = NULL;
1332 SHORTLOCK( &glThreadListLock );
1333 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1334 Threads_AddActive(Mutex->Owner);
1335 SHORTREL( &glThreadListLock );
1338 Mutex->Owner = NULL;
1340 SHORTREL( &Mutex->Protector );
1343 extern tMutex glPhysAlloc;
1344 if( Mutex != &glPhysAlloc )
1345 LogF("Mutex %p released by %i %p\n", Mutex, Threads_GetTID(), __builtin_return_address(0));
1350 * \brief Is this mutex locked?
1351 * \param Mutex Mutex pointer
1353 int Mutex_IsLocked(tMutex *Mutex)
1355 return Mutex->Owner != NULL;
1359 // Initialise a semaphore
1361 void Semaphore_Init(tSemaphore *Sem, int Value, int MaxValue, const char *Module, const char *Name)
1363 memset(Sem, 0, sizeof(tSemaphore));
1365 Sem->ModName = Module;
1367 Sem->MaxValue = MaxValue;
1370 // Wait for items to be avaliable
1372 int Semaphore_Wait(tSemaphore *Sem, int MaxToTake)
1376 if( MaxToTake < 0 ) {
1377 Log_Warning("Threads", "Semaphore_Wait: User bug - MaxToTake(%i) < 0, Sem=%p(%s)",
1378 MaxToTake, Sem, Sem->Name);
1381 SHORTLOCK( &Sem->Protector );
1383 // Check if there's already items avaliable
1384 if( Sem->Value > 0 ) {
1385 // Take what we need
1386 if( MaxToTake && Sem->Value > MaxToTake )
1390 Sem->Value -= taken;
1391 SHORTREL( &Sem->Protector );
1395 SHORTLOCK( &glThreadListLock );
1397 // - Remove from active list
1398 us = Threads_RemActive();
1400 // - Mark as sleeping
1401 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1402 us->WaitPointer = Sem;
1403 us->RetStatus = MaxToTake; // Use RetStatus as a temp variable
1406 if(Sem->LastWaiting) {
1407 Sem->LastWaiting->Next = us;
1408 Sem->LastWaiting = us;
1412 Sem->LastWaiting = us;
1415 SHORTREL( &glThreadListLock );
1416 SHORTREL( &Sem->Protector );
1417 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1418 // We're only woken when there's something avaliable
1419 us->WaitPointer = NULL;
1421 taken = us->RetStatus;
1423 // Get the lock again
1424 SHORTLOCK( &Sem->Protector );
1427 // While there is space, and there are thread waiting
1428 // wake the first thread and give it what it wants (or what's left)
1429 while( (Sem->MaxValue == 0 || Sem->Value < Sem->MaxValue) && Sem->Signaling )
1432 tThread *toWake = Sem->Signaling;
1434 Sem->Signaling = Sem->Signaling->Next;
1435 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1436 if( Sem->Signaling == NULL )
1437 Sem->LastSignaling = NULL;
1439 // Figure out how much to give
1440 if( toWake->RetStatus && Sem->Value + toWake->RetStatus < Sem->MaxValue )
1441 given = toWake->RetStatus;
1443 given = Sem->MaxValue - Sem->Value;
1444 Sem->Value -= given;
1446 // Save the number we gave to the thread's status
1447 toWake->RetStatus = given;
1450 SHORTLOCK( &glThreadListLock );
1451 if( toWake->Status != THREAD_STAT_ACTIVE )
1452 Threads_AddActive(toWake);
1453 SHORTREL( &glThreadListLock );
1455 SHORTREL( &Sem->Protector );
1461 // Add items to a semaphore
1463 int Semaphore_Signal(tSemaphore *Sem, int AmmountToAdd)
1468 if( AmmountToAdd < 0 ) {
1469 Log_Warning("Threads", "Semaphore_Signal: User bug - AmmountToAdd(%i) < 0, Sem=%p(%s)",
1470 AmmountToAdd, Sem, Sem->Name);
1472 SHORTLOCK( &Sem->Protector );
1474 // Check if we have to block
1475 if( Sem->MaxValue && Sem->Value == Sem->MaxValue )
1478 SHORTLOCK( &glThreadListLock );
1480 // - Remove from active list
1481 us = Threads_RemActive();
1483 // - Mark as sleeping
1484 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1485 us->WaitPointer = Sem;
1486 us->RetStatus = AmmountToAdd; // Use RetStatus as a temp variable
1489 if(Sem->LastSignaling) {
1490 Sem->LastSignaling->Next = us;
1491 Sem->LastSignaling = us;
1494 Sem->Signaling = us;
1495 Sem->LastSignaling = us;
1498 SHORTREL( &glThreadListLock );
1499 SHORTREL( &Sem->Protector );
1500 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1501 // We're only woken when there's something avaliable
1502 us->WaitPointer = NULL;
1504 added = us->RetStatus;
1506 // Get the lock again
1507 SHORTLOCK( &Sem->Protector );
1512 // Figure out how much we need to take off
1513 if( Sem->MaxValue && Sem->Value + AmmountToAdd > Sem->MaxValue)
1514 added = Sem->MaxValue - Sem->Value;
1516 added = AmmountToAdd;
1517 Sem->Value += added;
1520 // While there are items avaliable, and there are thread waiting
1521 // wake the first thread and give it what it wants (or what's left)
1522 while( Sem->Value && Sem->Waiting )
1524 tThread *toWake = Sem->Waiting;
1526 Sem->Waiting = Sem->Waiting->Next;
1527 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1528 if( Sem->Waiting == NULL )
1529 Sem->LastWaiting = NULL;
1531 // Figure out how much to give
1532 if( toWake->RetStatus && Sem->Value > toWake->RetStatus )
1533 given = toWake->RetStatus;
1536 Sem->Value -= given;
1538 // Save the number we gave to the thread's status
1539 toWake->RetStatus = given;
1542 SHORTLOCK( &glThreadListLock );
1543 if( toWake->Status != THREAD_STAT_ACTIVE )
1544 Threads_AddActive(toWake);
1545 SHORTREL( &glThreadListLock );
1547 SHORTREL( &Sem->Protector );
1553 // Get the current value of a semaphore
1555 int Semaphore_GetValue(tSemaphore *Sem)
1561 EXPORT(Threads_GetUID);
1562 EXPORT(Threads_GetGID);
1563 EXPORT(Mutex_Acquire);
1564 EXPORT(Mutex_Release);
1565 EXPORT(Mutex_IsLocked);
1566 EXPORT(Semaphore_Init);
1567 EXPORT(Semaphore_Wait);
1568 EXPORT(Semaphore_Signal);