internal static UIntPtr GetSipStackSegment(UIntPtr size) { UIntPtr stack; // @TODO: Historically we have disabled interrupts around stack growth. // Actually I think it is unnecessary; however to be conservative for // now we will disable interrupts while we use the interrupt stack. bool en = Processor.DisableInterrupts(); try { unsafe { // Sanity check: we allocate from the current stack segment, and // will set the thread context to point to a new stack segment VTable.Assert(Isa.GetStackPointer() <= Processor.GetCurrentThreadContext()->stackBegin); VTable.Assert(Isa.GetStackPointer() >= Processor.GetCurrentThreadContext()->stackLimit); } stack = Isa.CallbackOnInterruptStack(getSipStackCallback, size); } finally { Processor.RestoreInterrupts(en); } return(stack); }
public static void RestoreInterrupts(bool enabled) { int i = 0; try { #if CHECK_DISABLE_INTERRUPTS if (!InterruptsDisabled()) { DebugStub.Break(); } #endif i = 1; if (enabled) { i = 2; // Processor flag should be turned off before this call if (GetCurrentProcessor().InInterruptContext) { DebugStub.Break(); } i = 3; Isa.EnableInterrupts(); } i = 5; #if CHECK_DISABLE_INTERRUPTS if (enabled && InterruptsDisabled()) { DebugStub.Break(); } #endif } catch (Exception e) { DebugStub.Break(); } }
internal static UIntPtr GetKernelStackSegment(UIntPtr size) { UIntPtr stack; // @TODO: see note about disabling interrupts above. bool en = Processor.DisableInterrupts(); try { unsafe { // Sanity check: we allocate from the current stack segment, and // will set the thread context to point to a new stack segment VTable.Assert(Isa.GetStackPointer() <= Processor.GetCurrentThreadContext()->stackBegin); VTable.Assert(Isa.GetStackPointer() >= Processor.GetCurrentThreadContext()->stackLimit); } stack = Isa.CallbackOnInterruptStack(getKernelStackCallback, size); } finally { Processor.RestoreInterrupts(en); } return(stack); }
public static bool apic = false; // True if APIC is present public static object Initialize(Processor processor) { if (processor.Id == 0) { // We have hardware PICS, determine which kind // // Detect if an APIC is present on the CPU // // From 8.4.2 Presence of the Local APIC on page 337 of the // Intel 64 and IA-32 Architectures Software Developers Manual // // function (1) -> eax // cpuid // eax -> p0 // ebx -> p1 // ecx -> p2 // edx -> p3 Bit 9 set if APIC present // // // Note: It has been noted that some older motherboards // may have an APIC capable processor, but a chipset // that does not properly support the APIC interrupt // protocol. These motherboards will remove the APIC // hardware tables from the ACPI tables as an indication // that the APIC present on the processor should not // be used. Of course these are uni-processor only // motherboards without hyperthreading or multiple-cores. // uint p0, p1, p2, p3; Isa.ReadCpuid((uint)1, out p0, out p1, out p2, out p3); if (((p3 >> 9) & 0x1) != 0) { apic = true; DebugStub.Print("HalDevices: CPUID says APIC present\n"); } else { apic = false; DebugStub.Print("HalDevices: CPUID says APIC NOT present\n"); } // Dynamically select the proper hardware support drivers if (apic) { devices = HalDevicesApic.Create(); } else { devices = HalDevicesLegacyPC.Create(); } } // This happens for all processors devices.Initialize(processor); return(devices); }
public void LogStackTrace(UIntPtr eip, UIntPtr ebp) { if ((ControlFlags & Profile_Control_flag) != 0) { int actualStacks = 0; // // Capture the stack trace from the context // while (actualStacks < MaxStackSize) { if (eip == 0) { break; } StackTrace[actualStacks++] = eip; if (ebp == 0) { break; } eip = Isa.GetFrameReturnAddress(ebp); ebp = Isa.GetFrameCallerFrame(ebp); } // // Setup the log structure and log the event // unsafe { ProfilerEvent profilerEvent; profilerEvent.StackTrace = 1; ������������������� ArrayType arrayDescriptor; � ������������������� fixed(UIntPtr *ptr = StackTrace) { � ����������������������� arrayDescriptor.ItemSize = (ushort)sizeof(UIntPtr); ����������������������� arrayDescriptor.Length = (ushort)(actualStacks * arrayDescriptor.ItemSize); ����������������������� arrayDescriptor.Type = DataType.__UIntPtr; ����������������������� arrayDescriptor.Buffer = (void *)ptr; ��������������������������� ����������������������� LogEntry(ControlFlags, eventProfileType, (byte *)&profilerEvent, sizeof(ProfilerEvent), 1, &arrayDescriptor); ������������������� } } } }
internal static void SetCurrentThreadContext(ref ThreadContext context) { unsafe { fixed(ThreadContext *c = &context) { Isa.SetCurrentThread(ref c->threadRecord); } } }
internal void Initialize(byte baseVector) { DebugStub.Assert(255 - baseVector >= 48); this.baseVector = baseVector; Write(ApicOffset.LvtTimer, LvtFlags.Masked); Write(ApicOffset.LvtThermalSensor, LvtFlags.Masked); Write(ApicOffset.LvtPerfCounts, LvtFlags.Masked); Write(ApicOffset.LvtError, LvtFlags.Masked); Write(ApicOffset.SpuriousIntVector, 0xdfu); // set task priority to 0 so that it can // receive all interrupts from IPI // Write(ApicOffset.TaskPriority, 0x20u); Write(ApicOffset.TaskPriority, 0); Write(ApicOffset.LvtLint0, LvtFlags.Masked); Write(ApicOffset.LvtLint1, LvtFlags.Masked); SetId((byte)Processor.GetCurrentProcessorId()); if (this.IsBsp) { InitializeRouteableEntries(); InitializeMpResourceEntries(); } // Enable in s/w SetEnabled(true); // Enable in h/w Isa.WriteMsr(ApicMSR, Isa.ReadMsr(ApicMSR) | (1 << 11)); // Watch out for the uniprocessor case where the // FloatingPointer may be null. MpFloatingPointer floatingPointer = MpResources.FloatingPointer; if (floatingPointer != null && floatingPointer.ImcrPresent && this.IsBsp) { IoPort addrPort = new IoPort(ImcrAddressPort, 1, Access.Write); IoPort dataPort = new IoPort(ImcrDataPort, 1, Access.Write); addrPort.Write8(ImcrAddressSelect); dataPort.Write8(ImcrDataApic); } Write(ApicOffset.LvtLint0, LvtFlags.Level | LvtFlags.ExtInt); Write(ApicOffset.LvtLint1, LvtFlags.NMI | 0x02); for (int z = 0; z <= maxIrq; z++) { byte m = IrqToInterrupt((byte)z); byte n = InterruptToIrq(m); DebugStub.Assert((byte)z == n); } }
public Apic() { ulong msr = Isa.ReadMsr(0x1b); baseAddr = ((uint)msr) & 0xfffff000u; this.apicRegion = IoMemory.MapPhysicalMemory(baseAddr, new UIntPtr(ApicOffset.Max), true, true); }
public void Init() { cif = new CockpitInterface(); inp = new Inertia(plane.name); inp.SetBlock(0, new InertiaBlock("‹@‘Ì", plane.cg, plane.m0, plane.ixx_m0, plane.iyy_m0, plane.izz_m0, plane.ixy_m0, plane.iyz_m0, plane.izx_m0)); pMotion = new PlaneMotion(inp, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D, 0.0D); atmos = new Isa(pMotion.wpos.y); }
public static void InitializeEntry(ref Idte entry, UIntPtr address) { entry.offset_0_15 = (ushort)address; entry.offset_16_31 = (ushort)(((uint)address) >> 16); #if ISA_IX64 entry.offset_32_63 = (uint)(((ulong)address) >> 32); #endif entry.selector = (ushort)Isa.GetCs(); entry.flags = 0; entry.access = (byte)(Idte.PRESENT | Idte.DPL_RING0 | Idte.INT_GATE); }
private unsafe void Initialize(int processorId) { uint DefaultStackSize = 0xA000; processorTable[processorId] = this; context = (ProcessorContext *)Isa.GetCurrentCpu(); DebugStub.WriteLine("Processor context: {0} {1:x8}", __arglist(processorId, Kernel.AddressOf(context))); context->UpdateAfterGC(this); if (0 != processorId) { Thread.BindKernelThread(kernelThread, kernelStackBegin, kernelStackLimit); } AllocateStack(DefaultStackSize, out context->cpuRecord.interruptStackBegin, out context->cpuRecord.interruptStackLimit); Tracing.Log(Tracing.Debug, "Initialized Processor {0}", (UIntPtr)processorId); Tracing.Log(Tracing.Debug, "asmInterruptStack={0:x}..{1:x}", context->cpuRecord.interruptStackBegin, context->cpuRecord.interruptStackLimit); #if false DebugStub.WriteLine("proc{0}: InterruptStack={1:x}..{2:x}", __arglist( processorId, context->cpuRecord.interruptStackBegin, context->cpuRecord.interruptStackLimit )); #endif Interlocked.Increment(ref runningCpus); MpExecution.AddProcessorContext(context); // Need to allocate this callback object outside of NoThreadAllocation region if (processorId == 0) { resumeThreadCallback = new ResumeThreadCallback(); } Isa.EnableCycleCounter(); }
internal static unsafe void ActivatePreviousStackSegmentLimit() { // To avoid sprinkling [NoStackOverflowCheck] attributes // on too many methods, we manually inline a couple of methods. // ThreadContext *context = Processor.GetCurrentThreadContext(); ThreadRecord * threadRecord = Isa.GetCurrentThread(); ThreadContext *context = (ThreadContext *)threadRecord; StackHead * head = (StackHead *) (context->stackBegin - sizeof(StackHead)); // Isa.StackLimit = head->prevLimit; threadRecord->activeStackLimit = head->prevLimit; }
public Apic(IoApic[] ioApics) { ulong msr = Isa.ReadMsr(0x1b); baseAddr = ((uint)msr) & 0xfffff000u; this.apicRegion = IoMemory.MapPhysicalMemory(baseAddr, new UIntPtr(ApicOffset.Max), true, true); this.ioApics = ioApics; DebugStub.Assert(initialIdTable == null); // Check Single Apic instance initialIdTable = new byte [256]; }
public static bool DisableInterrupts() { #if CHECK_DISABLE_INTERRUPTS bool wasDisabled = InterruptsDisabled(); #endif bool result = Isa.DisableInterrupts(); #if CHECK_DISABLE_INTERRUPTS if (result && wasDisabled) { DebugStub.Break(); } #endif return(result); }
public Interfaces.Results.SP.SurgeonGroupActiveDayNumberBlockAssignments.ISPz GetElementsAt( ISPzResultElementFactory zResultElementFactory, ISPzFactory zFactory, Isa sa) { return(zFactory.Create( sa.Value .Select( i => zResultElementFactory.Create( i.sIndexElement, i.aIndexElement, this.GetElementAt( i.sIndexElement, i.aIndexElement))) .ToImmutableList())); }
public double Calc_engine_power(double th, double h_0, AirPlane ap) { double h_k_dash = Isa.Giopotential_altitude(h_k); double h_k2_dash = Isa.Giopotential_altitude(h_k2); double h_k2_shift_dash = Isa.Giopotential_altitude(h_k2_shift); double p; if (h_0 <= h_k) { p = (p_k - p_ck) * h_0 / h_k + p_ck; } else { if (h_0 <= h_k2_shift) { p = p_k * ap.atmos.p / Isa.Pressure(h_k_dash) * Math.Sqrt(Isa.Temperature(h_k_dash) / ap.atmos.t); } else { if (h_0 <= h_k2) { double p_k2_shift = p_k * Isa.Pressure(h_k2_shift_dash) / Isa.Pressure(h_k_dash) * Math.Sqrt(Isa.Temperature(h_k_dash) / Isa.Temperature(h_k2_shift_dash)); p = (p_k2 - p_k2_shift) * (h_0 - h_k2_shift) / (h_k2 - h_k2_shift) + p_k2_shift; } else { p = p_k2 * ap.atmos.p / Isa.Pressure(h_k2_dash) * Math.Sqrt(Isa.Temperature(h_k2_dash) / ap.atmos.t); } } } p *= th; if (th == 1.0D) { if (h_0 < 15.0D) { p = p_r; } else if (h_0 < 30.0D) { p = Jp.Maker1.Sim.Tools.Tool.Hokan(15.0D, p_r, 30.0D, p, h_0); } } return(p); }
public Isa Create( ImmutableList <IsaCrossJoinElement> value) { Isa crossJoin = null; try { crossJoin = new sa( value); } catch (Exception exception) { this.Log.Error( exception.Message, exception); } return(crossJoin); }
internal static void ReturnKernelStackSegment() { // @TODO: see note about disabling interrupts above. bool en = Processor.DisableInterrupts(); try { Isa.CallbackOnInterruptStack(returnKernelStackCallback, 0); unsafe { // Sanity check: we freed from the previous segment, and // should have set the thread context to point to this segment now. VTable.Assert(Isa.GetStackPointer() <= Processor.GetCurrentThreadContext()->stackBegin); VTable.Assert(Isa.GetStackPointer() >= Processor.GetCurrentThreadContext()->stackLimit); } } finally { Processor.RestoreInterrupts(en); } }
// Create a log entry for the allocation that just occurred on this thread. protected override void Allocation(UIntPtr objAddr, Type type, UIntPtr size) { bool iflag; // We cannot recurse inside an Allocation notification, or we will simply // blow the stack on the first entry. Also, we don't want to log allocations // that occur as a consequence of logging the state of the GC heap -- though // we could support that if we chose to. if (enabled && recurseThread != Thread.CurrentThread && // recurse? Buffer.OwningThread != Thread.CurrentThread) // GC logging? { iflag = Processor.DisableLocalPreemption(); allocationLock.Acquire(); try { DebugStub.Assert(recurseThread == null); recurseThread = Thread.CurrentThread; Buffer.LogTick(); uint stackSize = Isa.GetStackReturnAddresses(stackEips); uint stkNo = 0; if (stackSize > 0) { stkNo = GetStackId(type, size, stackEips, stackSize); } ProfilerBuffer.LogAllocation(Thread.CurrentThread.GetThreadId(), objAddr, stkNo); } finally { recurseThread = null; allocationLock.Release(); Processor.RestoreLocalPreemption(iflag); } } }
internal static unsafe void SwitchToThreadContextNoGC(ref ThreadContext newContext) { // Interrupts should be disabled at this point VTable.Assert(Processor.InterruptsDisabled()); // Save appears to returns twice: once with true on this thread after // the save, and once with false when the context is restored. if (GetCurrentThreadContext()->threadRecord.spill.Save()) { // Initial return from save; time to swap in the new context. // Must do this on the interrupt stack, since once we release the // dispatch lock the saved context is free to run (and we would // be on the same stack.) fixed(ThreadContext *c = &newContext) { // Note that this does not return. Isa.CallbackOnInterruptStack(resumeThreadCallback, (UIntPtr)c); } } // Saved context will resume here }
public void Update(double dt) { cif.UpdatePos(dt); pilot.Update(this, cif, dt); FlightModel(dt); crash_point = -1; if (flag_land == 0) { crash_point = Check_crash(); if (crash_point > -1) { Set_pMotionLand(); pMotion.wpos.x = (pMotion.wpos.z = 0.0D); } } pMotion.Calc_equation_of_motion(inp, force, torque, dt); atmos.Init(Isa.Giopotential_altitude(pMotion.wpos.y)); }
internal void DumpState() { ulong msr = Isa.ReadMsr(0x1b); uint baseAddr = ((uint)msr) & 0xfffff000u; uint en = (((uint)msr) >> 11) & 0x1; uint bsp = (((uint)msr) >> 8) & 0x1; DebugStub.Print("Apic Base {0:x8} MSR Enabled {1} BSP {2}\n", __arglist(baseAddr, en, bsp)); DebugStub.Print("Id {0:x} Version {1:x} TaskPriority {2:x} " + "ArbitrationPriority {3:x} ProcessorPriority {4:x}\n", __arglist( Read(ApicOffset.Id), Read(ApicOffset.Version), Read(ApicOffset.TaskPriority), Read(ApicOffset.ArbitrationPriority), Read(ApicOffset.ProcessorPriority))); DebugStub.Print("Timer LVT {0:x8} Thermal LVT {1:x8} " + "PerfCounts LVT {2:x8}\n", __arglist( Read(ApicOffset.LvtTimer), Read(ApicOffset.LvtThermalSensor), Read(ApicOffset.LvtPerfCounts))); DebugStub.Print("Lint0 LVT {0:x8} Lint1 LVT {1:x8}\n", __arglist( Read(ApicOffset.LvtLint0), Read(ApicOffset.LvtLint1))); DebugStub.Print("LvtError LVT {0:x8} Spurious LVT {1:x8} ESR {2:x2}\n", __arglist( Read(ApicOffset.LvtError), Read(ApicOffset.SpuriousIntVector), Read(ApicOffset.ErrorStatus) & 0xef)); }
public static void ReadCpuid(uint feature, out uint v0, out uint v1, out uint v2, out uint v3) { Isa.ReadCpuid(feature, out v0, out v1, out v2, out v3); }
public static void WalkStack() { Stacks.WalkStack(Isa.GetFramePointer()); }
private void PerformCollection(int currentThreadIndex, int generation) { // Clear the GCRequest bit (if necessary) before doing // anything that could cause a state transition. if (Transitions.HasGCRequest(currentThreadIndex)) { Transitions.ClearGCRequest(currentThreadIndex); } int startTicks = 0; bool enableGCTiming = VTable.enableGCTiming; if (enableGCTiming || VTable.enableFinalGCTiming) { VTable.enableGCTiming = false; startTicks = Environment.TickCount; if (enableGCTiming) { VTable.DebugPrint("[GC start: {0} bytes]\n", __arglist(TotalMemory)); } } #if SINGULARITY Tracing.Log(Tracing.Debug, "GC start"); #endif CollectorStatistics.Event(GCEvent.StopTheWorld); CurrentPhase = StopTheWorldPhase.Synchronizing; StopTheWorld(); CurrentPhase = StopTheWorldPhase.SingleThreaded; StartGCCycle(); #if SINGULARITY long preGcMemoryUsage = GC.GetTotalMemory(false); #if SINGULARITY_KERNEL #if THREAD_TIME_ACCOUNTING TimeSpan ticks = Thread.CurrentThread.ExecutionTime; TimeSpan ticks2 = SystemClock.KernelUpTime; #else TimeSpan ticks = SystemClock.KernelUpTime; #endif #elif SINGULARITY_PROCESS #if THREAD_TIME_ACCOUNTING TimeSpan ticks = ProcessService.GetThreadTime(); TimeSpan ticks2 = ProcessService.GetUpTime(); #else TimeSpan ticks = ProcessService.GetUpTime(); #endif #endif #endif //singularity #if SINGULARITY_KERNEL bool iflag = Processor.DisableInterrupts(); // Disable interrupts on other CPU's MpExecution.StopProcessorsForGC(); #endif #if SINGULARITY ulong beg = Isa.GetCycleCount(); #endif // Preparation GC.allocationGCInhibitCount++; // Verify the heap before GC if (VTable.enableGCVerify) { this.VerifyHeap(true); } // Invoke the chosen collector #if SINGULARITY Monitoring.Log(Monitoring.Provider.GC, (ushort)GarbageCollectorEvent.StartCollection); #endif this.CollectStopped(collectorThreadIndex, generation); #if SINGULARITY Monitoring.Log(Monitoring.Provider.GC, (ushort)GarbageCollectorEvent.EndCollection); #endif // Verify the heap after GC if (VTable.enableGCVerify) { this.VerifyHeap(false); } if (VTable.enableGCAccounting) { MemoryAccounting.Report(GC.gcType); } // Cleanup CollectorStatistics.Event(GCEvent.ResumeTheWorld); GC.allocationGCInhibitCount--; CurrentPhase = StopTheWorldPhase.Idle; #if SINGULARITY long postGcMemoryUsage = GC.GetTotalMemory(false); #endif if (enableGCTiming || VTable.enableFinalGCTiming) { int elapsedTicks = Environment.TickCount - startTicks; BaseCollector.RegisterPause(elapsedTicks); if (enableGCTiming) { VTable.DebugPrint("[GC end : {0} bytes, {1} ms]\n", __arglist(TotalMemory, elapsedTicks)); VTable.enableGCTiming = true; } } if (VTable.enableGCProfiling) { ulong totalMemory = (ulong)GC.GetTotalMemory(false); this.RegisterHeapSize(totalMemory); } ResumeTheWorld(); collectorThreadIndex = -1; #if SINGULARITY Tracing.Log(Tracing.Debug, "GC stop"); long pagesCollected = preGcMemoryUsage - postGcMemoryUsage; #if SINGULARITY_KERNEL #if THREAD_TIME_ACCOUNTING int procId = Thread.CurrentProcess.ProcessId; ticks = Thread.CurrentThread.ExecutionTime - ticks; ticks2 = SystemClock.KernelUpTime - ticks2; Process.kernelProcess.SetGcPerformanceCounters(ticks, (long)pagesCollected); #else ticks = SystemClock.KernelUpTime - ticks; #endif Thread.CurrentProcess.SetGcPerformanceCounters(ticks, (long)pagesCollected); #elif SINGULARITY_PROCESS #if THREAD_TIME_ACCOUNTING ushort procId = ProcessService.GetCurrentProcessId(); ticks = ProcessService.GetThreadTime() - ticks; ticks2 = ProcessService.GetUpTime() - ticks2; #else ticks = ProcessService.GetUpTime() - ticks; #endif ProcessService.SetGcPerformanceCounters(ticks, (long)pagesCollected); #endif #if DEBUG #if THREAD_TIME_ACCOUNTING DebugStub.WriteLine("~~~~~ StopTheWorld [collected pages={0:x8}, pid={1:x3}, ms(Thread)={2:d6}, ms(System)={3:d6}, procId={4}, tid={5}]", __arglist(pagesCollected, PageTable.processTag >> 16, ticks.Milliseconds, ticks2.Milliseconds, procId, Thread.GetCurrentThreadIndex() )); #endif #endif #endif #if SINGULARITY DebugStub.AddToPerfCounter(GC.perfCounter, Isa.GetCycleCount() - beg); #endif #if SINGULARITY_KERNEL // Resume interrupts on other CPU's MpExecution.ResumeProcessorsAfterGC(); Processor.RestoreInterrupts(iflag); #endif }
internal static unsafe ProcessorContext *GetCurrentProcessorContext() { unsafe { return((ProcessorContext *)Isa.GetCurrentCpu()); } }
internal static unsafe ThreadContext *GetCurrentThreadContext() { unsafe { return((ThreadContext *)Isa.GetCurrentThread()); } }
public static ulong ReadPmc(uint offset) { return(Isa.ReadPmc(offset)); }
public static bool AtKernelPrivilege() { return(!Isa.IsInUserMode()); }
public static ulong ReadMsr(uint offset) { return(Isa.ReadMsr(offset)); }