]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Core/PiSmmCore/Dispatcher.c
MdeModulePkg: Refine casting expression result to bigger size
[mirror_edk2.git] / MdeModulePkg / Core / PiSmmCore / Dispatcher.c
1 /** @file
2 SMM Driver Dispatcher.
3
4 Step #1 - When a FV protocol is added to the system every driver in the FV
5 is added to the mDiscoveredList. The Before, and After Depex are
6 pre-processed as drivers are added to the mDiscoveredList. If an Apriori
7 file exists in the FV those drivers are addeded to the
8 mScheduledQueue. The mFvHandleList is used to make sure a
9 FV is only processed once.
10
11 Step #2 - Dispatch. Remove driver from the mScheduledQueue and load and
12 start it. After mScheduledQueue is drained check the
13 mDiscoveredList to see if any item has a Depex that is ready to
14 be placed on the mScheduledQueue.
15
16 Step #3 - Adding to the mScheduledQueue requires that you process Before
17 and After dependencies. This is done recursively as the call to add
18 to the mScheduledQueue checks for Before and recursively adds
19 all Befores. It then addes the item that was passed in and then
20 processess the After dependecies by recursively calling the routine.
21
22 Dispatcher Rules:
23 The rules for the dispatcher are similar to the DXE dispatcher.
24
25 The rules for DXE dispatcher are in chapter 10 of the DXE CIS. Figure 10-3
26 is the state diagram for the DXE dispatcher
27
28 Depex - Dependency Expresion.
29
30 Copyright (c) 2014, Hewlett-Packard Development Company, L.P.
31 Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.<BR>
32 This program and the accompanying materials are licensed and made available
33 under the terms and conditions of the BSD License which accompanies this
34 distribution. The full text of the license may be found at
35 http://opensource.org/licenses/bsd-license.php
36
37 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
38 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
39
40 **/
41
42 #include "PiSmmCore.h"
43
44 //
45 // SMM Dispatcher Data structures
46 //
47 #define KNOWN_HANDLE_SIGNATURE SIGNATURE_32('k','n','o','w')
48 typedef struct {
49 UINTN Signature;
50 LIST_ENTRY Link; // mFvHandleList
51 EFI_HANDLE Handle;
52 } KNOWN_HANDLE;
53
54 //
55 // Function Prototypes
56 //
57
58 /**
59 Insert InsertedDriverEntry onto the mScheduledQueue. To do this you
60 must add any driver with a before dependency on InsertedDriverEntry first.
61 You do this by recursively calling this routine. After all the Befores are
62 processed you can add InsertedDriverEntry to the mScheduledQueue.
63 Then you can add any driver with an After dependency on InsertedDriverEntry
64 by recursively calling this routine.
65
66 @param InsertedDriverEntry The driver to insert on the ScheduledLink Queue
67
68 **/
69 VOID
70 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (
71 IN EFI_SMM_DRIVER_ENTRY *InsertedDriverEntry
72 );
73
74 //
75 // The Driver List contains one copy of every driver that has been discovered.
76 // Items are never removed from the driver list. List of EFI_SMM_DRIVER_ENTRY
77 //
78 LIST_ENTRY mDiscoveredList = INITIALIZE_LIST_HEAD_VARIABLE (mDiscoveredList);
79
80 //
81 // Queue of drivers that are ready to dispatch. This queue is a subset of the
82 // mDiscoveredList.list of EFI_SMM_DRIVER_ENTRY.
83 //
84 LIST_ENTRY mScheduledQueue = INITIALIZE_LIST_HEAD_VARIABLE (mScheduledQueue);
85
86 //
87 // List of handles who's Fv's have been parsed and added to the mFwDriverList.
88 //
89 LIST_ENTRY mFvHandleList = INITIALIZE_LIST_HEAD_VARIABLE (mFvHandleList);
90
91 //
92 // Flag for the SMM Dispacher. TRUE if dispatcher is execuing.
93 //
94 BOOLEAN gDispatcherRunning = FALSE;
95
96 //
97 // Flag for the SMM Dispacher. TRUE if there is one or more SMM drivers ready to be dispatched
98 //
99 BOOLEAN gRequestDispatch = FALSE;
100
101 //
102 // List of file types supported by dispatcher
103 //
104 EFI_FV_FILETYPE mSmmFileTypes[] = {
105 EFI_FV_FILETYPE_SMM,
106 EFI_FV_FILETYPE_COMBINED_SMM_DXE,
107 EFI_FV_FILETYPE_SMM_CORE,
108 //
109 // Note: DXE core will process the FV image file, so skip it in SMM core
110 // EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE
111 //
112 };
113
114 typedef struct {
115 MEDIA_FW_VOL_FILEPATH_DEVICE_PATH File;
116 EFI_DEVICE_PATH_PROTOCOL End;
117 } FV_FILEPATH_DEVICE_PATH;
118
119 FV_FILEPATH_DEVICE_PATH mFvDevicePath;
120
121 //
122 // DXE Architecture Protocols
123 //
124 EFI_SECURITY_ARCH_PROTOCOL *mSecurity = NULL;
125 EFI_SECURITY2_ARCH_PROTOCOL *mSecurity2 = NULL;
126
127 //
128 // The global variable is defined for Loading modules at fixed address feature to track the SMM code
129 // memory range usage. It is a bit mapped array in which every bit indicates the corresponding
130 // memory page available or not.
131 //
132 GLOBAL_REMOVE_IF_UNREFERENCED UINT64 *mSmmCodeMemoryRangeUsageBitMap=NULL;
133
134 /**
135 To check memory usage bit map array to figure out if the memory range in which the image will be loaded is available or not. If
136 memory range is available, the function will mark the corresponding bits to 1 which indicates the memory range is used.
137 The function is only invoked when load modules at fixed address feature is enabled.
138
139 @param ImageBase The base address the image will be loaded at.
140 @param ImageSize The size of the image
141
142 @retval EFI_SUCCESS The memory range the image will be loaded in is available
143 @retval EFI_NOT_FOUND The memory range the image will be loaded in is not available
144 **/
145 EFI_STATUS
146 CheckAndMarkFixLoadingMemoryUsageBitMap (
147 IN EFI_PHYSICAL_ADDRESS ImageBase,
148 IN UINTN ImageSize
149 )
150 {
151 UINT32 SmmCodePageNumber;
152 UINT64 SmmCodeSize;
153 EFI_PHYSICAL_ADDRESS SmmCodeBase;
154 UINTN BaseOffsetPageNumber;
155 UINTN TopOffsetPageNumber;
156 UINTN Index;
157 //
158 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressSmmCodePageNumber
159 //
160 SmmCodePageNumber = PcdGet32(PcdLoadFixAddressSmmCodePageNumber);
161 SmmCodeSize = EFI_PAGES_TO_SIZE (SmmCodePageNumber);
162 SmmCodeBase = gLoadModuleAtFixAddressSmramBase;
163
164 //
165 // If the memory usage bit map is not initialized, do it. Every bit in the array
166 // indicate the status of the corresponding memory page, available or not
167 //
168 if (mSmmCodeMemoryRangeUsageBitMap == NULL) {
169 mSmmCodeMemoryRangeUsageBitMap = AllocateZeroPool(((SmmCodePageNumber / 64) + 1)*sizeof(UINT64));
170 }
171 //
172 // If the Dxe code memory range is not allocated or the bit map array allocation failed, return EFI_NOT_FOUND
173 //
174 if (mSmmCodeMemoryRangeUsageBitMap == NULL) {
175 return EFI_NOT_FOUND;
176 }
177 //
178 // see if the memory range for loading the image is in the SMM code range.
179 //
180 if (SmmCodeBase + SmmCodeSize < ImageBase + ImageSize || SmmCodeBase > ImageBase) {
181 return EFI_NOT_FOUND;
182 }
183 //
184 // Test if the memory is avalaible or not.
185 //
186 BaseOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase - SmmCodeBase));
187 TopOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase + ImageSize - SmmCodeBase));
188 for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {
189 if ((mSmmCodeMemoryRangeUsageBitMap[Index / 64] & LShiftU64(1, (Index % 64))) != 0) {
190 //
191 // This page is already used.
192 //
193 return EFI_NOT_FOUND;
194 }
195 }
196
197 //
198 // Being here means the memory range is available. So mark the bits for the memory range
199 //
200 for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {
201 mSmmCodeMemoryRangeUsageBitMap[Index / 64] |= LShiftU64(1, (Index % 64));
202 }
203 return EFI_SUCCESS;
204 }
205 /**
206 Get the fixed loading address from image header assigned by build tool. This function only be called
207 when Loading module at Fixed address feature enabled.
208
209 @param ImageContext Pointer to the image context structure that describes the PE/COFF
210 image that needs to be examined by this function.
211 @retval EFI_SUCCESS An fixed loading address is assigned to this image by build tools .
212 @retval EFI_NOT_FOUND The image has no assigned fixed loading address.
213
214 **/
215 EFI_STATUS
216 GetPeCoffImageFixLoadingAssignedAddress(
217 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
218 )
219 {
220 UINTN SectionHeaderOffset;
221 EFI_STATUS Status;
222 EFI_IMAGE_SECTION_HEADER SectionHeader;
223 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
224 EFI_PHYSICAL_ADDRESS FixLoadingAddress;
225 UINT16 Index;
226 UINTN Size;
227 UINT16 NumberOfSections;
228 UINT64 ValueInSectionHeader;
229
230 FixLoadingAddress = 0;
231 Status = EFI_NOT_FOUND;
232
233 //
234 // Get PeHeader pointer
235 //
236 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset);
237 SectionHeaderOffset = ImageContext->PeCoffHeaderOffset +
238 sizeof (UINT32) +
239 sizeof (EFI_IMAGE_FILE_HEADER) +
240 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader;
241 NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections;
242
243 //
244 // Get base address from the first section header that doesn't point to code section.
245 //
246 for (Index = 0; Index < NumberOfSections; Index++) {
247 //
248 // Read section header from file
249 //
250 Size = sizeof (EFI_IMAGE_SECTION_HEADER);
251 Status = ImageContext->ImageRead (
252 ImageContext->Handle,
253 SectionHeaderOffset,
254 &Size,
255 &SectionHeader
256 );
257 if (EFI_ERROR (Status)) {
258 return Status;
259 }
260
261 Status = EFI_NOT_FOUND;
262
263 if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) {
264 //
265 // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields in the first section header
266 // that doesn't point to code section in image header.So there is an assumption that when the feature is enabled,
267 // if a module with a loading address assigned by tools, the PointerToRelocations & PointerToLineNumbers fields
268 // should not be Zero, or else, these 2 fields should be set to Zero
269 //
270 ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations);
271 if (ValueInSectionHeader != 0) {
272 //
273 // Found first section header that doesn't point to code section in which build tool saves the
274 // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields
275 //
276 FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(gLoadModuleAtFixAddressSmramBase + (INT64)ValueInSectionHeader);
277 //
278 // Check if the memory range is available.
279 //
280 Status = CheckAndMarkFixLoadingMemoryUsageBitMap (FixLoadingAddress, (UINTN)(ImageContext->ImageSize + ImageContext->SectionAlignment));
281 if (!EFI_ERROR(Status)) {
282 //
283 // The assigned address is valid. Return the specified loading address
284 //
285 ImageContext->ImageAddress = FixLoadingAddress;
286 }
287 }
288 break;
289 }
290 SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);
291 }
292 DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r\n", FixLoadingAddress, Status));
293 return Status;
294 }
295 /**
296 Loads an EFI image into SMRAM.
297
298 @param DriverEntry EFI_SMM_DRIVER_ENTRY instance
299
300 @return EFI_STATUS
301
302 **/
303 EFI_STATUS
304 EFIAPI
305 SmmLoadImage (
306 IN OUT EFI_SMM_DRIVER_ENTRY *DriverEntry
307 )
308 {
309 UINT32 AuthenticationStatus;
310 UINTN FilePathSize;
311 VOID *Buffer;
312 UINTN Size;
313 UINTN PageCount;
314 EFI_GUID *NameGuid;
315 EFI_STATUS Status;
316 EFI_STATUS SecurityStatus;
317 EFI_HANDLE DeviceHandle;
318 EFI_PHYSICAL_ADDRESS DstBuffer;
319 EFI_DEVICE_PATH_PROTOCOL *FilePath;
320 EFI_DEVICE_PATH_PROTOCOL *OriginalFilePath;
321 EFI_DEVICE_PATH_PROTOCOL *HandleFilePath;
322 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
323 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
324 UINT64 Tick;
325
326 Tick = 0;
327 PERF_CODE (
328 Tick = GetPerformanceCounter ();
329 );
330
331 Buffer = NULL;
332 Size = 0;
333 Fv = DriverEntry->Fv;
334 NameGuid = &DriverEntry->FileName;
335 FilePath = DriverEntry->FvFileDevicePath;
336
337 OriginalFilePath = FilePath;
338 HandleFilePath = FilePath;
339 DeviceHandle = NULL;
340 SecurityStatus = EFI_SUCCESS;
341 Status = EFI_SUCCESS;
342 AuthenticationStatus = 0;
343
344 //
345 // Try to get the image device handle by checking the match protocol.
346 //
347 Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &HandleFilePath, &DeviceHandle);
348 if (EFI_ERROR(Status)) {
349 return Status;
350 }
351
352 //
353 // If the Security2 and Security Architectural Protocol has not been located yet, then attempt to locate it
354 //
355 if (mSecurity2 == NULL) {
356 gBS->LocateProtocol (&gEfiSecurity2ArchProtocolGuid, NULL, (VOID**)&mSecurity2);
357 }
358 if (mSecurity == NULL) {
359 gBS->LocateProtocol (&gEfiSecurityArchProtocolGuid, NULL, (VOID**)&mSecurity);
360 }
361 //
362 // When Security2 is installed, Security Architectural Protocol must be published.
363 //
364 ASSERT (mSecurity2 == NULL || mSecurity != NULL);
365
366 //
367 // Pull out just the file portion of the DevicePath for the LoadedImage FilePath
368 //
369 FilePath = OriginalFilePath;
370 Status = gBS->HandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath);
371 if (!EFI_ERROR (Status)) {
372 FilePathSize = GetDevicePathSize (HandleFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);
373 FilePath = (EFI_DEVICE_PATH_PROTOCOL *) (((UINT8 *)FilePath) + FilePathSize );
374 }
375
376 //
377 // Try reading PE32 section firstly
378 //
379 Status = Fv->ReadSection (
380 Fv,
381 NameGuid,
382 EFI_SECTION_PE32,
383 0,
384 &Buffer,
385 &Size,
386 &AuthenticationStatus
387 );
388
389 if (EFI_ERROR (Status)) {
390 //
391 // Try reading TE section secondly
392 //
393 Buffer = NULL;
394 Size = 0;
395 Status = Fv->ReadSection (
396 Fv,
397 NameGuid,
398 EFI_SECTION_TE,
399 0,
400 &Buffer,
401 &Size,
402 &AuthenticationStatus
403 );
404 }
405
406 if (EFI_ERROR (Status)) {
407 if (Buffer != NULL) {
408 gBS->FreePool (Buffer);
409 }
410 return Status;
411 }
412
413 //
414 // Verify File Authentication through the Security2 Architectural Protocol
415 //
416 if (mSecurity2 != NULL) {
417 SecurityStatus = mSecurity2->FileAuthentication (
418 mSecurity2,
419 OriginalFilePath,
420 Buffer,
421 Size,
422 FALSE
423 );
424 }
425
426 //
427 // Verify the Authentication Status through the Security Architectural Protocol
428 // Only on images that have been read using Firmware Volume protocol.
429 // All SMM images are from FV protocol.
430 //
431 if (!EFI_ERROR (SecurityStatus) && (mSecurity != NULL)) {
432 SecurityStatus = mSecurity->FileAuthenticationState (
433 mSecurity,
434 AuthenticationStatus,
435 OriginalFilePath
436 );
437 }
438
439 if (EFI_ERROR (SecurityStatus) && SecurityStatus != EFI_SECURITY_VIOLATION) {
440 Status = SecurityStatus;
441 return Status;
442 }
443
444 //
445 // Initialize ImageContext
446 //
447 ImageContext.Handle = Buffer;
448 ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory;
449
450 //
451 // Get information about the image being loaded
452 //
453 Status = PeCoffLoaderGetImageInfo (&ImageContext);
454 if (EFI_ERROR (Status)) {
455 if (Buffer != NULL) {
456 gBS->FreePool (Buffer);
457 }
458 return Status;
459 }
460 //
461 // if Loading module at Fixed Address feature is enabled, then cut out a memory range started from TESG BASE
462 // to hold the Smm driver code
463 //
464 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {
465 //
466 // Get the fixed loading address assigned by Build tool
467 //
468 Status = GetPeCoffImageFixLoadingAssignedAddress (&ImageContext);
469 if (!EFI_ERROR (Status)) {
470 //
471 // Since the memory range to load Smm core alreay been cut out, so no need to allocate and free this range
472 // following statements is to bypass SmmFreePages
473 //
474 PageCount = 0;
475 DstBuffer = (UINTN)gLoadModuleAtFixAddressSmramBase;
476 } else {
477 DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED ERROR: Failed to load module at fixed address. \n"));
478 //
479 // allocate the memory to load the SMM driver
480 //
481 PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment);
482 DstBuffer = (UINTN)(-1);
483
484 Status = SmmAllocatePages (
485 AllocateMaxAddress,
486 EfiRuntimeServicesCode,
487 PageCount,
488 &DstBuffer
489 );
490 if (EFI_ERROR (Status)) {
491 if (Buffer != NULL) {
492 gBS->FreePool (Buffer);
493 }
494 return Status;
495 }
496 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer;
497 }
498 } else {
499 PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment);
500 DstBuffer = (UINTN)(-1);
501
502 Status = SmmAllocatePages (
503 AllocateMaxAddress,
504 EfiRuntimeServicesCode,
505 PageCount,
506 &DstBuffer
507 );
508 if (EFI_ERROR (Status)) {
509 if (Buffer != NULL) {
510 gBS->FreePool (Buffer);
511 }
512 return Status;
513 }
514
515 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer;
516 }
517 //
518 // Align buffer on section boundary
519 //
520 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
521 ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)ImageContext.SectionAlignment - 1);
522
523 //
524 // Load the image to our new buffer
525 //
526 Status = PeCoffLoaderLoadImage (&ImageContext);
527 if (EFI_ERROR (Status)) {
528 if (Buffer != NULL) {
529 gBS->FreePool (Buffer);
530 }
531 SmmFreePages (DstBuffer, PageCount);
532 return Status;
533 }
534
535 //
536 // Relocate the image in our new buffer
537 //
538 Status = PeCoffLoaderRelocateImage (&ImageContext);
539 if (EFI_ERROR (Status)) {
540 if (Buffer != NULL) {
541 gBS->FreePool (Buffer);
542 }
543 SmmFreePages (DstBuffer, PageCount);
544 return Status;
545 }
546
547 //
548 // Flush the instruction cache so the image data are written before we execute it
549 //
550 InvalidateInstructionCacheRange ((VOID *)(UINTN) ImageContext.ImageAddress, (UINTN) ImageContext.ImageSize);
551
552 //
553 // Save Image EntryPoint in DriverEntry
554 //
555 DriverEntry->ImageEntryPoint = ImageContext.EntryPoint;
556 DriverEntry->ImageBuffer = DstBuffer;
557 DriverEntry->NumberOfPage = PageCount;
558
559 //
560 // Allocate a Loaded Image Protocol in EfiBootServicesData
561 //
562 Status = gBS->AllocatePool (EfiBootServicesData, sizeof (EFI_LOADED_IMAGE_PROTOCOL), (VOID **)&DriverEntry->LoadedImage);
563 if (EFI_ERROR (Status)) {
564 if (Buffer != NULL) {
565 gBS->FreePool (Buffer);
566 }
567 SmmFreePages (DstBuffer, PageCount);
568 return Status;
569 }
570
571 ZeroMem (DriverEntry->LoadedImage, sizeof (EFI_LOADED_IMAGE_PROTOCOL));
572 //
573 // Fill in the remaining fields of the Loaded Image Protocol instance.
574 // Note: ImageBase is an SMRAM address that can not be accessed outside of SMRAM if SMRAM window is closed.
575 //
576 DriverEntry->LoadedImage->Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION;
577 DriverEntry->LoadedImage->ParentHandle = gSmmCorePrivate->SmmIplImageHandle;
578 DriverEntry->LoadedImage->SystemTable = gST;
579 DriverEntry->LoadedImage->DeviceHandle = DeviceHandle;
580
581 DriverEntry->SmmLoadedImage.Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION;
582 DriverEntry->SmmLoadedImage.ParentHandle = gSmmCorePrivate->SmmIplImageHandle;
583 DriverEntry->SmmLoadedImage.SystemTable = gST;
584 DriverEntry->SmmLoadedImage.DeviceHandle = DeviceHandle;
585
586 //
587 // Make an EfiBootServicesData buffer copy of FilePath
588 //
589 Status = gBS->AllocatePool (EfiBootServicesData, GetDevicePathSize (FilePath), (VOID **)&DriverEntry->LoadedImage->FilePath);
590 if (EFI_ERROR (Status)) {
591 if (Buffer != NULL) {
592 gBS->FreePool (Buffer);
593 }
594 SmmFreePages (DstBuffer, PageCount);
595 return Status;
596 }
597 CopyMem (DriverEntry->LoadedImage->FilePath, FilePath, GetDevicePathSize (FilePath));
598
599 DriverEntry->LoadedImage->ImageBase = (VOID *)(UINTN)DriverEntry->ImageBuffer;
600 DriverEntry->LoadedImage->ImageSize = ImageContext.ImageSize;
601 DriverEntry->LoadedImage->ImageCodeType = EfiRuntimeServicesCode;
602 DriverEntry->LoadedImage->ImageDataType = EfiRuntimeServicesData;
603
604 //
605 // Make a buffer copy of FilePath
606 //
607 Status = SmmAllocatePool (EfiRuntimeServicesData, GetDevicePathSize(FilePath), (VOID **)&DriverEntry->SmmLoadedImage.FilePath);
608 if (EFI_ERROR (Status)) {
609 if (Buffer != NULL) {
610 gBS->FreePool (Buffer);
611 }
612 gBS->FreePool (DriverEntry->LoadedImage->FilePath);
613 SmmFreePages (DstBuffer, PageCount);
614 return Status;
615 }
616 CopyMem (DriverEntry->SmmLoadedImage.FilePath, FilePath, GetDevicePathSize(FilePath));
617
618 DriverEntry->SmmLoadedImage.ImageBase = (VOID *)(UINTN)DriverEntry->ImageBuffer;
619 DriverEntry->SmmLoadedImage.ImageSize = ImageContext.ImageSize;
620 DriverEntry->SmmLoadedImage.ImageCodeType = EfiRuntimeServicesCode;
621 DriverEntry->SmmLoadedImage.ImageDataType = EfiRuntimeServicesData;
622
623 //
624 // Create a new image handle in the UEFI handle database for the SMM Driver
625 //
626 DriverEntry->ImageHandle = NULL;
627 Status = gBS->InstallMultipleProtocolInterfaces (
628 &DriverEntry->ImageHandle,
629 &gEfiLoadedImageProtocolGuid, DriverEntry->LoadedImage,
630 NULL
631 );
632
633 //
634 // Create a new image handle in the SMM handle database for the SMM Driver
635 //
636 DriverEntry->SmmImageHandle = NULL;
637 Status = SmmInstallProtocolInterface (
638 &DriverEntry->SmmImageHandle,
639 &gEfiLoadedImageProtocolGuid,
640 EFI_NATIVE_INTERFACE,
641 &DriverEntry->SmmLoadedImage
642 );
643
644 PERF_START (DriverEntry->ImageHandle, "LoadImage:", NULL, Tick);
645 PERF_END (DriverEntry->ImageHandle, "LoadImage:", NULL, 0);
646
647 //
648 // Print the load address and the PDB file name if it is available
649 //
650
651 DEBUG_CODE_BEGIN ();
652
653 UINTN Index;
654 UINTN StartIndex;
655 CHAR8 EfiFileName[256];
656
657
658 DEBUG ((DEBUG_INFO | DEBUG_LOAD,
659 "Loading SMM driver at 0x%11p EntryPoint=0x%11p ",
660 (VOID *)(UINTN) ImageContext.ImageAddress,
661 FUNCTION_ENTRY_POINT (ImageContext.EntryPoint)));
662
663
664 //
665 // Print Module Name by Pdb file path.
666 // Windows and Unix style file path are all trimmed correctly.
667 //
668 if (ImageContext.PdbPointer != NULL) {
669 StartIndex = 0;
670 for (Index = 0; ImageContext.PdbPointer[Index] != 0; Index++) {
671 if ((ImageContext.PdbPointer[Index] == '\\') || (ImageContext.PdbPointer[Index] == '/')) {
672 StartIndex = Index + 1;
673 }
674 }
675 //
676 // Copy the PDB file name to our temporary string, and replace .pdb with .efi
677 // The PDB file name is limited in the range of 0~255.
678 // If the length is bigger than 255, trim the redudant characters to avoid overflow in array boundary.
679 //
680 for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) {
681 EfiFileName[Index] = ImageContext.PdbPointer[Index + StartIndex];
682 if (EfiFileName[Index] == 0) {
683 EfiFileName[Index] = '.';
684 }
685 if (EfiFileName[Index] == '.') {
686 EfiFileName[Index + 1] = 'e';
687 EfiFileName[Index + 2] = 'f';
688 EfiFileName[Index + 3] = 'i';
689 EfiFileName[Index + 4] = 0;
690 break;
691 }
692 }
693
694 if (Index == sizeof (EfiFileName) - 4) {
695 EfiFileName[Index] = 0;
696 }
697 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex]));
698 }
699 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n"));
700
701 DEBUG_CODE_END ();
702
703 //
704 // Free buffer allocated by Fv->ReadSection.
705 //
706 // The UEFI Boot Services FreePool() function must be used because Fv->ReadSection
707 // used the UEFI Boot Services AllocatePool() function
708 //
709 Status = gBS->FreePool(Buffer);
710 if (!EFI_ERROR (Status) && EFI_ERROR (SecurityStatus)) {
711 Status = SecurityStatus;
712 }
713 return Status;
714 }
715
716 /**
717 Preprocess dependency expression and update DriverEntry to reflect the
718 state of Before and After dependencies. If DriverEntry->Before
719 or DriverEntry->After is set it will never be cleared.
720
721 @param DriverEntry DriverEntry element to update .
722
723 @retval EFI_SUCCESS It always works.
724
725 **/
726 EFI_STATUS
727 SmmPreProcessDepex (
728 IN EFI_SMM_DRIVER_ENTRY *DriverEntry
729 )
730 {
731 UINT8 *Iterator;
732
733 Iterator = DriverEntry->Depex;
734 DriverEntry->Dependent = TRUE;
735
736 if (*Iterator == EFI_DEP_BEFORE) {
737 DriverEntry->Before = TRUE;
738 } else if (*Iterator == EFI_DEP_AFTER) {
739 DriverEntry->After = TRUE;
740 }
741
742 if (DriverEntry->Before || DriverEntry->After) {
743 CopyMem (&DriverEntry->BeforeAfterGuid, Iterator + 1, sizeof (EFI_GUID));
744 }
745
746 return EFI_SUCCESS;
747 }
748
749 /**
750 Read Depex and pre-process the Depex for Before and After. If Section Extraction
751 protocol returns an error via ReadSection defer the reading of the Depex.
752
753 @param DriverEntry Driver to work on.
754
755 @retval EFI_SUCCESS Depex read and preprossesed
756 @retval EFI_PROTOCOL_ERROR The section extraction protocol returned an error
757 and Depex reading needs to be retried.
758 @retval Error DEPEX not found.
759
760 **/
761 EFI_STATUS
762 SmmGetDepexSectionAndPreProccess (
763 IN EFI_SMM_DRIVER_ENTRY *DriverEntry
764 )
765 {
766 EFI_STATUS Status;
767 EFI_SECTION_TYPE SectionType;
768 UINT32 AuthenticationStatus;
769 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
770
771 Fv = DriverEntry->Fv;
772
773 //
774 // Grab Depex info, it will never be free'ed.
775 // (Note: DriverEntry->Depex is in DXE memory)
776 //
777 SectionType = EFI_SECTION_SMM_DEPEX;
778 Status = Fv->ReadSection (
779 DriverEntry->Fv,
780 &DriverEntry->FileName,
781 SectionType,
782 0,
783 &DriverEntry->Depex,
784 (UINTN *)&DriverEntry->DepexSize,
785 &AuthenticationStatus
786 );
787 if (EFI_ERROR (Status)) {
788 if (Status == EFI_PROTOCOL_ERROR) {
789 //
790 // The section extraction protocol failed so set protocol error flag
791 //
792 DriverEntry->DepexProtocolError = TRUE;
793 } else {
794 //
795 // If no Depex assume depend on all architectural protocols
796 //
797 DriverEntry->Depex = NULL;
798 DriverEntry->Dependent = TRUE;
799 DriverEntry->DepexProtocolError = FALSE;
800 }
801 } else {
802 //
803 // Set Before and After state information based on Depex
804 // Driver will be put in Dependent state
805 //
806 SmmPreProcessDepex (DriverEntry);
807 DriverEntry->DepexProtocolError = FALSE;
808 }
809
810 return Status;
811 }
812
813 /**
814 This is the main Dispatcher for SMM and it exits when there are no more
815 drivers to run. Drain the mScheduledQueue and load and start a PE
816 image for each driver. Search the mDiscoveredList to see if any driver can
817 be placed on the mScheduledQueue. If no drivers are placed on the
818 mScheduledQueue exit the function.
819
820 @retval EFI_SUCCESS All of the SMM Drivers that could be dispatched
821 have been run and the SMM Entry Point has been
822 registered.
823 @retval EFI_NOT_READY The SMM Driver that registered the SMM Entry Point
824 was just dispatched.
825 @retval EFI_NOT_FOUND There are no SMM Drivers available to be dispatched.
826 @retval EFI_ALREADY_STARTED The SMM Dispatcher is already running
827
828 **/
829 EFI_STATUS
830 SmmDispatcher (
831 VOID
832 )
833 {
834 EFI_STATUS Status;
835 LIST_ENTRY *Link;
836 EFI_SMM_DRIVER_ENTRY *DriverEntry;
837 BOOLEAN ReadyToRun;
838 BOOLEAN PreviousSmmEntryPointRegistered;
839
840 if (!gRequestDispatch) {
841 return EFI_NOT_FOUND;
842 }
843
844 if (gDispatcherRunning) {
845 //
846 // If the dispatcher is running don't let it be restarted.
847 //
848 return EFI_ALREADY_STARTED;
849 }
850
851 gDispatcherRunning = TRUE;
852
853 do {
854 //
855 // Drain the Scheduled Queue
856 //
857 while (!IsListEmpty (&mScheduledQueue)) {
858 DriverEntry = CR (
859 mScheduledQueue.ForwardLink,
860 EFI_SMM_DRIVER_ENTRY,
861 ScheduledLink,
862 EFI_SMM_DRIVER_ENTRY_SIGNATURE
863 );
864
865 //
866 // Load the SMM Driver image into memory. If the Driver was transitioned from
867 // Untrused to Scheduled it would have already been loaded so we may need to
868 // skip the LoadImage
869 //
870 if (DriverEntry->ImageHandle == NULL) {
871 Status = SmmLoadImage (DriverEntry);
872
873 //
874 // Update the driver state to reflect that it's been loaded
875 //
876 if (EFI_ERROR (Status)) {
877 //
878 // The SMM Driver could not be loaded, and do not attempt to load or start it again.
879 // Take driver from Scheduled to Initialized.
880 //
881 DriverEntry->Initialized = TRUE;
882 DriverEntry->Scheduled = FALSE;
883 RemoveEntryList (&DriverEntry->ScheduledLink);
884
885 //
886 // If it's an error don't try the StartImage
887 //
888 continue;
889 }
890 }
891
892 DriverEntry->Scheduled = FALSE;
893 DriverEntry->Initialized = TRUE;
894 RemoveEntryList (&DriverEntry->ScheduledLink);
895
896 REPORT_STATUS_CODE_WITH_EXTENDED_DATA (
897 EFI_PROGRESS_CODE,
898 EFI_SOFTWARE_SMM_DRIVER | EFI_SW_PC_INIT_BEGIN,
899 &DriverEntry->ImageHandle,
900 sizeof (DriverEntry->ImageHandle)
901 );
902
903 //
904 // Cache state of SmmEntryPointRegistered before calling entry point
905 //
906 PreviousSmmEntryPointRegistered = gSmmCorePrivate->SmmEntryPointRegistered;
907
908 //
909 // For each SMM driver, pass NULL as ImageHandle
910 //
911 RegisterSmramProfileImage (DriverEntry, TRUE);
912 PERF_START (DriverEntry->ImageHandle, "StartImage:", NULL, 0);
913 Status = ((EFI_IMAGE_ENTRY_POINT)(UINTN)DriverEntry->ImageEntryPoint)(DriverEntry->ImageHandle, gST);
914 PERF_END (DriverEntry->ImageHandle, "StartImage:", NULL, 0);
915 if (EFI_ERROR(Status)){
916 UnregisterSmramProfileImage (DriverEntry, TRUE);
917 SmmFreePages(DriverEntry->ImageBuffer, DriverEntry->NumberOfPage);
918 //
919 // Uninstall LoadedImage
920 //
921 Status = gBS->UninstallProtocolInterface (
922 DriverEntry->ImageHandle,
923 &gEfiLoadedImageProtocolGuid,
924 DriverEntry->LoadedImage
925 );
926 if (!EFI_ERROR (Status)) {
927 if (DriverEntry->LoadedImage->FilePath != NULL) {
928 gBS->FreePool (DriverEntry->LoadedImage->FilePath);
929 }
930 gBS->FreePool (DriverEntry->LoadedImage);
931 }
932 Status = SmmUninstallProtocolInterface (
933 DriverEntry->SmmImageHandle,
934 &gEfiLoadedImageProtocolGuid,
935 &DriverEntry->SmmLoadedImage
936 );
937 if (!EFI_ERROR(Status)) {
938 if (DriverEntry->SmmLoadedImage.FilePath != NULL) {
939 SmmFreePool (DriverEntry->SmmLoadedImage.FilePath);
940 }
941 }
942 }
943
944 REPORT_STATUS_CODE_WITH_EXTENDED_DATA (
945 EFI_PROGRESS_CODE,
946 EFI_SOFTWARE_SMM_DRIVER | EFI_SW_PC_INIT_END,
947 &DriverEntry->ImageHandle,
948 sizeof (DriverEntry->ImageHandle)
949 );
950
951 if (!PreviousSmmEntryPointRegistered && gSmmCorePrivate->SmmEntryPointRegistered) {
952 //
953 // Return immediately if the SMM Entry Point was registered by the SMM
954 // Driver that was just dispatched. The SMM IPL will reinvoke the SMM
955 // Core Dispatcher. This is required so SMM Mode may be enabled as soon
956 // as all the dependent SMM Drivers for SMM Mode have been dispatched.
957 // Once the SMM Entry Point has been registered, then SMM Mode will be
958 // used.
959 //
960 gRequestDispatch = TRUE;
961 gDispatcherRunning = FALSE;
962 return EFI_NOT_READY;
963 }
964 }
965
966 //
967 // Search DriverList for items to place on Scheduled Queue
968 //
969 ReadyToRun = FALSE;
970 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
971 DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
972
973 if (DriverEntry->DepexProtocolError){
974 //
975 // If Section Extraction Protocol did not let the Depex be read before retry the read
976 //
977 Status = SmmGetDepexSectionAndPreProccess (DriverEntry);
978 }
979
980 if (DriverEntry->Dependent) {
981 if (SmmIsSchedulable (DriverEntry)) {
982 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
983 ReadyToRun = TRUE;
984 }
985 }
986 }
987 } while (ReadyToRun);
988
989 //
990 // If there is no more SMM driver to dispatch, stop the dispatch request
991 //
992 gRequestDispatch = FALSE;
993 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
994 DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
995
996 if (!DriverEntry->Initialized){
997 //
998 // We have SMM driver pending to dispatch
999 //
1000 gRequestDispatch = TRUE;
1001 break;
1002 }
1003 }
1004
1005 gDispatcherRunning = FALSE;
1006
1007 return EFI_SUCCESS;
1008 }
1009
1010 /**
1011 Insert InsertedDriverEntry onto the mScheduledQueue. To do this you
1012 must add any driver with a before dependency on InsertedDriverEntry first.
1013 You do this by recursively calling this routine. After all the Befores are
1014 processed you can add InsertedDriverEntry to the mScheduledQueue.
1015 Then you can add any driver with an After dependency on InsertedDriverEntry
1016 by recursively calling this routine.
1017
1018 @param InsertedDriverEntry The driver to insert on the ScheduledLink Queue
1019
1020 **/
1021 VOID
1022 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (
1023 IN EFI_SMM_DRIVER_ENTRY *InsertedDriverEntry
1024 )
1025 {
1026 LIST_ENTRY *Link;
1027 EFI_SMM_DRIVER_ENTRY *DriverEntry;
1028
1029 //
1030 // Process Before Dependency
1031 //
1032 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
1033 DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
1034 if (DriverEntry->Before && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) {
1035 DEBUG ((DEBUG_DISPATCH, "Evaluate SMM DEPEX for FFS(%g)\n", &DriverEntry->FileName));
1036 DEBUG ((DEBUG_DISPATCH, " BEFORE FFS(%g) = ", &DriverEntry->BeforeAfterGuid));
1037 if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {
1038 //
1039 // Recursively process BEFORE
1040 //
1041 DEBUG ((DEBUG_DISPATCH, "TRUE\n END\n RESULT = TRUE\n"));
1042 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
1043 } else {
1044 DEBUG ((DEBUG_DISPATCH, "FALSE\n END\n RESULT = FALSE\n"));
1045 }
1046 }
1047 }
1048
1049 //
1050 // Convert driver from Dependent to Scheduled state
1051 //
1052
1053 InsertedDriverEntry->Dependent = FALSE;
1054 InsertedDriverEntry->Scheduled = TRUE;
1055 InsertTailList (&mScheduledQueue, &InsertedDriverEntry->ScheduledLink);
1056
1057
1058 //
1059 // Process After Dependency
1060 //
1061 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
1062 DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
1063 if (DriverEntry->After && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) {
1064 DEBUG ((DEBUG_DISPATCH, "Evaluate SMM DEPEX for FFS(%g)\n", &DriverEntry->FileName));
1065 DEBUG ((DEBUG_DISPATCH, " AFTER FFS(%g) = ", &DriverEntry->BeforeAfterGuid));
1066 if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {
1067 //
1068 // Recursively process AFTER
1069 //
1070 DEBUG ((DEBUG_DISPATCH, "TRUE\n END\n RESULT = TRUE\n"));
1071 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
1072 } else {
1073 DEBUG ((DEBUG_DISPATCH, "FALSE\n END\n RESULT = FALSE\n"));
1074 }
1075 }
1076 }
1077 }
1078
1079 /**
1080 Return TRUE if the Fv has been processed, FALSE if not.
1081
1082 @param FvHandle The handle of a FV that's being tested
1083
1084 @retval TRUE Fv protocol on FvHandle has been processed
1085 @retval FALSE Fv protocol on FvHandle has not yet been
1086 processed
1087
1088 **/
1089 BOOLEAN
1090 FvHasBeenProcessed (
1091 IN EFI_HANDLE FvHandle
1092 )
1093 {
1094 LIST_ENTRY *Link;
1095 KNOWN_HANDLE *KnownHandle;
1096
1097 for (Link = mFvHandleList.ForwardLink; Link != &mFvHandleList; Link = Link->ForwardLink) {
1098 KnownHandle = CR(Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE);
1099 if (KnownHandle->Handle == FvHandle) {
1100 return TRUE;
1101 }
1102 }
1103 return FALSE;
1104 }
1105
1106 /**
1107 Remember that Fv protocol on FvHandle has had it's drivers placed on the
1108 mDiscoveredList. This fucntion adds entries on the mFvHandleList. Items are
1109 never removed/freed from the mFvHandleList.
1110
1111 @param FvHandle The handle of a FV that has been processed
1112
1113 **/
1114 VOID
1115 FvIsBeingProcesssed (
1116 IN EFI_HANDLE FvHandle
1117 )
1118 {
1119 KNOWN_HANDLE *KnownHandle;
1120
1121 KnownHandle = AllocatePool (sizeof (KNOWN_HANDLE));
1122 ASSERT (KnownHandle != NULL);
1123
1124 KnownHandle->Signature = KNOWN_HANDLE_SIGNATURE;
1125 KnownHandle->Handle = FvHandle;
1126 InsertTailList (&mFvHandleList, &KnownHandle->Link);
1127 }
1128
1129 /**
1130 Convert FvHandle and DriverName into an EFI device path
1131
1132 @param Fv Fv protocol, needed to read Depex info out of
1133 FLASH.
1134 @param FvHandle Handle for Fv, needed in the
1135 EFI_SMM_DRIVER_ENTRY so that the PE image can be
1136 read out of the FV at a later time.
1137 @param DriverName Name of driver to add to mDiscoveredList.
1138
1139 @return Pointer to device path constructed from FvHandle and DriverName
1140
1141 **/
1142 EFI_DEVICE_PATH_PROTOCOL *
1143 SmmFvToDevicePath (
1144 IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv,
1145 IN EFI_HANDLE FvHandle,
1146 IN EFI_GUID *DriverName
1147 )
1148 {
1149 EFI_STATUS Status;
1150 EFI_DEVICE_PATH_PROTOCOL *FvDevicePath;
1151 EFI_DEVICE_PATH_PROTOCOL *FileNameDevicePath;
1152
1153 //
1154 // Remember the device path of the FV
1155 //
1156 Status = gBS->HandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);
1157 if (EFI_ERROR (Status)) {
1158 FileNameDevicePath = NULL;
1159 } else {
1160 //
1161 // Build a device path to the file in the FV to pass into gBS->LoadImage
1162 //
1163 EfiInitializeFwVolDevicepathNode (&mFvDevicePath.File, DriverName);
1164 SetDevicePathEndNode (&mFvDevicePath.End);
1165
1166 //
1167 // Note: FileNameDevicePath is in DXE memory
1168 //
1169 FileNameDevicePath = AppendDevicePath (
1170 FvDevicePath,
1171 (EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath
1172 );
1173 }
1174 return FileNameDevicePath;
1175 }
1176
1177 /**
1178 Add an entry to the mDiscoveredList. Allocate memory to store the DriverEntry,
1179 and initilize any state variables. Read the Depex from the FV and store it
1180 in DriverEntry. Pre-process the Depex to set the Before and After state.
1181 The Discovered list is never free'ed and contains booleans that represent the
1182 other possible SMM driver states.
1183
1184 @param Fv Fv protocol, needed to read Depex info out of
1185 FLASH.
1186 @param FvHandle Handle for Fv, needed in the
1187 EFI_SMM_DRIVER_ENTRY so that the PE image can be
1188 read out of the FV at a later time.
1189 @param DriverName Name of driver to add to mDiscoveredList.
1190
1191 @retval EFI_SUCCESS If driver was added to the mDiscoveredList.
1192 @retval EFI_ALREADY_STARTED The driver has already been started. Only one
1193 DriverName may be active in the system at any one
1194 time.
1195
1196 **/
1197 EFI_STATUS
1198 SmmAddToDriverList (
1199 IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv,
1200 IN EFI_HANDLE FvHandle,
1201 IN EFI_GUID *DriverName
1202 )
1203 {
1204 EFI_SMM_DRIVER_ENTRY *DriverEntry;
1205
1206 //
1207 // Create the Driver Entry for the list. ZeroPool initializes lots of variables to
1208 // NULL or FALSE.
1209 //
1210 DriverEntry = AllocateZeroPool (sizeof (EFI_SMM_DRIVER_ENTRY));
1211 ASSERT (DriverEntry != NULL);
1212
1213 DriverEntry->Signature = EFI_SMM_DRIVER_ENTRY_SIGNATURE;
1214 CopyGuid (&DriverEntry->FileName, DriverName);
1215 DriverEntry->FvHandle = FvHandle;
1216 DriverEntry->Fv = Fv;
1217 DriverEntry->FvFileDevicePath = SmmFvToDevicePath (Fv, FvHandle, DriverName);
1218
1219 SmmGetDepexSectionAndPreProccess (DriverEntry);
1220
1221 InsertTailList (&mDiscoveredList, &DriverEntry->Link);
1222 gRequestDispatch = TRUE;
1223
1224 return EFI_SUCCESS;
1225 }
1226
1227 /**
1228 This function is the main entry point for an SMM handler dispatch
1229 or communicate-based callback.
1230
1231 Event notification that is fired every time a FV dispatch protocol is added.
1232 More than one protocol may have been added when this event is fired, so you
1233 must loop on SmmLocateHandle () to see how many protocols were added and
1234 do the following to each FV:
1235 If the Fv has already been processed, skip it. If the Fv has not been
1236 processed then mark it as being processed, as we are about to process it.
1237 Read the Fv and add any driver in the Fv to the mDiscoveredList.The
1238 mDiscoveredList is never free'ed and contains variables that define
1239 the other states the SMM driver transitions to..
1240 While you are at it read the A Priori file into memory.
1241 Place drivers in the A Priori list onto the mScheduledQueue.
1242
1243 @param DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().
1244 @param Context Points to an optional handler context which was specified when the handler was registered.
1245 @param CommBuffer A pointer to a collection of data in memory that will
1246 be conveyed from a non-SMM environment into an SMM environment.
1247 @param CommBufferSize The size of the CommBuffer.
1248
1249 @return Status Code
1250
1251 **/
1252 EFI_STATUS
1253 EFIAPI
1254 SmmDriverDispatchHandler (
1255 IN EFI_HANDLE DispatchHandle,
1256 IN CONST VOID *Context, OPTIONAL
1257 IN OUT VOID *CommBuffer, OPTIONAL
1258 IN OUT UINTN *CommBufferSize OPTIONAL
1259 )
1260 {
1261 EFI_STATUS Status;
1262 UINTN HandleCount;
1263 EFI_HANDLE *HandleBuffer;
1264 EFI_STATUS GetNextFileStatus;
1265 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
1266 EFI_DEVICE_PATH_PROTOCOL *FvDevicePath;
1267 EFI_HANDLE FvHandle;
1268 EFI_GUID NameGuid;
1269 UINTN Key;
1270 EFI_FV_FILETYPE Type;
1271 EFI_FV_FILE_ATTRIBUTES Attributes;
1272 UINTN Size;
1273 EFI_SMM_DRIVER_ENTRY *DriverEntry;
1274 EFI_GUID *AprioriFile;
1275 UINTN AprioriEntryCount;
1276 UINTN HandleIndex;
1277 UINTN SmmTypeIndex;
1278 UINTN AprioriIndex;
1279 LIST_ENTRY *Link;
1280 UINT32 AuthenticationStatus;
1281 UINTN SizeOfBuffer;
1282
1283 HandleBuffer = NULL;
1284 Status = gBS->LocateHandleBuffer (
1285 ByProtocol,
1286 &gEfiFirmwareVolume2ProtocolGuid,
1287 NULL,
1288 &HandleCount,
1289 &HandleBuffer
1290 );
1291 if (EFI_ERROR (Status)) {
1292 return EFI_NOT_FOUND;
1293 }
1294
1295 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1296 FvHandle = HandleBuffer[HandleIndex];
1297
1298 if (FvHasBeenProcessed (FvHandle)) {
1299 //
1300 // This Fv has already been processed so lets skip it!
1301 //
1302 continue;
1303 }
1304
1305 //
1306 // Since we are about to process this Fv mark it as processed.
1307 //
1308 FvIsBeingProcesssed (FvHandle);
1309
1310 Status = gBS->HandleProtocol (FvHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **)&Fv);
1311 if (EFI_ERROR (Status)) {
1312 //
1313 // FvHandle must have a Firmware Volume2 Protocol thus we should never get here.
1314 //
1315 ASSERT (FALSE);
1316 continue;
1317 }
1318
1319 Status = gBS->HandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);
1320 if (EFI_ERROR (Status)) {
1321 //
1322 // The Firmware volume doesn't have device path, can't be dispatched.
1323 //
1324 continue;
1325 }
1326
1327 //
1328 // Discover Drivers in FV and add them to the Discovered Driver List.
1329 // Process EFI_FV_FILETYPE_SMM type and then EFI_FV_FILETYPE_COMBINED_SMM_DXE
1330 // EFI_FV_FILETYPE_SMM_CORE is processed to produce a Loaded Image protocol for the core
1331 //
1332 for (SmmTypeIndex = 0; SmmTypeIndex < sizeof (mSmmFileTypes)/sizeof (EFI_FV_FILETYPE); SmmTypeIndex++) {
1333 //
1334 // Initialize the search key
1335 //
1336 Key = 0;
1337 do {
1338 Type = mSmmFileTypes[SmmTypeIndex];
1339 GetNextFileStatus = Fv->GetNextFile (
1340 Fv,
1341 &Key,
1342 &Type,
1343 &NameGuid,
1344 &Attributes,
1345 &Size
1346 );
1347 if (!EFI_ERROR (GetNextFileStatus)) {
1348 if (Type == EFI_FV_FILETYPE_SMM_CORE) {
1349 //
1350 // If this is the SMM core fill in it's DevicePath & DeviceHandle
1351 //
1352 if (mSmmCoreLoadedImage->FilePath == NULL) {
1353 //
1354 // Maybe one special FV contains only one SMM_CORE module, so its device path must
1355 // be initialized completely.
1356 //
1357 EfiInitializeFwVolDevicepathNode (&mFvDevicePath.File, &NameGuid);
1358 SetDevicePathEndNode (&mFvDevicePath.End);
1359
1360 //
1361 // Make an EfiBootServicesData buffer copy of FilePath
1362 //
1363 Status = gBS->AllocatePool (
1364 EfiBootServicesData,
1365 GetDevicePathSize ((EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath),
1366 (VOID **)&mSmmCoreLoadedImage->FilePath
1367 );
1368 ASSERT_EFI_ERROR (Status);
1369 CopyMem (mSmmCoreLoadedImage->FilePath, &mFvDevicePath, GetDevicePathSize ((EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath));
1370
1371 mSmmCoreLoadedImage->DeviceHandle = FvHandle;
1372 }
1373 if (mSmmCoreDriverEntry->SmmLoadedImage.FilePath == NULL) {
1374 //
1375 // Maybe one special FV contains only one SMM_CORE module, so its device path must
1376 // be initialized completely.
1377 //
1378 EfiInitializeFwVolDevicepathNode (&mFvDevicePath.File, &NameGuid);
1379 SetDevicePathEndNode (&mFvDevicePath.End);
1380
1381 //
1382 // Make a buffer copy FilePath
1383 //
1384 Status = SmmAllocatePool (
1385 EfiRuntimeServicesData,
1386 GetDevicePathSize ((EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath),
1387 (VOID **)&mSmmCoreDriverEntry->SmmLoadedImage.FilePath
1388 );
1389 ASSERT_EFI_ERROR (Status);
1390 CopyMem (mSmmCoreDriverEntry->SmmLoadedImage.FilePath, &mFvDevicePath, GetDevicePathSize((EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath));
1391
1392 mSmmCoreDriverEntry->SmmLoadedImage.DeviceHandle = FvHandle;
1393 }
1394 } else {
1395 SmmAddToDriverList (Fv, FvHandle, &NameGuid);
1396 }
1397 }
1398 } while (!EFI_ERROR (GetNextFileStatus));
1399 }
1400
1401 //
1402 // Read the array of GUIDs from the Apriori file if it is present in the firmware volume
1403 // (Note: AprioriFile is in DXE memory)
1404 //
1405 AprioriFile = NULL;
1406 Status = Fv->ReadSection (
1407 Fv,
1408 &gAprioriGuid,
1409 EFI_SECTION_RAW,
1410 0,
1411 (VOID **)&AprioriFile,
1412 &SizeOfBuffer,
1413 &AuthenticationStatus
1414 );
1415 if (!EFI_ERROR (Status)) {
1416 AprioriEntryCount = SizeOfBuffer / sizeof (EFI_GUID);
1417 } else {
1418 AprioriEntryCount = 0;
1419 }
1420
1421 //
1422 // Put drivers on Apriori List on the Scheduled queue. The Discovered List includes
1423 // drivers not in the current FV and these must be skipped since the a priori list
1424 // is only valid for the FV that it resided in.
1425 //
1426
1427 for (AprioriIndex = 0; AprioriIndex < AprioriEntryCount; AprioriIndex++) {
1428 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
1429 DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
1430 if (CompareGuid (&DriverEntry->FileName, &AprioriFile[AprioriIndex]) &&
1431 (FvHandle == DriverEntry->FvHandle)) {
1432 DriverEntry->Dependent = FALSE;
1433 DriverEntry->Scheduled = TRUE;
1434 InsertTailList (&mScheduledQueue, &DriverEntry->ScheduledLink);
1435 DEBUG ((DEBUG_DISPATCH, "Evaluate SMM DEPEX for FFS(%g)\n", &DriverEntry->FileName));
1436 DEBUG ((DEBUG_DISPATCH, " RESULT = TRUE (Apriori)\n"));
1437 break;
1438 }
1439 }
1440 }
1441
1442 //
1443 // Free data allocated by Fv->ReadSection ()
1444 //
1445 // The UEFI Boot Services FreePool() function must be used because Fv->ReadSection
1446 // used the UEFI Boot Services AllocatePool() function
1447 //
1448 gBS->FreePool (AprioriFile);
1449 }
1450
1451 //
1452 // Execute the SMM Dispatcher on any newly discovered FVs and previously
1453 // discovered SMM drivers that have been discovered but not dispatched.
1454 //
1455 Status = SmmDispatcher ();
1456
1457 //
1458 // Check to see if CommBuffer and CommBufferSize are valid
1459 //
1460 if (CommBuffer != NULL && CommBufferSize != NULL) {
1461 if (*CommBufferSize > 0) {
1462 if (Status == EFI_NOT_READY) {
1463 //
1464 // If a the SMM Core Entry Point was just registered, then set flag to
1465 // request the SMM Dispatcher to be restarted.
1466 //
1467 *(UINT8 *)CommBuffer = COMM_BUFFER_SMM_DISPATCH_RESTART;
1468 } else if (!EFI_ERROR (Status)) {
1469 //
1470 // Set the flag to show that the SMM Dispatcher executed without errors
1471 //
1472 *(UINT8 *)CommBuffer = COMM_BUFFER_SMM_DISPATCH_SUCCESS;
1473 } else {
1474 //
1475 // Set the flag to show that the SMM Dispatcher encountered an error
1476 //
1477 *(UINT8 *)CommBuffer = COMM_BUFFER_SMM_DISPATCH_ERROR;
1478 }
1479 }
1480 }
1481
1482 return EFI_SUCCESS;
1483 }
1484
1485 /**
1486 Traverse the discovered list for any drivers that were discovered but not loaded
1487 because the dependency experessions evaluated to false.
1488
1489 **/
1490 VOID
1491 SmmDisplayDiscoveredNotDispatched (
1492 VOID
1493 )
1494 {
1495 LIST_ENTRY *Link;
1496 EFI_SMM_DRIVER_ENTRY *DriverEntry;
1497
1498 for (Link = mDiscoveredList.ForwardLink;Link !=&mDiscoveredList; Link = Link->ForwardLink) {
1499 DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
1500 if (DriverEntry->Dependent) {
1501 DEBUG ((DEBUG_LOAD, "SMM Driver %g was discovered but not loaded!!\n", &DriverEntry->FileName));
1502 }
1503 }
1504 }