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 */
116 WRITE_PORT_UCHAR((PUCHAR
)(ULONG_PTR
)0x22, reg
);
117 return READ_PORT_UCHAR((PUCHAR
)(ULONG_PTR
)0x23);
120 #define setCx86(reg, data) do { \
121 WRITE_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x22,(reg)); \
122 WRITE_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x23,(data)); \
125 /* FUNCTIONS *****************************************************************/
130 KiSetProcessorType(VOID
)
132 ULONG EFlags
, NewEFlags
;
134 ULONG Stepping
, Type
;
136 /* Start by assuming no CPUID data */
137 KeGetCurrentPrcb()->CpuID
= 0;
140 EFlags
= __readeflags();
142 /* XOR out the ID bit and update EFlags */
143 NewEFlags
= EFlags
^ EFLAGS_ID
;
144 __writeeflags(NewEFlags
);
146 /* Get them back and see if they were modified */
147 NewEFlags
= __readeflags();
148 if (NewEFlags
!= EFlags
)
150 /* The modification worked, so CPUID exists. Set the ID Bit again. */
152 __writeeflags(EFlags
);
154 /* Peform CPUID 0 to see if CPUID 1 is supported */
155 CPUID(0, &Reg
, &Dummy
, &Dummy
, &Dummy
);
159 CPUID(1, &Reg
, &Dummy
, &Dummy
, &Dummy
);
162 * Get the Stepping and Type. The stepping contains both the
163 * Model and the Step, while the Type contains the returned Type.
164 * We ignore the family.
166 * For the stepping, we convert this: zzzzzzxy into this: x0y
168 Stepping
= Reg
& 0xF0;
170 Stepping
+= (Reg
& 0xFF);
175 /* Save them in the PRCB */
176 KeGetCurrentPrcb()->CpuID
= TRUE
;
177 KeGetCurrentPrcb()->CpuType
= (UCHAR
)Type
;
178 KeGetCurrentPrcb()->CpuStep
= (USHORT
)Stepping
;
182 DPRINT1("CPUID Support lacking\n");
187 DPRINT1("CPUID Support lacking\n");
191 __writeeflags(EFlags
);
199 PKPRCB Prcb
= KeGetCurrentPrcb();
203 /* Assume no Vendor ID and fail if no CPUID Support. */
204 Prcb
->VendorString
[0] = 0;
205 if (!Prcb
->CpuID
) return 0;
207 /* Get the Vendor ID and null-terminate it */
208 CPUID(0, &Vendor
[0], &Vendor
[1], &Vendor
[2], &Vendor
[3]);
211 /* Re-arrange vendor string */
213 Vendor
[2] = Vendor
[3];
216 /* Copy it to the PRCB and null-terminate it again */
217 RtlCopyMemory(Prcb
->VendorString
,
219 sizeof(Prcb
->VendorString
) - sizeof(CHAR
));
220 Prcb
->VendorString
[sizeof(Prcb
->VendorString
) - sizeof(CHAR
)] = ANSI_NULL
;
222 /* Now check the CPU Type */
223 if (!strcmp(Prcb
->VendorString
, CmpIntelID
))
227 else if (!strcmp(Prcb
->VendorString
, CmpAmdID
))
231 else if (!strcmp(Prcb
->VendorString
, CmpCyrixID
))
233 DPRINT1("Cyrix CPU support not fully tested!\n");
236 else if (!strcmp(Prcb
->VendorString
, CmpTransmetaID
))
238 DPRINT1("Transmeta CPU support not fully tested!\n");
239 return CPU_TRANSMETA
;
241 else if (!strcmp(Prcb
->VendorString
, CmpCentaurID
))
243 DPRINT1("Centaur CPU support not fully tested!\n");
246 else if (!strcmp(Prcb
->VendorString
, CmpRiseID
))
248 DPRINT1("Rise CPU support not fully tested!\n");
259 KiGetFeatureBits(VOID
)
261 PKPRCB Prcb
= KeGetCurrentPrcb();
263 ULONG FeatureBits
= KF_WORKING_PTE
;
264 ULONG Reg
[4], Dummy
, Ccr1
;
265 BOOLEAN ExtendedCPUID
= TRUE
;
266 ULONG CpuFeatures
= 0;
268 /* Get the Vendor ID */
269 Vendor
= KiGetCpuVendor();
271 /* Make sure we got a valid vendor ID at least. */
272 if (!Vendor
) return FeatureBits
;
274 /* Get the CPUID Info. Features are in Reg[3]. */
275 CPUID(1, &Reg
[0], &Reg
[1], &Dummy
, &Reg
[3]);
277 /* Set the initial APIC ID */
278 Prcb
->InitialApicId
= (UCHAR
)(Reg
[1] >> 24);
285 /* Check if it's a P6 */
286 if (Prcb
->CpuType
== 6)
288 /* Perform the special sequence to get the MicroCode Signature */
290 CPUID(1, &Dummy
, &Dummy
, &Dummy
, &Dummy
);
291 Prcb
->UpdateSignature
.QuadPart
= RDMSR(0x8B);
293 else if (Prcb
->CpuType
== 5)
295 /* On P5, enable workaround for the LOCK errata. */
296 KiI386PentiumLockErrataPresent
= TRUE
;
299 /* Check for broken P6 with bad SMP PTE implementation */
300 if (((Reg
[0] & 0x0FF0) == 0x0610 && (Reg
[0] & 0x000F) <= 0x9) ||
301 ((Reg
[0] & 0x0FF0) == 0x0630 && (Reg
[0] & 0x000F) <= 0x4))
303 /* Remove support for correct PTE support. */
304 FeatureBits
&= ~KF_WORKING_PTE
;
307 /* Check if the CPU is too old to support SYSENTER */
308 if ((Prcb
->CpuType
< 6) ||
309 ((Prcb
->CpuType
== 6) && (Prcb
->CpuStep
< 0x0303)))
315 /* Set the current features */
316 CpuFeatures
= Reg
[3];
323 /* Check if this is a K5 or K6. (family 5) */
324 if ((Reg
[0] & 0x0F00) == 0x0500)
326 /* Get the Model Number */
327 switch (Reg
[0] & 0x00F0)
329 /* Model 1: K5 - 5k86 (initial models) */
332 /* Check if this is Step 0 or 1. They don't support PGE */
333 if ((Reg
[0] & 0x000F) > 0x03) break;
335 /* Model 0: K5 - SSA5 */
338 /* Model 0 doesn't support PGE at all. */
345 /* K6-2, Step 8 and over have support for MTRR. */
346 if ((Reg
[0] & 0x000F) >= 0x8) FeatureBits
|= KF_AMDK6MTRR
;
350 Model D: K6-2+, K6-III+ */
354 FeatureBits
|= KF_AMDK6MTRR
;
358 else if((Reg
[0] & 0x0F00) < 0x0500)
360 /* Families below 5 don't support PGE, PSE or CMOV at all */
361 Reg
[3] &= ~(0x08 | 0x2000 | 0x8000);
363 /* They also don't support advanced CPUID functions. */
364 ExtendedCPUID
= FALSE
;
367 /* Set the current features */
368 CpuFeatures
= Reg
[3];
375 /* Workaround the "COMA" bug on 6x family of Cyrix CPUs */
376 if (Prcb
->CpuType
== 6 &&
380 Ccr1
= getCx86(CX86_CCR1
);
382 /* Enable the NO_LOCK bit */
385 /* Set the new CCR1 value */
386 setCx86(CX86_CCR1
, Ccr1
);
389 /* Set the current features */
390 CpuFeatures
= Reg
[3];
397 /* Enable CMPXCHG8B if the family (>= 5), model and stepping (>= 4.2) support it */
398 if ((Reg
[0] & 0x0FFF) >= 0x0542)
400 WRMSR(0x80860004, RDMSR(0x80860004) | 0x0100);
401 FeatureBits
|= KF_CMPXCHG8B
;
406 /* Centaur, IDT, Rise and VIA CPUs */
410 /* These CPUs don't report the presence of CMPXCHG8B through CPUID.
411 However, this feature exists and operates properly without any additional steps. */
412 FeatureBits
|= KF_CMPXCHG8B
;
417 /* Convert all CPUID Feature bits into our format */
418 if (CpuFeatures
& 0x00000002) FeatureBits
|= KF_V86_VIS
| KF_CR4
;
419 if (CpuFeatures
& 0x00000008) FeatureBits
|= KF_LARGE_PAGE
| KF_CR4
;
420 if (CpuFeatures
& 0x00000010) FeatureBits
|= KF_RDTSC
;
421 if (CpuFeatures
& 0x00000100) FeatureBits
|= KF_CMPXCHG8B
;
422 if (CpuFeatures
& 0x00000800) FeatureBits
|= KF_FAST_SYSCALL
;
423 if (CpuFeatures
& 0x00001000) FeatureBits
|= KF_MTRR
;
424 if (CpuFeatures
& 0x00002000) FeatureBits
|= KF_GLOBAL_PAGE
| KF_CR4
;
425 if (CpuFeatures
& 0x00008000) FeatureBits
|= KF_CMOV
;
426 if (CpuFeatures
& 0x00010000) FeatureBits
|= KF_PAT
;
427 if (CpuFeatures
& 0x00200000) FeatureBits
|= KF_DTS
;
428 if (CpuFeatures
& 0x00800000) FeatureBits
|= KF_MMX
;
429 if (CpuFeatures
& 0x01000000) FeatureBits
|= KF_FXSR
;
430 if (CpuFeatures
& 0x02000000) FeatureBits
|= KF_XMMI
;
431 if (CpuFeatures
& 0x04000000) FeatureBits
|= KF_XMMI64
;
433 /* Check if the CPU has hyper-threading */
434 if (CpuFeatures
& 0x10000000)
436 /* Set the number of logical CPUs */
437 Prcb
->LogicalProcessorsPerPhysicalProcessor
= (UCHAR
)(Reg
[1] >> 16);
438 if (Prcb
->LogicalProcessorsPerPhysicalProcessor
> 1)
440 /* We're on dual-core */
441 KiSMTProcessorsPresent
= TRUE
;
446 /* We only have a single CPU */
447 Prcb
->LogicalProcessorsPerPhysicalProcessor
= 1;
450 /* Check if CPUID 0x80000000 is supported */
454 CPUID(0x80000000, &Reg
[0], &Dummy
, &Dummy
, &Dummy
);
455 if ((Reg
[0] & 0xffffff00) == 0x80000000)
457 /* Check if CPUID 0x80000001 is supported */
458 if (Reg
[0] >= 0x80000001)
460 /* Check which extended features are available. */
461 CPUID(0x80000001, &Dummy
, &Dummy
, &Dummy
, &Reg
[3]);
463 /* Check if NX-bit is supported */
464 if (Reg
[3] & 0x00100000) FeatureBits
|= KF_NX_BIT
;
466 /* Now handle each features for each CPU Vendor */
471 if (Reg
[3] & 0x80000000) FeatureBits
|= KF_3DNOW
;
478 /* Return the Feature Bits */
485 KiGetCacheInformation(VOID
)
487 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
489 ULONG Data
[4], Dummy
;
490 ULONG CacheRequests
= 0, i
;
491 ULONG CurrentRegister
;
493 ULONG Size
, Associativity
= 0, CacheLine
= 64, CurrentSize
= 0;
494 BOOLEAN FirstPass
= TRUE
;
496 /* Set default L2 size */
497 Pcr
->SecondLevelCacheSize
= 0;
499 /* Get the Vendor ID and make sure we support CPUID */
500 Vendor
= KiGetCpuVendor();
503 /* Check the Vendor ID */
506 /* Handle Intel case */
509 /*Check if we support CPUID 2 */
510 CPUID(0, &Data
[0], &Dummy
, &Dummy
, &Dummy
);
513 /* We need to loop for the number of times CPUID will tell us to */
516 /* Do the CPUID call */
517 CPUID(2, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
519 /* Check if it was the first call */
523 * The number of times to loop is the first byte. Read
524 * it and then destroy it so we don't get confused.
526 CacheRequests
= Data
[0] & 0xFF;
527 Data
[0] &= 0xFFFFFF00;
529 /* Don't go over this again */
533 /* Loop all 4 registers */
534 for (i
= 0; i
< 4; i
++)
536 /* Get the current register */
537 CurrentRegister
= Data
[i
];
540 * If the upper bit is set, then this register should
543 if (CurrentRegister
& 0x80000000) continue;
545 /* Keep looping for every byte inside this register */
546 while (CurrentRegister
)
548 /* Read a byte, skip a byte. */
549 RegisterByte
= (UCHAR
)(CurrentRegister
& 0xFF);
550 CurrentRegister
>>= 8;
551 if (!RegisterByte
) continue;
554 * Valid values are from 0x40 (0 bytes) to 0x49
555 * (32MB), or from 0x80 to 0x89 (same size but
558 if (((RegisterByte
> 0x40) && (RegisterByte
<= 0x47)) ||
559 ((RegisterByte
> 0x78) && (RegisterByte
<= 0x7C)) ||
560 ((RegisterByte
> 0x80) && (RegisterByte
<= 0x85)))
562 /* Compute associativity */
564 if (RegisterByte
>= 0x79) Associativity
= 8;
566 /* Mask out only the first nibble */
567 RegisterByte
&= 0x07;
569 /* Check if this cache is bigger than the last */
570 Size
= 0x10000 << RegisterByte
;
571 if ((Size
/ Associativity
) > CurrentSize
)
573 /* Set the L2 Cache Size and Associativity */
574 CurrentSize
= Size
/ Associativity
;
575 Pcr
->SecondLevelCacheSize
= Size
;
576 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
579 else if ((RegisterByte
> 0x21) && (RegisterByte
<= 0x29))
581 /* Set minimum cache line size */
582 if (CacheLine
< 128) CacheLine
= 128;
584 /* Hard-code size/associativity */
586 switch (RegisterByte
)
610 /* Check if this cache is bigger than the last */
611 if ((Size
/ Associativity
) > CurrentSize
)
613 /* Set the L2 Cache Size and Associativity */
614 CurrentSize
= Size
/ Associativity
;
615 Pcr
->SecondLevelCacheSize
= Size
;
616 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
619 else if (((RegisterByte
> 0x65) && (RegisterByte
< 0x69)) ||
620 (RegisterByte
== 0x2C) || (RegisterByte
== 0xF0))
622 /* Indicates L1 cache line of 64 bytes */
623 KePrefetchNTAGranularity
= 64;
625 else if (RegisterByte
== 0xF1)
627 /* Indicates L1 cache line of 128 bytes */
628 KePrefetchNTAGranularity
= 128;
630 else if (((RegisterByte
>= 0x4A) && (RegisterByte
<= 0x4C)) ||
631 (RegisterByte
== 0x78) ||
632 (RegisterByte
== 0x7D) ||
633 (RegisterByte
== 0x7F) ||
634 (RegisterByte
== 0x86) ||
635 (RegisterByte
== 0x87))
637 /* Set minimum cache line size */
638 if (CacheLine
< 64) CacheLine
= 64;
640 /* Hard-code size/associativity */
641 switch (RegisterByte
)
644 Size
= 4 * 1024 * 1024;
649 Size
= 6 * 1024 * 1024;
654 Size
= 8 * 1024 * 1024;
659 Size
= 1 * 1024 * 1024;
664 Size
= 2 * 1024 * 1024;
679 Size
= 1 * 1024 * 1024;
688 /* Check if this cache is bigger than the last */
689 if ((Size
/ Associativity
) > CurrentSize
)
691 /* Set the L2 Cache Size and Associativity */
692 CurrentSize
= Size
/ Associativity
;
693 Pcr
->SecondLevelCacheSize
= Size
;
694 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
699 } while (--CacheRequests
);
705 /* Check if we support CPUID 0x80000005 */
706 CPUID(0x80000000, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
707 if (Data
[0] >= 0x80000006)
709 /* Get L1 size first */
710 CPUID(0x80000005, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
711 KePrefetchNTAGranularity
= Data
[2] & 0xFF;
713 /* Check if we support CPUID 0x80000006 */
714 CPUID(0x80000000, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
715 if (Data
[0] >= 0x80000006)
717 /* Get 2nd level cache and tlb size */
718 CPUID(0x80000006, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
720 /* Cache line size */
721 CacheLine
= Data
[2] & 0xFF;
723 /* Hardcode associativity */
724 RegisterByte
= Data
[2] >> 12;
725 switch (RegisterByte
)
750 Size
= (Data
[2] >> 16) << 10;
752 /* Hack for Model 6, Steping 300 */
753 if ((KeGetCurrentPrcb()->CpuType
== 6) &&
754 (KeGetCurrentPrcb()->CpuStep
== 0x300))
756 /* Stick 64K in there */
760 /* Set the L2 Cache Size and associativity */
761 Pcr
->SecondLevelCacheSize
= Size
;
762 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
776 /* Set the cache line */
777 if (CacheLine
> KeLargestCacheLine
) KeLargestCacheLine
= CacheLine
;
778 DPRINT1("Prefetch Cache: %d bytes\tL2 Cache: %d bytes\tL2 Cache Line: %d bytes\tL2 Cache Associativity: %d\n",
779 KePrefetchNTAGranularity
,
780 Pcr
->SecondLevelCacheSize
,
782 Pcr
->SecondLevelCacheAssociativity
);
792 /* Save current CR0 */
795 /* If this is a 486, enable Write-Protection */
796 if (KeGetCurrentPrcb()->CpuType
> 3) Cr0
|= CR0_WP
;
805 KiInitializeTSS2(IN PKTSS Tss
,
806 IN PKGDTENTRY TssEntry OPTIONAL
)
810 /* Make sure the GDT Entry is valid */
814 TssEntry
->LimitLow
= sizeof(KTSS
) - 1;
815 TssEntry
->HighWord
.Bits
.LimitHi
= 0;
818 /* Now clear the I/O Map */
819 ASSERT(IOPM_COUNT
== 1);
820 RtlFillMemory(Tss
->IoMaps
[0].IoMap
, IOPM_FULL_SIZE
, 0xFF);
822 /* Initialize Interrupt Direction Maps */
823 p
= (PUCHAR
)(Tss
->IoMaps
[0].DirectionMap
);
824 RtlZeroMemory(p
, IOPM_DIRECTION_MAP_SIZE
);
826 /* Add DPMI support for interrupts */
831 /* Initialize the default Interrupt Direction Map */
832 p
= Tss
->IntDirectionMap
;
833 RtlZeroMemory(Tss
->IntDirectionMap
, IOPM_DIRECTION_MAP_SIZE
);
835 /* Add DPMI support */
843 KiInitializeTSS(IN PKTSS Tss
)
845 /* Set an invalid map base */
846 Tss
->IoMapBase
= KiComputeIopmOffset(IO_ACCESS_MAP_NONE
);
848 /* Disable traps during Task Switches */
851 /* Set LDT and Ring 0 SS */
853 Tss
->Ss0
= KGDT_R0_DATA
;
859 Ki386InitializeTss(IN PKTSS Tss
,
863 PKGDTENTRY TssEntry
, TaskGateEntry
;
865 /* Initialize the boot TSS. */
866 TssEntry
= &Gdt
[KGDT_TSS
/ sizeof(KGDTENTRY
)];
867 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
868 TssEntry
->HighWord
.Bits
.Pres
= 1;
869 TssEntry
->HighWord
.Bits
.Dpl
= 0;
870 KiInitializeTSS2(Tss
, TssEntry
);
871 KiInitializeTSS(Tss
);
873 /* Load the task register */
874 Ke386SetTr(KGDT_TSS
);
876 /* Setup the Task Gate for Double Fault Traps */
877 TaskGateEntry
= (PKGDTENTRY
)&Idt
[8];
878 TaskGateEntry
->HighWord
.Bits
.Type
= I386_TASK_GATE
;
879 TaskGateEntry
->HighWord
.Bits
.Pres
= 1;
880 TaskGateEntry
->HighWord
.Bits
.Dpl
= 0;
881 ((PKIDTENTRY
)TaskGateEntry
)->Selector
= KGDT_DF_TSS
;
883 /* Initialize the TSS used for handling double faults. */
884 Tss
= (PKTSS
)KiDoubleFaultTSS
;
885 KiInitializeTSS(Tss
);
886 Tss
->CR3
= __readcr3();
887 Tss
->Esp0
= KiDoubleFaultStack
;
888 Tss
->Esp
= KiDoubleFaultStack
;
889 Tss
->Eip
= PtrToUlong(KiTrap08
);
890 Tss
->Cs
= KGDT_R0_CODE
;
891 Tss
->Fs
= KGDT_R0_PCR
;
892 Tss
->Ss
= Ke386GetSs();
893 Tss
->Es
= KGDT_R3_DATA
| RPL_MASK
;
894 Tss
->Ds
= KGDT_R3_DATA
| RPL_MASK
;
896 /* Setup the Double Trap TSS entry in the GDT */
897 TssEntry
= &Gdt
[KGDT_DF_TSS
/ sizeof(KGDTENTRY
)];
898 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
899 TssEntry
->HighWord
.Bits
.Pres
= 1;
900 TssEntry
->HighWord
.Bits
.Dpl
= 0;
901 TssEntry
->BaseLow
= (USHORT
)((ULONG_PTR
)Tss
& 0xFFFF);
902 TssEntry
->HighWord
.Bytes
.BaseMid
= (UCHAR
)((ULONG_PTR
)Tss
>> 16);
903 TssEntry
->HighWord
.Bytes
.BaseHi
= (UCHAR
)((ULONG_PTR
)Tss
>> 24);
904 TssEntry
->LimitLow
= KTSS_IO_MAPS
;
906 /* Now setup the NMI Task Gate */
907 TaskGateEntry
= (PKGDTENTRY
)&Idt
[2];
908 TaskGateEntry
->HighWord
.Bits
.Type
= I386_TASK_GATE
;
909 TaskGateEntry
->HighWord
.Bits
.Pres
= 1;
910 TaskGateEntry
->HighWord
.Bits
.Dpl
= 0;
911 ((PKIDTENTRY
)TaskGateEntry
)->Selector
= KGDT_NMI_TSS
;
913 /* Initialize the actual TSS */
914 Tss
= (PKTSS
)KiNMITSS
;
915 KiInitializeTSS(Tss
);
916 Tss
->CR3
= __readcr3();
917 Tss
->Esp0
= KiDoubleFaultStack
;
918 Tss
->Esp
= KiDoubleFaultStack
;
919 Tss
->Eip
= PtrToUlong(KiTrap02
);
920 Tss
->Cs
= KGDT_R0_CODE
;
921 Tss
->Fs
= KGDT_R0_PCR
;
922 Tss
->Ss
= Ke386GetSs();
923 Tss
->Es
= KGDT_R3_DATA
| RPL_MASK
;
924 Tss
->Ds
= KGDT_R3_DATA
| RPL_MASK
;
926 /* And its associated TSS Entry */
927 TssEntry
= &Gdt
[KGDT_NMI_TSS
/ sizeof(KGDTENTRY
)];
928 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
929 TssEntry
->HighWord
.Bits
.Pres
= 1;
930 TssEntry
->HighWord
.Bits
.Dpl
= 0;
931 TssEntry
->BaseLow
= (USHORT
)((ULONG_PTR
)Tss
& 0xFFFF);
932 TssEntry
->HighWord
.Bytes
.BaseMid
= (UCHAR
)((ULONG_PTR
)Tss
>> 16);
933 TssEntry
->HighWord
.Bytes
.BaseHi
= (UCHAR
)((ULONG_PTR
)Tss
>> 24);
934 TssEntry
->LimitLow
= KTSS_IO_MAPS
;
939 KeFlushCurrentTb(VOID
)
941 /* Flush the TLB by resetting CR3 */
942 __writecr3(__readcr3());
947 KiRestoreProcessorControlState(PKPROCESSOR_STATE ProcessorState
)
952 // Restore the CR registers
954 __writecr0(ProcessorState
->SpecialRegisters
.Cr0
);
955 Ke386SetCr2(ProcessorState
->SpecialRegisters
.Cr2
);
956 __writecr3(ProcessorState
->SpecialRegisters
.Cr3
);
957 if (KeFeatureBits
& KF_CR4
) __writecr4(ProcessorState
->SpecialRegisters
.Cr4
);
960 // Restore the DR registers
962 __writedr(0, ProcessorState
->SpecialRegisters
.KernelDr0
);
963 __writedr(1, ProcessorState
->SpecialRegisters
.KernelDr1
);
964 __writedr(2, ProcessorState
->SpecialRegisters
.KernelDr2
);
965 __writedr(3, ProcessorState
->SpecialRegisters
.KernelDr3
);
966 __writedr(6, ProcessorState
->SpecialRegisters
.KernelDr6
);
967 __writedr(7, ProcessorState
->SpecialRegisters
.KernelDr7
);
970 // Restore GDT and IDT
972 Ke386SetGlobalDescriptorTable(&ProcessorState
->SpecialRegisters
.Gdtr
.Limit
);
973 __lidt(&ProcessorState
->SpecialRegisters
.Idtr
.Limit
);
976 // Clear the busy flag so we don't crash if we reload the same selector
978 TssEntry
= (PKGDTENTRY
)(ProcessorState
->SpecialRegisters
.Gdtr
.Base
+
979 ProcessorState
->SpecialRegisters
.Tr
);
980 TssEntry
->HighWord
.Bytes
.Flags1
&= ~0x2;
983 // Restore TSS and LDT
985 Ke386SetTr(ProcessorState
->SpecialRegisters
.Tr
);
986 Ke386SetLocalDescriptorTable(ProcessorState
->SpecialRegisters
.Ldtr
);
991 KiSaveProcessorControlState(OUT PKPROCESSOR_STATE ProcessorState
)
993 /* Save the CR registers */
994 ProcessorState
->SpecialRegisters
.Cr0
= __readcr0();
995 ProcessorState
->SpecialRegisters
.Cr2
= __readcr2();
996 ProcessorState
->SpecialRegisters
.Cr3
= __readcr3();
997 ProcessorState
->SpecialRegisters
.Cr4
= (KeFeatureBits
& KF_CR4
) ?
1000 /* Save the DR registers */
1001 ProcessorState
->SpecialRegisters
.KernelDr0
= __readdr(0);
1002 ProcessorState
->SpecialRegisters
.KernelDr1
= __readdr(1);
1003 ProcessorState
->SpecialRegisters
.KernelDr2
= __readdr(2);
1004 ProcessorState
->SpecialRegisters
.KernelDr3
= __readdr(3);
1005 ProcessorState
->SpecialRegisters
.KernelDr6
= __readdr(6);
1006 ProcessorState
->SpecialRegisters
.KernelDr7
= __readdr(7);
1009 /* Save GDT, IDT, LDT and TSS */
1010 Ke386GetGlobalDescriptorTable(&ProcessorState
->SpecialRegisters
.Gdtr
.Limit
);
1011 __sidt(&ProcessorState
->SpecialRegisters
.Idtr
.Limit
);
1012 ProcessorState
->SpecialRegisters
.Tr
= Ke386GetTr();
1013 ProcessorState
->SpecialRegisters
.Ldtr
= Ke386GetLocalDescriptorTable();
1019 KiInitializeMachineType(VOID
)
1021 /* Set the Machine Type we got from NTLDR */
1022 KeI386MachineType
= KeLoaderBlock
->u
.I386
.MachineType
& 0x000FF;
1028 KiLoadFastSyscallMachineSpecificRegisters(IN ULONG_PTR Context
)
1030 /* Set CS and ESP */
1031 WRMSR(0x174, KGDT_R0_CODE
);
1032 WRMSR(0x175, (ULONG_PTR
)KeGetCurrentPrcb()->DpcStack
);
1035 WRMSR(0x176, (ULONG_PTR
)KiFastCallEntry
);
1042 KiRestoreFastSyscallReturnState(VOID
)
1044 /* Check if the CPU Supports fast system call */
1045 if (KeFeatureBits
& KF_FAST_SYSCALL
)
1047 /* Check if it has been disabled */
1048 if (!KiFastSystemCallDisable
)
1050 /* Do an IPI to enable it */
1051 KeIpiGenericCall(KiLoadFastSyscallMachineSpecificRegisters
, 0);
1053 /* It's enabled, so use the proper exit stub */
1054 KiFastCallExitHandler
= KiSystemCallSysExitReturn
;
1055 DPRINT1("Support for SYSENTER detected.\n");
1059 /* Disable fast system call */
1060 KeFeatureBits
&= ~KF_FAST_SYSCALL
;
1061 KiFastCallExitHandler
= KiSystemCallTrapReturn
;
1062 DPRINT1("Support for SYSENTER disabled.\n");
1067 /* Use the IRET handler */
1068 KiFastCallExitHandler
= KiSystemCallTrapReturn
;
1069 DPRINT1("No support for SYSENTER detected.\n");
1076 Ki386EnableDE(IN ULONG_PTR Context
)
1079 __writecr4(__readcr4() | CR4_DE
);
1086 Ki386EnableFxsr(IN ULONG_PTR Context
)
1089 __writecr4(__readcr4() | CR4_FXSR
);
1096 Ki386EnableXMMIExceptions(IN ULONG_PTR Context
)
1098 PKIDTENTRY IdtEntry
;
1100 /* Get the IDT Entry for Interrupt 0x13 */
1101 IdtEntry
= &((PKIPCR
)KeGetPcr())->IDT
[0x13];
1104 IdtEntry
->Selector
= KGDT_R0_CODE
;
1105 IdtEntry
->Offset
= ((ULONG_PTR
)KiTrap13
& 0xFFFF);
1106 IdtEntry
->ExtendedOffset
= ((ULONG_PTR
)KiTrap13
>> 16) & 0xFFFF;
1107 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->Dpl
= 0;
1108 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->Present
= 1;
1109 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->SegmentType
= I386_INTERRUPT_GATE
;
1111 /* Enable XMMI exceptions */
1112 __writecr4(__readcr4() | CR4_XMMEXCPT
);
1119 KiI386PentiumLockErrataFixup(VOID
)
1121 KDESCRIPTOR IdtDescriptor
;
1122 PKIDTENTRY NewIdt
, NewIdt2
;
1124 /* Allocate memory for a new IDT */
1125 NewIdt
= ExAllocatePool(NonPagedPool
, 2 * PAGE_SIZE
);
1127 /* Put everything after the first 7 entries on a new page */
1128 NewIdt2
= (PVOID
)((ULONG_PTR
)NewIdt
+ PAGE_SIZE
- (7 * sizeof(KIDTENTRY
)));
1130 /* Disable interrupts */
1133 /* Get the current IDT and copy it */
1134 __sidt(&IdtDescriptor
.Limit
);
1135 RtlCopyMemory(NewIdt2
,
1136 (PVOID
)IdtDescriptor
.Base
,
1137 IdtDescriptor
.Limit
+ 1);
1138 IdtDescriptor
.Base
= (ULONG
)NewIdt2
;
1140 /* Set the new IDT */
1141 __lidt(&IdtDescriptor
.Limit
);
1142 ((PKIPCR
)KeGetPcr())->IDT
= NewIdt2
;
1144 /* Restore interrupts */
1147 /* Set the first 7 entries as read-only to produce a fault */
1148 MmSetPageProtect(NULL
, NewIdt
, PAGE_READONLY
);
1153 KeDisableInterrupts(VOID
)
1158 /* Get EFLAGS and check if the interrupt bit is set */
1159 Flags
= __readeflags();
1160 Return
= (Flags
& EFLAGS_INTERRUPT_MASK
) ? TRUE
: FALSE
;
1162 /* Disable interrupts */
1169 KeInvalidateAllCaches(VOID
)
1171 /* Only supported on Pentium Pro and higher */
1172 if (KeI386CpuType
< 6) return FALSE
;
1174 /* Invalidate all caches */
1181 KeZeroPages(IN PVOID Address
,
1184 /* Not using XMMI in this routine */
1185 RtlZeroMemory(Address
, Size
);
1190 KiSaveProcessorState(IN PKTRAP_FRAME TrapFrame
,
1191 IN PKEXCEPTION_FRAME ExceptionFrame
)
1193 PKPRCB Prcb
= KeGetCurrentPrcb();
1196 // Save full context
1198 Prcb
->ProcessorState
.ContextFrame
.ContextFlags
= CONTEXT_FULL
|
1199 CONTEXT_DEBUG_REGISTERS
;
1200 KeTrapFrameToContext(TrapFrame
, NULL
, &Prcb
->ProcessorState
.ContextFrame
);
1203 // Save control registers
1205 KiSaveProcessorControlState(&Prcb
->ProcessorState
);
1211 KiIsNpxPresent(VOID
)
1219 /* Read CR0 and mask out FPU flags */
1220 Cr0
= __readcr0() & ~(CR0_MP
| CR0_TS
| CR0_EM
| CR0_ET
);
1222 /* Store on FPU stack */
1227 asm volatile ("fninit;" "fnstsw %0" : "+m"(Magic
));
1230 /* Magic should now be cleared */
1233 /* You don't have an FPU -- enable emulation for now */
1234 __writecr0(Cr0
| CR0_EM
| CR0_TS
);
1238 /* You have an FPU, enable it */
1241 /* Enable INT 16 on 486 and higher */
1242 if (KeGetCurrentPrcb()->CpuType
>= 3) Cr0
|= CR0_NE
;
1245 __writecr0(Cr0
| CR0_EM
| CR0_TS
);
1252 KiIsNpxErrataPresent(VOID
)
1254 BOOLEAN ErrataPresent
;
1256 volatile double Value1
, Value2
;
1258 /* Disable interrupts */
1261 /* Read CR0 and remove FPU flags */
1263 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1265 /* Initialize FPU state */
1268 /* Multiply the magic values and divide, we should get the result back */
1271 ErrataPresent
= (Value1
* Value2
/ 3145727.0) != 4195835.0;
1276 /* Enable interrupts */
1279 /* Return if there's an errata */
1280 return ErrataPresent
;
1285 KiFlushNPXState(IN PFLOATING_SAVE_AREA SaveArea
)
1288 PKTHREAD Thread
, NpxThread
;
1289 PFX_SAVE_AREA FxSaveArea
;
1291 /* Save volatiles and disable interrupts */
1292 EFlags
= __readeflags();
1295 /* Save the PCR and get the current thread */
1296 Thread
= KeGetCurrentThread();
1298 /* Check if we're already loaded */
1299 if (Thread
->NpxState
!= NPX_STATE_LOADED
)
1301 /* If there's nothing to load, quit */
1302 if (!SaveArea
) return;
1304 /* Need FXSR support for this */
1305 ASSERT(KeI386FxsrPresent
== TRUE
);
1307 /* Check for sane CR0 */
1309 if (Cr0
& (CR0_MP
| CR0_TS
| CR0_EM
))
1311 /* Mask out FPU flags */
1312 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1315 /* Get the NPX thread and check its FPU state */
1316 NpxThread
= KeGetCurrentPrcb()->NpxThread
;
1317 if ((NpxThread
) && (NpxThread
->NpxState
== NPX_STATE_LOADED
))
1319 /* Get the FX frame and store the state there */
1320 FxSaveArea
= KiGetThreadNpxArea(NpxThread
);
1321 Ke386FxSave(FxSaveArea
);
1323 /* NPX thread has lost its state */
1324 NpxThread
->NpxState
= NPX_STATE_NOT_LOADED
;
1327 /* Now load NPX state from the NPX area */
1328 FxSaveArea
= KiGetThreadNpxArea(Thread
);
1329 Ke386FxStore(FxSaveArea
);
1333 /* Check for sane CR0 */
1335 if (Cr0
& (CR0_MP
| CR0_TS
| CR0_EM
))
1337 /* Mask out FPU flags */
1338 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1342 FxSaveArea
= KiGetThreadNpxArea(Thread
);
1343 Thread
->NpxState
= NPX_STATE_NOT_LOADED
;
1345 /* Save state if supported by CPU */
1346 if (KeI386FxsrPresent
) Ke386FxSave(FxSaveArea
);
1349 /* Now save the FN state wherever it was requested */
1350 if (SaveArea
) Ke386FnSave(SaveArea
);
1352 /* Clear NPX thread */
1353 KeGetCurrentPrcb()->NpxThread
= NULL
;
1355 /* Add the CR0 from the NPX frame */
1356 Cr0
|= NPX_STATE_NOT_LOADED
;
1357 Cr0
|= FxSaveArea
->Cr0NpxState
;
1360 /* Restore interrupt state */
1361 __writeeflags(EFlags
);
1364 /* PUBLIC FUNCTIONS **********************************************************/
1371 KiCoprocessorError(VOID
)
1373 PFX_SAVE_AREA NpxArea
;
1375 /* Get the FPU area */
1376 NpxArea
= KiGetThreadNpxArea(KeGetCurrentThread());
1379 NpxArea
->Cr0NpxState
= CR0_TS
;
1380 __writecr0(__readcr0() | CR0_TS
);
1388 KeSaveFloatingPointState(OUT PKFLOATING_SAVE Save
)
1390 PFNSAVE_FORMAT FpState
;
1391 ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL
);
1392 DPRINT1("%s is not really implemented\n", __FUNCTION__
);
1394 /* check if we are doing software emulation */
1395 if (!KeI386NpxPresent
) return STATUS_ILLEGAL_FLOAT_CONTEXT
;
1397 FpState
= ExAllocatePool(NonPagedPool
, sizeof (FNSAVE_FORMAT
));
1398 if (!FpState
) return STATUS_INSUFFICIENT_RESOURCES
;
1400 *((PVOID
*) Save
) = FpState
;
1402 asm volatile("fnsave %0\n\t" : "=m" (*FpState
));
1410 KeGetCurrentThread()->DispatcherHeader
.NpxIrql
= KeGetCurrentIrql();
1411 return STATUS_SUCCESS
;
1419 KeRestoreFloatingPointState(IN PKFLOATING_SAVE Save
)
1421 PFNSAVE_FORMAT FpState
= *((PVOID
*) Save
);
1422 ASSERT(KeGetCurrentThread()->DispatcherHeader
.NpxIrql
== KeGetCurrentIrql());
1423 DPRINT1("%s is not really implemented\n", __FUNCTION__
);
1426 asm volatile("fnclex\n\t");
1427 asm volatile("frstor %0\n\t" : "=m" (*FpState
));
1436 ExFreePool(FpState
);
1437 return STATUS_SUCCESS
;
1445 KeGetRecommendedSharedDataAlignment(VOID
)
1447 /* Return the global variable */
1448 return KeLargestCacheLine
;
1453 KiFlushTargetEntireTb(IN PKIPI_CONTEXT PacketContext
,
1458 /* Signal this packet as done */
1459 KiIpiSignalPacketDone(PacketContext
);
1461 /* Flush the TB for the Current CPU */
1470 KeFlushEntireTb(IN BOOLEAN Invalid
,
1471 IN BOOLEAN AllProcessors
)
1475 KAFFINITY TargetAffinity
;
1476 PKPRCB Prcb
= KeGetCurrentPrcb();
1479 /* Raise the IRQL for the TB Flush */
1480 OldIrql
= KeRaiseIrqlToSynchLevel();
1483 /* FIXME: Use KiTbFlushTimeStamp to synchronize TB flush */
1485 /* Get the current processor affinity, and exclude ourselves */
1486 TargetAffinity
= KeActiveProcessors
;
1487 TargetAffinity
&= ~Prcb
->SetMember
;
1489 /* Make sure this is MP */
1492 /* Send an IPI TB flush to the other processors */
1493 KiIpiSendPacket(TargetAffinity
,
1494 KiFlushTargetEntireTb
,
1501 /* Flush the TB for the Current CPU, and update the flush stamp */
1505 /* If this is MP, wait for the other processors to finish */
1509 ASSERT(Prcb
== (volatile PKPRCB
)KeGetCurrentPrcb());
1512 ASSERTMSG("Not yet implemented\n", FALSE
);
1516 /* Update the flush stamp and return to original IRQL */
1517 InterlockedExchangeAdd(&KiTbFlushTimeStamp
, 1);
1518 KeLowerIrql(OldIrql
);
1526 KeSetDmaIoCoherency(IN ULONG Coherency
)
1528 /* Save the coherency globally */
1529 KiDmaIoCoherency
= Coherency
;
1537 KeQueryActiveProcessors(VOID
)
1541 /* Simply return the number of active processors */
1542 return KeActiveProcessors
;
1550 KeSaveStateForHibernate(IN PKPROCESSOR_STATE State
)
1552 /* Capture the context */
1553 RtlCaptureContext(&State
->ContextFrame
);
1555 /* Capture the control state */
1556 KiSaveProcessorControlState(State
);