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

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