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

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