]> git.proxmox.com Git - mirror_edk2.git/blob - StandaloneMmPkg/Core/Dispatcher.c
8d009b4f80c17a7ac787cf0b1a3950395ed1da60
[mirror_edk2.git] / StandaloneMmPkg / Core / Dispatcher.c
1 /** @file
2 MM Driver Dispatcher.
3
4 Step #1 - When a FV protocol is added to the system every driver in the FV
5 is added to the mDiscoveredList. The Before, and After Depex are
6 pre-processed as drivers are added to the mDiscoveredList. If an Apriori
7 file exists in the FV those drivers are addeded to the
8 mScheduledQueue. The mFvHandleList is used to make sure a
9 FV is only processed once.
10
11 Step #2 - Dispatch. Remove driver from the mScheduledQueue and load and
12 start it. After mScheduledQueue is drained check the
13 mDiscoveredList to see if any item has a Depex that is ready to
14 be placed on the mScheduledQueue.
15
16 Step #3 - Adding to the mScheduledQueue requires that you process Before
17 and After dependencies. This is done recursively as the call to add
18 to the mScheduledQueue checks for Before and recursively adds
19 all Befores. It then addes the item that was passed in and then
20 processess the After dependecies by recursively calling the routine.
21
22 Dispatcher Rules:
23 The rules for the dispatcher are similar to the DXE dispatcher.
24
25 The rules for DXE dispatcher are in chapter 10 of the DXE CIS. Figure 10-3
26 is the state diagram for the DXE dispatcher
27
28 Depex - Dependency Expresion.
29
30 Copyright (c) 2014, Hewlett-Packard Development Company, L.P.
31 Copyright (c) 2009 - 2014, Intel Corporation. All rights reserved.<BR>
32 Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.<BR>
33
34 This program and the accompanying materials are licensed and made available
35 under the terms and conditions of the BSD License which accompanies this
36 distribution. The full text of the license may be found at
37 http://opensource.org/licenses/bsd-license.php
38
39 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
40 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
41
42 **/
43
44 #include "StandaloneMmCore.h"
45
46 //
47 // MM Dispatcher Data structures
48 //
49 #define KNOWN_HANDLE_SIGNATURE SIGNATURE_32('k','n','o','w')
50
51 typedef struct {
52 UINTN Signature;
53 LIST_ENTRY Link; // mFvHandleList
54 EFI_HANDLE Handle;
55 } KNOWN_HANDLE;
56
57 //
58 // Function Prototypes
59 //
60
61 EFI_STATUS
62 MmCoreFfsFindMmDriver (
63 IN EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader
64 );
65
66 /**
67 Insert InsertedDriverEntry onto the mScheduledQueue. To do this you
68 must add any driver with a before dependency on InsertedDriverEntry first.
69 You do this by recursively calling this routine. After all the Befores are
70 processed you can add InsertedDriverEntry to the mScheduledQueue.
71 Then you can add any driver with an After dependency on InsertedDriverEntry
72 by recursively calling this routine.
73
74 @param InsertedDriverEntry The driver to insert on the ScheduledLink Queue
75
76 **/
77 VOID
78 MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (
79 IN EFI_MM_DRIVER_ENTRY *InsertedDriverEntry
80 );
81
82 //
83 // The Driver List contains one copy of every driver that has been discovered.
84 // Items are never removed from the driver list. List of EFI_MM_DRIVER_ENTRY
85 //
86 LIST_ENTRY mDiscoveredList = INITIALIZE_LIST_HEAD_VARIABLE (mDiscoveredList);
87
88 //
89 // Queue of drivers that are ready to dispatch. This queue is a subset of the
90 // mDiscoveredList.list of EFI_MM_DRIVER_ENTRY.
91 //
92 LIST_ENTRY mScheduledQueue = INITIALIZE_LIST_HEAD_VARIABLE (mScheduledQueue);
93
94 //
95 // List of handles who's Fv's have been parsed and added to the mFwDriverList.
96 //
97 LIST_ENTRY mFvHandleList = INITIALIZE_LIST_HEAD_VARIABLE (mFvHandleList);
98
99 //
100 // Flag for the MM Dispacher. TRUE if dispatcher is execuing.
101 //
102 BOOLEAN gDispatcherRunning = FALSE;
103
104 //
105 // Flag for the MM Dispacher. TRUE if there is one or more MM drivers ready to be dispatched
106 //
107 BOOLEAN gRequestDispatch = FALSE;
108
109 //
110 // The global variable is defined for Loading modules at fixed address feature to track the MM code
111 // memory range usage. It is a bit mapped array in which every bit indicates the correspoding
112 // memory page available or not.
113 //
114 GLOBAL_REMOVE_IF_UNREFERENCED UINT64 *mMmCodeMemoryRangeUsageBitMap=NULL;
115
116 /**
117 To check memory usage bit map array to figure out if the memory range in which the image will be loaded
118 is available or not. If memory range is avaliable, the function will mark the correponding bits to 1
119 which indicates the memory range is used. The function is only invoked when load modules at fixed address
120 feature is enabled.
121
122 @param ImageBase The base addres the image will be loaded at.
123 @param ImageSize The size of the image
124
125 @retval EFI_SUCCESS The memory range the image will be loaded in is available
126 @retval EFI_NOT_FOUND The memory range the image will be loaded in is not available
127 **/
128 EFI_STATUS
129 CheckAndMarkFixLoadingMemoryUsageBitMap (
130 IN EFI_PHYSICAL_ADDRESS ImageBase,
131 IN UINTN ImageSize
132 )
133 {
134 UINT32 MmCodePageNumber;
135 UINT64 MmCodeSize;
136 EFI_PHYSICAL_ADDRESS MmCodeBase;
137 UINTN BaseOffsetPageNumber;
138 UINTN TopOffsetPageNumber;
139 UINTN Index;
140
141 //
142 // Build tool will calculate the smm code size and then patch the PcdLoadFixAddressMmCodePageNumber
143 //
144 MmCodePageNumber = 0;
145 MmCodeSize = EFI_PAGES_TO_SIZE (MmCodePageNumber);
146 MmCodeBase = gLoadModuleAtFixAddressMmramBase;
147
148 //
149 // If the memory usage bit map is not initialized, do it. Every bit in the array
150 // indicate the status of the corresponding memory page, available or not
151 //
152 if (mMmCodeMemoryRangeUsageBitMap == NULL) {
153 mMmCodeMemoryRangeUsageBitMap = AllocateZeroPool (((MmCodePageNumber / 64) + 1) * sizeof (UINT64));
154 }
155
156 //
157 // If the Dxe code memory range is not allocated or the bit map array allocation failed, return EFI_NOT_FOUND
158 //
159 if (mMmCodeMemoryRangeUsageBitMap == NULL) {
160 return EFI_NOT_FOUND;
161 }
162
163 //
164 // see if the memory range for loading the image is in the MM code range.
165 //
166 if (MmCodeBase + MmCodeSize < ImageBase + ImageSize || MmCodeBase > ImageBase) {
167 return EFI_NOT_FOUND;
168 }
169
170 //
171 // Test if the memory is avalaible or not.
172 //
173 BaseOffsetPageNumber = (UINTN)EFI_SIZE_TO_PAGES ((UINT32)(ImageBase - MmCodeBase));
174 TopOffsetPageNumber = (UINTN)EFI_SIZE_TO_PAGES ((UINT32)(ImageBase + ImageSize - MmCodeBase));
175 for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {
176 if ((mMmCodeMemoryRangeUsageBitMap[Index / 64] & LShiftU64 (1, (Index % 64))) != 0) {
177 //
178 // This page is already used.
179 //
180 return EFI_NOT_FOUND;
181 }
182 }
183
184 //
185 // Being here means the memory range is available. So mark the bits for the memory range
186 //
187 for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {
188 mMmCodeMemoryRangeUsageBitMap[Index / 64] |= LShiftU64 (1, (Index % 64));
189 }
190 return EFI_SUCCESS;
191 }
192
193 /**
194 Get the fixed loading address from image header assigned by build tool. This function only be called
195 when Loading module at Fixed address feature enabled.
196
197 @param ImageContext Pointer to the image context structure that describes the PE/COFF
198 image that needs to be examined by this function.
199 @retval EFI_SUCCESS An fixed loading address is assigned to this image by build tools .
200 @retval EFI_NOT_FOUND The image has no assigned fixed loadding address.
201
202 **/
203 EFI_STATUS
204 GetPeCoffImageFixLoadingAssignedAddress(
205 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
206 )
207 {
208 UINTN SectionHeaderOffset;
209 EFI_STATUS Status;
210 EFI_IMAGE_SECTION_HEADER SectionHeader;
211 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
212 EFI_PHYSICAL_ADDRESS FixLoadingAddress;
213 UINT16 Index;
214 UINTN Size;
215 UINT16 NumberOfSections;
216 UINT64 ValueInSectionHeader;
217
218 FixLoadingAddress = 0;
219 Status = EFI_NOT_FOUND;
220
221 //
222 // Get PeHeader pointer
223 //
224 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )ImageContext->Handle + ImageContext->PeCoffHeaderOffset);
225 SectionHeaderOffset = ImageContext->PeCoffHeaderOffset + sizeof (UINT32) + sizeof (EFI_IMAGE_FILE_HEADER) +
226 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader;
227 NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections;
228
229 //
230 // Get base address from the first section header that doesn't point to code section.
231 //
232 for (Index = 0; Index < NumberOfSections; Index++) {
233 //
234 // Read section header from file
235 //
236 Size = sizeof (EFI_IMAGE_SECTION_HEADER);
237 Status = ImageContext->ImageRead (
238 ImageContext->Handle,
239 SectionHeaderOffset,
240 &Size,
241 &SectionHeader
242 );
243 if (EFI_ERROR (Status)) {
244 return Status;
245 }
246
247 Status = EFI_NOT_FOUND;
248
249 if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) {
250 //
251 // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields
252 // in the first section header that doesn't point to code section in image header. So there
253 // is an assumption that when the feature is enabled, if a module with a loading address
254 // assigned by tools, the PointerToRelocations & PointerToLineNumbers fields should not be
255 // Zero, or else, these 2 fields should be set to Zero
256 //
257 ValueInSectionHeader = ReadUnaligned64 ((UINT64*)&SectionHeader.PointerToRelocations);
258 if (ValueInSectionHeader != 0) {
259 //
260 // Found first section header that doesn't point to code section in which build tool saves the
261 // offset to SMRAM base as image base in PointerToRelocations & PointerToLineNumbers fields
262 //
263 FixLoadingAddress = (EFI_PHYSICAL_ADDRESS)(gLoadModuleAtFixAddressMmramBase + (INT64)ValueInSectionHeader);
264 //
265 // Check if the memory range is available.
266 //
267 Status = CheckAndMarkFixLoadingMemoryUsageBitMap (FixLoadingAddress, (UINTN)(ImageContext->ImageSize + ImageContext->SectionAlignment));
268 if (!EFI_ERROR(Status)) {
269 //
270 // The assigned address is valid. Return the specified loading address
271 //
272 ImageContext->ImageAddress = FixLoadingAddress;
273 }
274 }
275 break;
276 }
277 SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);
278 }
279 DEBUG ((DEBUG_INFO|DEBUG_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address %x, Status = %r\n",
280 FixLoadingAddress, Status));
281 return Status;
282 }
283 /**
284 Loads an EFI image into SMRAM.
285
286 @param DriverEntry EFI_MM_DRIVER_ENTRY instance
287
288 @return EFI_STATUS
289
290 **/
291 EFI_STATUS
292 EFIAPI
293 MmLoadImage (
294 IN OUT EFI_MM_DRIVER_ENTRY *DriverEntry
295 )
296 {
297 VOID *Buffer;
298 UINTN PageCount;
299 EFI_STATUS Status;
300 EFI_PHYSICAL_ADDRESS DstBuffer;
301 PE_COFF_LOADER_IMAGE_CONTEXT ImageContext;
302
303 DEBUG ((DEBUG_INFO, "MmLoadImage - %g\n", &DriverEntry->FileName));
304
305 Buffer = AllocateCopyPool (DriverEntry->Pe32DataSize, DriverEntry->Pe32Data);
306 if (Buffer == NULL) {
307 return EFI_OUT_OF_RESOURCES;
308 }
309
310 Status = EFI_SUCCESS;
311
312 //
313 // Initialize ImageContext
314 //
315 ImageContext.Handle = Buffer;
316 ImageContext.ImageRead = PeCoffLoaderImageReadFromMemory;
317
318 //
319 // Get information about the image being loaded
320 //
321 Status = PeCoffLoaderGetImageInfo (&ImageContext);
322 if (EFI_ERROR (Status)) {
323 if (Buffer != NULL) {
324 MmFreePool (Buffer);
325 }
326 return Status;
327 }
328
329 PageCount = (UINTN)EFI_SIZE_TO_PAGES ((UINTN)ImageContext.ImageSize + ImageContext.SectionAlignment);
330 DstBuffer = (UINTN)(-1);
331
332 Status = MmAllocatePages (
333 AllocateMaxAddress,
334 EfiRuntimeServicesCode,
335 PageCount,
336 &DstBuffer
337 );
338 if (EFI_ERROR (Status)) {
339 if (Buffer != NULL) {
340 MmFreePool (Buffer);
341 }
342 return Status;
343 }
344
345 ImageContext.ImageAddress = (EFI_PHYSICAL_ADDRESS)DstBuffer;
346
347 //
348 // Align buffer on section boundry
349 //
350 ImageContext.ImageAddress += ImageContext.SectionAlignment - 1;
351 ImageContext.ImageAddress &= ~((EFI_PHYSICAL_ADDRESS)(ImageContext.SectionAlignment - 1));
352
353 //
354 // Load the image to our new buffer
355 //
356 Status = PeCoffLoaderLoadImage (&ImageContext);
357 if (EFI_ERROR (Status)) {
358 if (Buffer != NULL) {
359 MmFreePool (Buffer);
360 }
361 MmFreePages (DstBuffer, PageCount);
362 return Status;
363 }
364
365 //
366 // Relocate the image in our new buffer
367 //
368 Status = PeCoffLoaderRelocateImage (&ImageContext);
369 if (EFI_ERROR (Status)) {
370 if (Buffer != NULL) {
371 MmFreePool (Buffer);
372 }
373 MmFreePages (DstBuffer, PageCount);
374 return Status;
375 }
376
377 //
378 // Flush the instruction cache so the image data are written before we execute it
379 //
380 InvalidateInstructionCacheRange ((VOID *)(UINTN) ImageContext.ImageAddress, (UINTN) ImageContext.ImageSize);
381
382 //
383 // Save Image EntryPoint in DriverEntry
384 //
385 DriverEntry->ImageEntryPoint = ImageContext.EntryPoint;
386 DriverEntry->ImageBuffer = DstBuffer;
387 DriverEntry->NumberOfPage = PageCount;
388
389 if (mEfiSystemTable != NULL) {
390 Status = mEfiSystemTable->BootServices->AllocatePool (
391 EfiBootServicesData,
392 sizeof (EFI_LOADED_IMAGE_PROTOCOL),
393 (VOID **)&DriverEntry->LoadedImage
394 );
395 if (EFI_ERROR (Status)) {
396 if (Buffer != NULL) {
397 MmFreePool (Buffer);
398 }
399 MmFreePages (DstBuffer, PageCount);
400 return Status;
401 }
402
403 ZeroMem (DriverEntry->LoadedImage, sizeof (EFI_LOADED_IMAGE_PROTOCOL));
404 //
405 // Fill in the remaining fields of the Loaded Image Protocol instance.
406 // Note: ImageBase is an SMRAM address that can not be accessed outside of SMRAM if SMRAM window is closed.
407 //
408 DriverEntry->LoadedImage->Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION;
409 DriverEntry->LoadedImage->ParentHandle = NULL;
410 DriverEntry->LoadedImage->SystemTable = mEfiSystemTable;
411 DriverEntry->LoadedImage->DeviceHandle = NULL;
412 DriverEntry->LoadedImage->FilePath = NULL;
413
414 DriverEntry->LoadedImage->ImageBase = (VOID *)(UINTN)DriverEntry->ImageBuffer;
415 DriverEntry->LoadedImage->ImageSize = ImageContext.ImageSize;
416 DriverEntry->LoadedImage->ImageCodeType = EfiRuntimeServicesCode;
417 DriverEntry->LoadedImage->ImageDataType = EfiRuntimeServicesData;
418
419 //
420 // Create a new image handle in the UEFI handle database for the MM Driver
421 //
422 DriverEntry->ImageHandle = NULL;
423 Status = mEfiSystemTable->BootServices->InstallMultipleProtocolInterfaces (
424 &DriverEntry->ImageHandle,
425 &gEfiLoadedImageProtocolGuid,
426 DriverEntry->LoadedImage,
427 NULL
428 );
429 }
430
431 //
432 // Print the load address and the PDB file name if it is available
433 //
434 DEBUG_CODE_BEGIN ();
435
436 UINTN Index;
437 UINTN StartIndex;
438 CHAR8 EfiFileName[256];
439
440 DEBUG ((DEBUG_INFO | DEBUG_LOAD,
441 "Loading MM driver at 0x%11p EntryPoint=0x%11p ",
442 (VOID *)(UINTN) ImageContext.ImageAddress,
443 FUNCTION_ENTRY_POINT (ImageContext.EntryPoint)));
444
445 //
446 // Print Module Name by Pdb file path.
447 // Windows and Unix style file path are all trimmed correctly.
448 //
449 if (ImageContext.PdbPointer != NULL) {
450 StartIndex = 0;
451 for (Index = 0; ImageContext.PdbPointer[Index] != 0; Index++) {
452 if ((ImageContext.PdbPointer[Index] == '\\') || (ImageContext.PdbPointer[Index] == '/')) {
453 StartIndex = Index + 1;
454 }
455 }
456
457 //
458 // Copy the PDB file name to our temporary string, and replace .pdb with .efi
459 // The PDB file name is limited in the range of 0~255.
460 // If the length is bigger than 255, trim the redudant characters to avoid overflow in array boundary.
461 //
462 for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) {
463 EfiFileName[Index] = ImageContext.PdbPointer[Index + StartIndex];
464 if (EfiFileName[Index] == 0) {
465 EfiFileName[Index] = '.';
466 }
467 if (EfiFileName[Index] == '.') {
468 EfiFileName[Index + 1] = 'e';
469 EfiFileName[Index + 2] = 'f';
470 EfiFileName[Index + 3] = 'i';
471 EfiFileName[Index + 4] = 0;
472 break;
473 }
474 }
475
476 if (Index == sizeof (EfiFileName) - 4) {
477 EfiFileName[Index] = 0;
478 }
479 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName));
480 }
481 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n"));
482
483 DEBUG_CODE_END ();
484
485 //
486 // Free buffer allocated by Fv->ReadSection.
487 //
488 // The UEFI Boot Services FreePool() function must be used because Fv->ReadSection
489 // used the UEFI Boot Services AllocatePool() function
490 //
491 MmFreePool (Buffer);
492 return Status;
493 }
494
495 /**
496 Preprocess dependency expression and update DriverEntry to reflect the
497 state of Before and After dependencies. If DriverEntry->Before
498 or DriverEntry->After is set it will never be cleared.
499
500 @param DriverEntry DriverEntry element to update .
501
502 @retval EFI_SUCCESS It always works.
503
504 **/
505 EFI_STATUS
506 MmPreProcessDepex (
507 IN EFI_MM_DRIVER_ENTRY *DriverEntry
508 )
509 {
510 UINT8 *Iterator;
511
512 Iterator = DriverEntry->Depex;
513 DriverEntry->Dependent = TRUE;
514
515 if (*Iterator == EFI_DEP_BEFORE) {
516 DriverEntry->Before = TRUE;
517 } else if (*Iterator == EFI_DEP_AFTER) {
518 DriverEntry->After = TRUE;
519 }
520
521 if (DriverEntry->Before || DriverEntry->After) {
522 CopyMem (&DriverEntry->BeforeAfterGuid, Iterator + 1, sizeof (EFI_GUID));
523 }
524
525 return EFI_SUCCESS;
526 }
527
528 /**
529 Read Depex and pre-process the Depex for Before and After. If Section Extraction
530 protocol returns an error via ReadSection defer the reading of the Depex.
531
532 @param DriverEntry Driver to work on.
533
534 @retval EFI_SUCCESS Depex read and preprossesed
535 @retval EFI_PROTOCOL_ERROR The section extraction protocol returned an error
536 and Depex reading needs to be retried.
537 @retval Error DEPEX not found.
538
539 **/
540 EFI_STATUS
541 MmGetDepexSectionAndPreProccess (
542 IN EFI_MM_DRIVER_ENTRY *DriverEntry
543 )
544 {
545 EFI_STATUS Status;
546
547 //
548 // Data already read
549 //
550 if (DriverEntry->Depex == NULL) {
551 Status = EFI_NOT_FOUND;
552 } else {
553 Status = EFI_SUCCESS;
554 }
555 if (EFI_ERROR (Status)) {
556 if (Status == EFI_PROTOCOL_ERROR) {
557 //
558 // The section extraction protocol failed so set protocol error flag
559 //
560 DriverEntry->DepexProtocolError = TRUE;
561 } else {
562 //
563 // If no Depex assume depend on all architectural protocols
564 //
565 DriverEntry->Depex = NULL;
566 DriverEntry->Dependent = TRUE;
567 DriverEntry->DepexProtocolError = FALSE;
568 }
569 } else {
570 //
571 // Set Before and After state information based on Depex
572 // Driver will be put in Dependent state
573 //
574 MmPreProcessDepex (DriverEntry);
575 DriverEntry->DepexProtocolError = FALSE;
576 }
577
578 return Status;
579 }
580
581 /**
582 This is the main Dispatcher for MM and it exits when there are no more
583 drivers to run. Drain the mScheduledQueue and load and start a PE
584 image for each driver. Search the mDiscoveredList to see if any driver can
585 be placed on the mScheduledQueue. If no drivers are placed on the
586 mScheduledQueue exit the function.
587
588 @retval EFI_SUCCESS All of the MM Drivers that could be dispatched
589 have been run and the MM Entry Point has been
590 registered.
591 @retval EFI_NOT_READY The MM Driver that registered the MM Entry Point
592 was just dispatched.
593 @retval EFI_NOT_FOUND There are no MM Drivers available to be dispatched.
594 @retval EFI_ALREADY_STARTED The MM Dispatcher is already running
595
596 **/
597 EFI_STATUS
598 MmDispatcher (
599 VOID
600 )
601 {
602 EFI_STATUS Status;
603 LIST_ENTRY *Link;
604 EFI_MM_DRIVER_ENTRY *DriverEntry;
605 BOOLEAN ReadyToRun;
606 BOOLEAN PreviousMmEntryPointRegistered;
607
608 DEBUG ((DEBUG_INFO, "MmDispatcher\n"));
609
610 if (!gRequestDispatch) {
611 DEBUG ((DEBUG_INFO, " !gRequestDispatch\n"));
612 return EFI_NOT_FOUND;
613 }
614
615 if (gDispatcherRunning) {
616 DEBUG ((DEBUG_INFO, " gDispatcherRunning\n"));
617 //
618 // If the dispatcher is running don't let it be restarted.
619 //
620 return EFI_ALREADY_STARTED;
621 }
622
623 gDispatcherRunning = TRUE;
624
625 do {
626 //
627 // Drain the Scheduled Queue
628 //
629 DEBUG ((DEBUG_INFO, " Drain the Scheduled Queue\n"));
630 while (!IsListEmpty (&mScheduledQueue)) {
631 DriverEntry = CR (
632 mScheduledQueue.ForwardLink,
633 EFI_MM_DRIVER_ENTRY,
634 ScheduledLink,
635 EFI_MM_DRIVER_ENTRY_SIGNATURE
636 );
637 DEBUG ((DEBUG_INFO, " DriverEntry (Scheduled) - %g\n", &DriverEntry->FileName));
638
639 //
640 // Load the MM Driver image into memory. If the Driver was transitioned from
641 // Untrused to Scheduled it would have already been loaded so we may need to
642 // skip the LoadImage
643 //
644 if (DriverEntry->ImageHandle == NULL) {
645 Status = MmLoadImage (DriverEntry);
646
647 //
648 // Update the driver state to reflect that it's been loaded
649 //
650 if (EFI_ERROR (Status)) {
651 //
652 // The MM Driver could not be loaded, and do not attempt to load or start it again.
653 // Take driver from Scheduled to Initialized.
654 //
655 DriverEntry->Initialized = TRUE;
656 DriverEntry->Scheduled = FALSE;
657 RemoveEntryList (&DriverEntry->ScheduledLink);
658
659 //
660 // If it's an error don't try the StartImage
661 //
662 continue;
663 }
664 }
665
666 DriverEntry->Scheduled = FALSE;
667 DriverEntry->Initialized = TRUE;
668 RemoveEntryList (&DriverEntry->ScheduledLink);
669
670 //
671 // Cache state of MmEntryPointRegistered before calling entry point
672 //
673 PreviousMmEntryPointRegistered = gMmCorePrivate->MmEntryPointRegistered;
674
675 //
676 // For each MM driver, pass NULL as ImageHandle
677 //
678 if (mEfiSystemTable == NULL) {
679 DEBUG ((DEBUG_INFO, "StartImage - 0x%x (Standalone Mode)\n", DriverEntry->ImageEntryPoint));
680 Status = ((MM_IMAGE_ENTRY_POINT)(UINTN)DriverEntry->ImageEntryPoint) (DriverEntry->ImageHandle, &gMmCoreMmst);
681 } else {
682 DEBUG ((DEBUG_INFO, "StartImage - 0x%x (Tradition Mode)\n", DriverEntry->ImageEntryPoint));
683 Status = ((EFI_IMAGE_ENTRY_POINT)(UINTN)DriverEntry->ImageEntryPoint) (
684 DriverEntry->ImageHandle,
685 mEfiSystemTable
686 );
687 }
688 if (EFI_ERROR(Status)) {
689 DEBUG ((DEBUG_INFO, "StartImage Status - %r\n", Status));
690 MmFreePages(DriverEntry->ImageBuffer, DriverEntry->NumberOfPage);
691 }
692
693 if (!PreviousMmEntryPointRegistered && gMmCorePrivate->MmEntryPointRegistered) {
694 //
695 // Return immediately if the MM Entry Point was registered by the MM
696 // Driver that was just dispatched. The MM IPL will reinvoke the MM
697 // Core Dispatcher. This is required so MM Mode may be enabled as soon
698 // as all the dependent MM Drivers for MM Mode have been dispatched.
699 // Once the MM Entry Point has been registered, then MM Mode will be
700 // used.
701 //
702 gRequestDispatch = TRUE;
703 gDispatcherRunning = FALSE;
704 return EFI_NOT_READY;
705 }
706 }
707
708 //
709 // Search DriverList for items to place on Scheduled Queue
710 //
711 DEBUG ((DEBUG_INFO, " Search DriverList for items to place on Scheduled Queue\n"));
712 ReadyToRun = FALSE;
713 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
714 DriverEntry = CR (Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);
715 DEBUG ((DEBUG_INFO, " DriverEntry (Discovered) - %g\n", &DriverEntry->FileName));
716
717 if (DriverEntry->DepexProtocolError) {
718 //
719 // If Section Extraction Protocol did not let the Depex be read before retry the read
720 //
721 Status = MmGetDepexSectionAndPreProccess (DriverEntry);
722 }
723
724 if (DriverEntry->Dependent) {
725 if (MmIsSchedulable (DriverEntry)) {
726 MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
727 ReadyToRun = TRUE;
728 }
729 }
730 }
731 } while (ReadyToRun);
732
733 //
734 // If there is no more MM driver to dispatch, stop the dispatch request
735 //
736 DEBUG ((DEBUG_INFO, " no more MM driver to dispatch, stop the dispatch request\n"));
737 gRequestDispatch = FALSE;
738 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
739 DriverEntry = CR (Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);
740 DEBUG ((DEBUG_INFO, " DriverEntry (Discovered) - %g\n", &DriverEntry->FileName));
741
742 if (!DriverEntry->Initialized) {
743 //
744 // We have MM driver pending to dispatch
745 //
746 gRequestDispatch = TRUE;
747 break;
748 }
749 }
750
751 gDispatcherRunning = FALSE;
752
753 return EFI_SUCCESS;
754 }
755
756 /**
757 Insert InsertedDriverEntry onto the mScheduledQueue. To do this you
758 must add any driver with a before dependency on InsertedDriverEntry first.
759 You do this by recursively calling this routine. After all the Befores are
760 processed you can add InsertedDriverEntry to the mScheduledQueue.
761 Then you can add any driver with an After dependency on InsertedDriverEntry
762 by recursively calling this routine.
763
764 @param InsertedDriverEntry The driver to insert on the ScheduledLink Queue
765
766 **/
767 VOID
768 MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (
769 IN EFI_MM_DRIVER_ENTRY *InsertedDriverEntry
770 )
771 {
772 LIST_ENTRY *Link;
773 EFI_MM_DRIVER_ENTRY *DriverEntry;
774
775 //
776 // Process Before Dependency
777 //
778 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
779 DriverEntry = CR(Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);
780 if (DriverEntry->Before && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) {
781 DEBUG ((DEBUG_DISPATCH, "Evaluate MM DEPEX for FFS(%g)\n", &DriverEntry->FileName));
782 DEBUG ((DEBUG_DISPATCH, " BEFORE FFS(%g) = ", &DriverEntry->BeforeAfterGuid));
783 if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {
784 //
785 // Recursively process BEFORE
786 //
787 DEBUG ((DEBUG_DISPATCH, "TRUE\n END\n RESULT = TRUE\n"));
788 MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
789 } else {
790 DEBUG ((DEBUG_DISPATCH, "FALSE\n END\n RESULT = FALSE\n"));
791 }
792 }
793 }
794
795 //
796 // Convert driver from Dependent to Scheduled state
797 //
798
799 InsertedDriverEntry->Dependent = FALSE;
800 InsertedDriverEntry->Scheduled = TRUE;
801 InsertTailList (&mScheduledQueue, &InsertedDriverEntry->ScheduledLink);
802
803
804 //
805 // Process After Dependency
806 //
807 for (Link = mDiscoveredList.ForwardLink; Link != &mDiscoveredList; Link = Link->ForwardLink) {
808 DriverEntry = CR(Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);
809 if (DriverEntry->After && DriverEntry->Dependent && DriverEntry != InsertedDriverEntry) {
810 DEBUG ((DEBUG_DISPATCH, "Evaluate MM DEPEX for FFS(%g)\n", &DriverEntry->FileName));
811 DEBUG ((DEBUG_DISPATCH, " AFTER FFS(%g) = ", &DriverEntry->BeforeAfterGuid));
812 if (CompareGuid (&InsertedDriverEntry->FileName, &DriverEntry->BeforeAfterGuid)) {
813 //
814 // Recursively process AFTER
815 //
816 DEBUG ((DEBUG_DISPATCH, "TRUE\n END\n RESULT = TRUE\n"));
817 MmInsertOnScheduledQueueWhileProcessingBeforeAndAfter (DriverEntry);
818 } else {
819 DEBUG ((DEBUG_DISPATCH, "FALSE\n END\n RESULT = FALSE\n"));
820 }
821 }
822 }
823 }
824
825 /**
826 Return TRUE if the Fv has been processed, FALSE if not.
827
828 @param FvHandle The handle of a FV that's being tested
829
830 @retval TRUE Fv protocol on FvHandle has been processed
831 @retval FALSE Fv protocol on FvHandle has not yet been
832 processed
833
834 **/
835 BOOLEAN
836 FvHasBeenProcessed (
837 IN EFI_HANDLE FvHandle
838 )
839 {
840 LIST_ENTRY *Link;
841 KNOWN_HANDLE *KnownHandle;
842
843 for (Link = mFvHandleList.ForwardLink; Link != &mFvHandleList; Link = Link->ForwardLink) {
844 KnownHandle = CR (Link, KNOWN_HANDLE, Link, KNOWN_HANDLE_SIGNATURE);
845 if (KnownHandle->Handle == FvHandle) {
846 return TRUE;
847 }
848 }
849 return FALSE;
850 }
851
852 /**
853 Remember that Fv protocol on FvHandle has had it's drivers placed on the
854 mDiscoveredList. This fucntion adds entries on the mFvHandleList. Items are
855 never removed/freed from the mFvHandleList.
856
857 @param FvHandle The handle of a FV that has been processed
858
859 **/
860 VOID
861 FvIsBeingProcesssed (
862 IN EFI_HANDLE FvHandle
863 )
864 {
865 KNOWN_HANDLE *KnownHandle;
866
867 DEBUG ((DEBUG_INFO, "FvIsBeingProcesssed - 0x%08x\n", FvHandle));
868
869 KnownHandle = AllocatePool (sizeof (KNOWN_HANDLE));
870 ASSERT (KnownHandle != NULL);
871
872 KnownHandle->Signature = KNOWN_HANDLE_SIGNATURE;
873 KnownHandle->Handle = FvHandle;
874 InsertTailList (&mFvHandleList, &KnownHandle->Link);
875 }
876
877 /**
878 Add an entry to the mDiscoveredList. Allocate memory to store the DriverEntry,
879 and initilize any state variables. Read the Depex from the FV and store it
880 in DriverEntry. Pre-process the Depex to set the Before and After state.
881 The Discovered list is never free'ed and contains booleans that represent the
882 other possible MM driver states.
883
884 @param Fv Fv protocol, needed to read Depex info out of
885 FLASH.
886 @param FvHandle Handle for Fv, needed in the
887 EFI_MM_DRIVER_ENTRY so that the PE image can be
888 read out of the FV at a later time.
889 @param DriverName Name of driver to add to mDiscoveredList.
890
891 @retval EFI_SUCCESS If driver was added to the mDiscoveredList.
892 @retval EFI_ALREADY_STARTED The driver has already been started. Only one
893 DriverName may be active in the system at any one
894 time.
895
896 **/
897 EFI_STATUS
898 MmAddToDriverList (
899 IN EFI_HANDLE FvHandle,
900 IN VOID *Pe32Data,
901 IN UINTN Pe32DataSize,
902 IN VOID *Depex,
903 IN UINTN DepexSize,
904 IN EFI_GUID *DriverName
905 )
906 {
907 EFI_MM_DRIVER_ENTRY *DriverEntry;
908
909 DEBUG ((DEBUG_INFO, "MmAddToDriverList - %g (0x%08x)\n", DriverName, Pe32Data));
910
911 //
912 // Create the Driver Entry for the list. ZeroPool initializes lots of variables to
913 // NULL or FALSE.
914 //
915 DriverEntry = AllocateZeroPool (sizeof (EFI_MM_DRIVER_ENTRY));
916 ASSERT (DriverEntry != NULL);
917
918 DriverEntry->Signature = EFI_MM_DRIVER_ENTRY_SIGNATURE;
919 CopyGuid (&DriverEntry->FileName, DriverName);
920 DriverEntry->FvHandle = FvHandle;
921 DriverEntry->Pe32Data = Pe32Data;
922 DriverEntry->Pe32DataSize = Pe32DataSize;
923 DriverEntry->Depex = Depex;
924 DriverEntry->DepexSize = DepexSize;
925
926 MmGetDepexSectionAndPreProccess (DriverEntry);
927
928 InsertTailList (&mDiscoveredList, &DriverEntry->Link);
929 gRequestDispatch = TRUE;
930
931 return EFI_SUCCESS;
932 }
933
934 /**
935 This function is the main entry point for an MM handler dispatch
936 or communicate-based callback.
937
938 Event notification that is fired every time a FV dispatch protocol is added.
939 More than one protocol may have been added when this event is fired, so you
940 must loop on MmLocateHandle () to see how many protocols were added and
941 do the following to each FV:
942 If the Fv has already been processed, skip it. If the Fv has not been
943 processed then mark it as being processed, as we are about to process it.
944 Read the Fv and add any driver in the Fv to the mDiscoveredList.The
945 mDiscoveredList is never free'ed and contains variables that define
946 the other states the MM driver transitions to..
947 While you are at it read the A Priori file into memory.
948 Place drivers in the A Priori list onto the mScheduledQueue.
949
950 @param DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().
951 @param Context Points to an optional handler context which was specified when the handler was registered.
952 @param CommBuffer A pointer to a collection of data in memory that will
953 be conveyed from a non-MM environment into an MM environment.
954 @param CommBufferSize The size of the CommBuffer.
955
956 @return Status Code
957
958 **/
959 EFI_STATUS
960 EFIAPI
961 MmDriverDispatchHandler (
962 IN EFI_HANDLE DispatchHandle,
963 IN CONST VOID *Context, OPTIONAL
964 IN OUT VOID *CommBuffer, OPTIONAL
965 IN OUT UINTN *CommBufferSize OPTIONAL
966 )
967 {
968 EFI_STATUS Status;
969
970 DEBUG ((DEBUG_INFO, "MmDriverDispatchHandler\n"));
971
972 //
973 // Execute the MM Dispatcher on any newly discovered FVs and previously
974 // discovered MM drivers that have been discovered but not dispatched.
975 //
976 Status = MmDispatcher ();
977
978 //
979 // Check to see if CommBuffer and CommBufferSize are valid
980 //
981 if (CommBuffer != NULL && CommBufferSize != NULL) {
982 if (*CommBufferSize > 0) {
983 if (Status == EFI_NOT_READY) {
984 //
985 // If a the MM Core Entry Point was just registered, then set flag to
986 // request the MM Dispatcher to be restarted.
987 //
988 *(UINT8 *)CommBuffer = COMM_BUFFER_MM_DISPATCH_RESTART;
989 } else if (!EFI_ERROR (Status)) {
990 //
991 // Set the flag to show that the MM Dispatcher executed without errors
992 //
993 *(UINT8 *)CommBuffer = COMM_BUFFER_MM_DISPATCH_SUCCESS;
994 } else {
995 //
996 // Set the flag to show that the MM Dispatcher encountered an error
997 //
998 *(UINT8 *)CommBuffer = COMM_BUFFER_MM_DISPATCH_ERROR;
999 }
1000 }
1001 }
1002
1003 return EFI_SUCCESS;
1004 }
1005
1006 /**
1007 This function is the main entry point for an MM handler dispatch
1008 or communicate-based callback.
1009
1010 @param DispatchHandle The unique handle assigned to this handler by SmiHandlerRegister().
1011 @param Context Points to an optional handler context which was specified when the handler was registered.
1012 @param CommBuffer A pointer to a collection of data in memory that will
1013 be conveyed from a non-MM environment into an MM environment.
1014 @param CommBufferSize The size of the CommBuffer.
1015
1016 @return Status Code
1017
1018 **/
1019 EFI_STATUS
1020 EFIAPI
1021 MmFvDispatchHandler (
1022 IN EFI_HANDLE DispatchHandle,
1023 IN CONST VOID *Context, OPTIONAL
1024 IN OUT VOID *CommBuffer, OPTIONAL
1025 IN OUT UINTN *CommBufferSize OPTIONAL
1026 )
1027 {
1028 EFI_STATUS Status;
1029 EFI_MM_COMMUNICATE_FV_DISPATCH_DATA *CommunicationFvDispatchData;
1030 EFI_FIRMWARE_VOLUME_HEADER *FwVolHeader;
1031
1032 DEBUG ((DEBUG_INFO, "MmFvDispatchHandler\n"));
1033
1034 CommunicationFvDispatchData = CommBuffer;
1035
1036 DEBUG ((DEBUG_INFO, " Dispatch - 0x%016lx - 0x%016lx\n", CommunicationFvDispatchData->Address,
1037 CommunicationFvDispatchData->Size));
1038
1039 FwVolHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)CommunicationFvDispatchData->Address;
1040
1041 MmCoreFfsFindMmDriver (FwVolHeader);
1042
1043 //
1044 // Execute the MM Dispatcher on any newly discovered FVs and previously
1045 // discovered MM drivers that have been discovered but not dispatched.
1046 //
1047 Status = MmDispatcher ();
1048
1049 return Status;
1050 }
1051
1052 /**
1053 Traverse the discovered list for any drivers that were discovered but not loaded
1054 because the dependency experessions evaluated to false.
1055
1056 **/
1057 VOID
1058 MmDisplayDiscoveredNotDispatched (
1059 VOID
1060 )
1061 {
1062 LIST_ENTRY *Link;
1063 EFI_MM_DRIVER_ENTRY *DriverEntry;
1064
1065 for (Link = mDiscoveredList.ForwardLink;Link !=&mDiscoveredList; Link = Link->ForwardLink) {
1066 DriverEntry = CR (Link, EFI_MM_DRIVER_ENTRY, Link, EFI_MM_DRIVER_ENTRY_SIGNATURE);
1067 if (DriverEntry->Dependent) {
1068 DEBUG ((DEBUG_LOAD, "MM Driver %g was discovered but not loaded!!\n", &DriverEntry->FileName));
1069 }
1070 }
1071 }