2 Capsule update PEIM for UEFI2.0
4 Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
5 Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
7 SPDX-License-Identifier: BSD-2-Clause-Patent
13 #define DEFAULT_SG_LIST_HEADS (20)
17 // Global Descriptor Table (GDT)
19 GLOBAL_REMOVE_IF_UNREFERENCED IA32_SEGMENT_DESCRIPTOR mGdtEntries
[] = {
20 /* selector { Global Segment Descriptor } */
22 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
25 { 0xffff, 0, 0, 0x3, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 }
26 }, // linear data segment descriptor
28 { 0xffff, 0, 0, 0xf, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 }
29 }, // linear code segment descriptor
31 { 0xffff, 0, 0, 0x3, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 }
32 }, // system data segment descriptor
34 { 0xffff, 0, 0, 0xb, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 }
35 }, // system code segment descriptor
37 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
38 }, // spare segment descriptor
40 { 0xffff, 0, 0, 0x3, 1, 0, 1, 0xf, 0, 0, 1, 1, 0 }
41 }, // system data segment descriptor
43 { 0xffff, 0, 0, 0xb, 1, 0, 1, 0xf, 0, 1, 0, 1, 0 }
44 }, // system code segment descriptor
46 { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
47 }, // spare segment descriptor
53 GLOBAL_REMOVE_IF_UNREFERENCED CONST IA32_DESCRIPTOR mGdt
= {
54 sizeof (mGdtEntries
) - 1,
59 The function will check if 1G page is supported.
61 @retval TRUE 1G page is supported.
62 @retval FALSE 1G page is not supported.
72 BOOLEAN Page1GSupport
;
74 Page1GSupport
= FALSE
;
75 if (PcdGetBool (PcdUse1GPageTable
)) {
76 AsmCpuid (0x80000000, &RegEax
, NULL
, NULL
, NULL
);
77 if (RegEax
>= 0x80000001) {
78 AsmCpuid (0x80000001, NULL
, NULL
, NULL
, &RegEdx
);
79 if ((RegEdx
& BIT26
) != 0) {
89 Calculate the total size of page table.
91 @param[in] Page1GSupport 1G page support or not.
93 @return The size of page table.
97 CalculatePageTableSize (
98 IN BOOLEAN Page1GSupport
101 UINTN ExtraPageTablePages
;
103 UINT8 PhysicalAddressBits
;
104 UINT32 NumberOfPml4EntriesNeeded
;
105 UINT32 NumberOfPdpEntriesNeeded
;
108 // Create 4G page table by default,
109 // and let PF handler to handle > 4G request.
111 PhysicalAddressBits
= 32;
112 ExtraPageTablePages
= EXTRA_PAGE_TABLE_PAGES
;
115 // Calculate the table entries needed.
117 if (PhysicalAddressBits
<= 39 ) {
118 NumberOfPml4EntriesNeeded
= 1;
119 NumberOfPdpEntriesNeeded
= (UINT32
)LShiftU64 (1, (PhysicalAddressBits
- 30));
121 NumberOfPml4EntriesNeeded
= (UINT32
)LShiftU64 (1, (PhysicalAddressBits
- 39));
122 NumberOfPdpEntriesNeeded
= 512;
125 if (!Page1GSupport
) {
126 TotalPagesNum
= (NumberOfPdpEntriesNeeded
+ 1) * NumberOfPml4EntriesNeeded
+ 1;
128 TotalPagesNum
= NumberOfPml4EntriesNeeded
+ 1;
131 TotalPagesNum
+= ExtraPageTablePages
;
133 return EFI_PAGES_TO_SIZE (TotalPagesNum
);
137 Allocates and fills in the Page Directory and Page Table Entries to
138 establish a 4G page table.
140 @param[in] PageTablesAddress The base address of page table.
141 @param[in] Page1GSupport 1G page support or not.
146 IN EFI_PHYSICAL_ADDRESS PageTablesAddress
,
147 IN BOOLEAN Page1GSupport
150 UINT8 PhysicalAddressBits
;
151 EFI_PHYSICAL_ADDRESS PageAddress
;
152 UINTN IndexOfPml4Entries
;
153 UINTN IndexOfPdpEntries
;
154 UINTN IndexOfPageDirectoryEntries
;
155 UINT32 NumberOfPml4EntriesNeeded
;
156 UINT32 NumberOfPdpEntriesNeeded
;
157 PAGE_MAP_AND_DIRECTORY_POINTER
*PageMapLevel4Entry
;
158 PAGE_MAP_AND_DIRECTORY_POINTER
*PageMap
;
159 PAGE_MAP_AND_DIRECTORY_POINTER
*PageDirectoryPointerEntry
;
160 PAGE_TABLE_ENTRY
*PageDirectoryEntry
;
161 UINTN BigPageAddress
;
162 PAGE_TABLE_1G_ENTRY
*PageDirectory1GEntry
;
163 UINT64 AddressEncMask
;
166 // Make sure AddressEncMask is contained to smallest supported address field.
168 AddressEncMask
= PcdGet64 (PcdPteMemoryEncryptionAddressOrMask
) & PAGING_1G_ADDRESS_MASK_64
;
171 // Create 4G page table by default,
172 // and let PF handler to handle > 4G request.
174 PhysicalAddressBits
= 32;
177 // Calculate the table entries needed.
179 if (PhysicalAddressBits
<= 39 ) {
180 NumberOfPml4EntriesNeeded
= 1;
181 NumberOfPdpEntriesNeeded
= (UINT32
)LShiftU64 (1, (PhysicalAddressBits
- 30));
183 NumberOfPml4EntriesNeeded
= (UINT32
)LShiftU64 (1, (PhysicalAddressBits
- 39));
184 NumberOfPdpEntriesNeeded
= 512;
188 // Pre-allocate big pages to avoid later allocations.
190 BigPageAddress
= (UINTN
)PageTablesAddress
;
193 // By architecture only one PageMapLevel4 exists - so lets allocate storage for it.
195 PageMap
= (VOID
*)BigPageAddress
;
196 BigPageAddress
+= SIZE_4KB
;
198 PageMapLevel4Entry
= PageMap
;
200 for (IndexOfPml4Entries
= 0; IndexOfPml4Entries
< NumberOfPml4EntriesNeeded
; IndexOfPml4Entries
++, PageMapLevel4Entry
++) {
202 // Each PML4 entry points to a page of Page Directory Pointer entires.
203 // So lets allocate space for them and fill them in in the IndexOfPdpEntries loop.
205 PageDirectoryPointerEntry
= (VOID
*)BigPageAddress
;
206 BigPageAddress
+= SIZE_4KB
;
211 PageMapLevel4Entry
->Uint64
= (UINT64
)(UINTN
)PageDirectoryPointerEntry
| AddressEncMask
;
212 PageMapLevel4Entry
->Bits
.ReadWrite
= 1;
213 PageMapLevel4Entry
->Bits
.Present
= 1;
216 PageDirectory1GEntry
= (VOID
*)PageDirectoryPointerEntry
;
218 for (IndexOfPageDirectoryEntries
= 0; IndexOfPageDirectoryEntries
< 512; IndexOfPageDirectoryEntries
++, PageDirectory1GEntry
++, PageAddress
+= SIZE_1GB
) {
220 // Fill in the Page Directory entries
222 PageDirectory1GEntry
->Uint64
= (UINT64
)PageAddress
| AddressEncMask
;
223 PageDirectory1GEntry
->Bits
.ReadWrite
= 1;
224 PageDirectory1GEntry
->Bits
.Present
= 1;
225 PageDirectory1GEntry
->Bits
.MustBe1
= 1;
228 for (IndexOfPdpEntries
= 0; IndexOfPdpEntries
< NumberOfPdpEntriesNeeded
; IndexOfPdpEntries
++, PageDirectoryPointerEntry
++) {
230 // Each Directory Pointer entries points to a page of Page Directory entires.
231 // So allocate space for them and fill them in in the IndexOfPageDirectoryEntries loop.
233 PageDirectoryEntry
= (VOID
*)BigPageAddress
;
234 BigPageAddress
+= SIZE_4KB
;
237 // Fill in a Page Directory Pointer Entries
239 PageDirectoryPointerEntry
->Uint64
= (UINT64
)(UINTN
)PageDirectoryEntry
| AddressEncMask
;
240 PageDirectoryPointerEntry
->Bits
.ReadWrite
= 1;
241 PageDirectoryPointerEntry
->Bits
.Present
= 1;
243 for (IndexOfPageDirectoryEntries
= 0; IndexOfPageDirectoryEntries
< 512; IndexOfPageDirectoryEntries
++, PageDirectoryEntry
++, PageAddress
+= SIZE_2MB
) {
245 // Fill in the Page Directory entries
247 PageDirectoryEntry
->Uint64
= (UINT64
)PageAddress
| AddressEncMask
;
248 PageDirectoryEntry
->Bits
.ReadWrite
= 1;
249 PageDirectoryEntry
->Bits
.Present
= 1;
250 PageDirectoryEntry
->Bits
.MustBe1
= 1;
254 for ( ; IndexOfPdpEntries
< 512; IndexOfPdpEntries
++, PageDirectoryPointerEntry
++) {
256 PageDirectoryPointerEntry
,
257 sizeof (PAGE_MAP_AND_DIRECTORY_POINTER
)
264 // For the PML4 entries we are not using fill in a null entry.
266 for ( ; IndexOfPml4Entries
< 512; IndexOfPml4Entries
++, PageMapLevel4Entry
++) {
269 sizeof (PAGE_MAP_AND_DIRECTORY_POINTER
)
275 Return function from long mode to 32-bit mode.
277 @param EntrypointContext Context for mode switching
278 @param ReturnContext Context for mode switching
283 SWITCH_32_TO_64_CONTEXT
*EntrypointContext
,
284 SWITCH_64_TO_32_CONTEXT
*ReturnContext
288 // Restore original GDT
290 AsmWriteGdtr (&ReturnContext
->Gdtr
);
293 // return to original caller
295 LongJump ((BASE_LIBRARY_JUMP_BUFFER
*)(UINTN
)EntrypointContext
->JumpBuffer
, 1);
304 Thunk function from 32-bit protection mode to long mode.
306 @param PageTableAddress Page table base address
307 @param Context Context for mode switching
308 @param ReturnContext Context for mode switching
310 @retval EFI_SUCCESS Function successfully executed.
315 EFI_PHYSICAL_ADDRESS PageTableAddress
,
316 SWITCH_32_TO_64_CONTEXT
*Context
,
317 SWITCH_64_TO_32_CONTEXT
*ReturnContext
324 // Save return address, LongJump will return here then
326 SetJumpFlag
= SetJump ((BASE_LIBRARY_JUMP_BUFFER
*)(UINTN
)Context
->JumpBuffer
);
328 if (SetJumpFlag
== 0) {
330 // Build 4G Page Tables.
332 Create4GPageTables (PageTableAddress
, Context
->Page1GSupport
);
337 AsmWriteGdtr (&mGdt
);
342 AsmWriteCr3 ((UINTN
)PageTableAddress
);
346 "%a() Stack Base: 0x%lx, Stack Size: 0x%lx\n",
348 Context
->StackBufferBase
,
349 Context
->StackBufferLength
353 // Disable interrupt of Debug timer, since the IDT table cannot work in long mode
355 SaveAndSetDebugTimerInterrupt (FALSE
);
357 // Transfer to long mode
361 (UINT64
)Context
->EntryPoint
,
362 (UINT64
)(UINTN
)Context
,
363 (UINT64
)(UINTN
)ReturnContext
,
364 Context
->StackBufferBase
+ Context
->StackBufferLength
369 // Convert to 32-bit Status and return
371 Status
= EFI_SUCCESS
;
372 if ((UINTN
)ReturnContext
->ReturnStatus
!= 0) {
373 Status
= ENCODE_ERROR ((UINTN
)ReturnContext
->ReturnStatus
);
380 If in 32 bit protection mode, and coalesce image is of X64, switch to long mode.
382 @param LongModeBuffer The context of long mode.
383 @param CoalesceEntry Entry of coalesce image.
384 @param BlockListAddr Address of block list.
385 @param MemoryResource Pointer to the buffer of memory resource descriptor.
386 @param MemoryBase Base of memory range.
387 @param MemorySize Size of memory range.
389 @retval EFI_SUCCESS Successfully switched to long mode and execute coalesce.
390 @retval Others Failed to execute coalesce in long mode.
395 IN EFI_CAPSULE_LONG_MODE_BUFFER
*LongModeBuffer
,
396 IN COALESCE_ENTRY CoalesceEntry
,
397 IN EFI_PHYSICAL_ADDRESS BlockListAddr
,
398 IN MEMORY_RESOURCE_DESCRIPTOR
*MemoryResource
,
399 IN OUT VOID
**MemoryBase
,
400 IN OUT UINTN
*MemorySize
404 EFI_PHYSICAL_ADDRESS MemoryBase64
;
406 EFI_PHYSICAL_ADDRESS MemoryEnd64
;
407 SWITCH_32_TO_64_CONTEXT Context
;
408 SWITCH_64_TO_32_CONTEXT ReturnContext
;
409 BASE_LIBRARY_JUMP_BUFFER JumpBuffer
;
410 EFI_PHYSICAL_ADDRESS ReservedRangeBase
;
411 EFI_PHYSICAL_ADDRESS ReservedRangeEnd
;
412 BOOLEAN Page1GSupport
;
414 ZeroMem (&Context
, sizeof (SWITCH_32_TO_64_CONTEXT
));
415 ZeroMem (&ReturnContext
, sizeof (SWITCH_64_TO_32_CONTEXT
));
417 MemoryBase64
= (UINT64
)(UINTN
)*MemoryBase
;
418 MemorySize64
= (UINT64
)(UINTN
)*MemorySize
;
419 MemoryEnd64
= MemoryBase64
+ MemorySize64
;
421 Page1GSupport
= IsPage1GSupport ();
424 // Merge memory range reserved for stack and page table
426 if (LongModeBuffer
->StackBaseAddress
< LongModeBuffer
->PageTableAddress
) {
427 ReservedRangeBase
= LongModeBuffer
->StackBaseAddress
;
428 ReservedRangeEnd
= LongModeBuffer
->PageTableAddress
+ CalculatePageTableSize (Page1GSupport
);
430 ReservedRangeBase
= LongModeBuffer
->PageTableAddress
;
431 ReservedRangeEnd
= LongModeBuffer
->StackBaseAddress
+ LongModeBuffer
->StackSize
;
435 // Check if memory range reserved is overlap with MemoryBase ~ MemoryBase + MemorySize.
436 // If they are overlapped, get a larger range to process capsule data.
438 if (ReservedRangeBase
<= MemoryBase64
) {
439 if (ReservedRangeEnd
< MemoryEnd64
) {
440 MemoryBase64
= ReservedRangeEnd
;
442 DEBUG ((DEBUG_ERROR
, "Memory is not enough to process capsule!\n"));
443 return EFI_OUT_OF_RESOURCES
;
445 } else if (ReservedRangeBase
< MemoryEnd64
) {
446 if ((ReservedRangeEnd
< MemoryEnd64
) &&
447 (ReservedRangeBase
- MemoryBase64
< MemoryEnd64
- ReservedRangeEnd
))
449 MemoryBase64
= ReservedRangeEnd
;
451 MemorySize64
= (UINT64
)(UINTN
)(ReservedRangeBase
- MemoryBase64
);
456 // Initialize context jumping to 64-bit enviroment
458 Context
.JumpBuffer
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)&JumpBuffer
;
459 Context
.StackBufferBase
= LongModeBuffer
->StackBaseAddress
;
460 Context
.StackBufferLength
= LongModeBuffer
->StackSize
;
461 Context
.EntryPoint
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)CoalesceEntry
;
462 Context
.BlockListAddr
= BlockListAddr
;
463 Context
.MemoryResource
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)MemoryResource
;
464 Context
.MemoryBase64Ptr
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)&MemoryBase64
;
465 Context
.MemorySize64Ptr
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)&MemorySize64
;
466 Context
.Page1GSupport
= Page1GSupport
;
467 Context
.AddressEncMask
= PcdGet64 (PcdPteMemoryEncryptionAddressOrMask
) & PAGING_1G_ADDRESS_MASK_64
;
470 // Prepare data for return back
472 ReturnContext
.ReturnCs
= 0x10;
473 ReturnContext
.ReturnEntryPoint
= (EFI_PHYSICAL_ADDRESS
)(UINTN
)ReturnFunction
;
475 // Will save the return status of processing capsule
477 ReturnContext
.ReturnStatus
= 0;
482 AsmReadGdtr ((IA32_DESCRIPTOR
*)&ReturnContext
.Gdtr
);
484 Status
= Thunk32To64 (LongModeBuffer
->PageTableAddress
, &Context
, &ReturnContext
);
486 if (!EFI_ERROR (Status
)) {
487 *MemoryBase
= (VOID
*)(UINTN
)MemoryBase64
;
488 *MemorySize
= (UINTN
)MemorySize64
;
495 Locates the coalesce image entry point, and detects its machine type.
497 @param CoalesceImageEntryPoint Pointer to coalesce image entry point for output.
498 @param CoalesceImageMachineType Pointer to machine type of coalesce image.
500 @retval EFI_SUCCESS Coalesce image successfully located.
501 @retval Others Failed to locate the coalesce image.
505 FindCapsuleCoalesceImage (
506 OUT EFI_PHYSICAL_ADDRESS
*CoalesceImageEntryPoint
,
507 OUT UINT16
*CoalesceImageMachineType
512 EFI_PEI_LOAD_FILE_PPI
*LoadFile
;
513 EFI_PEI_FV_HANDLE VolumeHandle
;
514 EFI_PEI_FILE_HANDLE FileHandle
;
515 EFI_PHYSICAL_ADDRESS CoalesceImageAddress
;
516 UINT64 CoalesceImageSize
;
517 UINT32 AuthenticationState
;
522 Status
= PeiServicesFfsFindNextVolume (Instance
++, &VolumeHandle
);
523 if (EFI_ERROR (Status
)) {
527 Status
= PeiServicesFfsFindFileByName (PcdGetPtr (PcdCapsuleCoalesceFile
), VolumeHandle
, &FileHandle
);
528 if (!EFI_ERROR (Status
)) {
529 Status
= PeiServicesLocatePpi (&gEfiPeiLoadFilePpiGuid
, 0, NULL
, (VOID
**)&LoadFile
);
530 ASSERT_EFI_ERROR (Status
);
532 Status
= LoadFile
->LoadFile (
535 &CoalesceImageAddress
,
537 CoalesceImageEntryPoint
,
540 if (EFI_ERROR (Status
)) {
541 DEBUG ((DEBUG_ERROR
, "Unable to find PE32 section in CapsuleX64 image ffs %r!\n", Status
));
545 *CoalesceImageMachineType
= PeCoffLoaderGetMachineType ((VOID
*)(UINTN
)CoalesceImageAddress
);
556 Gets the reserved long mode buffer.
558 @param LongModeBuffer Pointer to the long mode buffer for output.
560 @retval EFI_SUCCESS Long mode buffer successfully retrieved.
561 @retval Others Variable storing long mode buffer not found.
566 OUT EFI_CAPSULE_LONG_MODE_BUFFER
*LongModeBuffer
571 EFI_PEI_READ_ONLY_VARIABLE2_PPI
*PPIVariableServices
;
573 Status
= PeiServicesLocatePpi (
574 &gEfiPeiReadOnlyVariable2PpiGuid
,
577 (VOID
**)&PPIVariableServices
579 ASSERT_EFI_ERROR (Status
);
581 Size
= sizeof (EFI_CAPSULE_LONG_MODE_BUFFER
);
582 Status
= PPIVariableServices
->GetVariable (
584 EFI_CAPSULE_LONG_MODE_BUFFER_NAME
,
585 &gEfiCapsuleVendorGuid
,
590 if (EFI_ERROR (Status
)) {
591 DEBUG ((DEBUG_ERROR
, "Error Get LongModeBuffer variable %r!\n", Status
));
599 #if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64)
602 Get physical address bits.
604 @return Physical address bits.
608 GetPhysicalAddressBits (
613 UINT8 PhysicalAddressBits
;
617 // Get physical address bits supported.
619 Hob
= GetFirstHob (EFI_HOB_TYPE_CPU
);
621 PhysicalAddressBits
= ((EFI_HOB_CPU
*)Hob
)->SizeOfMemorySpace
;
623 AsmCpuid (0x80000000, &RegEax
, NULL
, NULL
, NULL
);
624 if (RegEax
>= 0x80000008) {
625 AsmCpuid (0x80000008, &RegEax
, NULL
, NULL
, NULL
);
626 PhysicalAddressBits
= (UINT8
)RegEax
;
628 PhysicalAddressBits
= 36;
633 // IA-32e paging translates 48-bit linear addresses to 52-bit physical addresses.
635 ASSERT (PhysicalAddressBits
<= 52);
636 if (PhysicalAddressBits
> 48) {
637 PhysicalAddressBits
= 48;
640 return PhysicalAddressBits
;
646 Sort memory resource entries based upon PhysicalStart, from low to high.
648 @param[in, out] MemoryResource A pointer to the memory resource entry buffer.
652 SortMemoryResourceDescriptor (
653 IN OUT MEMORY_RESOURCE_DESCRIPTOR
*MemoryResource
656 MEMORY_RESOURCE_DESCRIPTOR
*MemoryResourceEntry
;
657 MEMORY_RESOURCE_DESCRIPTOR
*NextMemoryResourceEntry
;
658 MEMORY_RESOURCE_DESCRIPTOR TempMemoryResource
;
660 MemoryResourceEntry
= MemoryResource
;
661 NextMemoryResourceEntry
= MemoryResource
+ 1;
662 while (MemoryResourceEntry
->ResourceLength
!= 0) {
663 while (NextMemoryResourceEntry
->ResourceLength
!= 0) {
664 if (MemoryResourceEntry
->PhysicalStart
> NextMemoryResourceEntry
->PhysicalStart
) {
665 CopyMem (&TempMemoryResource
, MemoryResourceEntry
, sizeof (MEMORY_RESOURCE_DESCRIPTOR
));
666 CopyMem (MemoryResourceEntry
, NextMemoryResourceEntry
, sizeof (MEMORY_RESOURCE_DESCRIPTOR
));
667 CopyMem (NextMemoryResourceEntry
, &TempMemoryResource
, sizeof (MEMORY_RESOURCE_DESCRIPTOR
));
670 NextMemoryResourceEntry
= NextMemoryResourceEntry
+ 1;
673 MemoryResourceEntry
= MemoryResourceEntry
+ 1;
674 NextMemoryResourceEntry
= MemoryResourceEntry
+ 1;
679 Merge continous memory resource entries.
681 @param[in, out] MemoryResource A pointer to the memory resource entry buffer.
685 MergeMemoryResourceDescriptor (
686 IN OUT MEMORY_RESOURCE_DESCRIPTOR
*MemoryResource
689 MEMORY_RESOURCE_DESCRIPTOR
*MemoryResourceEntry
;
690 MEMORY_RESOURCE_DESCRIPTOR
*NewMemoryResourceEntry
;
691 MEMORY_RESOURCE_DESCRIPTOR
*NextMemoryResourceEntry
;
692 MEMORY_RESOURCE_DESCRIPTOR
*MemoryResourceEnd
;
694 MemoryResourceEntry
= MemoryResource
;
695 NewMemoryResourceEntry
= MemoryResource
;
696 while (MemoryResourceEntry
->ResourceLength
!= 0) {
697 CopyMem (NewMemoryResourceEntry
, MemoryResourceEntry
, sizeof (MEMORY_RESOURCE_DESCRIPTOR
));
698 NextMemoryResourceEntry
= MemoryResourceEntry
+ 1;
700 while ((NextMemoryResourceEntry
->ResourceLength
!= 0) &&
701 (NextMemoryResourceEntry
->PhysicalStart
== (MemoryResourceEntry
->PhysicalStart
+ MemoryResourceEntry
->ResourceLength
)))
703 MemoryResourceEntry
->ResourceLength
+= NextMemoryResourceEntry
->ResourceLength
;
704 if (NewMemoryResourceEntry
!= MemoryResourceEntry
) {
705 NewMemoryResourceEntry
->ResourceLength
+= NextMemoryResourceEntry
->ResourceLength
;
708 NextMemoryResourceEntry
= NextMemoryResourceEntry
+ 1;
711 MemoryResourceEntry
= NextMemoryResourceEntry
;
712 NewMemoryResourceEntry
= NewMemoryResourceEntry
+ 1;
716 // Set NULL terminate memory resource descriptor after merging.
718 MemoryResourceEnd
= NewMemoryResourceEntry
;
719 ZeroMem (MemoryResourceEnd
, sizeof (MEMORY_RESOURCE_DESCRIPTOR
));
723 Build memory resource descriptor from resource descriptor in HOB list.
725 @return Pointer to the buffer of memory resource descriptor.
726 NULL if no memory resource descriptor reported in HOB list
727 before capsule Coalesce.
730 MEMORY_RESOURCE_DESCRIPTOR
*
731 BuildMemoryResourceDescriptor (
735 EFI_PEI_HOB_POINTERS Hob
;
737 EFI_HOB_RESOURCE_DESCRIPTOR
*ResourceDescriptor
;
738 MEMORY_RESOURCE_DESCRIPTOR
*MemoryResource
;
742 // Get the count of memory resource descriptor.
745 Hob
.Raw
= GetFirstHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR
);
746 while (Hob
.Raw
!= NULL
) {
747 ResourceDescriptor
= (EFI_HOB_RESOURCE_DESCRIPTOR
*)Hob
.Raw
;
748 if (ResourceDescriptor
->ResourceType
== EFI_RESOURCE_SYSTEM_MEMORY
) {
752 Hob
.Raw
= GET_NEXT_HOB (Hob
);
753 Hob
.Raw
= GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR
, Hob
.Raw
);
757 DEBUG ((DEBUG_INFO
| DEBUG_WARN
, "No memory resource descriptor reported in HOB list before capsule Coalesce\n"));
758 #if defined (MDE_CPU_IA32) || defined (MDE_CPU_X64)
760 // Allocate memory to hold memory resource descriptor,
761 // include extra one NULL terminate memory resource descriptor.
763 Status
= PeiServicesAllocatePool ((1 + 1) * sizeof (MEMORY_RESOURCE_DESCRIPTOR
), (VOID
**)&MemoryResource
);
764 ASSERT_EFI_ERROR (Status
);
765 ZeroMem (MemoryResource
, (1 + 1) * sizeof (MEMORY_RESOURCE_DESCRIPTOR
));
767 MemoryResource
[0].PhysicalStart
= 0;
768 MemoryResource
[0].ResourceLength
= LShiftU64 (1, GetPhysicalAddressBits ());
771 "MemoryResource[0x0] - Start(0x%0lx) Length(0x%0lx)\n",
772 MemoryResource
[0x0].PhysicalStart
,
773 MemoryResource
[0x0].ResourceLength
775 return MemoryResource
;
782 // Allocate memory to hold memory resource descriptor,
783 // include extra one NULL terminate memory resource descriptor.
785 Status
= PeiServicesAllocatePool ((Index
+ 1) * sizeof (MEMORY_RESOURCE_DESCRIPTOR
), (VOID
**)&MemoryResource
);
786 ASSERT_EFI_ERROR (Status
);
787 ZeroMem (MemoryResource
, (Index
+ 1) * sizeof (MEMORY_RESOURCE_DESCRIPTOR
));
790 // Get the content of memory resource descriptor.
793 Hob
.Raw
= GetFirstHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR
);
794 while (Hob
.Raw
!= NULL
) {
795 ResourceDescriptor
= (EFI_HOB_RESOURCE_DESCRIPTOR
*)Hob
.Raw
;
796 if (ResourceDescriptor
->ResourceType
== EFI_RESOURCE_SYSTEM_MEMORY
) {
799 "MemoryResource[0x%x] - Start(0x%0lx) Length(0x%0lx)\n",
801 ResourceDescriptor
->PhysicalStart
,
802 ResourceDescriptor
->ResourceLength
804 MemoryResource
[Index
].PhysicalStart
= ResourceDescriptor
->PhysicalStart
;
805 MemoryResource
[Index
].ResourceLength
= ResourceDescriptor
->ResourceLength
;
809 Hob
.Raw
= GET_NEXT_HOB (Hob
);
810 Hob
.Raw
= GetNextHob (EFI_HOB_TYPE_RESOURCE_DESCRIPTOR
, Hob
.Raw
);
813 SortMemoryResourceDescriptor (MemoryResource
);
814 MergeMemoryResourceDescriptor (MemoryResource
);
816 DEBUG ((DEBUG_INFO
, "Dump MemoryResource[] after sorted and merged\n"));
817 for (Index
= 0; MemoryResource
[Index
].ResourceLength
!= 0; Index
++) {
820 " MemoryResource[0x%x] - Start(0x%0lx) Length(0x%0lx)\n",
822 MemoryResource
[Index
].PhysicalStart
,
823 MemoryResource
[Index
].ResourceLength
827 return MemoryResource
;
831 Check if the capsules are staged.
833 @retval TRUE The capsules are staged.
834 @retval FALSE The capsules are not staged.
844 EFI_PEI_READ_ONLY_VARIABLE2_PPI
*PPIVariableServices
;
845 EFI_PHYSICAL_ADDRESS CapsuleDataPtr64
;
847 CapsuleDataPtr64
= 0;
849 Status
= PeiServicesLocatePpi (
850 &gEfiPeiReadOnlyVariable2PpiGuid
,
853 (VOID
**)&PPIVariableServices
856 if (EFI_ERROR (Status
)) {
857 DEBUG ((DEBUG_ERROR
, "Failed to find ReadOnlyVariable2PPI\n"));
862 // Check for Update capsule
864 Size
= sizeof (CapsuleDataPtr64
);
865 Status
= PPIVariableServices
->GetVariable (
867 EFI_CAPSULE_VARIABLE_NAME
,
868 &gEfiCapsuleVendorGuid
,
871 (VOID
*)&CapsuleDataPtr64
874 if (!EFI_ERROR (Status
)) {
882 Check all the variables for SG list heads and get the count and addresses.
884 @param ListLength A pointer would return the SG list length.
885 @param HeadList A ponter to the capsule SG list.
887 @retval EFI_SUCCESS a valid capsule is present
888 @retval EFI_NOT_FOUND if a valid capsule is not present
889 @retval EFI_INVALID_PARAMETER the input parameter is invalid
890 @retval EFI_OUT_OF_RESOURCES fail to allocate memory
894 GetScatterGatherHeadEntries (
895 OUT UINTN
*ListLength
,
896 OUT EFI_PHYSICAL_ADDRESS
**HeadList
905 CHAR16 CapsuleVarName
[30];
907 EFI_PHYSICAL_ADDRESS CapsuleDataPtr64
;
908 EFI_PEI_READ_ONLY_VARIABLE2_PPI
*PPIVariableServices
;
909 EFI_PHYSICAL_ADDRESS
*TempList
;
910 EFI_PHYSICAL_ADDRESS
*EnlargedTempList
;
911 UINTN TempListLength
;
915 CapsuleVarName
[0] = 0;
917 CapsuleDataPtr64
= 0;
919 if ((ListLength
== NULL
) || (HeadList
== NULL
)) {
920 DEBUG ((DEBUG_ERROR
, "%a Invalid parameters. Inputs can't be NULL\n", __FUNCTION__
));
921 ASSERT (ListLength
!= NULL
);
922 ASSERT (HeadList
!= NULL
);
923 return EFI_INVALID_PARAMETER
;
929 Status
= PeiServicesLocatePpi (
930 &gEfiPeiReadOnlyVariable2PpiGuid
,
933 (VOID
**)&PPIVariableServices
936 if (EFI_ERROR (Status
)) {
937 DEBUG ((DEBUG_ERROR
, "Failed to find ReadOnlyVariable2PPI\n"));
942 // Allocate memory for sg list head
944 TempListLength
= DEFAULT_SG_LIST_HEADS
* sizeof (EFI_PHYSICAL_ADDRESS
);
945 TempList
= AllocateZeroPool (TempListLength
);
946 if (TempList
== NULL
) {
947 DEBUG ((DEBUG_ERROR
, "Failed to allocate memory\n"));
948 return EFI_OUT_OF_RESOURCES
;
952 // setup var name buffer for update capsules
954 StrCpyS (CapsuleVarName
, sizeof (CapsuleVarName
) / sizeof (CHAR16
), EFI_CAPSULE_VARIABLE_NAME
);
955 TempVarName
= CapsuleVarName
+ StrLen (CapsuleVarName
);
958 UnicodeValueToStringS (
960 (sizeof (CapsuleVarName
) - ((UINTN
)TempVarName
- (UINTN
)CapsuleVarName
)),
967 Size
= sizeof (CapsuleDataPtr64
);
968 Status
= PPIVariableServices
->GetVariable (
971 &gEfiCapsuleVendorGuid
,
974 (VOID
*)&CapsuleDataPtr64
977 if (EFI_ERROR (Status
)) {
978 if (Status
!= EFI_NOT_FOUND
) {
979 DEBUG ((DEBUG_ERROR
, "Unexpected error getting Capsule Update variable. Status = %r\n"));
986 // If this BlockList has been linked before, skip this variable
989 for (TempIndex
= 0; TempIndex
< ValidIndex
; TempIndex
++) {
990 if (TempList
[TempIndex
] == CapsuleDataPtr64
) {
1002 // The TempList is full, enlarge it
1004 if ((ValidIndex
+ 1) >= TempListLength
) {
1005 EnlargedTempList
= AllocateZeroPool (TempListLength
* 2);
1006 if (EnlargedTempList
== NULL
) {
1007 DEBUG ((DEBUG_ERROR
, "Fail to allocate memory!\n"));
1008 return EFI_OUT_OF_RESOURCES
;
1011 CopyMem (EnlargedTempList
, TempList
, TempListLength
);
1012 FreePool (TempList
);
1013 TempList
= EnlargedTempList
;
1014 TempListLength
*= 2;
1018 // add it to the cached list
1020 TempList
[ValidIndex
++] = CapsuleDataPtr64
;
1024 if (ValidIndex
== 0) {
1025 DEBUG ((DEBUG_ERROR
, "%a didn't find any SG lists in variables\n", __FUNCTION__
));
1026 return EFI_NOT_FOUND
;
1029 *HeadList
= AllocateZeroPool ((ValidIndex
+ 1) * sizeof (EFI_PHYSICAL_ADDRESS
));
1030 if (*HeadList
== NULL
) {
1031 DEBUG ((DEBUG_ERROR
, "Failed to allocate memory\n"));
1032 return EFI_OUT_OF_RESOURCES
;
1035 CopyMem (*HeadList
, TempList
, (ValidIndex
) * sizeof (EFI_PHYSICAL_ADDRESS
));
1036 *ListLength
= ValidIndex
;
1042 Capsule PPI service to coalesce a fragmented capsule in memory.
1044 @param PeiServices General purpose services available to every PEIM.
1045 @param MemoryBase Pointer to the base of a block of memory that we can walk
1046 all over while trying to coalesce our buffers.
1047 On output, this variable will hold the base address of
1048 a coalesced capsule.
1049 @param MemorySize Size of the memory region pointed to by MemoryBase.
1050 On output, this variable will contain the size of the
1053 @retval EFI_NOT_FOUND if we can't determine the boot mode
1054 if the boot mode is not flash-update
1055 if we could not find the capsule descriptors
1057 @retval EFI_BUFFER_TOO_SMALL
1058 if we could not coalesce the capsule in the memory
1059 region provided to us
1061 @retval EFI_SUCCESS if there's no capsule, or if we processed the
1062 capsule successfully.
1067 IN EFI_PEI_SERVICES
**PeiServices
,
1068 IN OUT VOID
**MemoryBase
,
1069 IN OUT UINTN
*MemorySize
1073 EFI_BOOT_MODE BootMode
;
1075 EFI_PHYSICAL_ADDRESS
*VariableArrayAddress
;
1076 MEMORY_RESOURCE_DESCRIPTOR
*MemoryResource
;
1079 UINT16 CoalesceImageMachineType
;
1080 EFI_PHYSICAL_ADDRESS CoalesceImageEntryPoint
;
1081 COALESCE_ENTRY CoalesceEntry
;
1082 EFI_CAPSULE_LONG_MODE_BUFFER LongModeBuffer
;
1086 VariableArrayAddress
= NULL
;
1089 // Someone should have already ascertained the boot mode. If it's not
1090 // capsule update, then return normally.
1092 Status
= PeiServicesGetBootMode (&BootMode
);
1093 if (EFI_ERROR (Status
) || (BootMode
!= BOOT_ON_FLASH_UPDATE
)) {
1094 DEBUG ((DEBUG_ERROR
, "Boot mode is not correct for capsule update path.\n"));
1095 Status
= EFI_NOT_FOUND
;
1100 // Get SG list entries
1102 Status
= GetScatterGatherHeadEntries (&ListLength
, &VariableArrayAddress
);
1103 if (EFI_ERROR (Status
) || (VariableArrayAddress
== NULL
)) {
1104 DEBUG ((DEBUG_ERROR
, "%a failed to get Scatter Gather List Head Entries. Status = %r\n", __FUNCTION__
, Status
));
1108 MemoryResource
= BuildMemoryResourceDescriptor ();
1111 if (FeaturePcdGet (PcdDxeIplSwitchToLongMode
)) {
1113 // Switch to 64-bit mode to process capsule data when:
1114 // 1. When DXE phase is 64-bit
1115 // 2. When the buffer for 64-bit transition exists
1116 // 3. When Capsule X64 image is built in BIOS image
1117 // In 64-bit mode, we can process capsule data above 4GB.
1119 CoalesceImageEntryPoint
= 0;
1120 Status
= GetLongModeContext (&LongModeBuffer
);
1121 if (EFI_ERROR (Status
)) {
1122 DEBUG ((DEBUG_ERROR
, "Fail to find the variable for long mode context!\n"));
1123 Status
= EFI_NOT_FOUND
;
1127 Status
= FindCapsuleCoalesceImage (&CoalesceImageEntryPoint
, &CoalesceImageMachineType
);
1128 if ((EFI_ERROR (Status
)) || (CoalesceImageMachineType
!= EFI_IMAGE_MACHINE_X64
)) {
1129 DEBUG ((DEBUG_ERROR
, "Fail to find CapsuleX64 module in FV!\n"));
1130 Status
= EFI_NOT_FOUND
;
1134 ASSERT (CoalesceImageEntryPoint
!= 0);
1135 CoalesceEntry
= (COALESCE_ENTRY
)(UINTN
)CoalesceImageEntryPoint
;
1136 Status
= ModeSwitch (&LongModeBuffer
, CoalesceEntry
, (EFI_PHYSICAL_ADDRESS
)(UINTN
)VariableArrayAddress
, MemoryResource
, MemoryBase
, MemorySize
);
1139 // Capsule is processed in IA32 mode.
1141 Status
= CapsuleDataCoalesce (PeiServices
, (EFI_PHYSICAL_ADDRESS
*)(UINTN
)VariableArrayAddress
, MemoryResource
, MemoryBase
, MemorySize
);
1146 // Process capsule directly.
1148 Status
= CapsuleDataCoalesce (PeiServices
, (EFI_PHYSICAL_ADDRESS
*)(UINTN
)VariableArrayAddress
, MemoryResource
, MemoryBase
, MemorySize
);
1151 DEBUG ((DEBUG_INFO
, "Capsule Coalesce Status = %r!\n", Status
));
1153 if (Status
== EFI_BUFFER_TOO_SMALL
) {
1154 DEBUG ((DEBUG_ERROR
, "There is not enough memory to process capsule!\n"));
1157 if (Status
== EFI_NOT_FOUND
) {
1158 DEBUG ((DEBUG_ERROR
, "Fail to parse capsule descriptor in memory!\n"));
1159 REPORT_STATUS_CODE (
1160 EFI_ERROR_CODE
| EFI_ERROR_MAJOR
,
1161 (EFI_SOFTWARE_PEI_MODULE
| EFI_SW_PEI_EC_INVALID_CAPSULE_DESCRIPTOR
)
1170 Determine if we're in capsule update boot mode.
1172 @param PeiServices PEI services table
1174 @retval EFI_SUCCESS if we have a capsule available
1175 @retval EFI_NOT_FOUND no capsule detected
1180 CheckCapsuleUpdate (
1181 IN EFI_PEI_SERVICES
**PeiServices
1184 if (AreCapsulesStaged ()) {
1187 return EFI_NOT_FOUND
;
1192 This function will look at a capsule and determine if it's a test pattern.
1193 If it is, then it will verify it and emit an error message if corruption is detected.
1195 @param PeiServices Standard pei services pointer
1196 @param CapsuleBase Base address of coalesced capsule, which is preceeded
1197 by private data. Very implementation specific.
1199 @retval TRUE Capsule image is the test image
1200 @retval FALSE Capsule image is not the test image.
1204 CapsuleTestPattern (
1205 IN EFI_PEI_SERVICES
**PeiServices
,
1206 IN VOID
*CapsuleBase
1217 // Look at the capsule data and determine if it's a test pattern. If it
1218 // is, then test it now.
1220 TestPtr
= (UINT32
*)CapsuleBase
;
1222 // 0x54534554 "TEST"
1224 if (*TestPtr
== 0x54534554) {
1226 DEBUG ((DEBUG_INFO
, "Capsule test pattern mode activated...\n"));
1227 TestSize
= TestPtr
[1] / sizeof (UINT32
);
1229 // Skip over the signature and the size fields in the pattern data header
1233 while (TestSize
> 0) {
1234 if (*TestPtr
!= TestCounter
) {
1235 DEBUG ((DEBUG_INFO
, "Capsule test pattern mode FAILED: BaseAddr/FailAddr 0x%X 0x%X\n", (UINT32
)(UINTN
)(EFI_CAPSULE_PEIM_PRIVATE_DATA
*)CapsuleBase
, (UINT32
)(UINTN
)TestPtr
));
1244 DEBUG ((DEBUG_INFO
, "Capsule test pattern mode SUCCESS\n"));
1251 Capsule PPI service that gets called after memory is available. The
1252 capsule coalesce function, which must be called first, returns a base
1253 address and size, which can be anything actually. Once the memory init
1254 PEIM has discovered memory, then it should call this function and pass in
1255 the base address and size returned by the coalesce function. Then this
1256 function can create a capsule HOB and return.
1258 @param PeiServices standard pei services pointer
1259 @param CapsuleBase address returned by the capsule coalesce function. Most
1260 likely this will actually be a pointer to private data.
1261 @param CapsuleSize value returned by the capsule coalesce function.
1263 @retval EFI_VOLUME_CORRUPTED CapsuleBase does not appear to point to a
1265 @retval EFI_SUCCESS if all goes well.
1270 IN EFI_PEI_SERVICES
**PeiServices
,
1271 IN VOID
*CapsuleBase
,
1272 IN UINTN CapsuleSize
1276 EFI_CAPSULE_PEIM_PRIVATE_DATA
*PrivateData
;
1278 EFI_PHYSICAL_ADDRESS NewBuffer
;
1279 UINTN CapsuleNumber
;
1281 EFI_PHYSICAL_ADDRESS BaseAddress
;
1284 PrivateData
= (EFI_CAPSULE_PEIM_PRIVATE_DATA
*)CapsuleBase
;
1285 if (PrivateData
->Signature
!= EFI_CAPSULE_PEIM_PRIVATE_DATA_SIGNATURE
) {
1286 return EFI_VOLUME_CORRUPTED
;
1289 if (PrivateData
->CapsuleAllImageSize
>= MAX_ADDRESS
) {
1290 DEBUG ((DEBUG_ERROR
, "CapsuleAllImageSize too big - 0x%lx\n", PrivateData
->CapsuleAllImageSize
));
1291 return EFI_OUT_OF_RESOURCES
;
1294 if (PrivateData
->CapsuleNumber
>= MAX_ADDRESS
) {
1295 DEBUG ((DEBUG_ERROR
, "CapsuleNumber too big - 0x%lx\n", PrivateData
->CapsuleNumber
));
1296 return EFI_OUT_OF_RESOURCES
;
1300 // Capsule Number and Capsule Offset is in the tail of Capsule data.
1302 Size
= (UINTN
)PrivateData
->CapsuleAllImageSize
;
1303 CapsuleNumber
= (UINTN
)PrivateData
->CapsuleNumber
;
1305 // Allocate the memory so that it gets preserved into DXE
1307 Status
= PeiServicesAllocatePages (
1308 EfiRuntimeServicesData
,
1309 EFI_SIZE_TO_PAGES (Size
),
1313 if (Status
!= EFI_SUCCESS
) {
1314 DEBUG ((DEBUG_ERROR
, "AllocatePages Failed!\n"));
1319 // Copy to our new buffer for DXE
1321 DEBUG ((DEBUG_INFO
, "Capsule copy from 0x%8X to 0x%8X with size 0x%8X\n", (UINTN
)((UINT8
*)PrivateData
+ sizeof (EFI_CAPSULE_PEIM_PRIVATE_DATA
) + (CapsuleNumber
- 1) * sizeof (UINT64
)), (UINTN
)NewBuffer
, Size
));
1322 CopyMem ((VOID
*)(UINTN
)NewBuffer
, (VOID
*)(UINTN
)((UINT8
*)PrivateData
+ sizeof (EFI_CAPSULE_PEIM_PRIVATE_DATA
) + (CapsuleNumber
- 1) * sizeof (UINT64
)), Size
);
1324 // Check for test data pattern. If it is the test pattern, then we'll
1325 // test it and still create the HOB so that it can be used to verify
1326 // that capsules don't get corrupted all the way into BDS. BDS will
1327 // still try to turn it into a firmware volume, but will think it's
1328 // corrupted so nothing will happen.
1331 CapsuleTestPattern (PeiServices
, (VOID
*)(UINTN
)NewBuffer
);
1335 // Build the UEFI Capsule Hob for each capsule image.
1337 for (Index
= 0; Index
< CapsuleNumber
; Index
++) {
1338 BaseAddress
= NewBuffer
+ PrivateData
->CapsuleOffset
[Index
];
1339 Length
= ((EFI_CAPSULE_HEADER
*)((UINTN
)BaseAddress
))->CapsuleImageSize
;
1341 BuildCvHob (BaseAddress
, Length
);
1347 CONST EFI_PEI_CAPSULE_PPI mCapsulePpi
= {
1353 CONST EFI_PEI_PPI_DESCRIPTOR mUefiPpiListCapsule
= {
1354 (EFI_PEI_PPI_DESCRIPTOR_PPI
| EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST
),
1355 &gEfiPeiCapsulePpiGuid
,
1356 (EFI_PEI_CAPSULE_PPI
*)&mCapsulePpi
1360 Entry point function for the PEIM
1362 @param FileHandle Handle of the file being invoked.
1363 @param PeiServices Describes the list of possible PEI Services.
1365 @return EFI_SUCCESS If we installed our PPI
1371 IN EFI_PEI_FILE_HANDLE FileHandle
,
1372 IN CONST EFI_PEI_SERVICES
**PeiServices
1376 // Just produce our PPI
1378 return PeiServicesInstallPpi (&mUefiPpiListCapsule
);