]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Core/PiSmmCore/Dispatcher.c
178681ec90aecc58fd7d46c093afc3943dfefc74
[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
886 REPORT_STATUS_CODE_WITH_EXTENDED_DATA (
887 EFI_PROGRESS_CODE,
888 EFI_SOFTWARE_SMM_DRIVER | EFI_SW_PC_INIT_END,
889 &DriverEntry->ImageHandle,
890 sizeof (DriverEntry->ImageHandle)
891 );
892
893 if (!PreviousSmmEntryPointRegistered && gSmmCorePrivate->SmmEntryPointRegistered) {
894 //
895 // Return immediately if the SMM Entry Point was registered by the SMM
896 // Driver that was just dispatched. The SMM IPL will reinvoke the SMM
897 // Core Dispatcher. This is required so SMM Mode may be enabled as soon
898 // as all the dependent SMM Drivers for SMM Mode have been dispatched.
899 // Once the SMM Entry Point has been registered, then SMM Mode will be
900 // used.
901 //
902 gRequestDispatch = TRUE;
903 gDispatcherRunning = FALSE;
904 return EFI_NOT_READY;
905 }
906 }
907
908 //
909 // Search DriverList for items to place on Scheduled Queue
910 //
911 ReadyToRun = FALSE;
912 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
913 DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
914
915 if (DriverEntry->DepexProtocolError){
916 //
917 // If Section Extraction Protocol did not let the Depex be read before retry the read
918 //
919 Status = SmmGetDepexSectionAndPreProccess (DriverEntry);
920 }
921
922 if (DriverEntry->Dependent) {
923 if (SmmIsSchedulable (DriverEntry)) {
924 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
925 ReadyToRun = TRUE;
926 }
927 }
928 }
929 } while (ReadyToRun);
930
931 //
932 // If there is no more SMM driver to dispatch, stop the dispatch request
933 //
934 gRequestDispatch = FALSE;
935 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
936 DriverEntry = CR (Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
937
938 if (!DriverEntry->Initialized){
939 //
940 // We have SMM driver pending to dispatch
941 //
942 gRequestDispatch = TRUE;
943 break;
944 }
945 }
946
947 gDispatcherRunning = FALSE;
948
949 return EFI_SUCCESS;
950 }
951
952 /**
953 Insert InsertedDriverEntry onto the mScheduledQueue. To do this you
954 must add any driver with a before dependency on InsertedDriverEntry first.
955 You do this by recursively calling this routine. After all the Befores are
956 processed you can add InsertedDriverEntry to the mScheduledQueue.
957 Then you can add any driver with an After dependency on InsertedDriverEntry
958 by recursively calling this routine.
959
960 @param InsertedDriverEntry The driver to insert on the ScheduledLink Queue
961
962 **/
963 VOID
964 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (
965 IN EFI_SMM_DRIVER_ENTRY *InsertedDriverEntry
966 )
967 {
968 LIST_ENTRY *Link;
969 EFI_SMM_DRIVER_ENTRY *DriverEntry;
970
971 //
972 // Process Before Dependency
973 //
974 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
975 DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
976 if (DriverEntry->Before && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) {
977 DEBUG ((DEBUG_DISPATCH, "Evaluate SMM DEPEX for FFS(%g)\n", &DriverEntry->FileName));
978 DEBUG ((DEBUG_DISPATCH, " BEFORE FFS(%g) = ", &DriverEntry->BeforeAfterGuid));
979 if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {
980 //
981 // Recursively process BEFORE
982 //
983 DEBUG ((DEBUG_DISPATCH, "TRUE\n END\n RESULT = TRUE\n"));
984 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
985 } else {
986 DEBUG ((DEBUG_DISPATCH, "FALSE\n END\n RESULT = FALSE\n"));
987 }
988 }
989 }
990
991 //
992 // Convert driver from Dependent to Scheduled state
993 //
994
995 InsertedDriverEntry->Dependent = FALSE;
996 InsertedDriverEntry->Scheduled = TRUE;
997 InsertTailList (&mScheduledQueue, &InsertedDriverEntry->ScheduledLink);
998
999
1000 //
1001 // Process After Dependency
1002 //
1003 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
1004 DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
1005 if (DriverEntry->After && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) {
1006 DEBUG ((DEBUG_DISPATCH, "Evaluate SMM DEPEX for FFS(%g)\n", &DriverEntry->FileName));
1007 DEBUG ((DEBUG_DISPATCH, " AFTER FFS(%g) = ", &DriverEntry->BeforeAfterGuid));
1008 if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {
1009 //
1010 // Recursively process AFTER
1011 //
1012 DEBUG ((DEBUG_DISPATCH, "TRUE\n END\n RESULT = TRUE\n"));
1013 SmmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
1014 } else {
1015 DEBUG ((DEBUG_DISPATCH, "FALSE\n END\n RESULT = FALSE\n"));
1016 }
1017 }
1018 }
1019 }
1020
1021 /**
1022 Return TRUE if the Fv has been processed, FALSE if not.
1023
1024 @param FvHandle The handle of a FV that's being tested
1025
1026 @retval TRUE Fv protocol on FvHandle has been processed
1027 @retval FALSE Fv protocol on FvHandle has not yet been
1028 processed
1029
1030 **/
1031 BOOLEAN
1032 FvHasBeenProcessed (
1033 IN EFI_HANDLE FvHandle
1034 )
1035 {
1036 LIST_ENTRY *Link;
1037 KNOWN_HANDLE *KnownHandle;
1038
1039 for (Link = mFvHandleList.ForwardLink; Link != &mFvHandleList; Link = Link->ForwardLink) {
1040 KnownHandle = CR(Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE);
1041 if (KnownHandle->Handle == FvHandle) {
1042 return TRUE;
1043 }
1044 }
1045 return FALSE;
1046 }
1047
1048 /**
1049 Remember that Fv protocol on FvHandle has had it's drivers placed on the
1050 mDiscoveredList. This fucntion adds entries on the mFvHandleList. Items are
1051 never removed/freed from the mFvHandleList.
1052
1053 @param FvHandle The handle of a FV that has been processed
1054
1055 **/
1056 VOID
1057 FvIsBeingProcesssed (
1058 IN EFI_HANDLE FvHandle
1059 )
1060 {
1061 KNOWN_HANDLE *KnownHandle;
1062
1063 KnownHandle = AllocatePool (sizeof (KNOWN_HANDLE));
1064 ASSERT (KnownHandle != NULL);
1065
1066 KnownHandle->Signature = KNOWN_HANDLE_SIGNATURE;
1067 KnownHandle->Handle = FvHandle;
1068 InsertTailList (&mFvHandleList, &KnownHandle->Link);
1069 }
1070
1071 /**
1072 Convert FvHandle and DriverName into an EFI device path
1073
1074 @param Fv Fv protocol, needed to read Depex info out of
1075 FLASH.
1076 @param FvHandle Handle for Fv, needed in the
1077 EFI_SMM_DRIVER_ENTRY so that the PE image can be
1078 read out of the FV at a later time.
1079 @param DriverName Name of driver to add to mDiscoveredList.
1080
1081 @return Pointer to device path constructed from FvHandle and DriverName
1082
1083 **/
1084 EFI_DEVICE_PATH_PROTOCOL *
1085 SmmFvToDevicePath (
1086 IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv,
1087 IN EFI_HANDLE FvHandle,
1088 IN EFI_GUID *DriverName
1089 )
1090 {
1091 EFI_STATUS Status;
1092 EFI_DEVICE_PATH_PROTOCOL *FvDevicePath;
1093 EFI_DEVICE_PATH_PROTOCOL *FileNameDevicePath;
1094
1095 //
1096 // Remember the device path of the FV
1097 //
1098 Status = gBS->HandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);
1099 if (EFI_ERROR (Status)) {
1100 FileNameDevicePath = NULL;
1101 } else {
1102 //
1103 // Build a device path to the file in the FV to pass into gBS->LoadImage
1104 //
1105 EfiInitializeFwVolDevicepathNode (&mFvDevicePath.File, DriverName);
1106 SetDevicePathEndNode (&mFvDevicePath.End);
1107
1108 //
1109 // Note: FileNameDevicePath is in DXE memory
1110 //
1111 FileNameDevicePath = AppendDevicePath (
1112 FvDevicePath,
1113 (EFI_DEVICE_PATH_PROTOCOL *)&mFvDevicePath
1114 );
1115 }
1116 return FileNameDevicePath;
1117 }
1118
1119 /**
1120 Add an entry to the mDiscoveredList. Allocate memory to store the DriverEntry,
1121 and initilize any state variables. Read the Depex from the FV and store it
1122 in DriverEntry. Pre-process the Depex to set the Before and After state.
1123 The Discovered list is never free'ed and contains booleans that represent the
1124 other possible SMM driver states.
1125
1126 @param Fv Fv protocol, needed to read Depex info out of
1127 FLASH.
1128 @param FvHandle Handle for Fv, needed in the
1129 EFI_SMM_DRIVER_ENTRY so that the PE image can be
1130 read out of the FV at a later time.
1131 @param DriverName Name of driver to add to mDiscoveredList.
1132
1133 @retval EFI_SUCCESS If driver was added to the mDiscoveredList.
1134 @retval EFI_ALREADY_STARTED The driver has already been started. Only one
1135 DriverName may be active in the system at any one
1136 time.
1137
1138 **/
1139 EFI_STATUS
1140 SmmAddToDriverList (
1141 IN EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv,
1142 IN EFI_HANDLE FvHandle,
1143 IN EFI_GUID *DriverName
1144 )
1145 {
1146 EFI_SMM_DRIVER_ENTRY *DriverEntry;
1147
1148 //
1149 // Create the Driver Entry for the list. ZeroPool initializes lots of variables to
1150 // NULL or FALSE.
1151 //
1152 DriverEntry = AllocateZeroPool (sizeof (EFI_SMM_DRIVER_ENTRY));
1153 ASSERT (DriverEntry != NULL);
1154
1155 DriverEntry->Signature = EFI_SMM_DRIVER_ENTRY_SIGNATURE;
1156 CopyGuid (&DriverEntry->FileName, DriverName);
1157 DriverEntry->FvHandle = FvHandle;
1158 DriverEntry->Fv = Fv;
1159 DriverEntry->FvFileDevicePath = SmmFvToDevicePath (Fv, FvHandle, DriverName);
1160
1161 SmmGetDepexSectionAndPreProccess (DriverEntry);
1162
1163 InsertTailList (&mDiscoveredList, &DriverEntry->Link);
1164 gRequestDispatch = TRUE;
1165
1166 return EFI_SUCCESS;
1167 }
1168
1169 /**
1170 This function is the main entry point for an SMM handler dispatch
1171 or communicate-based callback.
1172
1173 Event notification that is fired every time a FV dispatch protocol is added.
1174 More than one protocol may have been added when this event is fired, so you
1175 must loop on SmmLocateHandle () to see how many protocols were added and
1176 do the following to each FV:
1177 If the Fv has already been processed, skip it. If the Fv has not been
1178 processed then mark it as being processed, as we are about to process it.
1179 Read the Fv and add any driver in the Fv to the mDiscoveredList.The
1180 mDiscoveredList is never free'ed and contains variables that define
1181 the other states the SMM driver transitions to..
1182 While you are at it read the A Priori file into memory.
1183 Place drivers in the A Priori list onto the mScheduledQueue.
1184
1185 @param DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().
1186 @param Context Points to an optional handler context which was specified when the handler was registered.
1187 @param CommBuffer A pointer to a collection of data in memory that will
1188 be conveyed from a non-SMM environment into an SMM environment.
1189 @param CommBufferSize The size of the CommBuffer.
1190
1191 @return Status Code
1192
1193 **/
1194 EFI_STATUS
1195 EFIAPI
1196 SmmDriverDispatchHandler (
1197 IN EFI_HANDLE DispatchHandle,
1198 IN CONST VOID *Context, OPTIONAL
1199 IN OUT VOID *CommBuffer, OPTIONAL
1200 IN OUT UINTN *CommBufferSize OPTIONAL
1201 )
1202 {
1203 EFI_STATUS Status;
1204 UINTN HandleCount;
1205 EFI_HANDLE *HandleBuffer;
1206 EFI_STATUS GetNextFileStatus;
1207 EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
1208 EFI_DEVICE_PATH_PROTOCOL *FvDevicePath;
1209 EFI_HANDLE FvHandle;
1210 EFI_GUID NameGuid;
1211 UINTN Key;
1212 EFI_FV_FILETYPE Type;
1213 EFI_FV_FILE_ATTRIBUTES Attributes;
1214 UINTN Size;
1215 EFI_SMM_DRIVER_ENTRY *DriverEntry;
1216 EFI_GUID *AprioriFile;
1217 UINTN AprioriEntryCount;
1218 UINTN Index;
1219 LIST_ENTRY *Link;
1220 UINT32 AuthenticationStatus;
1221 UINTN SizeOfBuffer;
1222
1223 HandleBuffer = NULL;
1224 Status = gBS->LocateHandleBuffer (
1225 ByProtocol,
1226 &gEfiFirmwareVolume2ProtocolGuid,
1227 NULL,
1228 &HandleCount,
1229 &HandleBuffer
1230 );
1231 if (EFI_ERROR (Status)) {
1232 return EFI_NOT_FOUND;
1233 }
1234
1235 for (Index = 0; Index < HandleCount; Index++) {
1236 FvHandle = HandleBuffer[Index];
1237
1238 if (FvHasBeenProcessed (FvHandle)) {
1239 //
1240 // This Fv has already been processed so lets skip it!
1241 //
1242 continue;
1243 }
1244
1245 //
1246 // Since we are about to process this Fv mark it as processed.
1247 //
1248 FvIsBeingProcesssed (FvHandle);
1249
1250 Status = gBS->HandleProtocol (FvHandle, &gEfiFirmwareVolume2ProtocolGuid, (VOID **)&Fv);
1251 if (EFI_ERROR (Status)) {
1252 //
1253 // FvHandle must have a Firmware Volume2 Protocol thus we should never get here.
1254 //
1255 ASSERT (FALSE);
1256 continue;
1257 }
1258
1259 Status = gBS->HandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);
1260 if (EFI_ERROR (Status)) {
1261 //
1262 // The Firmware volume doesn't have device path, can't be dispatched.
1263 //
1264 continue;
1265 }
1266
1267 //
1268 // Discover Drivers in FV and add them to the Discovered Driver List.
1269 // Process EFI_FV_FILETYPE_SMM type and then EFI_FV_FILETYPE_COMBINED_SMM_DXE
1270 //
1271 for (Index = 0; Index < sizeof (mSmmFileTypes)/sizeof (EFI_FV_FILETYPE); Index++) {
1272 //
1273 // Initialize the search key
1274 //
1275 Key = 0;
1276 do {
1277 Type = mSmmFileTypes[Index];
1278 GetNextFileStatus = Fv->GetNextFile (
1279 Fv,
1280 &Key,
1281 &Type,
1282 &NameGuid,
1283 &Attributes,
1284 &Size
1285 );
1286 if (!EFI_ERROR (GetNextFileStatus)) {
1287 SmmAddToDriverList (Fv, FvHandle, &NameGuid);
1288 }
1289 } while (!EFI_ERROR (GetNextFileStatus));
1290 }
1291
1292 //
1293 // Read the array of GUIDs from the Apriori file if it is present in the firmware volume
1294 // (Note: AprioriFile is in DXE memory)
1295 //
1296 AprioriFile = NULL;
1297 Status = Fv->ReadSection (
1298 Fv,
1299 &gAprioriGuid,
1300 EFI_SECTION_RAW,
1301 0,
1302 (VOID **)&AprioriFile,
1303 &SizeOfBuffer,
1304 &AuthenticationStatus
1305 );
1306 if (!EFI_ERROR (Status)) {
1307 AprioriEntryCount = SizeOfBuffer / sizeof (EFI_GUID);
1308 } else {
1309 AprioriEntryCount = 0;
1310 }
1311
1312 //
1313 // Put drivers on Apriori List on the Scheduled queue. The Discovered List includes
1314 // drivers not in the current FV and these must be skipped since the a priori list
1315 // is only valid for the FV that it resided in.
1316 //
1317
1318 for (Index = 0; Index < AprioriEntryCount; Index++) {
1319 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
1320 DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
1321 if (CompareGuid (&DriverEntry->FileName, &AprioriFile[Index]) &&
1322 (FvHandle == DriverEntry->FvHandle)) {
1323 DriverEntry->Dependent = FALSE;
1324 DriverEntry->Scheduled = TRUE;
1325 InsertTailList (&mScheduledQueue, &DriverEntry->ScheduledLink);
1326 DEBUG ((DEBUG_DISPATCH, "Evaluate SMM DEPEX for FFS(%g)\n", &DriverEntry->FileName));
1327 DEBUG ((DEBUG_DISPATCH, " RESULT = TRUE (Apriori)\n"));
1328 break;
1329 }
1330 }
1331 }
1332
1333 //
1334 // Free data allocated by Fv->ReadSection ()
1335 //
1336 // The UEFI Boot Services FreePool() function must be used because Fv->ReadSection
1337 // used the UEFI Boot Services AllocatePool() function
1338 //
1339 gBS->FreePool (AprioriFile);
1340 }
1341
1342 //
1343 // Execute the SMM Dispatcher on any newly discovered FVs and previously
1344 // discovered SMM drivers that have been discovered but not dispatched.
1345 //
1346 Status = SmmDispatcher ();
1347
1348 //
1349 // Check to see if CommBuffer and CommBufferSize are valid
1350 //
1351 if (CommBuffer != NULL && CommBufferSize != NULL) {
1352 if (*CommBufferSize > 0) {
1353 if (Status == EFI_NOT_READY) {
1354 //
1355 // If a the SMM Core Entry Point was just registered, then set flag to
1356 // request the SMM Dispatcher to be restarted.
1357 //
1358 *(UINT8 *)CommBuffer = COMM_BUFFER_SMM_DISPATCH_RESTART;
1359 } else if (!EFI_ERROR (Status)) {
1360 //
1361 // Set the flag to show that the SMM Dispatcher executed without errors
1362 //
1363 *(UINT8 *)CommBuffer = COMM_BUFFER_SMM_DISPATCH_SUCCESS;
1364 } else {
1365 //
1366 // Set the flag to show that the SMM Dispatcher encountered an error
1367 //
1368 *(UINT8 *)CommBuffer = COMM_BUFFER_SMM_DISPATCH_ERROR;
1369 }
1370 }
1371 }
1372
1373 return EFI_SUCCESS;
1374 }
1375
1376 /**
1377 Traverse the discovered list for any drivers that were discovered but not loaded
1378 because the dependency experessions evaluated to false.
1379
1380 **/
1381 VOID
1382 SmmDisplayDiscoveredNotDispatched (
1383 VOID
1384 )
1385 {
1386 LIST_ENTRY *Link;
1387 EFI_SMM_DRIVER_ENTRY *DriverEntry;
1388
1389 for (Link = mDiscoveredList.ForwardLink;Link !=&mDiscoveredList; Link = Link->ForwardLink) {
1390 DriverEntry = CR(Link, EFI_SMM_DRIVER_ENTRY, Link, EFI_SMM_DRIVER_ENTRY_SIGNATURE);
1391 if (DriverEntry->Dependent) {
1392 DEBUG ((DEBUG_LOAD, "SMM Driver %g was discovered but not loaded!!\n", &DriverEntry->FileName));
1393 }
1394 }
1395 }