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