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

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