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

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