]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Universal/BdsDxe/BdsEntry.c
MdeModulePkg/BdsDxe: Also call PlatformBootManagerWaitCallback on 0
[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 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 PlatformBootManagerWaitCallback (0);
345 DEBUG ((EFI_D_INFO, "[Bds]Exit the waiting!\n"));
346 }
347
348 /**
349 Attempt to boot each boot option in the BootOptions array.
350
351 @param BootOptions Input boot option array.
352 @param BootOptionCount Input boot option count.
353 @param BootManagerMenu Input boot manager menu.
354
355 @retval TRUE Successfully boot one of the boot options.
356 @retval FALSE Failed boot any of the boot options.
357 **/
358 BOOLEAN
359 BootBootOptions (
360 IN EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions,
361 IN UINTN BootOptionCount,
362 IN EFI_BOOT_MANAGER_LOAD_OPTION *BootManagerMenu OPTIONAL
363 )
364 {
365 UINTN Index;
366
367 //
368 // Report Status Code to indicate BDS starts attempting booting from the UEFI BootOrder list.
369 //
370 REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_ATTEMPT_BOOT_ORDER_EVENT));
371
372 //
373 // Attempt boot each boot option
374 //
375 for (Index = 0; Index < BootOptionCount; Index++) {
376 //
377 // According to EFI Specification, if a load option is not marked
378 // as LOAD_OPTION_ACTIVE, the boot manager will not automatically
379 // load the option.
380 //
381 if ((BootOptions[Index].Attributes & LOAD_OPTION_ACTIVE) == 0) {
382 continue;
383 }
384
385 //
386 // Boot#### load options with LOAD_OPTION_CATEGORY_APP are executables which are not
387 // part of the normal boot processing. Boot options with reserved category values will be
388 // ignored by the boot manager.
389 //
390 if ((BootOptions[Index].Attributes & LOAD_OPTION_CATEGORY) != LOAD_OPTION_CATEGORY_BOOT) {
391 continue;
392 }
393
394 //
395 // All the driver options should have been processed since
396 // now boot will be performed.
397 //
398 EfiBootManagerBoot (&BootOptions[Index]);
399
400 //
401 // If the boot via Boot#### returns with a status of EFI_SUCCESS, platform firmware
402 // supports boot manager menu, and if firmware is configured to boot in an
403 // interactive mode, the boot manager will stop processing the BootOrder variable and
404 // present a boot manager menu to the user.
405 //
406 if ((BootManagerMenu != NULL) && (BootOptions[Index].Status == EFI_SUCCESS)) {
407 EfiBootManagerBoot (BootManagerMenu);
408 break;
409 }
410 }
411
412 return (BOOLEAN) (Index < BootOptionCount);
413 }
414
415 /**
416 The function will load and start every Driver####, SysPrep#### or PlatformRecovery####.
417
418 @param LoadOptions Load option array.
419 @param LoadOptionCount Load option count.
420 **/
421 VOID
422 ProcessLoadOptions (
423 IN EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions,
424 IN UINTN LoadOptionCount
425 )
426 {
427 EFI_STATUS Status;
428 UINTN Index;
429 BOOLEAN ReconnectAll;
430 EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType;
431
432 ReconnectAll = FALSE;
433 LoadOptionType = LoadOptionTypeMax;
434
435 //
436 // Process the driver option
437 //
438 for (Index = 0; Index < LoadOptionCount; Index++) {
439 //
440 // All the load options in the array should be of the same type.
441 //
442 if (Index == 0) {
443 LoadOptionType = LoadOptions[Index].OptionType;
444 }
445 ASSERT (LoadOptionType == LoadOptions[Index].OptionType);
446 ASSERT (LoadOptionType != LoadOptionTypeBoot);
447
448 Status = EfiBootManagerProcessLoadOption (&LoadOptions[Index]);
449
450 //
451 // Status indicates whether the load option is loaded and executed
452 // LoadOptions[Index].Status is what the load option returns
453 //
454 if (!EFI_ERROR (Status)) {
455 //
456 // Stop processing if any PlatformRecovery#### returns success.
457 //
458 if ((LoadOptions[Index].Status == EFI_SUCCESS) &&
459 (LoadOptionType == LoadOptionTypePlatformRecovery)) {
460 break;
461 }
462
463 //
464 // Only set ReconnectAll flag when the load option executes successfully.
465 //
466 if (!EFI_ERROR (LoadOptions[Index].Status) &&
467 (LoadOptions[Index].Attributes & LOAD_OPTION_FORCE_RECONNECT) != 0) {
468 ReconnectAll = TRUE;
469 }
470 }
471 }
472
473 //
474 // If a driver load option is marked as LOAD_OPTION_FORCE_RECONNECT,
475 // then all of the EFI drivers in the system will be disconnected and
476 // reconnected after the last driver load option is processed.
477 //
478 if (ReconnectAll && LoadOptionType == LoadOptionTypeDriver) {
479 EfiBootManagerDisconnectAll ();
480 EfiBootManagerConnectAll ();
481 }
482 }
483
484 /**
485
486 Validate input console variable data.
487
488 If found the device path is not a valid device path, remove the variable.
489
490 @param VariableName Input console variable name.
491
492 **/
493 VOID
494 BdsFormalizeConsoleVariable (
495 IN CHAR16 *VariableName
496 )
497 {
498 EFI_DEVICE_PATH_PROTOCOL *DevicePath;
499 UINTN VariableSize;
500 EFI_STATUS Status;
501
502 GetEfiGlobalVariable2 (VariableName, (VOID **) &DevicePath, &VariableSize);
503 if ((DevicePath != NULL) && !IsDevicePathValid (DevicePath, VariableSize)) {
504 Status = gRT->SetVariable (
505 VariableName,
506 &gEfiGlobalVariableGuid,
507 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
508 0,
509 NULL
510 );
511 //
512 // Deleting variable with current variable implementation shouldn't fail.
513 //
514 ASSERT_EFI_ERROR (Status);
515 }
516
517 if (DevicePath != NULL) {
518 FreePool (DevicePath);
519 }
520 }
521
522 /**
523 Formalize OsIndication related variables.
524
525 For OsIndicationsSupported, Create a BS/RT/UINT64 variable to report caps
526 Delete OsIndications variable if it is not NV/BS/RT UINT64.
527
528 Item 3 is used to solve case when OS corrupts OsIndications. Here simply delete this NV variable.
529
530 Create a boot option for BootManagerMenu if it hasn't been created yet
531
532 **/
533 VOID
534 BdsFormalizeOSIndicationVariable (
535 VOID
536 )
537 {
538 EFI_STATUS Status;
539 UINT64 OsIndicationSupport;
540 UINT64 OsIndication;
541 UINTN DataSize;
542 UINT32 Attributes;
543 EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu;
544
545 //
546 // OS indicater support variable
547 //
548 Status = EfiBootManagerGetBootManagerMenu (&BootManagerMenu);
549 if (Status != EFI_NOT_FOUND) {
550 OsIndicationSupport = EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
551 EfiBootManagerFreeLoadOption (&BootManagerMenu);
552 } else {
553 OsIndicationSupport = 0;
554 }
555
556 if (PcdGetBool (PcdPlatformRecoverySupport)) {
557 OsIndicationSupport |= EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY;
558 }
559
560 if (PcdGetBool(PcdCapsuleOnDiskSupport)) {
561 OsIndicationSupport |= EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED;
562 }
563
564 Status = gRT->SetVariable (
565 EFI_OS_INDICATIONS_SUPPORT_VARIABLE_NAME,
566 &gEfiGlobalVariableGuid,
567 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
568 sizeof(UINT64),
569 &OsIndicationSupport
570 );
571 //
572 // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
573 //
574 ASSERT_EFI_ERROR (Status);
575
576 //
577 // If OsIndications is invalid, remove it.
578 // Invalid case
579 // 1. Data size != UINT64
580 // 2. OsIndication value inconsistence
581 // 3. OsIndication attribute inconsistence
582 //
583 OsIndication = 0;
584 Attributes = 0;
585 DataSize = sizeof(UINT64);
586 Status = gRT->GetVariable (
587 EFI_OS_INDICATIONS_VARIABLE_NAME,
588 &gEfiGlobalVariableGuid,
589 &Attributes,
590 &DataSize,
591 &OsIndication
592 );
593 if (Status == EFI_NOT_FOUND) {
594 return;
595 }
596
597 if ((DataSize != sizeof (OsIndication)) ||
598 ((OsIndication & ~OsIndicationSupport) != 0) ||
599 (Attributes != (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE))
600 ){
601
602 DEBUG ((EFI_D_ERROR, "[Bds] Unformalized OsIndications variable exists. Delete it\n"));
603 Status = gRT->SetVariable (
604 EFI_OS_INDICATIONS_VARIABLE_NAME,
605 &gEfiGlobalVariableGuid,
606 0,
607 0,
608 NULL
609 );
610 //
611 // Deleting variable with current variable implementation shouldn't fail.
612 //
613 ASSERT_EFI_ERROR(Status);
614 }
615 }
616
617 /**
618
619 Validate variables.
620
621 **/
622 VOID
623 BdsFormalizeEfiGlobalVariable (
624 VOID
625 )
626 {
627 //
628 // Validate Console variable.
629 //
630 BdsFormalizeConsoleVariable (EFI_CON_IN_VARIABLE_NAME);
631 BdsFormalizeConsoleVariable (EFI_CON_OUT_VARIABLE_NAME);
632 BdsFormalizeConsoleVariable (EFI_ERR_OUT_VARIABLE_NAME);
633
634 //
635 // Validate OSIndication related variable.
636 //
637 BdsFormalizeOSIndicationVariable ();
638 }
639
640 /**
641
642 Service routine for BdsInstance->Entry(). Devices are connected, the
643 consoles are initialized, and the boot options are tried.
644
645 @param This Protocol Instance structure.
646
647 **/
648 VOID
649 EFIAPI
650 BdsEntry (
651 IN EFI_BDS_ARCH_PROTOCOL *This
652 )
653 {
654 EFI_BOOT_MANAGER_LOAD_OPTION *LoadOptions;
655 UINTN LoadOptionCount;
656 CHAR16 *FirmwareVendor;
657 EFI_EVENT HotkeyTriggered;
658 UINT64 OsIndication;
659 UINTN DataSize;
660 EFI_STATUS Status;
661 UINT32 BootOptionSupport;
662 UINT16 BootTimeOut;
663 EDKII_VARIABLE_LOCK_PROTOCOL *VariableLock;
664 UINTN Index;
665 EFI_BOOT_MANAGER_LOAD_OPTION LoadOption;
666 UINT16 *BootNext;
667 CHAR16 BootNextVariableName[sizeof ("Boot####")];
668 EFI_BOOT_MANAGER_LOAD_OPTION BootManagerMenu;
669 BOOLEAN BootFwUi;
670 BOOLEAN PlatformRecovery;
671 BOOLEAN BootSuccess;
672 EFI_DEVICE_PATH_PROTOCOL *FilePath;
673 EFI_STATUS BootManagerMenuStatus;
674 EFI_BOOT_MANAGER_LOAD_OPTION PlatformDefaultBootOption;
675
676 HotkeyTriggered = NULL;
677 Status = EFI_SUCCESS;
678 BootSuccess = FALSE;
679
680 //
681 // Insert the performance probe
682 //
683 PERF_CROSSMODULE_END("DXE");
684 PERF_CROSSMODULE_BEGIN("BDS");
685 DEBUG ((EFI_D_INFO, "[Bds] Entry...\n"));
686
687 //
688 // Fill in FirmwareVendor and FirmwareRevision from PCDs
689 //
690 FirmwareVendor = (CHAR16 *) PcdGetPtr (PcdFirmwareVendor);
691 gST->FirmwareVendor = AllocateRuntimeCopyPool (StrSize (FirmwareVendor), FirmwareVendor);
692 ASSERT (gST->FirmwareVendor != NULL);
693 gST->FirmwareRevision = PcdGet32 (PcdFirmwareRevision);
694
695 //
696 // Fixup Tasble CRC after we updated Firmware Vendor and Revision
697 //
698 gST->Hdr.CRC32 = 0;
699 gBS->CalculateCrc32 ((VOID *) gST, sizeof (EFI_SYSTEM_TABLE), &gST->Hdr.CRC32);
700
701 //
702 // Validate Variable.
703 //
704 BdsFormalizeEfiGlobalVariable ();
705
706 //
707 // Mark the read-only variables if the Variable Lock protocol exists
708 //
709 Status = gBS->LocateProtocol (&gEdkiiVariableLockProtocolGuid, NULL, (VOID **) &VariableLock);
710 DEBUG ((EFI_D_INFO, "[BdsDxe] Locate Variable Lock protocol - %r\n", Status));
711 if (!EFI_ERROR (Status)) {
712 for (Index = 0; Index < ARRAY_SIZE (mReadOnlyVariables); Index++) {
713 Status = VariableLock->RequestToLock (VariableLock, mReadOnlyVariables[Index], &gEfiGlobalVariableGuid);
714 ASSERT_EFI_ERROR (Status);
715 }
716 }
717
718 InitializeHwErrRecSupport ();
719
720 //
721 // Initialize L"Timeout" EFI global variable.
722 //
723 BootTimeOut = PcdGet16 (PcdPlatformBootTimeOut);
724 if (BootTimeOut != 0xFFFF) {
725 //
726 // If time out value equal 0xFFFF, no need set to 0xFFFF to variable area because UEFI specification
727 // define same behavior between no value or 0xFFFF value for L"Timeout".
728 //
729 BdsDxeSetVariableAndReportStatusCodeOnError (
730 EFI_TIME_OUT_VARIABLE_NAME,
731 &gEfiGlobalVariableGuid,
732 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
733 sizeof (UINT16),
734 &BootTimeOut
735 );
736 }
737
738 //
739 // Initialize L"BootOptionSupport" EFI global variable.
740 // Lazy-ConIn implictly disables BDS hotkey.
741 //
742 BootOptionSupport = EFI_BOOT_OPTION_SUPPORT_APP | EFI_BOOT_OPTION_SUPPORT_SYSPREP;
743 if (!PcdGetBool (PcdConInConnectOnDemand)) {
744 BootOptionSupport |= EFI_BOOT_OPTION_SUPPORT_KEY;
745 SET_BOOT_OPTION_SUPPORT_KEY_COUNT (BootOptionSupport, 3);
746 }
747 Status = gRT->SetVariable (
748 EFI_BOOT_OPTION_SUPPORT_VARIABLE_NAME,
749 &gEfiGlobalVariableGuid,
750 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS,
751 sizeof (BootOptionSupport),
752 &BootOptionSupport
753 );
754 //
755 // Platform needs to make sure setting volatile variable before calling 3rd party code shouldn't fail.
756 //
757 ASSERT_EFI_ERROR (Status);
758
759 //
760 // Cache the "BootNext" NV variable before calling any PlatformBootManagerLib APIs
761 // This could avoid the "BootNext" set by PlatformBootManagerLib be consumed in this boot.
762 //
763 GetEfiGlobalVariable2 (EFI_BOOT_NEXT_VARIABLE_NAME, (VOID **) &BootNext, &DataSize);
764 if (DataSize != sizeof (UINT16)) {
765 if (BootNext != NULL) {
766 FreePool (BootNext);
767 }
768 BootNext = NULL;
769 }
770
771 //
772 // Initialize the platform language variables
773 //
774 InitializeLanguage (TRUE);
775
776 FilePath = FileDevicePath (NULL, EFI_REMOVABLE_MEDIA_FILE_NAME);
777 if (FilePath == NULL) {
778 DEBUG ((DEBUG_ERROR, "Fail to allocate memory for defualt boot file path. Unable to boot.\n"));
779 CpuDeadLoop ();
780 }
781 Status = EfiBootManagerInitializeLoadOption (
782 &PlatformDefaultBootOption,
783 LoadOptionNumberUnassigned,
784 LoadOptionTypePlatformRecovery,
785 LOAD_OPTION_ACTIVE,
786 L"Default PlatformRecovery",
787 FilePath,
788 NULL,
789 0
790 );
791 ASSERT_EFI_ERROR (Status);
792
793 //
794 // System firmware must include a PlatformRecovery#### variable specifying
795 // a short-form File Path Media Device Path containing the platform default
796 // file path for removable media if the platform supports Platform Recovery.
797 //
798 if (PcdGetBool (PcdPlatformRecoverySupport)) {
799 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery);
800 if (EfiBootManagerFindLoadOption (&PlatformDefaultBootOption, LoadOptions, LoadOptionCount) == -1) {
801 for (Index = 0; Index < LoadOptionCount; Index++) {
802 //
803 // The PlatformRecovery#### options are sorted by OptionNumber.
804 // Find the the smallest unused number as the new OptionNumber.
805 //
806 if (LoadOptions[Index].OptionNumber != Index) {
807 break;
808 }
809 }
810 PlatformDefaultBootOption.OptionNumber = Index;
811 Status = EfiBootManagerLoadOptionToVariable (&PlatformDefaultBootOption);
812 ASSERT_EFI_ERROR (Status);
813 }
814 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
815 }
816 FreePool (FilePath);
817
818 //
819 // Report Status Code to indicate connecting drivers will happen
820 //
821 REPORT_STATUS_CODE (
822 EFI_PROGRESS_CODE,
823 (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_BEGIN_CONNECTING_DRIVERS)
824 );
825
826 //
827 // Initialize ConnectConIn event before calling platform code.
828 //
829 if (PcdGetBool (PcdConInConnectOnDemand)) {
830 Status = gBS->CreateEventEx (
831 EVT_NOTIFY_SIGNAL,
832 TPL_CALLBACK,
833 BdsDxeOnConnectConInCallBack,
834 NULL,
835 &gConnectConInEventGuid,
836 &gConnectConInEvent
837 );
838 if (EFI_ERROR (Status)) {
839 gConnectConInEvent = NULL;
840 }
841 }
842
843 //
844 // Do the platform init, can be customized by OEM/IBV
845 // Possible things that can be done in PlatformBootManagerBeforeConsole:
846 // > Update console variable: 1. include hot-plug devices; 2. Clear ConIn and add SOL for AMT
847 // > Register new Driver#### or Boot####
848 // > Register new Key####: e.g.: F12
849 // > Signal ReadyToLock event
850 // > Authentication action: 1. connect Auth devices; 2. Identify auto logon user.
851 //
852 PERF_INMODULE_BEGIN("PlatformBootManagerBeforeConsole");
853 PlatformBootManagerBeforeConsole ();
854 PERF_INMODULE_END("PlatformBootManagerBeforeConsole");
855
856 //
857 // Initialize hotkey service
858 //
859 EfiBootManagerStartHotkeyService (&HotkeyTriggered);
860
861 //
862 // Execute Driver Options
863 //
864 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeDriver);
865 ProcessLoadOptions (LoadOptions, LoadOptionCount);
866 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
867
868 //
869 // Connect consoles
870 //
871 PERF_INMODULE_BEGIN("EfiBootManagerConnectAllDefaultConsoles");
872 if (PcdGetBool (PcdConInConnectOnDemand)) {
873 EfiBootManagerConnectConsoleVariable (ConOut);
874 EfiBootManagerConnectConsoleVariable (ErrOut);
875 //
876 // Do not connect ConIn devices when lazy ConIn feature is ON.
877 //
878 } else {
879 EfiBootManagerConnectAllDefaultConsoles ();
880 }
881 PERF_INMODULE_END("EfiBootManagerConnectAllDefaultConsoles");
882
883 //
884 // Do the platform specific action after the console is ready
885 // Possible things that can be done in PlatformBootManagerAfterConsole:
886 // > Console post action:
887 // > Dynamically switch output mode from 100x31 to 80x25 for certain senarino
888 // > Signal console ready platform customized event
889 // > Run diagnostics like memory testing
890 // > Connect certain devices
891 // > Dispatch aditional option roms
892 // > Special boot: e.g.: USB boot, enter UI
893 //
894 PERF_INMODULE_BEGIN("PlatformBootManagerAfterConsole");
895 PlatformBootManagerAfterConsole ();
896 PERF_INMODULE_END("PlatformBootManagerAfterConsole");
897
898 //
899 // If any component set PcdTestKeyUsed to TRUE because use of a test key
900 // was detected, then display a warning message on the debug log and the console
901 //
902 if (PcdGetBool (PcdTestKeyUsed)) {
903 DEBUG ((DEBUG_ERROR, "**********************************\n"));
904 DEBUG ((DEBUG_ERROR, "** WARNING: Test Key is used. **\n"));
905 DEBUG ((DEBUG_ERROR, "**********************************\n"));
906 Print (L"** WARNING: Test Key is used. **\n");
907 }
908
909 //
910 // Boot to Boot Manager Menu when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set. Skip HotkeyBoot
911 //
912 DataSize = sizeof (UINT64);
913 Status = gRT->GetVariable (
914 EFI_OS_INDICATIONS_VARIABLE_NAME,
915 &gEfiGlobalVariableGuid,
916 NULL,
917 &DataSize,
918 &OsIndication
919 );
920 if (EFI_ERROR (Status)) {
921 OsIndication = 0;
922 }
923
924 DEBUG_CODE (
925 EFI_BOOT_MANAGER_LOAD_OPTION_TYPE LoadOptionType;
926 DEBUG ((EFI_D_INFO, "[Bds]OsIndication: %016x\n", OsIndication));
927 DEBUG ((EFI_D_INFO, "[Bds]=============Begin Load Options Dumping ...=============\n"));
928 for (LoadOptionType = 0; LoadOptionType < LoadOptionTypeMax; LoadOptionType++) {
929 DEBUG ((
930 EFI_D_INFO, " %s Options:\n",
931 mBdsLoadOptionName[LoadOptionType]
932 ));
933 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionType);
934 for (Index = 0; Index < LoadOptionCount; Index++) {
935 DEBUG ((
936 EFI_D_INFO, " %s%04x: %s \t\t 0x%04x\n",
937 mBdsLoadOptionName[LoadOptionType],
938 LoadOptions[Index].OptionNumber,
939 LoadOptions[Index].Description,
940 LoadOptions[Index].Attributes
941 ));
942 }
943 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
944 }
945 DEBUG ((EFI_D_INFO, "[Bds]=============End Load Options Dumping=============\n"));
946 );
947
948 //
949 // BootManagerMenu doesn't contain the correct information when return status is EFI_NOT_FOUND.
950 //
951 BootManagerMenuStatus = EfiBootManagerGetBootManagerMenu (&BootManagerMenu);
952
953 BootFwUi = (BOOLEAN) ((OsIndication & EFI_OS_INDICATIONS_BOOT_TO_FW_UI) != 0);
954 PlatformRecovery = (BOOLEAN) ((OsIndication & EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY) != 0);
955 //
956 // Clear EFI_OS_INDICATIONS_BOOT_TO_FW_UI to acknowledge OS
957 //
958 if (BootFwUi || PlatformRecovery) {
959 OsIndication &= ~((UINT64) (EFI_OS_INDICATIONS_BOOT_TO_FW_UI | EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY));
960 Status = gRT->SetVariable (
961 EFI_OS_INDICATIONS_VARIABLE_NAME,
962 &gEfiGlobalVariableGuid,
963 EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE,
964 sizeof(UINT64),
965 &OsIndication
966 );
967 //
968 // Changing the content without increasing its size with current variable implementation shouldn't fail.
969 //
970 ASSERT_EFI_ERROR (Status);
971 }
972
973 //
974 // Launch Boot Manager Menu directly when EFI_OS_INDICATIONS_BOOT_TO_FW_UI is set. Skip HotkeyBoot
975 //
976 if (BootFwUi && (BootManagerMenuStatus != EFI_NOT_FOUND)) {
977 //
978 // Follow generic rule, Call BdsDxeOnConnectConInCallBack to connect ConIn before enter UI
979 //
980 if (PcdGetBool (PcdConInConnectOnDemand)) {
981 BdsDxeOnConnectConInCallBack (NULL, NULL);
982 }
983
984 //
985 // Directly enter the setup page.
986 //
987 EfiBootManagerBoot (&BootManagerMenu);
988 }
989
990 if (!PlatformRecovery) {
991 //
992 // Execute SysPrep####
993 //
994 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeSysPrep);
995 ProcessLoadOptions (LoadOptions, LoadOptionCount);
996 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
997
998 //
999 // Execute Key####
1000 //
1001 PERF_INMODULE_BEGIN ("BdsWait");
1002 BdsWait (HotkeyTriggered);
1003 PERF_INMODULE_END ("BdsWait");
1004 //
1005 // BdsReadKeys() can be removed after all keyboard drivers invoke callback in timer callback.
1006 //
1007 BdsReadKeys ();
1008
1009 EfiBootManagerHotkeyBoot ();
1010
1011 if (BootNext != NULL) {
1012 //
1013 // Delete "BootNext" NV variable before transferring control to it to prevent loops.
1014 //
1015 Status = gRT->SetVariable (
1016 EFI_BOOT_NEXT_VARIABLE_NAME,
1017 &gEfiGlobalVariableGuid,
1018 0,
1019 0,
1020 NULL
1021 );
1022 //
1023 // Deleting NV variable shouldn't fail unless it doesn't exist.
1024 //
1025 ASSERT (Status == EFI_SUCCESS || Status == EFI_NOT_FOUND);
1026
1027 //
1028 // Boot to "BootNext"
1029 //
1030 UnicodeSPrint (BootNextVariableName, sizeof (BootNextVariableName), L"Boot%04x", *BootNext);
1031 Status = EfiBootManagerVariableToLoadOption (BootNextVariableName, &LoadOption);
1032 if (!EFI_ERROR (Status)) {
1033 EfiBootManagerBoot (&LoadOption);
1034 EfiBootManagerFreeLoadOption (&LoadOption);
1035 if ((LoadOption.Status == EFI_SUCCESS) &&
1036 (BootManagerMenuStatus != EFI_NOT_FOUND) &&
1037 (LoadOption.OptionNumber != BootManagerMenu.OptionNumber)) {
1038 //
1039 // Boot to Boot Manager Menu upon EFI_SUCCESS
1040 // Exception: Do not boot again when the BootNext points to Boot Manager Menu.
1041 //
1042 EfiBootManagerBoot (&BootManagerMenu);
1043 }
1044 }
1045 }
1046
1047 do {
1048 //
1049 // Retry to boot if any of the boot succeeds
1050 //
1051 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypeBoot);
1052 BootSuccess = BootBootOptions (LoadOptions, LoadOptionCount, (BootManagerMenuStatus != EFI_NOT_FOUND) ? &BootManagerMenu : NULL);
1053 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
1054 } while (BootSuccess);
1055 }
1056
1057 if (BootManagerMenuStatus != EFI_NOT_FOUND) {
1058 EfiBootManagerFreeLoadOption (&BootManagerMenu);
1059 }
1060
1061 if (!BootSuccess) {
1062 if (PlatformRecovery) {
1063 LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery);
1064 ProcessLoadOptions (LoadOptions, LoadOptionCount);
1065 EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount);
1066 } else {
1067 //
1068 // When platform recovery is not enabled, still boot to platform default file path.
1069 //
1070 EfiBootManagerProcessLoadOption (&PlatformDefaultBootOption);
1071 }
1072 }
1073 EfiBootManagerFreeLoadOption (&PlatformDefaultBootOption);
1074
1075 DEBUG ((EFI_D_ERROR, "[Bds] Unable to boot!\n"));
1076 PlatformBootManagerUnableToBoot ();
1077 CpuDeadLoop ();
1078 }
1079
1080 /**
1081 Set the variable and report the error through status code upon failure.
1082
1083 @param VariableName A Null-terminated string that is the name of the vendor's variable.
1084 Each VariableName is unique for each VendorGuid. VariableName must
1085 contain 1 or more characters. If VariableName is an empty string,
1086 then EFI_INVALID_PARAMETER is returned.
1087 @param VendorGuid A unique identifier for the vendor.
1088 @param Attributes Attributes bitmask to set for the variable.
1089 @param DataSize The size in bytes of the Data buffer. Unless the EFI_VARIABLE_APPEND_WRITE,
1090 or EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS attribute is set, a size of zero
1091 causes the variable to be deleted. When the EFI_VARIABLE_APPEND_WRITE attribute is
1092 set, then a SetVariable() call with a DataSize of zero will not cause any change to
1093 the variable value (the timestamp associated with the variable may be updated however
1094 even if no new data value is provided,see the description of the
1095 EFI_VARIABLE_AUTHENTICATION_2 descriptor below. In this case the DataSize will not
1096 be zero since the EFI_VARIABLE_AUTHENTICATION_2 descriptor will be populated).
1097 @param Data The contents for the variable.
1098
1099 @retval EFI_SUCCESS The firmware has successfully stored the variable and its data as
1100 defined by the Attributes.
1101 @retval EFI_INVALID_PARAMETER An invalid combination of attribute bits, name, and GUID was supplied, or the
1102 DataSize exceeds the maximum allowed.
1103 @retval EFI_INVALID_PARAMETER VariableName is an empty string.
1104 @retval EFI_OUT_OF_RESOURCES Not enough storage is available to hold the variable and its data.
1105 @retval EFI_DEVICE_ERROR The variable could not be retrieved due to a hardware error.
1106 @retval EFI_WRITE_PROTECTED The variable in question is read-only.
1107 @retval EFI_WRITE_PROTECTED The variable in question cannot be deleted.
1108 @retval EFI_SECURITY_VIOLATION The variable could not be written due to EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACESS
1109 being set, but the AuthInfo does NOT pass the validation check carried out by the firmware.
1110
1111 @retval EFI_NOT_FOUND The variable trying to be updated or deleted was not found.
1112 **/
1113 EFI_STATUS
1114 BdsDxeSetVariableAndReportStatusCodeOnError (
1115 IN CHAR16 *VariableName,
1116 IN EFI_GUID *VendorGuid,
1117 IN UINT32 Attributes,
1118 IN UINTN DataSize,
1119 IN VOID *Data
1120 )
1121 {
1122 EFI_STATUS Status;
1123 EDKII_SET_VARIABLE_STATUS *SetVariableStatus;
1124 UINTN NameSize;
1125
1126 Status = gRT->SetVariable (
1127 VariableName,
1128 VendorGuid,
1129 Attributes,
1130 DataSize,
1131 Data
1132 );
1133 if (EFI_ERROR (Status)) {
1134 NameSize = StrSize (VariableName);
1135 SetVariableStatus = AllocatePool (sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize);
1136 if (SetVariableStatus != NULL) {
1137 CopyGuid (&SetVariableStatus->Guid, VendorGuid);
1138 SetVariableStatus->NameSize = NameSize;
1139 SetVariableStatus->DataSize = DataSize;
1140 SetVariableStatus->SetStatus = Status;
1141 SetVariableStatus->Attributes = Attributes;
1142 CopyMem (SetVariableStatus + 1, VariableName, NameSize);
1143 CopyMem (((UINT8 *) (SetVariableStatus + 1)) + NameSize, Data, DataSize);
1144
1145 REPORT_STATUS_CODE_EX (
1146 EFI_ERROR_CODE,
1147 PcdGet32 (PcdErrorCodeSetVariable),
1148 0,
1149 NULL,
1150 &gEdkiiStatusCodeDataTypeVariableGuid,
1151 SetVariableStatus,
1152 sizeof (EDKII_SET_VARIABLE_STATUS) + NameSize + DataSize
1153 );
1154
1155 FreePool (SetVariableStatus);
1156 }
1157 }
1158
1159 return Status;
1160 }