51cfbdfef3e9cfb70ed2c5d24cb27ef890fbe201
[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 tThread *Threads_RemActive(void);
47  int    Threads_GetPID(void);
48  int    Threads_GetTID(void);
49 tUID    Threads_GetUID(void);
50  int    Threads_SetUID(Uint *Errno, tUID ID);
51 tGID    Threads_GetGID(void);
52  int    Threads_SetGID(Uint *Errno, tUID ID);
53 void    Threads_Dump(void);
54 void    Mutex_Acquire(tMutex *Mutex);
55 void    Mutex_Release(tMutex *Mutex);
56  int    Mutex_IsLocked(tMutex *Mutex);
57
58 // === GLOBALS ===
59 // -- Core Thread --
60 // Only used for the core kernel
61 tThread gThreadZero = {
62         Status: THREAD_STAT_ACTIVE,     // Status
63         ThreadName:     "ThreadZero",   // Name
64         Quantum: DEFAULT_QUANTUM,       // Default Quantum
65         Remaining:      DEFAULT_QUANTUM,        // Current Quantum
66         NumTickets:     DEFAULT_TICKETS // Number of tickets
67         };
68 // -- Processes --
69 // --- Locks ---
70 tShortSpinlock  glThreadListLock;       ///\note NEVER use a heap function while locked
71 // --- Current State ---
72 volatile int    giNumActiveThreads = 0; // Number of threads on the active queue
73 volatile int    giFreeTickets = 0;      // Number of tickets held by non-scheduled threads
74 volatile Uint   giNextTID = 1;  // Next TID to allocate
75 // --- Thread Lists ---
76 tThread *gAllThreads = NULL;            // All allocated threads
77 tThread *gActiveThreads = NULL;         // Currently Running Threads
78 tThread *gSleepingThreads = NULL;       // Sleeping Threads
79 tThread *gDeleteThreads = NULL;         // Threads to delete
80  int    giNumCPUs = 1;  // Number of CPUs
81 BOOL     gaThreads_NoTaskSwitch[MAX_CPUS];      // Disables task switches for each core (Pseudo-IF)
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         // Clear Message Queue
442         while( Thread->Messages )
443         {
444                 msg = Thread->Messages->Next;
445                 free( Thread->Messages );
446                 Thread->Messages = msg;
447         }
448         
449         // Lock thread list
450         SHORTLOCK( &glThreadListLock );
451         
452         // Get previous thread on list
453         prev = Threads_int_GetPrev( &gActiveThreads, Thread );
454         if(!prev) {
455                 Warning("Proc_Exit - Current thread is not on the active queue");
456                 SHORTREL( &glThreadListLock );
457                 SHORTREL( &Thread->IsLocked );
458                 return;
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                 SHORTLOCK( &glThreadListLock );
569                 // Remove from sleeping queue
570                 prev = Threads_int_GetPrev(&gSleepingThreads, Thread);
571                 prev->Next = Thread->Next;
572                 
573                 Threads_AddActive( Thread );
574                 
575                 #if DEBUG_TRACE_STATE
576                 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
577                 #endif
578                 SHORTREL( &glThreadListLock );
579                 return -EOK;
580         
581         case THREAD_STAT_WAITING:
582                 Warning("Thread_Wake - Waiting threads are not currently supported");
583                 return -ENOTIMPL;
584         
585         case THREAD_STAT_DEAD:
586                 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
587                 return -ENOTIMPL;
588         
589         default:
590                 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
591                 return -EINTERNAL;
592         }
593 }
594
595 /**
596  * \brief Wake a thread given the TID
597  * \param TID   Thread ID to wake
598  * \return Boolean Faulure (errno)
599  */
600 int Threads_WakeTID(tTID TID)
601 {
602         tThread *thread = Threads_GetThread(TID);
603          int    ret;
604         if(!thread)
605                 return -ENOENT;
606         ret = Threads_Wake( thread );
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         
618         #if 1
619         {
620                 tThread *t;
621                 for( t = gActiveThreads; t; t = t->Next )
622                 {
623                         if( t == Thread ) {
624                                 Panic("Threads_AddActive: Attempting a double add of TID %i (0x%x)",
625                                         Thread->TID, __builtin_return_address(0));
626                         }
627                         
628                         if(t->Status != THREAD_STAT_ACTIVE) {
629                                 Panic("Threads_AddActive: TID %i status != THREAD_STAT_ACTIVE",
630                                         Thread->TID);
631                         }
632                 }
633         }
634         #endif
635         
636         // Add to active list
637         Thread->Next = gActiveThreads;
638         gActiveThreads = Thread;
639         // Set state
640         Thread->Status = THREAD_STAT_ACTIVE;
641         Thread->CurCPU = -1;
642         
643         // Update bookkeeping
644         giNumActiveThreads ++;
645         giFreeTickets += Thread->NumTickets;
646         
647         #if DEBUG_TRACE_TICKETS
648         Log("Threads_AddActive: %p %i (%s) added, new giFreeTickets = %i",
649                 Thread, Thread->TID, Thread->ThreadName, giFreeTickets);
650         #endif
651         SHORTREL( &glThreadListLock );
652 }
653
654 /**
655  * \brief Removes the current thread from the active queue
656  * \warning This should ONLY be called with task switches disabled
657  * \return Current thread pointer
658  */
659 tThread *Threads_RemActive(void)
660 {
661         tThread *ret = Proc_GetCurThread();
662         tThread *prev;
663         
664         SHORTLOCK( &glThreadListLock );
665         
666         prev = Threads_int_GetPrev(&gActiveThreads, ret);
667         if(!prev) {
668                 SHORTREL( &glThreadListLock );
669                 return NULL;
670         }
671         
672         ret->Remaining = 0;
673         ret->CurCPU = -1;
674         
675         prev->Next = ret->Next;
676         giNumActiveThreads --;
677         // no need to decrement tickets, scheduler did it for us
678         
679         #if DEBUG_TRACE_TICKETS
680         Log("Threads_RemActive: %p %i (%s) removed, giFreeTickets = %i",
681                 ret, ret->TID, ret->ThreadName, giFreeTickets);
682         #endif
683         
684         SHORTREL( &glThreadListLock );
685         
686         return ret;
687 }
688
689 /**
690  * \fn void Threads_SetFaultHandler(Uint Handler)
691  * \brief Sets the signal handler for a signal
692  */
693 void Threads_SetFaultHandler(Uint Handler)
694 {       
695         //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
696         Proc_GetCurThread()->FaultHandler = Handler;
697 }
698
699 /**
700  * \fn void Threads_Fault(int Num)
701  * \brief Calls a fault handler
702  */
703 void Threads_Fault(int Num)
704 {
705         tThread *thread = Proc_GetCurThread();
706         
707         Log_Log("Threads", "Threads_Fault: thread = %p", thread);
708         
709         if(!thread)     return ;
710         
711         Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
712         
713         switch(thread->FaultHandler)
714         {
715         case 0: // Panic?
716                 Threads_Kill(thread, -1);
717                 HALT();
718                 return ;
719         case 1: // Dump Core?
720                 Threads_Kill(thread, -1);
721                 HALT();
722                 return ;
723         }
724         
725         // Double Fault? Oh, F**k
726         if(thread->CurFaultNum != 0) {
727                 Threads_Kill(thread, -1);       // For now, just kill
728                 HALT();
729         }
730         
731         thread->CurFaultNum = Num;
732         
733         Proc_CallFaultHandler(thread);
734 }
735
736 // --- Process Structure Access Functions ---
737 tPID Threads_GetPID(void)
738 {
739         return Proc_GetCurThread()->TGID;
740 }
741 tTID Threads_GetTID(void)
742 {
743         return Proc_GetCurThread()->TID;
744 }
745 tUID Threads_GetUID(void)
746 {
747         return Proc_GetCurThread()->UID;
748 }
749 tGID Threads_GetGID(void)
750 {
751         return Proc_GetCurThread()->GID;
752 }
753
754 int Threads_SetUID(Uint *Errno, tUID ID)
755 {
756         tThread *t = Proc_GetCurThread();
757         if( t->UID != 0 ) {
758                 *Errno = -EACCES;
759                 return -1;
760         }
761         Log_Debug("Threads", "TID %i's UID set to %i", t->TID, ID);
762         t->UID = ID;
763         return 0;
764 }
765
766 int Threads_SetGID(Uint *Errno, tGID ID)
767 {
768         tThread *t = Proc_GetCurThread();
769         if( t->UID != 0 ) {
770                 *Errno = -EACCES;
771                 return -1;
772         }
773         Log_Debug("Threads", "TID %i's GID set to %i", t->TID, ID);
774         t->GID = ID;
775         return 0;
776 }
777
778 /**
779  * \fn void Threads_Dump(void)
780  * \brief Dumps a list of currently running threads
781  */
782 void Threads_Dump(void)
783 {
784         tThread *thread;
785         
786         Log("--- Thread Dump ---");
787         Log("Active Threads: (%i reported)", giNumActiveThreads);
788         for(thread=gActiveThreads;thread;thread=thread->Next)
789         {
790                 Log(" %i (%i) - %s (CPU %i)",
791                         thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
792                 if(thread->Status != THREAD_STAT_ACTIVE)
793                         Log("  ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
794                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
795                 Log("  KStack 0x%x", thread->KernelStack);
796         }
797         
798         Log("All Threads:");
799         for(thread=gAllThreads;thread;thread=thread->GlobalNext)
800         {
801                 Log(" %i (%i) - %s (CPU %i)",
802                         thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
803                 Log("  State %i", thread->Status);
804                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
805                 Log("  KStack 0x%x", thread->KernelStack);
806         }
807 }
808 /**
809  * \fn void Threads_Dump(void)
810  */
811 void Threads_DumpActive(void)
812 {
813         tThread *thread;
814         
815         Log("Active Threads:");
816         for(thread=gActiveThreads;thread;thread=thread->Next)
817         {
818                 Log(" %i (%i) - %s (CPU %i)",
819                         thread->TID, thread->TGID, thread->ThreadName, thread->CurCPU);
820                 if(thread->Status != THREAD_STAT_ACTIVE)
821                         Log("  ERROR State (%i) != THREAD_STAT_ACTIVE (%i)", thread->Status, THREAD_STAT_ACTIVE);
822                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
823                 Log("  KStack 0x%x", thread->KernelStack);
824         }
825 }
826
827 /**
828  * \brief Gets the next thread to run
829  * \param CPU   Current CPU
830  * \param Last  The thread the CPU was running
831  */
832 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
833 {
834         tThread *thread;
835          int    ticket;
836          int    number;
837         
838         // If this CPU has the lock, we must let it complete
839         if( CPU_HAS_LOCK( &glThreadListLock ) )
840                 return Last;
841         
842         // Same if the current CPU has any lock
843         if( gaThreads_NoTaskSwitch[CPU] )
844                 return Last;
845
846
847         // Lock thread list
848         SHORTLOCK( &glThreadListLock );
849         
850         // Clear Delete Queue
851         // - I should probably put this in a worker thread to avoid calling free() in the scheduler
852         while(gDeleteThreads)
853         {
854                 thread = gDeleteThreads->Next;
855                 if( IS_LOCKED(&gDeleteThreads->IsLocked) ) {    // Only free if structure is unused
856                         // Set to dead
857                         gDeleteThreads->Status = THREAD_STAT_DEAD;
858                         // Free name
859                         if( IsHeap(gDeleteThreads->ThreadName) )
860                                 free(gDeleteThreads->ThreadName);
861                         // Remove from global list
862                         if( gDeleteThreads == gAllThreads )
863                                 gAllThreads = gDeleteThreads->GlobalNext;
864                         else
865                                 gDeleteThreads->GlobalPrev->GlobalNext = gDeleteThreads->GlobalNext;
866                         free( gDeleteThreads );
867                 }
868                 gDeleteThreads = thread;
869         }
870         
871         // No active threads, just take a nap
872         if(giNumActiveThreads == 0) {
873                 SHORTREL( &glThreadListLock );
874                 #if DEBUG_TRACE_TICKETS
875                 Log("No active threads");
876                 #endif
877                 return NULL;
878         }
879         
880         // Special case: 1 thread
881         if(giNumActiveThreads == 1) {
882                 if( gActiveThreads->CurCPU == -1 )
883                         gActiveThreads->CurCPU = CPU;
884                 
885                 SHORTREL( &glThreadListLock );
886                 
887                 if( gActiveThreads->CurCPU == CPU )
888                         return gActiveThreads;
889                 
890                 return NULL;    // CPU has nothing to do
891         }
892         
893         // Allow the old thread to be scheduled again
894         if( Last ) {
895                 if( Last->Status == THREAD_STAT_ACTIVE ) {
896                         giFreeTickets += Last->NumTickets;
897                         #if DEBUG_TRACE_TICKETS
898                         LogF(" CPU %i released %p (%i %s) into the pool (%i tickets in pool)\n",
899                                 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets);
900                         #endif
901                 }
902                 #if DEBUG_TRACE_TICKETS
903                 else
904                         LogF(" CPU %i released %p (%s)->Status = %i (Released)\n",
905                                 CPU, Last, Last->ThreadName, Last->Status);
906                 #endif
907                 Last->CurCPU = -1;
908         }
909         
910         #if DEBUG_TRACE_TICKETS
911         //Threads_DumpActive();
912         #endif
913         
914         #if 1
915         number = 0;
916         for(thread = gActiveThreads; thread; thread = thread->Next) {
917                 if(thread->CurCPU >= 0) continue;
918                 if(thread->Status != THREAD_STAT_ACTIVE)
919                         Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
920                                 thread, thread->TID, thread->ThreadName, thread->Status);
921                 if(thread->Next == thread) {
922                         Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
923                                 thread, thread->TID, thread->ThreadName, thread->Status);
924                 }
925                 number += thread->NumTickets;
926         }
927         if(number != giFreeTickets) {
928                 Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
929                         giFreeTickets, number, CPU);
930         }
931         #endif
932         
933         // No free tickets (all tasks delegated to cores)
934         if( giFreeTickets == 0 ) {
935                 SHORTREL(&glThreadListLock);
936                 return NULL;
937         }
938         
939         // Get the ticket number
940         ticket = number = rand() % giFreeTickets;
941         
942         // Find the next thread
943         for(thread=gActiveThreads;thread;thread=thread->Next)
944         {
945                 if(thread->CurCPU >= 0) continue;
946                 if(thread->NumTickets > number) break;
947                 number -= thread->NumTickets;
948         }
949         // Error Check
950         if(thread == NULL)
951         {
952                 number = 0;
953                 for(thread=gActiveThreads;thread;thread=thread->Next) {
954                         if(thread->CurCPU >= 0) continue;
955                         number += thread->NumTickets;
956                 }
957                 Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
958                         giFreeTickets, number);
959         }
960         #if DEBUG_TRACE_TICKETS
961         LogF(" CPU%i giFreeTickets = %i\n", CPU, giFreeTickets);
962         #endif
963         
964         // Make the new thread non-schedulable
965         giFreeTickets -= thread->NumTickets;    
966         thread->CurCPU = CPU;
967         
968         //Threads_Dump();
969         #if DEBUG_TRACE_TICKETS
970         LogF(" CPU%i giFreeTickets = %i, giving %p (%i %s CPU=%i)\n",
971                 CPU, giFreeTickets, thread, thread->TID, thread->ThreadName, thread->CurCPU);
972         #endif
973         
974         SHORTREL( &glThreadListLock );
975         
976         return thread;
977 }
978
979 /**
980  * \fn void Threads_SegFault(tVAddr Addr)
981  * \brief Called when a Segment Fault occurs
982  */
983 void Threads_SegFault(tVAddr Addr)
984 {
985         Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
986         Threads_Fault( 1 );
987         //Threads_Exit( 0, -1 );
988 }
989
990 /**
991  * \brief Acquire a heavy mutex
992  * \param Mutex Mutex to acquire
993  * 
994  * This type of mutex checks if the mutex is avaliable, and acquires it
995  * if it is. Otherwise, the current thread is added to the mutex's wait
996  * queue and the thread suspends. When the holder of the mutex completes,
997  * the oldest thread (top thread) on the queue is given the lock and
998  * restarted.
999  */
1000 void Mutex_Acquire(tMutex *Mutex)
1001 {
1002         tThread *us = Proc_GetCurThread();
1003         
1004         // Get protector
1005         SHORTLOCK( &Mutex->Protector );
1006         
1007         //Log("Mutex_Acquire: (%p)", Mutex);
1008         
1009         // Check if the lock is already held
1010         if( Mutex->Owner ) {
1011                 SHORTLOCK( &glThreadListLock );
1012                 // - Remove from active list
1013                 Threads_RemActive();
1014                 // - Mark as sleeping
1015                 us->Status = THREAD_STAT_OFFSLEEP;
1016                 
1017                 // - Add to waiting
1018                 if(Mutex->LastWaiting) {
1019                         Mutex->LastWaiting->Next = us;
1020                         Mutex->LastWaiting = us;
1021                 }
1022                 else {
1023                         Mutex->Waiting = us;
1024                         Mutex->LastWaiting = us;
1025                 }
1026                 SHORTREL( &glThreadListLock );
1027                 SHORTREL( &Mutex->Protector );
1028                 while(us->Status == THREAD_STAT_OFFSLEEP)       Threads_Yield();
1029                 // We're only woken when we get the lock
1030         }
1031         // Ooh, let's take it!
1032         else {
1033                 Mutex->Owner = us;
1034                 SHORTREL( &Mutex->Protector );
1035         }
1036 }
1037
1038 /**
1039  * \brief Release a held mutex
1040  * \param Mutex Mutex to release
1041  */
1042 void Mutex_Release(tMutex *Mutex)
1043 {
1044         SHORTLOCK( &Mutex->Protector );
1045         //Log("Mutex_Release: (%p)", Mutex);
1046         if( Mutex->Waiting ) {
1047                 Mutex->Owner = Mutex->Waiting;  // Set owner
1048                 Mutex->Waiting = Mutex->Waiting->Next;  // Next!
1049                 
1050                 // Wake new owner
1051                 SHORTLOCK( &glThreadListLock );
1052                 if( Mutex->Owner->Status != THREAD_STAT_ACTIVE )
1053                         Threads_AddActive(Mutex->Owner);
1054                 SHORTREL( &glThreadListLock );
1055         }
1056         else {
1057                 Mutex->Owner = NULL;
1058         }
1059         SHORTREL( &Mutex->Protector );
1060 }
1061
1062 /**
1063  * \brief Is this mutex locked?
1064  * \param Mutex Mutex pointer
1065  */
1066 int Mutex_IsLocked(tMutex *Mutex)
1067 {
1068         return Mutex->Owner != NULL;
1069 }
1070
1071 // === EXPORTS ===
1072 EXPORT(Threads_GetUID);
1073 EXPORT(Mutex_Acquire);
1074 EXPORT(Mutex_Release);
1075 EXPORT(Mutex_IsLocked);

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