[NTOSKRNL]
[reactos.git] / reactos / ntoskrnl / ke / i386 / cpu.c
1 /*
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)
7 */
8
9 /* INCLUDES *****************************************************************/
10
11 #include <ntoskrnl.h>
12 #define NDEBUG
13 #include <debug.h>
14
15 /* GLOBALS *******************************************************************/
16
17 /* The TSS to use for Double Fault Traps (INT 0x9) */
18 UCHAR KiDoubleFaultTSS[KTSS_IO_MAPS];
19
20 /* The TSS to use for NMI Fault Traps (INT 0x2) */
21 UCHAR KiNMITSS[KTSS_IO_MAPS];
22
23 /* CPU Features and Flags */
24 ULONG KeI386CpuType;
25 ULONG KeI386CpuStep;
26 ULONG KeProcessorArchitecture;
27 ULONG KeProcessorLevel;
28 ULONG KeProcessorRevision;
29 ULONG KeFeatureBits;
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;
48
49 /* The distance between SYSEXIT and IRETD return modes */
50 UCHAR KiSystemCallExitAdjust;
51
52 /* The offset that was applied -- either 0 or the value above */
53 UCHAR KiSystemCallExitAdjusted;
54
55 /* Whether the adjustment was already done once */
56 BOOLEAN KiFastCallCopyDoneOnce;
57
58 /* Flush data */
59 volatile LONG KiTbFlushTimeStamp;
60
61 /* CPU Signatures */
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";
68
69 /* SUPPORT ROUTINES FOR MSVC COMPATIBILITY ***********************************/
70
71 VOID
72 NTAPI
73 CPUID(IN ULONG InfoType,
74 OUT PULONG CpuInfoEax,
75 OUT PULONG CpuInfoEbx,
76 OUT PULONG CpuInfoEcx,
77 OUT PULONG CpuInfoEdx)
78 {
79 ULONG CpuInfo[4];
80
81 /* Perform the CPUID Operation */
82 __cpuid((int*)CpuInfo, InfoType);
83
84 /* Return the results */
85 *CpuInfoEax = CpuInfo[0];
86 *CpuInfoEbx = CpuInfo[1];
87 *CpuInfoEcx = CpuInfo[2];
88 *CpuInfoEdx = CpuInfo[3];
89 }
90
91 VOID
92 NTAPI
93 WRMSR(IN ULONG Register,
94 IN LONGLONG Value)
95 {
96 /* Write to the MSR */
97 __writemsr(Register, Value);
98 }
99
100 LONGLONG
101 FASTCALL
102 RDMSR(IN ULONG Register)
103 {
104 /* Read from the MSR */
105 return __readmsr(Register);
106 }
107
108 /* NSC/Cyrix CPU configuration register index */
109 #define CX86_CCR1 0xc1
110
111 /* NSC/Cyrix CPU indexed register access macros */
112 static __inline
113 ULONG
114 getCx86(UCHAR reg)
115 {
116 WRITE_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x22, reg);
117 return READ_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x23);
118 }
119
120 #define setCx86(reg, data) do { \
121 WRITE_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x22,(reg)); \
122 WRITE_PORT_UCHAR((PUCHAR)(ULONG_PTR)0x23,(data)); \
123 } while (0)
124
125 /* FUNCTIONS *****************************************************************/
126
127 VOID
128 NTAPI
129 INIT_FUNCTION
130 KiSetProcessorType(VOID)
131 {
132 ULONG EFlags, NewEFlags;
133 ULONG Reg, Dummy;
134 ULONG Stepping, Type;
135
136 /* Start by assuming no CPUID data */
137 KeGetCurrentPrcb()->CpuID = 0;
138
139 /* Save EFlags */
140 EFlags = __readeflags();
141
142 /* XOR out the ID bit and update EFlags */
143 NewEFlags = EFlags ^ EFLAGS_ID;
144 __writeeflags(NewEFlags);
145
146 /* Get them back and see if they were modified */
147 NewEFlags = __readeflags();
148 if (NewEFlags != EFlags)
149 {
150 /* The modification worked, so CPUID exists. Set the ID Bit again. */
151 EFlags |= EFLAGS_ID;
152 __writeeflags(EFlags);
153
154 /* Peform CPUID 0 to see if CPUID 1 is supported */
155 CPUID(0, &Reg, &Dummy, &Dummy, &Dummy);
156 if (Reg > 0)
157 {
158 /* Do CPUID 1 now */
159 CPUID(1, &Reg, &Dummy, &Dummy, &Dummy);
160
161 /*
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.
165 *
166 * For the stepping, we convert this: zzzzzzxy into this: x0y
167 */
168 Stepping = Reg & 0xF0;
169 Stepping <<= 4;
170 Stepping += (Reg & 0xFF);
171 Stepping &= 0xF0F;
172 Type = Reg & 0xF00;
173 Type >>= 8;
174
175 /* Save them in the PRCB */
176 KeGetCurrentPrcb()->CpuID = TRUE;
177 KeGetCurrentPrcb()->CpuType = (UCHAR)Type;
178 KeGetCurrentPrcb()->CpuStep = (USHORT)Stepping;
179 }
180 else
181 {
182 DPRINT1("CPUID Support lacking\n");
183 }
184 }
185 else
186 {
187 DPRINT1("CPUID Support lacking\n");
188 }
189
190 /* Restore EFLAGS */
191 __writeeflags(EFlags);
192 }
193
194 ULONG
195 NTAPI
196 INIT_FUNCTION
197 KiGetCpuVendor(VOID)
198 {
199 PKPRCB Prcb = KeGetCurrentPrcb();
200 ULONG Vendor[5];
201 ULONG Temp;
202
203 /* Assume no Vendor ID and fail if no CPUID Support. */
204 Prcb->VendorString[0] = 0;
205 if (!Prcb->CpuID) return 0;
206
207 /* Get the Vendor ID and null-terminate it */
208 CPUID(0, &Vendor[0], &Vendor[1], &Vendor[2], &Vendor[3]);
209 Vendor[4] = 0;
210
211 /* Re-arrange vendor string */
212 Temp = Vendor[2];
213 Vendor[2] = Vendor[3];
214 Vendor[3] = Temp;
215
216 /* Copy it to the PRCB and null-terminate it again */
217 RtlCopyMemory(Prcb->VendorString,
218 &Vendor[1],
219 sizeof(Prcb->VendorString) - sizeof(CHAR));
220 Prcb->VendorString[sizeof(Prcb->VendorString) - sizeof(CHAR)] = ANSI_NULL;
221
222 /* Now check the CPU Type */
223 if (!strcmp(Prcb->VendorString, CmpIntelID))
224 {
225 return CPU_INTEL;
226 }
227 else if (!strcmp(Prcb->VendorString, CmpAmdID))
228 {
229 return CPU_AMD;
230 }
231 else if (!strcmp(Prcb->VendorString, CmpCyrixID))
232 {
233 DPRINT1("Cyrix CPU support not fully tested!\n");
234 return CPU_CYRIX;
235 }
236 else if (!strcmp(Prcb->VendorString, CmpTransmetaID))
237 {
238 DPRINT1("Transmeta CPU support not fully tested!\n");
239 return CPU_TRANSMETA;
240 }
241 else if (!strcmp(Prcb->VendorString, CmpCentaurID))
242 {
243 DPRINT1("Centaur CPU support not fully tested!\n");
244 return CPU_CENTAUR;
245 }
246 else if (!strcmp(Prcb->VendorString, CmpRiseID))
247 {
248 DPRINT1("Rise CPU support not fully tested!\n");
249 return CPU_RISE;
250 }
251
252 /* Invalid CPU */
253 return 0;
254 }
255
256 ULONG
257 NTAPI
258 INIT_FUNCTION
259 KiGetFeatureBits(VOID)
260 {
261 PKPRCB Prcb = KeGetCurrentPrcb();
262 ULONG Vendor;
263 ULONG FeatureBits = KF_WORKING_PTE;
264 ULONG Reg[4], Dummy, Ccr1;
265 BOOLEAN ExtendedCPUID = TRUE;
266 ULONG CpuFeatures = 0;
267
268 /* Get the Vendor ID */
269 Vendor = KiGetCpuVendor();
270
271 /* Make sure we got a valid vendor ID at least. */
272 if (!Vendor) return FeatureBits;
273
274 /* Get the CPUID Info. Features are in Reg[3]. */
275 CPUID(1, &Reg[0], &Reg[1], &Dummy, &Reg[3]);
276
277 /* Set the initial APIC ID */
278 Prcb->InitialApicId = (UCHAR)(Reg[1] >> 24);
279
280 switch (Vendor)
281 {
282 /* Intel CPUs */
283 case CPU_INTEL:
284
285 /* Check if it's a P6 */
286 if (Prcb->CpuType == 6)
287 {
288 /* Perform the special sequence to get the MicroCode Signature */
289 WRMSR(0x8B, 0);
290 CPUID(1, &Dummy, &Dummy, &Dummy, &Dummy);
291 Prcb->UpdateSignature.QuadPart = RDMSR(0x8B);
292 }
293 else if (Prcb->CpuType == 5)
294 {
295 /* On P5, enable workaround for the LOCK errata. */
296 KiI386PentiumLockErrataPresent = TRUE;
297 }
298
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))
302 {
303 /* Remove support for correct PTE support. */
304 FeatureBits &= ~KF_WORKING_PTE;
305 }
306
307 /* Virtualbox claims to have no SYSENTER support,
308 * which is false for processors >= Pentium Pro */
309 if(Prcb->CpuType >= 6)
310 {
311 Reg[3] |= 0x800;
312 }
313
314 /* Check if the CPU is too old to support SYSENTER,
315 * See Intel CPUID instruction manual for details*/
316 if ((Reg[0] & 0x0FFF3FFF) < 0x00000633)
317 {
318 /* Disable it */
319 Reg[3] &= ~0x800;
320 }
321
322 /* Set the current features */
323 CpuFeatures = Reg[3];
324
325 break;
326
327 /* AMD CPUs */
328 case CPU_AMD:
329
330 /* Check if this is a K5 or K6. (family 5) */
331 if ((Reg[0] & 0x0F00) == 0x0500)
332 {
333 /* Get the Model Number */
334 switch (Reg[0] & 0x00F0)
335 {
336 /* Model 1: K5 - 5k86 (initial models) */
337 case 0x0010:
338
339 /* Check if this is Step 0 or 1. They don't support PGE */
340 if ((Reg[0] & 0x000F) > 0x03) break;
341
342 /* Model 0: K5 - SSA5 */
343 case 0x0000:
344
345 /* Model 0 doesn't support PGE at all. */
346 Reg[3] &= ~0x2000;
347 break;
348
349 /* Model 8: K6-2 */
350 case 0x0080:
351
352 /* K6-2, Step 8 and over have support for MTRR. */
353 if ((Reg[0] & 0x000F) >= 0x8) FeatureBits |= KF_AMDK6MTRR;
354 break;
355
356 /* Model 9: K6-III
357 Model D: K6-2+, K6-III+ */
358 case 0x0090:
359 case 0x00D0:
360
361 FeatureBits |= KF_AMDK6MTRR;
362 break;
363 }
364 }
365 else if((Reg[0] & 0x0F00) < 0x0500)
366 {
367 /* Families below 5 don't support PGE, PSE or CMOV at all */
368 Reg[3] &= ~(0x08 | 0x2000 | 0x8000);
369
370 /* They also don't support advanced CPUID functions. */
371 ExtendedCPUID = FALSE;
372 }
373
374 /* Set the current features */
375 CpuFeatures = Reg[3];
376
377 break;
378
379 /* Cyrix CPUs */
380 case CPU_CYRIX:
381
382 /* Workaround the "COMA" bug on 6x family of Cyrix CPUs */
383 if (Prcb->CpuType == 6 &&
384 Prcb->CpuStep <= 1)
385 {
386 /* Get CCR1 value */
387 Ccr1 = getCx86(CX86_CCR1);
388
389 /* Enable the NO_LOCK bit */
390 Ccr1 |= 0x10;
391
392 /* Set the new CCR1 value */
393 setCx86(CX86_CCR1, Ccr1);
394 }
395
396 /* Set the current features */
397 CpuFeatures = Reg[3];
398
399 break;
400
401 /* Transmeta CPUs */
402 case CPU_TRANSMETA:
403
404 /* Enable CMPXCHG8B if the family (>= 5), model and stepping (>= 4.2) support it */
405 if ((Reg[0] & 0x0FFF) >= 0x0542)
406 {
407 WRMSR(0x80860004, RDMSR(0x80860004) | 0x0100);
408 FeatureBits |= KF_CMPXCHG8B;
409 }
410
411 break;
412
413 /* Centaur, IDT, Rise and VIA CPUs */
414 case CPU_CENTAUR:
415 case CPU_RISE:
416
417 /* These CPUs don't report the presence of CMPXCHG8B through CPUID.
418 However, this feature exists and operates properly without any additional steps. */
419 FeatureBits |= KF_CMPXCHG8B;
420
421 break;
422 }
423
424 /* Convert all CPUID Feature bits into our format */
425 if (CpuFeatures & 0x00000002) FeatureBits |= KF_V86_VIS | KF_CR4;
426 if (CpuFeatures & 0x00000008) FeatureBits |= KF_LARGE_PAGE | KF_CR4;
427 if (CpuFeatures & 0x00000010) FeatureBits |= KF_RDTSC;
428 if (CpuFeatures & 0x00000100) FeatureBits |= KF_CMPXCHG8B;
429 if (CpuFeatures & 0x00000800) FeatureBits |= KF_FAST_SYSCALL;
430 if (CpuFeatures & 0x00001000) FeatureBits |= KF_MTRR;
431 if (CpuFeatures & 0x00002000) FeatureBits |= KF_GLOBAL_PAGE | KF_CR4;
432 if (CpuFeatures & 0x00008000) FeatureBits |= KF_CMOV;
433 if (CpuFeatures & 0x00010000) FeatureBits |= KF_PAT;
434 if (CpuFeatures & 0x00200000) FeatureBits |= KF_DTS;
435 if (CpuFeatures & 0x00800000) FeatureBits |= KF_MMX;
436 if (CpuFeatures & 0x01000000) FeatureBits |= KF_FXSR;
437 if (CpuFeatures & 0x02000000) FeatureBits |= KF_XMMI;
438 if (CpuFeatures & 0x04000000) FeatureBits |= KF_XMMI64;
439
440 /* Check if the CPU has hyper-threading */
441 if (CpuFeatures & 0x10000000)
442 {
443 /* Set the number of logical CPUs */
444 Prcb->LogicalProcessorsPerPhysicalProcessor = (UCHAR)(Reg[1] >> 16);
445 if (Prcb->LogicalProcessorsPerPhysicalProcessor > 1)
446 {
447 /* We're on dual-core */
448 KiSMTProcessorsPresent = TRUE;
449 }
450 }
451 else
452 {
453 /* We only have a single CPU */
454 Prcb->LogicalProcessorsPerPhysicalProcessor = 1;
455 }
456
457 /* Check if CPUID 0x80000000 is supported */
458 if (ExtendedCPUID)
459 {
460 /* Do the call */
461 CPUID(0x80000000, &Reg[0], &Dummy, &Dummy, &Dummy);
462 if ((Reg[0] & 0xffffff00) == 0x80000000)
463 {
464 /* Check if CPUID 0x80000001 is supported */
465 if (Reg[0] >= 0x80000001)
466 {
467 /* Check which extended features are available. */
468 CPUID(0x80000001, &Dummy, &Dummy, &Dummy, &Reg[3]);
469
470 /* Check if NX-bit is supported */
471 if (Reg[3] & 0x00100000) FeatureBits |= KF_NX_BIT;
472
473 /* Now handle each features for each CPU Vendor */
474 switch (Vendor)
475 {
476 case CPU_AMD:
477 case CPU_CENTAUR:
478 if (Reg[3] & 0x80000000) FeatureBits |= KF_3DNOW;
479 break;
480 }
481 }
482 }
483 }
484
485 DPRINT1("Supported CPU features :\n");
486 #define print_supported(kf_value) \
487 if(FeatureBits & kf_value) DPRINT1("\t" #kf_value)
488 print_supported(KF_V86_VIS);
489 print_supported(KF_RDTSC);
490 print_supported(KF_CR4);
491 print_supported(KF_CMOV);
492 print_supported(KF_GLOBAL_PAGE);
493 print_supported(KF_LARGE_PAGE);
494 print_supported(KF_MTRR);
495 print_supported(KF_CMPXCHG8B);
496 print_supported(KF_MMX);
497 print_supported(KF_WORKING_PTE);
498 print_supported(KF_PAT);
499 print_supported(KF_FXSR);
500 print_supported(KF_FAST_SYSCALL);
501 print_supported(KF_XMMI);
502 print_supported(KF_3DNOW);
503 print_supported(KF_AMDK6MTRR);
504 print_supported(KF_XMMI64);
505 print_supported(KF_DTS);
506 print_supported(KF_NX_BIT);
507 print_supported(KF_NX_DISABLED);
508 print_supported(KF_NX_ENABLED);
509 #undef print_supported
510 DPRINT1("\n");
511
512 /* Return the Feature Bits */
513 return FeatureBits;
514 }
515
516 VOID
517 NTAPI
518 INIT_FUNCTION
519 KiGetCacheInformation(VOID)
520 {
521 PKIPCR Pcr = (PKIPCR)KeGetPcr();
522 ULONG Vendor;
523 ULONG Data[4], Dummy;
524 ULONG CacheRequests = 0, i;
525 ULONG CurrentRegister;
526 UCHAR RegisterByte;
527 ULONG Size, Associativity = 0, CacheLine = 64, CurrentSize = 0;
528 BOOLEAN FirstPass = TRUE;
529
530 /* Set default L2 size */
531 Pcr->SecondLevelCacheSize = 0;
532
533 /* Get the Vendor ID and make sure we support CPUID */
534 Vendor = KiGetCpuVendor();
535 if (!Vendor) return;
536
537 /* Check the Vendor ID */
538 switch (Vendor)
539 {
540 /* Handle Intel case */
541 case CPU_INTEL:
542
543 /*Check if we support CPUID 2 */
544 CPUID(0, &Data[0], &Dummy, &Dummy, &Dummy);
545 if (Data[0] >= 2)
546 {
547 /* We need to loop for the number of times CPUID will tell us to */
548 do
549 {
550 /* Do the CPUID call */
551 CPUID(2, &Data[0], &Data[1], &Data[2], &Data[3]);
552
553 /* Check if it was the first call */
554 if (FirstPass)
555 {
556 /*
557 * The number of times to loop is the first byte. Read
558 * it and then destroy it so we don't get confused.
559 */
560 CacheRequests = Data[0] & 0xFF;
561 Data[0] &= 0xFFFFFF00;
562
563 /* Don't go over this again */
564 FirstPass = FALSE;
565 }
566
567 /* Loop all 4 registers */
568 for (i = 0; i < 4; i++)
569 {
570 /* Get the current register */
571 CurrentRegister = Data[i];
572
573 /*
574 * If the upper bit is set, then this register should
575 * be skipped.
576 */
577 if (CurrentRegister & 0x80000000) continue;
578
579 /* Keep looping for every byte inside this register */
580 while (CurrentRegister)
581 {
582 /* Read a byte, skip a byte. */
583 RegisterByte = (UCHAR)(CurrentRegister & 0xFF);
584 CurrentRegister >>= 8;
585 if (!RegisterByte) continue;
586
587 /*
588 * Valid values are from 0x40 (0 bytes) to 0x49
589 * (32MB), or from 0x80 to 0x89 (same size but
590 * 8-way associative.
591 */
592 if (((RegisterByte > 0x40) && (RegisterByte <= 0x47)) ||
593 ((RegisterByte > 0x78) && (RegisterByte <= 0x7C)) ||
594 ((RegisterByte > 0x80) && (RegisterByte <= 0x85)))
595 {
596 /* Compute associativity */
597 Associativity = 4;
598 if (RegisterByte >= 0x79) Associativity = 8;
599
600 /* Mask out only the first nibble */
601 RegisterByte &= 0x07;
602
603 /* Check if this cache is bigger than the last */
604 Size = 0x10000 << RegisterByte;
605 if ((Size / Associativity) > CurrentSize)
606 {
607 /* Set the L2 Cache Size and Associativity */
608 CurrentSize = Size / Associativity;
609 Pcr->SecondLevelCacheSize = Size;
610 Pcr->SecondLevelCacheAssociativity = Associativity;
611 }
612 }
613 else if ((RegisterByte > 0x21) && (RegisterByte <= 0x29))
614 {
615 /* Set minimum cache line size */
616 if (CacheLine < 128) CacheLine = 128;
617
618 /* Hard-code size/associativity */
619 Associativity = 8;
620 switch (RegisterByte)
621 {
622 case 0x22:
623 Size = 512 * 1024;
624 Associativity = 4;
625 break;
626
627 case 0x23:
628 Size = 1024 * 1024;
629 break;
630
631 case 0x25:
632 Size = 2048 * 1024;
633 break;
634
635 case 0x29:
636 Size = 4096 * 1024;
637 break;
638
639 default:
640 Size = 0;
641 break;
642 }
643
644 /* Check if this cache is bigger than the last */
645 if ((Size / Associativity) > CurrentSize)
646 {
647 /* Set the L2 Cache Size and Associativity */
648 CurrentSize = Size / Associativity;
649 Pcr->SecondLevelCacheSize = Size;
650 Pcr->SecondLevelCacheAssociativity = Associativity;
651 }
652 }
653 else if (((RegisterByte > 0x65) && (RegisterByte < 0x69)) ||
654 (RegisterByte == 0x2C) || (RegisterByte == 0xF0))
655 {
656 /* Indicates L1 cache line of 64 bytes */
657 KePrefetchNTAGranularity = 64;
658 }
659 else if (RegisterByte == 0xF1)
660 {
661 /* Indicates L1 cache line of 128 bytes */
662 KePrefetchNTAGranularity = 128;
663 }
664 else if (((RegisterByte >= 0x4A) && (RegisterByte <= 0x4C)) ||
665 (RegisterByte == 0x78) ||
666 (RegisterByte == 0x7D) ||
667 (RegisterByte == 0x7F) ||
668 (RegisterByte == 0x86) ||
669 (RegisterByte == 0x87))
670 {
671 /* Set minimum cache line size */
672 if (CacheLine < 64) CacheLine = 64;
673
674 /* Hard-code size/associativity */
675 switch (RegisterByte)
676 {
677 case 0x4A:
678 Size = 4 * 1024 * 1024;
679 Associativity = 8;
680 break;
681
682 case 0x4B:
683 Size = 6 * 1024 * 1024;
684 Associativity = 12;
685 break;
686
687 case 0x4C:
688 Size = 8 * 1024 * 1024;
689 Associativity = 16;
690 break;
691
692 case 0x78:
693 Size = 1 * 1024 * 1024;
694 Associativity = 4;
695 break;
696
697 case 0x7D:
698 Size = 2 * 1024 * 1024;
699 Associativity = 8;
700 break;
701
702 case 0x7F:
703 Size = 512 * 1024;
704 Associativity = 2;
705 break;
706
707 case 0x86:
708 Size = 512 * 1024;
709 Associativity = 4;
710 break;
711
712 case 0x87:
713 Size = 1 * 1024 * 1024;
714 Associativity = 8;
715 break;
716
717 default:
718 Size = 0;
719 break;
720 }
721
722 /* Check if this cache is bigger than the last */
723 if ((Size / Associativity) > CurrentSize)
724 {
725 /* Set the L2 Cache Size and Associativity */
726 CurrentSize = Size / Associativity;
727 Pcr->SecondLevelCacheSize = Size;
728 Pcr->SecondLevelCacheAssociativity = Associativity;
729 }
730 }
731 }
732 }
733 } while (--CacheRequests);
734 }
735 break;
736
737 case CPU_AMD:
738
739 /* Check if we support CPUID 0x80000005 */
740 CPUID(0x80000000, &Data[0], &Data[1], &Data[2], &Data[3]);
741 if (Data[0] >= 0x80000006)
742 {
743 /* Get L1 size first */
744 CPUID(0x80000005, &Data[0], &Data[1], &Data[2], &Data[3]);
745 KePrefetchNTAGranularity = Data[2] & 0xFF;
746
747 /* Check if we support CPUID 0x80000006 */
748 CPUID(0x80000000, &Data[0], &Data[1], &Data[2], &Data[3]);
749 if (Data[0] >= 0x80000006)
750 {
751 /* Get 2nd level cache and tlb size */
752 CPUID(0x80000006, &Data[0], &Data[1], &Data[2], &Data[3]);
753
754 /* Cache line size */
755 CacheLine = Data[2] & 0xFF;
756
757 /* Hardcode associativity */
758 RegisterByte = Data[2] >> 12;
759 switch (RegisterByte)
760 {
761 case 2:
762 Associativity = 2;
763 break;
764
765 case 4:
766 Associativity = 4;
767 break;
768
769 case 6:
770 Associativity = 8;
771 break;
772
773 case 8:
774 case 15:
775 Associativity = 16;
776 break;
777
778 default:
779 Associativity = 1;
780 break;
781 }
782
783 /* Compute size */
784 Size = (Data[2] >> 16) << 10;
785
786 /* Hack for Model 6, Steping 300 */
787 if ((KeGetCurrentPrcb()->CpuType == 6) &&
788 (KeGetCurrentPrcb()->CpuStep == 0x300))
789 {
790 /* Stick 64K in there */
791 Size = 64 * 1024;
792 }
793
794 /* Set the L2 Cache Size and associativity */
795 Pcr->SecondLevelCacheSize = Size;
796 Pcr->SecondLevelCacheAssociativity = Associativity;
797 }
798 }
799 break;
800
801 case CPU_CYRIX:
802 case CPU_TRANSMETA:
803 case CPU_CENTAUR:
804 case CPU_RISE:
805
806 /* FIXME */
807 break;
808 }
809
810 /* Set the cache line */
811 if (CacheLine > KeLargestCacheLine) KeLargestCacheLine = CacheLine;
812 DPRINT1("Prefetch Cache: %d bytes\tL2 Cache: %d bytes\tL2 Cache Line: %d bytes\tL2 Cache Associativity: %d\n",
813 KePrefetchNTAGranularity,
814 Pcr->SecondLevelCacheSize,
815 KeLargestCacheLine,
816 Pcr->SecondLevelCacheAssociativity);
817 }
818
819 VOID
820 NTAPI
821 INIT_FUNCTION
822 KiSetCR0Bits(VOID)
823 {
824 ULONG Cr0;
825
826 /* Save current CR0 */
827 Cr0 = __readcr0();
828
829 /* If this is a 486, enable Write-Protection */
830 if (KeGetCurrentPrcb()->CpuType > 3) Cr0 |= CR0_WP;
831
832 /* Set new Cr0 */
833 __writecr0(Cr0);
834 }
835
836 VOID
837 NTAPI
838 INIT_FUNCTION
839 KiInitializeTSS2(IN PKTSS Tss,
840 IN PKGDTENTRY TssEntry OPTIONAL)
841 {
842 PUCHAR p;
843
844 /* Make sure the GDT Entry is valid */
845 if (TssEntry)
846 {
847 /* Set the Limit */
848 TssEntry->LimitLow = sizeof(KTSS) - 1;
849 TssEntry->HighWord.Bits.LimitHi = 0;
850 }
851
852 /* Now clear the I/O Map */
853 ASSERT(IOPM_COUNT == 1);
854 RtlFillMemory(Tss->IoMaps[0].IoMap, IOPM_FULL_SIZE, 0xFF);
855
856 /* Initialize Interrupt Direction Maps */
857 p = (PUCHAR)(Tss->IoMaps[0].DirectionMap);
858 RtlZeroMemory(p, IOPM_DIRECTION_MAP_SIZE);
859
860 /* Add DPMI support for interrupts */
861 p[0] = 4;
862 p[3] = 0x18;
863 p[4] = 0x18;
864
865 /* Initialize the default Interrupt Direction Map */
866 p = Tss->IntDirectionMap;
867 RtlZeroMemory(Tss->IntDirectionMap, IOPM_DIRECTION_MAP_SIZE);
868
869 /* Add DPMI support */
870 p[0] = 4;
871 p[3] = 0x18;
872 p[4] = 0x18;
873 }
874
875 VOID
876 NTAPI
877 KiInitializeTSS(IN PKTSS Tss)
878 {
879 /* Set an invalid map base */
880 Tss->IoMapBase = KiComputeIopmOffset(IO_ACCESS_MAP_NONE);
881
882 /* Disable traps during Task Switches */
883 Tss->Flags = 0;
884
885 /* Set LDT and Ring 0 SS */
886 Tss->LDT = 0;
887 Tss->Ss0 = KGDT_R0_DATA;
888 }
889
890 VOID
891 FASTCALL
892 INIT_FUNCTION
893 Ki386InitializeTss(IN PKTSS Tss,
894 IN PKIDTENTRY Idt,
895 IN PKGDTENTRY Gdt)
896 {
897 PKGDTENTRY TssEntry, TaskGateEntry;
898
899 /* Initialize the boot TSS. */
900 TssEntry = &Gdt[KGDT_TSS / sizeof(KGDTENTRY)];
901 TssEntry->HighWord.Bits.Type = I386_TSS;
902 TssEntry->HighWord.Bits.Pres = 1;
903 TssEntry->HighWord.Bits.Dpl = 0;
904 KiInitializeTSS2(Tss, TssEntry);
905 KiInitializeTSS(Tss);
906
907 /* Load the task register */
908 Ke386SetTr(KGDT_TSS);
909
910 /* Setup the Task Gate for Double Fault Traps */
911 TaskGateEntry = (PKGDTENTRY)&Idt[8];
912 TaskGateEntry->HighWord.Bits.Type = I386_TASK_GATE;
913 TaskGateEntry->HighWord.Bits.Pres = 1;
914 TaskGateEntry->HighWord.Bits.Dpl = 0;
915 ((PKIDTENTRY)TaskGateEntry)->Selector = KGDT_DF_TSS;
916
917 /* Initialize the TSS used for handling double faults. */
918 Tss = (PKTSS)KiDoubleFaultTSS;
919 KiInitializeTSS(Tss);
920 Tss->CR3 = __readcr3();
921 Tss->Esp0 = KiDoubleFaultStack;
922 Tss->Esp = KiDoubleFaultStack;
923 Tss->Eip = PtrToUlong(KiTrap08);
924 Tss->Cs = KGDT_R0_CODE;
925 Tss->Fs = KGDT_R0_PCR;
926 Tss->Ss = Ke386GetSs();
927 Tss->Es = KGDT_R3_DATA | RPL_MASK;
928 Tss->Ds = KGDT_R3_DATA | RPL_MASK;
929
930 /* Setup the Double Trap TSS entry in the GDT */
931 TssEntry = &Gdt[KGDT_DF_TSS / sizeof(KGDTENTRY)];
932 TssEntry->HighWord.Bits.Type = I386_TSS;
933 TssEntry->HighWord.Bits.Pres = 1;
934 TssEntry->HighWord.Bits.Dpl = 0;
935 TssEntry->BaseLow = (USHORT)((ULONG_PTR)Tss & 0xFFFF);
936 TssEntry->HighWord.Bytes.BaseMid = (UCHAR)((ULONG_PTR)Tss >> 16);
937 TssEntry->HighWord.Bytes.BaseHi = (UCHAR)((ULONG_PTR)Tss >> 24);
938 TssEntry->LimitLow = KTSS_IO_MAPS;
939
940 /* Now setup the NMI Task Gate */
941 TaskGateEntry = (PKGDTENTRY)&Idt[2];
942 TaskGateEntry->HighWord.Bits.Type = I386_TASK_GATE;
943 TaskGateEntry->HighWord.Bits.Pres = 1;
944 TaskGateEntry->HighWord.Bits.Dpl = 0;
945 ((PKIDTENTRY)TaskGateEntry)->Selector = KGDT_NMI_TSS;
946
947 /* Initialize the actual TSS */
948 Tss = (PKTSS)KiNMITSS;
949 KiInitializeTSS(Tss);
950 Tss->CR3 = __readcr3();
951 Tss->Esp0 = KiDoubleFaultStack;
952 Tss->Esp = KiDoubleFaultStack;
953 Tss->Eip = PtrToUlong(KiTrap02);
954 Tss->Cs = KGDT_R0_CODE;
955 Tss->Fs = KGDT_R0_PCR;
956 Tss->Ss = Ke386GetSs();
957 Tss->Es = KGDT_R3_DATA | RPL_MASK;
958 Tss->Ds = KGDT_R3_DATA | RPL_MASK;
959
960 /* And its associated TSS Entry */
961 TssEntry = &Gdt[KGDT_NMI_TSS / sizeof(KGDTENTRY)];
962 TssEntry->HighWord.Bits.Type = I386_TSS;
963 TssEntry->HighWord.Bits.Pres = 1;
964 TssEntry->HighWord.Bits.Dpl = 0;
965 TssEntry->BaseLow = (USHORT)((ULONG_PTR)Tss & 0xFFFF);
966 TssEntry->HighWord.Bytes.BaseMid = (UCHAR)((ULONG_PTR)Tss >> 16);
967 TssEntry->HighWord.Bytes.BaseHi = (UCHAR)((ULONG_PTR)Tss >> 24);
968 TssEntry->LimitLow = KTSS_IO_MAPS;
969 }
970
971 VOID
972 NTAPI
973 KeFlushCurrentTb(VOID)
974 {
975 /* Flush the TLB by resetting CR3 */
976 __writecr3(__readcr3());
977 }
978
979 VOID
980 NTAPI
981 KiRestoreProcessorControlState(PKPROCESSOR_STATE ProcessorState)
982 {
983 PKGDTENTRY TssEntry;
984
985 //
986 // Restore the CR registers
987 //
988 __writecr0(ProcessorState->SpecialRegisters.Cr0);
989 Ke386SetCr2(ProcessorState->SpecialRegisters.Cr2);
990 __writecr3(ProcessorState->SpecialRegisters.Cr3);
991 if (KeFeatureBits & KF_CR4) __writecr4(ProcessorState->SpecialRegisters.Cr4);
992
993 //
994 // Restore the DR registers
995 //
996 __writedr(0, ProcessorState->SpecialRegisters.KernelDr0);
997 __writedr(1, ProcessorState->SpecialRegisters.KernelDr1);
998 __writedr(2, ProcessorState->SpecialRegisters.KernelDr2);
999 __writedr(3, ProcessorState->SpecialRegisters.KernelDr3);
1000 __writedr(6, ProcessorState->SpecialRegisters.KernelDr6);
1001 __writedr(7, ProcessorState->SpecialRegisters.KernelDr7);
1002
1003 //
1004 // Restore GDT and IDT
1005 //
1006 Ke386SetGlobalDescriptorTable(&ProcessorState->SpecialRegisters.Gdtr.Limit);
1007 __lidt(&ProcessorState->SpecialRegisters.Idtr.Limit);
1008
1009 //
1010 // Clear the busy flag so we don't crash if we reload the same selector
1011 //
1012 TssEntry = (PKGDTENTRY)(ProcessorState->SpecialRegisters.Gdtr.Base +
1013 ProcessorState->SpecialRegisters.Tr);
1014 TssEntry->HighWord.Bytes.Flags1 &= ~0x2;
1015
1016 //
1017 // Restore TSS and LDT
1018 //
1019 Ke386SetTr(ProcessorState->SpecialRegisters.Tr);
1020 Ke386SetLocalDescriptorTable(ProcessorState->SpecialRegisters.Ldtr);
1021 }
1022
1023 VOID
1024 NTAPI
1025 KiSaveProcessorControlState(OUT PKPROCESSOR_STATE ProcessorState)
1026 {
1027 /* Save the CR registers */
1028 ProcessorState->SpecialRegisters.Cr0 = __readcr0();
1029 ProcessorState->SpecialRegisters.Cr2 = __readcr2();
1030 ProcessorState->SpecialRegisters.Cr3 = __readcr3();
1031 ProcessorState->SpecialRegisters.Cr4 = (KeFeatureBits & KF_CR4) ?
1032 __readcr4() : 0;
1033
1034 /* Save the DR registers */
1035 ProcessorState->SpecialRegisters.KernelDr0 = __readdr(0);
1036 ProcessorState->SpecialRegisters.KernelDr1 = __readdr(1);
1037 ProcessorState->SpecialRegisters.KernelDr2 = __readdr(2);
1038 ProcessorState->SpecialRegisters.KernelDr3 = __readdr(3);
1039 ProcessorState->SpecialRegisters.KernelDr6 = __readdr(6);
1040 ProcessorState->SpecialRegisters.KernelDr7 = __readdr(7);
1041 __writedr(7, 0);
1042
1043 /* Save GDT, IDT, LDT and TSS */
1044 Ke386GetGlobalDescriptorTable(&ProcessorState->SpecialRegisters.Gdtr.Limit);
1045 __sidt(&ProcessorState->SpecialRegisters.Idtr.Limit);
1046 ProcessorState->SpecialRegisters.Tr = Ke386GetTr();
1047 ProcessorState->SpecialRegisters.Ldtr = Ke386GetLocalDescriptorTable();
1048 }
1049
1050 VOID
1051 NTAPI
1052 INIT_FUNCTION
1053 KiInitializeMachineType(VOID)
1054 {
1055 /* Set the Machine Type we got from NTLDR */
1056 KeI386MachineType = KeLoaderBlock->u.I386.MachineType & 0x000FF;
1057 }
1058
1059 ULONG_PTR
1060 NTAPI
1061 INIT_FUNCTION
1062 KiLoadFastSyscallMachineSpecificRegisters(IN ULONG_PTR Context)
1063 {
1064 /* Set CS and ESP */
1065 WRMSR(0x174, KGDT_R0_CODE);
1066 WRMSR(0x175, (ULONG_PTR)KeGetCurrentPrcb()->DpcStack);
1067
1068 /* Set LSTAR */
1069 WRMSR(0x176, (ULONG_PTR)KiFastCallEntry);
1070 return 0;
1071 }
1072
1073 VOID
1074 NTAPI
1075 INIT_FUNCTION
1076 KiRestoreFastSyscallReturnState(VOID)
1077 {
1078 /* Check if the CPU Supports fast system call */
1079 if (KeFeatureBits & KF_FAST_SYSCALL)
1080 {
1081 /* Check if it has been disabled */
1082 if (!KiFastSystemCallDisable)
1083 {
1084 /* Do an IPI to enable it */
1085 KeIpiGenericCall(KiLoadFastSyscallMachineSpecificRegisters, 0);
1086
1087 /* It's enabled, so use the proper exit stub */
1088 KiFastCallExitHandler = KiSystemCallSysExitReturn;
1089 DPRINT1("Support for SYSENTER detected.\n");
1090 }
1091 else
1092 {
1093 /* Disable fast system call */
1094 KeFeatureBits &= ~KF_FAST_SYSCALL;
1095 KiFastCallExitHandler = KiSystemCallTrapReturn;
1096 DPRINT1("Support for SYSENTER disabled.\n");
1097 }
1098 }
1099 else
1100 {
1101 /* Use the IRET handler */
1102 KiFastCallExitHandler = KiSystemCallTrapReturn;
1103 DPRINT1("No support for SYSENTER detected.\n");
1104 }
1105 }
1106
1107 ULONG_PTR
1108 NTAPI
1109 INIT_FUNCTION
1110 Ki386EnableDE(IN ULONG_PTR Context)
1111 {
1112 /* Enable DE */
1113 __writecr4(__readcr4() | CR4_DE);
1114 return 0;
1115 }
1116
1117 ULONG_PTR
1118 NTAPI
1119 INIT_FUNCTION
1120 Ki386EnableFxsr(IN ULONG_PTR Context)
1121 {
1122 /* Enable FXSR */
1123 __writecr4(__readcr4() | CR4_FXSR);
1124 return 0;
1125 }
1126
1127 ULONG_PTR
1128 NTAPI
1129 INIT_FUNCTION
1130 Ki386EnableXMMIExceptions(IN ULONG_PTR Context)
1131 {
1132 PKIDTENTRY IdtEntry;
1133
1134 /* Get the IDT Entry for Interrupt 0x13 */
1135 IdtEntry = &((PKIPCR)KeGetPcr())->IDT[0x13];
1136
1137 /* Set it up */
1138 IdtEntry->Selector = KGDT_R0_CODE;
1139 IdtEntry->Offset = ((ULONG_PTR)KiTrap13 & 0xFFFF);
1140 IdtEntry->ExtendedOffset = ((ULONG_PTR)KiTrap13 >> 16) & 0xFFFF;
1141 ((PKIDT_ACCESS)&IdtEntry->Access)->Dpl = 0;
1142 ((PKIDT_ACCESS)&IdtEntry->Access)->Present = 1;
1143 ((PKIDT_ACCESS)&IdtEntry->Access)->SegmentType = I386_INTERRUPT_GATE;
1144
1145 /* Enable XMMI exceptions */
1146 __writecr4(__readcr4() | CR4_XMMEXCPT);
1147 return 0;
1148 }
1149
1150 VOID
1151 NTAPI
1152 INIT_FUNCTION
1153 KiI386PentiumLockErrataFixup(VOID)
1154 {
1155 KDESCRIPTOR IdtDescriptor;
1156 PKIDTENTRY NewIdt, NewIdt2;
1157
1158 /* Allocate memory for a new IDT */
1159 NewIdt = ExAllocatePool(NonPagedPool, 2 * PAGE_SIZE);
1160
1161 /* Put everything after the first 7 entries on a new page */
1162 NewIdt2 = (PVOID)((ULONG_PTR)NewIdt + PAGE_SIZE - (7 * sizeof(KIDTENTRY)));
1163
1164 /* Disable interrupts */
1165 _disable();
1166
1167 /* Get the current IDT and copy it */
1168 __sidt(&IdtDescriptor.Limit);
1169 RtlCopyMemory(NewIdt2,
1170 (PVOID)IdtDescriptor.Base,
1171 IdtDescriptor.Limit + 1);
1172 IdtDescriptor.Base = (ULONG)NewIdt2;
1173
1174 /* Set the new IDT */
1175 __lidt(&IdtDescriptor.Limit);
1176 ((PKIPCR)KeGetPcr())->IDT = NewIdt2;
1177
1178 /* Restore interrupts */
1179 _enable();
1180
1181 /* Set the first 7 entries as read-only to produce a fault */
1182 MmSetPageProtect(NULL, NewIdt, PAGE_READONLY);
1183 }
1184
1185 BOOLEAN
1186 NTAPI
1187 KeDisableInterrupts(VOID)
1188 {
1189 ULONG Flags;
1190 BOOLEAN Return;
1191
1192 /* Get EFLAGS and check if the interrupt bit is set */
1193 Flags = __readeflags();
1194 Return = (Flags & EFLAGS_INTERRUPT_MASK) ? TRUE: FALSE;
1195
1196 /* Disable interrupts */
1197 _disable();
1198 return Return;
1199 }
1200
1201 BOOLEAN
1202 NTAPI
1203 KeInvalidateAllCaches(VOID)
1204 {
1205 /* Only supported on Pentium Pro and higher */
1206 if (KeI386CpuType < 6) return FALSE;
1207
1208 /* Invalidate all caches */
1209 __wbinvd();
1210 return TRUE;
1211 }
1212
1213 VOID
1214 FASTCALL
1215 KeZeroPages(IN PVOID Address,
1216 IN ULONG Size)
1217 {
1218 /* Not using XMMI in this routine */
1219 RtlZeroMemory(Address, Size);
1220 }
1221
1222 VOID
1223 NTAPI
1224 KiSaveProcessorState(IN PKTRAP_FRAME TrapFrame,
1225 IN PKEXCEPTION_FRAME ExceptionFrame)
1226 {
1227 PKPRCB Prcb = KeGetCurrentPrcb();
1228
1229 //
1230 // Save full context
1231 //
1232 Prcb->ProcessorState.ContextFrame.ContextFlags = CONTEXT_FULL |
1233 CONTEXT_DEBUG_REGISTERS;
1234 KeTrapFrameToContext(TrapFrame, NULL, &Prcb->ProcessorState.ContextFrame);
1235
1236 //
1237 // Save control registers
1238 //
1239 KiSaveProcessorControlState(&Prcb->ProcessorState);
1240 }
1241
1242 BOOLEAN
1243 NTAPI
1244 INIT_FUNCTION
1245 KiIsNpxPresent(VOID)
1246 {
1247 ULONG Cr0;
1248 USHORT Magic;
1249
1250 /* Set magic */
1251 Magic = 0xFFFF;
1252
1253 /* Read CR0 and mask out FPU flags */
1254 Cr0 = __readcr0() & ~(CR0_MP | CR0_TS | CR0_EM | CR0_ET);
1255
1256 /* Store on FPU stack */
1257 #ifdef _MSC_VER
1258 __asm fninit;
1259 __asm fnstsw Magic;
1260 #else
1261 asm volatile ("fninit;" "fnstsw %0" : "+m"(Magic));
1262 #endif
1263
1264 /* Magic should now be cleared */
1265 if (Magic & 0xFF)
1266 {
1267 /* You don't have an FPU -- enable emulation for now */
1268 __writecr0(Cr0 | CR0_EM | CR0_TS);
1269 return FALSE;
1270 }
1271
1272 /* You have an FPU, enable it */
1273 Cr0 |= CR0_ET;
1274
1275 /* Enable INT 16 on 486 and higher */
1276 if (KeGetCurrentPrcb()->CpuType >= 3) Cr0 |= CR0_NE;
1277
1278 /* Set FPU state */
1279 __writecr0(Cr0 | CR0_EM | CR0_TS);
1280 return TRUE;
1281 }
1282
1283 BOOLEAN
1284 NTAPI
1285 INIT_FUNCTION
1286 KiIsNpxErrataPresent(VOID)
1287 {
1288 BOOLEAN ErrataPresent;
1289 ULONG Cr0;
1290 volatile double Value1, Value2;
1291
1292 /* Disable interrupts */
1293 _disable();
1294
1295 /* Read CR0 and remove FPU flags */
1296 Cr0 = __readcr0();
1297 __writecr0(Cr0 & ~(CR0_MP | CR0_TS | CR0_EM));
1298
1299 /* Initialize FPU state */
1300 Ke386FnInit();
1301
1302 /* Multiply the magic values and divide, we should get the result back */
1303 Value1 = 4195835.0;
1304 Value2 = 3145727.0;
1305 ErrataPresent = (Value1 * Value2 / 3145727.0) != 4195835.0;
1306
1307 /* Restore CR0 */
1308 __writecr0(Cr0);
1309
1310 /* Enable interrupts */
1311 _enable();
1312
1313 /* Return if there's an errata */
1314 return ErrataPresent;
1315 }
1316
1317 VOID
1318 NTAPI
1319 KiFlushNPXState(IN PFLOATING_SAVE_AREA SaveArea)
1320 {
1321 ULONG EFlags, Cr0;
1322 PKTHREAD Thread, NpxThread;
1323 PFX_SAVE_AREA FxSaveArea;
1324
1325 /* Save volatiles and disable interrupts */
1326 EFlags = __readeflags();
1327 _disable();
1328
1329 /* Save the PCR and get the current thread */
1330 Thread = KeGetCurrentThread();
1331
1332 /* Check if we're already loaded */
1333 if (Thread->NpxState != NPX_STATE_LOADED)
1334 {
1335 /* If there's nothing to load, quit */
1336 if (!SaveArea) return;
1337
1338 /* Need FXSR support for this */
1339 ASSERT(KeI386FxsrPresent == TRUE);
1340
1341 /* Check for sane CR0 */
1342 Cr0 = __readcr0();
1343 if (Cr0 & (CR0_MP | CR0_TS | CR0_EM))
1344 {
1345 /* Mask out FPU flags */
1346 __writecr0(Cr0 & ~(CR0_MP | CR0_TS | CR0_EM));
1347 }
1348
1349 /* Get the NPX thread and check its FPU state */
1350 NpxThread = KeGetCurrentPrcb()->NpxThread;
1351 if ((NpxThread) && (NpxThread->NpxState == NPX_STATE_LOADED))
1352 {
1353 /* Get the FX frame and store the state there */
1354 FxSaveArea = KiGetThreadNpxArea(NpxThread);
1355 Ke386FxSave(FxSaveArea);
1356
1357 /* NPX thread has lost its state */
1358 NpxThread->NpxState = NPX_STATE_NOT_LOADED;
1359 }
1360
1361 /* Now load NPX state from the NPX area */
1362 FxSaveArea = KiGetThreadNpxArea(Thread);
1363 Ke386FxStore(FxSaveArea);
1364 }
1365 else
1366 {
1367 /* Check for sane CR0 */
1368 Cr0 = __readcr0();
1369 if (Cr0 & (CR0_MP | CR0_TS | CR0_EM))
1370 {
1371 /* Mask out FPU flags */
1372 __writecr0(Cr0 & ~(CR0_MP | CR0_TS | CR0_EM));
1373 }
1374
1375 /* Get FX frame */
1376 FxSaveArea = KiGetThreadNpxArea(Thread);
1377 Thread->NpxState = NPX_STATE_NOT_LOADED;
1378
1379 /* Save state if supported by CPU */
1380 if (KeI386FxsrPresent) Ke386FxSave(FxSaveArea);
1381 }
1382
1383 /* Now save the FN state wherever it was requested */
1384 if (SaveArea) Ke386FnSave(SaveArea);
1385
1386 /* Clear NPX thread */
1387 KeGetCurrentPrcb()->NpxThread = NULL;
1388
1389 /* Add the CR0 from the NPX frame */
1390 Cr0 |= NPX_STATE_NOT_LOADED;
1391 Cr0 |= FxSaveArea->Cr0NpxState;
1392 __writecr0(Cr0);
1393
1394 /* Restore interrupt state */
1395 __writeeflags(EFlags);
1396 }
1397
1398 /* PUBLIC FUNCTIONS **********************************************************/
1399
1400 /*
1401 * @implemented
1402 */
1403 VOID
1404 NTAPI
1405 KiCoprocessorError(VOID)
1406 {
1407 PFX_SAVE_AREA NpxArea;
1408
1409 /* Get the FPU area */
1410 NpxArea = KiGetThreadNpxArea(KeGetCurrentThread());
1411
1412 /* Set CR0_TS */
1413 NpxArea->Cr0NpxState = CR0_TS;
1414 __writecr0(__readcr0() | CR0_TS);
1415 }
1416
1417 /*
1418 * @implemented
1419 */
1420 NTSTATUS
1421 NTAPI
1422 KeSaveFloatingPointState(OUT PKFLOATING_SAVE Save)
1423 {
1424 PFNSAVE_FORMAT FpState;
1425 ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
1426 DPRINT1("%s is not really implemented\n", __FUNCTION__);
1427
1428 /* check if we are doing software emulation */
1429 if (!KeI386NpxPresent) return STATUS_ILLEGAL_FLOAT_CONTEXT;
1430
1431 FpState = ExAllocatePool(NonPagedPool, sizeof (FNSAVE_FORMAT));
1432 if (!FpState) return STATUS_INSUFFICIENT_RESOURCES;
1433
1434 *((PVOID *) Save) = FpState;
1435 #ifdef __GNUC__
1436 asm volatile("fnsave %0\n\t" : "=m" (*FpState));
1437 #else
1438 __asm
1439 {
1440 fnsave [FpState]
1441 };
1442 #endif
1443
1444 KeGetCurrentThread()->DispatcherHeader.NpxIrql = KeGetCurrentIrql();
1445 return STATUS_SUCCESS;
1446 }
1447
1448 /*
1449 * @implemented
1450 */
1451 NTSTATUS
1452 NTAPI
1453 KeRestoreFloatingPointState(IN PKFLOATING_SAVE Save)
1454 {
1455 PFNSAVE_FORMAT FpState = *((PVOID *) Save);
1456 ASSERT(KeGetCurrentThread()->DispatcherHeader.NpxIrql == KeGetCurrentIrql());
1457 DPRINT1("%s is not really implemented\n", __FUNCTION__);
1458
1459 #ifdef __GNUC__
1460 asm volatile("fnclex\n\t");
1461 asm volatile("frstor %0\n\t" : "=m" (*FpState));
1462 #else
1463 __asm
1464 {
1465 fnclex
1466 frstor [FpState]
1467 };
1468 #endif
1469
1470 ExFreePool(FpState);
1471 return STATUS_SUCCESS;
1472 }
1473
1474 /*
1475 * @implemented
1476 */
1477 ULONG
1478 NTAPI
1479 KeGetRecommendedSharedDataAlignment(VOID)
1480 {
1481 /* Return the global variable */
1482 return KeLargestCacheLine;
1483 }
1484
1485 VOID
1486 NTAPI
1487 KiFlushTargetEntireTb(IN PKIPI_CONTEXT PacketContext,
1488 IN PVOID Ignored1,
1489 IN PVOID Ignored2,
1490 IN PVOID Ignored3)
1491 {
1492 /* Signal this packet as done */
1493 KiIpiSignalPacketDone(PacketContext);
1494
1495 /* Flush the TB for the Current CPU */
1496 KeFlushCurrentTb();
1497 }
1498
1499 /*
1500 * @implemented
1501 */
1502 VOID
1503 NTAPI
1504 KeFlushEntireTb(IN BOOLEAN Invalid,
1505 IN BOOLEAN AllProcessors)
1506 {
1507 KIRQL OldIrql;
1508 #ifdef CONFIG_SMP
1509 KAFFINITY TargetAffinity;
1510 PKPRCB Prcb = KeGetCurrentPrcb();
1511 #endif
1512
1513 /* Raise the IRQL for the TB Flush */
1514 OldIrql = KeRaiseIrqlToSynchLevel();
1515
1516 #ifdef CONFIG_SMP
1517 /* FIXME: Use KiTbFlushTimeStamp to synchronize TB flush */
1518
1519 /* Get the current processor affinity, and exclude ourselves */
1520 TargetAffinity = KeActiveProcessors;
1521 TargetAffinity &= ~Prcb->SetMember;
1522
1523 /* Make sure this is MP */
1524 if (TargetAffinity)
1525 {
1526 /* Send an IPI TB flush to the other processors */
1527 KiIpiSendPacket(TargetAffinity,
1528 KiFlushTargetEntireTb,
1529 NULL,
1530 0,
1531 NULL);
1532 }
1533 #endif
1534
1535 /* Flush the TB for the Current CPU, and update the flush stamp */
1536 KeFlushCurrentTb();
1537
1538 #ifdef CONFIG_SMP
1539 /* If this is MP, wait for the other processors to finish */
1540 if (TargetAffinity)
1541 {
1542 /* Sanity check */
1543 ASSERT(Prcb == (volatile PKPRCB)KeGetCurrentPrcb());
1544
1545 /* FIXME: TODO */
1546 ASSERTMSG("Not yet implemented\n", FALSE);
1547 }
1548 #endif
1549
1550 /* Update the flush stamp and return to original IRQL */
1551 InterlockedExchangeAdd(&KiTbFlushTimeStamp, 1);
1552 KeLowerIrql(OldIrql);
1553 }
1554
1555 /*
1556 * @implemented
1557 */
1558 VOID
1559 NTAPI
1560 KeSetDmaIoCoherency(IN ULONG Coherency)
1561 {
1562 /* Save the coherency globally */
1563 KiDmaIoCoherency = Coherency;
1564 }
1565
1566 /*
1567 * @implemented
1568 */
1569 KAFFINITY
1570 NTAPI
1571 KeQueryActiveProcessors(VOID)
1572 {
1573 PAGED_CODE();
1574
1575 /* Simply return the number of active processors */
1576 return KeActiveProcessors;
1577 }
1578
1579 /*
1580 * @implemented
1581 */
1582 VOID
1583 __cdecl
1584 KeSaveStateForHibernate(IN PKPROCESSOR_STATE State)
1585 {
1586 /* Capture the context */
1587 RtlCaptureContext(&State->ContextFrame);
1588
1589 /* Capture the control state */
1590 KiSaveProcessorControlState(State);
1591 }