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