Fixes to VM8086 handler to remove operand size errors.
[tpg/acess2.git] / Kernel / threads.c
1 /*
2  * Acess2
3  * threads.c
4  * - Common Thread Control
5  */
6 #include <acess.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 extern void     Proc_CallFaultHandler(tThread *Thread);
26
27 // === PROTOTYPES ===
28 void    Threads_Init();
29  int    Threads_SetName(char *NewName);
30 char    *Threads_GetName(int ID);
31 void    Threads_SetTickets(int Num);
32 tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
33  int    Threads_WaitTID(int TID, int *status);
34 tThread *Threads_GetThread(Uint TID);
35 void    Threads_AddToDelete(tThread *Thread);
36 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread);
37 void    Threads_Exit(int TID, int Status);
38 void    Threads_Kill(tThread *Thread, int Status);
39 void    Threads_Yield();
40 void    Threads_Sleep();
41 void    Threads_Wake(tThread *Thread);
42 void    Threads_AddActive(tThread *Thread);
43  int    Threads_GetPID();
44  int    Threads_GetTID();
45 tUID    Threads_GetUID();
46  int    Threads_SetUID(Uint *Errno, tUID ID);
47 tGID    Threads_GetGID();
48  int    Threads_SetGID(Uint *Errno, tUID ID);
49 void    Threads_Dump();
50
51 // === GLOBALS ===
52 // -- Core Thread --
53 tThread gThreadZero = {
54         NULL, 0,        // Next, Lock
55         THREAD_STAT_ACTIVE,     // Status
56         0,      // Exit Status
57         0, 0,   // TID, TGID
58         0, 0,   // UID, GID
59         0,      // Parent Thread ID
60         "ThreadZero",   // Name
61         
62         0,      // Kernel Stack
63         {0},    // Saved State
64         {0},    // VM State
65         
66         0, 0,   // Current Fault, Fault Handler
67         
68         NULL, NULL,     // Messages, Last Message
69         DEFAULT_QUANTUM, DEFAULT_QUANTUM,       // Quantum, Remaining
70         DEFAULT_TICKETS,
71         {0}     // Default config to zero
72         };
73 // -- Processes --
74 // --- Locks ---
75 volatile int    giThreadListLock = 0;   ///\note NEVER use a heap function while locked
76 // --- Current State ---
77 volatile int    giNumActiveThreads = 0;
78 volatile int    giTotalTickets = 0;
79 volatile Uint   giNextTID = 1;
80 // --- Thread Lists ---
81 tThread *gActiveThreads = NULL;         // Currently Running Threads
82 tThread *gSleepingThreads = NULL;       // Sleeping Threads
83 tThread *gDeleteThreads = NULL;         // Threads to delete
84  int    giNumCPUs = 1;
85
86 // === CODE ===
87 /**
88  * \fn void Threads_Init()
89  * \brief Initialse the thread list
90  */
91 void Threads_Init()
92 {
93         ArchThreads_Init();
94         
95         // Create Initial Task
96         gActiveThreads = &gThreadZero;
97         giTotalTickets = gThreadZero.NumTickets;
98         giNumActiveThreads = 1;
99         
100         #if 1
101         // Create Idle Task
102         if(Proc_Clone(0, 0) == 0)
103         {
104                 tThread *cur = Proc_GetCurThread();
105                 cur->ThreadName = "Idle Thread";
106                 Threads_SetTickets(0);  // Never called randomly
107                 cur->Quantum = 1;       // 1 slice quantum
108                 HALT();
109                 for(;;) {
110                         HALT(); // Just yeilds
111                 }
112         }
113         #endif
114         
115         Proc_Start();
116 }
117
118 /**
119  * \fn void Threads_SetName(char *NewName)
120  * \brief Sets the current thread's name
121  */
122 int Threads_SetName(char *NewName)
123 {
124         tThread *cur = Proc_GetCurThread();
125         if( IsHeap(cur->ThreadName) )
126                 free( cur->ThreadName );
127         cur->ThreadName = malloc(strlen(NewName)+1);
128         strcpy(cur->ThreadName, NewName);
129         return 0;
130 }
131
132 /**
133  * \fn char *Threads_GetName(int ID)
134  * \brief Gets a thread's name
135  */
136 char *Threads_GetName(int ID)
137 {
138         if(ID == -1) {
139                 return Proc_GetCurThread()->ThreadName;
140         }
141         return NULL;
142 }
143
144 /**
145  * \fn void Threads_SetTickets(int Num)
146  * \brief Sets the 'priority' of a task
147  */
148 void Threads_SetTickets(int Num)
149 {
150         tThread *cur = Proc_GetCurThread();
151         if(Num < 0)     return;
152         if(Num > MAX_TICKETS)   Num = MAX_TICKETS;
153         
154         LOCK( &giThreadListLock );
155         giTotalTickets -= cur->NumTickets;
156         cur->NumTickets = Num;
157         giTotalTickets += Num;
158         //LOG("giTotalTickets = %i", giTotalTickets);
159         RELEASE( &giThreadListLock );
160 }
161
162 /**
163  * \fn tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
164  */
165 tThread *Threads_CloneTCB(Uint *Err, Uint Flags)
166 {
167         tThread *cur, *new;
168          int    i;
169         cur = Proc_GetCurThread();
170         
171         new = malloc(sizeof(tThread));
172         if(new == NULL) {
173                 *Err = -ENOMEM;
174                 return NULL;
175         }
176         
177         new->Next = NULL;
178         new->IsLocked = 0;
179         new->Status = THREAD_STAT_ACTIVE;
180         new->RetStatus = 0;
181         
182         // Get Thread ID
183         new->TID = giNextTID++;
184         new->PTID = cur->TID;
185         
186         // Clone Name
187         new->ThreadName = malloc(strlen(cur->ThreadName)+1);
188         strcpy(new->ThreadName, cur->ThreadName);
189         
190         // Set Thread Group ID (PID)
191         if(Flags & CLONE_VM)
192                 new->TGID = new->TID;
193         else
194                 new->TGID = cur->TGID;
195         
196         // Messages are not inherited
197         new->Messages = NULL;
198         new->LastMessage = NULL;
199         
200         // Set State
201         new->Remaining = new->Quantum = cur->Quantum;
202         new->NumTickets = cur->NumTickets;
203         
204         // Set Signal Handlers
205         new->CurFaultNum = 0;
206         new->FaultHandler = cur->FaultHandler;
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                 
269                 if(initStatus != THREAD_STAT_ZOMBIE)
270                         while(t->Status == initStatus) {
271                                 Threads_Yield();
272                         }
273                 
274                 ret = t->RetStatus;
275                 switch(t->Status)
276                 {
277                 case THREAD_STAT_ZOMBIE:
278                         t->Status = THREAD_STAT_DEAD;
279                         if(status)      *status = 0;
280                         Threads_AddToDelete( t );
281                         break;
282                 default:
283                         if(status)      *status = -1;
284                         break;
285                 }
286                 return ret;
287         }
288         
289         return -1;
290 }
291
292 /**
293  * \fn tThread *Threads_GetThread(Uint TID)
294  * \brief Gets a thread given its TID
295  */
296 tThread *Threads_GetThread(Uint TID)
297 {
298         tThread *thread;
299         
300         // Search Active List
301         for(thread = gActiveThreads;
302                 thread;
303                 thread = thread->Next)
304         {
305                 if(thread->TID == TID)
306                         return thread;
307         }
308         
309         // Search Sleeping List
310         for(thread = gSleepingThreads;
311                 thread;
312                 thread = thread->Next)
313         {
314                 if(thread->TID == TID)
315                         return thread;
316         }
317         
318         return NULL;
319 }
320
321 /**
322  * \fn void Threads_AddToDelete(tThread *Thread)
323  * \brief Adds a thread to the delete queue
324  */
325 void Threads_AddToDelete(tThread *Thread)
326 {
327         // Add to delete queue
328         if(gDeleteThreads) {
329                 Thread->Next = gDeleteThreads;
330                 gDeleteThreads = Thread;
331         } else {
332                 Thread->Next = NULL;
333                 gDeleteThreads = Thread;
334         }
335 }
336
337 /**
338  * \fn tThread *Threads_int_GetPrev(tThread **List, tThread *Thread)
339  * \brief Gets the previous entry in a thead linked list
340  */
341 tThread *Threads_int_GetPrev(tThread **List, tThread *Thread)
342 {
343         tThread *ret;
344         // First Entry
345         if(*List == Thread) {
346                 return (tThread*)List;
347         } else {
348                 for(ret = *List;
349                         ret->Next && ret->Next != Thread;
350                         ret = ret->Next
351                         );
352                 // Error if the thread is not on the list
353                 if(!ret->Next || ret->Next != Thread) {
354                         return NULL;
355                 }
356         }
357         return ret;
358 }
359
360 /**
361  * \fn void Threads_Exit(int TID, int Status)
362  * \brief Exit the current process
363  */
364 void Threads_Exit(int TID, int Status)
365 {
366         if( TID == 0 )
367                 Threads_Kill( Proc_GetCurThread(), (Uint)Status & 0xFF );
368         else
369                 Threads_Kill( Threads_GetThread(TID), (Uint)Status & 0xFF );
370         for(;;) HALT(); // Just in case
371 }
372
373 /**
374  * \fn void Threads_Kill(tThread *Thread, int Status)
375  * \brief Kill a thread
376  * \param Thread        Thread to kill
377  * \param Status        Status code to return to the parent
378  */
379 void Threads_Kill(tThread *Thread, int Status)
380 {
381         tThread *prev;
382         tMsg    *msg;
383         
384         // Kill all children
385         #if 0
386         {
387                 tThread *child;
388                 for(child = gActiveThreads;
389                         child;
390                         child = child->Next)
391                 {
392                         if(child->PTID == Thread->TID)
393                                 Threads_Kill(child, -1);
394                 }
395         }
396         #endif
397         
398         ///\note Double lock is needed due to overlap of locks
399         
400         // Lock thread (stop us recieving messages)
401         LOCK( &Thread->IsLocked );
402         
403         // Lock thread list
404         LOCK( &giThreadListLock );
405         
406         // Get previous thread on list
407         prev = Threads_int_GetPrev( &gActiveThreads, Thread );
408         if(!prev) {
409                 Warning("Proc_Exit - Current thread is not on the active queue");
410                 return;
411         }
412         
413         // Clear Message Queue
414         while( Thread->Messages )
415         {
416                 msg = Thread->Messages->Next;
417                 free( Thread->Messages );
418                 Thread->Messages = msg;
419         }
420         
421         Thread->Remaining = 0;  // Clear Remaining Quantum
422         Thread->Quantum = 0;    // Clear Quantum to indicate dead thread
423         prev->Next = Thread->Next;      // Remove from active
424         
425         giNumActiveThreads --;
426         giTotalTickets -= Thread->NumTickets;
427         
428         // Mark thread as a zombie
429         Thread->RetStatus = Status;
430         
431         // Don't Zombie if we are being killed as part of a tree
432         if(Status == -1)
433         {
434                 Thread->Status = THREAD_STAT_DEAD;
435                 Threads_AddToDelete( Thread );
436         } else {
437                 Thread->Status = THREAD_STAT_ZOMBIE;
438         }
439         
440         // Release spinlocks
441         RELEASE( &Thread->IsLocked );   // Released first so that it IS released
442         RELEASE( &giThreadListLock );
443         
444         //Log("Thread %i went *hurk*", Thread->TID);
445         
446         if(Status != -1)        HALT();
447 }
448
449 /**
450  * \fn void Threads_Yield()
451  * \brief Yield remainder of timeslice
452  */
453 void Threads_Yield()
454 {
455         Proc_GetCurThread()->Remaining = 0;
456         HALT();
457 }
458
459 /**
460  * \fn void Threads_Sleep()
461  * \brief Take the current process off the run queue
462  */
463 void Threads_Sleep()
464 {
465         tThread *cur = Proc_GetCurThread();
466         tThread *thread;
467         
468         //Log_Log("Threads", "%i going to sleep", cur->TID);
469         
470         // Acquire Spinlock
471         LOCK( &giThreadListLock );
472         
473         // Get thread before current thread
474         thread = Threads_int_GetPrev( &gActiveThreads, cur );
475         if(!thread) {
476                 Warning("Threads_Sleep - Current thread is not on the active queue");
477                 Threads_Dump();
478                 return;
479         }
480         
481         // Don't sleep if there is a message waiting
482         if( cur->Messages ) {
483                 RELEASE( &giThreadListLock );
484                 return;
485         }
486         
487         // Unset remaining timeslices (force a task switch on timer fire)
488         cur->Remaining = 0;
489         
490         // Remove from active list
491         thread->Next = cur->Next;
492         
493         // Add to Sleeping List (at the top)
494         cur->Next = gSleepingThreads;
495         gSleepingThreads = cur;
496         
497         // Reduce the active count & ticket count
498         giNumActiveThreads --;
499         giTotalTickets -= cur->NumTickets;
500         
501         // Mark thread as sleeping
502         cur->Status = THREAD_STAT_SLEEPING;
503         
504         // Release Spinlock
505         RELEASE( &giThreadListLock );
506         
507         while(cur->Status != THREAD_STAT_ACTIVE)        HALT();
508 }
509
510
511 /**
512  * \fn void Threads_Wake( tThread *Thread )
513  * \brief Wakes a sleeping/waiting thread up
514  */
515 void Threads_Wake(tThread *Thread)
516 {
517         tThread *prev;
518         switch(Thread->Status)
519         {
520         case THREAD_STAT_ACTIVE:        break;
521         case THREAD_STAT_SLEEPING:
522                 //Log_Log("Threads", "Waking %i (%p) from sleeping", Thread->TID, Thread);
523                 LOCK( &giThreadListLock );
524                 prev = Threads_int_GetPrev(&gSleepingThreads, Thread);
525                 prev->Next = Thread->Next;      // Remove from sleeping queue
526                 Thread->Next = gActiveThreads;  // Add to active queue
527                 gActiveThreads = Thread;
528                 giNumActiveThreads ++;
529                 giTotalTickets += Thread->NumTickets;
530                 Thread->Status = THREAD_STAT_ACTIVE;
531                 RELEASE( &giThreadListLock );
532                 break;
533         case THREAD_STAT_WAITING:
534                 Warning("Thread_Wake - Waiting threads are not currently supported");
535                 break;
536         case THREAD_STAT_DEAD:
537                 Warning("Thread_Wake - Attempt to wake dead thread (%i)", Thread->TID);
538                 break;
539         default:
540                 Warning("Thread_Wake - Unknown process status (%i)\n", Thread->Status);
541                 break;
542         }
543 }
544
545 void Threads_WakeTID(tTID Thread)
546 {
547         Threads_Wake( Threads_GetThread(Thread) );
548 }
549
550 /**
551  * \fn void Threads_AddActive(tThread *Thread)
552  * \brief Adds a thread to the active queue
553  */
554 void Threads_AddActive(tThread *Thread)
555 {
556         LOCK( &giThreadListLock );
557         Thread->Next = gActiveThreads;
558         gActiveThreads = Thread;
559         giNumActiveThreads ++;
560         giTotalTickets += Thread->NumTickets;
561         //Log("Threads_AddActive: giNumActiveThreads = %i, giTotalTickets = %i",
562         //      giNumActiveThreads, giTotalTickets);
563         RELEASE( &giThreadListLock );
564 }
565
566 /**
567  * \fn void Threads_SetSignalHandler(Uint Handler)
568  * \brief Sets the signal handler for a signal
569  */
570 void Threads_SetFaultHandler(Uint Handler)
571 {       
572         Log_Log("Threads", "Threads_SetFaultHandler: Handler = %p", Handler);
573         Proc_GetCurThread()->FaultHandler = Handler;
574 }
575
576 /**
577  * \fn void Threads_Fault(int Num)
578  * \brief Calls a fault handler
579  */
580 void Threads_Fault(int Num)
581 {
582         tThread *thread = Proc_GetCurThread();
583         
584         Log_Log("Threads", "Threads_Fault: thread = %p", thread);
585         
586         if(!thread)     return ;
587         
588         Log_Log("Threads", "Threads_Fault: thread->FaultHandler = %p", thread->FaultHandler);
589         
590         switch(thread->FaultHandler)
591         {
592         case 0: // Panic?
593                 Threads_Kill(thread, -1);
594                 HALT();
595                 return ;
596         case 1: // Dump Core?
597                 Threads_Kill(thread, -1);
598                 HALT();
599                 return ;
600         }
601         
602         // Double Fault? Oh, F**k
603         if(thread->CurFaultNum != 0) {
604                 Threads_Kill(thread, -1);       // For now, just kill
605                 HALT();
606         }
607         
608         Proc_CallFaultHandler(thread);
609 }
610
611 // --- Process Structure Access Functions ---
612 tPID Threads_GetPID()
613 {
614         return Proc_GetCurThread()->TGID;
615 }
616 tTID Threads_GetTID()
617 {
618         return Proc_GetCurThread()->TID;
619 }
620 tUID Threads_GetUID()
621 {
622         return Proc_GetCurThread()->UID;
623 }
624 tGID Threads_GetGID()
625 {
626         return Proc_GetCurThread()->GID;
627 }
628
629 int Threads_SetUID(Uint *Errno, tUID ID)
630 {
631         tThread *t = Proc_GetCurThread();
632         if( t->UID != 0 ) {
633                 *Errno = -EACCES;
634                 return -1;
635         }
636         Log("Threads_SetUID - Setting User ID to %i", ID);
637         t->UID = ID;
638         return 0;
639 }
640
641 int Threads_SetGID(Uint *Errno, tGID ID)
642 {
643         tThread *t = Proc_GetCurThread();
644         if( t->UID != 0 ) {
645                 *Errno = -EACCES;
646                 return -1;
647         }
648         Log("Threads_SetGID - Setting Group ID to %i", ID);
649         t->GID = ID;
650         return 0;
651 }
652
653 /**
654  * \fn void Threads_Dump()
655  * \brief Dums a list of currently running threads
656  */
657 void Threads_Dump()
658 {
659         tThread *thread;
660         tThread *cur = Proc_GetCurThread();
661         
662         Log("Active Threads:");
663         for(thread=gActiveThreads;thread;thread=thread->Next)
664         {
665                 Log("%c%i (%i) - %s",
666                         (thread==cur?'*':' '),
667                         thread->TID, thread->TGID, thread->ThreadName);
668                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
669                 Log("  KStack 0x%x", thread->KernelStack);
670         }
671         Log("Sleeping Threads:");
672         for(thread=gSleepingThreads;thread;thread=thread->Next)
673         {
674                 Log("%c%i (%i) - %s",
675                         (thread==cur?'*':' '),
676                         thread->TID, thread->TGID, thread->ThreadName);
677                 Log("  %i Tickets, Quantum %i", thread->NumTickets, thread->Quantum);
678                 Log("  KStack 0x%x", thread->KernelStack);
679         }
680 }
681
682 /**
683  * \fn tThread *Threads_GetNextToRun(int CPU)
684  * \brief Gets the next thread to run
685  */
686 tThread *Threads_GetNextToRun(int CPU)
687 {
688         tThread *thread;
689          int    ticket;
690          int    number;
691         
692         if(giNumActiveThreads == 0) {
693                 //Log_Debug("Threads", "CPU%i has no threads to run", CPU);
694                 return NULL;
695         }
696         
697         // Special case: 1 thread
698         if(giNumActiveThreads == 1) {
699                 //Log_Debug("Threads", "CPU%i has only one thread %i %s",
700                 //      CPU, gActiveThreads->TID, gActiveThreads->ThreadName);
701                 return gActiveThreads;
702         }
703         
704         //Log(" Threads_GetNextToRun: giNumActiveThreads=%i,giTotalTickets=%i",
705         //      giNumActiveThreads, giTotalTickets);
706         // Get the ticket number
707         ticket = number = rand() % giTotalTickets;
708         
709         //Log(" Threads_GetNextToRun: ticket = %i", ticket);
710         
711         // Find the next thread
712         for(thread=gActiveThreads;thread;thread=thread->Next)
713         {
714                 if(thread->NumTickets > number) break;
715                 number -= thread->NumTickets;
716         }
717         
718         // Error Check
719         if(thread == NULL)
720         {
721                 number = 0;
722                 for(thread=gActiveThreads;thread;thread=thread->Next)
723                         number += thread->NumTickets;
724                 Panic("Bookeeping Failed - giTotalTicketCount (%i) != true count (%i)",
725                         giTotalTickets, number);
726         }
727         
728         //Log_Debug("Threads", "Switching CPU%i to %p (%s)",
729         //      CPU, thread, thread->ThreadName);
730         
731         return thread;
732 }
733
734 /**
735  * \fn void Threads_SegFault(tVAddr Addr)
736  * \brief Called when a Segment Fault occurs
737  */
738 void Threads_SegFault(tVAddr Addr)
739 {
740         Warning("Thread #%i committed a segfault at address %p", Proc_GetCurThread()->TID, Addr);
741         Threads_Fault( 1 );
742         //Threads_Exit( 0, -1 );
743 }
744
745 // === EXPORTS ===
746 EXPORT(Threads_GetUID);

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