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

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