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