2 UEFI Memory page management functions.
4 Copyright (c) 2007 - 2017, 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
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.
19 // Entry for tracking the memory regions for each memory type to coalesce similar memory types
22 EFI_PHYSICAL_ADDRESS BaseAddress
;
23 EFI_PHYSICAL_ADDRESS MaximumAddress
;
24 UINT64 CurrentNumberOfPages
;
26 UINTN InformationIndex
;
29 } EFI_MEMORY_TYPE_STATISTICS
;
32 // MemoryMap - The current memory map
34 UINTN mMemoryMapKey
= 0;
36 #define MAX_MAP_DEPTH 6
39 /// mMapDepth - depth of new descriptor stack
43 /// mMapStack - space to use as temp storage to build new map descriptors
45 MEMORY_MAP mMapStack
[MAX_MAP_DEPTH
];
46 UINTN mFreeMapStack
= 0;
48 /// This list maintain the free memory map list
50 LIST_ENTRY mFreeMemoryMapEntryList
= INITIALIZE_LIST_HEAD_VARIABLE (mFreeMemoryMapEntryList
);
51 BOOLEAN mMemoryTypeInformationInitialized
= FALSE
;
53 EFI_MEMORY_TYPE_STATISTICS mMemoryTypeStatistics
[EfiMaxMemoryType
+ 1] = {
54 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, TRUE
, FALSE
}, // EfiReservedMemoryType
55 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiLoaderCode
56 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiLoaderData
57 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiBootServicesCode
58 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiBootServicesData
59 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, TRUE
, TRUE
}, // EfiRuntimeServicesCode
60 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, TRUE
, TRUE
}, // EfiRuntimeServicesData
61 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiConventionalMemory
62 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiUnusableMemory
63 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, TRUE
, FALSE
}, // EfiACPIReclaimMemory
64 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, TRUE
, FALSE
}, // EfiACPIMemoryNVS
65 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiMemoryMappedIO
66 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiMemoryMappedIOPortSpace
67 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, TRUE
, TRUE
}, // EfiPalCode
68 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
}, // EfiPersistentMemory
69 { 0, MAX_ADDRESS
, 0, 0, EfiMaxMemoryType
, FALSE
, FALSE
} // EfiMaxMemoryType
72 EFI_PHYSICAL_ADDRESS mDefaultMaximumAddress
= MAX_ADDRESS
;
73 EFI_PHYSICAL_ADDRESS mDefaultBaseAddress
= MAX_ADDRESS
;
75 EFI_MEMORY_TYPE_INFORMATION gMemoryTypeInformation
[EfiMaxMemoryType
+ 1] = {
76 { EfiReservedMemoryType
, 0 },
79 { EfiBootServicesCode
, 0 },
80 { EfiBootServicesData
, 0 },
81 { EfiRuntimeServicesCode
, 0 },
82 { EfiRuntimeServicesData
, 0 },
83 { EfiConventionalMemory
, 0 },
84 { EfiUnusableMemory
, 0 },
85 { EfiACPIReclaimMemory
, 0 },
86 { EfiACPIMemoryNVS
, 0 },
87 { EfiMemoryMappedIO
, 0 },
88 { EfiMemoryMappedIOPortSpace
, 0 },
90 { EfiPersistentMemory
, 0 },
91 { EfiMaxMemoryType
, 0 }
94 // Only used when load module at fixed address feature is enabled. True means the memory is alreay successfully allocated
95 // and ready to load the module in to specified address.or else, the memory is not ready and module will be loaded at a
96 // address assigned by DXE core.
98 GLOBAL_REMOVE_IF_UNREFERENCED BOOLEAN gLoadFixedAddressCodeMemoryReady
= FALSE
;
101 Enter critical section by gaining lock on gMemoryLock.
105 CoreAcquireMemoryLock (
109 CoreAcquireLock (&gMemoryLock
);
115 Exit critical section by releasing lock on gMemoryLock.
119 CoreReleaseMemoryLock (
123 CoreReleaseLock (&gMemoryLock
);
130 Internal function. Removes a descriptor entry.
132 @param Entry The entry to remove
136 RemoveMemoryMapEntry (
137 IN OUT MEMORY_MAP
*Entry
140 RemoveEntryList (&Entry
->Link
);
141 Entry
->Link
.ForwardLink
= NULL
;
143 if (Entry
->FromPages
) {
145 // Insert the free memory map descriptor to the end of mFreeMemoryMapEntryList
147 InsertTailList (&mFreeMemoryMapEntryList
, &Entry
->Link
);
152 Internal function. Adds a ranges to the memory map.
153 The range must not already exist in the map.
155 @param Type The type of memory range to add
156 @param Start The starting address in the memory range Must be
158 @param End The last address in the range Must be the last
160 @param Attribute The attributes of the memory range to add
165 IN EFI_MEMORY_TYPE Type
,
166 IN EFI_PHYSICAL_ADDRESS Start
,
167 IN EFI_PHYSICAL_ADDRESS End
,
174 ASSERT ((Start
& EFI_PAGE_MASK
) == 0);
175 ASSERT (End
> Start
) ;
177 ASSERT_LOCKED (&gMemoryLock
);
179 DEBUG ((DEBUG_PAGE
, "AddRange: %lx-%lx to %d\n", Start
, End
, Type
));
182 // If memory of type EfiConventionalMemory is being added that includes the page
183 // starting at address 0, then zero the page starting at address 0. This has
184 // two benifits. It helps find NULL pointer bugs and it also maximizes
185 // compatibility with operating systems that may evaluate memory in this page
186 // for legacy data structures. If memory of any other type is added starting
187 // at address 0, then do not zero the page at address 0 because the page is being
188 // used for other purposes.
190 if (Type
== EfiConventionalMemory
&& Start
== 0 && (End
>= EFI_PAGE_SIZE
- 1)) {
191 if ((PcdGet8 (PcdNullPointerDetectionPropertyMask
) & BIT0
) == 0) {
192 SetMem ((VOID
*)(UINTN
)Start
, EFI_PAGE_SIZE
, 0);
197 // Memory map being altered so updated key
202 // UEFI 2.0 added an event group for notificaiton on memory map changes.
203 // So we need to signal this Event Group every time the memory map changes.
204 // If we are in EFI 1.10 compatability mode no event groups will be
205 // found and nothing will happen we we call this function. These events
206 // will get signaled but since a lock is held around the call to this
207 // function the notificaiton events will only be called after this function
208 // returns and the lock is released.
210 CoreNotifySignalList (&gEfiEventMemoryMapChangeGuid
);
213 // Look for adjoining memory descriptor
216 // Two memory descriptors can only be merged if they have the same Type
217 // and the same Attribute
220 Link
= gMemoryMap
.ForwardLink
;
221 while (Link
!= &gMemoryMap
) {
222 Entry
= CR (Link
, MEMORY_MAP
, Link
, MEMORY_MAP_SIGNATURE
);
223 Link
= Link
->ForwardLink
;
225 if (Entry
->Type
!= Type
) {
229 if (Entry
->Attribute
!= Attribute
) {
233 if (Entry
->End
+ 1 == Start
) {
235 Start
= Entry
->Start
;
236 RemoveMemoryMapEntry (Entry
);
238 } else if (Entry
->Start
== End
+ 1) {
241 RemoveMemoryMapEntry (Entry
);
249 mMapStack
[mMapDepth
].Signature
= MEMORY_MAP_SIGNATURE
;
250 mMapStack
[mMapDepth
].FromPages
= FALSE
;
251 mMapStack
[mMapDepth
].Type
= Type
;
252 mMapStack
[mMapDepth
].Start
= Start
;
253 mMapStack
[mMapDepth
].End
= End
;
254 mMapStack
[mMapDepth
].VirtualStart
= 0;
255 mMapStack
[mMapDepth
].Attribute
= Attribute
;
256 InsertTailList (&gMemoryMap
, &mMapStack
[mMapDepth
].Link
);
259 ASSERT (mMapDepth
< MAX_MAP_DEPTH
);
265 Internal function. Deque a descriptor entry from the mFreeMemoryMapEntryList.
266 If the list is emtry, then allocate a new page to refuel the list.
267 Please Note this algorithm to allocate the memory map descriptor has a property
268 that the memory allocated for memory entries always grows, and will never really be freed
269 For example, if the current boot uses 2000 memory map entries at the maximum point, but
270 ends up with only 50 at the time the OS is booted, then the memory associated with the 1950
271 memory map entries is still allocated from EfiBootServicesMemory.
274 @return The Memory map descriptor dequed from the mFreeMemoryMapEntryList
278 AllocateMemoryMapEntry (
282 MEMORY_MAP
* FreeDescriptorEntries
;
286 if (IsListEmpty (&mFreeMemoryMapEntryList
)) {
288 // The list is empty, to allocate one page to refuel the list
290 FreeDescriptorEntries
= CoreAllocatePoolPages (EfiBootServicesData
,
291 EFI_SIZE_TO_PAGES (DEFAULT_PAGE_ALLOCATION_GRANULARITY
),
292 DEFAULT_PAGE_ALLOCATION_GRANULARITY
);
293 if (FreeDescriptorEntries
!= NULL
) {
295 // Enque the free memmory map entries into the list
297 for (Index
= 0; Index
< DEFAULT_PAGE_ALLOCATION_GRANULARITY
/ sizeof(MEMORY_MAP
); Index
++) {
298 FreeDescriptorEntries
[Index
].Signature
= MEMORY_MAP_SIGNATURE
;
299 InsertTailList (&mFreeMemoryMapEntryList
, &FreeDescriptorEntries
[Index
].Link
);
306 // dequeue the first descriptor from the list
308 Entry
= CR (mFreeMemoryMapEntryList
.ForwardLink
, MEMORY_MAP
, Link
, MEMORY_MAP_SIGNATURE
);
309 RemoveEntryList (&Entry
->Link
);
316 Internal function. Moves any memory descriptors that are on the
317 temporary descriptor stack to heap.
321 CoreFreeMemoryMapStack (
329 ASSERT_LOCKED (&gMemoryLock
);
332 // If already freeing the map stack, then return
334 if (mFreeMapStack
!= 0) {
339 // Move the temporary memory descriptor stack into pool
343 while (mMapDepth
!= 0) {
345 // Deque an memory map entry from mFreeMemoryMapEntryList
347 Entry
= AllocateMemoryMapEntry ();
352 // Update to proper entry
356 if (mMapStack
[mMapDepth
].Link
.ForwardLink
!= NULL
) {
359 // Move this entry to general memory
361 RemoveEntryList (&mMapStack
[mMapDepth
].Link
);
362 mMapStack
[mMapDepth
].Link
.ForwardLink
= NULL
;
364 CopyMem (Entry
, &mMapStack
[mMapDepth
], sizeof (MEMORY_MAP
));
365 Entry
->FromPages
= TRUE
;
368 // Find insertion location
370 for (Link2
= gMemoryMap
.ForwardLink
; Link2
!= &gMemoryMap
; Link2
= Link2
->ForwardLink
) {
371 Entry2
= CR (Link2
, MEMORY_MAP
, Link
, MEMORY_MAP_SIGNATURE
);
372 if (Entry2
->FromPages
&& Entry2
->Start
> Entry
->Start
) {
377 InsertTailList (Link2
, &Entry
->Link
);
381 // This item of mMapStack[mMapDepth] has already been dequeued from gMemoryMap list,
382 // so here no need to move it to memory.
384 InsertTailList (&mFreeMemoryMapEntryList
, &Entry
->Link
);
392 Find untested but initialized memory regions in GCD map and convert them to be DXE allocatable.
396 PromoteMemoryResource (
401 EFI_GCD_MAP_ENTRY
*Entry
;
404 DEBUG ((DEBUG_PAGE
, "Promote the memory resource\n"));
406 CoreAcquireGcdMemoryLock ();
409 Link
= mGcdMemorySpaceMap
.ForwardLink
;
410 while (Link
!= &mGcdMemorySpaceMap
) {
412 Entry
= CR (Link
, EFI_GCD_MAP_ENTRY
, Link
, EFI_GCD_MAP_SIGNATURE
);
414 if (Entry
->GcdMemoryType
== EfiGcdMemoryTypeReserved
&&
415 Entry
->EndAddress
< MAX_ADDRESS
&&
416 (Entry
->Capabilities
& (EFI_MEMORY_PRESENT
| EFI_MEMORY_INITIALIZED
| EFI_MEMORY_TESTED
)) ==
417 (EFI_MEMORY_PRESENT
| EFI_MEMORY_INITIALIZED
)) {
419 // Update the GCD map
421 if ((Entry
->Capabilities
& EFI_MEMORY_MORE_RELIABLE
) == EFI_MEMORY_MORE_RELIABLE
) {
422 Entry
->GcdMemoryType
= EfiGcdMemoryTypeMoreReliable
;
424 Entry
->GcdMemoryType
= EfiGcdMemoryTypeSystemMemory
;
426 Entry
->Capabilities
|= EFI_MEMORY_TESTED
;
427 Entry
->ImageHandle
= gDxeCoreImageHandle
;
428 Entry
->DeviceHandle
= NULL
;
431 // Add to allocable system memory resource
435 EfiConventionalMemory
,
438 Entry
->Capabilities
& ~(EFI_MEMORY_PRESENT
| EFI_MEMORY_INITIALIZED
| EFI_MEMORY_TESTED
| EFI_MEMORY_RUNTIME
)
440 CoreFreeMemoryMapStack ();
445 Link
= Link
->ForwardLink
;
448 CoreReleaseGcdMemoryLock ();
453 This function try to allocate Runtime code & Boot time code memory range. If LMFA enabled, 2 patchable PCD
454 PcdLoadFixAddressRuntimeCodePageNumber & PcdLoadFixAddressBootTimeCodePageNumber which are set by tools will record the
455 size of boot time and runtime code.
459 CoreLoadingFixedAddressHook (
463 UINT32 RuntimeCodePageNumber
;
464 UINT32 BootTimeCodePageNumber
;
465 EFI_PHYSICAL_ADDRESS RuntimeCodeBase
;
466 EFI_PHYSICAL_ADDRESS BootTimeCodeBase
;
470 // Make sure these 2 areas are not initialzied.
472 if (!gLoadFixedAddressCodeMemoryReady
) {
473 RuntimeCodePageNumber
= PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber
);
474 BootTimeCodePageNumber
= PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber
);
475 RuntimeCodeBase
= (EFI_PHYSICAL_ADDRESS
)(gLoadModuleAtFixAddressConfigurationTable
.DxeCodeTopAddress
- EFI_PAGES_TO_SIZE (RuntimeCodePageNumber
));
476 BootTimeCodeBase
= (EFI_PHYSICAL_ADDRESS
)(RuntimeCodeBase
- EFI_PAGES_TO_SIZE (BootTimeCodePageNumber
));
478 // Try to allocate runtime memory.
480 Status
= CoreAllocatePages (
482 EfiRuntimeServicesCode
,
483 RuntimeCodePageNumber
,
486 if (EFI_ERROR(Status
)) {
488 // Runtime memory allocation failed
493 // Try to allocate boot memory.
495 Status
= CoreAllocatePages (
498 BootTimeCodePageNumber
,
501 if (EFI_ERROR(Status
)) {
503 // boot memory allocation failed. Free Runtime code range and will try the allocation again when
504 // new memory range is installed.
508 RuntimeCodePageNumber
512 gLoadFixedAddressCodeMemoryReady
= TRUE
;
518 Called to initialize the memory map and add descriptors to
519 the current descriptor list.
520 The first descriptor that is added must be general usable
521 memory as the addition allocates heap.
523 @param Type The type of memory to add
524 @param Start The starting address in the memory range Must be
526 @param NumberOfPages The number of pages in the range
527 @param Attribute Attributes of the memory to add
529 @return None. The range is added to the memory map
533 CoreAddMemoryDescriptor (
534 IN EFI_MEMORY_TYPE Type
,
535 IN EFI_PHYSICAL_ADDRESS Start
,
536 IN UINT64 NumberOfPages
,
540 EFI_PHYSICAL_ADDRESS End
;
545 if ((Start
& EFI_PAGE_MASK
) != 0) {
549 if (Type
>= EfiMaxMemoryType
&& Type
< MEMORY_TYPE_OEM_RESERVED_MIN
) {
552 CoreAcquireMemoryLock ();
553 End
= Start
+ LShiftU64 (NumberOfPages
, EFI_PAGE_SHIFT
) - 1;
554 CoreAddRange (Type
, Start
, End
, Attribute
);
555 CoreFreeMemoryMapStack ();
556 CoreReleaseMemoryLock ();
558 ApplyMemoryProtectionPolicy (EfiMaxMemoryType
, Type
, Start
,
559 LShiftU64 (NumberOfPages
, EFI_PAGE_SHIFT
));
562 // If Loading Module At Fixed Address feature is enabled. try to allocate memory with Runtime code & Boot time code type
564 if (PcdGet64(PcdLoadModuleAtFixAddressEnable
) != 0) {
565 CoreLoadingFixedAddressHook();
569 // Check to see if the statistics for the different memory types have already been established
571 if (mMemoryTypeInformationInitialized
) {
577 // Loop through each memory type in the order specified by the gMemoryTypeInformation[] array
579 for (Index
= 0; gMemoryTypeInformation
[Index
].Type
!= EfiMaxMemoryType
; Index
++) {
581 // Make sure the memory type in the gMemoryTypeInformation[] array is valid
583 Type
= (EFI_MEMORY_TYPE
) (gMemoryTypeInformation
[Index
].Type
);
584 if ((UINT32
)Type
> EfiMaxMemoryType
) {
587 if (gMemoryTypeInformation
[Index
].NumberOfPages
!= 0) {
589 // Allocate pages for the current memory type from the top of available memory
591 Status
= CoreAllocatePages (
594 gMemoryTypeInformation
[Index
].NumberOfPages
,
595 &mMemoryTypeStatistics
[Type
].BaseAddress
597 if (EFI_ERROR (Status
)) {
599 // If an error occurs allocating the pages for the current memory type, then
600 // free all the pages allocates for the previous memory types and return. This
601 // operation with be retied when/if more memory is added to the system
603 for (FreeIndex
= 0; FreeIndex
< Index
; FreeIndex
++) {
605 // Make sure the memory type in the gMemoryTypeInformation[] array is valid
607 Type
= (EFI_MEMORY_TYPE
) (gMemoryTypeInformation
[FreeIndex
].Type
);
608 if ((UINT32
)Type
> EfiMaxMemoryType
) {
612 if (gMemoryTypeInformation
[FreeIndex
].NumberOfPages
!= 0) {
614 mMemoryTypeStatistics
[Type
].BaseAddress
,
615 gMemoryTypeInformation
[FreeIndex
].NumberOfPages
617 mMemoryTypeStatistics
[Type
].BaseAddress
= 0;
618 mMemoryTypeStatistics
[Type
].MaximumAddress
= MAX_ADDRESS
;
625 // Compute the address at the top of the current statistics
627 mMemoryTypeStatistics
[Type
].MaximumAddress
=
628 mMemoryTypeStatistics
[Type
].BaseAddress
+
629 LShiftU64 (gMemoryTypeInformation
[Index
].NumberOfPages
, EFI_PAGE_SHIFT
) - 1;
632 // If the current base address is the lowest address so far, then update the default
635 if (mMemoryTypeStatistics
[Type
].BaseAddress
< mDefaultMaximumAddress
) {
636 mDefaultMaximumAddress
= mMemoryTypeStatistics
[Type
].BaseAddress
- 1;
642 // There was enough system memory for all the the memory types were allocated. So,
643 // those memory areas can be freed for future allocations, and all future memory
644 // allocations can occur within their respective bins
646 for (Index
= 0; gMemoryTypeInformation
[Index
].Type
!= EfiMaxMemoryType
; Index
++) {
648 // Make sure the memory type in the gMemoryTypeInformation[] array is valid
650 Type
= (EFI_MEMORY_TYPE
) (gMemoryTypeInformation
[Index
].Type
);
651 if ((UINT32
)Type
> EfiMaxMemoryType
) {
654 if (gMemoryTypeInformation
[Index
].NumberOfPages
!= 0) {
656 mMemoryTypeStatistics
[Type
].BaseAddress
,
657 gMemoryTypeInformation
[Index
].NumberOfPages
659 mMemoryTypeStatistics
[Type
].NumberOfPages
= gMemoryTypeInformation
[Index
].NumberOfPages
;
660 gMemoryTypeInformation
[Index
].NumberOfPages
= 0;
665 // If the number of pages reserved for a memory type is 0, then all allocations for that type
666 // should be in the default range.
668 for (Type
= (EFI_MEMORY_TYPE
) 0; Type
< EfiMaxMemoryType
; Type
++) {
669 for (Index
= 0; gMemoryTypeInformation
[Index
].Type
!= EfiMaxMemoryType
; Index
++) {
670 if (Type
== (EFI_MEMORY_TYPE
)gMemoryTypeInformation
[Index
].Type
) {
671 mMemoryTypeStatistics
[Type
].InformationIndex
= Index
;
674 mMemoryTypeStatistics
[Type
].CurrentNumberOfPages
= 0;
675 if (mMemoryTypeStatistics
[Type
].MaximumAddress
== MAX_ADDRESS
) {
676 mMemoryTypeStatistics
[Type
].MaximumAddress
= mDefaultMaximumAddress
;
680 mMemoryTypeInformationInitialized
= TRUE
;
685 Internal function. Converts a memory range to the specified type or attributes.
686 The range must exist in the memory map. Either ChangingType or
687 ChangingAttributes must be set, but not both.
689 @param Start The first address of the range Must be page
691 @param NumberOfPages The number of pages to convert
692 @param ChangingType Boolean indicating that type value should be changed
693 @param NewType The new type for the memory range
694 @param ChangingAttributes Boolean indicating that attributes value should be changed
695 @param NewAttributes The new attributes for the memory range
697 @retval EFI_INVALID_PARAMETER Invalid parameter
698 @retval EFI_NOT_FOUND Could not find a descriptor cover the specified
699 range or convertion not allowed.
700 @retval EFI_SUCCESS Successfully converts the memory range to the
707 IN UINT64 NumberOfPages
,
708 IN BOOLEAN ChangingType
,
709 IN EFI_MEMORY_TYPE NewType
,
710 IN BOOLEAN ChangingAttributes
,
711 IN UINT64 NewAttributes
715 UINT64 NumberOfBytes
;
719 EFI_MEMORY_TYPE MemType
;
724 NumberOfBytes
= LShiftU64 (NumberOfPages
, EFI_PAGE_SHIFT
);
725 End
= Start
+ NumberOfBytes
- 1;
727 ASSERT (NumberOfPages
);
728 ASSERT ((Start
& EFI_PAGE_MASK
) == 0);
729 ASSERT (End
> Start
) ;
730 ASSERT_LOCKED (&gMemoryLock
);
731 ASSERT ( (ChangingType
== FALSE
) || (ChangingAttributes
== FALSE
) );
733 if (NumberOfPages
== 0 || ((Start
& EFI_PAGE_MASK
) != 0) || (Start
>= End
)) {
734 return EFI_INVALID_PARAMETER
;
738 // Convert the entire range
741 while (Start
< End
) {
744 // Find the entry that the covers the range
746 for (Link
= gMemoryMap
.ForwardLink
; Link
!= &gMemoryMap
; Link
= Link
->ForwardLink
) {
747 Entry
= CR (Link
, MEMORY_MAP
, Link
, MEMORY_MAP_SIGNATURE
);
749 if (Entry
->Start
<= Start
&& Entry
->End
> Start
) {
754 if (Link
== &gMemoryMap
) {
755 DEBUG ((DEBUG_ERROR
| DEBUG_PAGE
, "ConvertPages: failed to find range %lx - %lx\n", Start
, End
));
756 return EFI_NOT_FOUND
;
760 // If we are converting the type of the range from EfiConventionalMemory to
761 // another type, we have to ensure that the entire range is covered by a
764 if (ChangingType
&& (NewType
!= EfiConventionalMemory
)) {
765 if (Entry
->End
< End
) {
766 DEBUG ((DEBUG_ERROR
| DEBUG_PAGE
, "ConvertPages: range %lx - %lx covers multiple entries\n", Start
, End
));
767 return EFI_NOT_FOUND
;
771 // Convert range to the end, or to the end of the descriptor
772 // if that's all we've got
776 ASSERT (Entry
!= NULL
);
777 if (Entry
->End
< End
) {
778 RangeEnd
= Entry
->End
;
782 DEBUG ((DEBUG_PAGE
, "ConvertRange: %lx-%lx to type %d\n", Start
, RangeEnd
, NewType
));
784 if (ChangingAttributes
) {
785 DEBUG ((DEBUG_PAGE
, "ConvertRange: %lx-%lx to attr %lx\n", Start
, RangeEnd
, NewAttributes
));
790 // Debug code - verify conversion is allowed
792 if (!(NewType
== EfiConventionalMemory
? 1 : 0) ^ (Entry
->Type
== EfiConventionalMemory
? 1 : 0)) {
793 DEBUG ((DEBUG_ERROR
| DEBUG_PAGE
, "ConvertPages: Incompatible memory types, "));
794 if (Entry
->Type
== EfiConventionalMemory
) {
795 DEBUG ((DEBUG_ERROR
| DEBUG_PAGE
, "the pages to free have been freed\n"));
797 DEBUG ((DEBUG_ERROR
| DEBUG_PAGE
, "the pages to allocate have been allocated\n"));
799 return EFI_NOT_FOUND
;
803 // Update counters for the number of pages allocated to each memory type
805 if ((UINT32
)Entry
->Type
< EfiMaxMemoryType
) {
806 if ((Start
>= mMemoryTypeStatistics
[Entry
->Type
].BaseAddress
&& Start
<= mMemoryTypeStatistics
[Entry
->Type
].MaximumAddress
) ||
807 (Start
>= mDefaultBaseAddress
&& Start
<= mDefaultMaximumAddress
) ) {
808 if (NumberOfPages
> mMemoryTypeStatistics
[Entry
->Type
].CurrentNumberOfPages
) {
809 mMemoryTypeStatistics
[Entry
->Type
].CurrentNumberOfPages
= 0;
811 mMemoryTypeStatistics
[Entry
->Type
].CurrentNumberOfPages
-= NumberOfPages
;
816 if ((UINT32
)NewType
< EfiMaxMemoryType
) {
817 if ((Start
>= mMemoryTypeStatistics
[NewType
].BaseAddress
&& Start
<= mMemoryTypeStatistics
[NewType
].MaximumAddress
) ||
818 (Start
>= mDefaultBaseAddress
&& Start
<= mDefaultMaximumAddress
) ) {
819 mMemoryTypeStatistics
[NewType
].CurrentNumberOfPages
+= NumberOfPages
;
820 if (mMemoryTypeStatistics
[NewType
].CurrentNumberOfPages
> gMemoryTypeInformation
[mMemoryTypeStatistics
[NewType
].InformationIndex
].NumberOfPages
) {
821 gMemoryTypeInformation
[mMemoryTypeStatistics
[NewType
].InformationIndex
].NumberOfPages
= (UINT32
)mMemoryTypeStatistics
[NewType
].CurrentNumberOfPages
;
828 // Pull range out of descriptor
830 if (Entry
->Start
== Start
) {
835 Entry
->Start
= RangeEnd
+ 1;
837 } else if (Entry
->End
== RangeEnd
) {
842 Entry
->End
= Start
- 1;
847 // Pull it out of the center, clip current
853 mMapStack
[mMapDepth
].Signature
= MEMORY_MAP_SIGNATURE
;
854 mMapStack
[mMapDepth
].FromPages
= FALSE
;
855 mMapStack
[mMapDepth
].Type
= Entry
->Type
;
856 mMapStack
[mMapDepth
].Start
= RangeEnd
+1;
857 mMapStack
[mMapDepth
].End
= Entry
->End
;
860 // Inherit Attribute from the Memory Descriptor that is being clipped
862 mMapStack
[mMapDepth
].Attribute
= Entry
->Attribute
;
864 Entry
->End
= Start
- 1;
865 ASSERT (Entry
->Start
< Entry
->End
);
867 Entry
= &mMapStack
[mMapDepth
];
868 InsertTailList (&gMemoryMap
, &Entry
->Link
);
871 ASSERT (mMapDepth
< MAX_MAP_DEPTH
);
875 // The new range inherits the same Attribute as the Entry
876 // it is being cut out of unless attributes are being changed
879 Attribute
= Entry
->Attribute
;
882 Attribute
= NewAttributes
;
883 MemType
= Entry
->Type
;
887 // If the descriptor is empty, then remove it from the map
889 if (Entry
->Start
== Entry
->End
+ 1) {
890 RemoveMemoryMapEntry (Entry
);
895 // Add our new range in
897 CoreAddRange (MemType
, Start
, RangeEnd
, Attribute
);
898 if (ChangingType
&& (MemType
== EfiConventionalMemory
)) {
900 // Avoid calling DEBUG_CLEAR_MEMORY() for an address of 0 because this
901 // macro will ASSERT() if address is 0. Instead, CoreAddRange() guarantees
902 // that the page starting at address 0 is always filled with zeros.
905 if (RangeEnd
> EFI_PAGE_SIZE
) {
906 DEBUG_CLEAR_MEMORY ((VOID
*)(UINTN
) EFI_PAGE_SIZE
, (UINTN
) (RangeEnd
- EFI_PAGE_SIZE
+ 1));
909 DEBUG_CLEAR_MEMORY ((VOID
*)(UINTN
) Start
, (UINTN
) (RangeEnd
- Start
+ 1));
914 // Move any map descriptor stack to general pool
916 CoreFreeMemoryMapStack ();
919 // Bump the starting address, and convert the next range
921 Start
= RangeEnd
+ 1;
925 // Converted the whole range, done
933 Internal function. Converts a memory range to the specified type.
934 The range must exist in the memory map.
936 @param Start The first address of the range Must be page
938 @param NumberOfPages The number of pages to convert
939 @param NewType The new type for the memory range
941 @retval EFI_INVALID_PARAMETER Invalid parameter
942 @retval EFI_NOT_FOUND Could not find a descriptor cover the specified
943 range or convertion not allowed.
944 @retval EFI_SUCCESS Successfully converts the memory range to the
951 IN UINT64 NumberOfPages
,
952 IN EFI_MEMORY_TYPE NewType
955 return CoreConvertPagesEx(Start
, NumberOfPages
, TRUE
, NewType
, FALSE
, 0);
960 Internal function. Converts a memory range to use new attributes.
962 @param Start The first address of the range Must be page
964 @param NumberOfPages The number of pages to convert
965 @param NewAttributes The new attributes value for the range.
969 CoreUpdateMemoryAttributes (
970 IN EFI_PHYSICAL_ADDRESS Start
,
971 IN UINT64 NumberOfPages
,
972 IN UINT64 NewAttributes
975 CoreAcquireMemoryLock ();
978 // Update the attributes to the new value
980 CoreConvertPagesEx(Start
, NumberOfPages
, FALSE
, (EFI_MEMORY_TYPE
)0, TRUE
, NewAttributes
);
982 CoreReleaseMemoryLock ();
987 Internal function. Finds a consecutive free page range below
988 the requested address.
990 @param MaxAddress The address that the range must be below
991 @param MinAddress The address that the range must be above
992 @param NumberOfPages Number of pages needed
993 @param NewType The type of memory the range is going to be
995 @param Alignment Bits to align with
997 @return The base address of the range, or 0 if the range was not found
1001 CoreFindFreePagesI (
1002 IN UINT64 MaxAddress
,
1003 IN UINT64 MinAddress
,
1004 IN UINT64 NumberOfPages
,
1005 IN EFI_MEMORY_TYPE NewType
,
1009 UINT64 NumberOfBytes
;
1013 UINT64 DescNumberOfBytes
;
1017 if ((MaxAddress
< EFI_PAGE_MASK
) ||(NumberOfPages
== 0)) {
1021 if ((MaxAddress
& EFI_PAGE_MASK
) != EFI_PAGE_MASK
) {
1024 // If MaxAddress is not aligned to the end of a page
1028 // Change MaxAddress to be 1 page lower
1030 MaxAddress
-= (EFI_PAGE_MASK
+ 1);
1033 // Set MaxAddress to a page boundary
1035 MaxAddress
&= ~(UINT64
)EFI_PAGE_MASK
;
1038 // Set MaxAddress to end of the page
1040 MaxAddress
|= EFI_PAGE_MASK
;
1043 NumberOfBytes
= LShiftU64 (NumberOfPages
, EFI_PAGE_SHIFT
);
1046 for (Link
= gMemoryMap
.ForwardLink
; Link
!= &gMemoryMap
; Link
= Link
->ForwardLink
) {
1047 Entry
= CR (Link
, MEMORY_MAP
, Link
, MEMORY_MAP_SIGNATURE
);
1050 // If it's not a free entry, don't bother with it
1052 if (Entry
->Type
!= EfiConventionalMemory
) {
1056 DescStart
= Entry
->Start
;
1057 DescEnd
= Entry
->End
;
1060 // If desc is past max allowed address or below min allowed address, skip it
1062 if ((DescStart
>= MaxAddress
) || (DescEnd
< MinAddress
)) {
1067 // If desc ends past max allowed address, clip the end
1069 if (DescEnd
>= MaxAddress
) {
1070 DescEnd
= MaxAddress
;
1073 DescEnd
= ((DescEnd
+ 1) & (~(Alignment
- 1))) - 1;
1075 // Skip if DescEnd is less than DescStart after alignment clipping
1076 if (DescEnd
< DescStart
) {
1081 // Compute the number of bytes we can used from this
1082 // descriptor, and see it's enough to satisfy the request
1084 DescNumberOfBytes
= DescEnd
- DescStart
+ 1;
1086 if (DescNumberOfBytes
>= NumberOfBytes
) {
1088 // If the start of the allocated range is below the min address allowed, skip it
1090 if ((DescEnd
- NumberOfBytes
+ 1) < MinAddress
) {
1095 // If this is the best match so far remember it
1097 if (DescEnd
> Target
) {
1104 // If this is a grow down, adjust target to be the allocation base
1106 Target
-= NumberOfBytes
- 1;
1109 // If we didn't find a match, return 0
1111 if ((Target
& EFI_PAGE_MASK
) != 0) {
1120 Internal function. Finds a consecutive free page range below
1121 the requested address
1123 @param MaxAddress The address that the range must be below
1124 @param NoPages Number of pages needed
1125 @param NewType The type of memory the range is going to be
1127 @param Alignment Bits to align with
1129 @return The base address of the range, or 0 if the range was not found.
1134 IN UINT64 MaxAddress
,
1136 IN EFI_MEMORY_TYPE NewType
,
1143 // Attempt to find free pages in the preferred bin based on the requested memory type
1145 if ((UINT32
)NewType
< EfiMaxMemoryType
&& MaxAddress
>= mMemoryTypeStatistics
[NewType
].MaximumAddress
) {
1146 Start
= CoreFindFreePagesI (
1147 mMemoryTypeStatistics
[NewType
].MaximumAddress
,
1148 mMemoryTypeStatistics
[NewType
].BaseAddress
,
1159 // Attempt to find free pages in the default allocation bin
1161 if (MaxAddress
>= mDefaultMaximumAddress
) {
1162 Start
= CoreFindFreePagesI (mDefaultMaximumAddress
, 0, NoPages
, NewType
, Alignment
);
1164 if (Start
< mDefaultBaseAddress
) {
1165 mDefaultBaseAddress
= Start
;
1172 // The allocation did not succeed in any of the prefered bins even after
1173 // promoting resources. Attempt to find free pages anywhere is the requested
1174 // address range. If this allocation fails, then there are not enough
1175 // resources anywhere to satisfy the request.
1177 Start
= CoreFindFreePagesI (MaxAddress
, 0, NoPages
, NewType
, Alignment
);
1183 // If allocations from the preferred bins fail, then attempt to promote memory resources.
1185 if (!PromoteMemoryResource ()) {
1190 // If any memory resources were promoted, then re-attempt the allocation
1192 return FindFreePages (MaxAddress
, NoPages
, NewType
, Alignment
);
1197 Allocates pages from the memory map.
1199 @param Type The type of allocation to perform
1200 @param MemoryType The type of memory to turn the allocated pages
1202 @param NumberOfPages The number of pages to allocate
1203 @param Memory A pointer to receive the base allocated memory
1206 @return Status. On success, Memory is filled in with the base address allocated
1207 @retval EFI_INVALID_PARAMETER Parameters violate checking rules defined in
1209 @retval EFI_NOT_FOUND Could not allocate pages match the requirement.
1210 @retval EFI_OUT_OF_RESOURCES No enough pages to allocate.
1211 @retval EFI_SUCCESS Pages successfully allocated.
1216 CoreInternalAllocatePages (
1217 IN EFI_ALLOCATE_TYPE Type
,
1218 IN EFI_MEMORY_TYPE MemoryType
,
1219 IN UINTN NumberOfPages
,
1220 IN OUT EFI_PHYSICAL_ADDRESS
*Memory
1225 UINT64 NumberOfBytes
;
1230 if ((UINT32
)Type
>= MaxAllocateType
) {
1231 return EFI_INVALID_PARAMETER
;
1234 if ((MemoryType
>= EfiMaxMemoryType
&& MemoryType
< MEMORY_TYPE_OEM_RESERVED_MIN
) ||
1235 (MemoryType
== EfiConventionalMemory
) || (MemoryType
== EfiPersistentMemory
)) {
1236 return EFI_INVALID_PARAMETER
;
1239 if (Memory
== NULL
) {
1240 return EFI_INVALID_PARAMETER
;
1243 Alignment
= DEFAULT_PAGE_ALLOCATION_GRANULARITY
;
1245 if (MemoryType
== EfiACPIReclaimMemory
||
1246 MemoryType
== EfiACPIMemoryNVS
||
1247 MemoryType
== EfiRuntimeServicesCode
||
1248 MemoryType
== EfiRuntimeServicesData
) {
1250 Alignment
= RUNTIME_PAGE_ALLOCATION_GRANULARITY
;
1253 if (Type
== AllocateAddress
) {
1254 if ((*Memory
& (Alignment
- 1)) != 0) {
1255 return EFI_NOT_FOUND
;
1259 NumberOfPages
+= EFI_SIZE_TO_PAGES (Alignment
) - 1;
1260 NumberOfPages
&= ~(EFI_SIZE_TO_PAGES (Alignment
) - 1);
1263 // If this is for below a particular address, then
1268 // The max address is the max natively addressable address for the processor
1270 MaxAddress
= MAX_ADDRESS
;
1273 // Check for Type AllocateAddress,
1274 // if NumberOfPages is 0 or
1275 // if (NumberOfPages << EFI_PAGE_SHIFT) is above MAX_ADDRESS or
1276 // if (Start + NumberOfBytes) rolls over 0 or
1277 // if Start is above MAX_ADDRESS or
1278 // if End is above MAX_ADDRESS,
1279 // return EFI_NOT_FOUND.
1281 if (Type
== AllocateAddress
) {
1282 if ((NumberOfPages
== 0) ||
1283 (NumberOfPages
> RShiftU64 (MaxAddress
, EFI_PAGE_SHIFT
))) {
1284 return EFI_NOT_FOUND
;
1286 NumberOfBytes
= LShiftU64 (NumberOfPages
, EFI_PAGE_SHIFT
);
1287 End
= Start
+ NumberOfBytes
- 1;
1289 if ((Start
>= End
) ||
1290 (Start
> MaxAddress
) ||
1291 (End
> MaxAddress
)) {
1292 return EFI_NOT_FOUND
;
1296 if (Type
== AllocateMaxAddress
) {
1300 CoreAcquireMemoryLock ();
1303 // If not a specific address, then find an address to allocate
1305 if (Type
!= AllocateAddress
) {
1306 Start
= FindFreePages (MaxAddress
, NumberOfPages
, MemoryType
, Alignment
);
1308 Status
= EFI_OUT_OF_RESOURCES
;
1314 // Convert pages from FreeMemory to the requested type
1316 Status
= CoreConvertPages (Start
, NumberOfPages
, MemoryType
);
1319 CoreReleaseMemoryLock ();
1321 if (!EFI_ERROR (Status
)) {
1329 Allocates pages from the memory map.
1331 @param Type The type of allocation to perform
1332 @param MemoryType The type of memory to turn the allocated pages
1334 @param NumberOfPages The number of pages to allocate
1335 @param Memory A pointer to receive the base allocated memory
1338 @return Status. On success, Memory is filled in with the base address allocated
1339 @retval EFI_INVALID_PARAMETER Parameters violate checking rules defined in
1341 @retval EFI_NOT_FOUND Could not allocate pages match the requirement.
1342 @retval EFI_OUT_OF_RESOURCES No enough pages to allocate.
1343 @retval EFI_SUCCESS Pages successfully allocated.
1349 IN EFI_ALLOCATE_TYPE Type
,
1350 IN EFI_MEMORY_TYPE MemoryType
,
1351 IN UINTN NumberOfPages
,
1352 OUT EFI_PHYSICAL_ADDRESS
*Memory
1357 Status
= CoreInternalAllocatePages (Type
, MemoryType
, NumberOfPages
, Memory
);
1358 if (!EFI_ERROR (Status
)) {
1360 (EFI_PHYSICAL_ADDRESS
) (UINTN
) RETURN_ADDRESS (0),
1361 MemoryProfileActionAllocatePages
,
1363 EFI_PAGES_TO_SIZE (NumberOfPages
),
1364 (VOID
*) (UINTN
) *Memory
,
1367 InstallMemoryAttributesTableOnMemoryAllocation (MemoryType
);
1368 ApplyMemoryProtectionPolicy (EfiConventionalMemory
, MemoryType
, *Memory
,
1369 EFI_PAGES_TO_SIZE (NumberOfPages
));
1375 Frees previous allocated pages.
1377 @param Memory Base address of memory being freed
1378 @param NumberOfPages The number of pages to free
1379 @param MemoryType Pointer to memory type
1381 @retval EFI_NOT_FOUND Could not find the entry that covers the range
1382 @retval EFI_INVALID_PARAMETER Address not aligned
1383 @return EFI_SUCCESS -Pages successfully freed.
1388 CoreInternalFreePages (
1389 IN EFI_PHYSICAL_ADDRESS Memory
,
1390 IN UINTN NumberOfPages
,
1391 OUT EFI_MEMORY_TYPE
*MemoryType OPTIONAL
1402 CoreAcquireMemoryLock ();
1405 // Find the entry that the covers the range
1408 for (Link
= gMemoryMap
.ForwardLink
; Link
!= &gMemoryMap
; Link
= Link
->ForwardLink
) {
1409 Entry
= CR(Link
, MEMORY_MAP
, Link
, MEMORY_MAP_SIGNATURE
);
1410 if (Entry
->Start
<= Memory
&& Entry
->End
> Memory
) {
1414 if (Link
== &gMemoryMap
) {
1415 Status
= EFI_NOT_FOUND
;
1419 Alignment
= DEFAULT_PAGE_ALLOCATION_GRANULARITY
;
1421 ASSERT (Entry
!= NULL
);
1422 if (Entry
->Type
== EfiACPIReclaimMemory
||
1423 Entry
->Type
== EfiACPIMemoryNVS
||
1424 Entry
->Type
== EfiRuntimeServicesCode
||
1425 Entry
->Type
== EfiRuntimeServicesData
) {
1427 Alignment
= RUNTIME_PAGE_ALLOCATION_GRANULARITY
;
1431 if ((Memory
& (Alignment
- 1)) != 0) {
1432 Status
= EFI_INVALID_PARAMETER
;
1436 NumberOfPages
+= EFI_SIZE_TO_PAGES (Alignment
) - 1;
1437 NumberOfPages
&= ~(EFI_SIZE_TO_PAGES (Alignment
) - 1);
1439 if (MemoryType
!= NULL
) {
1440 *MemoryType
= Entry
->Type
;
1443 Status
= CoreConvertPages (Memory
, NumberOfPages
, EfiConventionalMemory
);
1445 if (EFI_ERROR (Status
)) {
1450 CoreReleaseMemoryLock ();
1455 Frees previous allocated pages.
1457 @param Memory Base address of memory being freed
1458 @param NumberOfPages The number of pages to free
1460 @retval EFI_NOT_FOUND Could not find the entry that covers the range
1461 @retval EFI_INVALID_PARAMETER Address not aligned
1462 @return EFI_SUCCESS -Pages successfully freed.
1468 IN EFI_PHYSICAL_ADDRESS Memory
,
1469 IN UINTN NumberOfPages
1473 EFI_MEMORY_TYPE MemoryType
;
1475 Status
= CoreInternalFreePages (Memory
, NumberOfPages
, &MemoryType
);
1476 if (!EFI_ERROR (Status
)) {
1478 (EFI_PHYSICAL_ADDRESS
) (UINTN
) RETURN_ADDRESS (0),
1479 MemoryProfileActionFreePages
,
1481 EFI_PAGES_TO_SIZE (NumberOfPages
),
1482 (VOID
*) (UINTN
) Memory
,
1485 InstallMemoryAttributesTableOnMemoryAllocation (MemoryType
);
1486 ApplyMemoryProtectionPolicy (MemoryType
, EfiConventionalMemory
, Memory
,
1487 EFI_PAGES_TO_SIZE (NumberOfPages
));
1493 This function checks to see if the last memory map descriptor in a memory map
1494 can be merged with any of the other memory map descriptors in a memorymap.
1495 Memory descriptors may be merged if they are adjacent and have the same type
1498 @param MemoryMap A pointer to the start of the memory map.
1499 @param MemoryMapDescriptor A pointer to the last descriptor in MemoryMap.
1500 @param DescriptorSize The size, in bytes, of an individual
1501 EFI_MEMORY_DESCRIPTOR.
1503 @return A pointer to the next available descriptor in MemoryMap
1506 EFI_MEMORY_DESCRIPTOR
*
1507 MergeMemoryMapDescriptor (
1508 IN EFI_MEMORY_DESCRIPTOR
*MemoryMap
,
1509 IN EFI_MEMORY_DESCRIPTOR
*MemoryMapDescriptor
,
1510 IN UINTN DescriptorSize
1514 // Traverse the array of descriptors in MemoryMap
1516 for (; MemoryMap
!= MemoryMapDescriptor
; MemoryMap
= NEXT_MEMORY_DESCRIPTOR (MemoryMap
, DescriptorSize
)) {
1518 // Check to see if the Type fields are identical.
1520 if (MemoryMap
->Type
!= MemoryMapDescriptor
->Type
) {
1525 // Check to see if the Attribute fields are identical.
1527 if (MemoryMap
->Attribute
!= MemoryMapDescriptor
->Attribute
) {
1532 // Check to see if MemoryMapDescriptor is immediately above MemoryMap
1534 if (MemoryMap
->PhysicalStart
+ EFI_PAGES_TO_SIZE ((UINTN
)MemoryMap
->NumberOfPages
) == MemoryMapDescriptor
->PhysicalStart
) {
1536 // Merge MemoryMapDescriptor into MemoryMap
1538 MemoryMap
->NumberOfPages
+= MemoryMapDescriptor
->NumberOfPages
;
1541 // Return MemoryMapDescriptor as the next available slot int he MemoryMap array
1543 return MemoryMapDescriptor
;
1547 // Check to see if MemoryMapDescriptor is immediately below MemoryMap
1549 if (MemoryMap
->PhysicalStart
- EFI_PAGES_TO_SIZE ((UINTN
)MemoryMapDescriptor
->NumberOfPages
) == MemoryMapDescriptor
->PhysicalStart
) {
1551 // Merge MemoryMapDescriptor into MemoryMap
1553 MemoryMap
->PhysicalStart
= MemoryMapDescriptor
->PhysicalStart
;
1554 MemoryMap
->VirtualStart
= MemoryMapDescriptor
->VirtualStart
;
1555 MemoryMap
->NumberOfPages
+= MemoryMapDescriptor
->NumberOfPages
;
1558 // Return MemoryMapDescriptor as the next available slot int he MemoryMap array
1560 return MemoryMapDescriptor
;
1565 // MemoryMapDescrtiptor could not be merged with any descriptors in MemoryMap.
1567 // Return the slot immediately after MemoryMapDescriptor as the next available
1568 // slot in the MemoryMap array
1570 return NEXT_MEMORY_DESCRIPTOR (MemoryMapDescriptor
, DescriptorSize
);
1574 This function returns a copy of the current memory map. The map is an array of
1575 memory descriptors, each of which describes a contiguous block of memory.
1577 @param MemoryMapSize A pointer to the size, in bytes, of the
1578 MemoryMap buffer. On input, this is the size of
1579 the buffer allocated by the caller. On output,
1580 it is the size of the buffer returned by the
1581 firmware if the buffer was large enough, or the
1582 size of the buffer needed to contain the map if
1583 the buffer was too small.
1584 @param MemoryMap A pointer to the buffer in which firmware places
1585 the current memory map.
1586 @param MapKey A pointer to the location in which firmware
1587 returns the key for the current memory map.
1588 @param DescriptorSize A pointer to the location in which firmware
1589 returns the size, in bytes, of an individual
1590 EFI_MEMORY_DESCRIPTOR.
1591 @param DescriptorVersion A pointer to the location in which firmware
1592 returns the version number associated with the
1593 EFI_MEMORY_DESCRIPTOR.
1595 @retval EFI_SUCCESS The memory map was returned in the MemoryMap
1597 @retval EFI_BUFFER_TOO_SMALL The MemoryMap buffer was too small. The current
1598 buffer size needed to hold the memory map is
1599 returned in MemoryMapSize.
1600 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
1606 IN OUT UINTN
*MemoryMapSize
,
1607 IN OUT EFI_MEMORY_DESCRIPTOR
*MemoryMap
,
1609 OUT UINTN
*DescriptorSize
,
1610 OUT UINT32
*DescriptorVersion
1616 UINTN NumberOfEntries
;
1619 EFI_GCD_MAP_ENTRY
*GcdMapEntry
;
1620 EFI_GCD_MAP_ENTRY MergeGcdMapEntry
;
1621 EFI_MEMORY_TYPE Type
;
1622 EFI_MEMORY_DESCRIPTOR
*MemoryMapStart
;
1625 // Make sure the parameters are valid
1627 if (MemoryMapSize
== NULL
) {
1628 return EFI_INVALID_PARAMETER
;
1631 CoreAcquireGcdMemoryLock ();
1634 // Count the number of Reserved and runtime MMIO entries
1635 // And, count the number of Persistent entries.
1637 NumberOfEntries
= 0;
1638 for (Link
= mGcdMemorySpaceMap
.ForwardLink
; Link
!= &mGcdMemorySpaceMap
; Link
= Link
->ForwardLink
) {
1639 GcdMapEntry
= CR (Link
, EFI_GCD_MAP_ENTRY
, Link
, EFI_GCD_MAP_SIGNATURE
);
1640 if ((GcdMapEntry
->GcdMemoryType
== EfiGcdMemoryTypePersistent
) ||
1641 (GcdMapEntry
->GcdMemoryType
== EfiGcdMemoryTypeReserved
) ||
1642 ((GcdMapEntry
->GcdMemoryType
== EfiGcdMemoryTypeMemoryMappedIo
) &&
1643 ((GcdMapEntry
->Attributes
& EFI_MEMORY_RUNTIME
) == EFI_MEMORY_RUNTIME
))) {
1648 Size
= sizeof (EFI_MEMORY_DESCRIPTOR
);
1651 // Make sure Size != sizeof(EFI_MEMORY_DESCRIPTOR). This will
1652 // prevent people from having pointer math bugs in their code.
1653 // now you have to use *DescriptorSize to make things work.
1655 Size
+= sizeof(UINT64
) - (Size
% sizeof (UINT64
));
1657 if (DescriptorSize
!= NULL
) {
1658 *DescriptorSize
= Size
;
1661 if (DescriptorVersion
!= NULL
) {
1662 *DescriptorVersion
= EFI_MEMORY_DESCRIPTOR_VERSION
;
1665 CoreAcquireMemoryLock ();
1668 // Compute the buffer size needed to fit the entire map
1670 BufferSize
= Size
* NumberOfEntries
;
1671 for (Link
= gMemoryMap
.ForwardLink
; Link
!= &gMemoryMap
; Link
= Link
->ForwardLink
) {
1675 if (*MemoryMapSize
< BufferSize
) {
1676 Status
= EFI_BUFFER_TOO_SMALL
;
1680 if (MemoryMap
== NULL
) {
1681 Status
= EFI_INVALID_PARAMETER
;
1688 ZeroMem (MemoryMap
, BufferSize
);
1689 MemoryMapStart
= MemoryMap
;
1690 for (Link
= gMemoryMap
.ForwardLink
; Link
!= &gMemoryMap
; Link
= Link
->ForwardLink
) {
1691 Entry
= CR (Link
, MEMORY_MAP
, Link
, MEMORY_MAP_SIGNATURE
);
1692 ASSERT (Entry
->VirtualStart
== 0);
1695 // Convert internal map into an EFI_MEMORY_DESCRIPTOR
1697 MemoryMap
->Type
= Entry
->Type
;
1698 MemoryMap
->PhysicalStart
= Entry
->Start
;
1699 MemoryMap
->VirtualStart
= Entry
->VirtualStart
;
1700 MemoryMap
->NumberOfPages
= RShiftU64 (Entry
->End
- Entry
->Start
+ 1, EFI_PAGE_SHIFT
);
1702 // If the memory type is EfiConventionalMemory, then determine if the range is part of a
1703 // memory type bin and needs to be converted to the same memory type as the rest of the
1704 // memory type bin in order to minimize EFI Memory Map changes across reboots. This
1705 // improves the chances for a successful S4 resume in the presence of minor page allocation
1706 // differences across reboots.
1708 if (MemoryMap
->Type
== EfiConventionalMemory
) {
1709 for (Type
= (EFI_MEMORY_TYPE
) 0; Type
< EfiMaxMemoryType
; Type
++) {
1710 if (mMemoryTypeStatistics
[Type
].Special
&&
1711 mMemoryTypeStatistics
[Type
].NumberOfPages
> 0 &&
1712 Entry
->Start
>= mMemoryTypeStatistics
[Type
].BaseAddress
&&
1713 Entry
->End
<= mMemoryTypeStatistics
[Type
].MaximumAddress
) {
1714 MemoryMap
->Type
= Type
;
1718 MemoryMap
->Attribute
= Entry
->Attribute
;
1719 if (MemoryMap
->Type
< EfiMaxMemoryType
) {
1720 if (mMemoryTypeStatistics
[MemoryMap
->Type
].Runtime
) {
1721 MemoryMap
->Attribute
|= EFI_MEMORY_RUNTIME
;
1726 // Check to see if the new Memory Map Descriptor can be merged with an
1727 // existing descriptor if they are adjacent and have the same attributes
1729 MemoryMap
= MergeMemoryMapDescriptor (MemoryMapStart
, MemoryMap
, Size
);
1733 ZeroMem (&MergeGcdMapEntry
, sizeof (MergeGcdMapEntry
));
1735 for (Link
= mGcdMemorySpaceMap
.ForwardLink
; ; Link
= Link
->ForwardLink
) {
1736 if (Link
!= &mGcdMemorySpaceMap
) {
1738 // Merge adjacent same type and attribute GCD memory range
1740 GcdMapEntry
= CR (Link
, EFI_GCD_MAP_ENTRY
, Link
, EFI_GCD_MAP_SIGNATURE
);
1742 if ((MergeGcdMapEntry
.Capabilities
== GcdMapEntry
->Capabilities
) &&
1743 (MergeGcdMapEntry
.Attributes
== GcdMapEntry
->Attributes
) &&
1744 (MergeGcdMapEntry
.GcdMemoryType
== GcdMapEntry
->GcdMemoryType
) &&
1745 (MergeGcdMapEntry
.GcdIoType
== GcdMapEntry
->GcdIoType
)) {
1746 MergeGcdMapEntry
.EndAddress
= GcdMapEntry
->EndAddress
;
1751 if ((MergeGcdMapEntry
.GcdMemoryType
== EfiGcdMemoryTypeReserved
) ||
1752 ((MergeGcdMapEntry
.GcdMemoryType
== EfiGcdMemoryTypeMemoryMappedIo
) &&
1753 ((MergeGcdMapEntry
.Attributes
& EFI_MEMORY_RUNTIME
) == EFI_MEMORY_RUNTIME
))) {
1755 // Page Align GCD range is required. When it is converted to EFI_MEMORY_DESCRIPTOR,
1756 // it will be recorded as page PhysicalStart and NumberOfPages.
1758 ASSERT ((MergeGcdMapEntry
.BaseAddress
& EFI_PAGE_MASK
) == 0);
1759 ASSERT (((MergeGcdMapEntry
.EndAddress
- MergeGcdMapEntry
.BaseAddress
+ 1) & EFI_PAGE_MASK
) == 0);
1762 // Create EFI_MEMORY_DESCRIPTOR for every Reserved and runtime MMIO GCD entries
1764 MemoryMap
->PhysicalStart
= MergeGcdMapEntry
.BaseAddress
;
1765 MemoryMap
->VirtualStart
= 0;
1766 MemoryMap
->NumberOfPages
= RShiftU64 ((MergeGcdMapEntry
.EndAddress
- MergeGcdMapEntry
.BaseAddress
+ 1), EFI_PAGE_SHIFT
);
1767 MemoryMap
->Attribute
= (MergeGcdMapEntry
.Attributes
& ~EFI_MEMORY_PORT_IO
) |
1768 (MergeGcdMapEntry
.Capabilities
& (EFI_MEMORY_RP
| EFI_MEMORY_WP
| EFI_MEMORY_XP
| EFI_MEMORY_RO
|
1769 EFI_MEMORY_UC
| EFI_MEMORY_UCE
| EFI_MEMORY_WC
| EFI_MEMORY_WT
| EFI_MEMORY_WB
));
1771 if (MergeGcdMapEntry
.GcdMemoryType
== EfiGcdMemoryTypeReserved
) {
1772 MemoryMap
->Type
= EfiReservedMemoryType
;
1773 } else if (MergeGcdMapEntry
.GcdMemoryType
== EfiGcdMemoryTypeMemoryMappedIo
) {
1774 if ((MergeGcdMapEntry
.Attributes
& EFI_MEMORY_PORT_IO
) == EFI_MEMORY_PORT_IO
) {
1775 MemoryMap
->Type
= EfiMemoryMappedIOPortSpace
;
1777 MemoryMap
->Type
= EfiMemoryMappedIO
;
1782 // Check to see if the new Memory Map Descriptor can be merged with an
1783 // existing descriptor if they are adjacent and have the same attributes
1785 MemoryMap
= MergeMemoryMapDescriptor (MemoryMapStart
, MemoryMap
, Size
);
1788 if (MergeGcdMapEntry
.GcdMemoryType
== EfiGcdMemoryTypePersistent
) {
1790 // Page Align GCD range is required. When it is converted to EFI_MEMORY_DESCRIPTOR,
1791 // it will be recorded as page PhysicalStart and NumberOfPages.
1793 ASSERT ((MergeGcdMapEntry
.BaseAddress
& EFI_PAGE_MASK
) == 0);
1794 ASSERT (((MergeGcdMapEntry
.EndAddress
- MergeGcdMapEntry
.BaseAddress
+ 1) & EFI_PAGE_MASK
) == 0);
1797 // Create EFI_MEMORY_DESCRIPTOR for every Persistent GCD entries
1799 MemoryMap
->PhysicalStart
= MergeGcdMapEntry
.BaseAddress
;
1800 MemoryMap
->VirtualStart
= 0;
1801 MemoryMap
->NumberOfPages
= RShiftU64 ((MergeGcdMapEntry
.EndAddress
- MergeGcdMapEntry
.BaseAddress
+ 1), EFI_PAGE_SHIFT
);
1802 MemoryMap
->Attribute
= MergeGcdMapEntry
.Attributes
| EFI_MEMORY_NV
|
1803 (MergeGcdMapEntry
.Capabilities
& (EFI_MEMORY_RP
| EFI_MEMORY_WP
| EFI_MEMORY_XP
| EFI_MEMORY_RO
|
1804 EFI_MEMORY_UC
| EFI_MEMORY_UCE
| EFI_MEMORY_WC
| EFI_MEMORY_WT
| EFI_MEMORY_WB
));
1805 MemoryMap
->Type
= EfiPersistentMemory
;
1808 // Check to see if the new Memory Map Descriptor can be merged with an
1809 // existing descriptor if they are adjacent and have the same attributes
1811 MemoryMap
= MergeMemoryMapDescriptor (MemoryMapStart
, MemoryMap
, Size
);
1813 if (Link
== &mGcdMemorySpaceMap
) {
1815 // break loop when arrive at head.
1819 if (GcdMapEntry
!= NULL
) {
1821 // Copy new GCD map entry for the following GCD range merge
1823 CopyMem (&MergeGcdMapEntry
, GcdMapEntry
, sizeof (MergeGcdMapEntry
));
1828 // Compute the size of the buffer actually used after all memory map descriptor merge operations
1830 BufferSize
= ((UINT8
*)MemoryMap
- (UINT8
*)MemoryMapStart
);
1832 Status
= EFI_SUCCESS
;
1836 // Update the map key finally
1838 if (MapKey
!= NULL
) {
1839 *MapKey
= mMemoryMapKey
;
1842 CoreReleaseMemoryLock ();
1844 CoreReleaseGcdMemoryLock ();
1846 *MemoryMapSize
= BufferSize
;
1853 Internal function. Used by the pool functions to allocate pages
1854 to back pool allocation requests.
1856 @param PoolType The type of memory for the new pool pages
1857 @param NumberOfPages No of pages to allocate
1858 @param Alignment Bits to align.
1860 @return The allocated memory, or NULL
1864 CoreAllocatePoolPages (
1865 IN EFI_MEMORY_TYPE PoolType
,
1866 IN UINTN NumberOfPages
,
1873 // Find the pages to convert
1875 Start
= FindFreePages (MAX_ADDRESS
, NumberOfPages
, PoolType
, Alignment
);
1878 // Convert it to boot services data
1881 DEBUG ((DEBUG_ERROR
| DEBUG_PAGE
, "AllocatePoolPages: failed to allocate %d pages\n", (UINT32
)NumberOfPages
));
1883 CoreConvertPages (Start
, NumberOfPages
, PoolType
);
1886 return (VOID
*)(UINTN
) Start
;
1891 Internal function. Frees pool pages allocated via AllocatePoolPages ()
1893 @param Memory The base address to free
1894 @param NumberOfPages The number of pages to free
1899 IN EFI_PHYSICAL_ADDRESS Memory
,
1900 IN UINTN NumberOfPages
1903 CoreConvertPages (Memory
, NumberOfPages
, EfiConventionalMemory
);
1909 Make sure the memory map is following all the construction rules,
1910 it is the last time to check memory map error before exit boot services.
1912 @param MapKey Memory map key
1914 @retval EFI_INVALID_PARAMETER Memory map not consistent with construction
1916 @retval EFI_SUCCESS Valid memory map.
1920 CoreTerminateMemoryMap (
1928 Status
= EFI_SUCCESS
;
1930 CoreAcquireMemoryLock ();
1932 if (MapKey
== mMemoryMapKey
) {
1935 // Make sure the memory map is following all the construction rules
1936 // This is the last chance we will be able to display any messages on
1937 // the console devices.
1940 for (Link
= gMemoryMap
.ForwardLink
; Link
!= &gMemoryMap
; Link
= Link
->ForwardLink
) {
1941 Entry
= CR(Link
, MEMORY_MAP
, Link
, MEMORY_MAP_SIGNATURE
);
1942 if (Entry
->Type
< EfiMaxMemoryType
) {
1943 if (mMemoryTypeStatistics
[Entry
->Type
].Runtime
) {
1944 ASSERT (Entry
->Type
!= EfiACPIReclaimMemory
);
1945 ASSERT (Entry
->Type
!= EfiACPIMemoryNVS
);
1946 if ((Entry
->Start
& (RUNTIME_PAGE_ALLOCATION_GRANULARITY
- 1)) != 0) {
1947 DEBUG((DEBUG_ERROR
| DEBUG_PAGE
, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n"));
1948 Status
= EFI_INVALID_PARAMETER
;
1951 if (((Entry
->End
+ 1) & (RUNTIME_PAGE_ALLOCATION_GRANULARITY
- 1)) != 0) {
1952 DEBUG((DEBUG_ERROR
| DEBUG_PAGE
, "ExitBootServices: A RUNTIME memory entry is not on a proper alignment.\n"));
1953 Status
= EFI_INVALID_PARAMETER
;
1961 // The map key they gave us matches what we expect. Fall through and
1962 // return success. In an ideal world we would clear out all of
1963 // EfiBootServicesCode and EfiBootServicesData. However this function
1964 // is not the last one called by ExitBootServices(), so we have to
1965 // preserve the memory contents.
1968 Status
= EFI_INVALID_PARAMETER
;
1972 CoreReleaseMemoryLock ();