2 * AcessOS Microkernel Version
17 #define DEBUG_TRACE_SWITCH 0
18 #define DEBUG_DISABLE_DOUBLEFAULT 1
19 #define DEBUG_VERY_SLOW_PERIOD 0
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
34 Uint8 State; // 0: Unavaliable, 1: Idle, 2: Active
42 extern void APWait(void); // 16-bit AP pause code
43 extern void APStartup(void); // 16-bit AP startup code
44 extern Uint GetEIP(void); // start.asm
45 extern Uint GetEIP_Sched(void); // proc.asm
46 extern void NewTaskHeader(tThread *Thread, void *Fcn, int nArgs, ...); // Actually takes cdecl args
47 extern Uint Proc_CloneInt(Uint *ESP, Uint32 *CR3);
48 extern Uint32 gaInitPageDir[1024]; // start.asm
49 extern char Kernel_Stack_Top[];
52 extern tThread gThreadZero;
53 extern void Isr8(void); // Double Fault
54 extern void Proc_ReturnToUser(tVAddr Handler, Uint Argument, tVAddr KernelStack);
55 extern char scheduler_return[]; // Return address in SchedulerBase
56 extern char IRQCommon[]; // Common IRQ handler code
57 extern char IRQCommon_handled[]; // IRQCommon call return location
58 extern char GetEIP_Sched_ret[]; // GetEIP call return location
59 extern void SwitchTasks(Uint NewSP, Uint *OldSP, Uint NewIP, Uint *OldIO, Uint CR3);
60 extern void Proc_InitialiseSSE(void);
61 extern void Proc_SaveSSE(Uint DestPtr);
62 extern void Proc_DisableSSE(void);
65 //void ArchThreads_Init(void);
67 void MP_StartAP(int CPU);
68 void MP_SendIPIVector(int CPU, Uint8 Vector);
69 void MP_SendIPI(Uint8 APICID, int Vector, int DeliveryMode);
71 void Proc_IdleThread(void *Ptr);
72 //void Proc_Start(void);
73 //tThread *Proc_GetCurThread(void);
74 void Proc_ChangeStack(void);
75 // int Proc_NewKThread(void (*Fcn)(void*), void *Data);
76 // int Proc_Clone(Uint *Err, Uint Flags);
77 Uint Proc_MakeUserStack(void);
78 //void Proc_StartUser(Uint Entrypoint, Uint *Bases, int ArgC, char **ArgV, char **EnvP, int DataSize);
79 void Proc_StartProcess(Uint16 SS, Uint Stack, Uint Flags, Uint16 CS, Uint IP) NORETURN;
80 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs);
81 //void Proc_CallFaultHandler(tThread *Thread);
82 //void Proc_DumpThreadCPUState(tThread *Thread);
83 void Proc_Scheduler(int CPU);
86 // --- Multiprocessing ---
88 volatile int giNumInitingCPUs = 0;
89 tMPInfo *gMPFloatPtr = NULL;
90 volatile Uint32 giMP_TimerCount; // Start Count for Local APIC Timer
91 tAPIC *gpMP_LocalAPIC = NULL;
92 Uint8 gaAPIC_to_CPU[256] = {0};
93 int giProc_BootProcessorID = 0;
94 tTSS gaTSSs[MAX_CPUS]; // TSS Array
96 tCPU gaCPUs[MAX_CPUS] = {
97 {.Current = &gThreadZero}
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
169 Log("gMPFloatPtr = %p", gMPFloatPtr);
170 Log("*gMPFloatPtr = {");
171 Log("\t.Sig = 0x%08x", gMPFloatPtr->Sig);
172 Log("\t.MPConfig = 0x%08x", gMPFloatPtr->MPConfig);
173 Log("\t.Length = 0x%02x", gMPFloatPtr->Length);
174 Log("\t.Version = 0x%02x", gMPFloatPtr->Version);
175 Log("\t.Checksum = 0x%02x", gMPFloatPtr->Checksum);
176 Log("\t.Features = [0x%02x,0x%02x,0x%02x,0x%02x,0x%02x]",
177 gMPFloatPtr->Features[0], gMPFloatPtr->Features[1],
178 gMPFloatPtr->Features[2], gMPFloatPtr->Features[3],
179 gMPFloatPtr->Features[4]
184 mptable = (void*)( KERNEL_BASE|gMPFloatPtr->MPConfig );
186 Log("mptable = %p", mptable);
188 Log("\t.Sig = 0x%08x", mptable->Sig);
189 Log("\t.BaseTableLength = 0x%04x", mptable->BaseTableLength);
190 Log("\t.SpecRev = 0x%02x", mptable->SpecRev);
191 Log("\t.Checksum = 0x%02x", mptable->Checksum);
192 Log("\t.OEMID = '%8c'", mptable->OemID);
193 Log("\t.ProductID = '%8c'", mptable->ProductID);
194 Log("\t.OEMTablePtr = %p'", mptable->OEMTablePtr);
195 Log("\t.OEMTableSize = 0x%04x", mptable->OEMTableSize);
196 Log("\t.EntryCount = 0x%04x", mptable->EntryCount);
197 Log("\t.LocalAPICMemMap = 0x%08x", mptable->LocalAPICMemMap);
198 Log("\t.ExtendedTableLen = 0x%04x", mptable->ExtendedTableLen);
199 Log("\t.ExtendedTableChecksum = 0x%02x", mptable->ExtendedTableChecksum);
203 gpMP_LocalAPIC = (void*)MM_MapHWPages(mptable->LocalAPICMemMap, 1);
205 ents = mptable->Entries;
208 for( i = 0; i < mptable->EntryCount; i ++ )
216 Log("%i: Processor", i);
217 Log("\t.APICID = %i", ents->Proc.APICID);
218 Log("\t.APICVer = 0x%02x", ents->Proc.APICVer);
219 Log("\t.CPUFlags = 0x%02x", ents->Proc.CPUFlags);
220 Log("\t.CPUSignature = 0x%08x", ents->Proc.CPUSignature);
221 Log("\t.FeatureFlags = 0x%08x", ents->Proc.FeatureFlags);
224 if( !(ents->Proc.CPUFlags & 1) ) {
229 // Check if there is too many processors
230 if(giNumCPUs >= MAX_CPUS) {
231 giNumCPUs ++; // If `giNumCPUs` > MAX_CPUS later, it will be clipped
235 // Initialise CPU Info
236 gaAPIC_to_CPU[ents->Proc.APICID] = giNumCPUs;
237 gaCPUs[giNumCPUs].APICID = ents->Proc.APICID;
238 gaCPUs[giNumCPUs].State = 0;
242 if( ents->Proc.CPUFlags & 2 ) {
243 giProc_BootProcessorID = giNumCPUs-1;
248 #if DUMP_MP_TABLE >= 2
252 Log("\t.ID = %i", ents->Bus.ID);
253 Log("\t.TypeString = '%6C'", ents->Bus.TypeString);
257 Log("%i: I/O APIC", i);
258 Log("\t.ID = %i", ents->IOAPIC.ID);
259 Log("\t.Version = 0x%02x", ents->IOAPIC.Version);
260 Log("\t.Flags = 0x%02x", ents->IOAPIC.Flags);
261 Log("\t.Addr = 0x%08x", ents->IOAPIC.Addr);
263 case 3: // I/O Interrupt Assignment
265 Log("%i: I/O Interrupt Assignment", i);
266 Log("\t.IntType = %i", ents->IOInt.IntType);
267 Log("\t.Flags = 0x%04x", ents->IOInt.Flags);
268 Log("\t.SourceBusID = 0x%02x", ents->IOInt.SourceBusID);
269 Log("\t.SourceBusIRQ = 0x%02x", ents->IOInt.SourceBusIRQ);
270 Log("\t.DestAPICID = 0x%02x", ents->IOInt.DestAPICID);
271 Log("\t.DestAPICIRQ = 0x%02x", ents->IOInt.DestAPICIRQ);
273 case 4: // Local Interrupt Assignment
275 Log("%i: Local Interrupt Assignment", i);
276 Log("\t.IntType = %i", ents->LocalInt.IntType);
277 Log("\t.Flags = 0x%04x", ents->LocalInt.Flags);
278 Log("\t.SourceBusID = 0x%02x", ents->LocalInt.SourceBusID);
279 Log("\t.SourceBusIRQ = 0x%02x", ents->LocalInt.SourceBusIRQ);
280 Log("\t.DestLocalAPICID = 0x%02x", ents->LocalInt.DestLocalAPICID);
281 Log("\t.DestLocalAPICIRQ = 0x%02x", ents->LocalInt.DestLocalAPICIRQ);
284 Log("%i: Unknown (%i)", i, ents->Type);
288 ents = (void*)( (Uint)ents + entSize );
291 if( giNumCPUs > MAX_CPUS ) {
292 Warning("Too many CPUs detected (%i), only using %i of them", giNumCPUs, MAX_CPUS);
293 giNumCPUs = MAX_CPUS;
298 Log("No MP Table was found, assuming uniprocessor\n");
307 #if !DEBUG_DISABLE_DOUBLEFAULT
308 // Initialise Double Fault TSS
309 gGDT[5].BaseLow = (Uint)&gDoubleFault_TSS & 0xFFFF;
310 gGDT[5].BaseMid = (Uint)&gDoubleFault_TSS >> 16;
311 gGDT[5].BaseHi = (Uint)&gDoubleFault_TSS >> 24;
313 // Set double fault IDT to use the new TSS
314 gIDT[8].OffsetLo = 0;
316 gIDT[8].Flags = 0x8500;
317 gIDT[8].OffsetHi = 0;
320 // Set timer frequency
321 outb(0x43, 0x34); // Set Channel 0, Low/High, Rate Generator
322 outb(0x40, TIMER_DIVISOR&0xFF); // Low Byte of Divisor
323 outb(0x40, (TIMER_DIVISOR>>8)&0xFF); // High Byte
325 Log_Debug("Proc", "PIT Frequency %i.%03i Hz",
326 TIMER_BASE/TIMER_DIVISOR,
327 ((Uint64)TIMER_BASE*1000/TIMER_DIVISOR)%1000
331 // Get the count setting for APIC timer
332 Log("Determining APIC Count");
333 __asm__ __volatile__ ("sti");
334 while( giMP_TimerCount == 0 ) __asm__ __volatile__ ("hlt");
335 __asm__ __volatile__ ("cli");
336 Log("APIC Count %i", giMP_TimerCount);
338 Uint64 freq = giMP_TimerCount;
340 freq /= TIMER_DIVISOR;
341 if( (freq /= 1000) < 2*1000)
342 Log("Bus Frequency %i KHz", freq);
343 else if( (freq /= 1000) < 2*1000)
344 Log("Bus Frequency %i MHz", freq);
345 else if( (freq /= 1000) < 2*1000)
346 Log("Bus Frequency %i GHz", freq);
348 Log("Bus Frequency %i THz", freq);
351 // Initialise Normal TSS(s)
352 for(pos=0;pos<giNumCPUs;pos++)
357 gTSSs[pos].SS0 = 0x10;
358 gTSSs[pos].ESP0 = 0; // Set properly by scheduler
359 gGDT[6+pos].BaseLow = ((Uint)(&gTSSs[pos])) & 0xFFFF;
360 gGDT[6+pos].BaseMid = ((Uint)(&gTSSs[pos]) >> 16) & 0xFFFF;
361 gGDT[6+pos].BaseHi = ((Uint)(&gTSSs[pos])) >> 24;
366 // Load the BSP's TSS
367 __asm__ __volatile__ ("ltr %%ax"::"a"(0x30));
368 // Set Current Thread and CPU Number in DR0 and DR1
369 __asm__ __volatile__ ("mov %0, %%db0"::"r"(&gThreadZero));
370 __asm__ __volatile__ ("mov %0, %%db1"::"r"(0));
372 gaCPUs[0].Current = &gThreadZero;
373 gThreadZero.CurCPU = 0;
375 gThreadZero.MemState.CR3 = (Uint)gaInitPageDir - KERNEL_BASE;
377 // Create Per-Process Data Block
378 if( !MM_Allocate(MM_PPD_CFG) )
380 Panic("OOM - No space for initial Per-Process Config");
383 // Initialise SSE support
384 Proc_InitialiseSSE();
394 void MP_StartAP(int CPU)
396 Log_Log("Proc", "Starting AP %i (APIC %i)", CPU, gaCPUs[CPU].APICID);
398 // Set location of AP startup code and mark for a warm restart
399 *(Uint16*)(KERNEL_BASE|0x467) = (Uint)&APWait - (KERNEL_BASE|0xFFFF0);
400 *(Uint16*)(KERNEL_BASE|0x469) = 0xFFFF;
401 outb(0x70, 0x0F); outb(0x71, 0x0A); // Set warm reset flag
402 MP_SendIPI(gaCPUs[CPU].APICID, 0, 5); // Init IPI
405 inb(0x80); inb(0x80); inb(0x80); inb(0x80);
407 // TODO: Use a better address, preferably registered with the MM
408 // - MM_AllocDMA mabye?
410 *(Uint8*)(KERNEL_BASE|0x11000) = 0xEA; // Far JMP
411 *(Uint16*)(KERNEL_BASE|0x11001) = (Uint)&APStartup - (KERNEL_BASE|0xFFFF0); // IP
412 *(Uint16*)(KERNEL_BASE|0x11003) = 0xFFFF; // CS
413 // Send a Startup-IPI to make the CPU execute at 0x11000 (which we
415 MP_SendIPI(gaCPUs[CPU].APICID, 0x11, 6); // StartupIPI
420 void MP_SendIPIVector(int CPU, Uint8 Vector)
422 MP_SendIPI(gaCPUs[CPU].APICID, Vector, 0);
426 * \brief Send an Inter-Processor Interrupt
427 * \param APICID Processor's Local APIC ID
428 * \param Vector Argument of some kind
429 * \param DeliveryMode Type of signal
430 * \note 3A 10.5 "APIC/Handling Local Interrupts"
432 void MP_SendIPI(Uint8 APICID, int Vector, int DeliveryMode)
437 val = (Uint)APICID << 24;
438 // Log("%p = 0x%08x", &gpMP_LocalAPIC->ICR[1], val);
439 gpMP_LocalAPIC->ICR[1].Val = val;
441 val = ((DeliveryMode & 7) << 8) | (Vector & 0xFF);
442 // Log("%p = 0x%08x", &gpMP_LocalAPIC->ICR[0], val);
443 gpMP_LocalAPIC->ICR[0].Val = val;
447 void Proc_IdleThread(void *Ptr)
449 tCPU *cpu = &gaCPUs[GetCPUNum()];
450 cpu->Current->ThreadName = strdup("Idle Thread");
451 Threads_SetPriority( cpu->Current, -1 ); // Never called randomly
452 cpu->Current->Quantum = 1; // 1 slice quantum
454 __asm__ __volatile__ ("sti"); // Make sure interrupts are enabled
455 __asm__ __volatile__ ("hlt"); // Make sure interrupts are enabled
461 * \fn void Proc_Start(void)
462 * \brief Start process scheduler
464 void Proc_Start(void)
473 for( i = 0; i < giNumCPUs; i ++ )
475 if(i) gaCPUs[i].Current = NULL;
478 tid = Proc_NewKThread(Proc_IdleThread, &gaCPUs[i]);
481 if( i != giProc_BootProcessorID ) {
486 // BSP still should run the current task
487 gaCPUs[0].Current = &gThreadZero;
489 // Start interrupts and wait for APs to come up
490 Log_Debug("Proc", "Waiting for APs to come up");
491 __asm__ __volatile__ ("sti");
492 while( giNumInitingCPUs ) __asm__ __volatile__ ("hlt");
495 tid = Proc_NewKThread(Proc_IdleThread, &gaCPUs[0]);
496 // gaCPUs[0].IdleThread = Threads_GetThread(tid);
499 gaCPUs[0].Current = &gThreadZero;
501 // Start Interrupts (and hence scheduler)
502 __asm__ __volatile__("sti");
504 MM_FinishVirtualInit();
508 * \fn tThread *Proc_GetCurThread(void)
509 * \brief Gets the current thread
511 tThread *Proc_GetCurThread(void)
514 return gaCPUs[ GetCPUNum() ].Current;
516 return gaCPUs[ 0 ].Current;
521 * \fn void Proc_ChangeStack(void)
522 * \brief Swaps the current stack for a new one (in the proper stack reigon)
524 void Proc_ChangeStack(void)
528 Uint curBase, newBase;
530 __asm__ __volatile__ ("mov %%esp, %0":"=r"(esp));
531 __asm__ __volatile__ ("mov %%ebp, %0":"=r"(ebp));
536 newBase = MM_NewKStack();
539 Panic("What the?? Unable to allocate space for initial kernel stack");
543 curBase = (Uint)&Kernel_Stack_Top;
545 LOG("curBase = 0x%x, newBase = 0x%x", curBase, newBase);
547 // Get ESP as a used size
549 LOG("memcpy( %p, %p, 0x%x )", (void*)(newBase - esp), (void*)(curBase - esp), esp );
551 memcpy( (void*)(newBase - esp), (void*)(curBase - esp), esp );
552 // Get ESP as an offset in the new stack
555 ebp = newBase - (curBase - ebp);
557 // Repair EBPs & Stack Addresses
558 // Catches arguments also, but may trash stack-address-like values
559 for(tmpEbp = esp; tmpEbp < newBase; tmpEbp += 4)
561 if(oldEsp < *(Uint*)tmpEbp && *(Uint*)tmpEbp < curBase)
562 *(Uint*)tmpEbp += newBase - curBase;
565 Proc_GetCurThread()->KernelStack = newBase;
567 __asm__ __volatile__ ("mov %0, %%esp"::"r"(esp));
568 __asm__ __volatile__ ("mov %0, %%ebp"::"r"(ebp));
571 void Proc_ClearThread(tThread *Thread)
573 Log_Warning("Proc", "TODO: Nuke address space etc");
574 if(Thread->SavedState.SSE) {
575 free(Thread->SavedState.SSE);
576 Thread->SavedState.SSE = NULL;
580 int Proc_NewKThread(void (*Fcn)(void*), void *Data)
583 tThread *newThread, *cur;
585 cur = Proc_GetCurThread();
586 newThread = Threads_CloneTCB(0);
587 if(!newThread) return -1;
590 newThread->MemState.CR3 = cur->MemState.CR3;
593 newThread->KernelStack = MM_NewKStack();
595 if(newThread->KernelStack == 0) {
600 esp = newThread->KernelStack;
601 *(Uint*)(esp-=4) = (Uint)Data; // Data (shadowed)
602 *(Uint*)(esp-=4) = 1; // Number of params
603 *(Uint*)(esp-=4) = (Uint)Fcn; // Function to call
604 *(Uint*)(esp-=4) = (Uint)newThread; // Thread ID
606 newThread->SavedState.ESP = esp;
607 newThread->SavedState.EIP = (Uint)&NewTaskHeader;
608 newThread->SavedState.SSE = NULL;
609 // Log("New (KThread) %p, esp = %p", newThread->SavedState.EIP, newThread->SavedState.ESP);
612 Threads_AddActive(newThread);
614 return newThread->TID;
618 * \fn int Proc_Clone(Uint *Err, Uint Flags)
619 * \brief Clone the current process
621 int Proc_Clone(Uint Flags)
624 tThread *cur = Proc_GetCurThread();
628 if( !(Flags & CLONE_VM) ) {
629 Log_Error("Proc", "Proc_Clone: Don't leave CLONE_VM unset, use Proc_NewKThread instead");
634 newThread = Threads_CloneTCB(Flags);
635 if(!newThread) return -1;
637 newThread->KernelStack = cur->KernelStack;
640 eip = Proc_CloneInt(&newThread->SavedState.ESP, &newThread->MemState.CR3);
645 newThread->SavedState.EIP = eip;
646 newThread->SavedState.SSE = NULL;
647 newThread->SavedState.bSSEModified = 0;
650 if( newThread->MemState.CR3 == 0 ) {
651 Log_Error("Proc", "Proc_Clone: MM_Clone failed");
652 Threads_Delete(newThread);
656 // Add the new thread to the run queue
657 Threads_AddActive(newThread);
658 return newThread->TID;
662 * \fn int Proc_SpawnWorker(void)
663 * \brief Spawns a new worker thread
665 int Proc_SpawnWorker(void (*Fcn)(void*), void *Data)
668 Uint stack_contents[4];
671 new = Threads_CloneThreadZero();
673 Warning("Proc_SpawnWorker - Out of heap space!\n");
677 // Create the stack contents
678 stack_contents[3] = (Uint)Data;
679 stack_contents[2] = 1;
680 stack_contents[1] = (Uint)Fcn;
681 stack_contents[0] = (Uint)new;
683 // Create a new worker stack (in PID0's address space)
684 new->KernelStack = MM_NewWorkerStack(stack_contents, sizeof(stack_contents));
686 // Save core machine state
687 new->SavedState.ESP = new->KernelStack - sizeof(stack_contents);
688 new->SavedState.EIP = (Uint)NewTaskHeader;
689 new->SavedState.SSE = NULL;
690 new->SavedState.bSSEModified = 0;
693 new->Status = THREAD_STAT_PREINIT;
694 Threads_AddActive( new );
700 * \fn Uint Proc_MakeUserStack(void)
701 * \brief Creates a new user stack
703 Uint Proc_MakeUserStack(void)
706 Uint base = USER_STACK_TOP - USER_STACK_SZ;
708 // Check Prospective Space
709 for( i = USER_STACK_SZ >> 12; i--; )
710 if( MM_GetPhysAddr( base + (i<<12) ) != 0 )
713 if(i != -1) return 0;
715 // Allocate Stack - Allocate incrementally to clean up MM_Dump output
716 for( i = 0; i < USER_STACK_SZ/0x1000; i++ )
718 if( !MM_Allocate( base + (i<<12) ) )
720 Warning("OOM: Proc_MakeUserStack");
725 return base + USER_STACK_SZ;
728 void Proc_StartUser(Uint Entrypoint, Uint Base, int ArgC, char **ArgV, int DataSize)
735 // Copy data to the user stack and free original buffer
736 stack = (void*)Proc_MakeUserStack();
737 stack -= DataSize/sizeof(*stack);
738 memcpy( stack, ArgV, DataSize );
741 // Adjust Arguments and environment
744 Uint delta = (Uint)stack - (Uint)ArgV;
745 ArgV = (char**)stack;
746 for( i = 0; ArgV[i]; i++ ) ArgV[i] += delta;
748 for( i = 0; envp[i]; i++ ) envp[i] += delta;
751 // User Mode Segments
752 ss = 0x23; cs = 0x1B;
755 *--stack = (Uint)envp;
756 *--stack = (Uint)ArgV;
757 *--stack = (Uint)ArgC;
760 Proc_StartProcess(ss, (Uint)stack, 0x202, cs, Entrypoint);
763 void Proc_StartProcess(Uint16 SS, Uint Stack, Uint Flags, Uint16 CS, Uint IP)
765 Uint *stack = (void*)Stack;
766 *--stack = SS; //Stack Segment
767 *--stack = Stack; //Stack Pointer
768 *--stack = Flags; //EFLAGS (Resvd (0x2) and IF (0x20))
769 *--stack = CS; //Code Segment
772 *--stack = 0xAAAAAAAA; // eax
773 *--stack = 0xCCCCCCCC; // ecx
774 *--stack = 0xDDDDDDDD; // edx
775 *--stack = 0xBBBBBBBB; // ebx
776 *--stack = 0xD1D1D1D1; // edi
777 *--stack = 0x54545454; // esp - NOT POPED
778 *--stack = 0x51515151; // esi
779 *--stack = 0xB4B4B4B4; // ebp
786 __asm__ __volatile__ (
787 "mov %%eax,%%esp;\n\t" // Set stack pointer
793 "iret;\n\t" : : "a" (stack));
798 * \fn int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
799 * \brief Demotes a process to a lower permission level
800 * \param Err Pointer to user's errno
801 * \param Dest New Permission Level
802 * \param Regs Pointer to user's register structure
804 int Proc_Demote(Uint *Err, int Dest, tRegs *Regs)
806 int cpl = Regs->cs & 3;
808 if(Dest > 3 || Dest < 0) {
819 // Change the Segment Registers
820 Regs->cs = (((Dest+1)<<4) | Dest) - 8;
821 Regs->ss = ((Dest+1)<<4) | Dest;
822 // Check if the GP Segs are GDT, then change them
823 if(!(Regs->ds & 4)) Regs->ds = ((Dest+1)<<4) | Dest;
824 if(!(Regs->es & 4)) Regs->es = ((Dest+1)<<4) | Dest;
825 if(!(Regs->fs & 4)) Regs->fs = ((Dest+1)<<4) | Dest;
826 if(!(Regs->gs & 4)) Regs->gs = ((Dest+1)<<4) | Dest;
832 * \brief Calls a signal handler in user mode
833 * \note Used for signals
835 void Proc_CallFaultHandler(tThread *Thread)
837 // Rewinds the stack and calls the user function
839 Proc_ReturnToUser( Thread->FaultHandler, Thread->CurFaultNum, Thread->KernelStack );
843 void Proc_DumpThreadCPUState(tThread *Thread)
845 if( Thread->CurCPU > -1 )
847 int maxBacktraceDistance = 6;
851 if( Thread->CurCPU != GetCPUNum() ) {
852 Log(" Currently running");
856 // Backtrace to find the IRQ entrypoint
857 // - This will usually only be called by an IRQ, so this should
859 __asm__ __volatile__ ("mov %%ebp, %0" : "=r" (stack));
860 while( maxBacktraceDistance -- )
865 if( stack[1] == (tVAddr)&IRQCommon_handled ) {
866 regs = (void*)stack[2];
870 stack = (void*)stack[0];
874 Log(" Unable to find IRQ Entry");
878 Log(" at %04x:%08x", regs->cs, regs->eip);
882 tVAddr diffFromScheduler = Thread->SavedState.EIP - (tVAddr)SwitchTasks;
883 tVAddr diffFromClone = Thread->SavedState.EIP - (tVAddr)Proc_CloneInt;
884 tVAddr diffFromSpawn = Thread->SavedState.EIP - (tVAddr)NewTaskHeader;
886 if( diffFromClone > 0 && diffFromClone < 40 ) // When I last checked, .newTask was at .+27
888 Log(" Creating process");
892 if( diffFromSpawn == 0 )
894 Log(" Creating thread");
898 if( diffFromScheduler > 0 && diffFromScheduler < 128 ) // When I last checked, GetEIP was at .+0x30
901 Log(" At %04x:%08x", Thread->SavedState.UserCS, Thread->SavedState.UserEIP);
905 Log(" Just created (unknown %p)", Thread->SavedState.EIP);
908 void Proc_Reschedule(void)
910 tThread *nextthread, *curthread;
911 int cpu = GetCPUNum();
913 // TODO: Wait for the lock?
914 if(IS_LOCKED(&glThreadListLock)) return;
916 curthread = Proc_GetCurThread();
918 nextthread = Threads_GetNextToRun(cpu, curthread);
920 if(!nextthread || nextthread == curthread)
923 #if DEBUG_TRACE_SWITCH
924 // HACK: Ignores switches to the idle threads
925 if( nextthread->TID == 0 || nextthread->TID > giNumCPUs )
927 LogF("\nSwitching CPU %i to %p (%i %s) - CR3 = 0x%x, EIP = %p, ESP = %p\n",
929 nextthread, nextthread->TID, nextthread->ThreadName,
930 nextthread->MemState.CR3,
931 nextthread->SavedState.EIP,
932 nextthread->SavedState.ESP
938 gaCPUs[cpu].Current = nextthread;
939 gTSSs[cpu].ESP0 = nextthread->KernelStack-4;
940 __asm__ __volatile__("mov %0, %%db0\n\t" : : "r"(nextthread) );
942 // Save FPU/MMX/XMM/SSE state
943 if( curthread && curthread->SavedState.SSE )
945 Proc_SaveSSE( ((Uint)curthread->SavedState.SSE + 0xF) & ~0xF );
946 curthread->SavedState.bSSEModified = 0;
953 nextthread->SavedState.ESP, &curthread->SavedState.ESP,
954 nextthread->SavedState.EIP, &curthread->SavedState.EIP,
955 nextthread->MemState.CR3
961 nextthread->SavedState.ESP, 0,
962 nextthread->SavedState.EIP, 0,
963 nextthread->MemState.CR3
971 * \fn void Proc_Scheduler(int CPU)
972 * \brief Swap current thread and clears dead threads
974 void Proc_Scheduler(int CPU)
979 // If the spinlock is set, let it complete
980 if(IS_LOCKED(&glThreadListLock)) return;
982 // Get current thread
983 thread = gaCPUs[CPU].Current;
989 // Reduce remaining quantum and continue timeslice if non-zero
990 if( thread->Remaining-- )
992 // Reset quantum for next call
993 thread->Remaining = thread->Quantum;
995 // TODO: Make this more stable somehow
996 __asm__ __volatile__("mov %%ebp, %0" : "=r" (ebp));
997 regs = (tRegs*)(ebp+(2+2)*4); // EBP,Ret + CPU,CurThread
998 thread->SavedState.UserCS = regs->cs;
999 thread->SavedState.UserEIP = regs->eip;
1001 if(thread->bInstrTrace) {
1002 regs->eflags |= 0x100; // Set TF
1003 Log("%p De-scheduled", thread);
1006 regs->eflags &= ~0x100; // Clear TF
1012 gpMP_LocalAPIC->EOI.Val = 0;
1016 __asm__ __volatile__ ("sti");
1022 EXPORT(Proc_SpawnWorker);