More behavior fixes (changes to resolution only apply on a mode set)
[tpg/acess2.git] / Kernel / threads.c
index 23feb5d..297470c 100644 (file)
@@ -7,13 +7,15 @@
 #include <threads.h>
 #include <errno.h>
 
+#define DEBUG_TRACE_TICKETS    0
+
 // === CONSTANTS ===
 #define        DEFAULT_QUANTUM 10
 #define        DEFAULT_TICKETS 5
 #define MAX_TICKETS            10
 const enum eConfigTypes        cCONFIG_TYPES[] = {
-       CFGT_HEAPSTR,   // CFG_VFS_CWD
-       CFGT_INT,       // CFG_VFS_MAXFILES
+       CFGT_HEAPSTR,   // e.g. CFG_VFS_CWD
+       CFGT_INT,       // e.g. CFG_VFS_MAXFILES
        CFGT_NULL
 };
 
@@ -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);
@@ -50,32 +52,21 @@ void        Threads_Dump(void);
 
 // === GLOBALS ===
 // -- Core Thread --
+// Only used for the core kernel
 tThread        gThreadZero = {
-       NULL, 0,        // Next, Lock
-       THREAD_STAT_ACTIVE,     // Status
-       0,      // Exit Status
-       0, 0,   // TID, TGID
-       0, 0,   // UID, GID
-       0,      // Parent Thread ID
-       "ThreadZero",   // Name
-       
-       0,      // Kernel Stack
-       {0},    // Saved State
-       {0},    // VM State
-       
-       0, 0,   // Current Fault, Fault Handler
-       
-       NULL, NULL,     // Messages, Last Message
-       DEFAULT_QUANTUM, DEFAULT_QUANTUM,       // Quantum, Remaining
-       DEFAULT_TICKETS,
-       {0}     // Default config to zero
+       Status: THREAD_STAT_ACTIVE,     // Status
+       ThreadName:     "ThreadZero",   // Name
+       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
 // --- Current State ---
 volatile int   giNumActiveThreads = 0;
-volatile int   giTotalTickets = 0;
+//volatile int giTotalTickets = 0;
+volatile int   giFreeTickets = 0;
 volatile Uint  giNextTID = 1;
 // --- Thread Lists ---
 tThread        *gActiveThreads = NULL;         // Currently Running Threads
@@ -94,21 +85,9 @@ void Threads_Init(void)
        
        // Create Initial Task
        gActiveThreads = &gThreadZero;
-       giTotalTickets = gThreadZero.NumTickets;
+       //giFreeTickets = gThreadZero.NumTickets;
        giNumActiveThreads = 1;
-       
-       #if 1
-       // Create Idle Task
-       if(Proc_Clone(0, 0) == 0)
-       {
-               tThread *cur = Proc_GetCurThread();
-               cur->ThreadName = "Idle Thread";
-               Threads_SetTickets(0);  // Never called randomly
-               cur->Quantum = 1;       // 1 slice quantum
-               for(;;) HALT(); // Just yeilds
-       }
-       #endif
-       
+               
        Proc_Start();
 }
 
@@ -119,10 +98,13 @@ void Threads_Init(void)
 int Threads_SetName(char *NewName)
 {
        tThread *cur = Proc_GetCurThread();
-       if( IsHeap(cur->ThreadName) )
-               free( cur->ThreadName );
-       cur->ThreadName = malloc(strlen(NewName)+1);
-       strcpy(cur->ThreadName, NewName);
+       char    *oldname = cur->ThreadName;
+       
+       cur->ThreadName = NULL;
+       
+       if( IsHeap(oldname) )   free( oldname );
+       
+       cur->ThreadName = strdup(NewName);
        return 0;
 }
 
@@ -135,25 +117,29 @@ char *Threads_GetName(int ID)
        if(ID == -1) {
                return Proc_GetCurThread()->ThreadName;
        }
