8 // Thread Dispatcher Header DebugActive Mask
10 #define DR_MASK(x) (1 << (x))
11 #define DR_REG_MASK 0x4F
14 // INT3 is 1 byte long
16 #define KD_BREAKPOINT_TYPE UCHAR
17 #define KD_BREAKPOINT_SIZE sizeof(UCHAR)
18 #define KD_BREAKPOINT_VALUE 0xCC
21 // Macros for getting and setting special purpose registers in portable code
23 #define KeGetContextPc(Context) \
26 #define KeSetContextPc(Context, ProgramCounter) \
27 ((Context)->Eip = (ProgramCounter))
29 #define KeGetTrapFramePc(TrapFrame) \
32 #define KiGetLinkedTrapFrame(x) \
33 (PKTRAP_FRAME)((x)->Edx)
35 #define KeGetContextReturnRegister(Context) \
38 #define KeSetContextReturnRegister(Context, ReturnValue) \
39 ((Context)->Eax = (ReturnValue))
42 // Macro to get trap and exception frame from a thread stack
44 #define KeGetTrapFrame(Thread) \
45 (PKTRAP_FRAME)((ULONG_PTR)((Thread)->InitialStack) - \
46 sizeof(KTRAP_FRAME) - \
49 #define KeGetExceptionFrame(Thread) \
53 // Macro to get context switches from the PRCB
54 // All architectures but x86 have it in the PRCB's KeContextSwitches
56 #define KeGetContextSwitches(Prcb) \
57 CONTAINING_RECORD(Prcb, KIPCR, PrcbData)->ContextSwitches
60 // Macro to get the second level cache size field name which differs between
61 // CISC and RISC architectures, as the former has unified I/D cache
63 #define KiGetSecondLevelDCacheSize() ((PKIPCR)KeGetPcr())->SecondLevelCacheSize
66 // Returns the Interrupt State from a Trap Frame.
67 // ON = TRUE, OFF = FALSE
69 #define KeGetTrapFrameInterruptState(TrapFrame) \
70 BooleanFlagOn((TrapFrame)->EFlags, EFLAGS_INTERRUPT_MASK)
73 // Flags for exiting a trap
75 #define KTE_SKIP_PM_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipPreviousMode = TRUE } }).Bits)
76 #define KTE_SKIP_SEG_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipSegments = TRUE } }).Bits)
77 #define KTE_SKIP_VOL_BIT (((KTRAP_EXIT_SKIP_BITS) { { .SkipVolatiles = TRUE } }).Bits)
79 typedef union _KTRAP_EXIT_SKIP_BITS
83 UCHAR SkipPreviousMode
:1;
85 UCHAR SkipVolatiles
:1;
89 } KTRAP_EXIT_SKIP_BITS
, *PKTRAP_EXIT_SKIP_BITS
;
93 // Flags used by the VDM/V8086 emulation engine for determining instruction prefixes
95 #define PFX_FLAG_ES 0x00000100
96 #define PFX_FLAG_CS 0x00000200
97 #define PFX_FLAG_SS 0x00000400
98 #define PFX_FLAG_DS 0x00000800
99 #define PFX_FLAG_FS 0x00001000
100 #define PFX_FLAG_GS 0x00002000
101 #define PFX_FLAG_OPER32 0x00004000
102 #define PFX_FLAG_ADDR32 0x00008000
103 #define PFX_FLAG_LOCK 0x00010000
104 #define PFX_FLAG_REPNE 0x00020000
105 #define PFX_FLAG_REP 0x00040000
110 // All VDM/V8086 opcode emulators have the same FASTCALL function definition.
111 // We need to keep 2 parameters while the original ASM implementation uses 4:
112 // TrapFrame, PrefixFlags, Eip, InstructionSize;
114 // We pass the trap frame, and prefix flags, in our two parameters.
116 // We then realize that since the smallest prefix flag is 0x100, this gives us
117 // a count of up to 0xFF. So we OR in the instruction size with the prefix flags
119 // We further realize that we always have access to EIP from the trap frame, and
120 // that if we want the *current instruction* EIP, we simply have to add the
121 // instruction size *MINUS ONE*, and that gives us the EIP we should be looking
122 // at now, so we don't need to use the stack to push this parameter.
124 // We actually only care about the *current instruction* EIP in one location,
125 // so although it may be slightly more expensive to re-calculate the EIP one
126 // more time, this way we don't redefine ALL opcode handlers to have 3 parameters,
127 // which would be forcing stack usage in all other scenarios.
129 #define KiVdmSetVdmEFlags(x) InterlockedOr((PLONG)KiNtVdmState, (x));
130 #define KiVdmClearVdmEFlags(x) InterlockedAnd((PLONG)KiNtVdmState, ~(x))
131 #define KiCallVdmHandler(x) KiVdmOpcode##x(TrapFrame, Flags)
132 #define KiCallVdmPrefixHandler(x) KiVdmOpcodePrefix(TrapFrame, Flags | x)
133 #define KiVdmUnhandledOpcode(x) \
136 KiVdmOpcode##x(IN PKTRAP_FRAME TrapFrame, \
139 /* Not yet handled */ \
140 UNIMPLEMENTED_DBGBREAK(); \
144 C_ASSERT(NPX_FRAME_LENGTH
== sizeof(FX_SAVE_AREA
));
149 typedef struct _KV86_FRAME
154 } KV86_FRAME
, *PKV86_FRAME
;
157 // Virtual Stack Frame
159 typedef struct _KV8086_STACK_FRAME
161 KTRAP_FRAME TrapFrame
;
162 FX_SAVE_AREA NpxArea
;
164 } KV8086_STACK_FRAME
, *PKV8086_STACK_FRAME
;
167 // Large Pages Support
169 typedef struct _LARGE_IDENTITY_MAP
171 PHARDWARE_PTE TopLevelDirectory
;
173 ULONG_PTR StartAddress
;
176 } LARGE_IDENTITY_MAP
, *PLARGE_IDENTITY_MAP
;
178 /* Diable interrupts and return whether they were enabled before */
181 KeDisableInterrupts(VOID
)
186 /* Get EFLAGS and check if the interrupt bit is set */
187 Flags
= __readeflags();
188 Return
= (Flags
& EFLAGS_INTERRUPT_MASK
) ? TRUE
: FALSE
;
190 /* Disable interrupts */
195 /* Restore previous interrupt state */
198 KeRestoreInterrupts(BOOLEAN WereEnabled
)
200 if (WereEnabled
) _enable();
204 // Registers an interrupt handler with an IDT vector
208 KeRegisterInterruptHandler(IN ULONG Vector
,
213 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
216 // Get the entry from the HAL
218 Entry
= HalVectorToIDTEntry(Vector
);
219 Address
= PtrToUlong(Handler
);
224 Pcr
->IDT
[Entry
].ExtendedOffset
= (USHORT
)(Address
>> 16);
225 Pcr
->IDT
[Entry
].Offset
= (USHORT
)Address
;
229 // Returns the registered interrupt handler for a given IDT vector
233 KeQueryInterruptHandler(IN ULONG Vector
)
235 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
239 // Get the entry from the HAL
241 Entry
= HalVectorToIDTEntry(Vector
);
244 // Read the entry from the IDT
246 return (PVOID
)(((Pcr
->IDT
[Entry
].ExtendedOffset
<< 16) & 0xFFFF0000) |
247 (Pcr
->IDT
[Entry
].Offset
& 0xFFFF));
251 // Invalidates the TLB entry for a specified address
255 KeInvalidateTlbEntry(IN PVOID Address
)
257 /* Invalidate the TLB entry for this address */
263 KeFlushProcessTb(VOID
)
265 /* Flush the TLB by resetting CR3 */
266 __writecr3(__readcr3());
271 KeSweepICache(IN PVOID BaseAddress
,
275 // Always sweep the whole cache
277 UNREFERENCED_PARAMETER(BaseAddress
);
278 UNREFERENCED_PARAMETER(FlushSize
);
284 KeGetCurrentThread(VOID
)
286 /* Return the current thread */
287 return ((PKIPCR
)KeGetPcr())->PrcbData
.CurrentThread
;
292 KiRundownThread(IN PKTHREAD Thread
)
295 /* Check if this is the NPX Thread */
296 if (KeGetCurrentPrcb()->NpxThread
== Thread
)
299 KeGetCurrentPrcb()->NpxThread
= NULL
;
309 Ke386SetGdtEntryBase(PKGDTENTRY GdtEntry
, PVOID BaseAddress
)
311 GdtEntry
->BaseLow
= (USHORT
)((ULONG_PTR
)BaseAddress
& 0xFFFF);
312 GdtEntry
->HighWord
.Bytes
.BaseMid
= (UCHAR
)((ULONG_PTR
)BaseAddress
>> 16);
313 GdtEntry
->HighWord
.Bytes
.BaseHi
= (UCHAR
)((ULONG_PTR
)BaseAddress
>> 24);
318 KiSetTebBase(PKPCR Pcr
, PVOID TebAddress
)
320 Pcr
->NtTib
.Self
= TebAddress
;
321 Ke386SetGdtEntryBase(&Pcr
->GDT
[KGDT_R3_TEB
/ sizeof(KGDTENTRY
)], TebAddress
);
341 KiGetCacheInformation(VOID
);
353 KiIsNpxErrataPresent(
360 KiSetProcessorType(VOID
);
365 KiGetFeatureBits(VOID
);
369 KiThreadStartup(VOID
);
373 Ke386GetGdtEntryThread(
376 IN PKGDTENTRY Descriptor
382 IN FLOATING_SAVE_AREA
*SaveArea
388 IN PKTRAP_FRAME TrapFrame
393 Ki386SetupAndExitToV86Mode(
407 Ki386EnableGlobalPage(
414 Ki386EnableTargetLargePage(
420 Ki386CreateIdentityMap(
421 IN PLARGE_IDENTITY_MAP IdentityMap
,
428 Ki386FreeIdentityMap(
429 IN PLARGE_IDENTITY_MAP IdentityMap
434 Ki386EnableCurrentLargePage(
435 IN ULONG_PTR StartAddress
,
442 KiI386PentiumLockErrataFixup(
463 KiAmdK6InitializeMTRR(
470 KiRestoreFastSyscallReturnState(
491 Ki386EnableXMMIExceptions(
498 IN PKTRAP_FRAME TrapFrame
503 VdmDispatchPageFault(
504 _In_ PKTRAP_FRAME TrapFrame
510 IN PKTRAP_FRAME TrapFrame
,
516 Ki386HandleOpcodeV86(
517 IN PKTRAP_FRAME TrapFrame
524 IN PKTRAP_FRAME TrapFrame
529 Ki386BiosCallReturnAddress(
530 IN PKTRAP_FRAME TrapFrame
536 IN PKTRAP_FRAME TrapFrame
542 KiDispatchExceptionFromTrapFrame(
545 IN ULONG_PTR Address
,
546 IN ULONG ParameterCount
,
547 IN ULONG_PTR Parameter1
,
548 IN ULONG_PTR Parameter2
,
549 IN ULONG_PTR Parameter3
,
550 IN PKTRAP_FRAME TrapFrame
555 KiConvertToGuiThread(
560 // Global x86 only Kernel data
562 extern PVOID Ki386IopmSaveArea
;
563 extern ULONG KeI386EFlagsAndMaskV86
;
564 extern ULONG KeI386EFlagsOrMaskV86
;
565 extern BOOLEAN KeI386VirtualIntExtensions
;
566 extern KIDTENTRY KiIdt
[MAXIMUM_IDTVECTOR
+1];
567 extern KDESCRIPTOR KiIdtDescriptor
;
568 extern BOOLEAN KiI386PentiumLockErrataPresent
;
569 extern ULONG KeI386NpxPresent
;
570 extern ULONG KeI386XMMIPresent
;
571 extern ULONG KeI386FxsrPresent
;
572 extern ULONG KiMXCsrMask
;
573 extern ULONG KeI386CpuType
;
574 extern ULONG KeI386CpuStep
;
575 extern ULONG KiFastSystemCallDisable
;
576 extern UCHAR KiDebugRegisterTrapOffsets
[9];
577 extern UCHAR KiDebugRegisterContextOffsets
[9];
578 extern DECLSPEC_NORETURN VOID __cdecl
KiTrap02(VOID
);
579 extern VOID __cdecl
KiTrap08(VOID
);
580 extern VOID __cdecl
KiTrap13(VOID
);
581 extern VOID __cdecl
KiFastCallEntry(VOID
);
582 extern VOID NTAPI
ExpInterlockedPopEntrySListFault(VOID
);
583 extern VOID NTAPI
ExpInterlockedPopEntrySListResume(VOID
);
584 extern VOID __cdecl
CopyParams(VOID
);
585 extern VOID __cdecl
ReadBatch(VOID
);
586 extern CHAR KiSystemCallExitBranch
[];
587 extern CHAR KiSystemCallExit
[];
588 extern CHAR KiSystemCallExit2
[];
596 // Returns a thread's FPU save area
600 KiGetThreadNpxArea(IN PKTHREAD Thread
)
602 ASSERT((ULONG_PTR
)Thread
->InitialStack
% 16 == 0);
603 return (PFX_SAVE_AREA
)((ULONG_PTR
)Thread
->InitialStack
- sizeof(FX_SAVE_AREA
));
607 // Sanitizes a selector
611 Ke386SanitizeSeg(IN ULONG Cs
,
612 IN KPROCESSOR_MODE Mode
)
615 // Check if we're in kernel-mode, and force CPL 0 if so.
616 // Otherwise, force CPL 3.
618 return ((Mode
== KernelMode
) ?
619 (Cs
& (0xFFFF & ~RPL_MASK
)) :
620 (RPL_MASK
| (Cs
& 0xFFFF)));
628 Ke386SanitizeFlags(IN ULONG Eflags
,
629 IN KPROCESSOR_MODE Mode
)
632 // Check if we're in kernel-mode, and sanitize EFLAGS if so.
633 // Otherwise, also force interrupt mask on.
635 return ((Mode
== KernelMode
) ?
636 (Eflags
& (EFLAGS_USER_SANITIZE
| EFLAGS_INTERRUPT_MASK
)) :
637 (EFLAGS_INTERRUPT_MASK
| (Eflags
& EFLAGS_USER_SANITIZE
)));
641 // Sanitizes a Debug Register
645 Ke386SanitizeDr(IN PVOID DrAddress
,
646 IN KPROCESSOR_MODE Mode
)
649 // Check if we're in kernel-mode, and return the address directly if so.
650 // Otherwise, make sure it's not inside the kernel-mode address space.
651 // If it is, then clear the address.
653 return ((Mode
== KernelMode
) ? DrAddress
:
654 (DrAddress
<= MM_HIGHEST_USER_ADDRESS
) ? DrAddress
: 0);
658 // Exception with no arguments
663 KiDispatchException0Args(IN NTSTATUS Code
,
664 IN ULONG_PTR Address
,
665 IN PKTRAP_FRAME TrapFrame
)
667 /* Helper for exceptions with no arguments */
668 KiDispatchExceptionFromTrapFrame(Code
, 0, Address
, 0, 0, 0, 0, TrapFrame
);
672 // Exception with one argument
677 KiDispatchException1Args(IN NTSTATUS Code
,
678 IN ULONG_PTR Address
,
680 IN PKTRAP_FRAME TrapFrame
)
682 /* Helper for exceptions with no arguments */
683 KiDispatchExceptionFromTrapFrame(Code
, 0, Address
, 1, P1
, 0, 0, TrapFrame
);
687 // Exception with two arguments
692 KiDispatchException2Args(IN NTSTATUS Code
,
693 IN ULONG_PTR Address
,
696 IN PKTRAP_FRAME TrapFrame
)
698 /* Helper for exceptions with no arguments */
699 KiDispatchExceptionFromTrapFrame(Code
, 0, Address
, 2, P1
, P2
, 0, TrapFrame
);
703 // Performs a system call
707 * This sequence does a RtlCopyMemory(Stack - StackBytes, Arguments, StackBytes)
708 * and then calls the function associated with the system call.
710 * It's done in assembly for two reasons: we need to muck with the stack,
711 * and the call itself restores the stack back for us. The only way to do
712 * this in C is to do manual C handlers for every possible number of args on
713 * the stack, and then have the handler issue a call by pointer. This is
714 * wasteful since it'll basically push the values twice and require another
715 * level of call indirection.
717 * The ARM kernel currently does this, but it should probably be changed
718 * later to function like this as well.
724 KiSystemCallTrampoline(IN PVOID Handler
,
733 "movl %%esp, %%edi\n\t"
743 : "%esp", "%esi", "%edi"
747 #elif defined(_MSC_VER)
750 KiSystemCallTrampoline(IN PVOID Handler
,
765 /* Return with result in EAX */
768 #error Unknown Compiler
773 // Checks for pending APCs
777 KiCheckForApcDelivery(IN PKTRAP_FRAME TrapFrame
)
782 /* Check for V8086 or user-mode trap */
783 if ((TrapFrame
->EFlags
& EFLAGS_V86_MASK
) || (KiUserTrap(TrapFrame
)))
786 Thread
= KeGetCurrentThread();
789 /* Turn off the alerted state for kernel mode */
790 Thread
->Alerted
[KernelMode
] = FALSE
;
792 /* Are there pending user APCs? */
793 if (!Thread
->ApcState
.UserApcPending
) break;
795 /* Raise to APC level and enable interrupts */
796 OldIrql
= KfRaiseIrql(APC_LEVEL
);
800 KiDeliverApc(UserMode
, NULL
, TrapFrame
);
802 /* Restore IRQL and disable interrupts once again */
803 KfLowerIrql(OldIrql
);
810 // Switches from boot loader to initial kernel stack
815 KiSwitchToBootStack(IN ULONG_PTR InitialStack
)
817 INIT_FUNCTION VOID NTAPI
KiSystemStartupBootStack(VOID
);
819 /* We have to switch to a new stack before continuing kernel initialization */
826 "jmp _KiSystemStartupBootStack@0"
829 "i"(NPX_FRAME_LENGTH
+ KTRAP_FRAME_ALIGN
+ KTRAP_FRAME_LENGTH
),
830 "i"(CR0_EM
| CR0_TS
| CR0_MP
),
831 "p"(KiSystemStartupBootStack
)
834 #elif defined(_MSC_VER)
837 mov esp
, InitialStack
838 sub esp
, (NPX_FRAME_LENGTH
+ KTRAP_FRAME_ALIGN
+ KTRAP_FRAME_LENGTH
)
839 push (CR0_EM
| CR0_TS
| CR0_MP
)
840 jmp KiSystemStartupBootStack
843 #error Unknown Compiler
848 // Emits the iret instruction for C code
855 #if defined(__GNUC__)
860 #elif defined(_MSC_VER)
866 #error Unsupported compiler
872 // Normally this is done by the HAL, but on x86 as an optimization, the kernel
873 // initiates the end by calling back into the HAL and exiting the trap here.
877 KiEndInterrupt(IN KIRQL Irql
,
878 IN PKTRAP_FRAME TrapFrame
)
880 /* Disable interrupts and end the interrupt */
882 HalEndSystemInterrupt(Irql
, TrapFrame
);
884 /* Exit the interrupt */
885 KiEoiHelper(TrapFrame
);
895 extern ULONGLONG BootCyclesEnd
, BootCycles
;
896 BootCyclesEnd
= __rdtsc();
897 DbgPrint("Boot took %I64u cycles!\n", BootCyclesEnd
- BootCycles
);
898 DbgPrint("Interrupts: %u System Calls: %u Context Switches: %u\n",
899 KeGetCurrentPrcb()->InterruptCount
,
900 KeGetCurrentPrcb()->KeSystemCalls
,
901 KeGetContextSwitches(KeGetCurrentPrcb()));
906 KiGetUserModeStackAddress(void)
908 return &(KeGetCurrentThread()->TrapFrame
->HardwareEsp
);