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

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