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

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