Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2048 lines
50 KiB

  1. /*++
  2. Copyright (c) 1991-2000 Microsoft Corporation
  3. Module Name:
  4. mtrr.c
  5. Abstract:
  6. This module implements interfaces that support manipulation of
  7. memory type range registers.
  8. These entry points only exist on x86 machines.
  9. Author:
  10. Ken Reneris (kenr) 11-Oct-95
  11. Environment:
  12. Kernel mode only.
  13. Revision History:
  14. --*/
  15. #include "ki.h"
  16. #include "mtrr.h"
  17. #define STATIC
  18. #define IDBG 0
  19. #if DBG
  20. #define DBGMSG(a) DbgPrint(a)
  21. #else
  22. #define DBGMSG(a)
  23. #endif
  24. //
  25. // Internal declarations
  26. //
  27. //
  28. // Range in generic terms
  29. //
  30. typedef struct _ONE_RANGE {
  31. ULONGLONG Base;
  32. ULONGLONG Limit;
  33. UCHAR Type;
  34. } ONE_RANGE, *PONE_RANGE;
  35. #define GROW_RANGE_TABLE 4
  36. //
  37. // Range in specific mtrr terms
  38. //
  39. typedef struct _MTRR_RANGE {
  40. MTRR_VARIABLE_BASE Base;
  41. MTRR_VARIABLE_MASK Mask;
  42. } MTRR_RANGE, *PMTRR_RANGE;
  43. //
  44. // System static information concerning cached range types
  45. //
  46. typedef struct _RANGE_INFO {
  47. //
  48. // Global MTRR info
  49. //
  50. MTRR_DEFAULT Default; // h/w mtrr default
  51. MTRR_CAPABILITIES Capabilities; // h/w mtrr Capabilities
  52. UCHAR DefaultCachedType; // default type for MmCached
  53. //
  54. // Variable MTRR information
  55. //
  56. BOOLEAN RangesValid; // Ranges initialized and valid.
  57. BOOLEAN MtrrWorkaround; // Work Around needed/not.
  58. UCHAR NoRange; // No ranges currently in Ranges
  59. UCHAR MaxRange; // Max size of Ranges
  60. PONE_RANGE Ranges; // Current ranges as set into h/w
  61. } RANGE_INFO, *PRANGE_INFO;
  62. //
  63. // Structure used while processing range database
  64. //
  65. typedef struct _NEW_RANGE {
  66. //
  67. // Current Status
  68. //
  69. NTSTATUS Status;
  70. //
  71. // Generic info on new range
  72. //
  73. ULONGLONG Base;
  74. ULONGLONG Limit;
  75. UCHAR Type;
  76. //
  77. // MTRR image to be set into h/w
  78. //
  79. PMTRR_RANGE MTRR;
  80. //
  81. // RangeDatabase before edits were started
  82. //
  83. UCHAR NoRange;
  84. PONE_RANGE Ranges;
  85. //
  86. // IPI context to coordinate concurrent processor update
  87. //
  88. ULONG NoMTRR;
  89. PROCESSOR_LOCKSTEP Synchronize;
  90. ULONG Processor;
  91. } NEW_RANGE, *PNEW_RANGE;
  92. //
  93. // Prototypes
  94. //
  95. VOID
  96. KiInitializeMTRR (
  97. IN BOOLEAN LastProcessor
  98. );
  99. BOOLEAN
  100. KiRemoveRange (
  101. IN PNEW_RANGE NewRange,
  102. IN ULONGLONG Base,
  103. IN ULONGLONG Limit,
  104. IN PBOOLEAN RemoveThisType
  105. );
  106. VOID
  107. KiAddRange (
  108. IN PNEW_RANGE NewRange,
  109. IN ULONGLONG Base,
  110. IN ULONGLONG Limit,
  111. IN UCHAR Type
  112. );
  113. VOID
  114. KiStartEffectiveRangeChange (
  115. IN PNEW_RANGE NewRange
  116. );
  117. VOID
  118. KiCompleteEffectiveRangeChange (
  119. IN PNEW_RANGE NewRange
  120. );
  121. STATIC ULONG
  122. KiRangeWeight (
  123. IN PONE_RANGE Range
  124. );
  125. STATIC ULONG
  126. KiFindFirstSetLeftBit (
  127. IN ULONGLONG Set
  128. );
  129. STATIC ULONG
  130. KiFindFirstSetRightBit (
  131. IN ULONGLONG Set
  132. );
  133. VOID
  134. KiLoadMTRRTarget (
  135. IN PKIPI_CONTEXT SignalDone,
  136. IN PVOID Context,
  137. IN PVOID Parameter2,
  138. IN PVOID Parameter3
  139. );
  140. NTSTATUS
  141. KiLoadMTRR (
  142. IN PNEW_RANGE Context
  143. );
  144. ULONGLONG
  145. KiMaskToLength (
  146. IN ULONGLONG Mask
  147. );
  148. ULONGLONG
  149. KiLengthToMask (
  150. IN ULONGLONG Length
  151. );
  152. #if IDBG
  153. VOID
  154. KiDumpMTRR (
  155. PUCHAR DebugString,
  156. PMTRR_RANGE MTRR
  157. );
  158. #endif
  159. //
  160. // --- AMD - Prototypes for AMD K6 MTRR Support functions. ---
  161. //
  162. NTSTATUS
  163. KiAmdK6MtrrSetMemoryType (
  164. IN ULONG BaseAddress,
  165. IN ULONG NumberOfBytes,
  166. IN MEMORY_CACHING_TYPE CacheType
  167. );
  168. VOID
  169. KiAmdK6MtrrWRMSR (
  170. VOID
  171. );
  172. // --- AMD - End ---
  173. #ifdef ALLOC_PRAGMA
  174. #pragma alloc_text(INIT,KiInitializeMTRR)
  175. #pragma alloc_text(PAGELK,KiRemoveRange)
  176. #pragma alloc_text(PAGELK,KiAddRange)
  177. #pragma alloc_text(PAGELK,KiStartEffectiveRangeChange)
  178. #pragma alloc_text(PAGELK,KiCompleteEffectiveRangeChange)
  179. #pragma alloc_text(PAGELK,KiRangeWeight)
  180. #pragma alloc_text(PAGELK,KiFindFirstSetLeftBit)
  181. #pragma alloc_text(PAGELK,KiFindFirstSetRightBit)
  182. #pragma alloc_text(PAGELK,KiLoadMTRR)
  183. #pragma alloc_text(PAGELK,KiLoadMTRRTarget)
  184. #pragma alloc_text(PAGELK,KiLockStepExecution)
  185. #pragma alloc_text(PAGELK,KiLengthToMask)
  186. #pragma alloc_text(PAGELK,KiMaskToLength)
  187. #if IDBG
  188. #pragma alloc_text(PAGELK,KiDumpMTRR)
  189. #endif
  190. #endif
  191. //
  192. // KiRangeLock - Used to synchronize accesses to KiRangeInfo
  193. //
  194. KSPIN_LOCK KiRangeLock;
  195. //
  196. // KiRangeInfo - Range type mapping information. Details specific h/w support
  197. // and contains the current range database of how physical
  198. // addresses have been set
  199. RANGE_INFO KiRangeInfo;
  200. VOID
  201. KiInitializeMTRR (
  202. IN BOOLEAN LastProcessor
  203. )
  204. /*++
  205. Routine Description:
  206. Called to incrementally initialize the physical range
  207. database feature. First processor's MTRR set is read into the
  208. physical range database.
  209. Arguments:
  210. LastProcessor - If set this is the last processor to execute this routine
  211. such that when this processor finishes, the initialization is complete.
  212. Return Value:
  213. None - if there was a problem the function
  214. KeSetPhysicalCacheTypeRange type is disabled.
  215. --*/
  216. {
  217. BOOLEAN Status;
  218. ULONG Index, Size;
  219. MTRR_DEFAULT Default;
  220. MTRR_CAPABILITIES Capabilities;
  221. NEW_RANGE NewRange;
  222. MTRR_VARIABLE_BASE MtrrBase;
  223. MTRR_VARIABLE_MASK MtrrMask;
  224. ULONGLONG Base, Mask, Length;
  225. BOOLEAN RemoveThisType[MTRR_TYPE_MAX];
  226. NTSTATUS NtStatus;
  227. PKPRCB Prcb;
  228. Status = TRUE;
  229. RtlZeroMemory (&NewRange, sizeof (NewRange));
  230. NewRange.Status = STATUS_UNSUCCESSFUL;
  231. //
  232. // If this is the first processor, initialize some fields
  233. //
  234. if (KeGetPcr()->Number == 0) {
  235. KeInitializeSpinLock (&KiRangeLock);
  236. KiRangeInfo.Capabilities.u.QuadPart = RDMSR(MTRR_MSR_CAPABILITIES);
  237. KiRangeInfo.Default.u.QuadPart = RDMSR(MTRR_MSR_DEFAULT);
  238. KiRangeInfo.DefaultCachedType = MTRR_TYPE_MAX;
  239. //
  240. // If h/w mtrr support is not enabled, disable OS support
  241. //
  242. if (!KiRangeInfo.Default.u.hw.MtrrEnabled ||
  243. KiRangeInfo.Capabilities.u.hw.VarCnt == 0 ||
  244. KiRangeInfo.Default.u.hw.Type != MTRR_TYPE_UC) {
  245. DBGMSG("MTRR feature disabled.\n");
  246. Status = FALSE;
  247. } else {
  248. //
  249. // If USWC type is supported by hardware, but the MTRR
  250. // feature is not set in KeFeatureBits, it is because
  251. // the HAL indicated USWC should not be used on this
  252. // machine. (Possibly due to shared memory clusters).
  253. //
  254. if (KiRangeInfo.Capabilities.u.hw.UswcSupported &&
  255. ((KeFeatureBits & KF_MTRR) == 0)) {
  256. DBGMSG("KiInitializeMTRR: MTRR use globally disabled on this machine.\n");
  257. KiRangeInfo.Capabilities.u.hw.UswcSupported = 0;
  258. }
  259. //
  260. // Allocate initial range type database
  261. //
  262. KiRangeInfo.NoRange = 0;
  263. KiRangeInfo.MaxRange = (UCHAR) KiRangeInfo.Capabilities.u.hw.VarCnt + GROW_RANGE_TABLE;
  264. //
  265. // Don't allocate a new range on reinitialization from
  266. // hibernate.
  267. //
  268. if (KiRangeInfo.Ranges == NULL) {
  269. KiRangeInfo.Ranges = ExAllocatePoolWithTag (NonPagedPool,
  270. sizeof(ONE_RANGE) * KiRangeInfo.MaxRange,
  271. ' eK');
  272. }
  273. if (KiRangeInfo.Ranges != NULL) {
  274. RtlZeroMemory (KiRangeInfo.Ranges,
  275. sizeof(ONE_RANGE) * KiRangeInfo.MaxRange);
  276. }
  277. }
  278. }
  279. //
  280. // Workaround for cpu signatures 611, 612, 616 and 617
  281. // - if the request for setting a variable MTRR specifies
  282. // an address which is not 4M aligned or length is not
  283. // a multiple of 4M then possible problem for INVLPG inst.
  284. // Detect if workaround is required
  285. //
  286. Prcb = KeGetCurrentPrcb();
  287. if (Prcb->CpuType == 6 &&
  288. (Prcb->CpuStep == 0x0101 || Prcb->CpuStep == 0x0102 ||
  289. Prcb->CpuStep == 0x0106 || Prcb->CpuStep == 0x0107 )) {
  290. if (strcmp(Prcb->VendorString, "GenuineIntel") == 0) {
  291. //
  292. // Only do this if it's an Intel part, other
  293. // manufacturers may have the same stepping
  294. // numbers but no bug.
  295. //
  296. KiRangeInfo.MtrrWorkaround = TRUE;
  297. }
  298. }
  299. //
  300. // If MTRR support disabled on first processor or if
  301. // buffer not allocated then fall through
  302. //
  303. if (!KiRangeInfo.Ranges){
  304. Status = FALSE;
  305. } else {
  306. //
  307. // Verify MTRR support is symmetric
  308. //
  309. Capabilities.u.QuadPart = RDMSR(MTRR_MSR_CAPABILITIES);
  310. if ((Capabilities.u.hw.UswcSupported) &&
  311. ((KeFeatureBits & KF_MTRR) == 0)) {
  312. DBGMSG ("KiInitializeMTRR: setting UswcSupported FALSE\n");
  313. Capabilities.u.hw.UswcSupported = 0;
  314. }
  315. Default.u.QuadPart = RDMSR(MTRR_MSR_DEFAULT);
  316. if (Default.u.QuadPart != KiRangeInfo.Default.u.QuadPart ||
  317. Capabilities.u.QuadPart != KiRangeInfo.Capabilities.u.QuadPart) {
  318. DBGMSG ("KiInitializeMTRR: asymmetric mtrr support\n");
  319. Status = FALSE;
  320. }
  321. }
  322. NewRange.Status = STATUS_SUCCESS;
  323. //
  324. // MTRR registers should be identically set on each processor.
  325. // Ranges should be added to the range database only for one
  326. // processor.
  327. //
  328. if (Status && (KeGetPcr()->Number == 0)) {
  329. #if IDBG
  330. KiDumpMTRR ("Processor MTRR:", NULL);
  331. #endif
  332. //
  333. // Read current MTRR settings for various cached range types
  334. // and add them to the range database
  335. //
  336. for (Index=0; Index < Capabilities.u.hw.VarCnt; Index++) {
  337. MtrrBase.u.QuadPart = RDMSR(MTRR_MSR_VARIABLE_BASE+Index*2);
  338. MtrrMask.u.QuadPart = RDMSR(MTRR_MSR_VARIABLE_MASK+Index*2);
  339. Mask = MtrrMask.u.QuadPart & MTRR_MASK_MASK;
  340. Base = MtrrBase.u.QuadPart & MTRR_MASK_BASE;
  341. //
  342. // Note - the variable MTRR Mask does NOT contain the length
  343. // spanned by the variable MTRR. Thus just checking the Valid
  344. // Bit should be sufficient for identifying a valid MTRR.
  345. //
  346. if (MtrrMask.u.hw.Valid) {
  347. Length = KiMaskToLength(Mask);
  348. //
  349. // Check for non-contiguous MTRR mask.
  350. //
  351. if ((Mask + Length) & MASK_OVERFLOW_MASK) {
  352. DBGMSG ("KiInitializeMTRR: Found non-contiguous MTRR mask!\n");
  353. Status = FALSE;
  354. }
  355. //
  356. // Add this MTRR to the range database
  357. //
  358. Base &= Mask;
  359. KiAddRange (
  360. &NewRange,
  361. Base,
  362. Base + Length - 1,
  363. (UCHAR) MtrrBase.u.hw.Type
  364. );
  365. //
  366. // Check for default cache type
  367. //
  368. if (MtrrBase.u.hw.Type == MTRR_TYPE_WB) {
  369. KiRangeInfo.DefaultCachedType = MTRR_TYPE_WB;
  370. }
  371. if (KiRangeInfo.DefaultCachedType == MTRR_TYPE_MAX &&
  372. MtrrBase.u.hw.Type == MTRR_TYPE_WT) {
  373. KiRangeInfo.DefaultCachedType = MTRR_TYPE_WT;
  374. }
  375. }
  376. }
  377. //
  378. // If a default type for "cached" was not found, assume write-back
  379. //
  380. if (KiRangeInfo.DefaultCachedType == MTRR_TYPE_MAX) {
  381. DBGMSG ("KiInitializeMTRR: assume write-back\n");
  382. KiRangeInfo.DefaultCachedType = MTRR_TYPE_WB;
  383. }
  384. }
  385. //
  386. // Done
  387. //
  388. if (!NT_SUCCESS(NewRange.Status)) {
  389. Status = FALSE;
  390. }
  391. if (!Status) {
  392. DBGMSG ("KiInitializeMTRR: OS support for MTRRs disabled\n");
  393. if (KiRangeInfo.Ranges != NULL) {
  394. ExFreePool (KiRangeInfo.Ranges);
  395. KiRangeInfo.Ranges = NULL;
  396. }
  397. } else {
  398. // if last processor indicate initialization complete
  399. if (LastProcessor) {
  400. KiRangeInfo.RangesValid = TRUE;
  401. }
  402. }
  403. }
  404. VOID
  405. KeRestoreMtrr (
  406. VOID
  407. )
  408. /*++
  409. Routine Description:
  410. This function reloads the MTRR registers to be the current
  411. known values. This is used on a system wakeup to ensure the
  412. registers are sane.
  413. N.B. The caller must have the PAGELK code locked
  414. Arguments:
  415. none
  416. Return Value:
  417. none
  418. --*/
  419. {
  420. NEW_RANGE NewRange;
  421. KIRQL OldIrql;
  422. if (KiRangeInfo.RangesValid) {
  423. RtlZeroMemory (&NewRange, sizeof (NewRange));
  424. KeAcquireSpinLock (&KiRangeLock, &OldIrql);
  425. KiStartEffectiveRangeChange (&NewRange);
  426. ASSERT (NT_SUCCESS(NewRange.Status));
  427. KiCompleteEffectiveRangeChange (&NewRange);
  428. KeReleaseSpinLock (&KiRangeLock, OldIrql);
  429. return;
  430. }
  431. //
  432. // If the processor is a AMD K6 with MTRR support then perform
  433. // processor specific implentaiton.
  434. //
  435. if (KeFeatureBits & KF_AMDK6MTRR) {
  436. KeAcquireSpinLock (&KiRangeLock, &OldIrql);
  437. KiLoadMTRR(NULL);
  438. KeReleaseSpinLock (&KiRangeLock, OldIrql);
  439. }
  440. }
  441. NTSTATUS
  442. KeSetPhysicalCacheTypeRange (
  443. IN PHYSICAL_ADDRESS PhysicalAddress,
  444. IN ULONG NumberOfBytes,
  445. IN MEMORY_CACHING_TYPE CacheType
  446. )
  447. /*++
  448. Routine Description:
  449. This function sets a physical range to a particular cache type.
  450. If the system does not support setting cache policies based on
  451. physical ranges, no action is taken.
  452. Arguments:
  453. PhysicalAddress - The starting address of the range being set
  454. NumberOfBytes - The length, in bytes, of the range being set
  455. CacheType - The caching type for which the physical range is
  456. to be set to.
  457. NonCached:
  458. Setting ranges to be NonCached is done for
  459. book keeping reasons. A return of SUCCESS when
  460. setting a range NonCached does not mean it has
  461. been physically set to as NonCached. The caller
  462. must use a cache-disabled virtual pointer for
  463. any NonCached range.
  464. Cached:
  465. A successful return indicates that the physical
  466. range has been set to cached. This mode requires
  467. the caller to be at irql < dispatch_level.
  468. FrameBuffer:
  469. A successful return indicates that the physical
  470. range has been set to be framebuffer cached.
  471. This mode requires the caller to be at irql <
  472. dispatch_level.
  473. USWCCached:
  474. This type is to be satisfied only via PAT and
  475. fails for the MTRR interface.
  476. Return Value:
  477. STATUS_SUCCESS - if success, the cache attributes of the physical range
  478. have been set.
  479. STATUS_NOT_SUPPORTED - either feature not supported or not yet initialized,
  480. or MmWriteCombined type not supported and is
  481. requested, or input range does not match restrictions
  482. imposed by workarounds for current processor stepping
  483. or is below 1M (in the fixed MTRR range), or not yet
  484. initialized.
  485. STATUS_UNSUCCESSFUL - Unable to satisfy request due to
  486. - Unable to map software image into limited # of
  487. hardware MTRRs.
  488. - irql was not < DISPATCH_LEVEL.
  489. - Failure due to other internal error (out of memory).
  490. STATUS_INVALID_PARAMETER - Incorrect input memory type.
  491. --*/
  492. {
  493. KIRQL OldIrql;
  494. NEW_RANGE NewRange;
  495. BOOLEAN RemoveThisType[MTRR_TYPE_MAX];
  496. BOOLEAN EffectRangeChange, AddToRangeDatabase;
  497. //
  498. // If caller has requested the MmUSWCCached memory type then fail
  499. // - MmUSWCCached is supported via PAT and not otherwise
  500. //
  501. if (CacheType == MmUSWCCached) {
  502. return STATUS_NOT_SUPPORTED;
  503. }
  504. //
  505. // Addresses above 4GB, below 1MB or not page aligned and
  506. // page length are not supported.
  507. //
  508. if ((PhysicalAddress.HighPart != 0) ||
  509. (PhysicalAddress.LowPart < (1 * 1024 * 1024)) ||
  510. (PhysicalAddress.LowPart & 0xfff) ||
  511. (NumberOfBytes & 0xfff) ) {
  512. return STATUS_NOT_SUPPORTED;
  513. }
  514. ASSERT (NumberOfBytes != 0);
  515. //
  516. // If the processor is a AMD K6 with MTRR support then perform
  517. // processor specific implentaiton.
  518. //
  519. if (KeFeatureBits & KF_AMDK6MTRR) {
  520. if ((CacheType != MmWriteCombined) && (CacheType != MmNonCached)) {
  521. return STATUS_NOT_SUPPORTED;
  522. }
  523. return KiAmdK6MtrrSetMemoryType(PhysicalAddress.LowPart,
  524. NumberOfBytes,
  525. CacheType);
  526. }
  527. //
  528. // If processor doesn't have the memory type range feature
  529. // return not supported.
  530. //
  531. if (!KiRangeInfo.RangesValid) {
  532. return STATUS_NOT_SUPPORTED;
  533. }
  534. //
  535. // Workaround for cpu signatures 611, 612, 616 and 617
  536. // - if the request for setting a variable MTRR specifies
  537. // an address which is not 4M aligned or length is not
  538. // a multiple of 4M then return status not supported
  539. //
  540. if ((KiRangeInfo.MtrrWorkaround) &&
  541. ((PhysicalAddress.LowPart & 0x3fffff) ||
  542. (NumberOfBytes & 0x3fffff))) {
  543. return STATUS_NOT_SUPPORTED;
  544. }
  545. RtlZeroMemory (&NewRange, sizeof (NewRange));
  546. NewRange.Base = PhysicalAddress.QuadPart;
  547. NewRange.Limit = NewRange.Base + NumberOfBytes - 1;
  548. //
  549. // Determine what the new mtrr range type is. If setting NonCached then
  550. // the database need not be updated to reflect the virtual change. This
  551. // is because non-cached virtual pointers are mapped as cache disabled.
  552. //
  553. EffectRangeChange = TRUE;
  554. AddToRangeDatabase = TRUE;
  555. switch (CacheType) {
  556. case MmNonCached:
  557. NewRange.Type = MTRR_TYPE_UC;
  558. //
  559. // NonCached ranges do not need to be reflected into the h/w state
  560. // as all non-cached ranges are mapped with cache-disabled pointers.
  561. // This also means that cache-disabled ranges do not need to
  562. // be put into mtrrs, or held in the range, regardless of the default
  563. // range type.
  564. //
  565. EffectRangeChange = FALSE;
  566. AddToRangeDatabase = FALSE;
  567. break;
  568. case MmCached:
  569. NewRange.Type = KiRangeInfo.DefaultCachedType;
  570. break;
  571. case MmWriteCombined:
  572. NewRange.Type = MTRR_TYPE_USWC;
  573. //
  574. // If USWC type isn't supported, then request can not be honored
  575. //
  576. if (!KiRangeInfo.Capabilities.u.hw.UswcSupported) {
  577. DBGMSG ("KeSetPhysicalCacheTypeRange: USWC not supported\n");
  578. return STATUS_NOT_SUPPORTED;
  579. }
  580. break;
  581. default:
  582. DBGMSG ("KeSetPhysicalCacheTypeRange: no such cache type\n");
  583. return STATUS_INVALID_PARAMETER;
  584. break;
  585. }
  586. NewRange.Status = STATUS_SUCCESS;
  587. //
  588. // The default type is UC thus the range is still mapped using
  589. // a Cache Disabled VirtualPointer and hence it need not be added.
  590. //
  591. //
  592. // If h/w needs updated, lock down the code required to effect the change
  593. //
  594. if (EffectRangeChange) {
  595. if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
  596. //
  597. // Code can not be locked down. Supplying a new range type requires
  598. // that the caller calls at irql < dispatch_level.
  599. //
  600. DBGMSG ("KeSetPhysicalCacheTypeRange failed due to calling IRQL == DISPATCH_LEVEL\n");
  601. return STATUS_UNSUCCESSFUL;
  602. }
  603. MmLockPagableSectionByHandle(ExPageLockHandle);
  604. }
  605. //
  606. // Serialize the range type database
  607. //
  608. KeAcquireSpinLock (&KiRangeLock, &OldIrql);
  609. //
  610. // If h/w is going to need updated, then start an effective range change
  611. //
  612. if (EffectRangeChange) {
  613. KiStartEffectiveRangeChange (&NewRange);
  614. }
  615. if (NT_SUCCESS (NewRange.Status)) {
  616. //
  617. // If the new range is NonCached, then don't remove standard memory
  618. // caching types
  619. //
  620. memset (RemoveThisType, TRUE, MTRR_TYPE_MAX);
  621. if (NewRange.Type != MTRR_TYPE_UC) {
  622. //
  623. // If the requested type is uncached then the physical
  624. // memory region is mapped using a cache disabled virtual pointer.
  625. // The effective memory type for that region will be the lowest
  626. // common denominator of the MTRR type and the cache type in the
  627. // PTE. Therefore for a request of type UC, the effective type
  628. // will be UC irrespective of the MTRR settings in that range.
  629. // Hence it is not necessary to remove the existing MTRR settings
  630. // (if any) for that range.
  631. //
  632. //
  633. // Clip/remove any ranges in the target area
  634. //
  635. KiRemoveRange (&NewRange, NewRange.Base, NewRange.Limit, RemoveThisType);
  636. }
  637. //
  638. // If needed, add new range type
  639. //
  640. if (AddToRangeDatabase) {
  641. ASSERT (EffectRangeChange == TRUE);
  642. KiAddRange (&NewRange, NewRange.Base, NewRange.Limit, NewRange.Type);
  643. }
  644. //
  645. // If this is an effect range change, then complete it
  646. //
  647. if (EffectRangeChange) {
  648. KiCompleteEffectiveRangeChange (&NewRange);
  649. }
  650. }
  651. KeReleaseSpinLock (&KiRangeLock, OldIrql);
  652. if (EffectRangeChange) {
  653. MmUnlockPagableImageSection(ExPageLockHandle);
  654. }
  655. return NewRange.Status;
  656. }
  657. BOOLEAN
  658. KiRemoveRange (
  659. IN PNEW_RANGE NewRange,
  660. IN ULONGLONG Base,
  661. IN ULONGLONG Limit,
  662. IN PBOOLEAN RemoveThisType
  663. )
  664. /*++
  665. Routine Description:
  666. This function removes any range overlapping with the passed range, of
  667. type supplied in RemoveThisType from the global range database.
  668. Arguments:
  669. NewRange - Context information
  670. Base - Base & Limit signify the first & last address of a range
  671. Limit - which is to be removed from the range database
  672. RemoveThisType - A TRUE flag for each type which can not overlap the
  673. target range
  674. Return Value:
  675. TRUE - if the range database was altered such that it may no longer
  676. be sorted.
  677. --*/
  678. {
  679. ULONG i;
  680. PONE_RANGE Range;
  681. BOOLEAN DatabaseNeedsSorted;
  682. DatabaseNeedsSorted = FALSE;
  683. //
  684. // Check each range
  685. //
  686. for (i=0, Range=KiRangeInfo.Ranges; i < KiRangeInfo.NoRange; i++, Range++) {
  687. //
  688. // If this range type doesn't need to be altered, skip it
  689. //
  690. if (!RemoveThisType[Range->Type]) {
  691. continue;
  692. }
  693. //
  694. // Check range to see if it overlaps with range being removed
  695. //
  696. if (Range->Base < Base) {
  697. if (Range->Limit >= Base && Range->Limit <= Limit) {
  698. //
  699. // Truncate range to not overlap with area being removed
  700. //
  701. Range->Limit = Base - 1;
  702. }
  703. if (Range->Limit > Limit) {
  704. //
  705. // Target area is contained totally within this area.
  706. // Split into two ranges
  707. //
  708. //
  709. // Add range at end
  710. //
  711. DatabaseNeedsSorted = TRUE;
  712. KiAddRange (
  713. NewRange,
  714. Limit+1,
  715. Range->Limit,
  716. Range->Type
  717. );
  718. //
  719. // Turn current range into range at beginning
  720. //
  721. Range->Limit = Base - 1;
  722. }
  723. } else {
  724. // Range->Base >= Base
  725. if (Range->Base <= Limit) {
  726. if (Range->Limit <= Limit) {
  727. //
  728. // This range is totally within the target area. Remove it.
  729. //
  730. DatabaseNeedsSorted = TRUE;
  731. KiRangeInfo.NoRange -= 1;
  732. Range->Base = KiRangeInfo.Ranges[KiRangeInfo.NoRange].Base;
  733. Range->Limit = KiRangeInfo.Ranges[KiRangeInfo.NoRange].Limit;
  734. Range->Type = KiRangeInfo.Ranges[KiRangeInfo.NoRange].Type;
  735. //
  736. // recheck at current location
  737. //
  738. i -= 1;
  739. Range -= 1;
  740. } else {
  741. //
  742. // Bump beginning past area being removed
  743. //
  744. Range->Base = Limit + 1;
  745. }
  746. }
  747. }
  748. }
  749. if (!NT_SUCCESS (NewRange->Status)) {
  750. DBGMSG ("KiRemoveRange: failure\n");
  751. }
  752. return DatabaseNeedsSorted;
  753. }
  754. VOID
  755. KiAddRange (
  756. IN PNEW_RANGE NewRange,
  757. IN ULONGLONG Base,
  758. IN ULONGLONG Limit,
  759. IN UCHAR Type
  760. )
  761. /*++
  762. Routine Description:
  763. This function adds the passed range to the global range database.
  764. Arguments:
  765. NewRange - Context information
  766. Base - Base & Limit signify the first & last address of a range
  767. Limit - which is to be added to the range database
  768. Type - Type of caching required for this range
  769. Return Value:
  770. None - Context is updated with an error if the table has overflowed
  771. --*/
  772. {
  773. PONE_RANGE Range, OldRange;
  774. ULONG size;
  775. if (KiRangeInfo.NoRange >= KiRangeInfo.MaxRange) {
  776. //
  777. // Table is out of space, get a bigger one
  778. //
  779. OldRange = KiRangeInfo.Ranges;
  780. size = sizeof(ONE_RANGE) * (KiRangeInfo.MaxRange + GROW_RANGE_TABLE);
  781. Range = ExAllocatePoolWithTag (NonPagedPool, size, ' eK');
  782. if (!Range) {
  783. NewRange->Status = STATUS_UNSUCCESSFUL;
  784. return ;
  785. }
  786. //
  787. // Grow table
  788. //
  789. RtlZeroMemory (Range, size);
  790. RtlCopyMemory (Range, OldRange, sizeof(ONE_RANGE) * KiRangeInfo.MaxRange);
  791. KiRangeInfo.Ranges = Range;
  792. KiRangeInfo.MaxRange += GROW_RANGE_TABLE;
  793. ExFreePool (OldRange);
  794. }
  795. //
  796. // Add new entry to table
  797. //
  798. KiRangeInfo.Ranges[KiRangeInfo.NoRange].Base = Base;
  799. KiRangeInfo.Ranges[KiRangeInfo.NoRange].Limit = Limit;
  800. KiRangeInfo.Ranges[KiRangeInfo.NoRange].Type = Type;
  801. KiRangeInfo.NoRange += 1;
  802. }
  803. VOID
  804. KiStartEffectiveRangeChange (
  805. IN PNEW_RANGE NewRange
  806. )
  807. /*++
  808. Routine Description:
  809. This functions sets up the context information required to
  810. track & later effect a range change in hardware
  811. Arguments:
  812. NewRange - Context information
  813. Return Value:
  814. None
  815. --*/
  816. {
  817. ULONG size;
  818. //
  819. // Allocate working space for MTRR image
  820. //
  821. size = sizeof(MTRR_RANGE) * ((ULONG) KiRangeInfo.Capabilities.u.hw.VarCnt + 1);
  822. NewRange->MTRR = ExAllocatePoolWithTag (NonPagedPool, size, ' eK');
  823. if (!NewRange->MTRR) {
  824. NewRange->Status = STATUS_UNSUCCESSFUL;
  825. return ;
  826. }
  827. RtlZeroMemory (NewRange->MTRR, size);
  828. //
  829. // Save current range information in case of an error
  830. //
  831. size = sizeof(ONE_RANGE) * KiRangeInfo.NoRange;
  832. NewRange->NoRange = KiRangeInfo.NoRange;
  833. NewRange->Ranges = ExAllocatePoolWithTag (NonPagedPool, size, ' eK');
  834. if (!NewRange->Ranges) {
  835. NewRange->Status = STATUS_UNSUCCESSFUL;
  836. return ;
  837. }
  838. RtlCopyMemory (NewRange->Ranges, KiRangeInfo.Ranges, size);
  839. }
  840. VOID
  841. KiCompleteEffectiveRangeChange (
  842. IN PNEW_RANGE NewRange
  843. )
  844. /*++
  845. Routine Description:
  846. This functions commits the range database to hardware, or backs
  847. out the current changes to it.
  848. Arguments:
  849. NewRange - Context information
  850. Return Value:
  851. None
  852. --*/
  853. {
  854. BOOLEAN Restart;
  855. ULONG Index, Index2, RemIndex2, NoMTRR;
  856. ULONGLONG BestLength, WhichMtrr;
  857. ULONGLONG CurrLength;
  858. ULONGLONG l, Base, Length, MLength;
  859. PONE_RANGE Range;
  860. ONE_RANGE OneRange;
  861. PMTRR_RANGE MTRR;
  862. BOOLEAN RoundDown;
  863. BOOLEAN RemoveThisType[MTRR_TYPE_MAX];
  864. PKPRCB Prcb;
  865. KIRQL OldIrql, OldIrql2;
  866. KAFFINITY TargetProcessors;
  867. ASSERT (KeGetCurrentIrql() == DISPATCH_LEVEL);
  868. Prcb = KeGetCurrentPrcb();
  869. //
  870. // Round all ranges, according to type, to match what h/w can support
  871. //
  872. for (Index=0; Index < KiRangeInfo.NoRange; Index++) {
  873. Range = &KiRangeInfo.Ranges[Index];
  874. //
  875. // Determine rounding for this range type
  876. //
  877. RoundDown = TRUE;
  878. if (Range->Type == MTRR_TYPE_UC) {
  879. RoundDown = FALSE;
  880. }
  881. //
  882. // Apply rounding
  883. //
  884. if (RoundDown) {
  885. Range->Base = (Range->Base + MTRR_PAGE_SIZE - 1) & MTRR_PAGE_MASK;
  886. Range->Limit = ((Range->Limit+1) & MTRR_PAGE_MASK)-1;
  887. } else {
  888. Range->Base = (Range->Base & MTRR_PAGE_MASK);
  889. Range->Limit = ((Range->Limit + MTRR_PAGE_SIZE) & MTRR_PAGE_MASK)-1;
  890. }
  891. }
  892. do {
  893. Restart = FALSE;
  894. //
  895. // Sort the ranges by base address
  896. //
  897. for (Index=0; Index < KiRangeInfo.NoRange; Index++) {
  898. Range = &KiRangeInfo.Ranges[Index];
  899. for (Index2=Index+1; Index2 < KiRangeInfo.NoRange; Index2++) {
  900. if (KiRangeInfo.Ranges[Index2].Base < Range->Base) {
  901. //
  902. // Swap KiRangeInfo.Ranges[Index] with KiRangeInfo.Ranges[Index2]
  903. //
  904. OneRange = *Range;
  905. *Range = KiRangeInfo.Ranges[Index2];
  906. KiRangeInfo.Ranges[Index2] = OneRange;
  907. }
  908. }
  909. }
  910. //
  911. // At this point the range database is sorted on
  912. // base address. Scan range database combining adjacent and
  913. // overlapping ranges of the same type
  914. //
  915. for (Index=0; Index < (ULONG) KiRangeInfo.NoRange-1; Index++) {
  916. Range = &KiRangeInfo.Ranges[Index];
  917. //
  918. // Scan the range database. If ranges are adjacent/overlap and are of
  919. // the same type, combine them.
  920. //
  921. for (Index2 = Index+1; Index2 < (ULONG) KiRangeInfo.NoRange; Index2++) {
  922. l = Range[0].Limit + 1;
  923. if (l < Range[0].Limit) {
  924. l = Range[0].Limit;
  925. }
  926. if (l >= KiRangeInfo.Ranges[Index2].Base &&
  927. Range[0].Type == KiRangeInfo.Ranges[Index2].Type) {
  928. //
  929. // Increase Range[0] limit to cover Range[Index2]
  930. //
  931. if (KiRangeInfo.Ranges[Index2].Limit > Range[0].Limit) {
  932. Range[0].Limit = KiRangeInfo.Ranges[Index2].Limit;
  933. }
  934. //
  935. // Remove KiRangeInfo.Ranges[Index2]
  936. //
  937. if (Index2 < (ULONG) KiRangeInfo.NoRange - 1 ) {
  938. //
  939. // Copy everything from Index2 till end
  940. // of range list. # Entries to copy is
  941. // (KiRangeInfo.NoRange -1) - (Index2+1) + 1
  942. //
  943. RtlCopyMemory(
  944. &(KiRangeInfo.Ranges[Index2]),
  945. &(KiRangeInfo.Ranges[Index2+1]),
  946. sizeof(ONE_RANGE) * (KiRangeInfo.NoRange-Index2-1)
  947. );
  948. }
  949. KiRangeInfo.NoRange -= 1;
  950. //
  951. // Recheck current location
  952. //
  953. Index2 -= 1;
  954. }
  955. }
  956. }
  957. //
  958. // At this point the range database is sorted on base
  959. // address and adjacent/overlapping ranges of the same
  960. // type are combined. Check for overlapping ranges -
  961. // If legal then allow else truncate the less "weighty" range
  962. //
  963. for (Index = 0; Index < (ULONG) KiRangeInfo.NoRange-1 && !Restart; Index++) {
  964. Range = &KiRangeInfo.Ranges[Index];
  965. l = Range[0].Limit + 1;
  966. if (l < Range[0].Limit) {
  967. l = Range[0].Limit;
  968. }
  969. //
  970. // If ranges overlap and are not of same type, and if the
  971. // overlap is not legal then carve them to the best cache type
  972. // available.
  973. //
  974. for (Index2 = Index+1; Index2 < (ULONG) KiRangeInfo.NoRange && !Restart; Index2++) {
  975. if (l > KiRangeInfo.Ranges[Index2].Base) {
  976. if (Range[0].Type == MTRR_TYPE_UC ||
  977. KiRangeInfo.Ranges[Index2].Type == MTRR_TYPE_UC) {
  978. //
  979. // Overlap of a UC type with a range of any other type is
  980. // legal
  981. //
  982. } else if ((Range[0].Type == MTRR_TYPE_WT &&
  983. KiRangeInfo.Ranges[Index2].Type == MTRR_TYPE_WB) ||
  984. (Range[0].Type == MTRR_TYPE_WB &&
  985. KiRangeInfo.Ranges[Index2].Type == MTRR_TYPE_WT) ) {
  986. //
  987. // Overlap of WT and WB range is legal. The overlap range will
  988. // be WT.
  989. //
  990. } else {
  991. //
  992. // This is an illegal overlap and we need to carve the ranges
  993. // to remove the overlap.
  994. //
  995. // Pick range which has the cache type which should be used for
  996. // the overlapped area
  997. //
  998. if (KiRangeWeight(&Range[0]) > KiRangeWeight(&(KiRangeInfo.Ranges[Index2]))){
  999. RemIndex2 = Index2;
  1000. } else {
  1001. RemIndex2 = Index;
  1002. }
  1003. //
  1004. // Remove ranges of type which do not belong in the overlapped area
  1005. //
  1006. RtlZeroMemory (RemoveThisType, MTRR_TYPE_MAX);
  1007. RemoveThisType[KiRangeInfo.Ranges[RemIndex2].Type] = TRUE;
  1008. //
  1009. // Remove just the overlapped portion of the range.
  1010. //
  1011. Restart = KiRemoveRange (
  1012. NewRange,
  1013. KiRangeInfo.Ranges[Index2].Base,
  1014. (Range[0].Limit < KiRangeInfo.Ranges[Index2].Limit ?
  1015. Range[0].Limit : KiRangeInfo.Ranges[Index2].Limit),
  1016. RemoveThisType
  1017. );
  1018. }
  1019. }
  1020. }
  1021. }
  1022. } while (Restart);
  1023. //
  1024. // The range database is now rounded to fit in the h/w and sorted.
  1025. // Attempt to build MTRR settings which exactly describe the ranges
  1026. //
  1027. MTRR = NewRange->MTRR;
  1028. NoMTRR = 0;
  1029. for (Index=0;NT_SUCCESS(NewRange->Status)&& Index<KiRangeInfo.NoRange;Index++) {
  1030. Range = &KiRangeInfo.Ranges[Index];
  1031. //
  1032. // Build MTRRs to fit this range
  1033. //
  1034. Base = Range->Base;
  1035. Length = Range->Limit - Base + 1;
  1036. while (Length) {
  1037. //
  1038. // Compute MTRR length for current range base & length
  1039. //
  1040. if (Base == 0) {
  1041. MLength = Length;
  1042. } else {
  1043. MLength = (ULONGLONG) 1 << KiFindFirstSetRightBit(Base);
  1044. }
  1045. if (MLength > Length) {
  1046. MLength = Length;
  1047. }
  1048. l = (ULONGLONG) 1 << KiFindFirstSetLeftBit (MLength);
  1049. if (MLength > l) {
  1050. MLength = l;
  1051. }
  1052. //
  1053. // Store it in the next MTRR
  1054. //
  1055. MTRR[NoMTRR].Base.u.QuadPart = Base;
  1056. MTRR[NoMTRR].Base.u.hw.Type = Range->Type;
  1057. MTRR[NoMTRR].Mask.u.QuadPart = KiLengthToMask(MLength);
  1058. MTRR[NoMTRR].Mask.u.hw.Valid = 1;
  1059. NoMTRR += 1;
  1060. //
  1061. // Adjust off amount of data covered by that last MTRR
  1062. //
  1063. Base += MLength;
  1064. Length -= MLength;
  1065. //
  1066. // If there are too many MTRRs, and currently setting a
  1067. // Non-USWC range try to remove a USWC MTRR.
  1068. // (ie, convert some MmWriteCombined to MmNonCached).
  1069. //
  1070. if (NoMTRR > (ULONG) KiRangeInfo.Capabilities.u.hw.VarCnt) {
  1071. if (Range->Type != MTRR_TYPE_USWC) {
  1072. //
  1073. // Find smallest USWC type and drop it
  1074. //
  1075. // This is okay only if the default type is UC.
  1076. // Default type should always be UC unless BIOS changes
  1077. // it. Still ASSERT!
  1078. //
  1079. ASSERT(KiRangeInfo.Default.u.hw.Type == MTRR_TYPE_UC);
  1080. BestLength = (ULONGLONG) 1 << (MTRR_MAX_RANGE_SHIFT + 1);
  1081. for (Index2=0; Index2 < KiRangeInfo.Capabilities.u.hw.VarCnt; Index2++) {
  1082. if (MTRR[Index2].Base.u.hw.Type == MTRR_TYPE_USWC) {
  1083. CurrLength = KiMaskToLength(MTRR[Index2].Mask.u.QuadPart &
  1084. MTRR_MASK_MASK);
  1085. if (CurrLength < BestLength) {
  1086. WhichMtrr = Index2;
  1087. BestLength = CurrLength;
  1088. }
  1089. }
  1090. }
  1091. if (BestLength == ((ULONGLONG) 1 << (MTRR_MAX_RANGE_SHIFT + 1))) {
  1092. //
  1093. // Range was not found which could be dropped. Abort process
  1094. //
  1095. NewRange->Status = STATUS_UNSUCCESSFUL;
  1096. Length = 0;
  1097. } else {
  1098. //
  1099. // Remove WhichMtrr
  1100. //
  1101. NoMTRR -= 1;
  1102. MTRR[WhichMtrr] = MTRR[NoMTRR];
  1103. }
  1104. } else {
  1105. NewRange->Status = STATUS_UNSUCCESSFUL;
  1106. Length =0;
  1107. }
  1108. }
  1109. }
  1110. }
  1111. //
  1112. // Done building new MTRRs
  1113. //
  1114. if (NT_SUCCESS(NewRange->Status)) {
  1115. //
  1116. // Update the MTRRs on all processors
  1117. //
  1118. #if IDBG
  1119. KiDumpMTRR ("Loading the following MTRR:", NewRange->MTRR);
  1120. #endif
  1121. NewRange->Synchronize.TargetCount = 0;
  1122. NewRange->Synchronize.TargetPhase = &Prcb->ReverseStall;
  1123. NewRange->Synchronize.Processor = Prcb->Number;
  1124. //
  1125. // Previously enabled MTRRs with index > NoMTRR
  1126. // which could conflict with existing setting should be disabled
  1127. // This is taken care of by setting NewRange->NoMTRR to total
  1128. // number of variable MTRRs.
  1129. //
  1130. NewRange->NoMTRR = (ULONG) KiRangeInfo.Capabilities.u.hw.VarCnt;
  1131. //
  1132. // Synchronize with other IPI functions which may stall
  1133. //
  1134. KiLockContextSwap(&OldIrql);
  1135. #if !defined(NT_UP)
  1136. //
  1137. // Collect all the (other) processors
  1138. //
  1139. TargetProcessors = KeActiveProcessors & ~Prcb->SetMember;
  1140. if (TargetProcessors != 0) {
  1141. KiIpiSendSynchronousPacket (
  1142. Prcb,
  1143. TargetProcessors,
  1144. KiLoadMTRRTarget,
  1145. (PVOID) NewRange,
  1146. NULL,
  1147. NULL
  1148. );
  1149. //
  1150. // Wait for all processors to be collected
  1151. //
  1152. KiIpiStallOnPacketTargets(TargetProcessors);
  1153. //
  1154. // All processors are now waiting. Raise to high level to
  1155. // ensure this processor doesn't enter the debugger due to
  1156. // some interrupt service routine.
  1157. //
  1158. KeRaiseIrql (HIGH_LEVEL, &OldIrql2);
  1159. //
  1160. // There's no reason for any debug events now, so signal
  1161. // the other processors that they can all disable interrupts
  1162. // and begin the MTRR update
  1163. //
  1164. Prcb->ReverseStall += 1;
  1165. }
  1166. #endif
  1167. //
  1168. // Update MTRRs
  1169. //
  1170. KiLoadMTRR (NewRange);
  1171. //
  1172. // Release ContextSwap lock
  1173. //
  1174. KiUnlockContextSwap(OldIrql);
  1175. #if IDBG
  1176. KiDumpMTRR ("Processor MTRR:", NewRange->MTRR);
  1177. #endif
  1178. } else {
  1179. //
  1180. // There was an error, put original range database back
  1181. //
  1182. DBGMSG ("KiCompleteEffectiveRangeChange: mtrr update did not occur\n");
  1183. if (NewRange->Ranges) {
  1184. KiRangeInfo.NoRange = NewRange->NoRange;
  1185. RtlCopyMemory (
  1186. KiRangeInfo.Ranges,
  1187. NewRange->Ranges,
  1188. sizeof (ONE_RANGE) * KiRangeInfo.NoRange
  1189. );
  1190. }
  1191. }
  1192. //
  1193. // Cleanup
  1194. //
  1195. ExFreePool (NewRange->Ranges);
  1196. ExFreePool (NewRange->MTRR);
  1197. }
  1198. STATIC ULONG
  1199. KiRangeWeight (
  1200. IN PONE_RANGE Range
  1201. )
  1202. /*++
  1203. Routine Description:
  1204. This functions returns a weighting of the passed in range's cache
  1205. type. When two or more regions collide within the same h/w region
  1206. the types are weighted and that cache type of the higher weight
  1207. is used for the collision area.
  1208. Arguments:
  1209. Range - Range to obtain weighting for
  1210. Return Value:
  1211. The weight of the particular cache type
  1212. --*/
  1213. {
  1214. ULONG Weight;
  1215. switch (Range->Type) {
  1216. case MTRR_TYPE_UC: Weight = 5; break;
  1217. case MTRR_TYPE_USWC: Weight = 4; break;
  1218. case MTRR_TYPE_WP: Weight = 3; break;
  1219. case MTRR_TYPE_WT: Weight = 2; break;
  1220. case MTRR_TYPE_WB: Weight = 1; break;
  1221. default: Weight = 0; break;
  1222. }
  1223. return Weight;
  1224. }
  1225. STATIC ULONGLONG
  1226. KiMaskToLength (
  1227. IN ULONGLONG Mask
  1228. )
  1229. /*++
  1230. Routine Description:
  1231. This function returns the length specified by a particular
  1232. mtrr variable register mask.
  1233. --*/
  1234. {
  1235. if (Mask == 0) {
  1236. // Zero Mask signifies a length of 2**36
  1237. return(((ULONGLONG) 1 << MTRR_MAX_RANGE_SHIFT));
  1238. } else {
  1239. return(((ULONGLONG) 1 << KiFindFirstSetRightBit(Mask)));
  1240. }
  1241. }
  1242. STATIC ULONGLONG
  1243. KiLengthToMask (
  1244. IN ULONGLONG Length
  1245. )
  1246. /*++
  1247. Routine Description:
  1248. This function constructs the mask corresponding to the input length
  1249. to be set in a variable MTRR register. The length is assumed to be
  1250. a multiple of 4K.
  1251. --*/
  1252. {
  1253. ULONGLONG FullMask = 0xffffff;
  1254. if (Length == ((ULONGLONG) 1 << MTRR_MAX_RANGE_SHIFT)) {
  1255. return(0);
  1256. } else {
  1257. return(((FullMask << KiFindFirstSetRightBit(Length)) &
  1258. MTRR_RESVBIT_MASK));
  1259. }
  1260. }
  1261. STATIC ULONG
  1262. KiFindFirstSetRightBit (
  1263. IN ULONGLONG Set
  1264. )
  1265. /*++
  1266. Routine Description:
  1267. This function returns a bit position of the least significant
  1268. bit set in the passed ULONGLONG parameter. Passed parameter
  1269. must be non-zero.
  1270. --*/
  1271. {
  1272. ULONG bitno;
  1273. ASSERT(Set != 0);
  1274. for (bitno=0; !(Set & 0xFF); bitno += 8, Set >>= 8) ;
  1275. return KiFindFirstSetRight[Set & 0xFF] + bitno;
  1276. }
  1277. STATIC ULONG
  1278. KiFindFirstSetLeftBit (
  1279. IN ULONGLONG Set
  1280. )
  1281. /*++
  1282. Routine Description:
  1283. This function returns a bit position of the most significant
  1284. bit set in the passed ULONGLONG parameter. Passed parameter
  1285. must be non-zero.
  1286. --*/
  1287. {
  1288. ULONG bitno;
  1289. ASSERT(Set != 0);
  1290. for (bitno=56;!(Set & 0xFF00000000000000); bitno -= 8, Set <<= 8) ;
  1291. return KiFindFirstSetLeft[Set >> 56] + bitno;
  1292. }
  1293. #if IDBG
  1294. VOID
  1295. KiDumpMTRR (
  1296. PUCHAR DebugString,
  1297. PMTRR_RANGE MTRR
  1298. )
  1299. /*++
  1300. Routine Description:
  1301. This function dumps the MTRR information to the debugger
  1302. --*/
  1303. {
  1304. static PUCHAR Type[] = {
  1305. // 0 1 2 3 4 5 6
  1306. "UC ", "USWC", "????", "????", "WT ", "WP ", "WB " };
  1307. MTRR_VARIABLE_BASE Base;
  1308. MTRR_VARIABLE_MASK Mask;
  1309. ULONG Index;
  1310. ULONG i;
  1311. PUCHAR p;
  1312. DbgPrint ("%s\n", DebugString);
  1313. for (Index=0; Index < (ULONG) KiRangeInfo.Capabilities.u.hw.VarCnt; Index++) {
  1314. if (MTRR) {
  1315. Base = MTRR[Index].Base;
  1316. Mask = MTRR[Index].Mask;
  1317. } else {
  1318. Base.u.QuadPart = RDMSR(MTRR_MSR_VARIABLE_BASE+2*Index);
  1319. Mask.u.QuadPart = RDMSR(MTRR_MSR_VARIABLE_MASK+2*Index);
  1320. }
  1321. DbgPrint (" %d. ", Index);
  1322. if (Mask.u.hw.Valid) {
  1323. p = "????";
  1324. if (Base.u.hw.Type < 7) {
  1325. p = Type[Base.u.hw.Type];
  1326. }
  1327. DbgPrint ("%s %08x:%08x %08x:%08x",
  1328. p,
  1329. (ULONG) (Base.u.QuadPart >> 32),
  1330. ((ULONG) (Base.u.QuadPart & MTRR_MASK_BASE)),
  1331. (ULONG) (Mask.u.QuadPart >> 32),
  1332. ((ULONG) (Mask.u.QuadPart & MTRR_MASK_MASK))
  1333. );
  1334. }
  1335. DbgPrint ("\n");
  1336. }
  1337. }
  1338. #endif
  1339. VOID
  1340. KiLoadMTRRTarget (
  1341. IN PKIPI_CONTEXT SignalDone,
  1342. IN PVOID NewRange,
  1343. IN PVOID Parameter2,
  1344. IN PVOID Parameter3
  1345. )
  1346. {
  1347. PNEW_RANGE Context;
  1348. Context = (PNEW_RANGE) NewRange;
  1349. //
  1350. // Wait for all processors to be ready
  1351. //
  1352. KiIpiSignalPacketDoneAndStall(SignalDone,
  1353. Context->Synchronize.TargetPhase);
  1354. //
  1355. // Update MTRRs
  1356. //
  1357. KiLoadMTRR (Context);
  1358. }
  1359. #define MOV_EAX_CR4 _emit { 0Fh, 20h, E0h }
  1360. #define MOV_CR4_EAX _emit { 0Fh, 22h, E0h }
  1361. NTSTATUS
  1362. KiLoadMTRR (
  1363. IN PNEW_RANGE Context
  1364. )
  1365. /*++
  1366. Routine Description:
  1367. This function loads the memory type range registers into all processors
  1368. Arguments:
  1369. Context - Context which include the MTRRs to load
  1370. Return Value:
  1371. All processors are set into the new state
  1372. --*/
  1373. {
  1374. MTRR_DEFAULT Default;
  1375. BOOLEAN Enable;
  1376. ULONG HldCr0, HldCr4;
  1377. ULONG Index;
  1378. //
  1379. // Disable interrupts
  1380. //
  1381. Enable = KeDisableInterrupts();
  1382. //
  1383. // Synchronize all processors
  1384. //
  1385. if (!(KeFeatureBits & KF_AMDK6MTRR)) {
  1386. KiLockStepExecution (&Context->Synchronize);
  1387. }
  1388. _asm {
  1389. ;
  1390. ; Get current CR0
  1391. ;
  1392. mov eax, cr0
  1393. mov HldCr0, eax
  1394. ;
  1395. ; Disable caching & line fill
  1396. ;
  1397. and eax, not CR0_NW
  1398. or eax, CR0_CD
  1399. mov cr0, eax
  1400. ;
  1401. ; Flush caches
  1402. ;
  1403. ;
  1404. ; wbinvd
  1405. ;
  1406. _emit 0Fh
  1407. _emit 09h
  1408. ;
  1409. ; Get current cr4
  1410. ;
  1411. _emit 0Fh
  1412. _emit 20h
  1413. _emit 0E0h ; mov eax, cr4
  1414. mov HldCr4, eax
  1415. ;
  1416. ; Disable global page
  1417. ;
  1418. and eax, not CR4_PGE
  1419. _emit 0Fh
  1420. _emit 22h
  1421. _emit 0E0h ; mov cr4, eax
  1422. ;
  1423. ; Flush TLB
  1424. ;
  1425. mov eax, cr3
  1426. mov cr3, eax
  1427. }
  1428. if (KeFeatureBits & KF_AMDK6MTRR) {
  1429. //
  1430. // Write the MTRRs
  1431. //
  1432. KiAmdK6MtrrWRMSR();
  1433. } else {
  1434. //
  1435. // Disable MTRRs
  1436. //
  1437. Default.u.QuadPart = RDMSR(MTRR_MSR_DEFAULT);
  1438. Default.u.hw.MtrrEnabled = 0;
  1439. WRMSR (MTRR_MSR_DEFAULT, Default.u.QuadPart);
  1440. //
  1441. // Load new MTRRs
  1442. //
  1443. for (Index=0; Index < Context->NoMTRR; Index++) {
  1444. WRMSR (MTRR_MSR_VARIABLE_BASE+2*Index, Context->MTRR[Index].Base.u.QuadPart);
  1445. WRMSR (MTRR_MSR_VARIABLE_MASK+2*Index, Context->MTRR[Index].Mask.u.QuadPart);
  1446. }
  1447. }
  1448. _asm {
  1449. ;
  1450. ; Flush caches (this should be a "nop", but it was in the Intel reference algorithm)
  1451. ; This is required because of aggressive prefetch of both instr + data
  1452. ;
  1453. ;
  1454. ; wbinvd
  1455. ;
  1456. _emit 0Fh
  1457. _emit 09h
  1458. ;
  1459. ; Flush TLBs (same comment as above)
  1460. ; Same explanation as above
  1461. ;
  1462. mov eax, cr3
  1463. mov cr3, eax
  1464. }
  1465. if (!(KeFeatureBits & KF_AMDK6MTRR)) {
  1466. //
  1467. // Enable MTRRs
  1468. //
  1469. Default.u.hw.MtrrEnabled = 1;
  1470. WRMSR (MTRR_MSR_DEFAULT, Default.u.QuadPart);
  1471. }
  1472. _asm {
  1473. ;
  1474. ; Restore CR4 (global page enable)
  1475. ;
  1476. mov eax, HldCr4
  1477. _emit 0Fh
  1478. _emit 22h
  1479. _emit 0E0h ; mov cr4, eax
  1480. ;
  1481. ; Restore CR0 (cache enable)
  1482. ;
  1483. mov eax, HldCr0
  1484. mov cr0, eax
  1485. }
  1486. //
  1487. // Wait for all processors to reach the same place,
  1488. // restore interrupts and return.
  1489. //
  1490. if (!(KeFeatureBits & KF_AMDK6MTRR)) {
  1491. KiLockStepExecution (&Context->Synchronize);
  1492. }
  1493. KeEnableInterrupts (Enable);
  1494. return STATUS_SUCCESS;
  1495. }
  1496. VOID
  1497. KiLockStepExecution (
  1498. IN PPROCESSOR_LOCKSTEP Context
  1499. )
  1500. {
  1501. #if !defined(NT_UP)
  1502. ULONG CurrentPhase;
  1503. volatile ULONG *TargetPhase;
  1504. PKPRCB Prcb;
  1505. TargetPhase = Context->TargetPhase;
  1506. Prcb = KeGetCurrentPrcb();
  1507. if (Prcb->Number == (CCHAR) Context->Processor) {
  1508. //
  1509. // Wait for all processors to signal
  1510. //
  1511. while (Context->TargetCount != (ULONG) KeNumberProcessors - 1) {
  1512. KeYieldProcessor ();
  1513. }
  1514. //
  1515. // Reset count for next time
  1516. //
  1517. Context->TargetCount = 0;
  1518. //
  1519. // Let waiting processor go to next synchronization point
  1520. //
  1521. InterlockedIncrement ((PULONG) TargetPhase);
  1522. } else {
  1523. //
  1524. // Get current phase
  1525. //
  1526. CurrentPhase = *TargetPhase;
  1527. //
  1528. // Signal that we have completed the current phase
  1529. //
  1530. InterlockedIncrement ((PULONG) &Context->TargetCount);
  1531. //
  1532. // Wait for new phase to begin
  1533. //
  1534. while (*TargetPhase == CurrentPhase) {
  1535. KeYieldProcessor ();
  1536. }
  1537. }
  1538. #endif
  1539. }