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

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