2 * AcessOS Microkernel Version
14 #define SWITCH_MAGIC 0xFFFACE55 // There is no code in this area
15 #define TIMER_DIVISOR 11931 //~100Hz
19 extern Uint GetEIP(); // start.asm
20 extern Uint32 gaInitPageDir[1024]; // start.asm
21 extern void Kernel_Stack_Top;
22 extern volatile int giThreadListLock;
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 extern void Threads_Dump();
35 void ArchThreads_Init();
36 tThread *Proc_GetCurThread();
37 void Proc_ChangeStack();
38 int Proc_Clone(Uint *Err, Uint Flags);
39 void Proc_Scheduler();
42 // --- Current State ---
44 tThread *gCurrentThread[MAX_CPUS] = {NULL};
46 tThread *gCurrentThread = NULL;
48 // --- Multiprocessing ---
50 tMPInfo *gMPTable = NULL;
53 Uint32 *gPML4s[4] = NULL;
62 * \fn void ArchThreads_Init()
63 * \brief Starts the process scheduler
65 void ArchThreads_Init()
69 // -- Initialise Multiprocessing
70 // Find MP Floating Table
72 for(pos = KERNEL_BASE|0x9FC00; pos < (KERNEL_BASE|0xA0000); pos += 16) {
73 if( *(Uint*)(pos) == MPTABLE_IDENT ) {
74 if(ByteSum( (void*)pos, sizeof(tMPInfo) ) != 0) continue;
75 gMPTable = (void*)pos;
85 for(pos = KERNEL_BASE|0xF0000; pos < (KERNEL_BASE|0x100000); pos += 16) {
86 if( *(Uint*)(pos) == MPTABLE_IDENT ) {
87 if(ByteSum( (void*)pos, sizeof(tMPInfo) ) != 0) continue;
88 gMPTable = (void*)pos;
94 // If the MP Table Exists, parse it
97 Panic("Uh oh... MP Table Parsing is unimplemented\n");
106 for(pos=0;pos<giNumCPUs;pos++)
111 gTSSs[pos].SS0 = 0x10;
112 gTSSs[pos].ESP0 = 0; // Set properly by scheduler
113 gGDT[5+pos].LimitLow = sizeof(tTSS);
114 gGDT[5+pos].LimitHi = 0;
115 gGDT[5+pos].Access = 0x89; // Type
116 gGDT[5+pos].Flags = 0x4;
117 gGDT[5+pos].BaseLow = (Uint)&gTSSs[pos] & 0xFFFF;
118 gGDT[5+pos].BaseMid = (Uint)&gTSSs[pos] >> 16;
119 gGDT[5+pos].BaseHi = (Uint)&gTSSs[pos] >> 24;
122 for(pos=0;pos<giNumCPUs;pos++) {
124 __asm__ __volatile__ ("ltr %%ax"::"a"(0x28+pos*8));
130 gCurrentThread[0] = &gThreadZero;
132 gCurrentThread = &gThreadZero;
136 gThreadZero.MemState.PDP[0] = 0;
137 gThreadZero.MemState.PDP[1] = 0;
138 gThreadZero.MemState.PDP[2] = 0;
140 gThreadZero.MemState.CR3 = (Uint)gaInitPageDir - KERNEL_BASE;
143 // Set timer frequency
144 outb(0x43, 0x34); // Set Channel 0, Low/High, Rate Generator
145 outb(0x40, TIMER_DIVISOR&0xFF); // Low Byte of Divisor
146 outb(0x40, (TIMER_DIVISOR>>8)&0xFF); // High Byte
148 // Create Per-Process Data Block
149 MM_Allocate(MM_PPD_CFG);
156 * \fn void Proc_Start()
157 * \brief Start process scheduler
161 // Start Interrupts (and hence scheduler)
162 __asm__ __volatile__("sti");
166 * \fn tThread *Proc_GetCurThread()
167 * \brief Gets the current thread
169 tThread *Proc_GetCurThread()
174 return gCurrentThread;
179 * \fn void Proc_ChangeStack()
180 * \brief Swaps the current stack for a new one (in the proper stack reigon)
182 void Proc_ChangeStack()
186 Uint curBase, newBase;
188 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
189 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
194 newBase = MM_NewKStack();
197 Panic("What the?? Unable to allocate space for initial kernel stack");
201 curBase = (Uint)&Kernel_Stack_Top;
203 LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
205 // Get ESP as a used size
207 LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
209 memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
210 // Get ESP as an offset in the new stack
213 ebp = newBase - (curBase - ebp);
215 // Repair EBPs & Stack Addresses
216 // Catches arguments also, but may trash stack-address-like values
217 for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
219 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
220 *(Uint*)tmpEbp += newBase - curBase;
223 gCurrentThread->KernelStack = newBase;
225 __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
226 __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
230 * \fn int Proc_Clone(Uint *Err, Uint Flags)
231 * \brief Clone the current process
233 int Proc_Clone(Uint *Err, Uint Flags)
238 __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
239 __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
241 // Create new thread structure
242 newThread = malloc( sizeof(tThread) );
244 Warning("Proc_Clone - Out of memory when creating thread\n");
248 // Base new thread on old
249 memcpy(newThread, gCurrentThread, sizeof(tThread));
250 // Initialise Memory Space (New Addr space or kernel stack)
251 if(Flags & CLONE_VM) {
252 newThread->TGID = newThread->TID;
253 newThread->MemState.CR3 = MM_Clone();
255 Uint tmpEbp, oldEsp = esp;
258 newThread->KernelStack = MM_NewKStack();
260 if(newThread->KernelStack == 0) {
265 // Get ESP as a used size
266 esp = gCurrentThread->KernelStack - esp;
268 memcpy( (void*)(newThread->KernelStack - esp), (void*)(gCurrentThread->KernelStack - esp), esp );
269 // Get ESP as an offset in the new stack
270 esp = newThread->KernelStack - esp;
272 ebp = newThread->KernelStack - (gCurrentThread->KernelStack - ebp);
274 // Repair EBPs & Stack Addresses
275 // Catches arguments also, but may trash stack-address-like values
276 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
278 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < gCurrentThread->KernelStack)
279 *(Uint*)tmpEbp += newThread->KernelStack - gCurrentThread->KernelStack;
283 // Set Pointer, Spinlock and TID
284 newThread->Next = NULL;
285 newThread->IsLocked = 0;
286 newThread->TID = giNextTID++;
287 newThread->PTID = gCurrentThread->TID;
289 // Clear message list (messages are not inherited)
290 newThread->Messages = NULL;
291 newThread->LastMessage = NULL;
293 // Set remaining (sheduler expects remaining to be correct)
294 newThread->Remaining = newThread->Quantum;
296 // Save core machine state
297 newThread->SavedState.ESP = esp;
298 newThread->SavedState.EBP = ebp;
300 if(eip == SWITCH_MAGIC) {
301 outb(0x20, 0x20); // ACK Timer and return as child
306 newThread->SavedState.EIP = eip;
308 // Lock list and add to active
309 LOCK( &giThreadListLock );
310 newThread->Next = gActiveThreads;
311 gActiveThreads = newThread;
312 giNumActiveThreads ++;
313 giTotalTickets += newThread->NumTickets;
314 RELEASE( &giThreadListLock );
318 return newThread->TID;
322 * \fn Uint Proc_MakeUserStack()
323 * \brief Creates a new user stack
325 Uint Proc_MakeUserStack()
328 Uint base = USER_STACK_TOP - USER_STACK_SZ;
330 // Check Prospective Space
331 for( i = USER_STACK_SZ >> 12; i--; )
332 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
335 if(i != -1) return 0;
337 // Allocate Stack - Allocate incrementally to clean up MM_Dump output
338 for( i = 0; i < USER_STACK_SZ/4069; i++ )
339 MM_Allocate( base + (i<<12) );
341 return base + USER_STACK_SZ;
346 * \fn void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, char **EnvP, int DataSize)
347 * \brief Starts a user task
349 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
351 Uint *stack = (void*)Proc_MakeUserStack();
356 LOG("stack = 0x%x", stack);
359 stack = (void*)( (Uint)stack - DataSize );
360 memcpy( stack, ArgV, DataSize );
362 // Adjust Arguments and environment
363 delta = (Uint)stack - (Uint)ArgV;
364 ArgV = (char**)stack;
365 for( i = 0; ArgV[i]; i++ ) ArgV[i] += delta;
368 for( i = 0; EnvP[i]; i++ ) EnvP[i] += delta;
370 // User Mode Segments
371 ss = 0x23; cs = 0x1B;
374 *--stack = (Uint)EnvP;
375 *--stack = (Uint)ArgV;
376 *--stack = (Uint)ArgC;
379 *--stack = 0; // Return Address
380 delta = (Uint)stack; // Reuse delta to save SP
382 *--stack = ss; //Stack Segment
383 *--stack = delta; //Stack Pointer
384 *--stack = 0x0202; //EFLAGS (Resvd (0x2) and IF (0x20))
385 *--stack = cs; //Code Segment
386 *--stack = Entrypoint; //EIP
388 *--stack = 0xAAAAAAAA; // eax
389 *--stack = 0xCCCCCCCC; // ecx
390 *--stack = 0xDDDDDDDD; // edx
391 *--stack = 0xBBBBBBBB; // ebx
392 *--stack = 0xD1D1D1D1; // edi
393 *--stack = 0x54545454; // esp - NOT POPED
394 *--stack = 0x51515151; // esi
395 *--stack = 0xB4B4B4B4; // ebp
402 __asm__ __volatile__ (
403 "mov %%eax,%%esp;\n\t" // Set stack pointer
409 "iret;\n\t" : : "a" (stack));
414 * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
415 * \brief Demotes a process to a lower permission level
416 * \param Err Pointer to user's errno
418 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
420 int cpl = Regs->cs & 3;
422 if(Dest > 3 || Dest < 0) {
433 // Change the Segment Registers
434 Regs->cs = (((Dest+1)<<4) | Dest) - 8;
435 Regs->ss = ((Dest+1)<<4) | Dest;
436 // Check if the GP Segs are GDT, then change them
437 if(!(Regs->ds & 4)) Regs->ds = ((Dest+1)<<4) | Dest;
438 if(!(Regs->es & 4)) Regs->es = ((Dest+1)<<4) | Dest;
439 if(!(Regs->fs & 4)) Regs->fs = ((Dest+1)<<4) | Dest;
440 if(!(Regs->gs & 4)) Regs->gs = ((Dest+1)<<4) | Dest;
446 * \fn void Proc_Scheduler(int CPU)
447 * \brief Swap current thread and clears dead threads
449 void Proc_Scheduler(int CPU)
454 // If the spinlock is set, let it complete
455 if(giThreadListLock) return;
457 // Clear Delete Queue
458 while(gDeleteThreads)
460 thread = gDeleteThreads->Next;
461 if(gDeleteThreads->IsLocked) { // Only free if structure is unused
462 gDeleteThreads->Status = THREAD_STAT_NULL;
463 free( gDeleteThreads );
465 gDeleteThreads = thread;
468 // Check if there is any tasks running
469 if(giNumActiveThreads == 0) {
470 Log("No Active threads, sleeping");
471 __asm__ __volatile__ ("hlt");
475 // Reduce remaining quantum and continue timeslice if non-zero
476 if(gCurrentThread->Remaining--) return;
477 // Reset quantum for next call
478 gCurrentThread->Remaining = gCurrentThread->Quantum;
481 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
482 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
484 if(eip == SWITCH_MAGIC) return; // Check if a switch happened
486 // Save machine state
487 gCurrentThread->SavedState.ESP = esp;
488 gCurrentThread->SavedState.EBP = ebp;
489 gCurrentThread->SavedState.EIP = eip;
492 thread = Threads_GetNextToRun(CPU);
496 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
500 // Set current thread
501 gCurrentThread = thread;
503 // Update Kernel Stack pointer
504 gTSSs[CPU].ESP0 = thread->KernelStack;
507 __asm__ __volatile__ ("mov %0, %%cr3"::"a"(gCurrentThread->MemState.CR3));
509 __asm__ __volatile__ (
513 "a"(SWITCH_MAGIC), "b"(gCurrentThread->SavedState.ESP),
514 "d"(gCurrentThread->SavedState.EBP), "c"(gCurrentThread->SavedState.EIP));
515 for(;;); // Shouldn't reach here