336bcdb3e5a724da1ccb6627255bb95d05b99495
[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                 Log("Thread %i running", Proc_GetCurThread()->TID);
302                 outb(0x20, 0x20);       // ACK Timer and return as child
303                 return 0;
304         }
305         
306         // Set EIP as parent
307         newThread->SavedState.EIP = eip;
308         
309         // Lock list and add to active
310         LOCK( &giThreadListLock );
311         newThread->Next = gActiveThreads;
312         gActiveThreads = newThread;
313         giNumActiveThreads ++;
314         giTotalTickets += newThread->NumTickets;
315         RELEASE( &giThreadListLock );
316         
317         Threads_Dump();
318         
319         return newThread->TID;
320 }
321
322 /**
323  * \fn Uint Proc_MakeUserStack()
324  * \brief Creates a new user stack
325  */
326 Uint Proc_MakeUserStack()
327 {
328          int    i;
329         Uint    base = USER_STACK_TOP - USER_STACK_SZ;
330         
331         // Check Prospective Space
332         for( i = USER_STACK_SZ >> 12; i--; )
333                 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
334                         break;
335         
336         if(i != -1)     return 0;
337         
338         // Allocate Stack - Allocate incrementally to clean up MM_Dump output
339         for( i = 0; i < USER_STACK_SZ/4069; i++ )
340                 MM_Allocate( base + (i<<12) );
341         
342         return base + USER_STACK_SZ;
343 }
344
345
346 /**
347  * \fn void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, char **EnvP, int DataSize)
348  * \brief Starts a user task
349  */
350 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
351 {
352         Uint    *stack = (void*)Proc_MakeUserStack();
353          int    i;
354         Uint    delta;
355         Uint16  ss, cs;
356         
357         LOG("stack = 0x%x", stack);
358         
359         // Copy Arguments
360         stack = (void*)( (Uint)stack - DataSize );
361         memcpy( stack, ArgV, DataSize );
362         
363         // Adjust Arguments and environment
364         delta = (Uint)stack - (Uint)ArgV;
365         ArgV = (char**)stack;
366         for( i = 0; ArgV[i]; i++ )      ArgV[i] += delta;
367         i ++;
368         EnvP = &ArgV[i];
369         for( i = 0; EnvP[i]; i++ )      EnvP[i] += delta;
370         
371         // User Mode Segments
372         ss = 0x23;      cs = 0x1B;
373         
374         // Arguments
375         *--stack = (Uint)EnvP;
376         *--stack = (Uint)ArgV;
377         *--stack = (Uint)ArgC;
378         while(*Bases)
379                 *--stack = *Bases++;
380         *--stack = 0;   // Return Address
381         delta = (Uint)stack;    // Reuse delta to save SP
382         
383         *--stack = ss;          //Stack Segment
384         *--stack = delta;       //Stack Pointer
385         *--stack = 0x0202;      //EFLAGS (Resvd (0x2) and IF (0x20))
386         *--stack = cs;          //Code Segment
387         *--stack = Entrypoint;  //EIP
388         //PUSHAD
389         *--stack = 0xAAAAAAAA;  // eax
390         *--stack = 0xCCCCCCCC;  // ecx
391         *--stack = 0xDDDDDDDD;  // edx
392         *--stack = 0xBBBBBBBB;  // ebx
393         *--stack = 0xD1D1D1D1;  // edi
394         *--stack = 0x54545454;  // esp - NOT POPED
395         *--stack = 0x51515151;  // esi
396         *--stack = 0xB4B4B4B4;  // ebp
397         //Individual PUSHs
398         *--stack = ss;  // ds
399         *--stack = ss;  // es
400         *--stack = ss;  // fs
401         *--stack = ss;  // gs
402         
403         __asm__ __volatile__ (
404         "mov %%eax,%%esp;\n\t"  // Set stack pointer
405         "pop %%gs;\n\t"
406         "pop %%fs;\n\t"
407         "pop %%es;\n\t"
408         "pop %%ds;\n\t"
409         "popa;\n\t"
410         "iret;\n\t" : : "a" (stack));
411         for(;;);
412 }
413
414 /**
415  * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
416  * \brief Demotes a process to a lower permission level
417  * \param Err   Pointer to user's errno
418  */
419 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
420 {
421          int    cpl = Regs->cs & 3;
422         // Sanity Check
423         if(Dest > 3 || Dest < 0) {
424                 *Err = -EINVAL;
425                 return -1;
426         }
427         
428         // Permission Check
429         if(cpl > Dest) {
430                 *Err = -EACCES;
431                 return -1;
432         }
433         
434         // Change the Segment Registers
435         Regs->cs = (((Dest+1)<<4) | Dest) - 8;
436         Regs->ss = ((Dest+1)<<4) | Dest;
437         // Check if the GP Segs are GDT, then change them
438         if(!(Regs->ds & 4))     Regs->ds = ((Dest+1)<<4) | Dest;
439         if(!(Regs->es & 4))     Regs->es = ((Dest+1)<<4) | Dest;
440         if(!(Regs->fs & 4))     Regs->fs = ((Dest+1)<<4) | Dest;
441         if(!(Regs->gs & 4))     Regs->gs = ((Dest+1)<<4) | Dest;
442         
443         return 0;
444 }
445
446 /**
447  * \fn void Proc_Scheduler(int CPU)
448  * \brief Swap current thread and clears dead threads
449  */
450 void Proc_Scheduler(int CPU)
451 {
452         Uint    esp, ebp, eip;
453         tThread *thread;
454         
455         // If the spinlock is set, let it complete
456         if(giThreadListLock)    return;
457         
458         // Clear Delete Queue
459         while(gDeleteThreads)
460         {
461                 thread = gDeleteThreads->Next;
462                 if(gDeleteThreads->IsLocked) {  // Only free if structure is unused
463                         gDeleteThreads->Status = THREAD_STAT_NULL;
464                         free( gDeleteThreads );
465                 }
466                 gDeleteThreads = thread;
467         }
468         
469         // Check if there is any tasks running
470         if(giNumActiveThreads == 0) {
471                 Log("No Active threads, sleeping");
472                 __asm__ __volatile__ ("hlt");
473                 return;
474         }
475         
476         // Reduce remaining quantum and continue timeslice if non-zero
477         if(gCurrentThread->Remaining--) return;
478         // Reset quantum for next call
479         gCurrentThread->Remaining = gCurrentThread->Quantum;
480         
481         // Get machine state
482         __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
483         __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
484         eip = GetEIP();
485         if(eip == SWITCH_MAGIC) return; // Check if a switch happened
486         
487         // Save machine state
488         gCurrentThread->SavedState.ESP = esp;
489         gCurrentThread->SavedState.EBP = ebp;
490         gCurrentThread->SavedState.EIP = eip;
491         
492         // Get next thread
493         thread = Threads_GetNextToRun(CPU);
494         
495         // Error Check
496         if(thread == NULL) {
497                 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
498                 return;
499         }
500         
501         // Set current thread
502         gCurrentThread = thread;
503         
504         // Update Kernel Stack pointer
505         gTSSs[CPU].ESP0 = thread->KernelStack;
506         
507         // Set address space
508         __asm__ __volatile__ ("mov %0, %%cr3"::"a"(gCurrentThread->MemState.CR3));
509         // Switch threads
510         __asm__ __volatile__ (
511                 "mov %1, %%esp\n\t"
512                 "mov %2, %%ebp\n\t"
513                 "jmp *%3" : :
514                 "a"(SWITCH_MAGIC), "b"(gCurrentThread->SavedState.ESP),
515                 "d"(gCurrentThread->SavedState.EBP), "c"(gCurrentThread->SavedState.EIP));
516         for(;;);        // Shouldn't reach here
517 }

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