+       // TODO: Find a thread and get its name
        return NULL;
 }
 
 /**
- * \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;
        
-       LOCK( &glThreadListLock );
-       giTotalTickets -= cur->NumTickets;
-       cur->NumTickets = Num;
-       giTotalTickets += Num;
-       //LOG("giTotalTickets = %i", giTotalTickets);
-       RELEASE( &glThreadListLock );
+       if( Thread != Proc_GetCurThread() ) {
+               LOCK( &glThreadListLock );
+               giFreeTickets -= Thread->NumTickets - Num;
+               Thread->NumTickets = Num;
+               RELEASE( &glThreadListLock );
+       }
+       else
+               Thread->NumTickets = Num;
 }
 
 /**
@@ -172,6 +158,7 @@ tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
        }
        memcpy(new, cur, sizeof(tThread));
        
+       new->CurCPU = -1;
        new->Next = NULL;
        new->IsLocked = 0;
        new->Status = THREAD_STAT_ACTIVE;
@@ -290,6 +277,7 @@ int Threads_WaitTID(int TID, int *status)
 /**
  * \fn tThread *Threads_GetThread(Uint TID)
  * \brief Gets a thread given its TID
+ * \param TID  Thread ID
  */
 tThread *Threads_GetThread(Uint TID)
 {
@@ -365,7 +353,9 @@ void Threads_Exit(int TID, int Status)
                Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
        else
                Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
-       for(;;) HALT(); // Just in case
+       // Halt forever, just in case
+       for(;;)
+               HALT();
 }
 
 /**
@@ -393,7 +383,7 @@ void Threads_Kill(tThread *Thread, int Status)
        }
        #endif
        
-       ///\note Double lock is needed due to overlap of locks
+       ///\note Double lock is needed due to overlap of lock areas
        
        // Lock thread (stop us recieving messages)
        LOCK( &Thread->IsLocked );
@@ -421,7 +411,9 @@ void Threads_Kill(tThread *Thread, int Status)
        prev->Next = Thread->Next;      // Remove from active
        
        giNumActiveThreads --;
-       giTotalTickets -= Thread->NumTickets;
+       if( Thread != Proc_GetCurThread() )
+               giFreeTickets -= Thread->NumTickets;
+       //Log("Threads_Kill: giFreeTickets = %i", giFreeTickets);
        
        // Mark thread as a zombie
        Thread->RetStatus = Status;
@@ -473,6 +465,7 @@ void Threads_Sleep(void)
        if(!thread) {
                Warning("Threads_Sleep - Current thread is not on the active queue");
                Threads_Dump();
+               RELEASE( &glThreadListLock );
                return;
        }
        
@@ -494,7 +487,6 @@ void Threads_Sleep(void)
        
        // Reduce the active count & ticket count
        giNumActiveThreads --;
-       giTotalTickets -= cur->NumTickets;
        
        // Mark thread as sleeping
        cur->Status = THREAD_STAT_SLEEPING;
@@ -507,42 +499,64 @@ void Threads_Sleep(void)
 
 
 /**
- * \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_ACTIVE:
+               Log("Thread_Wake: Waking awake thread (%i)", Thread->TID);
+               return -EALREADY;
        case THREAD_STAT_SLEEPING:
-               //Log_Log("Threads", "Waking %i (%p) from sleeping", Thread->TID, Thread);
+               //Log_Log("Threads", "Waking %i (%p) from sleeping (CPU=%i)",
+               //      Thread->TID, Thread, Thread->CurCPU);
                LOCK( &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 ++;
-               giTotalTickets += Thread->NumTickets;
+               // 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;
+               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;
        }
 }
 
-void Threads_WakeTID(tTID Thread)
+/**
+ * \brief Wake a thread given the TID
+ * \param TID  Thread ID to wake
+ * \return Boolean Faulure (errno)
+ */
+int Threads_WakeTID(tTID TID)
 {
-       Threads_Wake( Threads_GetThread(Thread) );
+       tThread *thread = Threads_GetThread(TID);
+       if(!thread)
+               return -ENOENT;
+       return Threads_Wake( thread );
 }
 
 /**
@@ -555,9 +569,11 @@ void Threads_AddActive(tThread *Thread)
        Thread->Next = gActiveThreads;
        gActiveThreads = Thread;
        giNumActiveThreads ++;
-       giTotalTickets += Thread->NumTickets;
-       //Log("Threads_AddActive: giNumActiveThreads = %i, giTotalTickets = %i",
-       //      giNumActiveThreads, giTotalTickets);
+       // Thread can't be the current, so no need to check
+       giFreeTickets += Thread->NumTickets;
+       #if DEBUG_TRACE_TICKETS
+       Log("Threads_AddActive: giFreeTickets = %i", giFreeTickets);
+       #endif
        RELEASE( &glThreadListLock );
 }
 
@@ -657,22 +673,19 @@ 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)
        {
-               Log("%c%i (%i) - %s",
-                       (thread==cur?'*':' '),
-                       thread->TID, thread->TGID, thread->ThreadName);
+               Log(" %i (%i) - %s (CPU %i)",
+                       thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
                Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
                Log("  KStack 0x%x", thread->KernelStack);
        }
        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);
@@ -680,43 +693,131 @@ void Threads_Dump(void)
 }
 
 /**
- * \fn tThread *Threads_GetNextToRun(int CPU)
+ * \fn tThread *Threads_GetNextToRun(int CPU, tThread *Last)
  * \brief Gets the next thread to run
+ * \param CPU  Current CPU
+ * \param Last The thread the CPU was running
  */
-tThread *Threads_GetNextToRun(int CPU)
+tThread *Threads_GetNextToRun(int CPU, tThread *Last)
 {
        tThread *thread;
         int    ticket;
         int    number;
        
+       // 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(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;
        }
        
+       // Lock thread list
+       // - HLT lock (Used because only another CPU can obtain the lock,
+       //   but it has a potentially long lock period)
+       // - Well, this CPU can obtain the lock, but that is aliveviated by
+       //   the above.
+       TIGHTLOCK( &glThreadListLock );
+       
        // Special case: 1 thread
        if(giNumActiveThreads == 1) {
-               return gActiveThreads;
+               if( gActiveThreads->CurCPU == -1 )
+                       gActiveThreads->CurCPU = CPU;
+               RELEASE( &glThreadListLock );
+               if( gActiveThreads->CurCPU == CPU )
+                       return gActiveThreads;
+               return NULL;    // CPU has nothing to do
+       }
+       
+       // Allow the old thread to be scheduled again
+       if( Last ) {
+               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);
+               return NULL;
        }
        
        // Get the ticket number
-       ticket = number = rand() % giTotalTickets;
+       ticket = number = rand() % giFreeTickets;
        
        // Find the next thread
        for(thread=gActiveThreads;thread;thread=thread->Next)
        {
+               if(thread->CurCPU >= 0) continue;
                if(thread->NumTickets > number) break;
                number -= thread->NumTickets;
        }
-       
        // Error Check
        if(thread == NULL)
        {
                number = 0;
-               for(thread=gActiveThreads;thread;thread=thread->Next)
+               for(thread=gActiveThreads;thread;thread=thread->Next) {
+                       if(thread->CurCPU >= 0) continue;
                        number += thread->NumTickets;
-               Panic("Bookeeping Failed - giTotalTicketCount (%i) != true count (%i)",
-                       giTotalTickets, number);
+               }
+               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;
+       
+       //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
+       
+       RELEASE( &glThreadListLock );
        
        return thread;
 }

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