]> git.proxmox.com Git - mirror_edk2.git/blob - UefiCpuPkg/CpuDxe/CpuDxe.c
76661cbcd9bdc5be82fadccec5c00af126036bd9
[mirror_edk2.git] / UefiCpuPkg / CpuDxe / CpuDxe.c
1 /** @file
2 CPU DXE Module to produce CPU ARCH Protocol.
3
4 Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include "CpuDxe.h"
16 #include "CpuMp.h"
17 #include "CpuPageTable.h"
18
19 #define CACHE_ATTRIBUTE_MASK (EFI_MEMORY_UC | EFI_MEMORY_WC | EFI_MEMORY_WT | EFI_MEMORY_WB | EFI_MEMORY_UCE | EFI_MEMORY_WP)
20 #define MEMORY_ATTRIBUTE_MASK (EFI_MEMORY_RP | EFI_MEMORY_XP | EFI_MEMORY_RO)
21
22 //
23 // Global Variables
24 //
25 BOOLEAN InterruptState = FALSE;
26 EFI_HANDLE mCpuHandle = NULL;
27 BOOLEAN mIsFlushingGCD;
28 BOOLEAN mIsAllocatingPageTable = FALSE;
29 UINT64 mValidMtrrAddressMask;
30 UINT64 mValidMtrrBitsMask;
31 UINT64 mTimerPeriod = 0;
32
33 FIXED_MTRR mFixedMtrrTable[] = {
34 {
35 MSR_IA32_MTRR_FIX64K_00000,
36 0,
37 0x10000
38 },
39 {
40 MSR_IA32_MTRR_FIX16K_80000,
41 0x80000,
42 0x4000
43 },
44 {
45 MSR_IA32_MTRR_FIX16K_A0000,
46 0xA0000,
47 0x4000
48 },
49 {
50 MSR_IA32_MTRR_FIX4K_C0000,
51 0xC0000,
52 0x1000
53 },
54 {
55 MSR_IA32_MTRR_FIX4K_C8000,
56 0xC8000,
57 0x1000
58 },
59 {
60 MSR_IA32_MTRR_FIX4K_D0000,
61 0xD0000,
62 0x1000
63 },
64 {
65 MSR_IA32_MTRR_FIX4K_D8000,
66 0xD8000,
67 0x1000
68 },
69 {
70 MSR_IA32_MTRR_FIX4K_E0000,
71 0xE0000,
72 0x1000
73 },
74 {
75 MSR_IA32_MTRR_FIX4K_E8000,
76 0xE8000,
77 0x1000
78 },
79 {
80 MSR_IA32_MTRR_FIX4K_F0000,
81 0xF0000,
82 0x1000
83 },
84 {
85 MSR_IA32_MTRR_FIX4K_F8000,
86 0xF8000,
87 0x1000
88 },
89 };
90
91
92 EFI_CPU_ARCH_PROTOCOL gCpu = {
93 CpuFlushCpuDataCache,
94 CpuEnableInterrupt,
95 CpuDisableInterrupt,
96 CpuGetInterruptState,
97 CpuInit,
98 CpuRegisterInterruptHandler,
99 CpuGetTimerValue,
100 CpuSetMemoryAttributes,
101 1, // NumberOfTimers
102 4 // DmaBufferAlignment
103 };
104
105 //
106 // CPU Arch Protocol Functions
107 //
108
109 /**
110 Flush CPU data cache. If the instruction cache is fully coherent
111 with all DMA operations then function can just return EFI_SUCCESS.
112
113 @param This Protocol instance structure
114 @param Start Physical address to start flushing from.
115 @param Length Number of bytes to flush. Round up to chipset
116 granularity.
117 @param FlushType Specifies the type of flush operation to perform.
118
119 @retval EFI_SUCCESS If cache was flushed
120 @retval EFI_UNSUPPORTED If flush type is not supported.
121 @retval EFI_DEVICE_ERROR If requested range could not be flushed.
122
123 **/
124 EFI_STATUS
125 EFIAPI
126 CpuFlushCpuDataCache (
127 IN EFI_CPU_ARCH_PROTOCOL *This,
128 IN EFI_PHYSICAL_ADDRESS Start,
129 IN UINT64 Length,
130 IN EFI_CPU_FLUSH_TYPE FlushType
131 )
132 {
133 if (FlushType == EfiCpuFlushTypeWriteBackInvalidate) {
134 AsmWbinvd ();
135 return EFI_SUCCESS;
136 } else if (FlushType == EfiCpuFlushTypeInvalidate) {
137 AsmInvd ();
138 return EFI_SUCCESS;
139 } else {
140 return EFI_UNSUPPORTED;
141 }
142 }
143
144
145 /**
146 Enables CPU interrupts.
147
148 @param This Protocol instance structure
149
150 @retval EFI_SUCCESS If interrupts were enabled in the CPU
151 @retval EFI_DEVICE_ERROR If interrupts could not be enabled on the CPU.
152
153 **/
154 EFI_STATUS
155 EFIAPI
156 CpuEnableInterrupt (
157 IN EFI_CPU_ARCH_PROTOCOL *This
158 )
159 {
160 EnableInterrupts ();
161
162 InterruptState = TRUE;
163 return EFI_SUCCESS;
164 }
165
166
167 /**
168 Disables CPU interrupts.
169
170 @param This Protocol instance structure
171
172 @retval EFI_SUCCESS If interrupts were disabled in the CPU.
173 @retval EFI_DEVICE_ERROR If interrupts could not be disabled on the CPU.
174
175 **/
176 EFI_STATUS
177 EFIAPI
178 CpuDisableInterrupt (
179 IN EFI_CPU_ARCH_PROTOCOL *This
180 )
181 {
182 DisableInterrupts ();
183
184 InterruptState = FALSE;
185 return EFI_SUCCESS;
186 }
187
188
189 /**
190 Return the state of interrupts.
191
192 @param This Protocol instance structure
193 @param State Pointer to the CPU's current interrupt state
194
195 @retval EFI_SUCCESS If interrupts were disabled in the CPU.
196 @retval EFI_INVALID_PARAMETER State is NULL.
197
198 **/
199 EFI_STATUS
200 EFIAPI
201 CpuGetInterruptState (
202 IN EFI_CPU_ARCH_PROTOCOL *This,
203 OUT BOOLEAN *State
204 )
205 {
206 if (State == NULL) {
207 return EFI_INVALID_PARAMETER;
208 }
209
210 *State = InterruptState;
211 return EFI_SUCCESS;
212 }
213
214
215 /**
216 Generates an INIT to the CPU.
217
218 @param This Protocol instance structure
219 @param InitType Type of CPU INIT to perform
220
221 @retval EFI_SUCCESS If CPU INIT occurred. This value should never be
222 seen.
223 @retval EFI_DEVICE_ERROR If CPU INIT failed.
224 @retval EFI_UNSUPPORTED Requested type of CPU INIT not supported.
225
226 **/
227 EFI_STATUS
228 EFIAPI
229 CpuInit (
230 IN EFI_CPU_ARCH_PROTOCOL *This,
231 IN EFI_CPU_INIT_TYPE InitType
232 )
233 {
234 return EFI_UNSUPPORTED;
235 }
236
237
238 /**
239 Registers a function to be called from the CPU interrupt handler.
240
241 @param This Protocol instance structure
242 @param InterruptType Defines which interrupt to hook. IA-32
243 valid range is 0x00 through 0xFF
244 @param InterruptHandler A pointer to a function of type
245 EFI_CPU_INTERRUPT_HANDLER that is called
246 when a processor interrupt occurs. A null
247 pointer is an error condition.
248
249 @retval EFI_SUCCESS If handler installed or uninstalled.
250 @retval EFI_ALREADY_STARTED InterruptHandler is not NULL, and a handler
251 for InterruptType was previously installed.
252 @retval EFI_INVALID_PARAMETER InterruptHandler is NULL, and a handler for
253 InterruptType was not previously installed.
254 @retval EFI_UNSUPPORTED The interrupt specified by InterruptType
255 is not supported.
256
257 **/
258 EFI_STATUS
259 EFIAPI
260 CpuRegisterInterruptHandler (
261 IN EFI_CPU_ARCH_PROTOCOL *This,
262 IN EFI_EXCEPTION_TYPE InterruptType,
263 IN EFI_CPU_INTERRUPT_HANDLER InterruptHandler
264 )
265 {
266 return RegisterCpuInterruptHandler (InterruptType, InterruptHandler);
267 }
268
269
270 /**
271 Returns a timer value from one of the CPU's internal timers. There is no
272 inherent time interval between ticks but is a function of the CPU frequency.
273
274 @param This - Protocol instance structure.
275 @param TimerIndex - Specifies which CPU timer is requested.
276 @param TimerValue - Pointer to the returned timer value.
277 @param TimerPeriod - A pointer to the amount of time that passes
278 in femtoseconds (10-15) for each increment
279 of TimerValue. If TimerValue does not
280 increment at a predictable rate, then 0 is
281 returned. The amount of time that has
282 passed between two calls to GetTimerValue()
283 can be calculated with the formula
284 (TimerValue2 - TimerValue1) * TimerPeriod.
285 This parameter is optional and may be NULL.
286
287 @retval EFI_SUCCESS - If the CPU timer count was returned.
288 @retval EFI_UNSUPPORTED - If the CPU does not have any readable timers.
289 @retval EFI_DEVICE_ERROR - If an error occurred while reading the timer.
290 @retval EFI_INVALID_PARAMETER - TimerIndex is not valid or TimerValue is NULL.
291
292 **/
293 EFI_STATUS
294 EFIAPI
295 CpuGetTimerValue (
296 IN EFI_CPU_ARCH_PROTOCOL *This,
297 IN UINT32 TimerIndex,
298 OUT UINT64 *TimerValue,
299 OUT UINT64 *TimerPeriod OPTIONAL
300 )
301 {
302 UINT64 BeginValue;
303 UINT64 EndValue;
304
305 if (TimerValue == NULL) {
306 return EFI_INVALID_PARAMETER;
307 }
308
309 if (TimerIndex != 0) {
310 return EFI_INVALID_PARAMETER;
311 }
312
313 *TimerValue = AsmReadTsc ();
314
315 if (TimerPeriod != NULL) {
316 if (mTimerPeriod == 0) {
317 //
318 // Read time stamp counter before and after delay of 100 microseconds
319 //
320 BeginValue = AsmReadTsc ();
321 MicroSecondDelay (100);
322 EndValue = AsmReadTsc ();
323 //
324 // Calculate the actual frequency
325 //
326 mTimerPeriod = DivU64x64Remainder (
327 MultU64x32 (
328 1000 * 1000 * 1000,
329 100
330 ),
331 EndValue - BeginValue,
332 NULL
333 );
334 }
335 *TimerPeriod = mTimerPeriod;
336 }
337
338 return EFI_SUCCESS;
339 }
340
341 /**
342 A minimal wrapper function that allows MtrrSetAllMtrrs() to be passed to
343 EFI_MP_SERVICES_PROTOCOL.StartupAllAPs() as Procedure.
344
345 @param[in] Buffer Pointer to an MTRR_SETTINGS object, to be passed to
346 MtrrSetAllMtrrs().
347 **/
348 VOID
349 EFIAPI
350 SetMtrrsFromBuffer (
351 IN VOID *Buffer
352 )
353 {
354 MtrrSetAllMtrrs (Buffer);
355 }
356
357 /**
358 Implementation of SetMemoryAttributes() service of CPU Architecture Protocol.
359
360 This function modifies the attributes for the memory region specified by BaseAddress and
361 Length from their current attributes to the attributes specified by Attributes.
362
363 @param This The EFI_CPU_ARCH_PROTOCOL instance.
364 @param BaseAddress The physical address that is the start address of a memory region.
365 @param Length The size in bytes of the memory region.
366 @param Attributes The bit mask of attributes to set for the memory region.
367
368 @retval EFI_SUCCESS The attributes were set for the memory region.
369 @retval EFI_ACCESS_DENIED The attributes for the memory resource range specified by
370 BaseAddress and Length cannot be modified.
371 @retval EFI_INVALID_PARAMETER Length is zero.
372 Attributes specified an illegal combination of attributes that
373 cannot be set together.
374 @retval EFI_OUT_OF_RESOURCES There are not enough system resources to modify the attributes of
375 the memory resource range.
376 @retval EFI_UNSUPPORTED The processor does not support one or more bytes of the memory
377 resource range specified by BaseAddress and Length.
378 The bit mask of attributes is not support for the memory resource
379 range specified by BaseAddress and Length.
380
381 **/
382 EFI_STATUS
383 EFIAPI
384 CpuSetMemoryAttributes (
385 IN EFI_CPU_ARCH_PROTOCOL *This,
386 IN EFI_PHYSICAL_ADDRESS BaseAddress,
387 IN UINT64 Length,
388 IN UINT64 Attributes
389 )
390 {
391 RETURN_STATUS Status;
392 MTRR_MEMORY_CACHE_TYPE CacheType;
393 EFI_STATUS MpStatus;
394 EFI_MP_SERVICES_PROTOCOL *MpService;
395 MTRR_SETTINGS MtrrSettings;
396 UINT64 CacheAttributes;
397 UINT64 MemoryAttributes;
398 MTRR_MEMORY_CACHE_TYPE CurrentCacheType;
399
400 //
401 // If this function is called because GCD SetMemorySpaceAttributes () is called
402 // by RefreshGcdMemoryAttributes (), then we are just synchronzing GCD memory
403 // map with MTRR values. So there is no need to modify MTRRs, just return immediately
404 // to avoid unnecessary computing.
405 //
406 if (mIsFlushingGCD) {
407 DEBUG((DEBUG_VERBOSE, " Flushing GCD\n"));
408 return EFI_SUCCESS;
409 }
410
411 //
412 // During memory attributes updating, new pages may be allocated to setup
413 // smaller granularity of page table. Page allocation action might then cause
414 // another calling of CpuSetMemoryAttributes() recursively, due to memory
415 // protection policy configured (such as PcdDxeNxMemoryProtectionPolicy).
416 // Since this driver will always protect memory used as page table by itself,
417 // there's no need to apply protection policy requested from memory service.
418 // So it's safe to just return EFI_SUCCESS if this time of calling is caused
419 // by page table memory allocation.
420 //
421 if (mIsAllocatingPageTable) {
422 DEBUG((DEBUG_VERBOSE, " Allocating page table memory\n"));
423 return EFI_SUCCESS;
424 }
425
426 CacheAttributes = Attributes & CACHE_ATTRIBUTE_MASK;
427 MemoryAttributes = Attributes & MEMORY_ATTRIBUTE_MASK;
428
429 if (Attributes != (CacheAttributes | MemoryAttributes)) {
430 return EFI_INVALID_PARAMETER;
431 }
432
433 if (CacheAttributes != 0) {
434 if (!IsMtrrSupported ()) {
435 return EFI_UNSUPPORTED;
436 }
437
438 switch (CacheAttributes) {
439 case EFI_MEMORY_UC:
440 CacheType = CacheUncacheable;
441 break;
442
443 case EFI_MEMORY_WC:
444 CacheType = CacheWriteCombining;
445 break;
446
447 case EFI_MEMORY_WT:
448 CacheType = CacheWriteThrough;
449 break;
450
451 case EFI_MEMORY_WP:
452 CacheType = CacheWriteProtected;
453 break;
454
455 case EFI_MEMORY_WB:
456 CacheType = CacheWriteBack;
457 break;
458
459 default:
460 return EFI_INVALID_PARAMETER;
461 }
462 CurrentCacheType = MtrrGetMemoryAttribute(BaseAddress);
463 if (CurrentCacheType != CacheType) {
464 //
465 // call MTRR libary function
466 //
467 Status = MtrrSetMemoryAttribute (
468 BaseAddress,
469 Length,
470 CacheType
471 );
472
473 if (!RETURN_ERROR (Status)) {
474 MpStatus = gBS->LocateProtocol (
475 &gEfiMpServiceProtocolGuid,
476 NULL,
477 (VOID **)&MpService
478 );
479 //
480 // Synchronize the update with all APs
481 //
482 if (!EFI_ERROR (MpStatus)) {
483 MtrrGetAllMtrrs (&MtrrSettings);
484 MpStatus = MpService->StartupAllAPs (
485 MpService, // This
486 SetMtrrsFromBuffer, // Procedure
487 FALSE, // SingleThread
488 NULL, // WaitEvent
489 0, // TimeoutInMicrosecsond
490 &MtrrSettings, // ProcedureArgument
491 NULL // FailedCpuList
492 );
493 ASSERT (MpStatus == EFI_SUCCESS || MpStatus == EFI_NOT_STARTED);
494 }
495 }
496 if (EFI_ERROR(Status)) {
497 return Status;
498 }
499 }
500 }
501
502 //
503 // Set memory attribute by page table
504 //
505 return AssignMemoryPageAttributes (NULL, BaseAddress, Length, MemoryAttributes, NULL);
506 }
507
508 /**
509 Initializes the valid bits mask and valid address mask for MTRRs.
510
511 This function initializes the valid bits mask and valid address mask for MTRRs.
512
513 **/
514 VOID
515 InitializeMtrrMask (
516 VOID
517 )
518 {
519 UINT32 RegEax;
520 UINT8 PhysicalAddressBits;
521
522 AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL);
523
524 if (RegEax >= 0x80000008) {
525 AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL);
526
527 PhysicalAddressBits = (UINT8) RegEax;
528 } else {
529 PhysicalAddressBits = 36;
530 }
531
532 mValidMtrrBitsMask = LShiftU64 (1, PhysicalAddressBits) - 1;
533 mValidMtrrAddressMask = mValidMtrrBitsMask & 0xfffffffffffff000ULL;
534 }
535
536 /**
537 Gets GCD Mem Space type from MTRR Type.
538
539 This function gets GCD Mem Space type from MTRR Type.
540
541 @param MtrrAttributes MTRR memory type
542
543 @return GCD Mem Space type
544
545 **/
546 UINT64
547 GetMemorySpaceAttributeFromMtrrType (
548 IN UINT8 MtrrAttributes
549 )
550 {
551 switch (MtrrAttributes) {
552 case MTRR_CACHE_UNCACHEABLE:
553 return EFI_MEMORY_UC;
554 case MTRR_CACHE_WRITE_COMBINING:
555 return EFI_MEMORY_WC;
556 case MTRR_CACHE_WRITE_THROUGH:
557 return EFI_MEMORY_WT;
558 case MTRR_CACHE_WRITE_PROTECTED:
559 return EFI_MEMORY_WP;
560 case MTRR_CACHE_WRITE_BACK:
561 return EFI_MEMORY_WB;
562 default:
563 return 0;
564 }
565 }
566
567 /**
568 Searches memory descriptors covered by given memory range.
569
570 This function searches into the Gcd Memory Space for descriptors
571 (from StartIndex to EndIndex) that contains the memory range
572 specified by BaseAddress and Length.
573
574 @param MemorySpaceMap Gcd Memory Space Map as array.
575 @param NumberOfDescriptors Number of descriptors in map.
576 @param BaseAddress BaseAddress for the requested range.
577 @param Length Length for the requested range.
578 @param StartIndex Start index into the Gcd Memory Space Map.
579 @param EndIndex End index into the Gcd Memory Space Map.
580
581 @retval EFI_SUCCESS Search successfully.
582 @retval EFI_NOT_FOUND The requested descriptors does not exist.
583
584 **/
585 EFI_STATUS
586 SearchGcdMemorySpaces (
587 IN EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap,
588 IN UINTN NumberOfDescriptors,
589 IN EFI_PHYSICAL_ADDRESS BaseAddress,
590 IN UINT64 Length,
591 OUT UINTN *StartIndex,
592 OUT UINTN *EndIndex
593 )
594 {
595 UINTN Index;
596
597 *StartIndex = 0;
598 *EndIndex = 0;
599 for (Index = 0; Index < NumberOfDescriptors; Index++) {
600 if (BaseAddress >= MemorySpaceMap[Index].BaseAddress &&
601 BaseAddress < MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length) {
602 *StartIndex = Index;
603 }
604 if (BaseAddress + Length - 1 >= MemorySpaceMap[Index].BaseAddress &&
605 BaseAddress + Length - 1 < MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length) {
606 *EndIndex = Index;
607 return EFI_SUCCESS;
608 }
609 }
610 return EFI_NOT_FOUND;
611 }
612
613 /**
614 Sets the attributes for a specified range in Gcd Memory Space Map.
615
616 This function sets the attributes for a specified range in
617 Gcd Memory Space Map.
618
619 @param MemorySpaceMap Gcd Memory Space Map as array
620 @param NumberOfDescriptors Number of descriptors in map
621 @param BaseAddress BaseAddress for the range
622 @param Length Length for the range
623 @param Attributes Attributes to set
624
625 @retval EFI_SUCCESS Memory attributes set successfully
626 @retval EFI_NOT_FOUND The specified range does not exist in Gcd Memory Space
627
628 **/
629 EFI_STATUS
630 SetGcdMemorySpaceAttributes (
631 IN EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap,
632 IN UINTN NumberOfDescriptors,
633 IN EFI_PHYSICAL_ADDRESS BaseAddress,
634 IN UINT64 Length,
635 IN UINT64 Attributes
636 )
637 {
638 EFI_STATUS Status;
639 UINTN Index;
640 UINTN StartIndex;
641 UINTN EndIndex;
642 EFI_PHYSICAL_ADDRESS RegionStart;
643 UINT64 RegionLength;
644
645 //
646 // Get all memory descriptors covered by the memory range
647 //
648 Status = SearchGcdMemorySpaces (
649 MemorySpaceMap,
650 NumberOfDescriptors,
651 BaseAddress,
652 Length,
653 &StartIndex,
654 &EndIndex
655 );
656 if (EFI_ERROR (Status)) {
657 return Status;
658 }
659
660 //
661 // Go through all related descriptors and set attributes accordingly
662 //
663 for (Index = StartIndex; Index <= EndIndex; Index++) {
664 if (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeNonExistent) {
665 continue;
666 }
667 //
668 // Calculate the start and end address of the overlapping range
669 //
670 if (BaseAddress >= MemorySpaceMap[Index].BaseAddress) {
671 RegionStart = BaseAddress;
672 } else {
673 RegionStart = MemorySpaceMap[Index].BaseAddress;
674 }
675 if (BaseAddress + Length - 1 < MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length) {
676 RegionLength = BaseAddress + Length - RegionStart;
677 } else {
678 RegionLength = MemorySpaceMap[Index].BaseAddress + MemorySpaceMap[Index].Length - RegionStart;
679 }
680 //
681 // Set memory attributes according to MTRR attribute and the original attribute of descriptor
682 //
683 gDS->SetMemorySpaceAttributes (
684 RegionStart,
685 RegionLength,
686 (MemorySpaceMap[Index].Attributes & ~EFI_MEMORY_CACHETYPE_MASK) | (MemorySpaceMap[Index].Capabilities & Attributes)
687 );
688 }
689
690 return EFI_SUCCESS;
691 }
692
693
694 /**
695 Refreshes the GCD Memory Space attributes according to MTRRs.
696
697 This function refreshes the GCD Memory Space attributes according to MTRRs.
698
699 **/
700 VOID
701 RefreshMemoryAttributesFromMtrr (
702 VOID
703 )
704 {
705 EFI_STATUS Status;
706 UINTN Index;
707 UINTN SubIndex;
708 UINT64 RegValue;
709 EFI_PHYSICAL_ADDRESS BaseAddress;
710 UINT64 Length;
711 UINT64 Attributes;
712 UINT64 CurrentAttributes;
713 UINT8 MtrrType;
714 UINTN NumberOfDescriptors;
715 EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap;
716 UINT64 DefaultAttributes;
717 VARIABLE_MTRR VariableMtrr[MTRR_NUMBER_OF_VARIABLE_MTRR];
718 MTRR_FIXED_SETTINGS MtrrFixedSettings;
719 UINT32 FirmwareVariableMtrrCount;
720 UINT8 DefaultMemoryType;
721
722 FirmwareVariableMtrrCount = GetFirmwareVariableMtrrCount ();
723 ASSERT (FirmwareVariableMtrrCount <= MTRR_NUMBER_OF_VARIABLE_MTRR);
724
725 MemorySpaceMap = NULL;
726
727 //
728 // Initialize the valid bits mask and valid address mask for MTRRs
729 //
730 InitializeMtrrMask ();
731
732 //
733 // Get the memory attribute of variable MTRRs
734 //
735 MtrrGetMemoryAttributeInVariableMtrr (
736 mValidMtrrBitsMask,
737 mValidMtrrAddressMask,
738 VariableMtrr
739 );
740
741 //
742 // Get the memory space map from GCD
743 //
744 Status = gDS->GetMemorySpaceMap (
745 &NumberOfDescriptors,
746 &MemorySpaceMap
747 );
748 ASSERT_EFI_ERROR (Status);
749
750 DefaultMemoryType = (UINT8) MtrrGetDefaultMemoryType ();
751 DefaultAttributes = GetMemorySpaceAttributeFromMtrrType (DefaultMemoryType);
752
753 //
754 // Set default attributes to all spaces.
755 //
756 for (Index = 0; Index < NumberOfDescriptors; Index++) {
757 if (MemorySpaceMap[Index].GcdMemoryType == EfiGcdMemoryTypeNonExistent) {
758 continue;
759 }
760 gDS->SetMemorySpaceAttributes (
761 MemorySpaceMap[Index].BaseAddress,
762 MemorySpaceMap[Index].Length,
763 (MemorySpaceMap[Index].Attributes & ~EFI_MEMORY_CACHETYPE_MASK) |
764 (MemorySpaceMap[Index].Capabilities & DefaultAttributes)
765 );
766 }
767
768 //
769 // Go for variable MTRRs with WB attribute
770 //
771 for (Index = 0; Index < FirmwareVariableMtrrCount; Index++) {
772 if (VariableMtrr[Index].Valid &&
773 VariableMtrr[Index].Type == MTRR_CACHE_WRITE_BACK) {
774 SetGcdMemorySpaceAttributes (
775 MemorySpaceMap,
776 NumberOfDescriptors,
777 VariableMtrr[Index].BaseAddress,
778 VariableMtrr[Index].Length,
779 EFI_MEMORY_WB
780 );
781 }
782 }
783
784 //
785 // Go for variable MTRRs with the attribute except for WB and UC attributes
786 //
787 for (Index = 0; Index < FirmwareVariableMtrrCount; Index++) {
788 if (VariableMtrr[Index].Valid &&
789 VariableMtrr[Index].Type != MTRR_CACHE_WRITE_BACK &&
790 VariableMtrr[Index].Type != MTRR_CACHE_UNCACHEABLE) {
791 Attributes = GetMemorySpaceAttributeFromMtrrType ((UINT8) VariableMtrr[Index].Type);
792 SetGcdMemorySpaceAttributes (
793 MemorySpaceMap,
794 NumberOfDescriptors,
795 VariableMtrr[Index].BaseAddress,
796 VariableMtrr[Index].Length,
797 Attributes
798 );
799 }
800 }
801
802 //
803 // Go for variable MTRRs with UC attribute
804 //
805 for (Index = 0; Index < FirmwareVariableMtrrCount; Index++) {
806 if (VariableMtrr[Index].Valid &&
807 VariableMtrr[Index].Type == MTRR_CACHE_UNCACHEABLE) {
808 SetGcdMemorySpaceAttributes (
809 MemorySpaceMap,
810 NumberOfDescriptors,
811 VariableMtrr[Index].BaseAddress,
812 VariableMtrr[Index].Length,
813 EFI_MEMORY_UC
814 );
815 }
816 }
817
818 //
819 // Go for fixed MTRRs
820 //
821 Attributes = 0;
822 BaseAddress = 0;
823 Length = 0;
824 MtrrGetFixedMtrr (&MtrrFixedSettings);
825 for (Index = 0; Index < MTRR_NUMBER_OF_FIXED_MTRR; Index++) {
826 RegValue = MtrrFixedSettings.Mtrr[Index];
827 //
828 // Check for continuous fixed MTRR sections
829 //
830 for (SubIndex = 0; SubIndex < 8; SubIndex++) {
831 MtrrType = (UINT8) RShiftU64 (RegValue, SubIndex * 8);
832 CurrentAttributes = GetMemorySpaceAttributeFromMtrrType (MtrrType);
833 if (Length == 0) {
834 //
835 // A new MTRR attribute begins
836 //
837 Attributes = CurrentAttributes;
838 } else {
839 //
840 // If fixed MTRR attribute changed, then set memory attribute for previous atrribute
841 //
842 if (CurrentAttributes != Attributes) {
843 SetGcdMemorySpaceAttributes (
844 MemorySpaceMap,
845 NumberOfDescriptors,
846 BaseAddress,
847 Length,
848 Attributes
849 );
850 BaseAddress = mFixedMtrrTable[Index].BaseAddress + mFixedMtrrTable[Index].Length * SubIndex;
851 Length = 0;
852 Attributes = CurrentAttributes;
853 }
854 }
855 Length += mFixedMtrrTable[Index].Length;
856 }
857 }
858 //
859 // Handle the last fixed MTRR region
860 //
861 SetGcdMemorySpaceAttributes (
862 MemorySpaceMap,
863 NumberOfDescriptors,
864 BaseAddress,
865 Length,
866 Attributes
867 );
868
869 //
870 // Free memory space map allocated by GCD service GetMemorySpaceMap ()
871 //
872 if (MemorySpaceMap != NULL) {
873 FreePool (MemorySpaceMap);
874 }
875 }
876
877 /**
878 Check if paging is enabled or not.
879 **/
880 BOOLEAN
881 IsPagingAndPageAddressExtensionsEnabled (
882 VOID
883 )
884 {
885 IA32_CR0 Cr0;
886 IA32_CR4 Cr4;
887
888 Cr0.UintN = AsmReadCr0 ();
889 Cr4.UintN = AsmReadCr4 ();
890
891 return ((Cr0.Bits.PG != 0) && (Cr4.Bits.PAE != 0));
892 }
893
894 /**
895 Refreshes the GCD Memory Space attributes according to MTRRs and Paging.
896
897 This function refreshes the GCD Memory Space attributes according to MTRRs
898 and page tables.
899
900 **/
901 VOID
902 RefreshGcdMemoryAttributes (
903 VOID
904 )
905 {
906 mIsFlushingGCD = TRUE;
907
908 if (IsMtrrSupported ()) {
909 RefreshMemoryAttributesFromMtrr ();
910 }
911
912 if (IsPagingAndPageAddressExtensionsEnabled ()) {
913 RefreshGcdMemoryAttributesFromPaging ();
914 }
915
916 mIsFlushingGCD = FALSE;
917 }
918
919 /**
920 Initialize Interrupt Descriptor Table for interrupt handling.
921
922 **/
923 VOID
924 InitInterruptDescriptorTable (
925 VOID
926 )
927 {
928 EFI_STATUS Status;
929 EFI_VECTOR_HANDOFF_INFO *VectorInfoList;
930 EFI_VECTOR_HANDOFF_INFO *VectorInfo;
931
932 VectorInfo = NULL;
933 Status = EfiGetSystemConfigurationTable (&gEfiVectorHandoffTableGuid, (VOID **) &VectorInfoList);
934 if (Status == EFI_SUCCESS && VectorInfoList != NULL) {
935 VectorInfo = VectorInfoList;
936 }
937 Status = InitializeCpuInterruptHandlers (VectorInfo);
938 ASSERT_EFI_ERROR (Status);
939 }
940
941
942 /**
943 Callback function for idle events.
944
945 @param Event Event whose notification function is being invoked.
946 @param Context The pointer to the notification function's context,
947 which is implementation-dependent.
948
949 **/
950 VOID
951 EFIAPI
952 IdleLoopEventCallback (
953 IN EFI_EVENT Event,
954 IN VOID *Context
955 )
956 {
957 CpuSleep ();
958 }
959
960 /**
961 Ensure the compatibility of a memory space descriptor with the MMIO aperture.
962
963 The memory space descriptor can come from the GCD memory space map, or it can
964 represent a gap between two neighboring memory space descriptors. In the
965 latter case, the GcdMemoryType field is expected to be
966 EfiGcdMemoryTypeNonExistent.
967
968 If the memory space descriptor already has type
969 EfiGcdMemoryTypeMemoryMappedIo, and its capabilities are a superset of the
970 required capabilities, then no action is taken -- it is by definition
971 compatible with the aperture.
972
973 Otherwise, the intersection of the memory space descriptor is calculated with
974 the aperture. If the intersection is the empty set (no overlap), no action is
975 taken; the memory space descriptor is compatible with the aperture.
976
977 Otherwise, the type of the descriptor is investigated again. If the type is
978 EfiGcdMemoryTypeNonExistent (representing a gap, or a genuine descriptor with
979 such a type), then an attempt is made to add the intersection as MMIO space
980 to the GCD memory space map, with the specified capabilities. This ensures
981 continuity for the aperture, and the descriptor is deemed compatible with the
982 aperture.
983
984 Otherwise, the memory space descriptor is incompatible with the MMIO
985 aperture.
986
987 @param[in] Base Base address of the aperture.
988 @param[in] Length Length of the aperture.
989 @param[in] Capabilities Capabilities required by the aperture.
990 @param[in] Descriptor The descriptor to ensure compatibility with the
991 aperture for.
992
993 @retval EFI_SUCCESS The descriptor is compatible. The GCD memory
994 space map may have been updated, for
995 continuity within the aperture.
996 @retval EFI_INVALID_PARAMETER The descriptor is incompatible.
997 @return Error codes from gDS->AddMemorySpace().
998 **/
999 EFI_STATUS
1000 IntersectMemoryDescriptor (
1001 IN UINT64 Base,
1002 IN UINT64 Length,
1003 IN UINT64 Capabilities,
1004 IN CONST EFI_GCD_MEMORY_SPACE_DESCRIPTOR *Descriptor
1005 )
1006 {
1007 UINT64 IntersectionBase;
1008 UINT64 IntersectionEnd;
1009 EFI_STATUS Status;
1010
1011 if (Descriptor->GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo &&
1012 (Descriptor->Capabilities & Capabilities) == Capabilities) {
1013 return EFI_SUCCESS;
1014 }
1015
1016 IntersectionBase = MAX (Base, Descriptor->BaseAddress);
1017 IntersectionEnd = MIN (Base + Length,
1018 Descriptor->BaseAddress + Descriptor->Length);
1019 if (IntersectionBase >= IntersectionEnd) {
1020 //
1021 // The descriptor and the aperture don't overlap.
1022 //
1023 return EFI_SUCCESS;
1024 }
1025
1026 if (Descriptor->GcdMemoryType == EfiGcdMemoryTypeNonExistent) {
1027 Status = gDS->AddMemorySpace (EfiGcdMemoryTypeMemoryMappedIo,
1028 IntersectionBase, IntersectionEnd - IntersectionBase,
1029 Capabilities);
1030
1031 DEBUG ((EFI_ERROR (Status) ? DEBUG_ERROR : DEBUG_VERBOSE,
1032 "%a: %a: add [%Lx, %Lx): %r\n", gEfiCallerBaseName, __FUNCTION__,
1033 IntersectionBase, IntersectionEnd, Status));
1034 return Status;
1035 }
1036
1037 DEBUG ((DEBUG_ERROR, "%a: %a: desc [%Lx, %Lx) type %u cap %Lx conflicts "
1038 "with aperture [%Lx, %Lx) cap %Lx\n", gEfiCallerBaseName, __FUNCTION__,
1039 Descriptor->BaseAddress, Descriptor->BaseAddress + Descriptor->Length,
1040 (UINT32)Descriptor->GcdMemoryType, Descriptor->Capabilities,
1041 Base, Base + Length, Capabilities));
1042 return EFI_INVALID_PARAMETER;
1043 }
1044
1045 /**
1046 Add MMIO space to GCD.
1047 The routine checks the GCD database and only adds those which are
1048 not added in the specified range to GCD.
1049
1050 @param Base Base address of the MMIO space.
1051 @param Length Length of the MMIO space.
1052 @param Capabilities Capabilities of the MMIO space.
1053
1054 @retval EFI_SUCCES The MMIO space was added successfully.
1055 **/
1056 EFI_STATUS
1057 AddMemoryMappedIoSpace (
1058 IN UINT64 Base,
1059 IN UINT64 Length,
1060 IN UINT64 Capabilities
1061 )
1062 {
1063 EFI_STATUS Status;
1064 UINTN Index;
1065 UINTN NumberOfDescriptors;
1066 EFI_GCD_MEMORY_SPACE_DESCRIPTOR *MemorySpaceMap;
1067
1068 Status = gDS->GetMemorySpaceMap (&NumberOfDescriptors, &MemorySpaceMap);
1069 if (EFI_ERROR (Status)) {
1070 DEBUG ((DEBUG_ERROR, "%a: %a: GetMemorySpaceMap(): %r\n",
1071 gEfiCallerBaseName, __FUNCTION__, Status));
1072 return Status;
1073 }
1074
1075 for (Index = 0; Index < NumberOfDescriptors; Index++) {
1076 Status = IntersectMemoryDescriptor (Base, Length, Capabilities,
1077 &MemorySpaceMap[Index]);
1078 if (EFI_ERROR (Status)) {
1079 goto FreeMemorySpaceMap;
1080 }
1081 }
1082
1083 DEBUG_CODE (
1084 //
1085 // Make sure there are adjacent descriptors covering [Base, Base + Length).
1086 // It is possible that they have not been merged; merging can be prevented
1087 // by allocation and different capabilities.
1088 //
1089 UINT64 CheckBase;
1090 EFI_STATUS CheckStatus;
1091 EFI_GCD_MEMORY_SPACE_DESCRIPTOR Descriptor;
1092
1093 for (CheckBase = Base;
1094 CheckBase < Base + Length;
1095 CheckBase = Descriptor.BaseAddress + Descriptor.Length) {
1096 CheckStatus = gDS->GetMemorySpaceDescriptor (CheckBase, &Descriptor);
1097 ASSERT_EFI_ERROR (CheckStatus);
1098 ASSERT (Descriptor.GcdMemoryType == EfiGcdMemoryTypeMemoryMappedIo);
1099 ASSERT ((Descriptor.Capabilities & Capabilities) == Capabilities);
1100 }
1101 );
1102
1103 FreeMemorySpaceMap:
1104 FreePool (MemorySpaceMap);
1105
1106 return Status;
1107 }
1108
1109 /**
1110 Add and allocate CPU local APIC memory mapped space.
1111
1112 @param[in]ImageHandle Image handle this driver.
1113
1114 **/
1115 VOID
1116 AddLocalApicMemorySpace (
1117 IN EFI_HANDLE ImageHandle
1118 )
1119 {
1120 EFI_STATUS Status;
1121 EFI_PHYSICAL_ADDRESS BaseAddress;
1122
1123 BaseAddress = (EFI_PHYSICAL_ADDRESS) GetLocalApicBaseAddress();
1124 Status = AddMemoryMappedIoSpace (BaseAddress, SIZE_4KB, EFI_MEMORY_UC);
1125 ASSERT_EFI_ERROR (Status);
1126
1127 //
1128 // Try to allocate APIC memory mapped space, does not check return
1129 // status because it may be allocated by other driver, or DXE Core if
1130 // this range is built into Memory Allocation HOB.
1131 //
1132 Status = gDS->AllocateMemorySpace (
1133 EfiGcdAllocateAddress,
1134 EfiGcdMemoryTypeMemoryMappedIo,
1135 0,
1136 SIZE_4KB,
1137 &BaseAddress,
1138 ImageHandle,
1139 NULL
1140 );
1141 if (EFI_ERROR (Status)) {
1142 DEBUG ((DEBUG_INFO, "%a: %a: AllocateMemorySpace() Status - %r\n",
1143 gEfiCallerBaseName, __FUNCTION__, Status));
1144 }
1145 }
1146
1147 /**
1148 Initialize the state information for the CPU Architectural Protocol.
1149
1150 @param ImageHandle Image handle this driver.
1151 @param SystemTable Pointer to the System Table.
1152
1153 @retval EFI_SUCCESS Thread can be successfully created
1154 @retval EFI_OUT_OF_RESOURCES Cannot allocate protocol data structure
1155 @retval EFI_DEVICE_ERROR Cannot create the thread
1156
1157 **/
1158 EFI_STATUS
1159 EFIAPI
1160 InitializeCpu (
1161 IN EFI_HANDLE ImageHandle,
1162 IN EFI_SYSTEM_TABLE *SystemTable
1163 )
1164 {
1165 EFI_STATUS Status;
1166 EFI_EVENT IdleLoopEvent;
1167
1168 InitializePageTableLib();
1169
1170 InitializeFloatingPointUnits ();
1171
1172 //
1173 // Make sure interrupts are disabled
1174 //
1175 DisableInterrupts ();
1176
1177 //
1178 // Init GDT for DXE
1179 //
1180 InitGlobalDescriptorTable ();
1181
1182 //
1183 // Setup IDT pointer, IDT and interrupt entry points
1184 //
1185 InitInterruptDescriptorTable ();
1186
1187 //
1188 // Install CPU Architectural Protocol
1189 //
1190 Status = gBS->InstallMultipleProtocolInterfaces (
1191 &mCpuHandle,
1192 &gEfiCpuArchProtocolGuid, &gCpu,
1193 NULL
1194 );
1195 ASSERT_EFI_ERROR (Status);
1196
1197 //
1198 // Refresh GCD memory space map according to MTRR value.
1199 //
1200 RefreshGcdMemoryAttributes ();
1201
1202 //
1203 // Add and allocate local APIC memory mapped space
1204 //
1205 AddLocalApicMemorySpace (ImageHandle);
1206
1207 //
1208 // Setup a callback for idle events
1209 //
1210 Status = gBS->CreateEventEx (
1211 EVT_NOTIFY_SIGNAL,
1212 TPL_NOTIFY,
1213 IdleLoopEventCallback,
1214 NULL,
1215 &gIdleLoopEventGuid,
1216 &IdleLoopEvent
1217 );
1218 ASSERT_EFI_ERROR (Status);
1219
1220 InitializeMpSupport ();
1221
1222 return Status;
1223 }
1224