636717246908ac352f4a75cd9a0ac7d38d86e902
[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                 if( Flags & CLONE_PGID )
317                         newproc->PGID = oldproc->PGID;
318                 else
319                         newproc->PGID = newproc->PID;
320                 newproc->UID = oldproc->UID;
321                 newproc->GID = oldproc->GID;
322                 newproc->MaxFD = oldproc->MaxFD;
323                 if( oldproc->CurrentWorkingDir )
324                         newproc->CurrentWorkingDir = strdup( oldproc->CurrentWorkingDir );
325                 else
326                         newproc->CurrentWorkingDir = NULL;
327                 if( oldproc->RootDir )
328                         newproc->RootDir = strdup( oldproc->RootDir );
329                 else
330                         newproc->RootDir = NULL;
331                 newproc->nThreads = 1;
332                 // Reference all handles in the VFS
333                 VFS_ReferenceUserHandles();
334         }
335         else {
336                 new->Process->nThreads ++;
337         }
338         
339         // Messages are not inherited
340         new->Messages = NULL;
341         new->LastMessage = NULL;
342         
343         // Set State
344         new->Remaining = new->Quantum = cur->Quantum;
345         new->Priority = cur->Priority;
346         new->_errno = 0;
347         
348         // Set Signal Handlers
349         new->CurFaultNum = 0;
350         new->FaultHandler = cur->FaultHandler;
351         
352         // Maintain a global list of threads
353         SHORTLOCK( &glThreadListLock );
354         new->GlobalPrev = NULL; // Protect against bugs
355         new->GlobalNext = gAllThreads;
356         gAllThreads->GlobalPrev = new;
357         gAllThreads = new;
358         SHORTREL( &glThreadListLock );
359         
360         return new;
361 }
362
363 /**
364  * \brief Clone the TCB of the kernel thread
365  */
366 tThread *Threads_CloneThreadZero(void)
367 {
368         tThread *new;
369         
370         // Allocate and duplicate
371         new = malloc(sizeof(tThread));
372         if(new == NULL) {
373                 return NULL;
374         }
375         memcpy(new, &gThreadZero, sizeof(tThread));
376
377         new->Process->nThreads ++;
378         
379         new->CurCPU = -1;
380         new->Next = NULL;
381         memset( &new->IsLocked, 0, sizeof(new->IsLocked));
382         new->Status = THREAD_STAT_PREINIT;
383         new->RetStatus = 0;
384         
385         // Get Thread ID
386         new->TID = giNextTID++;
387         new->Parent = 0;
388         
389         // Clone Name
390         new->ThreadName = NULL;
391         
392         // Messages are not inherited
393         new->Messages = NULL;
394         new->LastMessage = NULL;
395         
396         // Set State
397         new->Remaining = new->Quantum = DEFAULT_QUANTUM;
398         new->Priority = DEFAULT_PRIORITY;
399         new->bInstrTrace = 0;
400         
401         // Set Signal Handlers
402         new->CurFaultNum = 0;
403         new->FaultHandler = 0;
404         
405         // Maintain a global list of threads
406         SHORTLOCK( &glThreadListLock );
407         new->GlobalPrev = NULL; // Protect against bugs
408         new->GlobalNext = gAllThreads;
409         gAllThreads->GlobalPrev = new;
410         gAllThreads = new;
411         SHORTREL( &glThreadListLock );
412         
413         return new;
414 }
415
416 /**
417  * \brief Wait for a task to change state
418  * \param TID   Thread ID to wait on (-1: Any child thread, 0: Any Child/Sibling, <-1: -PID)
419  * \param Status        Thread return status
420  * \return TID of child that changed state
421  */
422 tTID Threads_WaitTID(int TID, int *Status)
423 {       
424         // Any Child
425         if(TID == -1) {
426                 Log_Error("Threads", "TODO: Threads_WaitTID(TID=-1) - Any Child");
427                 return -1;
428         }
429         
430         // Any peer/child thread
431         if(TID == 0) {
432                 Log_Error("Threads", "TODO: Threads_WaitTID(TID=0) - Any Child/Sibling");
433                 return -1;
434         }
435         
436         // TGID = abs(TID)
437         if(TID < -1) {
438                 Log_Error("Threads", "TODO: Threads_WaitTID(TID<0) - TGID");
439                 return -1;
440         }
441         
442         // Specific Thread
443         if(TID > 0) {
444                 tThread *t = Threads_GetThread(TID);
445                 tTID    ret;
446                 
447                 // Wait for the thread to die!
448                 // TODO: Handle child also being suspended if wanted
449                 while(t->Status != THREAD_STAT_ZOMBIE) {
450                         Threads_Sleep();
451                         Log_Debug("Threads", "%i waiting for %i, t->Status = %i",
452                                 Threads_GetTID(), t->TID, t->Status);
453                 }
454                 
455                 // Set return status
456                 ret = t->TID;
457                 switch(t->Status)
458                 {
459                 case THREAD_STAT_ZOMBIE:
460                         // Kill the thread
461                         t->Status = THREAD_STAT_DEAD;
462                         // TODO: Child return value?
463                         if(Status)      *Status = t->RetStatus;
464                         // add to delete queue
465                         Threads_Delete( t );
466                         break;
467                 default:
468                         if(Status)      *Status = -1;
469                         break;
470                 }
471                 return ret;
472         }
473         
474         return -1;
475 }
476
477 /**
478  * \brief Gets a thread given its TID
479  * \param TID   Thread ID
480  * \return Thread pointer
481  */
482 tThread *Threads_GetThread(Uint TID)
483 {
484         tThread *thread;
485         
486         // Search global list
487         for(thread = gAllThreads;
488                 thread;
489                 thread = thread->GlobalNext)
490         {
491                 if(thread->TID == TID)
492                         return thread;
493         }
494
495         Log("Unable to find TID %i on main list\n", TID);
496         
497         return NULL;
498 }
499
500 /**
501  * \brief Deletes an entry from a list
502  * \param List  Pointer to the list head
503  * \param Thread        Thread to find
504  * \return \a Thread
505  */
506 tThread *Threads_int_DelFromQueue(tThreadList *List, tThread *Thread)
507 {
508         tThread *ret, *prev = NULL;
509         
510         for(ret = List->Head;
511                 ret && ret != Thread;
512                 prev = ret, ret = ret->Next
513                 );
514         
515         // Is the thread on the list
516         if(!ret) {
517                 //LogF("%p(%s) is not on list %p\n", Thread, Thread->ThreadName, List);
518                 return NULL;
519         }
520         
521         if( !prev ) {
522                 List->Head = Thread->Next;
523                 //LogF("%p(%s) removed from head of %p\n", Thread, Thread->ThreadName, List);
524         }
525         else {
526                 prev->Next = Thread->Next;
527                 //LogF("%p(%s) removed from %p (prev=%p)\n", Thread, Thread->ThreadName, List, prev);
528         }
529         if( Thread->Next == NULL )
530                 List->Tail = prev;
531         
532         return Thread;
533 }
534
535 void Threads_int_AddToList(tThreadList *List, tThread *Thread)
536 {
537         if( List->Head )
538                 List->Tail->Next = Thread;
539         else
540                 List->Head = Thread;
541         List->Tail = Thread;
542         Thread->Next = NULL;
543 }
544
545 /**
546  * \brief Exit the current process (or another?)
547  * \param TID   Thread ID to kill
548  * \param Status        Exit status
549  */
550 void Threads_Exit(int TID, int Status)
551 {
552         if( TID == 0 )
553                 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
554         else
555                 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
556         
557         // Halt forever, just in case
558         for(;;) HALT();
559 }
560
561 /**
562  * \fn void Threads_Kill(tThread *Thread, int Status)
563  * \brief Kill a thread
564  * \param Thread        Thread to kill
565  * \param Status        Status code to return to the parent
566  */
567 void Threads_Kill(tThread *Thread, int Status)
568 {
569         tMsg    *msg;
570          int    isCurThread = Thread == Proc_GetCurThread();
571         
572         // TODO: Disown all children?
573         #if 1
574         {
575                 tThread *child;
576                 // TODO: I should keep a .Children list
577                 for(child = gAllThreads;
578                         child;
579                         child = child->GlobalNext)
580                 {
581                         if(child->Parent == Thread)
582                                 child->Parent = &gThreadZero;
583                 }
584         }
585         #endif
586         
587         ///\note Double lock is needed due to overlap of lock areas
588         
589         // Lock thread (stop us recieving messages)
590         SHORTLOCK( &Thread->IsLocked );
591         
592         // Clear Message Queue
593         while( Thread->Messages )
594         {
595                 msg = Thread->Messages->Next;
596                 free( Thread->Messages );
597                 Thread->Messages = msg;
598         }
599         
600         // Lock thread list
601         SHORTLOCK( &glThreadListLock );
602         
603         switch(Thread->Status)
604         {
605         case THREAD_STAT_PREINIT:       // Only on main list
606                 break;
607         
608         // Currently active thread
609         case THREAD_STAT_ACTIVE:
610                 if( Thread != Proc_GetCurThread() )
611                 {
612                         #if SCHEDULER_TYPE == SCHED_RR_PRI
613                         tThreadList     *list = &gaActiveThreads[Thread->Priority];
614                         #else
615                         tThreadList     *list = &gActiveThreads;
616                         #endif
617                         if( Threads_int_DelFromQueue( list, Thread ) )
618                         {
619                         }
620                         else
621                         {
622                                 Log_Warning("Threads",
623                                         "Threads_Kill - Thread %p(%i,%s) marked as active, but not on list",
624                                         Thread, Thread->TID, Thread->ThreadName
625                                         );
626                         }
627                         #if SCHEDULER_TYPE == SCHED_LOTTERY
628                         giFreeTickets -= caiTICKET_COUNTS[ Thread->Priority ];
629                         #endif
630                 }
631                 // Ensure that we are not rescheduled
632                 Thread->Remaining = 0;  // Clear Remaining Quantum
633                 Thread->Quantum = 0;    // Clear Quantum to indicate dead thread
634                         
635                 // Update bookkeeping
636                 giNumActiveThreads --;
637                 break;
638         // Kill it while it sleeps!
639         case THREAD_STAT_SLEEPING:
640                 if( !Threads_int_DelFromQueue( &gSleepingThreads, Thread ) )
641                 {
642                         Log_Warning("Threads",
643                                 "Threads_Kill - Thread %p(%i,%s) marked as sleeping, but not on list",
644                                 Thread, Thread->TID, Thread->ThreadName
645                                 );
646                 }
647                 break;
648         
649         // Brains!... You cannot kill something that is already dead
650         case THREAD_STAT_ZOMBIE:
651                 Log_Warning("Threads", "Threads_Kill - Thread %p(%i,%s) is undead, you cannot kill it",
652                         Thread, Thread->TID, Thread->ThreadName);
653                 SHORTREL( &glThreadListLock );
654                 SHORTREL( &Thread->IsLocked );
655                 return ;
656         
657         default:
658                 Log_Warning("Threads", "Threads_Kill - BUG Un-checked status (%i)",
659                         Thread->Status);
660                 break;
661         }
662         
663         // Save exit status
664         Thread->RetStatus = Status;
665
666         SHORTREL( &Thread->IsLocked );
667
668         Thread->Status = THREAD_STAT_ZOMBIE;
669         SHORTREL( &glThreadListLock );
670         // TODO: Send something like SIGCHLD
671         Threads_Wake( Thread->Parent );
672         
673         Log("Thread %i went *hurk* (%i)", Thread->TID, Status);
674         
675         // And, reschedule
676         if(isCurThread)
677         {
678                 for( ;; )
679                         Proc_Reschedule();
680         }
681 }
682
683 /**
684  * \brief Yield remainder of the current thread's timeslice
685  */
686 void Threads_Yield(void)
687 {
688 //      Log("Threads_Yield: by %p", __builtin_return_address(0));
689         Proc_Reschedule();
690 }
691
692 /**
693  * \fn void Threads_Sleep(void)
694  * \brief Take the current process off the run queue
695  */
696 void Threads_Sleep(void)
697 {
698         tThread *cur = Proc_GetCurThread();
699         
700         // Acquire Spinlock
701         SHORTLOCK( &glThreadListLock );
702         
703         // Don't sleep if there is a message waiting
704         if( cur->Messages ) {
705                 SHORTREL( &glThreadListLock );
706                 return;
707         }
708         
709         // Remove us from running queue
710         Threads_RemActive();
711         // Mark thread as sleeping
712         cur->Status = THREAD_STAT_SLEEPING;
713         
714         // Add to Sleeping List (at the top)
715         Threads_int_AddToList( &gSleepingThreads, cur );
716         
717         #if DEBUG_TRACE_STATE
718         Log("Threads_Sleep: %p (%i %s) sleeping", cur, cur->TID, cur->ThreadName);
719         #endif
720         
721         // Release Spinlock
722         SHORTREL( &glThreadListLock );
723
724         while(cur->Status != THREAD_STAT_ACTIVE) {
725                 Proc_Reschedule();
726                 if( cur->Status != THREAD_STAT_ACTIVE )
727                         Log("%i - Huh? why am I up? zzzz...", cur->TID);
728         }
729 }
730
731
732 /**
733  * \brief Wakes a sleeping/waiting thread up
734  * \param Thread        Thread to wake
735  * \return Boolean Failure (Returns ERRNO)
736  * \warning This should ONLY be called with task switches disabled
737  */
738 int Threads_Wake(tThread *Thread)
739 {
740         if(!Thread)
741                 return -EINVAL;
742         
743         switch(Thread->Status)
744         {
745         case THREAD_STAT_ACTIVE:
746                 Log("Threads_Wake - Waking awake thread (%i)", Thread->TID);
747                 return -EALREADY;
748         
749         case THREAD_STAT_SLEEPING:
750                 SHORTLOCK( &glThreadListLock );
751                 // Remove from sleeping queue
752                 Threads_int_DelFromQueue(&gSleepingThreads, Thread);
753                 
754                 SHORTREL( &glThreadListLock );
755                 Threads_AddActive( Thread );
756                 
757                 #if DEBUG_TRACE_STATE
758                 Log("Threads_Sleep: %p (%i %s) woken", Thread, Thread->TID, Thread->ThreadName);
759                 #endif
760                 return -EOK;
761         
762         case THREAD_STAT_SEMAPHORESLEEP: {
763                 tSemaphore      *sem;
764                 tThread *th, *prev=NULL;
765                 
766                 sem = Thread->WaitPointer;
767                 
768                 SHORTLOCK( &sem->Protector );
769                 
770                 // Remove from sleeping queue
771                 for( th = sem->Waiting; th; prev = th, th = th->Next )
772                         if( th == Thread )      break;
773                 if( th )
774                 {
775                         if(prev)
776                                 prev->Next = Thread->Next;
777                         else
778                                 sem->Waiting = Thread->Next;
779                         if(sem->LastWaiting == Thread)
780                                 sem->LastWaiting = prev;
781                 }
782                 else
783                 {
784                         prev = NULL;
785                         for( th = sem->Signaling; th; prev = th, th = th->Next )
786                                 if( th == Thread )      break;
787                         if( !th ) {
788                                 Log_Warning("Threads", "Thread %p(%i %s) is not on semaphore %p(%s:%s)",
789                                         Thread, Thread->TID, Thread->ThreadName,
790                                         sem, sem->ModName, sem->Name);
791                                 return -EINTERNAL;
792                         }
793                         
794                         if(prev)
795                                 prev->Next = Thread->Next;
796                         else
797                                 sem->Signaling = Thread->Next;
798                         if(sem->LastSignaling == Thread)
799                                 sem->LastSignaling = prev;
800                 }
801                 
802                 Thread->RetStatus = 0;  // It didn't get anything
803                 Threads_AddActive( Thread );
804                 
805                 #if DEBUG_TRACE_STATE
806                 Log("Threads_Sleep: %p(%i %s) woken from semaphore", Thread, Thread->TID, Thread->ThreadName);
807                 #endif
808                 SHORTREL( &sem->Protector );
809                 } return -EOK;
810         
811         case THREAD_STAT_WAITING:
812                 Warning("Threads_Wake - Waiting threads are not currently supported");
813                 return -ENOTIMPL;
814         
815         case THREAD_STAT_DEAD:
816                 Warning("Threads_Wake - Attempt to wake dead thread (%i)", Thread->TID);
817                 return -ENOTIMPL;
818         
819         default:
820                 Warning("Threads_Wake - Unknown process status (%i)\n", Thread->Status);
821                 return -EINTERNAL;
822         }
823 }
824
825 /**
826  * \brief Wake a thread given the TID
827  * \param TID   Thread ID to wake
828  * \return Boolean Faulure (errno)
829  */
830 int Threads_WakeTID(tTID TID)
831 {
832         tThread *thread = Threads_GetThread(TID);
833          int    ret;
834         if(!thread)
835                 return -ENOENT;
836         ret = Threads_Wake( thread );
837         //Log_Debug("Threads", "TID %i woke %i (%p)", Threads_GetTID(), TID, thread);
838         return ret;
839 }
840
841 void Threads_ToggleTrace(int TID)
842 {
843         tThread *thread = Threads_GetThread(TID);
844         if(!thread)     return ;
845         thread->bInstrTrace = !thread->bInstrTrace;
846 }
847
848 /**
849  * \brief Adds a thread to the active queue
850  */
851 void Threads_AddActive(tThread *Thread)
852 {
853         SHORTLOCK( &glThreadListLock );
854         
855         if( Thread->Status == THREAD_STAT_ACTIVE ) {
856                 tThread *cur = Proc_GetCurThread();
857                 Log_Warning("Threads", "WTF, %p CPU%i %p (%i %s) is adding %p (%i %s) when it is active",
858                         __builtin_return_address(0),
859                         GetCPUNum(), cur, cur->TID, cur->ThreadName, Thread, Thread->TID, Thread->ThreadName);
860                 SHORTREL( &glThreadListLock );
861                 return ;
862         }
863         
864         // Set state
865         Thread->Status = THREAD_STAT_ACTIVE;
866 //      Thread->CurCPU = -1;
867         // Add to active list
868         {
869                 #if SCHEDULER_TYPE == SCHED_RR_PRI
870                 tThreadList     *list = &gaActiveThreads[Thread->Priority];
871                 #else
872                 tThreadList     *list = &gActiveThreads;
873                 #endif
874                 Threads_int_AddToList( list, Thread );
875         }
876         
877         // Update bookkeeping
878         giNumActiveThreads ++;
879         
880         #if SCHEDULER_TYPE == SCHED_LOTTERY
881         {
882                  int    delta;
883                 // Only change the ticket count if the thread is un-scheduled
884                 if(Thread->CurCPU != -1)
885                         delta = 0;
886                 else
887                         delta = caiTICKET_COUNTS[ Thread->Priority ];
888                 
889                 giFreeTickets += delta;
890                 # if DEBUG_TRACE_TICKETS
891                 Log("CPU%i %p (%i %s) added, new giFreeTickets = %i [+%i]",
892                         GetCPUNum(), Thread, Thread->TID, Thread->ThreadName,
893                         giFreeTickets, delta
894                         );
895                 # endif
896         }
897         #endif
898         
899         SHORTREL( &glThreadListLock );
900 }
901
902 /**
903  * \brief Removes the current thread from the active queue
904  * \warning This should ONLY be called with the lock held
905  * \return Current thread pointer
906  */
907 tThread *Threads_RemActive(void)
908 {
909         #if 0
910         tThread *ret = Proc_GetCurThread();
911
912         if( !IS_LOCKED(&glThreadListLock) ) {
913                 Log_KernelPanic("Threads", "Threads_RemActive called without lock held");
914                 return NULL;
915         }
916         
917         // Delete from active queue
918         #if SCHEDULER_TYPE == SCHED_RR_PRI
919         if( !Threads_int_DelFromQueue(&gaActiveThreads[ret->Priority], ret) )
920         #else
921         if( !Threads_int_DelFromQueue(&gActiveThreads, ret) )
922         #endif
923         {
924                 Log_Warning("Threads", "Current thread %p(%i %s) is not on active queue",
925                         ret, ret->TID, ret->ThreadName
926                         );
927                 return NULL;
928         }
929         
930         ret->Next = NULL;
931         ret->Remaining = 0;
932         
933         // no need to decrement tickets, scheduler did it for us
934         
935         #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
936         Log("CPU%i %p (%i %s) removed, giFreeTickets = %i [nc]",
937                 GetCPUNum(), ret, ret->TID, ret->ThreadName, giFreeTickets);
938         #endif
939         
940         return ret;
941         #else
942         giNumActiveThreads --;
943         return Proc_GetCurThread();
944         #endif
945 }
946
947 /**
948  * \fn void Threads_SetFaultHandler(Uint Handler)
949  * \brief Sets the signal handler for a signal
950  */
951 void Threads_SetFaultHandler(Uint Handler)
952 {       
953         //Log_Debug("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
954         Proc_GetCurThread()->FaultHandler = Handler;
955 }
956
957 /**
958  * \fn void Threads_Fault(int Num)
959  * \brief Calls a fault handler
960  */
961 void Threads_Fault(int Num)
962 {
963         tThread *thread = Proc_GetCurThread();
964         
965         if(!thread)     return ;
966         
967         Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
968         
969         switch(thread->FaultHandler)
970         {
971         case 0: // Panic?
972                 Threads_Kill(thread, -1);
973                 HALT();
974                 return ;
975         case 1: // Dump Core?
976                 Threads_Kill(thread, -1);
977                 HALT();
978                 return ;
979         }
980         
981         // Double Fault? Oh, F**k
982         if(thread->CurFaultNum != 0) {
983                 Log_Warning("Threads", "Threads_Fault: Double fault on %i", thread->TID);
984                 Threads_Kill(thread, -1);       // For now, just kill
985                 HALT();
986         }
987         
988         thread->CurFaultNum = Num;
989         
990         Proc_CallFaultHandler(thread);
991 }
992
993 /**
994  * \fn void Threads_SegFault(tVAddr Addr)
995  * \brief Called when a Segment Fault occurs
996  */
997 void Threads_SegFault(tVAddr Addr)
998 {
999         tThread *cur = Proc_GetCurThread();
1000         cur->bInstrTrace = 0;
1001         Log_Warning("Threads", "Thread #%i committed a segfault at address %p", cur->TID, Addr);
1002         MM_DumpTables(0, USER_MAX);
1003         Threads_Fault( 1 );
1004         //Threads_Exit( 0, -1 );
1005 }
1006
1007 // --- Process Structure Access Functions ---
1008 tPGID Threads_GetPGID(void)
1009 {
1010         return Proc_GetCurThread()->Process->PGID;
1011 }
1012 tPID Threads_GetPID(void)
1013 {
1014         return Proc_GetCurThread()->Process->PID;
1015 }
1016 tTID Threads_GetTID(void)
1017 {
1018         return Proc_GetCurThread()->TID;
1019 }
1020 tUID Threads_GetUID(void)
1021 {
1022         return Proc_GetCurThread()->Process->UID;
1023 }
1024 tGID Threads_GetGID(void)
1025 {
1026         return Proc_GetCurThread()->Process->GID;
1027 }
1028
1029 int Threads_SetUID(tUID ID)
1030 {
1031         tThread *t = Proc_GetCurThread();
1032         if( t->Process->UID != 0 ) {
1033                 errno = -EACCES;
1034                 return -1;
1035         }
1036         Log_Debug("Threads", "PID %i's UID set to %i", t->Process->PID, ID);
1037         t->Process->UID = ID;
1038         return 0;
1039 }
1040
1041 int Threads_SetGID(tGID ID)
1042 {
1043         tThread *t = Proc_GetCurThread();
1044         if( t->Process->UID != 0 ) {
1045                 errno = -EACCES;
1046                 return -1;
1047         }
1048         Log_Debug("Threads", "PID %i's GID set to %i", t->Process->PID, ID);
1049         t->Process->GID = ID;
1050         return 0;
1051 }
1052
1053 // --- Per-thread storage ---
1054 int *Threads_GetErrno(void)
1055 {
1056         return &Proc_GetCurThread()->_errno;
1057 }
1058
1059 // --- Configuration ---
1060 int *Threads_GetMaxFD(void)
1061 {
1062         return &Proc_GetCurThread()->Process->MaxFD;
1063 }
1064 char **Threads_GetChroot(void)
1065 {
1066         return &Proc_GetCurThread()->Process->RootDir;
1067 }
1068 char **Threads_GetCWD(void)
1069 {
1070         return &Proc_GetCurThread()->Process->CurrentWorkingDir;
1071 }
1072 // ---
1073
1074 /**
1075  * \fn void Threads_Dump(void)
1076  */
1077 void Threads_DumpActive(void)
1078 {
1079         tThread *thread;
1080         tThreadList     *list;
1081         #if SCHEDULER_TYPE == SCHED_RR_PRI
1082          int    i;
1083         #endif
1084         
1085         Log("Active Threads: (%i reported)", giNumActiveThreads);
1086         
1087         #if SCHEDULER_TYPE == SCHED_RR_PRI
1088         for( i = 0; i < MIN_PRIORITY+1; i++ )
1089         {
1090                 list = &gaActiveThreads[i];
1091         #else
1092                 list = &gActiveThreads;
1093         #endif
1094                 for(thread=list->Head;thread;thread=thread->Next)
1095                 {
1096                         Log(" %p %i (%i) - %s (CPU %i)",
1097                                 thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU);
1098                         if(thread->Status != THREAD_STAT_ACTIVE)
1099                                 Log("  ERROR State (%i) != THREAD_STAT_ACTIVE (%i)",
1100                                         thread->Status, THREAD_STAT_ACTIVE);
1101                         Log("  Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1102                         Log("  KStack 0x%x", thread->KernelStack);
1103                         if( thread->bInstrTrace )
1104                                 Log("  Tracing Enabled");
1105                         Proc_DumpThreadCPUState(thread);
1106                 }
1107         
1108         #if SCHEDULER_TYPE == SCHED_RR_PRI
1109         }
1110         #endif
1111 }
1112
1113 /**
1114  * \fn void Threads_Dump(void)
1115  * \brief Dumps a list of currently running threads
1116  */
1117 void Threads_Dump(void)
1118 {
1119         tThread *thread;
1120         
1121         Log("--- Thread Dump ---");
1122         Threads_DumpActive();
1123         
1124         Log("All Threads:");
1125         for(thread=gAllThreads;thread;thread=thread->GlobalNext)
1126         {
1127                 Log(" %p %i (%i) - %s (CPU %i)",
1128                         thread, thread->TID, thread->Process->PID, thread->ThreadName, thread->CurCPU);
1129                 Log("  State %i (%s)", thread->Status, casTHREAD_STAT[thread->Status]);
1130                 switch(thread->Status)
1131                 {
1132                 case THREAD_STAT_MUTEXSLEEP:
1133                         Log("  Mutex Pointer: %p", thread->WaitPointer);
1134                         break;
1135                 case THREAD_STAT_SEMAPHORESLEEP:
1136                         Log("  Semaphore Pointer: %p", thread->WaitPointer);
1137                         Log("  Semaphore Name: %s:%s", 
1138                                 ((tSemaphore*)thread->WaitPointer)->ModName,
1139                                 ((tSemaphore*)thread->WaitPointer)->Name
1140                                 );
1141                         break;
1142                 case THREAD_STAT_ZOMBIE:
1143                         Log("  Return Status: %i", thread->RetStatus);
1144                         break;
1145                 default:        break;
1146                 }
1147                 Log("  Priority %i, Quantum %i", thread->Priority, thread->Quantum);
1148                 Log("  KStack 0x%x", thread->KernelStack);
1149                 if( thread->bInstrTrace )
1150                         Log("  Tracing Enabled");
1151                 Proc_DumpThreadCPUState(thread);
1152         }
1153 }
1154
1155 /**
1156  * \brief Gets the next thread to run
1157  * \param CPU   Current CPU
1158  * \param Last  The thread the CPU was running
1159  */
1160 tThread *Threads_GetNextToRun(int CPU, tThread *Last)
1161 {
1162         tThread *thread;
1163         
1164         // If this CPU has the lock, we must let it complete
1165         if( CPU_HAS_LOCK( &glThreadListLock ) )
1166                 return Last;
1167         
1168         // Don't change threads if the current CPU has switches disabled
1169         if( gaThreads_NoTaskSwitch[CPU] )
1170                 return Last;
1171
1172         // Lock thread list
1173         SHORTLOCK( &glThreadListLock );
1174         
1175         // Make sure the current (well, old) thread is marked as de-scheduled   
1176         if(Last)        Last->CurCPU = -1;
1177
1178         // No active threads, just take a nap
1179         if(giNumActiveThreads == 0) {
1180                 SHORTREL( &glThreadListLock );
1181                 #if DEBUG_TRACE_TICKETS
1182                 Log("No active threads");
1183                 #endif
1184                 return NULL;
1185         }
1186
1187         #if 0   
1188         #if SCHEDULER_TYPE != SCHED_RR_PRI
1189         // Special case: 1 thread
1190         if(giNumActiveThreads == 1) {
1191                 if( gActiveThreads.Head->CurCPU == -1 )
1192                         gActiveThreads.Head->CurCPU = CPU;
1193                 
1194                 SHORTREL( &glThreadListLock );
1195                 
1196                 if( gActiveThreads.Head->CurCPU == CPU )
1197                         return gActiveThreads.Head;
1198                 
1199                 return NULL;    // CPU has nothing to do
1200         }
1201         #endif
1202         #endif  
1203
1204         // Allow the old thread to be scheduled again
1205         if( Last ) {
1206                 if( Last->Status == THREAD_STAT_ACTIVE ) {
1207                         tThreadList     *list;
1208                         #if SCHEDULER_TYPE == SCHED_LOTTERY
1209                         giFreeTickets += caiTICKET_COUNTS[ Last->Priority ];
1210                         # if DEBUG_TRACE_TICKETS
1211                         LogF("Log: CPU%i released %p (%i %s) into the pool (%i [+%i] tickets in pool)\n",
1212                                 CPU, Last, Last->TID, Last->ThreadName, giFreeTickets,
1213                                 caiTICKET_COUNTS[ Last->Priority ]);
1214                         # endif
1215                         #endif
1216                         
1217                         #if SCHEDULER_TYPE == SCHED_RR_PRI
1218                         list = &gaActiveThreads[ Last->Priority ];
1219                         #else
1220                         list = &gActiveThreads;
1221                         #endif
1222                         // Add to end of list
1223                         Threads_int_AddToList( list, Last );
1224                 }
1225                 #if SCHEDULER_TYPE == SCHED_LOTTERY && DEBUG_TRACE_TICKETS
1226                 else
1227                         LogF("Log: CPU%i released %p (%i %s)->Status = %i (Released,not in pool)\n",
1228                                 CPU, Last, Last->TID, Last->ThreadName, Last->Status);
1229                 #endif
1230                 Last->CurCPU = -1;
1231         }
1232         
1233         // ---
1234         // Lottery Scheduler
1235         // ---
1236         #if SCHEDULER_TYPE == SCHED_LOTTERY
1237         {
1238                  int    ticket, number;
1239                 # if 1
1240                 number = 0;
1241                 for(thread = gActiveThreads.Head; thread; thread = thread->Next)
1242                 {
1243                         if(thread->Status != THREAD_STAT_ACTIVE)
1244                                 Panic("Bookkeeping fail - %p %i(%s) is on the active queue with a status of %i",
1245                                         thread, thread->TID, thread->ThreadName, thread->Status);
1246                         if(thread->Next == thread) {
1247                                 Panic("Bookkeeping fail - %p %i(%s) loops back on itself",
1248                                         thread, thread->TID, thread->ThreadName, thread->Status);
1249                         }
1250                         number += caiTICKET_COUNTS[ thread->Priority ];
1251                 }
1252                 if(number != giFreeTickets) {
1253                         Panic("Bookkeeping fail (giFreeTickets(%i) != number(%i)) - CPU%i",
1254                                 giFreeTickets, number, CPU);
1255                 }
1256                 # endif
1257                 
1258                 // No free tickets (all tasks delegated to cores)
1259                 if( giFreeTickets == 0 ) {
1260                         SHORTREL(&glThreadListLock);
1261                         return NULL;
1262                 }
1263                 
1264                 // Get the ticket number
1265                 ticket = number = rand() % giFreeTickets;
1266                 
1267                 // Find the next thread
1268                 for(thread = gActiveThreads.Head; thread; prev = thread, thread = thread->Next )
1269                 {
1270                         if( caiTICKET_COUNTS[ thread->Priority ] > number)      break;
1271                         number -= caiTICKET_COUNTS[ thread->Priority ];
1272                 }
1273                 
1274                 // If we didn't find a thread, something went wrong
1275                 if(thread == NULL)
1276                 {
1277                         number = 0;
1278                         for(thread=gActiveThreads;thread;thread=thread->Next) {
1279                                 if(thread->CurCPU >= 0) continue;
1280                                 number += caiTICKET_COUNTS[ thread->Priority ];
1281                         }
1282                         Panic("Bookeeping Failed - giFreeTickets(%i) > true count (%i)",
1283                                 giFreeTickets, number);
1284                 }
1285
1286                 // Remove
1287                 if(prev)
1288                         prev->Next = thread->Next;
1289                 else
1290                         gActiveThreads.Head = thread->Next;
1291                 if(!thread->Next)
1292                         gActiveThreads.Tail = prev;             
1293
1294                 giFreeTickets -= caiTICKET_COUNTS[ thread->Priority ];
1295                 # if DEBUG_TRACE_TICKETS
1296                 LogF("Log: CPU%i allocated %p (%i %s), (%i [-%i] tickets in pool), \n",
1297                         CPU, thread, thread->TID, thread->ThreadName,
1298                         giFreeTickets, caiTICKET_COUNTS[ thread->Priority ]);
1299                 # endif
1300         }
1301         
1302         // ---
1303         // Priority based round robin scheduler
1304         // ---
1305         #elif SCHEDULER_TYPE == SCHED_RR_PRI
1306         {
1307                  int    i;
1308                 thread = NULL;
1309                 for( i = 0; i < MIN_PRIORITY + 1; i ++ )
1310                 {
1311                         if( !gaActiveThreads[i].Head )
1312                                 continue ;
1313         
1314                         thread = gaActiveThreads[i].Head;
1315                         
1316                         // Remove from head
1317                         gaActiveThreads[i].Head = thread->Next;
1318                         if(!thread->Next)
1319                                 gaActiveThreads[i].Tail = NULL;
1320                         thread->Next = NULL;
1321                         break;
1322                 }
1323                 
1324                 // Anything to do?
1325                 if( !thread ) {
1326                         SHORTREL(&glThreadListLock);
1327                         return NULL;
1328                 }
1329                 if( thread->Status != THREAD_STAT_ACTIVE ) {
1330                         LogF("Oops, Thread %i (%s) is not active\n", thread->TID, thread->ThreadName);
1331                 }
1332         }
1333         #elif SCHEDULER_TYPE == SCHED_RR_SIM
1334         {
1335                 // Get the next thread off the list
1336                 thread = gActiveThreads.Head;   
1337                 gActiveThreads.Head = thread->Next;
1338                 if(!thread->Next)
1339                         gaActiveThreads.Tail = NULL;
1340                 thread->Next = NULL;
1341                 
1342                 // Anything to do?
1343                 if( !thread ) {
1344                         SHORTREL(&glThreadListLock);
1345                         return NULL;
1346                 }
1347         }
1348         #else
1349         # error "Unimplemented scheduling algorithm"
1350         #endif
1351         
1352         // Make the new thread non-schedulable
1353         thread->CurCPU = CPU;
1354         thread->Remaining = thread->Quantum;
1355         
1356         SHORTREL( &glThreadListLock );
1357         
1358         return thread;
1359 }
1360
1361 // === EXPORTS ===
1362 EXPORT(Threads_GetUID);
1363 EXPORT(Threads_GetGID);

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