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

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