]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Core/PiSmmCore/PiSmmIpl.c
MdeModulePkg/SmmIpl: expose MM communicate 2 protocol
[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 - 2018, Intel Corporation. All rights reserved.<BR>
5 SPDX-License-Identifier: BSD-2-Clause-Patent
6
7 **/
8
9 #include <PiDxe.h>
10
11 #include <Protocol/SmmBase2.h>
12 #include <Protocol/SmmCommunication.h>
13 #include <Protocol/MmCommunication2.h>
14 #include <Protocol/SmmAccess2.h>
15 #include <Protocol/SmmConfiguration.h>
16 #include <Protocol/SmmControl2.h>
17 #include <Protocol/DxeSmmReadyToLock.h>
18 #include <Protocol/Cpu.h>
19
20 #include <Guid/EventGroup.h>
21 #include <Guid/EventLegacyBios.h>
22 #include <Guid/LoadModuleAtFixedAddress.h>
23
24 #include <Library/BaseLib.h>
25 #include <Library/BaseMemoryLib.h>
26 #include <Library/PeCoffLib.h>
27 #include <Library/CacheMaintenanceLib.h>
28 #include <Library/MemoryAllocationLib.h>
29 #include <Library/DebugLib.h>
30 #include <Library/UefiBootServicesTableLib.h>
31 #include <Library/DxeServicesTableLib.h>
32 #include <Library/DxeServicesLib.h>
33 #include <Library/UefiLib.h>
34 #include <Library/UefiRuntimeLib.h>
35 #include <Library/PcdLib.h>
36 #include <Library/ReportStatusCodeLib.h>
37
38 #include "PiSmmCorePrivateData.h"
39
40 #define SMRAM_CAPABILITIES (EFI_MEMORY_WB | EFI_MEMORY_UC)
41
42 #define MEMORY_CACHE_ATTRIBUTES (EFI_MEMORY_UC | EFI_MEMORY_WC | \
43 EFI_MEMORY_WT | EFI_MEMORY_WB | \
44 EFI_MEMORY_WP | EFI_MEMORY_UCE)
45
46 #define MEMORY_PAGE_ATTRIBUTES (EFI_MEMORY_XP | EFI_MEMORY_RP | EFI_MEMORY_RO)
47
48 //
49 // Function prototypes from produced protocols
50 //
51
52 /**
53 Indicate whether the driver is currently executing in the SMM Initialization phase.
54
55 @param This The EFI_SMM_BASE2_PROTOCOL instance.
56 @param InSmram Pointer to a Boolean which, on return, indicates that the driver is currently executing
57 inside of SMRAM (TRUE) or outside of SMRAM (FALSE).
58
59 @retval EFI_INVALID_PARAMETER InSmram was NULL.
60 @retval EFI_SUCCESS The call returned successfully.
61
62 **/
63 EFI_STATUS
64 EFIAPI
65 SmmBase2InSmram (
66 IN CONST EFI_SMM_BASE2_PROTOCOL *This,
67 OUT BOOLEAN *InSmram
68 );
69
70 /**
71 Retrieves the location of the System Management System Table (SMST).
72
73 @param This The EFI_SMM_BASE2_PROTOCOL instance.
74 @param Smst On return, points to a pointer to the System Management Service Table (SMST).
75
76 @retval EFI_INVALID_PARAMETER Smst or This was invalid.
77 @retval EFI_SUCCESS The memory was returned to the system.
78 @retval EFI_UNSUPPORTED Not in SMM.
79
80 **/
81 EFI_STATUS
82 EFIAPI
83 SmmBase2GetSmstLocation (
84 IN CONST EFI_SMM_BASE2_PROTOCOL *This,
85 OUT EFI_SMM_SYSTEM_TABLE2 **Smst
86 );
87
88 /**
89 Communicates with a registered handler.
90
91 This function provides a service to send and receive messages from a registered
92 UEFI service. This function is part of the SMM Communication Protocol that may
93 be called in physical mode prior to SetVirtualAddressMap() and in virtual mode
94 after SetVirtualAddressMap().
95
96 @param[in] This The EFI_SMM_COMMUNICATION_PROTOCOL instance.
97 @param[in, out] CommBuffer A pointer to the buffer to convey into SMRAM.
98 @param[in, out] CommSize The size of the data buffer being passed in. On exit, the size of data
99 being returned. Zero if the handler does not wish to reply with any data.
100 This parameter is optional and may be NULL.
101
102 @retval EFI_SUCCESS The message was successfully posted.
103 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
104 @retval EFI_BAD_BUFFER_SIZE The buffer is too large for the MM implementation.
105 If this error is returned, the MessageLength field
106 in the CommBuffer header or the integer pointed by
107 CommSize, are updated to reflect the maximum payload
108 size the implementation can accommodate.
109 @retval EFI_ACCESS_DENIED The CommunicateBuffer parameter or CommSize parameter,
110 if not omitted, are in address range that cannot be
111 accessed by the MM environment.
112
113 **/
114 EFI_STATUS
115 EFIAPI
116 SmmCommunicationCommunicate (
117 IN CONST EFI_SMM_COMMUNICATION_PROTOCOL *This,
118 IN OUT VOID *CommBuffer,
119 IN OUT UINTN *CommSize OPTIONAL
120 );
121
122 /**
123 Communicates with a registered handler.
124
125 This function provides a service to send and receive messages from a registered UEFI service.
126
127 @param[in] This The EFI_MM_COMMUNICATION_PROTOCOL instance.
128 @param[in] CommBufferPhysical Physical address of the MM communication buffer
129 @param[in] CommBufferVirtual Virtual address of the MM communication buffer
130 @param[in] CommSize The size of the data buffer being passed in. On exit, the size of data
131 being returned. Zero if the handler does not wish to reply with any data.
132 This parameter is optional and may be NULL.
133
134 @retval EFI_SUCCESS The message was successfully posted.
135 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
136 @retval EFI_BAD_BUFFER_SIZE The buffer is too large for the MM implementation.
137 If this error is returned, the MessageLength field
138 in the CommBuffer header or the integer pointed by
139 CommSize, are updated to reflect the maximum payload
140 size the implementation can accommodate.
141 @retval EFI_ACCESS_DENIED The CommunicateBuffer parameter or CommSize parameter,
142 if not omitted, are in address range that cannot be
143 accessed by the MM environment.
144
145 **/
146 EFI_STATUS
147 EFIAPI
148 SmmCommunicationMmCommunicate2 (
149 IN CONST EFI_MM_COMMUNICATION2_PROTOCOL *This,
150 IN OUT VOID *CommBufferPhysical,
151 IN OUT VOID *CommBufferVirtual,
152 IN OUT UINTN *CommSize OPTIONAL
153 );
154
155 /**
156 Event notification that is fired every time a gEfiSmmConfigurationProtocol installs.
157
158 @param Event The Event that is being processed, not used.
159 @param Context Event Context, not used.
160
161 **/
162 VOID
163 EFIAPI
164 SmmIplSmmConfigurationEventNotify (
165 IN EFI_EVENT Event,
166 IN VOID *Context
167 );
168
169 /**
170 Event notification that is fired every time a DxeSmmReadyToLock protocol is added
171 or if gEfiEventReadyToBootGuid is signalled.
172
173 @param Event The Event that is being processed, not used.
174 @param Context Event Context, not used.
175
176 **/
177 VOID
178 EFIAPI
179 SmmIplReadyToLockEventNotify (
180 IN EFI_EVENT Event,
181 IN VOID *Context
182 );
183
184 /**
185 Event notification that is fired when DxeDispatch Event Group is signaled.
186
187 @param Event The Event that is being processed, not used.
188 @param Context Event Context, not used.
189
190 **/
191 VOID
192 EFIAPI
193 SmmIplDxeDispatchEventNotify (
194 IN EFI_EVENT Event,
195 IN VOID *Context
196 );
197
198 /**
199 Event notification that is fired when a GUIDed Event Group is signaled.
200
201 @param Event The Event that is being processed, not used.
202 @param Context Event Context, not used.
203
204 **/
205 VOID
206 EFIAPI
207 SmmIplGuidedEventNotify (
208 IN EFI_EVENT Event,
209 IN VOID *Context
210 );
211
212 /**
213 Event notification that is fired when EndOfDxe Event Group is signaled.
214
215 @param Event The Event that is being processed, not used.
216 @param Context Event Context, not used.
217
218 **/
219 VOID
220 EFIAPI
221 SmmIplEndOfDxeEventNotify (
222 IN EFI_EVENT Event,
223 IN VOID *Context
224 );
225
226 /**
227 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
228
229 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
230 It convers pointer to new virtual address.
231
232 @param Event Event whose notification function is being invoked.
233 @param Context Pointer to the notification function's context.
234
235 **/
236 VOID
237 EFIAPI
238 SmmIplSetVirtualAddressNotify (
239 IN EFI_EVENT Event,
240 IN VOID *Context
241 );
242
243 //
244 // Data structure used to declare a table of protocol notifications and event
245 // notifications required by the SMM IPL
246 //
247 typedef struct {
248 BOOLEAN Protocol;
249 BOOLEAN CloseOnLock;
250 EFI_GUID *Guid;
251 EFI_EVENT_NOTIFY NotifyFunction;
252 VOID *NotifyContext;
253 EFI_TPL NotifyTpl;
254 EFI_EVENT Event;
255 } SMM_IPL_EVENT_NOTIFICATION;
256
257 //
258 // Handle to install the SMM Base2 Protocol and the SMM Communication Protocol
259 //
260 EFI_HANDLE mSmmIplHandle = NULL;
261
262 //
263 // SMM Base 2 Protocol instance
264 //
265 EFI_SMM_BASE2_PROTOCOL mSmmBase2 = {
266 SmmBase2InSmram,
267 SmmBase2GetSmstLocation
268 };
269
270 //
271 // SMM Communication Protocol instance
272 //
273 EFI_SMM_COMMUNICATION_PROTOCOL mSmmCommunication = {
274 SmmCommunicationCommunicate
275 };
276
277 //
278 // PI 1.7 MM Communication Protocol 2 instance
279 //
280 EFI_MM_COMMUNICATION2_PROTOCOL mMmCommunication2 = {
281 SmmCommunicationMmCommunicate2
282 };
283
284 //
285 // SMM Core Private Data structure that contains the data shared between
286 // the SMM IPL and the SMM Core.
287 //
288 SMM_CORE_PRIVATE_DATA mSmmCorePrivateData = {
289 SMM_CORE_PRIVATE_DATA_SIGNATURE, // Signature
290 NULL, // SmmIplImageHandle
291 0, // SmramRangeCount
292 NULL, // SmramRanges
293 NULL, // SmmEntryPoint
294 FALSE, // SmmEntryPointRegistered
295 FALSE, // InSmm
296 NULL, // Smst
297 NULL, // CommunicationBuffer
298 0, // BufferSize
299 EFI_SUCCESS // ReturnStatus
300 };
301
302 //
303 // Global pointer used to access mSmmCorePrivateData from outside and inside SMM
304 //
305 SMM_CORE_PRIVATE_DATA *gSmmCorePrivate = &mSmmCorePrivateData;
306
307 //
308 // SMM IPL global variables
309 //
310 EFI_SMM_CONTROL2_PROTOCOL *mSmmControl2;
311 EFI_SMM_ACCESS2_PROTOCOL *mSmmAccess;
312 EFI_SMRAM_DESCRIPTOR *mCurrentSmramRange;
313 BOOLEAN mSmmLocked = FALSE;
314 BOOLEAN mEndOfDxe = FALSE;
315 EFI_PHYSICAL_ADDRESS mSmramCacheBase;
316 UINT64 mSmramCacheSize;
317
318 EFI_SMM_COMMUNICATE_HEADER mCommunicateHeader;
319 EFI_LOAD_FIXED_ADDRESS_CONFIGURATION_TABLE *mLMFAConfigurationTable = NULL;
320
321 //
322 // Table of Protocol notification and GUIDed Event notifications that the SMM IPL requires
323 //
324 SMM_IPL_EVENT_NOTIFICATION mSmmIplEvents[] = {
325 //
326 // Declare protocol notification on the SMM Configuration protocol. When this notification is established,
327 // the associated event is immediately signalled, so the notification function will be executed and the
328 // SMM Configuration Protocol will be found if it is already in the handle database.
329 //
330 { TRUE, FALSE, &gEfiSmmConfigurationProtocolGuid, SmmIplSmmConfigurationEventNotify, &gEfiSmmConfigurationProtocolGuid, TPL_NOTIFY, NULL },
331 //
332 // Declare protocol notification on DxeSmmReadyToLock protocols. When this notification is established,
333 // the associated event is immediately signalled, so the notification function will be executed and the
334 // DXE SMM Ready To Lock Protocol will be found if it is already in the handle database.
335 //
336 { TRUE, TRUE, &gEfiDxeSmmReadyToLockProtocolGuid, SmmIplReadyToLockEventNotify, &gEfiDxeSmmReadyToLockProtocolGuid, TPL_CALLBACK, NULL },
337 //
338 // Declare event notification on EndOfDxe event. When this notification is established,
339 // the associated event is immediately signalled, so the notification function will be executed and the
340 // SMM End Of Dxe Protocol will be found if it is already in the handle database.
341 //
342 { FALSE, TRUE, &gEfiEndOfDxeEventGroupGuid, SmmIplGuidedEventNotify, &gEfiEndOfDxeEventGroupGuid, TPL_CALLBACK, NULL },
343 //
344 // Declare event notification on EndOfDxe event. This is used to set EndOfDxe event signaled flag.
345 //
346 { FALSE, TRUE, &gEfiEndOfDxeEventGroupGuid, SmmIplEndOfDxeEventNotify, &gEfiEndOfDxeEventGroupGuid, TPL_CALLBACK, NULL },
347 //
348 // Declare event notification on the DXE Dispatch Event Group. This event is signaled by the DXE Core
349 // each time the DXE Core dispatcher has completed its work. When this event is signalled, the SMM Core
350 // if notified, so the SMM Core can dispatch SMM drivers.
351 //
352 { FALSE, TRUE, &gEfiEventDxeDispatchGuid, SmmIplDxeDispatchEventNotify, &gEfiEventDxeDispatchGuid, TPL_CALLBACK, NULL },
353 //
354 // Declare event notification on Ready To Boot Event Group. This is an extra event notification that is
355 // used to make sure SMRAM is locked before any boot options are processed.
356 //
357 { FALSE, TRUE, &gEfiEventReadyToBootGuid, SmmIplReadyToLockEventNotify, &gEfiEventReadyToBootGuid, TPL_CALLBACK, NULL },
358 //
359 // Declare event notification on Legacy Boot Event Group. This is used to inform the SMM Core that the platform
360 // is performing a legacy boot operation, and that the UEFI environment is no longer available and the SMM Core
361 // must guarantee that it does not access any UEFI related structures outside of SMRAM.
362 // It is also to inform the SMM Core to notify SMM driver that system enter legacy boot.
363 //
364 { FALSE, FALSE, &gEfiEventLegacyBootGuid, SmmIplGuidedEventNotify, &gEfiEventLegacyBootGuid, TPL_CALLBACK, NULL },
365 //
366 // Declare event notification on Exit Boot Services Event Group. This is used to inform the SMM Core
367 // to notify SMM driver that system enter exit boot services.
368 //
369 { FALSE, FALSE, &gEfiEventExitBootServicesGuid, SmmIplGuidedEventNotify, &gEfiEventExitBootServicesGuid, TPL_CALLBACK, NULL },
370 //
371 // Declare event notification on Ready To Boot Event Group. This is used to inform the SMM Core
372 // to notify SMM driver that system enter ready to boot.
373 //
374 { FALSE, FALSE, &gEfiEventReadyToBootGuid, SmmIplGuidedEventNotify, &gEfiEventReadyToBootGuid, TPL_CALLBACK, NULL },
375 //
376 // Declare event notification on SetVirtualAddressMap() Event Group. This is used to convert gSmmCorePrivate
377 // and mSmmControl2 from physical addresses to virtual addresses.
378 //
379 { FALSE, FALSE, &gEfiEventVirtualAddressChangeGuid, SmmIplSetVirtualAddressNotify, NULL, TPL_CALLBACK, NULL },
380 //
381 // Terminate the table of event notifications
382 //
383 { FALSE, FALSE, NULL, NULL, NULL, TPL_CALLBACK, NULL }
384 };
385
386 /**
387 Find the maximum SMRAM cache range that covers the range specified by SmramRange.
388
389 This function searches and joins all adjacent ranges of SmramRange into a range to be cached.
390
391 @param SmramRange The SMRAM range to search from.
392 @param SmramCacheBase The returned cache range base.
393 @param SmramCacheSize The returned cache range size.
394
395 **/
396 VOID
397 GetSmramCacheRange (
398 IN EFI_SMRAM_DESCRIPTOR *SmramRange,
399 OUT EFI_PHYSICAL_ADDRESS *SmramCacheBase,
400 OUT UINT64 *SmramCacheSize
401 )
402 {
403 UINTN Index;
404 EFI_PHYSICAL_ADDRESS RangeCpuStart;
405 UINT64 RangePhysicalSize;
406 BOOLEAN FoundAjacentRange;
407
408 *SmramCacheBase = SmramRange->CpuStart;
409 *SmramCacheSize = SmramRange->PhysicalSize;
410
411 do {
412 FoundAjacentRange = FALSE;
413 for (Index = 0; Index < gSmmCorePrivate->SmramRangeCount; Index++) {
414 RangeCpuStart = gSmmCorePrivate->SmramRanges[Index].CpuStart;
415 RangePhysicalSize = gSmmCorePrivate->SmramRanges[Index].PhysicalSize;
416 if (RangeCpuStart < *SmramCacheBase && *SmramCacheBase == (RangeCpuStart + RangePhysicalSize)) {
417 *SmramCacheBase = RangeCpuStart;
418 *SmramCacheSize += RangePhysicalSize;
419 FoundAjacentRange = TRUE;
420 } else if ((*SmramCacheBase + *SmramCacheSize) == RangeCpuStart && RangePhysicalSize > 0) {
421 *SmramCacheSize += RangePhysicalSize;
422 FoundAjacentRange = TRUE;
423 }
424 }
425 } while (FoundAjacentRange);
426
427 }
428
429 /**
430 Indicate whether the driver is currently executing in the SMM Initialization phase.
431
432 @param This The EFI_SMM_BASE2_PROTOCOL instance.
433 @param InSmram Pointer to a Boolean which, on return, indicates that the driver is currently executing
434 inside of SMRAM (TRUE) or outside of SMRAM (FALSE).
435
436 @retval EFI_INVALID_PARAMETER InSmram was NULL.
437 @retval EFI_SUCCESS The call returned successfully.
438
439 **/
440 EFI_STATUS
441 EFIAPI
442 SmmBase2InSmram (
443 IN CONST EFI_SMM_BASE2_PROTOCOL *This,
444 OUT BOOLEAN *InSmram
445 )
446 {
447 if (InSmram == NULL) {
448 return EFI_INVALID_PARAMETER;
449 }
450
451 *InSmram = gSmmCorePrivate->InSmm;
452
453 return EFI_SUCCESS;
454 }
455
456 /**
457 Retrieves the location of the System Management System Table (SMST).
458
459 @param This The EFI_SMM_BASE2_PROTOCOL instance.
460 @param Smst On return, points to a pointer to the System Management Service Table (SMST).
461
462 @retval EFI_INVALID_PARAMETER Smst or This was invalid.
463 @retval EFI_SUCCESS The memory was returned to the system.
464 @retval EFI_UNSUPPORTED Not in SMM.
465
466 **/
467 EFI_STATUS
468 EFIAPI
469 SmmBase2GetSmstLocation (
470 IN CONST EFI_SMM_BASE2_PROTOCOL *This,
471 OUT EFI_SMM_SYSTEM_TABLE2 **Smst
472 )
473 {
474 if ((This == NULL) ||(Smst == NULL)) {
475 return EFI_INVALID_PARAMETER;
476 }
477
478 if (!gSmmCorePrivate->InSmm) {
479 return EFI_UNSUPPORTED;
480 }
481
482 *Smst = gSmmCorePrivate->Smst;
483
484 return EFI_SUCCESS;
485 }
486
487 /**
488 Communicates with a registered handler.
489
490 This function provides a service to send and receive messages from a registered
491 UEFI service. This function is part of the SMM Communication Protocol that may
492 be called in physical mode prior to SetVirtualAddressMap() and in virtual mode
493 after SetVirtualAddressMap().
494
495 @param[in] This The EFI_SMM_COMMUNICATION_PROTOCOL instance.
496 @param[in, out] CommBuffer A pointer to the buffer to convey into SMRAM.
497 @param[in, out] CommSize The size of the data buffer being passed in. On exit, the size of data
498 being returned. Zero if the handler does not wish to reply with any data.
499 This parameter is optional and may be NULL.
500
501 @retval EFI_SUCCESS The message was successfully posted.
502 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
503 @retval EFI_BAD_BUFFER_SIZE The buffer is too large for the MM implementation.
504 If this error is returned, the MessageLength field
505 in the CommBuffer header or the integer pointed by
506 CommSize, are updated to reflect the maximum payload
507 size the implementation can accommodate.
508 @retval EFI_ACCESS_DENIED The CommunicateBuffer parameter or CommSize parameter,
509 if not omitted, are in address range that cannot be
510 accessed by the MM environment.
511
512 **/
513 EFI_STATUS
514 EFIAPI
515 SmmCommunicationCommunicate (
516 IN CONST EFI_SMM_COMMUNICATION_PROTOCOL *This,
517 IN OUT VOID *CommBuffer,
518 IN OUT UINTN *CommSize OPTIONAL
519 )
520 {
521 EFI_STATUS Status;
522 EFI_SMM_COMMUNICATE_HEADER *CommunicateHeader;
523 BOOLEAN OldInSmm;
524 UINTN TempCommSize;
525
526 //
527 // Check parameters
528 //
529 if (CommBuffer == NULL) {
530 return EFI_INVALID_PARAMETER;
531 }
532
533 CommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *) CommBuffer;
534
535 if (CommSize == NULL) {
536 TempCommSize = OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data) + CommunicateHeader->MessageLength;
537 } else {
538 TempCommSize = *CommSize;
539 //
540 // CommSize must hold HeaderGuid and MessageLength
541 //
542 if (TempCommSize < OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data)) {
543 return EFI_INVALID_PARAMETER;
544 }
545 }
546
547 //
548 // If not already in SMM, then generate a Software SMI
549 //
550 if (!gSmmCorePrivate->InSmm && gSmmCorePrivate->SmmEntryPointRegistered) {
551 //
552 // Put arguments for Software SMI in gSmmCorePrivate
553 //
554 gSmmCorePrivate->CommunicationBuffer = CommBuffer;
555 gSmmCorePrivate->BufferSize = TempCommSize;
556
557 //
558 // Generate Software SMI
559 //
560 Status = mSmmControl2->Trigger (mSmmControl2, NULL, NULL, FALSE, 0);
561 if (EFI_ERROR (Status)) {
562 return EFI_UNSUPPORTED;
563 }
564
565 //
566 // Return status from software SMI
567 //
568 if (CommSize != NULL) {
569 *CommSize = gSmmCorePrivate->BufferSize;
570 }
571 return gSmmCorePrivate->ReturnStatus;
572 }
573
574 //
575 // If we are in SMM, then the execution mode must be physical, which means that
576 // OS established virtual addresses can not be used. If SetVirtualAddressMap()
577 // has been called, then a direct invocation of the Software SMI is not allowed,
578 // so return EFI_INVALID_PARAMETER.
579 //
580 if (EfiGoneVirtual()) {
581 return EFI_INVALID_PARAMETER;
582 }
583
584 //
585 // If we are not in SMM, don't allow call SmiManage() directly when SMRAM is closed or locked.
586 //
587 if ((!gSmmCorePrivate->InSmm) && (!mSmmAccess->OpenState || mSmmAccess->LockState)) {
588 return EFI_INVALID_PARAMETER;
589 }
590
591 //
592 // Save current InSmm state and set InSmm state to TRUE
593 //
594 OldInSmm = gSmmCorePrivate->InSmm;
595 gSmmCorePrivate->InSmm = TRUE;
596
597 //
598 // Before SetVirtualAddressMap(), we are in SMM or SMRAM is open and unlocked, call SmiManage() directly.
599 //
600 TempCommSize -= OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data);
601 Status = gSmmCorePrivate->Smst->SmiManage (
602 &CommunicateHeader->HeaderGuid,
603 NULL,
604 CommunicateHeader->Data,
605 &TempCommSize
606 );
607 TempCommSize += OFFSET_OF (EFI_SMM_COMMUNICATE_HEADER, Data);
608 if (CommSize != NULL) {
609 *CommSize = TempCommSize;
610 }
611
612 //
613 // Restore original InSmm state
614 //
615 gSmmCorePrivate->InSmm = OldInSmm;
616
617 return (Status == EFI_SUCCESS) ? EFI_SUCCESS : EFI_NOT_FOUND;
618 }
619
620 /**
621 Communicates with a registered handler.
622
623 This function provides a service to send and receive messages from a registered UEFI service.
624
625 @param[in] This The EFI_MM_COMMUNICATION_PROTOCOL instance.
626 @param[in] CommBufferPhysical Physical address of the MM communication buffer
627 @param[in] CommBufferVirtual Virtual address of the MM communication buffer
628 @param[in] CommSize The size of the data buffer being passed in. On exit, the size of data
629 being returned. Zero if the handler does not wish to reply with any data.
630 This parameter is optional and may be NULL.
631
632 @retval EFI_SUCCESS The message was successfully posted.
633 @retval EFI_INVALID_PARAMETER The CommBuffer was NULL.
634 @retval EFI_BAD_BUFFER_SIZE The buffer is too large for the MM implementation.
635 If this error is returned, the MessageLength field
636 in the CommBuffer header or the integer pointed by
637 CommSize, are updated to reflect the maximum payload
638 size the implementation can accommodate.
639 @retval EFI_ACCESS_DENIED The CommunicateBuffer parameter or CommSize parameter,
640 if not omitted, are in address range that cannot be
641 accessed by the MM environment.
642
643 **/
644 EFI_STATUS
645 EFIAPI
646 SmmCommunicationMmCommunicate2 (
647 IN CONST EFI_MM_COMMUNICATION2_PROTOCOL *This,
648 IN OUT VOID *CommBufferPhysical,
649 IN OUT VOID *CommBufferVirtual,
650 IN OUT UINTN *CommSize OPTIONAL
651 )
652 {
653 return SmmCommunicationCommunicate (&mSmmCommunication,
654 CommBufferPhysical,
655 CommSize);
656 }
657
658 /**
659 Event notification that is fired when GUIDed Event Group is signaled.
660
661 @param Event The Event that is being processed, not used.
662 @param Context Event Context, not used.
663
664 **/
665 VOID
666 EFIAPI
667 SmmIplGuidedEventNotify (
668 IN EFI_EVENT Event,
669 IN VOID *Context
670 )
671 {
672 UINTN Size;
673
674 //
675 // Use Guid to initialize EFI_SMM_COMMUNICATE_HEADER structure
676 //
677 CopyGuid (&mCommunicateHeader.HeaderGuid, (EFI_GUID *)Context);
678 mCommunicateHeader.MessageLength = 1;
679 mCommunicateHeader.Data[0] = 0;
680
681 //
682 // Generate the Software SMI and return the result
683 //
684 Size = sizeof (mCommunicateHeader);
685 SmmCommunicationCommunicate (&mSmmCommunication, &mCommunicateHeader, &Size);
686 }
687
688 /**
689 Event notification that is fired when EndOfDxe Event Group is signaled.
690
691 @param Event The Event that is being processed, not used.
692 @param Context Event Context, not used.
693
694 **/
695 VOID
696 EFIAPI
697 SmmIplEndOfDxeEventNotify (
698 IN EFI_EVENT Event,
699 IN VOID *Context
700 )
701 {
702 mEndOfDxe = TRUE;
703 }
704
705 /**
706 Event notification that is fired when DxeDispatch Event Group is signaled.
707
708 @param Event The Event that is being processed, not used.
709 @param Context Event Context, not used.
710
711 **/
712 VOID
713 EFIAPI
714 SmmIplDxeDispatchEventNotify (
715 IN EFI_EVENT Event,
716 IN VOID *Context
717 )
718 {
719 UINTN Size;
720 EFI_STATUS Status;
721
722 //
723 // Keep calling the SMM Core Dispatcher until there is no request to restart it.
724 //
725 while (TRUE) {
726 //
727 // Use Guid to initialize EFI_SMM_COMMUNICATE_HEADER structure
728 // Clear the buffer passed into the Software SMI. This buffer will return
729 // the status of the SMM Core Dispatcher.
730 //
731 CopyGuid (&mCommunicateHeader.HeaderGuid, (EFI_GUID *)Context);
732 mCommunicateHeader.MessageLength = 1;
733 mCommunicateHeader.Data[0] = 0;
734
735 //
736 // Generate the Software SMI and return the result
737 //
738 Size = sizeof (mCommunicateHeader);
739 SmmCommunicationCommunicate (&mSmmCommunication, &mCommunicateHeader, &Size);
740
741 //
742 // Return if there is no request to restart the SMM Core Dispatcher
743 //
744 if (mCommunicateHeader.Data[0] != COMM_BUFFER_SMM_DISPATCH_RESTART) {
745 return;
746 }
747
748 //
749 // Close all SMRAM ranges to protect SMRAM
750 // NOTE: SMRR is enabled by CPU SMM driver by calling SmmCpuFeaturesInitializeProcessor() from SmmCpuFeaturesLib
751 // so no need to reset the SMRAM to UC in MTRR.
752 //
753 Status = mSmmAccess->Close (mSmmAccess);
754 ASSERT_EFI_ERROR (Status);
755
756 //
757 // Print debug message that the SMRAM window is now closed.
758 //
759 DEBUG ((DEBUG_INFO, "SMM IPL closed SMRAM window\n"));
760 }
761 }
762
763 /**
764 Event notification that is fired every time a gEfiSmmConfigurationProtocol installs.
765
766 @param Event The Event that is being processed, not used.
767 @param Context Event Context, not used.
768
769 **/
770 VOID
771 EFIAPI
772 SmmIplSmmConfigurationEventNotify (
773 IN EFI_EVENT Event,
774 IN VOID *Context
775 )
776 {
777 EFI_STATUS Status;
778 EFI_SMM_CONFIGURATION_PROTOCOL *SmmConfiguration;
779
780 //
781 // Make sure this notification is for this handler
782 //
783 Status = gBS->LocateProtocol (Context, NULL, (VOID **)&SmmConfiguration);
784 if (EFI_ERROR (Status)) {
785 return;
786 }
787
788 //
789 // Register the SMM Entry Point provided by the SMM Core with the SMM Configuration protocol
790 //
791 Status = SmmConfiguration->RegisterSmmEntry (SmmConfiguration, gSmmCorePrivate->SmmEntryPoint);
792 ASSERT_EFI_ERROR (Status);
793
794 //
795 // Set flag to indicate that the SMM Entry Point has been registered which
796 // means that SMIs are now fully operational.
797 //
798 gSmmCorePrivate->SmmEntryPointRegistered = TRUE;
799
800 //
801 // Print debug message showing SMM Core entry point address.
802 //
803 DEBUG ((DEBUG_INFO, "SMM IPL registered SMM Entry Point address %p\n", (VOID *)(UINTN)gSmmCorePrivate->SmmEntryPoint));
804 }
805
806 /**
807 Event notification that is fired every time a DxeSmmReadyToLock protocol is added
808 or if gEfiEventReadyToBootGuid is signaled.
809
810 @param Event The Event that is being processed, not used.
811 @param Context Event Context, not used.
812
813 **/
814 VOID
815 EFIAPI
816 SmmIplReadyToLockEventNotify (
817 IN EFI_EVENT Event,
818 IN VOID *Context
819 )
820 {
821 EFI_STATUS Status;
822 VOID *Interface;
823 UINTN Index;
824
825 //
826 // See if we are already locked
827 //
828 if (mSmmLocked) {
829 return;
830 }
831
832 //
833 // Make sure this notification is for this handler
834 //
835 if (CompareGuid ((EFI_GUID *)Context, &gEfiDxeSmmReadyToLockProtocolGuid)) {
836 Status = gBS->LocateProtocol (&gEfiDxeSmmReadyToLockProtocolGuid, NULL, &Interface);
837 if (EFI_ERROR (Status)) {
838 return;
839 }
840 } else {
841 //
842 // If SMM is not locked yet and we got here from gEfiEventReadyToBootGuid being
843 // signaled, then gEfiDxeSmmReadyToLockProtocolGuid was not installed as expected.
844 // Print a warning on debug builds.
845 //
846 DEBUG ((DEBUG_WARN, "SMM IPL! DXE SMM Ready To Lock Protocol not installed before Ready To Boot signal\n"));
847 }
848
849 if (!mEndOfDxe) {
850 DEBUG ((DEBUG_ERROR, "EndOfDxe Event must be signaled before DxeSmmReadyToLock Protocol installation!\n"));
851 REPORT_STATUS_CODE (
852 EFI_ERROR_CODE | EFI_ERROR_UNRECOVERED,
853 (EFI_SOFTWARE_SMM_DRIVER | EFI_SW_EC_ILLEGAL_SOFTWARE_STATE)
854 );
855 ASSERT (FALSE);
856 }
857
858 //
859 // Lock the SMRAM (Note: Locking SMRAM may not be supported on all platforms)
860 //
861 mSmmAccess->Lock (mSmmAccess);
862
863 //
864 // Close protocol and event notification events that do not apply after the
865 // DXE SMM Ready To Lock Protocol has been installed or the Ready To Boot
866 // event has been signalled.
867 //
868 for (Index = 0; mSmmIplEvents[Index].NotifyFunction != NULL; Index++) {
869 if (mSmmIplEvents[Index].CloseOnLock) {
870 gBS->CloseEvent (mSmmIplEvents[Index].Event);
871 }
872 }
873
874 //
875 // Inform SMM Core that the DxeSmmReadyToLock protocol was installed
876 //
877 SmmIplGuidedEventNotify (Event, (VOID *)&gEfiDxeSmmReadyToLockProtocolGuid);
878
879 //
880 // Print debug message that the SMRAM window is now locked.
881 //
882 DEBUG ((DEBUG_INFO, "SMM IPL locked SMRAM window\n"));
883
884 //
885 // Set flag so this operation will not be performed again
886 //
887 mSmmLocked = TRUE;
888 }
889
890 /**
891 Notification function of EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE.
892
893 This is a notification function registered on EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE event.
894 It convers pointer to new virtual address.
895
896 @param Event Event whose notification function is being invoked.
897 @param Context Pointer to the notification function's context.
898
899 **/
900 VOID
901 EFIAPI
902 SmmIplSetVirtualAddressNotify (
903 IN EFI_EVENT Event,
904 IN VOID *Context
905 )
906 {
907 EfiConvertPointer (0x0, (VOID **)&mSmmControl2);
908 }
909
910 /**
911 Get the fixed loading address from image header assigned by build tool. This function only be called
912 when Loading module at Fixed address feature enabled.
913
914 @param ImageContext Pointer to the image context structure that describes the PE/COFF
915 image that needs to be examined by this function.
916 @retval EFI_SUCCESS An fixed loading address is assigned to this image by build tools .
917 @retval EFI_NOT_FOUND The image has no assigned fixed loading address.
918 **/
919 EFI_STATUS
920 GetPeCoffImageFixLoadingAssignedAddress(
921 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
922 )
923 {
924 UINTN SectionHeaderOffset;
925 EFI_STATUS Status;
926 EFI_IMAGE_SECTION_HEADER SectionHeader;
927 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
928 EFI_PHYSICAL_ADDRESS FixLoadingAddress;
929 UINT16 Index;
930 UINTN Size;
931 UINT16 NumberOfSections;
932 EFI_PHYSICAL_ADDRESS SmramBase;
933 UINT64 SmmCodeSize;
934 UINT64 ValueInSectionHeader;
935 //
936 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
937 //
938 SmmCodeSize = EFI_PAGES_TO_SIZE (PcdGet32(PcdLoadFixAddressSmmCodePageNumber));
939
940 FixLoadingAddress = 0;
941 Status = EFI_NOT_FOUND;
942 SmramBase = mLMFAConfigurationTable->SmramBase;
943 //
944 // Get PeHeader pointer
945 //
946 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset);
947 SectionHeaderOffset = ImageContext->PeCoffHeaderOffset +
948 sizeof (UINT32) +
949 sizeof (EFI_IMAGE_FILE_HEADER) +
950 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader;
951 NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections;
952
953 //
954 // Get base address from the first section header that doesn't point to code section.
955 //
956 for (Index = 0; Index < NumberOfSections; Index++) {
957 //
958 // Read section header from file
959 //
960 Size = sizeof (EFI_IMAGE_SECTION_HEADER);
961 Status = ImageContext->ImageRead (
962 ImageContext->Handle,
963 SectionHeaderOffset,
964 &Size,
965 &SectionHeader
966 );
967 if (EFI_ERROR (Status)) {
968 return Status;
969 }
970
971 Status = EFI_NOT_FOUND;
972
973 if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) {
974 //
975 // Build tool saves the offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields in the
976 // first section header that doesn't point to code section in image header. And there is an assumption that when the
977 // feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations & PointerToLineNumbers
978 // fields should NOT be Zero, or else, these 2 fields should be set to Zero
979 //
980 ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations);
981 if (ValueInSectionHeader != 0) {
982 //
983 // Found first section header that doesn't point to code section in which build tool saves the
984 // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields
985 //
986 FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(SmramBase + (INT64)ValueInSectionHeader);
987
988 if (SmramBase + SmmCodeSize > FixLoadingAddress && SmramBase <= FixLoadingAddress) {
989 //
990 // The assigned address is valid. Return the specified loading address
991 //
992 ImageContext->ImageAddress = FixLoadingAddress;
993 Status = EFI_SUCCESS;
994 }
995 }
996 break;
997 }
998 SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);
999 }
1000 DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r \n", FixLoadingAddress, Status));
1001 return Status;
1002 }
1003 /**
1004 Load the SMM Core image into SMRAM and executes the SMM Core from SMRAM.
1005
1006 @param[in, out] SmramRange Descriptor for the range of SMRAM to reload the
1007 currently executing image, the rang of SMRAM to
1008 hold SMM Core will be excluded.
1009 @param[in, out] SmramRangeSmmCore Descriptor for the range of SMRAM to hold SMM Core.
1010
1011 @param[in] Context Context to pass into SMM Core
1012
1013 @return EFI_STATUS
1014
1015 **/
1016 EFI_STATUS
1017 ExecuteSmmCoreFromSmram (
1018 IN OUT EFI_SMRAM_DESCRIPTOR *SmramRange,
1019 IN OUT EFI_SMRAM_DESCRIPTOR *SmramRangeSmmCore,
1020 IN VOID *Context
1021 )
1022 {
1023 EFI_STATUS Status;
1024 VOID *SourceBuffer;
1025 UINTN SourceSize;
1026 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
1027 UINTN PageCount;
1028 EFI_IMAGE_ENTRY_POINT EntryPoint;
1029
1030 //
1031 // Search all Firmware Volumes for a PE/COFF image in a file of type SMM_CORE
1032 //
1033 Status = GetSectionFromAnyFvByFileType (
1034 EFI_FV_FILETYPE_SMM_CORE,
1035 0,
1036 EFI_SECTION_PE32,
1037 0,
1038 &SourceBuffer,
1039 &SourceSize
1040 );
1041 if (EFI_ERROR (Status)) {
1042 return Status;
1043 }
1044
1045 //
1046 // Initialize ImageContext
1047 //
1048 ImageContext.Handle = SourceBuffer;
1049 ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory;
1050
1051 //
1052 // Get information about the image being loaded
1053 //
1054 Status = PeCoffLoaderGetImageInfo (&ImageContext);
1055 if (EFI_ERROR (Status)) {
1056 return Status;
1057 }
1058 //
1059 // if Loading module at Fixed Address feature is enabled, the SMM core driver will be loaded to
1060 // the address assigned by build tool.
1061 //
1062 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {
1063 //
1064 // Get the fixed loading address assigned by Build tool
1065 //
1066 Status = GetPeCoffImageFixLoadingAssignedAddress (&ImageContext);
1067 if (!EFI_ERROR (Status)) {
1068 //
1069 // Since the memory range to load SMM CORE will be cut out in SMM core, so no need to allocate and free this range
1070 //
1071 PageCount = 0;
1072 //
1073 // Reserved Smram Region for SmmCore is not used, and remove it from SmramRangeCount.
1074 //
1075 gSmmCorePrivate->SmramRangeCount --;
1076 } else {
1077 DEBUG ((EFI_D_INFO, "LOADING MODULE FIXED ERROR: Loading module at fixed address at address failed\n"));
1078 //
1079 // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR
1080 // specified by SmramRange
1081 //
1082 PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment);
1083
1084 ASSERT ((SmramRange->PhysicalSize & EFI_PAGE_MASK) == 0);
1085 ASSERT (SmramRange->PhysicalSize > EFI_PAGES_TO_SIZE (PageCount));
1086
1087 SmramRange->PhysicalSize -= EFI_PAGES_TO_SIZE (PageCount);
1088 SmramRangeSmmCore->CpuStart = SmramRange->CpuStart + SmramRange->PhysicalSize;
1089 SmramRangeSmmCore->PhysicalStart = SmramRange->PhysicalStart + SmramRange->PhysicalSize;
1090 SmramRangeSmmCore->RegionState = SmramRange->RegionState | EFI_ALLOCATED;
1091 SmramRangeSmmCore->PhysicalSize = EFI_PAGES_TO_SIZE (PageCount);
1092
1093 //
1094 // Align buffer on section boundary
1095 //
1096 ImageContext.ImageAddress = SmramRangeSmmCore->CpuStart;
1097 }
1098 } else {
1099 //
1100 // Allocate memory for the image being loaded from the EFI_SRAM_DESCRIPTOR
1101 // specified by SmramRange
1102 //
1103 PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment);
1104
1105 ASSERT ((SmramRange->PhysicalSize & EFI_PAGE_MASK) == 0);
1106 ASSERT (SmramRange->PhysicalSize > EFI_PAGES_TO_SIZE (PageCount));
1107
1108 SmramRange->PhysicalSize -= EFI_PAGES_TO_SIZE (PageCount);
1109 SmramRangeSmmCore->CpuStart = SmramRange->CpuStart + SmramRange->PhysicalSize;
1110 SmramRangeSmmCore->PhysicalStart = SmramRange->PhysicalStart + SmramRange->PhysicalSize;
1111 SmramRangeSmmCore->RegionState = SmramRange->RegionState | EFI_ALLOCATED;
1112 SmramRangeSmmCore->PhysicalSize = EFI_PAGES_TO_SIZE (PageCount);
1113
1114 //
1115 // Align buffer on section boundary
1116 //
1117 ImageContext.ImageAddress = SmramRangeSmmCore->CpuStart;
1118 }
1119
1120 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
1121 ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)ImageContext.SectionAlignment - 1);
1122
1123 //
1124 // Print debug message showing SMM Core load address.
1125 //
1126 DEBUG ((DEBUG_INFO, "SMM IPL loading SMM Core at SMRAM address %p\n", (VOID *)(UINTN)ImageContext.ImageAddress));
1127
1128 //
1129 // Load the image to our new buffer
1130 //
1131 Status = PeCoffLoaderLoadImage (&ImageContext);
1132 if (!EFI_ERROR (Status)) {
1133 //
1134 // Relocate the image in our new buffer
1135 //
1136 Status = PeCoffLoaderRelocateImage (&ImageContext);
1137 if (!EFI_ERROR (Status)) {
1138 //
1139 // Flush the instruction cache so the image data are written before we execute it
1140 //
1141 InvalidateInstructionCacheRange ((VOID *)(UINTN)ImageContext.ImageAddress, (UINTN)ImageContext.ImageSize);
1142
1143 //
1144 // Print debug message showing SMM Core entry point address.
1145 //
1146 DEBUG ((DEBUG_INFO, "SMM IPL calling SMM Core at SMRAM address %p\n", (VOID *)(UINTN)ImageContext.EntryPoint));
1147
1148 gSmmCorePrivate->PiSmmCoreImageBase = ImageContext.ImageAddress;
1149 gSmmCorePrivate->PiSmmCoreImageSize = ImageContext.ImageSize;
1150 DEBUG ((DEBUG_INFO, "PiSmmCoreImageBase - 0x%016lx\n", gSmmCorePrivate->PiSmmCoreImageBase));
1151 DEBUG ((DEBUG_INFO, "PiSmmCoreImageSize - 0x%016lx\n", gSmmCorePrivate->PiSmmCoreImageSize));
1152
1153 gSmmCorePrivate->PiSmmCoreEntryPoint = ImageContext.EntryPoint;
1154
1155 //
1156 // Execute image
1157 //
1158 EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)ImageContext.EntryPoint;
1159 Status = EntryPoint ((EFI_HANDLE)Context, gST);
1160 }
1161 }
1162
1163 //
1164 // Always free memory allocated by GetFileBufferByFilePath ()
1165 //
1166 FreePool (SourceBuffer);
1167
1168 return Status;
1169 }
1170
1171 /**
1172 SMM split SMRAM entry.
1173
1174 @param[in, out] RangeToCompare Pointer to EFI_SMRAM_DESCRIPTOR to compare.
1175 @param[in, out] ReservedRangeToCompare Pointer to EFI_SMM_RESERVED_SMRAM_REGION to compare.
1176 @param[out] Ranges Output pointer to hold split EFI_SMRAM_DESCRIPTOR entry.
1177 @param[in, out] RangeCount Pointer to range count.
1178 @param[out] ReservedRanges Output pointer to hold split EFI_SMM_RESERVED_SMRAM_REGION entry.
1179 @param[in, out] ReservedRangeCount Pointer to reserved range count.
1180 @param[out] FinalRanges Output pointer to hold split final EFI_SMRAM_DESCRIPTOR entry
1181 that no need to be split anymore.
1182 @param[in, out] FinalRangeCount Pointer to final range count.
1183
1184 **/
1185 VOID
1186 SmmSplitSmramEntry (
1187 IN OUT EFI_SMRAM_DESCRIPTOR *RangeToCompare,
1188 IN OUT EFI_SMM_RESERVED_SMRAM_REGION *ReservedRangeToCompare,
1189 OUT EFI_SMRAM_DESCRIPTOR *Ranges,
1190 IN OUT UINTN *RangeCount,
1191 OUT EFI_SMM_RESERVED_SMRAM_REGION *ReservedRanges,
1192 IN OUT UINTN *ReservedRangeCount,
1193 OUT EFI_SMRAM_DESCRIPTOR *FinalRanges,
1194 IN OUT UINTN *FinalRangeCount
1195 )
1196 {
1197 UINT64 RangeToCompareEnd;
1198 UINT64 ReservedRangeToCompareEnd;
1199
1200 RangeToCompareEnd = RangeToCompare->CpuStart + RangeToCompare->PhysicalSize;
1201 ReservedRangeToCompareEnd = ReservedRangeToCompare->SmramReservedStart + ReservedRangeToCompare->SmramReservedSize;
1202
1203 if ((RangeToCompare->CpuStart >= ReservedRangeToCompare->SmramReservedStart) &&
1204 (RangeToCompare->CpuStart < ReservedRangeToCompareEnd)) {
1205 if (RangeToCompareEnd < ReservedRangeToCompareEnd) {
1206 //
1207 // RangeToCompare ReservedRangeToCompare
1208 // ---- ---- --------------------------------------
1209 // | | | | -> 1. ReservedRangeToCompare
1210 // ---- | | |--| --------------------------------------
1211 // | | | | | |
1212 // | | | | | | -> 2. FinalRanges[*FinalRangeCount] and increment *FinalRangeCount
1213 // | | | | | | RangeToCompare->PhysicalSize = 0
1214 // ---- | | |--| --------------------------------------
1215 // | | | | -> 3. ReservedRanges[*ReservedRangeCount] and increment *ReservedRangeCount
1216 // ---- ---- --------------------------------------
1217 //
1218
1219 //
1220 // 1. Update ReservedRangeToCompare.
1221 //
1222 ReservedRangeToCompare->SmramReservedSize = RangeToCompare->CpuStart - ReservedRangeToCompare->SmramReservedStart;
1223 //
1224 // 2. Update FinalRanges[FinalRangeCount] and increment *FinalRangeCount.
1225 // Zero RangeToCompare->PhysicalSize.
1226 //
1227 FinalRanges[*FinalRangeCount].CpuStart = RangeToCompare->CpuStart;
1228 FinalRanges[*FinalRangeCount].PhysicalStart = RangeToCompare->PhysicalStart;
1229 FinalRanges[*FinalRangeCount].RegionState = RangeToCompare->RegionState | EFI_ALLOCATED;
1230 FinalRanges[*FinalRangeCount].PhysicalSize = RangeToCompare->PhysicalSize;
1231 *FinalRangeCount += 1;
1232 RangeToCompare->PhysicalSize = 0;
1233 //
1234 // 3. Update ReservedRanges[*ReservedRangeCount] and increment *ReservedRangeCount.
1235 //
1236 ReservedRanges[*ReservedRangeCount].SmramReservedStart = FinalRanges[*FinalRangeCount - 1].CpuStart + FinalRanges[*FinalRangeCount - 1].PhysicalSize;
1237 ReservedRanges[*ReservedRangeCount].SmramReservedSize = ReservedRangeToCompareEnd - RangeToCompareEnd;
1238 *ReservedRangeCount += 1;
1239 } else {
1240 //
1241 // RangeToCompare ReservedRangeToCompare
1242 // ---- ---- --------------------------------------
1243 // | | | | -> 1. ReservedRangeToCompare
1244 // ---- | | |--| --------------------------------------
1245 // | | | | | |
1246 // | | | | | | -> 2. FinalRanges[*FinalRangeCount] and increment *FinalRangeCount
1247 // | | | | | |
1248 // | | ---- |--| --------------------------------------
1249 // | | | | -> 3. RangeToCompare
1250 // ---- ---- --------------------------------------
1251 //
1252
1253 //
1254 // 1. Update ReservedRangeToCompare.
1255 //
1256 ReservedRangeToCompare->SmramReservedSize = RangeToCompare->CpuStart - ReservedRangeToCompare->SmramReservedStart;
1257 //
1258 // 2. Update FinalRanges[FinalRangeCount] and increment *FinalRangeCount.
1259 //
1260 FinalRanges[*FinalRangeCount].CpuStart = RangeToCompare->CpuStart;
1261 FinalRanges[*FinalRangeCount].PhysicalStart = RangeToCompare->PhysicalStart;
1262 FinalRanges[*FinalRangeCount].RegionState = RangeToCompare->RegionState | EFI_ALLOCATED;
1263 FinalRanges[*FinalRangeCount].PhysicalSize = ReservedRangeToCompareEnd - RangeToCompare->CpuStart;
1264 *FinalRangeCount += 1;
1265 //
1266 // 3. Update RangeToCompare.
1267 //
1268 RangeToCompare->CpuStart += FinalRanges[*FinalRangeCount - 1].PhysicalSize;
1269 RangeToCompare->PhysicalStart += FinalRanges[*FinalRangeCount - 1].PhysicalSize;
1270 RangeToCompare->PhysicalSize -= FinalRanges[*FinalRangeCount - 1].PhysicalSize;
1271 }
1272 } else if ((ReservedRangeToCompare->SmramReservedStart >= RangeToCompare->CpuStart) &&
1273 (ReservedRangeToCompare->SmramReservedStart < RangeToCompareEnd)) {
1274 if (ReservedRangeToCompareEnd < RangeToCompareEnd) {
1275 //
1276 // RangeToCompare ReservedRangeToCompare
1277 // ---- ---- --------------------------------------
1278 // | | | | -> 1. RangeToCompare
1279 // | | ---- |--| --------------------------------------
1280 // | | | | | |
1281 // | | | | | | -> 2. FinalRanges[*FinalRangeCount] and increment *FinalRangeCount
1282 // | | | | | | ReservedRangeToCompare->SmramReservedSize = 0
1283 // | | ---- |--| --------------------------------------
1284 // | | | | -> 3. Ranges[*RangeCount] and increment *RangeCount
1285 // ---- ---- --------------------------------------
1286 //
1287
1288 //
1289 // 1. Update RangeToCompare.
1290 //
1291 RangeToCompare->PhysicalSize = ReservedRangeToCompare->SmramReservedStart - RangeToCompare->CpuStart;
1292 //
1293 // 2. Update FinalRanges[FinalRangeCount] and increment *FinalRangeCount.
1294 // ReservedRangeToCompare->SmramReservedSize = 0
1295 //
1296 FinalRanges[*FinalRangeCount].CpuStart = ReservedRangeToCompare->SmramReservedStart;
1297 FinalRanges[*FinalRangeCount].PhysicalStart = RangeToCompare->PhysicalStart + RangeToCompare->PhysicalSize;
1298 FinalRanges[*FinalRangeCount].RegionState = RangeToCompare->RegionState | EFI_ALLOCATED;
1299 FinalRanges[*FinalRangeCount].PhysicalSize = ReservedRangeToCompare->SmramReservedSize;
1300 *FinalRangeCount += 1;
1301 ReservedRangeToCompare->SmramReservedSize = 0;
1302 //
1303 // 3. Update Ranges[*RangeCount] and increment *RangeCount.
1304 //
1305 Ranges[*RangeCount].CpuStart = FinalRanges[*FinalRangeCount - 1].CpuStart + FinalRanges[*FinalRangeCount - 1].PhysicalSize;
1306 Ranges[*RangeCount].PhysicalStart = FinalRanges[*FinalRangeCount - 1].PhysicalStart + FinalRanges[*FinalRangeCount - 1].PhysicalSize;
1307 Ranges[*RangeCount].RegionState = RangeToCompare->RegionState;
1308 Ranges[*RangeCount].PhysicalSize = RangeToCompareEnd - ReservedRangeToCompareEnd;
1309 *RangeCount += 1;
1310 } else {
1311 //
1312 // RangeToCompare ReservedRangeToCompare
1313 // ---- ---- --------------------------------------
1314 // | | | | -> 1. RangeToCompare
1315 // | | ---- |--| --------------------------------------
1316 // | | | | | |
1317 // | | | | | | -> 2. FinalRanges[*FinalRangeCount] and increment *FinalRangeCount
1318 // | | | | | |
1319 // ---- | | |--| --------------------------------------
1320 // | | | | -> 3. ReservedRangeToCompare
1321 // ---- ---- --------------------------------------
1322 //
1323
1324 //
1325 // 1. Update RangeToCompare.
1326 //
1327 RangeToCompare->PhysicalSize = ReservedRangeToCompare->SmramReservedStart - RangeToCompare->CpuStart;
1328 //
1329 // 2. Update FinalRanges[FinalRangeCount] and increment *FinalRangeCount.
1330 // ReservedRangeToCompare->SmramReservedSize = 0
1331 //
1332 FinalRanges[*FinalRangeCount].CpuStart = ReservedRangeToCompare->SmramReservedStart;
1333 FinalRanges[*FinalRangeCount].PhysicalStart = RangeToCompare->PhysicalStart + RangeToCompare->PhysicalSize;
1334 FinalRanges[*FinalRangeCount].RegionState = RangeToCompare->RegionState | EFI_ALLOCATED;
1335 FinalRanges[*FinalRangeCount].PhysicalSize = RangeToCompareEnd - ReservedRangeToCompare->SmramReservedStart;
1336 *FinalRangeCount += 1;
1337 //
1338 // 3. Update ReservedRangeToCompare.
1339 //
1340 ReservedRangeToCompare->SmramReservedStart += FinalRanges[*FinalRangeCount - 1].PhysicalSize;
1341 ReservedRangeToCompare->SmramReservedSize -= FinalRanges[*FinalRangeCount - 1].PhysicalSize;
1342 }
1343 }
1344 }
1345
1346 /**
1347 Returns if SMRAM range and SMRAM reserved range are overlapped.
1348
1349 @param[in] RangeToCompare Pointer to EFI_SMRAM_DESCRIPTOR to compare.
1350 @param[in] ReservedRangeToCompare Pointer to EFI_SMM_RESERVED_SMRAM_REGION to compare.
1351
1352 @retval TRUE There is overlap.
1353 @retval FALSE There is no overlap.
1354
1355 **/
1356 BOOLEAN
1357 SmmIsSmramOverlap (
1358 IN EFI_SMRAM_DESCRIPTOR *RangeToCompare,
1359 IN EFI_SMM_RESERVED_SMRAM_REGION *ReservedRangeToCompare
1360 )
1361 {
1362 UINT64 RangeToCompareEnd;
1363 UINT64 ReservedRangeToCompareEnd;
1364
1365 RangeToCompareEnd = RangeToCompare->CpuStart + RangeToCompare->PhysicalSize;
1366 ReservedRangeToCompareEnd = ReservedRangeToCompare->SmramReservedStart + ReservedRangeToCompare->SmramReservedSize;
1367
1368 if ((RangeToCompare->CpuStart >= ReservedRangeToCompare->SmramReservedStart) &&
1369 (RangeToCompare->CpuStart < ReservedRangeToCompareEnd)) {
1370 return TRUE;
1371 } else if ((ReservedRangeToCompare->SmramReservedStart >= RangeToCompare->CpuStart) &&
1372 (ReservedRangeToCompare->SmramReservedStart < RangeToCompareEnd)) {
1373 return TRUE;
1374 }
1375 return FALSE;
1376 }
1377
1378 /**
1379 Get full SMRAM ranges.
1380
1381 It will get SMRAM ranges from SmmAccess protocol and SMRAM reserved ranges from
1382 SmmConfiguration protocol, split the entries if there is overlap between them.
1383 It will also reserve one entry for SMM core.
1384
1385 @param[out] FullSmramRangeCount Output pointer to full SMRAM range count.
1386
1387 @return Pointer to full SMRAM ranges.
1388
1389 **/
1390 EFI_SMRAM_DESCRIPTOR *
1391 GetFullSmramRanges (
1392 OUT UINTN *FullSmramRangeCount
1393 )
1394 {
1395 EFI_STATUS Status;
1396 EFI_SMM_CONFIGURATION_PROTOCOL *SmmConfiguration;
1397 UINTN Size;
1398 UINTN Index;
1399 UINTN Index2;
1400 EFI_SMRAM_DESCRIPTOR *FullSmramRanges;
1401 UINTN TempSmramRangeCount;
1402 UINTN AdditionSmramRangeCount;
1403 EFI_SMRAM_DESCRIPTOR *TempSmramRanges;
1404 UINTN SmramRangeCount;
1405 EFI_SMRAM_DESCRIPTOR *SmramRanges;
1406 UINTN SmramReservedCount;
1407 EFI_SMM_RESERVED_SMRAM_REGION *SmramReservedRanges;
1408 UINTN MaxCount;
1409 BOOLEAN Rescan;
1410
1411 //
1412 // Get SMM Configuration Protocol if it is present.
1413 //
1414 SmmConfiguration = NULL;
1415 Status = gBS->LocateProtocol (&gEfiSmmConfigurationProtocolGuid, NULL, (VOID **) &SmmConfiguration);
1416
1417 //
1418 // Get SMRAM information.
1419 //
1420 Size = 0;
1421 Status = mSmmAccess->GetCapabilities (mSmmAccess, &Size, NULL);
1422 ASSERT (Status == EFI_BUFFER_TOO_SMALL);
1423
1424 SmramRangeCount = Size / sizeof (EFI_SMRAM_DESCRIPTOR);
1425
1426 //
1427 // Get SMRAM reserved region count.
1428 //
1429 SmramReservedCount = 0;
1430 if (SmmConfiguration != NULL) {
1431 while (SmmConfiguration->SmramReservedRegions[SmramReservedCount].SmramReservedSize != 0) {
1432 SmramReservedCount++;
1433 }
1434 }
1435
1436 //
1437 // Reserve one entry for SMM Core in the full SMRAM ranges.
1438 //
1439 AdditionSmramRangeCount = 1;
1440 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {
1441 //
1442 // Reserve two entries for all SMM drivers and SMM Core in the full SMRAM ranges.
1443 //
1444 AdditionSmramRangeCount = 2;
1445 }
1446
1447 if (SmramReservedCount == 0) {
1448 //
1449 // No reserved SMRAM entry from SMM Configuration Protocol.
1450 //
1451 *FullSmramRangeCount = SmramRangeCount + AdditionSmramRangeCount;
1452 Size = (*FullSmramRangeCount) * sizeof (EFI_SMRAM_DESCRIPTOR);
1453 FullSmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocateZeroPool (Size);
1454 ASSERT (FullSmramRanges != NULL);
1455
1456 Status = mSmmAccess->GetCapabilities (mSmmAccess, &Size, FullSmramRanges);
1457 ASSERT_EFI_ERROR (Status);
1458
1459 return FullSmramRanges;
1460 }
1461
1462 //
1463 // Why MaxCount = X + 2 * Y?
1464 // Take Y = 1 as example below, Y > 1 case is just the iteration of Y = 1.
1465 //
1466 // X = 1 Y = 1 MaxCount = 3 = 1 + 2 * 1
1467 // ---- ----
1468 // | | ---- |--|
1469 // | | | | -> | |
1470 // | | ---- |--|
1471 // ---- ----
1472 //
1473 // X = 2 Y = 1 MaxCount = 4 = 2 + 2 * 1
1474 // ---- ----
1475 // | | | |
1476 // | | ---- |--|
1477 // | | | | | |
1478 // |--| | | -> |--|
1479 // | | | | | |
1480 // | | ---- |--|
1481 // | | | |
1482 // ---- ----
1483 //
1484 // X = 3 Y = 1 MaxCount = 5 = 3 + 2 * 1
1485 // ---- ----
1486 // | | | |
1487 // | | ---- |--|
1488 // |--| | | |--|
1489 // | | | | -> | |
1490 // |--| | | |--|
1491 // | | ---- |--|
1492 // | | | |
1493 // ---- ----
1494 //
1495 // ......
1496 //
1497 MaxCount = SmramRangeCount + 2 * SmramReservedCount;
1498
1499 Size = MaxCount * sizeof (EFI_SMM_RESERVED_SMRAM_REGION);
1500 SmramReservedRanges = (EFI_SMM_RESERVED_SMRAM_REGION *) AllocatePool (Size);
1501 ASSERT (SmramReservedRanges != NULL);
1502 for (Index = 0; Index < SmramReservedCount; Index++) {
1503 CopyMem (&SmramReservedRanges[Index], &SmmConfiguration->SmramReservedRegions[Index], sizeof (EFI_SMM_RESERVED_SMRAM_REGION));
1504 }
1505
1506 Size = MaxCount * sizeof (EFI_SMRAM_DESCRIPTOR);
1507 TempSmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocatePool (Size);
1508 ASSERT (TempSmramRanges != NULL);
1509 TempSmramRangeCount = 0;
1510
1511 SmramRanges = (EFI_SMRAM_DESCRIPTOR *) AllocatePool (Size);
1512 ASSERT (SmramRanges != NULL);
1513 Status = mSmmAccess->GetCapabilities (mSmmAccess, &Size, SmramRanges);
1514 ASSERT_EFI_ERROR (Status);
1515
1516 do {
1517 Rescan = FALSE;
1518 for (Index = 0; (Index < SmramRangeCount) && !Rescan; Index++) {
1519 //
1520 // Skip zero size entry.
1521 //
1522 if (SmramRanges[Index].PhysicalSize != 0) {
1523 for (Index2 = 0; (Index2 < SmramReservedCount) && !Rescan; Index2++) {
1524 //
1525 // Skip zero size entry.
1526 //
1527 if (SmramReservedRanges[Index2].SmramReservedSize != 0) {
1528 if (SmmIsSmramOverlap (
1529 &SmramRanges[Index],
1530 &SmramReservedRanges[Index2]
1531 )) {
1532 //
1533 // There is overlap, need to split entry and then rescan.
1534 //
1535 SmmSplitSmramEntry (
1536 &SmramRanges[Index],
1537 &SmramReservedRanges[Index2],
1538 SmramRanges,
1539 &SmramRangeCount,
1540 SmramReservedRanges,
1541 &SmramReservedCount,
1542 TempSmramRanges,
1543 &TempSmramRangeCount
1544 );
1545 Rescan = TRUE;
1546 }
1547 }
1548 }
1549 if (!Rescan) {
1550 //
1551 // No any overlap, copy the entry to the temp SMRAM ranges.
1552 // Zero SmramRanges[Index].PhysicalSize = 0;
1553 //
1554 CopyMem (&TempSmramRanges[TempSmramRangeCount++], &SmramRanges[Index], sizeof (EFI_SMRAM_DESCRIPTOR));
1555 SmramRanges[Index].PhysicalSize = 0;
1556 }
1557 }
1558 }
1559 } while (Rescan);
1560 ASSERT (TempSmramRangeCount <= MaxCount);
1561
1562 //
1563 // Sort the entries
1564 //
1565 FullSmramRanges = AllocateZeroPool ((TempSmramRangeCount + AdditionSmramRangeCount) * sizeof (EFI_SMRAM_DESCRIPTOR));
1566 ASSERT (FullSmramRanges != NULL);
1567 *FullSmramRangeCount = 0;
1568 do {
1569 for (Index = 0; Index < TempSmramRangeCount; Index++) {
1570 if (TempSmramRanges[Index].PhysicalSize != 0) {
1571 break;
1572 }
1573 }
1574 ASSERT (Index < TempSmramRangeCount);
1575 for (Index2 = 0; Index2 < TempSmramRangeCount; Index2++) {
1576 if ((Index2 != Index) && (TempSmramRanges[Index2].PhysicalSize != 0) && (TempSmramRanges[Index2].CpuStart < TempSmramRanges[Index].CpuStart)) {
1577 Index = Index2;
1578 }
1579 }
1580 CopyMem (&FullSmramRanges[*FullSmramRangeCount], &TempSmramRanges[Index], sizeof (EFI_SMRAM_DESCRIPTOR));
1581 *FullSmramRangeCount += 1;
1582 TempSmramRanges[Index].PhysicalSize = 0;
1583 } while (*FullSmramRangeCount < TempSmramRangeCount);
1584 ASSERT (*FullSmramRangeCount == TempSmramRangeCount);
1585 *FullSmramRangeCount += AdditionSmramRangeCount;
1586
1587 FreePool (SmramRanges);
1588 FreePool (SmramReservedRanges);
1589 FreePool (TempSmramRanges);
1590
1591 return FullSmramRanges;
1592 }
1593
1594 /**
1595 The Entry Point for SMM IPL
1596
1597 Load SMM Core into SMRAM, register SMM Core entry point for SMIs, install
1598 SMM Base 2 Protocol and SMM Communication Protocol, and register for the
1599 critical events required to coordinate between DXE and SMM environments.
1600
1601 @param ImageHandle The firmware allocated handle for the EFI image.
1602 @param SystemTable A pointer to the EFI System Table.
1603
1604 @retval EFI_SUCCESS The entry point is executed successfully.
1605 @retval Other Some error occurred when executing this entry point.
1606
1607 **/
1608 EFI_STATUS
1609 EFIAPI
1610 SmmIplEntry (
1611 IN EFI_HANDLE ImageHandle,
1612 IN EFI_SYSTEM_TABLE *SystemTable
1613 )
1614 {
1615 EFI_STATUS Status;
1616 UINTN Index;
1617 UINT64 MaxSize;
1618 VOID *Registration;
1619 UINT64 SmmCodeSize;
1620 EFI_CPU_ARCH_PROTOCOL *CpuArch;
1621 EFI_STATUS SetAttrStatus;
1622 EFI_SMRAM_DESCRIPTOR *SmramRangeSmmDriver;
1623 EFI_GCD_MEMORY_SPACE_DESCRIPTOR MemDesc;
1624
1625 //
1626 // Fill in the image handle of the SMM IPL so the SMM Core can use this as the
1627 // ParentImageHandle field of the Load Image Protocol for all SMM Drivers loaded
1628 // by the SMM Core
1629 //
1630 mSmmCorePrivateData.SmmIplImageHandle = ImageHandle;
1631
1632 //
1633 // Get SMM Access Protocol
1634 //
1635 Status = gBS->LocateProtocol (&gEfiSmmAccess2ProtocolGuid, NULL, (VOID **)&mSmmAccess);
1636 ASSERT_EFI_ERROR (Status);
1637
1638 //
1639 // Get SMM Control2 Protocol
1640 //
1641 Status = gBS->LocateProtocol (&gEfiSmmControl2ProtocolGuid, NULL, (VOID **)&mSmmControl2);
1642 ASSERT_EFI_ERROR (Status);
1643
1644 gSmmCorePrivate->SmramRanges = GetFullSmramRanges (&gSmmCorePrivate->SmramRangeCount);
1645
1646 //
1647 // Open all SMRAM ranges
1648 //
1649 Status = mSmmAccess->Open (mSmmAccess);
1650 ASSERT_EFI_ERROR (Status);
1651
1652 //
1653 // Print debug message that the SMRAM window is now open.
1654 //
1655 DEBUG ((DEBUG_INFO, "SMM IPL opened SMRAM window\n"));
1656
1657 //
1658 // Find the largest SMRAM range between 1MB and 4GB that is at least 256KB - 4K in size
1659 //
1660 mCurrentSmramRange = NULL;
1661 for (Index = 0, MaxSize = SIZE_256KB - EFI_PAGE_SIZE; Index < gSmmCorePrivate->SmramRangeCount; Index++) {
1662 //
1663 // Skip any SMRAM region that is already allocated, needs testing, or needs ECC initialization
1664 //
1665 if ((gSmmCorePrivate->SmramRanges[Index].RegionState & (EFI_ALLOCATED | EFI_NEEDS_TESTING | EFI_NEEDS_ECC_INITIALIZATION)) != 0) {
1666 continue;
1667 }
1668
1669 if (gSmmCorePrivate->SmramRanges[Index].CpuStart >= BASE_1MB) {
1670 if ((gSmmCorePrivate->SmramRanges[Index].CpuStart + gSmmCorePrivate->SmramRanges[Index].PhysicalSize - 1) <= MAX_ADDRESS) {
1671 if (gSmmCorePrivate->SmramRanges[Index].PhysicalSize >= MaxSize) {
1672 MaxSize = gSmmCorePrivate->SmramRanges[Index].PhysicalSize;
1673 mCurrentSmramRange = &gSmmCorePrivate->SmramRanges[Index];
1674 }
1675 }
1676 }
1677 }
1678
1679 if (mCurrentSmramRange != NULL) {
1680 //
1681 // Print debug message showing SMRAM window that will be used by SMM IPL and SMM Core
1682 //
1683 DEBUG ((DEBUG_INFO, "SMM IPL found SMRAM window %p - %p\n",
1684 (VOID *)(UINTN)mCurrentSmramRange->CpuStart,
1685 (VOID *)(UINTN)(mCurrentSmramRange->CpuStart + mCurrentSmramRange->PhysicalSize - 1)
1686 ));
1687
1688 GetSmramCacheRange (mCurrentSmramRange, &mSmramCacheBase, &mSmramCacheSize);
1689 //
1690 // Make sure we can change the desired memory attributes.
1691 //
1692 Status = gDS->GetMemorySpaceDescriptor (
1693 mSmramCacheBase,
1694 &MemDesc
1695 );
1696 ASSERT_EFI_ERROR (Status);
1697 if ((MemDesc.Capabilities & SMRAM_CAPABILITIES) != SMRAM_CAPABILITIES) {
1698 gDS->SetMemorySpaceCapabilities (
1699 mSmramCacheBase,
1700 mSmramCacheSize,
1701 MemDesc.Capabilities | SMRAM_CAPABILITIES
1702 );
1703 }
1704 //
1705 // If CPU AP is present, attempt to set SMRAM cacheability to WB and clear
1706 // all paging attributes.
1707 // Note that it is expected that cacheability of SMRAM has been set to WB if CPU AP
1708 // is not available here.
1709 //
1710 CpuArch = NULL;
1711 Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&CpuArch);
1712 if (!EFI_ERROR (Status)) {
1713 MemDesc.Attributes &= ~(MEMORY_CACHE_ATTRIBUTES | MEMORY_PAGE_ATTRIBUTES);
1714 MemDesc.Attributes |= EFI_MEMORY_WB;
1715 Status = gDS->SetMemorySpaceAttributes (
1716 mSmramCacheBase,
1717 mSmramCacheSize,
1718 MemDesc.Attributes
1719 );
1720 if (EFI_ERROR (Status)) {
1721 DEBUG ((DEBUG_WARN, "SMM IPL failed to set SMRAM window to EFI_MEMORY_WB\n"));
1722 }
1723
1724 DEBUG_CODE (
1725 gDS->GetMemorySpaceDescriptor (
1726 mSmramCacheBase,
1727 &MemDesc
1728 );
1729 DEBUG ((DEBUG_INFO, "SMRAM attributes: %016lx\n", MemDesc.Attributes));
1730 ASSERT ((MemDesc.Attributes & MEMORY_PAGE_ATTRIBUTES) == 0);
1731 );
1732 }
1733 //
1734 // if Loading module at Fixed Address feature is enabled, save the SMRAM base to Load
1735 // Modules At Fixed Address Configuration Table.
1736 //
1737 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {
1738 //
1739 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
1740 //
1741 SmmCodeSize = LShiftU64 (PcdGet32(PcdLoadFixAddressSmmCodePageNumber), EFI_PAGE_SHIFT);
1742 //
1743 // The SMRAM available memory is assumed to be larger than SmmCodeSize
1744 //
1745 ASSERT (mCurrentSmramRange->PhysicalSize > SmmCodeSize);
1746 //
1747 // Retrieve Load modules At fixed address configuration table and save the SMRAM base.
1748 //
1749 Status = EfiGetSystemConfigurationTable (
1750 &gLoadFixedAddressConfigurationTableGuid,
1751 (VOID **) &mLMFAConfigurationTable
1752 );
1753 if (!EFI_ERROR (Status) && mLMFAConfigurationTable != NULL) {
1754 mLMFAConfigurationTable->SmramBase = mCurrentSmramRange->CpuStart;
1755 //
1756 // Print the SMRAM base
1757 //
1758 DEBUG ((EFI_D_INFO, "LOADING MODULE FIXED INFO: TSEG BASE is %x. \n", mLMFAConfigurationTable->SmramBase));
1759 }
1760
1761 //
1762 // Fill the Smram range for all SMM code
1763 //
1764 SmramRangeSmmDriver = &gSmmCorePrivate->SmramRanges[gSmmCorePrivate->SmramRangeCount - 2];
1765 SmramRangeSmmDriver->CpuStart = mCurrentSmramRange->CpuStart;
1766 SmramRangeSmmDriver->PhysicalStart = mCurrentSmramRange->PhysicalStart;
1767 SmramRangeSmmDriver->RegionState = mCurrentSmramRange->RegionState | EFI_ALLOCATED;
1768 SmramRangeSmmDriver->PhysicalSize = SmmCodeSize;
1769
1770 mCurrentSmramRange->PhysicalSize -= SmmCodeSize;
1771 mCurrentSmramRange->CpuStart = mCurrentSmramRange->CpuStart + SmmCodeSize;
1772 mCurrentSmramRange->PhysicalStart = mCurrentSmramRange->PhysicalStart + SmmCodeSize;
1773 }
1774 //
1775 // Load SMM Core into SMRAM and execute it from SMRAM
1776 //
1777 Status = ExecuteSmmCoreFromSmram (
1778 mCurrentSmramRange,
1779 &gSmmCorePrivate->SmramRanges[gSmmCorePrivate->SmramRangeCount - 1],
1780 gSmmCorePrivate
1781 );
1782 if (EFI_ERROR (Status)) {
1783 //
1784 // Print error message that the SMM Core failed to be loaded and executed.
1785 //
1786 DEBUG ((DEBUG_ERROR, "SMM IPL could not load and execute SMM Core from SMRAM\n"));
1787
1788 //
1789 // Attempt to reset SMRAM cacheability to UC
1790 //
1791 if (CpuArch != NULL) {
1792 SetAttrStatus = gDS->SetMemorySpaceAttributes(
1793 mSmramCacheBase,
1794 mSmramCacheSize,
1795 EFI_MEMORY_UC
1796 );
1797 if (EFI_ERROR (SetAttrStatus)) {
1798 DEBUG ((DEBUG_WARN, "SMM IPL failed to reset SMRAM window to EFI_MEMORY_UC\n"));
1799 }
1800 }
1801 }
1802 } else {
1803 //
1804 // Print error message that there are not enough SMRAM resources to load the SMM Core.
1805 //
1806 DEBUG ((DEBUG_ERROR, "SMM IPL could not find a large enough SMRAM region to load SMM Core\n"));
1807 }
1808
1809 //
1810 // If the SMM Core could not be loaded then close SMRAM window, free allocated
1811 // resources, and return an error so SMM IPL will be unloaded.
1812 //
1813 if (mCurrentSmramRange == NULL || EFI_ERROR (Status)) {
1814 //
1815 // Close all SMRAM ranges
1816 //
1817 Status = mSmmAccess->Close (mSmmAccess);
1818 ASSERT_EFI_ERROR (Status);
1819
1820 //
1821 // Print debug message that the SMRAM window is now closed.
1822 //
1823 DEBUG ((DEBUG_INFO, "SMM IPL closed SMRAM window\n"));
1824
1825 //
1826 // Free all allocated resources
1827 //
1828 FreePool (gSmmCorePrivate->SmramRanges);
1829
1830 return EFI_UNSUPPORTED;
1831 }
1832
1833 //
1834 // Install SMM Base2 Protocol and SMM Communication Protocol
1835 //
1836 Status = gBS->InstallMultipleProtocolInterfaces (
1837 &mSmmIplHandle,
1838 &gEfiSmmBase2ProtocolGuid, &mSmmBase2,
1839 &gEfiSmmCommunicationProtocolGuid, &mSmmCommunication,
1840 &gEfiMmCommunication2ProtocolGuid, &mMmCommunication2,
1841 NULL
1842 );
1843 ASSERT_EFI_ERROR (Status);
1844
1845 //
1846 // Create the set of protocol and event notifications that the SMM IPL requires
1847 //
1848 for (Index = 0; mSmmIplEvents[Index].NotifyFunction != NULL; Index++) {
1849 if (mSmmIplEvents[Index].Protocol) {
1850 mSmmIplEvents[Index].Event = EfiCreateProtocolNotifyEvent (
1851 mSmmIplEvents[Index].Guid,
1852 mSmmIplEvents[Index].NotifyTpl,
1853 mSmmIplEvents[Index].NotifyFunction,
1854 mSmmIplEvents[Index].NotifyContext,
1855 &Registration
1856 );
1857 } else {
1858 Status = gBS->CreateEventEx (
1859 EVT_NOTIFY_SIGNAL,
1860 mSmmIplEvents[Index].NotifyTpl,
1861 mSmmIplEvents[Index].NotifyFunction,
1862 mSmmIplEvents[Index].NotifyContext,
1863 mSmmIplEvents[Index].Guid,
1864 &mSmmIplEvents[Index].Event
1865 );
1866 ASSERT_EFI_ERROR (Status);
1867 }
1868 }
1869
1870 return EFI_SUCCESS;
1871 }