FAT - Removed unneeded malloc() calls
[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         if(!thread)     return ;
957         
958         Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
959         
960         switch(thread->FaultHandler)
961         {
962         case 0: // Panic?
963                 Threads_Kill(thread, -1);
964                 HALT();
965                 return ;
966         case 1: // Dump Core?
967                 Threads_Kill(thread, -1);
968                 HALT();
969                 return ;
970         }
971         
972         // Double Fault? Oh, F**k
973         if(thread->CurFaultNum != 0) {
974                 Threads_Kill(thread, -1);       // For now, just kill
975                 HALT();
976         }
977         
978         thread->CurFaultNum = Num;
979         
980         Proc_CallFaultHandler(thread);
981 }
982
983 /**
984  * \fn void Threads_SegFault(tVAddr Addr)
985  * \brief Called when a Segment Fault occurs
986  */
987 void Threads_SegFault(tVAddr Addr)
988 {
989         Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
990         Threads_Fault( 1 );
991         //Threads_Exit( 0, -1 );
992 }
993
994 // --- Process Structure Access Functions ---
995 tPID Threads_GetPID(void)
996 {
997         return Proc_GetCurThread()->TGID;
998 }
999 tTID Threads_GetTID(void)
1000 {
1001         return Proc_GetCurThread()->TID;
1002 }
1003 tUID Threads_GetUID(void)
1004 {
1005         return Proc_GetCurThread()->UID;
1006 }
1007 tGID Threads_GetGID(void)
1008 {
1009         return Proc_GetCurThread()->GID;
1010 }
1011
1012 int Threads_SetUID(Uint *Errno, tUID ID)
1013 {
1014         tThread *t = Proc_GetCurThread();
1015         if( t->UID != 0 ) {
1016                 *Errno = -EACCES;
1017                 return -1;
1018         }
1019         Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
1020         t->UID = ID;
1021         return 0;
1022 }
1023
1024 int Threads_SetGID(Uint *Errno, tGID ID)
1025 {
1026         tThread *t = Proc_GetCurThread();
1027         if( t->UID != 0 ) {
1028                 *Errno = -EACCES;
1029                 return -1;
1030         }
1031         Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
1032         t->GID = ID;
1033         return 0;
1034 }
1035
1036 /**
1037  * \fn void Threads_Dump(void)
1038  */
1039 void Threads_DumpActive(void)
1040 {
1041         tThread *thread;
1042         #if SCHEDULER_TYPE == SCHED_RR_PRI
1043          int    i;
1044         #endif
1045         
1046         Log("Active Threads: (%i reported)", giNumActiveThreads);
1047         
1048         #if SCHEDULER_TYPE == SCHED_RR_PRI
1049         for( i = 0; i < MIN_PRIORITY+1; i++ )
1050         {
1051                 for(thread=gaActiveThreads[i];thread;thread=thread->Next)
1052         #else
1053                 for(thread=gActiveThreads;thread;thread=thread->Next)
1054         #endif
1055                 {
1056                         Log(" %p %i (%i) - %s (CPU %i)",
1057                                 thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1058                         if(thread->Status != THREAD_STAT_ACTIVE)
1059                                 Log("  ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
1060                         Log("  Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1061                         Log("  KStack 0x%x", thread->KernelStack);
1062                         if( thread->bInstrTrace )
1063                                 Log("  Tracing Enabled");
1064                         Proc_DumpThreadCPUState(thread);
1065                 }
1066         
1067         #if SCHEDULER_TYPE == SCHED_RR_PRI
1068         }
1069         #endif
1070 }
1071
1072 /**
1073  * \fn void Threads_Dump(void)
1074  * \brief Dumps a list of currently running threads
1075  */
1076 void Threads_Dump(void)
1077 {
1078         tThread *thread;
1079         
1080         Log("--- Thread Dump ---");
1081         Threads_DumpActive();
1082         
1083         Log("All Threads:");
1084         for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1085         {
1086                 Log(" %p %i (%i) - %s (CPU %i)",
1087                         thread, thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
1088                 Log("  State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1089                 switch(thread->Status)
1090                 {
1091                 case THREAD_STAT_MUTEXSLEEP:
1092                         Log("  Mutex Pointer: %p", thread->WaitPointer);
1093                         break;
1094                 case THREAD_STAT_SEMAPHORESLEEP:
1095                         Log("  Semaphore Pointer: %p", thread->WaitPointer);
1096                         Log("  Semaphore Name: %s:%s", 
1097                                 ((tSemaphore*)thread->WaitPointer)->ModName,
1098                                 ((tSemaphore*)thread->WaitPointer)->Name
1099                                 );
1100                         break;
1101                 case THREAD_STAT_ZOMBIE:
1102                         Log("  Return Status: %i", thread->RetStatus);
1103                         break;
1104                 default:        break;
1105                 }
1106                 Log("  Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1107                 Log("  KStack 0x%x", thread->KernelStack);
1108                 if( thread->bInstrTrace )
1109                         Log("  Tracing Enabled");
1110                 Proc_DumpThreadCPUState(thread);
1111         }
1112 }
1113
1114 /**
1115  * \brief Gets the next thread to run
1116  * \param CPU   Current CPU
1117  * \param Last  The thread the CPU was running
1118  */
1119 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1120 {
1121         tThread *thread;
1122         
1123         // If this CPU has the lock, we must let it complete
1124         if( CPU_HAS_LOCK( &glThreadListLock ) )
1125                 return Last;
1126         
1127         // Don't change threads if the current CPU has switches disabled
1128         if( gaThreads_NoTaskSwitch[CPU] )
1129                 return Last;
1130
1131
1132         // Lock thread list
1133         SHORTLOCK( &glThreadListLock );
1134         
1135         // Clear Delete Queue
1136         // - I should probably put this in a worker thread to avoid calling free() in the scheduler
1137         //   DEFINITELY - free() can deadlock in this case
1138         //   I'll do it when it becomes an issue
1139         while(gDeleteThreads)
1140         {
1141                 thread = gDeleteThreads->Next;
1142                 // Only free if structure is unused
1143                 if( !IS_LOCKED(&gDeleteThreads->IsLocked) )
1144                 {
1145                         // Set to dead
1146                         gDeleteThreads->Status = THREAD_STAT_BURIED;
1147                         // Free name
1148                         if( IsHeap(gDeleteThreads->ThreadName) )
1149                                 free(gDeleteThreads->ThreadName);
1150                         // Remove from global list
1151                         if( gDeleteThreads == gAllThreads )
1152                                 gAllThreads = gDeleteThreads->GlobalNext;
1153                         else
1154                                 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
1155                         free( gDeleteThreads );
1156                 }
1157                 gDeleteThreads = thread;
1158         }
1159
1160         // Make sure the current (well, old) thread is marked as de-scheduled   
1161         if(Last)        Last->CurCPU = -1;
1162
1163         // No active threads, just take a nap
1164         if(giNumActiveThreads == 0) {
1165                 SHORTREL( &glThreadListLock );
1166                 #if DEBUG_TRACE_TICKETS
1167                 Log("No active threads");
1168                 #endif
1169                 return NULL;
1170         }
1171         
1172         #if SCHEDULER_TYPE != SCHED_RR_PRI
1173         // Special case: 1 thread
1174         if(giNumActiveThreads == 1) {
1175                 if( gActiveThreads->CurCPU == -1 )
1176                         gActiveThreads->CurCPU = CPU;
1177                 
1178                 SHORTREL( &glThreadListLock );
1179                 
1180                 if( gActiveThreads->CurCPU == CPU )
1181                         return gActiveThreads;
1182                 
1183                 return NULL;    // CPU has nothing to do
1184         }
1185         #endif
1186         
1187         // Allow the old thread to be scheduled again
1188         if( Last ) {
1189                 if( Last->Status == THREAD_STAT_ACTIVE ) {
1190                         #if SCHEDULER_TYPE == SCHED_LOTTERY
1191                         giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1192                         # if DEBUG_TRACE_TICKETS
1193                         LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1194                                 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1195                                 caiTICKET_COUNTS[ Last->Priority ]);
1196                         # endif
1197                         #endif
1198                 }
1199                 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1200                 else
1201                         LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1202                                 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1203                 #endif
1204                 Last->CurCPU = -1;
1205         }
1206         
1207         // ---
1208         // Lottery Scheduler
1209         // ---
1210         #if SCHEDULER_TYPE == SCHED_LOTTERY
1211         {
1212                  int    ticket, number;
1213                 # if 1
1214                 number = 0;
1215                 for(thread = gActiveThreads; thread; thread = thread->Next) {
1216                         if(thread->CurCPU >= 0) continue;
1217                         if(thread->Status != THREAD_STAT_ACTIVE)
1218                                 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1219                                         thread, thread->TID, thread->ThreadName, thread->Status);
1220                         if(thread->Next == thread) {
1221                                 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1222                                         thread, thread->TID, thread->ThreadName, thread->Status);
1223                         }
1224                         number += caiTICKET_COUNTS[ thread->Priority ];
1225                 }
1226                 if(number != giFreeTickets) {
1227                         Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1228                                 giFreeTickets, number, CPU);
1229                 }
1230                 # endif
1231                 
1232                 // No free tickets (all tasks delegated to cores)
1233                 if( giFreeTickets == 0 ) {
1234                         SHORTREL(&glThreadListLock);
1235                         return NULL;
1236                 }
1237                 
1238                 // Get the ticket number
1239                 ticket = number = rand() % giFreeTickets;
1240                 
1241                 // Find the next thread
1242                 for(thread=gActiveThreads;thread;thread=thread->Next)
1243                 {
1244                         if(thread->CurCPU >= 0) continue;
1245                         if( caiTICKET_COUNTS[ thread->Priority ] > number)      break;
1246                         number -= caiTICKET_COUNTS[ thread->Priority ];
1247                 }
1248                 
1249                 // If we didn't find a thread, something went wrong
1250                 if(thread == NULL)
1251                 {
1252                         number = 0;
1253                         for(thread=gActiveThreads;thread;thread=thread->Next) {
1254                                 if(thread->CurCPU >= 0) continue;
1255                                 number += caiTICKET_COUNTS[ thread->Priority ];
1256                         }
1257                         Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1258                                 giFreeTickets, number);
1259                 }
1260                 
1261                 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1262                 # if DEBUG_TRACE_TICKETS
1263                 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1264                         CPU, thread, thread->TID, thread->ThreadName,
1265                         giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1266                 # endif
1267         }
1268         
1269         // ---
1270         // Priority based round robin scheduler
1271         // ---
1272         #elif SCHEDULER_TYPE == SCHED_RR_PRI
1273         {
1274                  int    i;
1275                 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1276                 {
1277                         for(thread = gaActiveThreads[i]; thread; thread = thread->Next)
1278                         {
1279                                 if( thread->CurCPU == -1 )      break;
1280                         }
1281                         // If we fall onto the same queue again, special handling is
1282                         // needed
1283                         if( i == Last->Priority ) {
1284                                 tThread *savedThread = thread;
1285                                 
1286                                 // Find the next unscheduled thread in the list
1287                                 for( thread = Last->Next; thread; thread = thread->Next )
1288                                 {
1289                                         if( thread->CurCPU == -1 )      break;
1290                                 }
1291                                 // If we don't find anything after, just use the one 
1292                                 // found above.
1293                                 if( !thread )   thread = savedThread;
1294                         }
1295                         // Found a thread? Schedule it!
1296                         if( thread )    break;
1297                 }
1298                 
1299                 // Anything to do?
1300                 if( !thread ) {
1301                         SHORTREL(&glThreadListLock);
1302                         return NULL;
1303                 }
1304         }
1305         #elif SCHEDULER_TYPE == SCHED_RR_SIM
1306         {               
1307                 // Find the next unscheduled thread in the list
1308                 for( thread = Last->Next; thread; thread = thread->Next )
1309                 {
1310                         if( thread->CurCPU == -1 )      break;
1311                 }
1312                 // If we don't find anything after, search from the beginning
1313                 if( !thread )
1314                 {
1315                         for(thread = gActiveThreads; thread; thread = thread->Next)
1316                         {
1317                                 if( thread->CurCPU == -1 )      break;
1318                         }       
1319                 }
1320                 
1321                 // Anything to do?
1322                 if( !thread ) {
1323                         SHORTREL(&glThreadListLock);
1324                         return NULL;
1325                 }
1326         }
1327         #else
1328         # error "Unimplemented scheduling algorithm"
1329         #endif
1330         
1331         // Make the new thread non-schedulable
1332         thread->CurCPU = CPU;
1333         
1334         SHORTREL( &glThreadListLock );
1335         
1336         return thread;
1337 }
1338
1339 // Acquire mutex (see mutex.h for documentation)
1340 int Mutex_Acquire(tMutex *Mutex)
1341 {
1342         tThread *us = Proc_GetCurThread();
1343         
1344         // Get protector
1345         SHORTLOCK( &Mutex->Protector );
1346         
1347         //Log("Mutex_Acquire: (%p)", Mutex);
1348         
1349         // Check if the lock is already held
1350         if( Mutex->Owner ) {
1351                 SHORTLOCK( &glThreadListLock );
1352                 // - Remove from active list
1353                 us = Threads_RemActive();
1354                 us->Next = NULL;
1355                 // - Mark as sleeping
1356                 us->Status = THREAD_STAT_MUTEXSLEEP;
1357                 us->WaitPointer = Mutex;
1358                 
1359                 // - Add to waiting
1360                 if(Mutex->LastWaiting) {
1361                         Mutex->LastWaiting->Next = us;
1362                         Mutex->LastWaiting = us;
1363                 }
1364                 else {
1365                         Mutex->Waiting = us;
1366                         Mutex->LastWaiting = us;
1367                 }
1368                 
1369                 #if DEBUG_TRACE_STATE
1370                 Log("%p (%i %s) waiting on mutex %p",
1371                         us, us->TID, us->ThreadName, Mutex);
1372                 #endif
1373                 
1374                 #if 0
1375                 {
1376                          int    i = 0;
1377                         tThread *t;
1378                         for( t = Mutex->Waiting; t; t = t->Next, i++ )
1379                                 Log("[%i] (tMutex)%p->Waiting[%i] = %p (%i %s)", us->TID, Mutex, i,
1380                                         t, t->TID, t->ThreadName);
1381                 }
1382                 #endif
1383                 
1384                 SHORTREL( &glThreadListLock );
1385                 SHORTREL( &Mutex->Protector );
1386                 while(us->Status == THREAD_STAT_MUTEXSLEEP)     Threads_Yield();
1387                 // We're only woken when we get the lock
1388                 us->WaitPointer = NULL;
1389         }
1390         // Ooh, let's take it!
1391         else {
1392                 Mutex->Owner = us;
1393                 SHORTREL( &Mutex->Protector );
1394         }
1395         
1396         #if 0
1397         extern tMutex   glPhysAlloc;
1398         if( Mutex != &glPhysAlloc )
1399                 LogF("Mutex %p taken by %i %p\n", Mutex, us->TID, __builtin_return_address(0));
1400         #endif
1401         
1402         return 0;
1403 }
1404
1405 // Release a mutex
1406 void Mutex_Release(tMutex *Mutex)
1407 {
1408         SHORTLOCK( &Mutex->Protector );
1409         //Log("Mutex_Release: (%p)", Mutex);
1410         if( Mutex->Waiting ) {
1411                 Mutex->Owner = Mutex->Waiting;  // Set owner
1412                 Mutex->Waiting = Mutex->Waiting->Next;  // Next!
1413                 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1414                 // 2010-10-02 21:50 - Comemerating the death of the longest single
1415                 //                    blocker in the Acess2 history. REMEMBER TO
1416                 //                    FUCKING MAINTAIN YOUR FUCKING LISTS DIPWIT
1417                 if( Mutex->LastWaiting == Mutex->Owner )
1418                         Mutex->LastWaiting = NULL;
1419                 
1420                 // Wake new owner
1421                 SHORTLOCK( &glThreadListLock );
1422                 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1423                         Threads_AddActive(Mutex->Owner);
1424                 SHORTREL( &glThreadListLock );
1425         }
1426         else {
1427                 Mutex->Owner = NULL;
1428         }
1429         SHORTREL( &Mutex->Protector );
1430         
1431         #if 0
1432         extern tMutex   glPhysAlloc;
1433         if( Mutex != &glPhysAlloc )
1434                 LogF("Mutex %p released by %i %p\n", Mutex, Threads_GetTID(), __builtin_return_address(0));
1435         #endif
1436 }
1437
1438 // Check if a mutex is locked
1439 int Mutex_IsLocked(tMutex *Mutex)
1440 {
1441         return Mutex->Owner != NULL;
1442 }
1443
1444 //
1445 // Initialise a semaphore
1446 //
1447 void Semaphore_Init(tSemaphore *Sem, int Value, int MaxValue, const char *Module, const char *Name)
1448 {
1449         memset(Sem, 0, sizeof(tSemaphore));
1450         Sem->Value = Value;
1451         Sem->ModName = Module;
1452         Sem->Name = Name;
1453         Sem->MaxValue = MaxValue;
1454 }
1455 //
1456 // Wait for items to be avaliable
1457 //
1458 int Semaphore_Wait(tSemaphore *Sem, int MaxToTake)
1459 {
1460         tThread *us;
1461          int    taken;
1462         if( MaxToTake < 0 ) {
1463                 Log_Warning("Threads", "Semaphore_Wait: User bug - MaxToTake(%i) < 0, Sem=%p(%s)",
1464                         MaxToTake, Sem, Sem->Name);
1465         }
1466         
1467         SHORTLOCK( &Sem->Protector );
1468         
1469         // Check if there's already items avaliable
1470         if( Sem->Value > 0 ) {
1471                 // Take what we need
1472                 if( MaxToTake && Sem->Value > MaxToTake )
1473                         taken = MaxToTake;
1474                 else
1475                         taken = Sem->Value;
1476                 Sem->Value -= taken;
1477                 SHORTREL( &Sem->Protector );
1478         }
1479         else
1480         {
1481                 SHORTLOCK( &glThreadListLock );
1482                 
1483                 // - Remove from active list
1484                 us = Threads_RemActive();
1485                 us->Next = NULL;
1486                 // - Mark as sleeping
1487                 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1488                 us->WaitPointer = Sem;
1489                 us->RetStatus = MaxToTake;      // Use RetStatus as a temp variable
1490                 
1491                 // - Add to waiting
1492                 if(Sem->LastWaiting) {
1493                         Sem->LastWaiting->Next = us;
1494                         Sem->LastWaiting = us;
1495                 }
1496                 else {
1497                         Sem->Waiting = us;
1498                         Sem->LastWaiting = us;
1499                 }
1500                 
1501                 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1502                 Log("%p (%i %s) waiting on semaphore %p %s:%s",
1503                         us, us->TID, us->ThreadName,
1504                         Sem, Sem->ModName, Sem->Name);
1505                 #endif
1506                 
1507                 SHORTREL( &Sem->Protector );    // Release first to make sure it is released
1508                 SHORTREL( &glThreadListLock );  
1509                 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1510                 // We're only woken when there's something avaliable (or a signal arrives)
1511                 us->WaitPointer = NULL;
1512                 
1513                 taken = us->RetStatus;
1514                 
1515                 // Get the lock again
1516                 SHORTLOCK( &Sem->Protector );
1517         }
1518         
1519         // While there is space, and there are thread waiting
1520         // wake the first thread and give it what it wants (or what's left)
1521         while( (Sem->MaxValue == 0 || Sem->Value < Sem->MaxValue) && Sem->Signaling )
1522         {
1523                  int    given;
1524                 tThread *toWake = Sem->Signaling;
1525                 
1526                 Sem->Signaling = Sem->Signaling->Next;
1527                 // Reset ->LastWaiting to NULL if we have just removed the last waiting thread
1528                 if( Sem->Signaling == NULL )
1529                         Sem->LastSignaling = NULL;
1530                 
1531                 // Figure out how much to give
1532                 if( toWake->RetStatus && Sem->Value + toWake->RetStatus < Sem->MaxValue )
1533                         given = toWake->RetStatus;
1534                 else
1535                         given = Sem->MaxValue - Sem->Value;
1536                 Sem->Value -= given;
1537                 
1538                 
1539                 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1540                 Log("%p (%i %s) woken by wait on %p %s:%s",
1541                         toWake, toWake->TID, toWake->ThreadName,
1542                         Sem, Sem->ModName, Sem->Name);
1543                 #endif
1544                 
1545                 // Save the number we gave to the thread's status
1546                 toWake->RetStatus = given;
1547                 
1548                 // Wake the sleeper
1549                 SHORTLOCK( &glThreadListLock );
1550                 if( toWake->Status != THREAD_STAT_ACTIVE )
1551                         Threads_AddActive(toWake);
1552                 SHORTREL( &glThreadListLock );
1553         }
1554         SHORTREL( &Sem->Protector );
1555         
1556         return taken;
1557 }
1558
1559 //
1560 // Add items to a semaphore
1561 //
1562 int Semaphore_Signal(tSemaphore *Sem, int AmmountToAdd)
1563 {
1564          int    given;
1565          int    added;
1566         
1567         if( AmmountToAdd < 0 ) {
1568                 Log_Warning("Threads", "Semaphore_Signal: User bug - AmmountToAdd(%i) < 0, Sem=%p(%s)",
1569                         AmmountToAdd, Sem, Sem->Name);
1570         }
1571         SHORTLOCK( &Sem->Protector );
1572         
1573         // Check if we have to block
1574         if( Sem->MaxValue && Sem->Value == Sem->MaxValue )
1575         {
1576                 tThread *us;
1577                 #if 0
1578                 Log_Debug("Threads", "Semaphore_Signal: IDLE Sem = %s:%s", Sem->ModName, Sem->Name);
1579                 Log_Debug("Threads", "Semaphore_Signal: Sem->Value(%i) == Sem->MaxValue(%i)", Sem->Value, Sem->MaxValue);
1580                 #endif
1581                 
1582                 SHORTLOCK( &glThreadListLock );
1583                 // - Remove from active list
1584                 us = Threads_RemActive();
1585                 us->Next = NULL;
1586                 // - Mark as sleeping
1587                 us->Status = THREAD_STAT_SEMAPHORESLEEP;
1588                 us->WaitPointer = Sem;
1589                 us->RetStatus = AmmountToAdd;   // Use RetStatus as a temp variable
1590                 
1591                 // - Add to waiting
1592                 if(Sem->LastSignaling) {
1593                         Sem->LastSignaling->Next = us;
1594                         Sem->LastSignaling = us;
1595                 }
1596                 else {
1597                         Sem->Signaling = us;
1598                         Sem->LastSignaling = us;
1599                 }
1600                 
1601                 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1602                 Log("%p (%i %s) signaling semaphore %p %s:%s",
1603                         us, us->TID, us->ThreadName,
1604                         Sem, Sem->ModName, Sem->Name);
1605                 #endif
1606                 
1607                 SHORTREL( &glThreadListLock );  
1608                 SHORTREL( &Sem->Protector );
1609                 while(us->Status == THREAD_STAT_SEMAPHORESLEEP) Threads_Yield();
1610                 // We're only woken when there's something avaliable
1611                 us->WaitPointer = NULL;
1612                 
1613                 added = us->RetStatus;
1614                 
1615                 // Get the lock again
1616                 SHORTLOCK( &Sem->Protector );
1617         }
1618         // Non blocking
1619         else
1620         {
1621                 // Figure out how much we need to take off
1622                 if( Sem->MaxValue && Sem->Value + AmmountToAdd > Sem->MaxValue)
1623                         added = Sem->MaxValue - Sem->Value;
1624                 else
1625                         added = AmmountToAdd;
1626                 Sem->Value += added;
1627         }
1628         
1629         // While there are items avaliable, and there are thread waiting
1630         // wake the first thread and give it what it wants (or what's left)
1631         while( Sem->Value && Sem->Waiting )
1632         {
1633                 tThread *toWake = Sem->Waiting;
1634                 
1635                 // Remove thread from list (double ended, so clear LastWaiting if needed)
1636                 Sem->Waiting = Sem->Waiting->Next;
1637                 if( Sem->Waiting == NULL )
1638                         Sem->LastWaiting = NULL;
1639                 
1640                 // Figure out how much to give to woken thread
1641                 // - Requested count is stored in ->RetStatus
1642                 if( toWake->RetStatus && Sem->Value > toWake->RetStatus )
1643                         given = toWake->RetStatus;
1644                 else
1645                         given = Sem->Value;
1646                 Sem->Value -= given;
1647                 
1648                 // Save the number we gave to the thread's status
1649                 toWake->RetStatus = given;
1650                 
1651                 if(toWake->bInstrTrace)
1652                         Log("%s(%i) given %i from %p", toWake->ThreadName, toWake->TID, given, Sem);
1653                 #if DEBUG_TRACE_STATE || SEMAPHORE_DEBUG
1654                 Log("%p (%i %s) woken by signal on %p %s:%s",
1655                         toWake, toWake->TID, toWake->ThreadName,
1656                         Sem, Sem->ModName, Sem->Name);
1657                 #endif
1658                 
1659                 // Wake the sleeper
1660                 SHORTLOCK( &glThreadListLock );
1661                 if( toWake->Status != THREAD_STAT_ACTIVE )
1662                         Threads_AddActive(toWake);
1663                 else
1664                         Warning("Thread %p (%i %s) is already awake", toWake, toWake->TID, toWake->ThreadName);
1665                 SHORTREL( &glThreadListLock );
1666         }
1667         SHORTREL( &Sem->Protector );
1668         
1669         return added;
1670 }
1671
1672 //
1673 // Get the current value of a semaphore
1674 //
1675 int Semaphore_GetValue(tSemaphore *Sem)
1676 {
1677         return Sem->Value;
1678 }
1679
1680 // === EXPORTS ===
1681 EXPORT(Threads_GetUID);
1682 EXPORT(Threads_GetGID);
1683 EXPORT(Mutex_Acquire);
1684 EXPORT(Mutex_Release);
1685 EXPORT(Mutex_IsLocked);
1686 EXPORT(Semaphore_Init);
1687 EXPORT(Semaphore_Wait);
1688 EXPORT(Semaphore_Signal);

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