Fixing commenting (always nice)
[tpg/acess2.git] / Kernel / threads.c
index 53756ed..99a9add 100644 (file)
@@ -7,6 +7,8 @@
 #include <threads.h>
 #include <errno.h>
 
+#define DEBUG_TRACE_TICKETS    0
+
 // === CONSTANTS ===
 #define        DEFAULT_QUANTUM 10
 #define        DEFAULT_TICKETS 5
@@ -28,7 +30,7 @@ extern void   Proc_CallFaultHandler(tThread *Thread);
 void   Threads_Init(void);
  int   Threads_SetName(char *NewName);
 char   *Threads_GetName(int ID);
-void   Threads_SetTickets(int Num);
+void   Threads_SetTickets(tThread *Thread, int Num);
 tThread        *Threads_CloneTCB(Uint *Err, Uint Flags);
  int   Threads_WaitTID(int TID, int *status);
 tThread        *Threads_GetThread(Uint TID);
@@ -38,7 +40,7 @@ void  Threads_Exit(int TID, int Status);
 void   Threads_Kill(tThread *Thread, int Status);
 void   Threads_Yield(void);
 void   Threads_Sleep(void);
-void   Threads_Wake(tThread *Thread);
+ int   Threads_Wake(tThread *Thread);
 void   Threads_AddActive(tThread *Thread);
  int   Threads_GetPID(void);
  int   Threads_GetTID(void);
@@ -47,6 +49,9 @@ tUID  Threads_GetUID(void);
 tGID   Threads_GetGID(void);
  int   Threads_SetGID(Uint *Errno, tUID ID);
 void   Threads_Dump(void);
+void   Mutex_Acquire(tMutex *Mutex);
+void   Mutex_Release(tMutex *Mutex);
+ int   Mutex_IsLocked(tMutex *Mutex);
 
 // === GLOBALS ===
 // -- Core Thread --
@@ -54,12 +59,13 @@ void        Threads_Dump(void);
 tThread        gThreadZero = {
        Status: THREAD_STAT_ACTIVE,     // Status
        ThreadName:     "ThreadZero",   // Name
-       Quantum: DEFAULT_QUANTUM, Remaining:    DEFAULT_QUANTUM,        // Quantum, Remaining
-       NumTickets:     DEFAULT_TICKETS
+       Quantum: DEFAULT_QUANTUM,       // Default Quantum
+       Remaining:      DEFAULT_QUANTUM,        // Current Quantum
+       NumTickets:     DEFAULT_TICKETS // Number of tickets
        };
 // -- Processes --
 // --- Locks ---
-tSpinlock      glThreadListLock = 0;   ///\note NEVER use a heap function while locked
+tShortSpinlock glThreadListLock;       ///\note NEVER use a heap function while locked
 // --- Current State ---
 volatile int   giNumActiveThreads = 0;
 //volatile int giTotalTickets = 0;
@@ -119,16 +125,24 @@ char *Threads_GetName(int ID)
 }
 
 /**
- * \fn void Threads_SetTickets(int Num)
+ * \fn void Threads_SetTickets(tThread *Thread, int Num)
  * \brief Sets the 'priority' of a task
  */
