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

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