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