-void Threads_SetTickets(int Num)
+void Threads_SetTickets(tThread *Thread, int Num)
 {
-       tThread *cur = Proc_GetCurThread();
+       if(Thread == NULL)
+               Thread = Proc_GetCurThread();
        if(Num < 0)     return;
        if(Num > MAX_TICKETS)   Num = MAX_TICKETS;
        
-       cur->NumTickets = Num;
+       if( Thread != Proc_GetCurThread() ) {
+               SHORTLOCK( &glThreadListLock );
+               giFreeTickets -= Thread->NumTickets - Num;
+               Thread->NumTickets = Num;
+               SHORTREL( &glThreadListLock );
+       }
+       else
+               Thread->NumTickets = Num;
 }
 
 /**
@@ -149,7 +163,7 @@ tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
        
        new->CurCPU = -1;
        new->Next = NULL;
-       new->IsLocked = 0;
+       memset( &new->IsLocked, 0, sizeof(new->IsLocked));
        new->Status = THREAD_STAT_ACTIVE;
        new->RetStatus = 0;
        
@@ -158,7 +172,6 @@ tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
        new->PTID = cur->TID;
        
        // Clone Name
-       Log("Threads_CloneTCB: cur (%p) ->ThreadName = %p", cur, cur->ThreadName);
        new->ThreadName = strdup(cur->ThreadName);
        
        // Set Thread Group ID (PID)
@@ -376,15 +389,17 @@ void Threads_Kill(tThread *Thread, int Status)
        ///\note Double lock is needed due to overlap of lock areas
        
        // Lock thread (stop us recieving messages)
-       LOCK( &Thread->IsLocked );
+       SHORTLOCK( &Thread->IsLocked );
        
        // Lock thread list
-       LOCK( &glThreadListLock );
+       SHORTLOCK( &glThreadListLock );
        
        // Get previous thread on list
        prev = Threads_int_GetPrev( &gActiveThreads, Thread );
        if(!prev) {
                Warning("Proc_Exit - Current thread is not on the active queue");
+               Thread->IsLocked.Lock = 0;      // We can't use SHORTREL as that starts IRQs again
+               SHORTREL( &glThreadListLock );
                return;
        }
        
@@ -403,6 +418,7 @@ void Threads_Kill(tThread *Thread, int Status)
        giNumActiveThreads --;
        if( Thread != Proc_GetCurThread() )
                giFreeTickets -= Thread->NumTickets;
+       //Log("Threads_Kill: giFreeTickets = %i", giFreeTickets);
        
        // Mark thread as a zombie
        Thread->RetStatus = Status;
@@ -417,8 +433,8 @@ void Threads_Kill(tThread *Thread, int Status)
        }
        
        // Release spinlocks
-       RELEASE( &Thread->IsLocked );   // Released first so that it IS released
-       RELEASE( &glThreadListLock );
+       Thread->IsLocked.Lock = 0;      // Released first so that it IS released
+       SHORTREL( &glThreadListLock );
        
        //Log("Thread %i went *hurk*", Thread->TID);
        
@@ -447,20 +463,20 @@ void Threads_Sleep(void)
        //Log_Log("Threads", "%i going to sleep", cur->TID);
        
        // Acquire Spinlock
-       LOCK( &glThreadListLock );
+       SHORTLOCK( &glThreadListLock );
        
        // Get thread before current thread
        thread = Threads_int_GetPrev( &gActiveThreads, cur );
        if(!thread) {
                Warning("Threads_Sleep - Current thread is not on the active queue");
                Threads_Dump();
-               RELEASE( &glThreadListLock );
+               SHORTREL( &glThreadListLock );
                return;
        }
        
        // Don't sleep if there is a message waiting
        if( cur->Messages ) {
-               RELEASE( &glThreadListLock );
+               SHORTREL( &glThreadListLock );
                return;
        }
        
@@ -476,59 +492,77 @@ void Threads_Sleep(void)
        
        // Reduce the active count & ticket count
        giNumActiveThreads --;
-       //giTotalTickets -= cur->NumTickets;
+       // - No need to alter giFreeTickets (we're being executed)
        
        // Mark thread as sleeping
        cur->Status = THREAD_STAT_SLEEPING;
        
        // Release Spinlock
-       RELEASE( &glThreadListLock );
+       SHORTREL( &glThreadListLock );
        
        while(cur->Status != THREAD_STAT_ACTIVE)        HALT();
 }
 
 
 /**
- * \fn void Threads_Wake( tThread *Thread )
+ * \fn int Threads_Wake( tThread *Thread )
  * \brief Wakes a sleeping/waiting thread up
+ * \param Thread       Thread to wake
+ * \return Boolean Failure (Returns ERRNO)
  */
