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

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