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

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