Cut down on debug, fixed tabs, made process tree be killed when root is killed
[tpg/acess2.git] / Kernel / threads.c
1 /*
2  * Acess2
3  * threads.c
4  * - Common Thread Control
5  */
6 #include <common.h>
7 #include <threads.h>
8
9 // === CONSTANTS ===
10 #define DEFAULT_QUANTUM 10
11 #define DEFAULT_TICKETS 5
12 #define MAX_TICKETS             10
13
14 // === IMPORTS ===
15 extern void     ArchThreads_Init();
16 extern void     Proc_Start();
17 extern tThread  *Proc_GetCurThread();
18 extern int      Proc_Clone(Uint *Err, Uint Flags);
19
20 // === PROTOTYPES ===
21 void    Threads_Init();
22 void    Threads_SetName(char *NewName);
23 void    Threads_SetTickets(int Num);
24  int    Threads_WaitTID(int TID, int *status);
25 tThread *Threads_GetThread(Uint TID);
26 void    Threads_AddToDelete(tThread *Thread);
27 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread);
28 void    Threads_Exit(int TID, int Status);
29 void    Threads_Kill(tThread *Thread, int Status);
30 void    Threads_Yield();
31 void    Threads_Sleep();
32 void    Threads_Wake(tThread *Thread);
33 void    Threads_AddActive(tThread *Thread);
34  int    Threads_GetPID();
35  int    Threads_GetTID();
36  int    Threads_GetUID();
37  int    Threads_GetGID();
38 void    Threads_Dump();
39
40 // === GLOBALS ===
41 // -- Core Thread --
42 tThread gThreadZero = {
43         NULL, 0,        // Next, Lock
44         THREAD_STAT_ACTIVE,     // Status
45         0,      // Exit Status
46         0, 0,   // TID, TGID
47         0, 0,   // UID, GID
48         0,      // Parent Thread ID
49         "ThreadZero",   // Name
50         
51         0,      // Kernel Stack
52         {0},    // Saved State
53         {0},    // VM State
54         
55         0, {0}, {0},    // Signal State
56         
57         NULL, NULL,     // Messages, Last Message
58         DEFAULT_QUANTUM, DEFAULT_QUANTUM,       // Quantum, Remaining
59         DEFAULT_TICKETS,
60         {0}     // Default config to zero
61         };
62 // -- Processes --
63 // --- Locks ---
64 volatile int    giThreadListLock = 0;   ///\note NEVER use a heap function while locked
65 // --- Current State ---
66 volatile int    giNumActiveThreads = 0;
67 volatile int    giTotalTickets = 0;
68 volatile Uint   giNextTID = 1;
69 // --- Thread Lists ---
70 tThread *gActiveThreads = NULL;         // Currently Running Threads
71 tThread *gSleepingThreads = NULL;       // Sleeping Threads
72 tThread *gDeleteThreads = NULL;         // Threads to delete
73  int    giNumCPUs = 1;
74
75 // === CODE ===
76 /**
77  * \fn void Threads_Init()
78  * \brief Initialse the thread list
79  */
80 void Threads_Init()
81 {
82         ArchThreads_Init();
83         
84         // Create Initial Task
85         gActiveThreads = &gThreadZero;
86         giTotalTickets = gThreadZero.NumTickets;
87         giNumActiveThreads = 1;
88         
89         #if 1
90         // Create Idle Task
91         if(Proc_Clone(0, 0) == 0)
92         {
93                 tThread *cur = Proc_GetCurThread();
94                 cur->ThreadName = "Idle Thread";
95                 Threads_SetTickets(0);  // Never called randomly
96                 cur->Quantum = 1;       // 1 slice quantum
97                 HALT();
98                 for(;;) {
99                         HALT(); // Just yeilds
100                 }
101         }
102         #endif
103         
104         Proc_Start();
105 }
106
107 /**
108  * \fn void Threads_SetName(char *NewName)
109  * \brief Sets the current thread's name
110  */
111 void Threads_SetName(char *NewName)
112 {
113         tThread *cur = Proc_GetCurThread();
114         if( IsHeap(cur->ThreadName) )
115                 free( cur->ThreadName );
116         cur->ThreadName = malloc(strlen(NewName)+1);
117         strcpy(cur->ThreadName, NewName);
118 }
119
120 /**
121  * \fn void Threads_SetTickets(int Num)
122  * \brief Sets the 'priority' of a task
123  */
124 void Threads_SetTickets(int Num)
125 {
126         tThread *cur = Proc_GetCurThread();
127         if(Num < 0)     return;
128         if(Num > MAX_TICKETS)   Num = MAX_TICKETS;
129         
130         LOCK( &giThreadListLock );
131         giTotalTickets -= cur->NumTickets;
132         cur->NumTickets = Num;
133         giTotalTickets += Num;
134         //LOG("giTotalTickets = %i", giTotalTickets);
135         RELEASE( &giThreadListLock );
136 }
137
138 /**
139  * \fn void Threads_WaitTID(int TID, int *status)
140  * \brief Wait for a task to change state
141  */
142 int Threads_WaitTID(int TID, int *status)
143 {       
144         // Any Child
145         if(TID == -1) {
146                 
147                 return -1;
148         }
149         
150         // Any peer/child thread
151         if(TID == 0) {
152                 
153                 return -1;
154         }
155         
156         // TGID = abs(TID)
157         if(TID < -1) {
158                 return -1;
159         }
160         
161         // Specific Thread
162         if(TID > 0) {
163                 tThread *t = Threads_GetThread(TID);
164                  int    initStatus = t->Status;
165                  int    ret;
166                 while(t->Status == initStatus)  Threads_Yield();
167                 ret = t->RetStatus;
168                 switch(t->Status)
169                 {
170                 case THREAD_STAT_ZOMBIE:
171                         t->Status = THREAD_STAT_DEAD;
172                         if(status)      *status = 0;
173                         Threads_AddToDelete( t );
174                         break;
175                 default:
176                         if(status)      *status = -1;
177                         break;
178                 }
179                 return ret;
180         }
181         
182         return -1;
183 }
184
185 /**
186  * \fn tThread *Threads_GetThread(Uint TID)
187  * \brief Gets a thread given its TID
188  */
189 tThread *Threads_GetThread(Uint TID)
190 {
191         tThread *thread;
192         
193         // Search Active List
194         for(thread = gActiveThreads;
195                 thread;
196                 thread = thread->Next)
197         {
198                 if(thread->TID == TID)
199                         return thread;
200         }
201         
202         // Search Sleeping List
203         for(thread = gSleepingThreads;
204                 thread;
205                 thread = thread->Next)
206         {
207                 if(thread->TID == TID)
208                         return thread;
209         }
210         
211         return NULL;
212 }
213
214 /**
215  * \fn void Threads_AddToDelete(tThread *Thread)
216  * \brief Adds a thread to the delete queue
217  */
218 void Threads_AddToDelete(tThread *Thread)
219 {
220         // Add to delete queue
221         if(gDeleteThreads) {
222                 Thread->Next = gDeleteThreads;
223                 gDeleteThreads = Thread;
224         } else {
225                 Thread->Next = NULL;
226                 gDeleteThreads = Thread;
227         }
228 }
229
230 /**
231  * \fn tThread *Threads_int_GetPrev(tThread *List, tThread *Thread)
232  * \brief Gets the previous entry in a thead linked list
233  */
234 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread)
235 {
236         tThread *ret;
237         // First Entry
238         if(*List == Thread) {
239                 return (tThread*)List;
240         } else {
241                 for(ret = *List;
242                         ret->Next && ret->Next != Thread;
243                         ret = ret->Next
244                         );
245                 // Error if the thread is not on the list
246                 if(!ret->Next || ret->Next != Thread) {
247                         return NULL;
248                 }
249         }
250         return ret;
251 }
252
253 /**
254  * \fn void Threads_Exit(int TID, int Status)
255  * \brief Exit the current process
256  */
257 void Threads_Exit(int TID, int Status)
258 {
259         if( TID == 0 )
260                 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
261         else
262                 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
263 }
264
265 /**
266  * \fn void Threads_Kill(tThread *Thread, int Status)
267  * \brief Kill a thread
268  * \param TID   Thread ID (0 for current)
269  */
270 void Threads_Kill(tThread *Thread, int Status)
271 {
272         tThread *prev;
273         tMsg    *msg;
274         
275         // Kill all children
276         #if 1
277         {
278                 tThread *child;
279                 for(child = gActiveThreads;
280                         child;
281                         child = child->Next)
282                 {
283                         if(child->PTID == Thread->TID)
284                                 Threads_Kill(child, -1);
285                 }
286         }
287         #endif
288         
289         ///\note Double lock is needed due to overlap of locks
290         
291         // Lock thread (stop us recieving messages)
292         LOCK( &Thread->IsLocked );
293         
294         // Lock thread list
295         LOCK( &giThreadListLock );
296         
297         // Get previous thread on list
298         prev = Threads_int_GetPrev( &gActiveThreads, Thread );
299         if(!prev) {
300                 Warning("Proc_Exit - Current thread is not on the active queue");
301                 return;
302         }
303         
304         // Clear Message Queue
305         while( Thread->Messages )
306         {
307                 msg = Thread->Messages->Next;
308                 free( Thread->Messages );
309                 Thread->Messages = msg;
310         }
311         
312         Thread->Remaining = 0;  // Clear Remaining Quantum
313         Thread->Quantum = 0;    // Clear Quantum to indicate dead thread
314         prev->Next = Thread->Next;      // Remove from active
315         
316         giNumActiveThreads --;
317         giTotalTickets -= Thread->NumTickets;
318         
319         // Mark thread as a zombie
320         Thread->RetStatus = Status;
321         
322         // Don't Zombie if we are being killed as part of a tree
323         if(Status == -1)
324         {
325                 Thread->Status = THREAD_STAT_DEAD;
326                 Threads_AddToDelete( Thread );
327         } else {
328                 Thread->Status = THREAD_STAT_ZOMBIE;
329         }
330         
331         // Release spinlocks
332         RELEASE( &Thread->IsLocked );   // Released first so that it IS released
333         RELEASE( &giThreadListLock );
334         if(Status != -1)        HALT();
335 }
336
337 /**
338  * \fn void Threads_Yield()
339  * \brief Yield remainder of timeslice
340  */
341 void Threads_Yield()
342 {
343         Proc_GetCurThread()->Remaining = 0;
344         HALT();
345 }
346
347 /**
348  * \fn void Threads_Sleep()
349  * \brief Take the current process off the run queue
350  */
351 void Threads_Sleep()
352 {
353         tThread *cur = Proc_GetCurThread();
354         tThread *thread;
355         
356         Log("Proc_Sleep: %i going to sleep", cur->TID);
357         
358         // Acquire Spinlock
359         LOCK( &giThreadListLock );
360         
361         // Get thread before current thread
362         thread = Threads_int_GetPrev( &gActiveThreads, cur );
363         if(!thread) {
364                 Warning("Proc_Sleep - Current thread is not on the active queue");
365                 return;
366         }
367         
368         // Don't sleep if there is a message waiting
369         if( cur->Messages ) {
370                 RELEASE( &giThreadListLock );
371                 return;
372         }
373         
374         // Unset remaining timeslices (force a task switch on timer fire)
375         cur->Remaining = 0;
376         
377         // Remove from active list
378         thread->Next = cur->Next;
379         
380         // Add to Sleeping List (at the top)
381         cur->Next = gSleepingThreads;
382         gSleepingThreads = cur;
383         
384         // Reduce the active count & ticket count
385         giNumActiveThreads --;
386         giTotalTickets -= cur->NumTickets;
387         
388         // Mark thread as sleeping
389         cur->Status = THREAD_STAT_SLEEPING;
390         
391         // Release Spinlock
392         RELEASE( &giThreadListLock );
393         
394         HALT();
395 }
396
397
398 /**
399  * \fn void Threads_Wake( tThread *Thread )
400  * \brief Wakes a sleeping/waiting thread up
401  */
402 void Threads_Wake(tThread *Thread)
403 {
404         tThread *prev;
405         switch(Thread->Status)
406         {
407         case THREAD_STAT_ACTIVE:        break;
408         case THREAD_STAT_SLEEPING:
409                 LOCK( &giThreadListLock );
410                 prev = Threads_int_GetPrev(&gSleepingThreads, Thread);
411                 prev->Next = Thread->Next;      // Remove from sleeping queue
412                 Thread->Next = gActiveThreads;  // Add to active queue
413                 gActiveThreads = Thread;
414                 Thread->Status = THREAD_STAT_ACTIVE;
415                 RELEASE( &giThreadListLock );
416                 break;
417         case THREAD_STAT_WAITING:
418                 Warning("Thread_Wake - Waiting threads are not currently supported");
419                 break;
420         case THREAD_STAT_DEAD:
421                 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
422                 break;
423         default:
424                 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
425                 break;
426         }
427 }
428
429 /**
430  * \fn void Threads_AddActive(tThread *Thread)
431  * \brief Adds a thread to the active queue
432  */
433 void Threads_AddActive(tThread *Thread)
434 {
435         LOCK( &giThreadListLock );
436         Thread->Next = gActiveThreads;
437         gActiveThreads = Thread;
438         giNumActiveThreads ++;
439         giTotalTickets += Thread->NumTickets;
440         //Log("Threads_AddActive: giNumActiveThreads = %i, giTotalTickets = %i",
441         //      giNumActiveThreads, giTotalTickets);
442         RELEASE( &giThreadListLock );
443 }
444
445 #if 0
446 /**
447  * \fn void Threads_SetSignalHandler(int Num, void *Handler)
448  * \brief Sets the signal handler for a signal
449  */
450 void Threads_SetSignalHandler(int Num, void *Handler)
451 {
452         if(Num < 0 || Num >= NSIG)      return;
453         
454         gCurrentThread->SignalHandlers[Num] = Handler;
455 }
456
457 /**
458  * \fn void Threads_SendSignal(int TID, int Num)
459  * \brief Send a signal to a thread
460  */
461 void Threads_SendSignal(int TID, int Num)
462 {
463         tThread *thread = Proc_GetThread(TID);
464         void    *handler;
465         
466         if(!thread)     return ;
467         
468         handler = thread->SignalHandlers[Num];
469         
470         // Panic?
471         if(handler == SIG_ERR) {
472                 Proc_Kill(TID);
473                 return ;
474         }
475         // Dump Core?
476         if(handler == -2) {
477                 Proc_Kill(TID);
478                 return ;
479         }
480         // Ignore?
481         if(handler == -2)       return;
482         
483         // Check the type and handle if the thread is already in a signal
484         if(thread->CurSignal != 0) {
485                 if(Num < _SIGTYPE_FATAL)
486                         Proc_Kill(TID);
487                 } else {
488                         while(thread->CurSignal != 0)
489                                 Proc_Yield();
490                 }
491         }
492         
493         //TODO: 
494 }
495 #endif
496
497 // --- Process Structure Access Functions ---
498 int Threads_GetPID()
499 {
500         return Proc_GetCurThread()->TGID;
501 }
502 int Threads_GetTID()
503 {
504         return Proc_GetCurThread()->TID;
505 }
506 int Threads_GetUID()
507 {
508         return Proc_GetCurThread()->UID;
509 }
510 int Threads_GetGID()
511 {
512         return Proc_GetCurThread()->GID;
513 }
514
515 /**
516  * \fn void Threads_Dump()
517  * \brief Dums a list of currently running threads
518  */
519 void Threads_Dump()
520 {
521         tThread *thread;
522         
523         Log("Active Threads:");
524         for(thread=gActiveThreads;thread;thread=thread->Next)
525         {
526                 Log(" %i (%i) - %s", thread->TID, thread->TGID, thread->ThreadName);
527                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
528                 Log("  KStack 0x%x", thread->KernelStack);
529         }
530         Log("Sleeping Threads:");
531         for(thread=gSleepingThreads;thread;thread=thread->Next)
532         {
533                 Log(" %i (%i) - %s", thread->TID, thread->TGID, thread->ThreadName);
534                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
535                 Log("  KStack 0x%x", thread->KernelStack);
536         }
537 }
538
539 /**
540  * \fn tThread *Threads_GetNextToRun(int CPU)
541  * \brief Gets the next thread to run
542  */
543 tThread *Threads_GetNextToRun(int CPU)
544 {
545         tThread *thread;
546          int    ticket;
547          int    number;
548         
549         // Special case: 1 thread
550         if(giNumActiveThreads == 1)
551         {
552                 return gActiveThreads;
553         }
554         
555         //Log(" Threads_GetNextToRun: giNumActiveThreads=%i,giTotalTickets=%i",
556         //      giNumActiveThreads, giTotalTickets);
557         // Get the ticket number
558         ticket = number = rand() % giTotalTickets;
559         
560         //Log(" Threads_GetNextToRun: ticket = %i", ticket);
561         
562         // Find the next thread
563         for(thread=gActiveThreads;thread;thread=thread->Next)
564         {
565                 if(thread->NumTickets > number) break;
566                 number -= thread->NumTickets;
567         }
568         
569         // Error Check
570         if(thread == NULL)
571         {
572                 number = 0;
573                 for(thread=gActiveThreads;thread;thread=thread->Next)
574                         number += thread->NumTickets;
575                 Panic("Bookeeping Failed - giTotalTicketCount (%i) != true count (%i)",
576                         giTotalTickets, number);
577         }
578         
579         return thread;
580 }
581
582 /**
583  * \fn void Threads_SegFault(tVAddr Addr)
584  * \brief Called when a Segment Fault occurs
585  */
586 void Threads_SegFault(tVAddr Addr)
587 {
588         //Threads_SendSignal( Proc_GetCurThread()->TID, SIGSEGV );
589         Threads_Kill( Proc_GetCurThread(), 0 );
590 }

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