]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Universal/BdsDxe/BdsEntry.c
UefiCpuPkg: Move AsmRelocateApLoopStart from Mpfuncs.nasm to AmdSev.nasm
[mirror_edk2.git] / MdeModulePkg / Universal / BdsDxe / BdsEntry.c
1 /** @file
2 This module produce main entry for BDS phase - BdsEntry.
3 When this module was dispatched by DxeCore, gEfiBdsArchProtocolGuid will be installed
4 which contains interface of BdsEntry.
5 After DxeCore finish DXE phase, gEfiBdsArchProtocolGuid->BdsEntry will be invoked
6 to enter BDS phase.
7
8 Copyright (c) 2004 - 2019, Intel Corporation. All rights reserved.<BR>
9 (C) Copyright 2016-2019 Hewlett Packard Enterprise Development LP<BR>
10 (C) Copyright 2015 Hewlett-Packard Development Company, L.P.<BR>
11 SPDX-License-Identifier: BSD-2-Clause-Patent
12
13 **/
14
15 #include "Bds.h"
16 #include "Language.h"
17 #include "HwErrRecSupport.h"
18
19 #define SET_BOOT_OPTION_SUPPORT_KEY_COUNT(a, c) { \
20 (a) = ((a) & ~EFI_BOOT_OPTION_SUPPORT_COUNT) | (((c) << LowBitSet32 (EFI_BOOT_OPTION_SUPPORT_COUNT)) & EFI_BOOT_OPTION_SUPPORT_COUNT); \
21 }
22
23 ///
24 /// BDS arch protocol instance initial value.
25 ///
26 EFI_BDS_ARCH_PROTOCOL gBds = {
27 BdsEntry
28 };
29
30 //
31 // gConnectConInEvent - Event which is signaled when ConIn connection is required
32 //
33 EFI_EVENT gConnectConInEvent = NULL;
34
35 ///
36 /// The read-only variables defined in UEFI Spec.
37 ///
38 CHAR16 *mReadOnlyVariables[] = {
39 EFI_PLATFORM_LANG_CODES_VARIABLE_NAME,
40 EFI_LANG_CODES_VARIABLE_NAME,
41 EFI_BOOT_OPTION_SUPPORT_VARIABLE_NAME,
42 EFI_HW_ERR_REC_SUPPORT_VARIABLE_NAME,
43 EFI_OS_INDICATIONS_SUPPORT_VARIABLE_NAME
44 };
45
46 CHAR16 *mBdsLoadOptionName[] = {
47 L"Driver",
48 L"SysPrep",
49 L"Boot",
50 L"PlatformRecovery"
51 };
52
53 /**
54 Event to Connect ConIn.
55
56 @param Event Event whose notification function is being invoked.
57 @param Context Pointer to the notification function's context,
58 which is implementation-dependent.
59
60 **/
61 VOID
62 EFIAPI
63 BdsDxeOnConnectConInCallBack (
64 IN EFI_EVENT Event,
65 IN VOID *Context
66 )
67 {
68 EFI_STATUS Status;
69
70 //
71 // When Osloader call ReadKeyStroke to signal this event
72 // no driver dependency is assumed existing. So use a non-dispatch version
73 //
74 Status = EfiBootManagerConnectConsoleVariable (ConIn);
75 if (EFI_ERROR (Status)) {
76 //
77 // Should not enter this case, if enter, the keyboard will not work.
78 // May need platfrom policy to connect keyboard.
79 //
80 DEBUG ((EFI_D_WARN, "[Bds] Connect ConIn failed - %r!!!\n", Status));
81 }
82 }
83 /**
84 Notify function for event group EFI_EVENT_GROUP_READY_TO_BOOT. This is used to
85 check whether there is remaining deferred load images.
86
87 @param[in] Event The Event that is being processed.
88 @param[in] Context The Event Context.
89
90 **/
91 VOID
92 EFIAPI
93 CheckDeferredLoadImageOnReadyToBoot (
94 IN EFI_EVENT Event,
95 IN VOID *Context
96 )
97 {
98 EFI_STATUS Status;
99 EFI_DEFERRED_IMAGE_LOAD_PROTOCOL *DeferredImage;
100 UINTN HandleCount;
101 EFI_HANDLE *Handles;
102 UINTN Index;
103 UINTN ImageIndex;
104 EFI_DEVICE_PATH_PROTOCOL *ImageDevicePath;
105 VOID *Image;
106 UINTN ImageSize;
107 BOOLEAN BootOption;
108 CHAR16 *DevicePathStr;
109
110 //
111 // Find all the deferred image load protocols.
112 //
113 HandleCount = 0;
114 Handles = NULL;
115 Status = gBS->LocateHandleBuffer (
116 ByProtocol,
117 &gEfiDeferredImageLoadProtocolGuid,
118 NULL,
119 &HandleCount,
120 &Handles
121 );
122 if (EFI_ERROR (Status)) {
123 return;
124 }
125
126 for (Index = 0; Index < HandleCount; Index++) {
127 Status = gBS->HandleProtocol (Handles[Index], &gEfiDeferredImageLoadProtocolGuid, (VOID **) &DeferredImage);
128 if (EFI_ERROR (Status)) {
129 continue;
130 }
131
132 for (ImageIndex = 0; ; ImageIndex++) {
133 //
134 // Load all the deferred images in this protocol instance.
135 //
136 Status = DeferredImage->GetImageInfo (
137 DeferredImage,
138 ImageIndex,
139 &ImageDevicePath,
140 (VOID **) &Image,
141 &ImageSize,
142 &BootOption
143 );
144 if (EFI_ERROR (Status)) {
145 break;
146 }
147 DevicePathStr = ConvertDevicePathToText (ImageDevicePath, FALSE, FALSE);
148 DEBUG ((DEBUG_LOAD, "[Bds] Image was deferred but not loaded: %s.\n", DevicePathStr));
149 if (DevicePathStr != NULL) {
150 FreePool (DevicePathStr);
151 }
152 }
153 }
154 if (Handles != NULL) {
155 FreePool (Handles);
156 }
157 }
158
159 /**
160
161 Install Boot Device Selection Protocol
162
163 @param ImageHandle The image handle.
164 @param SystemTable The system table.
165
166 @retval EFI_SUCEESS BDS has finished initializing.
167 Return the dispatcher and recall BDS.Entry
168 @retval Other Return status from AllocatePool() or gBS->InstallProtocolInterface
169
170 **/
171 EFI_STATUS
172 EFIAPI
173 BdsInitialize (
174 IN EFI_HANDLE ImageHandle,
175 IN EFI_SYSTEM_TABLE *SystemTable
176 )
177 {
178 EFI_STATUS Status;
179 EFI_HANDLE Handle;
180 //
181 // Install protocol interface
182 //
183 Handle = NULL;
184 Status = gBS->InstallMultipleProtocolInterfaces (
185 &Handle,
186 &gEfiBdsArchProtocolGuid, &gBds,
187 NULL
188 );
189 ASSERT_EFI_ERROR (Status);
190
191 DEBUG_CODE (
192 EFI_EVENT Event;
193 //
194 // Register notify function to check deferred images on ReadyToBoot Event.
195 //
196 Status = gBS->CreateEventEx (
197 EVT_NOTIFY_SIGNAL,
198 TPL_CALLBACK,
199 CheckDeferredLoadImageOnReadyToBoot,
200 NULL,
201 &gEfiEventReadyToBootGuid,
202 &Event
203 );
204 ASSERT_EFI_ERROR (Status);
205 );
206 return Status;
207 }
208
209 /**
210 Function waits for a given event to fire, or for an optional timeout to expire.
211
212 @param Event The event to wait for
213 @param Timeout An optional timeout value in 100 ns units.
214
215 @retval EFI_SUCCESS Event fired before Timeout expired.
216 @retval EFI_TIME_OUT Timout expired before Event fired..
217
218 **/
219 EFI_STATUS
220 BdsWaitForSingleEvent (
221 IN EFI_EVENT Event,
222 IN UINT64 Timeout OPTIONAL
223 )
224 {
225 UINTN Index;
226 EFI_STATUS Status;
227 EFI_EVENT TimerEvent;
228 EFI_EVENT WaitList[2];
229
230 if (Timeout != 0) {
231 //
232 // Create a timer event
233 //
234 Status = gBS->CreateEvent (EVT_TIMER, 0, NULL, NULL, &TimerEvent);
235 if (!EFI_ERROR (Status)) {
236 //
237 // Set the timer event
238 //
239 gBS->SetTimer (
240 TimerEvent,
241 TimerRelative,
242 Timeout
243 );
244
245 //
246 // Wait for the original event or the timer
247 //
248 WaitList[0] = Event;
249 WaitList[1] = TimerEvent;
250 Status = gBS->WaitForEvent (2, WaitList, &Index);
251 ASSERT_EFI_ERROR (Status);
252 gBS->CloseEvent (TimerEvent);
253
254 //
255 // If the timer expired, change the return to timed out
256 //
257 if (Index == 1) {
258 Status = EFI_TIMEOUT;
259 }
260 }
261 } else {
262 //
263 // No timeout... just wait on the event
264 //
265 Status = gBS->WaitForEvent (1, &Event, &Index);
266 ASSERT (!EFI_ERROR (Status));
267 ASSERT (Index == 0);
268 }
269
270 return Status;
271 }
272
273 /**
274 The function reads user inputs.
275
276 **/
277 VOID
278 BdsReadKeys (
279 VOID
280 )
281 {
282 EFI_STATUS Status;
283 EFI_INPUT_KEY Key;
284
285 if (PcdGetBool (PcdConInConnectOnDemand)) {
286 return;
287 }
288
289 while (gST->ConIn != NULL) {
290
291 Status = gST->ConIn->ReadKeyStroke (gST->ConIn, &Key);
292
293 if (EFI_ERROR (Status)) {
294 //
295 // No more keys.
296 //
297 break;
298 }
299 }
300 }
301
302 /**
303 The function waits for the boot manager timeout expires or hotkey is pressed.
304
305 It calls PlatformBootManagerWaitCallback each second.
306
307 @param HotkeyTriggered Input hotkey event.
308 **/
309 VOID
310 BdsWait (
311 IN EFI_EVENT HotkeyTriggered
312 )
313 {
314 EFI_STATUS Status;
315 UINT16 TimeoutRemain;
316
317 DEBUG ((EFI_D_INFO, "[Bds]BdsWait ...Zzzzzzzzzzzz...\n"));
318
319 TimeoutRemain = PcdGet16 (PcdPlatformBootTimeOut);
320 while (TimeoutRemain != 0) {
321 DEBUG ((EFI_D_INFO, "[Bds]BdsWait(%d)..Zzzz...\n", (UINTN) TimeoutRemain));
322 PlatformBootManagerWaitCallback (TimeoutRemain);
323
324 BdsReadKeys (); // BUGBUG: Only reading can signal HotkeyTriggered
325 // Can be removed after all keyboard drivers invoke callback in timer callback.
326
327 if (HotkeyTriggered != NULL) {
328 Status = BdsWaitForSingleEvent (HotkeyTriggered, EFI_TIMER_PERIOD_SECONDS (1));
329 if (!EFI_ERROR (Status)) {
330 break;
331 }
332 } else {
333 gBS->Stall (1000000);
334 }
335
336 //
337 // 0xffff means waiting forever
338 // BDS with no hotkey provided and 0xffff as timeout will "hang" in the loop
339 //
340 if (TimeoutRemain != 0xffff) {
341 TimeoutRemain--;
342 }
343 }
344
345 //
346 // If the platform configured a nonzero and finite time-out, and we have
347 // actually reached that, report 100% completion to the platform.
348 //
349 // Note that the (TimeoutRemain == 0) condition excludes
350 // PcdPlatformBootTimeOut=0xFFFF, and that's deliberate.
351 //
352 if (PcdGet16 (PcdPlatformBootTimeOut) != 0 && TimeoutRemain == 0) {
353 PlatformBootManagerWaitCallback (0);
354 }
355 DEBUG ((EFI_D_INFO, "[Bds]Exit the waiting!\n"));
356 }
357
358 /**
359 Attempt to boot each boot option in the BootOptions array.
360
361 @param BootOptions Input boot option array.
362 @param BootOptionCount Input boot option count.
363 @param BootManagerMenu Input boot manager menu.
364
365 @retval TRUE Successfully boot one of the boot options.
366 @retval FALSE Failed boot any of the boot options.
367 **/
368 BOOLEAN
369 BootBootOptions (
370 IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions,
371 IN UINTN BootOptionCount,
372 IN EFI_BOOT_MANAGER_LOAD_OPTION *BootManagerMenu OPTIONAL
373 )
374 {
375 UINTN Index;
376
377 //
378 // Report Status Code to indicate BDS starts attempting booting from the UEFI BootOrder list.
379 //
380 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_ATTEMPT_BOOT_ORDER_EVENT));
381
382 //
383 // Attempt boot each boot option
384 //
385 for (Index = 0; Index < BootOptionCount; Index++) {
386 //
387 // According to EFI Specification, if a load option is not marked
388 // as LOAD_OPTION_ACTIVE, the boot manager will not automatically
389 // load the option.
390 //
391 if ((BootOptions[Index].Attributes & LOAD_OPTION_ACTIVE) == 0) {
392 continue;
393 }
394
395 //
396 // Boot#### load options with LOAD_OPTION_CATEGORY_APP are executables which are not
397 // part of the normal boot processing. Boot options with reserved category values will be
398 // ignored by the boot manager.
399 //
400 if ((BootOptions[Index].Attributes & LOAD_OPTION_CATEGORY) != LOAD_OPTION_CATEGORY_BOOT) {
401 continue;
402 }
403
404 //
405 // All the driver options should have been processed since
406 // now boot will be performed.
407 //
408 EfiBootManagerBoot (&BootOptions[Index]);
409
410 //
411 // If the boot via Boot#### returns with a status of EFI_SUCCESS, platform firmware
412 // supports boot manager menu, and if firmware is configured to boot in an
413 // interactive mode, the boot manager will stop processing the BootOrder variable and
414 // present a boot manager menu to the user.
415 //
416 if ((BootManagerMenu != NULL) && (BootOptions[Index].Status == EFI_SUCCESS)) {
417 EfiBootManagerBoot (BootManagerMenu);
418 break;
419 }
420 }
421
422 return (BOOLEAN) (Index < BootOptionCount);
423 }
424
425 /**
426 The function will load and start every Driver####, SysPrep#### or PlatformRecovery####.
427
428 @param LoadOptions Load option array.
429 @param LoadOptionCount Load option count.
430 **/
431 VOID
432 ProcessLoadOptions (
433 IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions,
434 IN UINTN LoadOptionCount
435 )
436 {
437 EFI_STATUS Status;
438 UINTN Index;
439 BOOLEAN ReconnectAll;
440 EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType;
441
442 ReconnectAll = FALSE;
443 LoadOptionType = LoadOptionTypeMax;
444
445 //
446 // Process the driver option
447 //
448 for (Index = 0; Index < LoadOptionCount; Index++) {
449 //
450 // All the load options in the array should be of the same type.
451 //
452 if (Index == 0) {
453 LoadOptionType = LoadOptions[Index].OptionType;
454 }
455 ASSERT (LoadOptionType == LoadOptions[Index].OptionType);
456 ASSERT (LoadOptionType != LoadOptionTypeBoot);
457
458 Status = EfiBootManagerProcessLoadOption (&LoadOptions[Index]);
459
460 //
461 // Status indicates whether the load option is loaded and executed
462 // LoadOptions[Index].Status is what the load option returns
463 //
464 if (!EFI_ERROR (Status)) {
465 //
466 // Stop processing if any PlatformRecovery#### returns success.
467 //
468 if ((LoadOptions[Index].Status == EFI_SUCCESS) &&
469 (LoadOptionType == LoadOptionTypePlatformRecovery)) {
470 break;
471 }
472
473 //
474 // Only set ReconnectAll flag when the load option executes successfully.
475 //
476 if (!EFI_ERROR (LoadOptions[Index].Status) &&
477 (LoadOptions[Index].Attributes & LOAD_OPTION_FORCE_RECONNECT) != 0) {
478 ReconnectAll = TRUE;
479 }
480 }
481 }
482
483 //
484 // If a driver load option is marked as LOAD_OPTION_FORCE_RECONNECT,
485 // then all of the EFI drivers in the system will be disconnected and
486 // reconnected after the last driver load option is processed.
487 //
488 if (ReconnectAll && LoadOptionType == LoadOptionTypeDriver) {
489 EfiBootManagerDisconnectAll ();
490 EfiBootManagerConnectAll ();
491 }
492 }
493
494 /**
495
496 Validate input console variable data.
497
498 If found the device path is not a valid device path, remove the variable.
499
500 @param VariableName Input console variable name.
501
502 **/
503 VOID
504 BdsFormalizeConsoleVariable (
505 IN CHAR16 *VariableName
506 )
507 {
508 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
509 UINTN VariableSize;
510 EFI_STATUS Status;
511
512 GetEfiGlobalVariable2 (VariableName, (VOID **) &DevicePath, &VariableSize);
513 if ((DevicePath != NULL) && !IsDevicePathValid (DevicePath, VariableSize)) {
514 Status = gRT->SetVariable (
515 VariableName,
516 &gEfiGlobalVariableGuid,
517 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
518 0,
519 NULL
520 );
521 //
522 // Deleting variable with current variable implementation shouldn't fail.
523 //
524 ASSERT_EFI_ERROR (Status);
525 }
526
527 if (DevicePath != NULL) {
528 FreePool (DevicePath);
529 }
530 }
531
532 /**
533 Formalize OsIndication related variables.
534
535 For OsIndicationsSupported, Create a BS/RT/UINT64 variable to report caps
536 Delete OsIndications variable if it is not NV/BS/RT UINT64.
537
538 Item 3 is used to solve case when OS corrupts OsIndications. Here simply delete this NV variable.
539
540 Create a boot option for BootManagerMenu if it hasn't been created yet
541
542 **/
543 VOID
544 BdsFormalizeOSIndicationVariable (
545 VOID
546 )
547 {
548 EFI_STATUS Status;
549 UINT64 OsIndicationSupport;
550 UINT64 OsIndication;
551 UINTN DataSize;
552 UINT32 Attributes;
553 EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu;
554
555 //
556 // OS indicater support variable
557 //
558 Status = EfiBootManagerGetBootManagerMenu (&BootManagerMenu);
559 if (Status != EFI_NOT_FOUND) {
560 OsIndicationSupport = EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
561 EfiBootManagerFreeLoadOption (&BootManagerMenu);
562 } else {
563 OsIndicationSupport = 0;
564 }
565
566 if (PcdGetBool (PcdPlatformRecoverySupport)) {
567 OsIndicationSupport |= EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY;
568 }
569
570 if (PcdGetBool(PcdCapsuleOnDiskSupport)) {
571 OsIndicationSupport |= EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED;
572 }
573
574 Status = gRT->SetVariable (
575 EFI_OS_INDICATIONS_SUPPORT_VARIABLE_NAME,
576 &gEfiGlobalVariableGuid,
577 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
578 sizeof(UINT64),
579 &OsIndicationSupport
580 );
581 //
582 // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
583 //
584 ASSERT_EFI_ERROR (Status);
585
586 //
587 // If OsIndications is invalid, remove it.
588 // Invalid case
589 // 1. Data size != UINT64
590 // 2. OsIndication value inconsistence
591 // 3. OsIndication attribute inconsistence
592 //
593 OsIndication = 0;
594 Attributes = 0;
595 DataSize = sizeof(UINT64);
596 Status = gRT->GetVariable (
597 EFI_OS_INDICATIONS_VARIABLE_NAME,
598 &gEfiGlobalVariableGuid,
599 &Attributes,
600 &DataSize,
601 &OsIndication
602 );
603 if (Status == EFI_NOT_FOUND) {
604 return;
605 }
606
607 if ((DataSize != sizeof (OsIndication)) ||
608 ((OsIndication & ~OsIndicationSupport) != 0) ||
609 (Attributes != (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE))
610 ){
611
612 DEBUG ((EFI_D_ERROR, "[Bds] Unformalized OsIndications variable exists. Delete it\n"));
613 Status = gRT->SetVariable (
614 EFI_OS_INDICATIONS_VARIABLE_NAME,
615 &gEfiGlobalVariableGuid,
616 0,
617 0,
618 NULL
619 );
620 //
621 // Deleting variable with current variable implementation shouldn't fail.
622 //
623 ASSERT_EFI_ERROR(Status);
624 }
625 }
626
627 /**
628
629 Validate variables.
630
631 **/
632 VOID
633 BdsFormalizeEfiGlobalVariable (
634 VOID
635 )
636 {
637 //
638 // Validate Console variable.
639 //
640 BdsFormalizeConsoleVariable (EFI_CON_IN_VARIABLE_NAME);
641 BdsFormalizeConsoleVariable (EFI_CON_OUT_VARIABLE_NAME);
642 BdsFormalizeConsoleVariable (EFI_ERR_OUT_VARIABLE_NAME);
643
644 //
645 // Validate OSIndication related variable.
646 //
647 BdsFormalizeOSIndicationVariable ();
648 }
649
650 /**
651
652 Service routine for BdsInstance->Entry(). Devices are connected, the
653 consoles are initialized, and the boot options are tried.
654
655 @param This Protocol Instance structure.
656
657 **/
658 VOID
659 EFIAPI
660 BdsEntry (
661 IN EFI_BDS_ARCH_PROTOCOL *This
662 )
663 {
664 EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions;
665 UINTN LoadOptionCount;
666 CHAR16 *FirmwareVendor;
667 EFI_EVENT HotkeyTriggered;
668 UINT64 OsIndication;
669 UINTN DataSize;
670 EFI_STATUS Status;
671 UINT32 BootOptionSupport;
672 UINT16 BootTimeOut;
673 EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock;
674 UINTN Index;
675 EFI_BOOT_MANAGER_LOAD_OPTION LoadOption;
676 UINT16 *BootNext;
677 CHAR16 BootNextVariableName[sizeof ("Boot####")];
678 EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu;
679 BOOLEAN BootFwUi;
680 BOOLEAN PlatformRecovery;
681 BOOLEAN BootSuccess;
682 EFI_DEVICE_PATH_PROTOCOL *FilePath;
683 EFI_STATUS BootManagerMenuStatus;
684 EFI_BOOT_MANAGER_LOAD_OPTION PlatformDefaultBootOption;
685
686 HotkeyTriggered = NULL;
687 Status = EFI_SUCCESS;
688 BootSuccess = FALSE;
689
690 //
691 // Insert the performance probe
692 //
693 PERF_CROSSMODULE_END("DXE");
694 PERF_CROSSMODULE_BEGIN("BDS");
695 DEBUG ((EFI_D_INFO, "[Bds] Entry...\n"));
696
697 //
698 // Fill in FirmwareVendor and FirmwareRevision from PCDs
699 //
700 FirmwareVendor = (CHAR16 *) PcdGetPtr (PcdFirmwareVendor);
701 gST->FirmwareVendor = AllocateRuntimeCopyPool (StrSize (FirmwareVendor), FirmwareVendor);
702 ASSERT (gST->FirmwareVendor != NULL);
703 gST->FirmwareRevision = PcdGet32 (PcdFirmwareRevision);
704
705 //
706 // Fixup Tasble CRC after we updated Firmware Vendor and Revision
707 //
708 gST->Hdr.CRC32 = 0;
709 gBS->CalculateCrc32 ((VOID *) gST, sizeof (EFI_SYSTEM_TABLE), &gST->Hdr.CRC32);
710
711 //
712 // Validate Variable.
713 //
714 BdsFormalizeEfiGlobalVariable ();
715
716 //
717 // Mark the read-only variables if the Variable Lock protocol exists
718 //
719 Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **) &VariableLock);
720 DEBUG ((EFI_D_INFO, "[BdsDxe] Locate Variable Lock protocol - %r\n", Status));
721 if (!EFI_ERROR (Status)) {
722 for (Index = 0; Index < ARRAY_SIZE (mReadOnlyVariables); Index++) {
723 Status = VariableLock->RequestToLock (VariableLock, mReadOnlyVariables[Index], &gEfiGlobalVariableGuid);
724 ASSERT_EFI_ERROR (Status);
725 }
726 }
727
728 InitializeHwErrRecSupport ();
729
730 //
731 // Initialize L"Timeout" EFI global variable.
732 //
733 BootTimeOut = PcdGet16 (PcdPlatformBootTimeOut);
734 if (BootTimeOut != 0xFFFF) {
735 //
736 // If time out value equal 0xFFFF, no need set to 0xFFFF to variable area because UEFI specification
737 // define same behavior between no value or 0xFFFF value for L"Timeout".
738 //
739 BdsDxeSetVariableAndReportStatusCodeOnError (
740 EFI_TIME_OUT_VARIABLE_NAME,
741 &gEfiGlobalVariableGuid,
742 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
743 sizeof (UINT16),
744 &BootTimeOut
745 );
746 }
747
748 //
749 // Initialize L"BootOptionSupport" EFI global variable.
750 // Lazy-ConIn implictly disables BDS hotkey.
751 //
752 BootOptionSupport = EFI_BOOT_OPTION_SUPPORT_APP | EFI_BOOT_OPTION_SUPPORT_SYSPREP;
753 if (!PcdGetBool (PcdConInConnectOnDemand)) {
754 BootOptionSupport |= EFI_BOOT_OPTION_SUPPORT_KEY;
755 SET_BOOT_OPTION_SUPPORT_KEY_COUNT (BootOptionSupport, 3);
756 }
757 Status = gRT->SetVariable (
758 EFI_BOOT_OPTION_SUPPORT_VARIABLE_NAME,
759 &gEfiGlobalVariableGuid,
760 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
761 sizeof (BootOptionSupport),
762 &BootOptionSupport
763 );
764 //
765 // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
766 //
767 ASSERT_EFI_ERROR (Status);
768
769 //
770 // Cache the "BootNext" NV variable before calling any PlatformBootManagerLib APIs
771 // This could avoid the "BootNext" set by PlatformBootManagerLib be consumed in this boot.
772 //
773 GetEfiGlobalVariable2 (EFI_BOOT_NEXT_VARIABLE_NAME, (VOID **) &BootNext, &DataSize);
774 if (DataSize != sizeof (UINT16)) {
775 if (BootNext != NULL) {
776 FreePool (BootNext);
777 }
778 BootNext = NULL;
779 }
780
781 //
782 // Initialize the platform language variables
783 //
784 InitializeLanguage (TRUE);
785
786 FilePath = FileDevicePath (NULL, EFI_REMOVABLE_MEDIA_FILE_NAME);
787 if (FilePath == NULL) {
788 DEBUG ((DEBUG_ERROR, "Fail to allocate memory for defualt boot file path. Unable to boot.\n"));
789 CpuDeadLoop ();
790 }
791 Status = EfiBootManagerInitializeLoadOption (
792 &PlatformDefaultBootOption,
793 LoadOptionNumberUnassigned,
794 LoadOptionTypePlatformRecovery,
795 LOAD_OPTION_ACTIVE,
796 L"Default PlatformRecovery",
797 FilePath,
798 NULL,
799 0
800 );
801 ASSERT_EFI_ERROR (Status);
802
803 //
804 // System firmware must include a PlatformRecovery#### variable specifying
805 // a short-form File Path Media Device Path containing the platform default
806 // file path for removable media if the platform supports Platform Recovery.
807 //
808 if (PcdGetBool (PcdPlatformRecoverySupport)) {
809 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery);
810 if (EfiBootManagerFindLoadOption (&PlatformDefaultBootOption, LoadOptions, LoadOptionCount) == -1) {
811 for (Index = 0; Index < LoadOptionCount; Index++) {
812 //
813 // The PlatformRecovery#### options are sorted by OptionNumber.
814 // Find the the smallest unused number as the new OptionNumber.
815 //
816 if (LoadOptions[Index].OptionNumber != Index) {
817 break;
818 }
819 }
820 PlatformDefaultBootOption.OptionNumber = Index;
821 Status = EfiBootManagerLoadOptionToVariable (&PlatformDefaultBootOption);
822 ASSERT_EFI_ERROR (Status);
823 }
824 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
825 }
826 FreePool (FilePath);
827
828 //
829 // Report Status Code to indicate connecting drivers will happen
830 //
831 REPORT_STATUS_CODE (
832 EFI_PROGRESS_CODE,
833 (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_BEGIN_CONNECTING_DRIVERS)
834 );
835
836 //
837 // Initialize ConnectConIn event before calling platform code.
838 //
839 if (PcdGetBool (PcdConInConnectOnDemand)) {
840 Status = gBS->CreateEventEx (
841 EVT_NOTIFY_SIGNAL,
842 TPL_CALLBACK,
843 BdsDxeOnConnectConInCallBack,
844 NULL,
845 &gConnectConInEventGuid,
846 &gConnectConInEvent
847 );
848 if (EFI_ERROR (Status)) {
849 gConnectConInEvent = NULL;
850 }
851 }
852
853 //
854 // Do the platform init, can be customized by OEM/IBV
855 // Possible things that can be done in PlatformBootManagerBeforeConsole:
856 // > Update console variable: 1. include hot-plug devices; 2. Clear ConIn and add SOL for AMT
857 // > Register new Driver#### or Boot####
858 // > Register new Key####: e.g.: F12
859 // > Signal ReadyToLock event
860 // > Authentication action: 1. connect Auth devices; 2. Identify auto logon user.
861 //
862 PERF_INMODULE_BEGIN("PlatformBootManagerBeforeConsole");
863 PlatformBootManagerBeforeConsole ();
864 PERF_INMODULE_END("PlatformBootManagerBeforeConsole");
865
866 //
867 // Initialize hotkey service
868 //
869 EfiBootManagerStartHotkeyService (&HotkeyTriggered);
870
871 //
872 // Execute Driver Options
873 //
874 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeDriver);
875 ProcessLoadOptions (LoadOptions, LoadOptionCount);
876 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
877
878 //
879 // Connect consoles
880 //
881 PERF_INMODULE_BEGIN("EfiBootManagerConnectAllDefaultConsoles");
882 if (PcdGetBool (PcdConInConnectOnDemand)) {
883 EfiBootManagerConnectConsoleVariable (ConOut);
884 EfiBootManagerConnectConsoleVariable (ErrOut);
885 //
886 // Do not connect ConIn devices when lazy ConIn feature is ON.
887 //
888 } else {
889 EfiBootManagerConnectAllDefaultConsoles ();
890 }
891 PERF_INMODULE_END("EfiBootManagerConnectAllDefaultConsoles");
892
893 //
894 // Do the platform specific action after the console is ready
895 // Possible things that can be done in PlatformBootManagerAfterConsole:
896 // > Console post action:
897 // > Dynamically switch output mode from 100x31 to 80x25 for certain senarino
898 // > Signal console ready platform customized event
899 // > Run diagnostics like memory testing
900 // > Connect certain devices
901 // > Dispatch aditional option roms
902 // > Special boot: e.g.: USB boot, enter UI
903 //
904 PERF_INMODULE_BEGIN("PlatformBootManagerAfterConsole");
905 PlatformBootManagerAfterConsole ();
906 PERF_INMODULE_END("PlatformBootManagerAfterConsole");
907
908 //
909 // If any component set PcdTestKeyUsed to TRUE because use of a test key
910 // was detected, then display a warning message on the debug log and the console
911 //
912 if (PcdGetBool (PcdTestKeyUsed)) {
913 DEBUG ((DEBUG_ERROR, "**********************************\n"));
914 DEBUG ((DEBUG_ERROR, "** WARNING: Test Key is used. **\n"));
915 DEBUG ((DEBUG_ERROR, "**********************************\n"));
916 Print (L"** WARNING: Test Key is used. **\n");
917 }
918
919 //
920 // Boot to Boot Manager Menu when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set. Skip HotkeyBoot
921 //
922 DataSize = sizeof (UINT64);
923 Status = gRT->GetVariable (
924 EFI_OS_INDICATIONS_VARIABLE_NAME,
925 &gEfiGlobalVariableGuid,
926 NULL,
927 &DataSize,
928 &OsIndication
929 );
930 if (EFI_ERROR (Status)) {
931 OsIndication = 0;
932 }
933
934 DEBUG_CODE (
935 EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType;
936 DEBUG ((EFI_D_INFO, "[Bds]OsIndication: %016x\n", OsIndication));
937 DEBUG ((EFI_D_INFO, "[Bds]=============Begin Load Options Dumping ...=============\n"));
938 for (LoadOptionType = 0; LoadOptionType < LoadOptionTypeMax; LoadOptionType++) {
939 DEBUG ((
940 EFI_D_INFO, " %s Options:\n",
941 mBdsLoadOptionName[LoadOptionType]
942 ));
943 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionType);
944 for (Index = 0; Index < LoadOptionCount; Index++) {
945 DEBUG ((
946 EFI_D_INFO, " %s%04x: %s \t\t 0x%04x\n",
947 mBdsLoadOptionName[LoadOptionType],
948 LoadOptions[Index].OptionNumber,
949 LoadOptions[Index].Description,
950 LoadOptions[Index].Attributes
951 ));
952 }
953 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
954 }
955 DEBUG ((EFI_D_INFO, "[Bds]=============End Load Options Dumping=============\n"));
956 );
957
958 //
959 // BootManagerMenu doesn't contain the correct information when return status is EFI_NOT_FOUND.
960 //
961 BootManagerMenuStatus = EfiBootManagerGetBootManagerMenu (&BootManagerMenu);
962
963 BootFwUi = (BOOLEAN) ((OsIndication & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0);
964 PlatformRecovery = (BOOLEAN) ((OsIndication & EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY) != 0);
965 //
966 // Clear EFI_OS_INDICATIONS_BOOT_TO_FW_UI to acknowledge OS
967 //
968 if (BootFwUi || PlatformRecovery) {
969 OsIndication &= ~((UINT64) (EFI_OS_INDICATIONS_BOOT_TO_FW_UI | EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY));
970 Status = gRT->SetVariable (
971 EFI_OS_INDICATIONS_VARIABLE_NAME,
972 &gEfiGlobalVariableGuid,
973 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
974 sizeof(UINT64),
975 &OsIndication
976 );
977 //
978 // Changing the content without increasing its size with current variable implementation shouldn't fail.
979 //
980 ASSERT_EFI_ERROR (Status);
981 }
982
983 //
984 // Launch Boot Manager Menu directly when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set. Skip HotkeyBoot
985 //
986 if (BootFwUi && (BootManagerMenuStatus != EFI_NOT_FOUND)) {
987 //
988 // Follow generic rule, Call BdsDxeOnConnectConInCallBack to connect ConIn before enter UI
989 //
990 if (PcdGetBool (PcdConInConnectOnDemand)) {
991 BdsDxeOnConnectConInCallBack (NULL, NULL);
992 }
993
994 //
995 // Directly enter the setup page.
996 //
997 EfiBootManagerBoot (&BootManagerMenu);
998 }
999
1000 if (!PlatformRecovery) {
1001 //
1002 // Execute SysPrep####
1003 //
1004 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeSysPrep);
1005 ProcessLoadOptions (LoadOptions, LoadOptionCount);
1006 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
1007
1008 //
1009 // Execute Key####
1010 //
1011 PERF_INMODULE_BEGIN ("BdsWait");
1012 BdsWait (HotkeyTriggered);
1013 PERF_INMODULE_END ("BdsWait");
1014 //
1015 // BdsReadKeys() can be removed after all keyboard drivers invoke callback in timer callback.
1016 //
1017 BdsReadKeys ();
1018
1019 EfiBootManagerHotkeyBoot ();
1020
1021 if (BootNext != NULL) {
1022 //
1023 // Delete "BootNext" NV variable before transferring control to it to prevent loops.
1024 //
1025 Status = gRT->SetVariable (
1026 EFI_BOOT_NEXT_VARIABLE_NAME,
1027 &gEfiGlobalVariableGuid,
1028 0,
1029 0,
1030 NULL
1031 );
1032 //
1033 // Deleting NV variable shouldn't fail unless it doesn't exist.
1034 //
1035 ASSERT (Status == EFI_SUCCESS || Status == EFI_NOT_FOUND);
1036
1037 //
1038 // Boot to "BootNext"
1039 //
1040 UnicodeSPrint (BootNextVariableName, sizeof (BootNextVariableName), L"Boot%04x", *BootNext);
1041 Status = EfiBootManagerVariableToLoadOption (BootNextVariableName, &LoadOption);
1042 if (!EFI_ERROR (Status)) {
1043 EfiBootManagerBoot (&LoadOption);
1044 EfiBootManagerFreeLoadOption (&LoadOption);
1045 if ((LoadOption.Status == EFI_SUCCESS) &&
1046 (BootManagerMenuStatus != EFI_NOT_FOUND) &&
1047 (LoadOption.OptionNumber != BootManagerMenu.OptionNumber)) {
1048 //
1049 // Boot to Boot Manager Menu upon EFI_SUCCESS
1050 // Exception: Do not boot again when the BootNext points to Boot Manager Menu.
1051 //
1052 EfiBootManagerBoot (&BootManagerMenu);
1053 }
1054 }
1055 }
1056
1057 do {
1058 //
1059 // Retry to boot if any of the boot succeeds
1060 //
1061 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeBoot);
1062 BootSuccess = BootBootOptions (LoadOptions, LoadOptionCount, (BootManagerMenuStatus != EFI_NOT_FOUND) ? &BootManagerMenu : NULL);
1063 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
1064 } while (BootSuccess);
1065 }
1066
1067 if (BootManagerMenuStatus != EFI_NOT_FOUND) {
1068 EfiBootManagerFreeLoadOption (&BootManagerMenu);
1069 }
1070
1071 if (!BootSuccess) {
1072 if (PcdGetBool (PcdPlatformRecoverySupport)) {
1073 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery);
1074 ProcessLoadOptions (LoadOptions, LoadOptionCount);
1075 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
1076 } else {
1077 //
1078 // When platform recovery is not enabled, still boot to platform default file path.
1079 //
1080 EfiBootManagerProcessLoadOption (&PlatformDefaultBootOption);
1081 }
1082 }
1083 EfiBootManagerFreeLoadOption (&PlatformDefaultBootOption);
1084
1085 DEBUG ((EFI_D_ERROR, "[Bds] Unable to boot!\n"));
1086 PlatformBootManagerUnableToBoot ();
1087 CpuDeadLoop ();
1088 }
1089
1090 /**
1091 Set the variable and report the error through status code upon failure.
1092
1093 @param VariableName A Null-terminated string that is the name of the vendor's variable.
1094 Each VariableName is unique for each VendorGuid. VariableName must
1095 contain 1 or more characters. If VariableName is an empty string,
1096 then EFI_INVALID_PARAMETER is returned.
1097 @param VendorGuid A unique identifier for the vendor.
1098 @param Attributes Attributes bitmask to set for the variable.
1099 @param DataSize The size in bytes of the Data buffer. Unless the EFI_VARIABLE_APPEND_WRITE,
1100 or EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute is set, a size of zero
1101 causes the variable to be deleted. When the EFI_VARIABLE_APPEND_WRITE attribute is
1102 set, then a SetVariable() call with a DataSize of zero will not cause any change to
1103 the variable value (the timestamp associated with the variable may be updated however
1104 even if no new data value is provided,see the description of the
1105 EFI_VARIABLE_AUTHENTICATION_2 descriptor below. In this case the DataSize will not
1106 be zero since the EFI_VARIABLE_AUTHENTICATION_2 descriptor will be populated).
1107 @param Data The contents for the variable.
1108
1109 @retval EFI_SUCCESS The firmware has successfully stored the variable and its data as
1110 defined by the Attributes.
1111 @retval EFI_INVALID_PARAMETER An invalid combination of attribute bits, name, and GUID was supplied, or the
1112 DataSize exceeds the maximum allowed.
1113 @retval EFI_INVALID_PARAMETER VariableName is an empty string.
1114 @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
1115 @retval EFI_DEVICE_ERROR The variable could not be retrieved due to a hardware error.
1116 @retval EFI_WRITE_PROTECTED The variable in question is read-only.
1117 @retval EFI_WRITE_PROTECTED The variable in question cannot be deleted.
1118 @retval EFI_SECURITY_VIOLATION The variable could not be written due to EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACESS
1119 being set, but the AuthInfo does NOT pass the validation check carried out by the firmware.
1120
1121 @retval EFI_NOT_FOUND The variable trying to be updated or deleted was not found.
1122 **/
1123 EFI_STATUS
1124 BdsDxeSetVariableAndReportStatusCodeOnError (
1125 IN CHAR16 *VariableName,
1126 IN EFI_GUID *VendorGuid,
1127 IN UINT32 Attributes,
1128 IN UINTN DataSize,
1129 IN VOID *Data
1130 )
1131 {
1132 EFI_STATUS Status;
1133 EDKII_SET_VARIABLE_STATUS *SetVariableStatus;
1134 UINTN NameSize;
1135
1136 Status = gRT->SetVariable (
1137 VariableName,
1138 VendorGuid,
1139 Attributes,
1140 DataSize,
1141 Data
1142 );
1143 if (EFI_ERROR (Status)) {
1144 NameSize = StrSize (VariableName);
1145 SetVariableStatus = AllocatePool (sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize);
1146 if (SetVariableStatus != NULL) {
1147 CopyGuid (&SetVariableStatus->Guid, VendorGuid);
1148 SetVariableStatus->NameSize = NameSize;
1149 SetVariableStatus->DataSize = DataSize;
1150 SetVariableStatus->SetStatus = Status;
1151 SetVariableStatus->Attributes = Attributes;
1152 CopyMem (SetVariableStatus + 1, VariableName, NameSize);
1153 CopyMem (((UINT8 *) (SetVariableStatus + 1)) + NameSize, Data, DataSize);
1154
1155 REPORT_STATUS_CODE_EX (
1156 EFI_ERROR_CODE,
1157 PcdGet32 (PcdErrorCodeSetVariable),
1158 0,
1159 NULL,
1160 &gEdkiiStatusCodeDataTypeVariableGuid,
1161 SetVariableStatus,
1162 sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize
1163 );
1164
1165 FreePool (SetVariableStatus);
1166 }
1167 }
1168
1169 return Status;
1170 }