2606297c1b41cc828dc0a24cdd4ffdb993ca2298
[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 /* Check if the CPU is too old to support SYSENTER */
308 if ((Prcb->CpuType < 6) ||
309 ((Prcb->CpuType == 6) && (Prcb->CpuStep < 0x0303)))
310 {
311 /* Disable it */
312 Reg[3] &= ~0x800;
313 }
314
315 /* Set the current features */
316 CpuFeatures = Reg[3];
317
318 break;
319
320 /* AMD CPUs */
321 case CPU_AMD:
322
323 /* Check if this is a K5 or K6. (family 5) */
324 if ((Reg[0] & 0x0F00) == 0x0500)
325 {
326 /* Get the Model Number */
327 switch (Reg[0] & 0x00F0)
328 {
329 /* Model 1: K5 - 5k86 (initial models) */
330 case 0x0010:
331
332 /* Check if this is Step 0 or 1. They don't support PGE */
333 if ((Reg[0] & 0x000F) > 0x03) break;
334
335 /* Model 0: K5 - SSA5 */
336 case 0x0000:
337
338 /* Model 0 doesn't support PGE at all. */
339 Reg[3] &= ~0x2000;
340 break;
341
342 /* Model 8: K6-2 */
343 case 0x0080:
344
345 /* K6-2, Step 8 and over have support for MTRR. */
346 if ((Reg[0] & 0x000F) >= 0x8) FeatureBits |= KF_AMDK6MTRR;
347 break;
348
349 /* Model 9: K6-III
350 Model D: K6-2+, K6-III+ */
351 case 0x0090:
352 case 0x00D0:
353
354 FeatureBits |= KF_AMDK6MTRR;
355 break;
356 }
357 }
358 else if((Reg[0] & 0x0F00) < 0x0500)
359 {
360 /* Families below 5 don't support PGE, PSE or CMOV at all */
361 Reg[3] &= ~(0x08 | 0x2000 | 0x8000);
362
363 /* They also don't support advanced CPUID functions. */
364 ExtendedCPUID = FALSE;
365 }
366
367 /* Set the current features */
368 CpuFeatures = Reg[3];
369
370 break;
371
372 /* Cyrix CPUs */
373 case CPU_CYRIX:
374
375 /* Workaround the "COMA" bug on 6x family of Cyrix CPUs */
376 if (Prcb->CpuType == 6 &&
377 Prcb->CpuStep <= 1)
378 {
379 /* Get CCR1 value */
380 Ccr1 = getCx86(CX86_CCR1);
381
382 /* Enable the NO_LOCK bit */
383 Ccr1 |= 0x10;
384
385 /* Set the new CCR1 value */
386 setCx86(CX86_CCR1, Ccr1);
387 }
388
389 /* Set the current features */
390 CpuFeatures = Reg[3];
391
392 break;
393
394 /* Transmeta CPUs */
395 case CPU_TRANSMETA:
396
397 /* Enable CMPXCHG8B if the family (>= 5), model and stepping (>= 4.2) support it */
398 if ((Reg[0] & 0x0FFF) >= 0x0542)
399 {
400 WRMSR(0x80860004, RDMSR(0x80860004) | 0x0100);
401 FeatureBits |= KF_CMPXCHG8B;
402 }
403
404 break;
405
406 /* Centaur, IDT, Rise and VIA CPUs */
407 case CPU_CENTAUR:
408 case CPU_RISE:
409
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;
413
414 break;
415 }
416
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;
432
433 /* Check if the CPU has hyper-threading */
434 if (CpuFeatures & 0x10000000)
435 {
436 /* Set the number of logical CPUs */
437 Prcb->LogicalProcessorsPerPhysicalProcessor = (UCHAR)(Reg[1] >> 16);
438 if (Prcb->LogicalProcessorsPerPhysicalProcessor > 1)
439 {
440 /* We're on dual-core */
441 KiSMTProcessorsPresent = TRUE;
442 }
443 }
444 else
445 {
446 /* We only have a single CPU */
447 Prcb->LogicalProcessorsPerPhysicalProcessor = 1;
448 }
449
450 /* Check if CPUID 0x80000000 is supported */
451 if (ExtendedCPUID)
452 {
453 /* Do the call */
454 CPUID(0x80000000, &Reg[0], &Dummy, &Dummy, &Dummy);
455 if ((Reg[0] & 0xffffff00) == 0x80000000)
456 {
457 /* Check if CPUID 0x80000001 is supported */
458 if (Reg[0] >= 0x80000001)
459 {
460 /* Check which extended features are available. */
461 CPUID(0x80000001, &Dummy, &Dummy, &Dummy, &Reg[3]);
462
463 /* Check if NX-bit is supported */
464 if (Reg[3] & 0x00100000) FeatureBits |= KF_NX_BIT;
465
466 /* Now handle each features for each CPU Vendor */
467 switch (Vendor)
468 {
469 case CPU_AMD:
470 case CPU_CENTAUR:
471 if (Reg[3] & 0x80000000) FeatureBits |= KF_3DNOW;
472 break;
473 }
474 }
475 }
476 }
477
478 /* Return the Feature Bits */
479 return FeatureBits;
480 }
481
482 VOID
483 NTAPI
484 INIT_FUNCTION
485 KiGetCacheInformation(VOID)
486 {
487 PKIPCR Pcr = (PKIPCR)KeGetPcr();
488 ULONG Vendor;
489 ULONG Data[4], Dummy;
490 ULONG CacheRequests = 0, i;
491 ULONG CurrentRegister;
492 UCHAR RegisterByte;
493 ULONG Size, Associativity = 0, CacheLine = 64, CurrentSize = 0;
494 BOOLEAN FirstPass = TRUE;
495
496 /* Set default L2 size */
497 Pcr->SecondLevelCacheSize = 0;
498
499 /* Get the Vendor ID and make sure we support CPUID */
500 Vendor = KiGetCpuVendor();
501 if (!Vendor) return;
502
503 /* Check the Vendor ID */
504 switch (Vendor)
505 {
506 /* Handle Intel case */
507 case CPU_INTEL:
508
509 /*Check if we support CPUID 2 */
510 CPUID(0, &Data[0], &Dummy, &Dummy, &Dummy);
511 if (Data[0] >= 2)
512 {
513 /* We need to loop for the number of times CPUID will tell us to */
514 do
515 {
516 /* Do the CPUID call */
517 CPUID(2, &Data[0], &Data[1], &Data[2], &Data[3]);
518
519 /* Check if it was the first call */
520 if (FirstPass)
521 {
522 /*
523 * The number of times to loop is the first byte. Read
524 * it and then destroy it so we don't get confused.
525 */
526 CacheRequests = Data[0] & 0xFF;
527 Data[0] &= 0xFFFFFF00;
528
529 /* Don't go over this again */
530 FirstPass = FALSE;
531 }
532
533 /* Loop all 4 registers */
534 for (i = 0; i < 4; i++)
535 {
536 /* Get the current register */
537 CurrentRegister = Data[i];
538
539 /*
540 * If the upper bit is set, then this register should
541 * be skipped.
542 */
543 if (CurrentRegister & 0x80000000) continue;
544
545 /* Keep looping for every byte inside this register */
546 while (CurrentRegister)
547 {
548 /* Read a byte, skip a byte. */
549 RegisterByte = (UCHAR)(CurrentRegister & 0xFF);
550 CurrentRegister >>= 8;
551 if (!RegisterByte) continue;
552
553 /*
554 * Valid values are from 0x40 (0 bytes) to 0x49
555 * (32MB), or from 0x80 to 0x89 (same size but
556 * 8-way associative.
557 */
558 if (((RegisterByte > 0x40) && (RegisterByte <= 0x47)) ||
559 ((RegisterByte > 0x78) && (RegisterByte <= 0x7C)) ||
560 ((RegisterByte > 0x80) && (RegisterByte <= 0x85)))
561 {
562 /* Compute associativity */
563 Associativity = 4;
564 if (RegisterByte >= 0x79) Associativity = 8;
565
566 /* Mask out only the first nibble */
567 RegisterByte &= 0x07;
568
569 /* Check if this cache is bigger than the last */
570 Size = 0x10000 << RegisterByte;
571 if ((Size / Associativity) > CurrentSize)
572 {
573 /* Set the L2 Cache Size and Associativity */
574 CurrentSize = Size / Associativity;
575 Pcr->SecondLevelCacheSize = Size;
576 Pcr->SecondLevelCacheAssociativity = Associativity;
577 }
578 }
579 else if ((RegisterByte > 0x21) && (RegisterByte <= 0x29))
580 {
581 /* Set minimum cache line size */
582 if (CacheLine < 128) CacheLine = 128;
583
584 /* Hard-code size/associativity */
585 Associativity = 8;
586 switch (RegisterByte)
587 {
588 case 0x22:
589 Size = 512 * 1024;
590 Associativity = 4;
591 break;
592
593 case 0x23:
594 Size = 1024 * 1024;
595 break;
596
597 case 0x25:
598 Size = 2048 * 1024;
599 break;
600
601 case 0x29:
602 Size = 4096 * 1024;
603 break;
604
605 default:
606 Size = 0;
607 break;
608 }
609
610 /* Check if this cache is bigger than the last */
611 if ((Size / Associativity) > CurrentSize)
612 {
613 /* Set the L2 Cache Size and Associativity */
614 CurrentSize = Size / Associativity;
615 Pcr->SecondLevelCacheSize = Size;
616 Pcr->SecondLevelCacheAssociativity = Associativity;
617 }
618 }
619 else if (((RegisterByte > 0x65) && (RegisterByte < 0x69)) ||
620 (RegisterByte == 0x2C) || (RegisterByte == 0xF0))
621 {
622 /* Indicates L1 cache line of 64 bytes */
623 KePrefetchNTAGranularity = 64;
624 }
625 else if (RegisterByte == 0xF1)
626 {
627 /* Indicates L1 cache line of 128 bytes */
628 KePrefetchNTAGranularity = 128;
629 }
630 else if (((RegisterByte >= 0x4A) && (RegisterByte <= 0x4C)) ||
631 (RegisterByte == 0x78) ||
632 (RegisterByte == 0x7D) ||
633 (RegisterByte == 0x7F) ||
634 (RegisterByte == 0x86) ||
635 (RegisterByte == 0x87))
636 {
637 /* Set minimum cache line size */
638 if (CacheLine < 64) CacheLine = 64;
639
640 /* Hard-code size/associativity */
641 switch (RegisterByte)
642 {
643 case 0x4A:
644 Size = 4 * 1024 * 1024;
645 Associativity = 8;
646 break;
647
648 case 0x4B:
649 Size = 6 * 1024 * 1024;
650 Associativity = 12;
651 break;
652
653 case 0x4C:
654 Size = 8 * 1024 * 1024;
655 Associativity = 16;
656 break;
657
658 case 0x78:
659 Size = 1 * 1024 * 1024;
660 Associativity = 4;
661 break;
662
663 case 0x7D:
664 Size = 2 * 1024 * 1024;
665 Associativity = 8;
666 break;
667
668 case 0x7F:
669 Size = 512 * 1024;
670 Associativity = 2;
671 break;
672
673 case 0x86:
674 Size = 512 * 1024;
675 Associativity = 4;
676 break;
677
678 case 0x87:
679 Size = 1 * 1024 * 1024;
680 Associativity = 8;
681 break;
682
683 default:
684 Size = 0;
685 break;
686 }
687
688 /* Check if this cache is bigger than the last */
689 if ((Size / Associativity) > CurrentSize)
690 {
691 /* Set the L2 Cache Size and Associativity */
692 CurrentSize = Size / Associativity;
693 Pcr->SecondLevelCacheSize = Size;
694 Pcr->SecondLevelCacheAssociativity = Associativity;
695 }
696 }
697 }
698 }
699 } while (--CacheRequests);
700 }
701 break;
702
703 case CPU_AMD:
704
705 /* Check if we support CPUID 0x80000005 */
706 CPUID(0x80000000, &Data[0], &Data[1], &Data[2], &Data[3]);
707 if (Data[0] >= 0x80000006)
708 {
709 /* Get L1 size first */
710 CPUID(0x80000005, &Data[0], &Data[1], &Data[2], &Data[3]);
711 KePrefetchNTAGranularity = Data[2] & 0xFF;
712
713 /* Check if we support CPUID 0x80000006 */
714 CPUID(0x80000000, &Data[0], &Data[1], &Data[2], &Data[3]);
715 if (Data[0] >= 0x80000006)
716 {
717 /* Get 2nd level cache and tlb size */
718 CPUID(0x80000006, &Data[0], &Data[1], &Data[2], &Data[3]);
719
720 /* Cache line size */
721 CacheLine = Data[2] & 0xFF;
722
723 /* Hardcode associativity */
724 RegisterByte = Data[2] >> 12;
725 switch (RegisterByte)
726 {
727 case 2:
728 Associativity = 2;
729 break;
730
731 case 4:
732 Associativity = 4;
733 break;
734
735 case 6:
736 Associativity = 8;
737 break;
738
739 case 8:
740 case 15:
741 Associativity = 16;
742 break;
743
744 default:
745 Associativity = 1;
746 break;
747 }
748
749 /* Compute size */
750 Size = (Data[2] >> 16) << 10;
751
752 /* Hack for Model 6, Steping 300 */
753 if ((KeGetCurrentPrcb()->CpuType == 6) &&
754 (KeGetCurrentPrcb()->CpuStep == 0x300))
755 {
756 /* Stick 64K in there */
757 Size = 64 * 1024;
758 }
759
760 /* Set the L2 Cache Size and associativity */
761 Pcr->SecondLevelCacheSize = Size;
762 Pcr->SecondLevelCacheAssociativity = Associativity;
763 }
764 }
765 break;
766
767 case CPU_CYRIX:
768 case CPU_TRANSMETA:
769 case CPU_CENTAUR:
770 case CPU_RISE:
771
772 /* FIXME */
773 break;
774 }
775
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,
781 KeLargestCacheLine,
782 Pcr->SecondLevelCacheAssociativity);
783 }
784
785 VOID
786 NTAPI
787 INIT_FUNCTION
788 KiSetCR0Bits(VOID)
789 {
790 ULONG Cr0;
791
792 /* Save current CR0 */
793 Cr0 = __readcr0();
794
795 /* If this is a 486, enable Write-Protection */
796 if (KeGetCurrentPrcb()->CpuType > 3) Cr0 |= CR0_WP;
797
798 /* Set new Cr0 */
799 __writecr0(Cr0);
800 }
801
802 VOID
803 NTAPI
804 INIT_FUNCTION
805 KiInitializeTSS2(IN PKTSS Tss,
806 IN PKGDTENTRY TssEntry OPTIONAL)
807 {
808 PUCHAR p;
809
810 /* Make sure the GDT Entry is valid */
811 if (TssEntry)
812 {
813 /* Set the Limit */
814 TssEntry->LimitLow = sizeof(KTSS) - 1;
815 TssEntry->HighWord.Bits.LimitHi = 0;
816 }
817
818 /* Now clear the I/O Map */
819 ASSERT(IOPM_COUNT == 1);
820 RtlFillMemory(Tss->IoMaps[0].IoMap, IOPM_FULL_SIZE, 0xFF);
821
822 /* Initialize Interrupt Direction Maps */
823 p = (PUCHAR)(Tss->IoMaps[0].DirectionMap);
824 RtlZeroMemory(p, IOPM_DIRECTION_MAP_SIZE);
825
826 /* Add DPMI support for interrupts */
827 p[0] = 4;
828 p[3] = 0x18;
829 p[4] = 0x18;
830
831 /* Initialize the default Interrupt Direction Map */
832 p = Tss->IntDirectionMap;
833 RtlZeroMemory(Tss->IntDirectionMap, IOPM_DIRECTION_MAP_SIZE);
834
835 /* Add DPMI support */
836 p[0] = 4;
837 p[3] = 0x18;
838 p[4] = 0x18;
839 }
840
841 VOID
842 NTAPI
843 KiInitializeTSS(IN PKTSS Tss)
844 {
845 /* Set an invalid map base */
846 Tss->IoMapBase = KiComputeIopmOffset(IO_ACCESS_MAP_NONE);
847
848 /* Disable traps during Task Switches */
849 Tss->Flags = 0;
850
851 /* Set LDT and Ring 0 SS */
852 Tss->LDT = 0;
853 Tss->Ss0 = KGDT_R0_DATA;
854 }
855
856 VOID
857 FASTCALL
858 INIT_FUNCTION
859 Ki386InitializeTss(IN PKTSS Tss,
860 IN PKIDTENTRY Idt,
861 IN PKGDTENTRY Gdt)
862 {
863 PKGDTENTRY TssEntry, TaskGateEntry;
864
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);
872
873 /* Load the task register */
874 Ke386SetTr(KGDT_TSS);
875
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;
882
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;
895
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;
905
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;
912
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;
925
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;
935 }
936
937 VOID
938 NTAPI
939 KeFlushCurrentTb(VOID)
940 {
941 /* Flush the TLB by resetting CR3 */
942 __writecr3(__readcr3());
943 }
944
945 VOID
946 NTAPI
947 KiRestoreProcessorControlState(PKPROCESSOR_STATE ProcessorState)
948 {
949 PKGDTENTRY TssEntry;
950
951 //
952 // Restore the CR registers
953 //
954 __writecr0(ProcessorState->SpecialRegisters.Cr0);
955 Ke386SetCr2(ProcessorState->SpecialRegisters.Cr2);
956 __writecr3(ProcessorState->SpecialRegisters.Cr3);
957 if (KeFeatureBits & KF_CR4) __writecr4(ProcessorState->SpecialRegisters.Cr4);
958
959 //
960 // Restore the DR registers
961 //
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);
968
969 //
970 // Restore GDT and IDT
971 //
972 Ke386SetGlobalDescriptorTable(&ProcessorState->SpecialRegisters.Gdtr.Limit);
973 __lidt(&ProcessorState->SpecialRegisters.Idtr.Limit);
974
975 //
976 // Clear the busy flag so we don't crash if we reload the same selector
977 //
978 TssEntry = (PKGDTENTRY)(ProcessorState->SpecialRegisters.Gdtr.Base +
979 ProcessorState->SpecialRegisters.Tr);
980 TssEntry->HighWord.Bytes.Flags1 &= ~0x2;
981
982 //
983 // Restore TSS and LDT
984 //
985 Ke386SetTr(ProcessorState->SpecialRegisters.Tr);
986 Ke386SetLocalDescriptorTable(ProcessorState->SpecialRegisters.Ldtr);
987 }
988
989 VOID
990 NTAPI
991 KiSaveProcessorControlState(OUT PKPROCESSOR_STATE ProcessorState)
992 {
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) ?
998 __readcr4() : 0;
999
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);
1007 __writedr(7, 0);
1008
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();
1014 }
1015
1016 VOID
1017 NTAPI
1018 INIT_FUNCTION
1019 KiInitializeMachineType(VOID)
1020 {
1021 /* Set the Machine Type we got from NTLDR */
1022 KeI386MachineType = KeLoaderBlock->u.I386.MachineType & 0x000FF;
1023 }
1024
1025 ULONG_PTR
1026 NTAPI
1027 INIT_FUNCTION
1028 KiLoadFastSyscallMachineSpecificRegisters(IN ULONG_PTR Context)
1029 {
1030 /* Set CS and ESP */
1031 WRMSR(0x174, KGDT_R0_CODE);
1032 WRMSR(0x175, (ULONG_PTR)KeGetCurrentPrcb()->DpcStack);
1033
1034 /* Set LSTAR */
1035 WRMSR(0x176, (ULONG_PTR)KiFastCallEntry);
1036 return 0;
1037 }
1038
1039 VOID
1040 NTAPI
1041 INIT_FUNCTION
1042 KiRestoreFastSyscallReturnState(VOID)
1043 {
1044 /* Check if the CPU Supports fast system call */
1045 if (KeFeatureBits & KF_FAST_SYSCALL)
1046 {
1047 /* Check if it has been disabled */
1048 if (!KiFastSystemCallDisable)
1049 {
1050 /* Do an IPI to enable it */
1051 KeIpiGenericCall(KiLoadFastSyscallMachineSpecificRegisters, 0);
1052
1053 /* It's enabled, so use the proper exit stub */
1054 KiFastCallExitHandler = KiSystemCallSysExitReturn;
1055 DPRINT1("Support for SYSENTER detected.\n");
1056 }
1057 else
1058 {
1059 /* Disable fast system call */
1060 KeFeatureBits &= ~KF_FAST_SYSCALL;
1061 KiFastCallExitHandler = KiSystemCallTrapReturn;
1062 DPRINT1("Support for SYSENTER disabled.\n");
1063 }
1064 }
1065 else
1066 {
1067 /* Use the IRET handler */
1068 KiFastCallExitHandler = KiSystemCallTrapReturn;
1069 DPRINT1("No support for SYSENTER detected.\n");
1070 }
1071 }
1072
1073 ULONG_PTR
1074 NTAPI
1075 INIT_FUNCTION
1076 Ki386EnableDE(IN ULONG_PTR Context)
1077 {
1078 /* Enable DE */
1079 __writecr4(__readcr4() | CR4_DE);
1080 return 0;
1081 }
1082
1083 ULONG_PTR
1084 NTAPI
1085 INIT_FUNCTION
1086 Ki386EnableFxsr(IN ULONG_PTR Context)
1087 {
1088 /* Enable FXSR */
1089 __writecr4(__readcr4() | CR4_FXSR);
1090 return 0;
1091 }
1092
1093 ULONG_PTR
1094 NTAPI
1095 INIT_FUNCTION
1096 Ki386EnableXMMIExceptions(IN ULONG_PTR Context)
1097 {
1098 PKIDTENTRY IdtEntry;
1099
1100 /* Get the IDT Entry for Interrupt 0x13 */
1101 IdtEntry = &((PKIPCR)KeGetPcr())->IDT[0x13];
1102
1103 /* Set it up */
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;
1110
1111 /* Enable XMMI exceptions */
1112 __writecr4(__readcr4() | CR4_XMMEXCPT);
1113 return 0;
1114 }
1115
1116 VOID
1117 NTAPI
1118 INIT_FUNCTION
1119 KiI386PentiumLockErrataFixup(VOID)
1120 {
1121 KDESCRIPTOR IdtDescriptor;
1122 PKIDTENTRY NewIdt, NewIdt2;
1123
1124 /* Allocate memory for a new IDT */
1125 NewIdt = ExAllocatePool(NonPagedPool, 2 * PAGE_SIZE);
1126
1127 /* Put everything after the first 7 entries on a new page */
1128 NewIdt2 = (PVOID)((ULONG_PTR)NewIdt + PAGE_SIZE - (7 * sizeof(KIDTENTRY)));
1129
1130 /* Disable interrupts */
1131 _disable();
1132
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;
1139
1140 /* Set the new IDT */
1141 __lidt(&IdtDescriptor.Limit);
1142 ((PKIPCR)KeGetPcr())->IDT = NewIdt2;
1143
1144 /* Restore interrupts */
1145 _enable();
1146
1147 /* Set the first 7 entries as read-only to produce a fault */
1148 MmSetPageProtect(NULL, NewIdt, PAGE_READONLY);
1149 }
1150
1151 BOOLEAN
1152 NTAPI
1153 KeDisableInterrupts(VOID)
1154 {
1155 ULONG Flags;
1156 BOOLEAN Return;
1157
1158 /* Get EFLAGS and check if the interrupt bit is set */
1159 Flags = __readeflags();
1160 Return = (Flags & EFLAGS_INTERRUPT_MASK) ? TRUE: FALSE;
1161
1162 /* Disable interrupts */
1163 _disable();
1164 return Return;
1165 }
1166
1167 BOOLEAN
1168 NTAPI
1169 KeInvalidateAllCaches(VOID)
1170 {
1171 /* Only supported on Pentium Pro and higher */
1172 if (KeI386CpuType < 6) return FALSE;
1173
1174 /* Invalidate all caches */
1175 __wbinvd();
1176 return TRUE;
1177 }
1178
1179 VOID
1180 FASTCALL
1181 KeZeroPages(IN PVOID Address,
1182 IN ULONG Size)
1183 {
1184 /* Not using XMMI in this routine */
1185 RtlZeroMemory(Address, Size);
1186 }
1187
1188 VOID
1189 NTAPI
1190 KiSaveProcessorState(IN PKTRAP_FRAME TrapFrame,
1191 IN PKEXCEPTION_FRAME ExceptionFrame)
1192 {
1193 PKPRCB Prcb = KeGetCurrentPrcb();
1194
1195 //
1196 // Save full context
1197 //
1198 Prcb->ProcessorState.ContextFrame.ContextFlags = CONTEXT_FULL |
1199 CONTEXT_DEBUG_REGISTERS;
1200 KeTrapFrameToContext(TrapFrame, NULL, &Prcb->ProcessorState.ContextFrame);
1201
1202 //
1203 // Save control registers
1204 //
1205 KiSaveProcessorControlState(&Prcb->ProcessorState);
1206 }
1207
1208 BOOLEAN
1209 NTAPI
1210 INIT_FUNCTION
1211 KiIsNpxPresent(VOID)
1212 {
1213 ULONG Cr0;
1214 USHORT Magic;
1215
1216 /* Set magic */
1217 Magic = 0xFFFF;
1218
1219 /* Read CR0 and mask out FPU flags */
1220 Cr0 = __readcr0() & ~(CR0_MP | CR0_TS | CR0_EM | CR0_ET);
1221
1222 /* Store on FPU stack */
1223 #ifdef _MSC_VER
1224 __asm fninit;
1225 __asm fnstsw Magic;
1226 #else
1227 asm volatile ("fninit;" "fnstsw %0" : "+m"(Magic));
1228 #endif
1229
1230 /* Magic should now be cleared */
1231 if (Magic & 0xFF)
1232 {
1233 /* You don't have an FPU -- enable emulation for now */
1234 __writecr0(Cr0 | CR0_EM | CR0_TS);
1235 return FALSE;
1236 }
1237
1238 /* You have an FPU, enable it */
1239 Cr0 |= CR0_ET;
1240
1241 /* Enable INT 16 on 486 and higher */
1242 if (KeGetCurrentPrcb()->CpuType >= 3) Cr0 |= CR0_NE;
1243
1244 /* Set FPU state */
1245 __writecr0(Cr0 | CR0_EM | CR0_TS);
1246 return TRUE;
1247 }
1248
1249 BOOLEAN
1250 NTAPI
1251 INIT_FUNCTION
1252 KiIsNpxErrataPresent(VOID)
1253 {
1254 BOOLEAN ErrataPresent;
1255 ULONG Cr0;
1256 volatile double Value1, Value2;
1257
1258 /* Disable interrupts */
1259 _disable();
1260
1261 /* Read CR0 and remove FPU flags */
1262 Cr0 = __readcr0();
1263 __writecr0(Cr0 & ~(CR0_MP | CR0_TS | CR0_EM));
1264
1265 /* Initialize FPU state */
1266 Ke386FnInit();
1267
1268 /* Multiply the magic values and divide, we should get the result back */
1269 Value1 = 4195835.0;
1270 Value2 = 3145727.0;
1271 ErrataPresent = (Value1 * Value2 / 3145727.0) != 4195835.0;
1272
1273 /* Restore CR0 */
1274 __writecr0(Cr0);
1275
1276 /* Enable interrupts */
1277 _enable();
1278
1279 /* Return if there's an errata */
1280 return ErrataPresent;
1281 }
1282
1283 VOID
1284 NTAPI
1285 KiFlushNPXState(IN PFLOATING_SAVE_AREA SaveArea)
1286 {
1287 ULONG EFlags, Cr0;
1288 PKTHREAD Thread, NpxThread;
1289 PFX_SAVE_AREA FxSaveArea;
1290
1291 /* Save volatiles and disable interrupts */
1292 EFlags = __readeflags();
1293 _disable();
1294
1295 /* Save the PCR and get the current thread */
1296 Thread = KeGetCurrentThread();
1297
1298 /* Check if we're already loaded */
1299 if (Thread->NpxState != NPX_STATE_LOADED)
1300 {
1301 /* If there's nothing to load, quit */
1302 if (!SaveArea) return;
1303
1304 /* Need FXSR support for this */
1305 ASSERT(KeI386FxsrPresent == TRUE);
1306
1307 /* Check for sane CR0 */
1308 Cr0 = __readcr0();
1309 if (Cr0 & (CR0_MP | CR0_TS | CR0_EM))
1310 {
1311 /* Mask out FPU flags */
1312 __writecr0(Cr0 & ~(CR0_MP | CR0_TS | CR0_EM));
1313 }
1314
1315 /* Get the NPX thread and check its FPU state */
1316 NpxThread = KeGetCurrentPrcb()->NpxThread;
1317 if ((NpxThread) && (NpxThread->NpxState == NPX_STATE_LOADED))
1318 {
1319 /* Get the FX frame and store the state there */
1320 FxSaveArea = KiGetThreadNpxArea(NpxThread);
1321 Ke386FxSave(FxSaveArea);
1322
1323 /* NPX thread has lost its state */
1324 NpxThread->NpxState = NPX_STATE_NOT_LOADED;
1325 }
1326
1327 /* Now load NPX state from the NPX area */
1328 FxSaveArea = KiGetThreadNpxArea(Thread);
1329 Ke386FxStore(FxSaveArea);
1330 }
1331 else
1332 {
1333 /* Check for sane CR0 */
1334 Cr0 = __readcr0();
1335 if (Cr0 & (CR0_MP | CR0_TS | CR0_EM))
1336 {
1337 /* Mask out FPU flags */
1338 __writecr0(Cr0 & ~(CR0_MP | CR0_TS | CR0_EM));
1339 }
1340
1341 /* Get FX frame */
1342 FxSaveArea = KiGetThreadNpxArea(Thread);
1343 Thread->NpxState = NPX_STATE_NOT_LOADED;
1344
1345 /* Save state if supported by CPU */
1346 if (KeI386FxsrPresent) Ke386FxSave(FxSaveArea);
1347 }
1348
1349 /* Now save the FN state wherever it was requested */
1350 if (SaveArea) Ke386FnSave(SaveArea);
1351
1352 /* Clear NPX thread */
1353 KeGetCurrentPrcb()->NpxThread = NULL;
1354
1355 /* Add the CR0 from the NPX frame */
1356 Cr0 |= NPX_STATE_NOT_LOADED;
1357 Cr0 |= FxSaveArea->Cr0NpxState;
1358 __writecr0(Cr0);
1359
1360 /* Restore interrupt state */
1361 __writeeflags(EFlags);
1362 }
1363
1364 /* PUBLIC FUNCTIONS **********************************************************/
1365
1366 /*
1367 * @implemented
1368 */
1369 VOID
1370 NTAPI
1371 KiCoprocessorError(VOID)
1372 {
1373 PFX_SAVE_AREA NpxArea;
1374
1375 /* Get the FPU area */
1376 NpxArea = KiGetThreadNpxArea(KeGetCurrentThread());
1377
1378 /* Set CR0_TS */
1379 NpxArea->Cr0NpxState = CR0_TS;
1380 __writecr0(__readcr0() | CR0_TS);
1381 }
1382
1383 /*
1384 * @implemented
1385 */
1386 NTSTATUS
1387 NTAPI
1388 KeSaveFloatingPointState(OUT PKFLOATING_SAVE Save)
1389 {
1390 PFNSAVE_FORMAT FpState;
1391 ASSERT(KeGetCurrentIrql() <= DISPATCH_LEVEL);
1392 DPRINT1("%s is not really implemented\n", __FUNCTION__);
1393
1394 /* check if we are doing software emulation */
1395 if (!KeI386NpxPresent) return STATUS_ILLEGAL_FLOAT_CONTEXT;
1396
1397 FpState = ExAllocatePool(NonPagedPool, sizeof (FNSAVE_FORMAT));
1398 if (!FpState) return STATUS_INSUFFICIENT_RESOURCES;
1399
1400 *((PVOID *) Save) = FpState;
1401 #ifdef __GNUC__
1402 asm volatile("fnsave %0\n\t" : "=m" (*FpState));
1403 #else
1404 __asm
1405 {
1406 fnsave [FpState]
1407 };
1408 #endif
1409
1410 KeGetCurrentThread()->DispatcherHeader.NpxIrql = KeGetCurrentIrql();
1411 return STATUS_SUCCESS;
1412 }
1413
1414 /*
1415 * @implemented
1416 */
1417 NTSTATUS
1418 NTAPI
1419 KeRestoreFloatingPointState(IN PKFLOATING_SAVE Save)
1420 {
1421 PFNSAVE_FORMAT FpState = *((PVOID *) Save);
1422 ASSERT(KeGetCurrentThread()->DispatcherHeader.NpxIrql == KeGetCurrentIrql());
1423 DPRINT1("%s is not really implemented\n", __FUNCTION__);
1424
1425 #ifdef __GNUC__
1426 asm volatile("fnclex\n\t");
1427 asm volatile("frstor %0\n\t" : "=m" (*FpState));
1428 #else
1429 __asm
1430 {
1431 fnclex
1432 frstor [FpState]
1433 };
1434 #endif
1435
1436 ExFreePool(FpState);
1437 return STATUS_SUCCESS;
1438 }
1439
1440 /*
1441 * @implemented
1442 */
1443 ULONG
1444 NTAPI
1445 KeGetRecommendedSharedDataAlignment(VOID)
1446 {
1447 /* Return the global variable */
1448 return KeLargestCacheLine;
1449 }
1450
1451 VOID
1452 NTAPI
1453 KiFlushTargetEntireTb(IN PKIPI_CONTEXT PacketContext,
1454 IN PVOID Ignored1,
1455 IN PVOID Ignored2,
1456 IN PVOID Ignored3)
1457 {
1458 /* Signal this packet as done */
1459 KiIpiSignalPacketDone(PacketContext);
1460
1461 /* Flush the TB for the Current CPU */
1462 KeFlushCurrentTb();
1463 }
1464
1465 /*
1466 * @implemented
1467 */
1468 VOID
1469 NTAPI
1470 KeFlushEntireTb(IN BOOLEAN Invalid,
1471 IN BOOLEAN AllProcessors)
1472 {
1473 KIRQL OldIrql;
1474 #ifdef CONFIG_SMP
1475 KAFFINITY TargetAffinity;
1476 PKPRCB Prcb = KeGetCurrentPrcb();
1477 #endif
1478
1479 /* Raise the IRQL for the TB Flush */
1480 OldIrql = KeRaiseIrqlToSynchLevel();
1481
1482 #ifdef CONFIG_SMP
1483 /* FIXME: Use KiTbFlushTimeStamp to synchronize TB flush */
1484
1485 /* Get the current processor affinity, and exclude ourselves */
1486 TargetAffinity = KeActiveProcessors;
1487 TargetAffinity &= ~Prcb->SetMember;
1488
1489 /* Make sure this is MP */
1490 if (TargetAffinity)
1491 {
1492 /* Send an IPI TB flush to the other processors */
1493 KiIpiSendPacket(TargetAffinity,
1494 KiFlushTargetEntireTb,
1495 NULL,
1496 0,
1497 NULL);
1498 }
1499 #endif
1500
1501 /* Flush the TB for the Current CPU, and update the flush stamp */
1502 KeFlushCurrentTb();
1503
1504 #ifdef CONFIG_SMP
1505 /* If this is MP, wait for the other processors to finish */
1506 if (TargetAffinity)
1507 {
1508 /* Sanity check */
1509 ASSERT(Prcb == (volatile PKPRCB)KeGetCurrentPrcb());
1510
1511 /* FIXME: TODO */
1512 ASSERTMSG("Not yet implemented\n", FALSE);
1513 }
1514 #endif
1515
1516 /* Update the flush stamp and return to original IRQL */
1517 InterlockedExchangeAdd(&KiTbFlushTimeStamp, 1);
1518 KeLowerIrql(OldIrql);
1519 }
1520
1521 /*
1522 * @implemented
1523 */
1524 VOID
1525 NTAPI
1526 KeSetDmaIoCoherency(IN ULONG Coherency)
1527 {
1528 /* Save the coherency globally */
1529 KiDmaIoCoherency = Coherency;
1530 }
1531
1532 /*
1533 * @implemented
1534 */
1535 KAFFINITY
1536 NTAPI
1537 KeQueryActiveProcessors(VOID)
1538 {
1539 PAGED_CODE();
1540
1541 /* Simply return the number of active processors */
1542 return KeActiveProcessors;
1543 }
1544
1545 /*
1546 * @implemented
1547 */
1548 VOID
1549 __cdecl
1550 KeSaveStateForHibernate(IN PKPROCESSOR_STATE State)
1551 {
1552 /* Capture the context */
1553 RtlCaptureContext(&State->ContextFrame);
1554
1555 /* Capture the control state */
1556 KiSaveProcessorControlState(State);
1557 }