Separated Architecture independent thread controll into the root of the tree
[tpg/acess2.git] / Kernel / arch / x86 / proc.c
1 /*
2  * AcessOS Microkernel Version
3  * proc.c
4  */
5 #include <common.h>
6 #include <proc.h>
7 #include <mm_virt.h>
8 #include <errno.h>
9 #if USE_MP
10 # include <mp.h>
11 #endif
12
13 // === CONSTANTS ===
14 #define SWITCH_MAGIC    0xFFFACE55      // There is no code in this area
15 #define TIMER_DIVISOR   11931   //~100Hz
16
17 // === IMPORTS ===
18 extern tGDT     gGDT[];
19 extern Uint     GetEIP();       // start.asm
20 extern Uint32   gaInitPageDir[1024];    // start.asm
21 extern void     Kernel_Stack_Top;
22 extern volatile int     giThreadListLock;
23 extern int      giNumCPUs;
24 extern int      giNextTID;
25 extern int      giTotalTickets;
26 extern int      giNumActiveThreads;
27 extern tThread  *gActiveThreads;
28 extern tThread  *gSleepingThreads;
29 extern tThread  *gDeleteThreads;
30
31 // === PROTOTYPES ===
32 void    ArchThreads_Init();
33 tThread *Proc_GetCurThread();
34 void    Proc_ChangeStack();
35  int    Proc_Clone(Uint *Err, Uint Flags);
36 void    Proc_Scheduler();
37
38 // === GLOBALS ===
39 // --- Current State ---
40 #if USE_MP
41 tThread **gCurrentThread = NULL;
42 #else
43 tThread *gCurrentThread = NULL;
44 #endif
45 // --- Multiprocessing ---
46 #if USE_MP
47 tMPInfo *gMPTable = NULL;
48 #endif
49 #if USE_PAE
50 Uint32  *gPML4s[4] = NULL;
51 #endif
52 tTSS    *gTSSs = NULL;
53 #if !USE_MP
54 tTSS    gTSS0 = {0};
55 #endif
56
57 // === CODE ===
58 /**
59  * \fn void ArchThreads_Init()
60  * \brief Starts the process scheduler
61  */
62 void ArchThreads_Init()
63 {
64         Uint    pos = 0;
65         #if USE_MP
66         // -- Initialise Multiprocessing
67         // Find MP Floating Table
68         // - EBDA
69         for(pos = KERNEL_BASE|0x9FC00; pos < (KERNEL_BASE|0xA0000); pos += 16) {
70                 if( *(Uint*)(pos) == MPTABLE_IDENT ) {
71                         if(ByteSum( (void*)pos, sizeof(tMPInfo) ) != 0) continue;
72                         gMPTable = (void*)pos;
73                         break;
74                 }
75         }
76         // - Last KiB
77         if(!gMPTable) {
78                 
79         }
80         // - BIOS ROM
81         if(!gMPTable) {
82                 for(pos = KERNEL_BASE|0xF0000; pos < (KERNEL_BASE|0x100000); pos += 16) {
83                         if( *(Uint*)(pos) == MPTABLE_IDENT ) {
84                                 if(ByteSum( (void*)pos, sizeof(tMPInfo) ) != 0) continue;
85                                 gMPTable = (void*)pos;
86                                 break;
87                         }
88                 }
89         }
90         
91         // If the MP Table Exists, parse it
92         if(gMPTable)
93         {
94                 Panic("Uh oh... MP Table Parsing is unimplemented\n");
95         } else {
96         #endif
97                 giNumCPUs = 1;
98                 gTSSs = &gTSS0;
99         #if USE_MP
100         }
101         
102         // Initialise TSS
103         for(pos=0;pos<giNumCPUs;pos++)
104         {
105         #else
106         pos = 0;
107         #endif
108                 gTSSs[pos].SS0 = 0x10;
109                 gTSSs[pos].ESP0 = 0;    // Set properly by scheduler
110                 gGDT[5+pos].LimitLow = sizeof(tTSS);
111                 gGDT[5+pos].LimitHi = 0;
112                 gGDT[5+pos].Access = 0x89;      // Type
113                 gGDT[5+pos].Flags = 0x4;
114                 gGDT[5+pos].BaseLow = (Uint)&gTSSs[pos] & 0xFFFF;
115                 gGDT[5+pos].BaseMid = (Uint)&gTSSs[pos] >> 16;
116                 gGDT[5+pos].BaseHi = (Uint)&gTSSs[pos] >> 24;
117         #if USE_MP
118         }
119         for(pos=0;pos<giNumCPUs;pos++) {
120         #endif
121                 __asm__ __volatile__ ("ltr %%ax"::"a"(0x28+pos*8));
122         #if USE_MP
123         }
124         #endif
125         
126         // Set timer frequency
127         outb(0x43, 0x34);       // Set Channel 0, Low/High, Rate Generator
128         outb(0x40, TIMER_DIVISOR&0xFF); // Low Byte of Divisor
129         outb(0x40, (TIMER_DIVISOR>>8)&0xFF);    // High Byte
130         
131         // Create Per-Process Data Block
132         MM_Allocate(MM_PPD_CFG);
133         
134         // Change Stacks
135         Proc_ChangeStack();
136         
137         // Start Interrupts (and hence scheduler)
138         __asm__ __volatile__("sti");
139 }
140
141 /**
142  * \fn tThread *Proc_GetCurThread()
143  * \brief Gets the current thread
144  */
145 tThread *Proc_GetCurThread()
146 {
147         #if USE_MP
148         return NULL;
149         #else
150         return gCurrentThread;
151         #endif
152 }
153
154 /**
155  * \fn void Proc_ChangeStack()
156  * \brief Swaps the current stack for a new one (in the proper stack reigon)
157  */
158 void Proc_ChangeStack()
159 {
160         Uint    esp, ebp;
161         Uint    tmpEbp, oldEsp;
162         Uint    curBase, newBase;
163
164         __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
165         __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
166
167         oldEsp = esp;
168
169         // Create new KStack
170         newBase = MM_NewKStack();
171         // Check for errors
172         if(newBase == 0) {
173                 Panic("What the?? Unable to allocate space for initial kernel stack");
174                 return;
175         }
176
177         curBase = gCurrentThread->KernelStack;
178         
179         LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
180
181         // Get ESP as a used size
182         esp = curBase - esp;
183         LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
184         // Copy used stack
185         memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
186         // Get ESP as an offset in the new stack
187         esp = newBase - esp;
188         // Adjust EBP
189         ebp = newBase - (curBase - ebp);
190
191         // Repair EBPs & Stack Addresses
192         // Catches arguments also, but may trash stack-address-like values
193         for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
194         {
195                 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
196                         *(Uint*)tmpEbp += newBase - curBase;
197         }
198         
199         gCurrentThread->KernelStack = newBase;
200         
201         __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
202         __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
203 }
204
205 /**
206  * \fn int Proc_Clone(Uint *Err, Uint Flags)
207  * \brief Clone the current process
208  */
209 int Proc_Clone(Uint *Err, Uint Flags)
210 {
211         tThread *newThread;
212         Uint    eip, esp, ebp;
213         
214         __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
215         __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
216         
217         // Create new thread structure
218         newThread = malloc( sizeof(tThread) );
219         if(!newThread) {
220                 Warning("Proc_Clone - Out of memory when creating thread\n");
221                 *Err = -ENOMEM;
222                 return -1;
223         }
224         // Base new thread on old
225         memcpy(newThread, gCurrentThread, sizeof(tThread));
226         // Initialise Memory Space (New Addr space or kernel stack)
227         if(Flags & CLONE_VM) {
228                 newThread->TGID = newThread->TID;
229                 newThread->MemState.CR3 = MM_Clone();
230         } else {
231                 Uint    tmpEbp, oldEsp = esp;
232
233                 // Create new KStack
234                 newThread->KernelStack = MM_NewKStack();
235                 // Check for errors
236                 if(newThread->KernelStack == 0) {
237                         free(newThread);
238                         return -1;
239                 }
240
241                 // Get ESP as a used size
242                 esp = gCurrentThread->KernelStack - esp;
243                 // Copy used stack
244                 memcpy( (void*)(newThread->KernelStack - esp), (void*)(gCurrentThread->KernelStack - esp), esp );
245                 // Get ESP as an offset in the new stack
246                 esp = newThread->KernelStack - esp;
247                 // Adjust EBP
248                 ebp = newThread->KernelStack - (gCurrentThread->KernelStack - ebp);
249
250                 // Repair EBPs & Stack Addresses
251                 // Catches arguments also, but may trash stack-address-like values
252                 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
253                 {
254                         if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < gCurrentThread->KernelStack)
255                                 *(Uint*)tmpEbp += newThread->KernelStack - gCurrentThread->KernelStack;
256                 }
257         }
258
259         // Set Pointer, Spinlock and TID
260         newThread->Next = NULL;
261         newThread->IsLocked = 0;
262         newThread->TID = giNextTID++;
263         newThread->PTID = gCurrentThread->TID;
264
265         // Clear message list (messages are not inherited)
266         newThread->Messages = NULL;
267         newThread->LastMessage = NULL;
268         
269         // Set remaining (sheduler expects remaining to be correct)
270         newThread->Remaining = newThread->Quantum;
271         
272         // Save core machine state
273         newThread->SavedState.ESP = esp;
274         newThread->SavedState.EBP = ebp;
275         eip = GetEIP();
276         if(eip == SWITCH_MAGIC) {
277                 outb(0x20, 0x20);       // ACK Timer and return as child
278                 return 0;
279         }
280         
281         // Set EIP as parent
282         newThread->SavedState.EIP = eip;
283         
284         // Lock list and add to active
285         LOCK( &giThreadListLock );
286         newThread->Next = gActiveThreads;
287         gActiveThreads = newThread;
288         giNumActiveThreads ++;
289         giTotalTickets += newThread->NumTickets;
290         RELEASE( &giThreadListLock );
291         
292         return newThread->TID;
293 }
294
295 #if 0
296 /**
297  * \fn void Proc_SetSignalHandler(int Num, void *Handler)
298  * \brief Sets the signal handler for a signal
299  */
300 void Proc_SetSignalHandler(int Num, void *Handler)
301 {
302         if(Num < 0 || Num >= NSIG)      return;
303         
304         gCurrentThread->SignalHandlers[Num] = Handler;
305 }
306
307 /**
308  * \fn void Proc_SendSignal(int TID, int Num)
309  */
310 void Proc_SendSignal(int TID, int Num)
311 {
312         tThread *thread = Proc_GetThread(TID);
313         void    *handler;
314         
315         if(!thread)     return ;
316         
317         handler = thread->SignalHandlers[Num];
318         
319         // Panic?
320         if(handler == SIG_ERR) {
321                 Proc_Kill(TID);
322                 return ;
323         }
324         // Dump Core?
325         if(handler == -2) {
326                 Proc_Kill(TID);
327                 return ;
328         }
329         // Ignore?
330         if(handler == -2)       return;
331         
332         // Check the type and handle if the thread is already in a signal
333         if(thread->CurSignal != 0) {
334                 if(Num < _SIGTYPE_FATAL)
335                         Proc_Kill(TID);
336                 } else {
337                         while(thread->CurSignal != 0)
338                                 Proc_Yield();
339                 }
340         }
341         
342         //TODO: 
343 }
344
345 #endif
346
347 /**
348  * \fn Uint Proc_MakeUserStack()
349  * \brief Creates a new user stack
350  */
351 Uint Proc_MakeUserStack()
352 {
353          int    i;
354         Uint    base = USER_STACK_TOP - USER_STACK_SZ;
355         
356         // Check Prospective Space
357         for( i = USER_STACK_SZ >> 12; i--; )
358                 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
359                         break;
360         
361         if(i != -1)     return 0;
362         
363         // Allocate Stack - Allocate incrementally to clean up MM_Dump output
364         for( i = 0; i < USER_STACK_SZ/4069; i++ )
365                 MM_Allocate( base + (i<<12) );
366         
367         return base + USER_STACK_SZ;
368 }
369
370
371 /**
372  * \fn void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, char **EnvP, int DataSize)
373  * \brief Starts a user task
374  */
375 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
376 {
377         Uint    *stack = (void*)Proc_MakeUserStack();
378          int    i;
379         Uint    delta;
380         Uint16  ss, cs;
381         
382         LOG("stack = 0x%x", stack);
383         
384         // Copy Arguments
385         stack = (void*)( (Uint)stack - DataSize );
386         memcpy( stack, ArgV, DataSize );
387         
388         // Adjust Arguments and environment
389         delta = (Uint)stack - (Uint)ArgV;
390         ArgV = (char**)stack;
391         for( i = 0; ArgV[i]; i++ )      ArgV[i] += delta;
392         i ++;
393         EnvP = &ArgV[i];
394         for( i = 0; EnvP[i]; i++ )      EnvP[i] += delta;
395         
396         // User Mode Segments
397         ss = 0x23;      cs = 0x1B;
398         
399         // Arguments
400         *--stack = (Uint)EnvP;
401         *--stack = (Uint)ArgV;
402         *--stack = (Uint)ArgC;
403         while(*Bases)
404                 *--stack = *Bases++;
405         *--stack = 0;   // Return Address
406         delta = (Uint)stack;    // Reuse delta to save SP
407         
408         *--stack = ss;          //Stack Segment
409         *--stack = delta;       //Stack Pointer
410         *--stack = 0x0202;      //EFLAGS (Resvd (0x2) and IF (0x20))
411         *--stack = cs;          //Code Segment
412         *--stack = Entrypoint;  //EIP
413         //PUSHAD
414         *--stack = 0xAAAAAAAA;  // eax
415         *--stack = 0xCCCCCCCC;  // ecx
416         *--stack = 0xDDDDDDDD;  // edx
417         *--stack = 0xBBBBBBBB;  // ebx
418         *--stack = 0xD1D1D1D1;  // edi
419         *--stack = 0x54545454;  // esp - NOT POPED
420         *--stack = 0x51515151;  // esi
421         *--stack = 0xB4B4B4B4;  // ebp
422         //Individual PUSHs
423         *--stack = ss;  // ds
424         *--stack = ss;  // es
425         *--stack = ss;  // fs
426         *--stack = ss;  // gs
427         
428         __asm__ __volatile__ (
429         "mov %%eax,%%esp;\n\t"  // Set stack pointer
430         "pop %%gs;\n\t"
431         "pop %%fs;\n\t"
432         "pop %%es;\n\t"
433         "pop %%ds;\n\t"
434         "popa;\n\t"
435         "iret;\n\t" : : "a" (stack));
436         for(;;);
437 }
438
439 /**
440  * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
441  * \brief Demotes a process to a lower permission level
442  * \param Err   Pointer to user's errno
443  */
444 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
445 {
446          int    cpl = Regs->cs & 3;
447         // Sanity Check
448         if(Dest > 3 || Dest < 0) {
449                 *Err = -EINVAL;
450                 return -1;
451         }
452         
453         // Permission Check
454         if(cpl > Dest) {
455                 *Err = -EACCES;
456                 return -1;
457         }
458         
459         // Change the Segment Registers
460         Regs->cs = (((Dest+1)<<4) | Dest) - 8;
461         Regs->ss = ((Dest+1)<<4) | Dest;
462         // Check if the GP Segs are GDT, then change them
463         if(!(Regs->ds & 4))     Regs->ds = ((Dest+1)<<4) | Dest;
464         if(!(Regs->es & 4))     Regs->es = ((Dest+1)<<4) | Dest;
465         if(!(Regs->fs & 4))     Regs->fs = ((Dest+1)<<4) | Dest;
466         if(!(Regs->gs & 4))     Regs->gs = ((Dest+1)<<4) | Dest;
467         
468         return 0;
469 }
470
471 /**
472  * \fn void Proc_Scheduler(int CPU)
473  * \brief Swap current thread and clears dead threads
474  */
475 void Proc_Scheduler(int CPU)
476 {
477         Uint    esp, ebp, eip;
478         Uint    number, ticket;
479         tThread *thread;
480         
481         // If the spinlock is set, let it complete
482         if(giThreadListLock)    return;
483         
484         // Clear Delete Queue
485         while(gDeleteThreads)
486         {
487                 thread = gDeleteThreads->Next;
488                 if(gDeleteThreads->IsLocked) {  // Only free if structure is unused
489                         gDeleteThreads->Status = THREAD_STAT_NULL;
490                         free( gDeleteThreads );
491                 }
492                 gDeleteThreads = thread;
493         }
494         
495         // Check if there is any tasks running
496         if(giNumActiveThreads == 0) {
497                 Log("No Active threads, sleeping\n");
498                 __asm__ __volatile__ ("hlt");
499                 return;
500         }
501         
502         // Reduce remaining quantum
503         if(gCurrentThread->Remaining--) return;
504         // Reset quantum for next call
505         gCurrentThread->Remaining = gCurrentThread->Quantum;
506         
507         // Get machine state
508         __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
509         __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
510         eip = GetEIP();
511         if(eip == SWITCH_MAGIC) return; // Check if a switch happened
512         
513         // Save machine state
514         gCurrentThread->SavedState.ESP = esp;
515         gCurrentThread->SavedState.EBP = ebp;
516         gCurrentThread->SavedState.EIP = eip;
517         
518         // Special case: 1 thread
519         if(giNumActiveThreads == 1)
520         {
521                 // Check if a switch is needed (NumActive can be 1 after a sleep)
522                 if(gActiveThreads == gCurrentThread)    return;
523                 // Switch processes
524                 gCurrentThread = gActiveThreads;
525                 goto performSwitch;
526         }
527         
528         // Get the ticket number
529         ticket = number = rand() % giTotalTickets;
530         
531         // Find the next thread
532         for(thread=gActiveThreads;thread;thread=thread->Next)
533         {
534                 if(thread->NumTickets > number) break;
535                 number -= thread->NumTickets;
536         }
537         
538         // Error Check
539         if(thread == NULL)
540         {
541                 number = 0;
542                 for(thread=gActiveThreads;thread;thread=thread->Next)
543                         number += thread->NumTickets;
544                 Panic("Bookeeping Failed - giTotalTicketCount (%i) != true count (%i)",
545                         giTotalTickets, number);
546         }
547         
548         // Set current thread
549         gCurrentThread = thread;
550         
551         // Update Kernel Stack pointer
552         gTSSs[CPU].ESP0 = thread->KernelStack;
553         
554 performSwitch:
555         // Set address space
556         //MM_SetCR3( gCurrentThread->CR3 );
557         __asm__ __volatile__ ("mov %0, %%cr3"::"a"(gCurrentThread->MemState.CR3));
558         // Switch threads
559         __asm__ __volatile__ (
560                 "mov %1, %%esp\n\t"
561                 "mov %2, %%ebp\n\t"
562                 "jmp *%3" : :
563                 "a"(SWITCH_MAGIC), "b"(gCurrentThread->SavedState.ESP),
564                 "d"(gCurrentThread->SavedState.EBP), "c"(gCurrentThread->SavedState.EIP));
565         for(;;);        // Shouldn't reach here
566 }

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