]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c
Enable "Load Module At fixed Address" feature in SMM Core
[mirror_edk2.git] / MdeModulePkg / Core / PiSmmCore / PiSmmIpl.c
1 /** @file
2 SMM IPL that produces SMM related runtime protocols and load the SMM Core into SMRAM
3
4 Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials are licensed and made available
6 under the terms and conditions of the BSD License which accompanies this
7 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 <PiDxe.h>
16
17 #include <Protocol/SmmBase2.h>
18 #include <Protocol/SmmCommunication.h>
19 #include <Protocol/SmmAccess2.h>
20 #include <Protocol/SmmConfiguration.h>
21 #include <Protocol/SmmControl2.h>
22 #include <Protocol/DxeSmmReadyToLock.h>
23 #include <Protocol/FirmwareVolume2.h>
24
25 #include <Guid/EventGroup.h>
26 #include <Guid/EventLegacyBios.h>
27 #include <Guid/LoadModuleAtFixedAddress.h>
28
29 #include <Library/BaseLib.h>
30 #include <Library/BaseMemoryLib.h>
31 #include <Library/PeCoffLib.h>
32 #include <Library/CacheMaintenanceLib.h>
33 #include <Library/MemoryAllocationLib.h>
34 #include <Library/DebugLib.h>
35 #include <Library/UefiBootServicesTableLib.h>
36 #include <Library/DxeServicesTableLib.h>
37 #include <Library/UefiLib.h>
38 #include <Library/UefiRuntimeLib.h>
39 #include <Library/PcdLib.h>
40
41 #include "PiSmmCorePrivateData.h"
42
43 //
44 // Function prototypes from produced protocols
45 //
46
47 /**
48 Indicate whether the driver is currently executing in the SMM Initialization phase.
49
50 @param This The EFI_SMM_BASE2_PROTOCOL instance.
51 @param InSmram Pointer to a Boolean which, on return, indicates that the driver is currently executing
52 inside of SMRAM (TRUE) or outside of SMRAM (FALSE).
53
54 @retval EFI_INVALID_PARAMETER InSmram was NULL.
55 @retval EFI_SUCCESS The call returned successfully.
56
57 **/
58 EFI_STATUS
59 EFIAPI
60 SmmBase2InSmram (
61 IN CONST EFI_SMM_BASE2_PROTOCOL *This,
62 OUT BOOLEAN *InSmram
63 );
64
65 /**
66 Retrieves the location of the System Management System Table (SMST).
67
68 @param This The EFI_SMM_BASE2_PROTOCOL instance.
69 @param Smst On return, points to a pointer to the System Management Service Table (SMST).
70
71 @retval EFI_INVALID_PARAMETER Smst or This was invalid.
72 @retval EFI_SUCCESS The memory was returned to the system.
73 @retval EFI_UNSUPPORTED Not in SMM.
74
75 **/
76 EFI_STATUS
77 EFIAPI
78 SmmBase2GetSmstLocation (
79 IN CONST EFI_SMM_BASE2_PROTOCOL *This,
80 OUT EFI_SMM_SYSTEM_TABLE2 **Smst
81 );
82
83 /**
84 Communicates with a registered handler.
85
86 This function provides a service to send and receive messages from a registered
87 UEFI service. This function is part of the SMM Communication Protocol that may
88 be called in physical mode prior to SetVirtualAddressMap() and in virtual mode
89 after SetVirtualAddressMap().
90
91 @param[in] This The EFI_SMM_COMMUNICATION_PROTOCOL instance.
92 @param[in, out] CommBuffer A pointer to the buffer to convey into SMRAM.
93 @param[in, out] CommSize The size of the data buffer being passed in.On exit, the size of data
94 being returned. Zero if the handler does not wish to reply with any data.
95
96 @retval EFI_SUCCESS The message was successfully posted.
97 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
98 **/
99 EFI_STATUS
100 EFIAPI
101 SmmCommunicationCommunicate (
102 IN CONST EFI_SMM_COMMUNICATION_PROTOCOL *This,
103 IN OUT VOID *CommBuffer,
104 IN OUT UINTN *CommSize
105 );
106
107 /**
108 Event notification that is fired every time a gEfiSmmConfigurationProtocol installs.
109
110 @param Event The Event that is being processed, not used.
111 @param Context Event Context, not used.
112
113 **/
114 VOID
115 EFIAPI
116 SmmIplSmmConfigurationEventNotify (
117 IN EFI_EVENT Event,
118 IN VOID *Context
119 );
120
121 /**
122 Event notification that is fired every time a DxeSmmReadyToLock protocol is added
123 or if gEfiEventReadyToBootGuid is signalled.
124
125 @param Event The Event that is being processed, not used.
126 @param Context Event Context, not used.
127
128 **/
129 VOID
130 EFIAPI
131 SmmIplReadyToLockEventNotify (
132 IN EFI_EVENT Event,
133 IN VOID *Context
134 );
135
136 /**
137 Event notification that is fired when DxeDispatch Event Group is signaled.
138
139 @param Event The Event that is being processed, not used.
140 @param Context Event Context, not used.
141
142 **/
143 VOID
144 EFIAPI
145 SmmIplGuidedEventNotify (
146 IN EFI_EVENT Event,
147 IN VOID *Context
148 );
149
150 /**
151 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
152
153 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
154 It convers pointer to new virtual address.
155
156 @param Event Event whose notification function is being invoked.
157 @param Context Pointer to the notification function's context.
158
159 **/
160 VOID
161 EFIAPI
162 SmmIplSetVirtualAddressNotify (
163 IN EFI_EVENT Event,
164 IN VOID *Context
165 );
166
167 //
168 // Data structure used to declare a table of protocol notifications and event
169 // notifications required by the SMM IPL
170 //
171 typedef struct {
172 BOOLEAN Protocol;
173 BOOLEAN CloseOnLock;
174 EFI_GUID *Guid;
175 EFI_EVENT_NOTIFY NotifyFunction;
176 VOID *NotifyContext;
177 EFI_EVENT Event;
178 } SMM_IPL_EVENT_NOTIFICATION;
179
180 //
181 // Handle to install the SMM Base2 Protocol and the SMM Communication Protocol
182 //
183 EFI_HANDLE mSmmIplHandle = NULL;
184
185 //
186 // SMM Base 2 Protocol instance
187 //
188 EFI_SMM_BASE2_PROTOCOL mSmmBase2 = {
189 SmmBase2InSmram,
190 SmmBase2GetSmstLocation
191 };
192
193 //
194 // SMM Communication Protocol instance
195 //
196 EFI_SMM_COMMUNICATION_PROTOCOL mSmmCommunication = {
197 SmmCommunicationCommunicate
198 };
199
200 //
201 // SMM Core Private Data structure that contains the data shared between
202 // the SMM IPL and the SMM Core.
203 //
204 SMM_CORE_PRIVATE_DATA mSmmCorePrivateData = {
205 SMM_CORE_PRIVATE_DATA_SIGNATURE, // Signature
206 NULL, // SmmIplImageHandle
207 0, // SmramRangeCount
208 NULL, // SmramRanges
209 NULL, // SmmEntryPoint
210 FALSE, // SmmEntryPointRegistered
211 FALSE, // InSmm
212 NULL, // Smst
213 0, // BufferSize
214 NULL, // CommunicationBuffer
215 EFI_SUCCESS // ReturnStatus
216 };
217
218 //
219 // Global pointer used to access mSmmCorePrivateData from outside and inside SMM
220 //
221 SMM_CORE_PRIVATE_DATA *gSmmCorePrivate = &mSmmCorePrivateData;
222
223 //
224 // SMM IPL global variables
225 //
226 EFI_SMM_CONTROL2_PROTOCOL *mSmmControl2;
227 EFI_SMM_ACCESS2_PROTOCOL *mSmmAccess;
228 EFI_SMRAM_DESCRIPTOR *mCurrentSmramRange;
229 BOOLEAN mSmmLocked = FALSE;
230
231 //
232 // Table of Protocol notification and GUIDed Event notifications that the SMM IPL requires
233 //
234 SMM_IPL_EVENT_NOTIFICATION mSmmIplEvents[] = {
235 //
236 // Declare protocol notification on the SMM Configuration protocol. When this notification is etablished,
237 // the associated event is immediately signalled, so the notification function will be executed and the
238 // SMM Configuration Protocol will be found if it is already in the handle database.
239 //
240 { TRUE, FALSE, &gEfiSmmConfigurationProtocolGuid, SmmIplSmmConfigurationEventNotify, &gEfiSmmConfigurationProtocolGuid, NULL },
241 //
242 // Declare protocl notification on DxeSmmReadyToLock protocols. When this notification is etablished,
243 // the associated event is immediately signalled, so the notification function will be executed and the
244 // DXE SMM Ready To Lock Protocol will be found if it is already in the handle database.
245 //
246 { TRUE, TRUE, &gEfiDxeSmmReadyToLockProtocolGuid, SmmIplReadyToLockEventNotify, &gEfiDxeSmmReadyToLockProtocolGuid, NULL },
247 //
248 // Declare event notification on the DXE Dispatch Event Group. This event is signaled by the DXE Core
249 // each time the DXE Core dispatcher has completed its work. When this event is signalled, the SMM Core
250 // if notified, so the SMM Core can dispatch SMM drivers.
251 //
252 { FALSE, TRUE, &gEfiEventDxeDispatchGuid, SmmIplGuidedEventNotify, &gEfiEventDxeDispatchGuid, NULL },
253 //
254 // Declare event notification on Ready To Boot Event Group. This is an extra event notification that is
255 // used to make sure SMRAM is locked before any boot options are processed.
256 //
257 { FALSE, TRUE, &gEfiEventReadyToBootGuid, SmmIplReadyToLockEventNotify, &gEfiEventReadyToBootGuid, NULL },
258 //
259 // Declare event notification on Legacy Boot Event Group. This is used to inform the SMM Core that the platform
260 // is performing a legacy boot operation, and that the UEFI environment is no longer available and the SMM Core
261 // must guarantee that it does not access any UEFI related structures outside of SMRAM.
262 //
263 { FALSE, FALSE, &gEfiEventLegacyBootGuid, SmmIplGuidedEventNotify, &gEfiEventLegacyBootGuid, NULL },
264 //
265 // Declare event notification on SetVirtualAddressMap() Event Group. This is used to convert gSmmCorePrivate
266 // and mSmmControl2 from physical addresses to virtual addresses.
267 //
268 { FALSE, FALSE, &gEfiEventVirtualAddressChangeGuid, SmmIplSetVirtualAddressNotify, NULL, NULL },
269 //
270 // Terminate the table of event notifications
271 //
272 { FALSE, FALSE, NULL, NULL, NULL, NULL }
273 };
274
275 /**
276 Indicate whether the driver is currently executing in the SMM Initialization phase.
277
278 @param This The EFI_SMM_BASE2_PROTOCOL instance.
279 @param InSmram Pointer to a Boolean which, on return, indicates that the driver is currently executing
280 inside of SMRAM (TRUE) or outside of SMRAM (FALSE).
281
282 @retval EFI_INVALID_PARAMETER InSmram was NULL.
283 @retval EFI_SUCCESS The call returned successfully.
284
285 **/
286 EFI_STATUS
287 EFIAPI
288 SmmBase2InSmram (
289 IN CONST EFI_SMM_BASE2_PROTOCOL *This,
290 OUT BOOLEAN *InSmram
291 )
292 {
293 if (InSmram == NULL) {
294 return EFI_INVALID_PARAMETER;
295 }
296
297 *InSmram = gSmmCorePrivate->InSmm;
298
299 return EFI_SUCCESS;
300 }
301
302 /**
303 Retrieves the location of the System Management System Table (SMST).
304
305 @param This The EFI_SMM_BASE2_PROTOCOL instance.
306 @param Smst On return, points to a pointer to the System Management Service Table (SMST).
307
308 @retval EFI_INVALID_PARAMETER Smst or This was invalid.
309 @retval EFI_SUCCESS The memory was returned to the system.
310 @retval EFI_UNSUPPORTED Not in SMM.
311
312 **/
313 EFI_STATUS
314 EFIAPI
315 SmmBase2GetSmstLocation (
316 IN CONST EFI_SMM_BASE2_PROTOCOL *This,
317 OUT EFI_SMM_SYSTEM_TABLE2 **Smst
318 )
319 {
320 if ((This == NULL) ||(Smst == NULL)) {
321 return EFI_INVALID_PARAMETER;
322 }
323
324 if (!gSmmCorePrivate->InSmm) {
325 return EFI_UNSUPPORTED;
326 }
327
328 *Smst = gSmmCorePrivate->Smst;
329
330 return EFI_SUCCESS;
331 }
332
333 /**
334 Communicates with a registered handler.
335
336 This function provides a service to send and receive messages from a registered
337 UEFI service. This function is part of the SMM Communication Protocol that may
338 be called in physical mode prior to SetVirtualAddressMap() and in virtual mode
339 after SetVirtualAddressMap().
340
341 @param[in] This The EFI_SMM_COMMUNICATION_PROTOCOL instance.
342 @param[in, out] CommBuffer A pointer to the buffer to convey into SMRAM.
343 @param[in, out] CommSize The size of the data buffer being passed in.On exit, the size of data
344 being returned. Zero if the handler does not wish to reply with any data.
345
346 @retval EFI_SUCCESS The message was successfully posted.
347 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
348 **/
349 EFI_STATUS
350 EFIAPI
351 SmmCommunicationCommunicate (
352 IN CONST EFI_SMM_COMMUNICATION_PROTOCOL *This,
353 IN OUT VOID *CommBuffer,
354 IN OUT UINTN *CommSize
355 )
356 {
357 EFI_STATUS Status;
358 EFI_SMM_COMMUNICATE_HEADER *CommunicateHeader;
359 BOOLEAN OldInSmm;
360
361 //
362 // Check parameters
363 //
364 if ((CommBuffer == NULL) || (CommSize == NULL)) {
365 return EFI_INVALID_PARAMETER;
366 }
367
368 //
369 // If not already in SMM, then generate a Software SMI
370 //
371 if (!gSmmCorePrivate->InSmm && gSmmCorePrivate->SmmEntryPointRegistered) {
372 //
373 // Put arguments for Software SMI in gSmmCorePrivate
374 //
375 gSmmCorePrivate->CommunicationBuffer = CommBuffer;
376 gSmmCorePrivate->BufferSize = CommSize;
377
378 //
379 // Generate Software SMI
380 //
381 Status = mSmmControl2->Trigger (mSmmControl2, NULL, NULL, FALSE, 0);
382 if (EFI_ERROR (Status)) {
383 return EFI_UNSUPPORTED;
384 }
385
386 //
387 // Return status from software SMI
388 //
389 return gSmmCorePrivate->ReturnStatus;
390 }
391
392 //
393 // If we are in SMM, then the execution mode must be physical, which means that
394 // OS established virtual addresses can not be used. If SetVirtualAddressMap()
395 // has been called, then a direct invocation of the Software SMI is not
396 // not allowed so return EFI_INVALID_PARAMETER.
397 //
398 if (EfiGoneVirtual()) {
399 return EFI_INVALID_PARAMETER;
400 }
401
402 //
403 // Don't allow call SmiManage() directly when SMRAM is closed or locked.
404 //
405 if (!mSmmAccess->OpenState || mSmmAccess->LockState) {
406 return EFI_INVALID_PARAMETER;
407 }
408
409 //
410 // Save current InSmm state and set InSmm state to TRUE
411 //
412 OldInSmm = gSmmCorePrivate->InSmm;
413 gSmmCorePrivate->InSmm = TRUE;
414
415 //
416 // Already in SMM and before SetVirtualAddressMap(), so call SmiManage() directly.
417 //
418 CommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *)CommBuffer;
419 *CommSize -= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data);
420 Status = gSmmCorePrivate->Smst->SmiManage (
421 &CommunicateHeader->HeaderGuid,
422 NULL,
423 CommunicateHeader->Data,
424 CommSize
425 );
426
427 //
428 // Update CommunicationBuffer, BufferSize and ReturnStatus
429 // Communicate service finished, reset the pointer to CommBuffer to NULL
430 //
431 *CommSize += OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data);
432
433 //
434 // Restore original InSmm state
435 //
436 gSmmCorePrivate->InSmm = OldInSmm;
437
438 return (Status == EFI_WARN_INTERRUPT_SOURCE_QUIESCED) ? EFI_SUCCESS : EFI_NOT_FOUND;
439 }
440
441 /**
442 Event notification that is fired when DxeDispatch Event Group is signaled.
443
444 @param Event The Event that is being processed, not used.
445 @param Context Event Context, not used.
446
447 **/
448 VOID
449 EFIAPI
450 SmmIplGuidedEventNotify (
451 IN EFI_EVENT Event,
452 IN VOID *Context
453 )
454 {
455 EFI_SMM_COMMUNICATE_HEADER CommunicateHeader;
456 UINTN Size;
457
458 //
459 // Use Guid to initialize EFI_SMM_COMMUNICATE_HEADER structure
460 //
461 CopyGuid (&CommunicateHeader.HeaderGuid, (EFI_GUID *)Context);
462 CommunicateHeader.MessageLength = 1;
463 CommunicateHeader.Data[0] = 0;
464
465 //
466 // Generate the Software SMI and return the result
467 //
468 Size = sizeof (CommunicateHeader);
469 SmmCommunicationCommunicate (&mSmmCommunication, &CommunicateHeader, &Size);
470 }
471
472 /**
473 Event notification that is fired every time a gEfiSmmConfigurationProtocol installs.
474
475 @param Event The Event that is being processed, not used.
476 @param Context Event Context, not used.
477
478 **/
479 VOID
480 EFIAPI
481 SmmIplSmmConfigurationEventNotify (
482 IN EFI_EVENT Event,
483 IN VOID *Context
484 )
485 {
486 EFI_STATUS Status;
487 EFI_SMM_CONFIGURATION_PROTOCOL *SmmConfiguration;
488
489 //
490 // Make sure this notification is for this handler
491 //
492 Status = gBS->LocateProtocol (Context, NULL, (VOID **)&SmmConfiguration);
493 if (EFI_ERROR (Status)) {
494 return;
495 }
496
497 //
498 // Register the SMM Entry Point provided by the SMM Core with the SMM COnfiguration protocol
499 //
500 Status = SmmConfiguration->RegisterSmmEntry (SmmConfiguration, gSmmCorePrivate->SmmEntryPoint);
501 ASSERT_EFI_ERROR (Status);
502
503 //
504 // Set flag to indicate that the SM< Entry Point has been registered which
505 // means that SMIs are now fully operational.
506 //
507 gSmmCorePrivate->SmmEntryPointRegistered = TRUE;
508
509 //
510 // Print debug message showing SMM Core entry point address.
511 //
512 DEBUG ((DEBUG_INFO, "SMM IPL registered SMM Entry Point address %p\n", (VOID *)(UINTN)gSmmCorePrivate->SmmEntryPoint));
513
514 //
515 // Attempt to reset SMRAM cacheability to UC
516 //
517 Status = gDS->SetMemorySpaceAttributes(
518 mCurrentSmramRange->CpuStart,
519 mCurrentSmramRange->PhysicalSize,
520 EFI_MEMORY_UC
521 );
522 if (EFI_ERROR (Status)) {
523 DEBUG ((DEBUG_WARN, "SMM IPL failed to reset SMRAM window to EFI_MEMORY_UC\n"));
524 }
525
526 //
527 // Close all SMRAM ranges to protect SMRAM
528 //
529 Status = mSmmAccess->Close (mSmmAccess);
530 ASSERT_EFI_ERROR (Status);
531
532 //
533 // Print debug message that the SMRAM window is now closed.
534 //
535 DEBUG ((DEBUG_INFO, "SMM IPL closed SMRAM window\n"));
536 }
537
538 /**
539 Event notification that is fired every time a DxeSmmReadyToLock protocol is added
540 or if gEfiEventReadyToBootGuid is signalled.
541
542 @param Event The Event that is being processed, not used.
543 @param Context Event Context, not used.
544
545 **/
546 VOID
547 EFIAPI
548 SmmIplReadyToLockEventNotify (
549 IN EFI_EVENT Event,
550 IN VOID *Context
551 )
552 {
553 EFI_STATUS Status;
554 VOID *Interface;
555 UINTN Index;
556
557 //
558 // See if we are already locked
559 //
560 if (mSmmLocked) {
561 return;
562 }
563
564 //
565 // Make sure this notification is for this handler
566 //
567 if (CompareGuid ((EFI_GUID *)Context, &gEfiDxeSmmReadyToLockProtocolGuid)) {
568 Status = gBS->LocateProtocol (&gEfiDxeSmmReadyToLockProtocolGuid, NULL, &Interface);
569 if (EFI_ERROR (Status)) {
570 return;
571 }
572 } else {
573 //
574 // If SMM is not locked yet and we got here from gEfiEventReadyToBootGuid being
575 // signalled, then gEfiDxeSmmReadyToLockProtocolGuid was not installed as expected.
576 // Print a warning on debug builds.
577 //
578 DEBUG ((DEBUG_WARN, "SMM IPL! DXE SMM Ready To Lock Protocol not installed before Ready To Boot signal\n"));
579 }
580
581 //
582 // Lock the SMRAM (Note: Locking SMRAM may not be supported on all platforms)
583 //
584 mSmmAccess->Lock (mSmmAccess);
585
586 //
587 // Close protocol and event notification events that do not apply after the
588 // DXE SMM Ready To Lock Protocol has been installed or the Ready To Boot
589 // event has been signalled.
590 //
591 for (Index = 0; mSmmIplEvents[Index].NotifyFunction != NULL; Index++) {
592 if (mSmmIplEvents[Index].CloseOnLock) {
593 gBS->CloseEvent (mSmmIplEvents[Index].Event);
594 }
595 }
596
597 //
598 // Inform SMM Core that the DxeSmmReadyToLock protocol was installed
599 //
600 SmmIplGuidedEventNotify (Event, (VOID *)&gEfiDxeSmmReadyToLockProtocolGuid);
601
602 //
603 // Print debug message that the SMRAM window is now locked.
604 //
605 DEBUG ((DEBUG_INFO, "SMM IPL locked SMRAM window\n"));
606
607 //
608 // Set flag so this operation will not be performed again
609 //
610 mSmmLocked = TRUE;
611 }
612
613 /**
614 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
615
616 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
617 It convers pointer to new virtual address.
618
619 @param Event Event whose notification function is being invoked.
620 @param Context Pointer to the notification function's context.
621
622 **/
623 VOID
624 EFIAPI
625 SmmIplSetVirtualAddressNotify (
626 IN EFI_EVENT Event,
627 IN VOID *Context
628 )
629 {
630 EfiConvertPointer (0x0, (VOID **)&mSmmControl2);
631 }
632
633 /**
634 Searches all Firmware Volumes for the first file matching FileType and SectionType and returns the section data.
635
636 @param FileType FileType to search for within any of the firmware volumes in the platform.
637 @param SectionType SectionType to search for within any of the matching FileTypes in the firmware volumes in the platform.
638 @param SourceSize Return the size of the returned section data..
639
640 @retval != NULL Pointer to the allocated buffer containing the section data.
641 @retval NULL Section data was not found.
642
643 **/
644 VOID *
645 GetSectionInAnyFv (
646 IN EFI_FV_FILETYPE FileType,
647 IN EFI_SECTION_TYPE SectionType,
648 OUT UINTN *SourceSize
649 )
650 {
651 EFI_STATUS Status;
652 UINTN HandleCount;
653 EFI_HANDLE *HandleBuffer;
654 UINTN Index;
655 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
656 UINTN Key;
657 EFI_GUID NameGuid;
658 EFI_FV_FILE_ATTRIBUTES Attributes;
659 VOID *SourceBuffer;
660 UINT32 AuthenticationStatus;
661
662 HandleBuffer = NULL;
663 Status = gBS->LocateHandleBuffer (
664 ByProtocol,
665 &gEfiFirmwareVolume2ProtocolGuid,
666 NULL,
667 &HandleCount,
668 &HandleBuffer
669 );
670 if (EFI_ERROR (Status)) {
671 return NULL;
672 }
673
674 for (Index = 0; Index < HandleCount; Index++) {
675 Status = gBS->HandleProtocol (
676 HandleBuffer[Index],
677 &gEfiFirmwareVolume2ProtocolGuid,
678 (VOID **)&Fv
679 );
680 if (EFI_ERROR (Status)) {
681 continue;
682 }
683
684 //
685 // Use Firmware Volume 2 Protocol to search for a file of type FileType
686 //
687 Key = 0;
688 Status = Fv->GetNextFile (Fv, &Key, &FileType, &NameGuid, &Attributes, SourceSize);
689 if (EFI_ERROR (Status)) {
690 continue;
691 }
692
693 //
694 // Use Firmware Volume 2 Protocol to read a section of type SectionType
695 //
696 SourceBuffer = NULL;
697 Status = Fv->ReadSection (Fv, &NameGuid, SectionType, 0, &SourceBuffer, SourceSize, &AuthenticationStatus);
698 if (!EFI_ERROR (Status)) {
699 FreePool (HandleBuffer);
700 return SourceBuffer;
701 }
702 }
703
704 FreePool(HandleBuffer);
705
706 return NULL;
707 }
708 /**
709 Get the fixed loadding address from image header assigned by build tool. This function only be called
710 when Loading module at Fixed address feature enabled.
711
712 @param ImageContext Pointer to the image context structure that describes the PE/COFF
713 image that needs to be examined by this function.
714 @retval EFI_SUCCESS An fixed loading address is assigned to this image by build tools .
715 @retval EFI_NOT_FOUND The image has no assigned fixed loadding address.
716 **/
717 EFI_STATUS
718 GetPeCoffImageFixLoadingAssignedAddress(
719 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
720 )
721 {
722 UINTN SectionHeaderOffset;
723 EFI_STATUS Status;
724 EFI_IMAGE_SECTION_HEADER SectionHeader;
725 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
726 EFI_PHYSICAL_ADDRESS FixLoaddingAddress;
727 UINT16 Index;
728 UINTN Size;
729 UINT16 NumberOfSections;
730 EFI_PHYSICAL_ADDRESS SmramBase;
731 UINT64 SmmCodeSize;
732 UINT64 ValueInSectionHeader;
733 //
734 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
735 //
736 SmmCodeSize = EFI_PAGES_TO_SIZE (PcdGet32(PcdLoadFixAddressSmmCodePageNumber));
737
738 FixLoaddingAddress = 0;
739 Status = EFI_NOT_FOUND;
740 SmramBase = mCurrentSmramRange->CpuStart;
741 //
742 // Get PeHeader pointer
743 //
744 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset);
745 SectionHeaderOffset = (UINTN)(
746 ImageContext->PeCoffHeaderOffset +
747 sizeof (UINT32) +
748 sizeof (EFI_IMAGE_FILE_HEADER) +
749 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader
750 );
751 NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections;
752
753 //
754 // Get base address from the first section header that doesn't point to code section.
755 //
756 for (Index = 0; Index < NumberOfSections; Index++) {
757 //
758 // Read section header from file
759 //
760 Size = sizeof (EFI_IMAGE_SECTION_HEADER);
761 Status = ImageContext->ImageRead (
762 ImageContext->Handle,
763 SectionHeaderOffset,
764 &Size,
765 &SectionHeader
766 );
767 if (EFI_ERROR (Status)) {
768 return Status;
769 }
770
771 Status = EFI_NOT_FOUND;
772
773 if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) {
774 //
775 // Build tool saves the offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields in the
776 // first section header that doesn't point to code section in image header. And there is an assumption that when the
777 // feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers
778 // fields should NOT be Zero, or else, these 2 fileds should be set to Zero
779 //
780 ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations);
781 if (ValueInSectionHeader != 0) {
782 //
783 // Found first section header that doesn't point to code section in which uild tool saves the
784 // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields
785 //
786 FixLoaddingAddress = (EFI_PHYSICAL_ADDRESS)(SmramBase + (INT64)ValueInSectionHeader);
787
788 if (SmramBase + SmmCodeSize > FixLoaddingAddress && SmramBase <= FixLoaddingAddress) {
789 //
790 // The assigned address is valid. Return the specified loadding address
791 //
792 ImageContext->ImageAddress = FixLoaddingAddress;
793 Status = EFI_SUCCESS;
794 }
795 }
796 break;
797 }
798 SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);
799 }
800 DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r \n", FixLoaddingAddress, Status));
801 return Status;
802 }
803 /**
804 Load the SMM Core image into SMRAM and executes the SMM Core from SMRAM.
805
806 @param[in] SmramRange Descriptor for the range of SMRAM to reload the
807 currently executing image.
808 @param[in] Context Context to pass into SMM Core
809
810 @return EFI_STATUS
811
812 **/
813 EFI_STATUS
814 ExecuteSmmCoreFromSmram (
815 IN EFI_SMRAM_DESCRIPTOR *SmramRange,
816 IN VOID *Context
817 )
818 {
819 EFI_STATUS Status;
820 VOID *SourceBuffer;
821 UINTN SourceSize;
822 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
823 UINTN PageCount;
824 EFI_PHYSICAL_ADDRESS DestinationBuffer;
825 EFI_IMAGE_ENTRY_POINT EntryPoint;
826
827 //
828 // Search all Firmware Volumes for a PE/COFF image in a file of type SMM_CORE
829 //
830 SourceBuffer = GetSectionInAnyFv (EFI_FV_FILETYPE_SMM_CORE, EFI_SECTION_PE32, &SourceSize);
831 if (SourceBuffer == NULL) {
832 return EFI_NOT_FOUND;
833 }
834
835 //
836 // Initilize ImageContext
837 //
838 ImageContext.Handle = SourceBuffer;
839 ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory;
840
841 //
842 // Get information about the image being loaded
843 //
844 Status = PeCoffLoaderGetImageInfo (&ImageContext);
845 if (EFI_ERROR (Status)) {
846 return Status;
847 }
848 //
849 // if Loading module at Fixed Address feature is enabled, the SMM core driver will be loaded to
850 // the address assigned by build tool.
851 //
852 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {
853 //
854 // Get the fixed loading address assigned by Build tool
855 //
856 Status = GetPeCoffImageFixLoadingAssignedAddress (&ImageContext);
857 if (!EFI_ERROR (Status)) {
858 //
859 // Since the memory range to load SMM CORE will be cut out in SMM core, so no need to allocate and free this range
860 //
861 PageCount = 0;
862 } else {
863 DEBUG ((EFI_D_INFO, "LOADING MODULE FIXED ERROR: Loading module at fixed address at address failed\n"));
864 //
865 // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR
866 // specified by SmramRange
867 //
868 PageCount = (UINTN)EFI_SIZE_TO_PAGES(ImageContext.ImageSize + ImageContext.SectionAlignment);
869
870 ASSERT ((SmramRange->PhysicalSize & EFI_PAGE_MASK) == 0);
871 ASSERT (SmramRange->PhysicalSize > EFI_PAGES_TO_SIZE (PageCount));
872
873 SmramRange->PhysicalSize -= EFI_PAGES_TO_SIZE (PageCount);
874 DestinationBuffer = SmramRange->CpuStart + SmramRange->PhysicalSize;
875
876 //
877 // Align buffer on section boundry
878 //
879 ImageContext.ImageAddress = DestinationBuffer;
880 }
881 } else {
882 //
883 // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR
884 // specified by SmramRange
885 //
886 PageCount = (UINTN)EFI_SIZE_TO_PAGES(ImageContext.ImageSize + ImageContext.SectionAlignment);
887
888 ASSERT ((SmramRange->PhysicalSize & EFI_PAGE_MASK) == 0);
889 ASSERT (SmramRange->PhysicalSize > EFI_PAGES_TO_SIZE (PageCount));
890
891 SmramRange->PhysicalSize -= EFI_PAGES_TO_SIZE (PageCount);
892 DestinationBuffer = SmramRange->CpuStart + SmramRange->PhysicalSize;
893
894 //
895 // Align buffer on section boundry
896 //
897 ImageContext.ImageAddress = DestinationBuffer;
898 }
899
900 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
901 ImageContext.ImageAddress &= ~(ImageContext.SectionAlignment - 1);
902
903 //
904 // Print debug message showing SMM Core load address.
905 //
906 DEBUG ((DEBUG_INFO, "SMM IPL loading SMM Core at SMRAM address %p\n", (VOID *)(UINTN)ImageContext.ImageAddress));
907
908 //
909 // Load the image to our new buffer
910 //
911 Status = PeCoffLoaderLoadImage (&ImageContext);
912 if (!EFI_ERROR (Status)) {
913 //
914 // Relocate the image in our new buffer
915 //
916 Status = PeCoffLoaderRelocateImage (&ImageContext);
917 if (!EFI_ERROR (Status)) {
918 //
919 // Flush the instruction cache so the image data are written before we execute it
920 //
921 InvalidateInstructionCacheRange ((VOID *)(UINTN)ImageContext.ImageAddress, (UINTN)ImageContext.ImageSize);
922
923 //
924 // Print debug message showing SMM Core entry point address.
925 //
926 DEBUG ((DEBUG_INFO, "SMM IPL calling SMM Core at SMRAM address %p\n", (VOID *)(UINTN)ImageContext.EntryPoint));
927
928 //
929 // Execute image
930 //
931 EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)ImageContext.EntryPoint;
932 Status = EntryPoint ((EFI_HANDLE)Context, gST);
933 }
934 }
935
936 //
937 // If the load operation, relocate operation, or the image execution return an
938 // error, then free memory allocated from the EFI_SRAM_DESCRIPTOR specified by
939 // SmramRange
940 //
941 if (EFI_ERROR (Status)) {
942 SmramRange->PhysicalSize += EFI_PAGES_TO_SIZE (PageCount);
943 }
944
945 //
946 // Always free memory allocted by GetFileBufferByFilePath ()
947 //
948 FreePool (SourceBuffer);
949
950 return Status;
951 }
952
953 /**
954 The Entry Point for SMM IPL
955
956 Load SMM Core into SMRAM, register SMM Core entry point for SMIs, install
957 SMM Base 2 Protocol and SMM Communication Protocol, and register for the
958 critical events required to coordinate between DXE and SMM environments.
959
960 @param ImageHandle The firmware allocated handle for the EFI image.
961 @param SystemTable A pointer to the EFI System Table.
962
963 @retval EFI_SUCCESS The entry point is executed successfully.
964 @retval Other Some error occurred when executing this entry point.
965
966 **/
967 EFI_STATUS
968 EFIAPI
969 SmmIplEntry (
970 IN EFI_HANDLE ImageHandle,
971 IN EFI_SYSTEM_TABLE *SystemTable
972 )
973 {
974 EFI_STATUS Status;
975 EFI_SMM_CONFIGURATION_PROTOCOL *SmmConfiguration;
976 UINTN Size;
977 UINTN Index;
978 EFI_SMM_RESERVED_SMRAM_REGION *SmramResRegion;
979 UINT64 MaxSize;
980 VOID *Registration;
981 UINT64 SmmCodeSize;
982 EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE *LMFAConfigurationTable;
983
984 //
985 // Fill in the image handle of the SMM IPL so the SMM Core can use this as the
986 // ParentImageHandle field of the Load Image Protocol for all SMM Drivers loaded
987 // by the SMM Core
988 //
989 mSmmCorePrivateData.SmmIplImageHandle = ImageHandle;
990
991 //
992 // Get SMM Access Protocol
993 //
994 Status = gBS->LocateProtocol (&gEfiSmmAccess2ProtocolGuid, NULL, (VOID **)&mSmmAccess);
995 ASSERT_EFI_ERROR (Status);
996
997 //
998 // Get SMM Control2 Protocol
999 //
1000 Status = gBS->LocateProtocol (&gEfiSmmControl2ProtocolGuid, NULL, (VOID **)&mSmmControl2);
1001 ASSERT_EFI_ERROR (Status);
1002
1003 //
1004 // Get SMM Configuration Protocol if it is present
1005 //
1006 SmmConfiguration = NULL;
1007 Status = gBS->LocateProtocol (&gEfiSmmConfigurationProtocolGuid, NULL, (VOID **) &SmmConfiguration);
1008
1009 //
1010 // Get SMRAM information
1011 //
1012 Size = 0;
1013 Status = mSmmAccess->GetCapabilities (mSmmAccess, &Size, NULL);
1014 ASSERT (Status == EFI_BUFFER_TOO_SMALL);
1015
1016 gSmmCorePrivate->SmramRanges = (EFI_SMRAM_DESCRIPTOR *)AllocatePool (Size);
1017 ASSERT (gSmmCorePrivate->SmramRanges != NULL);
1018
1019 Status = mSmmAccess->GetCapabilities (mSmmAccess, &Size, gSmmCorePrivate->SmramRanges);
1020 ASSERT_EFI_ERROR (Status);
1021
1022 gSmmCorePrivate->SmramRangeCount = Size / sizeof (EFI_SMRAM_DESCRIPTOR);
1023
1024 //
1025 // Open all SMRAM ranges
1026 //
1027 Status = mSmmAccess->Open (mSmmAccess);
1028 ASSERT_EFI_ERROR (Status);
1029
1030 //
1031 // Print debug message that the SMRAM window is now open.
1032 //
1033 DEBUG ((DEBUG_INFO, "SMM IPL opened SMRAM window\n"));
1034
1035 //
1036 // Subtract SMRAM any reserved SMRAM regions.
1037 //
1038 if (SmmConfiguration != NULL) {
1039 SmramResRegion = SmmConfiguration->SmramReservedRegions;
1040 while (SmramResRegion->SmramReservedSize != 0) {
1041 for (Index = 0; Index < gSmmCorePrivate->SmramRangeCount; Index ++) {
1042 if ((SmramResRegion->SmramReservedStart >= gSmmCorePrivate->SmramRanges[Index].CpuStart) && \
1043 ((SmramResRegion->SmramReservedStart + SmramResRegion->SmramReservedSize) <= \
1044 (gSmmCorePrivate->SmramRanges[Index].CpuStart + gSmmCorePrivate->SmramRanges[Index].PhysicalSize))) {
1045 //
1046 // This range has reserved area, calculate the left free size
1047 //
1048 gSmmCorePrivate->SmramRanges[Index].PhysicalSize = SmramResRegion->SmramReservedStart - gSmmCorePrivate->SmramRanges[Index].CpuStart;
1049 }
1050 }
1051 SmramResRegion++;
1052 }
1053 }
1054
1055 //
1056 // Find the largest SMRAM range between 1MB and 4GB that is at least 256KB - 4K in size
1057 //
1058 mCurrentSmramRange = NULL;
1059 for (Index = 0, MaxSize = SIZE_256KB - EFI_PAGE_SIZE; Index < gSmmCorePrivate->SmramRangeCount; Index++) {
1060 if (gSmmCorePrivate->SmramRanges[Index].CpuStart >= BASE_1MB) {
1061 if ((gSmmCorePrivate->SmramRanges[Index].CpuStart + gSmmCorePrivate->SmramRanges[Index].PhysicalSize) <= BASE_4GB) {
1062 if (gSmmCorePrivate->SmramRanges[Index].PhysicalSize >= MaxSize) {
1063 MaxSize = gSmmCorePrivate->SmramRanges[Index].PhysicalSize;
1064 mCurrentSmramRange = &gSmmCorePrivate->SmramRanges[Index];
1065 }
1066 }
1067 }
1068 }
1069
1070 if (mCurrentSmramRange != NULL) {
1071 //
1072 // Print debug message showing SMRAM window that will be used by SMM IPL and SMM Core
1073 //
1074 DEBUG ((DEBUG_INFO, "SMM IPL found SMRAM window %p - %p\n",
1075 (VOID *)(UINTN)mCurrentSmramRange->CpuStart,
1076 (VOID *)(UINTN)(mCurrentSmramRange->CpuStart + mCurrentSmramRange->PhysicalSize - 1)
1077 ));
1078
1079 //
1080 // Attempt to set SMRAM cacheability to WB
1081 //
1082 Status = gDS->SetMemorySpaceAttributes(
1083 mCurrentSmramRange->CpuStart,
1084 mCurrentSmramRange->PhysicalSize,
1085 EFI_MEMORY_WB
1086 );
1087 if (EFI_ERROR (Status)) {
1088 DEBUG ((DEBUG_WARN, "SMM IPL failed to set SMRAM window to EFI_MEMORY_WB\n"));
1089 }
1090 //
1091 // if Loading module at Fixed Address feature is enabled, save the SMRAM base to Load
1092 // Modules At Fixed Address Configuration Table.
1093 //
1094 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {
1095 //
1096 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
1097 //
1098 SmmCodeSize = LShiftU64 (PcdGet32(PcdLoadFixAddressSmmCodePageNumber), EFI_PAGE_SHIFT);
1099 //
1100 // The SMRAM available memory is assumed to be larger than SmmCodeSize
1101 //
1102 ASSERT (mCurrentSmramRange->PhysicalSize > SmmCodeSize);
1103 //
1104 // Retrieve Load modules At fixed address configuration table and save the SMRAM base.
1105 //
1106 Status = EfiGetSystemConfigurationTable (
1107 &gLoadFixedAddressConfigurationTableGuid,
1108 (VOID **) &LMFAConfigurationTable
1109 );
1110 if (!EFI_ERROR (Status) && LMFAConfigurationTable != NULL) {
1111 LMFAConfigurationTable->SmramBase = mCurrentSmramRange->CpuStart;
1112 }
1113 //
1114 // Print the SMRAM base
1115 //
1116 DEBUG ((EFI_D_INFO, "LOADING MODULE FIXED INFO: TSEG BASE is %x. \n", LMFAConfigurationTable->SmramBase));
1117 }
1118 //
1119 // Load SMM Core into SMRAM and execute it from SMRAM
1120 //
1121 Status = ExecuteSmmCoreFromSmram (mCurrentSmramRange, gSmmCorePrivate);
1122 if (EFI_ERROR (Status)) {
1123 //
1124 // Print error message that the SMM Core failed to be loaded and executed.
1125 //
1126 DEBUG ((DEBUG_ERROR, "SMM IPL could not load and execute SMM Core from SMRAM\n"));
1127
1128 //
1129 // Attempt to reset SMRAM cacheability to UC
1130 //
1131 Status = gDS->SetMemorySpaceAttributes(
1132 mCurrentSmramRange->CpuStart,
1133 mCurrentSmramRange->PhysicalSize,
1134 EFI_MEMORY_UC
1135 );
1136 if (EFI_ERROR (Status)) {
1137 DEBUG ((DEBUG_WARN, "SMM IPL failed to reset SMRAM window to EFI_MEMORY_UC\n"));
1138 }
1139 }
1140 } else {
1141 //
1142 // Print error message that there are not enough SMRAM resources to load the SMM Core.
1143 //
1144 DEBUG ((DEBUG_ERROR, "SMM IPL could not find a large enough SMRAM region to load SMM Core\n"));
1145 }
1146
1147 //
1148 // If the SMM Core could not be loaded then close SMRAM window, free allocated
1149 // resources, and return an error so SMM IPL will be unloaded.
1150 //
1151 if (mCurrentSmramRange == NULL || EFI_ERROR (Status)) {
1152 //
1153 // Close all SMRAM ranges
1154 //
1155 Status = mSmmAccess->Close (mSmmAccess);
1156 ASSERT_EFI_ERROR (Status);
1157
1158 //
1159 // Print debug message that the SMRAM window is now closed.
1160 //
1161 DEBUG ((DEBUG_INFO, "SMM IPL closed SMRAM window\n"));
1162
1163 //
1164 // Free all allocated resources
1165 //
1166 FreePool (gSmmCorePrivate->SmramRanges);
1167
1168 return EFI_UNSUPPORTED;
1169 }
1170
1171 //
1172 // Install SMM Base2 Protocol and SMM Communication Protocol
1173 //
1174 Status = gBS->InstallMultipleProtocolInterfaces (
1175 &mSmmIplHandle,
1176 &gEfiSmmBase2ProtocolGuid, &mSmmBase2,
1177 &gEfiSmmCommunicationProtocolGuid, &mSmmCommunication,
1178 NULL
1179 );
1180 ASSERT_EFI_ERROR (Status);
1181
1182 //
1183 // Create the set of protocol and event notififcations that the SMM IPL requires
1184 //
1185 for (Index = 0; mSmmIplEvents[Index].NotifyFunction != NULL; Index++) {
1186 if (mSmmIplEvents[Index].Protocol) {
1187 mSmmIplEvents[Index].Event = EfiCreateProtocolNotifyEvent (
1188 mSmmIplEvents[Index].Guid,
1189 TPL_CALLBACK,
1190 mSmmIplEvents[Index].NotifyFunction,
1191 mSmmIplEvents[Index].NotifyContext,
1192 &Registration
1193 );
1194 } else {
1195 Status = gBS->CreateEventEx (
1196 EVT_NOTIFY_SIGNAL,
1197 TPL_CALLBACK,
1198 mSmmIplEvents[Index].NotifyFunction,
1199 mSmmIplEvents[Index].NotifyContext,
1200 mSmmIplEvents[Index].Guid,
1201 &mSmmIplEvents[Index].Event
1202 );
1203 ASSERT_EFI_ERROR (Status);
1204 }
1205 }
1206
1207 return EFI_SUCCESS;
1208 }