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

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