Fiddling with threading code to attempt to fix this ____ bug
[tpg/acess2.git] / Kernel / threads.c
1 /*
2  * Acess2
3  * threads.c
4  * - Common Thread Control
5  */
6 #include <acess.h>
7 #include <threads.h>
8 #include <errno.h>
9
10 #define DEBUG_TRACE_TICKETS     0       // Trace ticket counts
11 #define DEBUG_TRACE_STATE       0       // Trace state changes (sleep/wake)
12
13 // === CONSTANTS ===
14 #define DEFAULT_QUANTUM 10
15 #define DEFAULT_TICKETS 5
16 #define MAX_TICKETS             10
17 const enum eConfigTypes cCONFIG_TYPES[] = {
18         CFGT_HEAPSTR,   // e.g. CFG_VFS_CWD
19         CFGT_INT,       // e.g. CFG_VFS_MAXFILES
20         CFGT_NULL
21 };
22
23 // === IMPORTS ===
24 extern void     ArchThreads_Init(void);
25 extern void     Proc_Start(void);
26 extern tThread  *Proc_GetCurThread(void);
27 extern int      Proc_Clone(Uint *Err, Uint Flags);
28 extern void     Proc_CallFaultHandler(tThread *Thread);
29
30 // === PROTOTYPES ===
31 void    Threads_Init(void);
32  int    Threads_SetName(char *NewName);
33 char    *Threads_GetName(int ID);
34 void    Threads_SetTickets(tThread *Thread, int Num);
35 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
36  int    Threads_WaitTID(int TID, int *status);
37 tThread *Threads_GetThread(Uint TID);
38 void    Threads_AddToDelete(tThread *Thread);
39 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread);
40 void    Threads_Exit(int TID, int Status);
41 void    Threads_Kill(tThread *Thread, int Status);
42 void    Threads_Yield(void);
43 void    Threads_Sleep(void);
44  int    Threads_Wake(tThread *Thread);
45 void    Threads_AddActive(tThread *Thread);
46 void    Threads_int_AddActive(tThread *Thread);
47 tThread *Threads_RemActive(void);
48  int    Threads_GetPID(void);
49  int    Threads_GetTID(void);
50 tUID    Threads_GetUID(void);
51  int    Threads_SetUID(Uint *Errno, tUID ID);
52 tGID    Threads_GetGID(void);
53  int    Threads_SetGID(Uint *Errno, tUID ID);
54 void    Threads_Dump(void);
55 void    Mutex_Acquire(tMutex *Mutex);
56 void    Mutex_Release(tMutex *Mutex);
57  int    Mutex_IsLocked(tMutex *Mutex);
58
59 // === GLOBALS ===
60 // -- Core Thread --
61 // Only used for the core kernel
62 tThread gThreadZero = {
63         Status: THREAD_STAT_ACTIVE,     // Status
64         ThreadName:     "ThreadZero",   // Name
65         Quantum: DEFAULT_QUANTUM,       // Default Quantum
66         Remaining:      DEFAULT_QUANTUM,        // Current Quantum
67         NumTickets:     DEFAULT_TICKETS // Number of tickets
68         };
69 // -- Processes --
70 // --- Locks ---
71 tShortSpinlock  glThreadListLock;       ///\note NEVER use a heap function while locked
72 // --- Current State ---
73 volatile int    giNumActiveThreads = 0; // Number of threads on the active queue
74 volatile int    giFreeTickets = 0;      // Number of tickets held by non-scheduled threads
75 volatile Uint   giNextTID = 1;  // Next TID to allocate
76 // --- Thread Lists ---
77 tThread *gAllThreads = NULL;            // All allocated threads
78 tThread *gActiveThreads = NULL;         // Currently Running Threads
79 tThread *gSleepingThreads = NULL;       // Sleeping Threads
80 tThread *gDeleteThreads = NULL;         // Threads to delete
81  int    giNumCPUs = 1;  // Number of CPUs
82
83 // === CODE ===
84 /**
85  * \fn void Threads_Init(void)
86  * \brief Initialse the thread list
87  */
88 void Threads_Init(void)
89 {
90         ArchThreads_Init();
91         
92         // Create Initial Task
93         gActiveThreads = &gThreadZero;
94         gAllThreads = &gThreadZero;
95         //giFreeTickets = gThreadZero.NumTickets;       // Not needed, as ThreadZero is scheduled
96         giNumActiveThreads = 1;
97                 
98         Proc_Start();
99 }
100
101 /**
102  * \fn void Threads_SetName(char *NewName)
103  * \brief Sets the current thread's name
104  * \param NewName       New name for the thread
105  * \return Boolean Failure
106  */
107 int Threads_SetName(char *NewName)
108 {
109         tThread *cur = Proc_GetCurThread();
110         char    *oldname = cur->ThreadName;
111         
112         // NOTE: There is a possibility of non-thread safety here
113         // A thread could read the current name pointer before it is zeroed
114         
115         cur->ThreadName = NULL;
116         
117         if( IsHeap(oldname) )   free( oldname );
118         
119         cur->ThreadName = strdup(NewName);
120         return 0;
121 }
122
123 /**
124  * \fn char *Threads_GetName(int ID)
125  * \brief Gets a thread's name
126  * \param ID    Thread ID (-1 indicates current thread)
127  * \return Pointer to name
128  * \retval NULL Failure
129  */
130 char *Threads_GetName(tTID ID)
131 {
132         if(ID == -1) {
133                 return Proc_GetCurThread()->ThreadName;
134         }
135         return Threads_GetThread(ID)->ThreadName;
136 }
137
138 /**
139  * \fn void Threads_SetTickets(tThread *Thread, int Num)
140  * \brief Sets the 'priority' of a task
141  * \param Thread        Thread to update ticket count (NULL means current thread)
142  * \param Num   New ticket count (must be >= 0, clipped to \a MAX_TICKETS)
143  */
144 void Threads_SetTickets(tThread *Thread, int Num)
145 {
146         // Get current thread
147         if(Thread == NULL)      Thread = Proc_GetCurThread();
148         // Bounds checking
149         if(Num < 0)     return;
150         if(Num > MAX_TICKETS)   Num = MAX_TICKETS;
151         
152         // If this isn't the current thread, we need to lock
153         if( Thread != Proc_GetCurThread() ) {
154                 SHORTLOCK( &glThreadListLock );
155                 giFreeTickets -= Thread->NumTickets - Num;
156                 Thread->NumTickets = Num;
157                 #if DEBUG_TRACE_TICKETS
158                 Log("Threads_SetTickets: new giFreeTickets = %i", giFreeTickets);
159                 #endif
160                 SHORTREL( &glThreadListLock );
161         }
162         else
163                 Thread->NumTickets = Num;
164 }
165
166 /**
167  * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
168  * \brief Clone the TCB of the current thread
169  * \param Err   Error pointer
170  * \param Flags Flags for something... (What is this for?)
171  */
172 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
173 {
174         tThread *cur, *new;
175          int    i;
176         cur = Proc_GetCurThread();
177         
178         // Allocate and duplicate
179         new = malloc(sizeof(tThread));
180         if(new == NULL) {
181                 *Err = -ENOMEM;
182                 return NULL;
183         }
184         memcpy(new, cur, sizeof(tThread));
185         
186         new->CurCPU = -1;
187         new->Next = NULL;
188         memset( &new->IsLocked, 0, sizeof(new->IsLocked));
189         new->Status = THREAD_STAT_PREINIT;
190         new->RetStatus = 0;
191         
192         // Get Thread ID
193         new->TID = giNextTID++;
194         new->Parent = cur;
195         
196         // Clone Name
197         new->ThreadName = strdup(cur->ThreadName);
198         
199         // Set Thread Group ID (PID)
200         if(Flags & CLONE_VM)
201                 new->TGID = new->TID;
202         else
203                 new->TGID = cur->TGID;
204         
205         // Messages are not inherited
206         new->Messages = NULL;
207         new->LastMessage = NULL;
208         
209         // Set State
210         new->Remaining = new->Quantum = cur->Quantum;
211         new->NumTickets = cur->NumTickets;
212         
213         // Set Signal Handlers
214         new->CurFaultNum = 0;
215         new->FaultHandler = cur->FaultHandler;
216         
217         for( i = 0; i < NUM_CFG_ENTRIES; i ++ )
218         {
219                 switch(cCONFIG_TYPES[i])
220                 {
221                 default:
222                         new->Config[i] = cur->Config[i];
223                         break;
224                 case CFGT_HEAPSTR:
225                         if(cur->Config[i])
226                                 new->Config[i] = (Uint) strdup( (void*)cur->Config[i] );
227                         else
228                                 new->Config[i] = 0;
229                         break;
230                 }
231         }
232         
233         // Maintain a global list of threads
234         SHORTLOCK( &glThreadListLock );
235         new->GlobalPrev = NULL; // Protect against bugs
236         new->GlobalNext = gAllThreads;
237         gAllThreads = new;
238         SHORTREL( &glThreadListLock );
239         
240         return new;
241 }
242
243 /**
244  * \brief Get a configuration pointer from the Per-Thread data area
245  * \param ID    Config slot ID
246  * \return Pointer at ID
247  */
248 Uint *Threads_GetCfgPtr(int ID)
249 {
250         if(ID < 0 || ID >= NUM_CFG_ENTRIES) {
251                 Warning("Threads_GetCfgPtr: Index %i is out of bounds", ID);
252                 return NULL;
253         }
254         
255         return &Proc_GetCurThread()->Config[ID];
256 }
257
258 /**
259  * \brief Wait for a task to change state
260  * \param TID   Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
261  * \param Status        Thread return status
262  * \return TID of child that changed state
263  */
264 tTID Threads_WaitTID(int TID, int *Status)
265 {       
266         // Any Child
267         if(TID == -1) {
268                 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
269                 return -1;
270         }
271         
272         // Any peer/child thread
273         if(TID == 0) {
274                 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
275                 return -1;
276         }
277         
278         // TGID = abs(TID)
279         if(TID < -1) {
280                 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
281                 return -1;
282         }
283         
284         // Specific Thread
285         if(TID > 0) {
286                 tThread *t = Threads_GetThread(TID);
287                  int    initStatus = t->Status;
288                 tTID    ret;
289                 
290                 // Wait for the thread to die!
291                 if(initStatus != THREAD_STAT_ZOMBIE) {
292                         // TODO: Handle child also being suspended if wanted
293                         while(t->Status != THREAD_STAT_ZOMBIE) {
294                                 Threads_Sleep();
295                                 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
296                                         Threads_GetTID(), t->TID, t->Status);
297                         }
298                 }
299                 
300                 // Set return status
301                 Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
302                         Threads_GetTID(), t->TID, t->Status);
303                 ret = t->TID;
304                 switch(t->Status)
305                 {
306                 case THREAD_STAT_ZOMBIE:
307                         // Kill the thread
308                         t->Status = THREAD_STAT_DEAD;
309                         // TODO: Child return value?
310                         if(Status)      *Status = t->RetStatus;
311                         // add to delete queue
312                         Threads_AddToDelete( t );
313                         break;
314                 default:
315                         if(Status)      *Status = -1;
316                         break;
317                 }
318                 return ret;
319         }
320         
321         return -1;
322 }
323
324 /**
325  * \brief Gets a thread given its TID
326  * \param TID   Thread ID
327  * \return Thread pointer
328  */
329 tThread *Threads_GetThread(Uint TID)
330 {
331         tThread *thread;
332         
333         // Search global list
334         for(thread = gAllThreads;
335                 thread;
336                 thread = thread->GlobalNext)
337         {
338                 if(thread->TID == TID)
339                         return thread;
340         }
341
342         Log("Unable to find TID %i on main list\n", TID);
343         
344         return NULL;
345 }
346
347 /**
348  * \brief Adds a thread to the delete queue
349  * \param Thread        Thread to delete
350  */
351 void Threads_AddToDelete(tThread *Thread)
352 {
353         // Add to delete queue
354         // TODO: Is locking needed?
355         if(gDeleteThreads) {
356                 Thread->Next = gDeleteThreads;
357                 gDeleteThreads = Thread;
358         } else {
359                 Thread->Next = NULL;
360                 gDeleteThreads = Thread;
361         }
362 }
363
364 /**
365  * \brief Gets the previous entry in a thead linked list
366  * \param List  Pointer to the list head
367  * \param Thread        Thread to find
368  * \return Thread before \a Thread on \a List
369  * \note This uses a massive hack of assuming that the first field in the
370  *       structure is the .Next pointer. By doing this, we can return \a List
371  *       as a (tThread*) and simplify other code.
372  */
373 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread)
374 {
375         tThread *ret;
376         // First Entry
377         if(*List == Thread) {
378                 return (tThread*)List;
379         }
380         // Or not
381         else {
382                 for(ret = *List;
383                         ret->Next && ret->Next != Thread;
384                         ret = ret->Next
385                         );
386                 // Error if the thread is not on the list
387                 if(!ret->Next || ret->Next != Thread) {
388                         return NULL;
389                 }
390         }
391         return ret;
392 }
393
394 /**
395  * \brief Exit the current process (or another?)
396  * \param TID   Thread ID to kill
397  * \param Status        Exit status
398  */
399 void Threads_Exit(int TID, int Status)
400 {
401         if( TID == 0 )
402                 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
403         else
404                 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
405         
406         // Halt forever, just in case
407         for(;;) HALT();
408 }
409
410 /**
411  * \fn void Threads_Kill(tThread *Thread, int Status)
412  * \brief Kill a thread
413  * \param Thread        Thread to kill
414  * \param Status        Status code to return to the parent
415  */
416 void Threads_Kill(tThread *Thread, int Status)
417 {
418         tThread *prev;
419         tMsg    *msg;
420         
421         // TODO: Kill all children
422         #if 0
423         {
424                 tThread *child;
425                 // TODO: I should keep a .Parent pointer, and a .Children list
426                 for(child = gActiveThreads;
427                         child;
428                         child = child->Next)
429                 {
430                         if(child->PTID == Thread->TID)
431                                 Threads_Kill(child, -1);
432                 }
433         }
434         #endif
435         
436         ///\note Double lock is needed due to overlap of lock areas
437         
438         // Lock thread (stop us recieving messages)
439         SHORTLOCK( &Thread->IsLocked );
440         
441         // Lock thread list
442         SHORTLOCK( &glThreadListLock );
443         
444         // Get previous thread on list
445         prev = Threads_int_GetPrev( &gActiveThreads, Thread );
446         if(!prev) {
447                 Warning("Proc_Exit - Current thread is not on the active queue");
448                 SHORTREL( &glThreadListLock );
449                 SHORTREL( &Thread->IsLocked );
450                 return;
451         }
452         
453         // Clear Message Queue
454         while( Thread->Messages )
455         {
456                 msg = Thread->Messages->Next;
457                 free( Thread->Messages );       // BIG NO-NO
458                 Thread->Messages = msg;
459         }
460         
461         // Ensure that we are not rescheduled
462         Thread->Remaining = 0;  // Clear Remaining Quantum
463         Thread->Quantum = 0;    // Clear Quantum to indicate dead thread
464         prev->Next = Thread->Next;      // Remove from active
465         
466         // Update bookkeeping
467         giNumActiveThreads --;
468         if( Thread != Proc_GetCurThread() )
469                 giFreeTickets -= Thread->NumTickets;
470         
471         // Save exit status
472         Thread->RetStatus = Status;
473         
474         // Don't Zombie if we are being killed because our parent is
475         if(Status == -1)
476         {
477                 Thread->Status = THREAD_STAT_DEAD;
478                 Threads_AddToDelete( Thread );
479         } else {
480                 Thread->Status = THREAD_STAT_ZOMBIE;
481                 // Wake parent
482                 Threads_Wake( Thread->Parent );
483         }
484         
485         Log("Thread %i went *hurk* (%i)", Thread->TID, Thread->Status);
486         
487         // Release spinlocks
488         SHORTREL( &glThreadListLock );
489         SHORTREL( &Thread->IsLocked );  // TODO: We may not actually be released...
490         
491         // And, reschedule
492         if(Status != -1) {
493                 for( ;; )
494                         HALT();
495         }
496 }
497
498 /**
499  * \brief Yield remainder of the current thread's timeslice
500  */
501 void Threads_Yield(void)
502 {
503         tThread *thread = Proc_GetCurThread();
504         thread->Remaining = 0;
505         //while(thread->Remaining == 0)
506                 HALT();
507 }
508
509 /**
510  * \fn void Threads_Sleep(void)
511  * \brief Take the current process off the run queue
512  */
513 void Threads_Sleep(void)
514 {
515         tThread *cur = Proc_GetCurThread();
516         
517         // Acquire Spinlock
518         SHORTLOCK( &glThreadListLock );
519         
520         // Don't sleep if there is a message waiting
521         if( cur->Messages ) {
522                 SHORTREL( &glThreadListLock );
523                 return;
524         }
525         
526         // Remove us from running queue
527         Threads_RemActive();
528         // Mark thread as sleeping
529         cur->Status = THREAD_STAT_SLEEPING;
530         
531         // Add to Sleeping List (at the top)
532         cur->Next = gSleepingThreads;
533         gSleepingThreads = cur;
534         
535         
536         #if DEBUG_TRACE_STATE
537         Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
538         #endif
539         
540         // Release Spinlock
541         SHORTREL( &glThreadListLock );
542         
543         while(cur->Status != THREAD_STAT_ACTIVE)        HALT();
544 }
545
546
547 /**
548  * \fn int Threads_Wake( tThread *Thread )
549  * \brief Wakes a sleeping/waiting thread up
550  * \param Thread        Thread to wake
551  * \return Boolean Failure (Returns ERRNO)
552  * \warning This should ONLY be called with task switches disabled
553  */
554 int Threads_Wake(tThread *Thread)
555 {
556         tThread *prev;
557         
558         if(!Thread)
559                 return -EINVAL;
560         
561         switch(Thread->Status)
562         {
563         case THREAD_STAT_ACTIVE:
564                 Log("Thread_Wake: Waking awake thread (%i)", Thread->TID);
565                 return -EALREADY;
566         
567         case THREAD_STAT_SLEEPING:
568                 // Remove from sleeping queue
569                 prev = Threads_int_GetPrev(&gSleepingThreads, Thread);
570                 prev->Next = Thread->Next;
571                 
572                 Threads_int_AddActive( Thread );
573                 
574                 #if DEBUG_TRACE_STATE
575                 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
576                 #endif
577                 return -EOK;
578         
579         case THREAD_STAT_WAITING:
580                 Warning("Thread_Wake - Waiting threads are not currently supported");
581                 return -ENOTIMPL;
582         
583         case THREAD_STAT_DEAD:
584                 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
585                 return -ENOTIMPL;
586         
587         default:
588                 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
589                 return -EINTERNAL;
590         }
591 }
592
593 /**
594  * \brief Wake a thread given the TID
595  * \param TID   Thread ID to wake
596  * \return Boolean Faulure (errno)
597  */
598 int Threads_WakeTID(tTID TID)
599 {
600         tThread *thread = Threads_GetThread(TID);
601          int    ret;
602         if(!thread)
603                 return -ENOENT;
604         SHORTLOCK( &glThreadListLock );
605         ret = Threads_Wake( thread );
606         SHORTREL( &glThreadListLock );
607         //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
608         return ret;
609 }
610
611 /**
612  * \brief Adds a thread to the active queue
613  */
614 void Threads_AddActive(tThread *Thread)
615 {
616         SHORTLOCK( &glThreadListLock );
617         Threads_int_AddActive(Thread);
618         SHORTREL( &glThreadListLock );
619 }
620
621 /**
622  * \brief Adds a thread to the active queue
623  * \note This version MUST have the thread list lock held
624  */
625 void Threads_int_AddActive(tThread *Thread)
626 {
627         // Add to active list
628         Thread->Next = gActiveThreads;
629         gActiveThreads = Thread;
630         // Set state
631         Thread->Status = THREAD_STAT_ACTIVE;
632         Thread->CurCPU = -1;
633         
634         // Update bookkeeping
635         giNumActiveThreads ++;
636         giFreeTickets += Thread->NumTickets;
637         
638         #if DEBUG_TRACE_TICKETS
639         Log("Threads_int_AddActive: new giFreeTickets = %i", giFreeTickets);
640         #endif
641 }
642
643 /**
644  * \brief Removes the current thread from the active queue
645  * \warning This should ONLY be called with task switches disabled
646  * \return Current thread pointer
647  */
648 tThread *Threads_RemActive(void)
649 {
650         tThread *ret = Proc_GetCurThread();
651         tThread *prev = Threads_int_GetPrev(&gActiveThreads, ret);
652         if(!prev)       return NULL;
653         ret->Remaining = 0;
654         ret->CurCPU = -1;
655         prev->Next = ret->Next;
656         giNumActiveThreads --;
657         return ret;
658 }
659
660 /**
661  * \fn void Threads_SetFaultHandler(Uint Handler)
662  * \brief Sets the signal handler for a signal
663  */
664 void Threads_SetFaultHandler(Uint Handler)
665 {       
666         //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
667         Proc_GetCurThread()->FaultHandler = Handler;
668 }
669
670 /**
671  * \fn void Threads_Fault(int Num)
672  * \brief Calls a fault handler
673  */
674 void Threads_Fault(int Num)
675 {
676         tThread *thread = Proc_GetCurThread();
677         
678         Log_Log("Threads", "Threads_Fault: thread = %p", thread);
679         
680         if(!thread)     return ;
681         
682         Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
683         
684         switch(thread->FaultHandler)
685         {
686         case 0: // Panic?
687                 Threads_Kill(thread, -1);
688                 HALT();
689                 return ;
690         case 1: // Dump Core?
691                 Threads_Kill(thread, -1);
692                 HALT();
693                 return ;
694         }
695         
696         // Double Fault? Oh, F**k
697         if(thread->CurFaultNum != 0) {
698                 Threads_Kill(thread, -1);       // For now, just kill
699                 HALT();
700         }
701         
702         thread->CurFaultNum = Num;
703         
704         Proc_CallFaultHandler(thread);
705 }
706
707 // --- Process Structure Access Functions ---
708 tPID Threads_GetPID(void)
709 {
710         return Proc_GetCurThread()->TGID;
711 }
712 tTID Threads_GetTID(void)
713 {
714         return Proc_GetCurThread()->TID;
715 }
716 tUID Threads_GetUID(void)
717 {
718         return Proc_GetCurThread()->UID;
719 }
720 tGID Threads_GetGID(void)
721 {
722         return Proc_GetCurThread()->GID;
723 }
724
725 int Threads_SetUID(Uint *Errno, tUID ID)
726 {
727         tThread *t = Proc_GetCurThread();
728         if( t->UID != 0 ) {
729                 *Errno = -EACCES;
730                 return -1;
731         }
732         Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
733         t->UID = ID;
734         return 0;
735 }
736
737 int Threads_SetGID(Uint *Errno, tGID ID)
738 {
739         tThread *t = Proc_GetCurThread();
740         if( t->UID != 0 ) {
741                 *Errno = -EACCES;
742                 return -1;
743         }
744         Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
745         t->GID = ID;
746         return 0;
747 }
748
749 /**
750  * \fn void Threads_Dump(void)
751  * \brief Dums a list of currently running threads
752  */
753 void Threads_Dump(void)
754 {
755         tThread *thread;
756         
757         Log("Active Threads:");
758         for(thread=gActiveThreads;thread;thread=thread->Next)
759         {
760                 Log(" %i (%i) - %s (CPU %i)",
761                         thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
762                 if(thread->Status != THREAD_STAT_ACTIVE)
763                         Log("  ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
764                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
765                 Log("  KStack 0x%x", thread->KernelStack);
766         }
767         
768         Log("All Threads:");
769         for(thread=gAllThreads;thread;thread=thread->GlobalNext)
770         {
771                 Log(" %i (%i) - %s (CPU %i)",
772                         thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
773                 Log("  State %i", thread->Status);
774                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
775                 Log("  KStack 0x%x", thread->KernelStack);
776         }
777 }
778
779 /**
780  * \brief Gets the next thread to run
781  * \param CPU   Current CPU
782  * \param Last  The thread the CPU was running
783  */
784 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
785 {
786         tThread *thread;
787          int    ticket;
788          int    number; 
789         
790         // Lock thread list
791         SHORTLOCK( &glThreadListLock );
792         
793         // Clear Delete Queue
794         // - I should probably put this in a worker thread to avoid calling free() in the scheduler
795         while(gDeleteThreads)
796         {
797                 thread = gDeleteThreads->Next;
798                 if( IS_LOCKED(&gDeleteThreads->IsLocked) ) {    // Only free if structure is unused
799                         // Set to dead
800                         gDeleteThreads->Status = THREAD_STAT_DEAD;
801                         // Free name
802                         if( IsHeap(gDeleteThreads->ThreadName) )
803                                 free(gDeleteThreads->ThreadName);
804                         // Remove from global list
805                         if( gDeleteThreads == gAllThreads )
806                                 gAllThreads = gDeleteThreads->GlobalNext;
807                         else
808                                 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
809                         free( gDeleteThreads );
810                 }
811                 gDeleteThreads = thread;
812         }
813         
814         // No active threads, just take a nap
815         if(giNumActiveThreads == 0) {
816                 SHORTREL( &glThreadListLock );
817                 #if DEBUG_TRACE_TICKETS
818                 Log("No active threads");
819                 #endif
820                 return NULL;
821         }
822         
823         // Special case: 1 thread
824         if(giNumActiveThreads == 1) {
825                 if( gActiveThreads->CurCPU == -1 )
826                         gActiveThreads->CurCPU = CPU;
827                 SHORTREL( &glThreadListLock );
828                 if( gActiveThreads->CurCPU == CPU )
829                         return gActiveThreads;
830                 return NULL;    // CPU has nothing to do
831         }
832         
833         // Allow the old thread to be scheduled again
834         if( Last ) {
835                 if( Last->Status == THREAD_STAT_ACTIVE ) {
836                         giFreeTickets += Last->NumTickets;
837                         #if DEBUG_TRACE_TICKETS
838                         LogF(" CPU %i released %p (%i %s) into the pool (%i tickets in pool)\n",
839                                 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets);
840                         #endif
841                 }
842                 #if DEBUG_TRACE_TICKETS
843                 else
844                         LogF(" %p (%s)->Status = %i (Released)\n", Last, Last->ThreadName, Last->Status);
845                 #endif
846                 Last->CurCPU = -1;
847         }
848         
849         #if 1
850         number = 0;
851         for(thread = gActiveThreads; thread; thread = thread->Next) {
852                 if(thread->CurCPU >= 0) continue;
853                 number += thread->NumTickets;
854         }
855         if(number != giFreeTickets) {
856                 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
857                         giFreeTickets, number, CPU);
858         }
859         #endif
860         
861         // No free tickets (all tasks delegated to cores)
862         if( giFreeTickets == 0 ) {
863                 SHORTREL(&glThreadListLock);
864                 return NULL;
865         }
866         
867         // Get the ticket number
868         ticket = number = rand() % giFreeTickets;
869         
870         // Find the next thread
871         for(thread=gActiveThreads;thread;thread=thread->Next)
872         {
873                 if(thread->CurCPU >= 0) continue;
874                 if(thread->NumTickets > number) break;
875                 number -= thread->NumTickets;
876         }
877         // Error Check
878         if(thread == NULL)
879         {
880                 number = 0;
881                 for(thread=gActiveThreads;thread;thread=thread->Next) {
882                         if(thread->CurCPU >= 0) continue;
883                         number += thread->NumTickets;
884                 }
885                 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
886                         giFreeTickets, number);
887         }
888         #if DEBUG_TRACE_TICKETS
889         LogF(" CPU%i giFreeTickets = %i\n", CPU, giFreeTickets);
890         #endif
891         
892         // Make the new thread non-schedulable
893         giFreeTickets -= thread->NumTickets;    
894         thread->CurCPU = CPU;
895         
896         //Threads_Dump();
897         #if DEBUG_TRACE_TICKETS
898         LogF(" CPU%i giFreeTickets = %i, giving %p (%i %s CPU=%i)\n",
899                 CPU, giFreeTickets, thread, thread->TID, thread->ThreadName, thread->CurCPU);
900         #endif
901         
902         SHORTREL( &glThreadListLock );
903         
904         return thread;
905 }
906
907 /**
908  * \fn void Threads_SegFault(tVAddr Addr)
909  * \brief Called when a Segment Fault occurs
910  */
911 void Threads_SegFault(tVAddr Addr)
912 {
913         Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
914         Threads_Fault( 1 );
915         //Threads_Exit( 0, -1 );
916 }
917
918 /**
919  * \brief Acquire a heavy mutex
920  * \param Mutex Mutex to acquire
921  * 
922  * This type of mutex checks if the mutex is avaliable, and acquires it
923  * if it is. Otherwise, the current thread is added to the mutex's wait
924  * queue and the thread suspends. When the holder of the mutex completes,
925  * the oldest thread (top thread) on the queue is given the lock and
926  * restarted.
927  */
928 void Mutex_Acquire(tMutex *Mutex)
929 {
930         tThread *us = Proc_GetCurThread();
931         
932         // Get protector
933         SHORTLOCK( &Mutex->Protector );
934         
935         //Log("Mutex_Acquire: (%p)", Mutex);
936         
937         // Check if the lock is already held
938         if( Mutex->Owner ) {
939                 SHORTLOCK( &glThreadListLock );
940                 // - Remove from active list
941                 Threads_RemActive();
942                 // - Mark as sleeping
943                 us->Status = THREAD_STAT_OFFSLEEP;
944                 
945                 // - Add to waiting
946                 if(Mutex->LastWaiting) {
947                         Mutex->LastWaiting->Next = us;
948                         Mutex->LastWaiting = us;
949                 }
950                 else {
951                         Mutex->Waiting = us;
952                         Mutex->LastWaiting = us;
953                 }
954                 SHORTREL( &glThreadListLock );
955                 SHORTREL( &Mutex->Protector );
956                 while(us->Status == THREAD_STAT_OFFSLEEP)       Threads_Yield();
957                 // We're only woken when we get the lock
958         }
959         // Ooh, let's take it!
960         else {
961                 Mutex->Owner = us;
962                 SHORTREL( &Mutex->Protector );
963         }
964 }
965
966 /**
967  * \brief Release a held mutex
968  * \param Mutex Mutex to release
969  */
970 void Mutex_Release(tMutex *Mutex)
971 {
972         SHORTLOCK( &Mutex->Protector );
973         //Log("Mutex_Release: (%p)", Mutex);
974         if( Mutex->Waiting ) {
975                 Mutex->Owner = Mutex->Waiting;  // Set owner
976                 Mutex->Waiting = Mutex->Waiting->Next;  // Next!
977                 // Wake new owner
978                 Threads_AddActive(Mutex->Owner);
979                 //Log("Mutex %p Woke %p", Mutex, Mutex->Owner);
980         }
981         else {
982                 Mutex->Owner = NULL;
983         }
984         SHORTREL( &Mutex->Protector );
985 }
986
987 /**
988  * \brief Is this mutex locked?
989  * \param Mutex Mutex pointer
990  */
991 int Mutex_IsLocked(tMutex *Mutex)
992 {
993         return Mutex->Owner != NULL;
994 }
995
996 // === EXPORTS ===
997 EXPORT(Threads_GetUID);
998 EXPORT(Mutex_Acquire);
999 EXPORT(Mutex_Release);
1000 EXPORT(Mutex_IsLocked);

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