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

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