2 * AcessOS Microkernel Version
16 #define DEBUG_TRACE_SWITCH 0
17 #define DEBUG_DISABLE_DOUBLEFAULT 1
18 #define DEBUG_VERY_SLOW_SWITCH 0
21 #define SWITCH_MAGIC 0xFF5317C8 // FF SWITCH - There is no code in this area
23 #define TIMER_BASE 1193182
24 #if DEBUG_VERY_SLOW_PERIOD
25 # define TIMER_DIVISOR 1193 //~10Hz switch, with 10 quantum = 1s per thread
27 # define TIMER_DIVISOR 11932 //~100Hz
35 Uint8 State; // 0: Unavaliable, 1: Idle, 2: Active
45 extern void APWait(void); // 16-bit AP pause code
46 extern void APStartup(void); // 16-bit AP startup code
47 extern Uint GetEIP(void); // start.asm
48 extern Uint GetEIP_Sched(void); // proc.asm
49 extern int GetCPUNum(void); // start.asm
50 extern Uint32 gaInitPageDir[1024]; // start.asm
51 extern char Kernel_Stack_Top[];
52 extern tShortSpinlock glThreadListLock;
55 extern tThread gThreadZero;
56 extern void Isr8(void); // Double Fault
57 extern void Proc_ReturnToUser(tVAddr Handler, Uint Argument, tVAddr KernelStack);
58 extern void scheduler_return; // Return address in SchedulerBase
59 extern void IRQCommon; // Common IRQ handler code
60 extern void IRQCommon_handled; // IRQCommon call return location
61 extern void GetEIP_Sched_ret; // GetEIP call return location
64 void ArchThreads_Init(void);
66 void MP_StartAP(int CPU);
67 void MP_SendIPI(Uint8 APICID, int Vector, int DeliveryMode);
69 //void Proc_Start(void);
70 //tThread *Proc_GetCurThread(void);
71 void Proc_ChangeStack(void);
72 // int Proc_Clone(Uint *Err, Uint Flags);
73 Uint Proc_MakeUserStack(void);
74 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize);
75 void Proc_StartProcess(Uint16 SS, Uint Stack, Uint Flags, Uint16 CS, Uint IP);
76 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs);
77 void Proc_CallFaultHandler(tThread *Thread);
78 void Proc_DumpThreadCPUState(tThread *Thread);
79 void Proc_Scheduler(int CPU);
82 // --- Multiprocessing ---
84 volatile int giNumInitingCPUs = 0;
85 tMPInfo *gMPFloatPtr = NULL;
86 volatile Uint32 giMP_TimerCount; // Start Count for Local APIC Timer
87 tAPIC *gpMP_LocalAPIC = NULL;
88 Uint8 gaAPIC_to_CPU[256] = {0};
89 tCPU gaCPUs[MAX_CPUS];
90 tTSS gaTSSs[MAX_CPUS]; // TSS Array
91 int giProc_BootProcessorID = 0;
93 tThread *gCurrentThread = NULL;
94 tThread *gpIdleThread = NULL;
97 Uint32 *gPML4s[4] = NULL;
99 tTSS *gTSSs = NULL; // Pointer to TSS array
101 // --- Error Recovery ---
102 char gaDoubleFaultStack[1024] __attribute__ ((section(".padata")));
103 tTSS gDoubleFault_TSS = {
104 .ESP0 = (Uint)&gaDoubleFaultStack[1024],
106 .CR3 = (Uint)gaInitPageDir - KERNEL_BASE,
108 .ESP = (Uint)&gaDoubleFaultStack[1024],
109 .CS = 0x08, .SS = 0x10,
110 .DS = 0x10, .ES = 0x10,
111 .FS = 0x10, .GS = 0x10,
116 * \fn void ArchThreads_Init(void)
117 * \brief Starts the process scheduler
119 void ArchThreads_Init(void)
126 // Mark BSP as active
129 // -- Initialise Multiprocessing
130 // Find MP Floating Table
131 // - EBDA/Last 1Kib (640KiB)
132 for(pos = KERNEL_BASE|0x9F000; pos < (KERNEL_BASE|0xA0000); pos += 16) {
133 if( *(Uint*)(pos) == MPPTR_IDENT ) {
134 Log("Possible %p", pos);
135 if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
136 gMPFloatPtr = (void*)pos;
140 // - Last KiB (512KiB base mem)
142 for(pos = KERNEL_BASE|0x7F000; pos < (KERNEL_BASE|0x80000); pos += 16) {
143 if( *(Uint*)(pos) == MPPTR_IDENT ) {
144 Log("Possible %p", pos);
145 if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
146 gMPFloatPtr = (void*)pos;
153 for(pos = KERNEL_BASE|0xE0000; pos < (KERNEL_BASE|0x100000); pos += 16) {
154 if( *(Uint*)(pos) == MPPTR_IDENT ) {
155 Log("Possible %p", pos);
156 if( ByteSum((void*)pos, sizeof(tMPInfo)) != 0 ) continue;
157 gMPFloatPtr = (void*)pos;
163 // If the MP Table Exists, parse it
168 Log("gMPFloatPtr = %p", gMPFloatPtr);
169 Log("*gMPFloatPtr = {");
170 Log("\t.Sig = 0x%08x", gMPFloatPtr->Sig);
171 Log("\t.MPConfig = 0x%08x", gMPFloatPtr->MPConfig);
172 Log("\t.Length = 0x%02x", gMPFloatPtr->Length);
173 Log("\t.Version = 0x%02x", gMPFloatPtr->Version);
174 Log("\t.Checksum = 0x%02x", gMPFloatPtr->Checksum);
175 Log("\t.Features = [0x%02x,0x%02x,0x%02x,0x%02x,0x%02x]",
176 gMPFloatPtr->Features[0], gMPFloatPtr->Features[1],
177 gMPFloatPtr->Features[2], gMPFloatPtr->Features[3],
178 gMPFloatPtr->Features[4]
182 mptable = (void*)( KERNEL_BASE|gMPFloatPtr->MPConfig );
183 Log("mptable = %p", mptable);
185 Log("\t.Sig = 0x%08x", mptable->Sig);
186 Log("\t.BaseTableLength = 0x%04x", mptable->BaseTableLength);
187 Log("\t.SpecRev = 0x%02x", mptable->SpecRev);
188 Log("\t.Checksum = 0x%02x", mptable->Checksum);
189 Log("\t.OEMID = '%8c'", mptable->OemID);
190 Log("\t.ProductID = '%8c'", mptable->ProductID);
191 Log("\t.OEMTablePtr = %p'", mptable->OEMTablePtr);
192 Log("\t.OEMTableSize = 0x%04x", mptable->OEMTableSize);
193 Log("\t.EntryCount = 0x%04x", mptable->EntryCount);
194 Log("\t.LocalAPICMemMap = 0x%08x", mptable->LocalAPICMemMap);
195 Log("\t.ExtendedTableLen = 0x%04x", mptable->ExtendedTableLen);
196 Log("\t.ExtendedTableChecksum = 0x%02x", mptable->ExtendedTableChecksum);
199 gpMP_LocalAPIC = (void*)MM_MapHWPages(mptable->LocalAPICMemMap, 1);
201 ents = mptable->Entries;
204 for( i = 0; i < mptable->EntryCount; i ++ )
211 Log("%i: Processor", i);
212 Log("\t.APICID = %i", ents->Proc.APICID);
213 Log("\t.APICVer = 0x%02x", ents->Proc.APICVer);
214 Log("\t.CPUFlags = 0x%02x", ents->Proc.CPUFlags);
215 Log("\t.CPUSignature = 0x%08x", ents->Proc.CPUSignature);
216 Log("\t.FeatureFlags = 0x%08x", ents->Proc.FeatureFlags);
219 if( !(ents->Proc.CPUFlags & 1) ) {
224 // Check if there is too many processors
225 if(giNumCPUs >= MAX_CPUS) {
226 giNumCPUs ++; // If `giNumCPUs` > MAX_CPUS later, it will be clipped
230 // Initialise CPU Info
231 gaAPIC_to_CPU[ents->Proc.APICID] = giNumCPUs;
232 gaCPUs[giNumCPUs].APICID = ents->Proc.APICID;
233 gaCPUs[giNumCPUs].State = 0;
237 if( ents->Proc.CPUFlags & 2 ) {
238 giProc_BootProcessorID = giNumCPUs-1;
247 Log("\t.ID = %i", ents->Bus.ID);
248 Log("\t.TypeString = '%6C'", ents->Bus.TypeString);
252 Log("%i: I/O APIC", i);
253 Log("\t.ID = %i", ents->IOAPIC.ID);
254 Log("\t.Version = 0x%02x", ents->IOAPIC.Version);
255 Log("\t.Flags = 0x%02x", ents->IOAPIC.Flags);
256 Log("\t.Addr = 0x%08x", ents->IOAPIC.Addr);
258 case 3: // I/O Interrupt Assignment
260 Log("%i: I/O Interrupt Assignment", i);
261 Log("\t.IntType = %i", ents->IOInt.IntType);
262 Log("\t.Flags = 0x%04x", ents->IOInt.Flags);
263 Log("\t.SourceBusID = 0x%02x", ents->IOInt.SourceBusID);
264 Log("\t.SourceBusIRQ = 0x%02x", ents->IOInt.SourceBusIRQ);
265 Log("\t.DestAPICID = 0x%02x", ents->IOInt.DestAPICID);
266 Log("\t.DestAPICIRQ = 0x%02x", ents->IOInt.DestAPICIRQ);
268 case 4: // Local Interrupt Assignment
270 Log("%i: Local Interrupt Assignment", i);
271 Log("\t.IntType = %i", ents->LocalInt.IntType);
272 Log("\t.Flags = 0x%04x", ents->LocalInt.Flags);
273 Log("\t.SourceBusID = 0x%02x", ents->LocalInt.SourceBusID);
274 Log("\t.SourceBusIRQ = 0x%02x", ents->LocalInt.SourceBusIRQ);
275 Log("\t.DestLocalAPICID = 0x%02x", ents->LocalInt.DestLocalAPICID);
276 Log("\t.DestLocalAPICIRQ = 0x%02x", ents->LocalInt.DestLocalAPICIRQ);
279 Log("%i: Unknown (%i)", i, ents->Type);
283 ents = (void*)( (Uint)ents + entSize );
286 if( giNumCPUs > MAX_CPUS ) {
287 Warning("Too many CPUs detected (%i), only using %i of them", giNumCPUs, MAX_CPUS);
288 giNumCPUs = MAX_CPUS;
293 Log("No MP Table was found, assuming uniprocessor\n");
302 #if !DEBUG_DISABLE_DOUBLEFAULT
303 // Initialise Double Fault TSS
304 gGDT[5].BaseLow = (Uint)&gDoubleFault_TSS & 0xFFFF;
305 gGDT[5].BaseMid = (Uint)&gDoubleFault_TSS >> 16;
306 gGDT[5].BaseHi = (Uint)&gDoubleFault_TSS >> 24;
308 // Set double fault IDT to use the new TSS
309 gIDT[8].OffsetLo = 0;
311 gIDT[8].Flags = 0x8500;
312 gIDT[8].OffsetHi = 0;
315 // Set timer frequency
316 outb(0x43, 0x34); // Set Channel 0, Low/High, Rate Generator
317 outb(0x40, TIMER_DIVISOR&0xFF); // Low Byte of Divisor
318 outb(0x40, (TIMER_DIVISOR>>8)&0xFF); // High Byte
320 Log("Timer Frequency %i.%03i Hz",
321 TIMER_BASE/TIMER_DIVISOR,
322 ((Uint64)TIMER_BASE*1000/TIMER_DIVISOR)%1000
326 // Get the count setting for APIC timer
327 Log("Determining APIC Count");
328 __asm__ __volatile__ ("sti");
329 while( giMP_TimerCount == 0 ) __asm__ __volatile__ ("hlt");
330 __asm__ __volatile__ ("cli");
331 Log("APIC Count %i", giMP_TimerCount);
333 Uint64 freq = giMP_TimerCount;
334 freq /= TIMER_DIVISOR;
336 if( (freq /= 1000) < 2*1000)
337 Log("Bus Frequency %i KHz", freq);
338 else if( (freq /= 1000) < 2*1000)
339 Log("Bus Frequency %i MHz", freq);
340 else if( (freq /= 1000) < 2*1000)
341 Log("Bus Frequency %i GHz", freq);
343 Log("Bus Frequency %i THz", freq);
346 // Initialise Normal TSS(s)
347 for(pos=0;pos<giNumCPUs;pos++)
352 gTSSs[pos].SS0 = 0x10;
353 gTSSs[pos].ESP0 = 0; // Set properly by scheduler
354 gGDT[6+pos].BaseLow = ((Uint)(&gTSSs[pos])) & 0xFFFF;
355 gGDT[6+pos].BaseMid = ((Uint)(&gTSSs[pos]) >> 16) & 0xFFFF;
356 gGDT[6+pos].BaseHi = ((Uint)(&gTSSs[pos])) >> 24;
361 // Load the BSP's TSS
362 __asm__ __volatile__ ("ltr %%ax"::"a"(0x30));
363 // Set Current Thread and CPU Number in DR0 and DR1
364 __asm__ __volatile__ ("mov %0, %%db0"::"r"(&gThreadZero));
365 __asm__ __volatile__ ("mov %0, %%db1"::"r"(0));
368 gaCPUs[0].Current = &gThreadZero;
370 gCurrentThread = &gThreadZero;
372 gThreadZero.CurCPU = 0;
375 gThreadZero.MemState.PDP[0] = 0;
376 gThreadZero.MemState.PDP[1] = 0;
377 gThreadZero.MemState.PDP[2] = 0;
379 gThreadZero.MemState.CR3 = (Uint)gaInitPageDir - KERNEL_BASE;
382 // Create Per-Process Data Block
383 if( !MM_Allocate(MM_PPD_CFG) )
385 Panic("OOM - No space for initiali Per-Process Config");
393 void MP_StartAP(int CPU)
395 Log("Starting AP %i (APIC %i)", CPU, gaCPUs[CPU].APICID);
397 // Set location of AP startup code and mark for a warm restart
398 *(Uint16*)(KERNEL_BASE|0x467) = (Uint)&APWait - (KERNEL_BASE|0xFFFF0);
399 *(Uint16*)(KERNEL_BASE|0x469) = 0xFFFF;
400 outb(0x70, 0x0F); outb(0x71, 0x0A); // Set warm reset flag
401 MP_SendIPI(gaCPUs[CPU].APICID, 0, 5); // Init IPI
404 inb(0x80); inb(0x80); inb(0x80); inb(0x80);
406 // TODO: Use a better address, preferably registered with the MM
407 // - MM_AllocDMA mabye?
409 *(Uint8*)(KERNEL_BASE|0x11000) = 0xEA; // Far JMP
410 *(Uint16*)(KERNEL_BASE|0x11001) = (Uint)&APStartup - (KERNEL_BASE|0xFFFF0); // IP
411 *(Uint16*)(KERNEL_BASE|0x11003) = 0xFFFF; // CS
412 // Send a Startup-IPI to make the CPU execute at 0x11000 (which we
414 MP_SendIPI(gaCPUs[CPU].APICID, 0x11, 6); // StartupIPI
420 * \brief Send an Inter-Processor Interrupt
421 * \param APICID Processor's Local APIC ID
422 * \param Vector Argument of some kind
423 * \param DeliveryMode Type of signal?
425 void MP_SendIPI(Uint8 APICID, int Vector, int DeliveryMode)
430 val = (Uint)APICID << 24;
431 Log("*%p = 0x%08x", &gpMP_LocalAPIC->ICR[1], val);
432 gpMP_LocalAPIC->ICR[1].Val = val;
434 val = ((DeliveryMode & 7) << 8) | (Vector & 0xFF);
435 Log("*%p = 0x%08x", &gpMP_LocalAPIC->ICR[0], val);
436 gpMP_LocalAPIC->ICR[0].Val = val;
441 * \fn void Proc_Start(void)
442 * \brief Start process scheduler
444 void Proc_Start(void)
452 for( i = 0; i < giNumCPUs; i ++ )
455 if(i) gaCPUs[i].Current = NULL;
458 if( (tid = Proc_Clone(0, 0)) == 0)
460 for(;;) HALT(); // Just yeilds
462 gaCPUs[i].IdleThread = Threads_GetThread(tid);
463 gaCPUs[i].IdleThread->ThreadName = (char*)"Idle Thread";
464 Threads_SetPriority( gaCPUs[i].IdleThread, -1 ); // Never called randomly
465 gaCPUs[i].IdleThread->Quantum = 1; // 1 slice quantum
469 if( i != giProc_BootProcessorID ) {
474 // BSP still should run the current task
475 gaCPUs[0].Current = &gThreadZero;
477 // Start interrupts and wait for APs to come up
478 Log("Waiting for APs to come up\n");
479 __asm__ __volatile__ ("sti");
480 while( giNumInitingCPUs ) __asm__ __volatile__ ("hlt");
483 if(Proc_Clone(0, 0) == 0)
485 gpIdleThread = Proc_GetCurThread();
486 gpIdleThread->ThreadName = strdup("Idle Thread");
487 Threads_SetPriority( gpIdleThread, -1 ); // Never called randomly
488 gpIdleThread->Quantum = 1; // 1 slice quantum
489 for(;;) HALT(); // Just yeilds
493 gCurrentThread = &gThreadZero;
495 // Start Interrupts (and hence scheduler)
496 __asm__ __volatile__("sti");
498 MM_FinishVirtualInit();
502 * \fn tThread *Proc_GetCurThread(void)
503 * \brief Gets the current thread
505 tThread *Proc_GetCurThread(void)
508 return gaCPUs[ GetCPUNum() ].Current;
510 return gCurrentThread;
515 * \fn void Proc_ChangeStack(void)
516 * \brief Swaps the current stack for a new one (in the proper stack reigon)
518 void Proc_ChangeStack(void)
522 Uint curBase, newBase;
524 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
525 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
530 newBase = MM_NewKStack();
533 Panic("What the?? Unable to allocate space for initial kernel stack");
537 curBase = (Uint)&Kernel_Stack_Top;
539 LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
541 // Get ESP as a used size
543 LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
545 memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
546 // Get ESP as an offset in the new stack
549 ebp = newBase - (curBase - ebp);
551 // Repair EBPs & Stack Addresses
552 // Catches arguments also, but may trash stack-address-like values
553 for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
555 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
556 *(Uint*)tmpEbp += newBase - curBase;
559 Proc_GetCurThread()->KernelStack = newBase;
561 __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
562 __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
566 * \fn int Proc_Clone(Uint *Err, Uint Flags)
567 * \brief Clone the current process
569 int Proc_Clone(Uint *Err, Uint Flags)
572 tThread *cur = Proc_GetCurThread();
575 __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
576 __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
578 newThread = Threads_CloneTCB(Err, Flags);
579 if(!newThread) return -1;
581 // Initialise Memory Space (New Addr space or kernel stack)
582 if(Flags & CLONE_VM) {
583 newThread->MemState.CR3 = MM_Clone();
585 if(newThread->MemState.CR3 == 0) {
586 Threads_Kill(newThread, -2);
589 newThread->KernelStack = cur->KernelStack;
591 Uint tmpEbp, oldEsp = esp;
595 # warning "PAE Unimplemented"
597 newThread->MemState.CR3 = cur->MemState.CR3;
601 newThread->KernelStack = MM_NewKStack();
603 if(newThread->KernelStack == 0) {
604 Threads_Kill(newThread, -2);
608 // Get ESP as a used size
609 esp = cur->KernelStack - esp;
611 memcpy( (void*)(newThread->KernelStack - esp), (void*)(cur->KernelStack - esp), esp );
612 // Get ESP as an offset in the new stack
613 esp = newThread->KernelStack - esp;
615 ebp = newThread->KernelStack - (cur->KernelStack - ebp);
617 // Repair EBPs & Stack Addresses
618 // Catches arguments also, but may trash stack-address-like values
619 for(tmpEbp = esp; tmpEbp < newThread->KernelStack; tmpEbp += 4)
621 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < cur->KernelStack)
622 *(Uint*)tmpEbp += newThread->KernelStack - cur->KernelStack;
626 // Save core machine state
627 newThread->SavedState.ESP = esp;
628 newThread->SavedState.EBP = ebp;
630 if(eip == SWITCH_MAGIC) {
631 //__asm__ __volatile__ ("mov %0, %%db0" : : "r" (newThread) );
635 gpMP_LocalAPIC->EOI.Val = 0;
638 outb(0x20, 0x20); // ACK Timer and return as child
639 __asm__ __volatile__ ("sti"); // Restart interrupts
644 newThread->SavedState.EIP = eip;
646 // Lock list and add to active
647 Threads_AddActive(newThread);
649 return newThread->TID;
653 * \fn int Proc_SpawnWorker(void)
654 * \brief Spawns a new worker thread
656 int Proc_SpawnWorker(void)
661 cur = Proc_GetCurThread();
664 new = Threads_CloneThreadZero();
666 Warning("Proc_SpawnWorker - Out of heap space!\n");
669 // Create a new worker stack (in PID0's address space)
670 // - The stack is relocated by this function
671 new->KernelStack = MM_NewWorkerStack();
673 // Get ESP and EBP based in the new stack
674 __asm__ __volatile__ ("mov %%esp, %0": "=r"(esp));
675 __asm__ __volatile__ ("mov %%ebp, %0": "=r"(ebp));
676 esp = new->KernelStack - (cur->KernelStack - esp);
677 ebp = new->KernelStack - (cur->KernelStack - ebp);
679 // Save core machine state
680 new->SavedState.ESP = esp;
681 new->SavedState.EBP = ebp;
683 if(eip == SWITCH_MAGIC) {
684 //__asm__ __volatile__ ("mov %0, %%db0" : : "r"(new));
688 gpMP_LocalAPIC->EOI.Val = 0;
691 outb(0x20, 0x20); // ACK Timer and return as child
692 __asm__ __volatile__ ("sti"); // Restart interrupts
697 new->SavedState.EIP = eip;
699 Threads_AddActive( new );
705 * \fn Uint Proc_MakeUserStack(void)
706 * \brief Creates a new user stack
708 Uint Proc_MakeUserStack(void)
711 Uint base = USER_STACK_TOP - USER_STACK_SZ;
713 // Check Prospective Space
714 for( i = USER_STACK_SZ >> 12; i--; )
715 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
718 if(i != -1) return 0;
720 // Allocate Stack - Allocate incrementally to clean up MM_Dump output
721 for( i = 0; i < USER_STACK_SZ/0x1000; i++ )
723 if( !MM_Allocate( base + (i<<12) ) )
725 Warning("OOM: Proc_MakeUserStack");
730 return base + USER_STACK_SZ;
734 * \fn void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
735 * \brief Starts a user task
737 void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize)
739 Uint *stack = (void*)Proc_MakeUserStack();
744 //Log("stack = %p", stack);
747 stack -= DataSize/sizeof(*stack);
748 memcpy( stack, ArgV, DataSize );
750 //Log("stack = %p", stack);
754 // Adjust Arguments and environment
755 delta = (Uint)stack - (Uint)ArgV;
756 ArgV = (char**)stack;
757 for( i = 0; ArgV[i]; i++ )
761 // Do we care about EnvP?
764 for( i = 0; EnvP[i]; i++ )
769 // User Mode Segments
770 ss = 0x23; cs = 0x1B;
773 *--stack = (Uint)EnvP;
774 *--stack = (Uint)ArgV;
775 *--stack = (Uint)ArgC;
778 *--stack = 0; // Return Address
780 Proc_StartProcess(ss, (Uint)stack, 0x202, cs, Entrypoint);
783 void Proc_StartProcess(Uint16 SS, Uint Stack, Uint Flags, Uint16 CS, Uint IP)
785 Uint *stack = (void*)Stack;
786 *--stack = SS; //Stack Segment
787 *--stack = Stack; //Stack Pointer
788 *--stack = Flags; //EFLAGS (Resvd (0x2) and IF (0x20))
789 *--stack = CS; //Code Segment
792 *--stack = 0xAAAAAAAA; // eax
793 *--stack = 0xCCCCCCCC; // ecx
794 *--stack = 0xDDDDDDDD; // edx
795 *--stack = 0xBBBBBBBB; // ebx
796 *--stack = 0xD1D1D1D1; // edi
797 *--stack = 0x54545454; // esp - NOT POPED
798 *--stack = 0x51515151; // esi
799 *--stack = 0xB4B4B4B4; // ebp
806 __asm__ __volatile__ (
807 "mov %%eax,%%esp;\n\t" // Set stack pointer
813 "iret;\n\t" : : "a" (stack));
818 * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
819 * \brief Demotes a process to a lower permission level
820 * \param Err Pointer to user's errno
821 * \param Dest New Permission Level
822 * \param Regs Pointer to user's register structure
824 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
826 int cpl = Regs->cs & 3;
828 if(Dest > 3 || Dest < 0) {
839 // Change the Segment Registers
840 Regs->cs = (((Dest+1)<<4) | Dest) - 8;
841 Regs->ss = ((Dest+1)<<4) | Dest;
842 // Check if the GP Segs are GDT, then change them
843 if(!(Regs->ds & 4)) Regs->ds = ((Dest+1)<<4) | Dest;
844 if(!(Regs->es & 4)) Regs->es = ((Dest+1)<<4) | Dest;
845 if(!(Regs->fs & 4)) Regs->fs = ((Dest+1)<<4) | Dest;
846 if(!(Regs->gs & 4)) Regs->gs = ((Dest+1)<<4) | Dest;
852 * \brief Calls a signal handler in user mode
853 * \note Used for signals
855 void Proc_CallFaultHandler(tThread *Thread)
857 // Rewinds the stack and calls the user function
859 Proc_ReturnToUser( Thread->FaultHandler, Thread->CurFaultNum, Thread->KernelStack );
863 void Proc_DumpThreadCPUState(tThread *Thread)
865 if( Thread->CurCPU > -1 )
867 int maxBacktraceDistance = 6;
871 if( Thread->CurCPU != GetCPUNum() ) {
872 Log(" Currently running");
876 // Backtrace to find the IRQ entrypoint
877 // - This will usually only be called by an IRQ, so this should
879 __asm__ __volatile__ ("mov %%ebp, %0" : "=r" (stack));
880 while( maxBacktraceDistance -- )
885 if( stack[1] == (tVAddr)&IRQCommon_handled ) {
886 regs = (void*)stack[2];
890 stack = (void*)stack[0];
894 Log(" Unable to find IRQ Entry");
898 Log(" at %04x:%08x", regs->cs, regs->eip);
903 tVAddr diffFromScheduler = Thread->SavedState.EIP - (tVAddr)Proc_Scheduler;
904 tVAddr diffFromClone = Thread->SavedState.EIP - (tVAddr)Proc_Clone;
905 tVAddr diffFromSpawn = Thread->SavedState.EIP - (tVAddr)Proc_SpawnWorker;
907 if( diffFromClone > 0 && diffFromClone < 512 ) // When I last checked, GetEIP was at .+0x183
909 Log(" Creating full thread");
913 if( diffFromSpawn > 0 && diffFromSpawn < 512 ) // When I last checked, GetEIP was at .+0x99
915 Log(" Creating worker thread");
919 if( diffFromScheduler > 0 && diffFromScheduler < 256 ) // When I last checked, GetEIP was at .+0x60
922 MM_ReadFromAddrSpace(Thread->MemState.CR3, Thread->SavedState.EBP, data, 12);
923 if( data[1] == (Uint32)&IRQCommon + 25 )
925 tRegs *regs = (void *) data[2];
926 Log(" oldebp = 0x%08x, ret = 0x%08x, regs = 0x%x",
927 data[0], data[1], data[2]
930 // [EBP+0x04] = Return Addr
931 // [EBP+0x08] = Arg 1 (CPU Number)
932 // [EBP+0x0C] = Arg 2 (Thread)
933 // [EBP+0x10] = GS (start of tRegs)
934 Log(" IRQ%i from %02x:%08x", regs->int_num regs->cs, regs->eip);
936 if( stack[1] == (Uint32)&scheduler_return )
940 Log(" At %04x:%08x", Thread->SavedState.UserCS, Thread->SavedState.UserEIP);
944 Log(" Just created (unknow %p)", Thread->SavedState.EIP);
948 * \fn void Proc_Scheduler(int CPU)
949 * \brief Swap current thread and clears dead threads
951 void Proc_Scheduler(int CPU)
956 // If the spinlock is set, let it complete
957 if(IS_LOCKED(&glThreadListLock)) return;
959 // Get current thread
961 thread = gaCPUs[CPU].Current;
963 thread = gCurrentThread;
968 // Bug may be caused by DR0 not being maintained somewhere, hence
969 // login is getting loaded with the idle state.
973 // Reduce remaining quantum and continue timeslice if non-zero
974 if( thread->Remaining-- )
976 // Reset quantum for next call
977 thread->Remaining = thread->Quantum;
980 __asm__ __volatile__ ( "mov %%esp, %0" : "=r" (esp) );
981 __asm__ __volatile__ ( "mov %%ebp, %0" : "=r" (ebp) );
983 if(eip == SWITCH_MAGIC) return; // Check if a switch happened
985 // Save machine state
986 thread->SavedState.ESP = esp;
987 thread->SavedState.EBP = ebp;
988 thread->SavedState.EIP = eip;
990 // TODO: Make this more stable somehow
991 regs = (tRegs*)(ebp+(2+2)*4); // EBP,Ret + CPU,CurThread
992 thread->SavedState.UserCS = regs->cs;
993 thread->SavedState.UserEIP = regs->eip;
995 if(thread->bInstrTrace) {
996 regs->eflags |= 0x100; // Set TF
997 Log("%p De-scheduled", thread);
1000 regs->eflags &= ~0x100; // Clear TF
1003 // Get next thread to run
1004 thread = Threads_GetNextToRun(CPU, thread);
1007 // No avaliable tasks, just go into low power mode (idle thread)
1008 if(thread == NULL) {
1010 thread = gaCPUs[CPU].IdleThread;
1011 Log("CPU %i Running Idle Thread", CPU);
1013 thread = gpIdleThread;
1017 #if DEBUG_TRACE_SWITCH
1018 if(thread && thread != Proc_GetCurThread() ) {
1019 Log("Switching to task %i(%s), CR3 = 0x%x, EIP = %p",
1022 thread->MemState.CR3,
1023 thread->SavedState.EIP
1028 // Set current thread
1030 gaCPUs[CPU].Current = thread;
1032 gCurrentThread = thread;
1035 #if USE_MP // MP Debug
1036 // Log("CPU = %i, Thread %p", CPU, thread);
1039 // Update Kernel Stack pointer
1040 gTSSs[CPU].ESP0 = thread->KernelStack-4;
1043 if(thread->SavedState.ESP > 0xC0000000
1044 && thread->SavedState.ESP < thread->KernelStack-0x2000) {
1045 Log_Warning("Proc", "Possible bad ESP %p (PID %i)", thread->SavedState.ESP);
1049 if( thread->bInstrTrace ) {
1050 Log("%p Scheduled", thread);
1054 # error "Todo: Implement PAE Address space switching"
1056 // Set thread pointer
1057 __asm__ __volatile__("mov %0, %%db0\n\t" : : "r"(thread) );
1059 __asm__ __volatile__ (
1060 "mov %4, %%cr3\n\t" // Set address space
1061 "mov %1, %%esp\n\t" // Restore ESP
1062 "mov %2, %%ebp\n\t" // and EBP
1063 "or %5, 72(%%ebp)\n\t" // or trace flag to eflags (2+2+4+8+2)*4
1064 "jmp *%3" : : // And return to where we saved state (Proc_Clone or Proc_Scheduler)
1065 "a"(SWITCH_MAGIC), "b"(thread->SavedState.ESP),
1066 "d"(thread->SavedState.EBP), "c"(thread->SavedState.EIP),
1067 "r"(thread->MemState.CR3),
1068 "r"(thread->bInstrTrace&&thread->SavedState.EIP==(Uint)&GetEIP_Sched_ret?0x100:0)
1071 for(;;); // Shouldn't reach here
1075 EXPORT(Proc_SpawnWorker);