]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Core/PiSmmCore/Dispatcher.c
MdeModulePkg: Clean up source files
[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 - 2018, 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
325 PERF_LOAD_IMAGE_BEGIN (DriverEntry->ImageHandle);
326
327 Buffer = NULL;
328 Size = 0;
329 Fv = DriverEntry->Fv;
330 NameGuid = &DriverEntry->FileName;
331 FilePath = DriverEntry->FvFileDevicePath;
332
333 OriginalFilePath = FilePath;
334 HandleFilePath = FilePath;
335 DeviceHandle = NULL;
336 SecurityStatus = EFI_SUCCESS;
337 Status = EFI_SUCCESS;
338 AuthenticationStatus = 0;
339
340 //
341 // Try to get the image device handle by checking the match protocol.
342 //
343 Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &HandleFilePath, &DeviceHandle);
344 if (EFI_ERROR(Status)) {
345 return Status;
346 }
347
348 //
349 // If the Security2 and Security Architectural Protocol has not been located yet, then attempt to locate it
350 //
351 if (mSecurity2 == NULL) {
352 gBS->LocateProtocol (&gEfiSecurity2ArchProtocolGuid, NULL, (VOID**)&mSecurity2);
353 }
354 if (mSecurity == NULL) {
355 gBS->LocateProtocol (&gEfiSecurityArchProtocolGuid, NULL, (VOID**)&mSecurity);
356 }
357 //
358 // When Security2 is installed, Security Architectural Protocol must be published.
359 //
360 ASSERT (mSecurity2 == NULL || mSecurity != NULL);
361
362 //
363 // Pull out just the file portion of the DevicePath for the LoadedImage FilePath
364 //
365 FilePath = OriginalFilePath;
366 Status = gBS->HandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath);
367 if (!EFI_ERROR (Status)) {
368 FilePathSize = GetDevicePathSize (HandleFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);
369 FilePath = (EFI_DEVICE_PATH_PROTOCOL *) (((UINT8 *)FilePath) + FilePathSize );
370 }
371
372 //
373 // Try reading PE32 section firstly
374 //
375 Status = Fv->ReadSection (
376 Fv,
377 NameGuid,
378 EFI_SECTION_PE32,
379 0,
380 &Buffer,
381 &Size,
382 &AuthenticationStatus
383 );
384
385 if (EFI_ERROR (Status)) {
386 //
387 // Try reading TE section secondly
388 //
389 Buffer = NULL;
390 Size = 0;
391 Status = Fv->ReadSection (
392 Fv,
393 NameGuid,
394 EFI_SECTION_TE,
395 0,
396 &Buffer,
397 &Size,
398 &AuthenticationStatus
399 );
400 }
401
402 if (EFI_ERROR (Status)) {
403 if (Buffer != NULL) {
404 gBS->FreePool (Buffer);
405 }
406 return Status;
407 }
408
409 //
410 // Verify File Authentication through the Security2 Architectural Protocol
411 //
412 if (mSecurity2 != NULL) {
413 SecurityStatus = mSecurity2->FileAuthentication (
414 mSecurity2,
415 OriginalFilePath,
416 Buffer,
417 Size,
418 FALSE
419 );
420 }
421
422 //
423 // Verify the Authentication Status through the Security Architectural Protocol
424 // Only on images that have been read using Firmware Volume protocol.
425 // All SMM images are from FV protocol.
426 //
427 if (!EFI_ERROR (SecurityStatus) && (mSecurity != NULL)) {
428 SecurityStatus = mSecurity->FileAuthenticationState (
429 mSecurity,
430 AuthenticationStatus,
431 OriginalFilePath
432 );
433 }
434
435 if (EFI_ERROR (SecurityStatus) && SecurityStatus != EFI_SECURITY_VIOLATION) {
436 Status = SecurityStatus;
437 return Status;
438 }
439
440 //
441 // Initialize ImageContext
442 //
443 ImageContext.Handle = Buffer;
444 ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory;
445
446 //
447 // Get information about the image being loaded
448 //
449 Status = PeCoffLoaderGetImageInfo (&ImageContext);
450 if (EFI_ERROR (Status)) {
451 if (Buffer != NULL) {
452 gBS->FreePool (Buffer);
453 }
454 return Status;
455 }
456 //
457 // if Loading module at Fixed Address feature is enabled, then cut out a memory range started from TESG BASE
458 // to hold the Smm driver code
459 //
460 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0) {
461 //
462 // Get the fixed loading address assigned by Build tool
463 //
464 Status = GetPeCoffImageFixLoadingAssignedAddress (&ImageContext);
465 if (!EFI_ERROR (Status)) {
466 //
467 // Since the memory range to load Smm core alreay been cut out, so no need to allocate and free this range
468 // following statements is to bypass SmmFreePages
469 //
470 PageCount = 0;
471 DstBuffer = (UINTN)gLoadModuleAtFixAddressSmramBase;
472 } else {
473 DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED ERROR: Failed to load module at fixed address. \n"));
474 //
475 // allocate the memory to load the SMM driver
476 //
477 PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment);
478 DstBuffer = (UINTN)(-1);
479
480 Status = SmmAllocatePages (
481 AllocateMaxAddress,
482 EfiRuntimeServicesCode,
483 PageCount,
484 &DstBuffer
485 );
486 if (EFI_ERROR (Status)) {
487 if (Buffer != NULL) {
488 gBS->FreePool (Buffer);
489 }
490 return Status;
491 }
492 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer;
493 }
494 } else {
495 PageCount = (UINTN)EFI_SIZE_TO_PAGES((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment);
496 DstBuffer = (UINTN)(-1);
497
498 Status = SmmAllocatePages (
499 AllocateMaxAddress,
500 EfiRuntimeServicesCode,
501 PageCount,
502 &DstBuffer
503 );
504 if (EFI_ERROR (Status)) {
505 if (Buffer != NULL) {
506 gBS->FreePool (Buffer);
507 }
508 return Status;
509 }
510
511 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer;
512 }
513 //
514 // Align buffer on section boundary
515 //
516 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
517 ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)ImageContext.SectionAlignment - 1);
518
519 //
520 // Load the image to our new buffer
521 //
522 Status = PeCoffLoaderLoadImage (&ImageContext);
523 if (EFI_ERROR (Status)) {
524 if (Buffer != NULL) {
525 gBS->FreePool (Buffer);
526 }
527 SmmFreePages (DstBuffer, PageCount);
528 return Status;
529 }
530
531 //
532 // Relocate the image in our new buffer
533 //
534 Status = PeCoffLoaderRelocateImage (&ImageContext);
535 if (EFI_ERROR (Status)) {
536 if (Buffer != NULL) {
537 gBS->FreePool (Buffer);
538 }
539 SmmFreePages (DstBuffer, PageCount);
540 return Status;
541 }
542
543 //
544 // Flush the instruction cache so the image data are written before we execute it
545 //
546 InvalidateInstructionCacheRange ((VOID *)(UINTN) ImageContext.ImageAddress, (UINTN) ImageContext.ImageSize);
547
548 //
549 // Save Image EntryPoint in DriverEntry
550 //
551 DriverEntry->ImageEntryPoint = ImageContext.EntryPoint;
552 DriverEntry->ImageBuffer = DstBuffer;
553 DriverEntry->NumberOfPage = PageCount;
554
555 //
556 // Allocate a Loaded Image Protocol in EfiBootServicesData
557 //
558 Status = gBS->AllocatePool (EfiBootServicesData, sizeof (EFI_LOADED_IMAGE_PROTOCOL), (VOID **)&DriverEntry->LoadedImage);
559 if (EFI_ERROR (Status)) {
560 if (Buffer != NULL) {
561 gBS->FreePool (Buffer);
562 }
563 SmmFreePages (DstBuffer, PageCount);
564 return Status;
565 }
566
567 ZeroMem (DriverEntry->LoadedImage, sizeof (EFI_LOADED_IMAGE_PROTOCOL));
568 //
569 // Fill in the remaining fields of the Loaded Image Protocol instance.
570 // Note: ImageBase is an SMRAM address that can not be accessed outside of SMRAM if SMRAM window is closed.
571 //
572 DriverEntry->LoadedImage->Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION;
573 DriverEntry->LoadedImage->ParentHandle = gSmmCorePrivate->SmmIplImageHandle;
574 DriverEntry->LoadedImage->SystemTable = gST;
575 DriverEntry->LoadedImage->DeviceHandle = DeviceHandle;
576
577 DriverEntry->SmmLoadedImage.Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION;
578 DriverEntry->SmmLoadedImage.ParentHandle = gSmmCorePrivate->SmmIplImageHandle;
579 DriverEntry->SmmLoadedImage.SystemTable = gST;
580 DriverEntry->SmmLoadedImage.DeviceHandle = DeviceHandle;
581
582 //
583 // Make an EfiBootServicesData buffer copy of FilePath
584 //
585 Status = gBS->AllocatePool (EfiBootServicesData, GetDevicePathSize (FilePath), (VOID **)&DriverEntry->LoadedImage->FilePath);
586 if (EFI_ERROR (Status)) {
587 if (Buffer != NULL) {
588 gBS->FreePool (Buffer);
589 }
590 SmmFreePages (DstBuffer, PageCount);
591 return Status;
592 }
593 CopyMem (DriverEntry->LoadedImage->FilePath, FilePath, GetDevicePathSize (FilePath));
594
595 DriverEntry->LoadedImage->ImageBase = (VOID *)(UINTN) ImageContext.ImageAddress;
596 DriverEntry->LoadedImage->ImageSize = ImageContext.ImageSize;
597 DriverEntry->LoadedImage->ImageCodeType = EfiRuntimeServicesCode;
598 DriverEntry->LoadedImage->ImageDataType = EfiRuntimeServicesData;
599
600 //
601 // Make a buffer copy of FilePath
602 //
603 Status = SmmAllocatePool (EfiRuntimeServicesData, GetDevicePathSize(FilePath), (VOID **)&DriverEntry->SmmLoadedImage.FilePath);
604 if (EFI_ERROR (Status)) {
605 if (Buffer != NULL) {
606 gBS->FreePool (Buffer);
607 }
608 gBS->FreePool (DriverEntry->LoadedImage->FilePath);
609 SmmFreePages (DstBuffer, PageCount);
610 return Status;
611 }
612 CopyMem (DriverEntry->SmmLoadedImage.FilePath, FilePath, GetDevicePathSize(FilePath));
613
614 DriverEntry->SmmLoadedImage.ImageBase = (VOID *)(UINTN) ImageContext.ImageAddress;
615 DriverEntry->SmmLoadedImage.ImageSize = ImageContext.ImageSize;
616 DriverEntry->SmmLoadedImage.ImageCodeType = EfiRuntimeServicesCode;
617 DriverEntry->SmmLoadedImage.ImageDataType = EfiRuntimeServicesData;
618
619 //
620 // Create a new image handle in the UEFI handle database for the SMM Driver
621 //
622 DriverEntry->ImageHandle = NULL;
623 Status = gBS->InstallMultipleProtocolInterfaces (
624 &DriverEntry->ImageHandle,
625 &gEfiLoadedImageProtocolGuid, DriverEntry->LoadedImage,
626 NULL
627 );
628
629 //
630 // Create a new image handle in the SMM handle database for the SMM Driver
631 //
632 DriverEntry->SmmImageHandle = NULL;
633 Status = SmmInstallProtocolInterface (
634 &DriverEntry->SmmImageHandle,
635 &gEfiLoadedImageProtocolGuid,
636 EFI_NATIVE_INTERFACE,
637 &DriverEntry->SmmLoadedImage
638 );
639
640 PERF_LOAD_IMAGE_END (DriverEntry->ImageHandle);
641
642 //
643 // Print the load address and the PDB file name if it is available
644 //
645
646 DEBUG_CODE_BEGIN ();
647
648 UINTN Index;
649 UINTN StartIndex;
650 CHAR8 EfiFileName[256];
651
652
653 DEBUG ((DEBUG_INFO | DEBUG_LOAD,
654 "Loading SMM driver at 0x%11p EntryPoint=0x%11p ",
655 (VOID *)(UINTN) ImageContext.ImageAddress,
656 FUNCTION_ENTRY_POINT (ImageContext.EntryPoint)));
657
658
659 //
660 // Print Module Name by Pdb file path.
661 // Windows and Unix style file path are all trimmed correctly.
662 //
663 if (ImageContext.PdbPointer != NULL) {
664 StartIndex = 0;
665 for (Index = 0; ImageContext.PdbPointer[Index] != 0; Index++) {
666 if ((ImageContext.PdbPointer[Index] == '\\') || (ImageContext.PdbPointer[Index] == '/')) {
667 StartIndex = Index + 1;
668 }
669 }
670 //
671 // Copy the PDB file name to our temporary string, and replace .pdb with .efi
672 // The PDB file name is limited in the range of 0~255.
673 // If the length is bigger than 255, trim the redudant characters to avoid overflow in array boundary.
674 //
675 for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) {
676 EfiFileName[Index] = ImageContext.PdbPointer[Index + StartIndex];
677 if (EfiFileName[Index] == 0) {
678 EfiFileName[Index] = '.';
679 }
680 if (EfiFileName[Index] == '.') {
681 EfiFileName[Index + 1] = 'e';
682 EfiFileName[Index + 2] = 'f';
683 EfiFileName[Index + 3] = 'i';
684 EfiFileName[Index + 4] = 0;
685 break;
686 }
687 }
688
689 if (Index == sizeof (EfiFileName) - 4) {
690 EfiFileName[Index] = 0;
691 }
692 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex]));
693 }
694 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n"));
695
696 DEBUG_CODE_END ();
697
698 //
699 // Free buffer allocated by Fv->ReadSection.
700 //
701 // The UEFI Boot Services FreePool() function must be used because Fv->ReadSection
702 // used the UEFI Boot Services AllocatePool() function
703 //
704 Status = gBS->FreePool(Buffer);
705 if (!EFI_ERROR (Status) && EFI_ERROR (SecurityStatus)) {
706 Status = SecurityStatus;
707 }
708 return Status;
709 }
710
711 /**
712 Preprocess dependency expression and update DriverEntry to reflect the
713 state of Before and After dependencies. If DriverEntry->Before
714 or DriverEntry->After is set it will never be cleared.
715
716 @param DriverEntry DriverEntry element to update .
717
718 @retval EFI_SUCCESS It always works.
719
720 **/
721 EFI_STATUS
722 SmmPreProcessDepex (
723 IN EFI_SMM_DRIVER_ENTRY *DriverEntry
724 )
725 {
726 UINT8 *Iterator;
727
728 Iterator = DriverEntry->Depex;
729 DriverEntry->Dependent = TRUE;
730
731 if (*Iterator == EFI_DEP_BEFORE) {
732 DriverEntry->Before = TRUE;
733 } else if (*Iterator == EFI_DEP_AFTER) {
734 DriverEntry->After = TRUE;
735 }
736
737 if (DriverEntry->Before || DriverEntry->After) {
738 CopyMem (&DriverEntry->BeforeAfterGuid, Iterator + 1, sizeof (EFI_GUID));
739 }
740
741 return EFI_SUCCESS;
742 }
743
744 /**
745 Read Depex and pre-process the Depex for Before and After. If Section Extraction
746 protocol returns an error via ReadSection defer the reading of the Depex.
747
748 @param DriverEntry Driver to work on.
749
750 @retval EFI_SUCCESS Depex read and preprossesed
751 @retval EFI_PROTOCOL_ERROR The section extraction protocol returned an error
752 and Depex reading needs to be retried.
753 @retval Error DEPEX not found.
754
755 **/
756 EFI_STATUS
757 SmmGetDepexSectionAndPreProccess (
758 IN EFI_SMM_DRIVER_ENTRY *DriverEntry
759 )
760 {
761 EFI_STATUS Status;
762 EFI_SECTION_TYPE SectionType;
763 UINT32 AuthenticationStatus;
764 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
765
766 Fv = DriverEntry->Fv;
767
768 //
769 // Grab Depex info, it will never be free'ed.
770 // (Note: DriverEntry->Depex is in DXE memory)
771 //
772 SectionType = EFI_SECTION_SMM_DEPEX;
773 Status = Fv->ReadSection (
774 DriverEntry->Fv,
775 &DriverEntry->FileName,
776 SectionType,
777 0,
778 &DriverEntry->Depex,
779 (UINTN *)&DriverEntry->DepexSize,
780 &AuthenticationStatus
781 );
782 if (EFI_ERROR (Status)) {
783 if (Status == EFI_PROTOCOL_ERROR) {
784 //
785 // The section extraction protocol failed so set protocol error flag
786 //
787 DriverEntry->DepexProtocolError = TRUE;
788 } else {
789 //
790 // If no Depex assume depend on all architectural protocols
791 //
792 DriverEntry->Depex = NULL;
793 DriverEntry->Dependent = TRUE;
794 DriverEntry->DepexProtocolError = FALSE;
795 }
796 } else {
797 //
798 // Set Before and After state information based on Depex
799 // Driver will be put in Dependent state
800 //
801 SmmPreProcessDepex (DriverEntry);
802 DriverEntry->DepexProtocolError = FALSE;
803 }
804
805 return Status;
806 }
807
808 /**
809 This is the main Dispatcher for SMM and it exits when there are no more
810 drivers to run. Drain the mScheduledQueue and load and start a PE
811 image for each driver. Search the mDiscoveredList to see if any driver can
812 be placed on the mScheduledQueue. If no drivers are placed on the
813 mScheduledQueue exit the function.
814
815 @retval EFI_SUCCESS All of the SMM Drivers that could be dispatched
816 have been run and the SMM Entry Point has been
817 registered.
818 @retval EFI_NOT_READY The SMM Driver that registered the SMM Entry Point
819 was just dispatched.
820 @retval EFI_NOT_FOUND There are no SMM Drivers available to be dispatched.
821 @retval EFI_ALREADY_STARTED The SMM Dispatcher is already running
822
823 **/
824 EFI_STATUS
825 SmmDispatcher (
826 VOID
827 )
828 {
829 EFI_STATUS Status;
830 LIST_ENTRY *Link;
831 EFI_SMM_DRIVER_ENTRY *DriverEntry;
832 BOOLEAN ReadyToRun;
833 BOOLEAN PreviousSmmEntryPointRegistered;
834
835 if (!gRequestDispatch) {
836 return EFI_NOT_FOUND;
837 }
838
839 if (gDispatcherRunning) {
840 //
841 // If the dispatcher is running don't let it be restarted.
842 //
843 return EFI_ALREADY_STARTED;
844 }
845
846 gDispatcherRunning = TRUE;
847
848 do {
849 //
850 // Drain the Scheduled Queue
851 //
852 while (!IsListEmpty (&mScheduledQueue)) {
853 DriverEntry = CR (
854 mScheduledQueue.ForwardLink,
855 EFI_SMM_DRIVER_ENTRY,
856 ScheduledLink,
857 EFI_SMM_DRIVER_ENTRY_SIGNATURE
858 );
859
860 //
861 // Load the SMM Driver image into memory. If the Driver was transitioned from
862 // Untrused to Scheduled it would have already been loaded so we may need to
863 // skip the LoadImage
864 //
865 if (DriverEntry->ImageHandle == NULL) {
866 Status = SmmLoadImage (DriverEntry);
867
868 //
869 // Update the driver state to reflect that it's been loaded
870 //
871 if (EFI_ERROR (Status)) {
872 //
873 // The SMM Driver could not be loaded, and do not attempt to load or start it again.
874 // Take driver from Scheduled to Initialized.
875 //
876 DriverEntry->Initialized = TRUE;
877 DriverEntry->Scheduled = FALSE;
878 RemoveEntryList (&DriverEntry->ScheduledLink);
879
880 //
881 // If it's an error don't try the StartImage
882 //
883 continue;
884 }
885 }
886
887 DriverEntry->Scheduled = FALSE;
888 DriverEntry->Initialized = TRUE;
889 RemoveEntryList (&DriverEntry->ScheduledLink);
890
891 REPORT_STATUS_CODE_WITH_EXTENDED_DATA (
892 EFI_PROGRESS_CODE,
893 EFI_SOFTWARE_SMM_DRIVER | EFI_SW_PC_INIT_BEGIN,
894 &DriverEntry->ImageHandle,
895 sizeof (DriverEntry->ImageHandle)
896 );
897
898 //
899 // Cache state of SmmEntryPointRegistered before calling entry point
900 //
901 PreviousSmmEntryPointRegistered = gSmmCorePrivate->SmmEntryPointRegistered;
902
903 //
904 // For each SMM driver, pass NULL as ImageHandle
905 //
906 RegisterSmramProfileImage (DriverEntry, TRUE);
907 PERF_START_IMAGE_BEGIN (DriverEntry->ImageHandle);
908 Status = ((EFI_IMAGE_ENTRY_POINT)(UINTN)DriverEntry->ImageEntryPoint)(DriverEntry->ImageHandle, gST);
909 PERF_START_IMAGE_END (DriverEntry->ImageHandle);
910 if (EFI_ERROR(Status)){
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 it's drivers placed on the
1103 mDiscoveredList. This fucntion 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 FvIsBeingProcesssed (
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 initilize 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 FvIsBeingProcesssed (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 experessions 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 }