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);
34 void ArchThreads_Init();
35 tThread *Proc_GetCurThread();
36 void Proc_ChangeStack();
37 int Proc_Clone(Uint *Err, Uint Flags);
38 void Proc_Scheduler();
41 // --- Current State ---
43 tThread *gCurrentThread[MAX_CPUS] = NULL;
45 tThread *gCurrentThread = NULL;
47 // --- Multiprocessing ---
49 tMPInfo *gMPTable = NULL;
52 Uint32 *gPML4s[4] = NULL;
61 * \fn void ArchThreads_Init()
62 * \brief Starts the process scheduler
64 void ArchThreads_Init()
68 // -- Initialise Multiprocessing
69 // Find MP Floating Table
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;
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;
93 // If the MP Table Exists, parse it
96 Panic("Uh oh... MP Table Parsing is unimplemented\n");
105 for(pos=0;pos<giNumCPUs;pos++)
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;
121 for(pos=0;pos<giNumCPUs;pos++) {
123 __asm__ __volatile__ ("ltr %%ax"::"a"(0x28+pos*8));
129 gCurrentThread[0] = &gThreadZero;
131 gCurrentThread = &gThreadZero;
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
139 // Create Per-Process Data Block
140 MM_Allocate(MM_PPD_CFG);
145 // Start Interrupts (and hence scheduler)
146 __asm__ __volatile__("sti");
150 * \fn tThread *Proc_GetCurThread()
151 * \brief Gets the current thread
153 tThread *Proc_GetCurThread()
158 return gCurrentThread;
163 * \fn void Proc_ChangeStack()
164 * \brief Swaps the current stack for a new one (in the proper stack reigon)
166 void Proc_ChangeStack()
170 Uint curBase, newBase;
172 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
173 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
178 newBase = MM_NewKStack();
181 Panic("What the?? Unable to allocate space for initial kernel stack");
185 curBase = (Uint)&Kernel_Stack_Top;
187 LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
189 // Get ESP as a used size
191 LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
193 memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
194 // Get ESP as an offset in the new stack
197 ebp = newBase - (curBase - ebp);
199 // Repair EBPs & Stack Addresses
200 // Catches arguments also, but may trash stack-address-like values
201 for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
203 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
204 *(Uint*)tmpEbp += newBase - curBase;
207 gCurrentThread->KernelStack = newBase;
209 __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
210 __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
214 * \fn int Proc_Clone(Uint *Err, Uint Flags)
215 * \brief Clone the current process
217 int Proc_Clone(Uint *Err, Uint Flags)
222 __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
223 __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
225 // Create new thread structure
226 newThread = malloc( sizeof(tThread) );
228 Warning("Proc_Clone - Out of memory when creating thread\n");
232 // Base new thread on old
233 memcpy(newThread, gCurrentThread, sizeof(tThread));
234 // Initialise Memory Space (New Addr space or kernel stack)
235 if(Flags & CLONE_VM) {
236 newThread->TGID = newThread->TID;
237 newThread->MemState.CR3 = MM_Clone();
239 Uint tmpEbp, oldEsp = esp;
242 newThread->KernelStack = MM_NewKStack();
244 if(newThread->KernelStack == 0) {
249 // Get ESP as a used size
250 esp = gCurrentThread->KernelStack - esp;
252 memcpy( (void*)(newThread->KernelStack - esp), (void*)(gCurrentThread->KernelStack - esp), esp );
253 // Get ESP as an offset in the new stack
254 esp = newThread->KernelStack - esp;
256 ebp = newThread->KernelStack - (gCurrentThread->KernelStack - ebp);
258 // Repair EBPs & Stack Addresses
259 // Catches arguments also, but may trash stack-address-like values
260 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
262 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < gCurrentThread->KernelStack)
263 *(Uint*)tmpEbp += newThread->KernelStack - gCurrentThread->KernelStack;
267 // Set Pointer, Spinlock and TID
268 newThread->Next = NULL;
269 newThread->IsLocked = 0;
270 newThread->TID = giNextTID++;
271 newThread->PTID = gCurrentThread->TID;
273 // Clear message list (messages are not inherited)
274 newThread->Messages = NULL;
275 newThread->LastMessage = NULL;
277 // Set remaining (sheduler expects remaining to be correct)
278 newThread->Remaining = newThread->Quantum;
280 // Save core machine state
281 newThread->SavedState.ESP = esp;
282 newThread->SavedState.EBP = ebp;
284 if(eip == SWITCH_MAGIC) {
285 outb(0x20, 0x20); // ACK Timer and return as child
290 newThread->SavedState.EIP = eip;
292 // Lock list and add to active
293 LOCK( &giThreadListLock );
294 newThread->Next = gActiveThreads;
295 gActiveThreads = newThread;
296 giNumActiveThreads ++;
297 giTotalTickets += newThread->NumTickets;
298 RELEASE( &giThreadListLock );
300 return newThread->TID;
304 * \fn Uint Proc_MakeUserStack()
305 * \brief Creates a new user stack
307 Uint Proc_MakeUserStack()
310 Uint base = USER_STACK_TOP - USER_STACK_SZ;
312 // Check Prospective Space
313 for( i = USER_STACK_SZ >> 12; i--; )
314 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
317 if(i != -1) return 0;
319 // Allocate Stack - Allocate incrementally to clean up MM_Dump output
320 for( i = 0; i < USER_STACK_SZ/4069; i++ )
321 MM_Allocate( base + (i<<12) );
323 return base + USER_STACK_SZ;
328 * \fn void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, char **EnvP, int DataSize)
329 * \brief Starts a user task
331 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
333 Uint *stack = (void*)Proc_MakeUserStack();
338 LOG("stack = 0x%x", stack);
341 stack = (void*)( (Uint)stack - DataSize );
342 memcpy( stack, ArgV, DataSize );
344 // Adjust Arguments and environment
345 delta = (Uint)stack - (Uint)ArgV;
346 ArgV = (char**)stack;
347 for( i = 0; ArgV[i]; i++ ) ArgV[i] += delta;
350 for( i = 0; EnvP[i]; i++ ) EnvP[i] += delta;
352 // User Mode Segments
353 ss = 0x23; cs = 0x1B;
356 *--stack = (Uint)EnvP;
357 *--stack = (Uint)ArgV;
358 *--stack = (Uint)ArgC;
361 *--stack = 0; // Return Address
362 delta = (Uint)stack; // Reuse delta to save SP
364 *--stack = ss; //Stack Segment
365 *--stack = delta; //Stack Pointer
366 *--stack = 0x0202; //EFLAGS (Resvd (0x2) and IF (0x20))
367 *--stack = cs; //Code Segment
368 *--stack = Entrypoint; //EIP
370 *--stack = 0xAAAAAAAA; // eax
371 *--stack = 0xCCCCCCCC; // ecx
372 *--stack = 0xDDDDDDDD; // edx
373 *--stack = 0xBBBBBBBB; // ebx
374 *--stack = 0xD1D1D1D1; // edi
375 *--stack = 0x54545454; // esp - NOT POPED
376 *--stack = 0x51515151; // esi
377 *--stack = 0xB4B4B4B4; // ebp
384 __asm__ __volatile__ (
385 "mov %%eax,%%esp;\n\t" // Set stack pointer
391 "iret;\n\t" : : "a" (stack));
396 * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
397 * \brief Demotes a process to a lower permission level
398 * \param Err Pointer to user's errno
400 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
402 int cpl = Regs->cs & 3;
404 if(Dest > 3 || Dest < 0) {
415 // Change the Segment Registers
416 Regs->cs = (((Dest+1)<<4) | Dest) - 8;
417 Regs->ss = ((Dest+1)<<4) | Dest;
418 // Check if the GP Segs are GDT, then change them
419 if(!(Regs->ds & 4)) Regs->ds = ((Dest+1)<<4) | Dest;
420 if(!(Regs->es & 4)) Regs->es = ((Dest+1)<<4) | Dest;
421 if(!(Regs->fs & 4)) Regs->fs = ((Dest+1)<<4) | Dest;
422 if(!(Regs->gs & 4)) Regs->gs = ((Dest+1)<<4) | Dest;
428 * \fn void Proc_Scheduler(int CPU)
429 * \brief Swap current thread and clears dead threads
431 void Proc_Scheduler(int CPU)
436 // If the spinlock is set, let it complete
437 if(giThreadListLock) return;
439 // Clear Delete Queue
440 while(gDeleteThreads)
442 thread = gDeleteThreads->Next;
443 if(gDeleteThreads->IsLocked) { // Only free if structure is unused
444 gDeleteThreads->Status = THREAD_STAT_NULL;
445 free( gDeleteThreads );
447 gDeleteThreads = thread;
450 // Check if there is any tasks running
451 if(giNumActiveThreads == 0) {
452 Log("No Active threads, sleeping\n");
453 __asm__ __volatile__ ("hlt");
457 // Reduce remaining quantum and continue timeslice if non-zero
458 if(gCurrentThread->Remaining--) return;
459 // Reset quantum for next call
460 gCurrentThread->Remaining = gCurrentThread->Quantum;
463 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
464 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
466 if(eip == SWITCH_MAGIC) return; // Check if a switch happened
468 // Save machine state
469 gCurrentThread->SavedState.ESP = esp;
470 gCurrentThread->SavedState.EBP = ebp;
471 gCurrentThread->SavedState.EIP = eip;
474 thread = Threads_GetNextToRun(CPU);
478 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
482 // Set current thread
483 gCurrentThread = thread;
485 // Update Kernel Stack pointer
486 gTSSs[CPU].ESP0 = thread->KernelStack;
489 __asm__ __volatile__ ("mov %0, %%cr3"::"a"(gCurrentThread->MemState.CR3));
491 __asm__ __volatile__ (
495 "a"(SWITCH_MAGIC), "b"(gCurrentThread->SavedState.ESP),
496 "d"(gCurrentThread->SavedState.EBP), "c"(gCurrentThread->SavedState.EIP));
497 for(;;); // Shouldn't reach here