-void Threads_Wake(tThread *Thread)
+int Threads_Wake(tThread *Thread)
 {
        tThread *prev;
+       
+       if(!Thread)
+               return -EINVAL;
+       
        switch(Thread->Status)
        {
-       case THREAD_STAT_ACTIVE:        break;
-       case THREAD_STAT_SLEEPING:
-               //Log_Log("Threads", "Waking %i (%p) from sleeping", Thread->TID, Thread);
-               LOCK( &glThreadListLock );
+       case THREAD_STAT_ACTIVE:
+               Log("Thread_Wake: Waking awake thread (%i)", Thread->TID);
+               return -EALREADY;
+       case THREAD_STAT_SLEEPING:      // TODO: Comment better
+               //Log_Log("Threads", "Waking %i (%p) from sleeping (CPU=%i)",
+               //      Thread->TID, Thread, Thread->CurCPU);
+               SHORTLOCK( &glThreadListLock );
                prev = Threads_int_GetPrev(&gSleepingThreads, Thread);
                prev->Next = Thread->Next;      // Remove from sleeping queue
                Thread->Next = gActiveThreads;  // Add to active queue
                gActiveThreads = Thread;
                giNumActiveThreads ++;
                // Thread can't be the current, so no need to check
+               Thread->CurCPU = -1;
                giFreeTickets += Thread->NumTickets;
+               #if DEBUG_TRACE_TICKETS
+               Log("Threads_Wake: giFreeTickets = %i", giFreeTickets);
+               #endif
                Thread->Status = THREAD_STAT_ACTIVE;
-               RELEASE( &glThreadListLock );
-               break;
+               SHORTREL( &glThreadListLock );
+               return -EOK;
        case THREAD_STAT_WAITING:
                Warning("Thread_Wake - Waiting threads are not currently supported");
-               break;
+               return -ENOTIMPL;
        case THREAD_STAT_DEAD:
                Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
-               break;
+               return -ENOTIMPL;
        default:
                Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
-               break;
+               return -EINTERNAL;
        }
 }
 
 /**
  * \brief Wake a thread given the TID
+ * \param TID  Thread ID to wake
+ * \return Boolean Faulure (errno)
  */
