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

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