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 void APStartup(); // 16-bit AP startup code
23 extern Uint GetEIP(); // start.asm
24 extern Uint32 gaInitPageDir[1024]; // start.asm
25 extern void Kernel_Stack_Top;
26 extern volatile int giThreadListLock;
29 extern int giTotalTickets;
30 extern int giNumActiveThreads;
31 extern tThread gThreadZero;
32 extern tThread *gActiveThreads;
33 extern tThread *gSleepingThreads;
34 extern tThread *gDeleteThreads;
35 extern tThread *Threads_GetNextToRun(int CPU);
36 extern void Threads_Dump();
37 extern tThread *Threads_CloneTCB(Uint *Err, Uint Flags);
41 void ArchThreads_Init();
43 void MP_StartAP(int CPU);
44 void MP_SendIPI(Uint8 APICID, int Vector, int DeliveryMode);
47 tThread *Proc_GetCurThread();
48 void Proc_ChangeStack();
49 int Proc_Clone(Uint *Err, Uint Flags);
50 void Proc_Scheduler();
53 // --- Multiprocessing ---
55 volatile int giNumInitingCPUs = 0;
56 tMPInfo *gMPFloatPtr = NULL;
57 tAPIC *gpMP_LocalAPIC = NULL;
58 Uint8 gaAPIC_to_CPU[256] = {0};
59 tCPU gaCPUs[MAX_CPUS];
61 tThread *gCurrentThread = NULL;
64 Uint32 *gPML4s[4] = NULL;
68 // --- Error Recovery ---
69 char gaDoubleFaultStack[1024];
70 tTSS gDoubleFault_TSS = {
71 .ESP0 = (Uint)&gaDoubleFaultStack[1023],
78 * \fn void ArchThreads_Init()
79 * \brief Starts the process scheduler
81 void ArchThreads_Init()
91 // -- Initialise Multiprocessing
92 // Find MP Floating Table
93 // - EBDA/Last 1Kib (640KiB)
94 for(pos = KERNEL_BASE|0x9F000; pos < (KERNEL_BASE|0xA0000); pos += 16) {
95 if( *(Uint*)(pos) == MPPTR_IDENT ) {
96 Log("Possible %p", pos);
97 if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
98 gMPFloatPtr = (void*)pos;
102 // - Last KiB (512KiB base mem)
104 for(pos = KERNEL_BASE|0x7F000; pos < (KERNEL_BASE|0x80000); pos += 16) {
105 if( *(Uint*)(pos) == MPPTR_IDENT ) {
106 Log("Possible %p", pos);
107 if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
108 gMPFloatPtr = (void*)pos;
115 for(pos = KERNEL_BASE|0xE0000; pos < (KERNEL_BASE|0x100000); pos += 16) {
116 if( *(Uint*)(pos) == MPPTR_IDENT ) {
117 Log("Possible %p", pos);
118 if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
119 gMPFloatPtr = (void*)pos;
125 // If the MP Table Exists, parse it
130 Log("gMPFloatPtr = %p", gMPFloatPtr);
131 Log("*gMPFloatPtr = {");
132 Log("\t.Sig = 0x%08x", gMPFloatPtr->Sig);
133 Log("\t.MPConfig = 0x%08x", gMPFloatPtr->MPConfig);
134 Log("\t.Length = 0x%02x", gMPFloatPtr->Length);
135 Log("\t.Version = 0x%02x", gMPFloatPtr->Version);
136 Log("\t.Checksum = 0x%02x", gMPFloatPtr->Checksum);
137 Log("\t.Features = [0x%02x,0x%02x,0x%02x,0x%02x,0x%02x]",
138 gMPFloatPtr->Features[0], gMPFloatPtr->Features[1],
139 gMPFloatPtr->Features[2], gMPFloatPtr->Features[3],
140 gMPFloatPtr->Features[4]
144 mptable = (void*)( KERNEL_BASE|gMPFloatPtr->MPConfig );
145 Log("mptable = %p", mptable);
147 Log("\t.Sig = 0x%08x", mptable->Sig);
148 Log("\t.BaseTableLength = 0x%04x", mptable->BaseTableLength);
149 Log("\t.SpecRev = 0x%02x", mptable->SpecRev);
150 Log("\t.Checksum = 0x%02x", mptable->Checksum);
151 Log("\t.OEMID = '%8c'", mptable->OemID);
152 Log("\t.ProductID = '%8c'", mptable->ProductID);
153 Log("\t.OEMTablePtr = %p'", mptable->OEMTablePtr);
154 Log("\t.OEMTableSize = 0x%04x", mptable->OEMTableSize);
155 Log("\t.EntryCount = 0x%04x", mptable->EntryCount);
156 Log("\t.LocalAPICMemMap = 0x%08x", mptable->LocalAPICMemMap);
157 Log("\t.ExtendedTableLen = 0x%04x", mptable->ExtendedTableLen);
158 Log("\t.ExtendedTableChecksum = 0x%02x", mptable->ExtendedTableChecksum);
161 gpMP_LocalAPIC = (void*)MM_MapHWPage(mptable->LocalAPICMemMap, 1);
163 ents = mptable->Entries;
166 for( i = 0; i < mptable->EntryCount; i ++ )
173 Log("%i: Processor", i);
174 Log("\t.APICID = %i", ents->Proc.APICID);
175 Log("\t.APICVer = 0x%02x", ents->Proc.APICVer);
176 Log("\t.CPUFlags = 0x%02x", ents->Proc.CPUFlags);
177 Log("\t.CPUSignature = 0x%08x", ents->Proc.CPUSignature);
178 Log("\t.FeatureFlags = 0x%08x", ents->Proc.FeatureFlags);
181 if( !(ents->Proc.CPUFlags & 1) ) {
186 // Check if there is too many processors
187 if(giNumCPUs >= MAX_CPUS) {
188 giNumCPUs ++; // If `giNumCPUs` > MAX_CPUS later, it will be clipped
192 // Initialise CPU Info
193 gaAPIC_to_CPU[ents->Proc.APICID] = giNumCPUs;
194 gaCPUs[giNumCPUs].APICID = ents->Proc.APICID;
195 gaCPUs[giNumCPUs].State = 0;
199 if( !(ents->Proc.CPUFlags & 2) )
201 MP_StartAP( giNumCPUs-1 );
208 Log("\t.ID = %i", ents->Bus.ID);
209 Log("\t.TypeString = '%6c'", ents->Bus.TypeString);
213 Log("%i: I/O APIC", i);
214 Log("\t.ID = %i", ents->IOAPIC.ID);
215 Log("\t.Version = 0x%02x", ents->IOAPIC.Version);
216 Log("\t.Flags = 0x%02x", ents->IOAPIC.Flags);
217 Log("\t.Addr = 0x%08x", ents->IOAPIC.Addr);
219 case 3: // I/O Interrupt Assignment
221 Log("%i: I/O Interrupt Assignment", i);
222 Log("\t.IntType = %i", ents->IOInt.IntType);
223 Log("\t.Flags = 0x%04x", ents->IOInt.Flags);
224 Log("\t.SourceBusID = 0x%02x", ents->IOInt.SourceBusID);
225 Log("\t.SourceBusIRQ = 0x%02x", ents->IOInt.SourceBusIRQ);
226 Log("\t.DestAPICID = 0x%02x", ents->IOInt.DestAPICID);
227 Log("\t.DestAPICIRQ = 0x%02x", ents->IOInt.DestAPICIRQ);
229 case 4: // Local Interrupt Assignment
231 Log("%i: Local Interrupt Assignment", i);
232 Log("\t.IntType = %i", ents->LocalInt.IntType);
233 Log("\t.Flags = 0x%04x", ents->LocalInt.Flags);
234 Log("\t.SourceBusID = 0x%02x", ents->LocalInt.SourceBusID);
235 Log("\t.SourceBusIRQ = 0x%02x", ents->LocalInt.SourceBusIRQ);
236 Log("\t.DestLocalAPICID = 0x%02x", ents->LocalInt.DestLocalAPICID);
237 Log("\t.DestLocalAPICIRQ = 0x%02x", ents->LocalInt.DestLocalAPICIRQ);
240 Log("%i: Unknown (%i)", i, ents->Type);
243 ents = (void*)( (Uint)ents + entSize );
246 if( giNumCPUs > MAX_CPUS ) {
247 Warning("Too many CPUs detected (%i), only using %i of them", giNumCPUs, MAX_CPUS);
248 giNumCPUs = MAX_CPUS;
251 while( giNumInitingCPUs )
252 MM_FinishVirtualInit();
254 Panic("Uh oh... MP Table Parsing is unimplemented\n");
257 Log("No MP Table was found, assuming uniprocessor\n");
264 MM_FinishVirtualInit();
267 // Initialise Double Fault TSS
269 gGDT[5].LimitLow = sizeof(tTSS);
271 gGDT[5].Access = 0x89; // Type
274 gGDT[5].BaseLow = (Uint)&gDoubleFault_TSS & 0xFFFF;
275 gGDT[5].BaseMid = (Uint)&gDoubleFault_TSS >> 16;
276 gGDT[5].BaseHi = (Uint)&gDoubleFault_TSS >> 24;
279 // Initialise Normal TSS(s)
280 for(pos=0;pos<giNumCPUs;pos++)
285 gTSSs[pos].SS0 = 0x10;
286 gTSSs[pos].ESP0 = 0; // Set properly by scheduler
287 gGDT[6+pos].BaseLow = ((Uint)(&gTSSs[pos])) & 0xFFFF;
288 gGDT[6+pos].BaseMid = ((Uint)(&gTSSs[pos])) >> 16;
289 gGDT[6+pos].BaseHi = ((Uint)(&gTSSs[pos])) >> 24;
292 for(pos=0;pos<giNumCPUs;pos++) {
294 __asm__ __volatile__ ("ltr %%ax"::"a"(0x30+pos*8));
300 gaCPUs[0].Current = &gThreadZero;
302 gCurrentThread = &gThreadZero;
306 gThreadZero.MemState.PDP[0] = 0;
307 gThreadZero.MemState.PDP[1] = 0;
308 gThreadZero.MemState.PDP[2] = 0;
310 gThreadZero.MemState.CR3 = (Uint)gaInitPageDir - KERNEL_BASE;
313 // Set timer frequency
314 outb(0x43, 0x34); // Set Channel 0, Low/High, Rate Generator
315 outb(0x40, TIMER_DIVISOR&0xFF); // Low Byte of Divisor
316 outb(0x40, (TIMER_DIVISOR>>8)&0xFF); // High Byte
318 // Create Per-Process Data Block
319 MM_Allocate(MM_PPD_CFG);
326 void MP_StartAP(int CPU)
328 Log("Starting AP %i (APIC %i)", CPU, gaCPUs[CPU].APICID);
329 // Set location of AP startup code and mark for a warm restart
330 *(Uint16*)(KERNEL_BASE|0x467) = (Uint)&APStartup - (KERNEL_BASE|0xFFFF0);
331 *(Uint16*)(KERNEL_BASE|0x469) = 0xFFFF;
332 outb(0x70, 0x0F); outb(0x71, 0x0A); // Warm Reset
333 MP_SendIPI(gaCPUs[CPU].APICID, 0, 5);
337 void MP_SendIPI(Uint8 APICID, int Vector, int DeliveryMode)
339 Uint32 addr = (Uint)gpMP_LocalAPIC + 0x300;
343 val = (Uint)APICID << 24;
344 Log("*%p = 0x%08x", addr+0x10, val);
345 *(Uint32*)(addr+0x10) = val;
347 val = ((DeliveryMode & 7) << 8) | (Vector & 0xFF);
348 Log("*%p = 0x%08x", addr, val);
349 *(Uint32*)addr = val;
354 * \fn void Proc_Start()
355 * \brief Start process scheduler
359 // Start Interrupts (and hence scheduler)
360 __asm__ __volatile__("sti");
364 * \fn tThread *Proc_GetCurThread()
365 * \brief Gets the current thread
367 tThread *Proc_GetCurThread()
370 return gaCPUs[ gaAPIC_to_CPU[gpMP_LocalAPIC->ID.Val&0xFF] ].Current;
372 return gCurrentThread;
377 * \fn void Proc_ChangeStack()
378 * \brief Swaps the current stack for a new one (in the proper stack reigon)
380 void Proc_ChangeStack()
384 Uint curBase, newBase;
386 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
387 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
392 newBase = MM_NewKStack();
395 Panic("What the?? Unable to allocate space for initial kernel stack");
399 curBase = (Uint)&Kernel_Stack_Top;
401 LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
403 // Get ESP as a used size
405 LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
407 memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
408 // Get ESP as an offset in the new stack
411 ebp = newBase - (curBase - ebp);
413 // Repair EBPs & Stack Addresses
414 // Catches arguments also, but may trash stack-address-like values
415 for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
417 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
418 *(Uint*)tmpEbp += newBase - curBase;
421 Proc_GetCurThread()->KernelStack = newBase;
423 __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
424 __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
428 * \fn int Proc_Clone(Uint *Err, Uint Flags)
429 * \brief Clone the current process
431 int Proc_Clone(Uint *Err, Uint Flags)
434 tThread *cur = Proc_GetCurThread();
437 __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
438 __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
440 newThread = Threads_CloneTCB(Err, Flags);
441 if(!newThread) return -1;
443 // Initialise Memory Space (New Addr space or kernel stack)
444 if(Flags & CLONE_VM) {
445 newThread->MemState.CR3 = MM_Clone();
446 newThread->KernelStack = cur->KernelStack;
448 Uint tmpEbp, oldEsp = esp;
451 newThread->MemState.CR3 = cur->MemState.CR3;
454 newThread->KernelStack = MM_NewKStack();
456 if(newThread->KernelStack == 0) {
461 // Get ESP as a used size
462 esp = cur->KernelStack - esp;
464 memcpy( (void*)(newThread->KernelStack - esp), (void*)(cur->KernelStack - esp), esp );
465 // Get ESP as an offset in the new stack
466 esp = newThread->KernelStack - esp;
468 ebp = newThread->KernelStack - (cur->KernelStack - ebp);
470 // Repair EBPs & Stack Addresses
471 // Catches arguments also, but may trash stack-address-like values
472 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
474 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < cur->KernelStack)
475 *(Uint*)tmpEbp += newThread->KernelStack - cur->KernelStack;
479 // Save core machine state
480 newThread->SavedState.ESP = esp;
481 newThread->SavedState.EBP = ebp;
483 if(eip == SWITCH_MAGIC) {
484 outb(0x20, 0x20); // ACK Timer and return as child
489 newThread->SavedState.EIP = eip;
491 // Lock list and add to active
492 Threads_AddActive(newThread);
494 return newThread->TID;
498 * \fn int Proc_SpawnWorker()
499 * \brief Spawns a new worker thread
501 int Proc_SpawnWorker()
506 cur = Proc_GetCurThread();
509 new = malloc( sizeof(tThread) );
511 Warning("Proc_SpawnWorker - Out of heap space!\n");
514 memcpy(new, &gThreadZero, sizeof(tThread));
516 new->TID = giNextTID++;
517 // Create a new worker stack (in PID0's address space)
518 // The stack is relocated by this code
519 new->KernelStack = MM_NewWorkerStack();
521 // Get ESP and EBP based in the new stack
522 __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
523 __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
524 esp = new->KernelStack - (cur->KernelStack - esp);
525 ebp = new->KernelStack - (cur->KernelStack - ebp);
527 // Save core machine state
528 new->SavedState.ESP = esp;
529 new->SavedState.EBP = ebp;
531 if(eip == SWITCH_MAGIC) {
532 outb(0x20, 0x20); // ACK Timer and return as child
537 new->SavedState.EIP = eip;
539 new->Status = THREAD_STAT_ACTIVE;
540 Threads_AddActive( new );
546 * \fn Uint Proc_MakeUserStack()
547 * \brief Creates a new user stack
549 Uint Proc_MakeUserStack()
552 Uint base = USER_STACK_TOP - USER_STACK_SZ;
554 // Check Prospective Space
555 for( i = USER_STACK_SZ >> 12; i--; )
556 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
559 if(i != -1) return 0;
561 // Allocate Stack - Allocate incrementally to clean up MM_Dump output
562 for( i = 0; i < USER_STACK_SZ/4069; i++ )
563 MM_Allocate( base + (i<<12) );
565 return base + USER_STACK_SZ;
570 * \fn void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
571 * \brief Starts a user task
573 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
575 Uint *stack = (void*)Proc_MakeUserStack();
580 LOG("stack = 0x%x", stack);
583 stack = (void*)( (Uint)stack - DataSize );
584 memcpy( stack, ArgV, DataSize );
586 // Adjust Arguments and environment
587 delta = (Uint)stack - (Uint)ArgV;
588 ArgV = (char**)stack;
589 for( i = 0; ArgV[i]; i++ ) ArgV[i] += delta;
592 for( i = 0; EnvP[i]; i++ ) EnvP[i] += delta;
594 // User Mode Segments
595 ss = 0x23; cs = 0x1B;
598 *--stack = (Uint)EnvP;
599 *--stack = (Uint)ArgV;
600 *--stack = (Uint)ArgC;
603 *--stack = 0; // Return Address
604 delta = (Uint)stack; // Reuse delta to save SP
606 *--stack = ss; //Stack Segment
607 *--stack = delta; //Stack Pointer
608 *--stack = 0x0202; //EFLAGS (Resvd (0x2) and IF (0x20))
609 *--stack = cs; //Code Segment
610 *--stack = Entrypoint; //EIP
612 *--stack = 0xAAAAAAAA; // eax
613 *--stack = 0xCCCCCCCC; // ecx
614 *--stack = 0xDDDDDDDD; // edx
615 *--stack = 0xBBBBBBBB; // ebx
616 *--stack = 0xD1D1D1D1; // edi
617 *--stack = 0x54545454; // esp - NOT POPED
618 *--stack = 0x51515151; // esi
619 *--stack = 0xB4B4B4B4; // ebp
626 __asm__ __volatile__ (
627 "mov %%eax,%%esp;\n\t" // Set stack pointer
633 "iret;\n\t" : : "a" (stack));
638 * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
639 * \brief Demotes a process to a lower permission level
640 * \param Err Pointer to user's errno
641 * \param Dest New Permission Level
642 * \param Regs Pointer to user's register structure
644 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
646 int cpl = Regs->cs & 3;
648 if(Dest > 3 || Dest < 0) {
659 // Change the Segment Registers
660 Regs->cs = (((Dest+1)<<4) | Dest) - 8;
661 Regs->ss = ((Dest+1)<<4) | Dest;
662 // Check if the GP Segs are GDT, then change them
663 if(!(Regs->ds & 4)) Regs->ds = ((Dest+1)<<4) | Dest;
664 if(!(Regs->es & 4)) Regs->es = ((Dest+1)<<4) | Dest;
665 if(!(Regs->fs & 4)) Regs->fs = ((Dest+1)<<4) | Dest;
666 if(!(Regs->gs & 4)) Regs->gs = ((Dest+1)<<4) | Dest;
672 * \fn void Proc_Scheduler(int CPU)
673 * \brief Swap current thread and clears dead threads
675 void Proc_Scheduler(int CPU)
680 // If the spinlock is set, let it complete
681 if(giThreadListLock) return;
683 // Clear Delete Queue
684 while(gDeleteThreads)
686 thread = gDeleteThreads->Next;
687 if(gDeleteThreads->IsLocked) { // Only free if structure is unused
688 gDeleteThreads->Status = THREAD_STAT_NULL;
689 free( gDeleteThreads );
691 gDeleteThreads = thread;
694 // Check if there is any tasks running
695 if(giNumActiveThreads == 0) {
696 Log("No Active threads, sleeping");
697 __asm__ __volatile__ ("hlt");
701 // Get current thread
703 thread = gaCPUs[CPU].Current;
705 thread = gCurrentThread;
708 // Reduce remaining quantum and continue timeslice if non-zero
709 if(thread->Remaining--) return;
710 // Reset quantum for next call
711 thread->Remaining = thread->Quantum;
714 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
715 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
717 if(eip == SWITCH_MAGIC) return; // Check if a switch happened
719 // Save machine state
720 thread->SavedState.ESP = esp;
721 thread->SavedState.EBP = ebp;
722 thread->SavedState.EIP = eip;
725 thread = Threads_GetNextToRun(CPU);
729 Warning("Hmm... Threads_GetNextToRun returned NULL, I don't think this should happen.\n");
733 #if DEBUG_TRACE_SWITCH
734 Log("Switching to task %i, CR3 = 0x%x, EIP = %p",
736 thread->MemState.CR3,
737 thread->SavedState.EIP
741 // Set current thread
743 gaCPUs[CPU].Current = thread;
745 gCurrentThread = thread;
748 // Update Kernel Stack pointer
749 gTSSs[CPU].ESP0 = thread->KernelStack-4;
753 # error "Todo: Implement PAE Address space switching"
755 __asm__ __volatile__ ("mov %0, %%cr3"::"a"(thread->MemState.CR3));
758 __asm__ __volatile__ (
759 "mov %1, %%esp\n\t" // Restore ESP
760 "mov %2, %%ebp\n\t" // and EBP
761 "jmp *%3" : : // And return to where we saved state (Proc_Clone or Proc_Scheduler)
762 "a"(SWITCH_MAGIC), "b"(thread->SavedState.ESP),
763 "d"(thread->SavedState.EBP), "c"(thread->SavedState.EIP)
765 for(;;); // Shouldn't reach here
769 EXPORT(Proc_SpawnWorker);