Kernel/threads - (minor) Clean up code (remove pre C99 constructs)
[tpg/acess2.git] / KernelLand / Kernel / threads.c
1 /*
2  * Acess2 Kernel
3  * - By John Hodge (thePowersGang)
4  * threads.c
5  * - Common Thread Control
6  */
7 #include <acess.h>
8 #include <threads.h>
9 #include <threads_int.h>
10 #include <errno.h>
11 #include <hal_proc.h>
12 #include <semaphore.h>
13 #include <rwlock.h>
14 #include <vfs_threads.h>        // VFS Handle maintainence
15 #include <events.h>
16 #include <debug_hooks.h>
17
18 // Configuration
19 #define DEBUG_TRACE_ACTIVEQUEUE 0       // Trace adds/removals from the active queue
20 #define DEBUG_TRACE_TICKETS     0       // Trace ticket counts
21 #define DEBUG_TRACE_STATE       0       // Trace state changes (sleep/wake)
22 #define DEBUG_TRACE_SCHEDULE    0       // Trace scheduling
23
24 // --- Schedulers ---
25 #define SCHED_UNDEF     0
26 #define SCHED_LOTTERY   1       // Lottery scheduler
27 #define SCHED_RR_SIM    2       // Single Queue Round Robin
28 #define SCHED_RR_PRI    3       // Multi Queue Round Robin
29 // Set scheduler type
30 #define SCHEDULER_TYPE  SCHED_RR_PRI
31
32 // === CONSTANTS ===
33 #define DEFAULT_QUANTUM 5
34 #define DEFAULT_PRIORITY        5
35 #define MIN_PRIORITY            10
36
37 #define PRIthread_fmt   "%p(%i %s)"
38 #define PRIthread_args(t)       (t), ((t)?(t)->TID:-1), ((t)?(t)->ThreadName:"-")
39
40 // === IMPORTS ===
41 extern void     User_Signal_Kill(int SigNum);
42
43 // === TYPE ===
44 typedef struct
45 {
46         tThread *Head;
47         tThread *Tail;
48 } tThreadList;
49
50 // === PROTOTYPES ===
51 void    Threads_Init(void);
52 #if 0
53 void    Threads_Delete(tThread *Thread);
54  int    Threads_SetName(const char *NewName);
55 #endif
56 char    *Threads_GetName(tTID ID);
57 #if 0
58 void    Threads_SetPriority(tThread *Thread, int Pri);
59 tThread *Threads_CloneTCB(Uint Flags);
60  int    Threads_WaitTID(int TID, int *status);
61 tThread *Threads_GetThread(Uint TID);
62 #endif
63 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread);
64 void    Threads_int_AddToList(tThreadList *List, tThread *Thread);
65 #if 0
66 void    Threads_Exit(int TID, int Status);
67 void    Threads_Kill(tThread *Thread, int Status);
68 void    Threads_Yield(void);
69  int    Threads_int_Sleep(enum eThreadStatus Status, void *Ptr, int Num, tThread **ListHead, tThread **ListTail, tShortSpinlock *Lock);
70 void    Threads_Sleep(void);
71  int    Threads_Wake(tThread *Thread);
72 void    Threads_AddActive(tThread *Thread);
73 tThread *Threads_RemActive(void);
74 void    Threads_ToggleTrace(int TID);
75 #endif
76 void    Threads_Fault(int Num);
77 void    Threads_SegFault(tVAddr Addr);
78 void    Threads_PostSignalTo(tThread *Thread, int SignalNum);
79 #if 0
80 void    Threads_PostSignal(int SignalNum);
81 void    Threads_SignalGroup(tPGID PGID, int SignalNum);
82 #endif
83  int    Threads_GetPendingSignal(void);
84 void    Threads_SetSignalHandler(int SignalNum, void *Handler);
85 void    *Threads_GetSignalHandler(int SignalNum);
86 #if 0
87  int    Threads_GetPID(void);
88  int    Threads_GetTID(void);
89 tUID    Threads_GetUID(void);
90 tGID    Threads_GetGID(void);
91  int    Threads_SetUID(Uint *Errno, tUID ID);
92  int    Threads_SetGID(Uint *Errno, tUID ID);
93 #endif
94 void    Threads_int_DumpThread(tThread *thread);
95 #if 0
96 void    Threads_Dump(void);
97 #endif
98 void    Threads_DumpActive(void);
99 tThread *Threads_int_GetRunnable(void);
100
101 // === GLOBALS ===
102 // -- Core Thread --
103 tProcess        gProcessZero = {
104         };
105 // Only used for the core kernel
106 tThread gThreadZero = {
107         .Status         = THREAD_STAT_ACTIVE,   // Status
108         .ThreadName     = (char*)"ThreadZero",  // Name
109         .Quantum        = DEFAULT_QUANTUM,      // Default Quantum
110         .Remaining      = DEFAULT_QUANTUM,      // Current Quantum
111         .Priority       = DEFAULT_PRIORITY      // Number of tickets
112         };
113 // -- Processes --
114 tProcess        *gAllProcesses = &gProcessZero;
115 // --- Locks ---
116 tShortSpinlock  glThreadListLock;       ///\note NEVER use a heap function while locked
117 // --- Current State ---
118 volatile int    giNumActiveThreads = 0; // Number of threads on the active queue
119 volatile Uint   giNextTID = 1;  // Next TID to allocate
120 // --- Thread Lists ---
121 tThread *gAllThreads = NULL;            // All allocated threads
122 tThreadList     gSleepingThreads;       // Sleeping Threads
123  int    giNumCPUs = 1;  // Number of CPUs
124 BOOL     gaThreads_NoTaskSwitch[MAX_CPUS];      // Disables task switches for each core (Pseudo-IF)
125 // --- Scheduler Types ---
126 #if SCHEDULER_TYPE == SCHED_LOTTERY
127 const int       caiTICKET_COUNTS[MIN_PRIORITY+1] = {100,81,64,49,36,25,16,9,4,1,0};
128 volatile int    giFreeTickets = 0;      // Number of tickets held by non-scheduled threads
129 tThreadList     gActiveThreads;         // Currently Running Threads
130 #elif SCHEDULER_TYPE == SCHED_RR_SIM
131 tThreadList     gActiveThreads;         // Currently Running Threads
132 #elif SCHEDULER_TYPE == SCHED_RR_PRI
133 tThreadList     gaActiveThreads[MIN_PRIORITY+1];        // Active threads for each priority level
134 #else
135 # error "Unkown scheduler type"
136 #endif
137
138 // === CODE ===
139 /**
140  * \fn void Threads_Init(void)
141  * \brief Initialse the thread list
142  */
143 void Threads_Init(void)
144 {
145         ArchThreads_Init();
146         
147         Log_Debug("Threads", "Offsets of tThread");
148         Log_Debug("Threads", ".Priority = %i", offsetof(tThread, Priority));
149         Log_Debug("Threads", ".KernelStack = %i", offsetof(tThread, KernelStack));
150         
151         // Create Initial Task
152         gAllThreads = &gThreadZero;
153         giNumActiveThreads = 1;
154         gThreadZero.Process = &gProcessZero;
155                 
156         Proc_Start();
157 }
158
159 void Threads_Delete(tThread *Thread)
160 {
161         // Set to dead
162         Thread->Status = THREAD_STAT_BURIED;
163
164         // Clear out process state
165         Proc_ClearThread(Thread);                       
166
167         Thread->Process->nThreads --;
168
169         if( Thread->Process->FirstThread == Thread )
170         {
171                 Thread->Process->FirstThread = Thread->ProcessNext;
172         }
173         else
174         {
175                 tThread *prev = Thread->Process->FirstThread;
176                 while(prev && prev->ProcessNext != Thread)
177                         prev = prev->ProcessNext;
178                 if( !prev )
179                         Log_Error("Threads", "Thread %p(%i %s) is not on the process's list",
180                                 Thread, Thread->TID, Thread->ThreadName
181                                 );
182                 else
183                         prev->ProcessNext = Thread->ProcessNext;
184         }
185
186         // If the final thread is being terminated, clean up the process
187         if( Thread->Process->nThreads == 0 )
188         {
189                 tProcess        *proc = Thread->Process;
190
191                 // Remove from global process list
192                 // TODO: RWLock
193                 if(proc->Prev)
194                         proc->Prev->Next = proc->Next;
195                 else
196                         gAllProcesses = proc->Next;
197                 if(proc->Next)
198                         proc->Next->Prev = proc->Prev;
199
200                 // VFS Cleanup
201                 VFS_CloseAllUserHandles();
202                 // Architecture cleanup
203                 Proc_ClearProcess( proc );
204                 // VFS Configuration strings
205                 if( proc->CurrentWorkingDir)
206                         free( proc->CurrentWorkingDir );
207                 if( proc->RootDir )
208                         free( proc->RootDir );
209                 // Process descriptor
210                 free( proc );
211         }
212         
213         // Free name
214         if( IsHeap(Thread->ThreadName) )
215                 free(Thread->ThreadName);
216         
217         // Remove from global list
218         // TODO: Lock this too
219         if( Thread == gAllThreads )
220                 gAllThreads = Thread->GlobalNext;
221         else
222                 Thread->GlobalPrev->GlobalNext = Thread->GlobalNext;
223         
224         free(Thread);
225 }
226
227 /**
228  * \fn void Threads_SetName(const char *NewName)
229  * \brief Sets the current thread's name
230  * \param NewName       New name for the thread
231  * \return Boolean Failure
232  */
233 int Threads_SetName(const char *NewName)
234 {
235         tThread *cur = Proc_GetCurThread();
236         char    *oldname = cur->ThreadName;
237         
238         // NOTE: There is a possibility of non-thread safety here
239         // A thread could read the current name pointer before it is zeroed
240         
241         cur->ThreadName = NULL;
242         
243         if( IsHeap(oldname) )   free( oldname );        
244         cur->ThreadName = strdup(NewName);
245
246         Log_Debug("Threads", "Thread renamed to '%s'", NewName);        
247
248         return 0;
249 }
250
251 /**
252  * \fn char *Threads_GetName(int ID)
253  * \brief Gets a thread's name
254  * \param ID    Thread ID (-1 indicates current thread)
255  * \return Pointer to name
256  * \retval NULL Failure
257  */
258 char *Threads_GetName(tTID ID)
259 {
260         if(ID == -1) {
261                 return Proc_GetCurThread()->ThreadName;
262         }
263         return Threads_GetThread(ID)->ThreadName;
264 }
265
266 /**
267  * \fn void Threads_SetPriority(tThread *Thread, int Pri)
268  * \brief Sets the priority of a task
269  * \param Thread        Thread to update ticket count (NULL means current thread)
270  * \param Pri   New priority
271  */
272 void Threads_SetPriority(tThread *Thread, int Pri)
273 {
274         // Get current thread
275         if(Thread == NULL)      Thread = Proc_GetCurThread();
276         // Bounds checking
277         // - If < 0, set to lowest priority
278         // - Minumum priority is actualy a high number, 0 is highest
279         if(Pri < 0)     Pri = MIN_PRIORITY;
280         if(Pri > MIN_PRIORITY)  Pri = MIN_PRIORITY;
281         
282         // Do we actually have to do anything?
283         if( Pri == Thread->Priority )   return;
284         
285         #if SCHEDULER_TYPE == SCHED_RR_PRI
286         if( Thread != Proc_GetCurThread() )
287         {
288                 SHORTLOCK( &glThreadListLock );
289                 // Remove from old priority
290                 Threads_int_DelFromQueue( &gaActiveThreads[Thread->Priority], Thread );
291                 // And add to new
292                 Threads_int_AddToList( &gaActiveThreads[Pri], Thread );
293                 Thread->Priority = Pri;
294                 SHORTREL( &glThreadListLock );
295         }
296         else
297                 Thread->Priority = Pri;
298         #else
299         // If this isn't the current thread, we need to lock
300         if( Thread != Proc_GetCurThread() )
301         {
302                 SHORTLOCK( &glThreadListLock );
303                 
304                 #if SCHEDULER_TYPE == SCHED_LOTTERY
305                 giFreeTickets -= caiTICKET_COUNTS[Thread->Priority] - caiTICKET_COUNTS[Pri];
306                 # if DEBUG_TRACE_TICKETS
307                 Log("Threads_SetTickets: new giFreeTickets = %i [-%i+%i]",
308                         giFreeTickets,
309                         caiTICKET_COUNTS[Thread->Priority], caiTICKET_COUNTS[Pri]);
310                 # endif
311                 #endif
312                 Thread->Priority = Pri;
313                 SHORTREL( &glThreadListLock );
314         }
315         else
316                 Thread->Priority = Pri;
317         #endif
318         
319         #if DEBUG_TRACE_STATE
320         Log("Threads_SetPriority: %p(%i %s) pri set %i",
321                 Thread, Thread->TID, Thread->ThreadName,
322                 Pri);
323         #endif
324 }
325
326 /**
327  * \brief Clone the TCB of the current thread
328  * \param Flags Flags for something... (What is this for?)
329  */
330 tThread *Threads_CloneTCB(Uint Flags)
331 {
332         tThread *cur, *new;
333         cur = Proc_GetCurThread();
334         
335         // Allocate and duplicate
336         new = malloc(sizeof(tThread));
337         if(new == NULL) { errno = -ENOMEM; return NULL; }
338         memcpy(new, cur, sizeof(tThread));
339         
340         new->CurCPU = -1;
341         new->Next = NULL;
342         memset( &new->IsLocked, 0, sizeof(new->IsLocked));
343         new->Status = THREAD_STAT_PREINIT;
344         new->RetStatus = 0;
345         
346         // Get Thread ID
347         new->TID = giNextTID++;
348         new->Parent = cur;
349         new->bInstrTrace = 0;
350         
351         // Clone Name
352         new->ThreadName = strdup(cur->ThreadName);
353         
354         // Set Thread Group ID (PID)
355         if(Flags & CLONE_VM) {
356                 tProcess        *newproc, *oldproc;
357                 oldproc = cur->Process;
358                 new->Process = calloc( sizeof(struct sProcess), 1 );
359                 newproc = new->Process;
360                 newproc->PID = new->TID;
361                 if( Flags & CLONE_PGID )
362                         newproc->PGID = oldproc->PGID;
363                 else
364                         newproc->PGID = newproc->PID;
365                 newproc->UID = oldproc->UID;
366                 newproc->GID = oldproc->GID;
367                 newproc->MaxFD = oldproc->MaxFD;
368                 newproc->CurrentWorkingDir = oldproc->CurrentWorkingDir ? strdup( oldproc->CurrentWorkingDir ) : NULL;
369                 newproc->RootDir = oldproc->RootDir ? strdup( oldproc->RootDir ) : NULL;
370                 newproc->nThreads = 1;
371                 // Reference all handles in the VFS
372                 VFS_ReferenceUserHandles();
373                 
374                 // Add to global list
375                 newproc->Prev = NULL;
376                 // TODO: RWLock
377                 newproc->Next = gAllProcesses;
378                 gAllProcesses = newproc;
379
380                 newproc->FirstThread = new;
381                 new->ProcessNext = NULL;
382         }
383         else {
384                 new->Process->nThreads ++;
385                 new->Process = cur->Process;
386                 // TODO: Locking
387                 new->ProcessNext = new->Process->FirstThread;
388                 new->Process->FirstThread = new;
389         }
390         
391         // Messages are not inherited
392         new->Messages = NULL;
393         new->LastMessage = NULL;
394         
395         // Set State
396         new->Remaining = new->Quantum = cur->Quantum;
397         new->Priority = cur->Priority;
398         new->_errno = 0;
399         
400         // Set Signal Handlers
401         new->CurFaultNum = 0;
402         new->FaultHandler = cur->FaultHandler;
403         
404         // Maintain a global list of threads
405         SHORTLOCK( &glThreadListLock );
406         new->GlobalPrev = NULL; // Protect against bugs
407         new->GlobalNext = gAllThreads;
408         gAllThreads->GlobalPrev = new;
409         gAllThreads = new;
410         SHORTREL( &glThreadListLock );
411         
412         return new;
413 }
414
415 /**
416  * \brief Clone the TCB of the kernel thread
417  */
418 tThread *Threads_CloneThreadZero(void)
419 {
420         tThread *new;
421         
422         // Allocate and duplicate
423         new = malloc(sizeof(tThread));
424         if(new == NULL) {
425                 return NULL;
426         }
427         memcpy(new, &gThreadZero, sizeof(tThread));
428
429         new->Process->nThreads ++;
430         
431         new->CurCPU = -1;
432         new->Next = NULL;
433         memset( &new->IsLocked, 0, sizeof(new->IsLocked));
434         new->Status = THREAD_STAT_PREINIT;
435         new->RetStatus = 0;
436         
437         // Get Thread ID
438         new->TID = giNextTID++;
439         new->Parent = 0;
440         
441         // Clone Name
442         new->ThreadName = NULL;
443         
444         // Messages are not inherited
445         new->Messages = NULL;
446         new->LastMessage = NULL;
447         
448         // Set State
449         new->Remaining = new->Quantum = DEFAULT_QUANTUM;
450         new->Priority = DEFAULT_PRIORITY;
451         new->bInstrTrace = 0;
452         
453         // Set Signal Handlers
454         new->CurFaultNum = 0;
455         new->FaultHandler = 0;
456         
457         // Maintain a global list of threads
458         SHORTLOCK( &glThreadListLock );
459         new->GlobalPrev = NULL; // Protect against bugs
460         new->GlobalNext = gAllThreads;
461         gAllThreads->GlobalPrev = new;
462         gAllThreads = new;
463         SHORTREL( &glThreadListLock );
464         
465         return new;
466 }
467
468 /**
469  * \brief Wait for a task to change state
470  * \param TID   Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
471  * \param Status        Thread return status
472  * \return TID of child that changed state
473  */
474 tTID Threads_WaitTID(int TID, int *Status)
475 {       
476         // Any Child
477         if(TID == -1)
478         {
479                 Uint32 ev = Threads_WaitEvents(THREAD_EVENT_DEADCHILD);
480                 tTID    ret = -1;
481                 if( ev & THREAD_EVENT_DEADCHILD )
482                 {
483                         // A child died, get the TID
484                         tThread *us = Proc_GetCurThread();
485                         ASSERT(us->LastDeadChild);
486                         ret = us->LastDeadChild->TID;
487                         // - Mark as dead (as opposed to undead)
488                         ASSERT(us->LastDeadChild->Status == THREAD_STAT_ZOMBIE);
489                         us->LastDeadChild->Status = THREAD_STAT_DEAD;
490                         // - Set return status
491                         if(Status)
492                                 *Status = us->LastDeadChild->RetStatus;
493                         us->LastDeadChild = NULL;
494                         Mutex_Release(&us->DeadChildLock);
495                 }
496                 else
497                 {
498                         Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
499                 }
500                 return ret;
501         }
502         
503         // Any peer/child thread
504         if(TID == 0) {
505                 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
506                 return -1;
507         }
508         
509         // TGID = abs(TID)
510         if(TID < -1) {
511                 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
512                 return -1;
513         }
514         
515         // Specific Thread
516         if(TID > 0)
517         {
518                 // TODO: Register on thread to be poked when it dies
519                 tTID    ret;
520                 // NOTE: Race condition - Other child dies, desired child dies, first death is 'lost'
521                 while( (ret = Threads_WaitTID(-1, Status)) != TID )
522                 {
523                         if( ret == -1 )
524                                 break;
525                 }
526                 return ret;
527         }
528         
529         return -1;
530 }
531
532 /**
533  * \brief Gets a thread given its TID
534  * \param TID   Thread ID
535  * \return Thread pointer
536  */
537 tThread *Threads_GetThread(Uint TID)
538 {
539         tThread *thread;
540         
541         // Search global list
542         for( thread = gAllThreads; thread; thread = thread->GlobalNext )
543         {
544                 if(thread->TID == TID)
545                         return thread;
546         }
547
548         Log_Notice("Threads", "Unable to find TID %i on main list\n", TID);
549         
550         return NULL;
551 }
552
553 /**
554  * \brief Deletes an entry from a list
555  * \param List  Pointer to the list head
556  * \param Thread        Thread to find
557  * \return \a Thread
558  */
559 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
560 {
561         tThread *ret, *prev = NULL;
562         
563         for(ret = List->Head;
564                 ret && ret != Thread;
565                 prev = ret, ret = ret->Next
566                 );
567         
568         // Is the thread on the list
569         if(!ret) {
570                 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
571                 return NULL;
572         }
573         
574         if( !prev ) {
575                 List->Head = Thread->Next;
576                 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
577         }
578         else {
579                 prev->Next = Thread->Next;
580                 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
581         }
582         if( Thread->Next == NULL )
583                 List->Tail = prev;
584         
585         return Thread;
586 }
587
588 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
589 {
590         if( List->Head )
591                 List->Tail->Next = Thread;
592         else
593                 List->Head = Thread;
594         List->Tail = Thread;
595         Thread->Next = NULL;
596 }
597
598 /**
599  * \brief Exit the current process (or another?)
600  * \param TID   Thread ID to kill
601  * \param Status        Exit status
602  */
603 void Threads_Exit(int TID, int Status)
604 {
605         if( TID == 0 )
606                 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
607         else
608                 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
609         
610         // Halt forever, just in case
611         for(;;) HALT();
612 }
613
614 /**
615  * \fn void Threads_Kill(tThread *Thread, int Status)
616  * \brief Kill a thread
617  * \param Thread        Thread to kill
618  * \param Status        Status code to return to the parent
619  */
620 void Threads_Kill(tThread *Thread, int Status)
621 {
622         tMsg    *msg;
623          int    isCurThread = Thread == Proc_GetCurThread();
624         
625         // TODO: Disown all children?
626         #if 1
627         {
628                 tThread *child;
629                 // TODO: I should keep a .Children list
630                 for(child = gAllThreads;
631                         child;
632                         child = child->GlobalNext)
633                 {
634                         if(child->Parent == Thread)
635                                 child->Parent = &gThreadZero;
636                 }
637         }
638         #endif
639         
640         ///\note Double lock is needed due to overlap of lock areas
641         
642         // Lock thread (stop us recieving messages)
643         SHORTLOCK( &Thread->IsLocked );
644         
645         // Clear Message Queue
646         while( Thread->Messages )
647         {
648                 msg = Thread->Messages->Next;
649                 free( Thread->Messages );
650                 Thread->Messages = msg;
651         }
652         
653         // Lock thread list
654         SHORTLOCK( &glThreadListLock );
655         
656         switch(Thread->Status)
657         {
658         case THREAD_STAT_PREINIT:       // Only on main list
659                 break;
660         
661         // Currently active thread
662         case THREAD_STAT_ACTIVE:
663                 if( Thread != Proc_GetCurThread() )
664                 {
665                         #if SCHEDULER_TYPE == SCHED_RR_PRI
666                         tThreadList     *list = &gaActiveThreads[Thread->Priority];
667                         #else
668                         tThreadList     *list = &gActiveThreads;
669                         #endif
670                         if( Threads_int_DelFromQueue( list, Thread ) )
671                         {
672                         }
673                         else
674                         {
675                                 Log_Warning("Threads",
676                                         "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
677                                         Thread, Thread->TID, Thread->ThreadName
678                                         );
679                         }
680                         #if SCHEDULER_TYPE == SCHED_LOTTERY
681                         giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
682                         #endif
683                 }
684                 // Ensure that we are not rescheduled
685                 Thread->Remaining = 0;  // Clear Remaining Quantum
686                 Thread->Quantum = 0;    // Clear Quantum to indicate dead thread
687                         
688                 // Update bookkeeping
689                 giNumActiveThreads --;
690                 break;
691         // Kill it while it sleeps!
692         case THREAD_STAT_SLEEPING:
693                 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
694                 {
695                         Log_Warning("Threads",
696                                 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
697                                 Thread, Thread->TID, Thread->ThreadName
698                                 );
699                 }
700                 break;
701         
702         // Brains!... You cannot kill something that is already dead
703         case THREAD_STAT_ZOMBIE:
704                 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
705                         Thread, Thread->TID, Thread->ThreadName);
706                 SHORTREL( &glThreadListLock );
707                 SHORTREL( &Thread->IsLocked );
708                 return ;
709         
710         default:
711                 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
712                         Thread->Status);
713                 break;
714         }
715         
716         // Save exit status
717         Thread->RetStatus = Status;
718
719         SHORTREL( &Thread->IsLocked );
720
721         Thread->Status = THREAD_STAT_ZOMBIE;
722         SHORTREL( &glThreadListLock );
723         // TODO: It's possible that we could be timer-preempted here, should disable that... somehow
724         Mutex_Acquire( &Thread->Parent->DeadChildLock );        // released by parent
725         Thread->Parent->LastDeadChild = Thread;
726         Threads_PostEvent( Thread->Parent, THREAD_EVENT_DEADCHILD );
727         
728         Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
729         
730         // And, reschedule
731         if(isCurThread)
732         {
733                 for( ;; )
734                         Proc_Reschedule();
735         }
736 }
737
738 /**
739  * \brief Yield remainder of the current thread's timeslice
740  */
741 void Threads_Yield(void)
742 {
743 //      Log("Threads_Yield: by %p", __builtin_return_address(0));
744         Proc_Reschedule();
745 }
746
747 /**
748  * \breif Wait for the thread status to not be a specified value
749  */
750 void Threads_int_WaitForStatusEnd(enum eThreadStatus Status)
751 {
752         tThread *us = Proc_GetCurThread();
753         ASSERT(Status != THREAD_STAT_ACTIVE);
754         ASSERT(Status != THREAD_STAT_DEAD);
755         while( us->Status == Status )
756         {
757                 Proc_Reschedule();
758                 if( us->Status == Status )
759                         Debug("Thread %p(%i %s) rescheduled while in %s state for %p",
760                                 us, us->TID, us->ThreadName,
761                                 casTHREAD_STAT[Status],
762                                 __builtin_return_address(0));
763         }
764 }
765
766 int Threads_int_Sleep(enum eThreadStatus Status, void *Ptr, int Num, tThread **ListHead, tThread **ListTail, tShortSpinlock *Lock)
767 {
768         SHORTLOCK( &glThreadListLock );
769         tThread *us = Threads_RemActive();
770         us->Next = NULL;
771         // - Mark as sleeping
772         us->Status = Status;
773         us->WaitPointer = Ptr;
774         us->RetStatus = Num;    // Use RetStatus as a temp variable
775                 
776         // - Add to waiting
777         if( ListTail ) {
778                 if(*ListTail) {
779                         (*ListTail)->Next = us;
780                 }
781                 else {
782                         *ListHead = us;
783                 }
784                 *ListTail = us;
785         }
786         else if( ListHead ) {
787                 us->Next = *ListHead;
788                 *ListHead = us;
789         }
790         else {
791                 // Nothing
792         }
793         
794         //if( Proc_ThreadSync(us) )
795         //      return ;
796         SHORTREL( &glThreadListLock );
797         if( Lock )
798                 SHORTREL( Lock );
799         Threads_int_WaitForStatusEnd(Status);
800         us->WaitPointer = NULL;
801         return us->RetStatus;
802 }
803
804 /**
805  * \fn void Threads_Sleep(void)
806  * \brief Take the current process off the run queue
807  */
808 void Threads_Sleep(void)
809 {
810         tThread *cur = Proc_GetCurThread();
811         
812         // Acquire Spinlock
813         SHORTLOCK( &glThreadListLock );
814         
815         // Don't sleep if there is a message waiting
816         if( cur->Messages ) {
817                 SHORTREL( &glThreadListLock );
818                 return;
819         }
820         
821         // Remove us from running queue
822         Threads_RemActive();
823         // Mark thread as sleeping
824         cur->Status = THREAD_STAT_SLEEPING;
825         
826         // Add to Sleeping List (at the top)
827         Threads_int_AddToList( &gSleepingThreads, cur );
828         
829         #if DEBUG_TRACE_STATE
830         Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
831         #endif
832         
833         // Release Spinlock
834         SHORTREL( &glThreadListLock );
835         Threads_int_WaitForStatusEnd(THREAD_STAT_SLEEPING);
836 }
837
838
839 /**
840  * \brief Wakes a sleeping/waiting thread up
841  * \param Thread        Thread to wake
842  * \return Boolean Failure (Returns ERRNO)
843  * \warning This should ONLY be called with task switches disabled
844  */
845 int Threads_Wake(tThread *Thread)
846 {
847         if(!Thread)
848                 return -EINVAL;
849         
850         switch(Thread->Status)
851         {
852         case THREAD_STAT_ACTIVE:
853                 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
854                 return -EALREADY;
855         
856         case THREAD_STAT_SLEEPING:
857                 // Remove from sleeping queue
858                 SHORTLOCK( &glThreadListLock );
859                 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
860                 SHORTREL( &glThreadListLock );
861                 
862                 Threads_AddActive( Thread );
863                 
864                 #if DEBUG_TRACE_STATE
865                 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
866                 #endif
867                 return -EOK;
868         
869         case THREAD_STAT_SEMAPHORESLEEP: {
870                 tSemaphore      *sem;
871                 tThread *th, *prev=NULL;
872                 
873                 sem = Thread->WaitPointer;
874                 
875                 SHORTLOCK( &sem->Protector );
876                 
877                 // Remove from sleeping queue
878                 for( th = sem->Waiting; th; prev = th, th = th->Next )
879                         if( th == Thread )      break;
880                 if( th )
881                 {
882                         if(prev)
883                                 prev->Next = Thread->Next;
884                         else
885                                 sem->Waiting = Thread->Next;
886                         if(sem->LastWaiting == Thread)
887                                 sem->LastWaiting = prev;
888                 }
889                 else
890                 {
891                         prev = NULL;
892                         for( th = sem->Signaling; th; prev = th, th = th->Next )
893                                 if( th == Thread )      break;
894                         if( !th ) {
895                                 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
896                                         Thread, Thread->TID, Thread->ThreadName,
897                                         sem, sem->ModName, sem->Name);
898                                 return -EINTERNAL;
899                         }
900                         
901                         if(prev)
902                                 prev->Next = Thread->Next;
903                         else
904                                 sem->Signaling = Thread->Next;
905                         if(sem->LastSignaling == Thread)
906                                 sem->LastSignaling = prev;
907                 }
908                 
909                 Thread->RetStatus = 0;  // It didn't get anything
910                 Threads_AddActive( Thread );
911                 
912                 #if DEBUG_TRACE_STATE
913                 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
914                 #endif
915                 SHORTREL( &sem->Protector );
916                 } return -EOK;
917         
918         case THREAD_STAT_WAITING:
919                 Warning("Threads_Wake - Waiting threads are not currently supported");
920                 return -ENOTIMPL;
921         
922         case THREAD_STAT_DEAD:
923                 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
924                 return -ENOTIMPL;
925         
926         default:
927                 Log_Warning("Threads", "Threads_Wake - Unknown process status (%i)", Thread->Status);
928                 return -EINTERNAL;
929         }
930 }
931
932 /**
933  * \brief Wake a thread given the TID
934  * \param TID   Thread ID to wake
935  * \return Boolean Faulure (errno)
936  */
937 int Threads_WakeTID(tTID TID)
938 {
939         tThread *thread = Threads_GetThread(TID);
940          int    ret;
941         if(!thread)
942                 return -ENOENT;
943         ret = Threads_Wake( thread );
944         //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
945         return ret;
946 }
947
948 void Threads_ToggleTrace(int TID)
949 {
950         tThread *thread = Threads_GetThread(TID);
951         if(!thread)     return ;
952         thread->bInstrTrace = !thread->bInstrTrace;
953 }
954
955 /**
956  * \brief Adds a thread to the active queue
957  */
958 void Threads_AddActive(tThread *Thread)
959 {
960         #if DEBUG_TRACE_ACTIVEQUEUE
961         Debug("Threads_AddActive("PRIthread_fmt")", PRIthread_args(Thread));
962         #endif
963         SHORTLOCK( &glThreadListLock );
964         
965         if( Thread->Status == THREAD_STAT_ACTIVE )
966         {
967                 tThread *cur = Proc_GetCurThread();
968                 Log_KernelPanic("Threads",
969                         "ret=%p CPU%i "PRIthread_fmt" is adding "PRIthread_fmt" when it is active",
970                         __builtin_return_address(0),
971                         GetCPUNum(), PRIthread_args(cur), PRIthread_args(Thread));
972                 SHORTREL( &glThreadListLock );
973                 return ;
974         }
975         
976         // Set state
977         Thread->Status = THREAD_STAT_ACTIVE;
978         // Add to active list
979         // - Thread can be the current thread if we're interrupted just before
980         //   Proc_Reschedule in a sleep state.
981         if( Thread != Proc_GetCurThread() )
982         {
983                 #if SCHEDULER_TYPE == SCHED_RR_PRI
984                 tThreadList     *list = &gaActiveThreads[Thread->Priority];
985                 #else
986                 tThreadList     *list = &gActiveThreads;
987                 #endif
988                 #if DEBUG_TRACE_ACTIVEQUEUE
989                 Debug(" - Head="PRIthread_fmt",Tail="PRIthread_fmt"",
990                         PRIthread_args(list->Head),
991                         PRIthread_args(list->Tail)
992                         );
993                 #endif
994                 Threads_int_AddToList( list, Thread );
995         }
996         
997         // Update bookkeeping
998         giNumActiveThreads ++;
999         
1000         #if SCHEDULER_TYPE == SCHED_LOTTERY
1001         {
1002                  int    delta;
1003                 // Only change the ticket count if the thread is un-scheduled
1004                 if(Thread->CurCPU != -1)
1005                         delta = 0;
1006                 else
1007                         delta = caiTICKET_COUNTS[ Thread->Priority ];
1008                 
1009                 giFreeTickets += delta;
1010                 # if DEBUG_TRACE_TICKETS
1011                 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
1012                         GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
1013                         giFreeTickets, delta
1014                         );
1015                 # endif
1016         }
1017         #endif
1018         
1019         SHORTREL( &glThreadListLock );
1020 }
1021
1022 /**
1023  * \brief Removes the current thread from the active queue
1024  * \warning This should ONLY be called with the lock held
1025  * \return Current thread pointer
1026  */
1027 tThread *Threads_RemActive(void)
1028 {
1029         tThread *us = Proc_GetCurThread();
1030         #if DEBUG_TRACE_ACTIVEQUEUE
1031         Debug("Threads_RemActive(%p(%i %s))", us, us->TID, us->ThreadName);
1032         #endif
1033         giNumActiveThreads --;
1034         return us;
1035 }
1036
1037 /**
1038  * \fn void Threads_SetFaultHandler(Uint Handler)
1039  * \brief Sets the signal handler for a signal
1040  */
1041 void Threads_SetFaultHandler(Uint Handler)
1042 {       
1043         //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
1044         Proc_GetCurThread()->FaultHandler = Handler;
1045 }
1046
1047 /**
1048  * \fn void Threads_Fault(int Num)
1049  * \brief Calls a fault handler
1050  */
1051 void Threads_Fault(int Num)
1052 {
1053         tThread *thread = Proc_GetCurThread();
1054         
1055         if(!thread)     return ;
1056         
1057         Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
1058         
1059         switch(thread->FaultHandler)
1060         {
1061         case 0: // Panic?
1062                 Threads_Kill(thread, -1);
1063                 HALT();
1064                 return ;
1065         case 1: // Dump Core?
1066                 Threads_Kill(thread, -1);
1067                 HALT();
1068                 return ;
1069         }
1070         
1071         // Double Fault? Oh, F**k
1072         if(thread->CurFaultNum != 0) {
1073                 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
1074                 Threads_Kill(thread, -1);       // For now, just kill
1075                 HALT();
1076         }
1077         
1078         thread->CurFaultNum = Num;
1079         
1080         Proc_CallFaultHandler(thread);
1081 }
1082
1083 /**
1084  * \fn void Threads_SegFault(tVAddr Addr)
1085  * \brief Called when a Segment Fault occurs
1086  */
1087 void Threads_SegFault(tVAddr Addr)
1088 {
1089         tThread *cur = Proc_GetCurThread();
1090         cur->bInstrTrace = 0;
1091         Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
1092         MM_DumpTables(0, USER_MAX);
1093         Threads_Fault( 1 );
1094         //Threads_Exit( 0, -1 );
1095 }
1096
1097
1098 void Threads_PostSignalTo(tThread *Thread, int SignalNum)
1099 {
1100         ASSERT(Thread);
1101         Log_Debug("Threads", "Signalling %i(%s) with %i", Thread->TID, Thread->ThreadName, SignalNum);
1102         Thread->PendingSignal = SignalNum;
1103         Threads_PostEvent(Thread, THREAD_EVENT_SIGNAL);
1104 }
1105 void Threads_PostSignal(int SignalNum)
1106 {
1107         Threads_PostSignalTo( Proc_GetCurThread(), SignalNum );
1108 }
1109
1110 void Threads_SignalGroup(tPGID PGID, int Signal)
1111 {
1112         for( tProcess *proc = gAllProcesses; proc; proc = proc->Next )
1113         {
1114                 if(proc->PGID == PGID)
1115                 {
1116                         Threads_PostSignalTo(proc->FirstThread, Signal);
1117                 }
1118         }
1119 }
1120
1121 /**
1122  */
1123 int Threads_GetPendingSignal(void)
1124 {
1125         tThread *cur = Proc_GetCurThread();
1126         
1127         // Atomic AND with 0 fetches and clears in one operation
1128         int ret = __sync_fetch_and_and( &cur->PendingSignal, 0 );
1129         if( ret )
1130         {
1131                 Log_Debug("Threads", "Thread %i(%s) has signal %i pending",
1132                         cur->TID, cur->ThreadName, ret);
1133         }
1134         return ret;
1135 }
1136
1137 /*
1138  * \brief Update the current thread's signal handler
1139  */
1140 void Threads_SetSignalHandler(int SignalNum, void *Handler)
1141 {
1142         if( SignalNum <= 0 || SignalNum >= NSIGNALS )
1143                 return ;
1144         if( !MM_IsUser(Handler) )
1145                 return ;
1146         Proc_GetCurThread()->Process->SignalHandlers[SignalNum] = Handler;
1147 }
1148
1149 /**
1150  * \brief Gets the registered (or default, if none set) handler for a signal.
1151  * \return Handler function pointer, OR NULL if no signal to be ignored
1152  */
1153 void *Threads_GetSignalHandler(int SignalNum)
1154 {
1155         // TODO: Core dump
1156         void *User_Signal_Core = User_Signal_Kill;
1157         
1158         if( SignalNum <= 0 || SignalNum >= NSIGNALS )
1159                 return NULL;
1160         void *ret = Proc_GetCurThread()->Process->SignalHandlers[SignalNum];
1161         if( !ret || (SignalNum == SIGKILL || SignalNum == SIGSTOP) )
1162         {
1163                 // Defaults
1164                 switch(SignalNum)
1165                 {
1166                 case SIGHUP:
1167                 case SIGINT:
1168                         ret = User_Signal_Kill;
1169                         break;
1170                 case SIGQUIT:
1171                 case SIGILL:
1172                 case SIGABRT:
1173                 case SIGFPE:
1174                         ret = User_Signal_Core;
1175                         break;
1176                 case SIGKILL:
1177                         ret = User_Signal_Kill;
1178                         break;
1179                 case SIGSEGV:
1180                         ret = User_Signal_Core;
1181                         break;
1182                 case SIGPIPE:
1183                 case SIGALRM:
1184                 case SIGTERM:
1185                         ret = User_Signal_Kill;
1186                         break;
1187                 default:
1188                         ret = NULL;
1189                         break;
1190                 }
1191         }
1192         Log_Debug("Threads", "Handler %p for signal %i", ret, SignalNum);
1193         return ret;
1194 }
1195
1196 // --- Process Structure Access Functions ---
1197 tPGID Threads_GetPGID(void)
1198 {
1199         return Proc_GetCurThread()->Process->PGID;
1200 }
1201 tPID Threads_GetPID(void)
1202 {
1203         return Proc_GetCurThread()->Process->PID;
1204 }
1205 tTID Threads_GetTID(void)
1206 {
1207         return Proc_GetCurThread()->TID;
1208 }
1209 tUID Threads_GetUID(void)
1210 {
1211         return Proc_GetCurThread()->Process->UID;
1212 }
1213 tGID Threads_GetGID(void)
1214 {
1215         return Proc_GetCurThread()->Process->GID;
1216 }
1217
1218 int Threads_SetUID(tUID ID)
1219 {
1220         tThread *t = Proc_GetCurThread();
1221         if( t->Process->UID != 0 ) {
1222                 errno = -EACCES;
1223                 return -1;
1224         }
1225         Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1226         t->Process->UID = ID;
1227         return 0;
1228 }
1229
1230 int Threads_SetGID(tGID ID)
1231 {
1232         tThread *t = Proc_GetCurThread();
1233         if( t->Process->UID != 0 ) {
1234                 errno = -EACCES;
1235                 return -1;
1236         }
1237         Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1238         t->Process->GID = ID;
1239         return 0;
1240 }
1241
1242 // --- Per-thread storage ---
1243 int *Threads_GetErrno(void)
1244 {
1245         return &Proc_GetCurThread()->_errno;
1246 }
1247
1248 // --- Configuration ---
1249 int *Threads_GetMaxFD(void)
1250 {
1251         return &Proc_GetCurThread()->Process->MaxFD;
1252 }
1253 char **Threads_GetChroot(void)
1254 {
1255         return &Proc_GetCurThread()->Process->RootDir;
1256 }
1257 char **Threads_GetCWD(void)
1258 {
1259         return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1260 }
1261 // ---
1262
1263 void Threads_int_DumpThread(tThread *thread)
1264 {
1265         if( !thread ) {
1266                 Log(" %p NULL", thread);
1267                 return ;
1268         }
1269         if( !CheckMem(thread, sizeof(tThread)) ) {
1270                 Log(" %p INVAL", thread);
1271                 return ;
1272         }
1273         tPID    pid = (thread->Process ? thread->Process->PID : -1);
1274         const char      *statstr = (thread->Status < sizeof(casTHREAD_STAT)/sizeof(casTHREAD_STAT[0])
1275                 ? casTHREAD_STAT[thread->Status] : "");
1276         Log(" %p %i (%i) - %s (CPU %i) - %i (%s)",
1277                 thread, thread->TID, pid, thread->ThreadName, thread->CurCPU,
1278                 thread->Status, statstr
1279                 );
1280         switch(thread->Status)
1281         {
1282         case THREAD_STAT_MUTEXSLEEP:
1283                 Log("  Mutex Pointer: %p", thread->WaitPointer);
1284                 break;
1285         case THREAD_STAT_RWLOCKSLEEP:
1286                 Log("  Lock Pointer: %p", thread->WaitPointer);
1287                 Log("  Lock Name: %s",
1288                         ((tRWLock*)thread->WaitPointer)->Name);
1289                 break;
1290         case THREAD_STAT_SEMAPHORESLEEP:
1291                 Log("  Semaphore Pointer: %p", thread->WaitPointer);
1292                 Log("  Semaphore Name: %s:%s", 
1293                         ((tSemaphore*)thread->WaitPointer)->ModName,
1294                         ((tSemaphore*)thread->WaitPointer)->Name
1295                         );
1296                 break;
1297         case THREAD_STAT_EVENTSLEEP:
1298                 Log("  Event Mask: %x", thread->RetStatus);
1299                 break;
1300         case THREAD_STAT_ZOMBIE:
1301                 Log("  Return Status: %i", thread->RetStatus);
1302                 break;
1303         default:        break;
1304         }
1305         Log("  Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1306         Log("  KStack %p", thread->KernelStack);
1307         if( thread->bInstrTrace )
1308                 Log("  Tracing Enabled");
1309         Proc_DumpThreadCPUState(thread);
1310 }
1311
1312 /**
1313  * \fn void Threads_Dump(void)
1314  */
1315 void Threads_DumpActive(void)
1316 {
1317         Log("Active Threads: (%i reported)", giNumActiveThreads);
1318         
1319         #if SCHEDULER_TYPE == SCHED_RR_PRI
1320         for( int i = 0; i < MIN_PRIORITY+1; i++ )
1321         {
1322                 tThreadList *list = &gaActiveThreads[i];
1323         #else
1324                 tThreadList *list = &gActiveThreads;
1325         #endif
1326                 for(tThread *thread = list->Head; thread; thread = thread->Next)
1327                 {
1328                         Threads_int_DumpThread(thread);
1329                         if(thread->Status != THREAD_STAT_ACTIVE)
1330                                 Log("  ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1331                                         thread->Status, THREAD_STAT_ACTIVE);
1332                 }
1333         
1334         #if SCHEDULER_TYPE == SCHED_RR_PRI
1335         }
1336         #endif
1337 }
1338
1339 /**
1340  * \fn void Threads_Dump(void)
1341  * \brief Dumps a list of currently running threads
1342  */
1343 void Threads_Dump(void)
1344 {
1345         Log("--- Thread Dump ---");
1346         Threads_DumpActive();
1347         
1348         Log("All Threads:");
1349         for(tThread *thread = gAllThreads; thread; thread = thread->GlobalNext)
1350         {
1351                 Threads_int_DumpThread(thread);
1352         }
1353 }
1354
1355 tThread *Threads_int_GetRunnable(void)
1356 {
1357         #if SCHEDULER_TYPE == SCHED_LOTTERY
1358         // -----------------------------------
1359         // Lottery Scheduler
1360         // -----------------------------------
1361         #if DEBUG_VALIDATE_TICKET_COUNTS
1362         {
1363                 int total_tickets = 0;
1364                 for(const tThread *thread = gActiveThreads.Head; thread; thread = thread->Next)
1365                 {
1366                         if(thread->Status != THREAD_STAT_ACTIVE)
1367                                 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1368                                         thread, thread->TID, thread->ThreadName, thread->Status);
1369                         if(thread->Next == thread) {
1370                                 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1371                                         thread, thread->TID, thread->ThreadName, thread->Status);
1372                         }
1373                         total_tickets += caiTICKET_COUNTS[ thread->Priority ];
1374                 }
1375                 if(total_tickets != giFreeTickets)
1376                 {
1377                         Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1378                                 giFreeTickets, total_tickets, CPU);
1379                 }
1380         }
1381         # endif
1382         
1383         // No free tickets (all tasks delegated to cores)
1384         if( giFreeTickets == 0 )
1385         {
1386                 return NULL;
1387         }
1388         
1389         // Get the ticket number
1390         int ticket = rand() % giFreeTickets;
1391         int number = ticket;
1392         
1393         // Find the next thread
1394         tThread **pnp = &gActiveThreads.Head;
1395         tThread *thread;
1396         for(thread = gActiveThreads.Head; thread; pnp = &thread->Next, thread = thread->Next )
1397         {
1398                 if( caiTICKET_COUNTS[ thread->Priority ] > number)
1399                         break;
1400                 number -= caiTICKET_COUNTS[ thread->Priority ];
1401         }
1402         
1403         // If we didn't find a thread, something went wrong
1404         if(thread == NULL)
1405         {
1406                 int total_tickets = 0;
1407                 for(thread=gActiveThreads;thread;thread=thread->Next) {
1408                         if(thread->CurCPU >= 0) continue;
1409                         total_tickets += caiTICKET_COUNTS[ thread->Priority ];
1410                 }
1411                 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1412                         giFreeTickets, total_tickets);
1413         }
1414
1415         // Remove
1416         *pnp = thread->Next;
1417         if( !thread->Next )
1418                 gActiveThreads.Tail = prev;             
1419
1420         giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1421         # if DEBUG_TRACE_TICKETS
1422         LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1423                 CPU, thread, thread->TID, thread->ThreadName,
1424                 giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1425         # endif
1426         return thread;
1427         
1428         #elif SCHEDULER_TYPE == SCHED_RR_PRI
1429         
1430         // -----------------------------------
1431         // Priority based round robin scheduler
1432         // -----------------------------------
1433         for( int i = 0; i < MIN_PRIORITY + 1; i ++ )
1434         {
1435                 if( gaActiveThreads[i].Head == NULL )
1436                         continue ;
1437         
1438                 tThread *thread = gaActiveThreads[i].Head;
1439
1440                 if( thread->Status != THREAD_STAT_ACTIVE ) {
1441                         for( const tThread *t = gaActiveThreads[i].Head; t; t = t->Next )
1442                                 LogF("- %p(%i %s)\n", t, t->TID, t->ThreadName);
1443                         Panic("Thread %p(%i %s) from pqueue %i is active!",
1444                                 thread, thread->TID, thread->ThreadName, i);
1445                 }
1446
1447                 // Remove from head
1448                 gaActiveThreads[i].Head = thread->Next;
1449                 if(!thread->Next)
1450                         gaActiveThreads[i].Tail = NULL;
1451                 thread->Next = NULL;
1452                 return thread;
1453         }
1454         return NULL;
1455         
1456         #elif SCHEDULER_TYPE == SCHED_RR_SIM
1457         
1458         // -----------------------------------
1459         // Single-list round-robin
1460         // -----------------------------------
1461         tThread *thread = gActiveThreads.Head;
1462         if( thread )
1463         {
1464                 gActiveThreads.Head = thread->Next;
1465                 if(!thread->Next)
1466                         gaActiveThreads.Tail = NULL;
1467                 thread->Next = NULL;
1468         }
1469         return thread;
1470         #else
1471         # error "Unimplemented scheduling algorithm"
1472         return NULL;
1473         #endif
1474 }
1475
1476 /**
1477  * \brief Gets the next thread to run
1478  * \param CPU   Current CPU
1479  * \param Last  The thread the CPU was running
1480  */
1481 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1482 {
1483         // If this CPU has the lock, we must let it complete
1484         if( CPU_HAS_LOCK( &glThreadListLock ) )
1485                 return Last;
1486         
1487         // Don't change threads if the current CPU has switches disabled
1488         if( gaThreads_NoTaskSwitch[CPU] )
1489                 return Last;
1490
1491         // Lock thread list
1492         SHORTLOCK( &glThreadListLock );
1493         
1494         // Make sure the current (well, old) thread is marked as de-scheduled   
1495         if(Last)        Last->CurCPU = -1;
1496
1497         // No active threads, just take a nap
1498         if(giNumActiveThreads == 0) {
1499                 SHORTREL( &glThreadListLock );
1500                 #if DEBUG_TRACE_TICKETS
1501                 Log("No active threads");
1502                 #endif
1503                 return NULL;
1504         }
1505
1506         // Allow the old thread to be scheduled again
1507         if( Last )
1508         {
1509                 if( Last->Status == THREAD_STAT_ACTIVE ) {
1510                         tThreadList     *list;
1511                         #if SCHEDULER_TYPE == SCHED_LOTTERY
1512                         giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1513                         # if DEBUG_TRACE_TICKETS
1514                         LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1515                                 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1516                                 caiTICKET_COUNTS[ Last->Priority ]);
1517                         # endif
1518                         #endif
1519                         
1520                         #if SCHEDULER_TYPE == SCHED_RR_PRI
1521                         list = &gaActiveThreads[ Last->Priority ];
1522                         #else
1523                         list = &gActiveThreads;
1524                         #endif
1525                         // Add to end of list
1526                         Threads_int_AddToList( list, Last );
1527                         #if DEBUG_TRACE_ACTIVEQUEUE > 1
1528                         Debug("Threads_GetNextToRun: Append thread %p(%i %s)",
1529                                 Last, Last->TID, Last->ThreadName);
1530                         #endif
1531                 }
1532                 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1533                 else
1534                         LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1535                                 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1536                 #endif
1537                 Last->CurCPU = -1;
1538         }
1539
1540         // Call actual scheduler        
1541         tThread *thread = Threads_int_GetRunnable();
1542                 
1543         // Anything to do?
1544         if( thread )
1545         {
1546                 if( thread->Status != THREAD_STAT_ACTIVE )
1547                 {
1548                         LogF("Thread %p(%i %s) scheduled while not active\n",
1549                                 thread, thread->TID, thread->ThreadName);
1550                 }
1551
1552                 // Make the new thread non-schedulable
1553                 thread->CurCPU = CPU;
1554                 thread->Remaining = thread->Quantum;
1555                 
1556                 #if DEBUG_TRACE_SCHEDULE
1557                 Debug("Scheduled "PRIthread_fmt", next = %p",
1558                         PRIthread_args(thread),
1559                         thread->Next);
1560                 #endif
1561         }
1562         else
1563         {
1564                 // No thread possible, warning condition (idle thread should be runnable)
1565                 Warning("No runnable thread for CPU%i", CPU);
1566         }
1567         
1568         SHORTREL( &glThreadListLock );
1569         
1570         return thread;
1571 }
1572
1573 // === EXPORTS ===
1574 EXPORT(Threads_GetUID);
1575 EXPORT(Threads_GetGID);

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