2 * PROJECT: ReactOS Kernel
3 * LICENSE: GPL - See COPYING in the top level directory
4 * FILE: ntoskrnl/ke/i386/cpu.c
5 * PURPOSE: Routines for CPU-level support
6 * PROGRAMMERS: Alex Ionescu (alex.ionescu@reactos.org)
9 /* INCLUDES *****************************************************************/
15 /* GLOBALS *******************************************************************/
17 /* The TSS to use for Double Fault Traps (INT 0x9) */
18 UCHAR KiDoubleFaultTSS
[KTSS_IO_MAPS
];
20 /* The TSS to use for NMI Fault Traps (INT 0x2) */
21 UCHAR KiNMITSS
[KTSS_IO_MAPS
];
23 /* CPU Features and Flags */
26 ULONG KeProcessorArchitecture
;
27 ULONG KeProcessorLevel
;
28 ULONG KeProcessorRevision
;
30 ULONG KiFastSystemCallDisable
;
31 ULONG KeI386NpxPresent
= 0;
32 ULONG KiMXCsrMask
= 0;
33 ULONG MxcsrFeatureMask
= 0;
34 ULONG KeI386XMMIPresent
= 0;
35 ULONG KeI386FxsrPresent
= 0;
36 ULONG KeI386MachineType
;
37 ULONG Ke386Pae
= FALSE
;
38 ULONG Ke386NoExecute
= FALSE
;
39 ULONG KeLargestCacheLine
= 0x40;
40 ULONG KeDcacheFlushCount
= 0;
41 ULONG KeIcacheFlushCount
= 0;
42 ULONG KiDmaIoCoherency
= 0;
43 ULONG KePrefetchNTAGranularity
= 32;
44 CHAR KeNumberProcessors
;
45 KAFFINITY KeActiveProcessors
= 1;
46 BOOLEAN KiI386PentiumLockErrataPresent
;
47 BOOLEAN KiSMTProcessorsPresent
;
49 /* The distance between SYSEXIT and IRETD return modes */
50 UCHAR KiSystemCallExitAdjust
;
52 /* The offset that was applied -- either 0 or the value above */
53 UCHAR KiSystemCallExitAdjusted
;
55 /* Whether the adjustment was already done once */
56 BOOLEAN KiFastCallCopyDoneOnce
;
59 volatile LONG KiTbFlushTimeStamp
;
62 static const CHAR CmpIntelID
[] = "GenuineIntel";
63 static const CHAR CmpAmdID
[] = "AuthenticAMD";
64 static const CHAR CmpCyrixID
[] = "CyrixInstead";
65 static const CHAR CmpTransmetaID
[] = "GenuineTMx86";
66 static const CHAR CmpCentaurID
[] = "CentaurHauls";
67 static const CHAR CmpRiseID
[] = "RiseRiseRise";
69 /* SUPPORT ROUTINES FOR MSVC COMPATIBILITY ***********************************/
73 CPUID(IN ULONG InfoType
,
74 OUT PULONG CpuInfoEax
,
75 OUT PULONG CpuInfoEbx
,
76 OUT PULONG CpuInfoEcx
,
77 OUT PULONG CpuInfoEdx
)
81 /* Perform the CPUID Operation */
82 __cpuid((int*)CpuInfo
, InfoType
);
84 /* Return the results */
85 *CpuInfoEax
= CpuInfo
[0];
86 *CpuInfoEbx
= CpuInfo
[1];
87 *CpuInfoEcx
= CpuInfo
[2];
88 *CpuInfoEdx
= CpuInfo
[3];
93 WRMSR(IN ULONG Register
,
96 /* Write to the MSR */
97 __writemsr(Register
, Value
);
102 RDMSR(IN ULONG Register
)
104 /* Read from the MSR */
105 return __readmsr(Register
);
108 /* NSC/Cyrix CPU configuration register index */
109 #define CX86_CCR1 0xc1
111 /* NSC/Cyrix CPU indexed register access macros */
112 #define getCx86(reg) ({ WRITE_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x22,(reg)); READ_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x23); })
114 #define setCx86(reg, data) do { \
115 WRITE_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x22,(reg)); \
116 WRITE_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x23,(data)); \
119 /* FUNCTIONS *****************************************************************/
124 KiSetProcessorType(VOID
)
126 ULONG EFlags
, NewEFlags
;
128 ULONG Stepping
, Type
;
130 /* Start by assuming no CPUID data */
131 KeGetCurrentPrcb()->CpuID
= 0;
134 EFlags
= __readeflags();
136 /* XOR out the ID bit and update EFlags */
137 NewEFlags
= EFlags
^ EFLAGS_ID
;
138 __writeeflags(NewEFlags
);
140 /* Get them back and see if they were modified */
141 NewEFlags
= __readeflags();
142 if (NewEFlags
!= EFlags
)
144 /* The modification worked, so CPUID exists. Set the ID Bit again. */
146 __writeeflags(EFlags
);
148 /* Peform CPUID 0 to see if CPUID 1 is supported */
149 CPUID(0, &Reg
, &Dummy
, &Dummy
, &Dummy
);
153 CPUID(1, &Reg
, &Dummy
, &Dummy
, &Dummy
);
156 * Get the Stepping and Type. The stepping contains both the
157 * Model and the Step, while the Type contains the returned Type.
158 * We ignore the family.
160 * For the stepping, we convert this: zzzzzzxy into this: x0y
162 Stepping
= Reg
& 0xF0;
164 Stepping
+= (Reg
& 0xFF);
169 /* Save them in the PRCB */
170 KeGetCurrentPrcb()->CpuID
= TRUE
;
171 KeGetCurrentPrcb()->CpuType
= (UCHAR
)Type
;
172 KeGetCurrentPrcb()->CpuStep
= (USHORT
)Stepping
;
176 DPRINT1("CPUID Support lacking\n");
181 DPRINT1("CPUID Support lacking\n");
185 __writeeflags(EFlags
);
193 PKPRCB Prcb
= KeGetCurrentPrcb();
197 /* Assume no Vendor ID and fail if no CPUID Support. */
198 Prcb
->VendorString
[0] = 0;
199 if (!Prcb
->CpuID
) return 0;
201 /* Get the Vendor ID and null-terminate it */
202 CPUID(0, &Vendor
[0], &Vendor
[1], &Vendor
[2], &Vendor
[3]);
205 /* Re-arrange vendor string */
207 Vendor
[2] = Vendor
[3];
210 /* Copy it to the PRCB and null-terminate it again */
211 RtlCopyMemory(Prcb
->VendorString
,
213 sizeof(Prcb
->VendorString
) - sizeof(CHAR
));
214 Prcb
->VendorString
[sizeof(Prcb
->VendorString
) - sizeof(CHAR
)] = ANSI_NULL
;
216 /* Now check the CPU Type */
217 if (!strcmp(Prcb
->VendorString
, CmpIntelID
))
221 else if (!strcmp(Prcb
->VendorString
, CmpAmdID
))
225 else if (!strcmp(Prcb
->VendorString
, CmpCyrixID
))
227 DPRINT1("Cyrix CPU support not fully tested!\n");
230 else if (!strcmp(Prcb
->VendorString
, CmpTransmetaID
))
232 DPRINT1("Transmeta CPU support not fully tested!\n");
233 return CPU_TRANSMETA
;
235 else if (!strcmp(Prcb
->VendorString
, CmpCentaurID
))
237 DPRINT1("Centaur CPU support not fully tested!\n");
240 else if (!strcmp(Prcb
->VendorString
, CmpRiseID
))
242 DPRINT1("Rise CPU support not fully tested!\n");
253 KiGetFeatureBits(VOID
)
255 PKPRCB Prcb
= KeGetCurrentPrcb();
257 ULONG FeatureBits
= KF_WORKING_PTE
;
258 ULONG Reg
[4], Dummy
, Ccr1
;
259 BOOLEAN ExtendedCPUID
= TRUE
;
260 ULONG CpuFeatures
= 0;
262 /* Get the Vendor ID */
263 Vendor
= KiGetCpuVendor();
265 /* Make sure we got a valid vendor ID at least. */
266 if (!Vendor
) return FeatureBits
;
268 /* Get the CPUID Info. Features are in Reg[3]. */
269 CPUID(1, &Reg
[0], &Reg
[1], &Dummy
, &Reg
[3]);
271 /* Set the initial APIC ID */
272 Prcb
->InitialApicId
= (UCHAR
)(Reg
[1] >> 24);
279 /* Check if it's a P6 */
280 if (Prcb
->CpuType
== 6)
282 /* Perform the special sequence to get the MicroCode Signature */
284 CPUID(1, &Dummy
, &Dummy
, &Dummy
, &Dummy
);
285 Prcb
->UpdateSignature
.QuadPart
= RDMSR(0x8B);
287 else if (Prcb
->CpuType
== 5)
289 /* On P5, enable workaround for the LOCK errata. */
290 KiI386PentiumLockErrataPresent
= TRUE
;
293 /* Check for broken P6 with bad SMP PTE implementation */
294 if (((Reg
[0] & 0x0FF0) == 0x0610 && (Reg
[0] & 0x000F) <= 0x9) ||
295 ((Reg
[0] & 0x0FF0) == 0x0630 && (Reg
[0] & 0x000F) <= 0x4))
297 /* Remove support for correct PTE support. */
298 FeatureBits
&= ~KF_WORKING_PTE
;
301 /* Check if the CPU is too old to support SYSENTER */
302 if ((Prcb
->CpuType
< 6) ||
303 ((Prcb
->CpuType
== 6) && (Prcb
->CpuStep
< 0x0303)))
309 /* Set the current features */
310 CpuFeatures
= Reg
[3];
317 /* Check if this is a K5 or K6. (family 5) */
318 if ((Reg
[0] & 0x0F00) == 0x0500)
320 /* Get the Model Number */
321 switch (Reg
[0] & 0x00F0)
323 /* Model 1: K5 - 5k86 (initial models) */
326 /* Check if this is Step 0 or 1. They don't support PGE */
327 if ((Reg
[0] & 0x000F) > 0x03) break;
329 /* Model 0: K5 - SSA5 */
332 /* Model 0 doesn't support PGE at all. */
339 /* K6-2, Step 8 and over have support for MTRR. */
340 if ((Reg
[0] & 0x000F) >= 0x8) FeatureBits
|= KF_AMDK6MTRR
;
344 Model D: K6-2+, K6-III+ */
348 FeatureBits
|= KF_AMDK6MTRR
;
352 else if((Reg
[0] & 0x0F00) < 0x0500)
354 /* Families below 5 don't support PGE, PSE or CMOV at all */
355 Reg
[3] &= ~(0x08 | 0x2000 | 0x8000);
357 /* They also don't support advanced CPUID functions. */
358 ExtendedCPUID
= FALSE
;
361 /* Set the current features */
362 CpuFeatures
= Reg
[3];
369 /* Workaround the "COMA" bug on 6x family of Cyrix CPUs */
370 if (Prcb
->CpuType
== 6 &&
374 Ccr1
= getCx86(CX86_CCR1
);
376 /* Enable the NO_LOCK bit */
379 /* Set the new CCR1 value */
380 setCx86(CX86_CCR1
, Ccr1
);
383 /* Set the current features */
384 CpuFeatures
= Reg
[3];
391 /* Enable CMPXCHG8B if the family (>= 5), model and stepping (>= 4.2) support it */
392 if ((Reg
[0] & 0x0FFF) >= 0x0542)
394 WRMSR(0x80860004, RDMSR(0x80860004) | 0x0100);
395 FeatureBits
|= KF_CMPXCHG8B
;
400 /* Centaur, IDT, Rise and VIA CPUs */
404 /* These CPUs don't report the presence of CMPXCHG8B through CPUID.
405 However, this feature exists and operates properly without any additional steps. */
406 FeatureBits
|= KF_CMPXCHG8B
;
411 /* Convert all CPUID Feature bits into our format */
412 if (CpuFeatures
& 0x00000002) FeatureBits
|= KF_V86_VIS
| KF_CR4
;
413 if (CpuFeatures
& 0x00000008) FeatureBits
|= KF_LARGE_PAGE
| KF_CR4
;
414 if (CpuFeatures
& 0x00000010) FeatureBits
|= KF_RDTSC
;
415 if (CpuFeatures
& 0x00000100) FeatureBits
|= KF_CMPXCHG8B
;
416 if (CpuFeatures
& 0x00000800) FeatureBits
|= KF_FAST_SYSCALL
;
417 if (CpuFeatures
& 0x00001000) FeatureBits
|= KF_MTRR
;
418 if (CpuFeatures
& 0x00002000) FeatureBits
|= KF_GLOBAL_PAGE
| KF_CR4
;
419 if (CpuFeatures
& 0x00008000) FeatureBits
|= KF_CMOV
;
420 if (CpuFeatures
& 0x00010000) FeatureBits
|= KF_PAT
;
421 if (CpuFeatures
& 0x00200000) FeatureBits
|= KF_DTS
;
422 if (CpuFeatures
& 0x00800000) FeatureBits
|= KF_MMX
;
423 if (CpuFeatures
& 0x01000000) FeatureBits
|= KF_FXSR
;
424 if (CpuFeatures
& 0x02000000) FeatureBits
|= KF_XMMI
;
425 if (CpuFeatures
& 0x04000000) FeatureBits
|= KF_XMMI64
;
427 /* Check if the CPU has hyper-threading */
428 if (CpuFeatures
& 0x10000000)
430 /* Set the number of logical CPUs */
431 Prcb
->LogicalProcessorsPerPhysicalProcessor
= (UCHAR
)(Reg
[1] >> 16);
432 if (Prcb
->LogicalProcessorsPerPhysicalProcessor
> 1)
434 /* We're on dual-core */
435 KiSMTProcessorsPresent
= TRUE
;
440 /* We only have a single CPU */
441 Prcb
->LogicalProcessorsPerPhysicalProcessor
= 1;
444 /* Check if CPUID 0x80000000 is supported */
448 CPUID(0x80000000, &Reg
[0], &Dummy
, &Dummy
, &Dummy
);
449 if ((Reg
[0] & 0xffffff00) == 0x80000000)
451 /* Check if CPUID 0x80000001 is supported */
452 if (Reg
[0] >= 0x80000001)
454 /* Check which extended features are available. */
455 CPUID(0x80000001, &Dummy
, &Dummy
, &Dummy
, &Reg
[3]);
457 /* Check if NX-bit is supported */
458 if (Reg
[3] & 0x00100000) FeatureBits
|= KF_NX_BIT
;
460 /* Now handle each features for each CPU Vendor */
465 if (Reg
[3] & 0x80000000) FeatureBits
|= KF_3DNOW
;
472 /* Return the Feature Bits */
479 KiGetCacheInformation(VOID
)
481 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
483 ULONG Data
[4], Dummy
;
484 ULONG CacheRequests
= 0, i
;
485 ULONG CurrentRegister
;
487 ULONG Size
, Associativity
= 0, CacheLine
= 64, CurrentSize
= 0;
488 BOOLEAN FirstPass
= TRUE
;
490 /* Set default L2 size */
491 Pcr
->SecondLevelCacheSize
= 0;
493 /* Get the Vendor ID and make sure we support CPUID */
494 Vendor
= KiGetCpuVendor();
497 /* Check the Vendor ID */
500 /* Handle Intel case */
503 /*Check if we support CPUID 2 */
504 CPUID(0, &Data
[0], &Dummy
, &Dummy
, &Dummy
);
507 /* We need to loop for the number of times CPUID will tell us to */
510 /* Do the CPUID call */
511 CPUID(2, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
513 /* Check if it was the first call */
517 * The number of times to loop is the first byte. Read
518 * it and then destroy it so we don't get confused.
520 CacheRequests
= Data
[0] & 0xFF;
521 Data
[0] &= 0xFFFFFF00;
523 /* Don't go over this again */
527 /* Loop all 4 registers */
528 for (i
= 0; i
< 4; i
++)
530 /* Get the current register */
531 CurrentRegister
= Data
[i
];
534 * If the upper bit is set, then this register should
537 if (CurrentRegister
& 0x80000000) continue;
539 /* Keep looping for every byte inside this register */
540 while (CurrentRegister
)
542 /* Read a byte, skip a byte. */
543 RegisterByte
= (UCHAR
)(CurrentRegister
& 0xFF);
544 CurrentRegister
>>= 8;
545 if (!RegisterByte
) continue;
548 * Valid values are from 0x40 (0 bytes) to 0x49
549 * (32MB), or from 0x80 to 0x89 (same size but
552 if (((RegisterByte
> 0x40) && (RegisterByte
<= 0x47)) ||
553 ((RegisterByte
> 0x78) && (RegisterByte
<= 0x7C)) ||
554 ((RegisterByte
> 0x80) && (RegisterByte
<= 0x85)))
556 /* Compute associativity */
558 if (RegisterByte
>= 0x79) Associativity
= 8;
560 /* Mask out only the first nibble */
561 RegisterByte
&= 0x07;
563 /* Check if this cache is bigger than the last */
564 Size
= 0x10000 << RegisterByte
;
565 if ((Size
/ Associativity
) > CurrentSize
)
567 /* Set the L2 Cache Size and Associativity */
568 CurrentSize
= Size
/ Associativity
;
569 Pcr
->SecondLevelCacheSize
= Size
;
570 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
573 else if ((RegisterByte
> 0x21) && (RegisterByte
<= 0x29))
575 /* Set minimum cache line size */
576 if (CacheLine
< 128) CacheLine
= 128;
578 /* Hard-code size/associativity */
580 switch (RegisterByte
)
604 /* Check if this cache is bigger than the last */
605 if ((Size
/ Associativity
) > CurrentSize
)
607 /* Set the L2 Cache Size and Associativity */
608 CurrentSize
= Size
/ Associativity
;
609 Pcr
->SecondLevelCacheSize
= Size
;
610 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
613 else if (((RegisterByte
> 0x65) && (RegisterByte
< 0x69)) ||
614 (RegisterByte
== 0x2C) || (RegisterByte
== 0xF0))
616 /* Indicates L1 cache line of 64 bytes */
617 KePrefetchNTAGranularity
= 64;
619 else if (RegisterByte
== 0xF1)
621 /* Indicates L1 cache line of 128 bytes */
622 KePrefetchNTAGranularity
= 128;
624 else if (((RegisterByte
>= 0x4A) && (RegisterByte
<= 0x4C)) ||
625 (RegisterByte
== 0x78) ||
626 (RegisterByte
== 0x7D) ||
627 (RegisterByte
== 0x7F) ||
628 (RegisterByte
== 0x86) ||
629 (RegisterByte
== 0x87))
631 /* Set minimum cache line size */
632 if (CacheLine
< 64) CacheLine
= 64;
634 /* Hard-code size/associativity */
635 switch (RegisterByte
)
638 Size
= 4 * 1024 * 1024;
643 Size
= 6 * 1024 * 1024;
648 Size
= 8 * 1024 * 1024;
653 Size
= 1 * 1024 * 1024;
658 Size
= 2 * 1024 * 1024;
673 Size
= 1 * 1024 * 1024;
682 /* Check if this cache is bigger than the last */
683 if ((Size
/ Associativity
) > CurrentSize
)
685 /* Set the L2 Cache Size and Associativity */
686 CurrentSize
= Size
/ Associativity
;
687 Pcr
->SecondLevelCacheSize
= Size
;
688 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
693 } while (--CacheRequests
);
699 /* Check if we support CPUID 0x80000005 */
700 CPUID(0x80000000, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
701 if (Data
[0] >= 0x80000006)
703 /* Get L1 size first */
704 CPUID(0x80000005, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
705 KePrefetchNTAGranularity
= Data
[2] & 0xFF;
707 /* Check if we support CPUID 0x80000006 */
708 CPUID(0x80000000, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
709 if (Data
[0] >= 0x80000006)
711 /* Get 2nd level cache and tlb size */
712 CPUID(0x80000006, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
714 /* Cache line size */
715 CacheLine
= Data
[2] & 0xFF;
717 /* Hardcode associativity */
718 RegisterByte
= Data
[2] >> 12;
719 switch (RegisterByte
)
744 Size
= (Data
[2] >> 16) << 10;
746 /* Hack for Model 6, Steping 300 */
747 if ((KeGetCurrentPrcb()->CpuType
== 6) &&
748 (KeGetCurrentPrcb()->CpuStep
== 0x300))
750 /* Stick 64K in there */
754 /* Set the L2 Cache Size and associativity */
755 Pcr
->SecondLevelCacheSize
= Size
;
756 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
770 /* Set the cache line */
771 if (CacheLine
> KeLargestCacheLine
) KeLargestCacheLine
= CacheLine
;
772 DPRINT1("Prefetch Cache: %d bytes\tL2 Cache: %d bytes\tL2 Cache Line: %d bytes\tL2 Cache Associativity: %d\n",
773 KePrefetchNTAGranularity
,
774 Pcr
->SecondLevelCacheSize
,
776 Pcr
->SecondLevelCacheAssociativity
);
786 /* Save current CR0 */
789 /* If this is a 486, enable Write-Protection */
790 if (KeGetCurrentPrcb()->CpuType
> 3) Cr0
|= CR0_WP
;
799 KiInitializeTSS2(IN PKTSS Tss
,
800 IN PKGDTENTRY TssEntry OPTIONAL
)
804 /* Make sure the GDT Entry is valid */
808 TssEntry
->LimitLow
= sizeof(KTSS
) - 1;
809 TssEntry
->HighWord
.Bits
.LimitHi
= 0;
812 /* Now clear the I/O Map */
813 ASSERT(IOPM_COUNT
== 1);
814 RtlFillMemory(Tss
->IoMaps
[0].IoMap
, IOPM_FULL_SIZE
, 0xFF);
816 /* Initialize Interrupt Direction Maps */
817 p
= (PUCHAR
)(Tss
->IoMaps
[0].DirectionMap
);
818 RtlZeroMemory(p
, IOPM_DIRECTION_MAP_SIZE
);
820 /* Add DPMI support for interrupts */
825 /* Initialize the default Interrupt Direction Map */
826 p
= Tss
->IntDirectionMap
;
827 RtlZeroMemory(Tss
->IntDirectionMap
, IOPM_DIRECTION_MAP_SIZE
);
829 /* Add DPMI support */
837 KiInitializeTSS(IN PKTSS Tss
)
839 /* Set an invalid map base */
840 Tss
->IoMapBase
= KiComputeIopmOffset(IO_ACCESS_MAP_NONE
);
842 /* Disable traps during Task Switches */
845 /* Set LDT and Ring 0 SS */
847 Tss
->Ss0
= KGDT_R0_DATA
;
853 Ki386InitializeTss(IN PKTSS Tss
,
857 PKGDTENTRY TssEntry
, TaskGateEntry
;
859 /* Initialize the boot TSS. */
860 TssEntry
= &Gdt
[KGDT_TSS
/ sizeof(KGDTENTRY
)];
861 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
862 TssEntry
->HighWord
.Bits
.Pres
= 1;
863 TssEntry
->HighWord
.Bits
.Dpl
= 0;
864 KiInitializeTSS2(Tss
, TssEntry
);
865 KiInitializeTSS(Tss
);
867 /* Load the task register */
868 Ke386SetTr(KGDT_TSS
);
870 /* Setup the Task Gate for Double Fault Traps */
871 TaskGateEntry
= (PKGDTENTRY
)&Idt
[8];
872 TaskGateEntry
->HighWord
.Bits
.Type
= I386_TASK_GATE
;
873 TaskGateEntry
->HighWord
.Bits
.Pres
= 1;
874 TaskGateEntry
->HighWord
.Bits
.Dpl
= 0;
875 ((PKIDTENTRY
)TaskGateEntry
)->Selector
= KGDT_DF_TSS
;
877 /* Initialize the TSS used for handling double faults. */
878 Tss
= (PKTSS
)KiDoubleFaultTSS
;
879 KiInitializeTSS(Tss
);
880 Tss
->CR3
= __readcr3();
881 Tss
->Esp0
= KiDoubleFaultStack
;
882 Tss
->Esp
= KiDoubleFaultStack
;
883 Tss
->Eip
= PtrToUlong(KiTrap08
);
884 Tss
->Cs
= KGDT_R0_CODE
;
885 Tss
->Fs
= KGDT_R0_PCR
;
886 Tss
->Ss
= Ke386GetSs();
887 Tss
->Es
= KGDT_R3_DATA
| RPL_MASK
;
888 Tss
->Ds
= KGDT_R3_DATA
| RPL_MASK
;
890 /* Setup the Double Trap TSS entry in the GDT */
891 TssEntry
= &Gdt
[KGDT_DF_TSS
/ sizeof(KGDTENTRY
)];
892 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
893 TssEntry
->HighWord
.Bits
.Pres
= 1;
894 TssEntry
->HighWord
.Bits
.Dpl
= 0;
895 TssEntry
->BaseLow
= (USHORT
)((ULONG_PTR
)Tss
& 0xFFFF);
896 TssEntry
->HighWord
.Bytes
.BaseMid
= (UCHAR
)((ULONG_PTR
)Tss
>> 16);
897 TssEntry
->HighWord
.Bytes
.BaseHi
= (UCHAR
)((ULONG_PTR
)Tss
>> 24);
898 TssEntry
->LimitLow
= KTSS_IO_MAPS
;
900 /* Now setup the NMI Task Gate */
901 TaskGateEntry
= (PKGDTENTRY
)&Idt
[2];
902 TaskGateEntry
->HighWord
.Bits
.Type
= I386_TASK_GATE
;
903 TaskGateEntry
->HighWord
.Bits
.Pres
= 1;
904 TaskGateEntry
->HighWord
.Bits
.Dpl
= 0;
905 ((PKIDTENTRY
)TaskGateEntry
)->Selector
= KGDT_NMI_TSS
;
907 /* Initialize the actual TSS */
908 Tss
= (PKTSS
)KiNMITSS
;
909 KiInitializeTSS(Tss
);
910 Tss
->CR3
= __readcr3();
911 Tss
->Esp0
= KiDoubleFaultStack
;
912 Tss
->Esp
= KiDoubleFaultStack
;
913 Tss
->Eip
= PtrToUlong(KiTrap02
);
914 Tss
->Cs
= KGDT_R0_CODE
;
915 Tss
->Fs
= KGDT_R0_PCR
;
916 Tss
->Ss
= Ke386GetSs();
917 Tss
->Es
= KGDT_R3_DATA
| RPL_MASK
;
918 Tss
->Ds
= KGDT_R3_DATA
| RPL_MASK
;
920 /* And its associated TSS Entry */
921 TssEntry
= &Gdt
[KGDT_NMI_TSS
/ sizeof(KGDTENTRY
)];
922 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
923 TssEntry
->HighWord
.Bits
.Pres
= 1;
924 TssEntry
->HighWord
.Bits
.Dpl
= 0;
925 TssEntry
->BaseLow
= (USHORT
)((ULONG_PTR
)Tss
& 0xFFFF);
926 TssEntry
->HighWord
.Bytes
.BaseMid
= (UCHAR
)((ULONG_PTR
)Tss
>> 16);
927 TssEntry
->HighWord
.Bytes
.BaseHi
= (UCHAR
)((ULONG_PTR
)Tss
>> 24);
928 TssEntry
->LimitLow
= KTSS_IO_MAPS
;
933 KeFlushCurrentTb(VOID
)
935 /* Flush the TLB by resetting CR3 */
936 __writecr3(__readcr3());
941 KiRestoreProcessorControlState(PKPROCESSOR_STATE ProcessorState
)
946 // Restore the CR registers
948 __writecr0(ProcessorState
->SpecialRegisters
.Cr0
);
949 Ke386SetCr2(ProcessorState
->SpecialRegisters
.Cr2
);
950 __writecr3(ProcessorState
->SpecialRegisters
.Cr3
);
951 if (KeFeatureBits
& KF_CR4
) __writecr4(ProcessorState
->SpecialRegisters
.Cr4
);
954 // Restore the DR registers
956 __writedr(0, ProcessorState
->SpecialRegisters
.KernelDr0
);
957 __writedr(1, ProcessorState
->SpecialRegisters
.KernelDr1
);
958 __writedr(2, ProcessorState
->SpecialRegisters
.KernelDr2
);
959 __writedr(3, ProcessorState
->SpecialRegisters
.KernelDr3
);
960 __writedr(6, ProcessorState
->SpecialRegisters
.KernelDr6
);
961 __writedr(7, ProcessorState
->SpecialRegisters
.KernelDr7
);
964 // Restore GDT and IDT
966 Ke386SetGlobalDescriptorTable(&ProcessorState
->SpecialRegisters
.Gdtr
.Limit
);
967 __lidt(&ProcessorState
->SpecialRegisters
.Idtr
.Limit
);
970 // Clear the busy flag so we don't crash if we reload the same selector
972 TssEntry
= (PKGDTENTRY
)(ProcessorState
->SpecialRegisters
.Gdtr
.Base
+
973 ProcessorState
->SpecialRegisters
.Tr
);
974 TssEntry
->HighWord
.Bytes
.Flags1
&= ~0x2;
977 // Restore TSS and LDT
979 Ke386SetTr(ProcessorState
->SpecialRegisters
.Tr
);
980 Ke386SetLocalDescriptorTable(ProcessorState
->SpecialRegisters
.Ldtr
);
985 KiSaveProcessorControlState(OUT PKPROCESSOR_STATE ProcessorState
)
987 /* Save the CR registers */
988 ProcessorState
->SpecialRegisters
.Cr0
= __readcr0();
989 ProcessorState
->SpecialRegisters
.Cr2
= __readcr2();
990 ProcessorState
->SpecialRegisters
.Cr3
= __readcr3();
991 ProcessorState
->SpecialRegisters
.Cr4
= (KeFeatureBits
& KF_CR4
) ?
994 /* Save the DR registers */
995 ProcessorState
->SpecialRegisters
.KernelDr0
= __readdr(0);
996 ProcessorState
->SpecialRegisters
.KernelDr1
= __readdr(1);
997 ProcessorState
->SpecialRegisters
.KernelDr2
= __readdr(2);
998 ProcessorState
->SpecialRegisters
.KernelDr3
= __readdr(3);
999 ProcessorState
->SpecialRegisters
.KernelDr6
= __readdr(6);
1000 ProcessorState
->SpecialRegisters
.KernelDr7
= __readdr(7);
1003 /* Save GDT, IDT, LDT and TSS */
1004 Ke386GetGlobalDescriptorTable(&ProcessorState
->SpecialRegisters
.Gdtr
.Limit
);
1005 __sidt(&ProcessorState
->SpecialRegisters
.Idtr
.Limit
);
1006 ProcessorState
->SpecialRegisters
.Tr
= Ke386GetTr();
1007 ProcessorState
->SpecialRegisters
.Ldtr
= Ke386GetLocalDescriptorTable();
1013 KiInitializeMachineType(VOID
)
1015 /* Set the Machine Type we got from NTLDR */
1016 KeI386MachineType
= KeLoaderBlock
->u
.I386
.MachineType
& 0x000FF;
1022 KiLoadFastSyscallMachineSpecificRegisters(IN ULONG_PTR Context
)
1024 /* Set CS and ESP */
1025 WRMSR(0x174, KGDT_R0_CODE
);
1026 WRMSR(0x175, (ULONG_PTR
)KeGetCurrentPrcb()->DpcStack
);
1029 WRMSR(0x176, (ULONG_PTR
)KiFastCallEntry
);
1036 KiRestoreFastSyscallReturnState(VOID
)
1038 /* Check if the CPU Supports fast system call */
1039 if (KeFeatureBits
& KF_FAST_SYSCALL
)
1041 /* Check if it has been disabled */
1042 if (!KiFastSystemCallDisable
)
1044 /* Do an IPI to enable it */
1045 KeIpiGenericCall(KiLoadFastSyscallMachineSpecificRegisters
, 0);
1047 /* It's enabled, so use the proper exit stub */
1048 KiFastCallExitHandler
= KiSystemCallSysExitReturn
;
1049 DPRINT1("Support for SYSENTER detected.\n");
1053 /* Disable fast system call */
1054 KeFeatureBits
&= ~KF_FAST_SYSCALL
;
1055 KiFastCallExitHandler
= KiSystemCallTrapReturn
;
1056 DPRINT1("Support for SYSENTER disabled.\n");
1061 /* Use the IRET handler */
1062 KiFastCallExitHandler
= KiSystemCallTrapReturn
;
1063 DPRINT1("No support for SYSENTER detected.\n");
1070 Ki386EnableDE(IN ULONG_PTR Context
)
1073 __writecr4(__readcr4() | CR4_DE
);
1080 Ki386EnableFxsr(IN ULONG_PTR Context
)
1083 __writecr4(__readcr4() | CR4_FXSR
);
1090 Ki386EnableXMMIExceptions(IN ULONG_PTR Context
)
1092 PKIDTENTRY IdtEntry
;
1094 /* Get the IDT Entry for Interrupt 0x13 */
1095 IdtEntry
= &((PKIPCR
)KeGetPcr())->IDT
[0x13];
1098 IdtEntry
->Selector
= KGDT_R0_CODE
;
1099 IdtEntry
->Offset
= ((ULONG_PTR
)KiTrap13
& 0xFFFF);
1100 IdtEntry
->ExtendedOffset
= ((ULONG_PTR
)KiTrap13
>> 16) & 0xFFFF;
1101 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->Dpl
= 0;
1102 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->Present
= 1;
1103 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->SegmentType
= I386_INTERRUPT_GATE
;
1105 /* Enable XMMI exceptions */
1106 __writecr4(__readcr4() | CR4_XMMEXCPT
);
1113 KiI386PentiumLockErrataFixup(VOID
)
1115 KDESCRIPTOR IdtDescriptor
;
1116 PKIDTENTRY NewIdt
, NewIdt2
;
1118 /* Allocate memory for a new IDT */
1119 NewIdt
= ExAllocatePool(NonPagedPool
, 2 * PAGE_SIZE
);
1121 /* Put everything after the first 7 entries on a new page */
1122 NewIdt2
= (PVOID
)((ULONG_PTR
)NewIdt
+ PAGE_SIZE
- (7 * sizeof(KIDTENTRY
)));
1124 /* Disable interrupts */
1127 /* Get the current IDT and copy it */
1128 __sidt(&IdtDescriptor
.Limit
);
1129 RtlCopyMemory(NewIdt2
,
1130 (PVOID
)IdtDescriptor
.Base
,
1131 IdtDescriptor
.Limit
+ 1);
1132 IdtDescriptor
.Base
= (ULONG
)NewIdt2
;
1134 /* Set the new IDT */
1135 __lidt(&IdtDescriptor
.Limit
);
1136 ((PKIPCR
)KeGetPcr())->IDT
= NewIdt2
;
1138 /* Restore interrupts */
1141 /* Set the first 7 entries as read-only to produce a fault */
1142 MmSetPageProtect(NULL
, NewIdt
, PAGE_READONLY
);
1147 KeDisableInterrupts(VOID
)
1152 /* Get EFLAGS and check if the interrupt bit is set */
1153 Flags
= __readeflags();
1154 Return
= (Flags
& EFLAGS_INTERRUPT_MASK
) ? TRUE
: FALSE
;
1156 /* Disable interrupts */
1163 KeInvalidateAllCaches(VOID
)
1165 /* Only supported on Pentium Pro and higher */
1166 if (KeI386CpuType
< 6) return FALSE
;
1168 /* Invalidate all caches */
1175 KeZeroPages(IN PVOID Address
,
1178 /* Not using XMMI in this routine */
1179 RtlZeroMemory(Address
, Size
);
1184 KiSaveProcessorState(IN PKTRAP_FRAME TrapFrame
,
1185 IN PKEXCEPTION_FRAME ExceptionFrame
)
1187 PKPRCB Prcb
= KeGetCurrentPrcb();
1190 // Save full context
1192 Prcb
->ProcessorState
.ContextFrame
.ContextFlags
= CONTEXT_FULL
|
1193 CONTEXT_DEBUG_REGISTERS
;
1194 KeTrapFrameToContext(TrapFrame
, NULL
, &Prcb
->ProcessorState
.ContextFrame
);
1197 // Save control registers
1199 KiSaveProcessorControlState(&Prcb
->ProcessorState
);
1205 KiIsNpxPresent(VOID
)
1213 /* Read CR0 and mask out FPU flags */
1214 Cr0
= __readcr0() & ~(CR0_MP
| CR0_TS
| CR0_EM
| CR0_ET
);
1216 /* Store on FPU stack */
1221 asm volatile ("fninit;" "fnstsw %0" : "+m"(Magic
));
1224 /* Magic should now be cleared */
1227 /* You don't have an FPU -- enable emulation for now */
1228 __writecr0(Cr0
| CR0_EM
| CR0_TS
);
1232 /* You have an FPU, enable it */
1235 /* Enable INT 16 on 486 and higher */
1236 if (KeGetCurrentPrcb()->CpuType
>= 3) Cr0
|= CR0_NE
;
1239 __writecr0(Cr0
| CR0_EM
| CR0_TS
);
1246 KiIsNpxErrataPresent(VOID
)
1248 BOOLEAN ErrataPresent
;
1250 volatile double Value1
, Value2
;
1252 /* Disable interrupts */
1255 /* Read CR0 and remove FPU flags */
1257 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1259 /* Initialize FPU state */
1262 /* Multiply the magic values and divide, we should get the result back */
1265 ErrataPresent
= (Value1
* Value2
/ 3145727.0) != 4195835.0;
1270 /* Enable interrupts */
1273 /* Return if there's an errata */
1274 return ErrataPresent
;
1279 KiFlushNPXState(IN PFLOATING_SAVE_AREA SaveArea
)
1282 PKTHREAD Thread
, NpxThread
;
1283 PFX_SAVE_AREA FxSaveArea
;
1285 /* Save volatiles and disable interrupts */
1286 EFlags
= __readeflags();
1289 /* Save the PCR and get the current thread */
1290 Thread
= KeGetCurrentThread();
1292 /* Check if we're already loaded */
1293 if (Thread
->NpxState
!= NPX_STATE_LOADED
)
1295 /* If there's nothing to load, quit */
1296 if (!SaveArea
) return;
1298 /* Need FXSR support for this */
1299 ASSERT(KeI386FxsrPresent
== TRUE
);
1301 /* Check for sane CR0 */
1303 if (Cr0
& (CR0_MP
| CR0_TS
| CR0_EM
))
1305 /* Mask out FPU flags */
1306 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1309 /* Get the NPX thread and check its FPU state */
1310 NpxThread
= KeGetCurrentPrcb()->NpxThread
;
1311 if ((NpxThread
) && (NpxThread
->NpxState
== NPX_STATE_LOADED
))
1313 /* Get the FX frame and store the state there */
1314 FxSaveArea
= KiGetThreadNpxArea(NpxThread
);
1315 Ke386FxSave(FxSaveArea
);
1317 /* NPX thread has lost its state */
1318 NpxThread
->NpxState
= NPX_STATE_NOT_LOADED
;
1321 /* Now load NPX state from the NPX area */
1322 FxSaveArea
= KiGetThreadNpxArea(Thread
);
1323 Ke386FxStore(FxSaveArea
);
1327 /* Check for sane CR0 */
1329 if (Cr0
& (CR0_MP
| CR0_TS
| CR0_EM
))
1331 /* Mask out FPU flags */
1332 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1336 FxSaveArea
= KiGetThreadNpxArea(Thread
);
1337 Thread
->NpxState
= NPX_STATE_NOT_LOADED
;
1339 /* Save state if supported by CPU */
1340 if (KeI386FxsrPresent
) Ke386FxSave(FxSaveArea
);
1343 /* Now save the FN state wherever it was requested */
1344 if (SaveArea
) Ke386FnSave(SaveArea
);
1346 /* Clear NPX thread */
1347 KeGetCurrentPrcb()->NpxThread
= NULL
;
1349 /* Add the CR0 from the NPX frame */
1350 Cr0
|= NPX_STATE_NOT_LOADED
;
1351 Cr0
|= FxSaveArea
->Cr0NpxState
;
1354 /* Restore interrupt state */
1355 __writeeflags(EFlags
);
1358 /* PUBLIC FUNCTIONS **********************************************************/
1365 KiCoprocessorError(VOID
)
1367 PFX_SAVE_AREA NpxArea
;
1369 /* Get the FPU area */
1370 NpxArea
= KiGetThreadNpxArea(KeGetCurrentThread());
1373 NpxArea
->Cr0NpxState
= CR0_TS
;
1374 __writecr0(__readcr0() | CR0_TS
);
1382 KeSaveFloatingPointState(OUT PKFLOATING_SAVE Save
)
1384 PFNSAVE_FORMAT FpState
;
1385 ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL
);
1386 DPRINT1("%s is not really implemented\n", __FUNCTION__
);
1388 /* check if we are doing software emulation */
1389 if (!KeI386NpxPresent
) return STATUS_ILLEGAL_FLOAT_CONTEXT
;
1391 FpState
= ExAllocatePool(NonPagedPool
, sizeof (FNSAVE_FORMAT
));
1392 if (!FpState
) return STATUS_INSUFFICIENT_RESOURCES
;
1394 *((PVOID
*) Save
) = FpState
;
1396 asm volatile("fnsave %0\n\t" : "=m" (*FpState
));
1404 KeGetCurrentThread()->DispatcherHeader
.NpxIrql
= KeGetCurrentIrql();
1405 return STATUS_SUCCESS
;
1413 KeRestoreFloatingPointState(IN PKFLOATING_SAVE Save
)
1415 PFNSAVE_FORMAT FpState
= *((PVOID
*) Save
);
1416 ASSERT(KeGetCurrentThread()->DispatcherHeader
.NpxIrql
== KeGetCurrentIrql());
1417 DPRINT1("%s is not really implemented\n", __FUNCTION__
);
1420 asm volatile("fnclex\n\t");
1421 asm volatile("frstor %0\n\t" : "=m" (*FpState
));
1430 ExFreePool(FpState
);
1431 return STATUS_SUCCESS
;
1439 KeGetRecommendedSharedDataAlignment(VOID
)
1441 /* Return the global variable */
1442 return KeLargestCacheLine
;
1447 KiFlushTargetEntireTb(IN PKIPI_CONTEXT PacketContext
,
1452 /* Signal this packet as done */
1453 KiIpiSignalPacketDone(PacketContext
);
1455 /* Flush the TB for the Current CPU */
1464 KeFlushEntireTb(IN BOOLEAN Invalid
,
1465 IN BOOLEAN AllProcessors
)
1469 KAFFINITY TargetAffinity
;
1470 PKPRCB Prcb
= KeGetCurrentPrcb();
1473 /* Raise the IRQL for the TB Flush */
1474 OldIrql
= KeRaiseIrqlToSynchLevel();
1477 /* FIXME: Use KiTbFlushTimeStamp to synchronize TB flush */
1479 /* Get the current processor affinity, and exclude ourselves */
1480 TargetAffinity
= KeActiveProcessors
;
1481 TargetAffinity
&= ~Prcb
->SetMember
;
1483 /* Make sure this is MP */
1486 /* Send an IPI TB flush to the other processors */
1487 KiIpiSendPacket(TargetAffinity
,
1488 KiFlushTargetEntireTb
,
1495 /* Flush the TB for the Current CPU, and update the flush stamp */
1499 /* If this is MP, wait for the other processors to finish */
1503 ASSERT(Prcb
== (volatile PKPRCB
)KeGetCurrentPrcb());
1506 ASSERTMSG("Not yet implemented\n", FALSE
);
1510 /* Update the flush stamp and return to original IRQL */
1511 InterlockedExchangeAdd(&KiTbFlushTimeStamp
, 1);
1512 KeLowerIrql(OldIrql
);
1520 KeSetDmaIoCoherency(IN ULONG Coherency
)
1522 /* Save the coherency globally */
1523 KiDmaIoCoherency
= Coherency
;
1531 KeQueryActiveProcessors(VOID
)
1535 /* Simply return the number of active processors */
1536 return KeActiveProcessors
;
1544 KeSaveStateForHibernate(IN PKPROCESSOR_STATE State
)
1546 /* Capture the context */
1547 RtlCaptureContext(&State
->ContextFrame
);
1549 /* Capture the control state */
1550 KiSaveProcessorControlState(State
);