2 * AcessOS Microkernel Version
14 #define DEBUG_TRACE_SWITCH 0
17 #define SWITCH_MAGIC 0xFFFACE55 // There is no code in this area
18 #define TIMER_DIVISOR 11931 //~100Hz
22 extern Uint GetEIP(); // start.asm
23 extern Uint32 gaInitPageDir[1024]; // start.asm
24 extern void Kernel_Stack_Top;
25 extern volatile int giThreadListLock;
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();
38 void ArchThreads_Init();
39 tThread *Proc_GetCurThread();
40 void Proc_ChangeStack();
41 int Proc_Clone(Uint *Err, Uint Flags);
42 void Proc_Scheduler();
45 // --- Current State ---
47 tThread *gCurrentThread[MAX_CPUS] = {NULL};
49 tThread *gCurrentThread = NULL;
51 // --- Multiprocessing ---
53 tMPInfo *gMPTable = NULL;
56 Uint32 *gPML4s[4] = NULL;
65 * \fn void ArchThreads_Init()
66 * \brief Starts the process scheduler
68 void ArchThreads_Init()
72 // -- Initialise Multiprocessing
73 // Find MP Floating Table
75 for(pos = KERNEL_BASE|0x9FC00; pos < (KERNEL_BASE|0xA0000); pos += 16) {
76 if( *(Uint*)(pos) == MPTABLE_IDENT ) {
77 if(ByteSum( (void*)pos, sizeof(tMPInfo) ) != 0) continue;
78 gMPTable = (void*)pos;
88 for(pos = KERNEL_BASE|0xF0000; pos < (KERNEL_BASE|0x100000); pos += 16) {
89 if( *(Uint*)(pos) == MPTABLE_IDENT ) {
90 if(ByteSum( (void*)pos, sizeof(tMPInfo) ) != 0) continue;
91 gMPTable = (void*)pos;
97 // If the MP Table Exists, parse it
100 Panic("Uh oh... MP Table Parsing is unimplemented\n");
109 for(pos=0;pos<giNumCPUs;pos++)
114 gTSSs[pos].SS0 = 0x10;
115 gTSSs[pos].ESP0 = 0; // Set properly by scheduler
116 gGDT[5+pos].LimitLow = sizeof(tTSS);
117 gGDT[5+pos].LimitHi = 0;
118 gGDT[5+pos].Access = 0x89; // Type
119 gGDT[5+pos].Flags = 0x4;
120 gGDT[5+pos].BaseLow = (Uint)&gTSSs[pos] & 0xFFFF;
121 gGDT[5+pos].BaseMid = (Uint)&gTSSs[pos] >> 16;
122 gGDT[5+pos].BaseHi = (Uint)&gTSSs[pos] >> 24;
125 for(pos=0;pos<giNumCPUs;pos++) {
127 __asm__ __volatile__ ("ltr %%ax"::"a"(0x28+pos*8));
133 gCurrentThread[0] = &gThreadZero;
135 gCurrentThread = &gThreadZero;
139 gThreadZero.MemState.PDP[0] = 0;
140 gThreadZero.MemState.PDP[1] = 0;
141 gThreadZero.MemState.PDP[2] = 0;
143 gThreadZero.MemState.CR3 = (Uint)gaInitPageDir - KERNEL_BASE;
146 // Set timer frequency
147 outb(0x43, 0x34); // Set Channel 0, Low/High, Rate Generator
148 outb(0x40, TIMER_DIVISOR&0xFF); // Low Byte of Divisor
149 outb(0x40, (TIMER_DIVISOR>>8)&0xFF); // High Byte
151 // Create Per-Process Data Block
152 MM_Allocate(MM_PPD_CFG);
159 * \fn void Proc_Start()
160 * \brief Start process scheduler
164 // Start Interrupts (and hence scheduler)
165 __asm__ __volatile__("sti");
169 * \fn tThread *Proc_GetCurThread()
170 * \brief Gets the current thread
172 tThread *Proc_GetCurThread()
177 return gCurrentThread;
182 * \fn void Proc_ChangeStack()
183 * \brief Swaps the current stack for a new one (in the proper stack reigon)
185 void Proc_ChangeStack()
189 Uint curBase, newBase;
191 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
192 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
197 newBase = MM_NewKStack();
200 Panic("What the?? Unable to allocate space for initial kernel stack");
204 curBase = (Uint)&Kernel_Stack_Top;
206 LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
208 // Get ESP as a used size
210 LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
212 memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
213 // Get ESP as an offset in the new stack
216 ebp = newBase - (curBase - ebp);
218 // Repair EBPs & Stack Addresses
219 // Catches arguments also, but may trash stack-address-like values
220 for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
222 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
223 *(Uint*)tmpEbp += newBase - curBase;
226 gCurrentThread->KernelStack = newBase;
228 __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
229 __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
233 * \fn int Proc_Clone(Uint *Err, Uint Flags)
234 * \brief Clone the current process
236 int Proc_Clone(Uint *Err, Uint Flags)
241 __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
242 __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
244 // Create new thread structure
245 newThread = malloc( sizeof(tThread) );
247 Warning("Proc_Clone - Out of memory when creating thread\n");
251 // Base new thread on old
252 memcpy(newThread, gCurrentThread, sizeof(tThread));
253 // Initialise Memory Space (New Addr space or kernel stack)
254 if(Flags & CLONE_VM) {
255 newThread->TGID = newThread->TID;
256 newThread->MemState.CR3 = MM_Clone();
258 Uint tmpEbp, oldEsp = esp;
261 newThread->KernelStack = MM_NewKStack();
263 if(newThread->KernelStack == 0) {
268 // Get ESP as a used size
269 esp = gCurrentThread->KernelStack - esp;
271 memcpy( (void*)(newThread->KernelStack - esp), (void*)(gCurrentThread->KernelStack - esp), esp );
272 // Get ESP as an offset in the new stack
273 esp = newThread->KernelStack - esp;
275 ebp = newThread->KernelStack - (gCurrentThread->KernelStack - ebp);
277 // Repair EBPs & Stack Addresses
278 // Catches arguments also, but may trash stack-address-like values
279 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
281 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < gCurrentThread->KernelStack)
282 *(Uint*)tmpEbp += newThread->KernelStack - gCurrentThread->KernelStack;
286 // Set Pointer, Spinlock and TID
287 newThread->Next = NULL;
288 newThread->IsLocked = 0;
289 newThread->TID = giNextTID++;
290 newThread->PTID = gCurrentThread->TID;
292 // Clear message list (messages are not inherited)
293 newThread->Messages = NULL;
294 newThread->LastMessage = NULL;
296 // Set remaining (sheduler expects remaining to be correct)
297 newThread->Remaining = newThread->Quantum;
299 // Save core machine state
300 newThread->SavedState.ESP = esp;
301 newThread->SavedState.EBP = ebp;
303 if(eip == SWITCH_MAGIC) {
304 outb(0x20, 0x20); // ACK Timer and return as child
309 newThread->SavedState.EIP = eip;
311 // Lock list and add to active
312 Threads_AddActive(newThread);
316 return newThread->TID;
320 * \fn Uint Proc_MakeUserStack()
321 * \brief Creates a new user stack
323 Uint Proc_MakeUserStack()
326 Uint base = USER_STACK_TOP - USER_STACK_SZ;
328 // Check Prospective Space
329 for( i = USER_STACK_SZ >> 12; i--; )
330 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
333 if(i != -1) return 0;
335 // Allocate Stack - Allocate incrementally to clean up MM_Dump output
336 for( i = 0; i < USER_STACK_SZ/4069; i++ )
337 MM_Allocate( base + (i<<12) );
339 return base + USER_STACK_SZ;
344 * \fn void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, char **EnvP, int DataSize)
345 * \brief Starts a user task
347 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
349 Uint *stack = (void*)Proc_MakeUserStack();
354 LOG("stack = 0x%x", stack);
357 stack = (void*)( (Uint)stack - DataSize );
358 memcpy( stack, ArgV, DataSize );
360 // Adjust Arguments and environment
361 delta = (Uint)stack - (Uint)ArgV;
362 ArgV = (char**)stack;
363 for( i = 0; ArgV[i]; i++ ) ArgV[i] += delta;
366 for( i = 0; EnvP[i]; i++ ) EnvP[i] += delta;
368 // User Mode Segments
369 ss = 0x23; cs = 0x1B;
372 *--stack = (Uint)EnvP;
373 *--stack = (Uint)ArgV;
374 *--stack = (Uint)ArgC;
377 *--stack = 0; // Return Address
378 delta = (Uint)stack; // Reuse delta to save SP
380 *--stack = ss; //Stack Segment
381 *--stack = delta; //Stack Pointer
382 *--stack = 0x0202; //EFLAGS (Resvd (0x2) and IF (0x20))
383 *--stack = cs; //Code Segment
384 *--stack = Entrypoint; //EIP
386 *--stack = 0xAAAAAAAA; // eax
387 *--stack = 0xCCCCCCCC; // ecx
388 *--stack = 0xDDDDDDDD; // edx
389 *--stack = 0xBBBBBBBB; // ebx
390 *--stack = 0xD1D1D1D1; // edi
391 *--stack = 0x54545454; // esp - NOT POPED
392 *--stack = 0x51515151; // esi
393 *--stack = 0xB4B4B4B4; // ebp
400 __asm__ __volatile__ (
401 "mov %%eax,%%esp;\n\t" // Set stack pointer
407 "iret;\n\t" : : "a" (stack));
412 * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
413 * \brief Demotes a process to a lower permission level
414 * \param Err Pointer to user's errno
416 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
418 int cpl = Regs->cs & 3;
420 if(Dest > 3 || Dest < 0) {
431 // Change the Segment Registers
432 Regs->cs = (((Dest+1)<<4) | Dest) - 8;
433 Regs->ss = ((Dest+1)<<4) | Dest;
434 // Check if the GP Segs are GDT, then change them
435 if(!(Regs->ds & 4)) Regs->ds = ((Dest+1)<<4) | Dest;
436 if(!(Regs->es & 4)) Regs->es = ((Dest+1)<<4) | Dest;
437 if(!(Regs->fs & 4)) Regs->fs = ((Dest+1)<<4) | Dest;
438 if(!(Regs->gs & 4)) Regs->gs = ((Dest+1)<<4) | Dest;
444 * \fn void Proc_Scheduler(int CPU)
445 * \brief Swap current thread and clears dead threads
447 void Proc_Scheduler(int CPU)
452 // If the spinlock is set, let it complete
453 if(giThreadListLock) return;
455 // Clear Delete Queue
456 while(gDeleteThreads)
458 thread = gDeleteThreads->Next;
459 if(gDeleteThreads->IsLocked) { // Only free if structure is unused
460 gDeleteThreads->Status = THREAD_STAT_NULL;
461 free( gDeleteThreads );
463 gDeleteThreads = thread;
466 // Check if there is any tasks running
467 if(giNumActiveThreads == 0) {
468 Log("No Active threads, sleeping");
469 __asm__ __volatile__ ("hlt");
473 // Reduce remaining quantum and continue timeslice if non-zero
474 if(gCurrentThread->Remaining--) return;
475 // Reset quantum for next call
476 gCurrentThread->Remaining = gCurrentThread->Quantum;
479 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
480 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
482 if(eip == SWITCH_MAGIC) return; // Check if a switch happened
484 // Save machine state
485 gCurrentThread->SavedState.ESP = esp;
486 gCurrentThread->SavedState.EBP = ebp;
487 gCurrentThread->SavedState.EIP = eip;
490 thread = Threads_GetNextToRun(CPU);
494 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
498 #if DEBUG_TRACE_SWITCH
499 Log("Switching to task %i, CR3 = 0x%x, EIP = %p",
501 thread->MemState.CR3,
502 thread->SavedState.EIP
506 // Set current thread
507 gCurrentThread = thread;
509 // Update Kernel Stack pointer
510 gTSSs[CPU].ESP0 = thread->KernelStack;
513 __asm__ __volatile__ ("mov %0, %%cr3"::"a"(gCurrentThread->MemState.CR3));
515 __asm__ __volatile__ (
519 "a"(SWITCH_MAGIC), "b"(gCurrentThread->SavedState.ESP),
520 "d"(gCurrentThread->SavedState.EBP), "c"(gCurrentThread->SavedState.EIP));
521 for(;;); // Shouldn't reach here