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

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