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

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