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