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

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