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

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