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)
239 tThread *cur = Proc_GetCurThread();
242 __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
243 __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
245 // Create new thread structure
246 newThread = malloc( sizeof(tThread) );
248 Warning("Proc_Clone - Out of memory when creating thread\n");
253 // Base new thread on current
254 memcpy(newThread, cur, sizeof(tThread));
256 // Initialise Memory Space (New Addr space or kernel stack)
257 if(Flags & CLONE_VM) {
258 newThread->TGID = newThread->TID;
259 newThread->MemState.CR3 = MM_Clone();
261 Uint tmpEbp, oldEsp = esp;
264 newThread->KernelStack = MM_NewKStack();
266 if(newThread->KernelStack == 0) {
271 // Get ESP as a used size
272 esp = cur->KernelStack - esp;
274 memcpy( (void*)(newThread->KernelStack - esp), (void*)(cur->KernelStack - esp), esp );
275 // Get ESP as an offset in the new stack
276 esp = newThread->KernelStack - esp;
278 ebp = newThread->KernelStack - (cur->KernelStack - ebp);
280 // Repair EBPs & Stack Addresses
281 // Catches arguments also, but may trash stack-address-like values
282 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
284 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < cur->KernelStack)
285 *(Uint*)tmpEbp += newThread->KernelStack - cur->KernelStack;
289 // Set Pointer, Spinlock and TID
290 newThread->Next = NULL;
291 newThread->IsLocked = 0;
292 newThread->TID = giNextTID++;
293 newThread->PTID = cur->TID;
295 // Create copy of name
296 newThread->ThreadName = malloc(strlen(cur->ThreadName)+1);
297 strcpy(newThread->ThreadName, cur->ThreadName);
299 // Clear message list (messages are not inherited)
300 newThread->Messages = NULL;
301 newThread->LastMessage = NULL;
303 // Set remaining (sheduler expects remaining to be correct)
304 newThread->Remaining = newThread->Quantum;
306 // Save core machine state
307 newThread->SavedState.ESP = esp;
308 newThread->SavedState.EBP = ebp;
310 if(eip == SWITCH_MAGIC) {
311 outb(0x20, 0x20); // ACK Timer and return as child
316 newThread->SavedState.EIP = eip;
318 // Lock list and add to active
319 Threads_AddActive(newThread);
323 return newThread->TID;
327 * \fn Uint Proc_MakeUserStack()
328 * \brief Creates a new user stack
330 Uint Proc_MakeUserStack()
333 Uint base = USER_STACK_TOP - USER_STACK_SZ;
335 // Check Prospective Space
336 for( i = USER_STACK_SZ >> 12; i--; )
337 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
340 if(i != -1) return 0;
342 // Allocate Stack - Allocate incrementally to clean up MM_Dump output
343 for( i = 0; i < USER_STACK_SZ/4069; i++ )
344 MM_Allocate( base + (i<<12) );
346 return base + USER_STACK_SZ;
351 * \fn void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, char **EnvP, int DataSize)
352 * \brief Starts a user task
354 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
356 Uint *stack = (void*)Proc_MakeUserStack();
361 LOG("stack = 0x%x", stack);
364 stack = (void*)( (Uint)stack - DataSize );
365 memcpy( stack, ArgV, DataSize );
367 // Adjust Arguments and environment
368 delta = (Uint)stack - (Uint)ArgV;
369 ArgV = (char**)stack;
370 for( i = 0; ArgV[i]; i++ ) ArgV[i] += delta;
373 for( i = 0; EnvP[i]; i++ ) EnvP[i] += delta;
375 // User Mode Segments
376 ss = 0x23; cs = 0x1B;
379 *--stack = (Uint)EnvP;
380 *--stack = (Uint)ArgV;
381 *--stack = (Uint)ArgC;
384 *--stack = 0; // Return Address
385 delta = (Uint)stack; // Reuse delta to save SP
387 *--stack = ss; //Stack Segment
388 *--stack = delta; //Stack Pointer
389 *--stack = 0x0202; //EFLAGS (Resvd (0x2) and IF (0x20))
390 *--stack = cs; //Code Segment
391 *--stack = Entrypoint; //EIP
393 *--stack = 0xAAAAAAAA; // eax
394 *--stack = 0xCCCCCCCC; // ecx
395 *--stack = 0xDDDDDDDD; // edx
396 *--stack = 0xBBBBBBBB; // ebx
397 *--stack = 0xD1D1D1D1; // edi
398 *--stack = 0x54545454; // esp - NOT POPED
399 *--stack = 0x51515151; // esi
400 *--stack = 0xB4B4B4B4; // ebp
407 __asm__ __volatile__ (
408 "mov %%eax,%%esp;\n\t" // Set stack pointer
414 "iret;\n\t" : : "a" (stack));
419 * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
420 * \brief Demotes a process to a lower permission level
421 * \param Err Pointer to user's errno
423 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
425 int cpl = Regs->cs & 3;
427 if(Dest > 3 || Dest < 0) {
438 // Change the Segment Registers
439 Regs->cs = (((Dest+1)<<4) | Dest) - 8;
440 Regs->ss = ((Dest+1)<<4) | Dest;
441 // Check if the GP Segs are GDT, then change them
442 if(!(Regs->ds & 4)) Regs->ds = ((Dest+1)<<4) | Dest;
443 if(!(Regs->es & 4)) Regs->es = ((Dest+1)<<4) | Dest;
444 if(!(Regs->fs & 4)) Regs->fs = ((Dest+1)<<4) | Dest;
445 if(!(Regs->gs & 4)) Regs->gs = ((Dest+1)<<4) | Dest;
451 * \fn void Proc_Scheduler(int CPU)
452 * \brief Swap current thread and clears dead threads
454 void Proc_Scheduler(int CPU)
459 // If the spinlock is set, let it complete
460 if(giThreadListLock) return;
462 // Clear Delete Queue
463 while(gDeleteThreads)
465 thread = gDeleteThreads->Next;
466 if(gDeleteThreads->IsLocked) { // Only free if structure is unused
467 gDeleteThreads->Status = THREAD_STAT_NULL;
468 free( gDeleteThreads );
470 gDeleteThreads = thread;
473 // Check if there is any tasks running
474 if(giNumActiveThreads == 0) {
475 Log("No Active threads, sleeping");
476 __asm__ __volatile__ ("hlt");
480 // Reduce remaining quantum and continue timeslice if non-zero
481 if(gCurrentThread->Remaining--) return;
482 // Reset quantum for next call
483 gCurrentThread->Remaining = gCurrentThread->Quantum;
486 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
487 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
489 if(eip == SWITCH_MAGIC) return; // Check if a switch happened
491 // Save machine state
492 gCurrentThread->SavedState.ESP = esp;
493 gCurrentThread->SavedState.EBP = ebp;
494 gCurrentThread->SavedState.EIP = eip;
497 thread = Threads_GetNextToRun(CPU);
501 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
505 #if DEBUG_TRACE_SWITCH
506 Log("Switching to task %i, CR3 = 0x%x, EIP = %p",
508 thread->MemState.CR3,
509 thread->SavedState.EIP
513 // Set current thread
514 gCurrentThread = thread;
516 // Update Kernel Stack pointer
517 gTSSs[CPU].ESP0 = thread->KernelStack;
520 __asm__ __volatile__ ("mov %0, %%cr3"::"a"(gCurrentThread->MemState.CR3));
522 __asm__ __volatile__ (
526 "a"(SWITCH_MAGIC), "b"(gCurrentThread->SavedState.ESP),
527 "d"(gCurrentThread->SavedState.EBP), "c"(gCurrentThread->SavedState.EIP));
528 for(;;); // Shouldn't reach here