-void Threads_WakeTID(tTID Thread)
+int Threads_WakeTID(tTID TID)
 {
-       Threads_Wake( Threads_GetThread(Thread) );
+       tThread *thread = Threads_GetThread(TID);
+       if(!thread)
+               return -ENOENT;
+       return Threads_Wake( thread );
 }
 
 /**
@@ -537,15 +571,16 @@ void Threads_WakeTID(tTID Thread)
  */
 void Threads_AddActive(tThread *Thread)
 {
-       LOCK( &glThreadListLock );
+       SHORTLOCK( &glThreadListLock );
        Thread->Next = gActiveThreads;
        gActiveThreads = Thread;
        giNumActiveThreads ++;
        // Thread can't be the current, so no need to check
        giFreeTickets += Thread->NumTickets;
-       //Log("Threads_AddActive: giNumActiveThreads = %i, giTotalTickets = %i",
-       //      giNumActiveThreads, giTotalTickets);
-       RELEASE( &glThreadListLock );
+       #if DEBUG_TRACE_TICKETS
+       Log("Threads_AddActive: giFreeTickets = %i", giFreeTickets);
+       #endif
+       SHORTREL( &glThreadListLock );
 }
 
 /**
@@ -644,7 +679,6 @@ int Threads_SetGID(Uint *Errno, tGID ID)
 void Threads_Dump(void)
 {
        tThread *thread;
-       tThread *cur = Proc_GetCurThread();
        
        Log("Active Threads:");
        for(thread=gActiveThreads;thread;thread=thread->Next)
@@ -657,8 +691,7 @@ void Threads_Dump(void)
        Log("Sleeping Threads:");
        for(thread=gSleepingThreads;thread;thread=thread->Next)
        {
-               Log("%c%i (%i) - %s",
-                       (thread==cur?'*':' '),
+               Log(" %i (%i) - %s",
                        thread->TID, thread->TGID, thread->ThreadName);
                Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
                Log("  KStack 0x%x", thread->KernelStack);
@@ -677,16 +710,30 @@ tThread *Threads_GetNextToRun(int CPU, tThread *Last)
         int    ticket;
         int    number;
        
-       // Note: Enable the code to tell if the switch code has the lock, or
-       // if it's the other code.
+       // TODO: Enable the code to tell if the current CPU has the lock or
+       //       another does.
        
        // Check if the thread list is locked by other code
        // - If so, don't switch (give it a chance to complete)
        if( IS_LOCKED(&glThreadListLock) )
                return Last;
        
+       // Clear Delete Queue
+       while(gDeleteThreads)
+       {
+               thread = gDeleteThreads->Next;
+               if( IS_LOCKED(&gDeleteThreads->IsLocked) ) {    // Only free if structure is unused
+                       gDeleteThreads->Status = THREAD_STAT_NULL;
+                       free( gDeleteThreads );
+               }
+               gDeleteThreads = thread;
+       }
+       
        // No active threads, just take a nap
        if(giNumActiveThreads == 0) {
+               #if DEBUG_TRACE_TICKETS
+               Log("No active threads");
+               #endif
                return NULL;
        }
        
@@ -695,13 +742,13 @@ tThread *Threads_GetNextToRun(int CPU, tThread *Last)
        //   but it has a potentially long lock period)
        // - Well, this CPU can obtain the lock, but that is aliveviated by
        //   the above.
-       TIGHTLOCK( &glThreadListLock );
+       SHORTLOCK( &glThreadListLock );
        
        // Special case: 1 thread
        if(giNumActiveThreads == 1) {
                if( gActiveThreads->CurCPU == -1 )
                        gActiveThreads->CurCPU = CPU;
-               RELEASE( &glThreadListLock );
+               SHORTREL( &glThreadListLock );
                if( gActiveThreads->CurCPU == CPU )
                        return gActiveThreads;
                return NULL;    // CPU has nothing to do
@@ -709,14 +756,35 @@ tThread *Threads_GetNextToRun(int CPU, tThread *Last)
        
        // Allow the old thread to be scheduled again
        if( Last ) {
-               if( Last->Status == THREAD_STAT_ACTIVE )
+               if( Last->Status == THREAD_STAT_ACTIVE ) {
                        giFreeTickets += Last->NumTickets;
+                       #if DEBUG_TRACE_TICKETS
+                       LogF(" CPU %i released %p (%s) into the pool (%i tickets in pool)\n",
+                               CPU, Last, Last->ThreadName, Last->NumTickets);
+                       #endif
+               }
+               #if DEBUG_TRACE_TICKETS
+               else
+                       LogF(" %p (%s)->Status = %i\n", Last, Last->ThreadName, Last->Status);
+               #endif
                Last->CurCPU = -1;
        }
        
+       #if 1
+       number = 0;
+       for(thread=gActiveThreads;thread;thread=thread->Next) {
+               if(thread->CurCPU >= 0) continue;
+               number += thread->NumTickets;
+       }
+       if(number != giFreeTickets) {
+               Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
+                       giFreeTickets, number, CPU);
+       }
+       #endif
+       
        // No free tickets (all tasks delegated to cores)
        if( giFreeTickets == 0 ) {
-               RELEASE(&glThreadListLock);
+               SHORTREL(&glThreadListLock);
                return NULL;
        }
        
@@ -741,12 +809,21 @@ tThread *Threads_GetNextToRun(int CPU, tThread *Last)
                Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
                        giFreeTickets, number);
        }
+       #if DEBUG_TRACE_TICKETS
+       LogF(" CPU%i giFreeTickets = %i\n", CPU, giFreeTickets);
+       #endif
        
        // Make the new thread non-schedulable
        giFreeTickets -= thread->NumTickets;    
        thread->CurCPU = CPU;
        
-       RELEASE( &glThreadListLock );
+       //Threads_Dump();
+       #if DEBUG_TRACE_TICKETS
+       LogF(" CPU%i giFreeTickets = %i, giving %p (%s CPU=%i)\n",
+               CPU, giFreeTickets, thread, thread->ThreadName, thread->CurCPU);
+       #endif
+       
+       SHORTREL( &glThreadListLock );
        
        return thread;
 }
@@ -762,5 +839,87 @@ void Threads_SegFault(tVAddr Addr)
        //Threads_Exit( 0, -1 );
 }
 
+/**
+ * \brief Acquire a heavy mutex
+ * \param Mutex        Mutex to acquire
+ * 
+ * This type of mutex checks if the mutex is avaliable, and acquires it
+ * if it is. Otherwise, the current thread is added to the mutex's wait
+ * queue and the thread suspends. When the holder of the mutex completes,
+ * the oldest thread (top thread) on the queue is given the lock and
+ * restarted.
+ */
+void Mutex_Acquire(tMutex *Mutex)
+{
+       tThread *us = Proc_GetCurThread();
+       tThread *prev;
+       
+       // Get protector
+       SHORTLOCK( &Mutex->Protector );
+       
+       //Log("Mutex_Acquire: (%p)", Mutex);
+       
+       // Check if the lock is already held
+       if( Mutex->Owner ) {
+               SHORTLOCK( &glThreadListLock );
+               // - Remove from active list
+               us->Remaining = 0;
+               prev = Threads_int_GetPrev(&gActiveThreads, us);
+               prev->Next = us->Next;
+               giNumActiveThreads --;
+               us->Status = THREAD_STAT_SLEEPING;
+               
+               // - Add to waiting
+               if(Mutex->LastWaiting) {
+                       Mutex->LastWaiting->Next = us;
+                       Mutex->LastWaiting = us;
+               }
+               else {
+                       Mutex->Waiting = us;
+                       Mutex->LastWaiting = us;
+               }
+               SHORTREL( &glThreadListLock );
+               SHORTREL( &Mutex->Protector );
+               while(us->Status == THREAD_STAT_SLEEPING)       HALT();
+               // We're only woken when we get the lock
+       }
+       // Ooh, let's take it!
+       else {
+               Mutex->Owner = us;
+               SHORTREL( &Mutex->Protector );
+       }
+}
+
+/**
+ * \brief Release a held mutex
+ * \param Mutex        Mutex to release
+ */
+void Mutex_Release(tMutex *Mutex)
+{
+       SHORTLOCK( &Mutex->Protector );
+       //Log("Mutex_Release: (%p)", Mutex);
+       if( Mutex->Waiting ) {
+               Mutex->Owner = Mutex->Waiting;  // Set owner
+               Mutex->Waiting = Mutex->Waiting->Next;  // Next!
+               // Wake new owner
+               Mutex->Owner->Status = THREAD_STAT_ACTIVE;
+               Threads_AddActive(Mutex->Owner);
+               Log("Mutex %p Woke %p", Mutex, Mutex->Owner);
+       }
+       else {
+               Mutex->Owner = NULL;
+       }
+       SHORTREL( &Mutex->Protector );
+}
+
+/**
+ * \brief Is this mutex locked?
+ * \param Mutex        Mutex pointer
+ */
+int Mutex_IsLocked(tMutex *Mutex)
+{
+       return Mutex->Owner != NULL;
+}
+
 // === EXPORTS ===
 EXPORT(Threads_GetUID);

UCC git Repository :: git.ucc.asn.au