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

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