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 KiFastSystemCallDisable
= 0;
27 ULONG KeI386NpxPresent
= 0;
28 ULONG KiMXCsrMask
= 0;
29 ULONG MxcsrFeatureMask
= 0;
30 ULONG KeI386XMMIPresent
= 0;
31 ULONG KeI386FxsrPresent
= 0;
32 ULONG KeI386MachineType
;
33 ULONG Ke386Pae
= FALSE
;
34 ULONG Ke386NoExecute
= FALSE
;
35 ULONG KeLargestCacheLine
= 0x40;
36 ULONG KeDcacheFlushCount
= 0;
37 ULONG KeIcacheFlushCount
= 0;
38 ULONG KiDmaIoCoherency
= 0;
39 ULONG KePrefetchNTAGranularity
= 32;
40 BOOLEAN KiI386PentiumLockErrataPresent
;
41 BOOLEAN KiSMTProcessorsPresent
;
43 /* The distance between SYSEXIT and IRETD return modes */
44 UCHAR KiSystemCallExitAdjust
;
46 /* The offset that was applied -- either 0 or the value above */
47 UCHAR KiSystemCallExitAdjusted
;
49 /* Whether the adjustment was already done once */
50 BOOLEAN KiFastCallCopyDoneOnce
;
53 volatile LONG KiTbFlushTimeStamp
;
56 static const CHAR CmpIntelID
[] = "GenuineIntel";
57 static const CHAR CmpAmdID
[] = "AuthenticAMD";
58 static const CHAR CmpCyrixID
[] = "CyrixInstead";
59 static const CHAR CmpTransmetaID
[] = "GenuineTMx86";
60 static const CHAR CmpCentaurID
[] = "CentaurHauls";
61 static const CHAR CmpRiseID
[] = "RiseRiseRise";
63 /* SUPPORT ROUTINES FOR MSVC COMPATIBILITY ***********************************/
67 CPUID(IN ULONG InfoType
,
68 OUT PULONG CpuInfoEax
,
69 OUT PULONG CpuInfoEbx
,
70 OUT PULONG CpuInfoEcx
,
71 OUT PULONG CpuInfoEdx
)
75 /* Perform the CPUID Operation */
76 __cpuid((int*)CpuInfo
, InfoType
);
78 /* Return the results */
79 *CpuInfoEax
= CpuInfo
[0];
80 *CpuInfoEbx
= CpuInfo
[1];
81 *CpuInfoEcx
= CpuInfo
[2];
82 *CpuInfoEdx
= CpuInfo
[3];
87 WRMSR(IN ULONG Register
,
90 /* Write to the MSR */
91 __writemsr(Register
, Value
);
96 RDMSR(IN ULONG Register
)
98 /* Read from the MSR */
99 return __readmsr(Register
);
102 /* NSC/Cyrix CPU configuration register index */
103 #define CX86_CCR1 0xc1
105 /* NSC/Cyrix CPU indexed register access macros */
110 WRITE_PORT_UCHAR((PUCHAR
)(ULONG_PTR
)0x22, reg
);
111 return READ_PORT_UCHAR((PUCHAR
)(ULONG_PTR
)0x23);
116 setCx86(UCHAR reg
, UCHAR data
)
118 WRITE_PORT_UCHAR((PUCHAR
)(ULONG_PTR
)0x22, reg
);
119 WRITE_PORT_UCHAR((PUCHAR
)(ULONG_PTR
)0x23, data
);
123 /* FUNCTIONS *****************************************************************/
128 KiSetProcessorType(VOID
)
130 ULONG EFlags
, NewEFlags
;
132 ULONG Stepping
, Type
;
134 /* Start by assuming no CPUID data */
135 KeGetCurrentPrcb()->CpuID
= 0;
138 EFlags
= __readeflags();
140 /* XOR out the ID bit and update EFlags */
141 NewEFlags
= EFlags
^ EFLAGS_ID
;
142 __writeeflags(NewEFlags
);
144 /* Get them back and see if they were modified */
145 NewEFlags
= __readeflags();
146 if (NewEFlags
!= EFlags
)
148 /* The modification worked, so CPUID exists. Set the ID Bit again. */
150 __writeeflags(EFlags
);
152 /* Peform CPUID 0 to see if CPUID 1 is supported */
153 CPUID(0, &Reg
, &Dummy
, &Dummy
, &Dummy
);
157 CPUID(1, &Reg
, &Dummy
, &Dummy
, &Dummy
);
160 * Get the Stepping and Type. The stepping contains both the
161 * Model and the Step, while the Type contains the returned Type.
162 * We ignore the family.
164 * For the stepping, we convert this: zzzzzzxy into this: x0y
166 Stepping
= Reg
& 0xF0;
168 Stepping
+= (Reg
& 0xFF);
173 /* Save them in the PRCB */
174 KeGetCurrentPrcb()->CpuID
= TRUE
;
175 KeGetCurrentPrcb()->CpuType
= (UCHAR
)Type
;
176 KeGetCurrentPrcb()->CpuStep
= (USHORT
)Stepping
;
180 DPRINT1("CPUID Support lacking\n");
185 DPRINT1("CPUID Support lacking\n");
189 __writeeflags(EFlags
);
197 PKPRCB Prcb
= KeGetCurrentPrcb();
201 /* Assume no Vendor ID and fail if no CPUID Support. */
202 Prcb
->VendorString
[0] = 0;
203 if (!Prcb
->CpuID
) return 0;
205 /* Get the Vendor ID and null-terminate it */
206 CPUID(0, &Vendor
[0], &Vendor
[1], &Vendor
[2], &Vendor
[3]);
209 /* Re-arrange vendor string */
211 Vendor
[2] = Vendor
[3];
214 /* Copy it to the PRCB and null-terminate it again */
215 RtlCopyMemory(Prcb
->VendorString
,
217 sizeof(Prcb
->VendorString
) - sizeof(CHAR
));
218 Prcb
->VendorString
[sizeof(Prcb
->VendorString
) - sizeof(CHAR
)] = ANSI_NULL
;
220 /* Now check the CPU Type */
221 if (!strcmp(Prcb
->VendorString
, CmpIntelID
))
225 else if (!strcmp(Prcb
->VendorString
, CmpAmdID
))
229 else if (!strcmp(Prcb
->VendorString
, CmpCyrixID
))
231 DPRINT1("Cyrix CPU support not fully tested!\n");
234 else if (!strcmp(Prcb
->VendorString
, CmpTransmetaID
))
236 DPRINT1("Transmeta CPU support not fully tested!\n");
237 return CPU_TRANSMETA
;
239 else if (!strcmp(Prcb
->VendorString
, CmpCentaurID
))
241 DPRINT1("Centaur CPU support not fully tested!\n");
244 else if (!strcmp(Prcb
->VendorString
, CmpRiseID
))
246 DPRINT1("Rise CPU support not fully tested!\n");
251 DPRINT1("%s CPU support not fully tested!\n", Prcb
->VendorString
);
258 KiGetFeatureBits(VOID
)
260 PKPRCB Prcb
= KeGetCurrentPrcb();
262 ULONG FeatureBits
= KF_WORKING_PTE
;
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)))
320 /* Check if this is a K5 or K6. (family 5) */
321 if ((Reg
[0] & 0x0F00) == 0x0500)
323 /* Get the Model Number */
324 switch (Reg
[0] & 0x00F0)
326 /* Model 1: K5 - 5k86 (initial models) */
329 /* Check if this is Step 0 or 1. They don't support PGE */
330 if ((Reg
[0] & 0x000F) > 0x03) break;
332 /* Model 0: K5 - SSA5 */
335 /* Model 0 doesn't support PGE at all. */
342 /* K6-2, Step 8 and over have support for MTRR. */
343 if ((Reg
[0] & 0x000F) >= 0x8) FeatureBits
|= KF_AMDK6MTRR
;
347 Model D: K6-2+, K6-III+ */
351 FeatureBits
|= KF_AMDK6MTRR
;
355 else if((Reg
[0] & 0x0F00) < 0x0500)
357 /* Families below 5 don't support PGE, PSE or CMOV at all */
358 Reg
[3] &= ~(0x08 | 0x2000 | 0x8000);
360 /* They also don't support advanced CPUID functions. */
361 ExtendedCPUID
= FALSE
;
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
);
388 /* Enable CMPXCHG8B if the family (>= 5), model and stepping (>= 4.2) support it */
389 if ((Reg
[0] & 0x0FFF) >= 0x0542)
391 WRMSR(0x80860004, RDMSR(0x80860004) | 0x0100);
392 FeatureBits
|= KF_CMPXCHG8B
;
397 /* Centaur, IDT, Rise and VIA CPUs */
401 /* These CPUs don't report the presence of CMPXCHG8B through CPUID.
402 However, this feature exists and operates properly without any additional steps. */
403 FeatureBits
|= KF_CMPXCHG8B
;
408 /* Set the current features */
409 CpuFeatures
= Reg
[3];
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 #define print_supported(kf_value) ((FeatureBits & kf_value) ? #kf_value : "")
473 DPRINT1("Supported CPU features : %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\n",
474 print_supported(KF_V86_VIS
),
475 print_supported(KF_RDTSC
),
476 print_supported(KF_CR4
),
477 print_supported(KF_CMOV
),
478 print_supported(KF_GLOBAL_PAGE
),
479 print_supported(KF_LARGE_PAGE
),
480 print_supported(KF_MTRR
),
481 print_supported(KF_CMPXCHG8B
),
482 print_supported(KF_MMX
),
483 print_supported(KF_WORKING_PTE
),
484 print_supported(KF_PAT
),
485 print_supported(KF_FXSR
),
486 print_supported(KF_FAST_SYSCALL
),
487 print_supported(KF_XMMI
),
488 print_supported(KF_3DNOW
),
489 print_supported(KF_AMDK6MTRR
),
490 print_supported(KF_XMMI64
),
491 print_supported(KF_DTS
),
492 print_supported(KF_NX_BIT
),
493 print_supported(KF_NX_DISABLED
),
494 print_supported(KF_NX_ENABLED
));
495 #undef print_supported
497 /* Return the Feature Bits */
504 KiGetCacheInformation(VOID
)
506 PKIPCR Pcr
= (PKIPCR
)KeGetPcr();
508 ULONG Data
[4], Dummy
;
509 ULONG CacheRequests
= 0, i
;
510 ULONG CurrentRegister
;
511 UCHAR RegisterByte
, Associativity
= 0;
512 ULONG Size
, CacheLine
= 64, CurrentSize
= 0;
513 BOOLEAN FirstPass
= TRUE
;
515 /* Set default L2 size */
516 Pcr
->SecondLevelCacheSize
= 0;
518 /* Get the Vendor ID and make sure we support CPUID */
519 Vendor
= KiGetCpuVendor();
522 /* Check the Vendor ID */
525 /* Handle Intel case */
528 /*Check if we support CPUID 2 */
529 CPUID(0, &Data
[0], &Dummy
, &Dummy
, &Dummy
);
532 /* We need to loop for the number of times CPUID will tell us to */
535 /* Do the CPUID call */
536 CPUID(2, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
538 /* Check if it was the first call */
542 * The number of times to loop is the first byte. Read
543 * it and then destroy it so we don't get confused.
545 CacheRequests
= Data
[0] & 0xFF;
546 Data
[0] &= 0xFFFFFF00;
548 /* Don't go over this again */
552 /* Loop all 4 registers */
553 for (i
= 0; i
< 4; i
++)
555 /* Get the current register */
556 CurrentRegister
= Data
[i
];
559 * If the upper bit is set, then this register should
562 if (CurrentRegister
& 0x80000000) continue;
564 /* Keep looping for every byte inside this register */
565 while (CurrentRegister
)
567 /* Read a byte, skip a byte. */
568 RegisterByte
= (UCHAR
)(CurrentRegister
& 0xFF);
569 CurrentRegister
>>= 8;
570 if (!RegisterByte
) continue;
573 * Valid values are from 0x40 (0 bytes) to 0x49
574 * (32MB), or from 0x80 to 0x89 (same size but
577 if (((RegisterByte
> 0x40) && (RegisterByte
<= 0x47)) ||
578 ((RegisterByte
> 0x78) && (RegisterByte
<= 0x7C)) ||
579 ((RegisterByte
> 0x80) && (RegisterByte
<= 0x85)))
581 /* Compute associativity */
583 if (RegisterByte
>= 0x79) Associativity
= 8;
585 /* Mask out only the first nibble */
586 RegisterByte
&= 0x07;
588 /* Check if this cache is bigger than the last */
589 Size
= 0x10000 << RegisterByte
;
590 if ((Size
/ Associativity
) > CurrentSize
)
592 /* Set the L2 Cache Size and Associativity */
593 CurrentSize
= Size
/ Associativity
;
594 Pcr
->SecondLevelCacheSize
= Size
;
595 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
598 else if ((RegisterByte
> 0x21) && (RegisterByte
<= 0x29))
600 /* Set minimum cache line size */
601 if (CacheLine
< 128) CacheLine
= 128;
603 /* Hard-code size/associativity */
605 switch (RegisterByte
)
629 /* Check if this cache is bigger than the last */
630 if ((Size
/ Associativity
) > CurrentSize
)
632 /* Set the L2 Cache Size and Associativity */
633 CurrentSize
= Size
/ Associativity
;
634 Pcr
->SecondLevelCacheSize
= Size
;
635 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
638 else if (((RegisterByte
> 0x65) && (RegisterByte
< 0x69)) ||
639 (RegisterByte
== 0x2C) || (RegisterByte
== 0xF0))
641 /* Indicates L1 cache line of 64 bytes */
642 KePrefetchNTAGranularity
= 64;
644 else if (RegisterByte
== 0xF1)
646 /* Indicates L1 cache line of 128 bytes */
647 KePrefetchNTAGranularity
= 128;
649 else if (((RegisterByte
>= 0x4A) && (RegisterByte
<= 0x4C)) ||
650 (RegisterByte
== 0x78) ||
651 (RegisterByte
== 0x7D) ||
652 (RegisterByte
== 0x7F) ||
653 (RegisterByte
== 0x86) ||
654 (RegisterByte
== 0x87))
656 /* Set minimum cache line size */
657 if (CacheLine
< 64) CacheLine
= 64;
659 /* Hard-code size/associativity */
660 switch (RegisterByte
)
663 Size
= 4 * 1024 * 1024;
668 Size
= 6 * 1024 * 1024;
673 Size
= 8 * 1024 * 1024;
678 Size
= 1 * 1024 * 1024;
683 Size
= 2 * 1024 * 1024;
698 Size
= 1 * 1024 * 1024;
707 /* Check if this cache is bigger than the last */
708 if ((Size
/ Associativity
) > CurrentSize
)
710 /* Set the L2 Cache Size and Associativity */
711 CurrentSize
= Size
/ Associativity
;
712 Pcr
->SecondLevelCacheSize
= Size
;
713 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
718 } while (--CacheRequests
);
724 /* Check if we support CPUID 0x80000005 */
725 CPUID(0x80000000, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
726 if (Data
[0] >= 0x80000006)
728 /* Get L1 size first */
729 CPUID(0x80000005, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
730 KePrefetchNTAGranularity
= Data
[2] & 0xFF;
732 /* Check if we support CPUID 0x80000006 */
733 CPUID(0x80000000, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
734 if (Data
[0] >= 0x80000006)
736 /* Get 2nd level cache and tlb size */
737 CPUID(0x80000006, &Data
[0], &Data
[1], &Data
[2], &Data
[3]);
739 /* Cache line size */
740 CacheLine
= Data
[2] & 0xFF;
742 /* Hardcode associativity */
743 RegisterByte
= (Data
[2] >> 12) & 0xFF;
744 switch (RegisterByte
)
769 Size
= (Data
[2] >> 16) << 10;
771 /* Hack for Model 6, Steping 300 */
772 if ((KeGetCurrentPrcb()->CpuType
== 6) &&
773 (KeGetCurrentPrcb()->CpuStep
== 0x300))
775 /* Stick 64K in there */
779 /* Set the L2 Cache Size and associativity */
780 Pcr
->SecondLevelCacheSize
= Size
;
781 Pcr
->SecondLevelCacheAssociativity
= Associativity
;
795 /* Set the cache line */
796 if (CacheLine
> KeLargestCacheLine
) KeLargestCacheLine
= CacheLine
;
797 DPRINT1("Prefetch Cache: %d bytes\tL2 Cache: %d bytes\tL2 Cache Line: %d bytes\tL2 Cache Associativity: %d\n",
798 KePrefetchNTAGranularity
,
799 Pcr
->SecondLevelCacheSize
,
801 Pcr
->SecondLevelCacheAssociativity
);
811 /* Save current CR0 */
814 /* If this is a 486, enable Write-Protection */
815 if (KeGetCurrentPrcb()->CpuType
> 3) Cr0
|= CR0_WP
;
824 KiInitializeTSS2(IN PKTSS Tss
,
825 IN PKGDTENTRY TssEntry OPTIONAL
)
829 /* Make sure the GDT Entry is valid */
833 TssEntry
->LimitLow
= sizeof(KTSS
) - 1;
834 TssEntry
->HighWord
.Bits
.LimitHi
= 0;
837 /* Now clear the I/O Map */
838 ASSERT(IOPM_COUNT
== 1);
839 RtlFillMemory(Tss
->IoMaps
[0].IoMap
, IOPM_FULL_SIZE
, 0xFF);
841 /* Initialize Interrupt Direction Maps */
842 p
= (PUCHAR
)(Tss
->IoMaps
[0].DirectionMap
);
843 RtlZeroMemory(p
, IOPM_DIRECTION_MAP_SIZE
);
845 /* Add DPMI support for interrupts */
850 /* Initialize the default Interrupt Direction Map */
851 p
= Tss
->IntDirectionMap
;
852 RtlZeroMemory(Tss
->IntDirectionMap
, IOPM_DIRECTION_MAP_SIZE
);
854 /* Add DPMI support */
862 KiInitializeTSS(IN PKTSS Tss
)
864 /* Set an invalid map base */
865 Tss
->IoMapBase
= KiComputeIopmOffset(IO_ACCESS_MAP_NONE
);
867 /* Disable traps during Task Switches */
870 /* Set LDT and Ring 0 SS */
872 Tss
->Ss0
= KGDT_R0_DATA
;
878 Ki386InitializeTss(IN PKTSS Tss
,
882 PKGDTENTRY TssEntry
, TaskGateEntry
;
884 /* Initialize the boot TSS. */
885 TssEntry
= &Gdt
[KGDT_TSS
/ sizeof(KGDTENTRY
)];
886 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
887 TssEntry
->HighWord
.Bits
.Pres
= 1;
888 TssEntry
->HighWord
.Bits
.Dpl
= 0;
889 KiInitializeTSS2(Tss
, TssEntry
);
890 KiInitializeTSS(Tss
);
892 /* Load the task register */
893 Ke386SetTr(KGDT_TSS
);
895 /* Setup the Task Gate for Double Fault Traps */
896 TaskGateEntry
= (PKGDTENTRY
)&Idt
[8];
897 TaskGateEntry
->HighWord
.Bits
.Type
= I386_TASK_GATE
;
898 TaskGateEntry
->HighWord
.Bits
.Pres
= 1;
899 TaskGateEntry
->HighWord
.Bits
.Dpl
= 0;
900 ((PKIDTENTRY
)TaskGateEntry
)->Selector
= KGDT_DF_TSS
;
902 /* Initialize the TSS used for handling double faults. */
903 Tss
= (PKTSS
)KiDoubleFaultTSS
;
904 KiInitializeTSS(Tss
);
905 Tss
->CR3
= __readcr3();
906 Tss
->Esp0
= KiDoubleFaultStack
;
907 Tss
->Esp
= KiDoubleFaultStack
;
908 Tss
->Eip
= PtrToUlong(KiTrap08
);
909 Tss
->Cs
= KGDT_R0_CODE
;
910 Tss
->Fs
= KGDT_R0_PCR
;
911 Tss
->Ss
= Ke386GetSs();
912 Tss
->Es
= KGDT_R3_DATA
| RPL_MASK
;
913 Tss
->Ds
= KGDT_R3_DATA
| RPL_MASK
;
915 /* Setup the Double Trap TSS entry in the GDT */
916 TssEntry
= &Gdt
[KGDT_DF_TSS
/ sizeof(KGDTENTRY
)];
917 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
918 TssEntry
->HighWord
.Bits
.Pres
= 1;
919 TssEntry
->HighWord
.Bits
.Dpl
= 0;
920 TssEntry
->BaseLow
= (USHORT
)((ULONG_PTR
)Tss
& 0xFFFF);
921 TssEntry
->HighWord
.Bytes
.BaseMid
= (UCHAR
)((ULONG_PTR
)Tss
>> 16);
922 TssEntry
->HighWord
.Bytes
.BaseHi
= (UCHAR
)((ULONG_PTR
)Tss
>> 24);
923 TssEntry
->LimitLow
= KTSS_IO_MAPS
;
925 /* Now setup the NMI Task Gate */
926 TaskGateEntry
= (PKGDTENTRY
)&Idt
[2];
927 TaskGateEntry
->HighWord
.Bits
.Type
= I386_TASK_GATE
;
928 TaskGateEntry
->HighWord
.Bits
.Pres
= 1;
929 TaskGateEntry
->HighWord
.Bits
.Dpl
= 0;
930 ((PKIDTENTRY
)TaskGateEntry
)->Selector
= KGDT_NMI_TSS
;
932 /* Initialize the actual TSS */
933 Tss
= (PKTSS
)KiNMITSS
;
934 KiInitializeTSS(Tss
);
935 Tss
->CR3
= __readcr3();
936 Tss
->Esp0
= KiDoubleFaultStack
;
937 Tss
->Esp
= KiDoubleFaultStack
;
938 Tss
->Eip
= PtrToUlong(KiTrap02
);
939 Tss
->Cs
= KGDT_R0_CODE
;
940 Tss
->Fs
= KGDT_R0_PCR
;
941 Tss
->Ss
= Ke386GetSs();
942 Tss
->Es
= KGDT_R3_DATA
| RPL_MASK
;
943 Tss
->Ds
= KGDT_R3_DATA
| RPL_MASK
;
945 /* And its associated TSS Entry */
946 TssEntry
= &Gdt
[KGDT_NMI_TSS
/ sizeof(KGDTENTRY
)];
947 TssEntry
->HighWord
.Bits
.Type
= I386_TSS
;
948 TssEntry
->HighWord
.Bits
.Pres
= 1;
949 TssEntry
->HighWord
.Bits
.Dpl
= 0;
950 TssEntry
->BaseLow
= (USHORT
)((ULONG_PTR
)Tss
& 0xFFFF);
951 TssEntry
->HighWord
.Bytes
.BaseMid
= (UCHAR
)((ULONG_PTR
)Tss
>> 16);
952 TssEntry
->HighWord
.Bytes
.BaseHi
= (UCHAR
)((ULONG_PTR
)Tss
>> 24);
953 TssEntry
->LimitLow
= KTSS_IO_MAPS
;
958 KeFlushCurrentTb(VOID
)
960 /* Flush the TLB by resetting CR3 */
961 __writecr3(__readcr3());
966 KiRestoreProcessorControlState(PKPROCESSOR_STATE ProcessorState
)
971 // Restore the CR registers
973 __writecr0(ProcessorState
->SpecialRegisters
.Cr0
);
974 Ke386SetCr2(ProcessorState
->SpecialRegisters
.Cr2
);
975 __writecr3(ProcessorState
->SpecialRegisters
.Cr3
);
976 if (KeFeatureBits
& KF_CR4
) __writecr4(ProcessorState
->SpecialRegisters
.Cr4
);
979 // Restore the DR registers
981 __writedr(0, ProcessorState
->SpecialRegisters
.KernelDr0
);
982 __writedr(1, ProcessorState
->SpecialRegisters
.KernelDr1
);
983 __writedr(2, ProcessorState
->SpecialRegisters
.KernelDr2
);
984 __writedr(3, ProcessorState
->SpecialRegisters
.KernelDr3
);
985 __writedr(6, ProcessorState
->SpecialRegisters
.KernelDr6
);
986 __writedr(7, ProcessorState
->SpecialRegisters
.KernelDr7
);
989 // Restore GDT and IDT
991 Ke386SetGlobalDescriptorTable(&ProcessorState
->SpecialRegisters
.Gdtr
.Limit
);
992 __lidt(&ProcessorState
->SpecialRegisters
.Idtr
.Limit
);
995 // Clear the busy flag so we don't crash if we reload the same selector
997 TssEntry
= (PKGDTENTRY
)(ProcessorState
->SpecialRegisters
.Gdtr
.Base
+
998 ProcessorState
->SpecialRegisters
.Tr
);
999 TssEntry
->HighWord
.Bytes
.Flags1
&= ~0x2;
1002 // Restore TSS and LDT
1004 Ke386SetTr(ProcessorState
->SpecialRegisters
.Tr
);
1005 Ke386SetLocalDescriptorTable(ProcessorState
->SpecialRegisters
.Ldtr
);
1010 KiSaveProcessorControlState(OUT PKPROCESSOR_STATE ProcessorState
)
1012 /* Save the CR registers */
1013 ProcessorState
->SpecialRegisters
.Cr0
= __readcr0();
1014 ProcessorState
->SpecialRegisters
.Cr2
= __readcr2();
1015 ProcessorState
->SpecialRegisters
.Cr3
= __readcr3();
1016 ProcessorState
->SpecialRegisters
.Cr4
= (KeFeatureBits
& KF_CR4
) ?
1019 /* Save the DR registers */
1020 ProcessorState
->SpecialRegisters
.KernelDr0
= __readdr(0);
1021 ProcessorState
->SpecialRegisters
.KernelDr1
= __readdr(1);
1022 ProcessorState
->SpecialRegisters
.KernelDr2
= __readdr(2);
1023 ProcessorState
->SpecialRegisters
.KernelDr3
= __readdr(3);
1024 ProcessorState
->SpecialRegisters
.KernelDr6
= __readdr(6);
1025 ProcessorState
->SpecialRegisters
.KernelDr7
= __readdr(7);
1028 /* Save GDT, IDT, LDT and TSS */
1029 Ke386GetGlobalDescriptorTable(&ProcessorState
->SpecialRegisters
.Gdtr
.Limit
);
1030 __sidt(&ProcessorState
->SpecialRegisters
.Idtr
.Limit
);
1031 ProcessorState
->SpecialRegisters
.Tr
= Ke386GetTr();
1032 ProcessorState
->SpecialRegisters
.Ldtr
= Ke386GetLocalDescriptorTable();
1038 KiInitializeMachineType(VOID
)
1040 /* Set the Machine Type we got from NTLDR */
1041 KeI386MachineType
= KeLoaderBlock
->u
.I386
.MachineType
& 0x000FF;
1047 KiLoadFastSyscallMachineSpecificRegisters(IN ULONG_PTR Context
)
1049 /* Set CS and ESP */
1050 WRMSR(0x174, KGDT_R0_CODE
);
1051 WRMSR(0x175, (ULONG_PTR
)KeGetCurrentPrcb()->DpcStack
);
1054 WRMSR(0x176, (ULONG_PTR
)KiFastCallEntry
);
1061 KiRestoreFastSyscallReturnState(VOID
)
1063 /* Check if the CPU Supports fast system call */
1064 if (KeFeatureBits
& KF_FAST_SYSCALL
)
1066 /* Check if it has been disabled */
1067 if (KiFastSystemCallDisable
)
1069 /* Disable fast system call */
1070 KeFeatureBits
&= ~KF_FAST_SYSCALL
;
1071 KiFastCallExitHandler
= KiSystemCallTrapReturn
;
1072 DPRINT1("Support for SYSENTER disabled.\n");
1076 /* Do an IPI to enable it */
1077 KeIpiGenericCall(KiLoadFastSyscallMachineSpecificRegisters
, 0);
1079 /* It's enabled, so use the proper exit stub */
1080 KiFastCallExitHandler
= KiSystemCallSysExitReturn
;
1081 DPRINT("Support for SYSENTER detected.\n");
1086 /* Use the IRET handler */
1087 KiFastCallExitHandler
= KiSystemCallTrapReturn
;
1088 DPRINT1("No support for SYSENTER detected.\n");
1095 Ki386EnableDE(IN ULONG_PTR Context
)
1098 __writecr4(__readcr4() | CR4_DE
);
1105 Ki386EnableFxsr(IN ULONG_PTR Context
)
1108 __writecr4(__readcr4() | CR4_FXSR
);
1115 Ki386EnableXMMIExceptions(IN ULONG_PTR Context
)
1117 PKIDTENTRY IdtEntry
;
1119 /* Get the IDT Entry for Interrupt 0x13 */
1120 IdtEntry
= &((PKIPCR
)KeGetPcr())->IDT
[0x13];
1123 IdtEntry
->Selector
= KGDT_R0_CODE
;
1124 IdtEntry
->Offset
= ((ULONG_PTR
)KiTrap13
& 0xFFFF);
1125 IdtEntry
->ExtendedOffset
= ((ULONG_PTR
)KiTrap13
>> 16) & 0xFFFF;
1126 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->Dpl
= 0;
1127 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->Present
= 1;
1128 ((PKIDT_ACCESS
)&IdtEntry
->Access
)->SegmentType
= I386_INTERRUPT_GATE
;
1130 /* Enable XMMI exceptions */
1131 __writecr4(__readcr4() | CR4_XMMEXCPT
);
1138 KiI386PentiumLockErrataFixup(VOID
)
1140 KDESCRIPTOR IdtDescriptor
;
1141 PKIDTENTRY NewIdt
, NewIdt2
;
1143 /* Allocate memory for a new IDT */
1144 NewIdt
= ExAllocatePool(NonPagedPool
, 2 * PAGE_SIZE
);
1146 /* Put everything after the first 7 entries on a new page */
1147 NewIdt2
= (PVOID
)((ULONG_PTR
)NewIdt
+ PAGE_SIZE
- (7 * sizeof(KIDTENTRY
)));
1149 /* Disable interrupts */
1152 /* Get the current IDT and copy it */
1153 __sidt(&IdtDescriptor
.Limit
);
1154 RtlCopyMemory(NewIdt2
,
1155 (PVOID
)IdtDescriptor
.Base
,
1156 IdtDescriptor
.Limit
+ 1);
1157 IdtDescriptor
.Base
= (ULONG
)NewIdt2
;
1159 /* Set the new IDT */
1160 __lidt(&IdtDescriptor
.Limit
);
1161 ((PKIPCR
)KeGetPcr())->IDT
= NewIdt2
;
1163 /* Restore interrupts */
1166 /* Set the first 7 entries as read-only to produce a fault */
1167 MmSetPageProtect(NULL
, NewIdt
, PAGE_READONLY
);
1172 KeInvalidateAllCaches(VOID
)
1174 /* Only supported on Pentium Pro and higher */
1175 if (KeI386CpuType
< 6) return FALSE
;
1177 /* Invalidate all caches */
1184 KeZeroPages(IN PVOID Address
,
1187 /* Not using XMMI in this routine */
1188 RtlZeroMemory(Address
, Size
);
1193 KiSaveProcessorState(IN PKTRAP_FRAME TrapFrame
,
1194 IN PKEXCEPTION_FRAME ExceptionFrame
)
1196 PKPRCB Prcb
= KeGetCurrentPrcb();
1199 // Save full context
1201 Prcb
->ProcessorState
.ContextFrame
.ContextFlags
= CONTEXT_FULL
|
1202 CONTEXT_DEBUG_REGISTERS
;
1203 KeTrapFrameToContext(TrapFrame
, NULL
, &Prcb
->ProcessorState
.ContextFrame
);
1206 // Save control registers
1208 KiSaveProcessorControlState(&Prcb
->ProcessorState
);
1214 KiIsNpxPresent(VOID
)
1222 /* Read CR0 and mask out FPU flags */
1223 Cr0
= __readcr0() & ~(CR0_MP
| CR0_TS
| CR0_EM
| CR0_ET
);
1225 /* Store on FPU stack */
1230 asm volatile ("fninit;" "fnstsw %0" : "+m"(Magic
));
1233 /* Magic should now be cleared */
1236 /* You don't have an FPU -- enable emulation for now */
1237 __writecr0(Cr0
| CR0_EM
| CR0_TS
);
1241 /* You have an FPU, enable it */
1244 /* Enable INT 16 on 486 and higher */
1245 if (KeGetCurrentPrcb()->CpuType
>= 3) Cr0
|= CR0_NE
;
1248 __writecr0(Cr0
| CR0_EM
| CR0_TS
);
1255 KiIsNpxErrataPresent(VOID
)
1257 static double Value1
= 4195835.0, Value2
= 3145727.0;
1261 /* Disable interrupts */
1264 /* Read CR0 and remove FPU flags */
1266 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1268 /* Initialize FPU state */
1271 /* Multiply the magic values and divide, we should get the result back */
1273 __asm__ __volatile__
1281 : "=m" (ErrataPresent
)
1300 /* Enable interrupts */
1303 /* Return if there's an errata */
1304 return ErrataPresent
!= 0;
1309 KiFlushNPXState(IN PFLOATING_SAVE_AREA SaveArea
)
1312 PKTHREAD Thread
, NpxThread
;
1313 PFX_SAVE_AREA FxSaveArea
;
1315 /* Save volatiles and disable interrupts */
1316 EFlags
= __readeflags();
1319 /* Save the PCR and get the current thread */
1320 Thread
= KeGetCurrentThread();
1322 /* Check if we're already loaded */
1323 if (Thread
->NpxState
!= NPX_STATE_LOADED
)
1325 /* If there's nothing to load, quit */
1328 /* Restore interrupt state and return */
1329 __writeeflags(EFlags
);
1333 /* Need FXSR support for this */
1334 ASSERT(KeI386FxsrPresent
== TRUE
);
1336 /* Check for sane CR0 */
1338 if (Cr0
& (CR0_MP
| CR0_TS
| CR0_EM
))
1340 /* Mask out FPU flags */
1341 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1344 /* Get the NPX thread and check its FPU state */
1345 NpxThread
= KeGetCurrentPrcb()->NpxThread
;
1346 if ((NpxThread
) && (NpxThread
->NpxState
== NPX_STATE_LOADED
))
1348 /* Get the FX frame and store the state there */
1349 FxSaveArea
= KiGetThreadNpxArea(NpxThread
);
1350 Ke386FxSave(FxSaveArea
);
1352 /* NPX thread has lost its state */
1353 NpxThread
->NpxState
= NPX_STATE_NOT_LOADED
;
1356 /* Now load NPX state from the NPX area */
1357 FxSaveArea
= KiGetThreadNpxArea(Thread
);
1358 Ke386FxStore(FxSaveArea
);
1362 /* Check for sane CR0 */
1364 if (Cr0
& (CR0_MP
| CR0_TS
| CR0_EM
))
1366 /* Mask out FPU flags */
1367 __writecr0(Cr0
& ~(CR0_MP
| CR0_TS
| CR0_EM
));
1371 FxSaveArea
= KiGetThreadNpxArea(Thread
);
1372 Thread
->NpxState
= NPX_STATE_NOT_LOADED
;
1374 /* Save state if supported by CPU */
1375 if (KeI386FxsrPresent
) Ke386FxSave(FxSaveArea
);
1378 /* Now save the FN state wherever it was requested */
1379 if (SaveArea
) Ke386FnSave(SaveArea
);
1381 /* Clear NPX thread */
1382 KeGetCurrentPrcb()->NpxThread
= NULL
;
1384 /* Add the CR0 from the NPX frame */
1385 Cr0
|= NPX_STATE_NOT_LOADED
;
1386 Cr0
|= FxSaveArea
->Cr0NpxState
;
1389 /* Restore interrupt state */
1390 __writeeflags(EFlags
);
1393 /* PUBLIC FUNCTIONS **********************************************************/
1400 KiCoprocessorError(VOID
)
1402 PFX_SAVE_AREA NpxArea
;
1404 /* Get the FPU area */
1405 NpxArea
= KiGetThreadNpxArea(KeGetCurrentThread());
1408 NpxArea
->Cr0NpxState
= CR0_TS
;
1409 __writecr0(__readcr0() | CR0_TS
);
1417 KeSaveFloatingPointState(OUT PKFLOATING_SAVE Save
)
1419 PFNSAVE_FORMAT FpState
;
1420 ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL
);
1421 DPRINT1("%s is not really implemented\n", __FUNCTION__
);
1423 /* check if we are doing software emulation */
1424 if (!KeI386NpxPresent
) return STATUS_ILLEGAL_FLOAT_CONTEXT
;
1426 FpState
= ExAllocatePool(NonPagedPool
, sizeof (FNSAVE_FORMAT
));
1427 if (!FpState
) return STATUS_INSUFFICIENT_RESOURCES
;
1429 *((PVOID
*) Save
) = FpState
;
1431 asm volatile("fnsave %0\n\t" : "=m" (*FpState
));
1439 KeGetCurrentThread()->Header
.NpxIrql
= KeGetCurrentIrql();
1440 return STATUS_SUCCESS
;
1448 KeRestoreFloatingPointState(IN PKFLOATING_SAVE Save
)
1450 PFNSAVE_FORMAT FpState
= *((PVOID
*) Save
);
1451 ASSERT(KeGetCurrentThread()->Header
.NpxIrql
== KeGetCurrentIrql());
1452 DPRINT1("%s is not really implemented\n", __FUNCTION__
);
1455 asm volatile("fnclex\n\t");
1456 asm volatile("frstor %0\n\t" : "=m" (*FpState
));
1465 ExFreePool(FpState
);
1466 return STATUS_SUCCESS
;
1474 KeGetRecommendedSharedDataAlignment(VOID
)
1476 /* Return the global variable */
1477 return KeLargestCacheLine
;
1482 KiFlushTargetEntireTb(IN PKIPI_CONTEXT PacketContext
,
1487 /* Signal this packet as done */
1488 KiIpiSignalPacketDone(PacketContext
);
1490 /* Flush the TB for the Current CPU */
1499 KeFlushEntireTb(IN BOOLEAN Invalid
,
1500 IN BOOLEAN AllProcessors
)
1504 KAFFINITY TargetAffinity
;
1505 PKPRCB Prcb
= KeGetCurrentPrcb();
1508 /* Raise the IRQL for the TB Flush */
1509 OldIrql
= KeRaiseIrqlToSynchLevel();
1512 /* FIXME: Use KiTbFlushTimeStamp to synchronize TB flush */
1514 /* Get the current processor affinity, and exclude ourselves */
1515 TargetAffinity
= KeActiveProcessors
;
1516 TargetAffinity
&= ~Prcb
->SetMember
;
1518 /* Make sure this is MP */
1521 /* Send an IPI TB flush to the other processors */
1522 KiIpiSendPacket(TargetAffinity
,
1523 KiFlushTargetEntireTb
,
1530 /* Flush the TB for the Current CPU, and update the flush stamp */
1534 /* If this is MP, wait for the other processors to finish */
1538 ASSERT(Prcb
== (volatile PKPRCB
)KeGetCurrentPrcb());
1541 ASSERTMSG("Not yet implemented\n", FALSE
);
1545 /* Update the flush stamp and return to original IRQL */
1546 InterlockedExchangeAdd(&KiTbFlushTimeStamp
, 1);
1547 KeLowerIrql(OldIrql
);
1555 KeSetDmaIoCoherency(IN ULONG Coherency
)
1557 /* Save the coherency globally */
1558 KiDmaIoCoherency
= Coherency
;
1566 KeQueryActiveProcessors(VOID
)
1570 /* Simply return the number of active processors */
1571 return KeActiveProcessors
;
1579 KeSaveStateForHibernate(IN PKPROCESSOR_STATE State
)
1581 /* Capture the context */
1582 RtlCaptureContext(&State
->ContextFrame
);
1584 /* Capture the control state */
1585 KiSaveProcessorControlState(State
);